No OneTemporary

File Metadata

Created
Wed, May 1, 9:57 AM
This file is larger than 256 KB, so syntax highlighting was skipped.
Index: tags/unmaintained/4/kdevelop4-extra-libraries/veritas/README
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-libraries/veritas/README (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-libraries/veritas/README (revision 1522570)
@@ -0,0 +1,11 @@
+Veritas has moved to Git.
+
+Put the following in your ~/.gitconfig:
+
+ [url "git://anongit.kde.org/"]
+ insteadOf = kde:
+ [url "ssh://git@git.kde.org/"]
+ pushInsteadOf = kde:
+
+Then to clone Veritas:
+ $ git clone kde:veritas
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop (revision 1522570)
@@ -0,0 +1,55 @@
+[Desktop Entry]
+Icon=kdevelop
+Type=Service
+ServiceTypes=KCModule
+
+X-KDE-ModuleType=Library
+X-KDE-Library=kcm_kdev_lcovsettings
+X-KDE-FactoryName=kcm_kdev_lcovsettings
+X-KDE-ParentApp=kdevplatform
+X-KDE-ParentComponents=kdevplatform
+
+Name=lcov settings
+Name[bs]=icov postavke
+Name[ca]=Arranjament de lcov
+Name[ca@valencia]=Arranjament de lcov
+Name[de]=LCov-Einstellungen
+Name[en_GB]=lcov settings
+Name[es]=Preferencias de lcov
+Name[et]=LCovi seadistused
+Name[fr]=Paramètres de lcov
+Name[ga]=Socruithe lcov
+Name[gl]=Configuración de Icov
+Name[hu]=lcov beállítások
+Name[it]=Impostazioni di lcov
+Name[nl]=lcov instellingen
+Name[pl]=Ustawienia lcov
+Name[pt]=Configuração do Lcov
+Name[pt_BR]=Configuração do lcov
+Name[sv]=Inställningar av Lcov
+Name[tr]=Lcov ayarları
+Name[uk]=Параметри lcov
+Name[x-test]=xxlcov settingsxx
+Comment=Configure lcov settings
+Comment[bs]=Konfiguracija Icov postavki
+Comment[ca]=Configura l'arranjament de lcov
+Comment[ca@valencia]=Configura l'arranjament de lcov
+Comment[de]=lcov-Einstellungen festlegen
+Comment[en_GB]=Configure lcov settings
+Comment[es]=Configurar las preferencias de lcov
+Comment[et]=LCovi seadistamine
+Comment[fr]=Configurer les paramètres de Icov
+Comment[ga]=Cumraigh socruithe lcov
+Comment[gl]=Configurar as opcións de Icov
+Comment[hu]=Icov beállítások módosítása
+Comment[it]=Configura le impostazioni di lcov
+Comment[nds]=lcov instellen
+Comment[nl]=Configureert lcov instellingen
+Comment[pl]=Ustawienia lcov
+Comment[pt]=Configurar as opções do 'lcov'
+Comment[pt_BR]=Configurar as opções do 'lcov'
+Comment[sv]=Anpassa inställningar av Lcov
+Comment[tr]=lcov ayarlarını yapılandır
+Comment[uk]=Налаштувати параметри lcov
+Comment[x-test]=xxConfigure lcov settingsxx
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop (revision 1522570)
@@ -0,0 +1,53 @@
+[Desktop Entry]
+Type=Service
+Icon=kdevelop
+Exec=blubb
+Comment=Gcov C(++) coverage
+Comment[bs]=Gcov C(++) pokrivenost
+Comment[ca]=Cobertura Gcov C(++)
+Comment[ca@valencia]=Cobertura Gcov C(++)
+Comment[de]=Gcov-C(++)-Testabdeckung
+Comment[en_GB]=Gcov C(++) coverage
+Comment[es]=Cobertura Gcov C(++)
+Comment[et]=Gcov C(++) kaetus
+Comment[fr]=Couverture de Gcov C(++)
+Comment[gl]=Cobertura de C(++) de Gcov
+Comment[it]=Copertura di C(++) Gcov
+Comment[nds]=GCov-C(++)-Afdecken
+Comment[nl]=Gcov C(++) coverage
+Comment[pl]=Pokrycie Gcov C(++)
+Comment[pt]=Cobertura de C(++) Gcov
+Comment[pt_BR]=Cobertura de C(++) Gcov
+Comment[sv]=Gcov C(++)-täckningsverktyg
+Comment[uk]=Покриття Gcov C(++)
+Comment[x-test]=xxGcov C(++) coveragexx
+
+Name=Code Coverage Report
+Name[bs]=Izvještaj pokrivenosti koda
+Name[ca]=Informe de cobertura del codi
+Name[ca@valencia]=Informe de cobertura del codi
+Name[de]=Bericht zur Testabdeckung
+Name[en_GB]=Code Coverage Report
+Name[es]=Informe de cobertura del código
+Name[et]=Koodi kaetuse aruanne
+Name[fr]=Rapport de couverture de code
+Name[gl]=Informe de cobertura de código
+Name[it]=Resoconto copertura del codice
+Name[nds]=Kodeafdeck-Bericht
+Name[nl]=Code Coverage Rapportage
+Name[pl]=Sprawozdanie pokrycia kodu
+Name[pt]=Relatório de Cobertura do Código
+Name[pt_BR]=Relatório de cobertura do código
+Name[sv]=Kodtäckningsrapport
+Name[uk]=Звіт щодо покриття коду
+Name[x-test]=xxCode Coverage Reportxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevcoverage
+X-KDE-PluginInfo-Name=coverageplugin
+X-KDE-PluginInfo-Author=Manuel Breugelmans
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=LGPL
+X-KDevelop-Version=15
+X-KDevelop-Category=Global
+X-KDevelop-IRequired=org.kdevelop.IOutputView
+X-KDevelop-Mode=GUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg (revision 1522570)
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
+ http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">
+ <kcfgfile name="kdeveloprc"/>
+ <group name="Code Coverage">
+ <entry name="geninfoPath" key="geninfoPath" type="Url">
+ <default>file:///usr/bin/geninfo</default>
+ <label>Specifies which geninfo executable to use to generate coverage information</label>
+ <whatsthis>The geninfo executable from the lcov toolset is needed to create a visualizable format from gcov code coverage data.
+ </whatsthis>
+ </entry>
+ </group>
+</kcfg>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.cpp (revision 1522570)
@@ -0,0 +1,484 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "reportwidget.h"
+#include "annotationmanager.h"
+#include "buildpathselection.h"
+#include "coveredfile.h"
+#include "drilldownview.h"
+#include "reportmodel.h"
+#include "reportproxymodel.h"
+#include "lcovinfoparser.h"
+#include "lcovjob.h"
+#include "covoutputdelegate.h"
+#include "removegcdafilesjob.h"
+#include "ui_reportwidget.h"
+
+#include <QTimer>
+#include <KLocale>
+#include <KComboBox>
+#include <KIcon>
+#include <KMessageBox>
+#include <KProcess>
+#include <KUrlNavigator>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocument.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/iuicontroller.h>
+#include <interfaces/iprojectcontroller.h>
+#include <interfaces/iproject.h>
+#include <interfaces/iruncontroller.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+
+using KDevelop::ICore;
+using KDevelop::IDocument;
+using KDevelop::IDocumentController;
+using KDevelop::IProject;
+using KDevelop::IProjectController;
+using KDevelop::IBuildSystemManager;
+
+using Veritas::AnnotationManager;
+using Veritas::BuildPathSelection;
+using Veritas::CoveredFile;
+using Veritas::CovOutputDelegate;
+using Veritas::DrillDownView;
+using Veritas::LcovInfoParser;
+using Veritas::LcovJob;
+using Veritas::RemoveGcdaFilesJob;
+using Veritas::ReportWidget;
+using Veritas::ReportDirData;
+using Veritas::ReportModel;
+using Veritas::ReportViewFactory;
+
+//////////////////////////////// ReportWidget ///////////////////////////////
+
+void ReportWidget::resizeEvent(QResizeEvent* event)
+{
+ Q_UNUSED(event);
+ installEventFilter(this);
+ switch(m_state) {
+ case DirView: { table()->resizeDirStateColumns(); break; }
+ case FileView: { table()->resizeFileStateColumns(); break; }
+ default: { Q_ASSERT(0); }
+ }
+ removeEventFilter(this);
+}
+
+bool ReportWidget::eventFilter(QObject* obj, QEvent* event)
+{
+ if (event->type()==QEvent::Resize) {
+ return true;
+ }
+ return QWidget::eventFilter(obj, event);
+}
+
+DrillDownView* ReportWidget::table() const
+{
+ return m_ui->table;
+}
+
+void ReportWidget::init()
+{
+ m_ui = new Ui::ReportWidget();
+ m_ui->setupUi(this);
+
+ //KUrlNavigator can't be set using a placeholder in Qt Designer as there is
+ //no KUrlNavigator(QWidget*) constructor
+ int startButtonIndex = m_ui->buildPathSelectionLayout->indexOf(m_ui->lcovJobButton);
+ m_targetDirectory = new KUrlNavigator(0, KUrl(QDir::homePath()), this);
+ m_ui->buildPathSelectionLayout->insertWidget(startButtonIndex, m_targetDirectory);
+
+ BuildPathSelection* buildPathSelection = new BuildPathSelection(m_targetDirectory, this);
+
+ //ProjectSelection widget can't be set using Qt Designer, as it is got from
+ //a method of a non widget class
+ int getFromProjectTextLabelIndex = m_ui->projectSelectionLayout->indexOf(m_ui->getFromProjectTextLabel);
+ QWidget* projectSelectionWidget = buildPathSelection->requestProjectSelectionWidget(m_ui->buildPathFrame);
+ m_ui->projectSelectionLayout->insertWidget(getFromProjectTextLabelIndex + 1, projectSelectionWidget);
+
+ if (qobject_cast<KComboBox*>(projectSelectionWidget) != 0) {
+ static_cast<KComboBox*>(projectSelectionWidget)->setSizeAdjustPolicy(QComboBox::AdjustToContents);
+ }
+
+ setStartLcovJobButton();
+ connect(m_ui->lcovJobButton, SIGNAL(clicked(bool)), SLOT(startOrStopLcovJob()));
+
+ setStartRemoveGcdaFilesJobButton();
+ connect(m_ui->removeGcdaFilesJobButton, SIGNAL(clicked(bool)), SLOT(startOrStopRemoveGcdaFilesJob()));
+
+ connect(table(), SIGNAL(doubleClicked(QModelIndex)),
+ SLOT(dispatchDoubleClickedSignal(QModelIndex)));
+
+ connect(table(), SIGNAL(completedSlideLeft()), SLOT(setDirViewState()));
+ connect(table(), SIGNAL(completedSlideRight()), SLOT(setFileViewState()));
+
+ m_timer->setInterval(50);
+ m_timer->setSingleShot(true);
+ connect(m_timer, SIGNAL(timeout()), this, SLOT(updateTableView()));
+}
+
+void ReportWidget::updateTableView()
+{
+ if (m_timerTicks < 10) {
+ table()->viewport()->update();
+ m_timerTicks += 1;
+ m_timer->start();
+ }
+}
+
+ReportWidget::ReportWidget(QWidget* parent) :
+ QWidget(parent),
+ m_state(ReportWidget::DirView),
+ m_manager(0),
+ m_proxy(0),
+ m_model(0),
+ m_timer(new QTimer(this)),
+ m_targetDirectory(0),
+ m_delegate(new CovOutputDelegate(this)),
+ m_ui(0)
+{
+ setObjectName("Coverage Report");
+ setWindowIcon(SmallIcon("system-file-manager"));
+}
+
+#define ILLEGAL_STATE \
+ Q_ASSERT_X(0, "ReportWidget::signalDispatch", \
+ "Serious corruption, impossible m_state value.")
+
+void ReportWidget::dispatchSelectionSignal(const QItemSelection& selected, const QItemSelection& deselected)
+{
+ switch(m_state) {
+ case DirView: {
+ setCoverageStatistics(selected, deselected); break;
+ } case FileView: {
+ /*jumpToSource(selected, deselected); */break;
+ } default: {
+ ILLEGAL_STATE;
+ }}
+}
+
+void ReportWidget::dispatchDoubleClickedSignal(const QModelIndex& index)
+{
+ switch(m_state) {
+ case DirView: {
+ table()->slideRight(index); break;
+ } case FileView: {
+ jumpToSource(index); break;
+ } default: {
+ ILLEGAL_STATE;
+ }}
+}
+
+void ReportWidget::jumpToSource(const QItemSelection& selected, const QItemSelection& deselected)
+{
+ Q_UNUSED(selected);
+ Q_UNUSED(deselected);
+ // TODO
+}
+
+void ReportWidget::jumpToSource(const QModelIndex& index)
+{
+ QStandardItem* item = getItemFromProxyIndex(index);
+ if (!item || item->type() != ReportModel::File ) return;
+ ReportFileItem* file = static_cast<ReportFileItem*>(item);
+ Q_ASSERT(file);
+
+ IDocumentController* dc = ICore::self()->documentController();
+ kDebug() << "Open doc with coverage annotations " << file->url();
+ KTextEditor::Cursor cursor;
+ IDocument* doc;
+ doc = dc->openDocument(file->url(), cursor);
+ if (!doc || !doc->isTextDocument()) return;
+ Q_ASSERT(m_manager);
+ m_manager->watch(doc);
+ dc->activateDocument(doc);
+}
+
+void ReportWidget::reset_()
+{
+ m_proxy->invalidate();
+ filterBox()->clear();
+ table()->viewport()->update();
+ m_timerTicks = 0;
+ m_timer->start(); // TODO figure out the correct signal instead of this kludge
+}
+
+void ReportWidget::setDirViewState()
+{
+ m_state = ReportWidget::DirView;
+ m_proxy->setDirViewState();
+ reset_();
+ table()->resizeDirStateColumns();
+ filterBox()->setReadOnly(false);
+ filterBox()->setText(m_oldDirFilter);
+
+ //When the view slides to the left, the previously selected directories are
+ //selected again. However, until the slide is completed we are in File
+ //state, so the statistics aren't updated.
+ m_ui->sloc->setText("0");
+ m_ui->nrofCoveredLines->setText("0");
+ setCoverageStatistics(table()->selectionModel()->selection(), QItemSelection());
+}
+
+QLineEdit* ReportWidget::filterBox() const //krazy:exclude=qclasses
+{
+ return m_ui->filterBox;
+}
+
+void ReportWidget::setFileViewState()
+{
+ m_state = ReportWidget::FileView;
+ m_proxy->setFileViewState();
+ m_oldDirFilter = filterBox()->text();
+ reset_();
+ table()->resizeFileStateColumns();
+ filterBox()->setReadOnly(true);
+
+ //Set the statistics for the current directory
+ setCoverageStatistics(table()->rootIndex());
+}
+
+ReportWidget::~ReportWidget()
+{
+ delete m_ui;
+}
+
+QStandardItem* ReportWidget::getItemFromProxyIndex(const QModelIndex& index) const
+{
+ if (!index.isValid()) {
+ kDebug() << "Invalid index";
+ return 0;
+ }
+ QModelIndex sourceIndex = m_proxy->mapToSource(index);
+ QStandardItem* item = m_model->itemFromIndex(sourceIndex);
+ Q_ASSERT(item);
+ return item;
+}
+
+const ReportDirData* ReportWidget::getReportDirDataFromProxyIndex(const QModelIndex& index) const
+{
+ QStandardItem* item = getItemFromProxyIndex(index);
+ if (!item || item->type() != ReportModel::Dir) return 0;
+
+ return &static_cast<ReportDirItem*>(item)->reportDirData();
+}
+
+void ReportWidget::setCoverageStatistics(const ReportDirData& data)
+{
+ //QLocale used as QString::number does not honor the user's locale setting
+ m_ui->coverageRatio->setText(QLocale().toString(data.coverageRatio(), 'f', 1) + " %");
+ m_ui->coverageRatio->update();
+ m_ui->sloc->setText(QString::number(data.sloc()));
+ m_ui->sloc->update();
+ m_ui->nrofCoveredLines->setText(QString::number(data.nrofCoveredLines()));
+ m_ui->nrofCoveredLines->update();
+}
+
+void ReportWidget::setCoverageStatistics(const QModelIndex& index)
+{
+ const ReportDirData* data = getReportDirDataFromProxyIndex(index);
+ if (!data) {
+ return;
+ }
+
+ setCoverageStatistics(*data);
+}
+
+void ReportWidget::setCoverageStatistics(const QItemSelection& selected, const QItemSelection& deselected)
+{
+ ReportDirData fullData;
+ if (m_ui->sloc->text() != "-" && m_ui->nrofCoveredLines->text() != "-") {
+ fullData.setSloc(m_ui->sloc->text().toInt());
+ fullData.setNrofCoveredLines(m_ui->nrofCoveredLines->text().toInt());
+ }
+
+ bool statisticsChanged = false;
+
+ foreach (const QModelIndex& index, selected.indexes()) {
+ const ReportDirData* data = getReportDirDataFromProxyIndex(index);
+ if (data) {
+ statisticsChanged = true;
+ fullData.setSloc(fullData.sloc() + data->sloc());
+ fullData.setNrofCoveredLines(fullData.nrofCoveredLines() + data->nrofCoveredLines());
+ }
+ }
+
+ foreach (const QModelIndex& index, deselected.indexes()) {
+ const ReportDirData* data = getReportDirDataFromProxyIndex(index);
+ if (data) {
+ statisticsChanged = true;
+ fullData.setSloc(fullData.sloc() - data->sloc());
+ fullData.setNrofCoveredLines(fullData.nrofCoveredLines() - data->nrofCoveredLines());
+ }
+ }
+
+ if (statisticsChanged) {
+ setCoverageStatistics(fullData);
+ }
+}
+
+void ReportWidget::startOrStopLcovJob()
+{
+ if (!m_lcovJob) {
+ startLcovJob();
+ } else {
+ m_lcovJob->kill(KJob::EmitResult);
+ }
+}
+
+void ReportWidget::startLcovJob()
+{
+ Q_ASSERT(m_delegate); Q_ASSERT(m_targetDirectory);
+
+ if (m_state == FileView) {
+ filterBox()->setReadOnly(false);
+ filterBox()->setText(m_oldDirFilter);
+ } else {
+ m_oldDirFilter = filterBox()->text();
+ }
+
+ m_ui->coverageRatio->setText("-");
+ m_ui->nrofCoveredLines->setText("-");
+ m_ui->sloc->setText("-");
+
+ m_state = DirView;
+
+ if (m_model) delete m_model;
+ if (m_manager) delete m_manager;
+ if (m_proxy) delete m_proxy;
+
+ m_model = new ReportModel(this);
+ m_model->setRootDirectory( m_targetDirectory->url() );
+ m_manager = new AnnotationManager(this);
+ m_proxy = new ReportProxyModel(this);
+ table()->setModel(m_proxy);
+ m_proxy->setSourceModel(m_model);
+ m_proxy->setFilterWildcard(m_oldDirFilter);
+
+ //Since Qt 4.1 (or maybe 4.0, but not documented), setting the model
+ //replaces the previous selection model, so it must be connected again
+ //http://doc.trolltech.com/4.1/qabstractitemview.html#setModel
+ connect(table()->selectionModel(),
+ SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
+ SLOT(dispatchSelectionSignal(QItemSelection,QItemSelection)));
+
+ setStopLcovJobButton();
+ m_ui->removeGcdaFilesJobButton->setEnabled(false);
+
+ LcovJob* job = new LcovJob(m_targetDirectory->url(), m_delegate);
+ LcovInfoParser* parser = new LcovInfoParser(job);
+
+ connect(parser, SIGNAL(parsedCoverageData(CoveredFile*)), m_model, SLOT(addCoverageData(CoveredFile*)));
+ connect(parser, SIGNAL(parsedCoverageData(CoveredFile*)), m_manager, SLOT(addCoverageData(CoveredFile*)));
+ connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(updateColumns()));
+ connect(filterBox(), SIGNAL(textChanged(QString)), m_proxy, SLOT(setFilterWildcard(QString)));
+
+ job->setDelegate(m_delegate);
+ job->setProcess(new KProcess);
+ job->setParser(parser);
+
+ connect(job, SIGNAL(finished(KJob*)), SLOT(updateStateWhenLcovJobFinishes()));
+
+ m_lcovJob = job;
+
+ ICore::self()->runController()->registerJob(job);
+}
+
+void ReportWidget::updateStateWhenLcovJobFinishes()
+{
+ setStartLcovJobButton();
+ m_ui->removeGcdaFilesJobButton->setEnabled(true);
+}
+
+void ReportWidget::setStartLcovJobButton()
+{
+ m_ui->lcovJobButton->setToolTip(i18nc("@info:tooltip", "Start coverage analysis"));
+ m_ui->lcovJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Start coverage analysis in the specified path.</para>\n"
+"<para>The directory and, recursively, its subdirectories are scanned for .gcda files.</para>"));
+ m_ui->lcovJobButton->setIcon(KIcon("arrow-right"));
+}
+
+void ReportWidget::setStopLcovJobButton()
+{
+ m_ui->lcovJobButton->setToolTip(i18nc("@info:tooltip", "Stop coverage analysis"));
+ m_ui->lcovJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Stop coverage analysis killing <command>geninfo</command> process.</para>"));
+ m_ui->lcovJobButton->setIcon(KIcon("process-stop"));
+}
+
+void ReportWidget::startOrStopRemoveGcdaFilesJob()
+{
+ if (!m_removeGcdaFilesJob) {
+ if (KMessageBox::warningContinueCancel(this, i18nc("@info", "Remove all the .gcda files in <filename>%1</filename> directory and, recursively, in its subdirectories?", m_targetDirectory->url().toLocalFile()),
+ i18nc("@title:window", "Remove .gcda files")) == KMessageBox::Continue) {
+ startRemoveGcdaFilesJob();
+ }
+ } else {
+ m_removeGcdaFilesJob->kill(KJob::EmitResult);
+ }
+}
+
+void ReportWidget::startRemoveGcdaFilesJob()
+{
+ Q_ASSERT(m_targetDirectory);
+
+ setStopRemoveGcdaFilesJobButton();
+ m_ui->lcovJobButton->setEnabled(false);
+
+ RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_targetDirectory->url(), this);
+ connect(job, SIGNAL(finished(KJob*)), SLOT(updateStateWhenRemoveGcdaFilesJobFinishes()));
+
+ m_removeGcdaFilesJob = job;
+
+ ICore::self()->runController()->registerJob(job);
+}
+
+void ReportWidget::updateStateWhenRemoveGcdaFilesJobFinishes()
+{
+ setStartRemoveGcdaFilesJobButton();
+ m_ui->lcovJobButton->setEnabled(true);
+}
+
+void ReportWidget::setStartRemoveGcdaFilesJobButton()
+{
+ m_ui->removeGcdaFilesJobButton->setToolTip(i18nc("@info:tooltip", "Remove coverage data"));
+ m_ui->removeGcdaFilesJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Remove coverage data from the specified path.</para>\n"
+"<para>The .gcda files are removed in the given directory and, recursively, its subdirectories.</para>"));
+ m_ui->removeGcdaFilesJobButton->setIcon(KIcon("edit-delete"));
+}
+
+void ReportWidget::setStopRemoveGcdaFilesJobButton()
+{
+ m_ui->removeGcdaFilesJobButton->setToolTip(i18nc("@info:tooltip", "Stop removing coverage data"));
+ m_ui->removeGcdaFilesJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Stop removing coverage data from the specified path.</para>"));
+ m_ui->removeGcdaFilesJobButton->setIcon(KIcon("process-stop"));
+}
+
+void ReportWidget::updateColumns()
+{
+ switch(m_state) {
+ case DirView: { table()->resizeDirStateColumns(); break; }
+ case FileView: { table()->resizeFileStateColumns(); break; }
+ default: { Q_ASSERT(0); }
+ }
+}
+
+#include "reportwidget.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.h (revision 1522570)
@@ -0,0 +1,208 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REPORTWIDGET_H
+#define VERITAS_COVERAGE_REPORTWIDGET_H
+
+#include <QPointer>
+#include <QtGui/QWidget>
+#include <KUrl>
+#include <interfaces/iuicontroller.h>
+#include "coverageexport.h"
+
+class QAbstractItemView;
+class QItemSelection;
+class QLineEdit;
+class QModelIndex;
+class QStandardItem;
+class QTableView;
+class KJob;
+class KUrlNavigator;
+
+namespace Ui
+{
+class ReportWidget;
+}
+
+namespace Veritas
+{
+
+class AnnotationManager;
+class CoveredFile;
+class DrillDownView;
+class LcovInfoParser;
+class ReportDirData;
+class ReportModel;
+class ReportProxyModel;
+class ReportViewFactory;
+class CovOutputDelegate;
+
+/*! Coverage report main widget, as shown in the toolview
+ * @unittest Veritas::ReportWidgetTest */
+class VERITAS_COVERAGE_EXPORT ReportWidget : public QWidget
+{
+Q_OBJECT
+public:
+ explicit ReportWidget(QWidget* parent = 0);
+ virtual ~ReportWidget();
+
+ /*! initialize child widgets and connects signals.
+ called by ReportViewFactory after construction */
+ void init();
+
+private Q_SLOTS:
+ void dispatchSelectionSignal(const QItemSelection&, const QItemSelection&);
+ void dispatchDoubleClickedSignal(const QModelIndex&);
+
+ void setDirViewState();
+ void setFileViewState();
+ void updateTableView();
+ void updateColumns();
+
+ /*!
+ * Starts or stops the lcov job depending on whether there is a job already
+ * running or not.
+ */
+ void startOrStopLcovJob();
+
+ /*!
+ * Restores the widgets changed when the lcov job was started.
+ */
+ void updateStateWhenLcovJobFinishes();
+
+ /*!
+ * Starts or stops the remove gcda files job depending on whether there is a
+ * job already running or not.
+ */
+ void startOrStopRemoveGcdaFilesJob();
+
+ /*!
+ * Restores the widgets changed when the remove gcda files job was started.
+ */
+ void updateStateWhenRemoveGcdaFilesJobFinishes();
+
+private:
+
+ /*!
+ * Starts the lcov job.
+ */
+ void startLcovJob();
+
+ /*!
+ * Starts the remove gcda files job.
+ */
+ void startRemoveGcdaFilesJob();
+
+ /*!
+ * Sets the icon and texts of lcov job button to start the job.
+ */
+ void setStartLcovJobButton();
+
+ /*!
+ * Sets the icon and texts of lcov job button to stop the job.
+ */
+ void setStopLcovJobButton();
+
+ /*!
+ * Sets the icon and texts of remove gcda files job button to start the job.
+ */
+ void setStartRemoveGcdaFilesJobButton();
+
+ /*!
+ * Sets the icon and texts of remove gcda files job button to stop the job.
+ */
+ void setStopRemoveGcdaFilesJobButton();
+
+ /*!
+ * Returns the ReportDirData used in the item identified by the index.
+ * If no ReportDirData exists for that index (that is, if the index does
+ * not identify a ReportDirItem), a null pointer is returned.
+ *
+ * @param index The index in the model of the table.
+ * @return The data if it exists, a null pointer otherwise.
+ */
+ const ReportDirData* getReportDirDataFromProxyIndex(const QModelIndex&) const;
+
+ /*!
+ * Updates the coverage statistics labels with the specified data.
+ * Coverage percentage is shown with 1 decimal. SLOC and instrumented lines
+ * are plain integers.
+ *
+ * @param data The data to set.
+ */
+ void setCoverageStatistics(const ReportDirData&);
+
+ /*!
+ * Updates the coverage statistics labels for the selection change.
+ * The newly selected directories data is added to the statistics, and the
+ * deselected directories data is removed from them. File items are
+ * ignored. If there is no directory, the statistics aren't modified.
+ *
+ * @param selected The newly selected items.
+ * @param deselected The deselected items.
+ * @see setCoverageStatistics(const ReportDirData&)
+ */
+ void setCoverageStatistics(const QItemSelection&, const QItemSelection&);
+
+ /*!
+ * Updates the coverage statistics labels for the specified index.
+ * The statistics are set to the data of the directory identified by the
+ * index. If it is not a directory, the statistics aren't modified.
+ *
+ * @param index The index of the item.
+ * @see setCoverageStatistics(const ReportDirData&)
+ */
+ void setCoverageStatistics(const QModelIndex&);
+
+ /*! open source file in editor */
+ void jumpToSource(const QItemSelection&, const QItemSelection&);
+ void jumpToSource(const QModelIndex&);
+
+ /*! fetch the item corresponding to a view index. returns 0 on failure */
+ QStandardItem* getItemFromProxyIndex(const QModelIndex&) const;
+ DrillDownView* table() const;
+ QLineEdit* filterBox() const; //krazy:exclude=qclasses
+
+ /*! totally reset the widget */
+ void reset_();
+
+protected:
+ void resizeEvent(QResizeEvent* event);
+ bool eventFilter(QObject* obj, QEvent* event);
+
+private:
+ friend class ReportViewFactory;
+ enum State { DirView, FileView } m_state;
+ AnnotationManager* m_manager;
+ ReportProxyModel* m_proxy;
+ ReportModel* m_model;
+ QTimer* m_timer;
+ int m_timerTicks;
+ QString m_oldDirFilter;
+ KUrlNavigator* m_targetDirectory; // lets the user select a directory to run coverage on
+ CovOutputDelegate* m_delegate;
+ Ui::ReportWidget* m_ui;
+ QPointer<KJob> m_lcovJob;
+ QPointer<KJob> m_removeGcdaFilesJob;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_REPORTWIDGET_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.cpp (revision 1522570)
@@ -0,0 +1,213 @@
+/* KDevelop coverage plugin
+ * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "lcovjob.h"
+#include "covoutputmodel.h"
+#include "covoutputdelegate.h"
+
+#include "lcovinfoparser.h"
+#include "lcovjobprogress.h"
+#include "coveredfile.h"
+#include "annotationmodel.h"
+#include "annotationmanager.h"
+#include "reportwidget.h"
+
+#include <QDir>
+#include <QTableWidget>
+
+#include <KProcess>
+#include <KLocale>
+#include <KConfigGroup>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <util/processlinemaker.h>
+#include <shell/core.h>
+
+#include <ktexteditor/annotationinterface.h>
+#include <ktexteditor/cursor.h>
+#include <ktexteditor/document.h>
+
+using KDevelop::ICore;
+using KDevelop::Core;
+using KDevelop::IDocument;
+using KDevelop::IDocumentController;
+using KDevelop::IOutputView;
+using KDevelop::IToolViewFactory;
+using KDevelop::ProcessLineMaker;
+
+using KTextEditor::AnnotationModel;
+using KTextEditor::AnnotationInterface;
+using KTextEditor::AnnotationViewInterface;
+using KTextEditor::Document;
+
+using Veritas::CoveredFile;
+using Veritas::LcovJob;
+using Veritas::LcovJobProgress;
+using Veritas::CovOutputModel;
+using Veritas::CovOutputDelegate;
+using Veritas::LcovInfoParser;
+using Veritas::AnnotationManager;
+using Veritas::ReportViewFactory;
+
+LcovJob::LcovJob(const KUrl& root, QObject* parent)
+ : OutputJob(parent), m_lcov(0), m_root(root), m_parser(0)
+{
+ setCapabilities(Killable);
+ setObjectName(i18nc("@action:inmenu", "Run <command>geninfo</command> on <filename>%1</filename> directory", root.toLocalFile()));
+
+ m_lcovJobProgress = new LcovJobProgress(this);
+ ICore::self()->uiController()->registerStatus(m_lcovJobProgress);
+ connect(this, SIGNAL(result(KJob*)), m_lcovJobProgress, SLOT(finish()));
+}
+
+LcovJob::~LcovJob()
+{}
+
+void LcovJob::setDelegate(CovOutputDelegate* delegate)
+{
+ OutputJob::setDelegate(delegate);
+}
+
+void LcovJob::setParser(LcovInfoParser* parser)
+{
+ Q_ASSERT(parser); Q_ASSERT(m_parser == 0);
+ m_parser = parser;
+}
+
+void LcovJob::setProcess(KProcess *proc)
+{
+ Q_ASSERT(proc);
+ m_lcov = proc;
+ m_lcov->setParent(this);
+}
+
+void LcovJob::initProcess()
+{
+ Q_ASSERT_X(m_lcov, "LcovJob::initProcess()", "illegal usage, set process first.");
+ QStringList args;
+ //m_tmpPath = QDir::tempPath() + QDir::separator() + "kdevcoverage.tmp";
+ QString root = m_root.pathOrUrl();
+ if (root.endsWith(QLatin1String("./"))) root.chop(3);
+ args << "-o"
+ //<< m_tmpPath
+ << "-"
+ << m_root.pathOrUrl();
+ KConfigGroup grp = KGlobal::config()->group("Code Coverage");
+ KUrl geninfo = grp.readEntry("geninfoPath", KUrl("/usr/bin/geninfo") );
+ m_lcov->setProgram( geninfo.toLocalFile(), args);
+ m_lcov->setWorkingDirectory(m_root.pathOrUrl());
+ m_lcov->setOutputChannelMode(KProcess::SeparateChannels);
+ m_lineMaker = new ProcessLineMaker(m_lcov);
+
+ //Ensure that the process output will be untranslated
+ m_lcov->unsetEnv("LC_ALL");
+ m_lcov->setEnv("LC_MESSAGES", "C");
+
+ //connect(m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
+ // model(), SLOT(appendOutputs(QStringList)));
+ connect(m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
+ model(), SLOT(appendErrors(QStringList)));
+ connect(m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
+ m_lcovJobProgress, SLOT(parseLines(QStringList)));
+ connect(m_lcov, SIGNAL(finished(int,QProcess::ExitStatus)),
+ this, SLOT(slotFinished()));
+ connect(m_lcov, SIGNAL(error(QProcess::ProcessError)),
+ this, SLOT(slotError(QProcess::ProcessError)));
+}
+
+void LcovJob::initOutputView()
+{
+ setToolTitle(i18n("Cov verbose output"));
+ setViewType(KDevelop::IOutputView::HistoryView);
+ setStandardToolView(KDevelop::IOutputView::TestView);
+ setBehaviours(IOutputView::AutoScroll | IOutputView::AllowUserClose);
+ setModel(new CovOutputModel(0));
+}
+
+void LcovJob::initParser()
+{
+ Q_ASSERT(m_parser);
+ connect(m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
+ m_parser, SLOT(parseLines(QStringList)));
+}
+
+
+void LcovJob::start()
+{
+ initOutputView();
+ startOutput();
+ initProcess();
+ initParser();
+ m_lcovJobProgress->start();
+ m_lcov->start();
+}
+
+void LcovJob::slotFinished()
+{
+ m_lineMaker->flushBuffers();
+ model()->slotCompleted();
+ emitResult();
+}
+
+void LcovJob::slotError(QProcess::ProcessError error)
+{
+ QStringList errorList;
+ if (error == QProcess::FailedToStart) {
+ //i18nc can't be used. It seems that at this moment (2009-09-04) only
+ //plain text can be used in the outputview
+ //errorList << i18nc("@info", "Failed to start <filename>%1</filename>. Make sure that the path to <command>geninfo</command> is specified correctly in <interface>Settings->Configure KDevelop...->Lcov Preferences->geninfo Executable</interface>.", m_lcov->program().first());
+ errorList << i18n("Failed to start '%1'. Make sure that the path to geninfo is specified correctly in Settings->Configure KDevelop...->Lcov Preferences->geninfo Executable.", m_lcov->program().first());
+ } else if (error == QProcess::Crashed) {
+ errorList << i18n("geninfo process crashed.");
+ } else if (error == QProcess::Timedout) {
+ errorList << i18n("geninfo process timed out.");
+ } else if (error == QProcess::WriteError) {
+ errorList << i18n("Failed to write to geninfo process.");
+ } else if (error == QProcess::ReadError) {
+ errorList << i18n("Failed to read from geninfo process.");
+ } else if (error == QProcess::UnknownError) {
+ errorList << i18n("Unknown geninfo process error.");
+ }
+ model()->appendErrors(errorList);
+
+ m_lineMaker->flushBuffers();
+ model()->slotCompleted();
+ m_lcov->kill();
+ setError(UserDefinedError);
+ emitResult();
+}
+
+CovOutputModel* LcovJob::model() const
+{
+ return static_cast<CovOutputModel*>(OutputJob::model());
+}
+
+bool LcovJob::doKill()
+{
+ m_lcov->kill();
+
+ model()->appendErrors(QStringList() << i18n("geninfo process was killed"));
+
+ return true;
+}
+
+#include "lcovjob.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp (revision 1522570)
@@ -0,0 +1,58 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "covoutputdelegate.h"
+#include "covoutputmodel.h"
+#include <QtGui/QPainter>
+#include <QtCore/QModelIndex>
+
+using Veritas::CovOutputDelegate;
+
+CovOutputDelegate::CovOutputDelegate(QObject* parent)
+ : QItemDelegate(parent),
+ textBrush(KColorScheme::View, KColorScheme::NormalText),
+ processBrush(KColorScheme::View, KColorScheme::PositiveText),
+ warningBrush(KColorScheme::View, KColorScheme::NeutralText),
+ errorBrush(KColorScheme::View, KColorScheme::NegativeText)
+{}
+
+CovOutputDelegate::~CovOutputDelegate()
+{}
+
+void CovOutputDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
+ const QModelIndex& index) const
+{
+ QStyleOptionViewItem opt = option;
+ opt.palette.setBrush(QPalette::Text, textBrush.brush(option.palette));
+ QString text = index.data().toString();
+ if (text.startsWith(QLatin1String("Processing"))) {
+ opt.palette.setBrush(QPalette::Text, processBrush.brush(option.palette));
+ } else if (text.contains("source file is newer than graph file")) {
+ opt.palette.setBrush(QPalette::Text, warningBrush.brush(option.palette));
+ } else if (text.contains("WARNING:")) {
+ opt.palette.setBrush(QPalette::Text, warningBrush.brush(option.palette));
+ } else if (text.contains("ERROR:")) {
+ opt.palette.setBrush(QPalette::Text, errorBrush.brush(option.palette));
+ }
+ QItemDelegate::paint(painter, opt, index);
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp (revision 1522570)
@@ -0,0 +1,135 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "lcovinfoparser.h"
+#include <QFile>
+#include <QTextStream>
+#include <QStringList>
+#include <KDebug>
+#include "coveredfile.h"
+
+
+using Veritas::LcovInfoParser;
+using Veritas::CoveredFile;
+
+LcovInfoParser::LcovInfoParser(QObject* parent) : QObject(parent), m_current(0)
+{}
+
+LcovInfoParser::~LcovInfoParser()
+{
+ if (m_current) m_current->deleteLater();
+ foreach(CoveredFile* f, m_files) {
+ f->deleteLater();
+ }
+}
+
+namespace
+{
+
+inline bool firstTwoCharsEqual(const char* one, char* two)
+{
+ return !qstrncmp(one, two, 2);
+}
+
+}
+
+void LcovInfoParser::parseLines(const QStringList& lines)
+{
+ foreach(const QString& l, lines) parseLine(l);
+}
+
+void LcovInfoParser::parseLine(const QString& line)
+{
+ // # SF:<absolute path to the source file>
+// # FN:<line number of function start>,<function name> for each function
+// # DA:<line number>,<execution count> for each instrumented line
+// # LH:<number of lines with an execution count> greater than 0
+// # LF:<number of instrumented lines>
+
+// SF:/usr/include/QtCore/qstringlist.h
+// FN:69,_ZN11QStringListD1Ev
+// FN:73,_ZN11QStringListC1ERKS_
+// FN:69,_ZN11QStringListaSERKS_
+// FN:85,_ZNK11QStringListplERKS_
+// FN:72,_ZN11QStringListC1ERK7QString
+// DA:69,36
+// DA:71,113
+// DA:72,88
+// DA:73,90
+// DA:74,0
+// DA:85,0
+// DA:86,0
+// DA:88,24
+// DA:90,0
+// LF:9
+// LH:5
+// end_of_record
+
+ if (line.count() < 3) return;
+ tmp_firstChar = line[0].toAscii();
+ tmp_secondChar = line[1].toAscii();
+ switch(tmp_firstChar) {
+ case 'D': {
+ if (tmp_secondChar != 'A') break;
+ // DA:<line number>,<execution count> for each instrumented line
+ Q_ASSERT(m_current);
+ //l = line.split(":");
+ tmp_f = line.mid(3, -1);
+ tmp_s = tmp_f.split(',');
+ int lineNumber = tmp_s.value(0).toInt();
+ int callCount = tmp_s.value(1).toInt();
+ m_current->setCallCount(lineNumber, callCount);
+ break;
+ } case 'F': { break;
+ } case 'S': {
+ if (tmp_secondChar != 'F') break;
+ // SF:<absolute path to the source file>
+ Q_ASSERT(m_current == 0);
+ m_current = new CoveredFile;
+ m_current->setUrl(KUrl(line.split(':').value(1)));
+ break;
+ } case 'L': {
+ /*if (tmp_secondChar == 'F') {
+ // # LF:<number of instrumented lines>
+ Q_ASSERT(m_current);
+ m_current->setSloc(line.split(":").value(1).toInt());
+ } else if (tmp_secondChar == 'H') {
+ // # LH:<number of lines with an execution count> greater than 0
+ Q_ASSERT(m_current);
+ m_current->setInstrumented(line.split(":").value(1).toInt());
+ }*/
+ break;
+ } case 'e': {
+ if (line.startsWith(QLatin1String("end_of_record"))) {
+ Q_ASSERT(m_current);
+ m_files << m_current;
+ emit parsedCoverageData(m_files.last());
+ m_current = 0;
+ }
+ break;
+ } default: {}}
+}
+
+QList<CoveredFile*> LcovInfoParser::fto_coveredFiles()
+{
+ return m_files;
+}
+
+#include "lcovinfoparser.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.cpp (revision 1522570)
@@ -0,0 +1,152 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "annotationmanager.h"
+#include "annotationmodel.h"
+#include "coveredfile.h"
+
+#include <interfaces/icore.h>
+#include <interfaces/idocument.h>
+#include <interfaces/idocumentcontroller.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+#include <ktexteditor/annotationinterface.h>
+#include <KDebug>
+
+using KDevelop::ICore;
+using KDevelop::IDocument;
+using KDevelop::IDocumentController;
+using KTextEditor::AnnotationViewInterface;
+
+using Veritas::AnnotationManager;
+using Veritas::AnnotationModel;
+
+namespace Veritas
+{
+
+AnnotationManager::AnnotationManager(QObject* parent)
+ : QObject(parent)
+{
+ IDocumentController* dc = ICore::self()->documentController();
+ connect(dc, SIGNAL(textDocumentCreated(KDevelop::IDocument*)),
+ this, SLOT(connectKDocWithTextDoc(KDevelop::IDocument*)));
+}
+
+AnnotationManager::~AnnotationManager()
+{
+ foreach(CoveredFile* f, m_files) {
+ delete f;
+ }
+}
+
+void AnnotationManager::connectKDocWithTextDoc(KDevelop::IDocument* doc)
+{
+ if (!m_docs.contains(doc)) return;
+ Q_ASSERT(doc->isTextDocument());
+ KTextEditor::Document* tdoc = doc->textDocument();
+ Q_ASSERT_X(tdoc, "AnnotationManager::watch()", "doc->textDoc() null.");
+ m_textDocUrls[tdoc] = doc->url();
+ tdoc->disconnect(this);
+ connect(tdoc, SIGNAL(viewCreated(KTextEditor::Document*,KTextEditor::View*)),
+ this, SLOT(fixAnnotation(KTextEditor::Document*,KTextEditor::View*)));
+}
+
+void AnnotationManager::setCoveredFiles(const QMap<KUrl, CoveredFile*>& files)
+{
+ m_files = files;
+}
+
+void AnnotationManager::watch(IDocument* doc)
+{
+ Q_ASSERT_X(doc, "AnotationManager::watch()", "got null document.");
+ Q_ASSERT(doc->isTextDocument());
+ m_docs << doc;
+ if (!doc->textDocument()) return;
+ m_textDocUrls[doc->textDocument()] = doc->url();
+ foreach(KTextEditor::View* view, doc->textDocument()->views()) {
+ fixAnnotation(doc->textDocument(), view);
+ }
+}
+
+void AnnotationManager::fixAnnotation(KTextEditor::Document* doc, KTextEditor::View* view)
+{
+ if (!m_textDocUrls.contains(doc)) {
+ kDebug() << "Shouldn't happen, got a doc for which no url was registered.";
+ return;
+ }
+ KUrl url = m_textDocUrls[doc];
+ if (!m_files.contains(url)) {
+ kDebug() << "No CoveredFile data available for " << url;
+ return;
+ }
+ CoveredFile* f = m_files[url];
+ Q_ASSERT(f);
+ AnnotationModel* model = new AnnotationModel(f, view);
+ AnnotationViewInterface *anno = qobject_cast<AnnotationViewInterface*>(view);
+ Q_ASSERT(anno);
+ anno->setAnnotationModel(model);
+ anno->setAnnotationBorderVisible(true);
+}
+
+void AnnotationManager::stopWatching(IDocument* doc)
+{
+ if (!m_docs.contains(doc)) return;
+ m_docs.removeOne(doc);
+ KTextEditor::Document* tdoc = doc->textDocument();
+ Q_ASSERT(tdoc);
+ tdoc->disconnect(this);
+ foreach(KTextEditor::View* view, tdoc->views()) {
+ AnnotationViewInterface* anno = qobject_cast<AnnotationViewInterface*>(view);
+ if (!anno) continue;
+ anno->setAnnotationBorderVisible(0);
+ anno->setAnnotationModel(0);
+ }
+}
+
+void AnnotationManager::addCoverageData(CoveredFile* f)
+{
+ QMap<int, int> cc = f->callCountMap();
+ QMapIterator<int, int> it(cc);
+ if (!m_files.contains(f->url())) {
+ CoveredFile* cf = new CoveredFile;
+ cf->setUrl(f->url());
+ while(it.hasNext()) {
+ it.next();
+ cf->setCallCount(it.key(), it.value());
+ }
+ m_files[f->url()] = cf;
+ } else {
+ CoveredFile* cf = m_files[f->url()];
+ QSet<int> newLines = f->reachableLines() - cf->reachableLines();
+ foreach(int line, newLines) {
+ cf->setCallCount(line, 0);
+ }
+ QMap<int, int> curcc = cf->callCountMap();
+ while(it.hasNext()) {
+ it.next();
+ const int& line = it.key();
+ const int& count = it.value();
+ cf->setCallCount(line, count + curcc[line]);
+ }
+ }
+}
+
+}
+
+#include "annotationmanager.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp (revision 1522570)
@@ -0,0 +1,189 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "removegcdafilesjobprogresstest.h"
+#include "../removegcdafilesjobprogress.h"
+
+#include "testutils.h"
+
+using Veritas::RemoveGcdaFilesJobProgress;
+using Veritas::RemoveGcdaFilesJobProgressTest;
+
+//KDevelop::IStatus* must be declared as a metatype to be used in qvariant_cast
+Q_DECLARE_METATYPE(KDevelop::IStatus*);
+
+void RemoveGcdaFilesJobProgressTest::init()
+{
+ m_removeGcdaFilesJobProgress = new RemoveGcdaFilesJobProgress();
+
+ //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
+ qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
+
+ m_clearMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
+ SIGNAL(clearMessage(KDevelop::IStatus*)));
+ m_showMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
+ SIGNAL(showMessage(KDevelop::IStatus*,QString,int)));
+ m_showErrorMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
+ SIGNAL(showErrorMessage(QString,int)));
+ m_hideProgressSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
+ SIGNAL(hideProgress(KDevelop::IStatus*)));
+ m_showProgressSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
+ SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
+}
+
+void RemoveGcdaFilesJobProgressTest::cleanup()
+{
+ delete m_clearMessageSpy;
+ delete m_showMessageSpy;
+ delete m_showErrorMessageSpy;
+ delete m_hideProgressSpy;
+ delete m_showProgressSpy;
+
+ delete m_removeGcdaFilesJobProgress;
+}
+
+void RemoveGcdaFilesJobProgressTest::testStatusName()
+{
+ QCOMPARE(m_removeGcdaFilesJobProgress->statusName(), i18nc("@info:progress", "Removing coverage data"));
+}
+
+void RemoveGcdaFilesJobProgressTest::testStart()
+{
+ m_removeGcdaFilesJobProgress->start();
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+ QVariant argument = m_showMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Scanning for .gcda files"));
+ QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
+}
+
+void RemoveGcdaFilesJobProgressTest::testSetNumberOfFilesFound()
+{
+ m_removeGcdaFilesJobProgress->setNumberOfFilesFound(42);
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+ QVariant argument = m_showMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Removing .gcda files"));
+ QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 2);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
+}
+
+void RemoveGcdaFilesJobProgressTest::testProgressUpdateWhenFilesAreRemoved()
+{
+ m_removeGcdaFilesJobProgress->setNumberOfFilesFound(5);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+
+ m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
+
+ QCOMPARE(m_showProgressSpy->count(), 2);
+ QVariant argument = m_showProgressSpy->at(1).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
+
+ m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
+
+ QCOMPARE(m_showProgressSpy->count(), 3);
+ argument = m_showProgressSpy->at(2).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
+
+ m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
+ m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
+ m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
+
+ QCOMPARE(m_showProgressSpy->count(), 6);
+ argument = m_showProgressSpy->at(3).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(3).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(3).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(3).at(3).toInt(), 70);
+
+ argument = m_showProgressSpy->at(4).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(4).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(4).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(4).at(3).toInt(), 80);
+
+ argument = m_showProgressSpy->at(5).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(5).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(5).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(5).at(3).toInt(), 90);
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+}
+
+void RemoveGcdaFilesJobProgressTest::testFinish()
+{
+ m_removeGcdaFilesJobProgress->finish();
+
+ QCOMPARE(m_showMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+
+ QCOMPARE(m_clearMessageSpy->count(), 1);
+ QVariant argument = m_clearMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
+
+ QCOMPARE(m_hideProgressSpy->count(), 1);
+ argument = m_hideProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
+}
+
+QTEST_KDEMAIN(RemoveGcdaFilesJobProgressTest, NoGUI)
+
+#include "removegcdafilesjobprogresstest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp (revision 1522570)
@@ -0,0 +1,273 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "lcovjobprogresstest.h"
+#include "../lcovjobprogress.h"
+
+#include "testutils.h"
+
+using Veritas::LcovJobProgress;
+using Veritas::LcovJobProgressTest;
+
+//KDevelop::IStatus* must be declared as a metatype to be used in qvariant_cast
+Q_DECLARE_METATYPE(KDevelop::IStatus*);
+
+void LcovJobProgressTest::init()
+{
+ m_lcovJobProgress = new LcovJobProgress();
+
+ //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
+ qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
+
+ m_clearMessageSpy = new QSignalSpy(m_lcovJobProgress,
+ SIGNAL(clearMessage(KDevelop::IStatus*)));
+ m_showMessageSpy = new QSignalSpy(m_lcovJobProgress,
+ SIGNAL(showMessage(KDevelop::IStatus*,QString,int)));
+ m_showErrorMessageSpy = new QSignalSpy(m_lcovJobProgress,
+ SIGNAL(showErrorMessage(QString,int)));
+ m_hideProgressSpy = new QSignalSpy(m_lcovJobProgress,
+ SIGNAL(hideProgress(KDevelop::IStatus*)));
+ m_showProgressSpy = new QSignalSpy(m_lcovJobProgress,
+ SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
+}
+
+void LcovJobProgressTest::cleanup()
+{
+ delete m_clearMessageSpy;
+ delete m_showMessageSpy;
+ delete m_showErrorMessageSpy;
+ delete m_hideProgressSpy;
+ delete m_showProgressSpy;
+
+ delete m_lcovJobProgress;
+}
+
+void LcovJobProgressTest::testStatusName()
+{
+ QCOMPARE(m_lcovJobProgress->statusName(),
+ i18nc("@info:progress", "Running <command>geninfo</command>"));
+}
+
+void LcovJobProgressTest::testStart()
+{
+ m_lcovJobProgress->start();
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ QVariant argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
+}
+
+void LcovJobProgressTest::testParseLinesBeforeScanning()
+{
+ m_lcovJobProgress->parseLines(QStringList() << "Found gcov version: 4.4.1");
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+ QCOMPARE(m_showProgressSpy->count(), 0);
+}
+
+void LcovJobProgressTest::testParseLinesScanning()
+{
+ m_lcovJobProgress->parseLines(QStringList() << "Scanning /home/vader for .gcda files ...");
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+ QVariant argument = m_showMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Scanning for .gcda files"));
+ QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
+}
+
+void LcovJobProgressTest::testParseLinesFilesFound()
+{
+ m_lcovJobProgress->parseLines(QStringList() << "Found 42 data files in /home/indiana");
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+ QVariant argument = m_showMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Processing .gcda files"));
+ QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 2);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
+}
+
+void LcovJobProgressTest::testParseLinesNoFilesFound()
+{
+ m_lcovJobProgress->parseLines(QStringList() << "ERROR: no .gcda files found in /home/threepwood!");
+
+ QCOMPARE(m_showMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_clearMessageSpy->count(), 1);
+ QVariant argument = m_clearMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
+}
+
+void LcovJobProgressTest::testParseLinesProcessing()
+{
+ QStringList lines;
+ lines << "Found 5 data files in /home/hammond";
+ lines << "Processing /home/hammond/brachiosaurus.cpp";
+ lines << "Processing /home/hammond/velociraptor.cpp";
+ lines << "Processing /home/hammond/dilophosaurus.cpp";
+ lines << "Processing /home/hammond/triceratops.cpp";
+ lines << "Processing /home/hammond/tyrannosaurus.cpp";
+ lines << "Finished .info-file creation";
+
+ m_lcovJobProgress->parseLines(lines);
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+
+ QCOMPARE(m_showProgressSpy->count(), 7);
+ QVariant argument = m_showProgressSpy->at(1).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
+
+ argument = m_showProgressSpy->at(2).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
+
+ argument = m_showProgressSpy->at(3).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(3).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(3).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(3).at(3).toInt(), 70);
+
+ argument = m_showProgressSpy->at(4).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(4).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(4).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(4).at(3).toInt(), 80);
+
+ argument = m_showProgressSpy->at(5).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(5).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(5).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(5).at(3).toInt(), 90);
+
+ argument = m_showProgressSpy->at(6).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(6).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(6).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(6).at(3).toInt(), 1);
+}
+
+void LcovJobProgressTest::testParseLinesProcessingWithGarbage()
+{
+ QStringList lines;
+ lines << "Found 5 data files in /home/doc";
+ lines << "Processing /home/doc/copernicus.cpp.gcda";
+ lines << "/home/doc/copernicus.cpp.gcno:version '402*', prefer '404*'";
+ lines << "/home/doc/copernicus.cpp.gcda:version '402*', prefer '404*'";
+ lines << "Processing /home/doc/einstein.cpp.gcda";
+ lines << "/home/doc/verne.h:cannot open source file";
+
+ m_lcovJobProgress->parseLines(lines);
+
+ QCOMPARE(m_clearMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+ QCOMPARE(m_hideProgressSpy->count(), 0);
+
+ QCOMPARE(m_showMessageSpy->count(), 1);
+
+ QCOMPARE(m_showProgressSpy->count(), 3);
+ QVariant argument = m_showProgressSpy->at(1).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
+
+ argument = m_showProgressSpy->at(2).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
+ QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
+}
+
+void LcovJobProgressTest::testFinish()
+{
+ m_lcovJobProgress->finish();
+
+ QCOMPARE(m_showMessageSpy->count(), 0);
+ QCOMPARE(m_showErrorMessageSpy->count(), 0);
+
+ QCOMPARE(m_clearMessageSpy->count(), 1);
+ QVariant argument = m_clearMessageSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+
+ QCOMPARE(m_showProgressSpy->count(), 1);
+ argument = m_showProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+ QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
+ QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
+ QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
+
+ QCOMPARE(m_hideProgressSpy->count(), 1);
+ argument = m_hideProgressSpy->at(0).at(0);
+ QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
+}
+
+QTEST_KDEMAIN(LcovJobProgressTest, NoGUI)
+
+#include "lcovjobprogresstest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp (revision 1522570)
@@ -0,0 +1,251 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "removegcdafilesjobtest.h"
+#define protected public
+#define private public
+#include "../removegcdafilesjob.h"
+#undef private
+#undef protected
+#include "../removegcdafilesjobprogress.h"
+#include "testutils.h"
+
+#include <KStandardDirs>
+
+#include <tests/autotestshell.h>
+#include <tests/testcore.h>
+
+using KDevelop::AutoTestShell;
+using KDevelop::Core;
+using KDevelop::TestCore;
+
+using Veritas::RemoveGcdaFilesJob;
+using Veritas::RemoveGcdaFilesJobProgress;
+using Veritas::RemoveGcdaFilesJobTest;
+
+void RemoveGcdaFilesJobTest::initTestCase() {
+ AutoTestShell::init();
+ TestCore::initialize(Core::NoUi);
+}
+
+void RemoveGcdaFilesJobTest::init() {
+ m_testPath = KStandardDirs().saveLocation("tmp", "removeGcdaFilesJobTest/");
+
+ QString currentDir = m_testPath;
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+
+ currentDir = m_testPath + "/parentDir/";
+ QDir().mkpath(currentDir);
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+ createFile(currentDir + "file2");
+ createFile(currentDir + "file2.gcda");
+ createFile(currentDir + "file2.gcda.bak");
+
+ currentDir = m_testPath + "/parentDir/dir1/";
+ QDir().mkpath(currentDir);
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+ createFile(currentDir + "file2");
+ createFile(currentDir + "file2.gcda");
+ createFile(currentDir + "file2.gcda.bak");
+
+ currentDir = m_testPath + "/parentDir/dir2/";
+ QDir().mkpath(currentDir);
+
+ currentDir = m_testPath + "/parentDir/dir3/";
+ QDir().mkpath(currentDir);
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+
+ currentDir = m_testPath + "/parentDir/dir2/childDir/";
+ QDir().mkpath(currentDir);
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+
+ currentDir = m_testPath + "/parentDir/dir3/childDir/";
+ QDir().mkpath(currentDir);
+ createFile(currentDir + "file");
+ createFile(currentDir + "file.gcda");
+ createFile(currentDir + "file.gcda.bak");
+}
+
+void RemoveGcdaFilesJobTest::cleanup() {
+ deleteDirectory(m_testPath);
+}
+
+void RemoveGcdaFilesJobTest::cleanupTestCase() {
+ TestCore::shutdown();
+}
+
+void RemoveGcdaFilesJobTest::testRemoveFilesInSingleDirectory() {
+ RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/dir1");
+
+ RemoveGcdaFilesJobProgress* progress = job->findChild<RemoveGcdaFilesJobProgress*>();
+
+ QVERIFY(progress);
+
+ //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
+ qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
+ QSignalSpy showProgressSpy(progress, SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
+
+ job->start();
+
+ QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file.gcda.bak"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file.gcda"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda.bak"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file2"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda.bak"));
+
+ QCOMPARE(showProgressSpy.count(), 5);
+ QCOMPARE(showProgressSpy.at(0).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(0).at(2).toInt(), 1);
+ QCOMPARE(showProgressSpy.at(0).at(3).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(1).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(1).at(2).toInt(), 2);
+ QCOMPARE(showProgressSpy.at(1).at(3).toInt(), 1);
+ QCOMPARE(showProgressSpy.at(2).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(2).at(2).toInt(), 100);
+ QCOMPARE(showProgressSpy.at(2).at(3).toInt(), 50);
+ QCOMPARE(showProgressSpy.at(3).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(3).at(2).toInt(), 100);
+ QCOMPARE(showProgressSpy.at(3).at(3).toInt(), 75);
+ QCOMPARE(showProgressSpy.at(4).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(4).at(2).toInt(), 1);
+ QCOMPARE(showProgressSpy.at(4).at(3).toInt(), 1);
+}
+
+void RemoveGcdaFilesJobTest::testRemoveFilesInComplexDirectory() {
+ RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/");
+ job->start();
+
+ QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda.bak"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file2"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/file.gcda"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/file2.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file.gcda.bak"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file.gcda"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir2/childDir/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/file.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir3/file.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/childDir/file"));
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda.bak"));
+ QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda"));
+
+ QVERIFY(QFile::exists(m_testPath + "/file"));
+ QVERIFY(QFile::exists(m_testPath + "/file.gcda.bak"));
+ QVERIFY(QFile::exists(m_testPath + "/file.gcda"));
+}
+
+void RemoveGcdaFilesJobTest::testStopJob() {
+ QPointer<RemoveGcdaFilesJob> job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/");
+
+ RemoveGcdaFilesJobProgress* progress = job->findChild<RemoveGcdaFilesJobProgress*>();
+
+ QVERIFY(progress);
+
+ //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
+ qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
+ QSignalSpy showProgressSpy(progress, SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
+
+ job->start();
+
+ job->kill();
+
+ //Ask the QFuture itself instead of the QFutureWatcher as the QFutureWatcher
+ //may return false for every isX() method if some events were not processed
+ //yet
+ QVERIFY(job->mDoWorkWatcher->future().isFinished());
+
+ QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
+
+ //This assertion may fail if the job was not killed quickly enough
+ QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/file2.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/dir1/file.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/dir3/file.gcda") ||
+ QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda"));
+
+ QVERIFY(showProgressSpy.count() >= 2);
+ QCOMPARE(showProgressSpy.at(0).at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.at(0).at(2).toInt(), 1);
+ QCOMPARE(showProgressSpy.at(0).at(3).toInt(), 0);
+ QCOMPARE(showProgressSpy.last().at(1).toInt(), 0);
+ QCOMPARE(showProgressSpy.last().at(2).toInt(), 1);
+ QCOMPARE(showProgressSpy.last().at(3).toInt(), 1);
+}
+
+/////////////////////////////////// Helpers ////////////////////////////////////
+
+void RemoveGcdaFilesJobTest::createFile(const QString& filename) {
+ QFile file(filename);
+ file.open(QIODevice::WriteOnly);
+ file.close();
+}
+
+void RemoveGcdaFilesJobTest::deleteDirectory(const QString& filename) {
+ QDir directory(filename);
+
+ foreach (QFileInfo fileInfo, directory.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files)) {
+ if (fileInfo.isDir()) {
+ deleteDirectory(fileInfo.absoluteFilePath());
+ } else {
+ QFile::remove(fileInfo.absoluteFilePath());
+ }
+ }
+
+ directory.rmdir(filename);
+}
+
+QTEST_KDEMAIN(RemoveGcdaFilesJobTest, NoGUI)
+
+#include "removegcdafilesjobtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/corestub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/corestub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/corestub.h (revision 1522570)
@@ -0,0 +1,281 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTFAKES_CORESTUB_H
+#define TESTFAKES_CORESTUB_H
+
+#include "interfaces/icore.h"
+#include <KComponentData>
+
+namespace KDevelop
+{
+class IDocumentController;
+class IDocumentationController;
+class ILanguageController;
+class IPluginController;
+class IProjectController;
+class IRunController;
+class IUiController;
+class ISessionController;
+class IPartController;
+}
+
+namespace TestStubs
+{
+
+/*! Allows for proper unit testing of components with an ICore dependency */
+class Core : public KDevelop::ICore
+{
+public:
+ Core() :
+ m_documentController(0),
+ m_languageController(0),
+ m_pluginController(0),
+ m_projectController(0),
+ m_uiController(0),
+ m_runController(0),
+ m_selectionController(0),
+ m_session(0),
+ m_partController(0),
+ m_documentationController(0),
+ m_debugController(0),
+ m_testController(0),
+ m_shuttingDown(0) {}
+
+ virtual ~Core() {}
+ virtual KDevelop::IDocumentController *documentController() {
+ return m_documentController;
+ }
+ virtual KDevelop::ISelectionController *selectionController() {
+ return m_selectionController;
+ }
+ virtual KDevelop::ILanguageController *languageController() {
+ return m_languageController;
+ }
+ virtual KDevelop::IPluginController *pluginController() {
+ return m_pluginController;
+ }
+ virtual KDevelop::IProjectController *projectController() {
+ return m_projectController;
+ }
+ virtual KDevelop::IRunController *runController() {
+ return m_runController;
+ }
+ virtual KDevelop::IUiController *uiController() {
+ return m_uiController;
+ }
+ virtual KDevelop::IPartController *partController() {
+ return m_partController;
+ }
+ virtual KDevelop::IDocumentationController* documentationController() {
+ return m_documentationController;
+ }
+ virtual KDevelop::IDebugController* debugController() {
+ return m_debugController;
+ }
+ virtual KDevelop::ITestController* testController() {
+ return m_testController;
+ }
+ virtual KDevelop::ISession* activeSession() {
+ return m_session;
+ }
+ virtual KDevelop::ISourceFormatterController *sourceFormatterController() {
+ return 0;
+ }
+ virtual KComponentData componentData() const {
+ return KGlobal::mainComponent();
+ }
+ virtual bool shuttingDown() const {
+ return m_shuttingDown;
+ }
+
+ // inject whatever it is you want.
+ KDevelop::IDocumentController* m_documentController;
+ KDevelop::ILanguageController* m_languageController;
+ KDevelop::IPluginController* m_pluginController;
+ KDevelop::IProjectController* m_projectController;
+ KDevelop::IUiController* m_uiController;
+ KDevelop::IRunController* m_runController;
+ KDevelop::ISelectionController* m_selectionController;
+ KDevelop::ISession* m_session;
+ KDevelop::IPartController* m_partController;
+ KDevelop::IDocumentationController* m_documentationController;
+ KDevelop::IDebugController* m_debugController;
+ KDevelop::ITestController* m_testController;
+ bool m_shuttingDown;
+};
+
+}
+
+#include "interfaces/iuicontroller.h"
+
+namespace TestStubs
+{
+
+class UiController : public KDevelop::IUiController {
+public:
+ UiController() : m_activeMainWindow(0) {}
+ virtual ~UiController() {}
+
+ //enum SwitchMode {
+ // ThisWindow /**< indicates that the area switch should be in the this window */,
+ // NewWindow /**< indicates that the area switch should be using a new window */
+ //};
+
+ virtual void switchToArea(const QString &areaName, SwitchMode switchMode) {}
+ virtual void addToolView(const QString &name, KDevelop::IToolViewFactory *factory) {}
+ virtual void removeToolView(KDevelop::IToolViewFactory *factory) {}
+ virtual QWidget* findToolView(const QString& name, KDevelop::IToolViewFactory *factory, KDevelop::IUiController::FindFlags flags = CreateAndRaise) { return m_activeMainWindow;}
+ virtual void raiseToolView(QWidget* toolViewWidget) {}
+ virtual KParts::MainWindow *activeMainWindow() { return m_activeMainWindow; }
+ virtual Sublime::Controller* controller() { return m_controller; }
+ virtual void registerStatus(QObject*) {}
+ virtual void popUpAssistant(const KSharedPtr<KDevelop::IAssistant>& ) {}
+ virtual void hideAssistant(const KSharedPtr<KDevelop::IAssistant>& ) {}
+ virtual void showErrorMessage(const QString &message, int timeout) {}
+ virtual Sublime::Area* activeArea() { return m_area; }
+
+ KParts::MainWindow* m_activeMainWindow;
+ Sublime::Area* m_area;
+ Sublime::Controller* m_controller;
+};
+
+}
+
+#include <interfaces/idocumentcontroller.h>
+
+namespace TestStubs
+{
+
+class DocumentController : public KDevelop::IDocumentController
+{
+// Q_OBJECT
+public:
+#if 0
+ enum DocumentActivation
+ {
+ DefaultMode = 0, /**Activate document and create a view if no other flags passed.*/
+ DoNotActivate = 1, /**Don't activate the Document.*/
+ DoNotCreateView = 2 /**Don't create and show the view for the Document.*/
+ };
+ Q_DECLARE_FLAGS(DocumentActivationParams, DocumentActivation)
+#endif
+ DocumentController(QObject *parent) : IDocumentController(parent) {}
+ virtual ~DocumentController() {}
+
+ virtual void setEncoding( const QString &encoding ) {}
+ virtual QString encoding() const { return ""; }
+
+ virtual KDevelop::IDocument* documentForUrl( const KUrl & url ) const { return 0; }
+ virtual QList<KDevelop::IDocument*> openDocuments() const { return QList<KDevelop::IDocument*>(); }
+ virtual KDevelop::IDocument* activeDocument() const { return 0; }
+ virtual void activateDocument( KDevelop::IDocument * document, const KTextEditor::Range& range = KTextEditor::Range::invalid() ) {}
+ virtual void registerDocumentForMimetype( const QString&, KDevelop::IDocumentFactory* ) {}
+ virtual bool saveAllDocuments(KDevelop::IDocument::DocumentSaveMode mode = KDevelop::IDocument::Default) { return true; }
+ virtual bool saveSomeDocuments(const QList<KDevelop::IDocument*>& list, KDevelop::IDocument::DocumentSaveMode mode = KDevelop::IDocument::Default) { return true; }
+ virtual bool saveAllDocumentsForWindow(KParts::MainWindow* mw, KDevelop::IDocument::DocumentSaveMode mode, bool currentAreaOnly = false) { return true; }
+ virtual KDevelop::IDocument* openDocumentFromText( const QString& data ) { return 0; }
+ virtual void notifyDocumentClosed(KDevelop::IDocument* doc) {}
+ virtual KTextEditor::Document* globalTextEditorInstance() { return 0; }
+
+ virtual KDevelop::IDocument* openDocument( const KUrl&, const QString& ) { return 0; }
+
+ // actually these are virtual slots, but so long as Qt does not cry we'r good.
+ virtual KDevelop::IDocument* openDocument( const KUrl &url,
+ const KTextEditor::Range& range = KTextEditor::Range::invalid(),
+ DocumentActivationParams activationParams = 0,
+ const QString& encoding = "") { return 0; }
+
+ virtual KDevelop::IDocument* openDocument( const KUrl &url,
+ const KTextEditor::Range& range = KTextEditor::Range::invalid(),
+ DocumentActivationParams activationParams = 0,
+ const QString& encoding = "",
+ KDevelop::IDocument* buddy = 0) { return 0; }
+
+ virtual bool openDocument(KDevelop::IDocument* doc,
+ const KTextEditor::Range& range = KTextEditor::Range::invalid(),
+ DocumentActivationParams activationParams = 0,
+ KDevelop::IDocument* buddy = 0) { return true; }
+
+ virtual KDevelop::IDocumentFactory* factory(const QString& mime) const { return 0; }
+ virtual void closeAllDocuments() {}
+
+ void emitDocumentActivated(KDevelop::IDocument* doc) {
+ emit documentActivated(doc);
+ }
+ void emitTextDocumentCreated(KDevelop::IDocument* doc) {
+ emit textDocumentCreated(doc);
+ }
+
+#if 0
+public Q_SLOTS:
+ /**Opens a new or existing document.
+ @param url The full Url of the document to open.
+ @param range The location information, if applicable.
+ @param activate Indicates whether to fully activate the document.*/
+ KDevelop::IDocument* openDocument( const KUrl &url,
+ const KTextEditor::Cursor& cursor,
+ DocumentActivationParams activationParams = 0 );
+
+ /**Opens a new or existing document.
+ @param url The full Url of the document to open.
+ @param range The range of text to select, if applicable.
+ @param activate Indicates whether to fully activate the document.*/
+ virtual KDevelop::IDocument* openDocument( const KUrl &url,
+ const KTextEditor::Range& range = KTextEditor::Range::invalid(),
+ DocumentActivationParams activationParams = 0 ) = 0;
+
+ virtual void closeAllDocuments() = 0;
+
+Q_SIGNALS:
+ /**Emitted when the document has been activated.*/
+ void documentActivated( KDevelop::IDocument* document );
+
+ /**Emitted when a document has been saved.*/
+ void documentSaved( KDevelop::IDocument* document );
+
+ /**Emitted when a document has been loaded.
+ Note, no views exist for the document at the time this signal is emitted.*/
+ void documentLoaded( KDevelop::IDocument* document );
+
+ /**Emitted when a text document has been loaded, and the text document created.
+ Note, no views exist for the document at the time this signal is emitted.*/
+ void textDocumentCreated( KDevelop::IDocument* document );
+
+ /**Emitted when a document has been closed.*/
+ void documentClosed( KDevelop::IDocument* document );
+
+ /**This is emitted when the document state(the relationship
+ * between the file in the editor and the file stored on disk) changes.*/
+ void documentStateChanged( KDevelop::IDocument* document );
+
+ /**This is emitted when the document content changed.*/
+ void documentContentChanged( KDevelop::IDocument* document );
+
+ /**Emitted when a document has been loaded, but before documentLoaded(..) is emitted.
+ * this allows parts of kdevplatform to prepare data-structures that can be used by other parts
+ * during documentLoaded(..).*/
+ void documentLoadedPrepare( KDevelop::IDocument* document );
+
+#endif
+};
+
+} // end namespace TestStubs
+
+#endif // TESTFAKES_CORESTUB_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/corestub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,65 @@
+set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+include_directories(..)
+
+# QtTest needs this in order to include the gui stuff.
+# The alternative (which requires Qt>=4.6) is #include <QTestGui>
+add_definitions(-DQT_GUI_LIB)
+
+macro(kdev_add_test test_EXEC test_SRCS)
+ qt4_automoc( ${test_SRCS} )
+ kde4_add_unit_test(gcov-${test_EXEC} ${test_SRCS} )
+ target_link_libraries(gcov-${test_EXEC}
+ kdevveritascoverage
+ ${KDEVPLATFORM_SUBLIME_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_SHELL_LIBRARIES}
+ ${KDEVPLATFORM_TESTS_LIBRARIES}
+ ${KDE4_KTEXTEDITOR_LIBRARY}
+ ${KDE4_KPARTS_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${QT_QTTEST_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDE4_KDEUI_LIBS}
+ ${KDE4_KFILE_LIBS})
+endmacro(kdev_add_test)
+
+
+kdev_add_test(unit-annotationmanager annotationmanagertest.cpp)
+kdev_add_test(unit-lcovinfoparser lcovinfoparsertest.cpp)
+kdev_add_test(unit-coveredfile coveredfiletest.cpp)
+#kdev_add_test(ut-lcovjob lcovjobtest.cpp)
+kdev_add_test(unit-lcovjobprogress lcovjobprogresstest.cpp)
+kdev_add_test(unit-buildpathselection buildpathselectiontest.cpp)
+kdev_add_test(unit-colorrange colorrangetest.cpp)
+kdev_add_test(unit-discretecolorrange discretecolorrangetest.cpp)
+kdev_add_test(unit-gradientcolorrange gradientcolorrangetest.cpp)
+kdev_add_test(unit-removegcdafilesjob removegcdafilesjobtest.cpp)
+kdev_add_test(unit-removegcdafilesjobprogress removegcdafilesjobprogresstest.cpp)
+kdev_add_test(unit-reportmodel reportmodeltest.cpp)
+kdev_add_test(unit-reportitems reportitemstest.cpp)
+kdev_add_test(unit-reportfileitem reportfileitemtest.cpp)
+if(NOT MSVC)
+kdev_add_test(unit-reportwidget reportwidgettest.cpp)
+endif(NOT MSVC)
+
+macro(coverage_add_mem_test test_EXEC prefix)
+ add_test(gcov-mem-${test_EXEC}
+ ${CMAKE_CURRENT_SOURCE_DIR}/runMemcheck.py ${CMAKE_CURRENT_BINARY_DIR}/gcov-${prefix}-${test_EXEC} ${CMAKE_BINARY_DIR})
+endmacro(coverage_add_mem_test)
+
+coverage_add_mem_test(annotationmanager unit)
+coverage_add_mem_test(lcovinfoparser unit)
+coverage_add_mem_test(coveredfile unit)
+coverage_add_mem_test(lcovjobprogress unit)
+# Disabled as it is too slow and uses too much memory (as it uses a KDevelop::Core)
+# coverage_add_mem_test(buildpathselection unit)
+coverage_add_mem_test(colorrange unit)
+coverage_add_mem_test(discretecolorrange unit)
+coverage_add_mem_test(gradientcolorrange unit)
+coverage_add_mem_test(removegcdafilesjob unit)
+coverage_add_mem_test(removegcdafilesjobprogress unit)
+coverage_add_mem_test(reportmodel unit)
+coverage_add_mem_test(reportitems unit)
+coverage_add_mem_test(reportfileitem unit)
+coverage_add_mem_test(reportwidget unit)
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h (revision 1522570)
@@ -0,0 +1,62 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESSTEST_H
+#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESSTEST_H
+
+#include <QtCore/QObject>
+
+class QSignalSpy;
+
+namespace Veritas
+{
+
+class RemoveGcdaFilesJobProgressTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void init();
+ void cleanup();
+
+ void testStatusName();
+
+ void testStart();
+
+ void testSetNumberOfFilesFound();
+
+ void testProgressUpdateWhenFilesAreRemoved();
+
+ void testFinish();
+
+private:
+
+ class RemoveGcdaFilesJobProgress* m_removeGcdaFilesJobProgress;
+
+ QSignalSpy* m_clearMessageSpy;
+ QSignalSpy* m_showMessageSpy;
+ QSignalSpy* m_showErrorMessageSpy;
+ QSignalSpy* m_hideProgressSpy;
+ QSignalSpy* m_showProgressSpy;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h (revision 1522570)
@@ -0,0 +1,52 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBTEST_H
+#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBTEST_H
+
+#include <QtCore/QObject>
+
+namespace Veritas {
+
+class RemoveGcdaFilesJobTest: public QObject {
+Q_OBJECT
+private slots:
+
+ void initTestCase();
+ void init();
+ void cleanup();
+ void cleanupTestCase();
+
+ void testRemoveFilesInSingleDirectory();
+ void testRemoveFilesInComplexDirectory();
+
+ void testStopJob();
+
+private:
+
+ QString m_testPath;
+
+ void createFile(const QString& filename);
+ void deleteDirectory(const QString& filename);
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp (revision 1522570)
@@ -0,0 +1,278 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "buildpathselectiontest.h"
+#include "../buildpathselection.h"
+#include "testutils.h"
+
+#include <KComboBox>
+#include <KStandardDirs>
+#include <KUrlNavigator>
+
+#include <interfaces/iproject.h>
+#include <interfaces/iprojectcontroller.h>
+#include <project/projectmodel.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <shell/core.h>
+#include <tests/autotestshell.h>
+
+using KDevelop::AutoTestShell;
+using KDevelop::Core;
+using KDevelop::IProject;
+
+using Veritas::BuildPathSelection;
+using Veritas::BuildPathSelectionTest;
+
+Q_DECLARE_METATYPE(KDevelop::IProject*)
+
+//Start of code adapted from veritas/tests/projectselectiontest.h
+
+/**
+ * Modified version of private KSignalSpy found in
+ * kdelibs/kdecore/util/qtest_kde.cpp.
+ * Original KDESignalSpy, accessed through
+ * QTest::kWaitForSignal(QObject*, const char*, int), can miss a signal if it is
+ * emitted too quickly (that is, before the connect is reached). This modified
+ * version, instead of starting the wait in the constructor, has a specific
+ * method for it. So the object can be created before executing the call that
+ * emits the signal, enabling it to register the signal before starting to wait
+ * and thus ensuring that no signal will be missed.
+ *
+ * Moreover, this modified version allows to wait for up to n emitted signals
+ * instead of only the first one. Note that the count isn't reseted after
+ * receiving all the expected signals, so if you wait for more signals use an
+ * absolute value (that is, the already received signals plus those you want to
+ * wait for now).
+ */
+class SignalSpy: public QObject
+{
+Q_OBJECT
+public:
+ SignalSpy(QObject* object, const char* signal):
+ QObject(0), m_signalSpy(object, signal), m_expectedCount(0)
+ {
+ connect(object, signal, this, SLOT(signalEmitted()));
+ }
+
+ bool waitForCount(int expectedCount, int timeout)
+ {
+ if (m_signalSpy.count() < expectedCount) {
+ m_expectedCount = expectedCount;
+
+ if (timeout > 0) {
+ QObject::connect(&m_timer, SIGNAL(timeout()), &m_loop, SLOT(quit()));
+ m_timer.setSingleShot(true);
+ m_timer.start(timeout);
+ }
+ m_loop.exec();
+ }
+
+ if (m_signalSpy.count() >= expectedCount) {
+ return true;
+ }
+ return false;
+ }
+
+private Q_SLOTS:
+ void signalEmitted()
+ {
+ if (m_signalSpy.count() >= m_expectedCount) {
+ m_timer.stop();
+ m_loop.quit();
+ }
+ }
+private:
+ QSignalSpy m_signalSpy;
+ int m_expectedCount;
+ QEventLoop m_loop;
+ QTimer m_timer;
+};
+
+void BuildPathSelectionTest::initTestCase()
+{
+ AutoTestShell::init();
+ Core::initialize();
+ qRegisterMetaType<KDevelop::IProject*>();
+
+ m_testPath = KStandardDirs().saveLocation("tmp", "buildPathSelectionTest/");
+
+ m_project1Url = writeProjectConfiguration("Project1", "/project1/build");
+ m_project2Url = writeProjectConfiguration("Project2", "/project2/build");
+ m_project3FilteredUrl = writeProjectConfiguration("Project3Filtered", "");
+}
+
+void BuildPathSelectionTest::init()
+{
+ m_urlNavigator = new KUrlNavigator(0, KUrl(QDir::homePath()), 0);
+ m_buildPathSelection = new BuildPathSelection(m_urlNavigator);
+
+ m_parent = new QWidget();
+ QWidget* widget = m_buildPathSelection->requestProjectSelectionWidget(m_parent);
+ m_comboBox = qobject_cast<KComboBox*>(widget);
+}
+
+void BuildPathSelectionTest::cleanup()
+{
+ SignalSpy projectClosedSignal(Core::self()->projectController(), SIGNAL(projectClosed(KDevelop::IProject*)));
+ int count = Core::self()->projectController()->projects().count();
+
+ foreach(IProject* project, Core::self()->projectController()->projects()) {
+ Core::self()->projectController()->closeProject(project);
+ }
+
+ projectClosedSignal.waitForCount(count, 30000);
+
+ //Project configuration file isn't the kdev4 project file used to load the
+ //project, so if the configuration was modified in a test it would be
+ //modified in the other tests if these files aren't removed
+ QFile(m_testPath + ".kdev4/Project1.kdev4").remove();
+ QFile(m_testPath + ".kdev4/Project2.kdev4").remove();
+ QFile(m_testPath + ".kdev4/Project3Filtered.kdev4").remove();
+
+ delete m_parent;
+ delete m_buildPathSelection;
+ delete m_urlNavigator;
+}
+
+void BuildPathSelectionTest::cleanupTestCase()
+{
+ QDir().rmdir(m_testPath + ".kdev4/");
+ QFile(m_project1Url.path()).remove();
+ QFile(m_project2Url.path()).remove();
+ QFile(m_project3FilteredUrl.path()).remove();
+ QDir().rmdir(m_testPath);
+}
+
+//End of code adapted from veritas/tests/projectselectiontest.h
+
+void BuildPathSelectionTest::testRequestProjectSelectionWidget()
+{
+ QVERIFY(m_comboBox);
+ QCOMPARE(m_comboBox->parentWidget(), m_parent);
+}
+
+void BuildPathSelectionTest::testProjectFilter()
+{
+ openProject(m_project1Url);
+ openProject(m_project2Url);
+ openProject(m_project3FilteredUrl);
+
+ QAbstractItemModel* model = m_comboBox->model();
+
+ QVERIFY(model->flags(model->index(0, 0)) & Qt::ItemIsEnabled);
+ QVERIFY(model->flags(model->index(1, 0)) & Qt::ItemIsEnabled);
+ QVERIFY(model->flags(model->index(2, 0)) & ~Qt::ItemIsEnabled);
+}
+
+void BuildPathSelectionTest::testSelectProject()
+{
+ openProject(m_project1Url);
+ openProject(m_project2Url);
+
+ QCOMPARE(m_comboBox->currentIndex(), -1);
+ QCOMPARE(m_urlNavigator->url(), KUrl(QDir::homePath()));
+
+ m_comboBox->setCurrentIndex(0);
+
+ QCOMPARE(m_urlNavigator->url().toLocalFile(KUrl::AddTrailingSlash), QString("/project1/build/"));
+
+ m_comboBox->setCurrentIndex(1);
+
+ QCOMPARE(m_urlNavigator->url().toLocalFile(KUrl::AddTrailingSlash), QString("/project2/build/"));
+}
+
+void BuildPathSelectionTest::testChangeBuildPath()
+{
+ openProject(m_project1Url);
+ openProject(m_project2Url);
+
+ m_urlNavigator->setUrl(QString("file:///project2/build/"));
+
+ QCOMPARE(m_comboBox->currentIndex(), 1);
+
+ m_urlNavigator->setUrl(QString("file:///project1/build"));
+
+ QCOMPARE(m_comboBox->currentIndex(), 0);
+}
+
+void BuildPathSelectionTest::testChangeBuildPathToUnknownPath()
+{
+ openProject(m_project1Url);
+ openProject(m_project2Url);
+
+ m_urlNavigator->setUrl(QString("file:///project1/build"));
+
+ QCOMPARE(m_comboBox->currentIndex(), 0);
+
+ m_urlNavigator->setUrl(QString("file:///project2"));
+
+ QCOMPARE(m_comboBox->currentIndex(), -1);
+}
+
+/////////////////////////////////// Helpers ////////////////////////////////////
+
+//Start of code adapted from veritas/tests/projectselectiontest.h
+
+KUrl BuildPathSelectionTest::writeProjectConfiguration(const QString& name,
+ const QString& buildPath) const
+{
+ KUrl configurationUrl = KUrl(m_testPath + name + ".kdev4");
+
+ QFile file(configurationUrl.pathOrUrl());
+ file.open(QIODevice::WriteOnly);
+ QTextStream out(&file);
+ out << "[Project]\n"
+ << "Name=" << name << "\n";
+ if (!buildPath.isEmpty()) {
+ out << "Manager=KDevCMakeManager\n"
+ << "[CMake]\n"
+ << "BuildDirs=" << buildPath << "\n"
+ << "CurrentBuildDir=file://" << buildPath << "\n";
+ }
+ file.close();
+
+ return configurationUrl;
+}
+
+void BuildPathSelectionTest::openProject(const KUrl& url) const
+{
+ SignalSpy projectOpenedSignal(Core::self()->projectController(),
+ SIGNAL(projectOpened(KDevelop::IProject*)));
+ Core::self()->projectController()->openProject(url);
+ if (!projectOpenedSignal.waitForCount(1, 30000)) {
+ QWARN("Timeout waiting for projectOpened");
+ }
+}
+
+void BuildPathSelectionTest::closeProject(IProject* project) const
+{
+ SignalSpy projectClosedSignal(Core::self()->projectController(),
+ SIGNAL(projectClosed(KDevelop::IProject*)));
+ Core::self()->projectController()->closeProject(project);
+ if (!projectClosedSignal.waitForCount(1, 30000)) {
+ QWARN("Timeout waiting for projectClosed");
+ }
+}
+
+//End of code adapted from veritas/tests/projectselectiontest.h
+
+QTEST_KDEMAIN(BuildPathSelectionTest, GUI)
+
+#include "moc_buildpathselectiontest.cpp"
+#include "buildpathselectiontest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py (revision 1522570)
@@ -0,0 +1,198 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+# run valgrind's memory error checker on all tests.
+# filter uninteresting errors and known false positives
+# eg staticly initialized memory from libraries like libfontconfig
+#
+
+from os import system, remove
+from sys import exit, stdout
+from subprocess import Popen, PIPE
+from xml.dom.minidom import parse, parseString
+
+def garbage(line):
+ ''' filter for valgridn output'''
+ return not line.startswith('<unknown program name>') and \
+ not line.startswith('profiling:') and \
+ line.find('</valgrindoutput>') # problem is that valgrind erroneously puts multiple of these end-document entries if processes are spawned _inside_ the exe under investigation
+
+def isValgrind3_5OrHigher():
+ process = Popen("valgrind --version", stdout=PIPE, shell=True)
+ process.wait()
+ valgrindOutput = process.stdout.read().strip()
+
+ import re, string
+ version = re.search("[0-9]+(.[0-9]+)*", valgrindOutput).group(0)
+ version = string.split(version, ".")
+
+ if map(int, version) < [3, 5]:
+ return False
+ else:
+ return True
+
+def memcheck(test):
+ ''' run valgrind-memcheck on test in testdir. return xml output as string '''
+ #proc = Popen("valgrind --tool=memcheck --leak-check=full --xml=yes " + test, stdout=PIPE, stderr=PIPE, shell=True, executable="/bin/bash")
+ #proc.wait()
+ #out = proc.stderr.readlines()
+ if isValgrind3_5OrHigher():
+ system("valgrind --tool=memcheck --leak-check=full --xml=yes --xml-file=.memcheck.tmp --num-callers=50 " + test + " 1>/dev/null")
+ else:
+ system("valgrind --tool=memcheck --leak-check=full --xml=yes --num-callers=75 " + test + " 1>/dev/null 2>.memcheck.tmp")
+ out = open(".memcheck.tmp").readlines()
+ remove(".memcheck.tmp")
+ out = filter(garbage, out)
+ return ''.join(out) + "\n</valgrindoutput>\n"
+
+def xml_child_data(dom,tag):
+ ''' extract child data for tag. return None if not found'''
+ elem = dom.getElementsByTagName(tag)
+ val = None
+ if len(elem) != 0:
+ val = elem[0].firstChild.data
+ return val
+
+class Frame:
+ ''' single entry in a memory error backtrace '''
+ def __init__(self, dom_frame):
+ '''<frame>
+ <ip>0x62ACDBF</ip>
+ <obj>/home/nix/KdeDev/kde4/lib/libkdevplatformlanguage.so.1.0.0</obj>
+ <fn>KDevelop::ParamIterator::ParamIterator(QString, QString, int)</fn>
+ <dir>/home/nix/KdeDev/kdevplatform/language/duchain</dir>
+ <file>stringhelpers.cpp</file>
+ <line>292</line>
+ </frame>'''
+ self.obj = xml_child_data(dom_frame, 'obj')
+ self.func = xml_child_data(dom_frame, 'fn')
+ self.sfile = xml_child_data(dom_frame, 'file')
+ self.sline = xml_child_data(dom_frame, 'line')
+
+ def __str__(self):
+ out = ""
+ if self.func:
+ out += "\t" + self.func
+ if self.sfile and self.sline:
+ out += " (" + self.sfile + ":" + self.sline + ")"
+ #if self.obj:
+ #out += "\t" + self.obj + "\n"
+ out += "\n"
+ return out
+
+class BackTrace:
+ ''' valgrind memcheck stack trace '''
+ def __init__(self, errordom):
+ self.dom = errordom
+ self.kind = self.dom.getElementsByTagName('kind')[0].firstChild.data
+ stack = self.dom.getElementsByTagName('frame')
+ self.stack = []
+ for frame in stack:
+ if xml_child_data(frame, 'fn'): # filter anonymous frames out
+ self.stack.append(Frame(frame))
+ self.what = xml_child_data(self.dom, 'what')
+ if self.dom.getElementsByTagName('xwhat').length > 0:
+ self.what = xml_child_data(self.dom.getElementsByTagName('xwhat')[0], 'text')
+
+ def is_definitely_lost(self):
+ return self.kind == u'Leak_DefinitelyLost'
+
+ def is_qtest(self):
+ is_interesting = False
+ for frame in self.stack:
+ if frame.func:
+ if frame.func.find("QTest") != -1 or frame.func.find("Veritas") != -1:
+ is_interesting = True
+ if frame.func.find('XRegisterIMInstantiateCallback') != -1:
+ return False # X-related static memory allocation, no leak
+ if frame.func.find('FcDefaultSubstitute') != -1:
+ return False # something Qt-Font related, not interested in this
+ if frame.func.find('__nss_database_lookup') != -1:
+ return False # more crap
+ if frame.func.find('HB_OpenTypePosition') != -1 and frame.sfile.find("harfbuzz-shaper.cpp") != -1:
+ return False
+ if frame.sfile:
+ if frame.sfile.find("xtest") != -1 or frame.sfile.find("veritas") != -1:
+ is_interesting = True
+ return is_interesting
+
+ def __str__(self):
+ out = self.what + "\n"
+ for frame in self.stack:
+ out += str(frame)
+ return out
+
+def parse_errors(out):
+ ''' extract the interesting memcheck errors from the xml-string input 'out'.
+ return these as a list '''
+ xmldoc = parseString(out)
+ errors = xmldoc.getElementsByTagName('error')
+ errors_ = []
+ for error in errors:
+ bt = BackTrace(error)
+ if bt.is_definitely_lost() and bt.is_qtest():
+ errors_.append(bt)
+ return errors_
+
+def run_all_tests():
+ tests=['qtest-unit-casebuilder', \
+ 'qtest-unit-qtestcase', 'qtest-ut-qtestcommand', \
+ 'qtest-unit-qtestoutputmorpher', 'qtest-unit-qtestoutputparser', \
+ 'qtest-unit-qtestregister', 'qtest-unit-qtestsuite', \
+ 'qtest-unit-suitebuilder', 'qtest-sys-qtestrunnertest']
+ tests=['qtest-it-qtestrunnertest']
+
+ root='/home/nix/KdeDev/kdevelop/build/'
+ testdir=root + 'plugins/xtest/qtest/tests/'
+ system("export LD_LIBRARY_PATH="+root+"lib/:$LD_LIBRARY_PATH")
+
+ print ">> running valgrind memcheck"
+ all = len(tests)
+ curr = 1
+ found_error = False
+ for test in tests:
+ print str(curr) + "/" + str(all) + " " + test + "\t",
+ if len(test) < 20: print "\t",
+ stdout.flush()
+ curr+=1
+ out = memcheck(testdir + test)
+ errors = parse_errors(out)
+ if len(errors) == 0:
+ print "OK"
+ else:
+ found_error = True
+ log = open(test+".memcheck", 'w')
+ for trace in errors:
+ log.write(str(trace))
+ log.write("---------------------------------------------------\n")
+ log.close()
+ print "NOK (see " + test + ".memcheck)"
+ if found_error: exit(-1)
+
+def run_single_test(exe_name):
+ print ">> running valgrind memcheck on " + exe_name
+ system("export LD_LIBRARY_PATH="+sys.argv[2]+"/lib/:$LD_LIBRARY_PATH")
+ count = 0
+ import xml
+ while count < 5:
+ try:
+ out = memcheck(exe_name)
+ errors = parse_errors(out)
+ if len(errors) == 0:
+ print "PASS"
+ exit(0)
+ else:
+ for trace in errors:
+ print trace,
+ print "---------------------------------------------------"
+ exit(-1)
+ except xml.parsers.expat.ExpatError:
+ print "Valgrind fooked up, retry"
+ count += 1
+ pass
+
+################### ENTRY ####################################################
+
+if __name__ == '__main__':
+ import sys
+ if len(sys.argv) == 1: run_all_tests()
+ else: run_single_test(sys.argv[1])
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h (revision 1522570)
@@ -0,0 +1,81 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_BUILDPATHSELECTIONTEST_H
+#define VERITAS_COVERAGE_BUILDPATHSELECTIONTEST_H
+
+#include <QObject>
+
+#include <KUrl>
+
+class KComboBox;
+class KUrlNavigator;
+
+namespace KDevelop
+{
+class IProject;
+}
+
+namespace Veritas
+{
+
+class BuildPathSelection;
+
+class BuildPathSelectionTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void initTestCase();
+ void init();
+ void cleanup();
+ void cleanupTestCase();
+
+ void testRequestProjectSelectionWidget();
+
+ void testProjectFilter();
+
+ void testSelectProject();
+
+ void testChangeBuildPath();
+ void testChangeBuildPathToUnknownPath();
+
+private:
+
+ KUrl writeProjectConfiguration(const QString& name, const QString& buildPath) const;
+ void openProject(const KUrl& url) const;
+ void closeProject(KDevelop::IProject* project) const;
+
+ QString m_testPath;
+
+ KUrl m_project1Url;
+ KUrl m_project2Url;
+ KUrl m_project3FilteredUrl;
+
+ KUrlNavigator* m_urlNavigator;;
+ BuildPathSelection* m_buildPathSelection;
+
+ QWidget* m_parent;
+ KComboBox* m_comboBox;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/kasserts.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/kasserts.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/kasserts.h (revision 1522570)
@@ -0,0 +1,90 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+/*! Various QTestLib convenience macros and toString printers */
+
+#ifndef QXQTEST_KASSERTS_H
+#define QXQTEST_KASSERTS_H
+
+#include <QtTest/QtTest>
+#include <KUrl>
+
+namespace QTest
+{
+
+template<> inline char* toString(const QFileInfo& fi)
+{
+ return qstrdup(fi.filePath().toLatin1().constData());
+}
+#if QT_VERSION < QT_VERSION_CHECK(4,6,0)
+template<> inline char* toString(const QVariant& va)
+{
+ return qstrdup(va.toString().toLatin1().constData());
+}
+#endif
+template<> inline char* toString(const KUrl& url)
+{
+ return qstrdup(url.toLocalFile().toLatin1().constData());
+}
+
+} // namespace QTest
+
+#define KVERIFY(condition) QVERIFY(condition)
+
+#define KVERIFY_MSG(condition,message) \
+{\
+ char* __failMsg__ = QTest::toString(message); \
+ bool __assertion_failed__ = \
+ !QTest::qVerify(condition, #condition, __failMsg__, __FILE__, __LINE__);\
+ delete [] __failMsg__; \
+ if (__assertion_failed__) return; \
+} (void)(0)
+
+#define KOMPARE(expected, actual) \
+{ \
+ char* __expected__ = QTest::toString(expected); \
+ char* __actual__ = QTest::toString(actual); \
+ QByteArray __failMsg__ = \
+ QByteArray("\nexpected: \'").append(__expected__).append("\' actual \'").\
+ append(__actual__).append("\'"); \
+ delete [] __expected__; \
+ delete [] __actual__; \
+ if (!QTest::qVerify(expected == actual, "KOMPARE", __failMsg__.constData(), __FILE__, __LINE__))\
+ return;\
+} (void)(0)
+
+#define KOMPARE_MSG(expected, actual, msg) \
+{ \
+ char* __expected__ = QTest::toString(expected); \
+ char* __actual__ = QTest::toString(actual); \
+ char* __fail_msg__ = QTest::toString(msg); \
+ QByteArray __failMsg__ = \
+ QByteArray("\nexpected: \'").append(__expected__).append("\' actual \'").\
+ append(__actual__).append("\'\n").append(__fail_msg__); \
+ delete [] __expected__; \
+ delete [] __actual__; \
+ delete [] __fail_msg__; \
+ if (!QTest::qVerify(expected == actual, "KOMPARE_MSG", __failMsg__.constData(), __FILE__, __LINE__))\
+ return;\
+} (void)(0)
+
+#define TDD_TODO QSKIP("Test command not implemented yet", SkipSingle)
+
+#endif // QXQTEST_KASSERTS_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/kasserts.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/testutils.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/testutils.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/testutils.h (revision 1522570)
@@ -0,0 +1,27 @@
+/*
+ * This file is part of KDevelop.
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef COVERAGE_TESTUTILS_H
+#define COVERAGE_TESTUTILS_H
+
+#include "kasserts.h"
+#include <qtest_kde.h>
+
+#endif // COVERAGE_TESTUTILS_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/testutils.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h (revision 1522570)
@@ -0,0 +1,66 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_LCOVJOBPROGRESSTEST_H
+#define VERITAS_COVERAGE_LCOVJOBPROGRESSTEST_H
+
+#include <QtCore/QObject>
+
+class QSignalSpy;
+
+namespace Veritas {
+
+class LcovJobProgressTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void init();
+ void cleanup();
+
+ void testStatusName();
+
+ void testStart();
+
+ void testParseLinesBeforeScanning();
+ void testParseLinesScanning();
+
+ void testParseLinesFilesFound();
+ void testParseLinesNoFilesFound();
+
+ void testParseLinesProcessing();
+ void testParseLinesProcessingWithGarbage();
+
+ void testFinish();
+
+private:
+
+ class LcovJobProgress* m_lcovJobProgress;
+
+ QSignalSpy* m_clearMessageSpy;
+ QSignalSpy* m_showMessageSpy;
+ QSignalSpy* m_showErrorMessageSpy;
+ QSignalSpy* m_hideProgressSpy;
+ QSignalSpy* m_showProgressSpy;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp (revision 1522570)
@@ -0,0 +1,75 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "lcovjobtest.h"
+#include "../lcovjob.h"
+#include "../covoutputdelegate.h"
+#include "plugincontrollerstub.h"
+#include "corestub.h"
+#include "pluginstub.h"
+#include <KProcess>
+#include <QtTest/QTest>
+#include <qtest_kde.h>
+
+using Veritas::CovOutputDelegate;
+using Veritas::LcovJob;
+using Veritas::LcovJobTest;
+
+namespace
+{
+class MyKProcess : public KProcess
+{
+public:
+ MyKProcess() : m_startCalled(false) {}
+ virtual ~MyKProcess() {}
+ virtual void start() { m_startCalled = true; }
+ bool m_startCalled;
+};
+}
+
+void LcovJobTest::initTestCase()
+{
+ m_core = new TestStubs::Core;
+ Q_ASSERT(m_core);
+ m_plugCtrl = new TestStubs::PluginController;
+ m_plugCtrl->m_pluginForExtension = new TestStubs::Plugin(KGlobal::mainComponent(), 0);
+ m_core->m_pluginController = m_plugCtrl;
+}
+
+void LcovJobTest::init()
+{
+}
+
+void LcovJobTest::cleanup()
+{
+}
+
+void LcovJobTest::basicRun()
+{
+ MyKProcess* proc = new MyKProcess;
+ CovOutputDelegate* del = new CovOutputDelegate;
+ LcovJob* m_job = new LcovJob(KUrl("/my/root/dir"));
+ m_job->setProcess(proc);
+ m_job->setDelegate(del);
+ m_job->start();
+}
+
+QTEST_KDEMAIN( LcovJobTest, NoGUI)
+#include "lcovjobtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h (revision 1522570)
@@ -0,0 +1,58 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_COLORRANGETEST_H
+#define VERITAS_COVERAGE_COLORRANGETEST_H
+
+#include <QtCore/QObject>
+#include <QColor>
+
+namespace Veritas {
+
+class ColorRangeTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void cleanup();
+
+ void testConstructor();
+ void testSetMode();
+ void testSetStopPoints();
+ void testColorAtDiscreteMode();
+ void testColorAtGradientMode();
+
+ void testLoad();
+ void testSave();
+ void testLoadAfterSave();
+
+ void testOperatorEqual();
+ void testOperatorEqualDifferentMode();
+ void testOperatorEqualDifferentDiscreteColorRange();
+ void testOperatorEqualDifferentGradientColorRange();
+
+private:
+
+ void assertFuzzyColor(const QColor& actual, const QColor& expected);
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QTEST_LCOVINFOPARSERTEST_H_INCLUDED
+#define QTEST_LCOVINFOPARSERTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas
+{
+
+class CoveredFile;
+class LcovInfoParser;
+class LcovInfoParserTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+ void cleanupTestCase();
+
+ void singleCoveredFile();
+ void multipleFiles();
+
+private:
+ void assertCoveredFilesEqual(CoveredFile*, CoveredFile*);
+
+private:
+ LcovInfoParser* m_parser;
+};
+
+}
+
+#endif // QTEST_LCOVINFOPARSERTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp (revision 1522570)
@@ -0,0 +1,22 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "viewstub.h"
+#include "viewstub.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp (revision 1522570)
@@ -0,0 +1,106 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "gradientcolorrangetest.h"
+#include "../gradientcolorrange.h"
+
+#include "testutils.h"
+
+using Veritas::GradientColorRangeTest;
+
+void GradientColorRangeTest::testConstructor()
+{
+ GradientColorRange gcr;
+
+ QCOMPARE(gcr.stopPoints().size(), 2);
+ QCOMPARE(gcr.colorAt(0), QColor(Qt::black));
+ QCOMPARE(gcr.colorAt(1), QColor(Qt::white));
+}
+
+void GradientColorRangeTest::testSetStopPoints()
+{
+ GradientColorRange gcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.23, QColor(Qt::blue)));
+ stopPoints.append(StopPoint(0.42, QColor(Qt::darkGreen)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ gcr.setStopPoints(stopPoints);
+
+ QCOMPARE(gcr.stopPoints().size(), 4);
+ QCOMPARE(gcr.stopPoints()[0].first, 0.0);
+ QCOMPARE(gcr.stopPoints()[0].second, QColor(Qt::red));
+ QCOMPARE(gcr.stopPoints()[1].first, 0.23);
+ QCOMPARE(gcr.stopPoints()[1].second, QColor(Qt::blue));
+ QCOMPARE(gcr.stopPoints()[2].first, 0.42);
+ QCOMPARE(gcr.stopPoints()[2].second, QColor(Qt::darkGreen));
+ QCOMPARE(gcr.stopPoints()[3].first, 1.0);
+ QCOMPARE(gcr.stopPoints()[3].second, QColor(Qt::cyan));
+}
+
+void GradientColorRangeTest::testColorAtWithNoMiddleStopPoints()
+{
+ GradientColorRange gcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(1, QColor(Qt::yellow)));
+ gcr.setStopPoints(stopPoints);
+
+ QCOMPARE(gcr.colorAt(0), QColor(Qt::red));
+ assertFuzzyColor(gcr.colorAt(0.5), QColor(255, 127, 0));
+ QCOMPARE(gcr.colorAt(1), QColor(Qt::yellow));
+}
+
+void GradientColorRangeTest::testColorAtWithSeveralStopPoints()
+{
+ GradientColorRange gcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::black)));
+ stopPoints.append(StopPoint(0.333, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.667, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ gcr.setStopPoints(stopPoints);
+
+ QCOMPARE(gcr.colorAt(0), QColor(Qt::black));
+ assertFuzzyColor(gcr.colorAt(0.167), QColor(127, 0, 0));
+ assertFuzzyColor(gcr.colorAt(0.333), QColor(Qt::red));
+ assertFuzzyColor(gcr.colorAt(0.5), QColor(255, 127, 0));
+ assertFuzzyColor(gcr.colorAt(0.667), QColor(Qt::yellow));
+ assertFuzzyColor(gcr.colorAt(0.834), QColor(127, 255, 0));
+ QCOMPARE(gcr.colorAt(1), QColor(Qt::green));
+}
+
+////////////////////////////// Asserts ////////////////////////////////////////
+
+void GradientColorRangeTest::assertFuzzyColor(const QColor& actual, const QColor& expected)
+{
+ QVERIFY(actual.red() >= expected.red() -1);
+ QVERIFY(actual.red() <= expected.red() + 1);
+ QVERIFY(actual.green() >= expected.green() -1);
+ QVERIFY(actual.green() <= expected.green() + 1);
+ QVERIFY(actual.blue() >= expected.blue() -1);
+ QVERIFY(actual.blue() <= expected.blue() + 1);
+}
+
+QTEST_KDEMAIN(GradientColorRangeTest, NoGUI)
+
+#include "gradientcolorrangetest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h (revision 1522570)
@@ -0,0 +1,80 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef COVERAGE_ANNOTATIONMANAGER_TEST_H
+#define COVERAGE_ANNOTATIONMANAGER_TEST_H
+
+#include <QtCore/QObject>
+#include <KUrl>
+
+namespace KDevelop { class ICore; class IDocument; }
+namespace KTextEditor { class View; }
+namespace TestStubs { class Core; class KDevDocument; class DocumentController; }
+namespace Veritas { class CoveredFile; }
+
+namespace Veritas
+{
+
+class AnnotationManager;
+class AnnotationManagerTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void initTestCase();
+ void init();
+ void cleanup();
+
+ void instantiate();
+ void singleLine();
+ void multipleLines();
+ void multipleViews();
+ void multipleFiles();
+ void notCovered();
+ void stopWatching();
+ void multiCoverageOneFile();
+ void annotationsOnExistingView();
+ void addRemoveAndReAddAnnotations();
+
+private: // helpers
+ void initManager(Veritas::CoveredFile* f);
+ KTextEditor::View* triggerAnnotationsOnView(KDevelop::IDocument*);
+ TestStubs::KDevDocument* createKDevDocument(const KUrl& u);
+ Veritas::CoveredFile* createCoveredFile(int line, int callCount, KUrl);
+ void assertAnnoCallCountEquals(int line, int count, KTextEditor::View*);
+ void assertNoAnnotationsOnLine(int line, KTextEditor::View* v);
+ void assertAnnotationsGone(KTextEditor::View* v);
+
+private: // fixture
+ AnnotationManager* m_annotationManager;
+ TestStubs::Core* m_core;
+ TestStubs::DocumentController* m_docCtrl;
+ KUrl m_someUrl;
+ QWidget* m_widget;
+ int m_lineNr; // source line number
+ int m_nrofCalls; // number of calls on this line
+
+ QList<CoveredFile*> m_garbageFiles;
+ QList<TestStubs::KDevDocument*> m_garbageDocs;
+ QList<QObject*> m_garbage;
+};
+
+}
+
+#endif // COVERAGE_ANNOTATIONMANAGER_TEST_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp (revision 1522570)
@@ -0,0 +1,104 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "discretecolorrangetest.h"
+#include "../discretecolorrange.h"
+
+#include "testutils.h"
+
+using Veritas::DiscreteColorRangeTest;
+
+void DiscreteColorRangeTest::testConstructor()
+{
+ DiscreteColorRange dcr;
+
+ QCOMPARE(dcr.stopPoints().size(), 1);
+ QCOMPARE(dcr.colorAt(1), QColor(Qt::white));
+}
+
+void DiscreteColorRangeTest::testSetStopPoints()
+{
+ DiscreteColorRange dcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0.23, QColor(Qt::blue)));
+ stopPoints.append(StopPoint(0.42, QColor(Qt::darkGreen)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ dcr.setStopPoints(stopPoints);
+
+ QCOMPARE(dcr.stopPoints().size(), 3);
+ QCOMPARE(dcr.stopPoints()[0].first, 0.23);
+ QCOMPARE(dcr.stopPoints()[0].second, QColor(Qt::blue));
+ QCOMPARE(dcr.stopPoints()[1].first, 0.42);
+ QCOMPARE(dcr.stopPoints()[1].second, QColor(Qt::darkGreen));
+ QCOMPARE(dcr.stopPoints()[2].first, 1.0);
+ QCOMPARE(dcr.stopPoints()[2].second, QColor(Qt::cyan));
+}
+
+void DiscreteColorRangeTest::testColorAtWithNoMiddleStopPoints()
+{
+ DiscreteColorRange dcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(1, QColor(QColor(Qt::green))));
+ dcr.setStopPoints(stopPoints);
+
+ QCOMPARE(dcr.colorAt(0), QColor(Qt::green));
+ QCOMPARE(dcr.colorAt(0.5), QColor(Qt::green));
+ QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
+}
+
+void DiscreteColorRangeTest::testColorAtWithSeveralStopPoints()
+{
+ DiscreteColorRange dcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0.333, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.667, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ dcr.setStopPoints(stopPoints);
+
+ QCOMPARE(dcr.colorAt(0), QColor(Qt::red));
+ QCOMPARE(dcr.colorAt(0.23), QColor(Qt::red));
+ QCOMPARE(dcr.colorAt(0.333), QColor(Qt::red));
+ QCOMPARE(dcr.colorAt(0.334), QColor(Qt::yellow));
+ QCOMPARE(dcr.colorAt(0.42), QColor(Qt::yellow));
+ QCOMPARE(dcr.colorAt(0.667), QColor(Qt::yellow));
+ QCOMPARE(dcr.colorAt(0.668), QColor(Qt::green));
+ QCOMPARE(dcr.colorAt(0.8), QColor(Qt::green));
+ QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
+}
+
+void DiscreteColorRangeTest::testColorAtWithStopPointAtBegin()
+{
+ DiscreteColorRange dcr;
+
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ dcr.setStopPoints(stopPoints);
+
+ QCOMPARE(dcr.colorAt(0), QColor(Qt::black));
+ QCOMPARE(dcr.colorAt(0.001), QColor(Qt::green));
+ QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
+}
+
+QTEST_KDEMAIN(DiscreteColorRangeTest, NoGUI)
+
+#include "discretecolorrangetest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h (revision 1522570)
@@ -0,0 +1,63 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef QTEST_REPORTITEMSTEST_H_INCLUDED
+#define QTEST_REPORTITEMSTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+class QStandardItem;
+
+namespace Veritas
+{
+
+class CoveredFile;
+class ReportDirItem;
+
+class ReportItemsTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void constructDoubleValueItem();
+ void constructIntValueItem();
+
+ void constructDirItem();
+ void addFileToDirItem();
+ void addMultipleFilesToDir();
+
+ void constructDirData();
+ void dirDataSetSloc();
+ void dirDataSetInstrumented();
+ void dirDataCoverage();
+
+private:
+ void addCoverageDataTo(ReportDirItem& dir, const QString& path, int sloc, int instrumented);
+
+private:
+ QList<QStandardItem*> m_garbage;
+ QList<CoveredFile*> m_garbageFiles;
+
+};
+
+}
+
+#endif // QTEST_REPORTITEMSTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h (revision 1522570)
@@ -0,0 +1,76 @@
+/* KDevelop coverage plugin
+ * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef QTEST_REPORTWIDGETTEST_H_INCLUDED
+#define QTEST_REPORTWIDGETTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas
+{
+
+class DrillDownView;
+class ReportModel;
+class ReportWidget;
+
+/*! @unitundertest Veritas::ReportWidget */
+class ReportWidgetTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void setCoverageStatisticsWithRawDataFloorRoundedCoverage();
+ void setCoverageStatisticsWithRawDataCeilRoundedCoverage();
+ void setCoverageStatisticsWithNewSelection();
+ void setCoverageStatisticsWithAddedSelection();
+ void setCoverageStatisticsWithRemovedSelection();
+ void setCoverageStatisticsWithChangedSelection();
+ void setCoverageStatisticsWithEmptySelection();
+ void setCoverageStatisticsWithInvalidSelection();
+ void setCoverageStatisticsWithDirectoriesAndFileSelection();
+ void setCoverageStatisticsWithIndex();
+ void setCoverageStatisticsWithInvalidIndex();
+ void setCoverageStatisticsWithFileIndex();
+
+ void statisticsSelectingSingleDirectory();
+ void statisticsSelectingSeveralDirectories();
+ void statisticsSelectingSeveralDirectoriesNotContiguous();
+ void statisticsSelectingSeveralDirectoriesNotContiguousUsingMouse();
+ void statisticsAfterClearingSelection();
+ void statisticsAfterSlidingRight();
+ void statisticsAfterSlidingLeft();
+
+private:
+
+ void assertStatistics(ReportWidget* rw, int sloc, int instrumented, double coverage);
+ void assertEmptyStatistics(ReportWidget* rw);
+
+ DrillDownView* table(ReportWidget* rw);
+ void setStatistics(ReportWidget* rw, int sloc, int instrumented);
+ void setModelFor(ReportWidget* rw);
+ ReportModel* createReportModel();
+ ReportWidget* m_reportWidget;
+};
+
+}
+
+#endif // QTEST_REPORTWIDGETTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h (revision 1522570)
@@ -0,0 +1,84 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_COVEREDFILEFACTORY_H
+#define VERITAS_COVERAGE_COVEREDFILEFACTORY_H
+
+#include "../coveredfile.h"
+
+namespace Veritas
+{
+namespace Test
+{
+
+class CoveredFileFactory
+{
+public:
+ typedef QList<int> Lines;
+
+ /*! Construct a covered file with @param sloc number of reachable lines and
+ @param instrumented covered lines */
+ static CoveredFile* create(const KUrl& name, int sloc, int instrumented)
+ {
+ CoveredFile* f = new CoveredFile;
+ f->setUrl(name);
+ for (int i=0; i<sloc; i++) {
+ f->setCallCount(i,0);
+ }
+ for (int i=0; i<instrumented; i++) {
+ f->setCallCount(i,1);
+ }
+ return f;
+ }
+
+ /*! Construct a covered file with the line numbers in @param notCoveredLines
+ as lines of code with call count zero and those in @param coveredLines with a call
+ count greater than zero. */
+ static CoveredFile* create(const KUrl& name, const Lines& coveredLines, const Lines& notCoveredLines)
+ {
+ CoveredFile* f = new CoveredFile;
+ f->setUrl(name);
+ foreach(int line, notCoveredLines) {
+ f->setCallCount(line,0);
+ }
+ foreach(int line, coveredLines) {
+ f->setCallCount(line, 1);
+ }
+ return f;
+ }
+
+ /*! Construct a covered file with given @param callCountMap Keys are line numbers, values the
+ associated call count */
+ static CoveredFile* create(const KUrl& name, const QMap<int, int>& callCountMap)
+ {
+ CoveredFile* f = new CoveredFile;
+ f->setUrl(name);
+ QMapIterator<int,int> it(callCountMap);
+ while(it.hasNext()) {
+ it.next();
+ f->setCallCount(it.key(), it.value());
+ }
+ return f;
+ }
+};
+
+}} // namespace Veritas
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp (revision 1522570)
@@ -0,0 +1,381 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "colorrangetest.h"
+#include "../colorrange.h"
+
+#include "testutils.h"
+
+#include <QFile>
+
+#include <KConfig>
+#include <KConfigGroup>
+#include <KStandardDirs>
+
+using Veritas::ColorRangeTest;
+
+static const char* filename = "coverageConfigurationTest";
+
+void ColorRangeTest::cleanup() {
+ QFile file(KStandardDirs().findResource("config", filename));
+ if (file.exists()) {
+ file.remove();
+ }
+}
+
+void ColorRangeTest::testConstructor()
+{
+ ColorRange cr;
+
+ QCOMPARE(cr.mode(), ColorRange::Discrete);
+ QCOMPARE(cr.stopPoints().size(), 1);
+ QCOMPARE(cr.colorAt(1), QColor(Qt::white));
+
+ cr.setMode(ColorRange::Gradient);
+ QCOMPARE(cr.stopPoints().size(), 2);
+ QCOMPARE(cr.colorAt(0), QColor(Qt::black));
+ QCOMPARE(cr.colorAt(1), QColor(Qt::white));
+}
+
+void ColorRangeTest::testSetMode()
+{
+ ColorRange cr;
+ cr.setMode(ColorRange::Gradient);
+
+ QCOMPARE(cr.mode(), ColorRange::Gradient);
+
+ cr.setMode(ColorRange::Discrete);
+
+ QCOMPARE(cr.mode(), ColorRange::Discrete);
+}
+
+void ColorRangeTest::testSetStopPoints()
+{
+ ColorRange cr;
+
+ cr.setMode(ColorRange::Discrete);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Gradient);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ QCOMPARE(cr.stopPoints().size(), 1);
+ QCOMPARE(cr.stopPoints()[0].first, 1.0);
+ QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::cyan));
+
+ cr.setMode(ColorRange::Gradient);
+ QCOMPARE(cr.stopPoints().size(), 2);
+ QCOMPARE(cr.stopPoints()[0].first, 0.0);
+ QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::red));
+ QCOMPARE(cr.stopPoints()[1].first, 1.0);
+ QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::green));
+}
+
+void ColorRangeTest::testColorAtDiscreteMode()
+{
+ ColorRange cr;
+
+ cr.setMode(ColorRange::Discrete);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(1, QColor(Qt::yellow)));
+ cr.setStopPoints(stopPoints);
+
+ QCOMPARE(cr.colorAt(0.42), QColor(Qt::yellow));
+}
+
+void ColorRangeTest::testColorAtGradientMode()
+{
+ ColorRange cr;
+
+ cr.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+
+ assertFuzzyColor(cr.colorAt(0.5), QColor(127, 127, 0));
+}
+
+void ColorRangeTest::testLoad()
+{
+ KConfig config(filename);
+ KConfigGroup group(&config, "Color range test");
+
+ group.writeEntry("Mode", "Gradient");
+ KConfigGroup discreteGroup(&group, "Discrete");
+ discreteGroup.writeEntry("NumberOfStopPoints", 2);
+ discreteGroup.writeEntry("StopPoint0Position", 0.42);
+ discreteGroup.writeEntry("StopPoint0Color", QColor(Qt::black));
+ discreteGroup.writeEntry("StopPoint1Position", 1.0);
+ discreteGroup.writeEntry("StopPoint1Color", QColor(Qt::cyan));
+
+ KConfigGroup gradientGroup(&group, "Gradient");
+ gradientGroup.writeEntry("NumberOfStopPoints", 3);
+ gradientGroup.writeEntry("StopPoint0Position", 0.0);
+ gradientGroup.writeEntry("StopPoint0Color", QColor(Qt::red));
+ gradientGroup.writeEntry("StopPoint1Position", 0.5);
+ gradientGroup.writeEntry("StopPoint1Color", QColor(Qt::yellow));
+ gradientGroup.writeEntry("StopPoint2Position", 1.0);
+ gradientGroup.writeEntry("StopPoint2Color", QColor(Qt::green));
+
+ ColorRange cr;
+ cr.load(group);
+
+ QCOMPARE(cr.mode(), ColorRange::Gradient);
+
+ cr.setMode(ColorRange::Discrete);
+ QCOMPARE(cr.stopPoints().size(), 2);
+ QCOMPARE(cr.stopPoints()[0].first, 0.42);
+ QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::black));
+ QCOMPARE(cr.stopPoints()[1].first, 1.0);
+ QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::cyan));
+
+ cr.setMode(ColorRange::Gradient);
+ QCOMPARE(cr.stopPoints().size(), 3);
+ QCOMPARE(cr.stopPoints()[0].first, 0.0);
+ QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::red));
+ QCOMPARE(cr.stopPoints()[1].first, 0.5);
+ QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::yellow));
+ QCOMPARE(cr.stopPoints()[2].first, 1.0);
+ QCOMPARE(cr.stopPoints()[2].second, QColor(Qt::green));
+}
+
+void ColorRangeTest::testSave()
+{
+ ColorRange cr;
+
+ cr.setMode(ColorRange::Discrete);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Gradient);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+
+ KConfig config(filename);
+ KConfigGroup group(&config, "Color range test");
+ cr.save(group);
+
+ QCOMPARE(group.readEntry("Mode"), QString("Gradient"));
+
+ KConfigGroup discreteGroup = group.group("Discrete");
+ QCOMPARE(discreteGroup.readEntry("NumberOfStopPoints", 0), 2);
+ QCOMPARE(discreteGroup.readEntry("StopPoint0Position", 0.0), 0.42);
+ QCOMPARE(discreteGroup.readEntry("StopPoint0Color", QColor()),
+ QColor(Qt::black));
+ QCOMPARE(discreteGroup.readEntry("StopPoint1Position", 0.0), 1.0);
+ QCOMPARE(discreteGroup.readEntry("StopPoint1Color", QColor()),
+ QColor(Qt::cyan));
+
+ KConfigGroup gradientGroup = group.group("Gradient");
+ QCOMPARE(gradientGroup.readEntry("NumberOfStopPoints", 0), 3);
+ QCOMPARE(gradientGroup.readEntry("StopPoint0Position", 1.0), 0.0);
+ QCOMPARE(gradientGroup.readEntry("StopPoint0Color", QColor()),
+ QColor(Qt::red));
+ QCOMPARE(gradientGroup.readEntry("StopPoint1Position", 0.0), 0.5);
+ QCOMPARE(gradientGroup.readEntry("StopPoint1Color", QColor()),
+ QColor(Qt::yellow));
+ QCOMPARE(gradientGroup.readEntry("StopPoint2Position", 0.0), 1.0);
+ QCOMPARE(gradientGroup.readEntry("StopPoint2Color", QColor()),
+ QColor(Qt::green));
+}
+
+void ColorRangeTest::testLoadAfterSave()
+{
+ ColorRange cr;
+
+ cr.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+
+ KConfig config(filename);
+ KConfigGroup group(&config, "Color range test");
+ cr.save(group);
+
+ ColorRange newCr;
+ newCr.load(group);
+
+ QCOMPARE(newCr.mode(), ColorRange::Discrete);
+
+ newCr.setMode(ColorRange::Discrete);
+ QCOMPARE(newCr.stopPoints().size(), 2);
+ QCOMPARE(newCr.stopPoints()[0].first, 0.42);
+ QCOMPARE(newCr.stopPoints()[0].second, QColor(Qt::black));
+ QCOMPARE(newCr.stopPoints()[1].first, 1.0);
+ QCOMPARE(newCr.stopPoints()[1].second, QColor(Qt::cyan));
+
+ newCr.setMode(ColorRange::Gradient);
+ QCOMPARE(newCr.stopPoints().size(), 3);
+ QCOMPARE(newCr.stopPoints()[0].first, 0.0);
+ QCOMPARE(newCr.stopPoints()[0].second, QColor(Qt::red));
+ QCOMPARE(newCr.stopPoints()[1].first, 0.5);
+ QCOMPARE(newCr.stopPoints()[1].second, QColor(Qt::yellow));
+ QCOMPARE(newCr.stopPoints()[2].first, 1.0);
+ QCOMPARE(newCr.stopPoints()[2].second, QColor(Qt::green));
+}
+
+void ColorRangeTest::testOperatorEqual()
+{
+ ColorRange cr;
+ ColorRange cr2;
+
+ cr.setMode(ColorRange::Gradient);
+ cr2.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ cr2.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ QVERIFY(cr == cr2);
+ QVERIFY(!(cr != cr2));
+}
+
+void ColorRangeTest::testOperatorEqualDifferentMode()
+{
+ ColorRange cr;
+ ColorRange cr2;
+
+ cr.setMode(ColorRange::Gradient);
+ cr2.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ cr2.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ cr2.setMode(ColorRange::Gradient);
+
+ QVERIFY(!(cr == cr2));
+ QVERIFY(cr != cr2);
+}
+
+void ColorRangeTest::testOperatorEqualDifferentDiscreteColorRange()
+{
+ ColorRange cr;
+ ColorRange cr2;
+
+ cr.setMode(ColorRange::Gradient);
+ cr2.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ cr2.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.23, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr2.setStopPoints(stopPoints);
+
+ QVERIFY(!(cr == cr2));
+ QVERIFY(cr != cr2);
+}
+
+void ColorRangeTest::testOperatorEqualDifferentGradientColorRange()
+{
+ ColorRange cr;
+ ColorRange cr2;
+
+ cr.setMode(ColorRange::Gradient);
+ cr2.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor(Qt::red)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr.setStopPoints(stopPoints);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0, QColor(Qt::blue)));
+ stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
+ stopPoints.append(StopPoint(1, QColor(Qt::green)));
+ cr2.setStopPoints(stopPoints);
+
+ cr.setMode(ColorRange::Discrete);
+ cr2.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
+ stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
+ cr.setStopPoints(stopPoints);
+ cr2.setStopPoints(stopPoints);
+
+ QVERIFY(!(cr == cr2));
+ QVERIFY(cr != cr2);
+}
+
+////////////////////////////// Asserts ////////////////////////////////////////
+
+void ColorRangeTest::assertFuzzyColor(const QColor& actual, const QColor& expected)
+{
+ QVERIFY(actual.red() >= expected.red() -1);
+ QVERIFY(actual.red() <= expected.red() + 1);
+ QVERIFY(actual.green() >= expected.green() -1);
+ QVERIFY(actual.green() <= expected.green() + 1);
+ QVERIFY(actual.blue() >= expected.blue() -1);
+ QVERIFY(actual.blue() <= expected.blue() + 1);
+}
+
+QTEST_KDEMAIN(ColorRangeTest, NoGUI)
+
+#include "colorrangetest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h (revision 1522570)
@@ -0,0 +1,50 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVEREDFILETEST_H_INCLUDED
+#define VERITAS_COVEREDFILETEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas
+{
+
+class CoveredFile;
+class CoveredFileTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void construct();
+ void sunny();
+ void zeroSloc();
+ void callCount();
+ void linesSet();
+ void isReachable();
+
+private:
+ CoveredFile* m_file;
+};
+
+}
+
+#endif // VERITAS_COVEREDFILETEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp (revision 1522570)
@@ -0,0 +1,139 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "lcovinfoparsertest.h"
+#include "../lcovinfoparser.h"
+#include "../coveredfile.h"
+#include "coveredfilefactory.h"
+#include <KDebug>
+#include "testutils.h"
+
+using Veritas::CoveredFile;
+using Veritas::LcovInfoParser;
+using Veritas::LcovInfoParserTest;
+using Veritas::Test::CoveredFileFactory;
+
+void LcovInfoParserTest::init()
+{
+ m_parser = new LcovInfoParser;
+}
+
+void LcovInfoParserTest::cleanup()
+{
+// delete m_parser;
+ m_parser->deleteLater();
+}
+
+void LcovInfoParserTest::cleanupTestCase()
+{
+ QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit()));
+ QCoreApplication::exec();
+}
+
+void LcovInfoParserTest::assertCoveredFilesEqual(CoveredFile* f1, CoveredFile* f2)
+{
+ KOMPARE(f1->url(), f2->url());
+ KOMPARE(f1->sloc(), f2->sloc());
+ KOMPARE(f1->nrofCoveredLines(), f2->nrofCoveredLines());
+ KVERIFY(qAbs(f1->coverageRatio() - f2->coverageRatio()) < 0.01);
+ KOMPARE(f1->callCountMap(), f2->callCountMap());
+ KOMPARE(f1->coveredLines(), f2->coveredLines());
+}
+
+void LcovInfoParserTest::singleCoveredFile()
+{
+ // just a quick test, needs to be extended and cleaned.
+
+ QString input =
+ "SF:/path/to/foo.h\n"
+ "FN:10,_ZN11QStringListD1Ev\n"
+ "DA:10,5\n"
+ "DA:11,0\n"
+ "LF:2\n"
+ "LH:1\n"
+ "end_of_record\n";
+
+ m_parser->parseLines( input.split( '\n' ) );
+ QList<CoveredFile*> files = m_parser->fto_coveredFiles();
+ KOMPARE(1, files.count());
+ CoveredFile* f = files[0];
+ KVERIFY(f != 0);
+
+ KOMPARE(KUrl("/path/to/foo.h"), f->url());
+ KOMPARE(2, f->sloc());
+ KOMPARE(1, f->nrofCoveredLines());
+ KOMPARE(50, f->coverageRatio());
+ KOMPARE(2, f->callCountMap().count());
+ KVERIFY(f->callCountMap().contains(10));
+ KVERIFY(f->callCountMap().contains(11));
+ KOMPARE(5, f->callCountMap()[10]);
+ KOMPARE(0, f->callCountMap()[11]);
+ }
+
+void LcovInfoParserTest::multipleFiles()
+{
+ QString input =
+ "SF:/path/to/foo.h\n"
+ "FN:10,functionFoo()\n"
+ "DA:10,5\n"
+ "DA:11,0\n"
+ "LF:2\n"
+ "LH:1\n"
+ "end_of_record\n"
+ "SF:/path/to/bar.h\n"
+ "FN:15,functionBar()\n"
+ "DA:15,5\n"
+ "DA:16,0\n"
+ "DA:17,10\n"
+ "LF:3\n"
+ "LH:2\n"
+ "end_of_record\n";
+
+ m_parser->parseLines( input.split( '\n' ) );
+ QList<CoveredFile*> files = m_parser->fto_coveredFiles();
+ KOMPARE(2, files.count());
+
+ CoveredFile* actualFile1 = files[0];
+ KVERIFY(actualFile1 != 0);
+ QMap<int, int> expCallCount; // expected number of calls on a source line.
+ // { source line x call count }
+ expCallCount[10] = 5;
+ expCallCount[11] = 0;
+ KUrl url("/path/to/foo.h");
+ CoveredFile* expFile1 = CoveredFileFactory::create(url, expCallCount);
+ assertCoveredFilesEqual(expFile1, actualFile1);
+
+ CoveredFile* actualFile2 = files[1];
+ KVERIFY(actualFile2 != 0);
+ url = KUrl("/path/to/bar.h");
+ expCallCount.clear();
+ expCallCount[15] = 5;
+ expCallCount[16] = 0;
+ expCallCount[17] = 10;
+ CoveredFile* expFile2 = CoveredFileFactory::create(url, expCallCount);
+ assertCoveredFilesEqual(expFile2, actualFile2);
+
+ delete expFile1;
+ delete expFile2;
+}
+
+
+QTEST_MAIN( LcovInfoParserTest )
+#include "lcovinfoparsertest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h (revision 1522570)
@@ -0,0 +1,58 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QTEST_REPORTFILEITEMTEST_H_INCLUDED
+#define QTEST_REPORTFILEITEMTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include <KUrl>
+#include <QString>
+
+namespace Veritas
+{
+
+class ReportFileItem;
+class CoveredFile;
+class ReportFileItemTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void construct();
+ void addCoverage();
+ void addMultipleCoverage();
+
+private:
+ void assertInstrumentedItem(int);
+ void assertCoverageItem(double);
+ void assertSlocItem(int);
+
+private:
+ ReportFileItem* m_file;
+ KUrl m_url;
+ QString m_fileName;
+ QList<CoveredFile*> m_garbage;
+};
+
+}
+
+#endif // QTEST_REPORTFILEITEMTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h (revision 1522570)
@@ -0,0 +1,62 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REPORTMODELTEST_H
+#define VERITAS_COVERAGE_REPORTMODELTEST_H
+
+#include <QtCore/QObject>
+#include <QtCore/QVariant>
+#include <KUrl>
+class QModelIndex;
+
+namespace Veritas
+{
+
+class CoveredFile;
+class ReportModel;
+class ReportModelTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void sortRole();
+ void addSingleCoverageData();
+ void multiCoverageOneFile();
+ void differentSlocSetOneFile();
+
+private:
+ QVariant fetchSortData(int row);
+ void assertDirAtEquals(const QModelIndex& i, QString path, int sloc, int instrumented);
+ void assertFileAtEquals(const QModelIndex& i, QString name, int sloc, int instrumented, double cov);
+
+private:
+ ReportModel* m_model;
+ KUrl m_fileUrl;
+ QString m_fileDir;
+ QString m_fileName;
+
+ QList<CoveredFile*> m_garbage;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_REPORTMODELTEST_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.h (revision 1522570)
@@ -0,0 +1,50 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTSTUBS_PLUGINSTUB_H
+#define TESTSTUBS_PLUGINSTUB_H
+
+#include "interfaces/iplugin.h"
+#include "interfaces/contextmenuextension.h"
+#include "../coverageexport.h"
+
+namespace TestStubs
+{
+class VERITAS_COVERAGE_EXPORT Plugin : public KDevelop::IPlugin
+{
+Q_OBJECT
+public:
+ Plugin(const KComponentData &instance, QObject *parent) : KDevelop::IPlugin(instance, parent) {}
+ virtual ~Plugin() {}
+ virtual void unload() { Q_ASSERT(0); }
+ KIconLoader* iconLoader() const { Q_ASSERT(0); return 0; }
+ KDevelop::ICore *core() const { Q_ASSERT(0); return 0; }
+ virtual KDevelop::ContextMenuExtension contextMenuExtension( KDevelop::Context* context ) { Q_UNUSED(context); return KDevelop::ContextMenuExtension(); }
+
+/*public Q_SLOTS:
+ void newIconLoader() const;
+
+protected:
+ void addExtension( const QString& );
+ virtual void initializeGuiState();*/
+};
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h (revision 1522570)
@@ -0,0 +1,49 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QTEST_LCOVJOBTEST_H_INCLUDED
+#define QTEST_LCOVJOBTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace TestStubs { class Core; class PluginController; }
+
+namespace Veritas
+{
+
+class LcovJobTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void initTestCase();
+ void init();
+ void cleanup();
+
+ void basicRun();
+
+private:
+ TestStubs::Core* m_core;
+ TestStubs::PluginController* m_plugCtrl;
+
+};
+
+}
+
+#endif // QTEST_LCOVJOBTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h (revision 1522570)
@@ -0,0 +1,76 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTSTUBS_PLUGINCONTROLLER_STUB_H
+#define TESTSTUBS_PLUGINCONTROLLER_STUB_H
+
+
+
+#include "interfaces/iplugincontroller.h"
+#include "interfaces/contextmenuextension.h"
+#include "shell/profileengine.h" // yaikes, needed because no interface + plugincontroller returns references.
+
+namespace TestStubs
+{
+
+class PluginController : public KDevelop::IPluginController
+{
+public:
+// enum PluginType {
+// Global = 0,
+// Project
+// };
+
+ PluginController( QObject* parent = 0 ) : KDevelop::IPluginController(parent), m_pluginForExtension(0) {} ;
+ virtual ~PluginController() {}
+
+ KDevelop::IPlugin* m_pluginForExtension;
+
+ virtual KPluginInfo pluginInfo( KDevelop::IPlugin* ) const { Q_ASSERT(0); return KPluginInfo(); }
+ virtual QList<KDevelop::IPlugin*> loadedPlugins() const { Q_ASSERT(0); return QList<KDevelop::IPlugin*>(); }
+ virtual void unloadPlugin( const QString & plugin ) {Q_ASSERT(0); }
+ virtual KDevelop::IPlugin* loadPlugin( const QString & pluginName ) { Q_ASSERT(0); return 0; }
+
+ virtual KDevelop::IPlugin *pluginForExtension(const QString &extension, const QString& pluginname = "" ) { return m_pluginForExtension; }
+ virtual QList<KDevelop::IPlugin*> allPluginsForExtension(const QString &extension, const QStringList &constraints) { Q_ASSERT(0); return QList<KDevelop::IPlugin*>(); }
+
+// static KPluginInfo::List query( const QString &serviceType, const QString &constraint );
+// static KPluginInfo::List queryPlugins( const QString &constraint );
+// static QStringList argumentsFromService( const KService::Ptr &service );
+
+ virtual QString currentProfile() const { Q_ASSERT(0); return ""; }
+ virtual void loadPlugins( PluginType offer ) { Q_ASSERT(0); return; }
+ virtual void unloadPlugins( PluginType offer ) { Q_ASSERT(0); return; }
+ KDevelop::ProfileEngine* m_engine;
+ virtual KDevelop::ProfileEngine &engine() const { Q_ASSERT(0); return *m_engine; }
+ virtual QString changeProfile( const QString &newProfile ) { Q_ASSERT(0); return ""; }
+ virtual QExtensionManager* extensionManager() { Q_ASSERT(0); return 0; }
+ virtual QList<KDevelop::ContextMenuExtension> queryPluginsForContextMenuExtensions( KDevelop::Context* context ) const { Q_ASSERT(0); return QList<KDevelop::ContextMenuExtension>(); }
+
+// Q_SIGNALS:
+// void loadingPlugin( const QString& );
+// void pluginLoaded( KDevelop::KDevelop::IPlugin* );
+// void pluginUnloaded( KDevelop::KDevelop::IPlugin* );
+// void profileChanged();
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp (revision 1522570)
@@ -0,0 +1,372 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "annotationmanagertest.h"
+#include "../annotationmanager.h"
+#include "../coveredfile.h"
+#include <interfaces/icore.h>
+#include <interfaces/idocument.h>
+#include <sublime/controller.h>
+
+#include <kparts/mainwindow.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+#include <ktexteditor/annotationinterface.h>
+
+#include "corestub.h"
+#include "documentstub.h"
+#include "viewstub.h"
+
+#include "testutils.h"
+#include <QTextStream>
+
+using KDevelop::ICore;
+using KDevelop::IDocument;
+using KDevelop::ILanguageController;
+using KDevelop::IProjectController;
+using KDevelop::IUiController;
+using KDevelop::IRunController;
+
+using Veritas::AnnotationManager;
+using Veritas::AnnotationManagerTest;
+using Veritas::CoveredFile;
+
+using KTextEditor::AnnotationModel;
+using KTextEditor::Cursor;
+using KTextEditor::Range;
+using KTextEditor::View;
+
+using TestStubs::KDevDocument;
+using TestStubs::Core;
+using TestStubs::TextDocument;
+using TestStubs::UiController;
+
+///////////////// fixture ////////////////////////////////////////////////////
+
+void AnnotationManagerTest::initTestCase()
+{
+ m_core = new TestStubs::Core;
+ Q_ASSERT(m_core);
+ UiController* uic = new TestStubs::UiController;
+ m_core->m_uiController = uic;
+ uic->m_activeMainWindow = new KParts::MainWindow;
+ uic->m_controller = new Sublime::Controller;
+ m_docCtrl = new TestStubs::DocumentController(0);
+ m_core->m_documentController = m_docCtrl;
+}
+
+void AnnotationManagerTest::init()
+{
+ m_annotationManager = new AnnotationManager;
+ m_someUrl = KUrl("foo.cpp");
+ m_widget = new QWidget;
+ m_lineNr = 10;
+ m_nrofCalls = 5;
+}
+
+void AnnotationManagerTest::cleanup()
+{
+ if (m_annotationManager) delete m_annotationManager;
+ if (m_widget) delete m_widget;
+ qDeleteAll(m_garbageFiles);
+ m_garbageFiles.clear();
+ qDeleteAll(m_garbageDocs);
+ m_garbageDocs.clear();
+ qDeleteAll(m_garbage);
+ m_garbage.clear();
+}
+
+///////////////// commands ///////////////////////////////////////////////////
+
+void AnnotationManagerTest::instantiate()
+{
+ QMap<KUrl, CoveredFile*> files;
+ m_annotationManager->setCoveredFiles(files);
+ KDevDocument* doc = createKDevDocument(m_someUrl);
+ m_annotationManager->watch(doc);
+ m_annotationManager->stopWatching(doc);
+}
+
+void AnnotationManagerTest::singleLine()
+{
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+ m_annotationManager->watch(doc);
+
+ View* v = triggerAnnotationsOnView(doc); // exercise
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v); // verify
+}
+
+void AnnotationManagerTest::multipleLines()
+{
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ int line2 = 20, callCount2 = 10;
+ f->setCallCount(line2, callCount2);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+ m_annotationManager->watch(doc);
+
+ View* v = triggerAnnotationsOnView(doc); // exercise
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v); // verify
+ assertAnnoCallCountEquals(line2, callCount2, v);
+}
+
+void AnnotationManagerTest::multipleViews()
+{
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+ m_annotationManager->watch(doc);
+
+ // exercise
+ View* v1 = triggerAnnotationsOnView(doc);
+ // inject another view in the stub
+ TextDocument* tdoc = (TextDocument*)doc->textDocument();
+ tdoc->m_createView = new TestStubs::TextView(0);
+ m_garbage << tdoc->m_createView;
+ View* v2 = triggerAnnotationsOnView(doc);
+ Q_ASSERT(v1 != v2);
+
+ // verify
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v1);
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v2);
+}
+
+void AnnotationManagerTest::multipleFiles()
+{
+ // setup
+ CoveredFile* f1 = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f1);
+ int line2 = 20, nrofCalls2 = 5;
+ CoveredFile* f2 = createCoveredFile(line2, nrofCalls2, KUrl("bar.cpp"));
+ m_annotationManager->addCoverageData(f2);
+
+ KDevDocument* doc1 = createKDevDocument(f1->url());
+ m_annotationManager->watch(doc1);
+ KDevDocument* doc2 = createKDevDocument(f2->url());
+ m_annotationManager->watch(doc2);
+
+ // exercise
+ View* v1 = triggerAnnotationsOnView(doc1);
+ View* v2 = triggerAnnotationsOnView(doc2);
+
+ // verify
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v1);
+ assertAnnoCallCountEquals(line2, nrofCalls2, v2);
+}
+
+void AnnotationManagerTest::notCovered()
+{
+ // setup
+ m_lineNr = 5;
+ CoveredFile* f = createCoveredFile(5, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+ m_annotationManager->watch(doc);
+
+ // exercise
+ View* v = triggerAnnotationsOnView(doc);
+
+ // verify
+ assertNoAnnotationsOnLine(4, v);
+ assertNoAnnotationsOnLine(6, v);
+ assertNoAnnotationsOnLine(10, v);
+}
+
+void AnnotationManagerTest::multiCoverageOneFile()
+{
+ CoveredFile* f1 = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ CoveredFile* f2 = createCoveredFile(m_lineNr+1, m_nrofCalls+1, m_someUrl);
+ m_annotationManager->addCoverageData(f1);
+ m_annotationManager->addCoverageData(f2);
+ KDevDocument* doc = createKDevDocument(m_someUrl);
+ m_annotationManager->watch(doc);
+
+ View* v = triggerAnnotationsOnView(doc);
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
+ assertAnnoCallCountEquals(m_lineNr+1, m_nrofCalls+1, v);
+}
+
+
+void AnnotationManagerTest::stopWatching()
+{
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+ m_annotationManager->watch(doc);
+
+ // exercise
+ View* v = triggerAnnotationsOnView(doc);
+ m_annotationManager->stopWatching(doc);
+
+ // verify
+ KTextEditor::AnnotationViewInterface *anno =
+ qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
+ Q_ASSERT_X(anno, "assertAnnoCallCountEquals()", "Err?");
+ KVERIFY(! anno->isAnnotationBorderVisible());
+ AnnotationModel* model = anno->annotationModel();
+ KVERIFY(! model);
+}
+
+void AnnotationManagerTest::annotationsOnExistingView()
+{
+ // create and activate a text view _before_ activating coverage
+ // annotations on the document
+
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+
+ // create a view
+ m_docCtrl->emitTextDocumentCreated(doc);
+ QTest::qWait(50);
+ KTextEditor::Document* tdoc = doc->textDocument();
+ KTextEditor::View* v = tdoc->createView(m_widget);
+ QTest::qWait(50);
+
+ // exercise
+ m_annotationManager->watch(doc);
+
+ // verify
+ KTextEditor::AnnotationViewInterface *anno =
+ qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
+ Q_ASSERT_X(anno, "annotationsOnExistingView", "Err?");
+ KVERIFY(anno->isAnnotationBorderVisible());
+ AnnotationModel* model = anno->annotationModel();
+ KVERIFY(model);
+
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
+}
+
+void AnnotationManagerTest::addRemoveAndReAddAnnotations()
+{
+ // setup
+ CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
+ m_annotationManager->addCoverageData(f);
+ KDevDocument* doc = createKDevDocument(f->url());
+
+ // exercise
+ m_annotationManager->watch(doc);
+ View* v = triggerAnnotationsOnView(doc);
+ m_annotationManager->stopWatching(doc);
+ m_annotationManager->watch(doc);
+
+ // verify
+ assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
+}
+
+////////////////// setup helpers /////////////////////////////////////////////
+
+void AnnotationManagerTest::initManager(CoveredFile* f)
+{
+ //QMap<KUrl, CoveredFile*> files;
+ //files[f->url()] = f;
+ //m_manager->setCoveredFiles(files);
+}
+
+KDevDocument* AnnotationManagerTest::createKDevDocument(const KUrl& u)
+{
+ TestStubs::KDevDocument* kdoc = new TestStubs::KDevDocument(m_core);
+ m_garbageDocs << kdoc;
+ kdoc->m_url = u;
+ TestStubs::TextDocument* doc = new TestStubs::TextDocument;
+ m_garbage << doc;
+ kdoc->m_textDocument = doc;
+ doc->m_createView = new TestStubs::TextView(0);
+ m_garbage << doc->m_createView;
+ return kdoc;
+}
+
+CoveredFile* AnnotationManagerTest::createCoveredFile(int line, int callCount, KUrl url)
+{
+ CoveredFile* f = new CoveredFile();
+ f->setUrl(url);
+ f->setCallCount(line, callCount);
+ m_garbageFiles << f;
+ return f;
+}
+
+/////////////////// exercise helpers /////////////////////////////////////////
+
+KTextEditor::View* AnnotationManagerTest::triggerAnnotationsOnView(KDevelop::IDocument* doc)
+{
+ m_docCtrl->emitTextDocumentCreated(doc); // fake activate the doc.
+ QTest::qWait(50);
+ KTextEditor::Document* tdoc = doc->textDocument();
+ // now spawn a view which should trigger annotations being set.
+ KTextEditor::View* v = tdoc->createView(m_widget);
+ QTest::qWait(50);
+ return v;
+}
+
+////////////////// custom assertions /////////////////////////////////////////
+
+AnnotationModel* annotationModelForView(View* v)
+{
+ KTextEditor::AnnotationViewInterface *anno =
+ qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
+ Q_ASSERT_X(anno, "assertAnnoCallCountEquals()", "Err?");
+ Q_ASSERT(anno->isAnnotationBorderVisible());
+ KTextEditor::AnnotationModel* model = anno->annotationModel();
+ return model;
+}
+
+void AnnotationManagerTest::assertAnnoCallCountEquals(int line, int count, KTextEditor::View* v)
+{
+ AnnotationModel* model = annotationModelForView(v);
+ KVERIFY_MSG(model != 0, "Annotation model not set");
+ QString expected = QString::number(count);
+ // annotationmodel starts counting from zero
+ QString actual = model->data(line-1, Qt::DisplayRole).toString();
+ QString failureMsg;
+ QTextStream str(&failureMsg);
+ str << "Wrong call count for line " << line
+ << " was expecting " << expected << " but got " << actual;
+ KOMPARE_MSG(expected, actual, failureMsg);
+}
+
+void AnnotationManagerTest::assertNoAnnotationsOnLine(int line, KTextEditor::View* v)
+{
+ AnnotationModel* model = annotationModelForView(v);
+ KVERIFY_MSG(model != 0, "Annotation model not set");
+ QVariant expected; // should return default qvariant.
+ QVariant actual = model->data(line-1, Qt::DisplayRole);
+ QString failureMsg;
+ QTextStream str(&failureMsg);
+ str << "Was not expecting annotation on line "
+ << line << " but got " << actual.toString();
+ KOMPARE_MSG(expected, actual, failureMsg);
+}
+
+void AnnotationManagerTest::assertAnnotationsGone(View* v)
+{
+ AnnotationModel* model = annotationModelForView(v);
+ KVERIFY_MSG(! model, "Annotation model should have be reset.");
+}
+
+
+#include "annotationmanagertest.moc"
+QTEST_KDEMAIN(AnnotationManagerTest, GUI)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp (revision 1522570)
@@ -0,0 +1,153 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "reportitemstest.h"
+#include "coveredfilefactory.h"
+#include "../coveredfile.h"
+#include "../reportmodel.h"
+
+#include "testutils.h"
+
+using Veritas::CoveredFile;
+using Veritas::ReportItemsTest;
+using Veritas::ReportValueItem;
+using Veritas::ReportDirData;
+using Veritas::ReportDirItem;
+using Veritas::ReportFileItem;
+using Veritas::ReportModel;
+using Veritas::Test::CoveredFileFactory;
+
+///////////////////////////// fixture ////////////////////////////////////////
+
+void ReportItemsTest::init()
+{}
+
+void ReportItemsTest::cleanup()
+{
+ qDeleteAll(m_garbage);
+ m_garbage.clear();
+ qDeleteAll(m_garbageFiles);
+ m_garbageFiles.clear();
+}
+
+///////////////////////////// commands ////////////////////////////////////////
+
+void ReportItemsTest::constructDoubleValueItem()
+{
+ ReportValueItem doubleItem(5.0);
+ KVERIFY(ReportModel::Value == doubleItem.type());
+ KOMPARE(5.0, doubleItem.value());
+ KOMPARE(QString("5.0"), doubleItem.data(Qt::DisplayRole));
+ KVERIFY(! doubleItem.isEditable());
+ KVERIFY(! doubleItem.isSelectable());
+ KVERIFY(! doubleItem.isCheckable());
+}
+
+void ReportItemsTest::constructIntValueItem()
+{
+ ReportValueItem intItem(5);
+ KVERIFY(ReportModel::Value == intItem.type());
+ KOMPARE(5, intItem.value());
+ KOMPARE(QString("5"), intItem.data(Qt::DisplayRole));
+ KVERIFY(! intItem.isEditable());
+ KVERIFY(! intItem.isSelectable());
+ KVERIFY(! intItem.isCheckable());
+}
+
+void ReportItemsTest::constructDirItem()
+{
+ ReportDirItem dir("/my/dir");
+ KVERIFY(ReportModel::Dir == dir.type());
+ KOMPARE(0, dir.sloc());
+ KOMPARE(0, dir.nrofCoveredLines());
+ KOMPARE(0, dir.coverageRatio());
+ KVERIFY(! dir.isEditable());
+ KVERIFY(dir.isSelectable());
+ KVERIFY(! dir.isCheckable());
+}
+
+void ReportItemsTest::addCoverageDataTo(ReportDirItem& dir, const QString& path, int sloc, int instrumented)
+{
+ CoveredFile* f = CoveredFileFactory::create(KUrl(path), sloc, instrumented);
+ ReportFileItem* fItem = new ReportFileItem(KUrl(path));
+ fItem->addCoverageData(f);
+ dir.appendRow(fItem);
+ dir.updateStats();
+ m_garbage << fItem->coverageRatioItem() << fItem->slocItem() << fItem->nrofCoveredLinesItem();
+ m_garbageFiles << f;
+}
+
+void ReportItemsTest::addFileToDirItem()
+{
+ ReportDirItem* dir = new ReportDirItem("/my/dir");
+ addCoverageDataTo(*dir, "/my/dir/foo.cpp", 10, 5);
+ KOMPARE(10, dir->sloc());
+ KOMPARE(5, dir->nrofCoveredLines());
+ KVERIFY(qAbs(100*5/10 - dir->coverageRatio()) < 0.1);
+ delete dir;
+}
+
+void ReportItemsTest::addMultipleFilesToDir()
+{
+ ReportDirItem* dir = new ReportDirItem("/my/dir");
+ addCoverageDataTo(*dir, "/my/dir/foo.cpp", 10, 5);
+ addCoverageDataTo(*dir, "/my/dir/bar.cpp", 20, 5);
+ KOMPARE(10+20, dir->sloc());
+ KOMPARE(5+5, dir->nrofCoveredLines());
+ KVERIFY(qAbs(100*((double)dir->nrofCoveredLines()/dir->sloc()) - dir->coverageRatio()) < 0.1);
+ delete dir;
+}
+
+void ReportItemsTest::constructDirData()
+{
+ ReportDirData dirData;
+ KOMPARE(0, dirData.sloc());
+ KOMPARE(0, dirData.nrofCoveredLines());
+}
+
+void ReportItemsTest::dirDataSetSloc()
+{
+ ReportDirData dirData;
+ dirData.setSloc(16);
+ KOMPARE(16, dirData.sloc());
+}
+
+void ReportItemsTest::dirDataSetInstrumented()
+{
+ ReportDirData dirData;
+ dirData.setNrofCoveredLines(23);
+ KOMPARE(23, dirData.nrofCoveredLines());
+}
+
+void ReportItemsTest::dirDataCoverage()
+{
+ ReportDirData dirData;
+ KOMPARE(0, dirData.coverageRatio());
+
+ dirData.setNrofCoveredLines(21);
+ dirData.setSloc(42);
+ KOMPARE(50, dirData.coverageRatio());
+
+ dirData.setNrofCoveredLines(4);
+ dirData.setSloc(2500);
+ QCOMPARE(0.16, dirData.coverageRatio());
+}
+
+QTEST_KDEMAIN( ReportItemsTest, NoGUI)
+#include "reportitemstest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.h (revision 1522570)
@@ -0,0 +1,124 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTSTUBS_VIEWSTUB_H
+#define TESTSTUBS_VIEWSTUB_H
+
+#include <ktexteditor/view.h>
+#include <ktexteditor/annotationinterface.h>
+#include "../coverageexport.h"
+
+namespace TestStubs
+{
+
+class VERITAS_COVERAGE_EXPORT TextView :
+ public KTextEditor::View,
+ public KTextEditor::AnnotationViewInterface
+{
+Q_OBJECT
+Q_INTERFACES(KTextEditor::AnnotationViewInterface)
+
+public:
+ void setAnnotationModel(KTextEditor::AnnotationModel* model) {
+ m_annotationModel = model;
+ }
+ KTextEditor::AnnotationModel* annotationModel() const {
+ return m_annotationModel;
+ }
+ void setAnnotationBorderVisible(bool visible) {
+ m_borderVisible = visible;
+ }
+ bool isAnnotationBorderVisible() const {
+ return m_borderVisible;
+ }
+ KTextEditor::AnnotationModel* m_annotationModel;
+ bool m_borderVisible;
+
+Q_SIGNALS:
+ void annotationContextMenuAboutToShow(KTextEditor::View* view, QMenu* menu, int line);
+ void annotationActivated(KTextEditor::View* view, int line);
+ void annotationBorderVisibilityChanged(View* view, bool visible);
+
+public:
+ TextView(QWidget *parent) :
+ KTextEditor::View(parent),
+ m_annotationModel(0) {}
+ virtual ~TextView() {}
+
+ virtual KTextEditor::Document *document() const { return 0; }
+ virtual QString viewMode() const { return ""; }
+// enum EditMode {
+// EditInsert = 0, /**< Insert mode. Characters will be added. */
+// EditOverwrite = 1 /**< Overwrite mode. Characters will be replaced. */
+// };
+ virtual enum EditMode viewEditMode() const { return EditOverwrite; }
+ virtual void setContextMenu(QMenu *menu) { Q_UNUSED(menu); }
+ virtual QMenu *contextMenu() const { return 0; }
+ virtual QMenu* defaultContextMenu(QMenu* menu = 0L) const { Q_UNUSED(menu); return 0; }
+ virtual bool setCursorPosition(KTextEditor::Cursor position) { Q_UNUSED(position); return false; }
+ virtual KTextEditor::Cursor cursorPosition() const { return KTextEditor::Cursor(); }
+ virtual KTextEditor::Cursor cursorPositionVirtual() const { return KTextEditor::Cursor(); }
+ virtual QPoint cursorToCoordinate(const KTextEditor::Cursor& cursor) const { Q_UNUSED(cursor); return QPoint(); }
+ virtual QPoint cursorPositionCoordinates() const { return QPoint(); }
+ virtual bool setSelection(const KTextEditor::Range &range) { Q_UNUSED(range); return true; }
+ /* virtual bool setSelection(const Cursor &position,
+ int length,
+ bool wrap = true);*/
+ virtual bool selection() const { return true; }
+
+ KTextEditor::Range m_selectionRange;
+
+ virtual const KTextEditor::Range &selectionRange() const { return m_selectionRange; }
+ virtual QString selectionText() const { return ""; }
+ virtual bool removeSelection() { return true; }
+ virtual bool removeSelectionText() { return true; }
+ virtual bool setBlockSelection(bool on) { Q_UNUSED(on); return true; }
+ virtual bool blockSelection() const { return true; }
+
+ virtual bool mouseTrackingEnabled() const { return true; }
+ virtual bool setMouseTrackingEnabled(bool b) { Q_UNUSED(b); return true; }
+
+#if 0
+ Q_SIGNALS:
+ void contextMenuAboutToShow(KTextEditor::View* view, QMenu* menu);
+ void focusIn(KTextEditor::View *view);
+ void focusOut(KTextEditor::View *view);
+ void viewModeChanged(KTextEditor::View *view);
+ void viewEditModeChanged(KTextEditor::View *view,
+ enum KTextEditor::View::EditMode mode);
+ void informationMessage(KTextEditor::View *view, const QString &message);
+ void textInserted(KTextEditor::View *view,
+ const KTextEditor::Cursor &position,
+ const QString &text);
+
+ void cursorPositionChanged(KTextEditor::View *view,
+ const KTextEditor::Cursor& newPosition);
+ void verticalScrollPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor& newPos);
+ void horizontalScrollPositionChanged(KTextEditor::View *view);
+ void mousePositionChanged(KTextEditor::View *view,
+ const KTextEditor::Cursor& newPosition);
+ void selectionChanged(KTextEditor::View *view);
+#endif
+
+};
+
+}
+
+#endif // TESTFAKES_VIEWSTUB
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/viewstub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h (revision 1522570)
@@ -0,0 +1,50 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_GRADIENTCOLORRANGETEST_H
+#define VERITAS_COVERAGE_GRADIENTCOLORRANGETEST_H
+
+#include <QtCore/QObject>
+#include <QColor>
+
+namespace Veritas {
+
+class GradientColorRangeTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void testConstructor();
+ void testSetStopPoints();
+ void testColorAtWithNoMiddleStopPoints();
+ void testColorAtWithSeveralStopPoints();
+
+private:
+
+ /**
+ * Checks that actual has the three RGB components equal to the RGB
+ * components +-1 of expected.
+ */
+ void assertFuzzyColor(const QColor& actual, const QColor& expected);
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp (revision 1522570)
@@ -0,0 +1,440 @@
+/* KDevelop coverage plugin
+ * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "reportwidgettest.h"
+
+#define protected public
+#define private public
+#include "../reportwidget.h"
+#undef private
+#undef protected
+
+#include "../coveredfile.h"
+#include "../drilldownview.h"
+#include "../reportmodel.h"
+#include "../reportproxymodel.h"
+#include "../ui_reportwidget.h"
+
+#include <QtTest/QTest>
+#include <QtTest/QTestKeyClicksEvent>
+#include <qtest_kde.h>
+#include <QDir>
+#include <QLabel>
+
+using Veritas::CoveredFile;
+using Veritas::DrillDownView;
+using Veritas::ReportDirData;
+using Veritas::ReportModel;
+using Veritas::ReportProxyModel;
+using Veritas::ReportWidget;
+using Veritas::ReportWidgetTest;
+
+void ReportWidgetTest::init()
+{
+ m_reportWidget = new ReportWidget(0);
+ m_reportWidget->init();
+}
+
+void ReportWidgetTest::cleanup()
+{
+ delete m_reportWidget;
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithRawDataFloorRoundedCoverage()
+{
+
+ ReportDirData data;
+ data.setSloc(10000);
+ data.setNrofCoveredLines(4223);
+ m_reportWidget->setCoverageStatistics(data);
+
+ assertStatistics(m_reportWidget, 10000, 4223, 42.2);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithRawDataCeilRoundedCoverage()
+{
+ ReportDirData data;
+ data.setSloc(100000);
+ data.setNrofCoveredLines(42160);
+ m_reportWidget->setCoverageStatistics(data);
+
+ assertStatistics(m_reportWidget, 100000, 42160, 42.2);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithNewSelection()
+{
+ setModelFor(m_reportWidget);
+
+ QItemSelection selection;
+ QModelIndex topLeft = table(m_reportWidget)->model()->index(0, 0);
+ QModelIndex bottomRight = table(m_reportWidget)->model()->index(3, 1);
+ selection.select(topLeft, bottomRight);
+
+ m_reportWidget->setCoverageStatistics(selection, QItemSelection());
+
+ assertStatistics(m_reportWidget, 8, 4, 50.0);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithAddedSelection()
+{
+ setModelFor(m_reportWidget);
+
+ setStatistics(m_reportWidget, 12, 12);
+
+ QItemSelection selection;
+ QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
+ QModelIndex second = table(m_reportWidget)->model()->index(1, 0);
+ selection.select(first, second);
+
+ m_reportWidget->setCoverageStatistics(selection, QItemSelection());
+
+ assertStatistics(m_reportWidget, 16, 15, 93.8);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithRemovedSelection()
+{
+ setModelFor(m_reportWidget);
+
+ setStatistics(m_reportWidget, 8, 6);
+
+ QItemSelection deselection;
+ QModelIndex second = table(m_reportWidget)->model()->index(1, 0);
+ QModelIndex third = table(m_reportWidget)->model()->index(2, 0);
+ deselection.select(second, third);
+
+ m_reportWidget->setCoverageStatistics(QItemSelection(), deselection);
+
+ assertStatistics(m_reportWidget, 4, 4, 100.0);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithChangedSelection()
+{
+ setModelFor(m_reportWidget);
+
+ setStatistics(m_reportWidget, 16, 15);
+
+ QItemSelection selection;
+ QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
+ selection.select(first, first);
+
+ QItemSelection deselection;
+ QModelIndex fourth = table(m_reportWidget)->model()->index(3, 0);
+ deselection.select(fourth, fourth);
+
+ m_reportWidget->setCoverageStatistics(selection, deselection);
+
+ assertStatistics(m_reportWidget, 18, 17, 94.4);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithEmptySelection()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->setCoverageStatistics(QItemSelection(), QItemSelection());
+
+ assertEmptyStatistics(m_reportWidget);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithInvalidSelection()
+{
+ setModelFor(m_reportWidget);
+
+ QItemSelection selection;
+ QModelIndex index;
+ selection.select(index, index);
+
+ m_reportWidget->setCoverageStatistics(selection, QItemSelection());
+
+ assertEmptyStatistics(m_reportWidget);
+}
+
+//Shouldn't happen, but just in case... it should ignore file items and only
+//take into account directory items
+void ReportWidgetTest::setCoverageStatisticsWithDirectoriesAndFileSelection()
+{
+ setModelFor(m_reportWidget);
+
+ QItemSelection selection;
+ QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
+ selection.select(first, first);
+
+ QModelIndex third = table(m_reportWidget)->model()->index(2, 1);
+ QModelIndex thirdFile1 = table(m_reportWidget)->model()->index(0, 0, third);
+ selection.select(thirdFile1, thirdFile1);
+
+ QModelIndex fourth = table(m_reportWidget)->model()->index(3, 0);
+ selection.select(fourth, fourth);
+
+ m_reportWidget->setCoverageStatistics(selection, QItemSelection());
+
+ assertStatistics(m_reportWidget, 4, 2, 50.0);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithIndex()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->setCoverageStatistics(table(m_reportWidget)->model()->index(0, 0));
+
+ assertStatistics(m_reportWidget, 3, 2, 66.7);
+}
+
+void ReportWidgetTest::setCoverageStatisticsWithInvalidIndex()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->setCoverageStatistics(QModelIndex());
+
+ assertEmptyStatistics(m_reportWidget);
+}
+
+//Shouldn't modify the statistics
+void ReportWidgetTest::setCoverageStatisticsWithFileIndex()
+{
+ setModelFor(m_reportWidget);
+
+ QModelIndex dirIndex = table(m_reportWidget)->model()->index(0, 0);
+ m_reportWidget->setCoverageStatistics(table(m_reportWidget)->model()->index(0, 0, dirIndex));
+
+ assertEmptyStatistics(m_reportWidget);
+}
+
+//Selects first directory
+void ReportWidgetTest::statisticsSelectingSingleDirectory()
+{
+ setModelFor(m_reportWidget);
+
+ //TODO I can't get it to work without showing the widget and waiting some
+ //time before triggering the click. Is there a way for this to work without
+ //showing the widget and waiting?
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
+
+ assertStatistics(m_reportWidget, 3, 2, 66.7);
+}
+
+//Selects all directories
+void ReportWidgetTest::statisticsSelectingSeveralDirectories()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
+
+ assertStatistics(m_reportWidget, 8, 4, 50.0);
+}
+
+//Selects second and fourth directories
+void ReportWidgetTest::statisticsSelectingSeveralDirectoriesNotContiguous()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ControlModifier);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ControlModifier);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::ControlModifier);
+
+ assertStatistics(m_reportWidget, 2, 1, 50.0);
+}
+
+//Selects second and fourth directories
+void ReportWidgetTest::statisticsSelectingSeveralDirectoriesNotContiguousUsingMouse()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+
+ QModelIndex dirIndex = table(m_reportWidget)->model()->index(1, 0);
+ QPoint point = table(m_reportWidget)->visualRect(dirIndex).center();
+ //The widget used must be the viewport, as simulating the mouse press on
+ //the table doesn't even deliver a mousePressEvent to it (I don't know
+ //why)
+ QTest::mousePress(table(m_reportWidget)->viewport(), Qt::LeftButton,
+ Qt::NoModifier, point, 500);
+
+ dirIndex = table(m_reportWidget)->model()->index(3, 1);
+ point = table(m_reportWidget)->visualRect(dirIndex).center();
+ QTest::mouseClick(table(m_reportWidget)->viewport(), Qt::LeftButton,
+ Qt::ControlModifier, point);
+
+ assertStatistics(m_reportWidget, 2, 1, 50.0);
+}
+
+//Selects first directory, and clicks on an empty space
+void ReportWidgetTest::statisticsAfterClearingSelection()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
+
+ QModelIndex dirIndex = table(m_reportWidget)->model()->index(3, 0);
+ QPoint point = table(m_reportWidget)->visualRect(dirIndex).bottomLeft();
+ point.setX(point.x() + 10);
+ point.setY(point.y() + 10);
+ QTest::mousePress(table(m_reportWidget)->viewport(), Qt::LeftButton,
+ Qt::NoModifier, point);
+
+ assertStatistics(m_reportWidget, 0, 0, 0.0);
+}
+
+//Selects first and second directory, and slides in second directory
+void ReportWidgetTest::statisticsAfterSlidingRight()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
+
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Right);
+
+ assertStatistics(m_reportWidget, 1, 1, 100.0);
+}
+
+//Selects fourth, third and second directory, slides in second directory,
+//selects first file, slides left, and selects third directory
+
+void ReportWidgetTest::statisticsAfterSlidingLeft()
+{
+ setModelFor(m_reportWidget);
+
+ m_reportWidget->show();
+ table(m_reportWidget)->setFocus();
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Up, Qt::ShiftModifier);
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Up, Qt::ShiftModifier);
+
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Right);
+
+ //Wait to avoid the slide to eat the event
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
+
+ assertStatistics(m_reportWidget, 1, 1, 100.0);
+
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Left);
+
+ assertStatistics(m_reportWidget, 5, 2, 40.0);
+
+ //Wait to avoid the slide to eat the event
+ QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
+
+ assertStatistics(m_reportWidget, 3, 1, 33.3);
+}
+
+////////////////////////////// Asserts ////////////////////////////////////////
+
+void ReportWidgetTest::assertStatistics(ReportWidget* rw, int sloc,
+ int instrumented, double coverage)
+{
+ QCOMPARE(rw->m_ui->sloc->text(), QString::number(sloc));
+ QCOMPARE(rw->m_ui->nrofCoveredLines->text(), QString::number(instrumented));
+ QCOMPARE(rw->m_ui->coverageRatio->text(), QLocale().toString(coverage, 'f', 1) + " %");
+}
+
+void ReportWidgetTest::assertEmptyStatistics(ReportWidget* rw)
+{
+ QCOMPARE(rw->m_ui->sloc->text(), QString("-"));
+ QCOMPARE(rw->m_ui->nrofCoveredLines->text(), QString("-"));
+ QCOMPARE(rw->m_ui->coverageRatio->text(), QString("-"));
+}
+
+////////////////////////////// Helpers ////////////////////////////////////////
+
+DrillDownView* ReportWidgetTest::table(ReportWidget* rw)
+{
+ return rw->table();
+}
+
+void ReportWidgetTest::setStatistics(ReportWidget* rw, int sloc, int instrumented)
+{
+ rw->m_ui->sloc->setText(QString::number(sloc));
+ rw->m_ui->nrofCoveredLines->setText(QString::number(instrumented));
+}
+
+void ReportWidgetTest::setModelFor(ReportWidget* rw)
+{
+ ReportModel* model = createReportModel();
+ ReportProxyModel* proxyModel = new ReportProxyModel(this);
+ proxyModel->setSourceModel(model);
+
+ rw->table()->setModel(proxyModel);
+ rw->m_proxy = proxyModel;
+ rw->m_model = model;
+
+ connect(rw->table()->selectionModel(),
+ SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
+ rw,
+ SLOT(dispatchSelectionSignal(QItemSelection,QItemSelection)));
+}
+
+// dir1: sloc 3, instrumented 2, coverage 66.6 %
+// dir1File1: sloc 3, instrumented 2, coverage 66.6 %
+// dir2: sloc 1, instrumented 1, coverage 100.0 %
+// dir2File1: sloc 1, instrumented 1, coverage 100.0 %
+// dir3: sloc 3, instrumented 1, coverage 33.3 %
+// dir3File1: sloc 3, instrumented 1, coverage 33.3 %
+// dir4: sloc 1, instrumented 0, coverage 0.0 %
+// dir4File1: sloc 1, instrumented 0, coverage 0.0 %
+ReportModel* ReportWidgetTest::createReportModel()
+{
+ ReportModel* model = new ReportModel(this);
+
+ CoveredFile dir1File1;
+ dir1File1.setUrl(KUrl("/dir1/file1"));
+ dir1File1.setCallCount(4, 1);
+ dir1File1.setCallCount(8, 0);
+ dir1File1.setCallCount(15, 1);
+ model->addCoverageData(&dir1File1);
+
+ CoveredFile dir2File1;
+ dir2File1.setUrl(KUrl("/dir2/file1"));
+ dir2File1.setCallCount(16, 1);
+ model->addCoverageData(&dir2File1);
+
+ CoveredFile dir3File1;
+ dir3File1.setUrl(KUrl("/dir2/dir3/file1"));
+ dir3File1.setCallCount(23, 0);
+ dir3File1.setCallCount(42, 0);
+ dir3File1.setCallCount(108, 1);
+ model->addCoverageData(&dir3File1);
+
+ CoveredFile dir4File1;
+ dir4File1.setUrl(KUrl("/dir2/dir4/file1"));
+ dir4File1.setCallCount(815, 0);
+ model->addCoverageData(&dir4File1);
+
+ return model;
+}
+
+QTEST_KDEMAIN( ReportWidgetTest, GUI )
+#include "reportwidgettest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/documentstub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/documentstub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/documentstub.h (revision 1522570)
@@ -0,0 +1,198 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTFAKES_DOCUMENTSTUB_H
+#define TESTFAKES_DOCUMENTSTUB_H
+
+#include "interfaces/idocument.h"
+
+namespace KDevelop
+{
+class ICore;
+}
+
+namespace TestStubs
+{
+
+class KDevDocument : public KDevelop::IDocument
+{
+public:
+ KDevDocument(KDevelop::ICore* c) : IDocument(c) {
+ m_isTextDocument = true;
+ m_isActive = true;
+ m_save = true;
+ m_partForView = 0;
+ m_state = IDocument::Clean;
+ m_textDocument = 0;
+ }
+ virtual ~KDevDocument() {}
+
+ virtual KUrl url() const {
+ return m_url;
+ }
+ virtual KMimeType::Ptr mimeType() const {
+ return KSharedPtr<KMimeType>();
+ }
+ virtual KParts::Part* partForView(QWidget *view) const {
+ return m_partForView;
+ }
+ virtual bool isTextDocument() const {
+ return m_isTextDocument;
+ }
+ virtual KTextEditor::Document* textDocument() const {
+ return m_textDocument;
+ }
+ virtual bool save(DocumentSaveMode mode = Default) {
+ return m_save;
+ }
+ virtual void reload() {}
+ virtual bool close(DocumentSaveMode mode = Default) {
+ return true;
+ }
+ virtual bool isActive() const {
+ return m_isActive;
+ }
+ virtual DocumentState state() const {
+ return m_state;
+ }
+ virtual KTextEditor::Cursor cursorPosition() const {
+ return KTextEditor::Cursor();
+ }
+ virtual void setCursorPosition(const KTextEditor::Cursor &cursor) {
+ }
+ virtual KTextEditor::Range textSelection() const {
+ return KTextEditor::Range();
+ }
+ virtual void setTextSelection(const KTextEditor::Range &/*range*/) {
+ }
+ virtual void activate(Sublime::View *activeView, KParts::MainWindow *mainWindow) {
+ }
+
+ // inject whatever it is you need
+ KUrl m_url;
+ bool m_isTextDocument;
+ bool m_isActive;
+ bool m_save;
+ KParts::Part* m_partForView;
+ DocumentState m_state;
+ KTextEditor::Document* m_textDocument;
+ KTextEditor::Cursor m_cursorPosition;
+ KTextEditor::Range m_textSelection;
+};
+
+}
+
+#include <ktexteditor/document.h>
+
+namespace TestStubs
+{
+
+class TextDocument : public KTextEditor::Document
+{
+// Q_OBJECT
+
+public:
+ TextDocument(QObject *parent = 0) :
+ KTextEditor::Document(parent),
+ m_createView(0) {}
+ virtual ~TextDocument() {}
+
+ QList<KTextEditor::View*> m_views;
+ KTextEditor::Editor* m_editor;
+ KTextEditor::View* m_createView;
+ KTextEditor::View* m_activeView;
+ QString m_encoding;
+ QString m_documentName;
+
+public:
+ virtual KTextEditor::Editor *editor() { return m_editor; }
+ virtual KTextEditor::View *createView(QWidget *parent) {
+ emit viewCreated(this, m_createView);
+ //m_views.clear();
+ m_views << m_createView;
+ return m_createView;
+ }
+
+ virtual KTextEditor::View* activeView() const { return m_activeView; }
+ virtual const QList<KTextEditor::View*> &views() const { return m_views; }
+ virtual const QString &documentName() const { return m_documentName; }
+ virtual QString mimeType() { return ""; }
+ virtual bool setEncoding(const QString &encoding) { return true; }
+ virtual const QString &encoding() const { return m_encoding; }
+ virtual bool documentReload() { return true; }
+ virtual bool documentSave() { return true; }
+ virtual bool documentSaveAs() { return true; }
+ virtual bool startEditing() { return true; }
+ virtual bool endEditing() { return true; }
+ virtual QString text() const { return ""; }
+ virtual QString text(const KTextEditor::Range& /*range*/, bool block = false) const { return ""; }
+ virtual QChar character(const KTextEditor::Cursor& position) const { return ' '; }
+ virtual QStringList textLines(const KTextEditor::Range& /*range*/, bool block = false) const { return QStringList(); }
+ virtual QString line(int /*line*/) const { return QString(); }
+ virtual int /*line*/s() const { return 0; }
+ virtual KTextEditor::Cursor documentEnd() const { return KTextEditor::Cursor(); }
+ virtual int totalCharacters() const { return 0; }
+ virtual bool isEmpty() const { return true; }
+ virtual int /*line*/Length(int /*line*/) const { return 0; }
+ virtual bool setText(const QString &/*text*/) { return true; }
+ virtual bool setText(const QStringList &text) { return true; }
+ virtual bool clear() { return true; }
+ virtual bool insertText(const KTextEditor::Cursor &/*position*/, const QString &/*text*/, bool block = false) { return true; }
+ virtual bool insertText(const KTextEditor::Cursor &/*position*/, const QStringList &text, bool block = false) { return true; }
+ virtual bool replaceText(const KTextEditor::Range &/*range*/, const QString &/*text*/, bool block = false) { return true; }
+ virtual bool replaceText(const KTextEditor::Range &/*range*/, const QStringList &/*text*/, bool block = false) { return true; }
+ virtual bool removeText(const KTextEditor::Range &/*range*/, bool block = false) { return true; }
+ virtual bool insertLine(int /*line*/, const QString &/*text*/) { return true; }
+ virtual bool insertLines(int /*line*/, const QStringList &/*text*/) { return true; }
+ virtual bool removeLine(int /*line*/) { return true; }
+ virtual QString mode() const { return ""; }
+ virtual QString highlightingMode() const { return ""; }
+ virtual QStringList modes() const { return QStringList(); }
+ virtual QStringList highlightingModes() const { return QStringList(); }
+ virtual bool setMode(const QString &/*name*/) { return true; }
+ virtual bool setHighlightingMode(const QString &/*name*/) { return true; }
+ virtual QString highlightingModeSection(int /*index*/) const { return ""; }
+ virtual QString modeSection(int /*index*/) const { return ""; }
+
+ virtual bool openFile() { return true; }
+ virtual bool saveFile() { return true; }
+ virtual int lines() const { return 0; }
+ virtual int lineLength(int) const { return 0; }
+
+
+#if 0
+Q_SIGNALS:
+ void viewCreated(KTextEditor::Document *document, KTextEditor::View *view);
+ void documentNameChanged(KTextEditor::Document *document);
+ void documentUrlChanged(KTextEditor::Document *document);
+ void modifiedChanged(KTextEditor::Document *document);
+ void textChanged(KTextEditor::Document *document);
+ void textInserted(KTextEditor::Document *document, const KTextEditor::Range& /*range*/);
+ void textRemoved(KTextEditor::Document *document, const KTextEditor::Range& /*range*/);
+ void textChanged(KTextEditor::Document *document, const KTextEditor::Range& oldRange,
+ const KTextEditor::Range& newRange);
+ void aboutToClose(KTextEditor::Document *document);
+ void aboutToReload(KTextEditor::Document *document);
+#endif
+};
+
+}
+
+
+#endif // TESTFAKES_DOCUMENTSTUB_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/documentstub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h (revision 1522570)
@@ -0,0 +1,42 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_DISCRETECOLORRANGETEST_H
+#define VERITAS_COVERAGE_DISCRETECOLORRANGETEST_H
+
+#include <QtCore/QObject>
+
+namespace Veritas {
+
+class DiscreteColorRangeTest: public QObject
+{
+Q_OBJECT
+private slots:
+
+ void testConstructor();
+ void testSetStopPoints();
+ void testColorAtWithNoMiddleStopPoints();
+ void testColorAtWithSeveralStopPoints();
+ void testColorAtWithStopPointAtBegin();
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp (revision 1522570)
@@ -0,0 +1,101 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "coveredfiletest.h"
+#include "../coveredfile.h"
+
+#include "testutils.h"
+
+using Veritas::CoveredFile;
+using Veritas::CoveredFileTest;
+
+void CoveredFileTest::init()
+{
+ m_file = new CoveredFile;
+}
+
+void CoveredFileTest::cleanup()
+{
+ if (m_file) delete m_file;
+}
+
+void CoveredFileTest::construct()
+{
+ KOMPARE(KUrl(), m_file->url());
+ KOMPARE(0, m_file->coverageRatio());
+ KOMPARE(0, m_file->sloc());
+ KOMPARE(0, m_file->nrofCoveredLines());
+ KOMPARE(0, m_file->callCountMap().count());
+}
+
+void CoveredFileTest::sunny()
+{
+ m_file->setCallCount(1,0);
+ m_file->setCallCount(2,0);
+ m_file->setCallCount(3,1);
+ m_file->setCallCount(4,1);
+ KOMPARE(50.0, m_file->coverageRatio());
+}
+
+void CoveredFileTest::zeroSloc()
+{
+ KOMPARE(0, m_file->coverageRatio());
+}
+
+void CoveredFileTest::callCount()
+{
+ m_file->setCallCount(10, 5);
+ m_file->setCallCount(11, 4);
+
+ QMap<int, int> callMap = m_file->callCountMap();
+ KOMPARE(2, callMap.count());
+ KVERIFY(callMap.contains(10));
+ KOMPARE(5, callMap[10]);
+ KVERIFY(callMap.contains(11));
+ KOMPARE(4, callMap[11]);
+}
+
+void CoveredFileTest::linesSet()
+{
+ m_file->setCallCount(9, 0);
+ m_file->setCallCount(10, 5);
+ m_file->setCallCount(11, 0);
+ m_file->setCallCount(12, 3);
+
+
+ QSet<int> lines;
+ lines << 10 << 12;
+ KOMPARE(lines, m_file->coveredLines());
+}
+
+void CoveredFileTest::isReachable()
+{
+ m_file->setCallCount(2,1);
+ KVERIFY(m_file->isReachable(2));
+ KVERIFY(!m_file->isReachable(1));
+
+ m_file->setCallCount(1,0);
+ KVERIFY(m_file->isReachable(1));
+ KVERIFY(m_file->isReachable(2));
+ KVERIFY(!m_file->isReachable(3));
+}
+
+QTEST_KDEMAIN( CoveredFileTest, NoGUI)
+#include "coveredfiletest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp (revision 1522570)
@@ -0,0 +1,123 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "reportfileitemtest.h"
+#include "coveredfilefactory.h"
+#include "../reportmodel.h"
+#include "../coveredfile.h"
+
+#include "testutils.h"
+
+using Veritas::ReportFileItemTest;
+using Veritas::ReportFileItem;
+using Veritas::CoveredFile;
+using Veritas::Test::CoveredFileFactory;
+
+void ReportFileItemTest::init()
+{
+ m_url = KUrl("/path/to/foo.cpp");
+ m_fileName = m_url.fileName();
+ m_file = new ReportFileItem(m_url);
+}
+
+void ReportFileItemTest::cleanup()
+{
+ if (m_file) {
+ delete m_file->coverageRatioItem();
+ delete m_file->nrofCoveredLinesItem();
+ delete m_file->slocItem();
+ delete m_file;
+ }
+ qDeleteAll(m_garbage);
+ m_garbage.clear();
+}
+
+void ReportFileItemTest::construct()
+{
+ KVERIFY(ReportModel::File == m_file->type());
+ KOMPARE(m_url, m_file->url());
+
+ // QStandardItem properties
+ KVERIFY(! m_file->isEditable());
+ KVERIFY(m_file->isSelectable());
+ KVERIFY(! m_file->isCheckable());
+
+ // Neighbour items should be initialized on 0
+ KOMPARE(0, m_file->slocItem());
+ KOMPARE(0, m_file->coverageRatioItem());
+ KOMPARE(0, m_file->nrofCoveredLinesItem());
+}
+
+void ReportFileItemTest::addCoverage()
+{
+ int sloc = 2, nrofCovered = 1;
+ CoveredFile* f = CoveredFileFactory::create(m_url, sloc, nrofCovered);
+ m_file->addCoverageData(f);
+
+ assertSlocItem(2);
+ assertInstrumentedItem(1);
+ assertCoverageItem(100*(double)1/2);
+
+ m_garbage << f;
+}
+
+void ReportFileItemTest::assertInstrumentedItem(int instrumented)
+{
+ ReportValueItem* instrumentedItem = m_file->nrofCoveredLinesItem();
+ KOMPARE(instrumented, instrumentedItem->value());
+}
+
+void ReportFileItemTest::assertSlocItem(int sloc)
+{
+ ReportValueItem* slocItem = m_file->slocItem();
+ KOMPARE(sloc, slocItem->value());
+}
+
+void ReportFileItemTest::assertCoverageItem(double coverage)
+{
+ ReportValueItem* coverageItem = m_file->coverageRatioItem();
+ double actual = coverageItem->value();
+ KVERIFY_MSG(qAbs(coverage - actual) < 0.1,
+ QString("\nWrong coverage percentage for coverage item.\n"
+ "expected %1 but got %2").arg(coverage).arg(actual));
+}
+
+void ReportFileItemTest::addMultipleCoverage()
+{
+ QList<int> covered; covered << 1 << 2 << 3;
+ QList<int> notCovered; notCovered << 4;
+ CoveredFile* f = CoveredFileFactory::create(m_url, covered, notCovered);
+ m_file->addCoverageData(f);
+
+ covered.clear(); covered << 3 << 4;
+ notCovered.clear(); notCovered << 1 << 2;
+ CoveredFile* f2 = CoveredFileFactory::create(m_url, covered, notCovered);
+ m_file->addCoverageData(f2);
+
+ assertInstrumentedItem(4);
+ assertSlocItem(4);
+ assertCoverageItem(100.0);
+
+ m_garbage << f << f2;
+}
+
+
+QTEST_KDEMAIN( ReportFileItemTest, NoGUI)
+#include "reportfileitemtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp (revision 1522570)
@@ -0,0 +1,191 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "reportmodeltest.h"
+#include "../reportmodel.h"
+#include "../coveredfile.h"
+#include "coveredfilefactory.h"
+
+#include "testutils.h"
+
+using Veritas::CoveredFile;
+using Veritas::ReportModelTest;
+using Veritas::ReportModel;
+using Veritas::ReportFileItem;
+using Veritas::ReportDirItem;
+using Veritas::ReportValueItem;
+using Veritas::Test::CoveredFileFactory;
+
+////////////////////////// fixture ///////////////////////////////////////////
+
+void ReportModelTest::init()
+{
+ m_model = new ReportModel;
+ KUrl m_fileUrl = KUrl("/path/to/foo.cpp");
+ QString m_fileDir = "/path/to/";
+ QString m_fileName = "foo.cpp";
+}
+
+void ReportModelTest::cleanup()
+{
+ if (m_model) delete m_model;
+ qDeleteAll(m_garbage);
+ m_garbage.clear();
+}
+
+////////////////////////// commands ///////////////////////////////////////////
+
+void ReportModelTest::sortRole()
+{
+ ReportDirItem* dir = new ReportDirItem(m_fileDir);
+ ReportFileItem* file = new ReportFileItem(m_fileUrl);
+ ReportValueItem* val = new ReportValueItem(10);
+ m_model->appendRow(dir);
+ m_model->appendRow(file);
+ m_model->appendRow(val);
+
+ KOMPARE(m_fileDir, fetchSortData(0));
+ KOMPARE(m_fileName, fetchSortData(1));
+ KOMPARE(10.0, fetchSortData(2));
+}
+
+void ReportModelTest::addSingleCoverageData()
+{
+ CoveredFile* f = CoveredFileFactory::create(m_fileUrl, 10, 5);
+ m_model->addCoverageData(f);
+
+ QModelIndex dirIndex = m_model->index(0,0);
+ int expSloc = 10;
+ int expInstrumented = 5;
+ assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
+
+ QModelIndex fileIndex = m_model->index(0,0, dirIndex);
+ double expCoverage = 50.0;
+ assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
+
+ KVERIFY(!m_model->index(1,0).isValid());
+ KVERIFY(!m_model->index(1,0, dirIndex).isValid());
+
+ m_garbage << f;
+}
+
+void ReportModelTest::multiCoverageOneFile()
+{
+ // The parser can emit multiple CoveredFile instances
+ // for a single URL [covered by multiple 'tests']
+ // The model aggregates this data.
+ QList<int> covered; covered << 1 << 2;
+ QList<int> notCovered; notCovered << 3 << 4;
+ CoveredFile* f1 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
+
+ covered.clear(); covered << 4;
+ notCovered.clear(); notCovered << 1 << 2 << 3;
+ CoveredFile* f2 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
+
+ m_model->addCoverageData(f1);
+ m_model->addCoverageData(f2);
+
+ QModelIndex dirIndex = m_model->index(0,0);
+ int expSloc = 4;
+ int expInstrumented = 2 + 1;
+ assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
+
+ QModelIndex fileIndex = m_model->index(0,0,dirIndex);
+ double expCoverage = 100*((double)expInstrumented/expSloc);
+ assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
+
+ KVERIFY(!m_model->index(1,0).isValid());
+ KVERIFY(!m_model->index(1,0, dirIndex).isValid());
+
+ m_garbage << f1 << f2;
+}
+
+void ReportModelTest::differentSlocSetOneFile()
+{
+ // It can happen that a file has different sets of reachable
+ // lines of code associated with it over multiple coverage
+ // data parses. For example on inline'd functions of header
+ // files. For such a case the SLOC should be adjust accordingly.
+ QList<int> covered; covered << 1;
+ QList<int> notCovered; notCovered << 2;
+ CoveredFile* f1 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
+
+ covered.clear(); covered << 2;
+ notCovered.clear(); notCovered << 3;
+ CoveredFile* f2 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
+
+ m_model->addCoverageData(f1);
+ m_model->addCoverageData(f2);
+
+ QModelIndex dirIndex = m_model->index(0,0);
+ int expSloc = 3; // lines 1,2,3
+ int expInstrumented = 2; // lines 1 and 2
+ assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
+
+ QModelIndex fileIndex = m_model->index(0,0,dirIndex);
+ double expCoverage = 100*((double)expInstrumented/expSloc);
+ assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
+
+ m_garbage << f1 << f2;
+}
+
+///////////////////////// helpers ////////////////////////////////////////////
+
+QVariant ReportModelTest::fetchSortData(int row)
+{
+ return m_model->index(row, 0).data(ReportModel::SortRole);
+}
+
+//////////////////////// custom assertions ///////////////////////////////////
+
+void ReportModelTest::assertDirAtEquals(const QModelIndex& i, QString path, int sloc, int instrumented)
+{
+ KVERIFY(i.isValid());
+ QStandardItem* sdir = m_model->itemFromIndex(i);
+ KVERIFY(ReportModel::Dir == sdir->type());
+ ReportDirItem* dir = dynamic_cast<ReportDirItem*>(sdir);
+ KVERIFY(dir);
+ QString actualPath = dir->data(Qt::DisplayRole).toString();
+ KOMPARE_MSG(path, actualPath,
+ QString("Wrong display data for diritem: expected: %1 but got %2.").
+ arg(path).arg(actualPath));
+ KOMPARE(sloc, dir->sloc());
+ KOMPARE(instrumented, dir->nrofCoveredLines());
+
+}
+
+void ReportModelTest::assertFileAtEquals(const QModelIndex& i, QString name, int sloc, int instrumented, double cov)
+{
+ KVERIFY(i.isValid());
+ QStandardItem* sfile = m_model->itemFromIndex(i);
+ KVERIFY(ReportModel::File == sfile->type());
+ ReportFileItem* file = dynamic_cast<ReportFileItem*>(sfile);
+ KVERIFY(file);
+ KOMPARE(QVariant(name), file->data(Qt::DisplayRole));
+ ReportValueItem* slocItem = file->slocItem();
+ KOMPARE((double)sloc, slocItem->value());
+ ReportValueItem* instrumentedItem = file->nrofCoveredLinesItem();
+ KOMPARE((double)instrumented, instrumentedItem->value());
+ ReportValueItem* coverageItem = file->coverageRatioItem();
+ KVERIFY(qAbs(cov - coverageItem->value()) < 0.1);
+}
+
+QTEST_KDEMAIN( ReportModelTest, NoGUI)
+#include "reportmodeltest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp (revision 1522570)
@@ -0,0 +1,21 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "pluginstub.h"
+#include "pluginstub.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp (revision 1522570)
@@ -0,0 +1,232 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "lcovprefswidget.h"
+#include "lcovsettingsbase.h"
+#include "colorrangebar.h"
+#include "stoppointwidget.h"
+
+using Veritas::ColorRange;
+using Veritas::StopPoint;
+using Veritas::StopPoints;
+
+LCovPrefsWidget::LCovPrefsWidget(LCovSettingsBase* settings, QWidget* parent):
+ QWidget(parent)
+{
+ mUi.setupUi(this);
+ mSettings = settings;
+
+ reloadColorRange();
+
+ QHBoxLayout* layout = new QHBoxLayout(mUi.colorRangeBarFrame);
+ ColorRangeBar* colorRangeBar = new ColorRangeBar(mSettings->colorRange(),
+ this);
+ layout->addWidget(colorRangeBar);
+ layout->setContentsMargins(0, 0, 0, 0);
+
+ connect(this, SIGNAL(changed(bool)), colorRangeBar, SLOT(update()));
+
+ connect(mUi.modeComboBox, SIGNAL(currentIndexChanged(QString)),
+ this, SLOT(changeMode(QString)));
+}
+
+LCovPrefsWidget::~LCovPrefsWidget()
+{
+}
+
+void LCovPrefsWidget::changeMode(const QString& mode)
+{
+ if (mode ==
+ i18nc("@item:inlistbox Discrete color range type", "Discrete")) {
+ mSettings->colorRange()->setMode(ColorRange::Discrete);
+ } else {
+ mSettings->colorRange()->setMode(ColorRange::Gradient);
+ }
+
+ reloadStopPoints();
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::changeColor(int index, const QColor& color)
+{
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ stopPoints[index].second = color;
+ mSettings->colorRange()->setStopPoints(stopPoints);
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::changePosition(int index, double position)
+{
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ stopPoints[index].first = position;
+ mSettings->colorRange()->setStopPoints(stopPoints);
+
+ if (index > 0) {
+ updateRange(index - 1);
+ }
+ updateRange(index + 1);
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::addStopPointAfter(int index)
+{
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ StopPoint newStopPoint;
+ if (index == -1) {
+ newStopPoint.first = 0.0001;
+ newStopPoint.second = stopPoints[0].second;
+ } else {
+ newStopPoint = stopPoints[index];
+ newStopPoint.first += 0.0001;
+ }
+ stopPoints.insert(index + 1, newStopPoint);
+
+ //Ensure that next values don't overlap
+ for (int i=index+2; i<stopPoints.size(); ++i) {
+ double minimum = stopPoints[i-1].first + 0.0001;
+ if (stopPoints[i].first < minimum) {
+ stopPoints[i].first = minimum;
+ }
+ }
+
+ mSettings->colorRange()->setStopPoints(stopPoints);
+
+ reloadStopPoints();
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::removeStopPoint(int index)
+{
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ stopPoints.remove(index);
+ mSettings->colorRange()->setStopPoints(stopPoints);
+
+ reloadStopPoints();
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::reloadColorRange()
+{
+ if (mSettings->colorRange()->mode() == ColorRange::Discrete) {
+ mUi.modeComboBox->setCurrentIndex(mUi.modeComboBox->findText(
+ i18nc("@item:inlistbox Discrete color range type", "Discrete")));
+ } else {
+ mUi.modeComboBox->setCurrentIndex(mUi.modeComboBox->findText(
+ i18nc("@item:inlistbox Gradient color range type", "Gradient")));
+ }
+
+ reloadStopPoints();
+
+ checkIfChanged();
+}
+
+void LCovPrefsWidget::reloadStopPoints()
+{
+ QLayout* layout = mUi.stopPointsScrollArea->widget()->layout();
+ QLayoutItem *child;
+ while ((child = layout->takeAt(0)) != 0) {
+ if (child->widget()) {
+ child->widget()->deleteLater();
+ }
+ delete child;
+ }
+
+ QVBoxLayout* boxLayout = qobject_cast<QVBoxLayout*>(layout);
+
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ if (stopPoints.size() == 1) {
+ boxLayout->addWidget(newDummyStopPointWidget());
+ }
+ for (int i=0; i<stopPoints.size(); ++i) {
+ ColorRange::Mode mode = mSettings->colorRange()->mode();
+ boxLayout->addWidget(newStopPointWidgetFor(stopPoints, i, mode));
+ }
+
+ boxLayout->addStretch();
+}
+
+StopPointWidget* LCovPrefsWidget::newStopPointWidgetFor(
+ const StopPoints& stopPoints, int index, ColorRange::Mode mode)
+{
+ StopPointWidget* stopPointWidget = new StopPointWidget(this);
+
+ stopPointWidget->setStopPoint(stopPoints[index], mode);
+ stopPointWidget->setStopPointIndex(index);
+
+ double minimum = index>0 ? stopPoints[index-1].first : 0;
+ double maximum = index<stopPoints.size()-1 ? stopPoints[index+1].first : 1;
+ stopPointWidget->setRange(minimum, maximum);
+
+ connect(stopPointWidget, SIGNAL(colorChanged(int,QColor)),
+ this, SLOT(changeColor(int,QColor)));
+ connect(stopPointWidget, SIGNAL(positionChanged(int,double)),
+ this, SLOT(changePosition(int,double)));
+ connect(stopPointWidget, SIGNAL(stopPointToAddAfter(int)),
+ this, SLOT(addStopPointAfter(int)));
+ connect(stopPointWidget, SIGNAL(stopPointToRemove(int)),
+ this, SLOT(removeStopPoint(int)));
+
+ return stopPointWidget;
+}
+
+StopPointWidget* LCovPrefsWidget::newDummyStopPointWidget()
+{
+ StopPointWidget* stopPointWidget = new StopPointWidget(this);
+ stopPointWidget->setDummy(true);
+ stopPointWidget->setStopPointIndex(-1);
+
+ connect(stopPointWidget, SIGNAL(stopPointToAddAfter(int)),
+ this, SLOT(addStopPointAfter(int)));
+
+ return stopPointWidget;
+}
+
+StopPointWidget* LCovPrefsWidget::getStopPointWidget(int index)
+{
+ QLayout* layout = mUi.stopPointsScrollArea->widget()->layout();
+ QLayoutItem* item = layout->itemAt(index);
+ return qobject_cast<StopPointWidget*>(item->widget());
+}
+
+void LCovPrefsWidget::updateRange(int index)
+{
+ StopPointWidget* stopPointWidget = getStopPointWidget(index);
+
+ StopPoints stopPoints = mSettings->colorRange()->stopPoints();
+ double minimum = index>0 ? stopPoints[index-1].first : 0;
+ double maximum = index<stopPoints.size()-1 ? stopPoints[index+1].first : 1;
+ stopPointWidget->setRange(minimum, maximum);
+}
+
+void LCovPrefsWidget::checkIfChanged()
+{
+ if (mSettings->isSavedColorRange()) {
+ emit changed(false);
+ } else {
+ emit changed(true);
+ }
+}
+
+#include "lcovprefswidget.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.h (revision 1522570)
@@ -0,0 +1,171 @@
+/* KDevelop coverage plugin
+ * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REPORTMODEL_H
+#define VERITAS_COVERAGE_REPORTMODEL_H
+
+#include <QtCore/QList>
+#include <QtGui/QStandardItem>
+#include <QtGui/QStandardItemModel>
+#include <QSet>
+#include <QHash>
+#include <KUrl>
+
+#include "coverageexport.h"
+#include "colorrange.h"
+
+namespace Veritas
+{
+
+class CoveredFile;
+class ReportDirData;
+class ReportDirItem;
+class ReportFileItem;
+class ReportValueItem;
+
+/*! Main model for the coverage report */
+class VERITAS_COVERAGE_EXPORT ReportModel : public QStandardItemModel
+{
+Q_OBJECT
+public:
+ explicit ReportModel(QObject* parent=0);
+ virtual ~ReportModel();
+ void setRootDirectory(const KUrl& root);
+
+ QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const;
+ enum
+ {
+ File = QStandardItem::UserType + 1,
+ Dir = QStandardItem::UserType + 2,
+ Value = QStandardItem::UserType + 3
+ };
+ enum { SortRole = Qt::UserRole + 1 };
+
+public Q_SLOTS:
+ void addCoverageData(CoveredFile*);
+
+private:
+ QList<QStandardItem*> createFileRow(CoveredFile*);
+ void appendDir(const QString& dir);
+ void updateColoredCoverageColumn(ReportDirItem* dir);
+
+ /**
+ * Returns the brush with the color for the given coverage percent.
+ *
+ * @param percent The coverage percent.
+ * @return The brush.
+ */
+ QBrush brushForCoverage(double percent);
+
+private:
+ KUrl m_root;
+ QHash<KUrl, ReportFileItem*> m_files;
+ QMap<QString, ReportDirItem*> m_dirs;
+
+ /**
+ * The color range used to associate colors with coverage percent values.
+ */
+ ColorRange m_colorRange;
+};
+
+// TODO merge this with the CoveredFile class, it is totally redundant to have both waste resources
+class VERITAS_COVERAGE_EXPORT ReportFileItem : public QStandardItem
+{
+public:
+ explicit ReportFileItem(const KUrl& url);
+ virtual ~ReportFileItem();
+ virtual int type() const;
+ KUrl url();
+
+ void addCoverageData(CoveredFile* f);
+
+ ReportValueItem* coverageRatioItem() const;
+ ReportValueItem* slocItem() const;
+ ReportValueItem* nrofCoveredLinesItem() const;
+
+private:
+ KUrl m_fullUrl;
+ ReportValueItem* m_coverageRatioItem;
+ ReportValueItem* m_slocItem;
+ ReportValueItem* m_nrofCoveredLinesItem;
+ QSet<int> m_coveredLines;
+ QSet<int> m_reachableLines;
+};
+
+/*!
+ * Stores the data for the report of a directory.
+ * The data stored are the SLOC and the number of covered lines.
+ * Coverage percentage is calculated based on those values.
+ */
+class VERITAS_COVERAGE_EXPORT ReportDirData
+{
+public:
+
+ /*!
+ * Creates a new ReportDirData.
+ * All the values are initialized to 0.
+ */
+ ReportDirData();
+
+ int sloc() const;
+ int nrofCoveredLines() const;
+ double coverageRatio() const;
+ void setSloc(int sloc);
+ void setNrofCoveredLines(int nrof);
+
+private:
+ int m_sloc;
+ int m_nrofCoveredLines;
+};
+
+class VERITAS_COVERAGE_EXPORT ReportDirItem : public QStandardItem
+{
+public:
+ explicit ReportDirItem(const QString& dir);
+ virtual ~ReportDirItem();
+ virtual int type() const;
+ void updateStats();
+ int sloc();
+ int nrofCoveredLines();
+ double coverageRatio();
+ const ReportDirData& reportDirData() const;
+
+private:
+ ReportDirData m_reportDirData;
+ };
+
+class VERITAS_COVERAGE_EXPORT ReportValueItem: public QStandardItem
+{
+public:
+ explicit ReportValueItem(double value);
+ explicit ReportValueItem(int value);
+ virtual ~ReportValueItem();
+ virtual int type() const;
+ double value() const;
+ void setValue(double value);
+ void setValue(int value);
+
+private:
+ void initProperties();
+ double m_value;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_REPORTMODEL_h
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.h (revision 1522570)
@@ -0,0 +1,50 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REPORTPROXYMODEL_H
+#define VERITAS_COVERAGE_REPORTPROXYMODEL_H
+
+#include <QSortFilterProxyModel>
+
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+/*! Used to filter coverage directories from the model */
+class VERITAS_COVERAGE_EXPORT ReportProxyModel : public QSortFilterProxyModel
+{
+Q_OBJECT
+public:
+ explicit ReportProxyModel(QObject* parent);
+ virtual ~ReportProxyModel();
+
+ void setFileViewState();
+ void setDirViewState();
+
+protected:
+ bool filterAcceptsColumn(int, const QModelIndex&) const;
+
+private:
+ enum State { DirView, FileView } m_state;
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.h (revision 1522570)
@@ -0,0 +1,50 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
+#define VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
+
+#include <QtGui/QItemDelegate>
+#include <kcolorscheme.h>
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+/*! Colorizes the lcovjob somewhat */
+class VERITAS_COVERAGE_EXPORT CovOutputDelegate : public QItemDelegate
+{
+public:
+ explicit CovOutputDelegate(QObject* parent = 0);
+ virtual ~CovOutputDelegate();
+
+ void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
+private:
+ KStatefulBrush textBrush;
+ KStatefulBrush processBrush;
+ KStatefulBrush warningBrush;
+ KStatefulBrush errorBrush;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputdelegate.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.h (revision 1522570)
@@ -0,0 +1,94 @@
+/***************************************************************************
+ * Copyright 2005 Benjamin Meyer <ben@meyerhome.net> *
+ * Copyright 2006 Alexander Dymo <adymo@kdevelop.org> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef VERITAS_COVERAGE_DRILLDOWNVIEW_H
+#define VERITAS_COVERAGE_DRILLDOWNVIEW_H
+
+#include <QtGui/QtGui>
+
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+/*! Coverage report table */
+class VERITAS_COVERAGE_EXPORT DrillDownView: public QTableView
+{
+Q_OBJECT
+
+public:
+ explicit DrillDownView(QWidget *parent = 0);
+ virtual ~DrillDownView();
+ void resizeFileStateColumns();
+
+ /*!
+ * Shows the coverage data for directories.
+ * The selection is cleared, and then set again to the directories selected
+ * before sliding to the left (including the current index).
+ */
+ void slideLeft();
+
+ /*!
+ * Shows the coverage data for the files in the currently selected
+ * directory.
+ * The selection is cleared.
+ */
+ void slideRight(const QModelIndex&);
+
+Q_SIGNALS:
+ void returnPressed(const QModelIndex &index);
+ void rootIndexChanged(const QModelIndex &index);
+ void completedSlideLeft();
+ void completedSlideRight();
+
+public Q_SLOTS:
+ void resizeDirStateColumns();
+ void setRootIndex(const QModelIndex &index);
+
+protected:
+ virtual void paintEvent(QPaintEvent * event);
+ virtual void keyPressEvent(QKeyEvent *event);
+ virtual void mousePressEvent(QMouseEvent* event);
+
+private Q_SLOTS:
+ void slide(int x);
+
+private:
+ bool isBusy();
+ void animateSlide(int moveDirection);
+ int maxWidth() const;
+
+private:
+ QTimeLine animation;
+ QPixmap oldView;
+ QPixmap newView;
+ int lastPosition;
+
+ /*!
+ * Stores the selection of directories to restore it when sliding left
+ * again.
+ */
+ QItemSelection leftSelection;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_DRILLDOWNVIEW_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.h (revision 1522570)
@@ -0,0 +1,72 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_LCOVINFOPARSER_H
+#define VERITAS_LCOVINFOPARSER_H
+
+#include <QIODevice>
+#include <QList>
+#include <QStringList>
+#include <KUrl>
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+class CoveredFile;
+
+/*! Parses lcov output into CoveredFile* and emits those as soon
+ * as they are read
+ * @note instantiate a fresh parser for every lcov.info file */
+class VERITAS_COVERAGE_EXPORT LcovInfoParser : public QObject
+{
+Q_OBJECT
+public:
+ explicit LcovInfoParser(QObject* parent=0);
+ ~LcovInfoParser();
+
+ /*! Parse a single line of lcov output. The results are
+ * emitted through `parsedCoverageData(CoveredFile*)' */
+ void parseLine(const QString& line);
+
+ QList<CoveredFile*> fto_coveredFiles();
+
+Q_SIGNALS:
+ /*! Emitted whenever a full coverage record was parsed.
+ * @p file contains the parsed coverage information */
+ void parsedCoverageData(CoveredFile* file);
+
+public Q_SLOTS:
+ void parseLines(const QStringList& lines);
+
+private:
+ CoveredFile* m_current;
+ QList<CoveredFile*> m_files;
+
+ // scratch variables
+ char tmp_firstChar;
+ char tmp_secondChar;
+ QStringList tmp_s;
+ QStringList tmp_l;
+ QString tmp_f;
+};
+
+}
+
+#endif // VERITAS_LCOVINFOPARSER_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovinfoparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.h (revision 1522570)
@@ -0,0 +1,66 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_ANNOTATIONMANAGER_H
+#define VERITAS_COVERAGE_ANNOTATIONMANAGER_H
+
+#include "coverageexport.h"
+
+#include <KUrl>
+#include <QMap>
+
+namespace KDevelop { class IDocument; }
+namespace KTextEditor { class Document; class View; }
+
+namespace Veritas
+{
+
+class CoveredFile;
+/*!
+ * Makes sure document views are annotated with coverage info
+ * @unittest AnnotationManagerTest
+ */
+class VERITAS_COVERAGE_EXPORT AnnotationManager : public QObject
+{
+Q_OBJECT
+public:
+ explicit AnnotationManager(QObject* parent=0);
+ virtual ~AnnotationManager();
+
+ void setCoveredFiles(const QMap<KUrl, CoveredFile*>& files);
+ void watch(KDevelop::IDocument*);
+ void stopWatching(KDevelop::IDocument*);
+
+public Q_SLOTS:
+ void addCoverageData(CoveredFile* f);
+
+private Q_SLOTS:
+ void connectKDocWithTextDoc(KDevelop::IDocument*);
+ void fixAnnotation(KTextEditor::Document*, KTextEditor::View*);
+
+private:
+ QMap<KUrl, CoveredFile*> m_files;
+ QList<KDevelop::IDocument*> m_docs;
+ QMap<KTextEditor::Document*, KUrl> m_textDocUrls;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_ANNOTATIONMANAGER_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.cpp (revision 1522570)
@@ -0,0 +1,93 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "coverageplugin.h"
+#include "reportwidget.h"
+
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+
+#include <QAbstractItemView>
+#include <QDir>
+#include <KAction>
+#include <KAboutData>
+#include <KActionCollection>
+#include <KActionMenu>
+#include <KLocale>
+#include <KPluginFactory>
+#include <KPluginLoader>
+
+using KDevelop::ICore;
+using KDevelop::IUiController;
+
+using Veritas::CoveragePlugin;
+using Veritas::ReportViewFactory;
+using Veritas::ReportWidget;
+
+K_PLUGIN_FACTORY(CoveragePluginFactory, registerPlugin<CoveragePlugin>();)
+K_EXPORT_PLUGIN(CoveragePluginFactory(KAboutData("kdevcoverage","kdevcoverage", ki18n("Coverage Support"), "0.1", ki18n("Support for running coverage tools"), KAboutData::License_GPL)))
+
+//////////////////////////// CoveragePlugin ///////////////////////////////
+
+CoveragePlugin::CoveragePlugin(QObject* parent, const QVariantList&)
+ : KDevelop::IPlugin( CoveragePluginFactory::componentData(), parent ),
+ m_factory(new ReportViewFactory())
+{
+ setXMLFile("kdevcoverage.rc");
+ core()->uiController()->addToolView(i18n("Coverage"), m_factory);
+}
+
+CoveragePlugin::~CoveragePlugin()
+{
+}
+
+void CoveragePlugin::unload()
+{
+ core()->uiController()->removeToolView( m_factory );
+}
+
+//////////////////////////// ReportViewFactory ///////////////////////////////
+
+ReportViewFactory::ReportViewFactory()
+{
+}
+
+ReportViewFactory::~ReportViewFactory()
+{
+}
+
+QWidget* ReportViewFactory::create(QWidget *parent)
+{
+ ReportWidget* w = new ReportWidget(parent);
+ w->init();
+ return w;
+}
+
+Qt::DockWidgetArea ReportViewFactory::defaultPosition()
+{
+ return Qt::RightDockWidgetArea;
+}
+
+QString ReportViewFactory::id() const
+{
+ return "org.kdevelop.CoverageReport";
+}
+
+#include "coverageplugin.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.h (revision 1522570)
@@ -0,0 +1,64 @@
+/* KDevelop coverage plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGEPLUGIN_H
+#define VERITAS_COVERAGEPLUGIN_H
+
+#include <KUrl>
+#include <QVariantList>
+#include <QFileInfo>
+#include <interfaces/iplugin.h>
+#include <interfaces/iuicontroller.h>
+
+class QDir;
+
+namespace Veritas
+{
+class ReportViewFactory;
+
+/*! GCC GCOV coverage plugin. Code coverage report with source annotations (line call count). */
+class CoveragePlugin : public KDevelop::IPlugin
+{
+Q_OBJECT
+
+public:
+ explicit CoveragePlugin(QObject* parent, const QVariantList& = QVariantList());
+ virtual ~CoveragePlugin();
+ virtual void unload();
+
+private:
+ ReportViewFactory* m_factory;
+};
+
+/*! Report toolview factory */
+class ReportViewFactory : public KDevelop::IToolViewFactory
+{
+public:
+ ReportViewFactory();
+ virtual ~ReportViewFactory();
+
+ virtual QWidget* create(QWidget *parent = 0);
+ virtual Qt::DockWidgetArea defaultPosition();
+ virtual QString id() const;
+};
+
+} // namespace Veritas
+
+#endif // VERITAS_COVERAGEPLUGIN_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageplugin.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h (revision 1522570)
@@ -0,0 +1,121 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOB_H
+#define VERITAS_COVERAGE_REMOVEGCDAFILESJOB_H
+
+#include <QFileInfo>
+#include <QFutureWatcher>
+
+#include <KJob>
+#include <KUrl>
+
+#include "coverageexport.h"
+
+class QDir;
+
+namespace Veritas {
+class RemoveGcdaFilesJobProgress;
+}
+
+namespace Veritas {
+
+/**
+ * Job to remove the .gcda files from the given directory and, recursively, its
+ * subdirectories.
+ * The job is a killable job, and it removes the files in an auxiliar thread.
+ */
+class VERITAS_COVERAGE_EXPORT RemoveGcdaFilesJob: public KJob {
+Q_OBJECT
+
+public:
+
+ /**
+ * Creates a new RemoveGcdaFilesJob for the given path.
+ *
+ * @param rootPath The root path to remove the .gcda files from.
+ * @param parent The parent object.
+ */
+ explicit RemoveGcdaFilesJob(const KUrl& rootPath, QObject* parent = 0);
+
+ /**
+ * Starts the job.
+ * It runs a new thread that does all the work.
+ */
+ virtual void start();
+
+protected:
+
+ /**
+ * Kills the job.
+ * The job waits until the auxiliar thread has finished.
+ *
+ * @return True.
+ */
+ virtual bool doKill();
+
+private Q_SLOTS:
+
+ /**
+ * Emits the result for this job.
+ */
+ void jobDone();
+
+private:
+
+ /**
+ * The root path to remove the .gcda files from it and its subdirectories.
+ */
+ KUrl mRootPath;
+
+ /**
+ * True if kill() was called.
+ */
+ bool mKillRequested;
+
+ /**
+ * Watches the execution of the auxiliar thread to know if it has finished.
+ */
+ QFutureWatcher<void>* mDoWorkWatcher;
+
+ /**
+ * The status updater for this job.
+ */
+ RemoveGcdaFilesJobProgress* mRemoveGcdaFilesJobProgress;
+
+ /**
+ * Finds and removes the .gcda files in the root path and its
+ * subdirectories.
+ */
+ void doWork() const;
+
+ /**
+ * Returns a list with the .gcda files in the given directory and its
+ * subdirectories.
+ *
+ * @param directory The directory to find its .gcda files.
+ * @return A list with the .gcda files.
+ */
+ QFileInfoList findGcdaFilesIn(const QDir& directory) const;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp (revision 1522570)
@@ -0,0 +1,71 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "removegcdafilesjobprogress.h"
+
+#include <KLocalizedString>
+
+using Veritas::RemoveGcdaFilesJobProgress;
+
+RemoveGcdaFilesJobProgress::RemoveGcdaFilesJobProgress(QObject* parent /*= 0*/):
+ QObject(parent),
+ m_numberOfFilesFound(0), m_numberOfFilesRemoved(0)
+{
+}
+
+QString RemoveGcdaFilesJobProgress::statusName() const
+{
+ return i18nc("@info:progress", "Removing coverage data");
+}
+
+void RemoveGcdaFilesJobProgress::start()
+{
+ emit showMessage(this, i18nc("@info:progress", "Scanning for .gcda files"));
+ emit showProgress(this, 0, 1, 0);
+}
+
+void RemoveGcdaFilesJobProgress::setNumberOfFilesFound(int numberOfFilesFound)
+{
+ Q_ASSERT(numberOfFilesFound >= 0);
+
+ m_numberOfFilesFound = numberOfFilesFound;
+
+ emit showMessage(this, i18nc("@info:progress", "Removing .gcda files"));
+ emit showProgress(this, 0, 2, 1);
+}
+
+void RemoveGcdaFilesJobProgress::fileAboutToBeRemoved()
+{
+ Q_ASSERT(m_numberOfFilesFound >= m_numberOfFilesRemoved + 1);
+
+ //Half total progress was scanning for .gcda files
+ int progress = 50;
+ progress += 50 * m_numberOfFilesRemoved / (float)m_numberOfFilesFound;
+
+ emit showProgress(this, 0, 100, progress);
+
+ m_numberOfFilesRemoved++;
+}
+
+void RemoveGcdaFilesJobProgress::finish()
+{
+ emit clearMessage(this);
+ emit showProgress(this, 0, 1, 1);
+ emit hideProgress(this);
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp (revision 1522570)
@@ -0,0 +1,103 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "removegcdafilesjob.h"
+
+#include "removegcdafilesjobprogress.h"
+
+#include <QDir>
+#include <QtConcurrentRun>
+#include <QFuture>
+
+#include <KLocale>
+
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+
+using KDevelop::ICore;
+
+using Veritas::RemoveGcdaFilesJob;
+using Veritas::RemoveGcdaFilesJobProgress;
+
+RemoveGcdaFilesJob::RemoveGcdaFilesJob(const KUrl& rootPath, QObject* parent):
+ KJob(parent),
+ mRootPath(rootPath),
+ mKillRequested(false) {
+
+ setCapabilities(Killable);
+ setObjectName(i18nc("@action:inmenu", "Remove coverage data from <filename>%1</filename> directory", rootPath.toLocalFile()));
+
+ mRemoveGcdaFilesJobProgress = new RemoveGcdaFilesJobProgress(this);
+ ICore::self()->uiController()->registerStatus(mRemoveGcdaFilesJobProgress);
+}
+
+void RemoveGcdaFilesJob::start() {
+ mRemoveGcdaFilesJobProgress->start();
+
+ mDoWorkWatcher = new QFutureWatcher<void>(this);
+ connect(mDoWorkWatcher, SIGNAL(finished()), this, SLOT(jobDone()));
+
+ QFuture<void> doWorkFuture = QtConcurrent::run(this, &RemoveGcdaFilesJob::doWork);
+ mDoWorkWatcher->setFuture(doWorkFuture);
+}
+
+bool RemoveGcdaFilesJob::doKill() {
+ mKillRequested = true;
+
+ mDoWorkWatcher->waitForFinished();
+
+ return true;
+}
+
+void RemoveGcdaFilesJob::jobDone() {
+ mRemoveGcdaFilesJobProgress->finish();
+
+ emitResult();
+}
+
+void RemoveGcdaFilesJob::doWork() const {
+ QFileInfoList gcdaFileInfos = findGcdaFilesIn(QDir(mRootPath.toLocalFile()));
+
+ mRemoveGcdaFilesJobProgress->setNumberOfFilesFound(gcdaFileInfos.count());
+
+ QListIterator<QFileInfo> it(gcdaFileInfos);
+ while (it.hasNext() && !mKillRequested) {
+ mRemoveGcdaFilesJobProgress->fileAboutToBeRemoved();
+
+ QFile(it.next().absoluteFilePath()).remove();
+ }
+}
+
+QFileInfoList RemoveGcdaFilesJob::findGcdaFilesIn(const QDir& directory) const {
+ QFileInfoList gcdaFileInfos;
+
+ QFileInfoList directories;
+ directories << directory.absolutePath();
+
+ while (!directories.isEmpty() && !mKillRequested) {
+ //Note that absolutePath() would return the path to the parent
+ //directory, not the one we are interested in
+ QDir currentDirectory = directories.takeFirst().absoluteFilePath();
+ directories << currentDirectory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
+
+ gcdaFileInfos << currentDirectory.entryInfoList(QStringList() << "*.gcda", QDir::Files | QDir::NoSymLinks);
+ }
+
+ return gcdaFileInfos;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,103 @@
+project(coverage)
+
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${coverage_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+find_package(KDevVeritas REQUIRED)
+
+include(KDE4Defaults)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDEVVERITAS_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+)
+
+kde4_no_enable_final(coverage)
+add_subdirectory(tests)
+
+add_definitions( ${KDE4_ENABLE_EXCEPTIONS} )
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+
+########### next target ###############
+
+set(veritascoverage_SRCS
+ coveredfile.cpp
+ annotationmodel.cpp
+ lcovinfoparser.cpp
+ annotationmanager.cpp
+ lcovjob.cpp
+ lcovjobprogress.cpp
+ covoutputmodel.cpp
+ covoutputdelegate.cpp
+ reportwidget.cpp
+ reportmodel.cpp
+ reportproxymodel.cpp
+ drilldownview.cpp
+ colorrange.cpp
+ discretecolorrange.cpp
+ gradientcolorrange.cpp
+ buildpathselection.cpp
+ removegcdafilesjob.cpp
+ removegcdafilesjobprogress.cpp
+ tests/viewstub.cpp
+ tests/pluginstub.cpp)
+
+kde4_add_ui_files(veritascoverage_SRCS reportwidget.ui)
+
+kde4_add_library(kdevveritascoverage SHARED ${veritascoverage_SRCS})
+target_link_libraries(kdevveritascoverage
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_SHELL_LIBRARIES}
+ ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
+ ${KDEVPLATFORM_UTIL_LIBRARIES}
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDE4_KDEUI_LIBS}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ ${KDE4_KFILE_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVVERITAS_LIBRARY})
+install(TARGETS kdevveritascoverage ${INSTALL_TARGETS_DEFAULT_ARGS})
+
+qt4_automoc(coverageplugin.cpp)
+kde4_add_plugin(kdevcoverage coverageplugin.cpp)
+target_link_libraries(kdevcoverage
+ kdevveritascoverage
+ ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_UTIL_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ ${KDE4_KDEUI_LIBS})
+install(TARGETS kdevcoverage DESTINATION ${PLUGIN_INSTALL_DIR})
+
+if( NOT KDE_VERSION VERSION_LESS "4.2.2" )
+
+ set(lcovsettings_cfg_SRCS
+ lcovprefs.cpp
+ lcovprefswidget.cpp
+ lcovsettingsbase.cpp
+ stoppointwidget.cpp
+ colorrangebar.cpp
+ colorrange.cpp
+ discretecolorrange.cpp
+ gradientcolorrange.cpp)
+
+ kde4_add_ui_files( lcovsettings_cfg_SRCS lcovprefswidget.ui stoppointwidget.ui)
+ kde4_add_kcfg_files( lcovsettings_cfg_SRCS lcovconfig.kcfgc )
+ kde4_add_plugin( kcm_kdev_lcovsettings ${lcovsettings_cfg_SRCS} )
+ target_link_libraries( kcm_kdev_lcovsettings ${KDE4_KUTILS_LIBS} ${KDE4_KDEUI_LIBS} ${KDE4_KIO_LIBS} )
+ install( TARGETS kcm_kdev_lcovsettings DESTINATION ${PLUGIN_INSTALL_DIR})
+ install( FILES kcm_kdev_lcovsettings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+
+endif( NOT KDE_VERSION VERSION_LESS "4.2.2" )
+
+########### install files ###############
+
+install( FILES kdevcoverage.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevcoverage.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcoverage )
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h (revision 1522570)
@@ -0,0 +1,126 @@
+/* KDevelop coverage plugin
+ * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESS_H
+#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESS_H
+
+#include <interfaces/istatus.h>
+
+#include "coverageexport.h"
+
+namespace KDevelop
+{
+class IStatus;
+}
+
+namespace Veritas
+{
+
+/**
+ * Shows progress information for remove gcda files job.
+ * The job first scans the given directory looking for gcda files and then
+ * removes each gcda file found.
+ * While the job is looking for gcda files no progress updates are given. Once
+ * it finishes looking for them, it tells how many files were found and then
+ * notifies the files removed one by one.
+ *
+ * The progress is reported by this class in this way:
+ * - 0: when the job starts and while it is scanning the directory.
+ * - 50: when the job finishes scanning the directory.
+ * - (50-100]: when the job is removing the files. The progress will be updated
+ * proportionally to how many files are going to be removed and how many files
+ * have already been removed.
+ * - 100: when the job finishes, no matter why.
+ *
+ * Also, the status message will specify whether the job is scanning for files
+ * or removing them already.
+ */
+class VERITAS_COVERAGE_EXPORT RemoveGcdaFilesJobProgress: public QObject, public KDevelop::IStatus
+{
+Q_OBJECT
+Q_INTERFACES(KDevelop::IStatus)
+
+public:
+
+ /**
+ * Creates a new RemoveGcdaFilesJobProgress.
+ *
+ * @param parent The parent QObject.
+ */
+ explicit RemoveGcdaFilesJobProgress(QObject* parent = 0);
+
+ //<KDevelop::IStatus>
+
+ /**
+ * The name of this status update.
+ *
+ * @return "Removing coverage data"
+ */
+ virtual QString statusName() const;
+
+Q_SIGNALS:
+
+ void clearMessage(KDevelop::IStatus* status);
+ void showMessage(KDevelop::IStatus* status, const QString & message, int timeout = 0);
+ void showErrorMessage(const QString & message, int timeout = 0);
+ void hideProgress(KDevelop::IStatus* status);
+ void showProgress(KDevelop::IStatus* status, int minimum, int maximum, int value);
+
+ //</KDevelop::IStatus>
+
+public:
+
+ /**
+ * Reports that the job has been started.
+ * The message will be set to "Scanning for .gcda files".
+ */
+ void start();
+
+ /**
+ * Sets the number of files found.
+ * It is assumed that the job has finished scanning the directory, so the
+ * message will be set to "Removing .gcda files" and the progress set to
+ * 50%.
+ *
+ * @param numberOfFilesFound The number of gcda files found.
+ */
+ void setNumberOfFilesFound(int numberOfFilesFound);
+
+ /**
+ * Updates the progress based on the number of files that were removed
+ * already.
+ */
+ void fileAboutToBeRemoved();
+
+ /**
+ * Reports that the job has finished, no matter why.
+ * Clears the message and shows a 100% progress before hidding it.
+ */
+ void finish();
+
+private:
+
+ int m_numberOfFilesFound;
+ int m_numberOfFilesRemoved;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportwidget.ui (revision 1522570)
@@ -0,0 +1,288 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ReportWidget</class>
+ <widget class="QWidget" name="ReportWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>357</width>
+ <height>498</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Coverage Report</string>
+ </property>
+ <property name="whatsThis">
+ <string>GCOV code coverage statistics.
+
+Set the directory to generate the report for and start the scan.
+
+Once finished, you can select the directories in the coverage report to see their statistics. A more detailed report can be seen for each directory, showing all the covered files in it. Each file can also be shown in the editor, annotated with line by line coverage information.</string>
+ </property>
+ <layout class="QVBoxLayout" name="reportWidgetLayout">
+ <item>
+ <widget class="QFrame" name="buildPathFrame">
+ <property name="frameShape">
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QVBoxLayout" name="buildPathFrameLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buildPathSelectionLayout">
+ <item>
+ <widget class="QLabel" name="buildPathTextLabel">
+ <property name="whatsThis">
+ <string>The directory to scan for .gcda files.</string>
+ </property>
+ <property name="text">
+ <string>Build Path: </string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="lcovJobButton">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeGcdaFilesJobButton">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="projectSelectionLayout">
+ <item>
+ <widget class="QLabel" name="getFromProjectTextLabel">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Use the build path from the selected project</string>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">When one of the opened projects is selected, the directory to scan for &lt;filename&gt;.gcda&lt;/filename&gt; files will be set to the build path of that project.</string>
+ </property>
+ <property name="text">
+ <string comment="@label:listbox">Get from project:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="projectSelectionSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QFrame" name="statisticsFrame">
+ <property name="frameShape">
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QHBoxLayout" name="statisticsFrameLayout">
+ <item>
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>71</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="KLineEdit" name="filterBox">
+ <property name="toolTip">
+ <string>Filter directories by name</string>
+ </property>
+ <property name="whatsThis">
+ <string>When the report is in directory mode, only those containing the specified text in their path are shown.
+
+In file mode, the filter has no effect.</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>30</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="coverageRatioTextLabel">
+ <property name="whatsThis">
+ <string>Percentage of covered lines in the selected directories.</string>
+ </property>
+ <property name="text">
+ <string>Line Coverage:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="coverageRatio">
+ <property name="whatsThis">
+ <string>Percentage of covered lines in the selected directories.</string>
+ </property>
+ <property name="text">
+ <string>-</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="nrofCoveredLinesTextLabel">
+ <property name="whatsThis">
+ <string>Number of covered lines in the selected directories.
+
+Covered lines are those that were executed at least once.</string>
+ </property>
+ <property name="text">
+ <string>Covered Lines:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="nrofCoveredLines">
+ <property name="whatsThis">
+ <string>Number of covered lines in the selected directories.
+
+Covered lines are those that were executed at least once.</string>
+ </property>
+ <property name="text">
+ <string>-</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="slocTextLabel">
+ <property name="whatsThis">
+ <string>Total number of lines of code in the selected directories.
+
+Note that it only includes executable lines. That is, things like comments, macros, forward declarations, etc. are not taken into account.</string>
+ </property>
+ <property name="text">
+ <string>Total SLOC:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLabel" name="sloc">
+ <property name="whatsThis">
+ <string>Total number of lines of code in the selected directories.
+
+Note that it only includes executable lines. That is, things like comments, macros, forward declarations, etc. are not taken into account.</string>
+ </property>
+ <property name="text">
+ <string>-</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>30</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_4">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>71</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="Veritas::DrillDownView" name="table">
+ <property name="whatsThis">
+ <string>Coverage report.
+
+In directory mode, the report summarizes the coverage with a list of all the directories that contain at least one covered file. It could include directories out of the specified path, depending on the files included in the source code.
+
+In file mode, all the files of the selected directory are shown. If several directories are selected, only the files of the last selected directory are shown. Double clicking on any of the items shows the associated file in the editor, annotated with the coverage information.
+
+You can change between directory and file mode using left and right keys.</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KLineEdit</class>
+ <extends>QLineEdit</extends>
+ <header>klineedit.h</header>
+ </customwidget>
+ <customwidget>
+ <class>Veritas::DrillDownView</class>
+ <extends>QTableView</extends>
+ <header>drilldownview.h</header>
+ <slots>
+ <signal>completedSlideLeft()</signal>
+ <signal>completedSlideRight()</signal>
+ </slots>
+ </customwidget>
+ </customwidgets>
+ <tabstops>
+ <tabstop>lcovJobButton</tabstop>
+ <tabstop>filterBox</tabstop>
+ <tabstop>table</tabstop>
+ </tabstops>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` `find . -name \*.kcfg` >>rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h | grep -v '/tests/'` -o $podir/kdevcoverage.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake (revision 1522570)
@@ -0,0 +1,30 @@
+#
+# Find the KDevelop Veritas library
+#
+# Example usage of this module:
+# find_package(KDevVeritas)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVVERITAS_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVVERITAS_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVVERITAS_LIBRARY - veritas module library
+#
+# Copyright 2009 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+find_path( KDEVVERITAS_INCLUDE_DIR veritas/test.h
+ PATH_SUFFIXES kdevplatform
+ )
+find_library( KDEVVERITAS_LIBRARY kdevplatformveritas
+ )
+
+# handle the QUIETLY and REQUIRED arguments and set JPEG_FOUND to TRUE if
+# all listed variables are TRUE
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevVeritas DEFAULT_MSG KDEVVERITAS_LIBRARY KDEVVERITAS_INCLUDE_DIR)
+
+mark_as_advanced(KDEVVERITAS_INCLUDE_DIR KDEVVERITAS_LIBRARY)
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.cpp (revision 1522570)
@@ -0,0 +1,104 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "buildpathselection.h"
+
+#include <KLocalizedString>
+#include <KUrlNavigator>
+
+#include <interfaces/iproject.h>
+#include <project/projectmodel.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+
+#include <veritas/projectselection.h>
+
+using Veritas::BuildPathSelection;
+using Veritas::ProjectSelection;
+
+class BuildPathProjectFilter: public ProjectSelection::IProjectFilter
+{
+public:
+
+ BuildPathProjectFilter():
+ IProjectFilter(i18nc("@info:whatsthis Appended to the end of another WhatsThis help",
+ "<para>In this case, only projects with a build path set can be selected.</para>"))
+ {
+ }
+
+ virtual bool canBeSelected(KDevelop::IProject* project)
+ {
+ if (!project->buildSystemManager() ||
+ project->buildSystemManager()->buildDirectory(project->projectItem()).isEmpty()) {
+ return false;
+ }
+
+ return true;
+ }
+
+};
+
+BuildPathSelection::BuildPathSelection(KUrlNavigator* targetDirectory, QObject* parent /*= 0*/):
+ QObject(parent)
+{
+ m_projectSelection = new ProjectSelection(this, new BuildPathProjectFilter());
+ m_projectSelection->setToolBarMode(KSelectAction::ComboBoxMode);
+ connect(m_projectSelection, SIGNAL(projectSelected(KDevelop::IProject*)),
+ this, SLOT(setBuildPathFromProject(KDevelop::IProject*)));
+ connect(targetDirectory, SIGNAL(urlChanged(KUrl)),
+ this, SLOT(setProjectFromBuildPath(KUrl)));
+ connect(this, SIGNAL(buildPathToSet(KUrl)),
+ targetDirectory, SLOT(setUrl(KUrl)));
+}
+
+QWidget* BuildPathSelection::requestProjectSelectionWidget(QWidget* parent)
+{
+ return m_projectSelection->requestWidget(parent);
+}
+
+void BuildPathSelection::setBuildPathFromProject(KDevelop::IProject* project)
+{
+ if (!project) {
+ return;
+ }
+
+ Q_ASSERT(project->buildSystemManager());
+ Q_ASSERT(!project->buildSystemManager()->buildDirectory(project->projectItem()).isEmpty());
+
+ //KUrlNavigator::setUrl emits KUrlNavigator::urlChanged signal, which is connected to
+ //setProjectFromBuildPath, so the project is set with itself. It does no
+ //harm, but that superfluous call to setProjectFromBuildPath should be
+ //avoided
+ emit buildPathToSet(project->buildSystemManager()->buildDirectory(project->projectItem()));
+}
+
+void BuildPathSelection::setProjectFromBuildPath(const KUrl& url)
+{
+ foreach (KDevelop::IProject* project, m_projectSelection->projects()) {
+ if (project->buildSystemManager()) {
+ KUrl buildDirectory = project->buildSystemManager()->buildDirectory(project->projectItem());
+ if (buildDirectory.equals(url, KUrl::CompareWithoutTrailingSlash)) {
+ m_projectSelection->selectProject(project);
+ return;
+ }
+ }
+ }
+
+ m_projectSelection->selectProject(0);
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.h (revision 1522570)
@@ -0,0 +1,120 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_BUILDPATHSELECTION_H
+#define VERITAS_COVERAGE_BUILDPATHSELECTION_H
+
+#include <QObject>
+
+#include "coverageexport.h"
+
+class QWidget;
+class KUrl;
+class KUrlNavigator;
+
+namespace KDevelop
+{
+class IProject;
+}
+
+namespace Veritas
+{
+
+class ProjectSelection;
+
+/**
+ * Manages the build path selection.
+ * The build path is scanned for .gcda files when the coverage analysis starts.
+ * It can be set directly in a KUrlNavigator, or got from the current build path
+ * used in an opened project.
+ *
+ * If a project is selected, the URL shown by the KUrlNavigator is set to the
+ * build path of that project. If the URL shown by the KUrlNavigator is changed,
+ * the selected project will change to the one that uses that build path. If
+ * there is none, the selected project will be cleared.
+ *
+ * Only projects that have a build manager with a build path set can be
+ * selected.
+ */
+class VERITAS_COVERAGE_EXPORT BuildPathSelection: public QObject
+{
+Q_OBJECT
+public:
+
+ /**
+ * Creates a new BuildPathSelection.
+ *
+ * @param targetDirectory The KUrlNavigator to update when a project is
+ * selected.
+ * @param parent The parent object.
+ */
+ explicit BuildPathSelection(KUrlNavigator* targetDirectory, QObject* parent = 0);
+
+ /**
+ * Returns a widget that represents the ProjectSelection action.
+ *
+ * @param parent The parent widget.
+ * @return The widget that represents the action.
+ */
+ QWidget* requestProjectSelectionWidget(QWidget* parent);
+
+public Q_SLOTS:
+
+ /**
+ * Sets the build path from the given project.
+ * If a project was selected, it must have a build system manager with a
+ * configured build directory. A null pointer can be received when the
+ * current project is cleared (because its configuration changed or because
+ * it is closed), and nothing is done in that case.
+ *
+ * @param project The project to get the build path from.
+ */
+ void setBuildPathFromProject(KDevelop::IProject* project);
+
+ /**
+ * Sets the selected project as the first one that has the given URL as
+ * build path.
+ * If no project has that URL as build path, the current project is
+ * deselected.
+ *
+ * @param url The URL of the build path.
+ */
+ void setProjectFromBuildPath(const KUrl& url);
+
+Q_SIGNALS:
+
+ /**
+ * Emitted when the build path from the selected project has to be set.
+ *
+ * @param url The build path.
+ */
+ void buildPathToSet(const KUrl& url);
+
+private:
+
+ /**
+ * Manages the selection of projects.
+ */
+ ProjectSelection* m_projectSelection;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/buildpathselection.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.h (revision 1522570)
@@ -0,0 +1,122 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_LCOVJOBPROGRESS_H
+#define VERITAS_COVERAGE_LCOVJOBPROGRESS_H
+
+#include <interfaces/istatus.h>
+
+#include "coverageexport.h"
+
+namespace KDevelop
+{
+class IStatus;
+}
+
+namespace Veritas
+{
+
+/**
+ * Shows progress information about geninfo execution.
+ * geninfo first scans the given directory looking for gcda files and then
+ * generates a report for each gcda file found.
+ * While geninfo is looking for gcda files no progress updates are given. Once
+ * it finishes looking for them, it tells how many files were found and then
+ * process them one for one.
+ *
+ * The progress is reported by this class in this way:
+ * - 0: when geninfo starts and while it is scanning the directory.
+ * - 50: when geninfo finishes scanning the directory.
+ * - (50-100]: when geninfo is processing the files. The progress will be
+ * updated proportionally to how many files are going to be processed and how
+ * many files have already been processed.
+ * - 100: when geninfo finishes, no matter why.
+ *
+ * Also, the status message will specify whether geninfo is scanning for files
+ * or processing them already.
+ */
+class VERITAS_COVERAGE_EXPORT LcovJobProgress: public QObject, public KDevelop::IStatus
+{
+Q_OBJECT
+Q_INTERFACES(KDevelop::IStatus)
+
+public:
+
+ /**
+ * Creates a new LcovJobProgress.
+ *
+ * @param parent The parent QObject.
+ */
+ explicit LcovJobProgress(QObject* parent = 0);
+
+ /**
+ * Destroys this LcovJobProgress.
+ */
+ virtual ~LcovJobProgress();
+
+ //<KDevelop::IStatus>
+
+ /**
+ * The name of this status update.
+ *
+ * @return "Running geninfo"
+ */
+ virtual QString statusName() const;
+
+Q_SIGNALS:
+
+ void clearMessage(KDevelop::IStatus* status);
+ void showMessage(KDevelop::IStatus* status, const QString & message, int timeout = 0);
+ void showErrorMessage(const QString & message, int timeout = 0);
+ void hideProgress(KDevelop::IStatus* status);
+ void showProgress(KDevelop::IStatus* status, int minimum, int maximum, int value);
+
+ //</KDevelop::IStatus>
+
+public slots:
+
+ /**
+ * Reports that geninfo has been started.
+ * No message will be given.
+ */
+ void start();
+
+ /**
+ * Parses the informative output of geninfo and updates the progress.
+ *
+ * @param lines The informative output received.
+ */
+ void parseLines(const QStringList &lines);
+
+ /**
+ * Reports that geninfo has finished, no matter why.
+ * Clears the message and shows a 100% progress before hidding it.
+ */
+ void finish();
+
+private:
+
+ int m_numberOfFilesFound;
+ int m_numberOfFilesProcessed;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.h (revision 1522570)
@@ -0,0 +1,93 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_LCOVJOB_H
+#define VERITAS_COVERAGE_LCOVJOB_H
+
+#include <interfaces/iplugin.h>
+#include <outputview/outputjob.h>
+#include "coverageexport.h"
+
+#include <QProcess>
+#include <QString>
+#include <KUrl>
+
+namespace KDevelop
+{
+class IOutputView;
+class IProject;
+class ProcessLineMaker;
+}
+
+class KProcess;
+
+namespace Veritas
+{
+
+class CovOutputModel;
+class CovOutputDelegate;
+class LcovInfoParser;
+class LcovJobProgress;
+
+/*! Executes the lcov coverage script in an outputview */
+class VERITAS_COVERAGE_EXPORT LcovJob : public KDevelop::OutputJob
+{
+ Q_OBJECT
+
+public:
+ explicit LcovJob(const KUrl& root, QObject* parent=0);
+ virtual ~LcovJob();
+ void setProcess(KProcess *proc); // takes ownership.
+ void setParser(LcovInfoParser* parser);
+ void setDelegate(CovOutputDelegate* delegate);
+ virtual void start();
+
+protected:
+ CovOutputModel* model() const;
+
+ /**
+ * Kill underlying geninfo/lcov process.
+ * An error message is also added to the model.
+ *
+ * @return true.
+ */
+ virtual bool doKill();
+
+private Q_SLOTS:
+ void slotFinished();
+ void slotError(QProcess::ProcessError error);
+
+private:
+ void initProcess();
+ void initOutputView();
+ void initParser();
+
+private:
+ KDevelop::ProcessLineMaker* m_lineMaker;
+ KProcess* m_lcov;
+ KUrl m_root;
+ QString m_tmpPath;
+ LcovInfoParser* m_parser;
+ LcovJobProgress* m_lcovJobProgress;
+};
+
+}
+
+#endif // VERITAS_COVERAGE_LCOVJOB_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjob.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp (revision 1522570)
@@ -0,0 +1,82 @@
+/* KDevelop coverage plugin
+ * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "lcovjobprogress.h"
+
+#include <QTimer>
+
+#include <KLocalizedString>
+
+using Veritas::LcovJobProgress;
+
+LcovJobProgress::LcovJobProgress(QObject* parent /*= 0*/): QObject(parent),
+ m_numberOfFilesFound(0), m_numberOfFilesProcessed(0)
+{
+}
+
+LcovJobProgress::~LcovJobProgress()
+{
+}
+
+QString LcovJobProgress::statusName() const
+{
+ return i18nc("@info:progress", "Running <command>geninfo</command>");
+}
+
+void LcovJobProgress::start()
+{
+ emit showProgress(this, 0, 1, 0);
+}
+
+void LcovJobProgress::parseLines(const QStringList &lines)
+{
+ foreach (const QString& line, lines) {
+ if (line.contains(QRegExp("^Scanning .* for \\.gcda files"))) {
+ emit showMessage(this, i18nc("@info:progress", "Scanning for .gcda files"));
+ emit showProgress(this, 0, 1, 0);
+ } else if (line.contains(QRegExp("^Found \\d+ data files in .*"))) {
+ m_numberOfFilesFound = line.split(' ')[1].toInt();
+
+ emit showMessage(this, i18nc("@info:progress", "Processing .gcda files"));
+ emit showProgress(this, 0, 2, 1);
+ } else if (line.contains(QRegExp("^ERROR: no .gcda files found in .*"))) {
+ emit clearMessage(this);
+ emit showProgress(this, 0, 1, 1);
+ } else if (line.contains(QRegExp("^Processing .*"))) {
+ //Half total progress was scanning for .gcda files
+ int progress = 50;
+ progress += 50 * m_numberOfFilesProcessed / (float)m_numberOfFilesFound;
+
+ emit showProgress(this, 0, 100, progress);
+
+ m_numberOfFilesProcessed++;
+ } else if (line.contains("Finished .info-file creation")) {
+ emit showProgress(this, 0, 1, 1);
+ }
+ }
+}
+
+void LcovJobProgress::finish()
+{
+ emit clearMessage(this);
+ emit showProgress(this, 0, 1, 1);
+ emit hideProgress(this);
+}
+
+#include "lcovjobprogress.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui (revision 1522570)
@@ -0,0 +1,170 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>LCovPrefsWidget</class>
+ <widget class="QWidget" name="LCovPrefsWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>427</width>
+ <height>346</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <item>
+ <widget class="QGroupBox" name="pathsGroupBox">
+ <property name="title">
+ <string comment="@title:group">Paths</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QLabel" name="geninfoPathLabel">
+ <property name="text">
+ <string comment="@label:textbox">geninfo Executable:</string>
+ </property>
+ <property name="buddy">
+ <cstring>kcfg_geninfoPath</cstring>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KUrlRequester" name="kcfg_geninfoPath">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Select the geninfo executable to use for extracting visualization from coverage data</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="colorsGroupBox">
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">&lt;para&gt;Configuration for coverage report colors.&lt;/para&gt;
+
+&lt;para&gt;In the directory view of the coverage report, each directory coverage percentage is represented using a color.&lt;/para&gt;
+
+&lt;para&gt;The color associated to each percentage is taken from a color range, made up of several stop points. Stop points represent a color at a specific percentage.&lt;/para&gt;
+
+&lt;para&gt;A color range has two different and independent modes: discrete and gradient. In discrete type, all percentage values between the previous stop point and the current one have the color of the current one. In gradient type, the values are interpolated between the previous stop point's color and the current stop point's color.&lt;/para&gt;</string>
+ </property>
+ <property name="title">
+ <string comment="@title:group">Report colors</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2" stretch="1,0,10">
+ <item>
+ <widget class="QFrame" name="colorRangeBarFrame">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>0</width>
+ <height>30</height>
+ </size>
+ </property>
+ <property name="toolTip">
+ <string comment="@info:tooltip">Current color range</string>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">Representation of the color range to be used in the coverage report colors.</string>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::Box</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Plain</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="typeLabel">
+ <property name="text">
+ <string comment="@label:listbox">Type:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KComboBox" name="modeComboBox">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Color range type</string>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">Choose the type of color range to be used in the coverage report colors.</string>
+ </property>
+ <item>
+ <property name="text">
+ <string comment="@item:inlistbox Discrete color range type">Discrete</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string comment="@item:inlistbox Gradient color range type">Gradient</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QScrollArea" name="stopPointsScrollArea">
+ <property name="frameShape">
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Plain</enum>
+ </property>
+ <property name="widgetResizable">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>387</width>
+ <height>154</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout"/>
+ </widget>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KUrlRequester</class>
+ <extends>QFrame</extends>
+ <header>kurlrequester.h</header>
+ </customwidget>
+ <customwidget>
+ <class>KComboBox</class>
+ <extends>QComboBox</extends>
+ <header>kcombobox.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVANNOTATIONMODEL_H
+#define VERITAS_COVANNOTATIONMODEL_H
+
+#include <ktexteditor/annotationinterface.h>
+#include <QBrush>
+
+namespace Veritas {
+
+class CoveredFile;
+
+/*! Places annotations on text-views, which show the covered lines
+ * and their callcount */
+class AnnotationModel : public KTextEditor::AnnotationModel
+{
+ Q_OBJECT
+ public:
+ explicit AnnotationModel(Veritas::CoveredFile* file, QObject* parent=0);
+ virtual ~AnnotationModel();
+ virtual QVariant data(int line, Qt::ItemDataRole role) const;
+ void update();
+
+private:
+ Veritas::CoveredFile* m_file;
+ QBrush m_notInstrumented;
+ QBrush m_noCoverage;
+ QBrush m_covered;
+
+};
+
+}
+
+#endif // VERITAS_COVANNOTATIONMODEL_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.h (revision 1522570)
@@ -0,0 +1,44 @@
+/* KDevelop Project Settings
+ *
+ * Copyright 2006 Matt Rogers <mattr@kde.org>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef LCOVPREFS_H
+#define LCOVPREFS_H
+
+#include <kcmodule.h>
+
+#include <kurl.h>
+
+class LCovPrefs : public KCModule
+{
+ Q_OBJECT
+public:
+ LCovPrefs( QWidget *parent, const QVariantList &args );
+
+ virtual void save();
+ virtual void load();
+ virtual void defaults();
+
+public slots:
+
+ void changeState(bool changed);
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.h (revision 1522570)
@@ -0,0 +1,102 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_DISCRETECOLORRANGE_H
+#define VERITAS_COVERAGE_DISCRETECOLORRANGE_H
+
+#include <QColor>
+#include <QPair>
+#include <QVector>
+
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+typedef QPair<double, QColor> StopPoint;
+typedef QVector<StopPoint> StopPoints;
+
+/**
+ * A collection of colors associated with discrete, non-overlapping ranges from
+ * 0 to 1 (both included).
+ * A stop point associate the range from the previous stop point (or
+ * the beginning) to that point with a color. There is always at least one stop
+ * point, the one at position 1.
+ *
+ * Method colorAt(double) can be used to know the color at some position (no
+ * matter if there is a stop point or not at that position).
+ *
+ * Setting a red stop point at 0.333, a yellow stop point at 0.667 and a green
+ * stop point at 1, the following values would be returned by colorAt:
+ * - [0, 0.333] -> Red
+ * - (0.333, 0.667] -> Yellow
+ * - (0.667, 1] -> Green
+ */
+class VERITAS_COVERAGE_EXPORT DiscreteColorRange
+{
+public:
+
+ /**
+ * Creates a new DiscreteColorRange.
+ * The color at 1 is set to white, and there are no other stop points.
+ */
+ DiscreteColorRange();
+
+ /**
+ * Destroys this DiscreteColorRange.
+ */
+ virtual ~DiscreteColorRange();
+
+ /**
+ * Returns the color at the given position.
+ *
+ * @param position The position, in the range 0 to 1 (both included).
+ * @return The color.
+ */
+ QColor colorAt(double position) const;
+
+ /**
+ * Returns the stop points.
+ *
+ * @return The stop points.
+ */
+ StopPoints stopPoints() const;
+
+ /**
+ * Sets the stop points.
+ * The StopPoints must be in the range [0, 1], in ascending order, and they
+ * must contain only valid colors. The list must contain at least the stop
+ * point located at position 1.
+ *
+ * @param stopPoints The StopPoints to set.
+ */
+ void setStopPoints(const StopPoints& stopPoints);
+
+private:
+
+ /**
+ * The stop points.
+ */
+ StopPoints mStopPoints;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.cpp (revision 1522570)
@@ -0,0 +1,84 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "coveredfile.h"
+
+using Veritas::CoveredFile;
+
+CoveredFile::CoveredFile()
+ : m_nrofLines(0), m_nrofCoveredLines(0)
+{}
+
+CoveredFile::~CoveredFile()
+{
+}
+
+KUrl CoveredFile::url() const
+{
+ return m_sourceLoc;
+}
+
+void CoveredFile::setUrl(const KUrl& url)
+{
+ m_sourceLoc = url;
+}
+
+void CoveredFile::setCallCount(int line, int count)
+{
+ m_nrofCalls[line] = count;
+ m_reachableLines << line;
+ m_nrofLines = m_reachableLines.count();
+ if (count != 0) {
+ m_coveredLines << line;
+ m_nrofCoveredLines = m_coveredLines.count();
+ }
+}
+
+QSet<int> CoveredFile::coveredLines() const
+{
+ return m_coveredLines;
+}
+
+QSet<int> CoveredFile::reachableLines() const
+{
+ return m_reachableLines;
+}
+
+double CoveredFile::coverageRatio() const
+{
+ if (m_nrofLines == 0) return 0;
+ return 100*(double)m_nrofCoveredLines/(double)m_nrofLines;
+}
+
+int CoveredFile::sloc() const
+{
+ return m_nrofLines;
+}
+
+int CoveredFile::nrofCoveredLines() const
+{
+ return m_nrofCoveredLines;
+}
+
+QMap<int, int> CoveredFile::callCountMap() const
+{
+ return m_nrofCalls;
+}
+
+#include "coveredfile.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.cpp (revision 1522570)
@@ -0,0 +1,101 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "annotationmodel.h"
+#include "coveredfile.h"
+#include <KLocale>
+
+using Veritas::AnnotationModel;
+using Veritas::CoveredFile;
+
+
+AnnotationModel::AnnotationModel(CoveredFile* file, QObject* parent)
+ : m_notInstrumented(QBrush(Qt::BDiagPattern)),
+ m_noCoverage(QBrush(Qt::red)),
+ m_covered(QBrush(Qt::green))
+{
+ setParent(parent);
+ m_file = new CoveredFile;
+ m_file->setUrl(file->url());
+ QMap<int, int> cc = file->callCountMap();
+ QMapIterator<int, int> it(cc);
+ while(it.hasNext()) {
+ it.next();
+ m_file->setCallCount(it.key(), it.value());
+ }
+}
+
+AnnotationModel::~AnnotationModel()
+{
+ delete m_file;
+}
+
+/**
+ * data() is used to retrieve the information needed to present the
+ * annotation information from the annotation model. The provider
+ * should return useful information for the line and the data role.
+ *
+ * \param line the line for which the data is to be retrieved
+ * \param role the role to identify which kind of annotation is to be retrieved
+ *
+ * \returns a \ref QVariant that contains the data for the given role. The
+ * following roles are supported:
+ *
+ * \ref Qt::DisplayRole - a short display text to be placed in the border
+ * \ref Qt::TooltipRole - a tooltip information, longer text possible
+ * \ref Qt::BackgroundRole - a brush to be used to paint the background on the border
+ * \ref Qt::ForegroundRole - a brush to be used to paint the text on the border
+ */
+QVariant AnnotationModel::data(int line, Qt::ItemDataRole role) const
+{
+ Q_ASSERT(m_file);
+ line += 1; // annotationmodel counts from zero
+ int count;
+ switch(role) {
+ case Qt::DisplayRole: {
+ if (m_file->isReachable(line)) {
+ return QString::number(m_file->callCountMap()[line]);
+ }
+ break;
+ } case Qt::BackgroundRole: {
+ if (!m_file->isReachable(line)) {
+ return m_notInstrumented;
+ }
+ count = m_file->callCountMap()[line];
+ if (count == 0) return m_noCoverage;
+ else return m_covered;
+ break;
+ } case Qt::ToolTipRole : {
+ if (m_file->isReachable(line)) {
+ return QVariant(i18n("Number of times visited."));
+ } else {
+ return QVariant(i18n("Line not reachable."));
+ }
+ break;
+ } default: break;
+ }
+ return QVariant();
+}
+
+void AnnotationModel::update()
+{
+ emit reset();
+}
+
+#include "annotationmodel.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/annotationmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.cpp (revision 1522570)
@@ -0,0 +1,327 @@
+/* KDevelop coverage plugin
+ * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "reportmodel.h"
+#include "coveredfile.h"
+#include <KConfigGroup>
+#include <KGlobal>
+#include <KLocale>
+
+using Veritas::CoveredFile;
+using Veritas::ReportModel;
+using Veritas::ReportDirData;
+using Veritas::ReportDirItem;
+using Veritas::ReportFileItem;
+using Veritas::ReportValueItem;
+
+///////////////// ReportItems ////////////////////////////////////////////////
+
+ReportValueItem* ReportFileItem::coverageRatioItem() const
+{
+ return m_coverageRatioItem;
+}
+
+ReportValueItem* ReportFileItem::slocItem() const
+{
+ return m_slocItem;
+}
+
+ReportValueItem* ReportFileItem::nrofCoveredLinesItem() const
+{
+ return m_nrofCoveredLinesItem;
+}
+
+ReportFileItem::ReportFileItem(const KUrl& url)
+ : QStandardItem(url.fileName()),
+ m_fullUrl(url),
+ m_coverageRatioItem(0),
+ m_slocItem(0),
+ m_nrofCoveredLinesItem(0)
+{
+ setEditable(false);
+ setSelectable(true);
+ setCheckable(false);
+}
+
+void ReportFileItem::addCoverageData(CoveredFile* f)
+{
+ Q_ASSERT(f->url() == url());
+ if (!m_coverageRatioItem) {
+ m_coverageRatioItem = new ReportValueItem(f->coverageRatio());
+ m_slocItem = new ReportValueItem(f->sloc());
+ m_nrofCoveredLinesItem = new ReportValueItem(f->nrofCoveredLines());
+ m_coveredLines = f->coveredLines();
+ m_reachableLines = f->reachableLines();
+ } else {
+ m_coveredLines += f->coveredLines(); // set union
+ m_reachableLines += f->reachableLines();
+ int covered = m_coveredLines.count();
+ int reachable = m_reachableLines.count();
+ m_nrofCoveredLinesItem->setValue(covered);
+ m_slocItem->setValue(reachable);
+ m_coverageRatioItem->setValue(100*(double)covered/reachable);
+ }
+}
+
+KUrl ReportFileItem::url()
+{
+ return m_fullUrl;
+}
+
+ReportFileItem::~ReportFileItem()
+{}
+
+int ReportFileItem::type() const
+{
+ return ReportModel::File;
+}
+
+ReportDirData::ReportDirData()
+{
+ m_sloc = 0;
+ m_nrofCoveredLines = 0;
+}
+
+int ReportDirData::sloc() const
+{
+ return m_sloc;
+}
+
+int ReportDirData::nrofCoveredLines() const
+{
+ return m_nrofCoveredLines;
+}
+
+double ReportDirData::coverageRatio() const
+{
+ return (m_sloc == 0) ? 0 : 100*double(m_nrofCoveredLines)/double(m_sloc);
+}
+
+void ReportDirData::setSloc(int sloc)
+{
+ m_sloc = sloc;
+}
+
+void ReportDirData::setNrofCoveredLines(int nrof)
+{
+ m_nrofCoveredLines = nrof;
+}
+
+ReportDirItem::ReportDirItem(const QString& dir)
+ : QStandardItem(dir) {
+ setEditable(false);
+ setSelectable(true);
+ setCheckable(false);
+}
+
+void ReportDirItem::updateStats()
+{
+ int sloc = 0;
+ int nrofCoveredLines = 0;
+ QStandardItem* si;
+ ReportFileItem* rfi;
+ for (int row=0; row<rowCount(); row++) {
+ si = child(row, 0);
+ if (si->type() == ReportModel::File) {
+ rfi = static_cast<ReportFileItem*>(si);
+ nrofCoveredLines += rfi->nrofCoveredLinesItem()->value();
+ sloc += rfi->slocItem()->value();
+ }
+ }
+
+ m_reportDirData.setSloc(sloc);
+ m_reportDirData.setNrofCoveredLines(nrofCoveredLines);
+}
+
+ReportDirItem::~ReportDirItem()
+{}
+
+int ReportDirItem::type() const
+{
+ return ReportModel::Dir;
+}
+
+int ReportDirItem::sloc()
+{
+ return m_reportDirData.sloc();
+}
+
+int ReportDirItem::nrofCoveredLines()
+{
+ return m_reportDirData.nrofCoveredLines();
+}
+
+double ReportDirItem::coverageRatio()
+{
+ return m_reportDirData.coverageRatio();
+}
+
+const ReportDirData& ReportDirItem::reportDirData() const
+{
+ return m_reportDirData;
+}
+
+ReportValueItem::ReportValueItem(double value)
+{
+ setValue(value);
+ initProperties();
+}
+
+ReportValueItem::ReportValueItem(int value)
+{
+ setValue(value);
+ initProperties();
+}
+
+double ReportValueItem::value() const
+{
+ return m_value;
+}
+
+void ReportValueItem::setValue(double value)
+{
+ m_value = value;
+ setData(QString::number(value, 'f', 1), Qt::DisplayRole);
+}
+
+void ReportValueItem::setValue(int value)
+{
+ m_value = value;
+ setData(QString::number(value), Qt::DisplayRole);
+}
+
+void ReportValueItem::initProperties()
+{
+ setEditable(false);
+ setSelectable(false);
+ setCheckable(false);
+}
+
+ReportValueItem::~ReportValueItem()
+{}
+
+int ReportValueItem::type() const
+{
+ return ReportModel::Value;
+}
+
+///////////////// ReportModel ////////////////////////////////////////////////
+
+ReportModel::ReportModel(QObject* parent)
+ : QStandardItemModel(parent)
+{
+ QStringList headers;
+ headers << i18nc("@title:column Coverage report column", "source")
+ << i18nc("@title:column Coverage report column", "coverage")
+ << i18nc("@title:column Coverage report column", "visited")
+ << i18nc("@title:column Coverage report column", "SLOC");
+ setHorizontalHeaderLabels(headers);
+
+ KConfigGroup group = KGlobal::config()->group("Code Coverage");
+ if (group.hasGroup("Color Range")) {
+ m_colorRange.load(group.group("Color Range"));
+ } else {
+ m_colorRange.setMode(ColorRange::Discrete);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0.25, QColor("black")));
+ stopPoints.append(StopPoint(0.50, QColor("red")));
+ stopPoints.append(StopPoint(0.75, QColor("orange")));
+ stopPoints.append(StopPoint(1, QColor("green")));
+ m_colorRange.setStopPoints(stopPoints);
+ }
+}
+
+void ReportModel::setRootDirectory(const KUrl& root)
+{
+ m_root = root;
+}
+
+ReportModel::~ReportModel()
+{}
+
+QVariant ReportModel::data(const QModelIndex& i, int role) const
+{
+ if (role != ReportModel::SortRole) {
+ return QStandardItemModel::data(i, role);
+ }
+ // SortRole
+ QStandardItem* item = itemFromIndex(i);
+ if (item->type() == ReportModel::Value) {
+ ReportValueItem* rvi = static_cast<ReportValueItem*>(item);
+ return QVariant(rvi->value());
+ } else { // sort on display value
+ return QStandardItemModel::data(i, Qt::DisplayRole);
+ }
+}
+
+QList<QStandardItem*> ReportModel::createFileRow(CoveredFile* f)
+{
+ ReportFileItem* file = new ReportFileItem(f->url()); // do these get cleaned?
+ m_files.insert(f->url(), file);
+ file->addCoverageData(f);
+ QList<QStandardItem*> row;
+ row << file << file->coverageRatioItem() << file->nrofCoveredLinesItem() << file->slocItem();
+ return row;
+}
+
+// slot called when new CoveredFile has been parsed
+void ReportModel::addCoverageData(CoveredFile* f)
+{
+ QString dir = f->url().directory();
+ if (!m_dirs.contains(dir)) appendDir(dir);
+ ReportDirItem* dirItem = m_dirs[dir];
+ if (!m_files.contains(f->url())) {
+ dirItem->appendRow(createFileRow(f));
+ } else {
+ m_files[f->url()]->addCoverageData(f);
+ }
+ dirItem->updateStats();
+ updateColoredCoverageColumn(dirItem);
+ }
+
+// helper for addCoverageData
+void ReportModel::appendDir(const QString& dir)
+{
+ ReportDirItem* dirItem = new ReportDirItem(dir);
+ m_dirs[dir] = dirItem;
+ QStandardItem *root = invisibleRootItem();
+ QList<QStandardItem*> row;
+ row << dirItem;
+ root->appendRow(row);
+}
+
+// helper for addCoverageData
+void ReportModel::updateColoredCoverageColumn(ReportDirItem* dir)
+{
+ QModelIndex i = dir->index();
+ i = i.sibling(i.row(), i.column()+1);
+ QStandardItem* it = itemFromIndex(i);
+ QBrush b = brushForCoverage(dir->coverageRatio());
+ it->setBackground(b);
+ it->setForeground(b);
+ it->setData(dir->coverageRatio(), Qt::DisplayRole);
+}
+
+QBrush ReportModel::brushForCoverage(double percent)
+{
+ return QBrush(m_colorRange.colorAt(percent / 100));
+}
+
+#include "reportmodel.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.h (revision 1522570)
@@ -0,0 +1,56 @@
+/* KDevelop coverage plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_COVOUTPUTMODEL_H
+#define VERITAS_COVERAGE_COVOUTPUTMODEL_H
+
+#include <QStandardItemModel>
+#include <outputview/ioutputviewmodel.h>
+
+class QModelIndex;
+
+namespace Veritas
+{
+
+/*! Used by the lcovjob */
+class CovOutputModel : public QStandardItemModel, public KDevelop::IOutputViewModel
+{
+ Q_OBJECT
+
+public:
+ explicit CovOutputModel(QObject *parent);
+ ~CovOutputModel();
+
+ void activate(const QModelIndex &idx);
+ QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
+ QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
+ QVariant data(const QModelIndex& index, int role) const;
+
+public Q_SLOTS:
+ void appendOutputs(const QStringList &lines);
+ void appendErrors(const QStringList &lines);
+ void slotCompleted();
+ void slotFailed();
+};
+
+}
+
+#endif // VERITAS_COVERAGE_COVOUTPUTMODEL_h
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp (revision 1522570)
@@ -0,0 +1,63 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "reportproxymodel.h"
+#include "reportmodel.h"
+
+using Veritas::ReportModel;
+using Veritas::ReportProxyModel;
+
+ReportProxyModel::ReportProxyModel(QObject* parent)
+ : QSortFilterProxyModel(parent), m_state(DirView)
+{
+ setDynamicSortFilter(true);
+ setSortRole(ReportModel::SortRole);
+}
+
+ReportProxyModel::~ReportProxyModel()
+{}
+
+
+bool ReportProxyModel::filterAcceptsColumn(int source_column, const QModelIndex & source_parent) const
+{
+ Q_UNUSED(source_parent);
+ switch(m_state) {
+ case DirView: {
+ return source_column == 0 || source_column == 1;
+ }case FileView: {
+ return true;
+ } default: {
+ Q_ASSERT_X(0, "filterAcceptsColumn", "Serious corruption, impossible m_state value.");
+ return false;
+ }}
+}
+
+void ReportProxyModel::setFileViewState()
+{
+ m_state = ReportProxyModel::FileView;
+}
+
+void ReportProxyModel::setDirViewState()
+{
+ m_state = ReportProxyModel::DirView;
+}
+
+
+#include "reportproxymodel.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.h (revision 1522570)
@@ -0,0 +1,191 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_COLORRANGE_H
+#define VERITAS_COVERAGE_COLORRANGE_H
+
+#include <QColor>
+#include <QPair>
+#include <QVector>
+
+#include "coverageexport.h"
+
+#include "discretecolorrange.h"
+#include "gradientcolorrange.h"
+
+class KConfigGroup;
+
+namespace Veritas
+{
+
+typedef QPair<double, QColor> StopPoint;
+typedef QVector<StopPoint> StopPoints;
+
+/**
+ * Colors associated with subranges or points in range 0 to 1 (both included).
+ * ColorRange has two independent modes: discrete and gradient. In discrete
+ * mode, each color is associated with a subrange of the full range. In gradient
+ * mode, each color is associated with a point, and the other points are
+ * calculated as a gradient between the set points. For further information
+ * about each mode, see the documentation of DiscreteColorRange and
+ * GradientColorRange.
+ *
+ * The changes made in each mode doesn't affect those made in the other mode.
+ * Also note that depending on the current mode, the semantics of the stop
+ * points change a bit, as discrete mode uses 1 stop point less than gradient
+ * mode, and in discrete mode they represent subranges and in gradient mode just
+ * points.
+ *
+ * A ColorRange can be loaded from and saved to a KConfigurationGroup.
+ *
+ * @see DiscreteColorRange
+ * @see GradientColorRange
+ */
+class VERITAS_COVERAGE_EXPORT ColorRange
+{
+public:
+
+ enum Mode {
+ Gradient = 0,
+ Discrete
+ };
+
+ /**
+ * Creates a new ColorRange.
+ * Default mode is Discrete.
+ */
+ ColorRange();
+
+ /**
+ * Destroys this ColorRange.
+ */
+ virtual ~ColorRange();
+
+ /**
+ * Returns the current mode of this ColorRange.
+ *
+ * @return The current mode of this ColorRange.
+ */
+ Mode mode() const;
+
+ /**
+ * Sets the current mode of this ColorRange.
+ *
+ * @param mode The current mode of this ColorRange.
+ */
+ void setMode(Mode mode);
+
+ /**
+ * Returns the color for the current mode at the given position.
+ *
+ * @param position The position, in the range 0 to 1 (both included).
+ * @return The color.
+ */
+ QColor colorAt(double position) const;
+
+ /**
+ * Returns the stop points for the current mode.
+ *
+ * @return The stop points.
+ */
+ StopPoints stopPoints() const;
+
+ /**
+ * Sets the stop points for the current mode.
+ *
+ * @param stopPoints The StopPoints to set.
+ * @see DiscreteColorRange::setStopPoints(const StopPoints&)
+ * @see GradientColorRange::setStopPoints(const StopPoints&)
+ */
+ void setStopPoints(const StopPoints& stopPoints);
+
+ /**
+ * Loads this ColorRange from the given configuration group.
+ *
+ * @param group The configuration group to load this ColorRange from.
+ * @see save(KConfigGroup&)
+ */
+ void load(const KConfigGroup& group);
+
+ /**
+ * Saves this ColorRange to the given configuration group.
+ * The configuration group is expected to be empty. Also note that no sync
+ * is made, only the needed groups and entries are added.
+ *
+ * The current mode of this ColorRange is saved, as a QString, in "Mode"
+ * entry (with values "Discrete" and "Gradient"). The StopPoints of discrete
+ * mode are saved in a group called "Discrete", and the StopPoints of
+ * gradient mode are saved in a group called "Gradient". Note that both
+ * modes are saved, no matter which is the current mode.
+ *
+ * @param group The empty configuration group to save this ColorRange to.
+ * @see saveStopPoints(const KConfigGroup&, const StopPoints&)
+ */
+ void save(KConfigGroup& group);
+
+ /**
+ * Check whether this ColorRange is equal to the given one or not.
+ *
+ * @param colorRange The ColorRange to compare to.
+ * @return True if both ColorRange are equal, false otherwise.
+ */
+ bool operator==(const ColorRange& colorRange) const;
+
+ /**
+ * Check whether this ColorRange is different to the given one or not.
+ *
+ * @param colorRange The ColorRange to compare to.
+ * @return True if both ColorRange are different, false otherwise.
+ */
+ bool operator!=(const ColorRange& colorRange) const;
+
+private:
+
+ Mode mMode;
+ DiscreteColorRange mDiscreteColorRange;
+ GradientColorRange mGradientColorRange;
+
+ /**
+ * Loads the StopPoints stored in the given configuration group.
+ *
+ * @param group The configuration group to load the StopPoints from.
+ * @return The loaded StopPoints.
+ * @see saveStopPoints(const KConfigGroup&, const StopPoints&)
+ */
+ StopPoints loadStopPoints(const KConfigGroup& group) const;
+
+ /**
+ * Saves the StopPoints in the given configuration group.
+ * The number of StopPoints are saved, as an integer, in
+ * "NumberOfStopPoints" entry. For each StopPoint, to entries are saved:
+ * "StopPointXPosition", a real, with the position of the StopPoint, and
+ * "StopPointXColor", a QColor, with the color of the StopPoint.
+ * In both names, the X refer to the index of the StopPoint, indexed at 0.
+ *
+ * @param group The configuration group to save the StopPoints to.
+ * @param stopPoints The StopPoints to save.
+ */
+ void saveStopPoints(KConfigGroup& group,
+ const StopPoints& stopPoints) const;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageexport.h (revision 1522570)
@@ -0,0 +1,42 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2004 Jarosław Staniek <staniek@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef VERITAS_COVERAGE_EXPORT_H
+#define VERITAS_COVERAGE_EXPORT_H
+
+#include <kdemacros.h>
+
+#ifndef VERITAS_COVERAGE_EXPORT
+# ifdef MAKE_KDEVVERITASCOVERAGE_LIB
+# define VERITAS_COVERAGE_EXPORT KDE_EXPORT
+# else
+# define VERITAS_COVERAGE_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#ifdef MAKE_KCM_KDEV_LCOVSETTINGS_LIB
+# undef VERITAS_COVERAGE_EXPORT
+# define VERITAS_COVERAGE_EXPORT
+#endif
+
+#endif // VERITAS_COVERAGE_EXPORT_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coverageexport.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.cpp (revision 1522570)
@@ -0,0 +1,72 @@
+/* KDevelop Covergage lcov settings
+*
+* Copyright 2009 Andreas Pakulat <apaku@gmx.de>
+*
+* 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+#include "lcovprefs.h"
+
+#include <kgenericfactory.h>
+#include <kaboutdata.h>
+
+#include "lcovconfig.h"
+#include "lcovprefswidget.h"
+
+K_PLUGIN_FACTORY(LCovPrefsFactory, registerPlugin<LCovPrefs>();)
+K_EXPORT_PLUGIN(LCovPrefsFactory(KAboutData("kcm_kdev_lcovsettings", "kdevelop", ki18n("LCov Settings"), "0.1")))
+
+LCovPrefs::LCovPrefs( QWidget *parent, const QVariantList &args )
+ : KCModule( LCovPrefsFactory::componentData(), parent, args )
+{
+
+ QVBoxLayout * l = new QVBoxLayout( this );
+ QWidget* w = new LCovPrefsWidget(LCovSettings::self(), parent);
+ l->addWidget( w );
+
+ connect(w, SIGNAL(changed(bool)), this, SLOT(changeState(bool)));
+ connect(LCovSettings::self(), SIGNAL(colorRangeChanged()),
+ w, SLOT(reloadColorRange()));
+
+ addConfig( LCovSettings::self(), w );
+
+ load();
+}
+
+void LCovPrefs::save()
+{
+ LCovSettings::self()->writeConfig();
+ KCModule::save();
+}
+
+void LCovPrefs::load()
+{
+ LCovSettings::self()->readConfig();
+ KCModule::load();
+}
+
+void LCovPrefs::defaults()
+{
+ LCovSettings::self()->setDefaults();
+ KCModule::defaults();
+}
+
+void LCovPrefs::changeState(bool changed)
+{
+ unmanagedWidgetChangeState(changed);
+}
+
+#include "lcovprefs.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefs.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp (revision 1522570)
@@ -0,0 +1,88 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "gradientcolorrange.h"
+
+using Veritas::GradientColorRange;
+using Veritas::StopPoints;
+using Veritas::StopPoint;
+
+GradientColorRange::GradientColorRange()
+{
+ mStopPoints.append(StopPoint(0, QColor(Qt::black)));
+ mStopPoints.append(StopPoint(1, QColor(Qt::white)));
+}
+
+GradientColorRange::~GradientColorRange()
+{
+}
+
+QColor GradientColorRange::colorAt(double position) const
+{
+ Q_ASSERT(position >= 0 && position <= 1);
+
+ for (int i=0; i<stopPoints().size(); i++) {
+ if (position == stopPoints()[i].first) {
+ return stopPoints()[i].second;
+ } else if (position < stopPoints()[i+1].first) {
+ return interpolateColor(stopPoints()[i], stopPoints()[i+1],
+ position);
+ }
+ }
+
+ return mStopPoints.last().second;
+}
+
+StopPoints GradientColorRange::stopPoints() const
+{
+ return mStopPoints;
+}
+
+void GradientColorRange::setStopPoints(const StopPoints& stopPoints)
+{
+ Q_ASSERT(stopPoints.size() >= 2);
+ Q_ASSERT(stopPoints.first().first == 0);
+ Q_ASSERT(stopPoints.last().first == 1);
+
+ mStopPoints = stopPoints;
+}
+
+QColor GradientColorRange::interpolateColor(const StopPoint& begin,
+ const StopPoint& end,
+ double position) const
+{
+ double beginPosition = begin.first;
+ double endPosition = end.first;
+ double width = endPosition - beginPosition;
+
+ double relativePosition = (position - beginPosition) / width;
+
+ QColor beginColor = begin.second;
+ QColor endColor = end.second;
+
+ QColor interpolatedColor;
+ interpolatedColor.setRed(qRound(beginColor.red() +
+ (endColor.red() - beginColor.red()) * relativePosition));
+ interpolatedColor.setGreen(qRound(beginColor.green() +
+ (endColor.green() - beginColor.green()) * relativePosition));
+ interpolatedColor.setBlue(qRound(beginColor.blue() +
+ (endColor.blue() - beginColor.blue()) * relativePosition));
+
+ return interpolatedColor;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp (revision 1522570)
@@ -0,0 +1,63 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "discretecolorrange.h"
+
+using Veritas::DiscreteColorRange;
+using Veritas::StopPoints;
+
+DiscreteColorRange::DiscreteColorRange()
+{
+ mStopPoints.append(StopPoint(1, QColor(Qt::white)));
+}
+
+DiscreteColorRange::~DiscreteColorRange()
+{
+}
+
+QColor DiscreteColorRange::colorAt(double position) const
+{
+ Q_ASSERT(position >= 0 && position <= 1);
+
+ if (position >= 0 && position <= mStopPoints[0].first) {
+ return mStopPoints[0].second;
+ }
+
+ for (int i=1; i<mStopPoints.size()-1; ++i) {
+ if (position > mStopPoints[i-1].first &&
+ position <= mStopPoints[i].first) {
+ return mStopPoints[i].second;
+ }
+ }
+
+ return mStopPoints.last().second;
+}
+
+StopPoints DiscreteColorRange::stopPoints() const
+{
+ return mStopPoints;
+}
+
+void DiscreteColorRange::setStopPoints(const StopPoints& stopPoints)
+{
+ Q_ASSERT(stopPoints.size() >= 1);
+ Q_ASSERT(stopPoints.last().first == 1);
+
+ mStopPoints = stopPoints;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.cpp (revision 1522570)
@@ -0,0 +1,213 @@
+/***************************************************************************
+ * Copyright 2005 Benjamin Meyer <ben@meyerhome.net> *
+ * Copyright 2006 Alexander Dymo <adymo@kdevelop.org> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "drilldownview.h"
+
+#include <QSortFilterProxyModel>
+#include <QHeaderView>
+#include <QAbstractScrollArea>
+
+using Veritas::DrillDownView;
+
+DrillDownView::DrillDownView(QWidget *parent)
+ : QTableView(parent)
+{
+ setFrameShape((QFrame::Shape)(QFrame::StyledPanel | QFrame::Raised));
+ setGridStyle(Qt::SolidLine);
+ setShowGrid(true);
+
+ connect(&animation, SIGNAL(frameChanged(int)), this, SLOT(slide(int)));
+ connect(&animation, SIGNAL(finished()), this, SLOT(update()));
+ animation.setDuration(125);
+ setAlternatingRowColors(true); // hmz
+ verticalHeader()->hide();
+ setSortingEnabled(true);
+ horizontalHeader()->resizeSection(0, width());
+
+ setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+
+ resizeDirStateColumns();
+
+ setSelectionBehavior(QAbstractItemView::SelectRows);
+}
+
+DrillDownView::~DrillDownView()
+{}
+
+void DrillDownView::paintEvent(QPaintEvent *event)
+{
+ if (animation.state() != QTimeLine::Running) {
+ QTableView::paintEvent(event);
+ return;
+ }
+
+ QPainter painter(viewport());
+ if (animation.direction() == QTimeLine::Backward) {
+ painter.drawPixmap(-animation.currentFrame(), 0, newView);
+ painter.drawPixmap(-animation.currentFrame() + animation.endFrame(), 0, oldView);
+ } else {
+ painter.drawPixmap(-animation.currentFrame(), 0, oldView);
+ painter.drawPixmap(-animation.currentFrame() + animation.endFrame(), 0, newView);
+ }
+}
+
+void DrillDownView::slide(int x)
+{
+ viewport()->scroll(lastPosition - x, 0);
+ lastPosition = x;
+}
+
+void DrillDownView::keyPressEvent(QKeyEvent *event)
+{
+ QModelIndex current = currentIndex();
+ if (isBusy()) {
+ return; //eat event if animation is running
+ }
+ if (!(current.isValid() || event->key() == Qt::Key_Left)) {
+ QTableView::keyPressEvent(event);
+ return;
+ }
+ QSortFilterProxyModel* p = static_cast<QSortFilterProxyModel*>(model());
+ QAbstractItemModel* m = p->sourceModel();
+ QModelIndex srcIndex;
+ switch(event->key()) {
+ case Qt::Key_Right:
+ current = current.sibling(current.row(), 0);
+ srcIndex = p->mapToSource(current);
+ if (m->hasChildren(srcIndex)) slideRight(current);
+ return;
+ break;
+ case Qt::Key_Left:
+ slideLeft();
+ return;
+ break;
+ case Qt::Key_Return:
+ emit returnPressed(current);
+ break;
+ default: break;
+ }
+ QTableView::keyPressEvent(event);
+}
+
+void DrillDownView::resizeFileStateColumns()
+{
+ QHeaderView* header = horizontalHeader();
+ header->resizeSection(1, 75);
+ header->resizeSection(2, 75);
+ header->resizeSection(3, 75);
+ header->resizeSection(0, (maxWidth()-225 > 75) ? maxWidth()-225 : 75);
+}
+
+int DrillDownView::maxWidth() const
+{
+ QScrollBar* vertbar = verticalScrollBar();
+ Q_ASSERT(vertbar);
+ int width = maximumViewportSize().width();
+ if (vertbar->isVisible()) {
+ width = width - vertbar->width();
+ }
+ return width - 5;
+}
+
+void DrillDownView::resizeDirStateColumns()
+{
+ horizontalHeader()->resizeSection(1, 20);
+ horizontalHeader()->resizeSection(0, maxWidth() - 20);
+}
+
+void DrillDownView::slideRight(const QModelIndex& current)
+{
+ if (current == rootIndex()) return;
+ if (model()->canFetchMore(current)) {
+ model()->fetchMore(current);
+ return;
+ }
+ setUpdatesEnabled(false);
+
+ leftSelection = selectionModel()->selection();
+ selectionModel()->clear();
+
+ setRootIndex(current);
+
+ animateSlide(Qt::Key_Right);
+ resizeFileStateColumns();
+ setUpdatesEnabled(true);
+ emit completedSlideRight();
+ }
+
+void DrillDownView::slideLeft()
+{
+ QModelIndex current = currentIndex();
+ QModelIndex root = rootIndex();
+ if (!root.isValid()) return;
+ setUpdatesEnabled(false);
+
+ setRootIndex(root.parent());
+
+ selectionModel()->clear();
+ selectionModel()->select(leftSelection, QItemSelectionModel::Select);
+ selectionModel()->setCurrentIndex(root, QItemSelectionModel::NoUpdate);
+
+ animateSlide(Qt::Key_Left);
+ resizeDirStateColumns();
+ setUpdatesEnabled(true);
+ emit completedSlideLeft();
+}
+
+void DrillDownView::animateSlide(int moveDirection)
+{
+ executeDelayedItemsLayout();
+ // Force the hiding/showing of scrollbars
+ setVerticalScrollBarPolicy(verticalScrollBarPolicy());
+ newView = QPixmap::grabWidget(viewport());
+ setUpdatesEnabled(true);
+ int length = qMax(oldView.width(), newView.width());
+ lastPosition = moveDirection == Qt::Key_Left ? length : 0;
+ animation.setFrameRange(0, length);
+ animation.stop();
+ animation.setDirection(moveDirection == Qt::Key_Right ?
+ QTimeLine::Forward : QTimeLine::Backward);
+ animation.start();
+}
+
+//TODO Since Qt 4.4.2, clicking on an empty space of the QTableView clears
+//the selection. Remove this whole method when required Qt version for
+//KDevelop is >= 4.4.2
+void DrillDownView::mousePressEvent(QMouseEvent* event)
+{
+ if (selectionModel() && !indexAt(event->pos()).isValid()) {
+ selectionModel()->clearSelection();
+ }
+ QTableView::mousePressEvent(event);
+}
+
+bool DrillDownView::isBusy()
+{
+ return animation.state() == QTimeLine::Running;
+}
+
+void DrillDownView::setRootIndex(const QModelIndex &index)
+{
+ QTableView::setRootIndex(index);
+ emit rootIndexChanged(index);
+}
+
+#include "drilldownview.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/drilldownview.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp (revision 1522570)
@@ -0,0 +1,87 @@
+/* KDevelop coverage plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "covoutputmodel.h"
+
+#include <QModelIndex>
+#include <KGlobalSettings>
+#include <interfaces/icore.h>
+
+using Veritas::CovOutputModel;
+
+CovOutputModel::CovOutputModel(QObject *parent)
+ : QStandardItemModel(parent)
+{}
+
+CovOutputModel::~CovOutputModel()
+{}
+
+QModelIndex CovOutputModel::nextHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+QModelIndex CovOutputModel::previousHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+
+QVariant CovOutputModel::data(const QModelIndex& index, int role) const
+{
+ if (role != Qt::FontRole) {
+ return QStandardItemModel::data(index, role);
+ } else {
+ return KGlobalSettings::fixedFont();
+ }
+}
+
+void CovOutputModel::activate(const QModelIndex &idx)
+{
+ Q_UNUSED(idx);
+}
+
+void CovOutputModel::appendOutputs(const QStringList &lines)
+{
+ Q_UNUSED(lines);
+ // stdout gets the lcov output, which contains the useful stuff
+ // so do nothing here. stderr gets status messages
+}
+
+void CovOutputModel::appendErrors(const QStringList &lines)
+{
+ foreach(const QString& line, lines) {
+ appendRow(new QStandardItem(line));
+ }
+}
+
+void CovOutputModel::slotCompleted()
+{
+}
+
+void CovOutputModel::slotFailed()
+{
+ appendRow(new QStandardItem("Failed"));
+}
+
+#include "covoutputmodel.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.cpp (revision 1522570)
@@ -0,0 +1,152 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "colorrange.h"
+
+#include <KConfigGroup>
+
+using Veritas::ColorRange;
+using Veritas::StopPoints;
+
+ColorRange::ColorRange()
+{
+ mMode = Discrete;
+}
+
+ColorRange::~ColorRange()
+{
+}
+
+ColorRange::Mode ColorRange::mode() const
+{
+ return mMode;
+}
+
+void ColorRange::setMode(Mode mode)
+{
+ mMode = mode;
+}
+
+QColor ColorRange::colorAt(double position) const
+{
+ if (mMode == Discrete) {
+ return mDiscreteColorRange.colorAt(position);
+ }
+
+ return mGradientColorRange.colorAt(position);
+}
+
+StopPoints ColorRange::stopPoints() const
+{
+ if (mMode == Discrete) {
+ return mDiscreteColorRange.stopPoints();
+ }
+
+ return mGradientColorRange.stopPoints();
+}
+
+void ColorRange::setStopPoints(const StopPoints& stopPoints)
+{
+ if (mMode == Discrete) {
+ mDiscreteColorRange.setStopPoints(stopPoints);
+ } else {
+ mGradientColorRange.setStopPoints(stopPoints);
+ }
+}
+
+void ColorRange::load(const KConfigGroup& group)
+{
+ if (group.readEntry("Mode") == "Gradient") {
+ mMode = Gradient;
+ } else {
+ mMode = Discrete;
+ }
+
+ mDiscreteColorRange.setStopPoints(loadStopPoints(group.group("Discrete")));
+ mGradientColorRange.setStopPoints(loadStopPoints(group.group("Gradient")));
+}
+
+void ColorRange::save(KConfigGroup& group)
+{
+ if (mMode == Gradient) {
+ group.writeEntry("Mode", "Gradient");
+ } else {
+ group.writeEntry("Mode", "Discrete");
+ }
+
+ KConfigGroup discreteGroup(&group, "Discrete");
+ saveStopPoints(discreteGroup, mDiscreteColorRange.stopPoints());
+
+ KConfigGroup gradientGroup(&group, "Gradient");
+ saveStopPoints(gradientGroup, mGradientColorRange.stopPoints());
+}
+
+bool ColorRange::operator==(const ColorRange& colorRange) const
+{
+ if (mMode != colorRange.mMode) {
+ return false;
+ }
+
+ if (mDiscreteColorRange.stopPoints() !=
+ colorRange.mDiscreteColorRange.stopPoints()) {
+ return false;
+ }
+
+ if (mGradientColorRange.stopPoints() !=
+ colorRange.mGradientColorRange.stopPoints()) {
+ return false;
+ }
+
+ return true;
+}
+
+bool ColorRange::operator!=(const ColorRange& colorRange) const
+{
+ return !(*this == colorRange);
+}
+
+StopPoints ColorRange::loadStopPoints(const KConfigGroup& group) const
+{
+ StopPoints stopPoints;
+
+ int numberOfStopPoints = group.readEntry("NumberOfStopPoints", 0);
+ for (int i=0; i<numberOfStopPoints; ++i) {
+ QString baseName = QString("StopPoint") + QString::number(i);
+
+ StopPoint stopPoint;
+ stopPoint.first = group.readEntry(baseName + "Position", 0.0);
+ stopPoint.second = group.readEntry(baseName + "Color", QColor());
+
+ stopPoints.append(stopPoint);
+ }
+
+ return stopPoints;
+}
+
+void ColorRange::saveStopPoints(KConfigGroup& group,
+ const StopPoints& stopPoints) const
+{
+ group.writeEntry("NumberOfStopPoints", stopPoints.size());
+ for (int i=0; i<stopPoints.size(); ++i) {
+ QString baseName = QString("StopPoint") + QString::number(i);
+
+ group.writeEntry(baseName + "Position", stopPoints[i].first);
+ group.writeEntry(baseName + "Color", stopPoints[i].second);
+ }
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrange.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.h (revision 1522570)
@@ -0,0 +1,71 @@
+/* KDevelop coverage plugin
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVEREDFILE_H
+#define VERITAS_COVEREDFILE_H
+
+#include "coverageexport.h"
+
+#include <QList>
+#include <KUrl>
+#include <QMap>
+#include <QSet>
+
+namespace Veritas
+{
+
+/*! Prime value class, holds coverage data for a file. This
+ * includes the covered lines, uncovered ones and callcounts */
+class VERITAS_COVERAGE_EXPORT CoveredFile : public QObject
+{
+Q_OBJECT
+public:
+ CoveredFile();
+ virtual ~CoveredFile();
+
+ KUrl url() const;
+ void setUrl(const KUrl& url);
+ void setCallCount(int line, int count);
+ /*! line coverage percentage */
+ double coverageRatio() const;
+ /*! number of source lines of code */
+ int sloc() const;
+
+ /*! number of visited lines of code */
+ int nrofCoveredLines() const;
+
+ QMap<int, int> callCountMap() const;
+ QSet<int> coveredLines() const;
+ QSet<int> reachableLines() const;
+ inline bool isReachable(int line) const {
+ return m_reachableLines.contains(line);
+ }
+
+private:
+ QMap<int, int> m_nrofCalls; // { line x nrofcalls }
+ int m_nrofLines;
+ int m_nrofCoveredLines;
+ KUrl m_sourceLoc;
+ QSet<int> m_coveredLines;
+ QSet<int> m_reachableLines;
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/coveredfile.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp (revision 1522570)
@@ -0,0 +1,64 @@
+/*
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+/*! KDevelop4 gcov coverage tool example.
+usage:
+1/ Boot up KDevelop4
+2/ Project -> Open -> prime.kdev4
+3/ Build. Notice the gcov data file `main.gcno'
+ in the project's directory
+4/ Run `is_prime'. Notice `main.gcda'
+5/ Add the coverage toolview. View -> Add Tool View -> Coverage
+6/ Enter the prime-projects root directory under 'Build Path:'
+7/ Hit the run coverage button, next to the breadcrumb widget
+8/ Use left and right arrow to navigate the report
+9/ Close this file
+10/ Double click 'main.cpp' to view coverage annotations
+*/
+
+#include <stdio.h>
+bool is_prime(long number);
+
+int main(int,char**)
+{
+ if (is_prime(2111*4111)) {
+ printf("not covered, not prime.\n");
+ }
+ if (is_prime(29)) {
+ printf("covered, 29 is prime.\n");
+ }
+ return 0;
+}
+
+const bool g_primes[10] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0};
+bool is_prime(long number)
+{
+ if (number < 10) {
+ return g_primes[number];
+ }
+ if (number % 2 == 0) {
+ return false;
+ }
+ for(long m = 3; m*m <= number; m += 2) {
+ if (number % m == 0) {
+ return false;
+ }
+ }
+ return true;
+}
+
+//krazy:skip
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4 (revision 1522570)
@@ -0,0 +1,3 @@
+[Project]
+Name=prime
+Manager=KDevCustomMakeManager
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4 (revision 1522570)
@@ -0,0 +1,2 @@
+[Buildset]
+Number of Builditems=0
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/Makefile
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/Makefile (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/examples/prime/Makefile (revision 1522570)
@@ -0,0 +1,8 @@
+is_prime: main.o
+ g++ -fprofile-arcs -ftest-coverage -o $@ $^
+
+main.o: main.cpp
+ g++ -fprofile-arcs -ftest-coverage -O0 -c $^
+
+clean:
+ @rm -v is_prime *.o *.gcno *.gcda *~
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.ui (revision 1522570)
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>StopPointWidget</class>
+ <widget class="QWidget" name="StopPointWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>425</width>
+ <height>43</height>
+ </rect>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">A stop point in the current color range type.</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,1,0,0,0,0">
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QLabel" name="colorLabel">
+ <property name="text">
+ <string comment="@label:chooser The color to be used">Color:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KColorButton" name="colorChooser">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Color for this stop point</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="percentageLabel">
+ <property name="text">
+ <string comment="@label:spinbox">For percentage:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDoubleSpinBox" name="percentageSpinBox">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Percentage for this stop point</string>
+ </property>
+ <property name="maximum">
+ <double>100.000000000000000</double>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QToolButton" name="addButton">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Add new stop point</string>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">Adds a new stop point after this one to the current color range type.</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QToolButton" name="removeButton">
+ <property name="toolTip">
+ <string comment="@info:tooltip">Remove this stop point</string>
+ </property>
+ <property name="whatsThis">
+ <string comment="@info:whatsthis">Removes this stop point from the current color range type.</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KColorButton</class>
+ <extends>QPushButton</extends>
+ <header>kcolorbutton.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp (revision 1522570)
@@ -0,0 +1,133 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "stoppointwidget.h"
+#include "ui_stoppointwidget.h"
+
+#include <KIcon>
+
+using Veritas::ColorRange;
+using Veritas::StopPoint;
+
+StopPointWidget::StopPointWidget(QWidget* parent): QWidget(parent)
+{
+ mIndex = -1;
+ mMode = ColorRange::Discrete;
+
+ mUi = new Ui::StopPointWidget();
+ mUi->setupUi(this);
+
+ mUi->addButton->setIcon(KIcon("list-add"));
+ mUi->removeButton->setIcon(KIcon("list-remove"));
+
+ connect(mUi->colorChooser, SIGNAL(changed(QColor)),
+ this, SLOT(changeColor(QColor)));
+ connect(mUi->percentageSpinBox, SIGNAL(valueChanged(double)),
+ this, SLOT(changePosition(double)));
+ connect(mUi->addButton, SIGNAL(clicked(bool)),
+ this, SLOT(addStopPointAfter()));
+ connect(mUi->removeButton, SIGNAL(clicked(bool)),
+ this, SLOT(removeStopPoint()));
+}
+
+StopPointWidget::~StopPointWidget()
+{
+ delete mUi;
+}
+
+void StopPointWidget::setStopPoint(const StopPoint& stopPoint,
+ ColorRange::Mode mode)
+{
+ mUi->percentageSpinBox->setValue(stopPoint.first * 100);
+ mUi->colorChooser->setColor(stopPoint.second);
+
+ if (stopPoint.first == 1) {
+ mUi->addButton->setEnabled(false);
+ mUi->removeButton->setEnabled(false);
+ mUi->percentageSpinBox->setEnabled(false);
+ } else if (stopPoint.first == 0 && mode == ColorRange::Gradient) {
+ mUi->addButton->setEnabled(true);
+ mUi->removeButton->setEnabled(false);
+ mUi->percentageSpinBox->setEnabled(false);
+ } else {
+ mUi->addButton->setEnabled(true);
+ mUi->removeButton->setEnabled(true);
+ mUi->percentageSpinBox->setEnabled(true);
+ }
+
+ mMode = mode;
+}
+
+void StopPointWidget::setStopPointIndex(int index)
+{
+ mIndex = index;
+}
+
+void StopPointWidget::setRange(double minimum, double maximum)
+{
+ if (mUi->percentageSpinBox->value() == 100 ||
+ (mUi->percentageSpinBox->value() == 0 &&
+ mMode == ColorRange::Gradient)) {
+ return;
+ }
+
+ mUi->percentageSpinBox->setMinimum(minimum * 100 + 0.01);
+ mUi->percentageSpinBox->setMaximum(maximum * 100 - 0.01);
+}
+
+void StopPointWidget::setDummy(bool dummy) {
+ if (dummy) {
+ mUi->horizontalSpacer->changeSize(5, 5, QSizePolicy::Expanding);
+ mUi->colorLabel->hide();
+ mUi->colorChooser->hide();
+ mUi->percentageLabel->hide();
+ mUi->percentageSpinBox->hide();
+ mUi->removeButton->hide();
+ } else {
+ mUi->horizontalSpacer->changeSize(0, 0);
+ mUi->colorLabel->show();
+ mUi->colorChooser->show();
+ mUi->percentageLabel->show();
+ mUi->percentageSpinBox->show();
+ mUi->removeButton->show();
+ }
+}
+
+void StopPointWidget::changeColor(const QColor& color)
+{
+ emit colorChanged(mIndex, color);
+}
+
+void StopPointWidget::changePosition(double percentage)
+{
+ emit positionChanged(mIndex, percentage/100);
+}
+
+void StopPointWidget::addStopPointAfter()
+{
+ emit stopPointToAddAfter(mIndex);
+}
+
+void StopPointWidget::removeStopPoint()
+{
+ emit stopPointToRemove(mIndex);
+}
+
+#include "stoppointwidget.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.h (revision 1522570)
@@ -0,0 +1,206 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITAS_COVERAGE_LCOVPREFSWIDGET_H
+#define VERITAS_COVERAGE_LCOVPREFSWIDGET_H
+
+#include <QtGui/QWidget>
+
+#include "ui_lcovprefswidget.h"
+
+#include "colorrange.h"
+
+class LCovSettingsBase;
+class StopPointWidget;
+
+/**
+ * Preferences widget for coverage plugin.
+ * This widget manages the ColorRange configuration used in coverage report
+ * colors, as it can be managed by the KDE Configuration Compiler itself.
+ * However, those widgets managed by the KDE Configuration Compiler aren't
+ * managed in any way by LCovPrefsWidget.
+ *
+ * This LCovPrefsWidget is meant to be used with LCovSettingsBase and LCovPrefs
+ * objects.
+ *
+ * LCovPrefs manages the dialog, and calls the appropriate methods in
+ * LCovSettingsBase when it is loaded, saved, or default values are set. When
+ * the ColorRange is modified by the user, LCovPrefsWidget emits changed(bool)
+ * signal. The parameter tells whether the ColorRange is different to the saved
+ * one (true), or equal to it (false), so "Apply" button can be enabled or
+ * disabled as needed by LCovPrefs.
+ *
+ * LCovSettingsBase manages the configuration: load, save and set default
+ * values. Using that class it can be checked whether the actual ColorRange is
+ * equal to the saved one. In order to show changes to the ColorRange made
+ * outside LCovPrefsWidget (for example, when setting the default ColorRange in
+ * LCovSettingsBase), reloadColorRange() slot is called.
+ */
+class LCovPrefsWidget: public QWidget
+{
+Q_OBJECT
+public:
+
+ /**
+ * Creates a new LCovPrefsWidget.
+ *
+ * @param settings The base settings that contain the ColorRange to show.
+ * @param parent The parent widget.
+ */
+ explicit LCovPrefsWidget(LCovSettingsBase* settings, QWidget* parent = 0);
+
+ /**
+ * Destroys this LCovPrefsWidget.
+ */
+ virtual ~LCovPrefsWidget();
+
+public slots:
+
+ /**
+ * Changes the mode of the ColorRange.
+ * Emits changed(bool).
+ *
+ * @param mode "Discrete" or "Gradient", depending on the mode to set.
+ */
+ void changeMode(const QString& mode);
+
+ /**
+ * Changes the color of the stop point at the given index.
+ * Emits changed(bool).
+ *
+ * @param index The index of the stop point.
+ * @param color The color to set.
+ */
+ void changeColor(int index, const QColor& color);
+
+ /**
+ * Changes the position of the stop point at the given index.
+ * The range for the previous and next StopPointWidget are updated.
+ * Emits changed(bool).
+ *
+ * @param index The index of the stop point.
+ * @param position The position to set.
+ */
+ void changePosition(int index, double position);
+
+ /**
+ * Adds a new stop point after the one at the given index.
+ * The value of the stop points that follow the added one are updated, so
+ * they don't overlap.
+ * The stop points are reloaded.
+ * Emits changed(bool).
+ *
+ * @param index The index to add the stop point after.
+ */
+ void addStopPointAfter(int index);
+
+ /**
+ * Removes the stop point at the given index.
+ * The stop points are reloaded.
+ * Emits changed(bool).
+ *
+ * @param index The index of the stop point to remove.
+ */
+ void removeStopPoint(int index);
+
+ /**
+ * Sets the type combobox to the current type of the ColorRange, and reloads
+ * the list of stop points.
+ * Emits changed(bool).
+ */
+ void reloadColorRange();
+
+signals:
+
+ /**
+ * Emitted when the ColorRange changes.
+ *
+ * @param changed True if it changed and it is different to the saved one,
+ * false otherwise.
+ */
+ void changed(bool changed);
+
+private:
+
+ /**
+ * The Qt Designer widget file.
+ */
+ Ui::LCovPrefsWidget mUi;
+
+ /**
+ * The base settings that contain the color range to show.
+ */
+ LCovSettingsBase* mSettings;
+
+ /**
+ * Reloads the list of StopPointWidgets.
+ * The previous StopPointWidgets are removed and deleted, and a new
+ * StopPointWidget is added for each StopPoint in the current mode of the
+ * ColorRange.
+ * If there is only one stop point, a dummy StopPointWidget is added first.
+ */
+ void reloadStopPoints();
+
+ /**
+ * Creates a new StopPointWidget.
+ *
+ * @param stopPoints The list of StopPoints.
+ * @param index The index of the StopPoint to create the widget for.
+ * @param mode The mode of the StopPoint.
+ * @return The new StopPointWidget.
+ */
+ StopPointWidget* newStopPointWidgetFor(
+ const Veritas::StopPoints& stopPoints, int index,
+ Veritas::ColorRange::Mode mode);
+
+ /**
+ * Creates a new dummy StopPointWidget.
+ *
+ * @return The new dummy StopPointWidget.
+ */
+ StopPointWidget* newDummyStopPointWidget();
+
+ /**
+ * Returns the StopPointWidget at the given index.
+ *
+ * @param index The index of the StopPointWidget.
+ * @return The StopPointWidget.
+ */
+ StopPointWidget* getStopPointWidget(int index);
+
+ /**
+ * Updates the range of the StopPointWidget at the given index.
+ * The range is set to the previous and next stop point positions, or 0 or 1
+ * if there are no previous or next stop points.
+ *
+ * @param index The index of the StopPointWidget.
+ */
+ void updateRange(int index);
+
+ /**
+ * Emits changed(bool).
+ * The boolean value is set to true if the actual color range in the
+ * settings is different to the saved one, false otherwise.
+ */
+ void checkIfChanged();
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovprefswidget.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.h (revision 1522570)
@@ -0,0 +1,120 @@
+/* KDevelop coverage plugin
+ * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_COVERAGE_GRADIENTCOLORRANGE_H
+#define VERITAS_COVERAGE_GRADIENTCOLORRANGE_H
+
+#include <QColor>
+#include <QPair>
+#include <QVector>
+
+#include "coverageexport.h"
+
+namespace Veritas
+{
+
+typedef QPair<double, QColor> StopPoint;
+typedef QVector<StopPoint> StopPoints;
+
+/**
+ * A gradient of colors, each of them associated with a point in range 0 to 1
+ * (both included).
+ * A stop point associate a point with a color. There are always at least two
+ * stop points, associated with positions 0 and 1. Any other position has a
+ * color calculated as a gradient between the set stop points.
+ *
+ * Method colorAt(double) can be used to know the color at some position (no
+ * matter if there is a stop point or not at that position). A color between two
+ * stop points is the linear interpolated color between them.
+ *
+ * Setting a red stop point at 0, a yellow stop point at 0.5 and a green stop
+ * point at 1, the following values would be returned by colorAt:
+ * - 0 -> Red
+ * - 0.25 -> Orange
+ * - 0.5 -> Yellow
+ * - 0.75 -> Yellowish green
+ * - 1 -> Green
+ */
+class VERITAS_COVERAGE_EXPORT GradientColorRange
+{
+public:
+
+ /**
+ * Creates a new GradientColorRange.
+ * The color at 0 is set to black, the color at 1 is set to white, and there
+ * are no middle stop points.
+ */
+ GradientColorRange();
+
+ /**
+ * Destroys this GradientColorRange.
+ */
+ virtual ~GradientColorRange();
+
+ /**
+ * Returns the color at the given position.
+ *
+ * @param position The position, in the range 0 to 1 (both included).
+ * @return The color.
+ */
+ QColor colorAt(double position) const;
+
+ /**
+ * Returns the stop points.
+ *
+ * @return The stop points.
+ */
+ StopPoints stopPoints() const;
+
+ /**
+ * Sets the stop points.
+ * The StopPoints must be in the range [0, 1], in ascending order, and they
+ * must contain only valid colors. The list must contain at least the stop
+ * points located at position 0 and 1.
+ *
+ * @param stopPoints The StopPoints to set.
+ */
+ void setStopPoints(const StopPoints& stopPoints);
+
+private:
+
+ /**
+ * The stop points.
+ */
+ StopPoints mStopPoints;
+
+ /**
+ * Interpolates a color between two stop points.
+ * Each component (red, green and blue) of the returned color is the result
+ * of applying linear interpolation between the components of the begin and
+ * end colors at the given position.
+ *
+ * @param begin The first stop point.
+ * @param end The second stop point.
+ * @param position The position of the color to interpolate.
+ * @return The interpolated color.
+ */
+ QColor interpolateColor(const StopPoint& begin, const StopPoint& end,
+ double position) const;
+
+};
+
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/gradientcolorrange.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp (revision 1522570)
@@ -0,0 +1,120 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "lcovsettingsbase.h"
+
+using Veritas::ColorRange;
+using Veritas::StopPoint;
+using Veritas::StopPoints;
+
+LCovSettingsBase::~LCovSettingsBase()
+{
+}
+
+Veritas::ColorRange* LCovSettingsBase::colorRange()
+{
+ return &mColorRange;
+}
+
+bool LCovSettingsBase::isDefaultColorRange() const
+{
+ return mColorRange == mDefaultColorRange;
+}
+
+bool LCovSettingsBase::isSavedColorRange() const
+{
+ return mColorRange == mSavedColorRange;
+}
+
+LCovSettingsBase::LCovSettingsBase(const QString &configurationFileName):
+ KConfigSkeleton(configurationFileName)
+{
+ mDefaultColorRange.setMode(ColorRange::Gradient);
+ StopPoints stopPoints;
+ stopPoints.append(StopPoint(0, QColor("black")));
+ stopPoints.append(StopPoint(0.3333, QColor("red")));
+ stopPoints.append(StopPoint(0.6667, QColor("orange")));
+ stopPoints.append(StopPoint(1, QColor("green")));
+ mDefaultColorRange.setStopPoints(stopPoints);
+
+ mDefaultColorRange.setMode(ColorRange::Discrete);
+ stopPoints.clear();
+ stopPoints.append(StopPoint(0.25, QColor("black")));
+ stopPoints.append(StopPoint(0.50, QColor("red")));
+ stopPoints.append(StopPoint(0.75, QColor("orange")));
+ stopPoints.append(StopPoint(1, QColor("green")));
+ mDefaultColorRange.setStopPoints(stopPoints);
+
+ mColorRange = mDefaultColorRange;
+ mSavedColorRange = mDefaultColorRange;
+}
+
+void LCovSettingsBase::usrReadConfig()
+{
+ KConfigGroup coverageGroup = config()->group("Code Coverage");
+ if (coverageGroup.hasGroup("Color Range")) {
+ mSavedColorRange.load(coverageGroup.group("Color Range"));
+ } else {
+ mSavedColorRange = mDefaultColorRange;
+ }
+
+ if (!isSavedColorRange()) {
+ mColorRange = mSavedColorRange;
+ emit colorRangeChanged();
+ }
+}
+
+void LCovSettingsBase::usrSetDefaults()
+{
+ if (!isDefaultColorRange()) {
+ mColorRange = mDefaultColorRange;
+ emit colorRangeChanged();
+ }
+}
+
+bool LCovSettingsBase::usrUseDefaults(bool)
+{
+ //Implemented following the implementation of
+ //KConfigSkeletonGenericItem::swapDefaults(), which is called in
+ //KCoreConfigSkeleton::useDefaults(bool)
+ ColorRange temporal = mColorRange;
+ mColorRange = mDefaultColorRange;
+ mDefaultColorRange = temporal;
+
+ emit colorRangeChanged();
+
+ return false;
+}
+
+void LCovSettingsBase::usrWriteConfig()
+{
+ KConfigGroup coverageGroup = config()->group("Code Coverage");
+ coverageGroup.deleteGroup("Color Range");
+
+ if (!isDefaultColorRange()) {
+ KConfigGroup colorRangeGroup(&coverageGroup, "Color Range");
+ mColorRange.save(colorRangeGroup);
+ }
+
+ //After writing the configuration, it is read again in KConfigSkeleton, so
+ //there is no need to set mSavedColorRange here.
+}
+
+#include "lcovsettingsbase.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.cpp (revision 1522570)
@@ -0,0 +1,74 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "colorrangebar.h"
+#include "colorrange.h"
+
+#include <QPainter>
+
+using Veritas::ColorRange;
+using Veritas::StopPoints;
+
+ColorRangeBar::ColorRangeBar(ColorRange* colorRange, QWidget* parent):
+ QWidget(parent) {
+ mColorRange = colorRange;
+}
+
+void ColorRangeBar::paintEvent(QPaintEvent*) {
+ QPainter painter(this);
+ if (mColorRange->mode() == ColorRange::Discrete) {
+ paintDiscreteColorRange(this->contentsRect(), &painter);
+ } else {
+ paintGradientColorRange(this->contentsRect(), &painter);
+ }
+}
+
+void ColorRangeBar::paintDiscreteColorRange(const QRect& rectangle,
+ QPainter* painter) {
+ QBrush brush(Qt::SolidPattern);
+ QRectF rectangleRange(rectangle);
+
+ StopPoints stopPoints = mColorRange->stopPoints();
+
+ for (int i=0; i<stopPoints.size(); ++i) {
+ double width = rectangle.width();
+ if (i == 0) {
+ width = width * stopPoints[i].first;
+ } else {
+ width = width * (stopPoints[i].first - stopPoints[i-1].first);
+ }
+ rectangleRange.setWidth(width);
+
+ brush.setColor(stopPoints[i].second);
+ painter->fillRect(rectangleRange, brush);
+ rectangleRange.translate(width, 0);
+ }
+}
+
+void ColorRangeBar::paintGradientColorRange(const QRect& rectangle,
+ QPainter* painter) {
+ QLinearGradient linearGradient(0, 0.5, 1, 0.5);
+ linearGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
+ linearGradient.setStops(mColorRange->stopPoints());
+
+ painter->fillRect(rectangle, QBrush(linearGradient));
+}
+
+#include "colorrangebar.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.h (revision 1522570)
@@ -0,0 +1,189 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITAS_COVERAGE_STOPPOINTWIDGET_H
+#define VERITAS_COVERAGE_STOPPOINTWIDGET_H
+
+#include <QtGui/QWidget>
+
+#include "colorrange.h"
+
+namespace Ui
+{
+class StopPointWidget;
+}
+
+/**
+ * Widget to display and edit a StopPoint.
+ * StopPoints are used to define ColorRanges: each StopPoint contains a Color
+ * and its position (in [0, 1] range), and a ColorRange contains several
+ * StopPoints for each mode (discrete and gradient).
+ *
+ * This widget is used with LCovPrefsWidget to modify a ColorRange.
+ * LCovPrefsWidget contains as many StopPointWidgets as StopPoint are in the
+ * current mode of the ColorRange.
+ *
+ * Each StopPointWidget displays the values for a StopPoint, identified by
+ * its index. When the values are modified, LCovPrefsWidget modifies the
+ * ColorRange to reflect the changes.
+ *
+ * As the position of a StopPoint must be greater than the position of the
+ * previous one, and lower than the position of the next one, the valid range of
+ * values for the StopPoint can be set using setRange(double, double).
+ *
+ * Although the methods expect positions in range [0, 1], the position of the
+ * StopPoint is shown to the user as a percentage.
+ *
+ * There is a special case in StopPointWidgets: dummy StopPointWidget. A dummy
+ * StopPointWidget only has its add button visible. It is used in discrete mode
+ * when there is only one stop point. A dummy StopPointWidget is added before
+ * its StopPointWidget to allow the user insert a new StopPoint (as the widget
+ * for the last and unique StopPoint would have its add button disabled).
+ */
+class StopPointWidget: public QWidget
+{
+Q_OBJECT
+public:
+
+ /**
+ * Creates a new StopPointWidget.
+ *
+ * @param parent The parent widget.
+ */
+ explicit StopPointWidget(QWidget* parent = 0);
+
+ /**
+ * Destroys this StopPointWidget.
+ */
+ virtual ~StopPointWidget();
+
+ /**
+ * Sets the StopPoint.
+ * A StopPoint at position 1 has its position, add and remove buttons
+ * disabled. Also, in Gradient mode, a StopPoint at 0 has its position and
+ * add button disabled.
+ *
+ * @param stopPoint The StopPoint.
+ */
+ void setStopPoint(const Veritas::StopPoint& stopPoint,
+ Veritas::ColorRange::Mode mode);
+
+ /**
+ * Sets the index of the StopPoint.
+ *
+ * @param index The index of the StopPoint.
+ */
+ void setStopPointIndex(int index);
+
+ /**
+ * Sets the range of valid position values.
+ * The range must be between 0 and 1, both inclusive. The range shown to the
+ * user is set to [minimum * 100 + 0,01, maximum * 100 - 0,01].
+ *
+ * When the StopPoint position is 1, or the StopPoint position is 0 and it
+ * is in GradientMode, the ranges are ignored.
+ *
+ * @param minimum The position of the previous stop point.
+ * @param maximum The position of the next stop point.
+ */
+ void setRange(double minimum, double maximum);
+
+ /**
+ * Sets this StopPointWidget in dummy mode.
+ *
+ * @param dummy True to hide everything but the add button, false to show
+ * everything.
+ */
+ void setDummy(bool dummy);
+
+signals:
+
+ /**
+ * Emitted when the color for the StopPoint at the given index changes.
+ *
+ * @param index The index of the StopPoint.
+ * @param color The new color.
+ */
+ void colorChanged(int index, const QColor& color);
+
+ /**
+ * Emitted when the position for the StopPoint at the given index changes.
+ *
+ * @param index The index of the StopPoint.
+ * @param position The new position.
+ */
+ void positionChanged(int index, double position);
+
+ /**
+ * Emitted when a new StopPoint has to be added after the given index.
+ *
+ * @param index The index of the StopPoint.
+ */
+ void stopPointToAddAfter(int index);
+
+ /**
+ * Emitted when the StopPoint at the given index has to be removed.
+ *
+ * @param index The index of the StopPoint.
+ */
+ void stopPointToRemove(int index);
+
+private:
+
+ /**
+ * The Qt Designer widget file.
+ */
+ Ui::StopPointWidget* mUi;
+
+ /**
+ * The index of the StopPoint.
+ */
+ int mIndex;
+
+ /**
+ * The mode of the StopPoint.
+ */
+ Veritas::ColorRange::Mode mMode;
+
+private slots:
+
+ /**
+ * Emits colorChanged(int, const QColor&).
+ */
+ void changeColor(const QColor& color);
+
+ /**
+ * Emits positionChanged(int, double).
+ */
+ void changePosition(double percentage);
+
+ /**
+ * Emits stopPointToAddAfter(int).
+ */
+ void addStopPointAfter();
+
+ /**
+ * Emits stopPointToRemove(int).
+ */
+ void removeStopPoint();
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/stoppointwidget.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc (revision 1522570)
@@ -0,0 +1,8 @@
+File=lcovconfig.kcfg
+ClassName=LCovSettings
+Inherits=LCovSettingsBase
+Singleton=true
+IncludeFiles=\"lcovsettingsbase.h\"
+UseEnumTypes=true
+SetUserTexts=true
+ItemAccessors=true
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h (revision 1522570)
@@ -0,0 +1,145 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITAS_COVERAGE_LCOVSETTINGSBASE_H
+#define VERITAS_COVERAGE_LCOVSETTINGSBASE_H
+
+#include <KConfigSkeleton>
+
+#include "colorrange.h"
+
+/**
+ * Base class for LCovSettings.
+ * This class manages the configuration of coverage report colors, as it can't
+ * be managed using the KDE Configuration Compiler.
+ *
+ * It is done implementing the usrReadConfig(), usrWriteConfig(),
+ * usrSetDefaults() and usrUseDefaults() protected methods. KConfigSkeleton
+ * takes care of calling them when needed.
+ *
+ * In order to allow the modification of the coverage report colors, the actual
+ * ColorRange is exposed in colorRange() method. It can be checked whether the
+ * actual ColorRange is equal to the default one or to the last saved one using
+ * isDefaultColorRange() and isSavedColorRange().
+ *
+ * When the ColorRange changes (due to being read or set to the default value),
+ * colorRangeChanged() is emitted.
+ */
+class LCovSettingsBase: public KConfigSkeleton
+{
+Q_OBJECT
+public:
+
+ /**
+ * Destroys this LCovSettingsBase.
+ */
+ virtual ~LCovSettingsBase();
+
+ /**
+ * Returns the actual ColorRange.
+ *
+ * @return The actual ColorRange.
+ */
+ Veritas::ColorRange* colorRange();
+
+ /**
+ * Whether the actual ColorRange is equal to the default one or not.
+ *
+ * @return True if the actual ColorRange is equal to the default one, false
+ * otherwise.
+ */
+ bool isDefaultColorRange() const;
+
+ /**
+ * Whether the actual ColorRange is equal to the saved one or not.
+ *
+ * @return True if the actual ColorRange is equal to the saved one, false
+ * otherwise.
+ */
+ bool isSavedColorRange() const;
+
+signals:
+
+ /**
+ * Emitted when the actual ColorRange changes (due to the configuration
+ * being read or the default values set).
+ * Note that it won't be emitted if the configuration is read but the actual
+ * ColorRange is equal to the newly read one, or if the default values are
+ * set and the actual ColorRange is equal to the default one.
+ */
+ void colorRangeChanged();
+
+protected:
+
+ /**
+ * Creates a new LCovSettingsBase.
+ * Actual and saved ColorRange are set to the default one.
+ *
+ * @param configurationFileName The name of the configuration file.
+ */
+ LCovSettingsBase(const QString &configurationFileName);
+
+ /**
+ * Loads the saved ColorRange from the configuration.
+ * If there is no entry for it, the saved ColorRange is the default one.
+ * The actual ColorRange is set to the saved one.
+ */
+ virtual void usrReadConfig();
+
+ /**
+ * Sets the actual ColorRange to the default one.
+ */
+ virtual void usrSetDefaults();
+
+ /**
+ * Swaps default and actual ColorRange values.
+ *
+ * @param useDefaults Ignored.
+ * @return False (ignored in KConfigSkeleton::useDefaults(bool)).
+ */
+ virtual bool usrUseDefaults(bool useDefaults);
+
+ /**
+ * Saves the ColorRange to the configuration.
+ * If the actual ColorRange is equal to the default ColorRange, it is
+ * removed from the configuration.
+ */
+ virtual void usrWriteConfig();
+
+private:
+
+ /**
+ * The actual ColorRange.
+ */
+ Veritas::ColorRange mColorRange;
+
+ /**
+ * The saved ColorRange.
+ */
+ Veritas::ColorRange mSavedColorRange;
+
+ /**
+ * The default ColorRange.
+ */
+ Veritas::ColorRange mDefaultColorRange;
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.h (revision 1522570)
@@ -0,0 +1,80 @@
+/* KDevelop Coverage lcov settings
+*
+* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITAS_COVERAGE_COLORRANGEBAR_H
+#define VERITAS_COVERAGE_COLORRANGEBAR_H
+
+#include <QtGui/QWidget>
+
+#include "colorrange.h"
+
+namespace Veritas
+{
+class ColorRange;
+}
+
+/**
+ * Graphical representation of a ColorRange.
+ * The ColorRangeBar should be updated when the ColorRange is modified. It can
+ * be done calling update() slot.
+ */
+class ColorRangeBar: public QWidget {
+Q_OBJECT
+public:
+
+ /**
+ * Creates a new ColorRangeBar for the given ColorRange.
+ *
+ * @param colorRange The ColorRange to show.
+ * @parent The parent widget.
+ */
+ ColorRangeBar(Veritas::ColorRange* colorRange, QWidget* parent);
+
+ /**
+ * Paints the ColorRange in this ColorRangeBar.
+ */
+ virtual void paintEvent(QPaintEvent*);
+
+private:
+
+ /**
+ * The ColorRange to show.
+ */
+ Veritas::ColorRange* mColorRange;
+
+ /**
+ * Paints the ColorRange when it is in discrete mode.
+ *
+ * @param rectangle The rectanble to paint the ColorRange to.
+ * @param painter The painter to use.
+ */
+ void paintDiscreteColorRange(const QRect& rectangle, QPainter* painter);
+
+ /**
+ * Paints the ColorRange when it is in gradient mode.
+ *
+ * @param rectangle The rectanble to paint the ColorRange to.
+ * @param painter The painter to use.
+ */
+ void paintGradientColorRange(const QRect& rectangle, QPainter* painter);
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/colorrangebar.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage/kdevcoverage.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="kdevcoverage" version="1">
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/coverage
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/coverage (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/coverage (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/coverage
___________________________________________________________________
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop (revision 1522570)
@@ -0,0 +1,55 @@
+[Desktop Entry]
+Type=Service
+Name=Automake Project Builder
+Name[bs]=Automatsko stvaranje projekta
+Name[ca]=Constructor de projecte Automake
+Name[ca@valencia]=Constructor de projecte Automake
+Name[de]=Automake-Projekterstellung
+Name[en_GB]=Automake Project Builder
+Name[es]=Constructor de proyectos Automake
+Name[et]=Automake'i projekti ehitaja
+Name[fr]=Constructeur de projets Automake
+Name[gl]=Construtor de proxectos Automake
+Name[it]=Creatore di progetti per Automake
+Name[ms]=Pembina Projek Automake
+Name[nds]=Automake-Projektbuumoduul
+Name[nl]=Automake projecten Builder
+Name[pl]=Budowanie projektu Automake
+Name[pt]=Construtor de Projectos do Automake
+Name[pt_BR]=Construtor de projetos do Automake
+Name[sv]=Bygg Automake-projekt
+Name[tr]=Automake Proje Oluşturucu
+Name[uk]=Інструмент збирання проектів Automake
+Name[x-test]=xxAutomake Project Builderxx
+Comment=Builds Automake Projects
+Comment[bs]=Izgraditelj Automake projekata
+Comment[ca]=Construeix projectes d'Automake
+Comment[ca@valencia]=Construeix projectes d'Automake
+Comment[de]=Erstellt Automake-Projekte
+Comment[en_GB]=Builds Automake Projects
+Comment[es]=Construye proyectos de Automake
+Comment[et]=Automake'i projektide ehitamine
+Comment[fr]=Construit des projets Automake
+Comment[gl]=Constrúe proxectos de Automake
+Comment[it]=Crea progetti Automake
+Comment[ms]=Bina Projek Automake
+Comment[nds]=Buut Automake-Projekten
+Comment[nl]=Creëert Automake projecten
+Comment[pl]=Buduje projekty Automake
+Comment[pt]=Compila projectos do Automake
+Comment[pt_BR]=Compila projetos do Automake
+Comment[sv]=Bygger Automake-projekt
+Comment[tr]=Automake Projelerini İnşa Eder
+Comment[uk]=Збирає проекти Automake
+Comment[x-test]=xxBuilds Automake Projectsxx
+Icon=gear
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevautomakebuilder
+X-KDE-PluginInfo-Name=KDevAutomakeBuilder
+X-KDE-PluginInfo-Category=Project Management
+X-KDevelop-ProjectBuilder=Automake
+X-KDevelop-Version=12
+X-KDevelop-Category=Project
+X-KDevelop-Interfaces=org.kdevelop.IAutomakeBuilder
+X-KDevelop-IRequired=org.kdevelop.IMakeBuilder
+X-KDevelop-Mode=NoGUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h (revision 1522570)
@@ -0,0 +1,45 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef IAUTOMAKEBUILDER_H
+#define IAUTOMAKEBUILDER_H
+
+#include <project/interfaces/iprojectbuilder.h>
+#include <interfaces/iplugin.h>
+
+
+class IProject;
+class ProjectItem;
+
+/**
+@author Robert Gruber
+*/
+
+class IAutomakeBuilder : public KDevelop::IProjectBuilder
+{
+public:
+ virtual ~IAutomakeBuilder() {}
+
+};
+
+//KDEV_DECLARE_EXTENSION_INTERFACE( IAutomakeBuilder, "org.kdevelop.IAutomakeBuilder" )
+Q_DECLARE_INTERFACE( IAutomakeBuilder, "org.kdevelop.IAutomakeBuilder" )
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,26 @@
+project(AutomakeBuilder)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDEVELOP_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+########### next target ###############
+
+set(automakebuilder_LIB_SRCS
+ automakebuilder.cpp
+ configurejob.cpp
+)
+
+
+kde4_add_plugin( kdevautomakebuilder ${automakebuilder_LIB_SRCS} )
+target_link_libraries( kdevautomakebuilder ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES} ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES} ${KDEVPLATFORM_UTIL_LIBRARIES} )
+
+install( TARGETS kdevautomakebuilder DESTINATION ${PLUGIN_INSTALL_DIR} )
+
+########### install files ###############
+install( FILES kdevautomakebuilder.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES iautomakebuilder.h DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/automake COMPONENT Devel)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h (revision 1522570)
@@ -0,0 +1,59 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CONFIGUREJOB_H
+#define CONFIGUREJOB_H
+
+#include <outputview/outputjob.h>
+
+namespace KDevelop{
+ class IProject;
+}
+
+/**
+@author Robert Gruber
+*/
+class ConfigureJob : public KDevelop::OutputJob
+{
+ Q_OBJECT
+
+public:
+ ConfigureJob(KDevelop::IProject* project, QObject *parent = 0);
+
+ enum ErrorTypes {
+ NoProjectError = UserDefinedError,
+ ConfigureError
+ };
+
+ virtual void start();
+
+private Q_SLOTS:
+ void slotFailed();
+ void slotCompleted();
+
+private:
+ QString buildConfigureCall();
+
+ KDevelop::IProject* m_project;
+
+ bool m_killed;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp (revision 1522570)
@@ -0,0 +1,95 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "configurejob.h"
+
+#include <QDir>
+
+#include <make/imakebuilder.h>
+
+#include <project/projectmodel.h>
+#include <interfaces/iproject.h>
+#include <interfaces/icore.h>
+#include <interfaces/iplugincontroller.h>
+#include <outputview/ioutputview.h>
+#include <outputview/outputmodel.h>
+#include <util/commandexecutor.h>
+
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+#include <kdebug.h>
+
+ConfigureJob::ConfigureJob(KDevelop::IProject* project, QObject *parent)
+ : OutputJob(parent),
+ m_project(project), m_killed(false)
+{
+ setCapabilities(Killable);
+}
+
+void ConfigureJob::start()
+{
+ if( !m_project ) {
+ setError(NoProjectError);
+ setErrorText(i18n("No project specified."));
+ return emitResult();
+ }
+
+ setStandardToolView(KDevelop::IOutputView::BuildView);
+ setBehaviours(KDevelop::IOutputView::AllowUserClose | KDevelop::IOutputView::AutoScroll);
+ setModel(new KDevelop::OutputModel(this), KDevelop::IOutputView::TakeOwnership);
+ startOutput();
+
+ KConfigGroup automakeGrp = m_project->projectConfiguration()->group("Automake");
+ KUrl buildDir = automakeGrp.readEntry( "CurrentBuildDir", KUrl() );
+
+ QString configure = buildConfigureCall();
+
+ /// @todo add additional configure args here (e.g. --prefix=<dir>)
+
+ KDevelop::CommandExecutor* cmd = new KDevelop::CommandExecutor(configure, this);
+ connect(cmd, SIGNAL(receivedStandardError(const QStringList&)),
+ model(), SLOT(appendLines(const QStringList&) ) );
+ connect(cmd, SIGNAL(receivedStandardOutput(const QStringList&)),
+ model(), SLOT(appendLines(const QStringList&) ) );
+ cmd->setWorkingDirectory( (buildDir.isValid())?buildDir.toLocalFile():m_project->folder().toLocalFile() );
+ connect( cmd, SIGNAL( failed() ), this, SLOT( slotFailed() ) );
+ connect( cmd, SIGNAL( completed() ), this, SLOT( slotCompleted() ) );
+ cmd->start();
+}
+
+QString ConfigureJob::buildConfigureCall()
+{
+ // always call the configure script from the project's directory
+ return m_project->folder().toLocalFile() + QDir::separator() + "configure";
+}
+
+void ConfigureJob::slotFailed()
+{
+ setError(ConfigureError);
+ setErrorText(i18n("Configure failed"));
+ emitResult();
+}
+
+void ConfigureJob::slotCompleted()
+{
+ emitResult();
+}
+
+#include "configurejob.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp (revision 1522570)
@@ -0,0 +1,136 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "automakebuilder.h"
+#include <make/imakebuilder.h>
+
+#include <project/projectmodel.h>
+
+#include <interfaces/iproject.h>
+#include <interfaces/icore.h>
+#include <interfaces/iplugincontroller.h>
+
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+#include <kaboutdata.h>
+#include <kdebug.h>
+
+#include "configurejob.h"
+
+K_PLUGIN_FACTORY(AutomakeBuilderFactory, registerPlugin<AutomakeBuilder>(); )
+K_EXPORT_PLUGIN(AutomakeBuilderFactory(KAboutData("kdevautomakebuilder","kdevautomakebuilder", ki18n("Automake Builder"), "0.1", ki18n("Support for building Automake projects"), KAboutData::License_GPL)))
+
+AutomakeBuilder::AutomakeBuilder(QObject *parent, const QVariantList &)
+ : KDevelop::IPlugin(AutomakeBuilderFactory::componentData(), parent)
+{
+ KDEV_USE_EXTENSION_INTERFACE( KDevelop::IProjectBuilder )
+ KDEV_USE_EXTENSION_INTERFACE( IAutomakeBuilder )
+
+ m_makeBuilder = core()->pluginController()->pluginForExtension("org.kdevelop.IMakeBuilder");
+ if( m_makeBuilder )
+ {
+ IMakeBuilder* mbuilder = m_makeBuilder->extension<IMakeBuilder>();
+ if( mbuilder )
+ {
+ connect( m_makeBuilder, SIGNAL( built( KDevelop::ProjectBaseItem* ) ),
+ this, SIGNAL( built( KDevelop::ProjectBaseItem* ) ) );
+ connect( m_makeBuilder, SIGNAL( cleaned( KDevelop::ProjectBaseItem* ) ),
+ this, SIGNAL( cleaned( KDevelop::ProjectBaseItem* ) ) );
+ connect( m_makeBuilder, SIGNAL( installed( KDevelop::ProjectBaseItem* ) ),
+ this, SIGNAL( installed( KDevelop::ProjectBaseItem* ) ) );
+ connect( m_makeBuilder, SIGNAL( failed( KDevelop::ProjectBaseItem* ) ),
+ this, SIGNAL( failed( KDevelop::ProjectBaseItem* ) ) );
+ connect( m_makeBuilder, SIGNAL( makeTargetBuilt( KDevelop::ProjectBaseItem*, const QString& ) ),
+ this, SIGNAL( pruned( KDevelop::ProjectBaseItem* ) ) );
+ }
+ }
+}
+
+AutomakeBuilder::~AutomakeBuilder()
+{
+}
+
+KJob* AutomakeBuilder::prune( KDevelop::IProject* project )
+{
+ kDebug() << "Distcleaning";
+ if( m_makeBuilder )
+ {
+ IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
+ if( builder )
+ {
+ kDebug() << "Distcleaning with make";
+ return builder->executeMakeTarget(project->projectItem(), "distclean");
+ }
+ }
+ return 0;
+}
+
+KJob* AutomakeBuilder::build(KDevelop::ProjectBaseItem *dom)
+{
+ kDebug() << "Building";
+ if( m_makeBuilder )
+ {
+ IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
+ if( builder )
+ {
+ kDebug() << "Building with make";
+ return builder->build(dom);
+ }
+ }
+ return 0;
+}
+
+KJob* AutomakeBuilder::configure( KDevelop::IProject* project )
+{
+ ConfigureJob* job = new ConfigureJob(project, this);
+ return job;
+}
+
+KJob* AutomakeBuilder::clean(KDevelop::ProjectBaseItem *dom)
+{
+ kDebug() << "Cleaning";
+ if( m_makeBuilder )
+ {
+ IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
+ if( builder )
+ {
+ kDebug() << "Cleaning with make";
+ return builder->clean(dom);
+ }
+ }
+ return 0;
+}
+
+KJob* AutomakeBuilder::install(KDevelop::ProjectBaseItem *dom)
+{
+ kDebug() << "Installing";
+ if( m_makeBuilder )
+ {
+ IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
+ if( builder )
+ {
+ kDebug() << "Installing with make";
+ return builder->install(dom);
+ }
+ }
+ return 0;
+}
+
+#include "automakebuilder.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevautomakebuilder.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h (revision 1522570)
@@ -0,0 +1,70 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef AUTOMAKEBUILDER_H
+#define AUTOMAKEBUILDER_H
+
+#include <interfaces/iplugin.h>
+#include "iautomakebuilder.h"
+#include <QtCore/QList>
+#include <QtCore/QPair>
+#include <QtCore/QVariant>
+
+class QStringList;
+class QSignalMapper;
+class KDialog;
+namespace KDevelop{
+ class ProjectBaseItem;
+ class CommandExecutor;
+ class OutputModel;
+}
+
+/**
+@author Robert Gruber
+*/
+class AutomakeBuilder : public KDevelop::IPlugin, public IAutomakeBuilder
+{
+ Q_OBJECT
+ Q_INTERFACES( IAutomakeBuilder )
+ Q_INTERFACES( KDevelop::IProjectBuilder )
+
+public:
+ explicit AutomakeBuilder(QObject *parent = 0, const QVariantList &args = QVariantList());
+ virtual ~AutomakeBuilder();
+
+ virtual KJob* build(KDevelop::ProjectBaseItem *dom);
+ virtual KJob* clean(KDevelop::ProjectBaseItem *dom);
+ virtual KJob* install(KDevelop::ProjectBaseItem *dom);
+ virtual KJob* configure(KDevelop::IProject *dom);
+ virtual KJob* prune(KDevelop::IProject *dom);
+
+Q_SIGNALS:
+ void built(KDevelop::ProjectBaseItem*);
+ void failed(KDevelop::ProjectBaseItem*);
+ void installed(KDevelop::ProjectBaseItem*);
+ void cleaned(KDevelop::ProjectBaseItem*);
+ void configured(KDevelop::ProjectBaseItem*);
+ void pruned(KDevelop::ProjectBaseItem*);
+
+private:
+ KDevelop::IPlugin* m_makeBuilder;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop (revision 1522570)
@@ -0,0 +1,62 @@
+[Desktop Entry]
+Icon=kdevelop
+Type=Service
+ServiceTypes=KCModule
+
+X-KDE-ModuleType=Library
+X-KDE-Library=kcm_kdevautomake_settings
+X-KDE-FactoryName=kcm_kdevautomake_settings
+X-KDE-ParentApp=kdevplatformproject
+X-KDE-ParentComponents=KDevAutotoolsImporter
+X-KDE-CfgDlgHierarchy=BUILDTOOL
+
+Name=Automake
+Name[bs]=Automake
+Name[ca]=Automake
+Name[ca@valencia]=Automake
+Name[de]=Automake
+Name[en_GB]=Automake
+Name[eo]=Automake
+Name[es]=Automake
+Name[et]=Automake
+Name[fr]=Automake
+Name[ga]=Automake
+Name[gl]=Automake
+Name[hu]=Automake
+Name[it]=Automake
+Name[ms]=Automake
+Name[nds]=Automake
+Name[nl]=Automake
+Name[pl]=Automake
+Name[pt]=Automake
+Name[pt_BR]=Automake
+Name[sk]=Automake
+Name[sv]=Automake
+Name[tr]=Automake
+Name[ug]=Automake
+Name[uk]=Automake
+Name[x-test]=xxAutomakexx
+Comment=Configure Automake settings
+Comment[bs]=Konfiguracija Automake postavki
+Comment[ca]=Configura els arranjaments d'Automake
+Comment[ca@valencia]=Configura els arranjaments d'Automake
+Comment[de]=Automake-Einstellungen festlegen
+Comment[en_GB]=Configure Automake settings
+Comment[es]=Configurar preferencias de Automake
+Comment[et]=Automake'i seadistamine
+Comment[fr]=Configure les paramètres Automake
+Comment[ga]=Cumraigh socruithe Automake
+Comment[gl]=Configurar as opcións de Automake
+Comment[hu]=Automake beállítások módosítása
+Comment[it]=Configura le impostazioni di Automake
+Comment[ms]=Konfigur Tetapan Automake
+Comment[nds]=Automake instellen
+Comment[nl]=Configureert Automake instellingen
+Comment[pl]=Ustawienia Automake
+Comment[pt]=Configurar as opções do Automake
+Comment[pt_BR]=Configurar as opções do Automake
+Comment[sv]=Anpassa Automake-inställningar
+Comment[tr]=Automake ayarlarını yapılandır
+Comment[uk]=Налаштувати параметри Automake
+Comment[x-test]=xxConfigure Automake settingsxx
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop (revision 1522570)
@@ -0,0 +1,53 @@
+[Desktop Entry]
+Type=Service
+Name=Autotools Importer
+Name[bs]=Autotools uvoz
+Name[ca]=Importador Autotools
+Name[ca@valencia]=Importador Autotools
+Name[de]=Autotools-Import
+Name[en_GB]=Autotools Importer
+Name[es]=Importador Autotools
+Name[et]=Autotoolsi importija
+Name[fr]=Importateur Autools
+Name[ga]=Iompórtálaí Autotools
+Name[gl]=Importador de Autotools
+Name[it]=Importatore per Autotools
+Name[nl]=Import van Autotools
+Name[pl]=Importowanie Autotools
+Name[pt]=Importação das Autotools
+Name[pt_BR]=Importação das Autotools
+Name[sv]=Import av Autotools
+Name[uk]=Імпортування з Autotools
+Name[x-test]=xxAutotools Importerxx
+Comment=Allows to manage projects using a GNU-based build system
+Comment[bs]=Dozvoljava upravljanje projektima korištenjem GNU-baziranog build sistema
+Comment[ca]=Permet gestionar projectes que usen un sistema de construcció basat en GNU
+Comment[ca@valencia]=Permet gestionar projectes que usen un sistema de construcció basat en GNU
+Comment[de]=Ermöglicht die Verwaltung von Projekten mit einem GNU-basierten Erstellungssystem
+Comment[en_GB]=Allows to manage projects using a GNU-based build system
+Comment[es]=Permite gestionar proyectos que usan un sistema de construcción basado en GNU
+Comment[et]=Võimaldab hallata projekte GNU-põhise ehitussüsteemi alusel
+Comment[fr]=Permet de gérer des projets à l'aide d'un système de construction fondé sur GNU
+Comment[gl]=Permite xestionar proxectos usando un sistema de compilación baseado en GNU.
+Comment[it]=Consente di gestire progetti utilizzando un sistema di creazione basato su GNU
+Comment[nl]=Geeft de mogelijkheid tot het beheren van projecten met een GNU-gebaseerd bouw systeem
+Comment[pl]=Pozwala na zarządzanie projektami przy użyciu systemu budowania opartego o GNU
+Comment[pt]=Permite ao KDevelop gerir projectos com um sistema de compilações baseado na GNU
+Comment[pt_BR]=Permite gerenciar projetos com um sistema de compilações baseado na GNU
+Comment[sv]=Gör det möjligt att hantera projekt som använder ett GNU-baserat byggsystem
+Comment[uk]=Надає змогу керувати проектами за допомогою заснованої на GNU системи збирання
+Comment[x-test]=xxAllows to manage projects using a GNU-based build systemxx
+Icon=gear
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevautomakeimporter
+X-KDE-PluginInfo-Author=Matt Rogers
+X-KDE-PluginInfo-Email=mattr@kde.org
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-Name=KDevAutotoolsImporter
+X-KDE-PluginInfo-Category=Project Management
+X-KDevelop-FileManager=GNU Autotools
+X-KDevelop-Version=12
+X-KDevelop-Interfaces=org.kdevelop.IBuildSystemManager,org.kdevelop.IProjectFileManager
+X-KDevelop-Mode=NoGUI
+X-KDevelop-ProjectFilesFilter=*.am
+X-KDevelop-ProjectFilesFilterDescription=Automake Project Files
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.cpp (revision 1522570)
@@ -0,0 +1,483 @@
+/* KDevelop Automake Support
+ *
+ * Copyright (C) 2005 Matt Rogers <mattr@kde.org>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "makefileinterface.h"
+
+#include <QtAlgorithms>
+#include <QFileInfo>
+#include <QList>
+#include <QHash>
+
+#include <kdebug.h>
+
+#include "automakeast.h"
+#include "automakedriver.h"
+
+
+uint qHash( const QFileInfo& key )
+{
+ return qHash( key.absolutePath() );
+}
+
+namespace AutoMake
+{
+ TargetType convertToType( const QString& type )
+ {
+ if ( type == "PROGRAMS" )
+ return Program;
+ else if ( type == "LIBRARIES" )
+ return Library;
+ else if ( type == "LTLIBRARIES" )
+ return LibtoolLibrary;
+ else if ( type == "LISP" )
+ return Lisp;
+ else if ( type == "PYTHON" )
+ return Python;
+ else if ( type == "JAVA" )
+ return Java;
+ else if ( type == "SCRIPTS" )
+ return Scripts;
+ else if ( type == "DATA" )
+ return Data;
+ else if ( type == "HEADERS" )
+ return Headers;
+ else if ( type == "MANS" )
+ return ManPages;
+ else if ( type == "TEXINFOS" )
+ return Texinfo;
+ else
+ return Unknown;
+ }
+
+ InstallLocation convertToLocation( const QString& location )
+ {
+ if ( location == "bin" )
+ return Bin;
+ else if ( location == "lib" )
+ return Lib;
+ else if ( location == "libexec" )
+ return Libexec;
+ else if ( location == "noinst" )
+ return None;
+ else if ( location == "check" )
+ return Check;
+ else if ( location == "info" )
+ return Info;
+ else if ( location.contains( "^man" ) )
+ return Man;
+ else if ( location == "kde_module" )
+ return Lib;
+ else if ( location == "EXTRA" )
+ return None;
+ else
+ return Custom;
+ }
+}
+
+
+using namespace AutoMake;
+
+class MakefileInterface::Private
+{
+public:
+ AutoMakeASTHash projects;
+ QStringList filesToParse;
+ KUrl topLevelParseDir;
+};
+
+MakefileInterface::MakefileInterface( QObject* parent )
+: QObject( parent )
+{
+ d = new MakefileInterface::Private;
+ d->filesToParse.append("Makefile.am.in");
+ d->filesToParse.append("Makefile.am");
+ d->filesToParse.append("Makefile.in");
+}
+
+MakefileInterface::~MakefileInterface()
+{
+ qDeleteAll( d->projects );
+ delete d;
+}
+
+QString MakefileInterface::canonicalize( const QString& target )
+{
+ QString result;
+ for ( int i = 0; i < target.length(); ++i )
+ {
+ QChar addition = target.at( i );
+ if ( !addition.isLetterOrNumber() && addition != '@' && addition != '_' )
+ addition = QChar( '_' );
+
+ result += addition;
+ }
+
+ kDebug(9020) << "'" << target << "' has been normalized to '"
+ << result << "'" << endl;
+
+ return result;
+}
+
+bool MakefileInterface::parse( const KUrl& dir, ParserRecursion recursive )
+{
+ kDebug(9020) << "directory to parse is:" << dir.path();
+ int ret = -1;
+ AutoMake::ProjectAST* ast = 0L;
+
+ QFileInfo parsingFile;
+ QStringList::const_iterator it, itEnd = d->filesToParse.constEnd();
+ for ( it = d->filesToParse.constBegin(); it != itEnd; ++it )
+ {
+ parsingFile.setFile( dir.path(), (*it) );
+ if ( parsingFile.exists() )
+ {
+ using namespace AutoMake;
+ ret = Driver::parseFile( parsingFile.absoluteFilePath(), &ast );
+ if ( ret != -1 )
+ break;
+ }
+ }
+
+ if ( !ast || ret == -1 )
+ {
+ kWarning(9020) << "parsing" << dir.path()
+ << "not successful! Fix your Makefile!" << endl;
+ return false;
+ }
+
+ d->projects[parsingFile] = ast;
+
+ if ( recursive == NonRecursive || ( ast && !ast->hasChildren() ) )
+ return ( ret != -1 );
+
+
+ QStringList subdirs = subdirsFor( dir );
+ foreach( const QString& sd, subdirs )
+ {
+ kDebug(9020) << "Beginning parsing of '" << sd << "'";
+ parse( dir.path() + '/' + sd, recursive );
+ }
+
+ return (ret != -1);
+}
+
+void MakefileInterface::setProjectRoot( const KUrl& dir )
+{
+ d->topLevelParseDir = dir;
+}
+
+QString MakefileInterface::projectRoot() const
+{
+ return d->topLevelParseDir.path();
+}
+
+QStringList MakefileInterface::topSubDirs() const
+{
+ return subdirsFor( d->topLevelParseDir );
+}
+
+AutoMake::ProjectAST* MakefileInterface::astForFolder( const KUrl& folder ) const
+{
+ ProjectAST* ast = 0;
+ QFileInfo parsingFile;
+ QStringList::const_iterator it, itEnd = d->filesToParse.constEnd();
+ for ( it = d->filesToParse.constBegin(); it != itEnd; ++it )
+ {
+ parsingFile.setFile( folder.path(), (*it) );
+ if ( parsingFile.exists() )
+ ast = d->projects[parsingFile];
+
+ if ( ast != 0 )
+ break;
+
+ }
+
+ return ast;
+}
+
+bool MakefileInterface::isVariable( const QString& item )
+{
+ if ( item.contains( QRegExp( "(\\$\\([a-zA-Z0-9_-]*\\)|@[a-zA-Z0-9_-]*@)" ) ) )
+ return true;
+ else
+ return false;
+}
+
+QString MakefileInterface::resolveVariable( const QString& variable, AutoMake::ProjectAST* ast ) const
+{
+ if ( !ast )
+ return variable;
+
+ kDebug(9020) << "attempting to resolve '" << variable << "'";
+ QList<AST*> childList = ast->children();
+ QList<AST*>::iterator it( childList.begin() ), clEnd( childList.end() );
+
+ for ( ; it != clEnd; ++it )
+ {
+ if ( ( *it )->nodeType() == AST::AssignmentAST )
+ {
+ AssignmentAST* assignment = static_cast<AssignmentAST*>( ( *it ) );
+ if ( variable.indexOf( assignment->scopedID ) != -1 )
+ {
+ QString resolution = assignment->values.join( " " ).trimmed();
+ kDebug(9020) << "Resolving variable '" << variable << "' to '"
+ << resolution << "'" << endl;
+ return resolution;
+ }
+ }
+ }
+
+ return variable;
+}
+
+QStringList MakefileInterface::subdirsFor( const KUrl& folder ) const
+{
+ AutoMake::ProjectAST* ast = astForFolder( folder );
+ if ( !ast )
+ {
+ kWarning(9020) << "Couldn't find AST for "
+ << folder.path() << endl;
+ return QStringList();
+ }
+
+ QStringList subdirs = subdirsFor( ast );
+ // check for and deal with KDE hacks (TOPSUBDIRS and AUTODIRS)
+ foreach (QString subdir, subdirs) {
+ if (subdir.contains("$(TOPSUBDIRS)")) {
+ kDebug() << "Found special subdir variable"<<subdir;
+ QFile subdirsFile(folder.toLocalFile()+QDir::separator()+"subdirs");
+ if ( subdirsFile.exists() ) {
+ if ( subdirsFile.open(QIODevice::ReadOnly) ) {
+ QTextStream in(&subdirsFile);
+ while (!in.atEnd()) {
+ subdirs.append( in.readLine() );
+ }
+ subdirs.removeAll( subdir );
+ }
+ } else {
+ // fallback -> act like AUTODIRS in case subdirs file is not present
+ subdir = "$(AUTODIRS)";
+ }
+ }
+ if (subdir.contains("$(AUTODIRS)")) {
+ kDebug() << "Found special subdir variable"<<subdir;
+ QDir dirHelper(folder.toLocalFile());
+ QStringList autodirs = dirHelper.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
+ subdirs.removeAll(subdir); // remove the TOPSUBDIRS entry...
+ subdirs.append(autodirs); // ... and insert all found subdirs instead
+ }
+ }
+
+ return subdirs;
+}
+
+QList<TargetInfo> MakefileInterface::targetsForFolder( const KUrl& folder ) const
+{
+ kDebug(9020) << folder.path();
+
+ QList<TargetInfo> targetList;
+ AutoMake::ProjectAST* ast = astForFolder( folder );
+
+ if ( !ast )
+ {
+ kWarning(9020) << "Unable to get AST for "
+ << folder.path() << endl;
+ return targetList;
+ }
+
+ QList<AST*> childList = ast->children();
+ QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
+ for ( cit = childList.constBegin(); cit != citEnd; ++cit )
+ {
+ if ( (*cit)->nodeType() == AST::AssignmentAST )
+ {
+ AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
+ if ( assignment->scopedID.contains( AutoMake::targetPrimaries ) )
+ {
+ foreach( const QString& target, assignment->values )
+ {
+ if ( target == "#" || target == "\\" )
+ continue;
+
+ QStringList targetSplit = assignment->scopedID.split( '_' );
+ QString primary = targetSplit.takeLast();
+ QString location = targetSplit.join( "_" );
+
+ kDebug( 9020 ) << "primary:" << primary
+ << "location:" << location << endl;
+
+ TargetInfo info;
+ info.type = AutoMake::convertToType( primary );
+ info.location = AutoMake::convertToLocation( location );
+ info.name = target;
+ info.url = folder;
+ kDebug( 9020 ) << "target name:" << target;
+ targetList.append( info );
+ }
+ }
+ }
+ }
+
+ return targetList;
+}
+
+QStringList MakefileInterface::subdirsFor( AutoMake::ProjectAST* ast ) const
+{
+ QList<AST*> childList = ast->children();
+ QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
+ for ( cit = childList.constBegin(); cit != citEnd; ++cit )
+ {
+ if ( (*cit)->nodeType() == AST::AssignmentAST )
+ {
+ AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
+ if ( assignment->scopedID == "SUBDIRS" )
+ {
+ QStringList subdirList = assignment->values;
+ subdirList.removeAll(".");
+ subdirList.removeAll("..");
+ subdirList.removeAll("\\");
+ subdirList.removeAll("#");
+
+ QStringList::const_iterator vit = subdirList.constBegin();
+ for ( ; vit != subdirList.constEnd(); ++vit )
+ {
+ QString dirFromList = ( *vit );
+ QString realDir = dirFromList;
+ if ( realDir.startsWith( "\\" ) )
+ realDir.remove( 0, 1 );
+
+ realDir = realDir.trimmed();
+ if ( !realDir.isEmpty() )
+ {
+ if ( isVariable( realDir ) )
+ {
+ kDebug(9020) << "'" << realDir << "' is a variable";
+ realDir = resolveVariable( realDir, ast );
+ }
+
+ subdirList.replace( subdirList.indexOf( dirFromList ),
+ realDir );
+ }
+ }
+ kDebug(9020) << "subdirs is '"
+ << assignment->values << "'" << endl;
+ return subdirList;
+ }
+ }
+ }
+
+ return QStringList();
+}
+
+QList<QFileInfo> MakefileInterface::filesForTarget( const TargetInfo& target ) const
+{
+ QList<QFileInfo> fileInfoList;
+ QString targetId;
+ AutoMake::ProjectAST* ast = astForFolder( target.url );
+ if ( !ast )
+ return QList<QFileInfo>();
+
+ if ( isVariable( target.name ) )
+ targetId = resolveVariable( target.name, ast );
+ else
+ targetId = canonicalize( target.name );
+
+
+ switch ( target.type )
+ {
+ case Program:
+ case Library:
+ case LibtoolLibrary:
+ targetId += QLatin1String( "_SOURCES" );
+ break;
+ case Lisp:
+ targetId += QLatin1String( "_LISP" );
+ break;
+ case Texinfo:
+ targetId += QLatin1String( "_TEXINFOS" );
+ break;
+ case Scripts:
+ targetId += QLatin1String( "_SCRIPTS" );
+ break;
+ case Java:
+ targetId += QLatin1String( "_JAVA" );
+ break;
+ case Python:
+ targetId += QLatin1String( "_PYTHON" );
+ break;
+ case Data:
+ targetId += QLatin1String( "_DATA" );
+ break;
+ case Headers:
+ targetId += QLatin1String( "_HEADERS" );
+ break;
+ case ManPages:
+ targetId += QLatin1String( "_MANS" );
+ break;
+ default:
+ break;
+ };
+
+
+ QStringList valuesList = valuesForId( targetId, ast );
+ foreach( const QString& value, valuesList )
+ {
+ if ( value == QLatin1String( "\\" ) )
+ continue;
+
+ QFileInfo fi( target.url.path(), value );
+ fileInfoList.append( fi );
+ }
+
+ return fileInfoList;
+}
+
+QStringList MakefileInterface::valuesForId( const QString& id, AutoMake::ProjectAST* ast ) const
+{
+ kDebug(9020) << "looking for '" << id << "'";
+
+ QStringList valuesList;
+ QList<AST*> childList = ast->children();
+ QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
+ for ( cit = childList.constBegin(); cit != citEnd; ++cit )
+ {
+ if ( (*cit)->nodeType() == AST::AssignmentAST )
+ {
+ AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
+ if ( assignment->scopedID == id )
+ {
+ kDebug(9020) << "found" << id;
+ QStringList valuesList = assignment->values;
+ valuesList.removeAll( QLatin1String( "\\" ) );
+
+ kDebug(9020) << "providing list '"
+ << assignment->values << "' for id" << id << endl;
+ return valuesList;
+ }
+ }
+ }
+
+ return valuesList;
+
+}
+#include "makefileinterface.moc"
+
+
+//kate: hl c++;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.h (revision 1522570)
@@ -0,0 +1,38 @@
+/***************************************************************************
+ * KDevelop Automake Support Tests *
+ * Copyright 2005 Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef TESTINTERFACE_H
+#define TESTINTERFACE_H
+
+#include <QtCore/QObject>
+
+class TestInterface : public QObject
+{
+Q_OBJECT
+private slots:
+ void testIsVariable();
+ void testIsVariable_data();
+
+ void testCanonicalize();
+ void testCanonicalize_data();
+
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,54 @@
+set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+
+add_definitions ( -DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)
+
+#if(false)
+
+include_directories(
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${AutomakeManager_SOURCE_DIR}
+ ${KDE4_INCLUDES}
+)
+
+########### next target ###############
+
+set(runner_SRCS
+ runner.cpp
+)
+
+kde4_add_executable(runner TEST ${runner_SRCS})
+target_link_libraries(runner ${KDE4_KDECORE_LIBS} ${KDE4_KIO_LIBS})
+
+
+
+########### next target ###############
+set(viewer_SRCS
+ viewer.cpp
+ viewer_main.cpp
+)
+
+set(viewer_UI
+ viewerbase.ui
+)
+
+kde4_add_ui3_files(viewer_SRCS ${viewer_UI})
+kde4_add_executable(viewer TEST ${viewer_SRCS})
+target_link_libraries(viewer ${KDE4_KDECORE_LIBS} ${KDE4_KIO_LIBS})
+
+
+########### next target ###############
+
+set(testinterface_SRCS
+ ../automakeast.cpp
+ ../automakedriver.cpp
+ ../automakeparser.cpp
+ ../makefileinterface.cpp
+ testinterface.cpp
+)
+
+kde4_add_unit_test(kdevautomake-test ${testinterface_SRCS})
+target_link_libraries(kdevautomake-test ${KDE4_KDECORE_LIBS} ${QT_QTTEST_LIBRARY} ${KDE4_KIO_LIBS})
+
+#endif(false)
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.cpp (revision 1522570)
@@ -0,0 +1,64 @@
+/***************************************************************************
+ * KDevelop Automake Support Tests *
+ * Copyright 2005 Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "testinterface.h"
+#include <QtTest/QtTest>
+#include "makefileinterface.h"
+
+QTEST_MAIN(TestInterface)
+
+void TestInterface::testIsVariable()
+{
+ QFETCH(QString, variable);
+ QFETCH(bool, result);
+
+ QCOMPARE( MakefileInterface::isVariable( variable ), result );
+}
+
+void TestInterface::testIsVariable_data()
+{
+ QTest::addColumn<QString>("variable");
+ QTest::addColumn<bool>("result");
+
+ QTest::newRow("v1") << "$(top_srcdir1)" << true;
+ QTest::newRow("v2") << "$(!DFDFDDFFD)" << false;
+ QTest::newRow("v3") << "@MY_1VARIABLE@" << true;
+ QTest::newRow("v4") << "@%#$ASDFSDF#@" << false;
+ QTest::newRow("v5") << "bin_PROGRAMS" << false;
+}
+
+void TestInterface::testCanonicalize()
+{
+ QFETCH(QString, target);
+ QFETCH(QString, result);
+
+ QCOMPARE( MakefileInterface::canonicalize( target ), result );
+}
+
+void TestInterface::testCanonicalize_data()
+{
+ QTest::addColumn<QString>("target");
+ QTest::addColumn<QString>("result");
+ QTest::newRow("v1") << "libfoo.la" << "libfoo_la";
+ QTest::newRow("v2") << "libbar++.la" << "libbar___la";
+ QTest::newRow("v3") << "lib123!#$%^.la" << "lib123______la";
+}
+
+#include "testinterface.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/testinterface.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.cpp (revision 1522570)
@@ -0,0 +1,164 @@
+/***************************************************************************
+ * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "viewer.h"
+
+#include <QDir>
+#include <QLineEdit>
+#include <q3listbox.h>
+#include <q3filedialog.h>
+#include <q3textedit.h>
+#include <QFile>
+#include <qtextstream.h>
+#include <q3listview.h>
+#include <qtabwidget.h>
+//Added by qt3to4:
+#include <Q3ValueList>
+
+#include <automakeast.h>
+#include <automakedriver.h>
+
+using namespace AutoMake;
+
+Viewer::Viewer(QWidget *parent)
+ : QWidget(parent), Ui::ViewerBase()
+{
+ setupUi(this);
+ if (QFile::exists(QDir::currentDirPath() + '/' + "qtlist"))
+ {
+ QFile f(QDir::currentDirPath() + '/' + "qtlist");
+ f.open(QIODevice::ReadOnly);
+ QTextStream str(&f);
+ while (!str.atEnd())
+ files->insertItem(str.readLine());
+ }
+ ast->setSorting(-1);
+ parentProject.push((Q3ListViewItem*)0);
+}
+
+void Viewer::on_addAll_clicked()
+{
+ if (allLocation->text().isEmpty())
+ return;
+ QDir d(allLocation->text());
+ QStringList l = d.entryList("*.am");
+ for (QStringList::iterator it = l.begin(); it != l.end(); ++it)
+ (*it) = QDir::cleanDirPath(allLocation->text() + '/' + (*it));
+ files->insertStringList(l);
+}
+
+void Viewer::on_choose_clicked()
+{
+ QString fileName = Q3FileDialog::getOpenFileName(QDir::currentDirPath(), "*.am", this);
+ if (!fileName.isEmpty())
+ files->insertItem(fileName);
+}
+
+void Viewer::on_files_currentChanged(Q3ListBoxItem* item)
+{
+ ast->clear();
+
+ QFile f(item->text());
+ f.open(QIODevice::ReadOnly);
+ QTextStream str(&f);
+ source->setText(str.read());
+ f.close();
+
+ int result = Driver::parseFile(item->text().ascii(), &projectAST);
+ if (projectAST && (result == 0))
+ {
+ processAST(projectAST);
+ }
+ if (tabWidget2->currentPageIndex() == 1)
+ tabWidget2_selected("Source to be written back");
+}
+
+void Viewer::tabWidget2_selected(const QString& text)
+{
+ if ((text == "Source to be written back") && projectAST)
+ {
+ QString buffer;
+ projectAST->writeBack(buffer);
+ writeBack->setText(buffer);
+ }
+}
+
+void Viewer::processAST(ProjectAST *projectAST, Q3ListViewItem *globAfter)
+{
+ Q3ListViewItem *projectIt;
+ if (!parentProject.top())
+ projectIt = new Q3ListViewItem(ast, "Project");
+ else
+ {
+ if ( projectAST->isConditionalScope() || projectAST->isRule() )
+ projectIt = new Q3ListViewItem(parentProject.top(), globAfter, projectAST->scopedID);
+ }
+ projectIt->setOpen(true);
+
+ Q3ListViewItem *after = 0;
+ for (QList<AST*>::const_iterator it = projectAST->statements.constBegin();
+ it != projectAST->statements.constEnd(); ++it)
+ {
+ AST *ast = *it;
+ if (ast == 0)
+ continue;
+ switch (ast->nodeType()) {
+ case AST::AssignmentAST: {
+ AssignmentAST *assignmentAST = static_cast<AssignmentAST*>(ast);
+ Q3ListViewItem *item = new Q3ListViewItem(projectIt, after,
+ assignmentAST->scopedID, assignmentAST->op, assignmentAST->values.join(""));
+ item->setMultiLinesEnabled(true);
+ after = item; }
+ break;
+
+ case AST::TargetAST:
+ {
+ AutomakeTargetAST* ata = static_cast<AutomakeTargetAST*>(ast);
+ Q3ListViewItem* item = new Q3ListViewItem(projectIt, after,
+ ata->target, QString(), ata->deps.join(""));
+ after = item;
+ }
+ break;
+
+ case AST::NewLineAST:
+// after = new QListViewItem(projectIt, after, "<newline>");
+ break;
+
+ case AST::CommentAST:
+// after = new QListViewItem(projectIt, after, "<comment>");
+ break;
+
+ case AST::MakefileConditionalAST:
+ {
+ ConditionAST* ata = static_cast<ConditionAST*>(ast);
+ Q3ListViewItem* item = new Q3ListViewItem(projectIt, after,
+ ata->type, ata->conditionName, QString() );
+ after = item;
+ }
+ case AST::ProjectAST: {
+ ProjectAST *projectAST = static_cast<ProjectAST*>(ast);
+ parentProject.push(projectIt);
+ processAST(projectAST, after);
+ parentProject.pop(); }
+ break;
+ }
+ }
+}
+
+#include "viewer.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp (revision 1522570)
@@ -0,0 +1,33 @@
+/***************************************************************************
+ * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include <qapplication.h>
+#include "viewer.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Viewer viewer;
+ app.setMainWidget(&viewer);
+ viewer.show();
+ viewer.resize(800, 600);
+ //viewer.setWindowState(viewer.windowState() | Qt::WindowMaximized);
+
+ return app.exec();
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.h (revision 1522570)
@@ -0,0 +1,46 @@
+/***************************************************************************
+ * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef VIEWER_H
+#define VIEWER_H
+
+#include <QStack>
+
+#include "viewerbase.h"
+
+namespace AutoMake { class ProjectAST; }
+
+class Q3ListViewItem;
+
+class Viewer: public QWidget, private Ui::ViewerBase
+{
+Q_OBJECT
+public:
+ Viewer(QWidget *parent = 0);
+ void processAST(AutoMake::ProjectAST *projectAST, Q3ListViewItem *globAfter = 0);
+public slots:
+ virtual void tabWidget2_selected(const QString&);
+ virtual void on_files_currentChanged(Q3ListBoxItem*);
+ virtual void on_choose_clicked();
+ virtual void on_addAll_clicked();
+private:
+ AutoMake::ProjectAST *projectAST;
+ QStack<Q3ListViewItem *> parentProject;
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewer.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/runner.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/runner.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/runner.cpp (revision 1522570)
@@ -0,0 +1,32 @@
+/***************************************************************************
+ * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include <automakeast.h>
+#include <automakedriver.h>
+
+using namespace AutoMake;
+
+int main(int argc, char *argv[])
+{
+ ProjectAST *projectAST;
+ if (argc > 1)
+ return Driver::parseFile(argv[1], &projectAST);
+ else
+ return 0;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/runner.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewerbase.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewerbase.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewerbase.ui (revision 1522570)
@@ -0,0 +1,220 @@
+<!DOCTYPE UI><UI version="3.2" stdsetdef="1">
+<class>ViewerBase</class>
+<widget class="QWidget">
+ <property name="name">
+ <cstring>ViewerBase</cstring>
+ </property>
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>600</width>
+ <height>480</height>
+ </rect>
+ </property>
+ <property name="caption">
+ <string>Viewer</string>
+ </property>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="QLayoutWidget" row="0" column="1" rowspan="4" colspan="1">
+ <property name="name">
+ <cstring>layout2</cstring>
+ </property>
+ <vbox>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="QTextEdit">
+ <property name="name">
+ <cstring>source</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>7</hsizetype>
+ <vsizetype>7</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>1</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ <widget class="QTabWidget">
+ <property name="name">
+ <cstring>tabWidget2</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>7</hsizetype>
+ <vsizetype>7</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>2</verstretch>
+ </sizepolicy>
+ </property>
+ <widget class="QWidget">
+ <property name="name">
+ <cstring>tab</cstring>
+ </property>
+ <attribute name="title">
+ <string>Parse Tree</string>
+ </attribute>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="QListView" row="0" column="0">
+ <column>
+ <property name="text">
+ <string>Name</string>
+ </property>
+ <property name="clickable">
+ <bool>true</bool>
+ </property>
+ <property name="resizable">
+ <bool>true</bool>
+ </property>
+ </column>
+ <column>
+ <property name="text">
+ <string>Value 1</string>
+ </property>
+ <property name="clickable">
+ <bool>true</bool>
+ </property>
+ <property name="resizable">
+ <bool>true</bool>
+ </property>
+ </column>
+ <column>
+ <property name="text">
+ <string>Value 2</string>
+ </property>
+ <property name="clickable">
+ <bool>true</bool>
+ </property>
+ <property name="resizable">
+ <bool>true</bool>
+ </property>
+ </column>
+ <property name="name">
+ <cstring>ast</cstring>
+ </property>
+ </widget>
+ </grid>
+ </widget>
+ <widget class="QWidget">
+ <property name="name">
+ <cstring>tab</cstring>
+ </property>
+ <attribute name="title">
+ <string>Source to Be Written Back</string>
+ </attribute>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="QTextEdit" row="0" column="0">
+ <property name="name">
+ <cstring>writeBack</cstring>
+ </property>
+ </widget>
+ </grid>
+ </widget>
+ </widget>
+ </vbox>
+ </widget>
+ <widget class="QLineEdit" row="0" column="0">
+ <property name="name">
+ <cstring>allLocation</cstring>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>150</width>
+ <height>32767</height>
+ </size>
+ </property>
+ </widget>
+ <widget class="QPushButton" row="1" column="0">
+ <property name="name">
+ <cstring>addAll</cstring>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>150</width>
+ <height>32767</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Add All From Directory</string>
+ </property>
+ </widget>
+ <widget class="QPushButton" row="2" column="0">
+ <property name="name">
+ <cstring>choose</cstring>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>150</width>
+ <height>32767</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Choose File to Add...</string>
+ </property>
+ </widget>
+ <widget class="QListBox" row="3" column="0">
+ <property name="name">
+ <cstring>files</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>7</hsizetype>
+ <vsizetype>7</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>150</width>
+ <height>32767</height>
+ </size>
+ </property>
+ </widget>
+ </grid>
+</widget>
+<connections>
+ <connection>
+ <sender>addAll</sender>
+ <signal>clicked()</signal>
+ <receiver>ViewerBase</receiver>
+ <slot>addAll_clicked()</slot>
+ </connection>
+ <connection>
+ <sender>choose</sender>
+ <signal>clicked()</signal>
+ <receiver>ViewerBase</receiver>
+ <slot>choose_clicked()</slot>
+ </connection>
+ <connection>
+ <sender>files</sender>
+ <signal>currentChanged(Q3ListBoxItem*)</signal>
+ <receiver>ViewerBase</receiver>
+ <slot>files_currentChanged(Q3ListBoxItem*)</slot>
+ </connection>
+ <connection>
+ <sender>tabWidget2</sender>
+ <signal>selected(const QString&amp;)</signal>
+ <receiver>ViewerBase</receiver>
+ <slot>tabWidget2_selected(const QString&amp;)</slot>
+ </connection>
+</connections>
+<slots>
+ <slot>addAll_clicked()</slot>
+ <slot>choose_clicked()</slot>
+ <slot>files_currentChanged(Q3ListBoxItem*)</slot>
+ <slot>tabWidget2_selected(const QString&amp;)</slot>
+</slots>
+<layoutdefaults spacing="6" margin="11"/>
+</UI>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests/viewerbase.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-designer
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/tests
___________________________________________________________________
Added: svn:ignore
## -0,0 +1,3 ##
+Makefile
+Makefile.in
+qtlist
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,57 @@
+project(AutomakeManager)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${AutomakeManager_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+find_package(KDevelop REQUIRED)
+
+#add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9020 )
+add_subdirectory(tests)
+add_subdirectory(automakebuilder)
+
+include_directories(
+ ${AutomakeBuilder_SOURCE_DIR}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDEVELOP_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+########### next target ###############
+
+set(kdevautomakeimporter_SRCS
+ automakeast.cpp
+ automakedriver.cpp
+ automakeparser.cpp
+ makefileinterface.cpp
+ automakeprojectmodel.cpp
+ automakeimporter.cpp
+)
+
+
+set( automakesettings_SRCS
+ settings/automakepreferences.cpp
+)
+
+set( automakesettings_UI
+ settings/automakebuildsettings.ui
+)
+
+
+kde4_add_plugin(kdevautomakeimporter ${kdevautomakeimporter_SRCS})
+target_link_libraries(kdevautomakeimporter ${KDE4_KDECORE_LIBS} ${KDEVPLATFORM_LANGUAGE_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES} )
+
+kde4_add_kcfg_files( automakesettings_SRCS automakeconfig.kcfgc )
+kde4_add_ui_files( automakesettings_SRCS ${automakesettings_UI} )
+kde4_add_plugin( kcm_kdevautomake_settings ${automakesettings_SRCS} )
+target_link_libraries( kcm_kdevautomake_settings ${KDE4_KDEUI_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES})
+
+
+install(TARGETS kdevautomakeimporter DESTINATION ${PLUGIN_INSTALL_DIR} )
+install(TARGETS kcm_kdevautomake_settings DESTINATION ${PLUGIN_INSTALL_DIR} )
+install(FILES kcm_kdevautomake_settings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install(FILES kdevautomakeimporter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp (revision 1522570)
@@ -0,0 +1,66 @@
+/*
+ * KDevelop Automake Support
+ * Copyright 2005 Matt Rogers <mattr@kde.org>
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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.
+ */
+
+#include "automakeprojectmodel.h"
+
+AutoMakeDirItem::AutoMakeDirItem( KDevelop::IProject* p, const KUrl& url, KDevelop::ProjectBaseItem* parent )
+ : KDevelop::ProjectBuildFolderItem( p, url, parent )
+{
+}
+
+AutoMakeDirItem::~AutoMakeDirItem()
+{
+}
+
+
+AutoMakeFileItem::AutoMakeFileItem( KDevelop::IProject* p, const KUrl& url, KDevelop::ProjectBaseItem* parent )
+ : KDevelop::ProjectFileItem( p, url, parent )
+{
+}
+
+AutoMakeFileItem::~AutoMakeFileItem()
+{
+}
+
+AutoMakeTargetItem::AutoMakeTargetItem( KDevelop::IProject* p, const TargetInfo& target, KDevelop::ProjectBaseItem* parent )
+ : KDevelop::ProjectTargetItem( p, target.url.pathOrUrl(), parent )
+{
+ m_target = target;
+ setText( target.name );
+}
+
+AutoMakeTargetItem::~AutoMakeTargetItem()
+{
+}
+
+AutoMakeBaseItem::AutoMakeBaseItem( KDevelop::IProject* p, const QString& target, KDevelop::ProjectBaseItem* parent )
+ : KDevelop::ProjectBaseItem( p, target, parent )
+{
+}
+
+AutoMakeBaseItem::~AutoMakeBaseItem()
+{
+}
+
+int AutoMakeBaseItem::type() const
+{
+ return ProjectBaseItem::Target;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.h (revision 1522570)
@@ -0,0 +1,92 @@
+/* This file is part of KDevelop
+ Copyright 2004 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+
+ 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.
+*/
+#ifndef AUTOMAKEPROJECTMODEL_H
+#define AUTOMAKEPROJECTMODEL_H
+
+#include <QList>
+#include <QIcon>
+#include <kdevplatform/project/projectmodel.h>
+#include "makefileinterface.h"
+
+namespace AutoTools { class ProjectAST; }
+
+class AutoMakeDirItem : public KDevelop::ProjectBuildFolderItem
+{
+public:
+ explicit AutoMakeDirItem( KDevelop::IProject*, const KUrl& url, KDevelop::ProjectBaseItem* parent = 0 );
+ virtual ~AutoMakeDirItem();
+
+ virtual KDevelop::ProjectFolderItem* folder() const
+ {
+ return const_cast<AutoMakeDirItem*>( this );
+ }
+
+ void parseInfoFromAst( AutoTools::ProjectAST* ) {}
+
+};
+
+class AutoMakeFileItem : public KDevelop::ProjectFileItem
+{
+public:
+ explicit AutoMakeFileItem( KDevelop::IProject*, const KUrl& url, KDevelop::ProjectBaseItem* parent = 0 );
+ virtual ~AutoMakeFileItem();
+
+ virtual KDevelop::ProjectFileItem* file() const
+ {
+ return const_cast<AutoMakeFileItem*>( this );
+ }
+};
+
+class AutoMakeTargetItem : public KDevelop::ProjectTargetItem
+{
+public:
+ explicit AutoMakeTargetItem( KDevelop::IProject*, const TargetInfo& target, KDevelop::ProjectBaseItem* parent = 0 );
+
+ virtual ~AutoMakeTargetItem();
+
+ virtual KDevelop::ProjectTargetItem* target() const
+ {
+ return const_cast<AutoMakeTargetItem*>( this );
+ }
+
+ virtual const KUrl::List& includeDirectories() const { return m_includes; }
+ virtual const QHash<QString, QString>& environment() const { return m_environment; }
+ virtual const QList<QPair<QString, QString> >& defines() const { return m_defines; }
+ void parseInfoFromAst( AutoTools::ProjectAST* ) {}
+
+
+private:
+ TargetInfo m_target;
+ KUrl::List m_includes;
+ QHash<QString, QString> m_environment;
+ QList<QPair<QString, QString> > m_defines;
+};
+
+class AutoMakeBaseItem : public KDevelop::ProjectBaseItem
+{
+public:
+ explicit AutoMakeBaseItem( KDevelop::IProject*, const QString& target, KDevelop::ProjectBaseItem* parent = 0 );
+ virtual ~AutoMakeBaseItem();
+
+ virtual int type() const;
+};
+
+#endif // AUTOMAKEPROJECTMODEL_H
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeprojectmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.cpp (revision 1522570)
@@ -0,0 +1,239 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2005 Matt Rogers <mattr@kde.org>
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "automakeimporter.h"
+
+#include <kdebug.h>
+
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+
+#include <interfaces/iplugincontroller.h>
+#include <interfaces/icore.h>
+#include <interfaces/iproject.h>
+
+#include "automakeprojectmodel.h"
+#include "makefileinterface.h"
+#include "iautomakebuilder.h"
+
+K_PLUGIN_FACTORY(AutotoolsSupportFactory, registerPlugin<AutoMakeImporter>(); )
+K_EXPORT_PLUGIN(AutotoolsSupportFactory("kdevautomakeimporter"))
+
+AutoMakeImporter::AutoMakeImporter( QObject* parent,
+ const QVariantList& )
+: KDevelop::IPlugin( AutotoolsSupportFactory::componentData(), parent ), m_rootItem(0L)
+{
+KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBuildSystemManager )
+KDEV_USE_EXTENSION_INTERFACE( KDevelop::IProjectFileManager )
+ m_interface = new MakefileInterface( this );
+
+ IPlugin* i = core()->pluginController()->pluginForExtension( "org.kdevelop.IAutomakeBuilder" );
+ Q_ASSERT(i);
+ m_builder = i->extension<IAutomakeBuilder>();
+ Q_ASSERT(m_builder);
+}
+
+AutoMakeImporter::~AutoMakeImporter()
+{
+ //delete m_rootItem;
+}
+
+KUrl AutoMakeImporter::buildDirectory(KDevelop::ProjectBaseItem* item) const
+{
+ kDebug() << "Looking up buildDirectory for item "<< item->text();
+
+ KUrl out;
+
+ // First we'll need to find the folder in the source directory tree
+ if( item->folder() ) {
+ kDebug() << item->text()<< "is a folder-item";
+ out = item->folder()->url();
+ } else if( item->parent() ) {
+ kDebug() << item->text()<< "must be either a target-item or member of a target-item";
+ KDevelop::ProjectBaseItem* base = static_cast<KDevelop::ProjectBaseItem*>(item->parent());
+ if( base->type() == KDevelop::ProjectBaseItem::Target )
+ {
+ out = static_cast<KDevelop::ProjectFolderItem*>(base->parent())->url();
+ } else {
+ out = static_cast<KDevelop::ProjectFolderItem*>(base)->url();
+ }
+ }
+
+ KConfigGroup automakeGrp = item->project()->projectConfiguration()->group("Automake");
+ KUrl buildDir = automakeGrp.readEntry( "CurrentBuildDir", KUrl() );
+
+ if (buildDir.isValid()) {
+ // If a separat buildDir is defined we need to locate the directory that
+ // matches the upper found directory from the source directory tree
+ kDebug() << "We need to build in a separat build directory";
+
+ KUrl projectPath = m_projectRoot[item->project()];
+ QString relUrl = KUrl::relativeUrl( projectPath, out );
+
+ kDebug() << "Separat buildDir: "<< buildDir;
+ kDebug() << "Relative URL: "<< relUrl;
+
+ buildDir.addPath(relUrl);
+ out = buildDir;
+ }
+
+ out.cleanPath();
+ kDebug() << "BuildDirectory for "<<item->text()<< "is:"<<out;
+
+ return out;
+}
+
+KDevelop::IProjectBuilder* AutoMakeImporter::builder(KDevelop::ProjectFolderItem*) const
+{
+ Q_ASSERT(m_builder);
+ return m_builder;
+}
+
+QList<KDevelop::ProjectFolderItem*> AutoMakeImporter::parse( KDevelop::ProjectFolderItem* item )
+{
+ kDebug() << "Got parse request for"<<item->text()<<"-"<<item->url();
+
+ // create all subdirs and repot them back to the caller
+ QList<KDevelop::ProjectFolderItem*> folder;
+ const QStringList subdirs = m_interface->subdirsFor( item->url() );
+ foreach( const QString& dir, subdirs ) {
+ QString fullPath = item->url().toLocalFile() + QDir::separator() + dir;
+ folder.append( new AutoMakeDirItem(item->project(), fullPath, item) );
+ }
+
+ // fill up this folder with all targets and files
+ createFolderItems( item );
+
+ return folder;
+}
+
+KDevelop::ProjectFolderItem* AutoMakeImporter::import( KDevelop::IProject* project)
+{
+ kDebug() << "Got import request for" << project->folder();
+
+ KUrl folderUrl = project->folder();
+ if (!folderUrl.isLocalFile()) {
+ kDebug() << project->folder() << "is not a local path";
+ return 0;
+ }
+
+ m_interface->setProjectRoot( folderUrl );
+ bool parsedCorrectly = m_interface->parse( folderUrl );
+ if (!parsedCorrectly) {
+ kDebug() << "something went wrong during the parse of "<<folderUrl;
+ return 0;
+ }
+
+ m_projectRoot[project] = folderUrl;
+
+ m_rootItem = new AutoMakeDirItem( project, folderUrl.url(), 0 );
+// m_rootItem->setProjectRoot(true);
+ return m_rootItem;
+}
+
+KUrl AutoMakeImporter::findMakefile( KDevelop::ProjectFolderItem* dom ) const
+{
+ Q_UNUSED( dom );
+ return KUrl();
+}
+
+KUrl::List AutoMakeImporter::findMakefiles( KDevelop::ProjectFolderItem* dom ) const
+{
+ Q_UNUSED( dom );
+ return KUrl::List();
+}
+
+void AutoMakeImporter::createFolderItems( KDevelop::ProjectFolderItem* item )
+{
+ kDebug() << "createProjectItems for"<<item->text()<<"-"<<item->url();
+
+ // check if we got an automake dir
+ AutoMakeDirItem* folderItem = dynamic_cast<AutoMakeDirItem*>(item);
+ if (!folderItem) {
+ kDebug() << item->text()<<"is not an AutoMakeDirItem";
+ return;
+ }
+
+ //now run through all targets for this folder and create the needed items
+ QList<TargetInfo> targets = m_interface->targetsForFolder( folderItem->url() );
+ KDevelop::ProjectBaseItem* dataTarget = 0;
+ KDevelop::ProjectBaseItem* notInstalledHeaders = 0;
+ KDevelop::ProjectBaseItem* installedHeaders = 0;
+
+ foreach( TargetInfo target, targets )
+ {
+ switch( target.type )
+ {
+ case AutoMake::Data:
+ {
+ if ( dataTarget == 0 )
+ dataTarget = new AutoMakeBaseItem( item->project(), "Data", folderItem );
+ QFileInfo rcInfo( target.url.path(), target.name );
+ new AutoMakeFileItem( item->project(), KUrl(rcInfo.absoluteFilePath()), dataTarget );
+ }
+ break;
+ case AutoMake::Headers:
+ if ( target.location != AutoMake::None )
+ {
+ if ( installedHeaders == 0 )
+ installedHeaders = new AutoMakeBaseItem( item->project(), "Installed headers", folderItem );
+ QFileInfo headerInfo( target.url.path(), target.name );
+ new AutoMakeFileItem( item->project(), KUrl(headerInfo.absoluteFilePath()), installedHeaders );
+ }
+ else
+ {
+ if ( notInstalledHeaders == 0 )
+ notInstalledHeaders = new AutoMakeBaseItem( item->project(), "Not Installed headers", folderItem );
+ QFileInfo headerInfo( target.url.path(), target.name );
+ new AutoMakeFileItem( item->project(), KUrl(headerInfo.absoluteFilePath()), notInstalledHeaders );
+ }
+ break;
+ case AutoMake::Program:
+ case AutoMake::Library:
+ case AutoMake::LibtoolLibrary:
+ default:
+ AutoMakeTargetItem* targetItem = new AutoMakeTargetItem( item->project(), target, folderItem );
+ QList<QFileInfo> targetFiles = m_interface->filesForTarget( target );
+ foreach( const QFileInfo& fi, targetFiles ) {
+ new AutoMakeFileItem( item->project(), KUrl(fi.absoluteFilePath()), targetItem );
+ }
+ break;
+ };
+ }
+
+ // add Makefile.am and other common files that are not mentioned inside Makefile.am
+ // but should nevertheless be added to the projectmodel
+ QFileInfo makefile(folderItem->url().toLocalFile(), "Makefile.am");
+ if (makefile.exists()) {
+ kDebug() << "Adding "<<makefile.absoluteFilePath();
+ new KDevelop::ProjectFileItem( item->project(), makefile.absoluteFilePath(), folderItem );
+ }
+}
+
+QList<KDevelop::ProjectTargetItem*> AutoMakeImporter::targets() const
+{
+ return QList<KDevelop::ProjectTargetItem*>();
+}
+
+QList< KDevelop::ProjectTargetItem * > AutoMakeImporter::targets(KDevelop::ProjectFolderItem * folder) const
+{
+ return folder->targetList();
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.h (revision 1522570)
@@ -0,0 +1,120 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2005 Matt Rogers <mattr@kde.org>
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef AUTOMAKEIMPORTER_H
+#define AUTOMAKEIMPORTER_H
+
+#include <QList>
+#include <QString>
+#include <QtCore/QVariant>
+#include <kdevplatform/project/interfaces/ibuildsystemmanager.h>
+#include <interfaces/iplugin.h>
+
+class QObject;
+
+class AutoMakeItem;
+class MakefileInterface;
+class QDir;
+class IAutomakeBuilder;
+
+namespace KDevelop
+{
+ class IProject;
+ class IProjectBuilder;
+ class ProjectBaseItem;
+ class ProjectFileItem;
+ class ProjectFolderItem;
+ class ProjectTargetItem;
+}
+
+
+class AutoMakeImporter : public KDevelop::IPlugin, public KDevelop::IBuildSystemManager
+{
+Q_OBJECT
+Q_INTERFACES( KDevelop::IBuildSystemManager )
+Q_INTERFACES( KDevelop::IProjectFileManager )
+
+public:
+
+ virtual Features features() const { return Features(Folders | Targets | Files); }
+
+ explicit AutoMakeImporter( QObject* parent = 0, const QVariantList& args = QVariantList() );
+ virtual ~AutoMakeImporter();
+
+ virtual KDevelop::IProjectBuilder* builder(KDevelop::ProjectFolderItem*) const;
+ virtual KUrl buildDirectory(KDevelop::ProjectBaseItem*) const;
+ virtual KUrl::List includeDirectories(KDevelop::ProjectBaseItem*) const { return KUrl::List(); }
+// virtual KUrl::List preprocessorDefines() const { return KUrl::List(); }
+
+ virtual KDevelop::ProjectFolderItem* addFolder( const KUrl&, KDevelop::ProjectFolderItem* ) { return 0; }
+
+ virtual QHash< QString, QString > defines(KDevelop::ProjectBaseItem *) const { return QHash<QString, QString>(); }
+ virtual QHash<QString, QString> environment(KDevelop::ProjectBaseItem*) const { return QHash<QString,QString>(); }
+
+ virtual KDevelop::ProjectTargetItem* createTarget( const QString&,
+ KDevelop::ProjectFolderItem* ) { return false; }
+
+ virtual KDevelop::ProjectFileItem* addFile( const KUrl&,
+ KDevelop::ProjectFolderItem* ) { return false; }
+
+ virtual bool addFileToTarget( KDevelop::ProjectFileItem*, KDevelop::ProjectTargetItem* ) { return false; }
+
+ virtual bool removeFolder( KDevelop::ProjectFolderItem* ) { return false; }
+
+ virtual bool removeTarget( KDevelop::ProjectTargetItem* ) { return false; }
+
+ virtual bool removeFile( KDevelop::ProjectFileItem* ) { return false; }
+ virtual bool removeFileFromTarget( KDevelop::ProjectFileItem*,
+ KDevelop::ProjectTargetItem* ) { return false; }
+
+ virtual bool removeFilesAndFolders(QList<KDevelop::ProjectBaseItem*>){return false;}
+ virtual bool removeFilesFromTargets(QList<QPair<KDevelop::ProjectTargetItem*, KDevelop::ProjectFileItem*> >){return false;}
+
+ virtual bool renameFile(KDevelop::ProjectFileItem*, const KUrl&) { return false; }
+ virtual bool renameFolder(KDevelop::ProjectFolderItem*, const KUrl&) { return false; }
+
+
+ virtual QList<KDevelop::ProjectTargetItem*> targets() const;
+ virtual QList<KDevelop::ProjectTargetItem*> targets(KDevelop::ProjectFolderItem* folder) const;
+
+ virtual QList<KDevelop::ProjectFolderItem*> parse( KDevelop::ProjectFolderItem* dom );
+ virtual KDevelop::ProjectFolderItem* import( KDevelop::IProject* project);
+
+
+ virtual bool reload(KDevelop::ProjectFolderItem*) { return false; }
+ virtual KUrl findMakefile( KDevelop::ProjectFolderItem* dom ) const;
+ virtual KUrl::List findMakefiles( KDevelop::ProjectFolderItem* dom ) const;
+
+private:
+ void createFolderItems( KDevelop::ProjectFolderItem* );
+
+
+ KDevelop::ProjectFolderItem* m_rootItem;
+ MakefileInterface* m_interface;
+
+ IAutomakeBuilder* m_builder;
+
+ QMap<KDevelop::IProject*, KUrl> m_projectRoot;
+};
+
+#endif
+// kate: indent-mode cstyle; space-indent off; tab-width 4; auto-insert-doxygen on;
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeimporter.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc -o -name \*.ui | grep -v '/tests/'` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h | grep -v '/tests/'` -o $podir/kdevautomake.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui (revision 1522570)
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>AutomakeBuildSettings</class>
+ <widget class="QWidget" name="AutomakeBuildSettings">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>605</width>
+ <height>36</height>
+ </rect>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Build Directory</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="KUrlRequester" name="kcfg_currentBuildDir"/>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KUrlRequester</class>
+ <extends>QFrame</extends>
+ <header>kurlrequester.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp (revision 1522570)
@@ -0,0 +1,49 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "automakepreferences.h"
+
+#include <KPluginFactory>
+#include <KUrl>
+
+#include "automakeconfig.h"
+#include "ui_automakebuildsettings.h"
+
+K_PLUGIN_FACTORY(AutomakePreferencesFactory, registerPlugin<AutomakePreferences>(); )
+K_EXPORT_PLUGIN(AutomakePreferencesFactory("kcm_kdevautomake_settings"))
+
+AutomakePreferences::AutomakePreferences(QWidget* parent, const QVariantList& args)
+ : ProjectKCModule<AutomakeSettings>(AutomakePreferencesFactory::componentData(), parent, args)
+{
+ QVBoxLayout* l = new QVBoxLayout( this );
+ QWidget* w = new QWidget;
+ m_prefsUi = new Ui::AutomakeBuildSettings;
+ m_prefsUi->setupUi( w );
+ m_prefsUi->kcfg_currentBuildDir->setMode(KFile::Directory|KFile::ExistingOnly);
+ l->addWidget( w );
+
+ addConfig( AutomakeSettings::self(), w );
+ load();
+}
+
+AutomakePreferences::~AutomakePreferences()
+{}
+
+#include "automakepreferences.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/settings/automakepreferences.h (revision 1522570)
@@ -0,0 +1,44 @@
+/* KDevelop Automake Support
+ *
+ * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef AUTOMAKEPREFERENCES_H
+#define AUTOMAKEPREFERENCES_H
+
+#include <project/projectkcmodule.h>
+
+class AutomakeSettings;
+
+namespace Ui { class AutomakeBuildSettings; }
+
+/**
+ * @author Robert Gruber <rgruber@users.sourceforge.net>
+ */
+class AutomakePreferences : public ProjectKCModule<AutomakeSettings>
+{
+ Q_OBJECT
+ public:
+ explicit AutomakePreferences(QWidget* parent = 0, const QVariantList& args = QVariantList());
+ ~AutomakePreferences();
+
+ private:
+ Ui::AutomakeBuildSettings* m_prefsUi;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfg
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfg (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfg (revision 1522570)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE kcfg SYSTEM "http://www.kde.org/standards/kcfg/1.0/kcfg.dtd">
+<kcfg>
+ <kcfgfile arg="true"/>
+ <group name="Automake">
+ <entry name="currentBuildDir" key="CurrentBuildDir" type="Url" />
+ </group>
+</kcfg>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc (revision 1522570)
@@ -0,0 +1,5 @@
+File=automakeconfig.kcfg
+ClassName=AutomakeSettings
+Singleton=true
+Inherits=KDevelop::ProjectConfigSkeleton
+IncludeFiles=project/projectconfigskeleton.h
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.cpp (revision 1522570)
@@ -0,0 +1,109 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "automakeast.h"
+
+namespace AutoMake {
+
+//AST
+
+AST::~AST()
+{
+ qDeleteAll( m_children );
+}
+
+void AST::addChildAST(AST *node)
+{
+ m_children.append(node);
+}
+
+void AST::writeBack(QString &buffer)
+{
+ foreach( AST* a, m_children )
+ {
+ a->writeBack(buffer);
+ }
+}
+
+QString AST::indentation()
+{
+ QString result;
+ for (int i = 0; i < depth(); i++)
+ result += '\t';
+ return result;
+}
+
+bool AST::hasChildren() const
+{
+ return !m_children.isEmpty();
+}
+
+QList<AST*> AST::children() const
+{
+ return m_children;
+}
+
+//ProjectAST
+
+void ProjectAST::writeBack(QString &buffer)
+{
+ if ( isRule() )
+ buffer += scopedID;
+ else
+ buffer += indentation();
+
+ AST::writeBack(buffer);
+
+}
+
+void ProjectAST::addChildAST(AST *node)
+{
+ statements.append(node);
+ AST::addChildAST(node);
+}
+
+void AssignmentAST::writeBack(QString &buffer)
+{
+ buffer += indentation() + scopedID + ' ' + op + ' ' + values.join(" ");
+}
+
+void AutomakeTargetAST::writeBack( QString& buffer )
+{
+ buffer += target + ':' + deps.join("");
+}
+
+void ConditionAST::writeBack( QString& buffer )
+{
+ buffer += indentation() + type + ' ' + conditionName;
+}
+
+void NewLineAST::writeBack(QString &buffer)
+{
+ buffer += '\n';
+}
+
+void CommentAST::writeBack(QString &buffer)
+{
+ buffer += indentation() + comment;
+}
+
+}
+
+// kate: indent-mode csands; tab-width 4; space-indent off;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.h (revision 1522570)
@@ -0,0 +1,59 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef AUTOMAKEDRIVER_H
+#define AUTOMAKEDRIVER_H
+
+#include <qlist.h>
+#include <kurl.h>
+
+namespace AutoMake {
+
+/**
+@file autotoolsdriver.h
+Driver for a automake parser.
+*/
+
+class ProjectAST;
+
+/**
+ * Driver.
+ * Use methods of this class to lauch parsing and build the AST.
+ */
+class Driver
+{
+public:
+ /**
+ * Parses the file @p fileName and stores the resulting ProjectAST root
+ * into @p ast. @p ast should not be initialized before. Driver will
+ * initialize it on its own.
+ * @return The result of parsing. Result is 0 on success and <> 0 on failure.
+ */
+ static int parseFile(const char *fileName, ProjectAST **ast);
+ static int parseFile(const QString& fileName, ProjectAST **ast);
+ static int parseFile(const KUrl & fileName, ProjectAST **ast);
+
+};
+
+}
+
+#endif
+
+// kate: indent-mode csands; tab-width 4; space-indent off; auto-insert-doxygen on;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.h (revision 1522570)
@@ -0,0 +1,102 @@
+/* KDevelop Automake Support
+ *
+ * Copyright (C) 2005 Matt Rogers <mattr@kde.org>
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef MAKEFILEINTERFACE_H
+#define MAKEFILEINTERFACE_H
+
+#include <QObject>
+#include <QRegExp>
+#include <QDir>
+#include <kurl.h>
+
+class QFileInfo;
+
+namespace AutoMake
+{
+ class ProjectAST;
+ enum TargetType { Program, Library, LibtoolLibrary, Lisp, Python, Java,
+ Scripts, Data, Headers, ManPages, Texinfo, Unknown };
+ enum InstallLocation { Bin, Libexec, Lib, None, Check, Info, Man, Custom };
+
+ const QRegExp targetPrimaries = QRegExp( "_(PROGRAMS|LIBRARIES|LISP|PYTHON|JAVA|SCRIPTS|DATA|HEADERS|MANS|TEXINFOS|LTLIBRARIES)" );
+
+ TargetType convertToType( const QString& );
+ InstallLocation convertToLocation( const QString& );
+
+}
+
+template <typename T> class QList;
+template <typename T1, typename T2> class QMap;
+template <typename T1, typename T2> class QHash;
+
+typedef QHash<QFileInfo, AutoMake::ProjectAST*> AutoMakeASTHash;
+typedef QMap<QFileInfo, AutoMake::ProjectAST*> AutoMakeASTMap;
+typedef QList<AutoMake::ProjectAST*> AutoMakeASTList;
+
+struct TargetInfo
+{
+ AutoMake::TargetType type;
+ AutoMake::InstallLocation location;
+ QString name;
+ KUrl url;
+ QString display;
+};
+
+class MakefileInterface : public QObject
+{
+ Q_OBJECT
+public:
+ enum ParserRecursion { Recursive, NonRecursive };
+ enum TargetType { Program, Library, LibtoolLibrary, Lisp, Python, Java,
+ Scripts, Data, Headers, ManPages, Texinfo };
+ enum InstallLocations { Bin, Libexec, Lib, None, Check, Info, Man, Extra };
+
+ MakefileInterface( QObject* parent );
+ ~MakefileInterface();
+
+ static QString canonicalize( const QString& target );
+ static bool isVariable( const QString& item );
+
+ QString resolveVariable( const QString& variable, AutoMake::ProjectAST* ast ) const;
+
+ bool parse( const KUrl& dir, ParserRecursion recursive = Recursive );
+
+ QString projectRoot() const;
+ void setProjectRoot( const KUrl& dir );
+ QStringList topSubDirs() const;
+ QStringList subdirsFor( const KUrl& dir ) const;
+
+ QList<TargetInfo> targetsForFolder( const KUrl& dir ) const;
+ QList<QFileInfo> filesForTarget( const TargetInfo& ) const;
+
+private:
+ QStringList subdirsFor( AutoMake::ProjectAST* ) const;
+ AutoMake::ProjectAST* astForFolder( const KUrl& dir ) const;
+ QStringList valuesForId( const QString&, AutoMake::ProjectAST* ) const;
+
+private:
+ class Private;
+ Private* d;
+
+};
+
+#endif
+
+//kate: hl c++;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/makefileinterface.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.h (revision 1522570)
@@ -0,0 +1,267 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef AUTOMAKEAST_H
+#define AUTOMAKEAST_H
+
+#include <QList>
+#include <QStringList>
+
+/**
+@file autotools.h
+Abstract Syntax Tree (AST) class declarations.
+*/
+
+namespace AutoMake
+{
+
+/**
+ * AST node.
+ * This is the base class. Objects of this type are not created by the parser.
+ *
+ * Each AST node holds the list of its children which are always deleted in the
+ * destructor. This way, it's possible call delete for only root AST node and
+ * others will be deleted automatically.
+ *
+ * Each AST node also knows how to write the information back into .pro file.
+ */
+class AST
+{
+public:
+ /**Type of AST node.*/
+ enum NodeType {
+ ProjectAST, ///< Project, scope or function scope.
+ AssignmentAST, ///< Variable assignment.
+ TargetAST, ///< Automake target
+ MakefileConditionalAST, ///< Makefile.am conditional
+ NewLineAST, ///< Line feed.
+ CommentAST ///< Comment.
+ };
+
+ /** Constructs AST with given node type.*/
+ AST(NodeType nodeType): m_nodeType(nodeType), m_depth(0) {}
+ virtual ~AST();
+
+ /**
+ * Adds child AST node to this node. Despite this function is virtual,
+ * reimplementations should call it to make automatic destruction of
+ * AST tree possible.*/
+ virtual void addChildAST(AST *node);
+
+ /**
+ * Writes information stored in the AST into the @p buffer.
+ * This is a default implementation which iterates over child nodes
+ * and calls writeBack for each child node.
+ */
+ virtual void writeBack(QString &buffer);
+
+ /** @return The type of the node.*/
+ virtual NodeType nodeType() const { return m_nodeType; }
+
+ /** Sets the depth of the node in AST.*/
+ void setDepth(int depth) { m_depth = depth; }
+
+ /** @return The depth of the node in AST.*/
+ int depth() const { return m_depth; }
+
+ /** @return The indentation string based on node depth.*/
+ virtual QString indentation();
+
+ //! \return true if this AST has children
+ bool hasChildren() const;
+
+ /**
+ * Get the children of this ast
+ * \return the list of this ast's children
+ */
+ QList<AST*> children() const;
+
+
+
+protected:
+ NodeType m_nodeType;
+ QList<AST*> m_children;
+
+private:
+ int m_depth;
+
+};
+
+
+/**
+ * Project AST node.
+ * Represents complete projects, scopes and function scopes.
+ * Examples:
+ * @code
+ * scopename{
+ * var=value
+ * }
+ * function(args){
+ * var=value
+ * }
+ * @endcode
+ */
+class ProjectAST: public AST
+{
+public:
+ /**The kind of a project node.*/
+ enum Kind
+ {
+ Project, ///< Project
+ Target, ///< Custom Automake Target
+ ConditionalScope, ///< Automake Conditional
+ Rule, ///< Automake Rule
+ Empty ///< Project does not exist. the AST is empty
+ };
+
+ /** Constructs a project node of given @p kind. */
+ ProjectAST(Kind kind = Project): AST(AST::ProjectAST), m_kind(kind) {}
+
+ virtual void writeBack(QString &buffer);
+ virtual void addChildAST(AST *node);
+
+ /** @return true if this node is a project.*/
+ bool isProject() const { return m_kind == Project; }
+
+ bool isRule() const { return m_kind == Rule; }
+
+ /** @return true if this node is an automake conditional */
+ bool isConditionalScope() const { return m_kind == ConditionalScope; }
+
+ /** @return true if this node is empty.*/
+ bool isEmpty() const { return m_kind == Empty; }
+
+ /**Scoped identifier (scope name or rule).*/
+ QString scopedID;
+
+ /**Function arguments. Empty for other kinds of projects.*/
+ QString args;
+
+ /** The automake conditional has an else attached */
+ bool hasElse;
+
+ /**List of statements.*/
+ QList<AutoMake::AST*> statements;
+
+private:
+ Kind m_kind;
+
+};
+
+
+/**
+ * Assignment AST node.
+ * Represents assignments, for example:
+ * \code
+ * var=value
+ * \endcode
+ *
+ * Values can be specified on several lines and
+ * each line is stored as a string in the list of values.@n
+ * For example, if we have in .pro:
+ * \code
+ * SOURCES=a.cpp \
+ * b.cpp c.cpp
+ * \endcode
+ * then values will be stored as a two elements list:
+ * \code
+ * a.cpp
+ * b.cpp c.cpp
+ * \endcode
+ */
+class AssignmentAST: public AST
+{
+public:
+ AssignmentAST(): AST(AST::AssignmentAST) {}
+
+ virtual void writeBack(QString &buffer);
+
+ /**Scoped name of the variable.*/
+ QString scopedID;
+
+ /**Operator.*/
+ QString op;
+
+ /**List of values.*/
+ QStringList values;
+};
+
+class AutomakeTargetAST : public AST
+{
+public:
+ AutomakeTargetAST() : AST(AST::TargetAST) {}
+
+ virtual void writeBack( QString& buffer );
+
+ /// The name of the target
+ QString target;
+
+ /// The dependencies for the target, if any
+ QStringList deps;
+};
+
+class ConditionAST : public AST
+{
+public:
+ ConditionAST() : AST( AST::MakefileConditionalAST ) {}
+
+ virtual void writeBack( QString& buffer );
+
+ /// The keyword for the condition (if, else, endif)
+ QString type;
+
+ /// The name of the condition
+ QString conditionName;
+};
+
+/**
+ * New line AST node.
+ * Represents line feeds in files.
+ */
+class NewLineAST: public AST
+{
+public:
+ NewLineAST(): AST(AST::NewLineAST) {}
+
+ virtual void writeBack(QString &buffer);
+};
+
+
+/**
+ * Comment AST node.
+ * Represents comments.
+ */
+class CommentAST: public AST
+{
+public:
+ CommentAST(): AST(AST::CommentAST) {}
+
+ virtual void writeBack(QString &buffer);
+
+ /**Comment text.*/
+ QString comment;
+
+};
+
+}
+
+#endif
+
+// kate: indent-mode csands; space-indent off; tab-width 4; auto-insert-doxygen on;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeast.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.ll
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.ll (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.ll (revision 1522570)
@@ -0,0 +1,136 @@
+%{
+/***************************************************************************
+ * Copyright 2006 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "autoconfparser.h"
+#include <stdlib.h>
+
+/**
+@file autoconf.ll
+Autoconf Lexer
+
+There are 3 types of identifiers recognized by this lexer:
+-id_simple: examples of such identifiers are qmake variables and scoped variables
+at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
+-id_list: those are "value list identifiers" at the right side in assignments
+(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
+-id_args: function arguments recognized as one identifier
+(example: ""${QMAKE_FILE} is intended only for Windows!""
+in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
+.
+
+To recognize those identifiers two additional start conditions are used: list and funcargs.
+
+@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
+the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
+so no indentation is preserved by this lexer (and parser).
+
+To debug this lexer, put the line below into the next flex file section.
+%option debug
+*/
+%}
+%option noyywrap
+%x list
+%x funcargs
+%x conditional
+
+delim [ \t]
+ws {delim}+
+letter [A-Za-z]
+digit [0-9]
+id_simple ({digit}|{letter}|\!|-|_|\*|\$|@)({letter}|{digit}|\||\!|-|_|\*|\$|\(|\.|\+|\-|\)|\/)*
+id_list [^\n#]*\\{ws}*
+id_args [^\n]*\)
+number {digit}+
+comment #.*
+comment_cont {ws}#.*\n
+id_list_single [^\n]*
+cont \\{ws}*\n
+keywords (if|else|endif|include)
+rule [\t]+[^\n]*
+
+%%
+
+<list,INITIAL>{ws} {}
+<list,INITIAL>{cont} { BEGIN(list); return CONT; }
+{keywords} {
+ yylval.value = yytext;
+ if ( yylval.value == "if" )
+ return IF_KEYWORD;
+
+ if ( yylval.value == "else" )
+ return ELSE_KEYWORD;
+
+ if ( yylval.value == "endif" )
+ return ENDIF_KEYWORD;
+
+ return KEYWORD;
+}
+
+
+{id_simple} { yylval.value = yytext; return (ID_SIMPLE); }
+
+<INITIAL>{rule} {
+ yylval.value = yytext;
+ return RULE;
+}
+
+<list>{id_list} {
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
+ unput('\\');
+ BEGIN(INITIAL);
+ return (ID_LIST);
+ }
+
+<list>{comment_cont} {
+ yylval.value = yytext;
+ BEGIN(list);
+ return (LIST_COMMENT);
+ }
+
+<list>{comment} {
+ yylval.value = yytext;
+ return LIST_COMMENT;
+ }
+
+<list>{id_list_single} {
+ yylval.value = yytext;
+ BEGIN(INITIAL);
+ return (ID_LIST_SINGLE);
+ }
+
+<funcargs>{id_args} {
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.length()-1);
+ unput(')');
+ BEGIN(INITIAL);
+ return (ID_ARGS);
+ }
+
+"=" { BEGIN(list); yylval.value = yytext; return EQ; }
+"+=" { BEGIN(list); yylval.value = yytext; return PLUSEQ; }
+"{" { return LCURLY; }
+"}" { return RCURLY; }
+":" { BEGIN(list); yylval.value = yytext; return COLON; }
+<list,INITIAL>"\n" { BEGIN(INITIAL); return NEWLINE; }
+{comment} { yylval.value = yytext; return (COMMENT); }
+
+%%
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.ll
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake_lex.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake_lex.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake_lex.cpp (revision 1522570)
@@ -0,0 +1,1896 @@
+#line 2 "autotools_lex.cpp"
+
+#line 4 "autotools_lex.cpp"
+
+#define YY_INT_ALIGNED short int
+
+/* A lexical scanner generated by flex */
+
+#define FLEX_SCANNER
+#define YY_FLEX_MAJOR_VERSION 2
+#define YY_FLEX_MINOR_VERSION 5
+#define YY_FLEX_SUBMINOR_VERSION 31
+#if YY_FLEX_SUBMINOR_VERSION > 0
+#define FLEX_BETA
+#endif
+
+/* First, we deal with platform-specific or compiler-specific issues. */
+
+/* begin standard C headers. */
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+/* end standard C headers. */
+
+/* flex integer type definitions */
+
+#ifndef FLEXINT_H
+#define FLEXINT_H
+
+/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
+
+#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#include <inttypes.h>
+typedef int8_t flex_int8_t;
+typedef uint8_t flex_uint8_t;
+typedef int16_t flex_int16_t;
+typedef uint16_t flex_uint16_t;
+typedef int32_t flex_int32_t;
+typedef uint32_t flex_uint32_t;
+#else
+typedef signed char flex_int8_t;
+typedef short int flex_int16_t;
+typedef int flex_int32_t;
+typedef unsigned char flex_uint8_t;
+typedef unsigned short int flex_uint16_t;
+typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
+
+/* Limits of integral types. */
+#ifndef INT8_MIN
+#define INT8_MIN (-128)
+#endif
+#ifndef INT16_MIN
+#define INT16_MIN (-32767-1)
+#endif
+#ifndef INT32_MIN
+#define INT32_MIN (-2147483647-1)
+#endif
+#ifndef INT8_MAX
+#define INT8_MAX (127)
+#endif
+#ifndef INT16_MAX
+#define INT16_MAX (32767)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX (2147483647)
+#endif
+#ifndef UINT8_MAX
+#define UINT8_MAX (255U)
+#endif
+#ifndef UINT16_MAX
+#define UINT16_MAX (65535U)
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX (4294967295U)
+#endif
+
+#endif /* ! FLEXINT_H */
+
+#ifdef __cplusplus
+
+/* The "const" storage-class-modifier is valid. */
+#define YY_USE_CONST
+
+#else /* ! __cplusplus */
+
+#if __STDC__
+
+#define YY_USE_CONST
+
+#endif /* __STDC__ */
+#endif /* ! __cplusplus */
+
+#ifdef YY_USE_CONST
+#define yyconst const
+#else
+#define yyconst
+#endif
+
+/* Returned upon end-of-file. */
+#define YY_NULL 0
+
+/* Promotes a possibly negative, possibly signed char to an unsigned
+ * integer for use as an array index. If the signed char is negative,
+ * we want to instead treat it as an 8-bit unsigned char, hence the
+ * double cast.
+ */
+#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+
+/* Enter a start condition. This macro really ought to take a parameter,
+ * but we do it the disgusting crufty way forced on us by the ()-less
+ * definition of BEGIN.
+ */
+#define BEGIN (yy_start) = 1 + 2 *
+
+/* Translate the current start state into a value that can be later handed
+ * to BEGIN to return to the state. The YYSTATE alias is for lex
+ * compatibility.
+ */
+#define YY_START (((yy_start) - 1) / 2)
+#define YYSTATE YY_START
+
+/* Action number for EOF rule of a given start state. */
+#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
+
+/* Special action meaning "start processing a new file". */
+#define YY_NEW_FILE yyrestart(yyin )
+
+#define YY_END_OF_BUFFER_CHAR 0
+
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#define YY_BUF_SIZE 16384
+#endif
+
+#ifndef YY_TYPEDEF_YY_BUFFER_STATE
+#define YY_TYPEDEF_YY_BUFFER_STATE
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+#endif
+
+extern int yyleng;
+
+extern FILE *yyin, *yyout;
+
+#define EOB_ACT_CONTINUE_SCAN 0
+#define EOB_ACT_END_OF_FILE 1
+#define EOB_ACT_LAST_MATCH 2
+
+ #define YY_LESS_LINENO(n)
+
+/* Return all but the first "n" matched characters back to the input stream. */
+#define yyless(n) \
+ do \
+ { \
+ /* Undo effects of setting up yytext. */ \
+ int yyless_macro_arg = (n); \
+ YY_LESS_LINENO(yyless_macro_arg);\
+ *yy_cp = (yy_hold_char); \
+ YY_RESTORE_YY_MORE_OFFSET \
+ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+ YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+ } \
+ while ( 0 )
+
+#define unput(c) yyunput( c, (yytext_ptr) )
+
+/* The following is because we cannot portably get our hands on size_t
+ * (without autoconf's help, which isn't available because we want
+ * flex-generated scanners to compile on their own).
+ */
+
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef unsigned int yy_size_t;
+#endif
+
+#ifndef YY_STRUCT_YY_BUFFER_STATE
+#define YY_STRUCT_YY_BUFFER_STATE
+struct yy_buffer_state
+ {
+ FILE *yy_input_file;
+
+ char *yy_ch_buf; /* input buffer */
+ char *yy_buf_pos; /* current position in input buffer */
+
+ /* Size of input buffer in bytes, not including room for EOB
+ * characters.
+ */
+ yy_size_t yy_buf_size;
+
+ /* Number of characters read into yy_ch_buf, not including EOB
+ * characters.
+ */
+ int yy_n_chars;
+
+ /* Whether we "own" the buffer - i.e., we know we created it,
+ * and can realloc() it to grow it, and should free() it to
+ * delete it.
+ */
+ int yy_is_our_buffer;
+
+ /* Whether this is an "interactive" input source; if so, and
+ * if we're using stdio for input, then we want to use getc()
+ * instead of fread(), to make sure we stop fetching input after
+ * each newline.
+ */
+ int yy_is_interactive;
+
+ /* Whether we're considered to be at the beginning of a line.
+ * If so, '^' rules will be active on the next match, otherwise
+ * not.
+ */
+ int yy_at_bol;
+
+ int yy_bs_lineno; /**< The line count. */
+ int yy_bs_column; /**< The column count. */
+
+ /* Whether to try to fill the input buffer when we reach the
+ * end of it.
+ */
+ int yy_fill_buffer;
+
+ int yy_buffer_status;
+
+#define YY_BUFFER_NEW 0
+#define YY_BUFFER_NORMAL 1
+ /* When an EOF's been seen but there's still some text to process
+ * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+ * shouldn't try reading from the input source any more. We might
+ * still have a bunch of tokens to match, though, because of
+ * possible backing-up.
+ *
+ * When we actually see the EOF, we change the status to "new"
+ * (via yyrestart()), so that the user can continue scanning by
+ * just pointing yyin at a new input file.
+ */
+#define YY_BUFFER_EOF_PENDING 2
+
+ };
+#endif /* !YY_STRUCT_YY_BUFFER_STATE */
+
+/* Stack of input buffers. */
+static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
+static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
+static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
+
+/* We provide macros for accessing buffer states in case in the
+ * future we want to put the buffer states in a more general
+ * "scanner state".
+ *
+ * Returns the top of the stack, or NULL.
+ */
+#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
+ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
+ : NULL)
+
+/* Same as previous macro, but useful when we know that the buffer stack is not
+ * NULL or when we need an lvalue. For internal use only.
+ */
+#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
+
+/* yy_hold_char holds the character lost when yytext is formed. */
+static char yy_hold_char;
+static int yy_n_chars; /* number of characters read into yy_ch_buf */
+int yyleng;
+
+/* Points to current character in buffer. */
+static char *yy_c_buf_p = (char *) 0;
+static int yy_init = 1; /* whether we need to initialize */
+static int yy_start = 0; /* start state number */
+
+/* Flag which is used to allow yywrap()'s to do buffer switches
+ * instead of setting up a fresh yyin. A bit of a hack ...
+ */
+static int yy_did_buffer_switch_on_eof;
+
+void yyrestart (FILE *input_file );
+void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
+YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
+void yy_delete_buffer (YY_BUFFER_STATE b );
+void yy_flush_buffer (YY_BUFFER_STATE b );
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
+void yypop_buffer_state (void );
+
+static void yyensure_buffer_stack (void );
+static void yy_load_buffer_state (void );
+static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
+
+#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
+
+YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
+YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len );
+
+void *yyalloc (yy_size_t );
+void *yyrealloc (void *,yy_size_t );
+void yyfree (void * );
+
+#define yy_new_buffer yy_create_buffer
+
+#define yy_set_interactive(is_interactive) \
+ { \
+ if ( ! YY_CURRENT_BUFFER ){ \
+ yyensure_buffer_stack (); \
+ YY_CURRENT_BUFFER_LVALUE = \
+ yy_create_buffer(yyin,YY_BUF_SIZE ); \
+ } \
+ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+ }
+
+#define yy_set_bol(at_bol) \
+ { \
+ if ( ! YY_CURRENT_BUFFER ){\
+ yyensure_buffer_stack (); \
+ YY_CURRENT_BUFFER_LVALUE = \
+ yy_create_buffer(yyin,YY_BUF_SIZE ); \
+ } \
+ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+ }
+
+#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
+
+/* Begin user sect3 */
+
+#define yywrap(n) 1
+#define YY_SKIP_YYWRAP
+
+typedef unsigned char YY_CHAR;
+
+FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
+
+typedef int yy_state_type;
+
+extern int yylineno;
+
+int yylineno = 1;
+
+extern char *yytext;
+#define yytext_ptr yytext
+
+static yy_state_type yy_get_previous_state (void );
+static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
+static int yy_get_next_buffer (void );
+static void yy_fatal_error (yyconst char msg[] );
+
+/* Done after the current pattern has been matched and before the
+ * corresponding action - sets up yytext.
+ */
+#define YY_DO_BEFORE_ACTION \
+ (yytext_ptr) = yy_bp; \
+ yyleng = (size_t) (yy_cp - yy_bp); \
+ (yy_hold_char) = *yy_cp; \
+ *yy_cp = '\0'; \
+ (yy_c_buf_p) = yy_cp;
+
+#define YY_NUM_RULES 18
+#define YY_END_OF_BUFFER 19
+/* This struct is not used in this scanner,
+ but its presence is necessary. */
+struct yy_trans_info
+ {
+ flex_int32_t yy_verify;
+ flex_int32_t yy_nxt;
+ };
+static yyconst flex_int16_t yy_accept[64] =
+ { 0,
+ 0, 0, 9, 9, 0, 0, 0, 0, 19, 18,
+ 1, 16, 1, 4, 17, 18, 15, 11, 18, 4,
+ 4, 13, 14, 9, 1, 8, 6, 18, 10, 5,
+ 1, 1, 1, 4, 4, 17, 12, 0, 2, 4,
+ 4, 3, 4, 9, 9, 6, 1, 9, 8, 6,
+ 0, 10, 4, 4, 4, 6, 9, 7, 4, 4,
+ 4, 4, 0
+ } ;
+
+static yyconst flex_int32_t yy_ec[256] =
+ { 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 4, 5, 1, 6, 7, 1, 1, 1, 8,
+ 9, 10, 11, 1, 12, 13, 14, 15, 15, 15,
+ 15, 15, 15, 15, 15, 15, 15, 16, 1, 1,
+ 17, 1, 1, 18, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 1, 20, 1, 1, 21, 1, 19, 19, 22, 23,
+
+ 24, 25, 19, 19, 26, 19, 19, 27, 19, 28,
+ 19, 19, 19, 19, 29, 19, 30, 19, 19, 19,
+ 19, 19, 31, 32, 33, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1
+ } ;
+
+static yyconst flex_int32_t yy_meta[34] =
+ { 0,
+ 1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1
+ } ;
+
+static yyconst flex_int16_t yy_base[74] =
+ { 0,
+ 0, 0, 32, 51, 34, 36, 0, 0, 142, 155,
+ 38, 155, 42, 67, 0, 124, 155, 155, 45, 23,
+ 31, 155, 155, 63, 64, 0, 98, 131, 130, 0,
+ 56, 59, 60, 0, 0, 0, 155, 103, 155, 109,
+ 114, 0, 114, 67, 0, 106, 107, 132, 0, 126,
+ 125, 122, 101, 98, 96, 113, 119, 155, 96, 90,
+ 93, 90, 155, 146, 148, 150, 102, 97, 84, 66,
+ 64, 40, 152
+ } ;
+
+static yyconst flex_int16_t yy_def[74] =
+ { 0,
+ 63, 1, 64, 64, 65, 65, 66, 66, 63, 63,
+ 67, 63, 63, 63, 68, 63, 63, 63, 63, 14,
+ 14, 63, 63, 69, 69, 70, 69, 71, 71, 67,
+ 67, 67, 63, 14, 14, 68, 63, 63, 63, 14,
+ 14, 14, 14, 69, 72, 69, 69, 73, 70, 69,
+ 71, 71, 14, 14, 14, 69, 73, 63, 14, 14,
+ 14, 14, 0, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63
+ } ;
+
+static yyconst flex_int16_t yy_nxt[189] =
+ { 0,
+ 10, 11, 12, 13, 14, 15, 14, 10, 10, 14,
+ 16, 14, 10, 10, 14, 17, 18, 14, 14, 19,
+ 14, 14, 14, 20, 14, 21, 14, 14, 14, 14,
+ 22, 10, 23, 25, 12, 25, 10, 26, 10, 31,
+ 45, 32, 29, 33, 29, 33, 38, 39, 38, 40,
+ 41, 27, 25, 12, 25, 42, 26, 31, 43, 32,
+ 32, 33, 32, 33, 51, 47, 49, 47, 45, 48,
+ 27, 34, 45, 34, 34, 34, 34, 34, 35, 34,
+ 34, 34, 46, 46, 44, 34, 46, 34, 34, 34,
+ 34, 34, 34, 34, 34, 34, 34, 36, 34, 50,
+
+ 39, 50, 30, 45, 38, 39, 38, 56, 47, 56,
+ 47, 45, 48, 42, 56, 62, 56, 46, 45, 61,
+ 42, 58, 60, 59, 42, 46, 46, 50, 39, 50,
+ 52, 45, 46, 52, 58, 55, 54, 53, 52, 52,
+ 37, 63, 63, 63, 63, 46, 24, 24, 28, 28,
+ 10, 10, 57, 57, 9, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63
+ } ;
+
+static yyconst flex_int16_t yy_chk[189] =
+ { 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 3, 3, 3, 5, 3, 6, 11,
+ 72, 11, 5, 13, 6, 13, 19, 19, 19, 20,
+ 20, 3, 4, 4, 4, 21, 4, 31, 21, 31,
+ 32, 33, 32, 33, 71, 25, 70, 25, 24, 25,
+ 4, 14, 44, 14, 14, 14, 14, 14, 14, 14,
+ 14, 14, 24, 25, 69, 14, 44, 14, 14, 14,
+ 14, 14, 14, 14, 14, 14, 14, 68, 14, 27,
+
+ 27, 27, 67, 27, 38, 38, 38, 46, 47, 46,
+ 47, 46, 47, 62, 56, 61, 56, 27, 56, 60,
+ 59, 57, 55, 54, 53, 46, 47, 50, 50, 50,
+ 52, 50, 56, 51, 48, 43, 41, 40, 29, 28,
+ 16, 9, 0, 0, 0, 50, 64, 64, 65, 65,
+ 66, 66, 73, 73, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63
+ } ;
+
+static yy_state_type yy_last_accepting_state;
+static char *yy_last_accepting_cpos;
+
+extern int yy_flex_debug;
+int yy_flex_debug = 0;
+
+/* The intent behind this definition is that it'll catch
+ * any uses of REJECT which flex missed.
+ */
+#define REJECT reject_used_but_not_detected
+#define yymore() yymore_used_but_not_detected
+#define YY_MORE_ADJ 0
+#define YY_RESTORE_YY_MORE_OFFSET
+char *yytext;
+#line 1 "autotools.ll"
+#line 2 "autotools.ll"
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "automakeparser.h"
+#include <stdlib.h>
+
+/**
+@file autotools.ll
+Autotools Lexer
+
+There are 3 types of identifiers recognized by this lexer:
+-id_simple: examples of such identifiers are qmake variables and scoped variables
+at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
+-id_list: those are "value list identifiers" at the right side in assignments
+(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
+-id_args: function arguments recognized as one identifier
+(example: ""${QMAKE_FILE} is intended only for Windows!""
+in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
+.
+
+To recognize those identifiers two additional start conditions are used: list and funcargs.
+
+@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
+the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
+so no indentation is preserved by this lexer (and parser).
+
+To debug this lexer, put the line below into the next flex file section.
+%option debug
+*/
+
+
+
+#line 559 "autotools_lex.cpp"
+
+#define INITIAL 0
+#define list 1
+#define funcargs 2
+#define conditional 3
+
+/* Special case for "unistd.h", since it is non-ANSI. We include it way
+ * down here because we want the user's section 1 to have been scanned first.
+ * The user has a chance to override it with an option.
+ */
+#include <unistd.h>
+
+#ifndef YY_EXTRA_TYPE
+#define YY_EXTRA_TYPE void *
+#endif
+
+/* Macros after this point can all be overridden by user definitions in
+ * section 1.
+ */
+
+#ifndef YY_SKIP_YYWRAP
+#ifdef __cplusplus
+extern "C" int yywrap (void );
+#else
+extern int yywrap (void );
+#endif
+#endif
+
+ static void yyunput (int c,char *buf_ptr );
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char *,yyconst char *,int );
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * );
+#endif
+
+#ifndef YY_NO_INPUT
+
+#ifdef __cplusplus
+static int yyinput (void );
+#else
+static int input (void );
+#endif
+
+#endif
+
+/* Amount of stuff to slurp up with each read. */
+#ifndef YY_READ_BUF_SIZE
+#define YY_READ_BUF_SIZE 8192
+#endif
+
+/* Copy whatever the last rule matched to the standard output. */
+#ifndef ECHO
+/* This used to be an fputs(), but since the string might contain NUL's,
+ * we now use fwrite().
+ */
+#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#endif
+
+/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
+ * is returned in "result".
+ */
+#ifndef YY_INPUT
+#define YY_INPUT(buf,result,max_size) \
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+ { \
+ int c = '*'; \
+ size_t n; \
+ for ( n = 0; n < max_size && \
+ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+ buf[n] = (char) c; \
+ if ( c == '\n' ) \
+ buf[n++] = (char) c; \
+ if ( c == EOF && ferror( yyin ) ) \
+ YY_FATAL_ERROR( "input in flex scanner failed" ); \
+ result = n; \
+ } \
+ else \
+ { \
+ errno=0; \
+ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ { \
+ if( errno != EINTR) \
+ { \
+ YY_FATAL_ERROR( "input in flex scanner failed" ); \
+ break; \
+ } \
+ errno=0; \
+ clearerr(yyin); \
+ } \
+ }\
+\
+
+#endif
+
+/* No semi-colon after return; correct usage is to write "yyterminate();" -
+ * we don't want an extra ';' after the "return" because that will cause
+ * some compilers to complain about unreachable statements.
+ */
+#ifndef yyterminate
+#define yyterminate() return YY_NULL
+#endif
+
+/* Number of entries by which start-condition stack grows. */
+#ifndef YY_START_STACK_INCR
+#define YY_START_STACK_INCR 25
+#endif
+
+/* Report a fatal error. */
+#ifndef YY_FATAL_ERROR
+#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
+#endif
+
+/* end tables serialization structures and prototypes */
+
+/* Default declaration of generated scanner - a define so the user can
+ * easily add parameters.
+ */
+#ifndef YY_DECL
+#define YY_DECL_IS_OURS 1
+
+extern int yylex (void);
+
+#define YY_DECL int yylex (void)
+#endif /* !YY_DECL */
+
+/* Code executed at the beginning of each rule, after yytext and yyleng
+ * have been set up.
+ */
+#ifndef YY_USER_ACTION
+#define YY_USER_ACTION
+#endif
+
+/* Code executed at the end of each rule. */
+#ifndef YY_BREAK
+#define YY_BREAK break;
+#endif
+
+#define YY_RULE_SETUP \
+ YY_USER_ACTION
+
+/** The main scanner function which does all the work.
+ */
+YY_DECL
+{
+ register yy_state_type yy_current_state;
+ register char *yy_cp, *yy_bp;
+ register int yy_act;
+
+#line 72 "autotools.ll"
+
+
+#line 714 "autotools_lex.cpp"
+
+ if ( (yy_init) )
+ {
+ (yy_init) = 0;
+
+#ifdef YY_USER_INIT
+ YY_USER_INIT;
+#endif
+
+ if ( ! (yy_start) )
+ (yy_start) = 1; /* first start state */
+
+ if ( ! yyin )
+ yyin = stdin;
+
+ if ( ! yyout )
+ yyout = stdout;
+
+ if ( ! YY_CURRENT_BUFFER ) {
+ yyensure_buffer_stack ();
+ YY_CURRENT_BUFFER_LVALUE =
+ yy_create_buffer(yyin,YY_BUF_SIZE );
+ }
+
+ yy_load_buffer_state( );
+ }
+
+ while ( 1 ) /* loops until end-of-file is reached */
+ {
+ yy_cp = (yy_c_buf_p);
+
+ /* Support of yytext. */
+ *yy_cp = (yy_hold_char);
+
+ /* yy_bp points to the position in yy_ch_buf of the start of
+ * the current run.
+ */
+ yy_bp = yy_cp;
+
+ yy_current_state = (yy_start);
+yy_match:
+ do
+ {
+ register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
+ if ( yy_accept[yy_current_state] )
+ {
+ (yy_last_accepting_state) = yy_current_state;
+ (yy_last_accepting_cpos) = yy_cp;
+ }
+ while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+ {
+ yy_current_state = (int) yy_def[yy_current_state];
+ if ( yy_current_state >= 64 )
+ yy_c = yy_meta[(unsigned int) yy_c];
+ }
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+ ++yy_cp;
+ }
+ while ( yy_base[yy_current_state] != 155 );
+
+yy_find_action:
+ yy_act = yy_accept[yy_current_state];
+ if ( yy_act == 0 )
+ { /* have to back up */
+ yy_cp = (yy_last_accepting_cpos);
+ yy_current_state = (yy_last_accepting_state);
+ yy_act = yy_accept[yy_current_state];
+ }
+
+ YY_DO_BEFORE_ACTION;
+
+do_action: /* This label is used only to access EOF actions. */
+
+ switch ( yy_act )
+ { /* beginning of action switch */
+ case 0: /* must back up */
+ /* undo the effects of YY_DO_BEFORE_ACTION */
+ *yy_cp = (yy_hold_char);
+ yy_cp = (yy_last_accepting_cpos);
+ yy_current_state = (yy_last_accepting_state);
+ goto yy_find_action;
+
+case 1:
+YY_RULE_SETUP
+#line 74 "autotools.ll"
+{}
+ YY_BREAK
+case 2:
+/* rule 2 can match eol */
+YY_RULE_SETUP
+#line 75 "autotools.ll"
+{ BEGIN(list); return CONT; }
+ YY_BREAK
+case 3:
+YY_RULE_SETUP
+#line 76 "autotools.ll"
+{
+ yylval.value = yytext;
+ if ( yylval.value == "if" )
+ return IF_KEYWORD;
+
+ if ( yylval.value == "else" )
+ return ELSE_KEYWORD;
+
+ if ( yylval.value == "endif" )
+ return ENDIF_KEYWORD;
+
+ return KEYWORD;
+}
+ YY_BREAK
+case 4:
+YY_RULE_SETUP
+#line 91 "autotools.ll"
+{ yylval.value = yytext; return (ID_SIMPLE); }
+ YY_BREAK
+case 5:
+YY_RULE_SETUP
+#line 93 "autotools.ll"
+{
+ yylval.value = yytext;
+ return RULE;
+}
+ YY_BREAK
+case 6:
+YY_RULE_SETUP
+#line 98 "autotools.ll"
+{
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
+ unput('\\');
+ BEGIN(INITIAL);
+ return (ID_LIST);
+ }
+ YY_BREAK
+case 7:
+/* rule 7 can match eol */
+YY_RULE_SETUP
+#line 106 "autotools.ll"
+{
+ yylval.value = yytext;
+ BEGIN(list);
+ return (LIST_COMMENT);
+ }
+ YY_BREAK
+case 8:
+YY_RULE_SETUP
+#line 112 "autotools.ll"
+{
+ yylval.value = yytext;
+ return LIST_COMMENT;
+ }
+ YY_BREAK
+case 9:
+YY_RULE_SETUP
+#line 117 "autotools.ll"
+{
+ yylval.value = yytext;
+ BEGIN(INITIAL);
+ return (ID_LIST_SINGLE);
+ }
+ YY_BREAK
+case 10:
+YY_RULE_SETUP
+#line 123 "autotools.ll"
+{
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.length()-1);
+ unput(')');
+ BEGIN(INITIAL);
+ return (ID_ARGS);
+ }
+ YY_BREAK
+case 11:
+YY_RULE_SETUP
+#line 131 "autotools.ll"
+{ BEGIN(list); yylval.value = yytext; return EQ; }
+ YY_BREAK
+case 12:
+YY_RULE_SETUP
+#line 132 "autotools.ll"
+{ BEGIN(list); yylval.value = yytext; return PLUSEQ; }
+ YY_BREAK
+case 13:
+YY_RULE_SETUP
+#line 133 "autotools.ll"
+{ return LCURLY; }
+ YY_BREAK
+case 14:
+YY_RULE_SETUP
+#line 134 "autotools.ll"
+{ return RCURLY; }
+ YY_BREAK
+case 15:
+YY_RULE_SETUP
+#line 135 "autotools.ll"
+{ BEGIN(list); yylval.value = yytext; return COLON; }
+ YY_BREAK
+case 16:
+/* rule 16 can match eol */
+YY_RULE_SETUP
+#line 136 "autotools.ll"
+{ BEGIN(INITIAL); return NEWLINE; }
+ YY_BREAK
+case 17:
+YY_RULE_SETUP
+#line 137 "autotools.ll"
+{ yylval.value = yytext; return (COMMENT); }
+ YY_BREAK
+case 18:
+YY_RULE_SETUP
+#line 139 "autotools.ll"
+ECHO;
+ YY_BREAK
+#line 928 "autotools_lex.cpp"
+case YY_STATE_EOF(INITIAL):
+case YY_STATE_EOF(list):
+case YY_STATE_EOF(funcargs):
+case YY_STATE_EOF(conditional):
+ yyterminate();
+
+ case YY_END_OF_BUFFER:
+ {
+ /* Amount of text matched not including the EOB char. */
+ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
+
+ /* Undo the effects of YY_DO_BEFORE_ACTION. */
+ *yy_cp = (yy_hold_char);
+ YY_RESTORE_YY_MORE_OFFSET
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+ {
+ /* We're scanning a new file or input source. It's
+ * possible that this happened because the user
+ * just pointed yyin at a new source and called
+ * yylex(). If so, then we have to assure
+ * consistency between YY_CURRENT_BUFFER and our
+ * globals. Here is the right place to do so, because
+ * this is the first action (other than possibly a
+ * back-up) that will match for the new input source.
+ */
+ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+ YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+ YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+ }
+
+ /* Note that here we test for yy_c_buf_p "<=" to the position
+ * of the first EOB in the buffer, since yy_c_buf_p will
+ * already have been incremented past the NUL character
+ * (since all states make transitions on EOB to the
+ * end-of-buffer state). Contrast this with the test
+ * in input().
+ */
+ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+ { /* This was really a NUL. */
+ yy_state_type yy_next_state;
+
+ (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
+
+ yy_current_state = yy_get_previous_state( );
+
+ /* Okay, we're now positioned to make the NUL
+ * transition. We couldn't have
+ * yy_get_previous_state() go ahead and do it
+ * for us because it doesn't know how to deal
+ * with the possibility of jamming (and we don't
+ * want to build jamming into it because then it
+ * will run more slowly).
+ */
+
+ yy_next_state = yy_try_NUL_trans( yy_current_state );
+
+ yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+
+ if ( yy_next_state )
+ {
+ /* Consume the NUL. */
+ yy_cp = ++(yy_c_buf_p);
+ yy_current_state = yy_next_state;
+ goto yy_match;
+ }
+
+ else
+ {
+ yy_cp = (yy_c_buf_p);
+ goto yy_find_action;
+ }
+ }
+
+ else switch ( yy_get_next_buffer( ) )
+ {
+ case EOB_ACT_END_OF_FILE:
+ {
+ (yy_did_buffer_switch_on_eof) = 0;
+
+ if ( yywrap( ) )
+ {
+ /* Note: because we've taken care in
+ * yy_get_next_buffer() to have set up
+ * yytext, we can now set up
+ * yy_c_buf_p so that if some total
+ * hoser (like flex itself) wants to
+ * call the scanner after we return the
+ * YY_NULL, it'll still work - another
+ * YY_NULL will get returned.
+ */
+ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
+
+ yy_act = YY_STATE_EOF(YY_START);
+ goto do_action;
+ }
+
+ else
+ {
+ if ( ! (yy_did_buffer_switch_on_eof) )
+ YY_NEW_FILE;
+ }
+ break;
+ }
+
+ case EOB_ACT_CONTINUE_SCAN:
+ (yy_c_buf_p) =
+ (yytext_ptr) + yy_amount_of_matched_text;
+
+ yy_current_state = yy_get_previous_state( );
+
+ yy_cp = (yy_c_buf_p);
+ yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+ goto yy_match;
+
+ case EOB_ACT_LAST_MATCH:
+ (yy_c_buf_p) =
+ &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
+
+ yy_current_state = yy_get_previous_state( );
+
+ yy_cp = (yy_c_buf_p);
+ yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+ goto yy_find_action;
+ }
+ break;
+ }
+
+ default:
+ YY_FATAL_ERROR(
+ "fatal flex scanner internal error--no action found" );
+ } /* end of action switch */
+ } /* end of scanning one token */
+} /* end of yylex */
+
+/* yy_get_next_buffer - try to read in a new buffer
+ *
+ * Returns a code representing an action:
+ * EOB_ACT_LAST_MATCH -
+ * EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ * EOB_ACT_END_OF_FILE - end of file
+ */
+static int yy_get_next_buffer (void)
+{
+ register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+ register char *source = (yytext_ptr);
+ register int number_to_move, i;
+ int ret_val;
+
+ if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
+ YY_FATAL_ERROR(
+ "fatal flex scanner internal error--end of buffer missed" );
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+ { /* Don't try to fill the buffer, so this is an EOF. */
+ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
+ {
+ /* We matched a single character, the EOB, so
+ * treat this as a final EOF.
+ */
+ return EOB_ACT_END_OF_FILE;
+ }
+
+ else
+ {
+ /* We matched some text prior to the EOB, first
+ * process it.
+ */
+ return EOB_ACT_LAST_MATCH;
+ }
+ }
+
+ /* Try to read more data. */
+
+ /* First move last chars to start of buffer. */
+ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
+
+ for ( i = 0; i < number_to_move; ++i )
+ *(dest++) = *(source++);
+
+ if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+ /* don't do the read, it's not guaranteed to return an EOF,
+ * just force an EOF
+ */
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
+
+ else
+ {
+ size_t num_to_read =
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+ while ( num_to_read <= 0 )
+ { /* Not enough room in the buffer - grow it. */
+
+ /* just a shorter name for the current buffer */
+ YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
+
+ int yy_c_buf_p_offset =
+ (int) ((yy_c_buf_p) - b->yy_ch_buf);
+
+ if ( b->yy_is_our_buffer )
+ {
+ int new_size = b->yy_buf_size * 2;
+
+ if ( new_size <= 0 )
+ b->yy_buf_size += b->yy_buf_size / 8;
+ else
+ b->yy_buf_size *= 2;
+
+ b->yy_ch_buf = (char *)
+ /* Include room in for 2 EOB chars. */
+ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
+ }
+ else
+ /* Can't grow it, we don't own it. */
+ b->yy_ch_buf = 0;
+
+ if ( ! b->yy_ch_buf )
+ YY_FATAL_ERROR(
+ "fatal error - scanner input buffer overflow" );
+
+ (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+ num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+ number_to_move - 1;
+
+ }
+
+ if ( num_to_read > YY_READ_BUF_SIZE )
+ num_to_read = YY_READ_BUF_SIZE;
+
+ /* Read in more data. */
+ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+ (yy_n_chars), num_to_read );
+
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+ }
+
+ if ( (yy_n_chars) == 0 )
+ {
+ if ( number_to_move == YY_MORE_ADJ )
+ {
+ ret_val = EOB_ACT_END_OF_FILE;
+ yyrestart(yyin );
+ }
+
+ else
+ {
+ ret_val = EOB_ACT_LAST_MATCH;
+ YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+ YY_BUFFER_EOF_PENDING;
+ }
+ }
+
+ else
+ ret_val = EOB_ACT_CONTINUE_SCAN;
+
+ (yy_n_chars) += number_to_move;
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
+
+ (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+
+ return ret_val;
+}
+
+/* yy_get_previous_state - get the state just before the EOB char was reached */
+
+ static yy_state_type yy_get_previous_state (void)
+{
+ register yy_state_type yy_current_state;
+ register char *yy_cp;
+
+ yy_current_state = (yy_start);
+
+ for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
+ {
+ register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+ if ( yy_accept[yy_current_state] )
+ {
+ (yy_last_accepting_state) = yy_current_state;
+ (yy_last_accepting_cpos) = yy_cp;
+ }
+ while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+ {
+ yy_current_state = (int) yy_def[yy_current_state];
+ if ( yy_current_state >= 64 )
+ yy_c = yy_meta[(unsigned int) yy_c];
+ }
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+ }
+
+ return yy_current_state;
+}
+
+/* yy_try_NUL_trans - try to make a transition on the NUL character
+ *
+ * synopsis
+ * next_state = yy_try_NUL_trans( current_state );
+ */
+ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
+{
+ register int yy_is_jam;
+ register char *yy_cp = (yy_c_buf_p);
+
+ register YY_CHAR yy_c = 1;
+ if ( yy_accept[yy_current_state] )
+ {
+ (yy_last_accepting_state) = yy_current_state;
+ (yy_last_accepting_cpos) = yy_cp;
+ }
+ while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+ {
+ yy_current_state = (int) yy_def[yy_current_state];
+ if ( yy_current_state >= 64 )
+ yy_c = yy_meta[(unsigned int) yy_c];
+ }
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+ yy_is_jam = (yy_current_state == 63);
+
+ return yy_is_jam ? 0 : yy_current_state;
+}
+
+ static void yyunput (int c, register char * yy_bp )
+{
+ register char *yy_cp;
+
+ yy_cp = (yy_c_buf_p);
+
+ /* undo effects of setting up yytext */
+ *yy_cp = (yy_hold_char);
+
+ if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+ { /* need to shift things up to make room */
+ /* +2 for EOB chars. */
+ register int number_to_move = (yy_n_chars) + 2;
+ register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+ register char *source =
+ &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+
+ while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+ *--dest = *--source;
+
+ yy_cp += (int) (dest - source);
+ yy_bp += (int) (dest - source);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+ if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+ YY_FATAL_ERROR( "flex scanner push-back overflow" );
+ }
+
+ *--yy_cp = (char) c;
+
+ (yytext_ptr) = yy_bp;
+ (yy_hold_char) = *yy_cp;
+ (yy_c_buf_p) = yy_cp;
+}
+
+#ifndef YY_NO_INPUT
+#ifdef __cplusplus
+ static int yyinput (void)
+#else
+ static int input (void)
+#endif
+
+{
+ int c;
+
+ *(yy_c_buf_p) = (yy_hold_char);
+
+ if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
+ {
+ /* yy_c_buf_p now points to the character we want to return.
+ * If this occurs *before* the EOB characters, then it's a
+ * valid NUL; if not, then we've hit the end of the buffer.
+ */
+ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+ /* This was really a NUL. */
+ *(yy_c_buf_p) = '\0';
+
+ else
+ { /* need more input */
+ int offset = (yy_c_buf_p) - (yytext_ptr);
+ ++(yy_c_buf_p);
+
+ switch ( yy_get_next_buffer( ) )
+ {
+ case EOB_ACT_LAST_MATCH:
+ /* This happens because yy_g_n_b()
+ * sees that we've accumulated a
+ * token and flags that we need to
+ * try matching the token before
+ * proceeding. But for input(),
+ * there's no matching to consider.
+ * So convert the EOB_ACT_LAST_MATCH
+ * to EOB_ACT_END_OF_FILE.
+ */
+
+ /* Reset buffer status. */
+ yyrestart(yyin );
+
+ /*FALLTHROUGH*/
+
+ case EOB_ACT_END_OF_FILE:
+ {
+ if ( yywrap( ) )
+ return EOF;
+
+ if ( ! (yy_did_buffer_switch_on_eof) )
+ YY_NEW_FILE;
+#ifdef __cplusplus
+ return yyinput();
+#else
+ return input();
+#endif
+ }
+
+ case EOB_ACT_CONTINUE_SCAN:
+ (yy_c_buf_p) = (yytext_ptr) + offset;
+ break;
+ }
+ }
+ }
+
+ c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
+ *(yy_c_buf_p) = '\0'; /* preserve yytext */
+ (yy_hold_char) = *++(yy_c_buf_p);
+
+ return c;
+}
+#endif /* ifndef YY_NO_INPUT */
+
+/** Immediately switch to a different input stream.
+ * @param input_file A readable stream.
+ *
+ * @note This function does not reset the start condition to @c INITIAL .
+ */
+ void yyrestart (FILE * input_file )
+{
+
+ if ( ! YY_CURRENT_BUFFER ){
+ yyensure_buffer_stack ();
+ YY_CURRENT_BUFFER_LVALUE =
+ yy_create_buffer(yyin,YY_BUF_SIZE );
+ }
+
+ yy_init_buffer(YY_CURRENT_BUFFER,input_file );
+ yy_load_buffer_state( );
+}
+
+/** Switch to a different input buffer.
+ * @param new_buffer The new input buffer.
+ *
+ */
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
+{
+
+ /* TODO. We should be able to replace this entire function body
+ * with
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
+ */
+ yyensure_buffer_stack ();
+ if ( YY_CURRENT_BUFFER == new_buffer )
+ return;
+
+ if ( YY_CURRENT_BUFFER )
+ {
+ /* Flush out information for old buffer. */
+ *(yy_c_buf_p) = (yy_hold_char);
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+ }
+
+ YY_CURRENT_BUFFER_LVALUE = new_buffer;
+ yy_load_buffer_state( );
+
+ /* We don't actually know whether we did this switch during
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
+ * to go ahead and always set it.
+ */
+ (yy_did_buffer_switch_on_eof) = 1;
+}
+
+static void yy_load_buffer_state (void)
+{
+ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+ (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+ yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+ (yy_hold_char) = *(yy_c_buf_p);
+}
+
+/** Allocate and initialize an input buffer state.
+ * @param file A readable stream.
+ * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
+ *
+ * @return the allocated buffer state.
+ */
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
+{
+ YY_BUFFER_STATE b;
+
+ b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
+ if ( ! b )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+ b->yy_buf_size = size;
+
+ /* yy_ch_buf has to be 2 characters longer than the size given because
+ * we need to put in 2 end-of-buffer characters.
+ */
+ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
+ if ( ! b->yy_ch_buf )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+ b->yy_is_our_buffer = 1;
+
+ yy_init_buffer(b,file );
+
+ return b;
+}
+
+/** Destroy the buffer.
+ * @param b a buffer created with yy_create_buffer()
+ *
+ */
+ void yy_delete_buffer (YY_BUFFER_STATE b )
+{
+
+ if ( ! b )
+ return;
+
+ if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+
+ if ( b->yy_is_our_buffer )
+ yyfree((void *) b->yy_ch_buf );
+
+ yyfree((void *) b );
+}
+
+#ifndef __cplusplus
+extern int isatty (int );
+#endif /* __cplusplus */
+
+/* Initializes or reinitializes a buffer.
+ * This function is sometimes called more than once on the same buffer,
+ * such as during a yyrestart() or at EOF.
+ */
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
+
+{
+ int oerrno = errno;
+
+ yy_flush_buffer(b );
+
+ b->yy_input_file = file;
+ b->yy_fill_buffer = 1;
+
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
+ * In that case, we don't want to reset the lineno or column.
+ */
+ if (b != YY_CURRENT_BUFFER){
+ b->yy_bs_lineno = 1;
+ b->yy_bs_column = 0;
+ }
+
+ b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
+
+ errno = oerrno;
+}
+
+/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
+ * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
+ *
+ */
+ void yy_flush_buffer (YY_BUFFER_STATE b )
+{
+ if ( ! b )
+ return;
+
+ b->yy_n_chars = 0;
+
+ /* We always need two end-of-buffer characters. The first causes
+ * a transition to the end-of-buffer state. The second causes
+ * a jam in that state.
+ */
+ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+ b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+
+ b->yy_buf_pos = &b->yy_ch_buf[0];
+
+ b->yy_at_bol = 1;
+ b->yy_buffer_status = YY_BUFFER_NEW;
+
+ if ( b == YY_CURRENT_BUFFER )
+ yy_load_buffer_state( );
+}
+
+/** Pushes the new state onto the stack. The new state becomes
+ * the current state. This function will allocate the stack
+ * if necessary.
+ * @param new_buffer The new state.
+ *
+ */
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
+{
+ if (new_buffer == NULL)
+ return;
+
+ yyensure_buffer_stack();
+
+ /* This block is copied from yy_switch_to_buffer. */
+ if ( YY_CURRENT_BUFFER )
+ {
+ /* Flush out information for old buffer. */
+ *(yy_c_buf_p) = (yy_hold_char);
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+ }
+
+ /* Only push if top exists. Otherwise, replace top. */
+ if (YY_CURRENT_BUFFER)
+ (yy_buffer_stack_top)++;
+ YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( );
+ (yy_did_buffer_switch_on_eof) = 1;
+}
+
+/** Removes and deletes the top of the stack, if present.
+ * The next element becomes the new top.
+ *
+ */
+void yypop_buffer_state (void)
+{
+ if (!YY_CURRENT_BUFFER)
+ return;
+
+ yy_delete_buffer(YY_CURRENT_BUFFER );
+ YY_CURRENT_BUFFER_LVALUE = NULL;
+ if ((yy_buffer_stack_top) > 0)
+ --(yy_buffer_stack_top);
+
+ if (YY_CURRENT_BUFFER) {
+ yy_load_buffer_state( );
+ (yy_did_buffer_switch_on_eof) = 1;
+ }
+}
+
+/* Allocates the stack if it does not exist.
+ * Guarantees space for at least one push.
+ */
+static void yyensure_buffer_stack (void)
+{
+ int num_to_alloc;
+
+ if (!(yy_buffer_stack)) {
+
+ /* First allocation is just for 2 elements, since we don't know if this
+ * scanner will even need a stack. We use 2 instead of 1 to avoid an
+ * immediate realloc on the next call.
+ */
+ num_to_alloc = 1;
+ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
+ (num_to_alloc * sizeof(struct yy_buffer_state*)
+ );
+
+ memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+ (yy_buffer_stack_max) = num_to_alloc;
+ (yy_buffer_stack_top) = 0;
+ return;
+ }
+
+ if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
+
+ /* Increase the buffer to prepare for a possible push. */
+ int grow_size = 8 /* arbitrary grow size */;
+
+ num_to_alloc = (yy_buffer_stack_max) + grow_size;
+ (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
+ ((yy_buffer_stack),
+ num_to_alloc * sizeof(struct yy_buffer_state*)
+ );
+
+ /* zero only the new slots.*/
+ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
+ (yy_buffer_stack_max) = num_to_alloc;
+ }
+}
+
+/** Setup the input buffer state to scan directly from a user-specified character buffer.
+ * @param base the character buffer
+ * @param size the size in bytes of the character buffer
+ *
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
+{
+ YY_BUFFER_STATE b;
+
+ if ( size < 2 ||
+ base[size-2] != YY_END_OF_BUFFER_CHAR ||
+ base[size-1] != YY_END_OF_BUFFER_CHAR )
+ /* They forgot to leave room for the EOB's. */
+ return 0;
+
+ b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
+ if ( ! b )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+
+ b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_pos = b->yy_ch_buf = base;
+ b->yy_is_our_buffer = 0;
+ b->yy_input_file = 0;
+ b->yy_n_chars = b->yy_buf_size;
+ b->yy_is_interactive = 0;
+ b->yy_at_bol = 1;
+ b->yy_fill_buffer = 0;
+ b->yy_buffer_status = YY_BUFFER_NEW;
+
+ yy_switch_to_buffer(b );
+
+ return b;
+}
+
+/** Setup the input buffer state to scan a string. The next call to yylex() will
+ * scan from a @e copy of @a str.
+ * @param str a NUL-terminated string to scan
+ *
+ * @return the newly allocated buffer state object.
+ * @note If you want to scan bytes that may contain NUL values, then use
+ * yy_scan_bytes() instead.
+ */
+YY_BUFFER_STATE yy_scan_string (yyconst char * str )
+{
+
+ return yy_scan_bytes(str,strlen(str) );
+}
+
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
+ * scan from a @e copy of @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
+ *
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_bytes (yyconst char * bytes, int len )
+{
+ YY_BUFFER_STATE b;
+ char *buf;
+ yy_size_t n;
+ int i;
+
+ /* Get memory for full buffer, including space for trailing EOB's. */
+ n = len + 2;
+ buf = (char *) yyalloc(n );
+ if ( ! buf )
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+
+ for ( i = 0; i < len; ++i )
+ buf[i] = bytes[i];
+
+ buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
+
+ b = yy_scan_buffer(buf,n );
+ if ( ! b )
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+
+ /* It's okay to grow etc. this buffer, and we should throw it
+ * away when we're done.
+ */
+ b->yy_is_our_buffer = 1;
+
+ return b;
+}
+
+#ifndef YY_EXIT_FAILURE
+#define YY_EXIT_FAILURE 2
+#endif
+
+static void yy_fatal_error (yyconst char* msg )
+{
+ (void) fprintf( stderr, "%s\n", msg );
+ exit( YY_EXIT_FAILURE );
+}
+
+/* Redefine yyless() so it works in section 3 code. */
+
+#undef yyless
+#define yyless(n) \
+ do \
+ { \
+ /* Undo effects of setting up yytext. */ \
+ int yyless_macro_arg = (n); \
+ YY_LESS_LINENO(yyless_macro_arg);\
+ yytext[yyleng] = (yy_hold_char); \
+ (yy_c_buf_p) = yytext + yyless_macro_arg; \
+ (yy_hold_char) = *(yy_c_buf_p); \
+ *(yy_c_buf_p) = '\0'; \
+ yyleng = yyless_macro_arg; \
+ } \
+ while ( 0 )
+
+/* Accessor methods (get/set functions) to struct members. */
+
+/** Get the current line number.
+ *
+ */
+int yyget_lineno (void)
+{
+
+ return yylineno;
+}
+
+/** Get the input stream.
+ *
+ */
+FILE *yyget_in (void)
+{
+ return yyin;
+}
+
+/** Get the output stream.
+ *
+ */
+FILE *yyget_out (void)
+{
+ return yyout;
+}
+
+/** Get the length of the current token.
+ *
+ */
+int yyget_leng (void)
+{
+ return yyleng;
+}
+
+/** Get the current token.
+ *
+ */
+
+char *yyget_text (void)
+{
+ return yytext;
+}
+
+/** Set the current line number.
+ * @param line_number
+ *
+ */
+void yyset_lineno (int line_number )
+{
+
+ yylineno = line_number;
+}
+
+/** Set the input stream. This does not discard the current
+ * input buffer.
+ * @param in_str A readable stream.
+ *
+ * @see yy_switch_to_buffer
+ */
+void yyset_in (FILE * in_str )
+{
+ yyin = in_str ;
+}
+
+void yyset_out (FILE * out_str )
+{
+ yyout = out_str ;
+}
+
+int yyget_debug (void)
+{
+ return yy_flex_debug;
+}
+
+void yyset_debug (int bdebug )
+{
+ yy_flex_debug = bdebug ;
+}
+
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (void)
+{
+
+ /* Pop the buffer stack, destroying each element. */
+ while(YY_CURRENT_BUFFER){
+ yy_delete_buffer(YY_CURRENT_BUFFER );
+ YY_CURRENT_BUFFER_LVALUE = NULL;
+ yypop_buffer_state();
+ }
+
+ /* Destroy the stack itself. */
+ yyfree((yy_buffer_stack) );
+ (yy_buffer_stack) = NULL;
+
+ return 0;
+}
+
+/*
+ * Internal utility routines.
+ */
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
+{
+ register int i;
+ for ( i = 0; i < n; ++i )
+ s1[i] = s2[i];
+}
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * s )
+{
+ register int n;
+ for ( n = 0; s[n]; ++n )
+ ;
+
+ return n;
+}
+#endif
+
+void *yyalloc (yy_size_t size )
+{
+ return (void *) malloc( size );
+}
+
+void *yyrealloc (void * ptr, yy_size_t size )
+{
+ /* The cast to (char *) in the following accommodates both
+ * implementations that use char* generic pointers, and those
+ * that use void* generic pointers. It works with the latter
+ * because both ANSI C and C++ allow castless assignment from
+ * any pointer type to void*, and deal with argument conversions
+ * as though doing an assignment.
+ */
+ return (void *) realloc( (char *) ptr, size );
+}
+
+void yyfree (void * ptr )
+{
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
+}
+
+#define YYTABLES_NAME "yytables"
+
+#undef YY_NEW_FILE
+#undef YY_FLUSH_BUFFER
+#undef yy_set_bol
+#undef yy_new_buffer
+#undef yy_set_interactive
+#undef YY_DO_BEFORE_ACTION
+
+#ifdef YY_DECL_IS_OURS
+#undef YY_DECL_IS_OURS
+#undef YY_DECL
+#endif
+#line 139 "autotools.ll"
+
+
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake_lex.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.cpp (revision 1522570)
@@ -0,0 +1,68 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "automakedriver.h"
+#include "automakeast.h"
+
+#include <stdio.h>
+#include <qstack.h>
+#include <kio/netaccess.h>
+
+extern FILE *yyin, *yyout;
+extern int yyparse();
+extern int yydebug;
+extern QStack<AutoMake::ProjectAST *> projects;
+
+namespace AutoMake {
+
+int Driver::parseFile(const char *fileName, ProjectAST **ast)
+{
+// yydebug = 1;
+ yyin = fopen(fileName, "r");
+ if (yyin == 0)
+ {
+ ast = 0;
+ return 1;
+ }
+ int ret = yyparse();
+ *ast = projects.top();
+ fclose(yyin);
+ return ret;
+}
+
+int Driver::parseFile(const QString& fileName, ProjectAST **ast)
+{
+ return parseFile(fileName.toAscii().constData(), ast);
+}
+
+int Driver::parseFile(const KUrl& fileName, ProjectAST **ast)
+{
+ QString tmpFile;
+ int ret = 0;
+ if (KIO::NetAccess::download(fileName, tmpFile, 0))
+ ret = parseFile(tmpFile, ast);
+ KIO::NetAccess::removeTempFile(tmpFile);
+ return ret;
+}
+
+}
+
+//kate: indent-mode csands; space-indent off; tab-width 4;
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakedriver.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.cpp (revision 1522570)
@@ -0,0 +1,1786 @@
+/* A Bison parser, made by GNU Bison 2.1. */
+
+/* Skeleton parser for Yacc-like parsing with Bison,
+ Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+
+ 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, 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., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA. */
+
+/* As a special exception, when this file is copied by Bison into a
+ Bison output file, you may use that output file without restriction.
+ This special exception was added by the Free Software Foundation
+ in version 1.24 of Bison. */
+
+/* Written by Richard Stallman by simplifying the original so called
+ ``semantic'' parser. */
+
+/* All symbols defined below should begin with yy or YY, to avoid
+ infringing on user name space. This should be done even for local
+ variables, as they might otherwise be expanded by user macros.
+ There are some unavoidable exceptions within include files to
+ define necessary library symbols; they are noted "INFRINGES ON
+ USER NAME SPACE" below. */
+
+/* Identify Bison output. */
+#define YYBISON 1
+
+/* Bison version. */
+#define YYBISON_VERSION "2.1"
+
+/* Skeleton name. */
+#define YYSKELETON_NAME "yacc.c"
+
+/* Pure parsers. */
+#define YYPURE 0
+
+/* Using locations. */
+#define YYLSP_NEEDED 0
+
+
+
+/* Tokens. */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+ /* Put the tokens into the symbol table, so that GDB and other debuggers
+ know about them. */
+ enum yytokentype {
+ ID_SIMPLE = 258,
+ ID_LIST = 259,
+ LBRACE = 260,
+ EQ = 261,
+ PLUSEQ = 262,
+ MINUSQE = 263,
+ STAREQ = 264,
+ TILDEEQ = 265,
+ RBRACE = 266,
+ COLON = 267,
+ NUMSIGN = 268,
+ NEWLINE = 269,
+ NUMBER = 270,
+ COMMENT = 271,
+ CONT = 272,
+ DOT = 273,
+ RCURLY = 274,
+ LCURLY = 275,
+ ID_ARGS = 276,
+ LIST_COMMENT = 277,
+ ID_LIST_SINGLE = 278,
+ IF_KEYWORD = 279,
+ ELSE_KEYWORD = 280,
+ ENDIF_KEYWORD = 281,
+ KEYWORD = 282,
+ RULE = 283
+ };
+#endif
+/* Tokens. */
+#define ID_SIMPLE 258
+#define ID_LIST 259
+#define LBRACE 260
+#define EQ 261
+#define PLUSEQ 262
+#define MINUSQE 263
+#define STAREQ 264
+#define TILDEEQ 265
+#define RBRACE 266
+#define COLON 267
+#define NUMSIGN 268
+#define NEWLINE 269
+#define NUMBER 270
+#define COMMENT 271
+#define CONT 272
+#define DOT 273
+#define RCURLY 274
+#define LCURLY 275
+#define ID_ARGS 276
+#define LIST_COMMENT 277
+#define ID_LIST_SINGLE 278
+#define IF_KEYWORD 279
+#define ELSE_KEYWORD 280
+#define ENDIF_KEYWORD 281
+#define KEYWORD 282
+#define RULE 283
+
+
+
+
+/* Copy the first part of user declarations. */
+#line 1 "autotools.yy"
+
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+/**
+@file autotools.yy
+Autotools Parser
+
+Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
+
+@todo Recognize comments after statements like:
+noinst_HEADERS = foo.h #regognize me
+
+@fixme Parser fails on files that do not end with a newline
+@fixme 1 shift/reduce conflict in "line_body" rule
+*/
+
+
+#include <qstack.h>
+#include "automakeast.h"
+
+#define YYSTYPE_IS_DECLARED
+
+using namespace AutoMake;
+
+/**
+The yylval type.
+*/
+typedef struct Result {
+ Result(): node(0) {}
+
+ /**Type of semantic value for simple grammar rules.*/
+ QString value;
+ /**Type of semantic value for grammar rules which are parts of AST.*/
+ AST *node;
+ /**Type of semantic value for "multiline_values" grammar rule.
+ Each line of multiline value is stored as a string in the list.
+
+ For example we have in Makefile.am file:
+ @code
+ foo_SOURCES = foo1.cpp \
+ foo2.cpp \
+ foo3.cpp foo4.cpp
+ @endcode
+ The string list will be populated with three strings:
+ <pre>
+ foo1.cpp
+ foo2.cpp
+ foo3.cpp foo4.cpp
+ </pre>
+ */
+ QStringList values;
+} YYSTYPE;
+
+
+void yyerror(const char *str) {
+ qWarning("bison error: %s\n", str);
+}
+
+int yylex();
+
+/**
+The stack to store ProjectAST pointers when a new child
+ProjectAST is created and filled with statements.
+
+Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
+adding statements. Each statement is added as a child StatementAST to the ProjectAST
+currently on the top in the stack.
+
+When a scope or function scope statement is parsed, the child ProjectAST is created
+and pushed onto the stack. Therefore all statements which belong to the scope
+or function scope are added as childs to their direct parent (scope or function scope).
+*/
+QStack<ProjectAST*> projects;
+
+/**
+The current depth of AST node is stored here.
+AST depth is important to know because automatic indentation can
+be easily implemented (the parser itself looses all information
+about indentation).
+*/
+int depth = 0;
+
+/*
+To debug this parser, put the line below into the next bison file section.
+Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
+%debug
+*/
+
+
+/* Enabling traces. */
+#ifndef YYDEBUG
+# define YYDEBUG 1
+#endif
+
+/* Enabling verbose error messages. */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
+
+/* Enabling the token table. */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE 0
+#endif
+
+#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
+typedef int YYSTYPE;
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
+
+
+
+/* Copy the second part of user declarations. */
+
+
+/* Line 219 of yacc.c. */
+#line 262 "autotools_yacc.cpp"
+
+#if ! defined (YYSIZE_T) && defined (__SIZE_TYPE__)
+# define YYSIZE_T __SIZE_TYPE__
+#endif
+#if ! defined (YYSIZE_T) && defined (size_t)
+# define YYSIZE_T size_t
+#endif
+#if ! defined (YYSIZE_T) && (defined (__STDC__) || defined (__cplusplus))
+# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+# define YYSIZE_T size_t
+#endif
+#if ! defined (YYSIZE_T)
+# define YYSIZE_T unsigned int
+#endif
+
+#ifndef YY_
+# if YYENABLE_NLS
+# if ENABLE_NLS
+# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+# define YY_(msgid) dgettext ("bison-runtime", msgid)
+# endif
+# endif
+# ifndef YY_
+# define YY_(msgid) msgid
+# endif
+#endif
+
+#if ! defined (yyoverflow) || YYERROR_VERBOSE
+
+/* The parser invokes alloca or malloc; define the necessary symbols. */
+
+# ifdef YYSTACK_USE_ALLOCA
+# if YYSTACK_USE_ALLOCA
+# ifdef __GNUC__
+# define YYSTACK_ALLOC __builtin_alloca
+# else
+# define YYSTACK_ALLOC alloca
+# if defined (__STDC__) || defined (__cplusplus)
+# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+# define YYINCLUDED_STDLIB_H
+# endif
+# endif
+# endif
+# endif
+
+# ifdef YYSTACK_ALLOC
+ /* Pacify GCC's `empty if-body' warning. */
+# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
+# ifndef YYSTACK_ALLOC_MAXIMUM
+ /* The OS might guarantee only one guard page at the bottom of the stack,
+ and a page size can be as small as 4096 bytes. So we cannot safely
+ invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
+ to allow for a few compiler-allocated temporary stack slots. */
+# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2005 */
+# endif
+# else
+# define YYSTACK_ALLOC YYMALLOC
+# define YYSTACK_FREE YYFREE
+# ifndef YYSTACK_ALLOC_MAXIMUM
+# define YYSTACK_ALLOC_MAXIMUM ((YYSIZE_T) -1)
+# endif
+# ifdef __cplusplus
+extern "C" {
+# endif
+# ifndef YYMALLOC
+# define YYMALLOC malloc
+# if (! defined (malloc) && ! defined (YYINCLUDED_STDLIB_H) \
+ && (defined (__STDC__) || defined (__cplusplus)))
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# ifndef YYFREE
+# define YYFREE free
+# if (! defined (free) && ! defined (YYINCLUDED_STDLIB_H) \
+ && (defined (__STDC__) || defined (__cplusplus)))
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+# endif
+# endif
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif /* ! defined (yyoverflow) || YYERROR_VERBOSE */
+
+
+#if (! defined (yyoverflow) \
+ && (! defined (__cplusplus) \
+ || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))
+
+/* A type that is properly aligned for any stack member. */
+union yyalloc
+{
+ short int yyss;
+ YYSTYPE yyvs;
+ };
+
+/* The size of the maximum gap between one aligned stack and the next. */
+# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+
+/* The size of an array large to enough to hold all stacks, each with
+ N elements. */
+# define YYSTACK_BYTES(N) \
+ ((N) * (sizeof (short int) + sizeof (YYSTYPE)) \
+ + YYSTACK_GAP_MAXIMUM)
+
+/* Copy COUNT objects from FROM to TO. The source and destination do
+ not overlap. */
+# ifndef YYCOPY
+# if defined (__GNUC__) && 1 < __GNUC__
+# define YYCOPY(To, From, Count) \
+ __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
+# else
+# define YYCOPY(To, From, Count) \
+ do \
+ { \
+ YYSIZE_T yyi; \
+ for (yyi = 0; yyi < (Count); yyi++) \
+ (To)[yyi] = (From)[yyi]; \
+ } \
+ while (0)
+# endif
+# endif
+
+/* Relocate STACK from its old location to the new one. The
+ local variables YYSIZE and YYSTACKSIZE give the old and new number of
+ elements in the stack, and YYPTR gives the new location of the
+ stack. Advance YYPTR to a properly aligned location for the next
+ stack. */
+# define YYSTACK_RELOCATE(Stack) \
+ do \
+ { \
+ YYSIZE_T yynewbytes; \
+ YYCOPY (&yyptr->Stack, Stack, yysize); \
+ Stack = &yyptr->Stack; \
+ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+ yyptr += yynewbytes / sizeof (*yyptr); \
+ } \
+ while (0)
+
+#endif
+
+#if defined (__STDC__) || defined (__cplusplus)
+ typedef signed char yysigned_char;
+#else
+ typedef short int yysigned_char;
+#endif
+
+/* YYFINAL -- State number of the termination state. */
+#define YYFINAL 3
+/* YYLAST -- Last index in YYTABLE. */
+#define YYLAST 33
+
+/* YYNTOKENS -- Number of terminals. */
+#define YYNTOKENS 29
+/* YYNNTS -- Number of nonterminals. */
+#define YYNNTS 18
+/* YYNRULES -- Number of rules. */
+#define YYNRULES 35
+/* YYNRULES -- Number of states. */
+#define YYNSTATES 43
+
+/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
+#define YYUNDEFTOK 2
+#define YYMAXUTOK 283
+
+#define YYTRANSLATE(YYX) \
+ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+
+/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
+static const unsigned char yytranslate[] =
+{
+ 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
+ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28
+};
+
+#if YYDEBUG
+/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
+ YYRHS. */
+static const unsigned char yyprhs[] =
+{
+ 0, 0, 3, 4, 7, 10, 11, 13, 15, 17,
+ 19, 21, 23, 25, 27, 29, 32, 34, 37, 39,
+ 42, 46, 49, 51, 54, 55, 58, 61, 63, 65,
+ 69, 71, 74, 76, 78, 81
+};
+
+/* YYRHS -- A `-1'-separated list of the rules' RHS. */
+static const yysigned_char yyrhs[] =
+{
+ 30, 0, -1, -1, 31, 32, -1, 32, 33, -1,
+ -1, 37, -1, 34, -1, 36, -1, 35, -1, 41,
+ -1, 42, -1, 43, -1, 45, -1, 46, -1, 24,
+ 38, -1, 26, -1, 26, 38, -1, 25, -1, 25,
+ 38, -1, 38, 44, 39, -1, 3, 38, -1, 3,
+ -1, 39, 40, -1, -1, 4, 17, -1, 23, 14,
+ -1, 17, -1, 22, -1, 38, 12, 39, -1, 28,
+ -1, 27, 38, -1, 6, -1, 7, -1, 16, 14,
+ -1, 14, -1
+};
+
+/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
+static const unsigned short int yyrline[] =
+{
+ 0, 142, 142, 142, 149, 175, 178, 182, 186, 190,
+ 194, 198, 202, 206, 210, 216, 224, 230, 239, 245,
+ 254, 264, 266, 269, 274, 277, 278, 279, 280, 283,
+ 292, 300, 309, 309, 312, 320
+};
+#endif
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+ First, the terminals, then, starting at YYNTOKENS, nonterminals. */
+static const char *const yytname[] =
+{
+ "$end", "error", "$undefined", "ID_SIMPLE", "ID_LIST", "LBRACE", "EQ",
+ "PLUSEQ", "MINUSQE", "STAREQ", "TILDEEQ", "RBRACE", "COLON", "NUMSIGN",
+ "NEWLINE", "NUMBER", "COMMENT", "CONT", "DOT", "RCURLY", "LCURLY",
+ "ID_ARGS", "LIST_COMMENT", "ID_LIST_SINGLE", "IF_KEYWORD",
+ "ELSE_KEYWORD", "ENDIF_KEYWORD", "KEYWORD", "RULE", "$accept", "project",
+ "@1", "statements", "statement", "automake_if", "endif_statement",
+ "else_statement", "variable_assignment", "scoped_identifier",
+ "multiline_values", "line_body", "target", "am_rule",
+ "include_directive", "operator", "comment", "emptyline", 0
+};
+#endif
+
+# ifdef YYPRINT
+/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
+ token YYLEX-NUM. */
+static const unsigned short int yytoknum[] =
+{
+ 0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
+ 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
+ 275, 276, 277, 278, 279, 280, 281, 282, 283
+};
+# endif
+
+/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
+static const unsigned char yyr1[] =
+{
+ 0, 29, 31, 30, 32, 32, 33, 33, 33, 33,
+ 33, 33, 33, 33, 33, 34, 35, 35, 36, 36,
+ 37, 38, 38, 39, 39, 40, 40, 40, 40, 41,
+ 42, 43, 44, 44, 45, 46
+};
+
+/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
+static const unsigned char yyr2[] =
+{
+ 0, 2, 0, 2, 2, 0, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 2, 1, 2, 1, 2,
+ 3, 2, 1, 2, 0, 2, 2, 1, 1, 3,
+ 1, 2, 1, 1, 2, 1
+};
+
+/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
+ STATE-NUM when YYTABLE doesn't specify something else to do. Zero
+ means the default is an error. */
+static const unsigned char yydefact[] =
+{
+ 2, 0, 5, 1, 3, 22, 35, 0, 0, 18,
+ 16, 0, 30, 4, 7, 9, 8, 6, 0, 10,
+ 11, 12, 13, 14, 21, 34, 15, 19, 17, 31,
+ 32, 33, 24, 24, 29, 20, 0, 27, 28, 0,
+ 23, 25, 26
+};
+
+/* YYDEFGOTO[NTERM-NUM]. */
+static const yysigned_char yydefgoto[] =
+{
+ -1, 1, 2, 4, 13, 14, 15, 16, 17, 18,
+ 34, 40, 19, 20, 21, 33, 22, 23
+};
+
+/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+ STATE-NUM. */
+#define YYPACT_NINF -18
+static const yysigned_char yypact[] =
+{
+ -18, 2, -18, -18, -3, 0, -18, -6, 0, 0,
+ 0, 0, -18, -18, -18, -18, -18, -18, 3, -18,
+ -18, -18, -18, -18, -18, -18, -18, -18, -18, -18,
+ -18, -18, -18, -18, 10, 10, -5, -18, -18, 4,
+ -18, -18, -18
+};
+
+/* YYPGOTO[NTERM-NUM]. */
+static const yysigned_char yypgoto[] =
+{
+ -18, -18, -18, -18, -18, -18, -18, -18, -18, -4,
+ -17, -18, -18, -18, -18, -18, -18, -18
+};
+
+/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
+ positive, shift that token. If negative, reduce the rule which
+ number is the opposite. If zero, do what YYDEFACT says.
+ If YYTABLE_NINF, syntax error. */
+#define YYTABLE_NINF -1
+static const unsigned char yytable[] =
+{
+ 5, 24, 3, 5, 26, 27, 28, 29, 25, 30,
+ 31, 6, 41, 7, 36, 32, 35, 0, 42, 0,
+ 0, 8, 9, 10, 11, 12, 0, 37, 0, 0,
+ 0, 0, 38, 39
+};
+
+static const yysigned_char yycheck[] =
+{
+ 3, 5, 0, 3, 8, 9, 10, 11, 14, 6,
+ 7, 14, 17, 16, 4, 12, 33, -1, 14, -1,
+ -1, 24, 25, 26, 27, 28, -1, 17, -1, -1,
+ -1, -1, 22, 23
+};
+
+/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+ symbol of state STATE-NUM. */
+static const unsigned char yystos[] =
+{
+ 0, 30, 31, 0, 32, 3, 14, 16, 24, 25,
+ 26, 27, 28, 33, 34, 35, 36, 37, 38, 41,
+ 42, 43, 45, 46, 38, 14, 38, 38, 38, 38,
+ 6, 7, 12, 44, 39, 39, 4, 17, 22, 23,
+ 40, 17, 14
+};
+
+#define yyerrok (yyerrstatus = 0)
+#define yyclearin (yychar = YYEMPTY)
+#define YYEMPTY (-2)
+#define YYEOF 0
+
+#define YYACCEPT goto yyacceptlab
+#define YYABORT goto yyabortlab
+#define YYERROR goto yyerrorlab
+
+
+/* Like YYERROR except do call yyerror. This remains here temporarily
+ to ease the transition to the new meaning of YYERROR, for GCC.
+ Once GCC version 2 has supplanted version 1, this can go. */
+
+#define YYFAIL goto yyerrlab
+
+#define YYRECOVERING() (!!yyerrstatus)
+
+#define YYBACKUP(Token, Value) \
+do \
+ if (yychar == YYEMPTY && yylen == 1) \
+ { \
+ yychar = (Token); \
+ yylval = (Value); \
+ yytoken = YYTRANSLATE (yychar); \
+ YYPOPSTACK; \
+ goto yybackup; \
+ } \
+ else \
+ { \
+ yyerror (YY_("syntax error: cannot back up")); \
+ YYERROR; \
+ } \
+while (0)
+
+
+#define YYTERROR 1
+#define YYERRCODE 256
+
+
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+ If N is 0, then set CURRENT to the empty location which ends
+ the previous symbol: RHS[0] (always defined). */
+
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N) \
+ do \
+ if (N) \
+ { \
+ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
+ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
+ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
+ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
+ } \
+ else \
+ { \
+ (Current).first_line = (Current).last_line = \
+ YYRHSLOC (Rhs, 0).last_line; \
+ (Current).first_column = (Current).last_column = \
+ YYRHSLOC (Rhs, 0).last_column; \
+ } \
+ while (0)
+#endif
+
+
+/* YY_LOCATION_PRINT -- Print the location on the stream.
+ This macro was not mandated originally: define only if we know
+ we won't break user code: when these are the locations we know. */
+
+#ifndef YY_LOCATION_PRINT
+# if YYLTYPE_IS_TRIVIAL
+# define YY_LOCATION_PRINT(File, Loc) \
+ fprintf (File, "%d.%d-%d.%d", \
+ (Loc).first_line, (Loc).first_column, \
+ (Loc).last_line, (Loc).last_column)
+# else
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# endif
+#endif
+
+
+/* YYLEX -- calling `yylex' with the right arguments. */
+
+#ifdef YYLEX_PARAM
+# define YYLEX yylex (YYLEX_PARAM)
+#else
+# define YYLEX yylex ()
+#endif
+
+/* Enable debugging if requested. */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+# define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args) \
+do { \
+ if (yydebug) \
+ YYFPRINTF Args; \
+} while (0)
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
+do { \
+ if (yydebug) \
+ { \
+ YYFPRINTF (stderr, "%s ", Title); \
+ yysymprint (stderr, \
+ Type, Value); \
+ YYFPRINTF (stderr, "\n"); \
+ } \
+} while (0)
+
+/*------------------------------------------------------------------.
+| yy_stack_print -- Print the state stack from its BOTTOM up to its |
+| TOP (included). |
+`------------------------------------------------------------------*/
+
+#if defined (__STDC__) || defined (__cplusplus)
+static void
+yy_stack_print (short int *bottom, short int *top)
+#else
+static void
+yy_stack_print (bottom, top)
+ short int *bottom;
+ short int *top;
+#endif
+{
+ YYFPRINTF (stderr, "Stack now");
+ for (/* Nothing. */; bottom <= top; ++bottom)
+ YYFPRINTF (stderr, " %d", *bottom);
+ YYFPRINTF (stderr, "\n");
+}
+
+# define YY_STACK_PRINT(Bottom, Top) \
+do { \
+ if (yydebug) \
+ yy_stack_print ((Bottom), (Top)); \
+} while (0)
+
+
+/*------------------------------------------------.
+| Report that the YYRULE is going to be reduced. |
+`------------------------------------------------*/
+
+#if defined (__STDC__) || defined (__cplusplus)
+static void
+yy_reduce_print (int yyrule)
+#else
+static void
+yy_reduce_print (yyrule)
+ int yyrule;
+#endif
+{
+ int yyi;
+ unsigned long int yylno = yyrline[yyrule];
+ YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu), ",
+ yyrule - 1, yylno);
+ /* Print the symbols being reduced, and their result. */
+ for (yyi = yyprhs[yyrule]; 0 <= yyrhs[yyi]; yyi++)
+ YYFPRINTF (stderr, "%s ", yytname[yyrhs[yyi]]);
+ YYFPRINTF (stderr, "-> %s\n", yytname[yyr1[yyrule]]);
+}
+
+# define YY_REDUCE_PRINT(Rule) \
+do { \
+ if (yydebug) \
+ yy_reduce_print (Rule); \
+} while (0)
+
+/* Nonzero means print parse trace. It is left uninitialized so that
+ multiple parsers can coexist. */
+int yydebug;
+#else /* !YYDEBUG */
+# define YYDPRINTF(Args)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_STACK_PRINT(Bottom, Top)
+# define YY_REDUCE_PRINT(Rule)
+#endif /* !YYDEBUG */
+
+
+/* YYINITDEPTH -- initial size of the parser's stacks. */
+#ifndef YYINITDEPTH
+# define YYINITDEPTH 200
+#endif
+
+/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
+ if the built-in stack extension method is used).
+
+ Do not make this value too large; the results are undefined if
+ YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
+ evaluated with infinite-precision integer arithmetic. */
+
+#ifndef YYMAXDEPTH
+# define YYMAXDEPTH 10000
+#endif
+
+
+
+#if YYERROR_VERBOSE
+
+# ifndef yystrlen
+# if defined (__GLIBC__) && defined (_STRING_H)
+# define yystrlen strlen
+# else
+/* Return the length of YYSTR. */
+static YYSIZE_T
+# if defined (__STDC__) || defined (__cplusplus)
+yystrlen (const char *yystr)
+# else
+yystrlen (yystr)
+ const char *yystr;
+# endif
+{
+ const char *yys = yystr;
+
+ while (*yys++ != '\0')
+ continue;
+
+ return yys - yystr - 1;
+}
+# endif
+# endif
+
+# ifndef yystpcpy
+# if defined (__GLIBC__) && defined (_STRING_H) && defined (_GNU_SOURCE)
+# define yystpcpy stpcpy
+# else
+/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
+ YYDEST. */
+static char *
+# if defined (__STDC__) || defined (__cplusplus)
+yystpcpy (char *yydest, const char *yysrc)
+# else
+yystpcpy (yydest, yysrc)
+ char *yydest;
+ const char *yysrc;
+# endif
+{
+ char *yyd = yydest;
+ const char *yys = yysrc;
+
+ while ((*yyd++ = *yys++) != '\0')
+ continue;
+
+ return yyd - 1;
+}
+# endif
+# endif
+
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+ quotes and backslashes, so that it's suitable for yyerror. The
+ heuristic is that double-quoting is unnecessary unless the string
+ contains an apostrophe, a comma, or backslash (other than
+ backslash-backslash). YYSTR is taken from yytname. If YYRES is
+ null, do not copy; instead, return the length of what the result
+ would have been. */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+ if (*yystr == '"')
+ {
+ size_t yyn = 0;
+ char const *yyp = yystr;
+
+ for (;;)
+ switch (*++yyp)
+ {
+ case '\'':
+ case ',':
+ goto do_not_strip_quotes;
+
+ case '\\':
+ if (*++yyp != '\\')
+ goto do_not_strip_quotes;
+ /* Fall through. */
+ default:
+ if (yyres)
+ yyres[yyn] = *yyp;
+ yyn++;
+ break;
+
+ case '"':
+ if (yyres)
+ yyres[yyn] = '\0';
+ return yyn;
+ }
+ do_not_strip_quotes: ;
+ }
+
+ if (! yyres)
+ return yystrlen (yystr);
+
+ return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+#endif /* YYERROR_VERBOSE */
+
+
+
+#if YYDEBUG
+/*--------------------------------.
+| Print this symbol on YYOUTPUT. |
+`--------------------------------*/
+
+#if defined (__STDC__) || defined (__cplusplus)
+static void
+yysymprint (FILE *yyoutput, int yytype, YYSTYPE *yyvaluep)
+#else
+static void
+yysymprint (yyoutput, yytype, yyvaluep)
+ FILE *yyoutput;
+ int yytype;
+ YYSTYPE *yyvaluep;
+#endif
+{
+ /* Pacify ``unused variable'' warnings. */
+ (void) yyvaluep;
+
+ if (yytype < YYNTOKENS)
+ YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
+ else
+ YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+
+
+# ifdef YYPRINT
+ if (yytype < YYNTOKENS)
+ YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# endif
+ switch (yytype)
+ {
+ default:
+ break;
+ }
+ YYFPRINTF (yyoutput, ")");
+}
+
+#endif /* ! YYDEBUG */
+/*-----------------------------------------------.
+| Release the memory associated to this symbol. |
+`-----------------------------------------------*/
+
+#if defined (__STDC__) || defined (__cplusplus)
+static void
+yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
+#else
+static void
+yydestruct (yymsg, yytype, yyvaluep)
+ const char *yymsg;
+ int yytype;
+ YYSTYPE *yyvaluep;
+#endif
+{
+ /* Pacify ``unused variable'' warnings. */
+ (void) yyvaluep;
+
+ if (!yymsg)
+ yymsg = "Deleting";
+ YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+ switch (yytype)
+ {
+
+ default:
+ break;
+ }
+}
+
+
+/* Prevent warnings from -Wmissing-prototypes. */
+
+#ifdef YYPARSE_PARAM
+# if defined (__STDC__) || defined (__cplusplus)
+int yyparse (void *YYPARSE_PARAM);
+# else
+int yyparse ();
+# endif
+#else /* ! YYPARSE_PARAM */
+#if defined (__STDC__) || defined (__cplusplus)
+int yyparse (void);
+#else
+int yyparse ();
+#endif
+#endif /* ! YYPARSE_PARAM */
+
+
+
+/* The look-ahead symbol. */
+int yychar;
+
+/* The semantic value of the look-ahead symbol. */
+YYSTYPE yylval;
+
+/* Number of syntax errors so far. */
+int yynerrs;
+
+
+
+/*----------.
+| yyparse. |
+`----------*/
+
+#ifdef YYPARSE_PARAM
+# if defined (__STDC__) || defined (__cplusplus)
+int yyparse (void *YYPARSE_PARAM)
+# else
+int yyparse (YYPARSE_PARAM)
+ void *YYPARSE_PARAM;
+# endif
+#else /* ! YYPARSE_PARAM */
+#if defined (__STDC__) || defined (__cplusplus)
+int
+yyparse (void)
+#else
+int
+yyparse ()
+ ;
+#endif
+#endif
+{
+
+ int yystate;
+ int yyn;
+ int yyresult;
+ /* Number of tokens to shift before error messages enabled. */
+ int yyerrstatus;
+ /* Look-ahead token as an internal (translated) token number. */
+ int yytoken = 0;
+
+ /* Three stacks and their tools:
+ `yyss': related to states,
+ `yyvs': related to semantic values,
+ `yyls': related to locations.
+
+ Refer to the stacks thru separate pointers, to allow yyoverflow
+ to reallocate them elsewhere. */
+
+ /* The state stack. */
+ short int yyssa[YYINITDEPTH];
+ short int *yyss = yyssa;
+ short int *yyssp;
+
+ /* The semantic value stack. */
+ YYSTYPE yyvsa[YYINITDEPTH];
+ YYSTYPE *yyvs = yyvsa;
+ YYSTYPE *yyvsp;
+
+
+
+#define YYPOPSTACK (yyvsp--, yyssp--)
+
+ YYSIZE_T yystacksize = YYINITDEPTH;
+
+ /* The variables used to return semantic value and location from the
+ action routines. */
+ YYSTYPE yyval;
+
+
+ /* When reducing, the number of symbols on the RHS of the reduced
+ rule. */
+ int yylen;
+
+ YYDPRINTF ((stderr, "Starting parse\n"));
+
+ yystate = 0;
+ yyerrstatus = 0;
+ yynerrs = 0;
+ yychar = YYEMPTY; /* Cause a token to be read. */
+
+ /* Initialize stack pointers.
+ Waste one element of value and location stack
+ so that they stay on the same level as the state stack.
+ The wasted elements are never initialized. */
+
+ yyssp = yyss;
+ yyvsp = yyvs;
+
+ goto yysetstate;
+
+/*------------------------------------------------------------.
+| yynewstate -- Push a new state, which is found in yystate. |
+`------------------------------------------------------------*/
+ yynewstate:
+ /* In all cases, when you get here, the value and location stacks
+ have just been pushed. so pushing a state here evens the stacks.
+ */
+ yyssp++;
+
+ yysetstate:
+ *yyssp = yystate;
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ {
+ /* Get the current used size of the three stacks, in elements. */
+ YYSIZE_T yysize = yyssp - yyss + 1;
+
+#ifdef yyoverflow
+ {
+ /* Give user a chance to reallocate the stack. Use copies of
+ these so that the &'s don't force the real ones into
+ memory. */
+ YYSTYPE *yyvs1 = yyvs;
+ short int *yyss1 = yyss;
+
+
+ /* Each stack pointer address is followed by the size of the
+ data in use in that stack, in bytes. This used to be a
+ conditional around just the two extra args, but that might
+ be undefined if yyoverflow is a macro. */
+ yyoverflow (YY_("memory exhausted"),
+ &yyss1, yysize * sizeof (*yyssp),
+ &yyvs1, yysize * sizeof (*yyvsp),
+
+ &yystacksize);
+
+ yyss = yyss1;
+ yyvs = yyvs1;
+ }
+#else /* no yyoverflow */
+# ifndef YYSTACK_RELOCATE
+ goto yyexhaustedlab;
+# else
+ /* Extend the stack our own way. */
+ if (YYMAXDEPTH <= yystacksize)
+ goto yyexhaustedlab;
+ yystacksize *= 2;
+ if (YYMAXDEPTH < yystacksize)
+ yystacksize = YYMAXDEPTH;
+
+ {
+ short int *yyss1 = yyss;
+ union yyalloc *yyptr =
+ (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+ if (! yyptr)
+ goto yyexhaustedlab;
+ YYSTACK_RELOCATE (yyss);
+ YYSTACK_RELOCATE (yyvs);
+
+# undef YYSTACK_RELOCATE
+ if (yyss1 != yyssa)
+ YYSTACK_FREE (yyss1);
+ }
+# endif
+#endif /* no yyoverflow */
+
+ yyssp = yyss + yysize - 1;
+ yyvsp = yyvs + yysize - 1;
+
+
+ YYDPRINTF ((stderr, "Stack size increased to %lu\n",
+ (unsigned long int) yystacksize));
+
+ if (yyss + yystacksize - 1 <= yyssp)
+ YYABORT;
+ }
+
+ YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+ goto yybackup;
+
+/*-----------.
+| yybackup. |
+`-----------*/
+yybackup:
+
+/* Do appropriate processing given the current state. */
+/* Read a look-ahead token if we need one and don't already have one. */
+/* yyresume: */
+
+ /* First try to decide what to do without reference to look-ahead token. */
+
+ yyn = yypact[yystate];
+ if (yyn == YYPACT_NINF)
+ goto yydefault;
+
+ /* Not known => get a look-ahead token if don't already have one. */
+
+ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */
+ if (yychar == YYEMPTY)
+ {
+ YYDPRINTF ((stderr, "Reading a token: "));
+ yychar = YYLEX;
+ }
+
+ if (yychar <= YYEOF)
+ {
+ yychar = yytoken = YYEOF;
+ YYDPRINTF ((stderr, "Now at end of input.\n"));
+ }
+ else
+ {
+ yytoken = YYTRANSLATE (yychar);
+ YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+ }
+
+ /* If the proper action on seeing token YYTOKEN is to reduce or to
+ detect an error, take that action. */
+ yyn += yytoken;
+ if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+ goto yydefault;
+ yyn = yytable[yyn];
+ if (yyn <= 0)
+ {
+ if (yyn == 0 || yyn == YYTABLE_NINF)
+ goto yyerrlab;
+ yyn = -yyn;
+ goto yyreduce;
+ }
+
+ if (yyn == YYFINAL)
+ YYACCEPT;
+
+ /* Shift the look-ahead token. */
+ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+ /* Discard the token being shifted unless it is eof. */
+ if (yychar != YYEOF)
+ yychar = YYEMPTY;
+
+ *++yyvsp = yylval;
+
+
+ /* Count tokens shifted since error; after three, turn off error
+ status. */
+ if (yyerrstatus)
+ yyerrstatus--;
+
+ yystate = yyn;
+ goto yynewstate;
+
+
+/*-----------------------------------------------------------.
+| yydefault -- do the default action for the current state. |
+`-----------------------------------------------------------*/
+yydefault:
+ yyn = yydefact[yystate];
+ if (yyn == 0)
+ goto yyerrlab;
+ goto yyreduce;
+
+
+/*-----------------------------.
+| yyreduce -- Do a reduction. |
+`-----------------------------*/
+yyreduce:
+ /* yyn is the number of a rule to reduce with. */
+ yylen = yyr2[yyn];
+
+ /* If YYLEN is nonzero, implement the default value of the action:
+ `$$ = $1'.
+
+ Otherwise, the following line sets YYVAL to garbage.
+ This behavior is undocumented and Bison
+ users should not rely upon it. Assigning to YYVAL
+ unconditionally makes the parser a bit smaller, and it avoids a
+ GCC warning that YYVAL may be used uninitialized. */
+ yyval = yyvsp[1-yylen];
+
+
+ YY_REDUCE_PRINT (yyn);
+ switch (yyn)
+ {
+ case 2:
+#line 142 "autotools.yy"
+ {
+ ProjectAST *projectAST = new ProjectAST();
+ projects.push(projectAST);
+;}
+ break;
+
+ case 4:
+#line 150 "autotools.yy"
+ {
+ projects.top()->addChildAST((yyvsp[0].node));
+
+ if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "if" )
+ {
+ (yyvsp[0].node)->setDepth(depth);
+ depth++;
+ }
+ else if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "else" )
+ {
+ --depth;
+ (yyvsp[0].node)->setDepth(depth);
+ ++depth;
+ }
+ else if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "endif" )
+ {
+ --depth;
+ (yyvsp[0].node)->setDepth(depth);
+ }
+ else
+ (yyvsp[0].node)->setDepth(depth);
+;}
+ break;
+
+ case 6:
+#line 179 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 7:
+#line 183 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 8:
+#line 187 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 9:
+#line 191 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 10:
+#line 195 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 11:
+#line 199 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 12:
+#line 203 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 13:
+#line 207 "autotools.yy"
+ {
+ (yyval.node) = (yyvsp[0].node);
+;}
+ break;
+
+ case 14:
+#line 211 "autotools.yy"
+ {
+ (yyval.node) = new NewLineAST();
+;}
+ break;
+
+ case 15:
+#line 217 "autotools.yy"
+ {
+ ConditionAST* projectAST = new ConditionAST();
+ projectAST->type = "if";
+ projectAST->conditionName = (yyvsp[0].value);
+ (yyval.node) = projectAST;
+;}
+ break;
+
+ case 16:
+#line 225 "autotools.yy"
+ {
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ (yyval.node) = past;
+;}
+ break;
+
+ case 17:
+#line 231 "autotools.yy"
+ {
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ past->conditionName = (yyvsp[0].value);
+ (yyval.node) = past;
+;}
+ break;
+
+ case 18:
+#line 240 "autotools.yy"
+ {
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ (yyval.node) = past;
+;}
+ break;
+
+ case 19:
+#line 246 "autotools.yy"
+ {
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ past->conditionName = (yyvsp[0].value);
+ (yyval.node) = past;
+;}
+ break;
+
+ case 20:
+#line 255 "autotools.yy"
+ {
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = (yyvsp[-2].value);
+ node->op = (yyvsp[-1].value);
+ node->values = (yyvsp[0].values);
+ (yyval.node) = node;
+;}
+ break;
+
+ case 21:
+#line 265 "autotools.yy"
+ { (yyval.value) = (yyvsp[-1].value) + (yyvsp[0].value); ;}
+ break;
+
+ case 23:
+#line 270 "autotools.yy"
+ {
+ QStringList list = (yyvsp[0].value).split(QRegExp("\\s+"), QString::SkipEmptyParts);
+ (yyval.values) = (yyval.values) + list; //.append($<value>2);
+;}
+ break;
+
+ case 24:
+#line 274 "autotools.yy"
+ { (yyval.values).clear(); ;}
+ break;
+
+ case 25:
+#line 277 "autotools.yy"
+ { (yyval.value) = (yyvsp[-1].value) + " \\\n"; ;}
+ break;
+
+ case 26:
+#line 278 "autotools.yy"
+ { (yyval.value) = (yyvsp[-1].value) + "\n"; ;}
+ break;
+
+ case 27:
+#line 279 "autotools.yy"
+ { (yyval.value) = "\\\n"; ;}
+ break;
+
+ case 29:
+#line 284 "autotools.yy"
+ {
+ AutomakeTargetAST *node = new AutomakeTargetAST();
+ node->target = (yyvsp[-2].value);
+ node->deps = (yyvsp[0].values);
+ (yyval.node) = node;
+;}
+ break;
+
+ case 30:
+#line 293 "autotools.yy"
+ {
+ ProjectAST* node = new ProjectAST(ProjectAST::Rule);
+ node->scopedID = (yyvsp[0].value);
+ (yyval.node) = node;
+;}
+ break;
+
+ case 31:
+#line 301 "autotools.yy"
+ {
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = (yyvsp[-1].value);
+ node->values = QStringList((yyvsp[0].value));
+ (yyval.node) = node;
+;}
+ break;
+
+ case 34:
+#line 313 "autotools.yy"
+ {
+ CommentAST *node = new CommentAST();
+ node->comment = (yyvsp[-1].value) + "\n";
+ (yyval.node) = node;
+;}
+ break;
+
+
+ default: break;
+ }
+
+/* Line 1126 of yacc.c. */
+#line 1517 "autotools_yacc.cpp"
+
+ yyvsp -= yylen;
+ yyssp -= yylen;
+
+
+ YY_STACK_PRINT (yyss, yyssp);
+
+ *++yyvsp = yyval;
+
+
+ /* Now `shift' the result of the reduction. Determine what state
+ that goes to, based on the state we popped back to and the rule
+ number reduced by. */
+
+ yyn = yyr1[yyn];
+
+ yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
+ if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
+ yystate = yytable[yystate];
+ else
+ yystate = yydefgoto[yyn - YYNTOKENS];
+
+ goto yynewstate;
+
+
+/*------------------------------------.
+| yyerrlab -- here on detecting error |
+`------------------------------------*/
+yyerrlab:
+ /* If not already recovering from an error, report this error. */
+ if (!yyerrstatus)
+ {
+ ++yynerrs;
+#if YYERROR_VERBOSE
+ yyn = yypact[yystate];
+
+ if (YYPACT_NINF < yyn && yyn < YYLAST)
+ {
+ int yytype = YYTRANSLATE (yychar);
+ YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
+ YYSIZE_T yysize = yysize0;
+ YYSIZE_T yysize1;
+ int yysize_overflow = 0;
+ char *yymsg = 0;
+# define YYERROR_VERBOSE_ARGS_MAXIMUM 5
+ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+ int yyx;
+
+#if 0
+ /* This is so xgettext sees the translatable formats that are
+ constructed on the fly. */
+ YY_("syntax error, unexpected %s");
+ YY_("syntax error, unexpected %s, expecting %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s or %s");
+ YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
+#endif
+ char *yyfmt;
+ char const *yyf;
+ static char const yyunexpected[] = "syntax error, unexpected %s";
+ static char const yyexpecting[] = ", expecting %s";
+ static char const yyor[] = " or %s";
+ char yyformat[sizeof yyunexpected
+ + sizeof yyexpecting - 1
+ + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
+ * (sizeof yyor - 1))];
+ char const *yyprefix = yyexpecting;
+
+ /* Start YYX at -YYN if negative to avoid negative indexes in
+ YYCHECK. */
+ int yyxbegin = yyn < 0 ? -yyn : 0;
+
+ /* Stay within bounds of both yycheck and yytname. */
+ int yychecklim = YYLAST - yyn;
+ int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+ int yycount = 1;
+
+ yyarg[0] = yytname[yytype];
+ yyfmt = yystpcpy (yyformat, yyunexpected);
+
+ for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+ if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+ {
+ if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+ {
+ yycount = 1;
+ yysize = yysize0;
+ yyformat[sizeof yyunexpected - 1] = '\0';
+ break;
+ }
+ yyarg[yycount++] = yytname[yyx];
+ yysize1 = yysize + yytnamerr (0, yytname[yyx]);
+ yysize_overflow |= yysize1 < yysize;
+ yysize = yysize1;
+ yyfmt = yystpcpy (yyfmt, yyprefix);
+ yyprefix = yyor;
+ }
+
+ yyf = YY_(yyformat);
+ yysize1 = yysize + yystrlen (yyf);
+ yysize_overflow |= yysize1 < yysize;
+ yysize = yysize1;
+
+ if (!yysize_overflow && yysize <= YYSTACK_ALLOC_MAXIMUM)
+ yymsg = (char *) YYSTACK_ALLOC (yysize);
+ if (yymsg)
+ {
+ /* Avoid sprintf, as that infringes on the user's name space.
+ Don't have undefined behavior even if the translation
+ produced a string with the wrong number of "%s"s. */
+ char *yyp = yymsg;
+ int yyi = 0;
+ while ((*yyp = *yyf))
+ {
+ if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
+ {
+ yyp += yytnamerr (yyp, yyarg[yyi++]);
+ yyf += 2;
+ }
+ else
+ {
+ yyp++;
+ yyf++;
+ }
+ }
+ yyerror (yymsg);
+ YYSTACK_FREE (yymsg);
+ }
+ else
+ {
+ yyerror (YY_("syntax error"));
+ goto yyexhaustedlab;
+ }
+ }
+ else
+#endif /* YYERROR_VERBOSE */
+ yyerror (YY_("syntax error"));
+ }
+
+
+
+ if (yyerrstatus == 3)
+ {
+ /* If just tried and failed to reuse look-ahead token after an
+ error, discard it. */
+
+ if (yychar <= YYEOF)
+ {
+ /* Return failure if at end of input. */
+ if (yychar == YYEOF)
+ YYABORT;
+ }
+ else
+ {
+ yydestruct ("Error: discarding", yytoken, &yylval);
+ yychar = YYEMPTY;
+ }
+ }
+
+ /* Else will try to reuse look-ahead token after shifting the error
+ token. */
+ goto yyerrlab1;
+
+
+/*---------------------------------------------------.
+| yyerrorlab -- error raised explicitly by YYERROR. |
+`---------------------------------------------------*/
+yyerrorlab:
+
+ /* Pacify compilers like GCC when the user code never invokes
+ YYERROR and the label yyerrorlab therefore never appears in user
+ code. */
+ if (0)
+ goto yyerrorlab;
+
+yyvsp -= yylen;
+ yyssp -= yylen;
+ yystate = *yyssp;
+ goto yyerrlab1;
+
+
+/*-------------------------------------------------------------.
+| yyerrlab1 -- common code for both syntax error and YYERROR. |
+`-------------------------------------------------------------*/
+yyerrlab1:
+ yyerrstatus = 3; /* Each real token shifted decrements this. */
+
+ for (;;)
+ {
+ yyn = yypact[yystate];
+ if (yyn != YYPACT_NINF)
+ {
+ yyn += YYTERROR;
+ if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+ {
+ yyn = yytable[yyn];
+ if (0 < yyn)
+ break;
+ }
+ }
+
+ /* Pop the current state because it cannot handle the error token. */
+ if (yyssp == yyss)
+ YYABORT;
+
+
+ yydestruct ("Error: popping", yystos[yystate], yyvsp);
+ YYPOPSTACK;
+ yystate = *yyssp;
+ YY_STACK_PRINT (yyss, yyssp);
+ }
+
+ if (yyn == YYFINAL)
+ YYACCEPT;
+
+ *++yyvsp = yylval;
+
+
+ /* Shift the error token. */
+ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
+
+ yystate = yyn;
+ goto yynewstate;
+
+
+/*-------------------------------------.
+| yyacceptlab -- YYACCEPT comes here. |
+`-------------------------------------*/
+yyacceptlab:
+ yyresult = 0;
+ goto yyreturn;
+
+/*-----------------------------------.
+| yyabortlab -- YYABORT comes here. |
+`-----------------------------------*/
+yyabortlab:
+ yyresult = 1;
+ goto yyreturn;
+
+#ifndef yyoverflow
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here. |
+`-------------------------------------------------*/
+yyexhaustedlab:
+ yyerror (YY_("memory exhausted"));
+ yyresult = 2;
+ /* Fall through. */
+#endif
+
+yyreturn:
+ if (yychar != YYEOF && yychar != YYEMPTY)
+ yydestruct ("Cleanup: discarding lookahead",
+ yytoken, &yylval);
+ while (yyssp != yyss)
+ {
+ yydestruct ("Cleanup: popping",
+ yystos[*yyssp], yyvsp);
+ YYPOPSTACK;
+ }
+#ifndef yyoverflow
+ if (yyss != yyssa)
+ YYSTACK_FREE (yyss);
+#endif
+ return yyresult;
+}
+
+
+#line 322 "autotools.yy"
+
+
+#include "automake_lex.cpp"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.yy
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.yy (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.yy (revision 1522570)
@@ -0,0 +1,322 @@
+%{
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+/**
+@file autotools.yy
+Autotools Parser
+
+Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
+
+@todo Recognize comments after statements like:
+noinst_HEADERS = foo.h #regognize me
+
+@fixme Parser fails on files that do not end with a newline
+@fixme 1 shift/reduce conflict in "line_body" rule
+*/
+
+
+#include <qstack.h>
+#include "automakeast.h"
+
+#define YYSTYPE_IS_DECLARED
+
+using namespace AutoMake;
+
+/**
+The yylval type.
+*/
+typedef struct Result {
+ Result(): node(0) {}
+
+ /**Type of semantic value for simple grammar rules.*/
+ QString value;
+ /**Type of semantic value for grammar rules which are parts of AST.*/
+ AST *node;
+ /**Type of semantic value for "multiline_values" grammar rule.
+ Each line of multiline value is stored as a string in the list.
+
+ For example we have in Makefile.am file:
+ @code
+ foo_SOURCES = foo1.cpp \
+ foo2.cpp \
+ foo3.cpp foo4.cpp
+ @endcode
+ The string list will be populated with three strings:
+ <pre>
+ foo1.cpp
+ foo2.cpp
+ foo3.cpp foo4.cpp
+ </pre>
+ */
+ QStringList values;
+} YYSTYPE;
+
+
+void yyerror(const char *str) {
+ qWarning("bison error: %s\n", str);
+}
+
+int yylex();
+
+/**
+The stack to store ProjectAST pointers when a new child
+ProjectAST is created and filled with statements.
+
+Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
+adding statements. Each statement is added as a child StatementAST to the ProjectAST
+currently on the top in the stack.
+
+When a scope or function scope statement is parsed, the child ProjectAST is created
+and pushed onto the stack. Therefore all statements which belong to the scope
+or function scope are added as childs to their direct parent (scope or function scope).
+*/
+QStack<ProjectAST*> projects;
+
+/**
+The current depth of AST node is stored here.
+AST depth is important to know because automatic indentation can
+be easily implemented (the parser itself looses all information
+about indentation).
+*/
+int depth = 0;
+
+/*
+To debug this parser, put the line below into the next bison file section.
+Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
+%debug
+*/
+%}
+%debug
+%token ID_SIMPLE
+%token ID_LIST
+%token LBRACE
+%token EQ
+%token PLUSEQ
+%token MINUSQE
+%token STAREQ
+%token TILDEEQ
+%token LBRACE
+%token RBRACE
+%token COLON
+%token NUMSIGN
+%token NEWLINE
+%token NUMBER
+%token COMMENT
+%token CONT
+%token DOT
+%token RCURLY
+%token LCURLY
+%token ID_ARGS
+%token LIST_COMMENT
+%token ID_LIST_SINGLE
+%token IF_KEYWORD
+%token ELSE_KEYWORD
+%token ENDIF_KEYWORD
+%token KEYWORD
+%token RULE
+
+%%
+
+project :
+{
+ ProjectAST *projectAST = new ProjectAST();
+ projects.push(projectAST);
+}
+statements
+;
+
+statements : statements statement
+{
+ projects.top()->addChildAST($<node>2);
+
+ if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "if" )
+ {
+ $<node>2->setDepth(depth);
+ depth++;
+ }
+ else if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "else" )
+ {
+ --depth;
+ $<node>2->setDepth(depth);
+ ++depth;
+ }
+ else if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "endif" )
+ {
+ --depth;
+ $<node>2->setDepth(depth);
+ }
+ else
+ $<node>2->setDepth(depth);
+}
+|
+;
+
+statement : variable_assignment
+{
+ $<node>$ = $<node>1;
+}
+| automake_if
+{
+ $<node>$ = $<node>1;
+}
+| else_statement
+{
+ $<node>$ = $<node>1;
+}
+| endif_statement
+{
+ $<node>$ = $<node>1;
+}
+| target
+{
+ $<node>$ = $<node>1;
+}
+| am_rule
+{
+ $<node>$ = $<node>1;
+}
+| include_directive
+{
+ $<node>$ = $<node>1;
+}
+| comment
+{
+ $<node>$ = $<node>1;
+}
+| emptyline
+{
+ $<node>$ = new NewLineAST();
+}
+;
+
+automake_if: IF_KEYWORD scoped_identifier
+{
+ ConditionAST* projectAST = new ConditionAST();
+ projectAST->type = "if";
+ projectAST->conditionName = $<value>2;
+ $<node>$ = projectAST;
+};
+
+endif_statement: ENDIF_KEYWORD
+{
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ $<node>$ = past;
+}
+| ENDIF_KEYWORD scoped_identifier
+{
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ past->conditionName = $<value>2;
+ $<node>$ = past;
+}
+;
+
+else_statement: ELSE_KEYWORD
+{
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ $<node>$ = past;
+}
+| ELSE_KEYWORD scoped_identifier
+{
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ past->conditionName = $<value>2;
+ $<node>$ = past;
+}
+;
+
+variable_assignment : scoped_identifier operator multiline_values
+{
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = $<value>1;
+ node->op = $<value>2;
+ node->values = $<values>3;
+ $<node>$ = node;
+}
+;
+
+scoped_identifier : ID_SIMPLE scoped_identifier
+{ $<value>$ = $<value>1 + $<value>2; }
+| ID_SIMPLE
+;
+
+multiline_values : multiline_values line_body
+{
+ QStringList list = $<value>2.split(QRegExp("\\s+"), QString::SkipEmptyParts);
+ $<values>$ = $<values>$ + list; //.append($<value>2);
+}
+| { $<values>$.clear(); }
+ ;
+
+line_body : ID_LIST CONT { $<value>$ = $<value>1 + " \\\n"; }
+ | ID_LIST_SINGLE NEWLINE { $<value>$ = $<value>1 + "\n"; }
+ | CONT { $<value>$ = "\\\n"; }
+ | LIST_COMMENT
+ ;
+
+target: scoped_identifier COLON multiline_values
+{
+ AutomakeTargetAST *node = new AutomakeTargetAST();
+ node->target = $<value>1;
+ node->deps = $<values>3;
+ $<node>$ = node;
+}
+;
+
+am_rule: RULE
+{
+ ProjectAST* node = new ProjectAST(ProjectAST::Rule);
+ node->scopedID = $<value>1;
+ $<node>$ = node;
+}
+;
+
+include_directive: KEYWORD scoped_identifier
+{
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = $<value>1;
+ node->values = QStringList($<value>2);
+ $<node>$ = node;
+}
+;
+
+operator : EQ | PLUSEQ
+;
+
+comment : COMMENT NEWLINE
+{
+ CommentAST *node = new CommentAST();
+ node->comment = $<value>1 + "\n";
+ $<node>$ = node;
+}
+;
+
+emptyline : NEWLINE
+;
+%%
+
+#include "automake_lex.cpp"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.yy
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.ll
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.ll (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.ll (revision 1522570)
@@ -0,0 +1,137 @@
+%{
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "autotools_yacc.h"
+
+/**
+@file autotools.ll
+Autotools Lexer
+
+There are 3 types of identifiers recognized by this lexer:
+-id_simple: examples of such identifiers are qmake variables and scoped variables
+at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
+-id_list: those are "value list identifiers" at the right side in assignments
+(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
+-id_args: function arguments recognized as one identifier
+(example: ""${QMAKE_FILE} is intended only for Windows!""
+in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
+.
+
+To recognize those identifiers two additional start conditions are used: list and funcargs.
+
+@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
+the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
+so no indentation is preserved by this lexer (and parser).
+
+To debug this lexer, put the line below into the next flex file section.
+%option debug
+*/
+%}
+%option noyywrap
+%x list
+%x funcargs
+%x conditional
+
+delim [ \t]
+ws {delim}+
+letter [A-Za-z]
+digit [0-9]
+id_simple ({digit}|{letter}|\!|-|_|\*|\$|@)({letter}|{digit}|\||\!|-|_|\*|\$|\(|\.|\+|\-|\)|\/)*
+id_list [^\n#]*\\{ws}*
+id_args [^\n]*\)
+number {digit}+
+comment #.*
+comment_cont {ws}#.*\n
+id_list_single [^\n]*
+cont \\{ws}*\n
+keywords (if|else|endif|include)
+rule [\t]+[^\n]*
+
+%%
+
+<list,INITIAL>{ws} {}
+<list,INITIAL>{cont} { BEGIN(list); return CONT; }
+{keywords} {
+ yylval.value = yytext;
+ if ( yylval.value == "if" )
+ return IF_KEYWORD;
+
+ if ( yylval.value == "else" )
+ return ELSE_KEYWORD;
+
+ if ( yylval.value == "endif" )
+ return ENDIF_KEYWORD;
+
+ return KEYWORD;
+}
+
+
+{id_simple} { yylval.value = yytext; return (ID_SIMPLE); }
+
+<INITIAL>{rule} {
+ yylval.value = yytext;
+ return RULE;
+}
+
+<list>{id_list} {
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
+ unput('\\');
+ BEGIN(INITIAL);
+ return (ID_LIST);
+ }
+
+<list>{comment_cont} {
+ yylval.value = yytext;
+ BEGIN(list);
+ return (LIST_COMMENT);
+ }
+
+<list>{comment} {
+ yylval.value = yytext;
+ return LIST_COMMENT;
+ }
+
+<list>{id_list_single} {
+ yylval.value = yytext;
+ BEGIN(INITIAL);
+ return (ID_LIST_SINGLE);
+ }
+
+<funcargs>{id_args} {
+ yylval.value = yytext;
+ yylval.value = yylval.value.mid(0, yylval.value.length()-1);
+ unput(')');
+ BEGIN(INITIAL);
+ return (ID_ARGS);
+ }
+
+"=" { BEGIN(list); yylval.value = yytext; return EQ; }
+"+=" { BEGIN(list); yylval.value = yytext; return PLUSEQ; }
+"{" { return LCURLY; }
+"}" { return RCURLY; }
+":" { BEGIN(list); yylval.value = yytext; return COLON; }
+<list,INITIAL>"\n" { BEGIN(INITIAL); return NEWLINE; }
+{comment} { yylval.value = yytext; return (COMMENT); }
+
+%%
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automake.ll
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.yy
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.yy (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.yy (revision 1522570)
@@ -0,0 +1,322 @@
+%{
+/***************************************************************************
+ * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
+ * *
+ * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+/**
+@file autotools.yy
+Autotools Parser
+
+Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
+
+@todo Recognize comments after statements like:
+noinst_HEADERS = foo.h #regognize me
+
+@fixme Parser fails on files that do not end with a newline
+@fixme 1 shift/reduce conflict in "line_body" rule
+*/
+
+
+#include <qstack.h>
+#include "automakeast.h"
+
+#define YYSTYPE_IS_DECLARED
+
+using namespace AutoMake;
+
+/**
+The yylval type.
+*/
+typedef struct Result {
+ Result(): node(0) {}
+
+ /**Type of semantic value for simple grammar rules.*/
+ QString value;
+ /**Type of semantic value for grammar rules which are parts of AST.*/
+ AST *node;
+ /**Type of semantic value for "multiline_values" grammar rule.
+ Each line of multiline value is stored as a string in the list.
+
+ For example we have in Makefile.am file:
+ @code
+ foo_SOURCES = foo1.cpp \
+ foo2.cpp \
+ foo3.cpp foo4.cpp
+ @endcode
+ The string list will be populated with three strings:
+ <pre>
+ foo1.cpp
+ foo2.cpp
+ foo3.cpp foo4.cpp
+ </pre>
+ */
+ QStringList values;
+} YYSTYPE;
+
+
+void yyerror(const char *str) {
+ qWarning("bison error: %s\n", str);
+}
+
+int yylex();
+
+/**
+The stack to store ProjectAST pointers when a new child
+ProjectAST is created and filled with statements.
+
+Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
+adding statements. Each statement is added as a child StatementAST to the ProjectAST
+currently on the top in the stack.
+
+When a scope or function scope statement is parsed, the child ProjectAST is created
+and pushed onto the stack. Therefore all statements which belong to the scope
+or function scope are added as childs to their direct parent (scope or function scope).
+*/
+QStack<ProjectAST*> projects;
+
+/**
+The current depth of AST node is stored here.
+AST depth is important to know because automatic indentation can
+be easily implemented (the parser itself looses all information
+about indentation).
+*/
+int depth = 0;
+
+/*
+To debug this parser, put the line below into the next bison file section.
+Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
+%debug
+*/
+%}
+%debug
+%token ID_SIMPLE
+%token ID_LIST
+%token LBRACE
+%token EQ
+%token PLUSEQ
+%token MINUSQE
+%token STAREQ
+%token TILDEEQ
+%token LBRACE
+%token RBRACE
+%token COLON
+%token NUMSIGN
+%token NEWLINE
+%token NUMBER
+%token COMMENT
+%token CONT
+%token DOT
+%token RCURLY
+%token LCURLY
+%token ID_ARGS
+%token LIST_COMMENT
+%token ID_LIST_SINGLE
+%token IF_KEYWORD
+%token ELSE_KEYWORD
+%token ENDIF_KEYWORD
+%token KEYWORD
+%token RULE
+
+%%
+
+project :
+{
+ ProjectAST *projectAST = new ProjectAST();
+ projects.push(projectAST);
+}
+statements
+;
+
+statements : statements statement
+{
+ projects.top()->addChildAST($<node>2);
+
+ if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "if" )
+ {
+ $<node>2->setDepth(depth);
+ depth++;
+ }
+ else if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "else" )
+ {
+ --depth;
+ $<node>2->setDepth(depth);
+ ++depth;
+ }
+ else if ( $<node>2->nodeType() == AST::ProjectAST &&
+ static_cast<ProjectAST*>( $<node>2 )->scopedID == "endif" )
+ {
+ --depth;
+ $<node>2->setDepth(depth);
+ }
+ else
+ $<node>2->setDepth(depth);
+}
+|
+;
+
+statement : variable_assignment
+{
+ $<node>$ = $<node>1;
+}
+| automake_if
+{
+ $<node>$ = $<node>1;
+}
+| else_statement
+{
+ $<node>$ = $<node>1;
+}
+| endif_statement
+{
+ $<node>$ = $<node>1;
+}
+| target
+{
+ $<node>$ = $<node>1;
+}
+| am_rule
+{
+ $<node>$ = $<node>1;
+}
+| include_directive
+{
+ $<node>$ = $<node>1;
+}
+| comment
+{
+ $<node>$ = $<node>1;
+}
+| emptyline
+{
+ $<node>$ = new NewLineAST();
+}
+;
+
+automake_if: IF_KEYWORD scoped_identifier
+{
+ ConditionAST* projectAST = new ConditionAST();
+ projectAST->type = "if";
+ projectAST->conditionName = $<value>2;
+ $<node>$ = projectAST;
+};
+
+endif_statement: ENDIF_KEYWORD
+{
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ $<node>$ = past;
+}
+| ENDIF_KEYWORD scoped_identifier
+{
+ ConditionAST* past = new ConditionAST();
+ past->type= "endif";
+ past->conditionName = $<value>2;
+ $<node>$ = past;
+}
+;
+
+else_statement: ELSE_KEYWORD
+{
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ $<node>$ = past;
+}
+| ELSE_KEYWORD scoped_identifier
+{
+ ConditionAST* past = new ConditionAST();
+ past->type = "else";
+ past->conditionName = $<value>2;
+ $<node>$ = past;
+}
+;
+
+variable_assignment : scoped_identifier operator multiline_values
+{
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = $<value>1;
+ node->op = $<value>2;
+ node->values = $<values>3;
+ $<node>$ = node;
+}
+;
+
+scoped_identifier : ID_SIMPLE scoped_identifier
+{ $<value>$ = $<value>1 + $<value>2; }
+| ID_SIMPLE
+;
+
+multiline_values : multiline_values line_body
+{
+ QStringList list = $<value>2.split(QRegExp("\\s+"), QString::SkipEmptyParts);
+ $<values>$ = $<values>$ + list; //.append($<value>2);
+}
+| { $<values>$.clear(); }
+ ;
+
+line_body : ID_LIST CONT { $<value>$ = $<value>1 + " \\\n"; }
+ | ID_LIST_SINGLE NEWLINE { $<value>$ = $<value>1 + "\n"; }
+ | CONT { $<value>$ = "\\\n"; }
+ | LIST_COMMENT
+ ;
+
+target: scoped_identifier COLON multiline_values
+{
+ AutomakeTargetAST *node = new AutomakeTargetAST();
+ node->target = $<value>1;
+ node->deps = $<values>3;
+ $<node>$ = node;
+}
+;
+
+am_rule: RULE
+{
+ ProjectAST* node = new ProjectAST(ProjectAST::Rule);
+ node->scopedID = $<value>1;
+ $<node>$ = node;
+}
+;
+
+include_directive: KEYWORD scoped_identifier
+{
+ AssignmentAST *node = new AssignmentAST();
+ node->scopedID = $<value>1;
+ node->values = QStringList($<value>2);
+ $<node>$ = node;
+}
+;
+
+operator : EQ | PLUSEQ
+;
+
+comment : COMMENT NEWLINE
+{
+ CommentAST *node = new CommentAST();
+ node->comment = $<value>1 + "\n";
+ $<node>$ = node;
+}
+;
+
+emptyline : NEWLINE
+;
+%%
+
+#include "automake_lex.cpp"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autoconf.yy
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autotoolsparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/autotoolsparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/autotoolsparser.h (revision 1522570)
@@ -0,0 +1,101 @@
+/* A Bison parser, made by GNU Bison 2.1. */
+
+/* Skeleton parser for Yacc-like parsing with Bison,
+ Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+
+ 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, 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., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA. */
+
+/* As a special exception, when this file is copied by Bison into a
+ Bison output file, you may use that output file without restriction.
+ This special exception was added by the Free Software Foundation
+ in version 1.24 of Bison. */
+
+/* Tokens. */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+ /* Put the tokens into the symbol table, so that GDB and other debuggers
+ know about them. */
+ enum yytokentype {
+ ID_SIMPLE = 258,
+ ID_LIST = 259,
+ LBRACE = 260,
+ EQ = 261,
+ PLUSEQ = 262,
+ MINUSQE = 263,
+ STAREQ = 264,
+ TILDEEQ = 265,
+ RBRACE = 266,
+ COLON = 267,
+ NUMSIGN = 268,
+ NEWLINE = 269,
+ NUMBER = 270,
+ COMMENT = 271,
+ CONT = 272,
+ DOT = 273,
+ RCURLY = 274,
+ LCURLY = 275,
+ ID_ARGS = 276,
+ LIST_COMMENT = 277,
+ ID_LIST_SINGLE = 278,
+ IF_KEYWORD = 279,
+ ELSE_KEYWORD = 280,
+ ENDIF_KEYWORD = 281,
+ KEYWORD = 282,
+ RULE = 283
+ };
+#endif
+/* Tokens. */
+#define ID_SIMPLE 258
+#define ID_LIST 259
+#define LBRACE 260
+#define EQ 261
+#define PLUSEQ 262
+#define MINUSQE 263
+#define STAREQ 264
+#define TILDEEQ 265
+#define RBRACE 266
+#define COLON 267
+#define NUMSIGN 268
+#define NEWLINE 269
+#define NUMBER 270
+#define COMMENT 271
+#define CONT 272
+#define DOT 273
+#define RCURLY 274
+#define LCURLY 275
+#define ID_ARGS 276
+#define LIST_COMMENT 277
+#define ID_LIST_SINGLE 278
+#define IF_KEYWORD 279
+#define ELSE_KEYWORD 280
+#define ENDIF_KEYWORD 281
+#define KEYWORD 282
+#define RULE 283
+
+
+
+
+#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
+typedef int YYSTYPE;
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
+
+extern YYSTYPE yylval;
+
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/autotoolsparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.h (revision 1522570)
@@ -0,0 +1,101 @@
+/* A Bison parser, made by GNU Bison 2.1. */
+
+/* Skeleton parser for Yacc-like parsing with Bison,
+ Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
+
+ 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, 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., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA. */
+
+/* As a special exception, when this file is copied by Bison into a
+ Bison output file, you may use that output file without restriction.
+ This special exception was added by the Free Software Foundation
+ in version 1.24 of Bison. */
+
+/* Tokens. */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+ /* Put the tokens into the symbol table, so that GDB and other debuggers
+ know about them. */
+ enum yytokentype {
+ ID_SIMPLE = 258,
+ ID_LIST = 259,
+ LBRACE = 260,
+ EQ = 261,
+ PLUSEQ = 262,
+ MINUSQE = 263,
+ STAREQ = 264,
+ TILDEEQ = 265,
+ RBRACE = 266,
+ COLON = 267,
+ NUMSIGN = 268,
+ NEWLINE = 269,
+ NUMBER = 270,
+ COMMENT = 271,
+ CONT = 272,
+ DOT = 273,
+ RCURLY = 274,
+ LCURLY = 275,
+ ID_ARGS = 276,
+ LIST_COMMENT = 277,
+ ID_LIST_SINGLE = 278,
+ IF_KEYWORD = 279,
+ ELSE_KEYWORD = 280,
+ ENDIF_KEYWORD = 281,
+ KEYWORD = 282,
+ RULE = 283
+ };
+#endif
+/* Tokens. */
+#define ID_SIMPLE 258
+#define ID_LIST 259
+#define LBRACE 260
+#define EQ 261
+#define PLUSEQ 262
+#define MINUSQE 263
+#define STAREQ 264
+#define TILDEEQ 265
+#define RBRACE 266
+#define COLON 267
+#define NUMSIGN 268
+#define NEWLINE 269
+#define NUMBER 270
+#define COMMENT 271
+#define CONT 272
+#define DOT 273
+#define RCURLY 274
+#define LCURLY 275
+#define ID_ARGS 276
+#define LIST_COMMENT 277
+#define ID_LIST_SINGLE 278
+#define IF_KEYWORD 279
+#define ELSE_KEYWORD 280
+#define ENDIF_KEYWORD 281
+#define KEYWORD 282
+#define RULE 283
+
+
+
+
+#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
+typedef int YYSTYPE;
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
+
+extern YYSTYPE yylval;
+
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake/automakeparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/automake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/automake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/automake (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/automake
___________________________________________________________________
Added: svn:ignore
## -0,0 +1,4 ##
+.libs
+Makefile
+Makefile.in
+*.moc
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop (revision 1522570)
@@ -0,0 +1,84 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=This plugin integrates Bazaar
+Comment[bs]=Ovaj dodatak integrira Bazaar
+Comment[ca]=Aquest connector integra Bazaar
+Comment[ca@valencia]=Aquest connector integra Bazaar
+Comment[de]=Dieses Modul integriert Bazaar
+Comment[en_GB]=This plugin integrates Bazaar
+Comment[es]=Este complemento integra Bazaar
+Comment[et]=See plugin lõimib Bazaari
+Comment[fr]=Ce module externe intègre Bazaar
+Comment[gl]=Complemento de integración con Bazaar.
+Comment[it]=Questa estensione integra Bazaar
+Comment[nl]=Deze plugin integreert Bazaar
+Comment[pl]=Wtyczka ta integruje Bazaar
+Comment[pt]=Este 'plugin' integra o Bazaar
+Comment[pt_BR]=Este plugin integra o Bazaar
+Comment[sv]=Insticksprogrammet integrerar Bazaar
+Comment[uk]=За допомогою цього додатка можна інтегрувати Bazaar
+Comment[x-test]=xxThis plugin integrates Bazaarxx
+Name=Bazaar Support
+Name[bs]=Bazaar podrška
+Name[ca]=Implementació de Bazaar
+Name[ca@valencia]=Implementació de Bazaar
+Name[cs]=Podpora Bazaar
+Name[de]=Bazaar-Unterstützung
+Name[en_GB]=Bazaar Support
+Name[es]=Implementación de Bazaar
+Name[et]=Bazaari toetus
+Name[fr]=Gestion de Bazaar
+Name[ga]=Tacaíocht Bazaar
+Name[gl]=Compatibilidade con Bazaar
+Name[hu]=Bazaar támogatás
+Name[it]=Supporto per Bazaar
+Name[ja]=Bazaar サポート
+Name[ms]=Penyokong Bazaar
+Name[nds]=Bazaar-Ünnerstütten
+Name[nl]=Ondersteuning van Bazaar
+Name[pa]=ਬਜ਼ਾਰ ਸਹਿਯੋਗ
+Name[pl]=Obsługa Bazaar
+Name[pt]=Suporte para Bazaar
+Name[pt_BR]=Suporte a Bazaar
+Name[sk]=Podpora Bazaar
+Name[sv]=Bazaar-stöd
+Name[tr]=Bazaar Desteği
+Name[ug]=Bazaar قوللىشى
+Name[uk]=Підтримка Bazaar
+Name[x-test]=xxBazaar Supportxx
+GenericName=Bazaar frontend
+GenericName[bs]=Bazaar prikaz
+GenericName[ca]=Frontal de Bazaar
+GenericName[ca@valencia]=Frontal de Bazaar
+GenericName[de]=Bazaar-Oberfläche
+GenericName[en_GB]=Bazaar frontend
+GenericName[es]=Interfaz Bazaar
+GenericName[et]=Bazaari kasutajaliides
+GenericName[fr]=Interface pour Bazaar
+GenericName[gl]=Interface para Bazaar
+GenericName[hu]=Bazaar előtétprogram
+GenericName[it]=Interfaccia di Bazaar
+GenericName[ja]=Bazaar フロントエンド
+GenericName[ms]=Mukadepan Bazaar
+GenericName[nds]=Bazaar-Böversiet
+GenericName[nl]=Frontend voor Bazaar
+GenericName[pa]=ਬਜ਼ਾਰ ਫਰੰਟਐਂਡ
+GenericName[pl]=Interfejs do Bazaar
+GenericName[pt]=Interface para o Bazaar
+GenericName[pt_BR]=Interface do Bazaar
+GenericName[sv]=Bazaar-gränssnitt
+GenericName[tr]=Bazaar Önucu
+GenericName[uk]=Графічна оболонка для Bazaar
+GenericName[x-test]=xxBazaar frontendxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevbzr
+X-KDE-PluginInfo-Name=kdevbzr
+X-KDE-PluginInfo-Author=Evgeniy Ivanov
+X-KDE-PluginInfo-Email=powerfox@kde.ru
+X-KDE-PluginInfo-Version=0.5
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=7
+X-KDevelop-Category=Global
+X-KDevelop-Mode=NoGUI
+X-KDevelop-Interfaces=org.kdevelop.IBasicVersionControl, org.kdevelop.IDistributedVersionControl
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp (revision 1522570)
@@ -0,0 +1,378 @@
+/***************************************************************************
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "bzrplugin.h"
+
+#include <KPluginFactory>
+#include <KPluginLoader>
+#include <KAboutData>
+#include <klocalizedstring.h>
+
+
+#include <QtCore/QDir>
+#include <QtCore/QDateTime>
+#include <QtCore/QFileInfo>
+
+
+#include <interfaces/icore.h>
+
+#include <vcs/dvcs/dvcsjob.h>
+
+//#include "bzrexecutor.h"
+
+#include <memory>
+
+K_PLUGIN_FACTORY(KDevBzrFactory, registerPlugin<BzrPlugin>(); )
+K_EXPORT_PLUGIN(KDevBzrFactory(KAboutData("kdevbzr","kdevbazaar", ki18n("Bazaar Plugin"), "0.1", ki18n("Bazaar version control system support"), KAboutData::License_GPL, ki18n("Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru>") ) ) )
+
+BzrPlugin::BzrPlugin( QObject *parent, const QVariantList & )
+ : DistributedVersionControlPlugin(parent, KDevBzrFactory::componentData())
+{
+ KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
+ KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )
+
+ core()->uiController()->addToolView(i18n("Bazaar"), DistributedVersionControlPlugin::dvcsViewFactory());
+
+ setXMLFile("kdevbzr.rc");
+
+// m_exec = new BzrExecutor(this);
+}
+
+BzrPlugin::~BzrPlugin()
+{
+// delete m_exec;
+}
+
+QString BzrPlugin::name() const
+{
+ return QLatin1String("Bazaar");
+}
+
+
+KDevelop::VcsJob* BzrPlugin::add(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
+{
+ Q_UNUSED(recursion)
+ if (localLocations.empty())
+ return NULL;
+
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, localLocations.front().path()) ) {
+ *job << "bzr";
+ *job << "add";
+ addFileList(job, localLocations);
+
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::remove(const KUrl::List& files)
+{
+ if (files.empty())
+ return NULL;
+
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, files.front().path()) ) {
+ *job << "bzr";
+ *job << "rm";
+ addFileList(job, files);
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::status(const KUrl::List& localLocations,
+ KDevelop::IBasicVersionControl::RecursionMode recursion)
+{
+ Q_UNUSED(recursion)
+ //it's a hack!!! See VcsCommitDialog::setCommitCandidates and the usage of DVcsJob/IDVCSexecutor
+ //We need results just in status, so we set them here before execution in VcsCommitDialog::setCommitCandidates
+ QString repo = localLocations[0].toLocalFile();
+ QList<QVariant> statuses;
+ qDebug("BzrPlugin::status");
+ statuses << getCachedFiles(repo)
+ << getModifiedFiles(repo)
+ << getOtherFiles(repo);
+ DVcsJob * noOp = empty_cmd();
+ noOp->setResults(QVariant(statuses));
+ return noOp;
+}
+
+KDevelop::VcsJob* BzrPlugin::commit(const QString& message,
+ const KUrl::List& localLocations,
+ KDevelop::IBasicVersionControl::RecursionMode recursion)
+{
+ Q_UNUSED(recursion)
+
+ if (localLocations.empty() || message.isEmpty())
+ return NULL;
+
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, localLocations.front().path()) ) {
+ *job << "bzr";
+ *job << "commit";
+ *job << "-m";
+ *job << message;
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::log(const KUrl& localLocation,
+ const KDevelop::VcsRevision& rev,
+ unsigned long limit)
+{
+ Q_UNUSED(rev)
+ Q_UNUSED(limit)
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, localLocation.path()) ) {
+ *job << "bzr";
+ *job << "log";
+ addFileList(job, localLocation);
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::init(const KUrl &directory)
+{
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, directory.toLocalFile(), BzrPlugin::Init) ) {
+ *job << "bzr";
+ *job << "init";
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::clone(const KDevelop::VcsLocation & localOrRepoLocationSrc, const KUrl& localRepositoryRoot)
+{
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, localRepositoryRoot.toLocalFile(), BzrPlugin::Init) ) {
+ *job << "bzr";
+ *job << "clone";
+ *job << localOrRepoLocationSrc.localUrl().pathOrUrl();
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+KDevelop::VcsJob* BzrPlugin::reset(const KUrl& repository, const QStringList &args, const KUrl::List& files)
+{
+ if (files.empty())
+ return NULL;
+
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, repository.path()) ) {
+ *job << "bzr";
+ *job << "revert";
+ //Empty branch has 'something' so it breaks the command
+ if (!args.isEmpty())
+ *job << args;
+ addFileList(job, files);
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+void BzrPlugin::parseLogOutput(const DVcsJob * job, QList<DVcsEvent>& commits) const
+{
+// static QRegExp rx_sep( "[-=]+" );
+// static QRegExp rx_date( "date:\\s+([^;]*);\\s+author:\\s+([^;]*).*" );
+
+ QStringList lines = job->output().split('\n', QString::SkipEmptyParts);
+
+ QString commitLog;
+
+ for (int i=0; i<lines.count(); ++i) {
+ ++i; // skip line of --------------s
+ QString rev = lines[i++]; // revno
+ QString author = lines[i++]; // committer
+ ++i; // branch nick
+ QString date = lines[i++]; // timestamp
+ ++i; // the word 'message'
+ QString desc = lines[i];
+
+ DVcsEvent commit;
+ commit.setCommit(rev);
+ commit.setAuthor(author);
+ commit.setDate(date);
+ if (!desc.startsWith("--")) {
+ commit.setLog(desc); // only put on message if there was one
+ } else {
+ --i; // rewind by one if the message was blank
+ }
+
+ commits.push_front(commit);
+ }
+}
+
+DVcsJob* BzrPlugin::switchBranch(const QString &repository, const QString &branch)
+{
+ ///TODO Check if the branch exists. or send only existed branch names here!
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "merge";
+ *job << repository;
+ *job << branch;
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVcsJob* BzrPlugin::branch(const QString &repository, const QString &basebranch, const QString &branch, const QStringList &args)
+{
+ Q_UNUSED(basebranch)
+
+ DVcsJob* job = new DVcsJob(this);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "branch";
+ if (!args.isEmpty())
+ *job << args;
+ *job << branch;
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+QString BzrPlugin::curBranch(const QString &repository)
+{
+ std::auto_ptr<DVcsJob> job(new DVcsJob(this));
+
+ if (!prepareJob(job.get(), repository)) {
+ return NULL;
+ }
+ *job << "bzr" << "nick";
+
+ if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
+ return QString();
+
+ return job->output();
+}
+
+QStringList BzrPlugin::branches(const QString &repository)
+{
+ QStringList toReturn;
+
+ QString currName = curBranch(repository);
+ if (!currName.isEmpty()) {
+ toReturn.push_back(currName);
+ }
+ return toReturn;
+
+}
+
+bool BzrPlugin::isValidDirectory(const KUrl & directory)
+{
+ static const QString bzrDir(".bzr");
+ const QString initialPath(directory.toLocalFile());
+ const QFileInfo finfo(initialPath);
+ QDir dir;
+ if (finfo.isFile()) {
+ dir = finfo.absoluteDir();
+ } else {
+ dir = QDir(initialPath);
+ dir.makeAbsolute();
+ }
+
+ while (!dir.cd(bzrDir) && dir.cdUp()) ;
+
+ return bzrDir == dir.dirName();
+}
+
+
+QList<DVcsEvent> BzrPlugin::getAllCommits(const QString &repo)
+{
+ std::auto_ptr<DVcsJob> job(new DVcsJob(this));
+ job->setAutoDelete(false);
+
+ if (!prepareJob(job.get(), repo)) {
+ return QList<DVcsEvent>();
+ }
+
+ *job << "bzr" << "log";
+
+ if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
+ return QList<DVcsEvent>();
+
+ QList<DVcsEvent> commits;
+
+ parseLogOutput(job.get(), commits);
+
+ return commits;
+}
+
+bool BzrPlugin::isVersionControlled(const KUrl & url)
+{
+ const QFileInfo fsObject(url.path());
+
+ if (!fsObject.isFile()) {
+ return isValidDirectory(url);
+ }
+
+ // Clean, Added, Modified. Escape possible files starting with "-"
+ const QString absolutePath = fsObject.absolutePath();
+ const QStringList filesInDir = getLsFiles(absolutePath);
+
+ return !filesInDir.empty();
+}
+
+QStringList BzrPlugin::getLsFiles(const QString &directory, const QStringList &args)
+{
+ std::auto_ptr<DVcsJob> job(new DVcsJob(this));
+
+ if (!prepareJob(job.get(), directory)) {
+ return QStringList();
+ }
+
+ *job << "bzr" << "ls" << "--non-recursive";
+
+ if (!args.isEmpty())
+ *job << args;
+
+ if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
+ return QStringList();
+
+ const QString prefix = directory.endsWith(QDir::separator()) ? directory : directory + QDir::separator();
+ QStringList fileList = job->output().split('\n', QString::SkipEmptyParts);
+ for (QStringList::iterator it = fileList.begin(); it != fileList.end(); ++it) {
+ it->prepend(prefix);
+ }
+ return fileList;
+}
+
+KDevelop::VcsJob* BzrPlugin::log(const KUrl& localLocation,
+ const KDevelop::VcsRevision& rev,
+ const KDevelop::VcsRevision& limit)
+{
+ Q_UNUSED(limit)
+ return log(localLocation, rev, 0);
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,42 @@
+project(bazaar)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${bazaar_SOURCE_DIRECTORY}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+add_definitions(-DKDE_DEFAULT_DEBUG_AREA=9527)
+#add_subdirectory(tests)
+
+########### next target ###############
+
+set(kdevbzr_PART_SRCS
+ bzrplugin.cpp
+# bzrexecutor.cpp
+)
+
+kde4_add_plugin(kdevbzr ${kdevbzr_PART_SRCS})
+
+
+target_link_libraries(kdevbzr
+ ${KDE4_KDEUI_LIBS}
+ kdevplatformutil
+ kdevplatforminterfaces
+ kdevplatformvcs
+ kdevplatformshell
+ kdevplatformproject
+)
+
+install(TARGETS kdevbzr DESTINATION ${PLUGIN_INSTALL_DIR} )
+
+
+########### install files ###############
+install( FILES kdevbzr.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevbzr.rc DESTINATION ${DATA_INSTALL_DIR}/kdevbzr )
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrplugin.h (revision 1522570)
@@ -0,0 +1,97 @@
+/***************************************************************************
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef BZR_PLUGIN_H
+#define BZR_PLUGIN_H
+
+#include <QtCore/QObject>
+
+#include <vcs/interfaces/idistributedversioncontrol.h>
+#include <vcs/interfaces/ibasicversioncontrol.h>
+
+#include <vcs/vcsexport.h>
+#include <vcs/vcsstatusinfo.h>
+#include <vcs/dvcs/dvcsplugin.h>
+
+//class BzrExecutor;
+
+/**
+ * This is the main class of KDevelop's Git plugin.
+ *
+ * It implements the DVCS dependent things not implemented in KDevelop::DistributedVersionControlPlugin
+ * @author Evgeniy Ivanov <powerfox@kde.ru>
+ */
+class BzrPlugin: public KDevelop::DistributedVersionControlPlugin
+{
+ Q_OBJECT
+ Q_INTERFACES(KDevelop::IBasicVersionControl KDevelop::IDistributedVersionControl)
+
+//friend class BzrExecutor;
+
+public:
+ BzrPlugin(QObject *parent, const QVariantList & args = QVariantList() );
+ ~BzrPlugin();
+
+ virtual QString name() const;
+ virtual bool isVersionControlled(const KUrl& localLocation);
+ virtual KDevelop::VcsJob* add(const KUrl::List& localLocations,
+ KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
+ virtual KDevelop::VcsJob* remove(const KUrl::List& localLocations);
+ virtual KDevelop::VcsJob* status(const KUrl::List& localLocations,
+ KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
+
+ virtual KDevelop::VcsJob* commit(const QString& message,
+ const KUrl::List& localLocations,
+ KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
+ virtual KDevelop::VcsJob* log(const KUrl& localLocation,
+ const KDevelop::VcsRevision& rev,
+ const KDevelop::VcsRevision& limit);
+ virtual KDevelop::VcsJob* log(const KUrl& localLocation,
+ const KDevelop::VcsRevision& rev,
+ unsigned long limit);
+ virtual KDevelop::VcsJob* init(const KUrl& localRepositoryRoot);
+ virtual KDevelop::VcsJob* clone(const KDevelop::VcsLocation& localOrRepoLocationSrc,
+ const KUrl& localRepositoryRoot);
+ virtual KDevelop::VcsJob* reset(const KUrl& repository,
+ const QStringList &args, const KUrl::List& files);
+
+ virtual void parseLogOutput(const DVcsJob * job,
+ QList<DVcsEvent>& revisions) const;
+
+ virtual DVcsJob* switchBranch(const QString &repository,
+ const QString &branch);
+ virtual DVcsJob* branch(const QString &repository,
+ const QString &basebranch = QString(),
+ const QString &branch = QString(),
+ const QStringList &args = QStringList());
+
+ virtual QString curBranch(const QString &repository);
+ virtual QStringList branches(const QString &repository);
+
+ virtual bool isValidDirectory(const KUrl &dirPath);
+ virtual QList<DVcsEvent> getAllCommits(const QString &repo);
+ QStringList getLsFiles(const QString &directory, const QStringList &args = QStringList());
+//
+//private:
+// BzrExecutor * m_exec;
+
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp (revision 1522570)
@@ -0,0 +1,181 @@
+/***************************************************************************
+ * This file was partly taken from KDevelop's cvs plugin *
+ * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
+ * *
+ * Adapted for Bazaar *
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "bzrexecutor.h"
+
+#include <QFileInfo>
+#include <QDir>
+#include <QString>
+#include <QDateTime>
+#include <KLocale>
+#include <KUrl>
+#include <KMessageBox>
+#include <kshell.h>
+#include <KDebug>
+
+#include <vcs/vcsexport.h>
+#include <vcs/vcsstatusinfo.h>
+#include <vcs/dvcs/dvcsplugin.h>
+
+#include <vcs/dvcs/dvcsjob.h>
+#include <interfaces/iplugin.h>
+
+BzrExecutor::BzrExecutor(KDevelop::IPlugin* parent)
+ : QObject(parent), vcsplugin(parent)
+{
+}
+
+BzrExecutor::~BzrExecutor()
+{
+}
+
+//TODO: write tests for this method!
+//maybe func()const?
+bool BzrExecutor::isValidDirectory(const KUrl & dirPath)
+{
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (job)
+ {
+ QString path = dirPath.path();
+ QFileInfo fsObject(path);
+ if (fsObject.isFile())
+ path = fsObject.path();
+
+ job->clear();
+ job->setDirectory(path);
+ *job << "bzr";
+ *job << "root";
+ job->exec();
+ if (job->status() == KDevelop::VcsJob::JobSucceeded)
+ {
+ kDebug() << "Dir:" << path << " is inside work tree of bzr" ;
+ return true;
+ }
+ }
+ kDebug() << "Dir:" << dirPath.path() << " is not inside work tree of bzr" ;
+ return false;
+}
+
+QString BzrExecutor::name() const
+{
+ return QLatin1String("Bazaar");
+}
+
+DVCSjob* BzrExecutor::init(const KUrl &directory)
+{
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, directory.toLocalFile(), BzrExecutor::Init) ) {
+ *job << "bzr";
+ *job << "init";
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVCSjob* BzrExecutor::clone(const KUrl &repository, const KUrl directory)
+{
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, directory.toLocalFile(), BzrExecutor::Init) ) {
+ *job << "bzr";
+ *job << "clone";
+ *job << repository.path();
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVCSjob* BzrExecutor::add(const QString& repository, const KUrl::List &files)
+{
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "add";
+ addFileList(job, files);
+
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+//TODO: bzr doesn't like empty messages, but "KDevelop didn't provide any message, it may be a bug" looks ugly...
+//If no files specified then commit already added files
+DVCSjob* BzrExecutor::commit(const QString& repository,
+ const QString &message, /*= "KDevelop didn't provide any message, it may be a bug"*/
+ const KUrl::List &files /*= QStringList("-a")*/)
+{
+ Q_UNUSED(files)
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "commit";
+ *job << "-m";
+ *job << KShell::quoteArg( message );
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVCSjob* BzrExecutor::remove(const QString& repository, const KUrl::List &files)
+{
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "rm";
+ addFileList(job, files);
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVCSjob* BzrExecutor::status(const QString & repository, const KUrl::List & files, bool recursive, bool taginfo)
+{
+ Q_UNUSED(recursive)
+ Q_UNUSED(taginfo)
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ if (prepareJob(job, repository) ) {
+ *job << "bzr";
+ *job << "status";
+ addFileList(job, files);
+
+ return job;
+ }
+ if (job) delete job;
+ return NULL;
+}
+
+DVCSjob* BzrExecutor::empty_cmd() const
+{
+ ///TODO: maybe just "" command?
+ DVCSjob* job = new DVCSjob(vcsplugin);
+ *job << "echo";
+ *job << "-n";
+ return job;
+}
+
+// #include "bzrexecutor.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevbazaar.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp (revision 1522570)
@@ -0,0 +1,225 @@
+/***************************************************************************
+ * This file was partly taken from KDevelop's cvs plugin *
+ * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
+ * *
+ * Adapted for Bazaar *
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "initTest.h"
+
+#include <qtest_kde.h>
+#include <QtTest/QtTest>
+
+#include <KUrl>
+#include <KDebug>
+#include <kio/netaccess.h>
+
+#include <interfaces/iplugincontroller.h>
+#include <interfaces/iplugin.h>
+
+#include <vcs/interfaces/ibasicversioncontrol.h>
+
+#include <vcs/dvcs/dvcsjob.h>
+#include "../bzrexecutor.h"
+
+const QString tempDir = QDir::tempPath();
+const QString bzrTest_BaseDir(tempDir + "/kdevBazaar_testdir/");
+const QString bzrTest_BaseDir2(tempDir + "/kdevBazaar_testdir2/");
+const QString bzrRepo(bzrTest_BaseDir + ".bzr");
+const QString bzrTest_FileName("testfile");
+
+
+//TODO: bugs, this test didn't notice:
+//* git commit home/... wasn't notice
+// test for isValidDirectory is required!!!
+
+void BzrInitTest::initTestCase()
+{
+ m_proxy = new BzrExecutor;
+
+ // If the basedir for this cvs test exists from a
+ // previous run; remove it...
+ if ( QFileInfo(bzrTest_BaseDir).exists() )
+ KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0);
+ if ( QFileInfo(bzrTest_BaseDir2).exists() )
+ KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0);
+
+ // Now create the basic directory structure
+ QDir tmpdir(tempDir);
+ tmpdir.mkdir(bzrTest_BaseDir);
+ tmpdir.mkdir(bzrTest_BaseDir2);
+}
+
+void BzrInitTest::cleanupTestCase()
+{
+ delete m_proxy;
+
+ if ( QFileInfo(bzrTest_BaseDir).exists() )
+ KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0);
+ if ( QFileInfo(bzrTest_BaseDir2).exists() )
+ KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0);
+}
+
+void BzrInitTest::repoInit()
+{
+ // make job that creates the local repository
+ DVCSjob* j = m_proxy->init(KUrl(bzrTest_BaseDir));
+ QVERIFY( j );
+
+ // try to start the job
+ QVERIFY( j->exec() );
+
+ //check if the CVSROOT directory in the new local repository exists now
+ QVERIFY( QFileInfo(QString(bzrRepo)).exists() );
+}
+
+void BzrInitTest::addFiles()
+{
+ //we start it after repoInit, so we still have empty bazaar repo
+ //First let's create a file
+ QFile f(bzrTest_BaseDir + bzrTest_FileName);
+ if(f.open(QIODevice::WriteOnly)) {
+ QTextStream input( &f );
+ input << "HELLO WORLD";
+ }
+ f.flush();
+
+ DVCSjob* j = m_proxy->add(QString(bzrTest_BaseDir), KUrl::List(QStringList(bzrTest_FileName)));
+ QVERIFY( j );
+
+ // try to start the job
+ QVERIFY( j->exec() );
+
+//TODO: Bazaar just change checkout/dirstate created by bzr init
+// //TODO: maybe other method should be used
+// QString testfile(BZR_REPO"/dirstate");
+// QVERIFY( QFileInfo(testfile).exists() );
+}
+
+void BzrInitTest::commitFiles()
+{
+ //we start it after addFiles, so we just have to commit
+ DVCSjob* j = m_proxy->commit(QString(bzrTest_BaseDir), QString("KDevelop's Test commit"),
+ KUrl::List(QStringList(bzrTest_FileName)));
+ QVERIFY( j );
+
+ // try to start the job
+ QVERIFY( j->exec() );
+
+ //since we commited the file to the "pure" repository, .bzr/store/data/BZR_TESTFILE_NAME.i should exist
+ //TODO: maybe other method should be used
+ QString headRefName(bzrRepo + "/repository/indices/");
+ QVERIFY( QFileInfo(headRefName).exists() );
+
+ QString firstCommit;
+ QFile headRef(headRefName);
+ if(headRef.open(QIODevice::ReadOnly)) {
+ QTextStream output( &headRef );
+ output>>firstCommit;
+ }
+ headRef.flush();
+ headRef.close();
+
+// QVERIFY(firstCommit!="");
+
+ //let's try to change the file and test "bazaar commit -A"
+ QFile f(bzrTest_BaseDir + bzrTest_FileName);
+ if(f.open(QIODevice::WriteOnly)) {
+ QTextStream input( &f );
+ input << "Just another HELLO WORLD";
+ }
+ f.flush();
+
+ //Since KJob uses delete later we don't care about deleting pld *j
+ j = m_proxy->commit(QString(bzrTest_BaseDir), QString("KDevelop's Test commit2"));
+ QVERIFY( j );
+
+ // try to start the job
+ QVERIFY( j->exec() );
+
+// QString secondCommit;
+// if(headRef.open(QIODevice::ReadOnly)) {
+// QTextStream output( &headRef );
+// output>>secondCommit;
+// }
+// headRef.flush();
+// headRef.close();
+//
+// QVERIFY(secondCommit!="");
+// QVERIFY(firstCommit != secondCommit);
+}
+
+void BzrInitTest::cloneRepository()
+{
+ // make job that clones the local repository, created in the previous test
+ DVCSjob* j = m_proxy->clone(KUrl(bzrTest_BaseDir), KUrl(bzrTest_BaseDir2));
+ QVERIFY( j );
+
+ // try to start the job
+ QVERIFY( j->exec() );
+
+ //check if the .bzr directory in the new local repository exists now
+ QVERIFY( QFileInfo(QString(bzrTest_BaseDir2 + "kdevBazaar_testdir/.bzr/")).exists() );
+}
+
+void BzrInitTest::testInitAndCommit()
+{
+ repoInit();
+ addFiles();
+ commitFiles();
+ cloneRepository();
+}
+
+using namespace KDevelop;
+
+void BzrInitTest::testPlugin()
+{
+// Core::initialize();
+// Core *core;
+// core->initialize();
+// IPluginController* controller = core->pluginController();
+
+// IPlugin* bzrPlugin = controller->loadPlugin(QString("kdevbzr"));
+// QVERIFY(bzrPlugin);
+//
+// KPluginInfo bzrInfo = controller->pluginInfo(bzrPlugin);
+// QVERIFY(bzrInfo.isValid());
+//
+// //TODO: compare name() etc
+// kDebug()<<"name: "<<bzrInfo.name()<<" pluginName: "<<bzrInfo.pluginName();
+//
+// IBasicVersionControl* iface = bzrPlugin->extension<IBasicVersionControl>();
+// QVERIFY(iface);
+}
+
+void BzrInitTest::removeTempDirs()
+{
+ if (QFileInfo(bzrTest_BaseDir).exists() )
+ if (!KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0) )
+ qDebug() << "KIO::NetAccess::del(" << bzrTest_BaseDir << ") returned false";
+ if (QFileInfo(bzrTest_BaseDir2).exists() )
+ if (!KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0) )
+ qDebug() << "KIO::NetAccess::del(" << bzrTest_BaseDir2 << ") returned false";
+}
+
+QTEST_KDEMAIN(BzrInitTest, GUI)
+
+
+#include "initTest.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/initTest.h (revision 1522570)
@@ -0,0 +1,53 @@
+/***************************************************************************
+ * This file was partly taken from KDevelop's cvs plugin *
+ * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
+ * *
+ * Adapted for Bazaar *
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef GIT_INIT_H
+#define GIT_INIT_H
+
+#include <QtCore/QObject>
+
+class BzrExecutor;
+
+class BzrInitTest: public QObject
+{
+ Q_OBJECT
+
+ private:
+ void repoInit();
+ void addFiles();
+ void commitFiles();
+ void cloneRepository();
+
+ private slots:
+ void initTestCase();
+ void testInitAndCommit();
+ void testPlugin();
+ void cleanupTestCase();
+
+ private:
+ BzrExecutor* m_proxy;
+ void removeTempDirs();
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,31 @@
+# Due to the use of system() and some unix-style paths this test will only run
+# under Linux. (Maybe this can be fixed later)
+#
+# Moreover, I'm not sure if there is a cvs commandline client for windows
+# (need to check this out ...)
+
+if (UNIX)
+
+# Running the test only makes sense if the git command line client
+# is present. So check for it before adding the test...
+FIND_PROGRAM(BZR NAMES bzr
+ PATHS
+ /bin
+ /usr/bin
+ /usr/local/bin
+)
+
+if (BZR)
+
+ set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+ set(bzrInitTest_SRCS initTest.cpp ${CMAKE_SOURCE_DIR}/vcs/dvcs/dvcsjob.cpp ../bzrexecutor.cpp)
+ kde4_add_unit_test(kdevbzr-test ${bzrInitTest_SRCS})
+ target_link_libraries(kdevbzr-test
+ ${QT_QTTEST_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ kdevplatformutil
+ kdevplatformvcs
+ )
+endif (BZR)
+
+endif (UNIX)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/bzrexecutor.h (revision 1522570)
@@ -0,0 +1,92 @@
+/***************************************************************************
+ * This file was partly taken from KDevelop's cvs plugin *
+ * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
+ * *
+ * Adapted for Bazaar *
+ * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 2 of *
+ * the License or (at your option) version 3 or any later version *
+ * accepted by the membership of KDE e.V. (or its successor approved *
+ * by the membership of KDE e.V.), which shall act as a proxy *
+ * defined in Section 14 of version 3 of the license. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef BZR_EXECUTOR_H
+#define BZR_EXECUTOR_H
+
+#include <KUrl>
+#include <KJob>
+#include <QStringList>
+
+#include <vcs/dvcs/idvcsexecutor.h>
+#include <vcs/vcsrevision.h>
+
+class DVCSjob;
+
+namespace KDevelop
+{
+ class IPlugin;
+}
+
+/**
+ * This proxy acts as a single point of entry for most of the common hg commands.
+ * It is very easy to use, as the caller does not have to deal which the DVCSjob class directly.
+ * All the command line generation and job handling is done internally. The caller gets a DVCSjob
+ * object returned from the proxy and can then call it's start() method.
+ *
+ * Here is and example of how to user the proxy:
+ * @code
+ * DVCSjob* job = proxy->editors( repo, urls );
+ * if ( job ) {
+ * connect(job, SIGNAL( result(KJob*) ),
+ * this, SIGNAL( jobFinished(KJob*) ));
+ * job->start();
+ * }
+ * @endcode
+ *
+ * @note All actions that take a KUrl::List also need an url to the repository which
+ * must be a common base directory to all files from the KUrl::List.
+ * Actions that just take a single KUrl don't need a repository, the hg command will be
+ * called directly in the directory of the given file
+ *
+ * @author Robert Gruber <rgruber@users.sourceforge.net>
+ * @author Evgeniy Ivanov <powerfox@kde.ru>
+ */
+class BzrExecutor : public QObject, public KDevelop::IDVCSexecutor
+{
+ Q_OBJECT
+public:
+ explicit BzrExecutor(KDevelop::IPlugin* parent = 0);
+ ~BzrExecutor();
+
+ bool isValidDirectory(const KUrl &dirPath);
+ QString name() const;
+
+ DVCSjob* init(const KUrl & directory);
+ DVCSjob* clone(const KUrl &directory, const KUrl repository);
+ DVCSjob* add(const QString& repository, const KUrl::List &files);
+ DVCSjob* commit(const QString& repository,
+ const QString& message = "KDevelop did not provide any message, it may be a bug",
+ const KUrl::List& files = QStringList());
+ DVCSjob* remove(const QString& repository, const KUrl::List& files);
+ DVCSjob* status(const QString & repo, const KUrl::List & files,
+ bool recursive=false, bool taginfo=false);
+ DVCSjob* empty_cmd() const;
+
+private:
+ KDevelop::IPlugin* vcsplugin;
+
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/bazaar/kdevbzr.rc (revision 1522570)
@@ -0,0 +1,10 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevBazaar" version="1">
+
+ <Menu name="dvcs_popup">
+ <text context="@title:menu">Bazaar</text>
+ <Action name="dvcs_init" />
+ <Action name="dvcs_clone" />
+ </Menu>
+
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.desktop (revision 1522570)
@@ -0,0 +1,87 @@
+[Desktop Entry]
+Type=Service
+Icon=kdevelop
+Exec=blubb
+Comment=Check test runner
+Comment[bs]=Provjeri test runner(pokreće neku akciju)
+Comment[ca]=Comprovador de l'executor de proves
+Comment[ca@valencia]=Comprovador de l'executor de proves
+Comment[de]=Check-Test ausführen
+Comment[el]=Εκτελεστής εκτελεστή ελέγχου
+Comment[en_GB]=Check test runner
+Comment[es]=Comprobar lanzador de pruebas
+Comment[et]=Kontrolltesti käivitaja
+Comment[fr]=Lanceur de tests de vérification
+Comment[ga]=Seiceáil an feidhmitheoir tástála
+Comment[gl]=Executor de probas de comprobación
+Comment[it]=Controlla l'esecutore test
+Comment[ms]=Periksa pelari ujian
+Comment[nds]=Prööv-Testdreger
+Comment[nl]=Test controles uitvoeren
+Comment[pa]=ਟੈਸਟ ਰਨਰ ਚੈੱਕ ਕਰੋ
+Comment[pl]=Uruchamianie testu sprawdzającego
+Comment[pt]=Verificar a execução dos testes
+Comment[pt_BR]=Verificar a execução dos testes
+Comment[sv]=Kör kontrolltest
+Comment[tr]=Denetim sınaması çalıştırıcı
+Comment[uk]=Засіб запуску перевірки Check
+Comment[x-test]=xxCheck test runnerxx
+Name=Check runner
+Name[bs]=Provjeri runner(pokreće neku akciju)
+Name[ca]=Comprova executor
+Name[ca@valencia]=Comprova executor
+Name[de]=Check ausführen
+Name[el]=Έλεγχος εκτελεστή
+Name[en_GB]=Check runner
+Name[es]=Comprobar lanzador
+Name[et]=Kontrolli käivitaja
+Name[fr]=Lanceur de vérification
+Name[ga]=Seiceáil an feidhmitheoir
+Name[gl]=Executor de probas de comprobación
+Name[it]=Esecutore controlli
+Name[ms]=Periksa pelari
+Name[nds]=Pröövdreger
+Name[nl]=Controles uitvoeren
+Name[pa]=ਰਨਰ ਚੈੱਕ
+Name[pl]=Uruchamianie sprawdzania
+Name[pt]=Verificar a execução
+Name[pt_BR]=Verificar a execução
+Name[sv]=Kör kontroll
+Name[tr]=Denetim çalıştırıcı
+Name[uk]=Засіб запуску Check
+Name[x-test]=xxCheck runnerxx
+GenericName=Unit test runner
+GenericName[bs]=Jednični test runner(pokreće neku akciju)
+GenericName[ca]=Executor de prova Unit
+GenericName[ca@valencia]=Executor de prova Unit
+GenericName[de]=Unittest ausführen
+GenericName[el]=Εκτελεστής ελέγχου unit
+GenericName[en_GB]=Unit test runner
+GenericName[es]=Lanzador de pruebas unitarias
+GenericName[et]=Unit-testi käivitaja
+GenericName[fr]=Lanceur de test unitaire
+GenericName[ga]=Feidhmitheoir tástála aonad
+GenericName[gl]=Executor de probas unitarias
+GenericName[it]=Esecutore di unit test
+GenericName[ms]=Pelari unit uji
+GenericName[nds]=Unit-Testdreger
+GenericName[nl]=Test-startprogramma voor eenheid
+GenericName[pa]=ਯੂਨਿਟ ਟੈਸਟ ਰਨਰ
+GenericName[pl]=Uruchamianie jednostki testu
+GenericName[pt]=Execução de testes unitários
+GenericName[pt_BR]=Execução de testes unitários
+GenericName[sk]=Spúštač unit testov
+GenericName[sv]=Kör enhetstest
+GenericName[tr]=Birim sınaması çalıştırıcı
+GenericName[uk]=Засіб запуску перевірки модулів
+GenericName[x-test]=xxUnit test runnerxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevcheckview
+X-KDE-PluginInfo-Name=checkview
+X-KDE-PluginInfo-Author=Manuel Breugelmans
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=LGPL
+X-KDevelop-Version=7
+X-KDevelop-Interfaces=org.kdevelop.ITestFramework
+X-KDevelop-Category=Global
+X-KDevelop-Properties=GlobalFileManagement
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,58 @@
+project(check)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${check_SOURCE_DIR}/cmake)
+
+add_subdirectory(tests)
+#
+# TODO install kdevcheck headers
+#
+
+add_definitions(${KDE4_ENABLE_EXCEPTIONS})
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+
+set(TestBuild on)
+if(TestBuild)
+# expose all symbols
+ add_definitions( -fvisibility=default )
+endif(TestBuild)
+
+include_directories(
+ ${XtestPlugin_SOURCE_DIR}
+)
+
+set(kdevcheck_SRCS
+ ../cppunit/testcase.cpp
+ ../cppunit/testcommand.cpp
+ outputparser.cpp
+ testsuite.cpp
+ checkviewdata.cpp
+ testroot.cpp)
+
+qt4_automoc( ${kdevcheck_SRCS} )
+kde4_add_library(kdevcheck SHARED ${kdevcheck_SRCS})
+target_link_libraries(kdevcheck
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${CHECK_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${QT_QTCORE_LIBRARY})
+install(TARGETS kdevcheck ${INSTALL_TARGETS_DEFAULT_ARGS} )
+
+#########################################
+
+set(kdevcheckview_SRCS checkplugin.cpp)
+qt4_automoc(${kdevcheckview_SRCS})
+kde4_add_plugin(kdevcheckview ${kdevcheckview_SRCS})
+target_link_libraries(kdevcheckview
+ kdevcheck
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDE4_KDEUI_LIBS}
+ ${QT_QTCORE_LIBRARY})
+install(TARGETS kdevcheckview DESTINATION ${PLUGIN_INSTALL_DIR})
+
+########### install files ###############
+
+install( FILES kdevcheck.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevcheck.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcheck )
+install( FILES checkwrapper.h check_impl.h check_list.h
+ DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/veritas/ )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,31 @@
+set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+include_directories(
+ ${XtestPlugin_SOURCE_DIR}/check
+ ${XtestPlugin_SOURCE_DIR} # for kasserts.h
+)
+
+add_definitions(${KDE4_ENABLE_EXCEPTIONS})
+
+macro(kdev_add_test test_EXEC)
+ set(test_SRCS ${ARGN})
+ qt4_automoc( ${test_SRCS} )
+ kde4_add_unit_test(check-${test_EXEC} ${test_SRCS})
+ target_link_libraries(check-${test_EXEC}
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTXML_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ kdevcheck)
+endmacro(kdev_add_test)
+
+kdev_add_test(sys-checkrunnertest checkrunnertest.cpp)
+
+add_executable(emptysuite fake_emptysuite.cpp)
+target_link_libraries(emptysuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
+
+add_executable(sunnysuite fake_sunnysuite.cpp)
+target_link_libraries(sunnysuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
+
+add_executable(multisuite fake_multisuite.cpp)
+target_link_libraries(multisuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp (revision 1522570)
@@ -0,0 +1,146 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "checkrunnertest.h"
+
+#include <kasserts.h>
+#include <qtest_kde.h>
+#include "plugins/xtest/cppunit/register.h"
+#include <veritas/runnertesthelper.h>
+#include "testsuite.h"
+#include "testroot.h"
+
+
+using Veritas::RunnerTestHelper;
+using Check::TestSuite;
+using Check::TestRoot;
+using Check::Test::CheckRunnerTest;
+
+void CheckRunnerTest::init()
+{
+ m_runner = new RunnerTestHelper;
+ m_runner->initializeGUI();
+}
+
+void CheckRunnerTest::cleanup()
+{
+ m_runner->cleanupGUI();
+ delete m_runner;
+}
+
+// helper
+Veritas::Test* CheckRunnerTest::fetchRoot(const char* exe)
+{
+ Register<TestRoot, TestSuite> reg;
+ QFileInfo executable(exe);
+ reg.addFromExe(executable);
+ reg.rootItem()->setExecutable(executable);
+ return reg.rootItem();
+}
+
+// command
+void CheckRunnerTest::empty()
+{
+ Veritas::Test* root = fetchRoot("./emptysuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ QStringList runnerItems;
+ runnerItems << "0 my_suite"
+ << "0 0 x"
+ << "1 x";
+ m_runner->verifyTestTree(runnerItems);
+
+ QList<QStringList> results;
+ m_runner->verifyResultItems(results);
+}
+
+QStringList sunnyDayTests()
+{
+ QStringList runnerItems;
+ runnerItems
+ << "0 root_suite"
+ << "0 0 foo_test"
+ << "0 0 0 foo_cmd1"
+ << "0 0 1 foo_cmd2"
+ << "0 0 2 x"
+ << "0 1 bar_test"
+ << "0 1 0 bar_cmd1"
+ << "0 1 1 bar_cmd2"
+ << "0 1 2 x"
+ << "0 2 baz_test"
+ << "0 2 0 baz_cmd1"
+ << "0 2 1 x"
+ << "0 3 x"
+ << "1 x";
+ return runnerItems;
+}
+
+QMap<QString, Veritas::TestState> sunnyDayTestStates()
+{
+ QMap<QString, Veritas::TestState> states;
+ states["root_suite/foo_test/foo_cmd1"] = Veritas::RunSuccess;
+ states["root_suite/foo_test/foo_cmd2"] = Veritas::RunSuccess;
+ states["root_suite/bar_test/bar_cmd1"] = Veritas::RunSuccess;
+ states["root_suite/bar_test/bar_cmd2"] = Veritas::RunError;
+ states["root_suite/baz_test/baz_cmd1"] = Veritas::RunSuccess;
+ return states;
+}
+
+// command
+void CheckRunnerTest::sunnyDay()
+{
+ Veritas::Test* root = fetchRoot("./sunnysuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ m_runner->verifyTestTree(sunnyDayTests());
+ m_runner->verifyTestStates(sunnyDayTestStates(), root);
+ QStringList result;
+ result << "bar_cmd2" << "Assertion '0' failed" << "fake_sunnysuite.cpp" << "53";
+ m_runner->verifyResultItems(QList<QStringList>() << result);
+}
+
+// command
+void CheckRunnerTest::multiSuite()
+{
+ Veritas::Test* root = fetchRoot("./multisuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ QStringList topo;
+ topo << "0 foo"
+ << "0 0 foo_test"
+ << "0 0 0 foo_cmd"
+ << "0 0 1 x"
+ << "1 bar"
+ << "1 0 bar_test"
+ << "1 0 0 bar_cmd"
+ << "1 0 1 x"
+ << "1 1 x"
+ << "2 x";
+ m_runner->verifyTestTree(topo);
+
+ QList<QStringList> results;
+ m_runner->verifyResultItems(results);
+}
+
+#include "checkrunnertest.moc"
+QTEST_KDEMAIN(CheckRunnerTest, GUI)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/checkrunnertest.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CHECK_CHECKRUNNERTEST_H
+#define VERITAS_CHECK_CHECKRUNNERTEST_H
+
+#include <QtTest/QTest>
+
+namespace Veritas { class RunnerTestHelper; class Test; }
+
+namespace Check { namespace Test {
+
+class CheckRunnerTest : public QObject
+{
+Q_OBJECT
+
+private slots:
+ void init();
+ void cleanup();
+
+ void empty();
+ void sunnyDay();
+ void multiSuite();
+
+private:
+ Veritas::Test* fetchRoot(const char* exe);
+
+private:
+ Veritas::RunnerTestHelper* m_runner;
+};
+
+}}
+
+#endif // VERITAS_CHECK_CHECKRUNNERTEST
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp (revision 1522570)
@@ -0,0 +1,87 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <checkwrapper.h>
+#include <unistd.h>
+
+// "0 root_suite"
+// "0 0 foo_test"
+// "0 0 0 foo_cmd1"
+// "0 0 1 foo_cmd2"
+// "0 0 2 x"
+// "0 1 bar_test"
+// "0 1 0 bar_cmd1"
+// "0 1 1 bar_cmd2"
+// "0 1 2 x"
+// "0 2 baz_test"
+// "0 2 0 baz_cmd1"
+// "0 2 1 x"
+// "0 3 x"
+// "1 x"
+
+START_TEST( foo_cmd1 )
+{}
+END_TEST
+
+START_TEST( foo_cmd2 )
+{}
+END_TEST
+
+START_TEST( bar_cmd1 )
+{}
+END_TEST
+
+START_TEST( bar_cmd2 )
+{
+ fail_unless(0);
+}
+END_TEST
+
+START_TEST( baz_cmd1 )
+{
+ usleep(50000);
+}
+END_TEST
+
+Suite* suite(void)
+{
+ Suite *s = suite_create("root_suite");
+
+ /* foo test case */
+ TCase *tc_foo = tcase_create("foo_test");
+ tcase_add_test(tc_foo, foo_cmd1);
+ tcase_add_test(tc_foo, foo_cmd2);
+ suite_add_tcase(s, tc_foo);
+
+ /* bar test case */
+ TCase *tc_bar = tcase_create("bar_test");
+ tcase_add_test(tc_bar, bar_cmd1);
+ tcase_add_test(tc_bar, bar_cmd2);
+ suite_add_tcase(s, tc_bar);
+
+ /* baz test case */
+ TCase *tc_baz = tcase_create("baz_test");
+ tcase_add_test(tc_baz, baz_cmd1);
+ suite_add_tcase(s, tc_baz);
+
+ return s;
+}
+
+CHECK_VERITAS_MAIN_( suite() )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp (revision 1522570)
@@ -0,0 +1,23 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <checkwrapper.h>
+
+CHECK_VERITAS_MAIN_( suite_create("my_suite") )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp (revision 1522570)
@@ -0,0 +1,62 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <checkwrapper.h>
+#include <unistd.h>
+
+// "0 foo"
+// "0 0 foo_test"
+// "0 0 0 foo_cmd"
+// "0 0 1 x"
+// "0 bar"
+// "1 0 bar_test"
+// "1 0 0 bar_cmd"
+// "1 1 1 x"
+// "1 1 x"
+// "2 x"
+
+START_TEST( foo_cmd )
+{}
+END_TEST
+
+START_TEST( bar_cmd )
+{}
+END_TEST
+
+Suite* ss[2];
+
+Suite** suites(void)
+{
+ Suite *fs = suite_create("foo");
+ TCase *tc_foo = tcase_create("foo_test");
+ tcase_add_test(tc_foo, foo_cmd);
+ suite_add_tcase(fs, tc_foo);
+
+ Suite *bs = suite_create("bar");
+ TCase *tc_bar = tcase_create("bar_test");
+ tcase_add_test(tc_bar, bar_cmd);
+ suite_add_tcase(bs, tc_bar);
+
+ ss[0] = fs;
+ ss[1] = bs;
+ return ss;
+}
+
+CHECK_VERITAS_MAIN( suites(), 2 )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcheck.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.h (revision 1522570)
@@ -0,0 +1,39 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CHECK_CHECKVIEWDATA_H
+#define CHECK_CHECKVIEWDATA_H
+
+#include <veritas/itestrunner.h>
+
+namespace Veritas { class Test; class ITestFramework; }
+
+/*! Assorted check toolview data and operation */
+class CheckViewData : public Veritas::ITestRunner
+{
+Q_OBJECT
+public:
+ CheckViewData(Veritas::ITestFramework* framework);
+ virtual ~CheckViewData();
+ void registerTests();
+ QString fetchExe();
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkexport.h (revision 1522570)
@@ -0,0 +1,37 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef VERITAS_CHECKEXPORT_H
+#define VERITAS_CHECKEXPORT_H
+
+#include <kdemacros.h>
+
+#ifndef VERITAS_CHECK_EXPORT
+# ifdef MAKE_KDEVCHECK_LIB
+# define VERITAS_CHECK_EXPORT KDE_EXPORT
+# else
+# define VERITAS_CHECK_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif // VERITAS_CHECK_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.cpp (revision 1522570)
@@ -0,0 +1,78 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "checkplugin.h"
+#include <veritas/testtoolviewfactory.h>
+
+#include <kpluginfactory.h>
+#include <kaboutdata.h>
+#include <kpluginloader.h>
+#include <ksharedconfig.h>
+
+#include <interfaces/iuicontroller.h>
+#include <interfaces/iproject.h>
+#include <interfaces/iprojectcontroller.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <project/projectmodel.h>
+#include <interfaces/icore.h>
+#include <veritas/test.h>
+#include "plugins/xtest/cppunit/register.h"
+#include <QFile>
+#include <KDebug>
+#include <KConfigGroup>
+
+#include "testroot.h"
+#include "testsuite.h"
+#include "checkviewdata.h"
+
+using KDevelop::IProject;
+using KDevelop::IProjectController;
+using Veritas::TestToolViewFactory;
+using Check::TestRoot;
+using Check::TestSuite;
+
+K_PLUGIN_FACTORY(CheckPluginFactory, registerPlugin<CheckPlugin>();)
+K_EXPORT_PLUGIN(CheckPluginFactory(KAboutData("kdevcheck","kdevcheck", ki18n("Check Test"), "0.1", ki18n("Support for running check unit tests"), KAboutData::License_GPL)))
+
+CheckPlugin::CheckPlugin(QObject* parent, const QVariantList &)
+ : IPlugin(CheckPluginFactory::componentData(), parent)
+{
+ KDEV_USE_EXTENSION_INTERFACE( Veritas::ITestFramework );
+ TestToolViewFactory* factory = new TestToolViewFactory(this);
+ core()->uiController()->addToolView(name() + " Runner", factory);
+ setXMLFile("kdevcheck.rc");
+}
+
+CheckPlugin::~CheckPlugin()
+{
+}
+
+QString CheckPlugin::name() const
+{
+ static QString s_name("Check");
+ return s_name;
+}
+
+Veritas::ITestRunner* CheckPlugin::createRunner()
+{
+ return new CheckViewData(this);
+}
+
+#include "checkplugin.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.cpp
___________________________________________________________________
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.h (revision 1522570)
@@ -0,0 +1,44 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CHECK_CHECKPLUGIN
+#define CHECK_CHECKPLUGIN
+
+#include <QVariantList>
+#include <interfaces/iplugin.h>
+#include <veritas/itestframework.h>
+
+namespace Veritas { class TestToolViewFactory; }
+
+/*! Test runner plugin for the Check C unit testing framework */
+class CheckPlugin : public KDevelop::IPlugin, public Veritas::ITestFramework
+{
+Q_OBJECT
+Q_INTERFACES(Veritas::ITestFramework)
+
+public:
+ explicit CheckPlugin(QObject* parent, const QVariantList & = QVariantList());
+ virtual ~CheckPlugin();
+ virtual Veritas::ITestRunner* createRunner();
+ virtual QString name() const;
+ virtual QWidget* createConfigWidget() { return 0; }
+};
+
+#endif // CHECK_CHECKPLUGIN
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkplugin.h
___________________________________________________________________
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkviewdata.cpp (revision 1522570)
@@ -0,0 +1,63 @@
+ /* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "checkviewdata.h"
+#include <KSharedConfig>
+#include <KConfigGroup>
+#include <interfaces/iproject.h>
+#include "../cppunit/register.h"
+#include "testroot.h"
+#include "testsuite.h"
+
+using namespace KDevelop;
+using namespace Veritas;
+using namespace Check;
+
+CheckViewData::CheckViewData(Veritas::ITestFramework* framework) : Veritas::ITestRunner(framework)
+{}
+
+CheckViewData::~CheckViewData() {}
+
+void CheckViewData::registerTests()
+{
+ Register<TestRoot, TestSuite> reg;
+ QString testExe = fetchExe();
+ if (testExe.isEmpty()) {
+ return; // TODO failure message
+ }
+ reg.addFromExe(KUrl(testExe));
+ reg.rootItem()->setExecutable(testExe);
+ emit registerFinished(reg.rootItem());
+}
+
+QString CheckViewData::fetchExe()
+{
+ if (project() == 0) return QString();
+ KSharedConfig::Ptr cfg = project()->projectConfiguration();
+ KConfigGroup group(cfg.data(), "Veritas");
+ QStringList executables;
+ executables = group.readEntry("executables", executables);
+ if (executables.isEmpty()) {
+ return QString();
+ }
+ return executables[0];
+}
+
+#include "checkviewdata.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/check_impl.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/check_impl.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/check_impl.h (revision 1522570)
@@ -0,0 +1,128 @@
+/*
+ * Check: a unit test framework for C
+ * Copyright (C) 2001,2002 Arien Malec
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef CHECK_IMPL_H
+#define CHECK_IMPL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This header should be included by any module that needs
+ to know the implementation details of the check structures
+ Include stdio.h & list.h before this header
+*/
+
+/* magic values */
+
+/* Unspecified fork status, used only internally */
+#define CK_FORK_UNSPECIFIED -1
+
+
+typedef struct TF {
+ TFun fn;
+ int loop_start;
+ int loop_end;
+ const char *name;
+ int signal;
+} TF;
+
+struct Suite {
+ const char *name;
+ List *tclst; /* List of test cases */
+};
+
+typedef struct Fixture
+{
+ int ischecked;
+ SFun fun;
+} Fixture;
+
+struct TCase {
+ const char *name;
+ int timeout;
+ List *tflst; /* list of test functions */
+ List *unch_sflst;
+ List *unch_tflst;
+ List *ch_sflst;
+ List *ch_tflst;
+};
+
+typedef struct TestStats {
+ int n_checked;
+ int n_failed;
+ int n_errors;
+} TestStats;
+
+struct TestResult {
+ enum test_result rtype; /* Type of result */
+ enum ck_result_ctx ctx; /* When the result occurred */
+ char *file; /* File where the test occurred */
+ int line; /* Line number where the test occurred */
+ int iter; /* The iteration value for looping tests */
+ const char *tcname; /* Test case that generated the result */
+ const char *tname; /* Test that generated the result */
+ char *msg; /* Failure message */
+};
+
+TestResult *tr_create(void);
+void tr_reset(TestResult *tr);
+
+enum cl_event {
+ CLINITLOG_SR,
+ CLENDLOG_SR,
+ CLSTART_SR,
+ CLSTART_S,
+ CLEND_SR,
+ CLEND_S,
+ CLEND_T
+};
+
+typedef void (*LFun) (SRunner *, FILE*, enum print_output,
+ void *, enum cl_event);
+
+typedef struct Log {
+ FILE *lfile;
+ LFun lfun;
+ int close;
+ enum print_output mode;
+} Log;
+
+struct SRunner {
+ List *slst; /* List of Suite objects */
+ TestStats *stats; /* Run statistics */
+ List *resultlst; /* List of unit test results */
+ const char *log_fname; /* name of log file */
+ const char *xml_fname; /* name of xml output file */
+ List *loglst; /* list of Log objects */
+ enum fork_status fstat; /* controls if suites are forked or not
+ NOTE: Don't use this value directly,
+ instead use srunner_fork_status */
+};
+
+
+void set_fork_status(enum fork_status fstat);
+enum fork_status cur_fork_status (void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CHECK_IMPL_H */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.cpp (revision 1522570)
@@ -0,0 +1,227 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "outputparser.h"
+#include "testsuite.h"
+#include "testroot.h"
+#include "plugins/xtest/cppunit/testcase.h"
+#include <KUrl>
+#include <KDebug>
+
+using Check::TestRoot;
+using Check::OutputParser;
+using Veritas::TestResult;
+
+/*example xml:
+<?xml version="1.0"?>
+<testsuites xmlns="http://check.sourceforge.net/ns">
+ <datetime>2008-06-20 13:59:25</datetime>
+ <suite>
+ <title>Money</title>
+ <test result="success">
+ <path>.</path>
+ <fn>check_money.c:28</fn>
+ <id>test_money_create</id>
+ <iteration>0</iteration>
+ <description>Core</description>
+ <message>Passed</message>
+ </test>
+ <test result="error">
+ <path>.</path>
+ <fn>check_money.c:37</fn>
+ <id>test_money_create_neg</id>
+ <iteration>0</iteration>
+ <description>Limits</description>
+ <message>Test timeout expired</message>
+ </test>
+ <test result="success">
+ <path>.</path>
+ <fn>check_money.c:46</fn>
+ <id>test_money_create_zero</id>
+ <iteration>0</iteration>
+ <description>Limits</description>
+ <message>Passed</message>
+ </test>
+ </suite>
+ <duration>0.000000</duration>
+</testsuites>
+*/
+
+const QString OutputParser::c_suite("suite");
+const QString OutputParser::c_test("test");
+const QString OutputParser::c_title("title");
+const QString OutputParser::c_path("path");
+const QString OutputParser::c_file("fn");
+const QString OutputParser::c_id("id");
+const QString OutputParser::c_description("description");
+const QString OutputParser::c_message("message");
+const QString OutputParser::c_result("result");
+const QString OutputParser::c_error("error");
+const QString OutputParser::c_failure("failure");
+const QString OutputParser::c_success("success");
+
+#define ENSURE_FOUND(c,p,n) Q_ASSERT_X(c, "hm",\
+ qstrdup((QString("Failed to find ") + n + QString(" as child of ")\
+ + p->name()).toAscii().data()));
+
+
+OutputParser::OutputParser(QIODevice* device)
+ : QXmlStreamReader(device),
+ m_result(0)
+{}
+
+OutputParser::~OutputParser()
+{}
+
+bool OutputParser::isStartElement_(const QString& elementName)
+{
+ return isStartElement() && (name() == elementName);
+}
+
+bool OutputParser::isEndElement_(const QString& elementName)
+{
+ return isEndElement() && (name() == elementName);
+}
+
+void OutputParser::go(TestRoot* root)
+{
+ m_root = root;
+ if (!device()->isOpen()) {
+ device()->open(QIODevice::ReadOnly);
+ }
+ if (!device()->isReadable()) {
+ // do something
+ }
+ while (!atEnd()) {
+ readNext();
+ if (isStartElement_(c_suite)) {
+ processSuite();
+ }
+ }
+ kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
+}
+
+void OutputParser::processSuite()
+{
+ QString name = fetchName();
+ m_suite = m_root->childNamed(name);
+ ENSURE_FOUND(m_suite, m_root, name);
+ while (!atEnd() && !isEndElement_(c_suite)) {
+ readNext();
+ if (isStartElement_(c_test)) {
+ processTest();
+ }
+ }
+}
+
+void OutputParser::processTest()
+{
+ QString caze, cmd, result, file, msg;
+ bool ok = readTestElement(caze, cmd, result, file, msg);
+ if (ok) postResult(caze, cmd, result, file, msg);
+}
+
+void OutputParser::postResult(const QString& caze, const QString& cmd, const QString& result,
+ const QString& file, const QString& msg)
+{
+ if (result == c_success) {
+ setSuccess();
+ } else if (result == c_error || result == c_failure) {
+ setFailure(file, msg);
+ } else {
+ kDebug() << "unkwown result: " << result << " for " << caze << ":" << cmd;
+ }
+ m_case = m_suite->childNamed(caze);
+ ENSURE_FOUND(m_case, m_suite, caze);
+ m_cmd = m_case->childNamed(cmd);
+ ENSURE_FOUND(m_cmd, m_case, cmd);
+
+ m_cmd->setResult(m_result);
+ m_cmd->signalStarted();
+ m_cmd->signalFinished();
+}
+
+/*
+<test result="success">
+ <path>.</path>
+ <fn>check_money.c:28</fn>
+ <id>test_money_create</id>
+ <iteration>0</iteration>
+ <description>Core</description>
+ <message>Passed</message>
+</test>
+*/
+bool OutputParser::readTestElement(QString& caze, QString& cmd, QString& result,
+ QString& file, QString& msg)
+{
+ int count = 0;
+ QString path;
+ result = attributes().value("result").toString();
+ m_result = new TestResult;
+ while (!atEnd() && !isEndElement_(c_test)) {
+ readNext();
+ if (!isStartElement()) {
+ continue;
+ } else if (name() == c_path) {
+ path = readElementText();
+ } else if(name() == c_file) {
+ file = readElementText();
+ } else if (name() == c_description) {
+ caze = readElementText();
+ } else if (name() == c_message) {
+ msg = readElementText();
+ } else if (name() == c_id) {
+ cmd = readElementText();
+ }
+ count++;
+ }
+ if (isEndElement_(c_test)) {
+ Q_ASSERT_X(count == 6, "readTestElement", QString("Execpted 5 elements, got " + QString::number(count)).toAscii());
+ return true;
+ } else {
+ return false;
+ }
+}
+
+QString OutputParser::fetchName()
+{
+ while (!atEnd()) {
+ readNext();
+ if (isStartElement_(c_title)) {
+ return readElementText();
+ }
+ }
+ Q_ASSERT(0);
+ return "??????";
+}
+
+void OutputParser::setSuccess()
+{
+ m_result->setState(Veritas::RunSuccess);
+}
+
+void OutputParser::setFailure(const QString& location, const QString& msg)
+{
+ m_result->setState(Veritas::RunError);
+ QStringList spl = location.split(':');
+ m_result->setFile(KUrl(spl.value(0)));
+ m_result->setLine(spl.value(1).toInt());
+ m_result->setMessage(msg);
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.h (revision 1522570)
@@ -0,0 +1,53 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CHECK_TESTSUITE_H
+#define VERITAS_CHECK_TESTSUITE_H
+
+#include <QString>
+#include <QFileInfo>
+#include <KProcess>
+
+#include <veritas/test.h>
+
+#include "plugins/xtest/cppunit/testcase.h"
+
+namespace Check
+{
+
+/*! Test aggregate item in the test tree. Contains TestCases */
+class TestSuite : public Veritas::Test
+{
+Q_OBJECT
+public:
+ /*!
+ * Provide name, executable location and Test parent.
+ */
+ TestSuite(const QString&, const QFileInfo&, Veritas::Test*);
+ virtual ~TestSuite();
+ TestCase* child(int i) const;
+
+private:
+ QFileInfo m_exe;
+};
+
+} // end namespace Check
+
+#endif // VERITAS_CHECK_TESTSUITE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/outputparser.h (revision 1522570)
@@ -0,0 +1,84 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CHECK_CHECKOUTPUTPARSER
+#define VERITAS_CHECK_CHECKOUTPUTPARSER
+
+#include <QXmlStreamReader>
+#include <veritas/testresult.h>
+
+class QIODevice;
+namespace Veritas { class Test; }
+
+namespace Check
+{
+class TestRoot;
+
+/*! Translates Check XML Output into TestResults */
+class OutputParser : public QXmlStreamReader
+{
+public:
+ OutputParser(QIODevice* device);
+ virtual ~OutputParser();
+
+ /**
+ * Start parsing and emit results
+ **/
+ void go(TestRoot*);
+
+private: // helpers
+ void processSuite();
+ void processTest();
+ bool readTestElement(QString&, QString&, QString&, QString&, QString&);
+ void postResult(const QString&, const QString&, const QString&,
+ const QString&, const QString&);
+ QString fetchName();
+ void setFailure(const QString&, const QString&);
+ void setSuccess();
+
+ inline bool isStartElement_(const QString& elem);
+ inline bool isEndElement_(const QString& elem);
+
+private: // state
+ Veritas::TestResult* m_result;
+ QString m_currentSuite;
+ TestRoot* m_root;
+ Veritas::Test* m_suite;
+ Veritas::Test* m_case;
+ Veritas::Test* m_cmd;
+
+private: // some xml constants
+ static const QString c_suite;
+ static const QString c_test;
+ static const QString c_title;
+ static const QString c_path;
+ static const QString c_file;
+ static const QString c_id;
+ static const QString c_description;
+ static const QString c_message;
+ static const QString c_result;
+ static const QString c_error;
+ static const QString c_failure;
+ static const QString c_success;
+};
+
+} // namespace Check
+
+#endif // VERITAS_CHECK_CHECKOUTPUTPARSER
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/checkwrapper.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/checkwrapper.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/checkwrapper.h (revision 1522570)
@@ -0,0 +1,107 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+/*!
+Constructs a compatible check executable for check Suite(s)
+through main macro's. See CHECK_VERITAS_MAIN.
+This header is intended for users of the runner, not a part of the
+check plugin.
+*/
+
+#ifndef CHECK_WRAPPER_H
+#define CHECK_WRAPPER_H
+
+#include <stdio.h>
+#include <check.h>
+#include "check_list.h"
+#include "check_impl.h"
+
+void qxcheck_print_suite(Suite* suite)
+{
+ printf("<suite name=\"%s\">\n", suite->name);
+ List *cases = suite->tclst;
+ list_front(cases);
+ while (!list_at_end(cases)) {
+ TCase* caze = (struct TCase*)list_val(cases);
+ printf(" <case name=\"%s\">\n", caze->name);
+ List *cmds = caze->tflst;
+ list_front(cmds);
+ while (!list_at_end(cmds)) {
+ TF* cmd = (struct TF*)list_val(cmds);
+ printf(" <command name=\"%s\"/>\n", cmd->name);
+ list_advance(cmds);
+ }
+ printf(" </case>\n");
+ list_advance(cases);
+ }
+ printf("</suite>\n");
+}
+
+int qxcheck_print_tests(Suite** suites, int num)
+{
+ int i;
+ printf("<?xml version=\"1.0\"?>\n"
+ "<testsuites>\n");
+ for (i=0; i<num; i++) {
+ Suite* s = suites[i];
+ qxcheck_print_suite(s);
+ }
+ printf("</testsuites>\n");
+ return 0;
+}
+
+int qxcheck_run_tests(Suite** suites, int num)
+{
+ int number_failed, i;
+
+ SRunner *sr = srunner_create(suites[0]);
+ for (i=1; i<num; i++) {
+ srunner_add_suite(sr, suites[i]);
+ }
+ srunner_set_xml(sr, "checklog.xml");
+ srunner_run_all(sr, CK_SILENT);
+ number_failed = srunner_ntests_failed(sr);
+ srunner_free(sr);
+ return (number_failed == 0) ? 0 : 1;
+}
+
+#define CHECK_VERITAS_MAIN_( root ) \
+int main(int argc, char** argv)\
+{\
+ Suite* s = root; \
+ Suite* suites[1] = {s}; \
+ if (argc == 1 || argv[1][0] != '-') { \
+ return qxcheck_run_tests(suites,1); \
+ } else { \
+ return qxcheck_print_tests(suites,1); \
+ }\
+}
+
+#define CHECK_VERITAS_MAIN( multi, num ) \
+int main(int argc, char** argv)\
+{\
+ if (argc == 1 || argv[1][0] != '-') {\
+ return qxcheck_run_tests(multi, num); \
+ } else { \
+ return qxcheck_print_tests(multi, num); \
+ }\
+}
+
+#endif // CHECK_WRAPPER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CHECK_TESTROOT_H
+#define VERITAS_CHECK_TESTROOT_H
+
+#include <QString>
+#include <QFileInfo>
+
+#include <veritas/test.h>
+#include "testsuite.h"
+
+namespace Check
+{
+
+/*! Prime item in the Check Test Tree. Holds the executable */
+class TestRoot : public Veritas::Test
+{
+Q_OBJECT
+public:
+ TestRoot(const QList<QVariant>& data);
+ virtual ~TestRoot();
+ TestSuite* child(int i) const;
+ void setExecutable(const QFileInfo& e) { m_exe = e; }
+ int run();
+ bool shouldRun() const;
+
+private:
+ QFileInfo m_exe;
+};
+
+} // end namespace Check
+
+#endif // VERITAS_CHECK_TESTROOT_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/check.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/check.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/check.kdev4 (revision 1522570)
@@ -0,0 +1,3 @@
+[Project]
+Name=check
+Manager=KDevCustomMakeManager
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/testroot.cpp (revision 1522570)
@@ -0,0 +1,73 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testroot.h"
+#include "outputparser.h"
+#include <QDir>
+#include <KDebug>
+#include <KProcess>
+
+
+using Veritas::Test;
+
+using Check::TestRoot;
+using Check::TestSuite;
+using Check::OutputParser;
+
+TestRoot::TestRoot(const QList<QVariant>& data)
+ : Test(data, 0)
+{}
+
+TestRoot::~TestRoot()
+{}
+
+bool TestRoot::shouldRun() const
+{
+ return true;
+}
+
+TestSuite* TestRoot::child(int i) const
+{
+ Test* child = Test::child(i);
+ TestSuite* suite = qobject_cast<TestSuite*>(child);
+ kWarning(suite==0) << "cast failed? " << name() << " "
+ << i << " " << ((child!=0) ? child->name() : "null");
+ return suite;
+}
+
+int TestRoot::run()
+{
+ KProcess proc;
+ QStringList argv;
+ proc.setProgram(m_exe.filePath(), argv);
+ kDebug() << "executing " << proc.program();
+ proc.setOutputChannelMode(KProcess::SeparateChannels);
+ proc.start();
+ proc.waitForFinished(-1);
+ QStringList spl = m_exe.filePath().split('/');
+ QFile f(QFileInfo(QDir::currentPath(), "checklog.xml").filePath());
+ kWarning(!f.exists()) << "Failure: testresult dump does not exist [" << f.fileName();
+ OutputParser parser(&f);
+ parser.go(this);
+ emit executionFinished();
+ return 0;
+}
+
+#include "testroot.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/testsuite.cpp (revision 1522570)
@@ -0,0 +1,46 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testsuite.h"
+#include "outputparser.h"
+#include <KDebug>
+#include <QDir>
+
+using Check::TestSuite;
+using Check::OutputParser;
+using Veritas::Test;
+
+TestSuite::TestSuite(const QString& name, const QFileInfo& exe, Test* parent)
+ : Test(name, parent), m_exe(exe)
+{}
+
+TestSuite::~TestSuite()
+{}
+
+TestCase* TestSuite::child(int i) const
+{
+ Test* child = Test::child(i);
+ TestCase* caze = qobject_cast<TestCase*>(child);
+ kWarning(caze==0) << "cast failed? " << name() << " "
+ << i << " " << ((child!=0) ? child->name() : "null");
+ return caze;
+}
+
+#include "testsuite.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/kdevcheck.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevXtest" version="1">
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/check/check_list.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/check/check_list.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/check/check_list.h (revision 1522570)
@@ -0,0 +1,71 @@
+/*
+ * Check: a unit test framework for C
+ * Copyright (C) 2001, 2002 Arien Malec
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef CHECK_LIST_H
+#define CHECK_LIST_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct List {
+ int n_elts;
+ int max_elts;
+ int current; /* pointer to the current node */
+ int last; /* pointer to the node before END */
+ const void **data;
+};
+
+typedef struct List List;
+
+/* Create an empty list */
+List * check_list_create (void);
+
+/* Is list at end? */
+int list_at_end (List * lp);
+
+/* Position list at front */
+void list_front(List *lp);
+
+/* Add a value to the front of the list,
+ positioning newly added value as current value.
+ More expensive than list_add_end, as it uses memmove. */
+void list_add_front (List *lp, const void *val);
+
+/* Add a value to the end of the list,
+ positioning newly added value as current value */
+void list_add_end (List *lp, const void *val);
+
+/* Give the value of the current node */
+void *list_val (List * lp);
+
+/* Position the list at the next node */
+void list_advance (List * lp);
+
+/* Free a list, but don't free values */
+void list_free (List * lp);
+
+void list_apply (List *lp, void (*fp) (void *));
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CHECK_LIST_H */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop (revision 1522570)
@@ -0,0 +1,85 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Icon=kdevelop
+Comment=CppUnit test runner
+Comment[bs]=CppUnit izvršitelj testova
+Comment[ca]=Llançador de proves Cppunit
+Comment[ca@valencia]=Llançador de proves Cppunit
+Comment[de]=CppUnit-Test ausführen
+Comment[el]=Εκτελεστής ελέγχου μονάδας Cpp
+Comment[en_GB]=CppUnit test runner
+Comment[es]=Lanzador de pruebas unitarias de Cpp
+Comment[et]=CppUniti testi käivitaja
+Comment[fr]=Lanceur de tests CppUnit
+Comment[ga]=Feidhmitheoir tástála CppUnit
+Comment[gl]=Executor de probas de CppUnit
+Comment[it]=Esecutore di test CppUnit
+Comment[ms]=Pelari unit CppUnit
+Comment[nds]=CppUnit-Testdreger
+Comment[nl]=Voert CppUnit tests uit
+Comment[pl]=Uruchomienie testu CppUnit
+Comment[pt]=Execução de testes do CppUnit
+Comment[pt_BR]=Execução de testes do CppUnit
+Comment[sv]=Kör Cpp-enhetstest
+Comment[tr]=CppUnit sınaması çalıştırıcı
+Comment[uk]=Засіб запуску перевірки CppUnit
+Comment[x-test]=xxCppUnit test runnerxx
+Name=CppUnit runner
+Name[bs]=CppUnit runner(pokreće neku akciju)
+Name[ca]=Executor CppUnit
+Name[ca@valencia]=Executor CppUnit
+Name[de]=CppUnit ausführen
+Name[el]=Εκτελεστής μονάδας Cpp
+Name[en_GB]=CppUnit runner
+Name[es]=Lanzador CppUnit
+Name[et]=CppUniti käivitaja
+Name[fr]=Lanceur CppUnit
+Name[ga]=Feidhmitheoir CppUnit
+Name[gl]=Executor de CppUnit
+Name[it]=Esecutore CppUnit
+Name[ms]=Pelari CppUnit
+Name[nds]=CppUnit-Dreger
+Name[nl]=Voert CppUnit uit
+Name[pl]=Uruchomienie CppUnit
+Name[pt]=Execução do CppUnit
+Name[pt_BR]=Execução do CppUnit
+Name[sv]=Kör Cpp-enhet
+Name[tr]=CppUnit çalıştırıcı
+Name[uk]=Засіб запуску CppUnit
+Name[x-test]=xxCppUnit runnerxx
+GenericName=Unit test runner
+GenericName[bs]=Jednični test runner(pokreće neku akciju)
+GenericName[ca]=Executor de prova Unit
+GenericName[ca@valencia]=Executor de prova Unit
+GenericName[de]=Unittest ausführen
+GenericName[el]=Εκτελεστής ελέγχου unit
+GenericName[en_GB]=Unit test runner
+GenericName[es]=Lanzador de pruebas unitarias
+GenericName[et]=Unit-testi käivitaja
+GenericName[fr]=Lanceur de test unitaire
+GenericName[ga]=Feidhmitheoir tástála aonad
+GenericName[gl]=Executor de probas unitarias
+GenericName[it]=Esecutore di unit test
+GenericName[ms]=Pelari unit uji
+GenericName[nds]=Unit-Testdreger
+GenericName[nl]=Test-startprogramma voor eenheid
+GenericName[pa]=ਯੂਨਿਟ ਟੈਸਟ ਰਨਰ
+GenericName[pl]=Uruchamianie jednostki testu
+GenericName[pt]=Execução de testes unitários
+GenericName[pt_BR]=Execução de testes unitários
+GenericName[sk]=Spúštač unit testov
+GenericName[sv]=Kör enhetstest
+GenericName[tr]=Birim sınaması çalıştırıcı
+GenericName[uk]=Засіб запуску перевірки модулів
+GenericName[x-test]=xxUnit test runnerxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevcppunitview
+X-KDE-PluginInfo-Name=cppunitview
+X-KDE-PluginInfo-Author=Manuel Breugelmans
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=LGPL
+X-KDevelop-Interfaces=org.kdevelop.ITestFramework
+X-KDevelop-Version=7
+X-KDevelop-Category=Global
+X-KDevelop-Properties=GlobalFileManagement
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,75 @@
+project(cppunit)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${cppunit_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+find_package(CppUnit)
+macro_log_feature(CPPUNIT_FOUND "CppUnit" "KDevelop4 extra plugin cppunit" "http://TODO" FALSE "" "")
+
+if (CPPUNIT_FOUND)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+add_subdirectory(tests)
+
+#
+# TODO install qxcppunit headers
+#
+
+add_definitions(${KDE4_ENABLE_EXCEPTIONS})
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+
+include_directories(
+ ${XtestPlugin_SOURCE_DIR}
+ )
+
+set(kdevcppunit_SRCS
+ testcommand.cpp
+ testcase.cpp
+ testsuite.cpp
+ testroot.cpp
+ cppunitviewdata.cpp
+ cppunittesttreebuilder.cpp
+ outputparser.cpp)
+
+qt4_add_resources(kdevcppunit_SRCS
+ resources/qxcppunit.qrc)
+
+qt4_automoc( ${kdevcppunit_SRCS} )
+kde4_add_library(kdevcppunit SHARED ${kdevcppunit_SRCS})
+target_link_libraries(kdevcppunit
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${CPPUNIT_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${QT_QTCORE_LIBRARY})
+install(TARGETS kdevcppunit ${INSTALL_TARGETS_DEFAULT_ARGS} )
+
+#########################################
+
+set(kdevcppunitview_SRCS cppunitplugin.cpp cppunittesttreebuilder.cpp)
+qt4_automoc(${kdevcppunitview_SRCS})
+kde4_add_plugin(kdevcppunitview ${kdevcppunitview_SRCS})
+target_link_libraries(kdevcppunitview
+ kdevcppunit
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${KDE4_KDEUI_LIBS}
+ ${QT_QTCORE_LIBRARY})
+install(TARGETS kdevcppunitview DESTINATION ${PLUGIN_INSTALL_DIR})
+
+########### install files ###############
+
+install( FILES kdevcppunit.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevcppunit.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcppunit )
+install( FILES cppunitwrapper.h DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/veritas/ )
+
+endif()
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake (revision 1522570)
@@ -0,0 +1,34 @@
+# - Find CppUnit
+# This module finds an installed CppUnit package.
+#
+# Obtained from:
+# http://root.cern.ch/viewvc/trunk/cint/reflex/cmake/modules/FindCppUnit.cmake?view=log&pathrev=24750
+#
+# It sets the following variables:
+# CPPUNIT_FOUND - Set to false, or undefined, if CppUnit isn't found.
+# CPPUNIT_INCLUDE_DIR - The CppUnit include directory.
+# CPPUNIT_LIBRARY - The CppUnit library to link against.
+
+FIND_PATH(CPPUNIT_INCLUDE_DIR cppunit/Test.h)
+FIND_LIBRARY(CPPUNIT_LIBRARY NAMES cppunit)
+
+IF (CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARY)
+ SET(CPPUNIT_FOUND TRUE)
+ENDIF (CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARY)
+
+IF (CPPUNIT_FOUND)
+
+ # show which CppUnit was found only if not quiet
+ IF (NOT CppUnit_FIND_QUIETLY)
+ MESSAGE(STATUS "Found CppUnit: ${CPPUNIT_LIBRARY}")
+ ENDIF (NOT CppUnit_FIND_QUIETLY)
+
+ELSE (CPPUNIT_FOUND)
+
+ # fatal error if CppUnit is required but not found
+ IF (CppUnit_FIND_REQUIRED)
+ MESSAGE(FATAL_ERROR "Could not find CppUnit")
+ ENDIF (CppUnit_FIND_REQUIRED)
+
+ENDIF (CPPUNIT_FOUND)
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,30 @@
+set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+include_directories(
+ ${XtestPlugin_SOURCE_DIR}/cppunit
+ ${XtestPlugin_SOURCE_DIR} # for kasserts.h
+)
+
+add_definitions(${KDE4_ENABLE_EXCEPTIONS})
+
+macro(kdev_qx_add_test test_EXEC)
+ set(test_SRCS ${ARGN})
+ qt4_automoc( ${test_SRCS} )
+ kde4_add_unit_test(cppunit-${test_EXEC} ${test_SRCS})
+ target_link_libraries(cppunit-${test_EXEC}
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTXML_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDEVPLATFORM_VERITAS_LIBRARIES}
+ kdevcppunit)
+endmacro(kdev_qx_add_test)
+
+kdev_qx_add_test(sys-cppunitrunnertest cppunitrunnertest.cpp)
+
+add_executable(emptysuite fake_emptysuite.cpp)
+target_link_libraries(emptysuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
+
+add_executable(sunnysuite fake_sunnysuite.cpp)
+target_link_libraries(sunnysuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
+
+add_executable(multisuite fake_multisuite.cpp)
+target_link_libraries(multisuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp (revision 1522570)
@@ -0,0 +1,144 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "cppunitrunnertest.h"
+
+#include <kasserts.h>
+#include <qtest_kde.h>
+#include <veritas/testresult.h>
+#include <veritas/runnertesthelper.h>
+#include "register.h"
+
+#include "testroot.h"
+#include "testsuite.h"
+
+using Veritas::RunnerTestHelper;
+using CppUnit::Test::CppUnitRunnerTest;
+
+Q_DECLARE_METATYPE(QList<QStringList>)
+
+void CppUnitRunnerTest::init()
+{
+ m_runner = new RunnerTestHelper;
+ m_runner->initializeGUI();
+}
+
+void CppUnitRunnerTest::cleanup()
+{
+ delete m_runner;
+}
+
+// command
+void CppUnitRunnerTest::empty()
+{
+ Veritas::Test* root = fetchRoot("./emptysuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ QStringList runnerItems;
+ runnerItems << "0 x"; // an empty test-tree
+ m_runner->verifyTestTree(runnerItems);
+
+ QList<QStringList> results; // no test failures
+ m_runner->verifyResultItems(results);
+}
+
+QStringList sunnyDayTests()
+{
+ QStringList runnerItems;
+ runnerItems << "0 RootSuite"
+ << "0 0 FooTest"
+ << "0 0 0 testCmd1"
+ << "0 0 1 testCmd2"
+ << "0 0 2 x"
+ << "0 1 BarTest"
+ << "0 1 0 testCmd1"
+ << "0 1 1 testCmd2"
+ << "0 1 2 x"
+ << "0 2 BazTest"
+ << "0 2 0 testCmd1"
+ << "0 2 1 x"
+ << "0 3 x"
+ << "1 x";
+ return runnerItems;
+}
+
+QMap<QString, Veritas::TestState> sunnyDayTestStates()
+{
+ QMap<QString, Veritas::TestState> states;
+ states["RootSuite/FooTest/testCmd1"] = Veritas::RunSuccess;
+ states["RootSuite/FooTest/testCmd2"] = Veritas::RunSuccess;
+ states["RootSuite/BarTest/testCmd1"] = Veritas::RunSuccess;
+ states["RootSuite/BarTest/testCmd2"] = Veritas::RunError;
+ states["RootSuite/BazTest/testCmd1"] = Veritas::RunSuccess;
+ return states;
+}
+
+// command
+void CppUnitRunnerTest::sunnyDay()
+{
+ Veritas::Test* root = fetchRoot("./sunnysuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ m_runner->verifyTestTree(sunnyDayTests());
+ m_runner->verifyTestStates(sunnyDayTestStates(), root);
+ QStringList result0;
+ result0 << "testCmd2" << "" << KUrl(__FILE__).upUrl().path() + "fake_sunnysuite.cpp" << "63";
+ QList<QStringList> results;
+ results << result0;
+ m_runner->verifyResultItems(results);
+}
+
+// command
+void CppUnitRunnerTest::multiSuite()
+{
+ Veritas::Test* root = fetchRoot("./multisuite");
+ m_runner->setRoot(root);
+ m_runner->runTests();
+
+ QStringList topo;
+ topo << "0 FooSuite"
+ << "0 0 FooTest"
+ << "0 0 0 FooTest::fooCmd"
+ << "0 0 1 x"
+ << "0 1 x"
+ << "1 BarSuite"
+ << "1 0 BarTest"
+ << "1 0 0 BarTest::barCmd"
+ << "1 0 1 x"
+ << "1 1 x"
+ << "2 x";
+ m_runner->verifyTestTree(topo);
+
+ QList<QStringList> results;
+ m_runner->verifyResultItems(results);
+}
+
+Veritas::Test* CppUnitRunnerTest::fetchRoot(const char* exe)
+{
+ Register<TestRoot, TestSuite> reg;
+ reg.addFromExe(QFileInfo(exe));
+ reg.rootItem()->setExecutable(QFileInfo(exe));
+ return reg.rootItem();
+}
+
+#include "cppunitrunnertest.moc"
+QTEST_KDEMAIN(CppUnitRunnerTest, GUI)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h (revision 1522570)
@@ -0,0 +1,52 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CPPUNIT_CPPUNITRUNNERTEST_H
+#define CPPUNIT_CPPUNITRUNNERTEST_H
+
+#include <QtTest/QTest>
+
+namespace Veritas { class RunnerTestHelper; class Test; }
+
+namespace CppUnit {
+namespace Test {
+
+class CppUnitRunnerTest : public QObject
+{
+Q_OBJECT
+
+private slots:
+ void init();
+ void cleanup();
+
+ void empty();
+ void sunnyDay();
+ void multiSuite();
+
+private:
+ Veritas::Test* fetchRoot(const char*);
+
+private:
+ Veritas::RunnerTestHelper* m_runner;
+};
+
+}}
+
+#endif // CPPUNIT_CPPUNITRUNNERTEST_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp (revision 1522570)
@@ -0,0 +1,108 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <cppunit/TestSuite.h>
+#include <cppunit/TestFixture.h>
+#include <cppunit/TestCaller.h>
+#include <cppunitwrapper.h>
+
+// "0 RootSuite"
+// "0 0 FooTest"
+// "0 0 0 testCmd1"
+// "0 0 1 testCmd2"
+// "0 0 2 x"
+// "0 1 BarTest"
+// "0 1 0 testCmd1"
+// "0 1 1 testCmd2"
+// "0 1 2 x"
+// "0 2 BazTest"
+// "0 2 0 testCmd1"
+// "0 2 1 x"
+// "0 3 x"
+// "1 x"
+
+using namespace CppUnit;
+
+class FooTest : public TestFixture
+{
+public:
+ void testCmd1() {}
+ void testCmd2() {}
+
+ static Test* suite() {
+ TestSuite* suite = new CppUnit::TestSuite("FooTest");
+ typedef TestCaller<FooTest> fooCaller;
+ suite->addTest(new fooCaller("testCmd1", &FooTest::testCmd1));
+ suite->addTest(new fooCaller("testCmd2", &FooTest::testCmd2));
+ return suite;
+ }
+};
+
+class BarTest : public TestFixture
+{
+public:
+ void testCmd1() {}
+ void testCmd2() {
+ CPPUNIT_ASSERT(false);
+ }
+
+ static Test* suite() {
+ TestSuite* suite = new CppUnit::TestSuite("BarTest");
+ typedef TestCaller<BarTest> barCaller;
+ suite->addTest(new barCaller("testCmd1", &BarTest::testCmd1));
+ suite->addTest(new barCaller("testCmd2", &BarTest::testCmd2));
+ return suite;
+ }
+};
+
+#include <QThread>
+
+class Sleep : public QThread
+{
+public:
+ void run() {}
+ static void waitAbit() {
+ QThread::usleep(50000); // 0.05 sec
+ }
+};
+
+class BazTest : public TestFixture
+{
+public:
+ void testCmd1() { Sleep::waitAbit(); }
+
+ static Test* suite() {
+ TestSuite* suite = new CppUnit::TestSuite("BazTest");
+ typedef TestCaller<BazTest> bazCaller;
+ suite->addTest(new bazCaller("testCmd1", &BazTest::testCmd1));
+ return suite;
+ }
+};
+
+Test* suite()
+{
+ TestSuite* suite = new TestSuite("RootSuite");
+ suite->addTest(FooTest::suite());
+ suite->addTest(BarTest::suite());
+ suite->addTest(BazTest::suite());
+ return suite;
+}
+
+CPPUNIT_VERITAS_MAIN(suite())
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp (revision 1522570)
@@ -0,0 +1,24 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <cppunit/TestSuite.h>
+#include <cppunitwrapper.h>
+
+CPPUNIT_VERITAS_MAIN( new CppUnit::TestSuite() )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp (revision 1522570)
@@ -0,0 +1,75 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <cppunit/TestSuite.h>
+#include <cppunit/TestFixture.h>
+#include <cppunit/TestCaller.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunitwrapper.h>
+#include <vector>
+
+// "0 FooSuite"
+// "0 0 FooTest"
+// "0 0 0 fooCmd"
+// "0 0 1 x"
+// "0 1 x"
+// "1 BarSuite"
+// "1 0 BarTest"
+// "1 0 0 barCmd"
+// "1 0 1 x"
+// "1 1 x"
+// "2 x"
+
+using namespace CppUnit;
+
+class FooTest : public TestFixture
+{
+CPPUNIT_TEST_SUITE( FooTest );
+ CPPUNIT_TEST( fooCmd );
+CPPUNIT_TEST_SUITE_END();
+
+public:
+ void fooCmd() {}
+};
+
+class BarTest : public TestFixture
+{
+CPPUNIT_TEST_SUITE( BarTest );
+ CPPUNIT_TEST( barCmd );
+CPPUNIT_TEST_SUITE_END();
+
+public:
+ void barCmd() {}
+};
+
+std::vector<TestSuite*> suite()
+{
+ TestSuite* fs = new TestSuite("FooSuite");
+ fs->addTest(FooTest::suite());
+ TestSuite* bs = new TestSuite("BarSuite");
+ bs->addTest(BarTest::suite());
+
+ std::vector<TestSuite*> suites;
+ suites.push_back(fs);
+ suites.push_back(bs);
+ return suites;
+}
+
+CPPUNIT_VERITAS_MAIN_(suite())
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp (revision 1522570)
@@ -0,0 +1,37 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "cppunitviewdata.h"
+#include <interfaces/iproject.h>
+#include "register.h"
+#include "testroot.h"
+#include "testsuite.h"
+
+using namespace KDevelop;
+using namespace Veritas;
+using namespace CppUnit;
+
+CppUnitViewData::CppUnitViewData(ITestFramework* framework, ITestTreeBuilder * builder) : TestRunner(framework, builder)
+{
+}
+
+CppUnitViewData::~CppUnitViewData() {}
+
+#include "cppunitviewdata.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h (revision 1522570)
@@ -0,0 +1,57 @@
+/*
+* KDevelop CPPUnit integration
+* Copyright 2009 Andrew Coles <andrew_coles@yahoo.co.uk
+*
+* 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef CPPUNIT_CPPUNITTESTTREEBUILDER_H
+#define CPPUNIT_CPPUNITTESTTREEBUILDER_H
+
+#include <QObject>
+#include <veritas/testexecutableinfo.h>
+#include <veritas/itesttreebuilder.h>
+#include "qxcppunitexport.h"
+#include "register.h"
+#include "testroot.h"
+#include "testsuite.h"
+
+namespace KDevelop { class IProject; }
+namespace Veritas { class Test; }
+
+/*! Collects the test tree structure for a project. */
+class CppUnitTestTreeBuilder : public Veritas::ITestTreeBuilder
+{
+Q_OBJECT
+
+public:
+ CppUnitTestTreeBuilder();
+ virtual ~CppUnitTestTreeBuilder();
+
+ virtual Veritas::Test* root() const;
+ virtual void reload(KDevelop::IProject* project);
+
+ QString fetchExe(KDevelop::IProject* project);
+
+private:
+
+ Register<CppUnit::TestRoot, CppUnit::TestSuite> * reg;
+ CppUnit::TestRoot * m_root;
+
+
+};
+
+#endif // CPPUNIT_CPPUNITTESTTREEBUILDER_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp (revision 1522570)
@@ -0,0 +1,83 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "cppunitplugin.h"
+
+#include <kpluginfactory.h>
+#include <kaboutdata.h>
+#include <kpluginloader.h>
+#include <ksharedconfig.h>
+
+#include <interfaces/iuicontroller.h>
+#include <interfaces/iproject.h>
+#include <interfaces/iprojectcontroller.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <project/projectmodel.h>
+#include <interfaces/icore.h>
+#include <veritas/test.h>
+#include <veritas/testtoolviewfactory.h>
+#include "register.h"
+
+#include <QFile>
+#include <KConfigGroup>
+#include <KDebug>
+#include <KProcess>
+
+#include "testroot.h"
+#include "cppunitviewdata.h"
+#include "cppunittesttreebuilder.h"
+
+using KDevelop::IPlugin;
+using KDevelop::IProject;
+using KDevelop::IProjectController;
+
+using Veritas::Test;
+
+using CppUnit::TestRoot;
+using CppUnit::TestSuite;
+
+K_PLUGIN_FACTORY(CppUnitPluginFactory, registerPlugin<CppUnitPlugin>();)
+K_EXPORT_PLUGIN(CppUnitPluginFactory(KAboutData("kdevcppunit","kdevcppunit", ki18n("CppUnit test"), "0.1", ki18n("Support running CppUnit tests"), KAboutData::License_GPL)))
+
+CppUnitPlugin::CppUnitPlugin(QObject* parent, const QVariantList &)
+ : IPlugin(CppUnitPluginFactory::componentData(), parent)
+{
+ KDEV_USE_EXTENSION_INTERFACE( Veritas::ITestFramework );
+ Veritas::TestToolViewFactory* factory = new Veritas::TestToolViewFactory(this);
+ core()->uiController()->addToolView("CppUnit Runner", factory);
+ setXMLFile("kdevcppunit.rc");
+}
+
+CppUnitPlugin::~CppUnitPlugin()
+{
+}
+
+QString CppUnitPlugin::name() const
+{
+ static QString s_name("CppUnit");
+ return s_name;
+}
+
+Veritas::TestRunner* CppUnitPlugin::createRunner()
+{
+ return new CppUnitViewData(this, new CppUnitTestTreeBuilder);
+}
+
+#include "cppunitplugin.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp
___________________________________________________________________
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.h (revision 1522570)
@@ -0,0 +1,41 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CPPUNIT_CPPUNITPLUGIN_H
+#define CPPUNIT_CPPUNITPLUGIN_H
+
+#include <interfaces/iplugin.h>
+#include <veritas/itestframework.h>
+#include <QVariantList>
+
+class CppUnitPlugin : public KDevelop::IPlugin, public Veritas::ITestFramework
+{
+Q_OBJECT
+Q_INTERFACES(Veritas::ITestFramework)
+
+public:
+ explicit CppUnitPlugin(QObject* parent, const QVariantList & = QVariantList());
+ virtual ~CppUnitPlugin();
+ virtual Veritas::TestRunner* createRunner();
+ virtual QString name() const;
+ virtual QWidget* createConfigWidget() { return 0; }
+};
+
+#endif // CPPUNIT_CPPUNITPLUGIN_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitplugin.h
___________________________________________________________________
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp (revision 1522570)
@@ -0,0 +1,75 @@
+/*
+* KDevelop CPPUnit integration
+* Copyright 2009 Andrew Coles <andrew_coles@yahoo.co.uk
+*
+* 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "cppunittesttreebuilder.h"
+#include <interfaces/iproject.h>
+#include <KSharedConfig>
+#include <KConfigGroup>
+#include <QtCore/QString>
+
+using namespace KDevelop;
+using namespace Veritas;
+using namespace CppUnit;
+
+CppUnitTestTreeBuilder::CppUnitTestTreeBuilder() : reg(0), m_root(0) {};
+
+CppUnitTestTreeBuilder::~CppUnitTestTreeBuilder() {
+ delete reg;
+}
+
+void CppUnitTestTreeBuilder::reload(KDevelop::IProject* project) {
+ delete reg;
+ reg = new Register<TestRoot, TestSuite>;
+ KUrl testExe = KUrl(fetchExe(project));
+ if (testExe.isEmpty()) {
+// emit reloadFailed();
+ return;
+ }
+ reg->addFromExe(testExe);
+ reg->rootItem()->setExecutable(testExe.path());
+ m_root = reg->rootItem();
+/* if (m_root) {
+ emit reloadFinished(m_root);
+ } else {
+ emit reloadFailed();
+ }*/
+};
+
+QString CppUnitTestTreeBuilder::fetchExe(KDevelop::IProject* project)
+{
+ if (project == 0) return QString();
+ KSharedConfig::Ptr cfg = project->projectConfiguration();
+ KConfigGroup group(cfg.data(), "Veritas");
+ QStringList executables;
+ executables = group.readEntry<QStringList>("executables", executables);
+ if (executables.isEmpty()) return QString();
+ return executables[0];
+}
+
+
+
+Test* CppUnitTestTreeBuilder::root() const
+{
+ Q_ASSERT(m_root);
+ return m_root;
+}
+
+
+#include "cppunittesttreebuilder.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h (revision 1522570)
@@ -0,0 +1,39 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CPPUNIT_CPPUNITVIEWDATA_H
+#define CPPUNIT_CPPUNITVIEWDATA_H
+
+#include <veritas/testrunner.h>
+#include "qxcppunitexport.h"
+
+namespace Veritas { class Test; class ITestFramework; class ITestTreeBuilder; }
+
+/*! Assorted test runner operations and data */
+class QXCPPUNIT_EXPORT CppUnitViewData : public Veritas::TestRunner
+{
+Q_OBJECT
+public:
+ CppUnitViewData(Veritas::ITestFramework* framework, Veritas::ITestTreeBuilder* builder);
+ virtual ~CppUnitViewData();
+};
+
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcppunit.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h (revision 1522570)
@@ -0,0 +1,37 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef QXCPPUNITEXPORT_H
+#define QXCPPUNITEXPORT_H
+
+#include <kdemacros.h>
+
+#ifndef QXCPPUNIT_EXPORT
+# ifdef MAKE_KDEVCPPUNIT_LIB
+# define QXCPPUNIT_EXPORT KDE_EXPORT
+# else
+# define QXCPPUNIT_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif // QXCPPUNIT_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/register.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/register.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/register.h (revision 1522570)
@@ -0,0 +1,215 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CPPUNIT_TESTREGISTER_H
+#define CPPUNIT_TESTREGISTER_H
+
+#include <QtCore/QString>
+#include <QtCore/QFileInfo>
+#include <QtXml/QXmlStreamReader>
+
+#include <veritas/test.h>
+#include "testcase.h"
+#include "qxcppunitexport.h"
+
+class KProcess;
+class QIODevice;
+
+/*!
+ * Retrieves and builds a Test Tree from an external executable's
+ * xml output.
+ *
+ * This class removes bad duplication between the Check
+ * & CppUnit plugins. It might be completely irrelevant for
+ * other frameworks.
+ */
+template<typename R, typename S>
+class QXCPPUNIT_EXPORT Register : public QXmlStreamReader
+{
+public:
+ typedef R TestRoot;
+ typedef S TestSuite;
+
+ Register();
+ virtual ~Register();
+
+ void addFromXml(QIODevice*);
+ void addFromExe(const QFileInfo& exe);
+ void addFromExe(const KUrl& exe);
+ TestRoot* rootItem();
+ void setRootDir(const QString& root);
+ void setExecutable(const QFileInfo& exe);
+
+private: // helpers
+ void execute(KProcess*);
+ bool isStartElement_(const QString& elem);
+ bool isEndElement_(const QString& elem);
+ void processSuite();
+ void processCase(TestSuite* suite);
+ void processCmd(TestCase* caze);
+ QString fetchName();
+ QFileInfo fetchDir();
+ QFileInfo fetchExe();
+
+private: // state
+ TestRoot* m_rootItem;
+ QString m_root;
+ QFileInfo m_exe;
+
+private: // some xml constants
+ const QString c_suite;
+ const QString c_case;
+ const QString c_cmd;
+ const QString c_name;
+};
+
+///// template implementation
+
+#include <KDebug>
+#include <KProcess>
+#include <KLocalizedString>
+
+template<typename R, typename S>
+Register<R,S>::Register()
+ : m_root(""),
+ c_suite("suite"),
+ c_case("case"),
+ c_cmd("command"),
+ c_name("name")
+{}
+
+template<typename R, typename S>
+Register<R,S>::~Register()
+{}
+
+template<typename R, typename S>
+R* Register<R,S>::rootItem()
+{
+ return m_rootItem;
+}
+
+template<typename R, typename S>
+bool Register<R,S>::isStartElement_(const QString& elem)
+{
+ return isStartElement() && (name() == elem);
+}
+
+template<typename R, typename S>
+bool Register<R,S>::isEndElement_(const QString& elem)
+{
+ return isEndElement() && (name() == elem);
+}
+
+template<typename R, typename S>
+void Register<R,S>::addFromExe(const QFileInfo& exe)
+{
+ KProcess* proc = new KProcess;
+ setExecutable(exe);
+ execute(proc);
+ addFromXml(proc);
+}
+
+template<typename R, typename S>
+void Register<R,S>::addFromExe(const KUrl& exe)
+{
+ KProcess* proc = new KProcess;
+ setExecutable(QFileInfo(exe.path()));
+ execute(proc);
+ addFromXml(proc);
+}
+
+template<typename R, typename S>
+void Register<R,S>::execute(KProcess* proc)
+{
+ QStringList argv;
+ argv << "-proto";
+ proc->setProgram(m_exe.filePath(), argv);
+ kDebug() << "executing " << proc->program();
+ proc->setOutputChannelMode(KProcess::SeparateChannels);
+ proc->start();
+ proc->waitForFinished(-1);
+}
+
+template<typename R, typename S>
+void Register<R,S>::addFromXml(QIODevice* dev)
+{
+ m_rootItem = new TestRoot(QList<QVariant>() << "" << "" << "" << "");
+
+ Q_ASSERT(dev != 0);
+ setDevice(dev);
+ if (!device()->isOpen())
+ device()->open(QIODevice::ReadOnly);
+
+ while (!atEnd()) {
+ readNext();
+ if (isStartElement_(c_suite))
+ processSuite();
+ }
+ kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
+}
+
+template<typename R, typename S>
+void Register<R,S>::processSuite()
+{
+ TestSuite* suite = new TestSuite(fetchName(), m_exe, m_rootItem);
+ m_rootItem->addChild(suite);
+ kDebug() << suite->name();
+
+ while (!atEnd() && !isEndElement_(c_suite)) {
+ readNext();
+ if (isStartElement_(c_case))
+ processCase(suite);
+ }
+}
+
+template<typename R, typename S>
+void Register<R,S>::processCase(TestSuite* suite)
+{
+ TestCase* caze = new TestCase(fetchName(), suite);
+ suite->addChild(caze);
+ kDebug() << caze->name();
+ while (!atEnd() && !isEndElement_(c_case)) {
+ readNext();
+ if (isStartElement_(c_cmd))
+ processCmd(caze);
+ }
+}
+
+template<typename R, typename S>
+void Register<R,S>::setExecutable(const QFileInfo& exe)
+{
+ m_exe = exe;
+}
+
+template<typename R, typename S>
+void Register<R,S>::processCmd(TestCase* caze)
+{
+ TestCommand* cmd = new TestCommand(fetchName(), caze);
+ caze->addChild(cmd);
+ kDebug() << cmd->name();
+}
+
+template<typename R, typename S>
+QString Register<R,S>::fetchName()
+{
+ return attributes().value(c_name).toString();
+}
+
+#endif // CPPUNIT_REGISTER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.cpp (revision 1522570)
@@ -0,0 +1,191 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "outputparser.h"
+#include "testroot.h"
+#include <veritas/test.h>
+#include "testcase.h"
+#include <KUrl>
+#include <KDebug>
+
+using Veritas::Test;
+using Veritas::TestResult;
+using CppUnit::TestRoot;
+using CppUnit::OutputParser;
+
+/*example xml:
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<root>
+<suite name="RootSuite">
+ <case name="FooTest">
+ <command name="testCmd1"></command>
+ <command name="testCmd2"></command>
+ </case>
+ <case name="BarTest">
+ <command name="testCmd1"></command>
+ <command name="testCmd2">
+ <status type="assertion" file="/home/nix/KdeDev/kdevelop/plugins/xtest/qxcppunit/tests/fake_sunnysuite.cpp" line="63"/>
+ </command>
+ </case>
+ <case name="BazTest">
+ <command name="testCmd1"></command>
+ </case>
+</suite>
+</root>
+*/
+
+const QString OutputParser::c_suite("suite");
+const QString OutputParser::c_case("case");
+const QString OutputParser::c_command("command");
+const QString OutputParser::c_name("name");
+const QString OutputParser::c_status("status");
+const QString OutputParser::c_type("type");
+const QString OutputParser::c_assertion("assertion");
+const QString OutputParser::c_file("file");
+const QString OutputParser::c_line("line");
+
+#define ENSURE_FOUND(c,p,n) Q_ASSERT_X(c, "hm",\
+ qstrdup((QString("Failed to find ") + n + QString(" as child of ")\
+ + p->name()).toAscii().data()));
+
+
+OutputParser::OutputParser(QIODevice* device)
+ : QXmlStreamReader(device),
+ m_result(0),
+ m_processingSuite(false),
+ m_processingCase(false),
+ m_processingCmd(false)
+{}
+
+OutputParser::~OutputParser()
+{}
+
+bool OutputParser::isStartElement_(const QString& elementName)
+{
+ return isStartElement() && (name() == elementName);
+}
+
+bool OutputParser::isEndElement_(const QString& elementName)
+{
+ return isEndElement() && (name() == elementName);
+}
+
+void OutputParser::go(TestRoot* root)
+{
+ m_root = root;
+ if (!device()->isOpen())
+ device()->open(QIODevice::ReadOnly);
+ if (!device()->isReadable()) {
+ // do something
+ }
+
+ if (m_processingCmd)
+ processCmd();
+ if (m_processingCase)
+ processCase();
+ if (m_processingSuite)
+ processSuite();
+
+ while (!atEnd()) {
+ readNext();
+ if (isStartElement_(c_suite)) {
+ processSuite();
+ }
+ }
+
+ kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
+}
+
+void OutputParser::processSuite()
+{
+ m_processingSuite = true;
+ QString name = fetchName();
+ m_suite = m_root->childNamed(name);
+ ENSURE_FOUND(m_suite, m_root, name);
+ while (!atEnd() && !isEndElement_(c_suite)) {
+ readNext();
+ if (isStartElement_(c_case))
+ processCase();
+ }
+ if (isEndElement_(c_suite))
+ m_processingSuite = false;
+}
+
+void OutputParser::processCase()
+{
+ if (!m_processingCase) {
+ m_currentCase = fetchName();
+ m_case = m_suite->childNamed(m_currentCase);
+ }
+ ENSURE_FOUND(m_case, m_suite, m_currentCase);
+ m_processingCase = true;
+ while (!atEnd() && !isEndElement_(c_case)) {
+ readNext();
+ if (isStartElement_(c_command))
+ processCmd();
+ }
+ if (isEndElement_(c_case))
+ m_processingCase = false;
+}
+
+QString OutputParser::fetchName()
+{
+ return attributes().value(c_name).toString();
+}
+
+void OutputParser::processCmd()
+{
+ if (!m_processingCmd) {
+ m_currentCmd = fetchName();
+ m_cmd = m_case->childNamed(m_currentCmd);
+ ENSURE_FOUND(m_cmd, m_case, m_currentCmd);
+ m_cmd->signalStarted();
+ m_result = new TestResult;
+ }
+ Q_ASSERT(m_cmd);
+ m_processingCmd = true;
+ bool gotFailureMsg = false;
+ while (!atEnd() && !isEndElement_(c_command)) {
+ readNext();
+ if (isStartElement_(c_status)) {
+ gotFailureMsg = true;
+ setFailure();
+ }
+ }
+ if (isEndElement_(c_command)) {
+ m_processingCmd = false;
+ if (!gotFailureMsg)
+ setSuccess();
+ m_cmd->setResult(m_result);
+ m_cmd->signalFinished();
+ }
+}
+
+void OutputParser::setSuccess()
+{
+ m_result->setState(Veritas::RunSuccess);
+}
+
+void OutputParser::setFailure()
+{
+ m_result->setState(Veritas::RunError);
+ m_result->setFile(KUrl(attributes().value(c_file).toString()));
+ m_result->setLine(attributes().value(c_line).toString().toInt());
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QXCPPUNIT_TESTSUITE_H
+#define QXCPPUNIT_TESTSUITE_H
+
+#include <QString>
+#include <QFileInfo>
+#include <KProcess>
+#include <veritas/test.h>
+#include "qxcppunitexport.h"
+
+#include "testcase.h"
+
+namespace CppUnit
+{
+
+/*! Aggregate item in the test tree */
+class QXCPPUNIT_EXPORT TestSuite : public Veritas::Test
+{
+Q_OBJECT
+public:
+ TestSuite();
+ TestSuite(const QString&, const QFileInfo& executable, Veritas::Test* parent);
+ virtual ~TestSuite();
+ TestCase* child(int i) const;
+
+private:
+ QFileInfo m_exe;
+};
+
+} // CppUnit
+
+#endif // QXCPPUNIT_TESTSUITE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.h (revision 1522570)
@@ -0,0 +1,46 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTCASE_H
+#define TESTCASE_H
+
+#include <veritas/test.h>
+#include "testcommand.h"
+#include <QtCore/QString>
+#include "qxcppunitexport.h"
+
+/*!
+ * Item in the test tree that contains TestCommands
+ *
+ * This class removes bad duplication between the Check
+ * & CppUnit plugins. It might be completely irrelevant for
+ * other frameworks.
+ */
+class QXCPPUNIT_EXPORT TestCase : public Veritas::Test
+{
+Q_OBJECT
+public:
+ TestCase(const QString& name, Veritas::Test* parent);
+ virtual ~TestCase();
+ TestCommand* child(int i) const;
+};
+
+
+#endif // TESTCASE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.h (revision 1522570)
@@ -0,0 +1,43 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef TESTCOMMAND_H
+#define TESTCOMMAND_H
+
+#include <veritas/test.h>
+#include <QtCore/QString>
+#include "qxcppunitexport.h"
+
+/*!
+ * Leaf item in the test tree.
+ *
+ * This class removes bad duplication between the Check
+ * & CppUnit plugins. It might be completely irrelevant for
+ * other frameworks.
+ */
+class VERITAS_EXPORT TestCommand : public Veritas::Test
+{
+Q_OBJECT
+public:
+ TestCommand(const QString& name, Veritas::Test* parent);
+ virtual ~TestCommand();
+};
+
+#endif // TESTCOMMAND_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.h (revision 1522570)
@@ -0,0 +1,53 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CPPUNIT_TESTROOT_H
+#define VERITAS_CPPUNIT_TESTROOT_H
+
+#include <QString>
+#include <QFileInfo>
+
+#include <veritas/test.h>
+#include "testsuite.h"
+#include "qxcppunitexport.h"
+
+namespace CppUnit
+{
+
+/*! Prime item in the test tree responsible for calling
+the executable */
+class QXCPPUNIT_EXPORT TestRoot : public Veritas::Test
+{
+Q_OBJECT
+public:
+ TestRoot(const QList<QVariant>& data);
+ virtual ~TestRoot();
+ TestSuite* child(int i) const;
+ void setExecutable(const QFileInfo& e) { m_exe = e; }
+ int run();
+ bool shouldRun() const;
+
+private:
+ QFileInfo m_exe;
+};
+
+} // end namespace Check
+
+#endif // VERITAS_CPPUNIT_TESTROOT_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/outputparser.h (revision 1522570)
@@ -0,0 +1,91 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QXCPPUNIT_CPPUNITOUTPUTPARSER
+#define QXCPPUNIT_CPPUNITOUTPUTPARSER
+
+#include <QXmlStreamReader>
+#include <veritas/testresult.h>
+
+class QIODevice;
+
+namespace Veritas { class Test; }
+
+namespace CppUnit
+{
+
+class TestRoot;
+
+/*! Parses CppUnit XML output into TestResults */
+class OutputParser : public QXmlStreamReader
+{
+public:
+ OutputParser(QIODevice* device);
+ virtual ~OutputParser();
+
+ /**
+ * Start parsing and emit results
+ **/
+ void go(TestRoot*);
+
+private: // helpers
+ void processSuite();
+ void processCase();
+ void processCmd();
+ void setFailure();
+ void setSuccess();
+ QString fetchName();
+
+ inline bool isStartElement_(const QString& elem);
+ inline bool isEndElement_(const QString& elem);
+
+private: // state
+ Veritas::TestResult* m_result;
+
+ // remember state to continue when parsing
+ // incrementally
+ bool m_processingSuite;
+ bool m_processingCase;
+ bool m_processingCmd;
+
+ QString m_currentSuite;
+ QString m_currentCase;
+ QString m_currentCmd;
+
+ TestRoot* m_root;
+ Veritas::Test* m_suite;
+ Veritas::Test* m_case;
+ Veritas::Test* m_cmd;
+
+private: // some xml constants
+ static const QString c_suite;
+ static const QString c_case;
+ static const QString c_command;
+ static const QString c_name;
+ static const QString c_status;
+ static const QString c_type;
+ static const QString c_assertion;
+ static const QString c_file;
+ static const QString c_line;
+};
+
+} // namespace CppUnit
+
+#endif // QXCPPUNIT_CPPUNITOUTPUTPARSER
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h (revision 1522570)
@@ -0,0 +1,231 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+/*!
+Constructs a compatible CppUnit executable from CppUnit::TestSuite(s)
+through main macro's. See CPPUNIT_VERITAS_MAIN.
+This header is intended for users of the runner, not a part of the
+cppunit plugin.
+*/
+
+#ifndef CPPUNIT_WRAPPER_H
+#define CPPUNIT_WRAPPER_H
+
+#include <exception>
+#include <vector>
+#include <cppunit/TestCase.h>
+#include <cppunit/TestPath.h>
+#include <cppunit/TestSuite.h>
+#include <cppunit/TestRunner.h>
+#include <cppunit/TestResult.h>
+#include <cppunit/TestFailure.h>
+#include <cppunit/TestListener.h>
+
+//
+// CppUnit's terminology is a tad different from
+// the standard way of naming things.
+//
+// The following mapping is used:
+// CppUnit --> xTest
+// TestCase --> TestCommand
+// TestSuite (with case children) --> TestCase
+// TestSuite (without case children) --> TestSuite
+//
+
+namespace CppUnit
+{
+
+static inline bool isSuite(CppUnit::Test* test)
+{
+ CppUnit::TestSuite* suite = dynamic_cast<CppUnit::TestSuite*>(test);
+ if (!suite || suite->getChildTestCount() == 0)
+ return false;
+ CppUnit::Test* child = suite->getChildTestAt(0);
+ CppUnit::TestCase* caze = dynamic_cast<CppUnit::TestCase*>(child);
+ return (caze == 0); // no testcase children, ie a pure suite
+}
+
+static inline bool isCase(CppUnit::Test* test)
+{
+ CppUnit::TestSuite* suite = dynamic_cast<CppUnit::TestSuite*>(test);
+ if (!suite) {
+ return false;
+ }
+ if (suite->getChildTestCount() == 0) {
+ return true;
+ }
+ CppUnit::Test* child = suite->getChildTestAt(0);
+ CppUnit::TestCase* caze = dynamic_cast<CppUnit::TestCase*>(child);
+ return (caze != 0);
+}
+
+static inline bool isCommand(CppUnit::Test* test)
+{
+ CppUnit::TestCase* cmd = dynamic_cast<CppUnit::TestCase*>(test);
+ return (cmd != 0);
+}
+
+static inline const char* tagFor(CppUnit::Test* test)
+{
+ static const char* suite = "suite";
+ static const char* caze = "case";
+ static const char* cmd = "command";
+ static const char* unkw = "unknown";
+ const char* tag;
+ if (isSuite(test)) {
+ tag = suite;
+ } else if (isCase(test)) {
+ tag = caze;
+ } else if (isCommand(test)) {
+ tag = cmd;
+ } else {
+ tag = unkw;
+ }
+ return tag;
+}
+
+// recursivly print the test structure as XML
+static inline void printTestTree(CppUnit::Test* test)
+{
+ const char* tag = tagFor(test);
+ int nrofChilds = test->getChildTestCount();
+ if (nrofChilds == 0) {
+ printf("<%s name=\"%s\" />\n", tag, test->getName().c_str());
+ } else {
+ printf("<%s name=\"%s\" >\n", tag, test->getName().c_str());
+ for (int i = 0; i < nrofChilds; i++) {
+ printTestTree(test->getChildTestAt(i));
+ }
+ printf("</%s>\n", tag);
+ }
+}
+
+class XMLProgressListener : public CppUnit::TestListener
+{
+public:
+ XMLProgressListener() {};
+ virtual ~XMLProgressListener() {};
+
+ virtual void startTest(CppUnit::Test *test) {
+ printf("<command name=\"%s\">\n", test->getName().c_str());
+ }
+
+ virtual void addFailure(const CppUnit::TestFailure &failure) {
+ CppUnit::SourceLine loc = failure.sourceLine();
+ printf("<status type=\"%s\" file=\"%s\" line=\"%d\"/>\n",
+ (failure.isError() ? "error" : "assertion"),
+ loc.fileName().c_str(),
+ loc.lineNumber());
+ }
+
+ virtual void endTest(CppUnit::Test*) {
+ printf("</command>\n");
+ }
+
+ virtual void startSuite(CppUnit::Test* test) {
+ printf("<%s name=\"%s\">\n", tagFor(test), test->getName().c_str());
+ }
+
+ virtual void endSuite(CppUnit::Test *test) {
+ printf("</%s>\n", tagFor(test));
+ }
+
+private:
+ XMLProgressListener(const XMLProgressListener &copy);
+ void operator=(const XMLProgressListener &copy);
+
+};
+
+static inline void runTest(CppUnit::Test* root)
+{
+ CppUnit::TestResult testresult;
+ CppUnit::XMLProgressListener progress;
+ testresult.addListener(&progress);
+ CppUnit::TestRunner testrunner;
+ testrunner.addTest(root);
+ testrunner.run(testresult);
+}
+
+template<typename T>
+static inline void runAllTests(T suites, int argc, char **)
+{
+ printf("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
+ "<root>\n");
+ if (argc == 1) {
+ // run evrything
+ typename T::const_iterator it;
+ for (it=suites.begin(); it!=suites.end(); it++) {
+ runTest(*it);
+ }
+ } else {
+// try {
+// for (int i = 1; i < argc; i++) {
+// CppUnit::TestPath path;
+// path = root->resolveTestPath(argv[i]);
+// runTest(path.getChildTest());
+// }
+// } catch (std::exception& exc) {
+// printf("<error message=\"%s\" />\n", exc.what());
+// } catch (...) {
+// printf("<error message=\"unknown exception occurred in client test code\"/>\n");
+// }
+ }
+ printf("</root>\n");
+}
+
+template<typename T>
+static inline void printAllTests(T suites)
+{
+ printf("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
+ "<root>\n");
+ typename T::const_iterator it;
+ for (it=suites.begin(); it!= suites.end(); it++) {
+ printTestTree(*it);
+ }
+ printf("</root>\n");
+}
+
+#define CPPUNIT_VERITAS_MAIN( root ) \
+int main(int argc, char** argv)\
+{\
+ std::vector<CppUnit::Test*> suites;\
+ suites.push_back(root);\
+ if (argc == 1 || argv[1][0] != '-') { \
+ CppUnit::runAllTests(suites, argc, argv); \
+ } else { \
+ CppUnit::printAllTests(suites); \
+ }\
+ return 0;\
+}
+
+#define CPPUNIT_VERITAS_MAIN_( suites ) \
+int main(int argc, char** argv)\
+{\
+ if (argc == 1 || argv[1][0] != '-') { \
+ CppUnit::runAllTests(suites, argc, argv); \
+ } else { \
+ CppUnit::printAllTests(suites); \
+ }\
+ return 0;\
+}
+
+} // namespace CppUnit
+
+#endif // CPPUNIT_WRAPPER
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testroot.cpp (revision 1522570)
@@ -0,0 +1,70 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testroot.h"
+#include "outputparser.h"
+#include <QDir>
+#include <KDebug>
+#include <KProcess>
+
+
+using Veritas::Test;
+
+using CppUnit::TestRoot;
+using CppUnit::TestSuite;
+using CppUnit::OutputParser;
+
+TestRoot::TestRoot(const QList<QVariant>& data)
+ : Test(data, 0)
+{}
+
+TestRoot::~TestRoot()
+{}
+
+bool TestRoot::shouldRun() const
+{
+ return true;
+}
+
+TestSuite* TestRoot::child(int i) const
+{
+ Test* child = Test::child(i);
+ TestSuite* suite = qobject_cast<TestSuite*>(child);
+ kWarning(suite==0) << "cast failed? " << name() << " "
+ << i << " " << ((child!=0) ? child->name() : "null");
+ return suite;
+}
+
+int TestRoot::run()
+{
+ KProcess proc;
+ QStringList argv;
+ proc.setProgram(m_exe.filePath(), argv);
+ kDebug() << "executing " << proc.program();
+ proc.setOutputChannelMode(KProcess::SeparateChannels);
+ proc.start();
+ proc.waitForFinished(-1);
+ OutputParser parser(&proc);
+ parser.go(this);
+ emit executionFinished();
+ return 0;
+}
+
+#include "testroot.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcase.cpp (revision 1522570)
@@ -0,0 +1,37 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testcase.h"
+
+using Veritas::Test;
+
+TestCase::TestCase(const QString& name, Test* parent)
+ : Test(name, parent)
+{}
+
+TestCase::~TestCase()
+{}
+
+TestCommand* TestCase::child(int i) const
+{
+ return static_cast<TestCommand*>(Test::child(i));
+}
+
+#include "testcase.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testcommand.cpp (revision 1522570)
@@ -0,0 +1,32 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testcommand.h"
+
+using Veritas::Test;
+
+TestCommand::TestCommand(const QString& name, Test* parent)
+ : Test(name, parent)
+{}
+
+TestCommand::~TestCommand()
+{}
+
+#include "testcommand.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/testsuite.cpp (revision 1522570)
@@ -0,0 +1,45 @@
+/* KDevelop xUnit plugin
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "testsuite.h"
+#include "outputparser.h"
+#include <KDebug>
+
+using CppUnit::TestSuite;
+using CppUnit::OutputParser;
+using Veritas::Test;
+
+TestSuite::TestSuite()
+ : Test("", 0)
+{}
+
+TestSuite::TestSuite(const QString& name, const QFileInfo& exe, Test* parent)
+ : Test(name, parent), m_exe(exe)
+{}
+
+TestSuite::~TestSuite()
+{}
+
+TestCase* TestSuite::child(int i) const
+{
+ return static_cast<TestCase*>(Test::child(i));
+}
+
+#include "testsuite.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
___________________________________________________________________
Added: svn:mime-type
## -0,0 +1 ##
+application/octet-stream
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
___________________________________________________________________
Added: svn:mime-type
## -0,0 +1 ##
+application/octet-stream
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc (revision 1522570)
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/icons" >
+ <file>qxcppunit_16x16.png</file>
+ </qresource>
+</RCC>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/mainpage_
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/mainpage_ (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/mainpage_ (revision 1522570)
@@ -0,0 +1,144 @@
+/*!
+ * \file mainpage.h
+ *
+ * \brief Contains documentation.
+ *
+ * This file contains text and doxygen formatting commands for the
+ * \ref main "Main Page" and other parts of the API documentation.
+ */
+
+/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
+
+/*!
+\page license License
+\verbatim
+
+QxCppUnit Library
+Copyright (C) 2006 systest.ch
+
+This library is free software; you can redistribute it and/or modify it under
+the terms of the GNU Lesser General Public License as published by the Free
+Software Foundation; either version 2.1 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 Lesser General Public License for more
+details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library; if not, write to the Free Software Foundation, Inc.,
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+\endverbatim
+*/
+
+
+namespace QxCppUnit { // Enables doxygen to create links to documented items
+
+
+/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
+
+/*!
+\mainpage
+
+\image html qxcppunit_64x64.png
+
+<!------------------------------------------------------------------->
+
+\section intro Introduction
+
+The QxCppUnit library provides a GUI frontend for CppUnit test execution.
+It is based on the QxRunner and Qt libraries. It can be used to unit test
+any kind of C++ software, it's not limited to Qt applications.
+
+This library is just a thin wrapper around the QxRunner library.
+Actually the idea to write a Qt test runner with a user-friendly GUI
+led to the development of the QxRunner library.
+
+The QxCppUnit library mainly consists of the CppUnitItem class, which
+subclasses QxRunner::RunnerItem, and the CppUnitModel class derived from
+QxRunner::RunnerModel. The TestRunner class populates a CppUnitModel
+instance with CppUnitItem objects and uses a QxRunner::Runner instance
+to show the GUI on the screen.
+
+To write a GUI test runner for CppUnit just the TestRunner class
+is needed as described in the \ref examples page.
+*/
+
+/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
+
+/*!
+\page implementation_ascpects Implementation Aspects
+
+<!------------------------------------------------------------------->
+
+\section symbols Exported Symbols
+
+This applies for the Win32 world only. By default symbols of the library
+are 'hidden' when created as a DLL. Therefore symbols, in particular
+classes, that must be accessible from the outside of the library are
+exported with the QXCPPUNIT_EXPORT macro:
+
+\code
+class QXCPPUNIT_EXPORT TestRunner
+{
+public: // Operations
+ ...
+\endcode
+
+Only the TestRunner class is exported right now, the other classes are
+for internal use only. This might be reconsidered in the future and more
+classes could become exported to be used somewhere outside the library.
+
+<!------------------------------------------------------------------->
+
+\section result_types Result Types
+
+See the CppUnitModel class for the result types handled by the library.
+*/
+
+/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
+
+/*!
+\namespace QxCppUnit
+
+\brief Namespace for the QxCppUnit library entities.
+
+\namespace QxRunner
+
+\brief Namespace of the
+<a target="_blank" href="http://qxrunner.systest.ch">QxRunner Library</a>.
+
+\namespace CPPUNIT_NS
+
+\brief The CppUnit library exposes its classes in the CPPUNIT_NS namespace.
+*/
+
+/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
+
+/*!
+\page examples Examples
+
+The demo program shipped with the QxCppUnit library can be used as the
+starting point for writing a GUI test runner for CppUnit. It has some
+CppUnit test fixtures with simple test cases which succeed or fail and
+uses a TestRunner instance in the main program to launch the GUI.
+
+\section demo_test_example A CppUnit Test Example
+
+This is one of the test fixtures of the demo program. Of course this is a
+very simple test and only used for demonstration purposes. It isn't
+intended to show how to write CppUnit tests.
+
+\includelineno testexamples2.cpp
+
+\section demo_main The Demo Main Program
+
+The main program is straightforward:
+
+\includelineno main.cpp
+*/
+
+} // namespace
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevCppUnit" version="1">
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop (revision 1522570)
@@ -0,0 +1,85 @@
+[Desktop Entry]
+Encoding=UTF-8
+Type=Service
+Exec=blubb
+Comment=CSharp Language Support
+Comment[bs]=CSharp jezička podrška
+Comment[ca]=Implementació del llenguatge CSharp
+Comment[ca@valencia]=Implementació del llenguatge CSharp
+Comment[de]=Sprachunterstützung für CSharp
+Comment[el]=Υποστήριξη γλώσσας CSharp
+Comment[en_GB]=CSharp Language Support
+Comment[es]=Implementación del lenguaje CSharp
+Comment[et]=CSharpi keele toetus
+Comment[fr]=Prise en charge du langage C#
+Comment[ga]=Tacaíocht C#
+Comment[gl]=Compatibilidade coa linguaxe CSharp
+Comment[hne]=सी# भाखा समर्थन
+Comment[it]=Supporto per il linguaggio CSharp
+Comment[ja]=CSharp 言語のサポート
+Comment[nds]=Ünnerstütten för C-Sharp
+Comment[nl]=Ondersteuning voor de taal CSharp
+Comment[pl]=Obsługa języka CSharp
+Comment[pt]=Suporte à Linguagem C#
+Comment[pt_BR]=Suporte à linguagem CSharp
+Comment[sv]=Stöd för språket C#
+Comment[tr]=CSharp Dil Desteği
+Comment[uk]=Підтримка мови C#
+Comment[x-test]=xxCSharp Language Supportxx
+Name=CSharp Support
+Name[bs]=CSharp podrška
+Name[ca]=Implementació de CSharp
+Name[ca@valencia]=Implementació de CSharp
+Name[de]=Unterstützung für CSharp
+Name[en_GB]=CSharp Support
+Name[es]=Implementación de CSharp
+Name[et]=CSharpi toetus
+Name[fr]=Prise en charge de CSharp
+Name[ga]=Tacaíocht C#
+Name[gl]=Compatibilidade con CSharp
+Name[hu]=CSharp támogatás
+Name[it]=Supporto per CSharp
+Name[nl]=Ondersteuning voor CSharp
+Name[pl]=Obsługa CSharp
+Name[pt]=Suporte a C#
+Name[pt_BR]=Suporte a CSharp
+Name[sv]=C#-stöd
+Name[ug]=CSharp قوللىشى
+Name[uk]=Підтримка CSharp
+Name[x-test]=xxCSharp Supportxx
+GenericName=CSharp Support
+GenericName[bs]=CSharp podrška
+GenericName[ca]=Implementació de CSharp
+GenericName[ca@valencia]=Implementació de CSharp
+GenericName[de]=Unterstützung für CSharp
+GenericName[el]=Υποστήριξη CSharp
+GenericName[en_GB]=CSharp Support
+GenericName[es]=Implementación de CSharp
+GenericName[et]=CSharpi toetus
+GenericName[fr]=Prise en charge du langage C#
+GenericName[ga]=Tacaíocht C#
+GenericName[gl]=Compatibilidade con CSharp
+GenericName[hne]=केडेवसीसार्पसपोर्ट
+GenericName[hu]=CSharp támogatás
+GenericName[it]=Supporto per CSharp
+GenericName[ja]=CSharp サポート
+GenericName[nds]=C-Sharp-Ünnerstütten
+GenericName[nl]=Ondersteuning voor CSharp
+GenericName[pl]=Obsługa CSharp
+GenericName[pt]=Suporte a C#
+GenericName[pt_BR]=Suporte a CSharp
+GenericName[sv]=C#-stöd
+GenericName[tr]=CSharp Desteği
+GenericName[ug]=CSharp قوللىشى
+GenericName[uk]=Підтримка CSharp
+GenericName[x-test]=xxCSharp Supportxx
+ServiceTypes=KDevelop/Plugin
+Icon=source
+X-KDE-Library=kdevcsharplanguagesupport
+X-KDE-PluginInfo-Name=kdevcsharplanguagesupport
+X-KDevelop-Version=7
+X-KDevelop-Language=C#
+X-KDevelop-Args=C#
+X-KDevelop-Interfaces=ILanguageSupport
+X-KDevelop-SupportedMimeTypes=text/x-csharp
+X-KDevelop-Mode=NoGUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp (revision 1522570)
@@ -0,0 +1,338 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "typebuilder.h"
+
+#include <ktexteditor/smartrange.h>
+
+#include "editorintegrator.h"
+#include "parsesession.h"
+#include "declarationbuilder.h"
+//#define DEBUG
+
+#ifdef DEBUG
+#define ifDebug(x) x;
+#else
+#define ifDebug(x)
+#endif
+
+using namespace KDevelop;
+
+namespace CSharp {
+
+StructureType* TypeBuilder::openClass(bool interface, bool /*parameters*/)
+{
+ Q_UNUSED(interface);
+
+ StructureType* classType = /*parameters ? new ParameterizedType() :*/ new StructureType();
+
+ //classType->setClassType(interface ? StructureType::Interface : StructureType::Class);
+
+ return classType;
+}
+
+void TypeBuilder::visitIntegralType(IntegralTypeAst *node)
+{
+ bool openedType = false;
+
+ if (node) {
+ uint type = IntegralType::TypeNone;
+ uint modifiers = AbstractType::NoModifiers;
+
+ switch (node->type) {
+ case PredefinedType::TypeBool:
+ type = IntegralType::TypeBoolean;
+ break;
+ case PredefinedType::TypeByte:
+ type = IntegralType::TypeByte;
+ break;
+ case PredefinedType::TypeChar:
+ type = IntegralType::TypeChar;
+ break;
+ case PredefinedType::TypeDecimal:
+ type = CustomIntegrals::TypeDecimal;
+ break;
+ case PredefinedType::TypeDouble:
+ type = IntegralType::TypeDouble;
+ break;
+ case PredefinedType::TypeFloat:
+ type = IntegralType::TypeFloat;
+ break;
+ case PredefinedType::TypeInt:
+ type = IntegralType::TypeInt;
+ break;
+ case PredefinedType::TypeLong:
+ type = IntegralType::TypeLong;
+ break;
+ case PredefinedType::TypeObject:
+ type = CustomIntegrals::TypeObject;
+ break;
+ case PredefinedType::TypeSbyte:
+ type = IntegralType::TypeSbyte;
+ break;
+ case PredefinedType::TypeShort:
+ type = IntegralType::TypeShort;
+ break;
+ case PredefinedType::TypeString:
+ type = IntegralType::TypeString;
+ break;
+ case PredefinedType::TypeUint:
+ type = IntegralType::TypeInt;
+ modifiers |= AbstractType::UnsignedModifier;
+ break;
+ case PredefinedType::TypeUlong:
+ type = IntegralType::TypeLong;
+ modifiers |= AbstractType::UnsignedModifier;
+ break;
+ case PredefinedType::TypeUshort:
+ type = IntegralType::TypeShort;
+ modifiers |= AbstractType::UnsignedModifier;
+ break;
+ default:
+ break;
+ }
+
+ IntegralType::Ptr integral(new IntegralType(type));
+ integral->setModifiers( modifiers );
+
+ openedType = true;
+ openType(integral);
+ }
+
+ TypeBuilderBase::visitIntegralType(node);
+
+ if (openedType)
+ closeType();
+}
+
+void TypeBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
+{
+ visitNode(node->returnType);
+
+ FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType());
+ functionType->setModifiers( parseModifiers(node->modifiers) );
+
+ if (lastType())
+ functionType->setReturnType(lastType());
+
+ openType(functionType);
+
+ TypeBuilderBase::visitMethodDeclaration(node);
+
+ closeType();
+}
+
+void TypeBuilder::visitTypeName(TypeNameAst *node)
+{
+ TypeBuilderBase::visitTypeName(node);
+
+ if (openTypeFromName(identifierForNode(node->typeName), node, true))
+ closeType();
+}
+
+#if 0
+void TypeBuilder::visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node)
+{
+ visitNode(node->returnType);
+
+ FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType(parseModifiers(node->modifiers)));
+
+ if (lastType())
+ functionType->setReturnType(lastType());
+
+ openType(functionType);
+
+ TypeBuilderBase::visitInterfaceMethodDeclaration(node);
+
+ closeType();
+}
+#endif
+
+void TypeBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
+{
+ // TODO set constructor type
+
+ FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType());
+ functionType->setModifiers( parseModifiers(node->modifiers) );
+
+ if (lastType())
+ functionType->setReturnType(lastType());
+
+ openType(functionType);
+
+ TypeBuilderBase::visitConstructorDeclaration(node);
+
+ closeType();
+}
+
+void TypeBuilder::visitClassDeclaration(ClassDeclarationAst *node)
+{
+ StructureType::Ptr classType = StructureType::Ptr(openClass(false, node->typeParameters));
+
+ openType(classType);
+
+ classTypeOpened( currentAbstractType() ); //This callback is needed, because the type of the class-declaration needs to be set early so the class can be referenced from within itself
+
+ TypeBuilderBase::visitClassDeclaration(node);
+
+ closeType();
+}
+
+#if 0
+void TypeBuilder::visitInterfaceDeclaration(InterfaceDeclarationAst * node)
+{
+ StructureType::Ptr classType = StructureType::Ptr(openClass(true, node->typeParameters));
+
+ openType(classType);
+
+ classTypeOpened( TypeRepository::self()->registerType(currentAbstractType()) ); //This callback is needed, because the type of the class-declaration needs to be set early so the class can be referenced from within itself
+
+ TypeBuilderBase::visitInterfaceDeclaration(node);
+
+ // Prevent additional elements being added if this becomes the current type again
+ classType->close();
+
+ closeType();
+}
+
+bool TypeBuilder::nodeValid(AstNode* node) const
+{
+ return node && node->startToken <= node->endToken;
+}
+
+void TypeBuilder::visitOptionalArrayBuiltInType(OptionalArrayBuiltInTypeAst * node)
+{
+ visitNode(node->type);
+
+ if (nodeValid(node->declaratorBrackets)) {
+ ArrayType::Ptr array(new ArrayType());
+
+ array->setElementType(lastType());
+
+ if( node->declaratorBrackets ) {
+ array->setDimension(node->declaratorBrackets->bracketCount);
+ } else {
+ array->setDimension(0);
+ }
+
+ injectType(array);
+ }
+}
+
+void TypeBuilder::visitTypeArgument(TypeArgumentAst * node)
+{
+ //node->
+
+ TypeBuilderBase::visitTypeArgument(node);
+}
+#endif
+
+uint TypeBuilder::parseModifiers(OptionalModifiersAst * node) const
+{
+ uint modifiers = AbstractType::NoModifiers;
+
+ if (node->modifiers & Modifiers::ModNew)
+ modifiers |= AbstractType::NewModifier;
+ if (node->modifiers & Modifiers::ModSealed)
+ modifiers |= AbstractType::SealedModifier;
+ // TODO
+ //if (node->modifiers & Modifiers::ModVirtual)
+ //modifiers |= AbstractType::
+ if (node->modifiers & Modifiers::ModVolatile)
+ modifiers |= AbstractType::VolatileModifier;
+ // TODO
+ //if (node->modifiers & Modifiers::ModExtern)
+ //modifiers |= AbstractType::;
+ if (node->modifiers & Modifiers::ModUnsafe)
+ modifiers |= AbstractType::UnsafeModifier;
+ if (node->modifiers & Modifiers::ModFixed)
+ modifiers |= AbstractType::FixedModifier;
+
+ // TODO Move to Declaration Builder
+ //if (node->modifiers & Modifiers::ModAbstract)
+ //modifiers |= AbstractType::AbstractModifier;
+ //if (node->modifiers & Modifiers::ModStatic)
+ //modifiers |= AbstractType::StaticModifier;
+ //if (node->modifiers & Modifiers::ModOverride)
+ //modifiers |= AbstractType::OverrideModifier;
+ //if (node->modifiers & Modifiers::ModReadonly)
+ //modifiers |= AbstractType::ReadonlyModifier;
+
+ return modifiers;
+}
+
+#if 0
+void TypeBuilder::visitClassExtendsClause(ClassExtendsClauseAst * node)
+{
+ m_rememberClassNames.clear();
+
+ TypeBuilderBase::visitClassExtendsClause(node);
+
+ StructureType* klass = dynamic_cast<StructureType*>(currentAbstractType().data());
+
+ foreach (const StructureType::Ptr& extends, m_rememberClassNames) {
+ // TODO read locking required??
+ if (extends->classType() == StructureType::Interface) {
+ DUChainWriteLocker lock(DUChain::lock());
+ klass->addExtendsClass(extends);
+ } else {
+ // TODO problem reporter
+ kDebug() << "Tried to extend rather than implement an interface";
+ }
+ }
+}
+
+void TypeBuilder::visitClassOrInterfaceTypeName(ClassOrInterfaceTypeNameAst * node)
+{
+ m_currentIdentifier.clear();
+
+ TypeBuilderBase::visitClassOrInterfaceTypeName(node);
+
+ if (openTypeFromName(m_currentIdentifier, node, true))
+ closeType();
+}
+
+void TypeBuilder::visitClassOrInterfaceTypeNamePart(ClassOrInterfaceTypeNamePartAst * node)
+{
+ m_currentIdentifier.push(identifierForNode(node->identifier));
+
+ TypeBuilderBase::visitClassOrInterfaceTypeNamePart(node);
+}
+
+void TypeBuilder::visitImplementsClause(ImplementsClauseAst * node)
+{
+ /*m_rememberClassNames.clear();
+
+ TypeBuilderBase::visitImplements_clause(node);
+
+ StructureType* klass = dynamic_cast<StructureType*>(m_typeStack.top().data());
+
+ foreach (const StructureType::Ptr& interface, m_rememberClassNames) {
+ // TODO read locking required??
+ if (interface->classType() == StructureType::Interface) {
+ DUChainWriteLocker lock(DUChain::lock());
+ klass->addImplementsInterface(interface);
+ } else {
+ // TODO problem reporter
+ kDebug() << "Tried to implement a class rather than an interface";
+ }
+ }*/
+}
+#endif
+
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h (revision 1522570)
@@ -0,0 +1,79 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef TYPEBUILDER_H
+#define TYPEBUILDER_H
+
+#include "contextbuilder.h"
+#include <language/duchain/builders/abstracttypebuilder.h>
+
+#include <language/duchain/declaration.h>
+#include <language/duchain/identifier.h>
+#include <language/duchain/types/alltypes.h>
+
+namespace CSharp {
+
+typedef KDevelop::AbstractTypeBuilder<AstNode, IdentifierAst, CSharp::ContextBuilder> TypeBuilderBase;
+
+namespace CustomIntegrals
+{
+ enum {
+ TypeDecimal = KDevelop::IntegralType::TypeLanguageSpecific,
+ TypeObject
+ };
+}
+
+/**
+ * Create types from an AstNode tree.
+ *
+ * \note This builder overrides visitDeclarator, in order to support
+ * array types; parent classes will not have
+ * their visitDeclarator function called.
+ */
+class TypeBuilder: public TypeBuilderBase
+{
+protected:
+#if 0
+ virtual void visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node);
+ virtual void visitInterfaceDeclaration(InterfaceDeclarationAst *node);
+#endif
+
+ virtual void visitClassDeclaration(ClassDeclarationAst *node);
+ virtual void visitMethodDeclaration(MethodDeclarationAst *node);
+ virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
+
+ virtual void visitIntegralType(IntegralTypeAst *node);
+ virtual void visitTypeName(TypeNameAst *node);
+
+private:
+ bool nodeValid(AstNode* node) const;
+
+ /// @TODO Do we need the argument \e parameters or not?
+ KDevelop::StructureType* openClass(bool interface, bool parameters);
+ KDevelop::FunctionType* openFunction();
+
+ uint parseModifiers(OptionalModifiersAst* node) const;
+
+ QList<KDevelop::StructureType::Ptr> m_rememberClassNames;
+ KDevelop::QualifiedIdentifier m_currentIdentifier;
+};
+
+}
+
+#endif // TYPEBUILDER_H
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h (revision 1522570)
@@ -0,0 +1,81 @@
+/* This file is part of KDevelop
+ Copyright 2006 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef CONTEXTBUILDER_H
+#define CONTEXTBUILDER_H
+
+#include "csharpdefaultvisitor.h"
+
+#include <language/duchain/builders/abstractcontextbuilder.h>
+
+namespace CSharp {
+
+class EditorIntegrator;
+class IdentifierCompiler;
+class ParseSession;
+
+typedef KDevelop::AbstractContextBuilder<AstNode, AstNode> ContextBuilderBase;
+
+/**
+ * A class which iterates the AST to identify contexts.
+ */
+class ContextBuilder: public ContextBuilderBase, protected DefaultVisitor
+{
+public:
+ ContextBuilder();
+ virtual ~ContextBuilder ();
+
+ void setEditor(EditorIntegrator* editor);
+ void setEditor(ParseSession* session);
+
+protected:
+ EditorIntegrator* editor() const;
+
+ virtual void startVisiting( AstNode* node );
+ virtual void setContextOnNode( AstNode* node, KDevelop::DUContext* ctx );
+ virtual KDevelop::DUContext* contextFromNode( AstNode* node );
+ virtual KTextEditor::Range editorFindRange( AstNode* fromRange, AstNode* toRange );
+
+ /**
+ * Compile an identifier for the specified AstNode \a id.
+ *
+ * \note this reference will only be valid until the next time the function
+ * is called, so you need to create a copy (store as non-reference).
+ * @param typeSpecifier a pointer that will eventually be filled with a type-specifier that can be found in the name(for example the return-type of a cast-operator)
+ */
+ virtual KDevelop::QualifiedIdentifier identifierForNode(AstNode* id);
+
+ // Visitors
+ virtual void visitForStatement(ForStatementAst *node);
+ virtual void visitForeachStatement(ForeachStatementAst *node);
+ virtual void visitIfStatement(IfStatementAst *node);
+ virtual void visitClassDeclaration(ClassDeclarationAst *node);
+ virtual void visitMethodDeclaration(MethodDeclarationAst *node);
+ virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
+
+protected:
+ // Variables
+ IdentifierCompiler* m_identifierCompiler;
+ bool m_mapAst;
+};
+
+}
+
+#endif // CONTEXTBUILDER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp (revision 1522570)
@@ -0,0 +1,46 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "usebuilder.h"
+
+#include "editorintegrator.h"
+#include "parsesession.h"
+
+using namespace KTextEditor;
+using namespace KDevelop;
+
+namespace CSharp {
+
+UseBuilder::UseBuilder (ParseSession* session)
+{
+ setEditor(session);
+}
+
+UseBuilder::UseBuilder (EditorIntegrator* editor)
+{
+ setEditor(editor);
+}
+
+void UseBuilder::visitSimpleNameOrMemberAccess(SimpleNameOrMemberAccessAst *node)
+{
+ newUse(node->memberName);
+
+ UseBuilderBase::visitSimpleNameOrMemberAccess(node);
+}
+
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp (revision 1522570)
@@ -0,0 +1,285 @@
+/* This file is part of KDevelop
+ Copyright 2006 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "contextbuilder.h"
+
+#include <language/duchain/duchain.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/duchainlock.h>
+
+#include "parsesession.h"
+#include "editorintegrator.h"
+#include "identifiercompiler.h"
+
+using namespace KTextEditor;
+using namespace KDevelop;
+
+namespace CSharp {
+
+ContextBuilder::ContextBuilder()
+ : m_identifierCompiler(0), m_mapAst(false)
+{
+}
+
+void ContextBuilder::setEditor(EditorIntegrator* editor)
+{
+ m_identifierCompiler = new IdentifierCompiler(editor->parseSession());
+ ContextBuilderBase::setEditor(editor, false);
+}
+
+void ContextBuilder::setEditor(ParseSession* session)
+{
+ EditorIntegrator* e = new EditorIntegrator(session);
+ m_identifierCompiler = new IdentifierCompiler(e->parseSession());
+ ContextBuilderBase::setEditor(e, false);
+}
+
+ContextBuilder::~ContextBuilder ()
+{
+ delete m_identifierCompiler;
+}
+
+void ContextBuilder::startVisiting( AstNode* node )
+{
+ visitNode(node);
+}
+
+void ContextBuilder::setContextOnNode( AstNode* node, KDevelop::DUContext* ctx )
+{
+ node->ducontext = ctx;
+}
+
+KDevelop::DUContext* ContextBuilder::contextFromNode( AstNode* node )
+{
+ return node->ducontext;
+}
+
+EditorIntegrator* ContextBuilder::editor() const
+{
+ return static_cast<EditorIntegrator*>(ContextBuilderBase::editor());
+}
+
+KTextEditor::Range ContextBuilder::editorFindRange( AstNode* fromRange, AstNode* toRange )
+{
+ return editor()->findRange(fromRange, toRange).textRange();
+}
+
+QualifiedIdentifier ContextBuilder::identifierForNode(AstNode* id)
+{
+ if( !id )
+ return QualifiedIdentifier();
+
+ m_identifierCompiler->run(id);
+
+ return m_identifierCompiler->identifier();
+}
+
+void ContextBuilder::visitClassDeclaration(ClassDeclarationAst * node)
+{
+ visitNode(node->attributes);
+ visitNode(node->modifiers);
+
+ //visitNode(node->className);
+ QualifiedIdentifier id = identifierForNode(node->className);
+
+ visitNode(node->typeParameters);
+ visitNode(node->classBase);
+
+ if (node->typeParametersConstraintsSequence)
+ {
+ const KDevPG::ListNode<TypeParametersConstraintsClauseAst*> *__it = node->typeParametersConstraintsSequence->front(), *__end = __it;
+ do
+ {
+ visitNode(__it->element);
+ __it = __it->next;
+ }
+ while (__it != __end);
+ }
+
+ if (node->body) {
+ openContext(node->body, DUContext::Class, id);
+
+ visitNode(node->body);
+
+ closeContext();
+ }
+}
+
+void ContextBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
+{
+ visitNode(node->attributes);
+ visitNode(node->modifiers);
+ visitNode(node->returnType);
+
+ QualifiedIdentifier id = identifierForNode(node->methodName);
+
+ visitNode(node->typeParameters);
+
+ DUContext* parameters = 0;
+ if (node->formalParameters) {
+ parameters = openContext(node->formalParameters, DUContext::Other, id);
+ id = currentContext()->localScopeIdentifier();
+ visitNode(node->formalParameters);
+ closeContext();
+ }
+
+ if (node->typeParametersConstraintsSequence)
+ {
+ const KDevPG::ListNode<TypeParametersConstraintsClauseAst*> *__it = node->typeParametersConstraintsSequence->front(), *__end = __it;
+ do
+ {
+ visitNode(__it->element);
+ __it = __it->next;
+ }
+ while (__it != __end);
+ }
+
+ DUContext* body = openContext(node->body, DUContext::Function, id);
+ if (parameters) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(parameters);
+ }
+
+ visitNode(node->body);
+
+ closeContext();
+}
+
+void ContextBuilder::visitForStatement(ForStatementAst *node)
+{
+ DUContext* control = 0;
+ if (node->forControl) {
+ control = openContext(node->forControl, DUContext::Other, 0);
+ visitNode(node->forControl);
+ closeContext();
+ }
+
+ if (node->forBody) {
+ DUContext* body = openContext(node->forBody, DUContext::Other, 0);
+ if (control) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(control);
+ }
+ visitNode(node->forBody);
+ closeContext();
+ }
+}
+
+void ContextBuilder::visitForeachStatement(ForeachStatementAst *node)
+{
+ DUContext* control = 0;
+ if (node->variableType) {
+ AstNode* last = node->collection;
+ if (!last) {
+ last = node->variableName;
+ if (!last)
+ last = node->variableType;
+ }
+ control = openContext(node->variableType, last, DUContext::Other, 0);
+
+ visitNode(node->variableType);
+ visitNode(node->variableName);
+ visitNode(node->collection);
+
+ closeContext();
+ }
+
+ if (node->body) {
+ DUContext* body = openContext(node->body, DUContext::Other, 0);
+ if (control) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(control);
+ }
+ visitNode(node->body);
+ closeContext();
+ }
+}
+
+void ContextBuilder::visitIfStatement(IfStatementAst * node)
+{
+ DUContext* condition = 0;
+ if (node->condition) {
+ condition = openContext(node->condition, DUContext::Other, 0);
+ visitNode(node->condition);
+ closeContext();
+ }
+
+ if (node->ifBody) {
+ DUContext* body = openContext(node->ifBody, DUContext::Other, 0);
+
+ if (condition) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(condition);
+ }
+
+ visitNode(node->ifBody);
+ closeContext();
+ }
+
+ if (node->elseBody) {
+ DUContext* body = openContext(node->elseBody, DUContext::Other, 0);
+
+ if (condition) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(condition);
+ }
+
+ visitNode(node->elseBody);
+ closeContext();
+ }
+}
+
+void ContextBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
+{
+ visitNode(node->attributes);
+ visitNode(node->modifiers);
+ //visitNode(node->className);
+
+ QualifiedIdentifier id;
+
+ DUContext* parameters = 0;
+ if (node->formalParameters) {
+ parameters = openContext(node->formalParameters, DUContext::Other, node->className);
+ id = currentContext()->localScopeIdentifier();
+ visitNode(node->formalParameters);
+ closeContext();
+ }
+
+ if (node->constructorInitializer) {
+ DUContext* body = openContext(node->constructorInitializer, node->body ? static_cast<AstNode*>(node->body) : static_cast<AstNode*>(node->constructorInitializer), DUContext::Other, id);
+ if (parameters) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(parameters);
+ }
+ visitNode(node->constructorInitializer);
+ visitNode(node->body);
+ closeContext();
+
+ } else if (node->body) {
+ DUContext* body = openContext(node->body, DUContext::Class, id);
+ if (parameters) {
+ DUChainWriteLocker lock(DUChain::lock());
+ body->addImportedParentContext(parameters);
+ }
+ visitNode(node->body);
+ closeContext();
+ }
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp (revision 1522570)
@@ -0,0 +1,320 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "dumpchain.h"
+
+#include <QtCore/QString>
+#include <QTextStream>
+
+#include <kdebug.h>
+#include <ktexteditor/range.h>
+
+#include <language/duchain/types/identifiedtype.h>
+#include "editorintegrator.h"
+#include <language/duchain/ducontext.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainpointer.h>
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/identifier.h>
+#include <language/duchain/use.h>
+#include "parser/parsesession.h"
+
+using namespace KDevelop;
+using namespace CSharp;
+
+static char const * const names[] = {
+ "BaseAccess",
+ "ConstructorConstraint",
+ "PointerType",
+ "PredefinedType",
+ "PrimarySuffix",
+ "RelationalExpression",
+ "ReturnType",
+ "TypeofExpression",
+ "UnboundtypeName",
+ "UnboundtypeNamePart",
+ "AccessorDeclarations",
+ "AccessorModifier",
+ "AdditiveExpression",
+ "AdditiveExpressionRest",
+ "AnonymousMethodExpression",
+ "AnonymousMethodParameter",
+ "AnonymousMethodSignature",
+ "Argument",
+ "ArrayCreationExpressionRest",
+ "ArrayInitializer",
+ "ArrayType",
+ "Attribute",
+ "AttributeArguments",
+ "AttributeSection",
+ "AttributeTarget",
+ "BitAndExpression",
+ "BitOrExpression",
+ "BitXorExpression",
+ "Block",
+ "BlockStatement",
+ "BooleanExpression",
+ "BreakStatement",
+ "BuiltinClassType",
+ "CastExpression",
+ "CatchClauses",
+ "CheckedStatement",
+ "ClassBase",
+ "ClassBody",
+ "ClassDeclaration",
+ "ClassMemberDeclaration",
+ "ClassOrStructMemberDeclaration",
+ "ClassType",
+ "CompilationUnit",
+ "ConditionalExpression",
+ "ConstantDeclaration",
+ "ConstantDeclarationData",
+ "ConstantDeclarator",
+ "ConstantExpression",
+ "ConstructorDeclaration",
+ "ConstructorInitializer",
+ "ContinueStatement",
+ "ConversionOperatorDeclaration",
+ "DelegateDeclaration",
+ "DoWhileStatement",
+ "EmbeddedStatement",
+ "EnumBase",
+ "EnumBody",
+ "EnumDeclaration",
+ "EnumMemberDeclaration",
+ "EqualityExpression",
+ "EqualityExpressionRest",
+ "EventAccessorDeclaration",
+ "EventDeclaration",
+ "EventaccessorDeclarations",
+ "Expression",
+ "ExternAliasDirective",
+ "FinalizerDeclaration",
+ "FixedPointerDeclarator",
+ "FixedStatement",
+ "FloatingPointType",
+ "ForControl",
+ "ForStatement",
+ "ForeachStatement",
+ "FormalParameter",
+ "FormalParameterList",
+ "GeneralCatchClause",
+ "GenericDimensionSpecifier",
+ "GlobalAttributeSection",
+ "GotoStatement",
+ "Identifier",
+ "IfStatement",
+ "IndexerDeclaration",
+ "IntegralType",
+ "InterfaceAccessors",
+ "InterfaceBase",
+ "InterfaceBody",
+ "InterfaceDeclaration",
+ "InterfaceEventDeclaration",
+ "InterfaceIndexerDeclaration",
+ "InterfaceMemberDeclaration",
+ "InterfaceMethodDeclaration",
+ "InterfacePropertyDeclaration",
+ "Keyword",
+ "LabeledStatement",
+ "Literal",
+ "LocalConstantDeclaration",
+ "LocalVariableDeclaration",
+ "LocalVariableDeclarationStatement",
+ "LockStatement",
+ "LogicalAndExpression",
+ "LogicalOrExpression",
+ "ManagedType",
+ "MethodDeclaration",
+ "MultiplicativeExpression",
+ "MultiplicativeExpressionRest",
+ "NamedArgument",
+ "NamespaceBody",
+ "NamespaceDeclaration",
+ "NamespaceMemberDeclaration",
+ "NamespaceName",
+ "NamespaceOrtypeName",
+ "NamespaceOrtypeNamePart",
+ "NamespaceOrtypeNameSafe",
+ "NewExpression",
+ "NonArrayType",
+ "NonNullableType",
+ "NullCoalescingExpression",
+ "NumericType",
+ "ObjectOrDelegateCreationExpressionRest",
+ "OperatorDeclarationParameter",
+ "OptionalArgumentList",
+ "OptionalAttributeSections",
+ "OptionalModifiers",
+ "OptionalParameterModifier",
+ "OptionallyNullableType",
+ "OverloadableBinaryOnlyOperator",
+ "OverloadableUnaryOnlyOperator",
+ "OverloadableUnaryOrBinaryOperator",
+ "PositionalArgument",
+ "PrimaryAtom",
+ "PrimaryExpression",
+ "PrimaryOrSecondaryConstraint",
+ "PropertyDeclaration",
+ "QualifiedIdentifier",
+ "RankSpecifier",
+ "RelationalExpressionRest",
+ "ResourceAcquisition",
+ "ReturnStatement",
+ "SecondaryConstraint",
+ "ShiftExpression",
+ "ShiftExpressionRest",
+ "SimpleNameOrMemberAccess",
+ "SimpleType",
+ "SpecificCatchClause",
+ "StackallocInitializer",
+ "StatementExpression",
+ "StructBody",
+ "StructDeclaration",
+ "StructMemberDeclaration",
+ "SwitchLabel",
+ "SwitchSection",
+ "SwitchStatement",
+ "ThrowStatement",
+ "TryStatement",
+ "Type",
+ "TypeArguments",
+ "TypeArgumentsOrParametersEnd",
+ "TypeDeclaration",
+ "TypeDeclarationRest",
+ "TypeName",
+ "TypeNameSafe",
+ "TypeParameters",
+ "TypeParametersConstraints",
+ "TypeParametersConstraintsClause",
+ "UnaryExpression",
+ "UnaryOrBinaryOperatorDeclaration",
+ "UncheckedStatement",
+ "UnmanagedType",
+ "UnmanagedTypeSuffix",
+ "UnsafeStatement",
+ "UsingAliasDirectiveData",
+ "UsingDirective",
+ "UsingNamespaceDirectiveData",
+ "UsingStatement",
+ "VariableDeclarationData",
+ "VariableDeclarator",
+ "VariableInitializer",
+ "WhileStatement",
+ "YieldStatement"
+};
+
+DumpChain::DumpChain()
+ : m_editor(0)
+ , indent(0)
+{
+}
+
+void DumpChain::dump( AstNode * node, ParseSession* session)
+{
+ delete m_editor;
+ m_editor = 0;
+
+ Q_ASSERT(session);
+ m_session = session;
+ m_editor = new EditorIntegrator(session);
+
+ visitNode(node);
+}
+
+void DumpChain::visitNode(AstNode *node)
+{
+ QString indentation;
+ for( int a = 0; a < indent; a++ )
+ indentation += "| ";
+
+ if (node) {
+ if (m_editor) {
+ QString nodeText;
+ for( qint64 a = node->startToken; a <= node->endToken; a++ ) {
+ if( !nodeText.isEmpty() )
+ nodeText += ' ';
+ nodeText += m_session->symbol(a);
+ }
+ if( !nodeText.isEmpty() ) nodeText = "\"" + nodeText + "\"";
+
+
+ kDebug() << indentation << "\\" << names[node->kind - 1000]
+ << "[" << node->startToken << m_editor->findPosition(node->startToken, EditorIntegrator::FrontEdge).textCursor() << ", "
+ << node->endToken << m_editor->findPosition(node->endToken, EditorIntegrator::BackEdge).textCursor() << "]" << nodeText << endl;
+ } else {
+ kDebug() << indentation << "\\" << names[node->kind - 1000]
+ << "[" << node->startToken << "," << node->endToken << "]" << endl;
+ }
+ }
+
+ ++indent;
+ DefaultVisitor::visitNode(node);
+ --indent;
+
+ if (node) {
+ if (m_editor) {
+ kDebug() << indentation << "/" << names[node->kind - 1000]
+ << "[(" << node->endToken << ") "/*<< m_editor->findPosition(node->startToken, EditorIntegrator::FrontEdge) << ", "*/
+ << m_editor->findPosition(node->endToken, EditorIntegrator::FrontEdge).textCursor() << "]" << endl;
+ } else {
+ kDebug() << indentation << "/" << names[node->kind - 1000]
+ << "[" << node->startToken << "," << node->endToken << ']' << endl;
+ }
+ }
+}
+
+DumpChain::~ DumpChain( )
+{
+ delete m_editor;
+}
+
+void DumpChain::dump( DUContext * context, bool imported )
+{
+ kDebug() << QString(indent * 2, ' ') << (imported ? "==import==> Context " : "New Context ") << context << "\"" << context->localScopeIdentifier() << "\" [" << context->scopeIdentifier() << "]" << context->range().textRange() << " " << (dynamic_cast<TopDUContext*>(context) ? "top-context" : "");
+ if( !context )
+ return;
+ if (!imported) {
+ foreach (Declaration* dec, context->localDeclarations()) {
+
+ kDebug() << QString((indent+1) * 2, ' ') << "Declaration: " << dec->toString() << /*(idType ? (" (type-identity: " + idType->identifier().toString() + ")") : QString()) <<*/ " [" << dec->qualifiedIdentifier() << "]" << dec << "(internal ctx" << dec->internalContext() << ")" << dec->range().textRange() << "," << (dec->isDefinition() ? "definition, " : "not a definition, ") << dec->uses().count() << "use(s).";
+ QMap<IndexedString, QList<SimpleRange> > uses = dec->uses();
+ for(QMap<IndexedString, QList<SimpleRange> >::const_iterator it = uses.begin(); it != uses.end(); ++it) {
+ kDebug() << QString((indent+2) * 2, ' ') << "File:" << it.key().str();
+ foreach (const SimpleRange& range, *it)
+ kDebug() << QString((indent+2) * 2+1, ' ') << "Use:" << range.textRange();
+ }
+ }
+ }
+
+ ++indent;
+ if (!imported) {
+ ///@todo Think whether this is used for top-contexts, and if it is, prevent endless recursion due to loops
+ foreach (const KDevelop::DUContext::Import& parent, context->importedParentContexts()) {
+ dump(parent.context(context->topContext()), true);
+ }
+
+ foreach (DUContext* child, context->childContexts())
+ dump(child);
+ }
+ --indent;
+}
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp (revision 1522570)
@@ -0,0 +1,140 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "declarationbuilder.h"
+
+#include <QByteArray>
+
+#include <ktexteditor/smartrange.h>
+#include <ktexteditor/smartinterface.h>
+
+#include "editorintegrator.h"
+#include "identifiercompiler.h"
+#include <language/duchain/functiondeclaration.h>
+#include "csharpast.h"
+#include "parsesession.h"
+
+using namespace KTextEditor;
+using namespace KDevelop;
+
+namespace CSharp {
+
+DeclarationBuilder::DeclarationBuilder (ParseSession* session)
+{
+ setEditor(session);
+}
+
+DeclarationBuilder::DeclarationBuilder (EditorIntegrator* editor)
+{
+ setEditor(editor);
+}
+
+void DeclarationBuilder::closeDeclaration()
+{
+ if (currentDeclaration()) {
+ DUChainWriteLocker lock(DUChain::lock());
+
+ currentDeclaration()->setType(lastType());
+ }
+
+ eventuallyAssignInternalContext();
+
+ //kDebug() << "Mangled declaration:" << currentDeclaration()->mangledIdentifier();
+
+ DeclarationBuilderBase::closeDeclaration();
+}
+
+void DeclarationBuilder::visitClassDeclaration(ClassDeclarationAst * node)
+{
+ // TODO csharp-specific class declaration
+ openDefinition<Declaration>(node->className, node);
+
+ currentDeclaration()->setKind(Declaration::Type);
+
+ DeclarationBuilderBase::visitClassDeclaration(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitInterfaceDeclaration(InterfaceDeclarationAst * node)
+{
+ // TODO csharp-specific class declaration
+ openDefinition<Declaration>(node->interfaceName, node);
+
+ currentDeclaration()->setKind(Declaration::Type);
+
+ DeclarationBuilderBase::visitInterfaceDeclaration(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node)
+{
+ openDefinition<ClassFunctionDeclaration>(node->methodName, node);
+
+ currentDeclaration()->setKind(Declaration::Type);
+
+ DeclarationBuilderBase::visitInterfaceMethodDeclaration(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
+{
+ openDefinition<ClassFunctionDeclaration>(node->className, node);
+
+ currentDeclaration()->setKind(Declaration::Type);
+
+ DeclarationBuilderBase::visitConstructorDeclaration(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
+{
+ openDefinition<ClassFunctionDeclaration>(node->methodName, node);
+
+ currentDeclaration()->setKind(Declaration::Type);
+
+ DeclarationBuilderBase::visitMethodDeclaration(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitVariableDeclarator(VariableDeclaratorAst * node)
+{
+ if (currentContext()->type() == DUContext::Class)
+ openDefinition<ClassMemberDeclaration>(node->variableName, node);
+ else
+ openDefinition<Declaration>(node->variableName, node);
+
+ DeclarationBuilderBase::visitVariableDeclarator(node);
+
+ closeDeclaration();
+}
+
+void DeclarationBuilder::visitFormalParameter(FormalParameterAst *node)
+{
+ openDefinition<Declaration>(node->variableName, node);
+
+ DeclarationBuilderBase::visitFormalParameter(node);
+
+ closeDeclaration();
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h (revision 1522570)
@@ -0,0 +1,56 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef DECLARATIONBUILDER_H
+#define DECLARATIONBUILDER_H
+
+#include "typebuilder.h"
+#include <language/duchain/builders/abstractdeclarationbuilder.h>
+
+namespace CSharp {
+
+class ParseSession;
+
+typedef KDevelop::AbstractDeclarationBuilder<AstNode, AstNode, CSharp::TypeBuilder> DeclarationBuilderBase;
+
+/**
+ * A class which iterates the AST to extract definitions of types.
+ */
+class DeclarationBuilder: public DeclarationBuilderBase
+{
+public:
+ DeclarationBuilder(ParseSession* session);
+ DeclarationBuilder(EditorIntegrator* editor);
+
+protected:
+ virtual void closeDeclaration();
+
+ virtual void visitClassDeclaration(ClassDeclarationAst *node);
+ virtual void visitMethodDeclaration(MethodDeclarationAst *node);
+ virtual void visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst *node);
+ virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
+ virtual void visitInterfaceDeclaration(InterfaceDeclarationAst *node);
+ //virtual void visitVariableDeclaration(VariableDeclarationAst *node);
+ virtual void visitVariableDeclarator(VariableDeclaratorAst *node);
+ virtual void visitFormalParameter(FormalParameterAst *node);
+};
+
+}
+
+#endif // DECLARATIONBUILDER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h (revision 1522570)
@@ -0,0 +1,48 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef USEBUILDER_H
+#define USEBUILDER_H
+
+#include "contextbuilder.h"
+
+#include <language/duchain/builders/abstractusebuilder.h>
+
+namespace CSharp {
+
+class ParseSession;
+
+typedef KDevelop::AbstractUseBuilder<AstNode, AstNode, CSharp::ContextBuilder> UseBuilderBase;
+
+/**
+ * A class which iterates the AST to extract uses of definitions.
+ */
+class UseBuilder: public UseBuilderBase
+{
+public:
+ UseBuilder(ParseSession* session);
+ UseBuilder(EditorIntegrator* editor);
+
+protected:
+ virtual void visitSimpleNameOrMemberAccess(SimpleNameOrMemberAccessAst *node);
+};
+
+}
+
+#endif // USEBUILDER_H
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp (revision 1522570)
@@ -0,0 +1,55 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2007 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+//krazy:excludeall=cpp
+
+#include "identifiercompiler.h"
+#include "csharpast.h"
+#include "csharpparser.h"
+#include "parsesession.h"
+
+using namespace KDevelop;
+using namespace CSharp;
+
+IdentifierCompiler::IdentifierCompiler(ParseSession* session)
+ : m_session(session)
+{
+}
+
+void IdentifierCompiler::run(AstNode *node)
+{
+ m_name.clear();
+ visitNode(node);
+}
+
+void IdentifierCompiler::visitIdentifier(IdentifierAst *node)
+{
+ IndexedString id;
+
+ if (node->ident)
+ id = m_session->indexedSymbol(node->ident);
+
+ m_name.push(Identifier(id));
+}
+
+const QualifiedIdentifier& IdentifierCompiler::identifier() const
+{
+ return m_name;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h (revision 1522570)
@@ -0,0 +1,58 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef DUMPCHAIN_H
+#define DUMPCHAIN_H
+
+
+#include "csharpdefaultvisitor.h"
+
+namespace KDevelop
+{
+class DUContext;
+}
+
+namespace CSharp {
+
+class ParseSession;
+
+class DumpChain: protected DefaultVisitor
+{
+public:
+ DumpChain();
+ virtual ~DumpChain();
+
+ void dump(AstNode *node, ParseSession* session = 0);
+
+ void dump(KDevelop::DUContext* context, bool imported = false);
+
+
+protected:
+ virtual void visitNode(CSharp::AstNode *node);
+
+private:
+ class EditorIntegrator* m_editor;
+ ParseSession* m_session;
+ int indent;
+};
+
+}
+
+#endif // DUMPCHAIN_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006-2007 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef NAME_COMPILER_H
+#define NAME_COMPILER_H
+
+#include "csharpdefaultvisitor.h"
+#include <language/duchain/identifier.h>
+#include <language/duchain/declaration.h>
+
+namespace CSharp {
+
+class ParseSession;
+
+class IdentifierCompiler: protected DefaultVisitor
+{
+public:
+ IdentifierCompiler(ParseSession* session);
+
+ void run(AstNode *node);
+
+ const KDevelop::QualifiedIdentifier& identifier() const;
+
+protected:
+ virtual void visitIdentifier(IdentifierAst *node);
+
+private:
+ ParseSession* m_session;
+ KDevelop::QualifiedIdentifier m_name;
+};
+
+}
+
+#endif // NAME_COMPILER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp (revision 1522570)
@@ -0,0 +1,83 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "editorintegrator.h"
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/smartrange.h>
+#include <ktexteditor/smartinterface.h>
+
+#include <language/editor/documentrange.h>
+#include <language/editor/documentrangeobject.h>
+
+#include "csharpast.h"
+#include "parsesession.h"
+
+using namespace KTextEditor;
+using namespace CSharp;
+
+EditorIntegrator::EditorIntegrator( ParseSession* session )
+ : m_session(session)
+{
+}
+
+KDevelop::SimpleCursor EditorIntegrator::findPosition( qint64 token, Edge edge ) const
+{
+ const KDevPG::TokenStream::Token& t = m_session->tokenStream->token(token);
+ return findPosition(t, edge);
+}
+
+KDevelop::SimpleCursor EditorIntegrator::findPosition( const KDevPG::TokenStream::Token & token, Edge edge ) const
+{
+ if(edge == BackEdge)
+ return m_session->positionAt(token.end + 1);
+ else
+ return m_session->positionAt(token.begin + 1);
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange( AstNode * node, RangeEdge edge )
+{
+ Q_UNUSED(edge);
+ return KDevelop::SimpleRange(findPosition(node->startToken, FrontEdge), findPosition(node->endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange( qint64 startToken, qint64 endToken )
+{
+ return KDevelop::SimpleRange(findPosition(startToken, FrontEdge), findPosition(endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(AstNode* from, AstNode* to)
+{
+ return KDevelop::SimpleRange(findPosition(from->startToken, FrontEdge), findPosition(to->endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange( const KDevPG::TokenStream::Token & token )
+{
+ return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
+}
+
+QString EditorIntegrator::tokenToString(qint64 token) const
+{
+ return m_session->symbol(token);
+}
+
+ParseSession * EditorIntegrator::parseSession() const
+{
+ return m_session;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h (revision 1522570)
@@ -0,0 +1,115 @@
+/* This file is part of KDevelop
+ Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef CSHARPEDITORINTEGRATOR_H
+#define CSHARPEDITORINTEGRATOR_H
+
+#include <language/editor/editorintegrator.h>
+#include <language/editor/simplerange.h>
+
+#include "kdev-pg-token-stream.h"
+
+namespace CSharp {
+
+class ParseSession;
+class AstNode;
+
+class EditorIntegrator : public KDevelop::EditorIntegrator
+{
+public:
+ EditorIntegrator(ParseSession* session);
+
+ ParseSession* parseSession() const;
+
+ /**
+ * Finds the location and \a file where the given \a token was parsed from. This function
+ * does not change any of the EditorIntegrator's state.
+ *
+ * \param token token to locate
+ * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
+ *
+ * \returns the requested cursor relating to the start or end of the given token.
+ */
+ KDevelop::SimpleCursor findPosition(const KDevPG::TokenStream::Token& token, Edge edge = BackEdge) const;
+
+ /**
+ * Finds the location and \a file where the given \a token was parsed from.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \param token token to locate
+ * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
+ *
+ * \returns the requested cursor relating to the start or end of the given token.
+ */
+ KDevelop::SimpleCursor findPosition(qint64 token, Edge edge = BackEdge) const;
+
+ using KDevelop::EditorIntegrator::createRange;
+
+ /**
+ * Create a range encompassing the given AstNode \a node.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(AstNode* node, RangeEdge = OuterEdge);
+
+ /**
+ * Create a range encompassing the given AstNode \a nodes.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(AstNode* from, AstNode* to);
+
+ /**
+ * Create a range encompassing the given AstNode \a token.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(const KDevPG::TokenStream::Token& token);
+
+ /**
+ * Create a range encompassing the given AstNode \a token.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(qint64 token);
+
+ /**
+ * Create a range encompassing the given AstNode \a tokens.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(qint64 start_token, qint64 end_token);
+
+ /**
+ * Retrieve the string represented by a token.
+ */
+ QString tokenToString(qint64 token) const;
+
+private:
+ ParseSession* m_session;
+};
+
+}
+
+#endif // CSHARPEDITORINTEGRATOR_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.h (revision 1522570)
@@ -0,0 +1,76 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright (C) 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSHARP_PARSESESSION_H
+#define CSHARP_PARSESESSION_H
+
+#include <QtCore/QByteArray>
+
+#include <csharpparser.h>
+#include <language/editor/simplecursor.h>
+#include <language/duchain/indexedstring.h>
+#include <language/duchain/ducontext.h>
+
+namespace CSharp
+{
+
+typedef QPair<KDevelop::DUContextPointer, KDevelop::SimpleRange> SimpleUse;
+
+/// Contains everything needed to keep an AST useful once the rest of the parser
+/// has gone away.
+class KDEVCSHARPPARSER_EXPORT ParseSession
+{
+public:
+ ParseSession();
+ ~ParseSession();
+
+ /**
+ * Return the position (\a line%, \a column%) of the \a offset in the file.
+ *
+ * \note the line starts from 0.
+ */
+ KDevelop::SimpleCursor positionAt( qint64 offset ) const;
+
+ void setContents( const QByteArray& contents );
+
+ const char *contents() const;
+ qint64 size() const;
+ Parser::memoryPoolType *memoryPool;
+ KDevPG::TokenStream *tokenStream;
+ Parser::CSharpCompatibilityMode compatibilityMode;
+
+ KDevelop::IndexedString indexedSymbol(qint64 token) const;
+ QString symbol(qint64 token) const;
+
+ /// @TODO implement this
+ void mapAstUse(AstNode* node, const SimpleUse& use)
+ {
+ Q_UNUSED(node);
+ Q_UNUSED(use);
+ }
+
+private:
+ QByteArray m_contents;
+};
+
+} // end of namespace CSharp
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,139 @@
+
+include_directories(
+ ${KDE4_INCLUDES}
+ ${KDE4_INCLUDE_DIR}/kdevelop-pg-qt
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDEVPLATFORM_INCLUDE_DIR}/interfaces
+ ${KDEVPLATFORM_INCLUDE_DIR}/editor
+ ${KDEVPLATFORM_INCLUDE_DIR}/project
+ ${KDEVPLATFORM_INCLUDE_DIR}/project/interfaces
+ ${KDEVPLATFORM_INCLUDE_DIR}/language
+ ${KDEVPLATFORM_INCLUDE_DIR}/language/interfaces
+ ${KDEVPLATFORM_INCLUDE_DIR}/language/backgroundparser
+ ${KDEVPLATFORM_INCLUDE_DIR}/language/duchain
+ ${KDEVPLATFORM_INCLUDE_DIR}/language/duchain/viewer
+)
+
+find_package(KDevelop-PG-Qt)
+
+########### next target ###############
+
+# autogenerate the lexer and the parser
+kdevpgqt_generate(_kdevpgList csharp NAMESPACE CSharp DEBUG_VISITOR
+ "${CMAKE_CURRENT_SOURCE_DIR}/csharp.g"
+ "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.h"
+)
+
+kdevpgqt_generate(_kdevpgList2 csharppp NAMESPACE CSharpPP DEBUG_VISITOR
+ "${CMAKE_CURRENT_SOURCE_DIR}/csharppp.g"
+ "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.h"
+)
+
+set(kdevcsharpparser_STAT_SRCS
+ csharpio.cpp
+ csharpppscope.cpp
+ csharppphandlervisitor.cpp
+ parsesession.cpp
+ ${_kdevpgList}
+ ${_kdevpgList2}
+)
+
+find_package(Flex)
+
+if(FLEX_FOUND)
+ # Copy csharplexer.ll to the builddir, so that flex doesn't write out
+ # absolute paths in the generated file when we pass them as arguments.
+ # In short, I don't want stuff like
+ # '#line 2 "/home/kde/build/.../csharplexer.cpp" in SVN.
+ add_custom_command(
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
+ MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.ll"
+ COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
+ "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.ll"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
+ )
+ set_source_files_properties(
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
+ GENERATED
+ )
+ # Add command to generate the lexer.
+ add_custom_command(
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+ MAIN_DEPENDENCY "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
+ DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
+ COMMAND ${FLEX_EXECUTABLE}
+ ARGS -o"csharplexer.cpp"
+ "csharplexer.ll"
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ )
+else(FLEX_FOUND)
+ # If flex is not available, copy the pre-generated lexer from SVN.
+ add_custom_command(
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
+ COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+ COMMENT "flex is not installed, using the pre-generated lexer from SVN."
+ )
+endif(FLEX_FOUND)
+
+set(kdevcsharpparser_STAT_SRCS
+ ${kdevcsharpparser_STAT_SRCS}
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+)
+set_source_files_properties(
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+ GENERATED
+)
+
+
+
+# Note: This library doesn't follow API/ABI/BC rules and shouldn't have a SOVERSION
+# Its only purpose is to support the plugin without needing to add all source files
+# to the plugin target
+kde4_add_library(kdev4csharpparser SHARED ${kdevcsharpparser_STAT_SRCS})
+target_link_libraries(kdev4csharpparser ${KDE4_KDECORE_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_LANGUAGE_LIBRARIES})
+install(TARGETS kdev4csharpparser ${INSTALL_TARGETS_DEFAULT_ARGS} )
+
+
+add_custom_target( copy-generated
+
+# 1. copy the kdev-pg generated files for the csharp parser
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpast.h"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpast.h"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpparser.h"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpparser.cpp"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.h"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpvisitor.h"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpvisitor.cpp"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.h"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpdefaultvisitor.h"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpdefaultvisitor.cpp"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
+
+# 2. depend on the files being copied
+ DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/csharpast.h"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.cpp"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.h"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.cpp"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.h"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.cpp"
+ "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
+)
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharp.g
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharp.g (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharp.g (revision 1522570)
@@ -0,0 +1,3015 @@
+-----------------------------------------------------------------------------
+-- Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
+--
+-- This grammar 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 grammar 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
+-- Lesser 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.
+-----------------------------------------------------------------------------
+
+
+-----------------------------------------------------------------------------
+-- Grammar for C# 2.0
+-- Modelled after the reference grammar of the C# 2.0 language specification
+-- (ECMA-334, Third Edition from June 2005, available at
+-- http://www.ecma-international.org/publications/standards/Ecma-334.htm),
+-- and the BSD-licensed ANTLR C# 1.0 grammar "kcsparse" at
+-- http://antlr.org/grammar/list (version from December 01, 2005)
+-----------------------------------------------------------------------------
+
+
+-- 16 first/follow conflicts:
+-- - The EXTERN conflicts in compilationUnit. They would be gone if
+-- typeDeclaration used OptionalTypeModifiers instead of
+-- broader optionalModifiers, but we stick with the latter one in order
+-- to improve the AST. As the externAliasDirective comes first, it
+-- rightfully gets selected, and so the conflict is harmless.
+-- (done right by default, 2 conflicts)
+-- - The LBRACKET conflict in compilationUnit,
+-- and the following EXTERN, LBRACKET conflict there.
+-- LBRACKET is resolved, EXTERN is just the above harmless conflict again.
+-- (manually resolved, 2 conflicts)
+-- - The COMMA conflict in attributeArguments: greedy is ok.
+-- (done right by default, 1 conflict)
+-- - The COMMA conflict in enumBody, also similar to the above.
+-- (manually resolved, 1 conflict)
+-- - The COMMA conflict in typeArguments:
+-- the approach for catching ">" signs works this way, and the conflict
+-- is resolved by the trailing condition at the end of the rule.
+-- (manually resolved, 1 conflict)
+-- - The COMMA conflict in arrayInitializer, another one of those.
+-- (manually resolved, 1 conflict)
+-- - The BIT_AND conflict in bitAndExpression,
+-- the PLUS, MINUS conflict in additiveExpression,
+-- the STAR conflict in multiplicativeExpression, and
+-- the LPAREN, INCREMENT, DECREMENT conflict in primaryExpression.
+-- They originate in the rather hackish solution to make expressions like
+-- "a is SomeType ? ifExp : elseExp" work (see conditionalExpression)
+-- and can be ignored, because the condition does the necessary check.
+-- (manually resolved, 4 conflicts)
+-- - The LBRACKET conflict in arrayCreationExpressionRest, for which
+-- newExpression with its arrayCreationExpression part is to blame.
+-- Caused by the fact that arrayCreationExpression can't be seperated
+-- from primaryAtom and put into primaryExpression instead.
+-- (manually resolved, 1 conflict)
+-- - The LBRACKET, STAR conflict in unmanagedType, similar to the one
+-- in arrayCreationExpression, only that it's triggered by the
+-- rank specifiers instead. The LBRACKET conflict is caused by the fact
+-- that arrayCreationExpression can't be seperated.
+-- As a consequence, all rank specifiers are checked for safety, always.
+-- The star conflict is caused by the may-end-with-epsilon typeArguments.
+-- It doesn't apply at all, only kdevelop-pg thinks it does. Code segments...
+-- (manually resolved, 1 conflict)
+-- - The DOT conflict in namespaceOrTypeName:
+-- Caused by the may-end-with-epsilon typeArguments. It doesn't apply
+-- at all, only kdevelop-pg thinks it does. Code segments...
+-- (done right by default, 1 conflict)
+-- - The DOT conflict in namespaceOrTypeNameSafe,
+-- which actually stems from indexerDeclaration.
+-- (manually resolved, 1 conflict)
+
+-- 14 first/first conflicts:
+-- - The ADD, ALIAS, etc. (identifier) conflict in usingDirective.
+-- (manually resolved, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflicts in attributeArguments,
+-- two similar ones.
+-- (manually resolved, 2 conflicts)
+-- - The PARTIAL conflict in classOrStructMemberDeclaration,
+-- between typeDeclarationRest and identifier.
+-- (manually resolved, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflict
+-- in classOrStructMemberDeclaration, between constructorDeclaration
+-- and the (Type ...) part of the rule.
+-- (manually resolved, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflict
+-- in classOrStructMemberDeclaration (another one), between
+-- the field declaration and the (typeNameSafe ...) part of the subrule.
+-- (manually resolved, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflict in eventDeclaration,
+-- between variableDeclarator and typeName.
+-- (manually resolved, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflict
+-- in typeParametersConstraints, caused by the similarity of
+-- primaryOrSecondaryConstraint (with ClassType) and
+-- secondaryConstraints (with typeName). Not resolved, instead,
+-- primaryOrSecondaryConstraint may be both, as indicated by the name.
+-- (done right by default, 1 conflict)
+-- - The ADD, ALIAS, etc. (identifier) conflict in blockStatement
+-- between all three statement Types. labeledStatement vs. the other two
+-- is resolved easily, whereas localVariableDeclarationStatement
+-- vs. embeddedStatement needs arbitrary-length LL(k), and is solved
+-- with a try/rollback() block.
+-- (manually resolved, 1 conflict)
+-- - The CHECKED, UNCHECKED, YIELD conflict in embeddedStatement.
+-- For "checked" and "unchecked", this is because there are both blocks
+-- and expression statements starting with "(un)checked". For "Yield",
+-- this is because "Yield" is not only the start of yieldStatement,
+-- but also a non-keyword identifier, and as such needs special treatment.
+-- Seperate LA(2) comparisons for all three of them.
+-- (manually resolved, 1 conflict)
+-- - The CATCH conflict in catchClauses.
+-- (manually resolved, 1 conflict)
+-- - The VOID conflict in TypeofExpression.
+-- (manually resolved, 1 conflict)
+-- - The BOOL, BYTE, CHAR, etc. conflict in TypeofExpression.
+-- That conflict is only naturally, because there's the same "Type" rule
+-- in two branches of an alternative item. One for C# 2.0 or higher,
+-- and another one for C# 1.0. So, this is an artificial conflict.
+-- (manually resolved, 1 conflict)
+-- - The VOID conflict in returnType.
+-- (manually resolved, 1 conflict)
+
+-- Total amount of conflicts: 30
+
+
+
+------------------------------------------------------------
+-- Global declarations
+------------------------------------------------------------
+
+[:
+#include <QtCore/QString>
+#include <QtCore/QSet>
+
+namespace KDevelop
+{
+class DUContext;
+}
+
+namespace CSharpPP
+{
+class HandlerVisitor;
+}
+
+namespace CSharp
+{
+class ParseSession;
+}
+
+#define yy_block_errors 0
+
+:]
+
+%export_macro "KDEVCSHARPPARSER_EXPORT"
+%export_macro_header "csharpparserexport.h"
+
+
+------------------------------------------------------------
+-- Ast Node class members
+------------------------------------------------------------
+%ast_extra_members
+[:
+ KDevelop::DUContext* ducontext;
+:]
+
+------------------------------------------------------------
+-- Parser class members
+------------------------------------------------------------
+
+%parserclass (public declaration)
+[:
+ /**
+ * Transform the raw input into tokens.
+ * When this method returns, the parser's token stream has been filled
+ * and any parse*() method can be called.
+ */
+ void tokenize( ParseSession* session );
+
+ /**
+ * The compatibilityMode status variable tells which version of C#
+ * should be checked against.
+ */
+ enum CSharpCompatibilityMode {
+ CSharp10Compatibility = 100,
+ CSharp20Compatibility = 200
+ };
+ Parser::CSharpCompatibilityMode compatibilityMode();
+ void setCompatibilityMode( Parser::CSharpCompatibilityMode Mode );
+
+ void ppDefineSymbol( QString symbolName );
+
+ enum ProblemType {
+ error,
+ warning,
+ info
+ };
+ void reportProblem( Parser::ProblemType type, const char* message );
+ void reportProblem( Parser::ProblemType type, QString message );
+:]
+
+%parserclass (protected declaration)
+[:
+ friend class ::CSharpPP::HandlerVisitor; // calls the pp_*() methods
+
+ /** Called when an #error or #warning directive has been found.
+ * @param type Either Parser::Error or Parser::Warning.
+ * @param label The error/warning text.
+ */
+ virtual void ppDiagnostic( Parser::ProblemType /*type*/, QString /*message*/ ) {}
+ virtual void ppDiagnostic( Parser::ProblemType /*type*/ ) {}
+:]
+
+%parserclass (private declaration)
+[:
+ void ppUndefineSymbol( QString symbolName );
+ bool ppIsSymbolDefined( QString symbolName );
+
+ Parser::CSharpCompatibilityMode m_compatibilityMode;
+ QSet<QString> m_ppDefinedSymbols;
+
+ struct ParserState {
+ // ltCounter stores the amount of currently open type arguments rules,
+ // all of which are beginning with a less than ("<") character.
+ // This way, also RSHIFT (">>") can be used to close type arguments rules,
+ // in addition to GREATER_THAN (">").
+ int ltCounter;
+ };
+ ParserState m_state;
+
+ // Rather hackish solution for recognizing expressions like
+ // "a is SomeType ? ifExp : elseExp", see conditionalExpression.
+ bool isNullableType( TypeAst *type );
+ void unsetNullableType( TypeAst *type );
+ TypeAst *lastRelationalExpressionRestType(
+ NullCoalescingExpressionAst *nullCoalescingExpression );
+:]
+
+%parserclass (constructor)
+[:
+ m_compatibilityMode = CSharp20Compatibility;
+:]
+
+
+
+------------------------------------------------------------
+-- Enumeration Types for additional AST members
+------------------------------------------------------------
+
+%namespace
+[:
+namespace AccessPolicy
+{
+ enum AccessPolicyEnum {
+ AccessPrivate = 0, // default value: memory pool initializes everything with zeros
+ AccessProtected,
+ AccessProtectedInternal,
+ AccessInternal,
+ AccessPublic
+ };
+}
+
+namespace Modifiers
+{
+ enum ModifierEnum {
+ ModNew = 1,
+ ModAbstract = 1 << 1,
+ ModSealed = 1 << 2,
+ ModStatic = 1 << 3,
+ ModReadonly = 1 << 4,
+ ModVolatile = 1 << 5,
+ ModVirtual = 1 << 6,
+ ModOverride = 1 << 7,
+ ModExtern = 1 << 8,
+ ModUnsafe = 1 << 9,
+ ModFixed = 1 << 10
+ };
+}
+
+namespace ConversionOperatorDeclaration
+{
+ enum ConversionTypeEnum {
+ ConversionImplicit,
+ ConversionExplicit
+ };
+}
+
+namespace ConstructorInitializer
+{
+ enum ConstructorInitializerTypeEnum {
+ TypeBase,
+ TypeThis
+ };
+}
+
+namespace OverloadableOperator
+{
+ enum UnaryOrBinaryEnum {
+ TypeUnary,
+ TypeBinary
+ };
+
+ enum OverloadableOperatorEnum
+ {
+ // Overloadable Unary operators:
+ OpBang,
+ OpTilde,
+ OpIncrement,
+ OpDecrement,
+ OpTrue,
+ OpFalse,
+ // Overloadable Unary or binary operators:
+ OpPlus,
+ OpMinus,
+ // Overloadable binary operators:
+ OpStar,
+ OpSlash,
+ OpRemainder,
+ OpBitAnd,
+ OpBitOr,
+ OpBitXor,
+ OpLShift,
+ OpRShift,
+ OpEqual,
+ OpNotEqual,
+ OpGreaterThan,
+ OpLessThan,
+ OpGreaterEqual,
+ OpLessEqual
+ };
+}
+
+namespace AccessorDeclarations
+{
+ enum AccessorTypeEnum {
+ TypeGet,
+ TypeSet,
+ TypeNone // only possible for the second, optional Accessor
+ };
+}
+
+namespace PrimaryOrSecondaryConstraint
+{
+ enum PrimaryOrSecondaryConstraintEnum {
+ TypeType,
+ TypeClass,
+ TypeStruct
+ };
+}
+
+namespace Argument
+{
+ enum ArgumentTypeEnum {
+ TypeValueParameter,
+ TypeReferenceParameter,
+ TypeOutputParameter
+ };
+}
+
+namespace GotoStatement
+{
+ enum GotoStatementEnum {
+ TypeLabeledStatement,
+ TypeSwitchCase,
+ TypeSwitchDefault
+ };
+}
+
+namespace YieldStatement
+{
+ enum YieldStatementEnum {
+ TypeYieldReturn,
+ TypeYieldBreak
+ };
+}
+
+namespace SwitchLabel
+{
+ enum BranchTypeEnum {
+ CaseBranch,
+ DefaultBranch
+ };
+}
+
+namespace Expression
+{
+ enum AssignmentOperatorEnum {
+ NoAssignment,
+ OpAssign,
+ OpPlusAssign,
+ OpMinusAssign,
+ OpStarAssign,
+ OpSlashAssign,
+ OpRemainderAssign,
+ OpBitAndAssign,
+ OpBitOrAssign,
+ OpBitXorAssign,
+ OpLShiftAssign,
+ OpRShiftAssign
+ };
+}
+
+namespace EqualityExpressionRest
+{
+ enum EqualityOperatorEnum {
+ OpEqual,
+ OpNotEqual
+ };
+}
+
+namespace RelationalExpressionRest
+{
+ enum RelationalOperatorEnum {
+ OpLessThan,
+ OpGreaterThan,
+ OpLessEqual,
+ OpGreaterEqual,
+ OpIs,
+ OpAs
+ };
+}
+
+namespace ShiftExpressionRest
+{
+ enum ShiftOperatorEnum {
+ OpLShift,
+ OpRShift
+ };
+}
+
+namespace AdditiveExpressionRest
+{
+ enum AdditiveOperatorEnum {
+ OpPlus,
+ OpMinus
+ };
+}
+
+namespace MultiplicativeExpressionRest
+{
+ enum MultiplicativeOperatorEnum {
+ OpStar,
+ OpSlash,
+ OpRemainder
+ };
+}
+
+namespace UnaryExpression
+{
+ enum UnaryExpressionEnum {
+ TypeIncrementedExpression,
+ TypeDecrementedExpression,
+ TypeUnaryMinusExpression,
+ TypeUnaryPlusExpression,
+ TypeBitwiseNotExpression,
+ TypeLogicalNotExpression,
+ TypeCastExpression,
+ TypeprimaryExpression,
+ TypePointerIndirectionExpression,
+ TypeAddressofExpression
+ };
+}
+
+namespace PrimarySuffix
+{
+ enum PrimarySuffixEnum {
+ TypeMemberAccess,
+ TypePointerMemberAccess,
+ TypeInvocation,
+ TypeElementAccess,
+ TypeIncrement,
+ TypeDecrement
+ };
+}
+
+namespace PrimaryAtom
+{
+ enum PrimaryAtomEnum {
+ TypeLiteral,
+ TypeParenthesizedExpression,
+ TypeMemberAccess,
+ TypeThisAccess,
+ TypeBaseAccess,
+ TypeNewExpression,
+ TypeTypeofExpression,
+ TypeCheckedExpression,
+ TypeUncheckedExpression,
+ TypeDefaultValueExpression,
+ TypeAnonymousMethodExpression,
+ TypeSizeofExpression
+ };
+}
+
+namespace PredefinedType
+{
+ enum PredefinedTypeEnum {
+ TypeBool,
+ TypeByte,
+ TypeChar,
+ TypeDecimal,
+ TypeDouble,
+ TypeFloat,
+ TypeInt,
+ TypeLong,
+ TypeObject,
+ TypeSbyte,
+ TypeShort,
+ TypeString,
+ TypeUint,
+ TypeUlong,
+ TypeUshort
+ };
+}
+
+namespace BaseAccess
+{
+ enum BaseAccessEnum {
+ TypeBaseMemberAccess,
+ TypeBaseIndexerAccess
+ };
+}
+
+namespace TypeofExpression
+{
+ enum TypeofExpressionEnum {
+ TypeVoid,
+ TypeUnboundTypeName,
+ TypeType
+ };
+}
+
+namespace ReturnType
+{
+ enum ReturnTypeEnum {
+ TypeRegular,
+ TypeVoid
+ };
+}
+
+namespace PointerType
+{
+ enum PointerTypeEnum {
+ TypeRegular,
+ TypeVoidStar
+ };
+}
+
+namespace UnmanagedTypeSuffix
+{
+ enum SuffixType {
+ TypeStar,
+ TypeRankSpecifier
+ };
+}
+
+namespace BuiltinClassType
+{
+ enum BuiltinClassTypeEnum {
+ TypeObject,
+ TypeString
+ };
+}
+
+namespace SimpleType
+{
+ enum SimpleTypeEnum {
+ TypeNumeric,
+ TypeBool
+ };
+}
+
+namespace NumericType
+{
+ enum NumericTypeEnum {
+ TypeIntegral,
+ TypeFloatingPoint,
+ TypeDecimal
+ };
+}
+
+namespace IntegralTypes
+{
+ enum IntegralTypeEnum {
+ TypeSbyte,
+ TypeByte,
+ TypeShort,
+ TypeUshort,
+ TypeInt,
+ TypeUint,
+ TypeLong,
+ TypeUlong,
+ TypeChar
+ };
+}
+
+namespace FloatingPointType
+{
+ enum FloatingPointTypeEnum {
+ TypeFloat,
+ TypeDouble
+ };
+}
+
+namespace Parameter
+{
+ enum ParameterTypeEnum {
+ ValueParameter,
+ ReferenceParameter,
+ OutputParameter
+ };
+}
+
+namespace Literal
+{
+ enum LiteralTypeEnum {
+ TypeTrue,
+ TypeFalse,
+ TypeNull,
+ TypeInteger,
+ TypeReal,
+ TypeCharacter,
+ TypeString
+ };
+}
+:]
+
+
+
+------------------------------------------------------------
+-- List of defined tokens
+------------------------------------------------------------
+
+-- keywords:
+%token ABSTRACT ("abstract"), AS ("as"), BASE ("base"), BOOL ("bool"),
+ BREAK ("break"), BYTE ("byte"), CASE ("case"), CATCH ("catch"),
+ CHAR ("char"), CHECKED ("checked"), CLASS ("class"), CONST ("const"),
+ CONTINUE ("continue"), DECIMAL ("decimal"), DEFAULT ("default"),
+ DELEGATE ("delegate"), DO ("do"), DOUBLE ("double"), ELSE ("else"),
+ ENUM ("enum"), EVENT ("event"), EXPLICIT ("explicit"),
+ EXTERN ("extern"), FINALLY ("finally"), FIXED ("fixed"),
+ FLOAT ("float"), FOREACH ("foreach"), FOR ("for"), GOTO ("goto"),
+ IF ("if"), IMPLICIT ("implicit"), IN ("in"), INT ("int"),
+ INTERFACE ("interface"), INTERNAL ("internal"), IS ("is"),
+ LOCK ("lock"), LONG ("long"), NAMESPACE ("namespace"), NEW ("new"),
+ OBJECT ("object"), OPERATOR ("operator"), OUT ("out"),
+ OVERRIDE ("override"), PARAMS ("params"), PRIVATE ("private"),
+ PROTECTED ("protected"), PUBLIC ("public"), READONLY ("readonly"),
+ REF ("ref"), RETURN ("return"), SBYTE ("sbyte"), SEALED ("sealed"),
+ SHORT ("short"), SIZEOF ("sizeof"), STACKALLOC ("stackalloc"),
+ STATIC ("static"), STRING ("string"), STRUCT ("struct"),
+ SWITCH ("switch"), THIS ("this"), THROW ("throw"), TRY ("try"),
+ TYPEOF ("typeof"), UINT ("uint"), ULONG ("ulong"),
+ UNCHECKED ("unchecked"), UNSAFE ("unsafe"), USHORT ("ushort"),
+ USING ("using"), VIRTUAL ("virtual"), VOID ("void"),
+ VOLATILE ("volatile"), WHILE ("while") ;;
+
+-- non-keyword identifiers with special meaning in the grammar:
+%token ADD ("add"), ALIAS("alias"), GET ("get"), GLOBAL ("global"),
+ PARTIAL ("partial"), REMOVE ("remove"), SET ("set"), VALUE ("value"),
+ WHERE ("where"), YIELD ("yield"), ASSEMBLY ("assembly") ;;
+
+-- seperators:
+%token LPAREN ("("), RPAREN (")"), LBRACE ("{"), RBRACE ("}"), LBRACKET ("["),
+ RBRACKET ("]"), COMMA (","), SEMICOLON (";"), DOT (".") ;;
+
+-- operators:
+%token COLON (":"), SCOPE ("::"), QUESTION ("?"), QUESTIONQUESTION ("??"),
+ BANG ("!"), TILDE ("~"), EQUAL ("=="), LESS_THAN ("<"),
+ LESS_EQUAL ("<="), GREATER_THAN (">"), GREATER_EQUAL (">="),
+ NOT_EQUAL ("!="), LOG_AND ("&&"), LOG_OR ("||"), ARROW_RIGHT ("->"),
+ INCREMENT ("++"), DECREMENT ("--"), ASSIGN ("="), PLUS ("+"),
+ PLUS_ASSIGN ("+="), MINUS ("-"), MINUS_ASSIGN ("-="), STAR ("*"),
+ STAR_ASSIGN ("*="), SLASH ("/"), SLASH_ASSIGN ("/="), BIT_AND ("&"),
+ BIT_AND_ASSIGN ("&="), BIT_OR ("|"), BIT_OR_ASSIGN ("|="),
+ BIT_XOR ("^"), BIT_XOR_ASSIGN ("^="), REMAINDER ("%"),
+ REMAINDER_ASSIGN ("%="), LSHIFT ("<<"), LSHIFT_ASSIGN ("<<="),
+ RSHIFT (">>"), RSHIFT_ASSIGN (">>=") ;;
+
+-- literals and identifiers:
+%token TRUE ("true"), FALSE ("false"), NULL ("null"),
+ INTEGER_LITERAL ("integer literal"), REAL_LITERAL ("real literal"),
+ CHARACTER_LITERAL ("character literal"),
+ STRING_LITERAL ("string literal"), IDENTIFIER ("identifier") ;;
+
+-- token that makes the parser fail in any case:
+%token INVALID ("invalid token") ;;
+
+
+
+
+------------------------------------------------------------
+-- Start of the actual grammar
+------------------------------------------------------------
+
+
+ 0 [: m_state.ltCounter = 0; :]
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#externAlias=externAliasDirective)+
+ | 0
+ )
+ try/recover(#using=usingDirective)*
+ try/recover(
+ 0 [: if (LA(2).kind != Token_ASSEMBLY) break; :] -- exit the "star loop"
+ #globalAttribute=globalAttributeSection
+ )*
+ try/recover(#namespace=namespaceMemberDeclaration)*
+-> compilationUnit ;;
+
+
+ EXTERN ALIAS identifier=identifier SEMICOLON
+-> externAliasDirective ;;
+
+ USING
+ ( ?[: LA(2).kind == Token_ASSIGN :] -- "using alias" directive
+ alias:identifier ASSIGN namespaceOrTypeName:namespaceOrTypeName
+ usingAliasDirective=usingAliasDirectiveData[alias, namespaceOrTypeName]
+ |
+ namespaceName:namespaceName -- "using namespace" directive
+ usingNamespaceDirective=usingNamespaceDirectiveData[namespaceName]
+ )
+ SEMICOLON
+-> usingDirective ;;
+
+ 0
+-> usingAliasDirectiveData [
+ argument member node alias: identifier;
+ argument member node namespaceOrTypeName: namespaceOrTypeName;
+] ;;
+
+ 0
+-> usingNamespaceDirectiveData [
+ argument member node namespaceName: namespaceName;
+] ;;
+
+
+
+
+-- ATTRIBUTE sections, global and standard ones. They have a slight similarity
+-- with Java's annotations in that they are used as advanced Type Modifiers.
+
+-- Strictly seen, the ASSEMBLY here should just be attributeTarget.
+-- But for the sake of avoiding an LL(k)-ambiguous conflict
+-- (in compilationUnit), we just allow "assembly".
+
+ LBRACKET ASSEMBLY COLON
+ #attribute=attribute
+ ( COMMA [: if (yytoken == Token_RBRACKET) { break; } :]
+ #attribute=attribute
+ )*
+ RBRACKET
+-> globalAttributeSection ;;
+
+ try/recover(#attribute=attributeSection)*
+-> optionalAttributeSections ;;
+
+ LBRACKET
+ ( ?[: LA(2).kind == Token_COLON :] target=attributeTarget COLON
+ | 0
+ )
+ #attribute=attribute
+ ( COMMA [: if (yytoken == Token_RBRACKET) { break; } :]
+ #attribute=attribute
+ )*
+ RBRACKET
+-> attributeSection ;;
+
+ identifier=identifier | keyword=keyword
+-> attributeTarget ;;
+
+ name=typeName (arguments=attributeArguments | 0)
+-> attribute ;;
+
+ LPAREN
+ (
+ -- empty argument list:
+ RPAREN
+ |
+ -- argument list only containing named arguments:
+ ?[: LA(2).kind == Token_ASSIGN :]
+ #namedArgument=namedArgument @ COMMA
+ RPAREN
+ |
+ -- argument list with positional arguments and
+ -- optionally appended named arguments:
+ #positionalArgument=positionalArgument
+ ( COMMA
+ ( ?[: LA(2).kind == Token_ASSIGN :]
+ (#namedArgument=namedArgument @ COMMA)
+ [: break; :] -- go directly to the closing parenthesis
+ |
+ #positionalArgument=positionalArgument
+ )
+ )*
+ RPAREN
+ )
+-> attributeArguments ;;
+
+ attributeArgumentExpression=expression
+-> positionalArgument ;;
+
+ argumentName=identifier ASSIGN attributeArgumentExpression=expression
+-> namedArgument ;;
+
+
+
+
+-- NAMESPACES can be nested arbitrarily and contain stuff
+-- like classes, interfaces, or other declarations.
+
+ namespaceDeclaration=namespaceDeclaration
+ | typeDeclaration=typeDeclaration
+-> namespaceMemberDeclaration ;;
+
+ NAMESPACE name=qualifiedIdentifier body=namespaceBody (SEMICOLON | 0)
+-> namespaceDeclaration ;;
+
+ LBRACE
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#externAlias=externAliasDirective)+
+ | 0
+ )
+ try/recover(#using=usingDirective)*
+ try/recover(#namespace=namespaceMemberDeclaration)*
+ RBRACE
+-> namespaceBody ;;
+
+ attributes:optionalAttributeSections
+ modifiers:optionalModifiers
+ rest=typeDeclarationRest[ attributes, modifiers ]
+-> typeDeclaration ;;
+
+-- C# 2.0 or higher allows partial classes, structs and interfaces.
+-- We don't need to introduce an additional check here, because the lexer only
+-- returns the PARTIAL token for C# versions >= 2.0, and IDENTIFIER otherwise.
+-- TODO: after parsing, check if the modifiers are allowed for the specific
+-- kind of type declaration.
+
+ (
+ PARTIAL
+ ( classDeclaration=classDeclaration[ attributes, modifiers, true ]
+ | structDeclaration=structDeclaration[ attributes, modifiers, true ]
+ | interfaceDeclaration=interfaceDeclaration[ attributes, modifiers, true ]
+ )
+ |
+ ( classDeclaration=classDeclaration[ attributes, modifiers, false ]
+ | structDeclaration=structDeclaration[ attributes, modifiers, false ]
+ | interfaceDeclaration=interfaceDeclaration[ attributes, modifiers, false ]
+ | enumDeclaration=enumDeclaration[ attributes, modifiers ]
+ | delegateDeclaration=delegateDeclaration[ attributes, modifiers ]
+ )
+ )
+-> typeDeclarationRest [
+ argument temporary node attributes: optionalAttributeSections;
+ argument temporary node modifiers: optionalModifiers;
+] ;;
+
+
+
+-- Definition of a C# CLASS
+
+ CLASS className=identifier
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ (classBase=classBase | 0)
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ body=classBody
+ (SEMICOLON | 0)
+-> classDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member variable partial: bool;
+] ;;
+
+
+-- Definition of a C# STRUCT
+
+ STRUCT structName=identifier
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ (structInterfaces=interfaceBase | 0)
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ body=structBody
+ (SEMICOLON | 0)
+-> structDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member variable partial: bool;
+] ;;
+
+
+-- Definition of a C# INTERFACE
+
+ INTERFACE interfaceName=identifier
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ (interfaceBase=interfaceBase | 0)
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ body=interfaceBody
+ (SEMICOLON | 0)
+-> interfaceDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member variable partial: bool;
+] ;;
+
+
+-- Definition of a C# ENUM
+
+ ENUM enumName=identifier
+ (enumBase=enumBase | 0)
+ body=enumBody
+ (SEMICOLON | 0)
+-> enumDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+] ;;
+
+
+-- Definition of a C# DELEGATE
+
+ DELEGATE returnType=returnType delegateName=identifier
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ LPAREN (formalParameters=formalParameterList | 0) RPAREN
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ SEMICOLON
+-> delegateDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+] ;;
+
+
+-- BASE CLASSES and INTERFACES
+-- which can be implemented by the Types above
+
+-- For classBase, the first type in the list of Base types May_ be a class.
+-- (But it can also be an interface.) In order to avoid ambiguities, only the
+-- first part of the rule has the exact seperation. If the second part of the
+-- rule is chosen, then the first element of baseTypeSequence can be
+-- the Base class.
+
+ COLON
+ ( builtinClassType=builtinClassType
+ (COMMA (#interfaceType=typeName @ COMMA) | 0)
+ |
+ #baseType=typeName @ COMMA
+ )
+-> classBase ;;
+
+ COLON #interfaceType=typeName @ COMMA
+-> interfaceBase ;;
+
+ COLON integralType=integralType
+-> enumBase ;;
+
+
+
+-- BODIES of classes, interfaces, and the likes.
+
+ LBRACE try/recover(#memberDeclaration=classMemberDeclaration)* RBRACE
+-> classBody ;;
+
+ LBRACE try/recover(#memberDeclaration=structMemberDeclaration)* RBRACE
+-> structBody ;;
+
+ LBRACE try/recover(#memberDeclaration=interfaceMemberDeclaration)* RBRACE
+-> interfaceBody ;;
+
+ LBRACE
+ try/recover(
+ #memberDeclaration=enumMemberDeclaration
+ ( 0 [: if (LA(2).kind == Token_RBRACE) break; :] -- exit the "star loop"
+ COMMA #memberDeclaration=enumMemberDeclaration
+ )*
+ (COMMA | 0)
+ |
+ 0
+ )
+ RBRACE
+-> enumBody ;;
+
+ attributes=optionalAttributeSections
+ memberName=identifier
+ (ASSIGN value=constantExpression | 0)
+-> enumMemberDeclaration ;;
+
+
+
+
+-- Now on to what happens inside the class, interface, etc. bodies:
+
+
+-- The CLASS MEMBER DECLARATION is one of the most complex rules in here,
+-- and covers everything that can occur inside a class body.
+
+ attributes:optionalAttributeSections
+ modifiers:optionalModifiers
+ ( finalizerDeclaration=finalizerDeclaration[ attributes, modifiers ]
+ | otherDeclaration=classOrStructMemberDeclaration[ attributes, modifiers ]
+ )
+-> classMemberDeclaration ;;
+
+ attributes:optionalAttributeSections
+ modifiers:optionalModifiers
+ declaration=classOrStructMemberDeclaration[ attributes, modifiers ]
+-> structMemberDeclaration ;;
+
+-- The first few declarations start with a specific token and don't need
+-- to be refactored. The other declarations must be split to avoid conflicts.
+
+ (
+ constantDeclaration=constantDeclaration[ attributes, modifiers ]
+ | eventDeclaration=eventDeclaration[ attributes, modifiers ]
+ |
+ -- The OPERATOR DECLARATION, part one: Conversion operator overloading.
+ conversionOperatorDeclaration=conversionOperatorDeclaration[ attributes, modifiers ]
+ |
+ -- A normal or static CONSTRUCTOR DECLARATION.
+ ?[: LA(2).kind == Token_LPAREN :]
+ constructorDeclaration=constructorDeclaration[ attributes, modifiers ]
+ |
+ -- The TYPE DECLARATION, buried under lookahead conditions ;)
+ ?[: (yytoken != Token_PARTIAL) || (LA(2).kind == Token_CLASS
+ || LA(2).kind == Token_INTERFACE || LA(2).kind == Token_ENUM
+ || LA(2).kind == Token_STRUCT || LA(2).kind == Token_DELEGATE) :]
+ typeDeclarationRest=typeDeclarationRest[ attributes, modifiers ]
+ |
+ -- Many of the declarations start with a type, and method declarations
+ -- start with a return type which is therefore the least common denominator.
+ MemberType:returnType
+ (
+ -- The OPERATOR DECLARATION rest, part two: overloading of real operators
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ unaryOrBinaryOperatorDeclaration=unaryOrBinaryOperatorDeclaration[
+ attributes, modifiers, MemberType->regularType
+ ]
+ |
+ -- The INDEXER DECLARATION rest, part one.
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ indexerDeclaration=indexerDeclaration[
+ attributes, modifiers, MemberType->regularType, 0 /* no interface Type */
+ ]
+ |
+ -- The FIELD DECLARATION rest. Declares member variables.
+ ?[: ( LA(2).kind == Token_SEMICOLON || LA(2).kind == Token_ASSIGN
+ || LA(2).kind == Token_COMMA || LA(2).kind == Token_LBRACKET
+ ) && (MemberType->type == ReturnType::TypeRegular) :]
+ (#variableDeclarator:variableDeclarator[
+ ((modifiers->modifiers & Modifiers::ModFixed) != 0) /* is a fixed size buffer? */
+ ] @ COMMA)
+ SEMICOLON
+ fieldDeclaration=variableDeclarationData[
+ attributes, modifiers,
+ MemberType->regularType, variableDeclaratorSequence
+ ]
+ |
+ -- and this is for rules that are still not split up sufficiently:
+ MemberNameOrInterfaceType:typeNameSafe
+ -- (interfaceType for the indexer declaration, memberName otherwise)
+ (
+ -- The INDEXER DECLARATION rest, part two.
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ DOT
+ indexerDeclaration=indexerDeclaration[
+ attributes, modifiers,
+ MemberType->regularType, MemberNameOrInterfaceType
+ ]
+ |
+ -- The PROPERTY DECLARATION rest.
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ propertyDeclaration=propertyDeclaration[
+ attributes, modifiers, MemberType->regularType, MemberNameOrInterfaceType
+ ]
+ |
+ -- The METHOD DECLARATION rest.
+ methodDeclaration=methodDeclaration[
+ attributes, modifiers, MemberType, MemberNameOrInterfaceType
+ ]
+ )
+ )
+ )
+-> classOrStructMemberDeclaration [
+ argument temporary node attributes: optionalAttributeSections;
+ argument temporary node modifiers: optionalModifiers;
+] ;;
+
+
+
+-- Having summarized the possible class/struct members, we now specify
+-- what they look like.
+
+
+-- The FINALIZER is what other languages know as deConstructor.
+-- Only allowed inside classes.
+
+ TILDE className=identifier LPAREN RPAREN
+ (body=block | SEMICOLON)
+-> finalizerDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+] ;;
+
+
+
+-- The CONSTRUCTOR DECLARATION. Naturally quite similar to the method one.
+-- Will also be folded into the memberDeclaration.
+
+ className=identifier
+ LPAREN (formalParameters=formalParameterList | 0) RPAREN
+ (constructorInitializer=constructorInitializer | 0)
+ (body=block | SEMICOLON)
+-> constructorDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+] ;;
+
+ COLON
+ ( BASE [: (*yynode)->initializerType = ConstructorInitializer::TypeBase; :]
+ | THIS [: (*yynode)->initializerType = ConstructorInitializer::TypeThis; :]
+ )
+ LPAREN arguments=optionalArgumentList RPAREN
+-> constructorInitializer [
+ member variable initializerType: ConstructorInitializer::ConstructorInitializerTypeEnum;
+] ;;
+
+-- There is also a STATIC CONSTRUCTOR DECLARATION which is only used if
+-- the Modifiers contain "static" (and optionally "extern", and nothing else).
+-- Apart from the "static" Modifier, the static Constructor declaration
+-- is a subset of the generic one. In order to keep the parser simple,
+-- we don't check on the Modifiers here and thus only use
+-- constructorDeclaration. On the whole, Modifier checking should be done
+-- in the visitor, later on... but we could make an exception here.
+
+-- className=identifier LPAREN RPAREN
+-- (body=block | SEMICOLON)
+-- -> staticConstructorDeclaration ;;
+
+
+
+-- The EVENT DECLARATION.
+
+ EVENT type=type
+ (
+ -- this condition avoids the LL(k) conflict here:
+ ?[: (LA(2).kind == Token_COMMA) || (LA(2).kind == Token_ASSIGN)
+ || (LA(2).kind == Token_SEMICOLON)
+ :]
+ (#variableDeclarator=variableDeclarator[false] @ COMMA) SEMICOLON
+ |
+ eventName=typeName
+ LBRACE eventaccessorDeclarations=eventaccessorDeclarations RBRACE
+ )
+-> eventDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+] ;;
+
+-- EVENT ACCESSOR DECLARATIONS appear inside an event declaration.
+
+ accessor1Attributes:optionalAttributeSections
+ (
+ ADD accessor1Body:block
+ addAccessorDeclaration=eventAccessorDeclaration[
+ accessor1Attributes, accessor1Body
+ ]
+ accessor2Attributes:optionalAttributeSections
+ REMOVE accessor2Body:block
+ removeAccessorDeclaration=eventAccessorDeclaration[
+ accessor2Attributes, accessor2Body
+ ]
+ |
+ REMOVE accessor1Body:block
+ removeAccessorDeclaration=eventAccessorDeclaration[
+ accessor1Attributes, accessor1Body
+ ]
+ accessor2Attributes:optionalAttributeSections
+ ADD accessor2Body:block
+ addAccessorDeclaration=eventAccessorDeclaration[
+ accessor2Attributes, accessor2Body
+ ]
+ )
+-> eventaccessorDeclarations ;;
+
+ 0
+-> eventAccessorDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node body: block;
+] ;;
+
+
+
+-- The different forms of the OPERATOR DECLARATION which overloads operators:
+-- Conversion, Unary and binary operator declarations.
+
+ ( IMPLICIT [: (*yynode)->conversion = ConversionOperatorDeclaration::ConversionImplicit; :]
+ | EXPLICIT [: (*yynode)->conversion = ConversionOperatorDeclaration::ConversionExplicit; :]
+ )
+ OPERATOR targetType=type
+ LPAREN sourceParameter=operatorDeclarationParameter RPAREN
+ (body=block | SEMICOLON)
+-> conversionOperatorDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ member variable conversion: ConversionOperatorDeclaration::ConversionTypeEnum;
+] ;;
+
+ OPERATOR
+ ( UnaryOp:overloadableUnaryOnlyOperator[&(*yynode)->overloadableOperatorType]
+ LPAREN sourceParameter1=operatorDeclarationParameter RPAREN
+ [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeUnary;
+ (*yynode)->overloadableOperatorToken = UnaryOp->token; :]
+ |
+ binaryOp:overloadableBinaryOnlyOperator[&(*yynode)->overloadableOperatorType]
+ LPAREN sourceParameter1=operatorDeclarationParameter
+ COMMA sourceParameter2=operatorDeclarationParameter RPAREN
+ [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeBinary;
+ (*yynode)->overloadableOperatorToken = binaryOp->token; :]
+ |
+ UnaryOrBinaryOp:overloadableUnaryOrBinaryOperator[&(*yynode)->overloadableOperatorType]
+ LPAREN sourceParameter1=operatorDeclarationParameter
+ (
+ COMMA sourceParameter2=operatorDeclarationParameter
+ [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeBinary;
+ (*yynode)->overloadableOperatorToken = UnaryOrBinaryOp->token; :]
+ |
+ 0 [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeUnary;
+ (*yynode)->overloadableOperatorToken = UnaryOrBinaryOp->token; :]
+ )
+ RPAREN
+ )
+ (body=block | SEMICOLON)
+-> unaryOrBinaryOperatorDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member node returnType: type;
+ member variable unaryOrBinary: OverloadableOperator::UnaryOrBinaryEnum;
+ member variable overloadableOperatorType: OverloadableOperator::OverloadableOperatorEnum;
+ member token overloadableOperatorToken;
+] ;;
+
+ type=type name=identifier
+-> operatorDeclarationParameter ;;
+
+
+-- OVERLOADABLE OPERATORS for operator declarations.
+
+ (
+ token=BANG [: *op = OverloadableOperator::OpBang; :]
+ | token=TILDE [: *op = OverloadableOperator::OpTilde; :]
+ | token=INCREMENT [: *op = OverloadableOperator::OpIncrement; :]
+ | token=DECREMENT [: *op = OverloadableOperator::OpDecrement; :]
+ | token=TRUE [: *op = OverloadableOperator::OpTrue; :]
+ | token=FALSE [: *op = OverloadableOperator::OpFalse; :]
+ )
+-> overloadableUnaryOnlyOperator [
+ argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
+] ;;
+
+ (
+ token=STAR [: *op = OverloadableOperator::OpStar; :]
+ | token=SLASH [: *op = OverloadableOperator::OpSlash; :]
+ | token=REMAINDER [: *op = OverloadableOperator::OpRemainder; :]
+ | token=BIT_AND [: *op = OverloadableOperator::OpBitAnd; :]
+ | token=BIT_OR [: *op = OverloadableOperator::OpBitOr; :]
+ | token=BIT_XOR [: *op = OverloadableOperator::OpBitXor; :]
+ | token=LSHIFT [: *op = OverloadableOperator::OpLShift; :]
+ | token=RSHIFT [: *op = OverloadableOperator::OpRShift; :]
+ | token=EQUAL [: *op = OverloadableOperator::OpEqual; :]
+ | token=NOT_EQUAL [: *op = OverloadableOperator::OpNotEqual; :]
+ | token=GREATER_THAN [: *op = OverloadableOperator::OpGreaterThan; :]
+ | token=LESS_THAN [: *op = OverloadableOperator::OpLessThan; :]
+ | token=GREATER_EQUAL [: *op = OverloadableOperator::OpGreaterEqual; :]
+ | token=LESS_EQUAL [: *op = OverloadableOperator::OpLessEqual; :]
+ )
+-> overloadableBinaryOnlyOperator [
+ argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
+] ;;
+
+ (
+ token=PLUS [: *op = OverloadableOperator::OpPlus; :]
+ | token=MINUS [: *op = OverloadableOperator::OpMinus; :]
+ )
+-> overloadableUnaryOrBinaryOperator [
+ argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
+] ;;
+
+
+
+-- The INDEXER DECLARATION rest.
+
+ THIS LBRACKET formalParameters=formalParameterList RBRACKET
+ LBRACE accessorDeclarations=accessorDeclarations RBRACE
+-> indexerDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member node type: type;
+ argument member node interfaceType: typeNameSafe;
+] ;;
+
+
+
+-- The PROPERTY DECLARATION rest.
+
+ LBRACE accessorDeclarations=accessorDeclarations RBRACE
+-> propertyDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member node type: type;
+ argument member node propertyName: typeNameSafe;
+] ;;
+
+-- ACCESSOR DECLARATIONS appear inside a property declaration.
+
+ accessor1Attributes=optionalAttributeSections
+ (accessor1Modifier=accessorModifier | 0)
+ (
+ GET (accessor1Body=block | SEMICOLON)
+ [: (*yynode)->accessor1Type = AccessorDeclarations::TypeGet; :]
+ (
+ accessor2Attributes=optionalAttributeSections
+ (accessor2Modifier=accessorModifier | 0)
+ SET (accessor2Body=block | SEMICOLON)
+ [: (*yynode)->accessor2Type = AccessorDeclarations::TypeSet; :]
+ | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
+ )
+ |
+ SET (accessor1Body=block | SEMICOLON)
+ [: (*yynode)->accessor1Type = AccessorDeclarations::TypeSet; :]
+ (
+ accessor2Attributes=optionalAttributeSections
+ (accessor2Modifier=accessorModifier | 0)
+ GET (accessor2Body=block | SEMICOLON)
+ [: (*yynode)->accessor2Type = AccessorDeclarations::TypeGet; :]
+ | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
+ )
+ )
+-> accessorDeclarations [
+ member variable accessor1Type: AccessorDeclarations::AccessorTypeEnum;
+ member variable accessor2Type: AccessorDeclarations::AccessorTypeEnum;
+] ;;
+
+ (
+ PROTECTED [: (*yynode)->accessPolicy = AccessPolicy::AccessProtected; :]
+ ( INTERNAL [: (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal; :]
+ | 0
+ )
+ | INTERNAL [: (*yynode)->accessPolicy = AccessPolicy::AccessInternal; :]
+ ( PROTECTED [: (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal; :]
+ | 0
+ )
+ | PRIVATE [: (*yynode)->accessPolicy = AccessPolicy::AccessPrivate; :]
+ )
+-> accessorModifier [
+ member variable accessPolicy: AccessPolicy::AccessPolicyEnum;
+] ;;
+
+
+
+-- The METHOD DECLARATION rest.
+
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ LPAREN (formalParameters=formalParameterList | 0) RPAREN
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ (body=block | SEMICOLON)
+-> methodDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member node modifiers: optionalModifiers;
+ argument member node returnType: returnType;
+ argument member node methodName: typeNameSafe;
+] ;;
+
+
+
+
+-- Interfaces have their own specific INTERFACE MEMBER DECLARATIONS.
+-- Resembling the classOrStructMemberDeclaration, but less complex.
+
+ attributes:optionalAttributeSections
+ ( NEW [: declNew = true; :]
+ | 0 [: declNew = false; :]
+ )
+ (
+ eventDeclaration=interfaceEventDeclaration[
+ attributes, declNew
+ ]
+ |
+ -- Many of the declarations start with a type, and method declarations
+ -- start with a return type which is therefore the least common denominator.
+ MemberType:returnType
+ (
+ -- The INDEXER DECLARATION rest.
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ indexerDeclaration=interfaceIndexerDeclaration[
+ attributes, declNew, MemberType->regularType
+ ]
+ |
+ -- The method and property declarations need to be split further.
+ memberName:identifier
+ (
+ -- The INTERFACE PROPERTY DECLARATION rest.
+ ?[: MemberType->type == ReturnType::TypeRegular :]
+ interfacePropertyDeclaration=interfacePropertyDeclaration[
+ attributes, declNew,
+ MemberType->regularType, memberName
+ ]
+ |
+ -- The INTERFACE METHOD DECLARATION rest.
+ interfaceMethodDeclaration=interfaceMethodDeclaration[
+ attributes, declNew, MemberType, memberName
+ ]
+ )
+ )
+ )
+-> interfaceMemberDeclaration [
+ temporary variable declNew: bool; -- specifies if the "new" keyword prepends the declaration
+] ;;
+
+
+-- Here are the detailed interface member declaration rules. Basically,
+-- all of them are just simplified versions of the class/struct ones.
+
+-- The INTERFACE EVENT DECLARATION.
+
+ EVENT EventType=type eventName=identifier SEMICOLON
+-> interfaceEventDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member variable declNew: bool;
+] ;;
+
+-- The INTERFACE INDEXER DECLARATION.
+
+ THIS LBRACKET formalParameters=formalParameterList RBRACKET
+ LBRACE interfaceAccessors=interfaceAccessors RBRACE
+-> interfaceIndexerDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member variable declNew: bool;
+ argument member node type: type;
+] ;;
+
+-- The INTERFACE PROPERTY DECLARATION.
+
+ LBRACE interfaceAccessors=interfaceAccessors RBRACE
+-> interfacePropertyDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member variable declNew: bool;
+ argument member node type: type;
+ argument member node propertyName: identifier;
+] ;;
+
+-- And last but not least, the INTERFACE METHOD DECLARATION.
+
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(typeParameters=typeParameters)
+ | 0
+ )
+ LPAREN (formalParameters=formalParameterList | 0) RPAREN
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
+ | 0
+ )
+ SEMICOLON
+-> interfaceMethodDeclaration [
+ argument member node attributes: optionalAttributeSections;
+ argument member variable declNew: bool;
+ argument member node returnType: returnType;
+ argument member node methodName: identifier;
+] ;;
+
+
+
+-- An INTERFACE ACCESSOR looks like "[attributes] get;" or "[attributes] set;"
+-- and is used by interfaceIndexerDeclaration and interfacePropertyDeclaration.
+
+ accessor1Attributes=optionalAttributeSections
+ (
+ GET SEMICOLON
+ [: (*yynode)->accessor1Type = AccessorDeclarations::TypeGet; :]
+ (
+ accessor2Attributes=optionalAttributeSections SET SEMICOLON
+ [: (*yynode)->accessor2Type = AccessorDeclarations::TypeSet; :]
+ | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
+ )
+ |
+ SET SEMICOLON
+ [: (*yynode)->accessor1Type = AccessorDeclarations::TypeSet; :]
+ (
+ accessor2Attributes=optionalAttributeSections GET SEMICOLON
+ [: (*yynode)->accessor2Type = AccessorDeclarations::TypeGet; :]
+ | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
+ )
+ )
+-> interfaceAccessors [
+ member variable accessor1Type: AccessorDeclarations::AccessorTypeEnum;
+ member variable accessor2Type: AccessorDeclarations::AccessorTypeEnum;
+] ;;
+
+
+
+
+-- A FORMAL PARAMETER LIST is part of a method header and contains one or more
+-- Parameters, optionally ending with a variable-length "Parameter array".
+-- It's not as hackish as it used to be, nevertheless it could still be nicer.
+
+ 0 [: bool parameterArrayOccurred = false; :]
+ (
+ try/recover(
+ #formalParameter=formalParameter[&parameterArrayOccurred]
+ ( 0 [: if( parameterArrayOccurred == true ) { break; } :]
+ -- Don't proceed after the Parameter array. If there's a cleaner way
+ -- to exit the loop when m_parameterArrayOccurred == true,
+ -- please use that instead of this construct.
+ COMMA #formalParameter=formalParameter[&parameterArrayOccurred]
+ )*
+ )
+ | 0
+ )
+-> formalParameterList ;;
+
+-- How it _should_ look:
+--
+-- 0 [: bool parameterArrayOccurred = false; :]
+-- (
+-- try/recover(
+-- #formalParameter=formalParameter[&parameterArrayOccurred]
+-- ( ?[: parameterArrayOccurred == false :] -- kdev-pg dismisses this condition!
+-- COMMA #formalParameter=formalParameter[&parameterArrayOccurred]
+-- )*
+-- )
+-- | 0
+-- )
+-- -> formalParameterList ;;
+
+ attributes=optionalAttributeSections
+ (
+ PARAMS paramsType=arrayType variableName=identifier
+ [: *parameterArrayOccurred = true; :]
+ |
+ modifier=optionalParameterModifier type=type variableName=identifier
+ )
+-> formalParameter [
+ argument temporary variable parameterArrayOccurred: bool*;
+] ;;
+
+
+-- An OPTIONAL ARGUMENT LIST is used when calling methods
+-- (not for declaring them, that's what formal Parameter lists are for).
+
+ try/recover(#argument=argument @ COMMA) | 0
+-> optionalArgumentList ;;
+
+ (
+ expression=expression
+ [: (*yynode)->argumentType = Argument::TypeValueParameter; :]
+ | REF expression=expression
+ [: (*yynode)->argumentType = Argument::TypeReferenceParameter; :]
+ | OUT expression=expression
+ [: (*yynode)->argumentType = Argument::TypeOutputParameter; :]
+ )
+-> argument [
+ member variable argumentType: Argument::ArgumentTypeEnum;
+] ;;
+
+
+
+
+-- type Parameters, type arguments, and constraints clauses form C#'s support
+-- for generics and are responsible for the greater-than special casing.
+
+-- TYPE PARAMETERS are used in class, interface etc. declarations to
+-- determine the generic types allowed as type argument.
+
+ LESS_THAN [: int currentLtLevel = m_state.ltCounter; m_state.ltCounter++; :]
+ #typeParameters=typeParameters @ COMMA
+ (
+ typeArgumentsOrParametersEnd
+ | 0 -- they can also be changed by typeParameters or TypeArgument
+ )
+ -- make sure we have gobbled up enough '>' characters
+ -- if we are at the "top level" of nested typeParameters productions
+ [: if (currentLtLevel == 0 && m_state.ltCounter != currentLtLevel ) {
+ if (!yy_block_errors) {
+ reportProblem(error, "The amount of closing ``>'' characters is incorrect");
+ }
+ return false;
+ }
+ :]
+-> typeParameters ;;
+
+ attributes=optionalAttributeSections parameterName=identifier
+-> typeParameters ;;
+
+
+-- TYPE ARGUMENTS are used in initializers, invocations, etc. to
+-- specify the exact types for this generic class/method instance.
+
+ LESS_THAN [: int currentLtLevel = m_state.ltCounter; m_state.ltCounter++; :]
+ #typeArgument=type @ COMMA
+ (
+ typeArgumentsOrParametersEnd
+ | 0 -- they can also be changed by typeParameters or TypeArgument
+ )
+ -- make sure we have gobbled up enough '>' characters
+ -- if we are at the "top level" of nested typeArguments productions
+ [: if (currentLtLevel == 0 && m_state.ltCounter != currentLtLevel ) {
+ if (!yy_block_errors) {
+ reportProblem(error, "The amount of closing ``>'' characters is incorrect");
+ }
+ return false;
+ }
+ :]
+-> typeArguments ;;
+
+
+ GREATER_THAN [: m_state.ltCounter -= 1; :] -- ">"
+ | RSHIFT [: m_state.ltCounter -= 2; :] -- ">>"
+-> typeArgumentsOrParametersEnd ;;
+
+
+-- type Parameter CONSTRAINTS CLAUSES also belong to C#'s generics,
+-- and can narrow down the allowed types given as type arguments.
+
+ WHERE typeParameters=identifier COLON constraints=typeParametersConstraints
+-> typeParametersConstraintsClause ;;
+
+ (
+ primaryOrSecondaryConstraint=primaryOrSecondaryConstraint
+ ( COMMA
+ ( #secondaryConstraint=secondaryConstraint
+ (COMMA ( #secondaryConstraint=secondaryConstraint
+ | ConstructorConstraint=ConstructorConstraint
+ [: break; :] -- it's the last item: exit the "star loop"
+ )
+ )*
+ |
+ ConstructorConstraint=ConstructorConstraint
+ )
+ | 0
+ )
+ |
+ #secondaryConstraint=secondaryConstraint
+ (COMMA ( #secondaryConstraint=secondaryConstraint
+ | ConstructorConstraint=ConstructorConstraint
+ [: break; :] -- it's the last item: exit the "star loop"
+ )
+ )*
+ |
+ ConstructorConstraint=ConstructorConstraint
+ )
+-> typeParametersConstraints ;;
+
+ (
+ classTypeOrSecondaryConstraint=classType
+ [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeType; :]
+ | CLASS [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeClass; :]
+ | STRUCT [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeStruct; :]
+ )
+-> primaryOrSecondaryConstraint [
+ member variable constraintType: PrimaryOrSecondaryConstraint::PrimaryOrSecondaryConstraintEnum;
+] ;;
+
+ #interfaceTypeOrTypeParameters=typeName
+-> secondaryConstraint ;;
+
+ NEW LPAREN RPAREN
+-> ConstructorConstraint ;;
+
+
+
+
+
+-- And now for the good stuff: statements, expressions and the likes. Yay!
+
+-- This is a BLOCK, a list of statements. It is used in many contexts:
+-- - As the body of a method, Constructor, overloaded operator, ...
+-- - As the body of an Accessor
+-- - As a completely independent braced block of code inside a method,
+-- starting a new scope for variable definitions
+
+ LBRACE try/recover(#statement=blockStatement)* RBRACE
+-> block ;;
+
+-- A BLOCK STATEMENT is either an embedded statement or a variable declaration.
+
+ (
+ ?[: LA(2).kind == Token_COLON :]
+ labeledStatement=labeledStatement
+ |
+ localConstantDeclarationStatement=localConstantDeclaration SEMICOLON
+ |
+ -- Local variable declarations, as well as expression statements, can start
+ -- with class1<xxx>.bla or similar. This is only solvable with LL(k), so
+ -- what's needed here is the following hack lookahead function, until
+ -- backtracking or real LL(k) is implemented.
+ try/rollback (
+ localVariableDeclarationStatement=localVariableDeclarationStatement
+ ) catch (
+ statement=embeddedStatement
+ )
+ )
+-> blockStatement ;;
+
+ label=identifier COLON blockStatement
+-> labeledStatement ;;
+
+
+
+-- VARIABLE DECLARATIONS, initializers, etc.
+
+-- The LOCAL VARIABLE DECLARATION does not allow attributes or Modifiers,
+-- this is only allowed in field declarations. Both store their data with
+-- the variableDeclarationData rule, using rule arguments.
+
+ declaration=localVariableDeclaration SEMICOLON
+-> localVariableDeclarationStatement ;;
+
+ type:type (#declarator:variableDeclarator[false] @ COMMA)
+ data=variableDeclarationData[
+ 0 /* no attributes */, 0 /* no Modifiers */, type, declaratorSequence
+ ]
+-> localVariableDeclaration ;;
+
+ 0
+-> variableDeclarationData [
+ argument member node attributes: optionalAttributeSections; -- not used in local
+ argument member node modifiers: optionalModifiers; -- variable declarations
+ argument member node type: type;
+ argument member node #variableDeclarator: variableDeclarator;
+] ;;
+
+-- The VARIABLE DECLARATOR is the part after the type specification for a
+-- variable declaration. There can be more declarators, seperated by commas.
+
+ variableName=identifier
+ (
+ -- Fixed size buffers are a C# 2.0 feature. Not in the
+ -- ECMA specification, but used by both Microsoft and Mono compilers.
+ ?[: fixedSizeBuffer :]
+ LBRACKET arraySize=expression RBRACKET
+ |
+ ?[: !fixedSizeBuffer :]
+ ASSIGN variableInitializer=variableInitializer
+ |
+ ?[: !fixedSizeBuffer :]
+ 0
+ )
+-> variableDeclarator [
+ argument temporary variable fixedSizeBuffer: bool;
+] ;;
+
+
+-- The CONSTANT DECLARATION. Declares "const" values.
+-- Analog to variable declarations, attributes and Modifiers are not allowed
+-- in local constant declarations, only in class-wide ones.
+
+ CONST type:type (#declarator:constantDeclarator @ COMMA)
+ data=constantDeclarationData[
+ 0 /* no attributes */, 0 /* no Modifiers */, type, declaratorSequence
+ ]
+-> localConstantDeclaration ;;
+
+ CONST type:type (#declarator:constantDeclarator @ COMMA) SEMICOLON
+ data=constantDeclarationData[
+ attributes, modifiers, type, declaratorSequence
+ ]
+-> constantDeclaration [
+ argument temporary node attributes: optionalAttributeSections;
+ argument temporary node modifiers: optionalModifiers;
+] ;;
+
+ 0
+-> constantDeclarationData [
+ argument member node attributes: optionalAttributeSections; -- not used in local
+ argument member node modifiers: optionalModifiers; -- constant declarations
+ argument member node type: type;
+ argument member node #constantDeclarator: constantDeclarator;
+] ;;
+
+ constantName=identifier ASSIGN expression=constantExpression
+-> constantDeclarator ;;
+
+
+-- The INITIALIZERS provide the actual values for the variable declarators.
+
+ expression=expression
+ | arrayInitializer=arrayInitializer
+ -- unsafe grammar extension: stackalloc initializer
+ | stackallocInitializer=stackallocInitializer
+-> variableInitializer ;;
+
+ LBRACE
+ try/recover(
+ #variableInitializer=variableInitializer
+ ( 0 [: if (LA(2).kind == Token_RBRACE) { break; } :]
+ COMMA #variableInitializer=variableInitializer
+ )*
+ ( COMMA | 0 )
+ |
+ 0
+ )
+ RBRACE
+-> arrayInitializer ;;
+
+-- unsafe grammar extension: stackalloc initializer
+ STACKALLOC unmanagedType LBRACKET expression=expression RBRACKET
+-> stackallocInitializer ;;
+
+
+
+
+-- The (embedded) STATEMENT is a central point of the grammar,
+-- even if delegating most of the work to its children.
+
+ (
+ block=block -- more blockStatements within {} braces
+ -- selection statements:
+ | ifStatement=ifStatement
+ | switchStatement=switchStatement
+ -- iteration statements:
+ | whileStatement=whileStatement
+ | doWhileStatement=doWhileStatement
+ | forStatement=forStatement
+ | foreachStatement=foreachStatement
+ -- jump statements:
+ | breakStatement=breakStatement
+ | continueStatement=continueStatement
+ | gotoStatement=gotoStatement
+ | returnStatement=returnStatement
+ | throwStatement=throwStatement
+ -- other statements:
+ | tryStatement=tryStatement
+ | lockStatement=lockStatement
+ | usingStatement=usingStatement
+ | SEMICOLON -- the specification calls it emptyStatement
+ |
+ -- CHECKED and UNCHECKED can also be the start of an expression.
+ -- So, manual checking if the second token is the start of a block.
+ ?[: LA(2).kind == Token_LBRACE :]
+ checkedStatement=checkedStatement
+ |
+ ?[: LA(2).kind == Token_LBRACE :]
+ uncheckedStatement=uncheckedStatement
+ |
+ -- Iterators with Yield have been introduced by C# 2.0, and for C# 1.0
+ -- the lexer returns the IDENTIFIER token instead of YIELD, so we don't
+ -- need to do a specific version check here.
+ -- YIELD is a non-keyword identifier, so it clashes with expressions:
+ ?[: LA(2).kind == Token_RETURN || LA(2).kind == Token_BREAK :]
+ yieldStatement=yieldStatement
+ |
+ -- method call, Assignment, etc.:
+ expressionStatement=statementExpression SEMICOLON
+ |
+ -- unsafe grammar extension: "unsafe" statement
+ unsafeStatement=unsafeStatement
+ |
+ -- unsafe grammar extension: "fixed" statement
+ fixedStatement=fixedStatement
+ )
+-> embeddedStatement ;;
+
+
+-- Simple one-rule statements:
+
+ IF LPAREN condition=booleanExpression RPAREN ifBody=embeddedStatement
+ (ELSE elseBody=embeddedStatement | 0)
+ -- the traditional "dangling-else" conflict:
+ -- kdevelop-pg generates proper code here, matching as soon as possible.
+-> ifStatement ;;
+
+ WHILE LPAREN condition=booleanExpression RPAREN body=embeddedStatement
+-> whileStatement ;;
+
+ DO body=embeddedStatement
+ WHILE LPAREN condition=booleanExpression RPAREN SEMICOLON
+-> doWhileStatement ;;
+
+ FOREACH LPAREN
+ variableType=type variableName=identifier IN collection=expression
+ RPAREN
+ body=embeddedStatement
+-> foreachStatement ;;
+
+ BREAK SEMICOLON
+-> breakStatement ;;
+
+ CONTINUE SEMICOLON
+-> continueStatement ;;
+
+ GOTO
+ ( label=identifier
+ [: (*yynode)->gotoType = GotoStatement::TypeLabeledStatement; :]
+ | CASE constantExpression=constantExpression
+ [: (*yynode)->gotoType = GotoStatement::TypeSwitchCase; :]
+ | DEFAULT
+ [: (*yynode)->gotoType = GotoStatement::TypeSwitchDefault; :]
+ )
+ SEMICOLON
+-> gotoStatement [
+ member variable gotoType: GotoStatement::GotoStatementEnum;
+] ;;
+
+ RETURN (returnExpression=expression | 0) SEMICOLON
+-> returnStatement ;;
+
+ THROW (exception=expression | 0) SEMICOLON
+-> throwStatement ;;
+
+ CHECKED body=block
+-> checkedStatement ;;
+
+ UNCHECKED body=block
+-> uncheckedStatement ;;
+
+ LOCK LPAREN lockExpression=expression RPAREN body=embeddedStatement
+-> lockStatement ;;
+
+ YIELD
+ ( RETURN returnExpression=expression
+ [: (*yynode)->yieldType = YieldStatement::TypeYieldReturn; :]
+ | BREAK
+ [: (*yynode)->yieldType = YieldStatement::TypeYieldBreak; :]
+ )
+ SEMICOLON
+-> yieldStatement [
+ member variable yieldType: YieldStatement::YieldStatementEnum;
+] ;;
+
+
+-- unsafe grammar extension: "unsafe" and "fixed" statements
+
+ UNSAFE body=block
+-> unsafeStatement ;;
+
+ FIXED LPAREN
+ pointerType=pointerType
+ (fixedPointerDeclarator=fixedPointerDeclarator @ COMMA)
+ RPAREN
+ body=embeddedStatement
+-> fixedStatement ;;
+
+ pointerName=identifier ASSIGN initializer=expression
+-> fixedPointerDeclarator ;;
+
+
+-- The SWITCH STATEMENT, consisting of a header and multiple
+-- "case x:" or "default:" Switch statement groups.
+
+ SWITCH LPAREN switchExpression=expression RPAREN
+ LBRACE try/recover(#switchSection=switchSection)* RBRACE
+-> switchStatement ;;
+
+ (#label=switchLabel)+
+ ( 0 [: if (yytoken == Token_DEFAULT && LA(2).kind != Token_LPAREN)
+ { break; } // don't give in to defaultValueExpression
+ :]
+ #statement=blockStatement
+ )+
+-> switchSection ;;
+
+ ( CASE caseExpression=constantExpression
+ [: (*yynode)->branchType = SwitchLabel::CaseBranch; :]
+ | DEFAULT
+ [: (*yynode)->branchType = SwitchLabel::DefaultBranch; :]
+ ) COLON
+-> switchLabel [
+ member variable branchType: SwitchLabel::BranchTypeEnum;
+] ;;
+
+
+-- The TRY STATEMENT, also known as try/catch/finally block.
+
+ TRY tryBody=block
+ ( catchClauses=catchClauses (FINALLY finallyBody=block | 0)
+ | FINALLY finallyBody=block
+ )
+-> tryStatement ;;
+
+ (
+ ?[: LA(2).kind != Token_LPAREN :]
+ generalCatchClause=generalCatchClause
+ |
+ ( -- also let general catch clauses get through:
+ 0 [: if (LA(2).kind != Token_LPAREN) { break; } :]
+ #specificCatchClause=specificCatchClause
+ )+
+ ( generalCatchClause=generalCatchClause | 0 )
+ )
+-> catchClauses ;;
+
+ CATCH LPAREN
+ exceptionType=classType (exceptionName=identifier | 0)
+ RPAREN
+ body=block
+-> specificCatchClause ;;
+
+ CATCH body=block
+-> generalCatchClause ;;
+
+
+-- The USING STATEMENT, acquiring and afterwards disposing a System.Disposable.
+
+ USING LPAREN resourceAcquisition=resourceAcquisition RPAREN
+ body=embeddedStatement
+-> usingStatement ;;
+
+-- Hm, we know that LL(k) conflict from somewhere, don't we?
+-- Right, it's the same one as in blockStatement and the upcoming forControl.
+
+ try/rollback( localVariableDeclaration=localVariableDeclaration )
+ catch( expression=expression )
+-> resourceAcquisition ;;
+
+
+-- The FOR STATEMENT, including its problematic child forControl.
+
+ FOR LPAREN forControl=forControl RPAREN forBody=embeddedStatement
+-> forStatement ;;
+
+-- The FOR CONTROL is the three statements inside the for(...) parentheses,
+-- or the alternative foreach specifier. It has the same problematic conflict
+-- between localVariableDeclaration and expression that blockStatement also
+-- has and which is only solvable with LL(k). Until backtracking or real LL(k)
+-- is implemented, we have to workaround with a lookahead hack function.
+
+ (
+ try/rollback (
+ localVariableDeclaration=localVariableDeclaration -- "int i = 0"
+ ) catch (
+ #statementExpression=statementExpression @ COMMA
+ )
+ |
+ 0
+ )
+ SEMICOLON
+ (forCondition=booleanExpression | 0) SEMICOLON -- "i < size;"
+ (#forIterator=statementExpression @ COMMA | 0) -- "i++"
+-> forControl ;;
+
+
+
+
+-- EXPRESSIONS
+-- Note that most of these expressions follow the pattern
+-- thisLevelExpression :
+-- nextHigherPrecedenceExpression @ OPERATOR
+--
+-- The operators in C# have the following precedences:
+-- lowest (14) Assignment = *= /= %= += -= <<= >>= &= ^= |=
+-- (13) Conditional ?:
+-- (12) Conditional OR ||
+-- (11) Conditional AND &&
+-- (10) Logical OR |
+-- ( 9) Logical XOR ^
+-- ( 8) Logical AND &
+-- ( 7) Equality == !=
+-- ( 6) Relational and type-testing < > <= >= is as
+-- ( 5) Shift << >>
+-- ( 4) Additive +(binary) -(binary)
+-- ( 3) Multiplicative * / %
+-- ( 2) Unary +(Unary) -(Unary) ! ~ ++x --x (type)x
+-- highest ( 1) Primary x.y f(x) a[x] x++ x-- new
+
+
+-- Both BOOLEAN and CONSTANT EXPRESSIONS ought to return a certain kind of
+-- value, but it's not possible for any parser to check those restrictions.
+
+ expression=expression
+-> constantExpression ;;
+
+ expression=expression
+-> booleanExpression ;;
+
+-- A STATEMENT EXPRESSION may not contain certain subsets of expression,
+-- but it's just not feasible for LL(k) parsers to filter them out.
+
+ expression=expression
+-> statementExpression ;;
+
+
+-- So this is the actual EXPRESSION, also known as Assignment expression.
+
+ conditionalExpression=conditionalExpression
+ (
+ ( ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpAssign; :]
+ | PLUS_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpPlusAssign; :]
+ | MINUS_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpMinusAssign; :]
+ | STAR_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpStarAssign; :]
+ | SLASH_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpSlashAssign; :]
+ | REMAINDER_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpRemainderAssign; :]
+ | BIT_AND_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpBitAndAssign; :]
+ | BIT_OR_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpBitOrAssign; :]
+ | BIT_XOR_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpBitXorAssign; :]
+ | LSHIFT_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpLShiftAssign; :]
+ | RSHIFT_ASSIGN
+ [: (*yynode)->assignmentOperator = Expression::OpRShiftAssign; :]
+ )
+ assignmentExpression=expression
+ |
+ 0 [: (*yynode)->assignmentOperator = Expression::NoAssignment; :]
+ )
+-> expression [
+ member variable assignmentOperator: Expression::AssignmentOperatorEnum;
+] ;;
+
+
+ nullCoalescingExpression=nullCoalescingExpression
+ (
+ QUESTION ifExpression=expression COLON elseExpression=expression
+ |
+ -- this rather hackish solution prevents false errors for expressions
+ -- like "a is SomeType ? ifExp : elseExp", where NullableType steals
+ -- the question mark from conditionalExpression.
+ ?[: (compatibilityMode() >= CSharp20Compatibility)
+ && isNullableType(lastRelationalExpressionRestType((*yynode)->nullCoalescingExpression)) :]
+ 0 [: unsetNullableType(lastRelationalExpressionRestType((*yynode)->nullCoalescingExpression)); :]
+ ifExpression=expression COLON elseExpression=expression
+ |
+ 0
+ )
+-> conditionalExpression ;;
+
+-- The NULL COALESCING EXPRESSION is new in C# 2.0 and provides fallback values
+-- for nullable variables. If a is non-null, (a ?? b) returns a,
+-- but if a is null, (a ?? b) returns b.
+-- Version checking is already done by the lexer and not needed here.
+
+ #expression=logicalOrExpression @ QUESTIONQUESTION
+-> nullCoalescingExpression ;;
+
+ #expression=logicalAndExpression @ LOG_OR
+-> logicalOrExpression ;;
+
+ #expression=bitOrExpression @ LOG_AND
+-> logicalAndExpression ;;
+
+ #expression=bitXorExpression @ BIT_OR
+-> bitOrExpression ;;
+
+ #expression=bitAndExpression @ BIT_XOR
+-> bitXorExpression ;;
+
+ #expression=equalityExpression @ BIT_AND
+-> bitAndExpression ;;
+
+ expression=relationalExpression
+ (#additionalExpression=equalityExpressionRest)*
+-> equalityExpression ;;
+
+ ( EQUAL [: (*yynode)->equalityOperator = EqualityExpressionRest::OpEqual; :]
+ | NOT_EQUAL [: (*yynode)->equalityOperator = EqualityExpressionRest::OpNotEqual; :]
+ )
+ expression=relationalExpression
+-> equalityExpressionRest [
+ member variable equalityOperator: EqualityExpressionRest::EqualityOperatorEnum;
+] ;;
+
+ expression=shiftExpression
+ (#additionalExpression=relationalExpressionRest)*
+-> relationalExpression ;;
+
+ (
+ ( LESS_THAN [: (*yynode)->relationalOperator = RelationalExpressionRest::OpLessThan; :]
+ | GREATER_THAN [: (*yynode)->relationalOperator = RelationalExpressionRest::OpGreaterThan; :]
+ | LESS_EQUAL [: (*yynode)->relationalOperator = RelationalExpressionRest::OpLessEqual; :]
+ | GREATER_EQUAL [: (*yynode)->relationalOperator = RelationalExpressionRest::OpGreaterEqual; :]
+ )
+ expression=shiftExpression
+ |
+ ( IS [: (*yynode)->relationalOperator = RelationalExpressionRest::OpIs; :]
+ | AS [: (*yynode)->relationalOperator = RelationalExpressionRest::OpAs; :]
+ )
+ type=type
+ )
+-> relationalExpressionRest [
+ member variable relationalOperator: RelationalExpressionRest::RelationalOperatorEnum;
+] ;;
+
+ expression=additiveExpression
+ (#additionalExpression=shiftExpressionRest)*
+-> shiftExpression ;;
+
+ ( LSHIFT [: (*yynode)->shiftOperator = ShiftExpressionRest::OpLShift; :]
+ | RSHIFT [: (*yynode)->shiftOperator = ShiftExpressionRest::OpRShift; :]
+ )
+ expression=additiveExpression
+-> shiftExpressionRest [
+ member variable shiftOperator: ShiftExpressionRest::ShiftOperatorEnum;
+] ;;
+
+ expression=multiplicativeExpression
+ (#additionalExpression=additiveExpressionRest)*
+-> additiveExpression ;;
+
+ ( PLUS [: (*yynode)->additiveOperator = AdditiveExpressionRest::OpPlus; :]
+ | MINUS [: (*yynode)->additiveOperator = AdditiveExpressionRest::OpMinus; :]
+ )
+ expression=multiplicativeExpression
+-> additiveExpressionRest [
+ member variable additiveOperator: AdditiveExpressionRest::AdditiveOperatorEnum;
+] ;;
+
+ expression=unaryExpression
+ (#additionalExpression=multiplicativeExpressionRest)*
+-> multiplicativeExpression ;;
+
+ ( STAR [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpStar; :]
+ | SLASH [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpSlash; :]
+ | REMAINDER [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpRemainder; :]
+ )
+ expression=unaryExpression
+-> multiplicativeExpressionRest [
+ member variable multiplicativeOperator: MultiplicativeExpressionRest::MultiplicativeOperatorEnum;
+] ;;
+
+
+
+-- So, up till now this was the easy stuff. Here comes another sincere
+-- conflict in the grammar that can only be solved with LL(k).
+-- The conflict in this rule is the ambiguity between type casts (which
+-- can be arbitrary class names within parentheses) and primaryExpressions,
+-- which can also look that way from an LL(1) perspective.
+-- Until real LL(k) or backtracking is implemented in kdev-pg, this problem
+-- is solved with another lookahead hack function.
+
+ (
+ INCREMENT unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeIncrementedExpression; :]
+ | DECREMENT unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeDecrementedExpression; :]
+ | MINUS unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeUnaryMinusExpression; :]
+ | PLUS unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeUnaryPlusExpression; :]
+ | TILDE unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeBitwiseNotExpression; :]
+ | BANG unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeLogicalNotExpression; :]
+ |
+ try/rollback (
+ castExpression=castExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeCastExpression; :]
+ )
+ catch (
+ primaryExpression=primaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeprimaryExpression; :]
+ )
+ |
+ -- unsafe grammar extension: pointer indirection expression
+ STAR unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypePointerIndirectionExpression; :]
+ |
+ -- unsafe grammar extension: addressof expression
+ BIT_AND unaryExpression=unaryExpression
+ [: (*yynode)->ruleType = UnaryExpression::TypeAddressofExpression; :]
+ )
+-> unaryExpression [
+ member variable ruleType: UnaryExpression::UnaryExpressionEnum;
+] ;;
+
+ LPAREN type=type RPAREN castedExpression=unaryExpression
+-> castExpression ;;
+
+
+-- PRIMARY EXPRESSIONs: qualified names, array expressions,
+-- method invocation, post increment/decrement, etc.
+
+ primaryAtom=primaryAtom (#primarySuffix=primarySuffix)*
+-> primaryExpression ;;
+
+ (
+ -- this is the part of memberAccess that's not in primaryAtom
+ DOT memberName=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+ [: (*yynode)->suffixType = PrimarySuffix::TypeMemberAccess; :]
+ |
+ -- the suffix part of invocationExpression
+ LPAREN arguments=optionalArgumentList RPAREN
+ [: (*yynode)->suffixType = PrimarySuffix::TypeInvocation; :]
+ |
+ -- elementAccess (also known as array Access)
+ LBRACKET (#expression=expression @ COMMA) RBRACKET
+ [: (*yynode)->suffixType = PrimarySuffix::TypeElementAccess; :]
+ |
+ INCREMENT
+ [: (*yynode)->suffixType = PrimarySuffix::TypeIncrement; :]
+ |
+ DECREMENT
+ [: (*yynode)->suffixType = PrimarySuffix::TypeDecrement; :]
+ |
+ -- unsafe grammar extension: pointer Access
+ ARROW_RIGHT memberName=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+ [: (*yynode)->suffixType = PrimarySuffix::TypePointerMemberAccess; :]
+ )
+-> primarySuffix [
+ member variable suffixType: PrimarySuffix::PrimarySuffixEnum;
+] ;;
+
+
+-- PRIMARY ATOM: the basic element of a Primary expression,
+-- and expressions in general
+
+ (
+ literal=literal
+ [: (*yynode)->ruleType = PrimaryAtom::TypeLiteral; :]
+ |
+ LPAREN expression=expression RPAREN
+ [: (*yynode)->ruleType = PrimaryAtom::TypeParenthesizedExpression; :]
+ |
+ simpleNameOrMemberAccess=simpleNameOrMemberAccess
+ [: (*yynode)->ruleType = PrimaryAtom::TypeMemberAccess; :]
+ |
+ THIS
+ [: (*yynode)->ruleType = PrimaryAtom::TypeThisAccess; :]
+ |
+ baseAccess=baseAccess
+ [: (*yynode)->ruleType = PrimaryAtom::TypeBaseAccess; :]
+ |
+ newExpression=newExpression
+ [: (*yynode)->ruleType = PrimaryAtom::TypeNewExpression; :]
+ |
+ TypeofExpression=TypeofExpression
+ [: (*yynode)->ruleType = PrimaryAtom::TypeTypeofExpression; :]
+ |
+ CHECKED LPAREN expression=expression RPAREN
+ [: (*yynode)->ruleType = PrimaryAtom::TypeCheckedExpression; :]
+ |
+ UNCHECKED LPAREN expression=expression RPAREN
+ [: (*yynode)->ruleType = PrimaryAtom::TypeUncheckedExpression; :]
+ |
+ DEFAULT LPAREN type=type RPAREN
+ [: (*yynode)->ruleType = PrimaryAtom::TypeDefaultValueExpression; :]
+ |
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ anonymousMethodExpression=anonymousMethodExpression
+ [: (*yynode)->ruleType = PrimaryAtom::TypeAnonymousMethodExpression; :]
+ |
+ -- unsafe grammar extension: sizeof(type)
+ SIZEOF LPAREN unmanagedType=unmanagedType RPAREN
+ [: (*yynode)->ruleType = PrimaryAtom::TypeSizeofExpression; :]
+ )
+-> primaryAtom [
+ member variable ruleType: PrimaryAtom::PrimaryAtomEnum;
+] ;;
+
+
+-- Here come the more complex parts of primaryAtom that have been split out.
+
+-- This rule covers two rules from the specification, the SIMPLE NAME and
+-- most of MEMBER ACCESS.
+
+ (
+ ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
+ | 0
+ )
+ memberName=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+ |
+ predefinedType=predefinedType DOT memberName=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+ )
+-> simpleNameOrMemberAccess ;;
+
+ (
+ BOOL [: (*yynode)->type = PredefinedType::TypeBool; :]
+ | BYTE [: (*yynode)->type = PredefinedType::TypeByte; :]
+ | CHAR [: (*yynode)->type = PredefinedType::TypeChar; :]
+ | DECIMAL [: (*yynode)->type = PredefinedType::TypeDecimal; :]
+ | DOUBLE [: (*yynode)->type = PredefinedType::TypeDouble; :]
+ | FLOAT [: (*yynode)->type = PredefinedType::TypeFloat; :]
+ | INT [: (*yynode)->type = PredefinedType::TypeInt; :]
+ | LONG [: (*yynode)->type = PredefinedType::TypeLong; :]
+ | OBJECT [: (*yynode)->type = PredefinedType::TypeObject; :]
+ | SBYTE [: (*yynode)->type = PredefinedType::TypeSbyte; :]
+ | SHORT [: (*yynode)->type = PredefinedType::TypeShort; :]
+ | STRING [: (*yynode)->type = PredefinedType::TypeString; :]
+ | UINT [: (*yynode)->type = PredefinedType::TypeUint; :]
+ | ULONG [: (*yynode)->type = PredefinedType::TypeUlong; :]
+ | USHORT [: (*yynode)->type = PredefinedType::TypeUshort; :]
+ )
+-> predefinedType [
+ member variable type: PredefinedType::PredefinedTypeEnum;
+] ;;
+
+
+ BASE
+ ( DOT identifier=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+ [: (*yynode)->accessType = BaseAccess::TypeBaseMemberAccess; :]
+ |
+ LBRACKET (#expression=expression @ COMMA) RBRACKET
+ [: (*yynode)->accessType = BaseAccess::TypeBaseIndexerAccess; :]
+ )
+-> baseAccess [
+ member variable accessType: BaseAccess::BaseAccessEnum;
+] ;;
+
+
+ DELEGATE (anonymousMethodSignature=anonymousMethodSignature | 0)
+ body=block
+-> anonymousMethodExpression ;;
+
+ LPAREN
+ ( (#anonymousMethodParameter=anonymousMethodParameter @ COMMA) | 0 )
+ RPAREN
+-> anonymousMethodSignature ;;
+
+ modifier=optionalParameterModifier type=type variableName=identifier
+-> anonymousMethodParameter ;;
+
+
+-- NEW EXPRESSION is actually three rules in one: arrayCreationExpression,
+-- objectCreationExpression and delegateCreationExpression.
+-- But as they all contain a "type" rule in the same place, it's not
+-- a good idea to try to tell them apart. Also, object creation and
+-- delegate creation can derive the exact same token sequence.
+
+ NEW type:type
+ ( arrayCreationExpression=arrayCreationExpressionRest[type]
+ | objectOrDelegateCreationExpression=objectOrDelegateCreationExpressionRest[type]
+ )
+-> newExpression ;;
+
+-- The rest of object/delegate or array creation expressions.
+
+ LPAREN argumentListOrExpression=optionalArgumentList RPAREN
+-> objectOrDelegateCreationExpressionRest [
+ argument member node type: type;
+] ;;
+
+ (
+ arrayInitializer=arrayInitializer
+ |
+ LBRACKET (#expression=expression @ COMMA) RBRACKET
+ ( 0 [: if (LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
+ { break; }
+ :] -- avoids swallowing the LBRACKETs in
+ -- primarySuffix's element Access part.
+ #rankSpecifier=rankSpecifier
+ )*
+ (arrayInitializer=arrayInitializer | 0)
+ )
+-> arrayCreationExpressionRest [
+ argument member node type: type;
+] ;;
+
+
+-- The TYPEOF EXPRESSION is nasty, because it either needs LL(k) lookahead
+-- or a very ugly duplication of the type system. And when I say Very_ ugly,
+-- I mean it. I tried it, and decided to go with the cleaner lookahead hack.
+
+ TYPEOF LPAREN
+ (
+ ?[: LA(2).kind == Token_RPAREN :]
+ VOID
+ [: (*yynode)->typeofType = TypeofExpression::TypeVoid; :]
+ |
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ try/rollback(
+ unboundTypeName=unboundTypeName
+ [: (*yynode)->typeofType = TypeofExpression::TypeUnboundTypeName; :]
+ )
+ catch(
+ otherType=type
+ [: (*yynode)->typeofType = TypeofExpression::TypeType; :]
+ )
+ |
+ otherType=type
+ [: (*yynode)->typeofType = TypeofExpression::TypeType; :]
+ )
+ RPAREN
+-> TypeofExpression [
+ member variable typeofType: TypeofExpression::TypeofExpressionEnum;
+] ;;
+
+ ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
+ | 0
+ )
+ #namePart=unboundTypeNamePart @ DOT
+-> unboundTypeName ;;
+
+ identifier=identifier
+ genericDimensionSpecifier=genericDimensionSpecifier
+-> unboundTypeNamePart ;;
+
+ LESS_THAN [: (*yynode)->commaCount = 0; :]
+ ( COMMA [: (*yynode)->commaCount++; :] )*
+ GREATER_THAN
+-> genericDimensionSpecifier [
+ member variable commaCount: int;
+] ;;
+
+
+
+
+
+--
+-- All kinds of rules for types here.
+--
+
+-- The RETURN TYPE can only be used as return value, not in a declaration.
+
+ (
+ ?[: LA(2).kind != Token_STAR :] -- "void*" is a regular type in unsafe code
+ VOID [: (*yynode)->type = ReturnType::TypeVoid; :]
+ |
+ regularType=type [: (*yynode)->type = ReturnType::TypeRegular; :]
+ )
+-> returnType [
+ member variable type: ReturnType::ReturnTypeEnum;
+] ;;
+
+-- The regular TYPE recognizes the same set of tokens as the one in the C#
+-- specification, but had to be refactored quite a bit. Looks different here.
+
+ unmanagedType=unmanagedType -- it's too cumbersome to track "unsafe",
+ -- | managedType=managedType -- so have it on by default
+-> type ;;
+
+ -- unsafe grammar extension: unmanaged type (includes all of the managed one)
+ ( regularType=nonArrayType
+ [: (*yynode)->type = PointerType::TypeRegular; :]
+ | VOID STAR
+ [: (*yynode)->type = PointerType::TypeVoidStar; :]
+ )
+ ( 0 [: if (yytoken == Token_LBRACKET &&
+ LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
+ { break; }
+ :] -- prevents rankSpecifier from swallowing the LBRACKETs in
+ -- newExpression/arrayCreationExpression.
+ #unmanagedTypeSuffix=unmanagedTypeSuffix
+ )*
+-> unmanagedType [
+ member variable type: PointerType::PointerTypeEnum;
+] ;;
+
+ -- unsafe grammar extension: pointer type
+ ( regularType=nonArrayType
+ #unmanagedTypeSuffix=unmanagedTypeSuffix
+ [: (*yynode)->type = PointerType::TypeRegular; :]
+ | VOID STAR
+ [: (*yynode)->type = PointerType::TypeVoidStar; :]
+ )
+ ( 0 [: if (yytoken == Token_LBRACKET &&
+ LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
+ { break; }
+ :] -- prevents rankSpecifier from swallowing the LBRACKETs in
+ -- newExpression/arrayCreationExpression.
+ #unmanagedTypeSuffix=unmanagedTypeSuffix
+ )*
+-> pointerType [
+ member variable type: PointerType::PointerTypeEnum;
+ member variable starCount: int;
+] ;;
+
+ STAR [: (*yynode)->type = UnmanagedTypeSuffix::TypeStar; :]
+ | rankSpecifier=rankSpecifier [: (*yynode)->type = UnmanagedTypeSuffix::TypeRankSpecifier; :]
+-> unmanagedTypeSuffix [
+ member variable type: UnmanagedTypeSuffix::SuffixType;
+] ;;
+
+ nonArrayType=nonArrayType
+ ( 0 [: if (LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
+ { break; }
+ :] -- avoids swallowing the LBRACKETs in
+ -- newExpression/arrayCreationExpression.
+ #rankSpecifier=rankSpecifier
+ )*
+-> managedType ;;
+
+ nonArrayType=nonArrayType (#rankSpecifier=rankSpecifier)+
+-> arrayType ;;
+
+ LBRACKET [: (*yynode)->dimensionSeperatorCount = 0; :]
+ ( COMMA [: (*yynode)->dimensionSeperatorCount++; :] )*
+ RBRACKET
+-> rankSpecifier [
+ member variable dimensionSeperatorCount: int;
+] ;;
+
+ builtinClassType=builtinClassType
+ | optionallyNullableType=optionallyNullableType
+-> nonArrayType ;;
+
+ typeName=typeName
+ | builtinClassType=builtinClassType
+-> classType ;;
+
+ OBJECT [: (*yynode)->type = BuiltinClassType::TypeObject; :]
+ | STRING [: (*yynode)->type = BuiltinClassType::TypeString; :]
+-> builtinClassType [
+ member variable type: BuiltinClassType::BuiltinClassTypeEnum;
+] ;;
+
+-- NULLABLE TYPES are new in C# 2.0 and need to be expressed a little bit
+-- differently than in LALR grammars like in the C# specification.
+
+ nonNullableType=nonNullableType
+ ( ?[: compatibilityMode() >= CSharp20Compatibility :]
+ QUESTION [: (*yynode)->nullable = true; :]
+ |
+ 0 [: (*yynode)->nullable = false; :]
+ )
+-> optionallyNullableType [
+ member variable nullable: bool;
+] ;;
+
+ typeName=typeName
+ | simpleType=simpleType
+-> nonNullableType ;;
+
+
+-- Now for SIMPLE TYPES, this is easier ;)
+
+ (
+ numericType=numericType
+ [: (*yynode)->type = SimpleType::TypeNumeric; :]
+ | BOOL
+ [: (*yynode)->type = SimpleType::TypeBool; :]
+ )
+-> simpleType [
+ member variable type: SimpleType::SimpleTypeEnum;
+] ;;
+
+
+-- NUMERIC TYPES include INTEGRAL TYPES, FLOATING POINT TYPES, and DECIMAL.
+
+ (
+ intType=integralType
+ [: (*yynode)->type = NumericType::TypeIntegral; :]
+ | floatType=floatingPointType
+ [: (*yynode)->type = NumericType::TypeFloatingPoint; :]
+ | DECIMAL
+ [: (*yynode)->type = NumericType::TypeDecimal; :]
+ )
+-> numericType [
+ member variable type: NumericType::NumericTypeEnum;
+] ;;
+
+ (
+ SBYTE [: (*yynode)->type = IntegralTypes::TypeSbyte; :]
+ | BYTE [: (*yynode)->type = IntegralTypes::TypeByte; :]
+ | SHORT [: (*yynode)->type = IntegralTypes::TypeShort; :]
+ | USHORT [: (*yynode)->type = IntegralTypes::TypeUshort; :]
+ | INT [: (*yynode)->type = IntegralTypes::TypeInt; :]
+ | UINT [: (*yynode)->type = IntegralTypes::TypeUint; :]
+ | LONG [: (*yynode)->type = IntegralTypes::TypeLong; :]
+ | ULONG [: (*yynode)->type = IntegralTypes::TypeUlong; :]
+ | CHAR [: (*yynode)->type = IntegralTypes::TypeChar; :]
+ )
+-> integralType [
+ member variable type: IntegralTypes::IntegralTypeEnum;
+] ;;
+
+ (
+ FLOAT [: (*yynode)->type = FloatingPointType::TypeFloat; :]
+ | DOUBLE [: (*yynode)->type = FloatingPointType::TypeDouble; :]
+ )
+-> floatingPointType [
+ member variable type: FloatingPointType::FloatingPointTypeEnum;
+] ;;
+
+
+-- TYPE NAMES and NAMESPACE NAMES are the same thing,
+-- essentially qualified identifiers with optional type arguments.
+
+ namespaceName=namespaceOrTypeName
+-> namespaceName ;;
+
+ typeName=namespaceOrTypeName
+-> typeName ;;
+
+ ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
+ | 0
+ )
+ #namePart=namespaceOrTypeNamePart @ DOT
+-> namespaceOrTypeName ;;
+
+ identifier=identifier
+ try/rollback(
+ ?[: compatibilityMode() >= CSharp20Compatibility :]
+ typeArguments=typeArguments
+ | 0
+ ) catch(0)
+-> namespaceOrTypeNamePart ;;
+
+ typeName=namespaceOrTypeNameSafe
+-> typeNameSafe ;;
+
+ ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
+ | 0
+ )
+ #namePart=namespaceOrTypeNamePart
+ ( 0 [: if (LA(2).kind != Token_IDENTIFIER) break; :] -- exit the "star loop"
+ DOT #namePart=namespaceOrTypeNamePart
+ )*
+-> namespaceOrTypeNameSafe ;;
+
+
+-- QUALIFIED IDENTIFIERs are either qualified ones or raw identifiers.
+-- In the C# grammar, they're only used as namespace Names.
+
+ #name=identifier @ DOT
+-> qualifiedIdentifier ;;
+
+
+
+
+--
+-- MODIFIERS, KEYWORDS, LITERALS, and the IDENTIFIER wrapper
+--
+
+ (
+ REF [: (*yynode)->parameterType = Parameter::ReferenceParameter; :]
+ | OUT [: (*yynode)->parameterType = Parameter::OutputParameter; :]
+ | 0 [: (*yynode)->parameterType = Parameter::ValueParameter; :]
+ )
+-> optionalParameterModifier [
+ member variable parameterType: Parameter::ParameterTypeEnum;
+] ;;
+
+-- These are all the Modifiers that can occur in front of type and type member
+-- declarations. They are not valid in every combination, this has to be
+-- checked seperately after parsing this rule.
+
+ (
+ PUBLIC [: (*yynode)->accessPolicy = AccessPolicy::AccessPublic; :]
+ | PRIVATE [: (*yynode)->accessPolicy = AccessPolicy::AccessPrivate; :]
+ | PROTECTED
+ [: if ((*yynode)->accessPolicy == AccessPolicy::AccessInternal)
+ (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal;
+ else
+ (*yynode)->accessPolicy = AccessPolicy::AccessProtected;
+ :]
+ | INTERNAL
+ [: if ((*yynode)->accessPolicy == AccessPolicy::AccessProtected)
+ (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal;
+ else
+ (*yynode)->accessPolicy = AccessPolicy::AccessInternal;
+ :]
+ | NEW [: (*yynode)->modifiers |= Modifiers::ModNew; :]
+ | ABSTRACT [: (*yynode)->modifiers |= Modifiers::ModAbstract; :]
+ | SEALED [: (*yynode)->modifiers |= Modifiers::ModSealed; :]
+ | STATIC [: (*yynode)->modifiers |= Modifiers::ModStatic; :]
+ | READONLY [: (*yynode)->modifiers |= Modifiers::ModReadonly; :]
+ | VOLATILE [: (*yynode)->modifiers |= Modifiers::ModVolatile; :]
+ | VIRTUAL [: (*yynode)->modifiers |= Modifiers::ModVirtual; :]
+ | OVERRIDE [: (*yynode)->modifiers |= Modifiers::ModOverride; :]
+ | EXTERN [: (*yynode)->modifiers |= Modifiers::ModExtern; :]
+ -- unsafe grammar extension: "unsafe" keyword
+ | UNSAFE [: (*yynode)->modifiers |= Modifiers::ModUnsafe; :]
+ -- unspecified unsafe Modifier, but used by MS and Mono, so accept it here as well:
+ | ?[: compatibilityMode() >= CSharp20Compatibility :]
+ FIXED [: (*yynode)->modifiers |= Modifiers::ModFixed; :]
+ )*
+-> optionalModifiers [
+ member variable modifiers: unsigned int; -- using the ModifierEnum values
+ member variable accessPolicy: AccessPolicy::AccessPolicyEnum;
+] ;;
+
+ (
+ keyword=ABSTRACT | keyword=AS | keyword=BASE | keyword=BOOL
+ | keyword=BREAK | keyword=BYTE | keyword=CASE | keyword=CATCH | keyword=CHAR
+ | keyword=CHECKED | keyword=CLASS | keyword=CONST | keyword=CONTINUE
+ | keyword=DECIMAL | keyword=DEFAULT | keyword=DELEGATE | keyword=DO
+ | keyword=DOUBLE | keyword=ELSE | keyword=ENUM | keyword=EVENT
+ | keyword=EXPLICIT | keyword=EXTERN | keyword=FINALLY | keyword=FIXED
+ | keyword=FLOAT | keyword=FOREACH | keyword=FOR | keyword=GOTO | keyword=IF
+ | keyword=IMPLICIT | keyword=IN | keyword=INT | keyword=INTERFACE
+ | keyword=INTERNAL | keyword=IS | keyword=LOCK | keyword=LONG
+ | keyword=NAMESPACE | keyword=NEW | keyword=OBJECT | keyword=OPERATOR
+ | keyword=OUT | keyword=OVERRIDE | keyword=PARAMS | keyword=PRIVATE
+ | keyword=PROTECTED | keyword=PUBLIC | keyword=READONLY | keyword=REF
+ | keyword=RETURN | keyword=SBYTE | keyword=SEALED | keyword=SHORT
+ | keyword=SIZEOF | keyword=STACKALLOC | keyword=STATIC | keyword=STRING
+ | keyword=STRUCT | keyword=SWITCH | keyword=THIS | keyword=THROW | keyword=TRY
+ | keyword=TYPEOF | keyword=UINT | keyword=ULONG | keyword=UNCHECKED
+ | keyword=UNSAFE | keyword=USHORT | keyword=USING | keyword=VIRTUAL
+ | keyword=VOID | keyword=VOLATILE | keyword=WHILE
+ )
+-> keyword ;;
+
+ (
+ ident=IDENTIFIER
+ | ident=ADD
+ | ident=ALIAS
+ | ident=GET
+ | ident=GLOBAL
+ | ident=PARTIAL
+ | ident=REMOVE
+ | ident=SET
+ | ident=VALUE
+ | ident=WHERE
+ | ident=YIELD
+ | ident=ASSEMBLY
+ )
+-> identifier ;;
+
+ (
+ TRUE [: (*yynode)->literalType = Literal::TypeTrue; :]
+ | FALSE [: (*yynode)->literalType = Literal::TypeFalse; :]
+ | NULL [: (*yynode)->literalType = Literal::TypeNull; :]
+ |
+ integerLiteral=INTEGER_LITERAL
+ [: (*yynode)->literalType = Literal::TypeInteger; :]
+ |
+ floatingPointLiteral=REAL_LITERAL
+ [: (*yynode)->literalType = Literal::TypeReal; :]
+ |
+ characterLiteral=CHARACTER_LITERAL
+ [: (*yynode)->literalType = Literal::TypeCharacter; :]
+ |
+ stringLiteral=STRING_LITERAL
+ [: (*yynode)->literalType = Literal::TypeString; :]
+ )
+-> literal [
+ member variable literalType: Literal::LiteralTypeEnum;
+] ;;
+
+
+
+
+
+
+-----------------------------------------------------------------
+-- Code segments copied to the implementation (.cpp) file.
+-- If existent, kdevelop-pg's current syntax requires this block
+-- to occur at the end of the file.
+-----------------------------------------------------------------
+
+[:
+#include "csharplexer.h"
+
+
+namespace CSharp
+{
+
+void Parser::tokenize( ParseSession* session )
+{
+ Lexer lexer( this, session );
+
+ int kind = Parser::Token_EOF;
+ do
+ {
+ kind = lexer.yylex();
+ //std::Cerr << lexer.YYText() << std::Endl; //" "; // debug output
+
+ if ( !kind ) // when the lexer returns 0, the end of file is reached
+ kind = Parser::Token_EOF;
+
+ Parser::Token &t = this->tokenStream->next();
+ t.kind = kind;
+ t.begin = lexer.tokenBegin();
+ t.end = lexer.tokenEnd();
+ }
+ while (kind != Parser::Token_EOF);
+
+ this->yylex(); // produce the look ahead token
+}
+
+
+Parser::CSharpCompatibilityMode Parser::compatibilityMode()
+{
+ return m_compatibilityMode;
+}
+void Parser::setCompatibilityMode( Parser::CSharpCompatibilityMode Mode )
+{
+ m_compatibilityMode = Mode;
+}
+
+void Parser::ppDefineSymbol( QString symbolName )
+{
+ m_ppDefinedSymbols.insert( symbolName );
+}
+
+void Parser::ppUndefineSymbol( QString symbolName )
+{
+ m_ppDefinedSymbols.remove( symbolName );
+}
+
+bool Parser::ppIsSymbolDefined( QString symbolName )
+{
+ return (m_ppDefinedSymbols.find(symbolName) != m_ppDefinedSymbols.end());
+}
+
+
+// Rather hackish solution for recognizing expressions like
+// "a is SomeType ? ifExp : elseExp", see conditionalExpression.
+// Needs three methods to fix parsing for about 0.2% of all C# source files.
+
+bool Parser::isNullableType( TypeAst *type )
+{
+ if ( !type )
+ return false;
+ else if ( !type->unmanagedType )
+ return false;
+ else if ( !type->unmanagedType->regularType || type->unmanagedType->unmanagedTypeSuffixSequence )
+ return false;
+ else if ( !type->unmanagedType->regularType->optionallyNullableType )
+ return false;
+ else if ( type->unmanagedType->regularType->optionallyNullableType->nullable == false )
+ return false;
+ else // if ( type->optionallyNullableType->nullable == true )
+ return true;
+}
+
+// This method is only to be called after isNullableType(Type) returns true,
+// and therefore expects all the appropriate members not to be 0.
+void Parser::unsetNullableType( TypeAst *type )
+{
+ type->unmanagedType->regularType->optionallyNullableType->nullable = false;
+}
+
+// This method expects nullCoalescingExpression to be fully parsed and valid.
+// (Otherwise, this method is not called at all.
+TypeAst *Parser::lastRelationalExpressionRestType(
+ NullCoalescingExpressionAst *nullCoalescingExpression )
+{
+ RelationalExpressionAst *relexp =
+ nullCoalescingExpression
+ ->expressionSequence->back()->element // gets a logicalOrExpression
+ ->expressionSequence->back()->element // gets a logicalAndExpression
+ ->expressionSequence->back()->element // gets a bitOrExpression
+ ->expressionSequence->back()->element // gets a bitXorExpression
+ ->expressionSequence->back()->element // gets a bitAndExpression
+ ->expressionSequence->back()->element // gets an equalityExpression
+ ->expression // gets a RelationalExpression
+ ;
+
+ if ( relexp->additionalExpressionSequence != 0 )
+ return relexp->additionalExpressionSequence->back()->element->type;
+ else
+ return 0;
+}
+
+
+Parser::ParserState *Parser::copyCurrentState()
+{
+ ParserState *state = new ParserState();
+ state->ltCounter = m_state.ltCounter;
+ return state;
+}
+
+void Parser::restoreState( Parser::ParserState *state )
+{
+ m_state.ltCounter = state->ltCounter;
+}
+
+} // end of namespace CSharp
+
+:]
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp (revision 1522570)
@@ -0,0 +1,265 @@
+/*****************************************************************************
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+#include "csharppphandlervisitor.h"
+#include "csharpppparser.h"
+#include "csharpppscope.h"
+#include "parsesession.h"
+
+#include <QString>
+
+
+namespace CSharpPP
+{
+
+HandlerVisitor::HandlerVisitor(CSharp::ParseSession* session)
+ : DefaultVisitor(), m_session(session), m_scope(0)
+{
+}
+
+HandlerVisitor::~HandlerVisitor()
+{
+}
+
+void HandlerVisitor::setScope(Scope* currentScope)
+{
+ m_scope = currentScope;
+}
+
+
+
+void HandlerVisitor::visitPPDeclaration(PPDeclarationAst* node)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+ else if (m_scope->isActive() == false)
+ return; // don't do anything if the current section is #if'd out.
+
+ QString symbolName = m_session->symbol(node->conditionalSymbol);
+
+ if (node->type == PPDeclaration::TypeDefine)
+ m_scope->csharpParser()->ppDefineSymbol(symbolName);
+ else if (node->type == PPDeclaration::TypeUndef)
+ m_scope->csharpParser()->ppUndefineSymbol(symbolName);
+}
+
+void HandlerVisitor::visitPPIfClause(PPIfClauseAst* node)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ m_scope->pushScope(Scope::TypeIf, &m_scope);
+
+ if (m_scope->isActive() == false)
+ return;
+ else if (m_scope->isWaitingForActiveSection())
+ {
+ visitNode(node->expression);
+ m_scope->setActivated(m_expressionBool);
+ }
+ else
+ m_scope->setActivated(false);
+}
+
+void HandlerVisitor::visitPPElifClause(PPElifClauseAst* node)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ if (m_scope->type() != Scope::TypeIf)
+ {
+ m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
+ "#elif is unexpected here");
+ }
+
+ if (m_scope->isWaitingForActiveSection())
+ {
+ visitNode(node->expression);
+ m_scope->setActivated(m_expressionBool);
+ }
+ else
+ m_scope->setActivated(false);
+}
+
+void HandlerVisitor::visitPPElseClause(PPElseClauseAst*)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ if (m_scope->type() != Scope::TypeIf)
+ {
+ m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
+ "#else is unexpected here");
+ }
+
+ if (m_scope->isWaitingForActiveSection())
+ m_scope->setActivated(true);
+ else
+ m_scope->setActivated(false);
+}
+
+void HandlerVisitor::visitPPEndifClause(PPEndifClauseAst*)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ bool successful = m_scope->popScope( Scope::TypeIf, &m_scope );
+ if (!successful && m_scope->csharpParser() != 0)
+ {
+ m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
+ "#endif is unexpected here");
+ }
+}
+
+void HandlerVisitor::visitPPDiagnostic(PPDiagnosticAst* node)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ if (!m_scope->csharpParser() != 0)
+ {
+ ::CSharp::Parser::ProblemType diagnosticType;
+ if (node->type == PPDiagnostic::TypeError)
+ diagnosticType = ::CSharp::Parser::error;
+ else // if (node->type == PPDiagnostic::TypeWarning)
+ diagnosticType = ::CSharp::Parser::warning;
+
+ if (node->message)
+ {
+ m_scope->csharpParser()->ppDiagnostic( diagnosticType, m_session->symbol(node->message) );
+ }
+ else
+ m_scope->csharpParser()->ppDiagnostic( diagnosticType );
+ }
+}
+
+void HandlerVisitor::visitPPRegion(PPRegionAst* node)
+{
+ if (m_scope == 0 || m_session == 0)
+ return;
+
+ if (node->type == PPRegion::TypeRegion)
+ {
+ m_scope->pushScope( Scope::TypeRegion, &m_scope );
+ }
+ if (node->type == PPRegion::TypeEndregion)
+ {
+ bool successful = m_scope->popScope( Scope::TypeRegion, &m_scope );
+ if (!successful && m_scope->csharpParser() != 0)
+ {
+ m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
+ "#endregion is unexpected here");
+ }
+ }
+}
+
+void HandlerVisitor::visitPPLine(PPLineAst* node)
+{
+ DefaultVisitor::visitPPLine(node);
+}
+
+void HandlerVisitor::visitPPPragma(PPPragmaAst* node)
+{
+ DefaultVisitor::visitPPPragma(node);
+}
+
+
+void HandlerVisitor::visitPPExpression(PPExpressionAst* node)
+{
+ bool result = false;
+ const KDevPG::ListNode<PPAndExpressionAst*> *_It =
+ node->expressionSequence->front(), *_End = _It;
+
+ do
+ {
+ visitNode(_It->element);
+ _It = _It->next;
+
+ result = result || m_expressionBool;
+ // PPExpression is actually PPOrExpression
+ }
+ while (_It != _End && result == false);
+
+ m_expressionBool = result;
+}
+
+void HandlerVisitor::visitPPAndExpression(PPAndExpressionAst* node)
+{
+ bool result = true;
+ const KDevPG::ListNode<PPEqualityExpressionAst*> *_It =
+ node->expressionSequence->front(), *_End = _It;
+
+ do
+ {
+ visitNode(_It->element);
+ _It = _It->next;
+
+ result = result && m_expressionBool;
+ }
+ while (_It != _End && result == true);
+
+ m_expressionBool = result;
+}
+
+void HandlerVisitor::visitPPEqualityExpression(PPEqualityExpressionAst* node)
+{
+ DefaultVisitor::visitPPEqualityExpression(node);
+ // the child visit_*() methods assign the right value to m_expressionBool
+}
+
+void HandlerVisitor::visitPPEqualityExpressionRest(PPEqualityExpressionRestAst* node)
+{
+ bool previous = m_expressionBool;
+ visitNode(node->expression);
+ if (node->equalityOperator == PPEqualityExpressionRest::opEqual)
+ m_expressionBool = (previous == m_expressionBool);
+ else // opNotEqual
+ m_expressionBool = (previous != m_expressionBool);
+}
+
+void HandlerVisitor::visitPPUnaryExpression(PPUnaryExpressionAst* node)
+{
+ DefaultVisitor::visitPPUnaryExpression(node);
+
+ if (node->negated == true)
+ m_expressionBool = !m_expressionBool;
+}
+
+void HandlerVisitor::visitPPPrimaryExpression(PPPrimaryExpressionAst* node)
+{
+ switch (node->type)
+ {
+ case PPPrimaryExpression::TypeTrue:
+ m_expressionBool = true;
+ break;
+ case PPPrimaryExpression::TypeFalse:
+ m_expressionBool = false;
+ break;
+ case PPPrimaryExpression::TypeConditionalSymbol:
+ {
+ m_expressionBool = m_scope->csharpParser()->ppIsSymbolDefined(m_session->symbol(node->conditionalSymbol));
+ }
+ break;
+ case PPPrimaryExpression::TypeParenthesisExpression:
+ DefaultVisitor::visitNode(node->parenthesisExpression);
+ break;
+ }
+}
+
+} // end of namespace CSharpPP
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h (revision 1522570)
@@ -0,0 +1,138 @@
+/*****************************************************************************
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+#ifndef CSHARP_PP_SCOPE_H
+#define CSHARP_PP_SCOPE_H
+
+namespace CSharp
+{
+ class Parser;
+}
+
+namespace CSharpPP
+{
+
+/**
+ * Pre-processor Scopes are managed by the pre-processor parser
+ * and contain information about the current state of how the
+ * pre-processor directives are nested at the moment, and most importantly,
+ * if the current code segment is to be included or excluded by the lexer.
+ *
+ * After each pre-processor directive, the lexer checks the current Scope
+ * in order to to know if the upcoming text is to be treated as tokens
+ * or like #ifdef'd out.
+ */
+class Scope
+{
+public:
+ enum ScopeType {
+ TypeRoot,
+ TypeIf,
+ TypeRegion
+ };
+
+ Scope( CSharp::Parser* parser );
+ ~Scope();
+
+ /**
+ * Retrieves the last child of the Scope hierarchy. That child contains
+ * the state at the current code position and should be used for getting
+ * info.
+ */
+ Scope* currentScope();
+
+ Scope::ScopeType type();
+
+ /**
+ * Returns @true if the code at the current position is included into
+ * the parser's token stream, or @false if it's a skipped section.
+ * This is called by the lexer after each pre-processor line, and
+ * makes him treat the upcoming text either as tokens or like #ifdef'd out.
+ */
+ bool isActive();
+
+ /**
+ * Returns @true if the Scope corresponds to an #if/#elif/#else condition
+ * and has not yet seen a code segment that is included
+ * (as in: not skipped), and @false otherwise.
+ */
+ bool isWaitingForActiveSection();
+
+ /**
+ * Set the current state of the Scope to "active" or "not active".
+ * To be called for #if and #elif conditions with the expression value
+ * as argument.
+ */
+ void setActivated( bool active );
+
+ /**
+ * Creates a new child Scope inside this one, inheriting its state.
+ *
+ * @param type Determines the type of the new Scope.
+ * @param newCurrent The new current Scope, given as a return value.
+ * @return @true if the Scope has been created, or @false if this Scope
+ * already possesses a child (in this case, nothing is done).
+ */
+ bool pushScope( Scope::ScopeType type, Scope** newCurrent = 0 );
+
+ /**
+ * Destroys this Scope so that its parent is the current Scope again.
+ * If this one is already the root Scope, it is not destroyed and stays
+ * the currently active Scope.
+ *
+ * @param type The type of the Scope that should be closed.
+ * If it doesn't match with this Scope's type,
+ * it's semantically wrong and the Scope is not destroyed.
+ * @param newCurrent The new current Scope, given as a return value.
+ * @return @true if the Scope has been destroyed,
+ * @false if it is already the root Scope.
+ */
+ bool popScope( Scope::ScopeType type, Scope** newCurrent = 0 );
+
+ /**
+ * Sets the actual parser class - the one not handling the pre-processor.
+ */
+ void setCSharpParser( ::CSharp::Parser* parser );
+ ::CSharp::Parser* csharpParser();
+
+private:
+ Scope( Scope::ScopeType type, CSharp::Parser* parser, bool active );
+
+ void setParent( Scope* parent );
+ Scope* parent();
+
+ ScopeType m_type;
+ CSharp::Parser* m_parser;
+
+ /** Child Scope of the current one. (May be recursive.) */
+ Scope* m_child;
+
+ /** Parent Scope of the current one. */
+ Scope* m_parent;
+
+ bool m_isActive;
+
+ /** This flag is initially set true, and becomes false when an #if or
+ * #elif expression is found that evaluates to true. */
+ bool m_waitingForActiveSection;
+};
+
+} // end of namespace CSharpPP
+
+#endif // CSHARP_PP_SCOPE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h (revision 1522570)
@@ -0,0 +1,71 @@
+/*****************************************************************************
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+#ifndef CSHARP_PP_HANDLER_VISITOR_H
+#define CSHARP_PP_HANDLER_VISITOR_H
+
+#include "csharpppdefaultvisitor.h"
+
+namespace CSharp
+{
+class ParseSession;
+}
+
+namespace CSharpPP
+{
+
+class Scope;
+
+
+class HandlerVisitor : public DefaultVisitor
+{
+public:
+ HandlerVisitor( CSharp::ParseSession* session );
+ ~HandlerVisitor();
+
+ void setScope( Scope* currentScope );
+
+ virtual void visitPPDeclaration(PPDeclarationAst* node);
+ virtual void visitPPIfClause(PPIfClauseAst* node);
+ virtual void visitPPElifClause(PPElifClauseAst* node);
+ virtual void visitPPElseClause(PPElseClauseAst* node);
+ virtual void visitPPEndifClause(PPEndifClauseAst* node);
+ virtual void visitPPDiagnostic(PPDiagnosticAst* node);
+ virtual void visitPPRegion(PPRegionAst* node);
+ virtual void visitPPLine(PPLineAst* node);
+ virtual void visitPPPragma(PPPragmaAst* node);
+
+ virtual void visitPPExpression(PPExpressionAst* node);
+ virtual void visitPPAndExpression(PPAndExpressionAst* node);
+ virtual void visitPPEqualityExpression(PPEqualityExpressionAst* node);
+ virtual void visitPPEqualityExpressionRest(PPEqualityExpressionRestAst* node);
+ virtual void visitPPUnaryExpression(PPUnaryExpressionAst* node);
+ virtual void visitPPPrimaryExpression(PPPrimaryExpressionAst* node);
+
+private:
+ CSharp::ParseSession* m_session;
+ Scope* m_scope;
+
+ /** Temporary variable for evaluating #if and #elif conditions. */
+ bool m_expressionBool;
+};
+
+} // end of namespace CSharp_PP
+
+#endif // CSHARP_PP_HANDLER_VISITOR_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppp.g
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppp.g (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharppp.g (revision 1522570)
@@ -0,0 +1,437 @@
+-----------------------------------------------------------------------------
+-- Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
+--
+-- This grammar 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 grammar 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
+-- Lesser 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.
+-----------------------------------------------------------------------------
+
+
+-----------------------------------------------------------------------------
+-- Grammar for the pre-processor part of C# 2.0
+-- Modelled after the reference grammar of the C# 2.0 language specification
+-- (ECMA-334, Third Edition from June 2005, available at
+-- http://www.ecma-international.org/publications/standards/Ecma-334.htm).
+-----------------------------------------------------------------------------
+
+
+------------------------------------------------------------
+-- Global declarations
+------------------------------------------------------------
+
+[:
+#include <QtCore/QString>
+namespace KDevelop
+{
+class DUContext;
+}
+
+namespace CSharp
+{
+class Lexer;
+class ParseSession;
+}
+
+:]
+
+%export_macro "KDEVCSHARPPARSER_EXPORT"
+%export_macro_header "csharpparserexport.h"
+
+
+------------------------------------------------------------
+-- Parser class members
+------------------------------------------------------------
+
+%parserclass (public declaration)
+[:
+ enum PPParseResult {
+ ResultOk,
+ ResultInvalid,
+ ResultEof
+ };
+
+ /**
+ * Process a pre-processor line.
+ * This method occupies the lexer until a PP_NEW_LINE token is found,
+ * and carries out the appropriate action. For example, when processing
+ * a #define statement it stores the defined symbol, or when processing
+ * an #if statement it evaluates the expression and sets the correct value
+ * for the ppIsSectionSkipped() method.
+ *
+ * @param firstToken The first token of the pre-processor line.
+ * @param Scope The currently active pre-processor state, stored as a Scope.
+ * @param lexer The lexer object which is currently processing the source file.
+ * @return CSharpPP::Parser::ResultOk if the line was processed correctly,
+ * CSharpPP::Parser::ResultInvalid if there was a parsing error,
+ * or CSharpPP::Parser::ResultEof if the end of file was found (unexpectedly).
+ */
+ Parser::PPParseResult ppParseLine(
+ Parser::TokenType firstToken, Scope *Scope, CSharp::Lexer *lexer, CSharp::ParseSession* session );
+:]
+
+%parserclass (private declaration)
+[:
+ Scope *m_scope;
+ CSharp::Lexer *m_lexer;
+
+ /**
+ * Transform the raw input into tokens.
+ * When this method returns, the parser's token stream has been filled
+ * and any parse_*() method can be called. Alternatively, the end of file
+ * has been reached and we have to issue an error.
+ */
+ void tokenize(bool &encounteredEof);
+
+ /**
+ * Add the currently lexed token into the token stream, using the
+ * given token kind. Used by the pre-processor that has to bypass
+ * the normal tokenizing process.
+ */
+ void addToken(Parser::TokenType tokenKind);
+
+ KDevPG::TokenStream m_tokenStream;
+ KDevPG::MemoryPool m_memoryPool;
+:]
+
+%parserclass (constructor)
+[:
+ setTokenStream(&m_tokenStream);
+ setMemoryPool(&m_memoryPool);
+:]
+
+
+
+------------------------------------------------------------
+-- Enumeration Types for additional AST members
+------------------------------------------------------------
+
+%namespace
+[:
+class Scope;
+
+namespace PPEqualityExpressionRest
+{
+ enum PPEqualityOperatorEnum {
+ opEqual,
+ opNotEqual
+ };
+}
+
+namespace PPPrimaryExpression
+{
+ enum PPPrimaryExpressionTypeEnum {
+ TypeTrue,
+ TypeFalse,
+ TypeConditionalSymbol,
+ TypeParenthesisExpression
+ };
+}
+
+namespace PPDeclaration
+{
+ enum PPDeclarationTypeEnum {
+ TypeDefine,
+ TypeUndef
+ };
+}
+
+namespace PPDiagnostic
+{
+ enum PPDiagnosticTypeEnum {
+ TypeError,
+ TypeWarning
+ };
+}
+
+namespace PPRegion
+{
+ enum PPRegionTypeEnum {
+ TypeRegion,
+ TypeEndregion
+ };
+}
+:]
+
+
+
+
+------------------------------------------------------------
+-- List of defined tokens
+------------------------------------------------------------
+
+-- start tokens:
+%token PP_DEFINE ("#define"), PP_UNDEF ("#undef"), PP_IF ("#if"),
+ PP_ELIF ("#elif"), PP_ELSE ("#else"), PP_ENDIF ("#endif"),
+ PP_LINE ("#line"), PP_ERROR ("#error"), PP_WARNING ("#warning"),
+ PP_REGION ("#region"), PP_ENDREGION ("#endregion"),
+ PP_PRAGMA ("#pragma") ;;
+
+-- value tokens and the line break:
+%token PP_CONDITIONAL_SYMBOL ("pre-processor symbol"),
+ PP_NEW_LINE ("line break"), PP_LINE_NUMBER ("line number"),
+ PP_FILE_NAME ("file name (in double quotes)"),
+ PP_IDENTIFIER_OR_KEYWORD ("identifier or keyword"),
+ PP_MESSAGE ("single-line text"), PP_PRAGMA_TEXT ("pragma text") ;;
+
+-- operators and keywords:
+%token PP_EQUAL ("=="), PP_NOT_EQUAL ("!="), PP_LOG_AND ("&&"),
+ PP_LOG_OR ("||"), PP_BANG ("!"), PP_LPAREN ("("), PP_RPAREN (")"),
+ PP_TRUE ("true"), PP_FALSE ("false"), PP_DEFAULT ("default") ;;
+
+-- token that makes the parser fail in any case:
+%token PP_INVALID ("invalid token") ;;
+
+
+
+
+------------------------------------------------------------
+-- Start of the actual grammar
+------------------------------------------------------------
+
+--
+-- Preprocessor rules. Those are handled before the grammar is
+-- actually processed, as part of the lexing (called from within the lexer).
+--
+
+ ( declaration=PPDeclaration
+ | ifClause=PPIfClause
+ | elifClause=PPElifClause
+ | elseClause=PPElseClause
+ | endifClause=PPEndifClause
+ | diagnostic=PPDiagnostic
+ | region=PPRegion
+ | line=PPLine
+ | pragma=PPPragma
+ )
+ PP_NEW_LINE
+-> PPDirective ;;
+
+ ( PP_DEFINE [: (*yynode)->type = PPDeclaration::TypeDefine; :]
+ | PP_UNDEF [: (*yynode)->type = PPDeclaration::TypeUndef; :]
+ )
+ conditionalSymbol=PP_CONDITIONAL_SYMBOL
+-> PPDeclaration [
+ member variable type: PPDeclaration::PPDeclarationTypeEnum;
+] ;;
+
+ PP_IF expression=PPExpression
+-> PPIfClause ;;
+
+ PP_ELIF expression=PPExpression
+-> PPElifClause ;;
+
+ PP_ELSE
+-> PPElseClause ;;
+
+ PP_ENDIF
+-> PPEndifClause ;;
+
+ ( PP_ERROR [: (*yynode)->type = PPDiagnostic::TypeError; :]
+ | PP_WARNING [: (*yynode)->type = PPDiagnostic::TypeWarning; :]
+ )
+ (message=PP_MESSAGE | 0)
+-> PPDiagnostic [
+ member variable type: PPDiagnostic::PPDiagnosticTypeEnum;
+] ;;
+
+ ( PP_REGION [: (*yynode)->type = PPRegion::TypeRegion; :]
+ | PP_ENDREGION [: (*yynode)->type = PPRegion::TypeEndregion; :]
+ )
+ (label=PP_MESSAGE | 0)
+-> PPRegion [
+ member variable type: PPRegion::PPRegionTypeEnum;
+] ;;
+
+ PP_LINE
+ ( lineNumber=PP_LINE_NUMBER (fileName=PP_FILE_NAME | 0)
+ | tokenDefault=PP_DEFAULT
+ | identifierOrKeyword=PP_IDENTIFIER_OR_KEYWORD
+ )
+-> PPLine ;;
+
+ PP_PRAGMA (pragmaText=PP_PRAGMA_TEXT | 0)
+-> PPPragma ;;
+
+
+
+-- Expressions used in #if and #elif
+
+ #expression=PPAndExpression @ PP_LOG_OR
+-> PPExpression ;;
+
+ #expression=PPEqualityExpression @ PP_LOG_AND
+-> PPAndExpression ;;
+
+ expression=PPUnaryExpression
+ (#additionalExpression=PPEqualityExpressionRest)*
+-> PPEqualityExpression ;;
+
+ ( PP_EQUAL [: (*yynode)->equalityOperator = PPEqualityExpressionRest::opEqual; :]
+ | PP_NOT_EQUAL [: (*yynode)->equalityOperator = PPEqualityExpressionRest::opNotEqual; :]
+ )
+ expression=PPUnaryExpression
+-> PPEqualityExpressionRest [
+ member variable equalityOperator: PPEqualityExpressionRest::PPEqualityOperatorEnum;
+] ;;
+
+ ( PP_BANG expression=PPPrimaryExpression [: (*yynode)->negated = true; :]
+ | expression=PPPrimaryExpression [: (*yynode)->negated = false; :]
+ )
+-> PPUnaryExpression [
+ member variable negated: bool;
+] ;;
+
+ (
+ PP_TRUE [: (*yynode)->type = PPPrimaryExpression::TypeTrue; :]
+ | PP_FALSE [: (*yynode)->type = PPPrimaryExpression::TypeFalse; :]
+ | conditionalSymbol=PP_CONDITIONAL_SYMBOL
+ [: (*yynode)->type = PPPrimaryExpression::TypeConditionalSymbol; :]
+ | PP_LPAREN parenthesisExpression=PPExpression PP_RPAREN
+ [: (*yynode)->type = PPPrimaryExpression::TypeParenthesisExpression; :]
+ )
+-> PPPrimaryExpression [
+ member variable type: PPPrimaryExpression::PPPrimaryExpressionTypeEnum;
+] ;;
+
+
+
+
+
+-----------------------------------------------------------------
+-- Code segments copied to the implementation (.cpp) file.
+-- If existent, kdevelop-pg's current syntax requires this block
+-- to occur at the end of the file.
+-----------------------------------------------------------------
+
+[:
+#include "csharpparser.h"
+#include "csharplexer.h"
+#include "csharppphandlervisitor.h"
+#include "csharpppscope.h"
+
+#include <QString>
+
+
+namespace CSharpPP
+{
+
+void Parser::tokenize(bool &encounteredEof)
+{
+ encounteredEof = false;
+ int kind = Parser::Token_EOF;
+ do
+ {
+ kind = m_lexer->yylex();
+ //std::cerr << "pp: " << lexer.YYText() << std::endl; //" "; // debug output
+
+ Parser::Token &t = this->tokenStream->next();
+ t.kind = kind;
+ t.begin = m_lexer->tokenBegin();
+ t.end = m_lexer->tokenEnd();
+
+ if (kind == Parser::Token_EOF)
+ {
+ t.kind = Parser::Token_PP_NEW_LINE;
+ encounteredEof = true;
+ break;
+ }
+ }
+ while (kind != Parser::Token_PP_NEW_LINE);
+
+ Parser::Token &t = this->tokenStream->next();
+ t.kind = Parser::Token_EOF;
+ t.begin = m_lexer->tokenBegin();
+ t.end = m_lexer->tokenEnd();
+
+ this->yylex(); // produce the look ahead token
+}
+
+void Parser::addToken(Parser::TokenType tokenKind)
+{
+ //std::cerr << "pp: " << lexer.YYText() << std::endl; //" "; // debug output
+ Parser::Token &t = this->tokenStream->next();
+ t.kind = tokenKind;
+ t.begin = m_lexer->tokenBegin();
+ t.end = m_lexer->tokenEnd();
+}
+
+
+Parser::PPParseResult Parser::ppParseLine(
+ Parser::TokenType firstToken, Scope* Scope, CSharp::Lexer *lexer, CSharp::ParseSession* session )
+{
+ // 0) setup
+ if (Scope == 0)
+ return Parser::ResultInvalid;
+
+ m_scope = Scope;
+ bool encounteredEof;
+
+ // 1) tokenize
+ m_lexer = lexer;
+ addToken(firstToken);
+ tokenize(encounteredEof);
+
+ // 2) parse
+ PPDirectiveAst* PPDirectiveNode = 0;
+ bool matched = parsePPDirective(&PPDirectiveNode);
+
+ if (matched)
+ {
+ HandlerVisitor v(session);
+ v.setScope(m_scope);
+ v.visitNode(PPDirectiveNode);
+ }
+ else
+ {
+ expectedSymbol(AstNode::PPDirectiveKind, "PPDirective"); // ### remove me
+ return Parser::ResultInvalid;
+ }
+
+ if (encounteredEof)
+ return Parser::ResultEof;
+ else
+ return Parser::ResultOk;
+}
+
+
+// custom error recovery
+void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
+{
+ //printTokenEnvironment(this);
+ if (m_scope->csharpParser() != 0)
+ {
+ m_scope->csharpParser()->reportProblem(
+ CSharp::Parser::error,
+ QString("Invalid pre-processor directive: Expected token ``%1''").arg(name)
+ //+ "'' instead of ``" + currentTokenText
+ );
+ }
+}
+
+void Parser::expectedSymbol(int /*expectedSymbol*/, const QString& name)
+{
+ //printTokenEnvironment(this);
+ if (m_scope->csharpParser() != 0)
+ {
+ m_scope->csharpParser()->reportProblem(
+ CSharp::Parser::error,
+ QString("Invalid pre-processor directive: Expected symbol ``%1''").arg(name)
+ //+ "'' instead of ``" + currentTokenText
+ );
+ }
+}
+
+} // end of namespace CSharpPP
+
+:]
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.h (revision 1522570)
@@ -0,0 +1,77 @@
+/*****************************************************************************
+ * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+#include "csharpparser.h"
+#include "csharpppparser.h"
+
+#include <iostream>
+
+#ifndef DONT_INCLUDE_FLEXLEXER
+#include "FlexLexer.h"
+#endif
+
+// The YY_USER_ACTION macro is called whenever a token is found by Flex
+#define YY_USER_ACTION \
+m_tokenBegin = m_tokenEnd; \
+m_tokenEnd += yyleng;
+
+
+namespace CSharp
+{
+
+class Lexer : public yyFlexLexer
+{
+public:
+ Lexer( CSharp::Parser *parser, ParseSession* session );
+ void restart( CSharp::Parser *parser, ParseSession* session );
+
+ virtual ~Lexer() { cleanup(); }
+
+ int yylex();
+ const char *contents() const;
+ qint64 tokenBegin() { return m_tokenBegin; }
+ qint64 tokenEnd() { return m_tokenEnd; }
+
+private:
+ // Takes care of handling and destroying unclosed Scopes.
+ void cleanup();
+
+ // retrieves the upper-most pre-processor Scope
+ CSharpPP::Scope* ppCurrentScope();
+
+protected:
+ // custom input, replacing the Flex default input stdin
+ virtual int LexerInput( char *buf, int max_size );
+
+ // dismisses any lexer output (which should not happen anyways)
+ virtual void LexerOutput( const char * /*buf*/, int /*max_size*/ ) { return; }
+ virtual void LexerError( const char */*msg*/ ) { return; }
+
+private:
+ CSharp::Parser* m_parser;
+ ParseSession *m_session;
+ qint64 m_tokenBegin, m_tokenEnd;
+ qint64 m_currentOffset;
+ CSharpPP::Scope* m_ppRootScope;
+ KDevPG::LocationTable *m_locationTable;
+};
+
+} // end of namespace CSharp
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll (revision 1522570)
@@ -0,0 +1,628 @@
+%{
+/*****************************************************************************
+ * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+%}
+
+%option c++
+%option yyclass="CSharp::Lexer"
+%option noyywrap
+
+
+%{
+
+#define DONT_INCLUDE_FLEXLEXER
+#include "csharplexer.h"
+#include "csharpppscope.h"
+#include "parsesession.h"
+
+
+// This is meant to be called with the first token in a pre-processor line.
+// Pre-processing completely bypasses the normal tokenizing process.
+#define PP_PROCESS_TOKEN(t) \
+{ \
+ CSharpPP::Parser ppParser; \
+ CSharpPP::Parser::PPParseResult Result = \
+ ppParser.ppParseLine( CSharpPP::Parser::Token_##t, ppCurrentScope(), this, m_session ); \
+ \
+ if ( Result == CSharpPP::Parser::ResultEof ) \
+ { \
+ BEGIN(INITIAL); \
+ return 0; /* end of file */ \
+ } \
+ else if ( Result == CSharpPP::Parser::ResultInvalid ) \
+ { \
+ BEGIN(INITIAL); \
+ return Parser::Token_INVALID; \
+ } \
+ else if ( Result == CSharpPP::Parser::ResultOk ) \
+ { \
+ if (ppCurrentScope()->isActive()) \
+ BEGIN(INITIAL); \
+ else \
+ BEGIN(PP_SKIPPED_SECTION_PART); \
+ } \
+}
+
+%}
+
+
+ /* UTF-8 sequences, generated with the Unicode.hs script from
+ * http://lists.gnu.org/archive/html/help-flex/2005-01/msg00043.html */
+
+ /* 0x0041-0x005a, 0x005f, 0x0061-0x007a: one byte in UTF-8 */
+Letter1 [A-Za-z_]
+ /* 0x00c0-0x00d6, 0x00d8-0x00f6, 0x00f8-0x00ff */
+Letter2 [\xC3]([\x80-\x96]|[\x98-\xB6]|[\xB8-\xBF])
+ /* 0x0100-0x1fff */
+Letter3 [\xC4-\xDF][\x80-\xBF]|([\xE0][\xA0-\xBF]|[\xE1][\x80-\xBF])[\x80-\xBF]
+ /* 0x3040-0x318f */
+Letter4 [\xE3]([\x86][\x80-\x8F]|[\x81-\x85][\x80-\xBF])
+ /* 0x3300-0x337f */
+Letter5 [\xE3][\x8C-\x8D][\x80-\xBF]
+ /* 0x3400-0x3d2d */
+Letter6 [\xE3](\xB4[\x80-\xAD]|[\x90-\xB3][\x80-\xBF])
+ /* 0x4e00-0x9fff */
+Letter7 ([\xE4][\xB8-\xBF]|[\xE5-\xE9][\x80-\xBF])[\x80-\xBF]
+ /* 0xf900-0xfaff */
+Letter8 [\xEF][\xA4-\xAB][\x80-\xBF]
+
+Letter {Letter1}|{Letter2}|{Letter3}|{Letter4}|{Letter5}|{Letter6}|{Letter7}|{Letter8}
+
+
+ /* 0x0080-0xffff */
+Multibyte1 ([\xC2-\xDF]|[\xE0][\xA0-\xBF]|[\xE1-\xEF][\x80-\xBF])[\x80-\xBF]
+ /* 0x10000-0x10ffff */
+Multibyte2 (\xF0[\x90-\xBF]|\xF4[\x80-\x8F]|[\xF1-\xF3][\x80-\xBF])[\x80-\xBF][\x80-\xBF]
+ /* Unicode characters above 0x10ffff are not supported by C#. */
+ /* Any multi-byte Unicode character. Single-byte ones are just . in lex. */
+Multibyte {Multibyte1}|{Multibyte2}
+
+
+ /* 0x2028 and 0x2029, currently unused in this lexer
+ for performance and convenience reasons. */
+UnicodeNewLine [\xE2][\x80][\xA8-\xA9]
+
+
+ /* non-Unicode stuff */
+
+Whitespace [ \t\v\f]+
+LineComment "//"[^\n]*
+
+DecimalDigit [0-9]
+HexDigit [0-9a-fA-F]
+
+ShortUnicodeEscape [\\][u]{HexDigit}{HexDigit}{HexDigit}{HexDigit}
+LongUnicodeEscape [\\][U]{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}
+UnicodeEscape {ShortUnicodeEscape}|{LongUnicodeEscape}
+HexEscape [\\][x]{HexDigit}{HexDigit}?{HexDigit}?{HexDigit}?
+SimpleEscape [\\]([']|["]|[\\]|[0abfnrtv])
+Escape ({SimpleEscape}|{UnicodeEscape}|{HexEscape})
+
+IntegerSuffix (([Ll][Uu]?)|([Uu][Ll]?))
+DecimalLiteral {DecimalDigit}+{IntegerSuffix}?
+HexLiteral [0][xX]{HexDigit}+{IntegerSuffix}?
+IntegerLiteral ({DecimalLiteral}|{HexLiteral})
+
+Sign [+-]
+RealSuffix ([fF]|[dD]|[m_m])
+Exponent [eE]{Sign}?{DecimalDigit}+
+Real1 {DecimalDigit}+[\.]{DecimalDigit}+{Exponent}?{RealSuffix}?
+Real2 [\.]{DecimalDigit}+{Exponent}?{RealSuffix}?
+Real3 {DecimalDigit}+{Exponent}{RealSuffix}?
+Real4 {DecimalDigit}+{RealSuffix}
+RealLiteral ({Real1}|{Real2}|{Real3}|{Real4})
+InvalidReal {DecimalDigit}+[\.]{Exponent}?{RealSuffix}?
+
+AvailableIdentifier {Letter}({Letter}|{DecimalDigit})*
+Verbatim_identifier [@]{Letter}({Letter}|{DecimalDigit})*
+Identifier ({AvailableIdentifier}|{Verbatim_identifier})
+
+ppPrefix ^{Whitespace}?[#]{Whitespace}?
+ppNewLine {Whitespace}?{LineComment}?[\n]
+
+
+%x IN_BLOCKCOMMENT
+%x PP_EXPECT_NEW_LINE
+%x PP_DECLARATION
+%x PP_IF_CLAUSE
+%x PP_LINE
+%x PP_MESSAGE
+%x PP_PRAGMA
+%x PP_SKIPPED_SECTION_PART
+
+%%
+
+ /* whitespace, newlines and comments */
+
+{Whitespace} /* skip */ ;
+[\n] /* skip */ ;
+
+{LineComment} /* line comments, skip */ ;
+
+"/*" BEGIN(IN_BLOCKCOMMENT);
+<IN_BLOCKCOMMENT>{
+[^*\n]* /* eat anything that's not a '*' */ ;
+"*"+[^*/\n]* /* eat up '*'s that are not followed by slashes or newlines */;
+[\n] /* skip */ ;
+"*"+"/" BEGIN(INITIAL);
+<<EOF>> {
+ m_parser->reportProblem( Parser::error,
+ "Encountered end of file in an unclosed block comment" );
+ cleanup();
+ return Parser::Token_EOF;
+}
+}
+
+
+ /* seperators */
+
+"(" return Parser::Token_LPAREN;
+")" return Parser::Token_RPAREN;
+"{" return Parser::Token_LBRACE;
+"}" return Parser::Token_RBRACE;
+"[" return Parser::Token_LBRACKET;
+"]" return Parser::Token_RBRACKET;
+"," return Parser::Token_COMMA;
+";" return Parser::Token_SEMICOLON;
+"." return Parser::Token_DOT;
+
+
+ /* operators */
+
+":" return Parser::Token_COLON;
+"::" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
+ return Parser::Token_SCOPE;
+ }
+ else {
+ m_parser->reportProblem( Parser::error,
+ "Global alias access (with \"::\") is not supported by C# 1.0" );
+ return Parser::Token_INVALID;
+ }
+}
+"?" return Parser::Token_QUESTION;
+"??" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
+ return Parser::Token_QUESTIONQUESTION;
+ }
+ else {
+ m_parser->reportProblem( Parser::error,
+ "Null coalescing expressions (with \"??\") are not supported by C# 1.0" );
+ return Parser::Token_INVALID;
+ }
+}
+"!" return Parser::Token_BANG;
+"~" return Parser::Token_TILDE;
+"==" return Parser::Token_EQUAL;
+"<" return Parser::Token_LESS_THAN;
+"<=" return Parser::Token_LESS_EQUAL;
+">" return Parser::Token_GREATER_THAN;
+">=" return Parser::Token_GREATER_EQUAL;
+"!=" return Parser::Token_NOT_EQUAL;
+"&&" return Parser::Token_LOG_AND;
+"||" return Parser::Token_LOG_OR;
+"->" return Parser::Token_ARROW_RIGHT; // TODO: new in 2.0 or not?
+"++" return Parser::Token_INCREMENT;
+"--" return Parser::Token_DECREMENT;
+"=" return Parser::Token_ASSIGN;
+"+" return Parser::Token_PLUS;
+"+=" return Parser::Token_PLUS_ASSIGN;
+"-" return Parser::Token_MINUS;
+"-=" return Parser::Token_MINUS_ASSIGN;
+"*" return Parser::Token_STAR;
+"*=" return Parser::Token_STAR_ASSIGN;
+"/" return Parser::Token_SLASH;
+"/=" return Parser::Token_SLASH_ASSIGN;
+"&" return Parser::Token_BIT_AND;
+"&=" return Parser::Token_BIT_AND_ASSIGN;
+"|" return Parser::Token_BIT_OR;
+"|=" return Parser::Token_BIT_OR_ASSIGN;
+"^" return Parser::Token_BIT_XOR;
+"^=" return Parser::Token_BIT_XOR_ASSIGN;
+"%" return Parser::Token_REMAINDER;
+"%=" return Parser::Token_REMAINDER_ASSIGN;
+"<<" return Parser::Token_LSHIFT;
+"<<=" return Parser::Token_LSHIFT_ASSIGN;
+">>" return Parser::Token_RSHIFT;
+">>=" return Parser::Token_RSHIFT_ASSIGN;
+
+
+ /* reserved words */
+
+"abstract" return Parser::Token_ABSTRACT;
+"as" return Parser::Token_AS;
+"base" return Parser::Token_BASE;
+"bool" return Parser::Token_BOOL;
+"break" return Parser::Token_BREAK;
+"byte" return Parser::Token_BYTE;
+"case" return Parser::Token_CASE;
+"catch" return Parser::Token_CATCH;
+"char" return Parser::Token_CHAR;
+"checked" return Parser::Token_CHECKED;
+"class" return Parser::Token_CLASS;
+"const" return Parser::Token_CONST;
+"continue" return Parser::Token_CONTINUE;
+"decimal" return Parser::Token_DECIMAL;
+"default" return Parser::Token_DEFAULT;
+"delegate" return Parser::Token_DELEGATE;
+"do" return Parser::Token_DO;
+"double" return Parser::Token_DOUBLE;
+"else" return Parser::Token_ELSE;
+"enum" return Parser::Token_ENUM;
+"event" return Parser::Token_EVENT;
+"explicit" return Parser::Token_EXPLICIT;
+"extern" return Parser::Token_EXTERN;
+"false" return Parser::Token_FALSE;
+"finally" return Parser::Token_FINALLY;
+"fixed" return Parser::Token_FIXED;
+"float" return Parser::Token_FLOAT;
+"for" return Parser::Token_FOR;
+"foreach" return Parser::Token_FOREACH;
+"goto" return Parser::Token_GOTO;
+"if" return Parser::Token_IF;
+"implicit" return Parser::Token_IMPLICIT;
+"in" return Parser::Token_IN;
+"int" return Parser::Token_INT;
+"interface" return Parser::Token_INTERFACE;
+"internal" return Parser::Token_INTERNAL;
+"is" return Parser::Token_IS;
+"lock" return Parser::Token_LOCK;
+"long" return Parser::Token_LONG;
+"namespace" return Parser::Token_NAMESPACE;
+"new" return Parser::Token_NEW;
+"null" return Parser::Token_NULL;
+"object" return Parser::Token_OBJECT;
+"operator" return Parser::Token_OPERATOR;
+"out" return Parser::Token_OUT;
+"override" return Parser::Token_OVERRIDE;
+"params" return Parser::Token_PARAMS;
+"private" return Parser::Token_PRIVATE;
+"protected" return Parser::Token_PROTECTED;
+"public" return Parser::Token_PUBLIC;
+"readonly" return Parser::Token_READONLY;
+"ref" return Parser::Token_REF;
+"return" return Parser::Token_RETURN;
+"sbyte" return Parser::Token_SBYTE;
+"sealed" return Parser::Token_SEALED;
+"short" return Parser::Token_SHORT;
+"sizeof" return Parser::Token_SIZEOF;
+"stackalloc" return Parser::Token_STACKALLOC;
+"static" return Parser::Token_STATIC;
+"string" return Parser::Token_STRING;
+"struct" return Parser::Token_STRUCT;
+"switch" return Parser::Token_SWITCH;
+"this" return Parser::Token_THIS;
+"throw" return Parser::Token_THROW;
+"true" return Parser::Token_TRUE;
+"try" return Parser::Token_TRY;
+"typeof" return Parser::Token_TYPEOF;
+"uint" return Parser::Token_UINT;
+"ulong" return Parser::Token_ULONG;
+"unchecked" return Parser::Token_UNCHECKED;
+"unsafe" return Parser::Token_UNSAFE;
+"ushort" return Parser::Token_USHORT;
+"using" return Parser::Token_USING;
+"virtual" return Parser::Token_VIRTUAL;
+"void" return Parser::Token_VOID;
+"volatile" return Parser::Token_VOLATILE;
+"while" return Parser::Token_WHILE;
+
+
+ /* Non-keyword identifiers. They only have special meaning in
+ * specific contexts and are treated as identifiers otherwise.
+ * Many of those have been introduced by C# 2.0. */
+
+"add" return Parser::Token_ADD;
+"alias" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
+ return Parser::Token_ALIAS;
+ else
+ return Parser::Token_IDENTIFIER;
+}
+"get" return Parser::Token_GET;
+"global" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
+ return Parser::Token_GLOBAL;
+ else
+ return Parser::Token_IDENTIFIER;
+}
+"partial" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
+ return Parser::Token_PARTIAL;
+ else
+ return Parser::Token_IDENTIFIER;
+}
+"remove" return Parser::Token_REMOVE;
+"set" return Parser::Token_SET;
+"value" return Parser::Token_VALUE;
+"where" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
+ return Parser::Token_WHERE;
+ else
+ return Parser::Token_IDENTIFIER;
+}
+"yield" {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
+ return Parser::Token_YIELD;
+ else
+ return Parser::Token_IDENTIFIER;
+}
+
+ /* A non-keyword identifier that is not marked as such by the specification,
+ * for global attributes: */
+"assembly" return Parser::Token_ASSEMBLY;
+
+
+ /* characters and strings */
+
+[']({Escape}|{Multibyte}|[^\\\n\'])['] return Parser::Token_CHARACTER_LITERAL;
+[']({Escape}|{Multibyte}|[\\][^\\\n\']|[^\\\n\'])*(([\\]?[\n])|[']) {
+ m_parser->reportProblem( Parser::error,
+ QString("Invalid character literal: %1").arg(yytext) );
+ return Parser::Token_CHARACTER_LITERAL;
+}
+
+["]({Escape}|{Multibyte}|[^\\\n\"])*["] return Parser::Token_STRING_LITERAL;
+["]({Escape}|{Multibyte}|[\\][^\\\n\"]|[^\\\n\"])*(([\\]?[\n])|["]) {
+ m_parser->reportProblem( Parser::error,
+ QString("Invalid string literal: %1").arg(yytext) );
+ return Parser::Token_STRING_LITERAL;
+}
+ /* verbatim strings: */
+[@]["](["]["]|[^"])*["] return Parser::Token_STRING_LITERAL;
+
+
+
+ /* the pre-processor */
+
+<INITIAL,PP_SKIPPED_SECTION_PART>{
+{ppPrefix}"define" BEGIN(PP_DECLARATION); PP_PROCESS_TOKEN(PP_DEFINE);
+{ppPrefix}"undef" BEGIN(PP_DECLARATION); PP_PROCESS_TOKEN(PP_UNDEF);
+{ppPrefix}"if" BEGIN(PP_IF_CLAUSE); PP_PROCESS_TOKEN(PP_IF);
+{ppPrefix}"elif" BEGIN(PP_IF_CLAUSE); PP_PROCESS_TOKEN(PP_ELIF);
+{ppPrefix}"else" BEGIN(PP_EXPECT_NEW_LINE); PP_PROCESS_TOKEN(PP_ELSE);
+{ppPrefix}"endif" BEGIN(PP_EXPECT_NEW_LINE); PP_PROCESS_TOKEN(PP_ENDIF);
+{ppPrefix}"line" BEGIN(PP_LINE); PP_PROCESS_TOKEN(PP_LINE);
+{ppPrefix}"error"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_ERROR);
+{ppPrefix}"warning"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_WARNING);
+{ppPrefix}"region"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_REGION);
+{ppPrefix}"endregion"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_ENDREGION);
+{ppPrefix}"pragma"{Whitespace}? {
+ if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
+ BEGIN(PP_PRAGMA); PP_PROCESS_TOKEN(PP_PRAGMA);
+ }
+ else {
+ BEGIN(INITIAL);
+ m_parser->reportProblem( Parser::error,
+ "#pragma directives are not supported by C# 1.0" );
+ return Parser::Token_INVALID;
+ }
+}
+{ppPrefix}{Identifier} {
+ m_parser->reportProblem( Parser::error,
+ QString("Invalid pre-processor directive: ``%1").arg(yytext) + "''" );
+ return Parser::Token_INVALID;
+}
+}
+
+<PP_EXPECT_NEW_LINE,PP_DECLARATION,PP_IF_CLAUSE,PP_LINE,PP_MESSAGE,PP_PRAGMA>{
+<<EOF>> {
+ m_parser->reportProblem( Parser::warning,
+ "No newline at the end of the file" );
+ return CSharpPP::Parser::Token_EOF;
+}
+}
+
+<PP_EXPECT_NEW_LINE,PP_DECLARATION,PP_IF_CLAUSE,PP_LINE>{
+{Whitespace} /* skip */ ;
+{LineComment} /* before an unexpected EOF, skip */ ;
+}
+
+
+<PP_EXPECT_NEW_LINE>{
+{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
+. return CSharpPP::Parser::Token_PP_INVALID;
+}
+
+<PP_DECLARATION>{
+"true"|"false" {
+ m_parser->reportProblem( Parser::error,
+ "You may not define ``true'' or ``false'' with #define or #undef" );
+ return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL; // we could do Token_INVALID here,
+ // but this way the error is shown and the parser continues, I prefer this.
+}
+{Identifier} return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL; // ...including keywords
+{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
+. return CSharpPP::Parser::Token_PP_INVALID;
+}
+
+<PP_IF_CLAUSE>{
+"==" return CSharpPP::Parser::Token_PP_EQUAL;
+"!=" return CSharpPP::Parser::Token_PP_NOT_EQUAL;
+"&&" return CSharpPP::Parser::Token_PP_LOG_AND;
+"||" return CSharpPP::Parser::Token_PP_LOG_OR;
+"!" return CSharpPP::Parser::Token_PP_BANG;
+"true" return CSharpPP::Parser::Token_PP_TRUE;
+"false" return CSharpPP::Parser::Token_PP_FALSE;
+"(" return CSharpPP::Parser::Token_PP_LPAREN;
+")" return CSharpPP::Parser::Token_PP_RPAREN;
+{Identifier} return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL;
+{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
+. return CSharpPP::Parser::Token_PP_INVALID;
+}
+
+<PP_SKIPPED_SECTION_PART>{
+ /* splitting the line at "#" keeps the token shorter than real directives, */
+ /* so that those are recognized and not taken as skipped text as well. */
+[^#\n]* /* skip */ ;
+[#] /* skip */ ;
+[\n] /* skip */ ;
+}
+
+<PP_LINE>{
+{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
+{DecimalDigit}+ return CSharpPP::Parser::Token_PP_LINE_NUMBER;
+["][^\"\n]+["] return CSharpPP::Parser::Token_PP_FILE_NAME;
+"default" return CSharpPP::Parser::Token_PP_DEFAULT;
+{Identifier} return CSharpPP::Parser::Token_PP_IDENTIFIER_OR_KEYWORD;
+. return CSharpPP::Parser::Token_PP_INVALID;
+}
+
+<PP_MESSAGE>{
+[^\n]+ return CSharpPP::Parser::Token_PP_MESSAGE;
+[\n] return CSharpPP::Parser::Token_PP_NEW_LINE;
+}
+
+<PP_PRAGMA>{
+[^\n]+ return CSharpPP::Parser::Token_PP_PRAGMA_TEXT;
+[\n] return CSharpPP::Parser::Token_PP_NEW_LINE;
+}
+
+
+ /* identifiers and number literals */
+
+{Identifier} return Parser::Token_IDENTIFIER;
+
+{IntegerLiteral} return Parser::Token_INTEGER_LITERAL;
+{RealLiteral} return Parser::Token_REAL_LITERAL;
+
+
+ /* everything else is not a valid lexeme */
+
+. return Parser::Token_INVALID;
+
+
+ /* some additional checking for unclosed #ifs and #regions at the EOF */
+
+<INITIAL,PP_SKIPPED_SECTION_PART>{
+<<EOF>> {
+ cleanup();
+ return Parser::Token_EOF;
+}
+}
+
+%%
+
+namespace CSharp
+{
+
+Lexer::Lexer( Parser *parser, ParseSession* session ) : m_ppRootScope(0)
+{
+ restart( parser, session );
+}
+
+void Lexer::restart( Parser *parser, ParseSession* session )
+{
+ cleanup();
+
+ m_parser = parser;
+ m_locationTable = parser->tokenStream->locationTable();
+ m_session = session;
+ m_ppRootScope = 0;
+ m_tokenBegin = m_tokenEnd = 0;
+ m_currentOffset = 0;
+
+ // check for and ignore the UTF-8 byte order mark
+ const unsigned char *ucontents = (const unsigned char *) contents();
+ if ( ucontents[0] == 0xEF && ucontents[1] == 0xBB && ucontents[2] == 0xBF )
+ {
+ m_tokenBegin = m_tokenEnd = 3;
+ m_currentOffset = 3;
+ }
+
+ yyrestart(NULL);
+ BEGIN(INITIAL); // is not set automatically by yyrestart()
+}
+
+// reads a character, and returns 1 as the number of characters read
+// (or 0 when the end of the string is reached)
+int Lexer::LexerInput( char *buf, int /*maxSize*/ )
+{
+ int c = contents()[ m_currentOffset++ ];
+
+ switch(c)
+ {
+ case '\r':
+ c = '\n'; // only have one single line break character: '\n'
+ if ( contents()[m_currentOffset + 1] == '\n' )
+ {
+ m_currentOffset++;
+ m_tokenEnd++;
+ }
+
+ // fall through
+ case '\n':
+ m_locationTable->newline( m_currentOffset );
+ break;
+
+ default:
+ break;
+ }
+
+ return (c == 0) ? 0 : (buf[0] = c, 1);
+}
+
+CSharpPP::Scope* Lexer::ppCurrentScope()
+{
+ if ( m_ppRootScope == 0 )
+ {
+ m_ppRootScope = new CSharpPP::Scope( m_parser );
+ }
+ return m_ppRootScope->currentScope();
+}
+
+void Lexer::cleanup()
+{
+ // check for open Scopes, and pop them / report errors as needed
+ if (m_ppRootScope != 0)
+ {
+ CSharpPP::Scope* currentScope = ppCurrentScope();
+ CSharpPP::Scope::ScopeType ScopeType = currentScope->type();
+
+ while ( ScopeType != CSharpPP::Scope::TypeRoot )
+ {
+ if ( ScopeType == CSharpPP::Scope::TypeIf )
+ {
+ m_parser->reportProblem( Parser::error,
+ "Encountered end of file in an unclosed #if/#elif/#else section" );
+ }
+ else if ( ScopeType == CSharpPP::Scope::TypeRegion )
+ {
+ m_parser->reportProblem( Parser::error,
+ "Encountered end of file in an unclosed #region section" );
+ }
+
+ if ( !currentScope->popScope(ScopeType, &currentScope) )
+ break;
+
+ ScopeType = currentScope->type();
+ }
+
+ delete m_ppRootScope;
+ m_ppRootScope = 0;
+ }
+}
+
+const char *Lexer::contents() const
+{
+ return m_session->contents();
+}
+
+} // end of namespace CSharp
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp (revision 1522570)
@@ -0,0 +1,76 @@
+/*****************************************************************************
+ * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+// This file is meant to be specific to the framework in which the parser
+// operates, and is likely to be adapted for different environments.
+// Specifically, the error output might not always go to std::cerr,
+// but will rather be placed as items inside some listbox.
+
+
+#include "csharpparser.h"
+#include "csharplexer.h"
+
+#include <QString>
+
+#include <KDebug>
+
+// void print_token_environment(CSharp::parser* parser);
+
+
+namespace CSharp
+{
+
+void Parser::reportProblem( Parser::ProblemType type, QString message )
+{
+ if (type == error)
+ kDebug() << "** ERROR: " << message;
+ else if (type == warning)
+ kDebug() << "** WARNING: " << message;
+ else if (type == info)
+ kDebug() << "** Info: " << message;
+}
+
+void Parser::reportProblem( Parser::ProblemType type, const char* message )
+{
+ reportProblem(type, QString::fromUtf8(message));
+}
+
+
+// custom error recovery
+void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
+{
+ // print_token_environment(this);
+ reportProblem(
+ Parser::error,
+ QString("Expected token ``%1''").arg(name)
+ //+ "'' instead of ``" + current_token_text
+ );
+}
+
+void Parser::expectedSymbol(int /*expected_symbol*/, const QString& name)
+{
+ // print_token_environment(this);
+ reportProblem(
+ Parser::error,
+ QString("Expected symbol ``%1''").arg(name)
+ //+ "'' instead of ``" + current_token_text
+ );
+}
+
+} // end of namespace CSharp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp (revision 1522570)
@@ -0,0 +1,139 @@
+/*****************************************************************************
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
+ * *
+ * This program 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 grammar 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 *
+ * Lesser 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. *
+ *****************************************************************************/
+
+#include "csharpppscope.h"
+
+
+namespace CSharpPP
+{
+
+Scope::Scope( CSharp::Parser* parser )
+ : m_type(Scope::TypeRoot), m_parser(parser), m_child(0), m_parent(0)
+{
+ m_isActive = true;
+ m_waitingForActiveSection = true;
+}
+
+Scope::Scope( Scope::ScopeType Type, CSharp::Parser* Parser, bool active )
+ : m_type(Type), m_parser(Parser), m_child(0)
+{
+ if (active == true)
+ {
+ m_waitingForActiveSection = true;
+ m_isActive = true;
+ }
+ else
+ {
+ m_waitingForActiveSection = false;
+ m_isActive = false;
+ }
+}
+
+Scope::~Scope()
+{
+ if (m_child != 0)
+ delete m_child;
+ if (m_parent != 0)
+ m_parent->m_child = 0;
+}
+
+Scope* Scope::currentScope()
+{
+ if (m_child == 0)
+ return this;
+ else
+ return m_child->currentScope();
+}
+
+Scope::ScopeType Scope::type()
+{
+ return m_type;
+}
+
+bool Scope::isActive()
+{
+ return m_isActive;
+}
+
+bool Scope::isWaitingForActiveSection()
+{
+ return m_waitingForActiveSection;
+}
+
+void Scope::setActivated( bool active )
+{
+ if (m_type != Scope::TypeIf)
+ return;
+ else if (m_waitingForActiveSection == false)
+ m_isActive = false;
+ else
+ {
+ m_isActive = active;
+
+ if (active == true)
+ m_waitingForActiveSection = false;
+ }
+}
+
+bool Scope::pushScope( Scope::ScopeType type, Scope** newCurrent )
+{
+ if (m_child != 0) {
+ *newCurrent = m_child->currentScope();
+ return false; // only the deepest nested Scope shall create children
+ }
+
+ m_child = new Scope(type, m_parser, m_isActive);
+ m_child->setParent(this);
+ *newCurrent = m_child;
+ return true;
+}
+
+bool Scope::popScope( Scope::ScopeType type, Scope** newCurrent )
+{
+ if (m_parent == 0 || type != m_type) {
+ *newCurrent = this->currentScope();
+ return false;
+ }
+
+ *newCurrent = m_parent;
+ delete this;
+ return true;
+}
+
+void Scope::setCSharpParser( ::CSharp::Parser* parser )
+{
+ m_parser = parser;
+}
+
+::CSharp::Parser* Scope::csharpParser()
+{
+ return m_parser;
+}
+
+void Scope::setParent( Scope* parent )
+{
+ m_parent = parent;
+}
+
+Scope* Scope::parent()
+{
+ return m_parent;
+}
+
+} // end of namespace CSharpPP
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp (revision 1522570)
@@ -0,0 +1,77 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright (C) 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "parsesession.h"
+
+#include "kdev-pg-memory-pool.h"
+#include "kdev-pg-token-stream.h"
+
+namespace CSharp
+{
+
+ParseSession::ParseSession()
+ : memoryPool( new Parser::memoryPoolType )
+ , tokenStream( new KDevPG::TokenStream )
+ , compatibilityMode( Parser::CSharp20Compatibility )
+{
+}
+
+ParseSession::~ParseSession()
+{
+ delete memoryPool;
+ delete tokenStream;
+}
+
+KDevelop::SimpleCursor ParseSession::positionAt( qint64 offset ) const
+{
+ qint64 line, column;
+ tokenStream->locationTable()->positionAt( offset, &line, &column );
+ return KDevelop::SimpleCursor(line, column);
+}
+
+qint64 ParseSession::size() const
+{
+ return m_contents.size();
+}
+
+const char *ParseSession::contents() const
+{
+ return m_contents.constData();
+}
+
+void ParseSession::setContents( const QByteArray & contents )
+{
+ m_contents = contents;
+}
+
+QString ParseSession::symbol( qint64 token ) const
+{
+ const KDevPG::TokenStream::Token& tok = tokenStream->token( token );
+ return QString::fromUtf8(m_contents.constData() + tok.begin, tok.end - tok.begin);
+}
+
+KDevelop::IndexedString ParseSession::indexedSymbol( qint64 token ) const
+{
+ const KDevPG::TokenStream::Token& tok = tokenStream->token( token );
+ return KDevelop::IndexedString(m_contents.constData() + tok.begin, tok.end - tok.begin);
+}
+
+} // end of namespace CSharp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h (revision 1522570)
@@ -0,0 +1,208 @@
+
+// -*-C++-*-
+// FlexLexer.h -- define interfaces for lexical analyzer classes generated
+// by flex
+
+// Copyright (c) 1993 The Regents of the University of California.
+// All rights reserved.
+//
+// This code is derived from software contributed to Berkeley by
+// Kent Williams and Tom Epperly.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+
+// 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+
+// Neither the name of the University nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+
+// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+// PURPOSE.
+
+// This file defines FlexLexer, an abstract class which specifies the
+// external interface provided to flex C++ lexer objects, and yyFlexLexer,
+// which defines a particular lexer class.
+//
+// If you want to create multiple lexer classes, you use the -P flag
+// to rename each yyFlexLexer to some other xxFlexLexer. You then
+// include <FlexLexer.h> in your other sources once per lexer class:
+//
+// #undef yyFlexLexer
+// #define yyFlexLexer xxFlexLexer
+// #include <FlexLexer.h>
+//
+// #undef yyFlexLexer
+// #define yyFlexLexer zzFlexLexer
+// #include <FlexLexer.h>
+// ...
+
+#ifndef __FLEX_LEXER_H
+// Never included before - need to define base class.
+#define __FLEX_LEXER_H
+
+#include <iostream>
+# ifndef FLEX_STD
+# define FLEX_STD std::
+# endif
+
+extern "C++" {
+
+struct yy_buffer_state;
+typedef int yy_state_type;
+
+class FlexLexer {
+public:
+ virtual ~FlexLexer() { }
+
+ const char* YYText() const { return yytext; }
+ int YYLeng() const { return yyleng; }
+
+ virtual void
+ yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0;
+ virtual struct yy_buffer_state*
+ yy_create_buffer( FLEX_STD istream* s, int size ) = 0;
+ virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0;
+ virtual void yyrestart( FLEX_STD istream* s ) = 0;
+
+ virtual int yylex() = 0;
+
+ // Call yylex with new input/output sources.
+ int yylex( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0 )
+ {
+ switch_streams( new_in, new_out );
+ return yylex();
+ }
+
+ // Switch to new input/output streams. A nil stream pointer
+ // indicates "keep the current one".
+ virtual void switch_streams( FLEX_STD istream* new_in = 0,
+ FLEX_STD ostream* new_out = 0 ) = 0;
+
+ int lineno() const { return yylineno; }
+
+ int debug() const { return yy_flex_debug; }
+ void set_debug( int flag ) { yy_flex_debug = flag; }
+
+protected:
+ char* yytext;
+ int yyleng;
+ int yylineno; // only maintained if you use %option yylineno
+ int yy_flex_debug; // only has effect with -d or "%option debug"
+};
+
+}
+#endif
+
+#if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce)
+// Either this is the first time through (yyFlexLexerOnce not defined),
+// or this is a repeated include to define a different flavor of
+// yyFlexLexer, as discussed in the flex man page.
+#define yyFlexLexerOnce
+
+extern "C++" {
+
+class yyFlexLexer : public FlexLexer {
+public:
+ // arg_yyin and arg_yyout default to the cin and cout, but we
+ // only make that assignment when initializing in yylex().
+ yyFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 );
+
+ virtual ~yyFlexLexer();
+
+ void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
+ struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size );
+ void yy_delete_buffer( struct yy_buffer_state* b );
+ void yyrestart( FLEX_STD istream* s );
+
+ void yypush_buffer_state( struct yy_buffer_state* new_buffer );
+ void yypop_buffer_state(void);
+
+#ifndef yywrap
+ int yywrap();
+#endif
+ virtual int yylex();
+ virtual void switch_streams( FLEX_STD istream* new_in, FLEX_STD ostream* new_out );
+
+protected:
+ virtual int LexerInput( char* buf, int max_size );
+ virtual void LexerOutput( const char* buf, int size );
+ virtual void LexerError( const char* msg );
+
+ void yyunput( int c, char* buf_ptr );
+ int yyinput();
+
+ void yy_load_buffer_state();
+ void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream* s );
+ void yy_flush_buffer( struct yy_buffer_state* b );
+
+ int yy_start_stack_ptr;
+ int yy_start_stack_depth;
+ int* yy_start_stack;
+
+ void yy_push_state( int new_state );
+ void yy_pop_state();
+ int yy_top_state();
+
+ yy_state_type yy_get_previous_state();
+ yy_state_type yy_try_NUL_trans( yy_state_type current_state );
+ int yy_get_next_buffer();
+
+ FLEX_STD istream* yyin; // input source for default LexerInput
+ FLEX_STD ostream* yyout; // output sink for default LexerOutput
+
+ // yy_hold_char holds the character lost when yytext is formed.
+ char yy_hold_char;
+
+ // Number of characters read into yy_ch_buf.
+ int yy_n_chars;
+
+ // Points to current character in buffer.
+ char* yy_c_buf_p;
+
+ int yy_init; // whether we need to initialize
+ int yy_start; // start state number
+
+ // Flag which is used to allow yywrap()'s to do buffer switches
+ // instead of setting up a fresh yyin. A bit of a hack ...
+ int yy_did_buffer_switch_on_eof;
+
+
+ size_t yy_buffer_stack_top; /**< index of top of stack. */
+ size_t yy_buffer_stack_max; /**< capacity of stack. */
+ struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */
+ void yyensure_buffer_stack(void);
+
+ // The following are not always needed, but may be depending
+ // on use of certain flex features (like REJECT or yymore()).
+
+ yy_state_type yy_last_accepting_state;
+ char* yy_last_accepting_cpos;
+
+ yy_state_type* yy_state_buf;
+ yy_state_type* yy_state_ptr;
+
+ char* yy_full_match;
+ int* yy_full_state;
+ int yy_full_lp;
+
+ int yy_lp;
+ int yy_looking_for_trail_begin;
+
+ int yy_more_flag;
+ int yy_more_len;
+ int yy_more_offset;
+ int yy_prev_more_offset;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h (revision 1522570)
@@ -0,0 +1,36 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef CSHARPPARSEREXPORT_H
+#define CSHARPPARSEREXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+#ifndef KDEVCSHARPPARSER_EXPORT
+# ifdef MAKE_KDEVCSHARPPARSER_LIB
+# define KDEVCSHARPPARSER_EXPORT KDE_EXPORT
+# else
+# define KDEVCSHARPPARSER_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt (revision 1522570)
@@ -0,0 +1,77 @@
+Where I got the specifications, grammars and stuff.
+
+
+Different versions of the Language specification:
+
+ECMA-334 (C# Language specification), 3rd edition (June 2005):
+http://www.ecma-international.org/publications/standards/Ecma-334.htm
+...covers C# 2.0.
+
+ISO/IEC 23270:2003 (C# Language specification, 2nd edition, April 2004):
+http://isotc.iso.org/livelink/livelink/fetch/2000/2489/Ittf_Home/PubliclyAvailableStandards.htm
+...covers C# 1.0.
+
+HTML version of the ECMA-334 (2rd edition / C# 1.0, it seems) standard:
+http://www.jaggersoft.com/csharp_standard/index.htm
+
+For more information and more links, check out the page from the Mono project:
+http://www.mono-project.com/ECMA
+
+
+Grammars:
+
+- Every specification contains an example grammar, yay!
+
+Mono's C# 2.0 grammar (.jay format, very bison-like):
+http://svn.myrealbox.com/viewcvs/trunk/mcs/gmcs/cs-parser.jay?rev=60352&view=auto
+
+Mono's C# 1.0 grammar (.jay format, very bison-like):
+http://svn.myrealbox.com/viewcvs/trunk/mcs/mcs/cs-parser.jay?rev=60352&view=auto
+
+James Power's flex/bison C# parser:
+http://www.cs.nuim.ie/~jpower/Research/csharp/
+http://www.cs.may.ie/~jpower/
+
+ANTLR contains a C# parser in examples/csharp/csharp_v1/, which appears to be
+an approximate copy (or rather the origin) of kcsparse.
+
+From http://antlr.org/grammar/list:
+
+- kcsparse: parses C# 1.0 files
+Kunle Odutola Thu Dec 8, 2005 06:37
+"Yet Another C# Grammar For ANTLR implemented in C#. It is probably more
+complete and includes both an ANTLR and a C# Flex lexer. With kcsparse, you can
+(a) Parse C# 1.x source code including some with C# preprocessing directives,
+(b)Build and display an AST from C# source and,
+(c) Unparse the AST (i.e. pretty prints the AST)."
+
+- C# Grammar with minimal lookaheads
+Todd King Mon Sep 26, 2005 00:48
+"This C# antlr grammar implements most of the C# spec except for a few of the
+unsafe elements. I designed this grammar for speed so I avoided using arbitrary
+lookaheads where I could. I got it down to just 7 lookaheads. This grammar can
+parse large files very fast because it doesnýt waste time spinning in arbitrary
+lookaheads. (It can parse the entire NAnt project in 5 seconds, that is
+90986 LOC)"
+
+- C# grammar (based on ecma-334 spec)
+Robin Debreuil Fri Mar 5, 2004 11:50
+"A (mostly) complete cs parser. It parses into a tree structure loosely based
+on the CodeDom. Does not yet do #if preprocessor segments, and no unsafe code
+(as of yet). You can test by downloading the CSharp.zip file and dragging
+cs files into CSharp.exe. The zip includes the grammar file, as well as the
+cs token classes (the grammar uses a heterogeneous tree, though that should
+be simple to turn off). permalink: http://www.debreuil.com/CSharp. TJP: copied
+src, exe to antlr.org and changed link as debreuil's links are dead."
+
+- C# Grammar File
+Rajendra Kumar Komandur Wed Oct 29, 2003 20:07
+"Grammar file for cSharp language which supports most part of the cSharp
+language spec."
+
+
+Other resources:
+
+A Comparison Of Microsoft'S C# Programming Language
+To Sun Microsystems' Java Programming Language (by Dare Obasanjo)
+http://www.25hoursaday.com/CsharpVsJava.html
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,60 @@
+project(csharp)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${csharp_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+include (KDE4Defaults)
+include (MacroLibrary)
+include (MacroOptionalAddSubdirectory)
+
+find_package(KDevPlatform REQUIRED)
+
+add_subdirectory(parser)
+
+include_directories(
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_SOURCE_DIR}/parser
+ ${CMAKE_CURRENT_BINARY_DIR}/parser
+ ${KDE4_INCLUDE_DIR}/threadweaver
+ ${KDE4_INCLUDE_DIR}/kdevelop-pg-qt
+ ${KDEVPLATFORM_INCLUDE_DIR}
+)
+
+
+########### next target ###############
+
+add_definitions( ${QT_DEFINITIONS} ${KDE4_DEFINITIONS} -DKDE_DEFAULT_DEBUG_AREA=9044 )
+
+set(kdevcsharplanguagesupport_PART_SRCS
+ csharplanguagesupport.cpp
+ parsejob.cpp
+
+ duchain/editorintegrator.cpp
+ duchain/identifiercompiler.cpp
+ duchain/contextbuilder.cpp
+ duchain/declarationbuilder.cpp
+ duchain/usebuilder.cpp
+ duchain/dumpchain.cpp
+ duchain/typebuilder.cpp
+)
+
+kde4_add_plugin(kdevcsharplanguagesupport ${kdevcsharplanguagesupport_PART_SRCS})
+target_link_libraries(kdevcsharplanguagesupport
+ ${QT_QTDESIGNER_LIBRARY}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${KDE4_THREADWEAVER_LIBRARIES}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+ ${KDE4_KDEUI_LIBS}
+ kdev4csharpparser
+)
+
+install(TARGETS kdevcsharplanguagesupport DESTINATION ${PLUGIN_INSTALL_DIR})
+
+
+########### install files ###############
+
+install(FILES kdevcsharpsupport.desktop DESTINATION ${SERVICES_INSTALL_DIR})
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/Messages.sh (revision 1522570)
@@ -0,0 +1,7 @@
+#!/bin/sh
+files=`find . -name \*.rc -o -name \*.ui`
+if [ "x$files" != "x" ]; then
+ $EXTRACTRC $files >> rc.cpp
+fi
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcsharp.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp (revision 1522570)
@@ -0,0 +1,96 @@
+/* This file is part of KDevelop
+Copyright (C) 2006 Adam Treat <treat@kde.org>
+Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
+
+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.
+*/
+
+#include "csharplanguagesupport.h"
+
+#include <kdebug.h>
+#include <kcomponentdata.h>
+#include <kstandarddirs.h>
+#include <kgenericfactory.h>
+
+#include <QExtensionFactory>
+
+#include <interfaces/icore.h>
+#include <interfaces/ilanguagecontroller.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/iprojectcontroller.h>
+#include <language/backgroundparser/backgroundparser.h>
+#include <interfaces/iproject.h>
+
+#include "parsejob.h"
+
+K_PLUGIN_FACTORY(KDevCSharpSupportFactory, registerPlugin<CSharpLanguageSupport>(); )
+K_EXPORT_PLUGIN(KDevCSharpSupportFactory("kdevcsharpsupport"))
+
+using namespace CSharp;
+
+CSharpLanguageSupport::CSharpLanguageSupport( QObject* parent, const QVariantList& /*args*/ )
+ : KDevelop::IPlugin( KDevCSharpSupportFactory::componentData(), parent )
+ , KDevelop::ILanguageSupport()
+{
+ KDEV_USE_EXTENSION_INTERFACE( KDevelop::ILanguageSupport )
+
+ connect( core()->projectController(),
+ SIGNAL( projectOpened(KDevelop::IProject*) ),
+ this, SLOT( projectOpened(KDevelop::IProject*) ) );
+ connect( core()->projectController(),
+ SIGNAL( projectClosed() ),
+ this, SLOT( projectClosed() ) );
+
+ kDebug() << "CSharp support loaded";
+}
+
+CSharpLanguageSupport::~CSharpLanguageSupport()
+{}
+
+KDevelop::ParseJob *CSharpLanguageSupport::createParseJob( const KUrl &url )
+{
+ return new ParseJob( url, this );
+}
+
+void CSharpLanguageSupport::projectOpened(KDevelop::IProject *project)
+{
+ foreach(KDevelop::IDocument* doc, core()->documentController()->openDocuments()) {
+ if (project->inProject(doc->url())) {
+ QString path = doc->url().path();
+
+ core()->languageController()->backgroundParser()->addDocument(doc->url());
+ }
+ }
+}
+
+void CSharpLanguageSupport::projectClosed()
+{
+ // FIXME This should remove the project files from the backgroundparser
+}
+
+KDevelop::ILanguage * CSharpLanguageSupport::language()
+{
+ return core()->languageController()->language(name());
+}
+
+QString CSharpLanguageSupport::name() const
+{
+ return "C#";
+}
+
+#include "csharplanguagesupport.moc"
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.cpp (revision 1522570)
@@ -0,0 +1,222 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright (c) 2006 Adam Treat <treat@kde.org>
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
+ * Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "parsejob.h"
+
+#include <cassert>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include "Thread.h"
+
+#include <QFile>
+#include <QFileInfo>
+#include <QByteArray>
+#include <QReadLocker>
+
+#include <kdebug.h>
+#include <klocale.h>
+
+#include <KTextEditor/SmartInterface>
+
+#include <interfaces/ilanguage.h>
+#include <language/interfaces/icodehighlighting.h>
+
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+
+// from the parser subdirectory
+#include <parsesession.h>
+#include <csharpparser.h>
+
+#include "csharplanguagesupport.h"
+#include "csharpdebugvisitor.h"
+
+#include "duchain/declarationbuilder.h"
+#include "duchain/usebuilder.h"
+#include "duchain/editorintegrator.h"
+#include "duchain/dumpchain.h"
+
+namespace CSharp
+{
+
+ParseJob::ParseJob( const KUrl &url, CSharpLanguageSupport *parent )
+ : KDevelop::ParseJob( url, parent )
+ , m_session( new ParseSession )
+ , m_AST( 0 )
+ , m_readFromDisk( false )
+{}
+
+#if 0
+ParseJob::ParseJob( KDevelop::Document *document, CSharpLanguageSupport *parent )
+ : KDevelop::ParseJob( document, parent )
+ , m_session( new ParseSession )
+ , m_AST( 0 )
+ , m_readFromDisk( false )
+{}
+#endif
+
+ParseJob::~ParseJob()
+{}
+
+CSharpLanguageSupport* ParseJob::csharp() const
+{
+ return static_cast<CSharpLanguageSupport*>(const_cast<QObject*>(parent()));
+}
+
+CSharp::AstNode *ParseJob::AST() const
+{
+ Q_ASSERT ( isFinished () && m_AST );
+ return m_AST;
+}
+
+ParseSession *ParseJob::parseSession() const
+{
+ return m_session;
+}
+
+bool ParseJob::wasReadFromDisk() const
+{
+ return m_readFromDisk;
+}
+
+void ParseJob::run()
+{
+ if ( abortRequested())
+ return abortJob();
+
+ QReadLocker lock(csharp()->language()->parseLock());
+
+ m_readFromDisk = !contentsAvailableFromEditor();
+
+ QString localFile(KUrl(document().str()).toLocalFile());
+
+ QFileInfo fileInfo( localFile );
+
+ if ( m_readFromDisk )
+ {
+ QFile file( localFile );
+ if ( !file.open( QIODevice::ReadOnly ) )
+ {
+ KDevelop::ProblemPointer p(new KDevelop::Problem());
+ p->setSource(KDevelop::ProblemData::Disk);
+ p->setDescription(i18n( "Could not open file '%1'", localFile ));
+ switch (file.error()) {
+ case QFile::ReadError:
+ p->setExplanation(i18n("File could not be read from."));
+ break;
+ case QFile::OpenError:
+ p->setExplanation(i18n("File could not be opened."));
+ break;
+ case QFile::PermissionsError:
+ p->setExplanation(i18n("File permissions prevent opening for read."));
+ break;
+ default:
+ break;
+ }
+ p->setFinalLocation(KDevelop::DocumentRange(document().str(), KTextEditor::Cursor(0,0), KTextEditor::Cursor(0,0)));
+ // TODO addProblem(p);
+ kWarning( ) << "Could not open file " << document().str() << " (path " << fileInfo.filePath() << ")";
+ return ;
+ }
+
+ m_session->setContents( file.readAll() );
+ Q_ASSERT ( m_session->size() > 0 );
+ file.close();
+ }
+ else
+ {
+ m_session->setContents( contentsFromEditor().toAscii() );
+ }
+
+ kDebug() << "===-- PARSING --===> "
+ << document().str()
+ << " <== readFromDisk: " << m_readFromDisk
+ << " size: " << m_session->size()
+ << endl;
+
+ if ( abortRequested() )
+ return abortJob();
+
+ // 0) setup
+ Parser csharpParser;
+ csharpParser.setCompatibilityMode( m_session->compatibilityMode );
+ csharpParser.setTokenStream( m_session->tokenStream );
+ csharpParser.setMemoryPool( m_session->memoryPool );
+
+ // 1) tokenize
+ csharpParser.tokenize( m_session );
+
+ if ( abortRequested() )
+ return abortJob();
+
+ // 2) parse
+ csharpParser.parseCompilationUnit( &m_AST );
+
+ if ( abortRequested() )
+ return abortJob();
+
+ DebugVisitor debug(m_session->tokenStream, QString::fromUtf8(m_session->contents()));
+ debug.visitNode(m_AST);
+
+ if ( abortRequested() )
+ return abortJob();
+
+ // 3) Form definition-use chain
+ CSharp::EditorIntegrator editor(parseSession());
+ editor.setCurrentUrl(document());
+
+ //kDebug( ) << (contentContext ? "updating" : "building") << "duchain for" << parentJob()->document().str();
+
+ DeclarationBuilder builder(&editor);
+ KDevelop::TopDUContext* chain = builder.build(document(), m_AST);
+ setDuChain(chain);
+
+ if ( abortRequested() )
+ return abortJob();
+
+ UseBuilder useBuilder(&editor);
+ useBuilder.buildUses(m_AST);
+
+ /*if (!abortRequested() && editor.smart()) {
+ editor.smart()->clearRevision();
+
+ if ( csharp()->codeHighlighting() )
+ {
+ QMutexLocker lock(editor.smart()->smartMutex());
+ csharp()->codeHighlighting()->highlightDUChain( chain );
+ }
+ }*/
+
+ KDevelop::DUChainReadLocker duchainlock(KDevelop::DUChain::lock());
+
+ DumpChain dump;
+ dump.dump(chain);
+}
+
+} // end of namespace CSharp
+
+#include "parsejob.moc"
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h (revision 1522570)
@@ -0,0 +1,54 @@
+/* This file is part of KDevelop
+Copyright (C) 2006 Adam Treat <treat@kde.org>
+Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
+
+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.
+*/
+
+#ifndef KDEVCSHARPLANGUAGESUPPORT_H
+#define KDEVCSHARPLANGUAGESUPPORT_H
+
+#include <interfaces/iplugin.h>
+#include <language/interfaces/ilanguagesupport.h>
+
+namespace KDevelop {
+class IDocument;
+class IProject;
+}
+
+class CSharpLanguageSupport : public KDevelop::IPlugin, public KDevelop::ILanguageSupport
+{
+Q_OBJECT
+Q_INTERFACES( KDevelop::ILanguageSupport )
+public:
+ CSharpLanguageSupport( QObject *parent, const QVariantList& args = QVariantList() );
+ virtual ~CSharpLanguageSupport();
+
+ virtual QString name() const;
+
+ virtual KDevelop::ParseJob *createParseJob(const KUrl &url);
+ virtual KDevelop::ILanguage *language();
+
+private slots:
+ void projectOpened(KDevelop::IProject *project);
+ void projectClosed();
+
+private:
+};
+
+#endif
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/csharp/parsejob.h (revision 1522570)
@@ -0,0 +1,74 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright (c) 2006 Adam Treat <treat@kde.org>
+ * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
+ * Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSHARP_PARSEJOB_H
+#define CSHARP_PARSEJOB_H
+
+#include <kurl.h>
+#include <language/backgroundparser/parsejob.h>
+
+namespace KDevelop {
+class Document;
+}
+
+class CSharpLanguageSupport;
+
+namespace CSharp
+{
+
+class ParseSession;
+class CompilationUnitAst;
+class AstNode;
+
+class ParseJob : public KDevelop::ParseJob
+{
+ Q_OBJECT
+
+public:
+ ParseJob( const KUrl &url, CSharpLanguageSupport* parent );
+ //ParseJob( KDevelop::Document* document, CSharpLanguageSupport* parent );
+
+ virtual ~ParseJob();
+
+ CSharpLanguageSupport* csharp() const;
+
+ ParseSession* parseSession() const;
+
+ bool wasReadFromDisk() const;
+
+ virtual AstNode *AST() const;
+
+protected:
+ virtual void run();
+
+private:
+ ParseSession *m_session;
+ CompilationUnitAst *m_AST;
+ bool m_readFromDisk;
+};
+
+} // end of namespace CSharp
+
+#endif
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.desktop (revision 1522570)
@@ -0,0 +1,69 @@
+[Desktop Entry]
+Type=Service
+Icon=kdevelop
+Exec=blubb
+Comment=CTest
+Comment[bs]=CTest
+Comment[ca]=CTest
+Comment[ca@valencia]=CTest
+Comment[cs]=CTest
+Comment[de]=CTest
+Comment[el]=CTest
+Comment[en_GB]=CTest
+Comment[eo]=CTest
+Comment[es]=CTest
+Comment[et]=CTest
+Comment[fr]=CTest
+Comment[ga]=CTest
+Comment[gl]=CTest
+Comment[hu]=CTest
+Comment[it]=CTest
+Comment[ja]=CTest
+Comment[ms]=CTest
+Comment[nds]=C-Test
+Comment[nl]=CTest
+Comment[pa]=CTest
+Comment[pl]=CTest
+Comment[pt]=CTest
+Comment[pt_BR]=CTest
+Comment[si]=CTest
+Comment[sk]=CTest
+Comment[sv]=CTest
+Comment[tr]=CTest
+Comment[ug]=CTest
+Comment[uk]=CTest
+Comment[x-test]=xxCTestxx
+
+Name=CTest
+Name[bs]=CTest
+Name[ca]=CTest
+Name[ca@valencia]=CTest
+Name[cs]=CTest
+Name[de]=CTest
+Name[en_GB]=CTest
+Name[eo]=CTest
+Name[es]=CTest
+Name[et]=CTest
+Name[fr]=CTest
+Name[ga]=CTest
+Name[gl]=CTest
+Name[hu]=CTest
+Name[it]=CTest
+Name[nl]=CTest
+Name[pl]=CTest
+Name[pt]=CTest
+Name[pt_BR]=CTest
+Name[sk]=CTest
+Name[sv]=CTest
+Name[ug]=CTest
+Name[uk]=CTest
+Name[x-test]=xxCTestxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevctest
+X-KDE-PluginInfo-Name=kdevctest
+X-KDE-PluginInfo-Author=Manuel Breugelmans
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=LGPL
+X-KDevelop-Version=7
+X-KDevelop-Category=Global
+X-KDevelop-Properties=GlobalFileManagement
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp (revision 1522570)
@@ -0,0 +1,171 @@
+/* This file is part of KDevelop
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "ctestoutmodel.h"
+#include "ctestlogjob.h"
+#include "ctestlogmodel.h"
+#include "ctestlogdelegate.h"
+
+#include <QModelIndex>
+#include <KGlobalSettings>
+#include <interfaces/icore.h>
+#include <QRegExp>
+#include <interfaces/icore.h>
+#include <interfaces/iruncontroller.h>
+
+using namespace KDevelop;
+
+
+namespace
+{
+QRegExp g_ctestStatusLine("^[ ]*([0-9]+/[ ]+[0-9]+)[ ]+Testing[ ](.*)[ ].*$"); // eg: '1/ 52 Testing parsertest PASSED'
+}
+
+QRegExp& ctestStatusLineRegExp()
+{
+ return g_ctestStatusLine;
+}
+
+CTestOutItem::CTestOutItem(const QString &text)
+ : QStandardItem(text), m_state(NotRun)
+{
+ qRegisterMetaType<CTestOutItem::State>();
+}
+
+CTestOutItem::~CTestOutItem()
+{}
+
+#include <KDebug>
+
+void CTestOutItem::extractNameAndNumber()
+{
+ // extract test name and test number from a model line like:
+ // 1 / 20 Testing Foo
+ // name = Foo; number = 1
+
+ QRegExp re = ctestStatusLineRegExp();
+ #ifndef QT_NO_DEBUG
+ int i = re.indexIn(data(Qt::DisplayRole).toString());
+ Q_ASSERT(i!=-1);
+ #endif
+ QStringList captured = re.capturedTexts();
+ m_id = captured.value(1).split(" ").join("");
+ m_name = captured.value(2).trimmed();
+}
+
+QVariant CTestOutItem::data(int role) const
+{
+ if(role == StateRole) {
+ return (int)m_state;
+ } else {
+ return QStandardItem::data(role);
+ }
+}
+
+CTestOutModel::CTestOutModel(QObject *parent)
+ : QStandardItemModel(parent)
+{}
+
+CTestOutModel::~CTestOutModel()
+{}
+
+QVariant CTestOutModel::data(const QModelIndex& index, int role) const
+{
+ if (role != Qt::FontRole) {
+ return QStandardItemModel::data(index, role);
+ } else {
+ return KGlobalSettings::fixedFont();
+ }
+}
+
+void CTestOutModel::startLogJobFor(CTestOutItem* item)
+{
+ CTestLogDelegate* delegate = new CTestLogDelegate();
+ CTestLogModel* model = new CTestLogModel();
+ CTestLogJob* job = new CTestLogJob(delegate, model, m_testRoot, item);
+ ICore::self()->runController()->registerJob(job);
+}
+
+void CTestOutModel::activate(const QModelIndex &idx)
+{
+ // show verbose output when a user clicks on a test
+ QStandardItem *stditem = itemFromIndex(idx);
+ CTestOutItem *ctestitem = dynamic_cast<CTestOutItem*>(stditem);
+ if (!ctestitem) return;
+ ctestitem->extractNameAndNumber();
+ startLogJobFor(ctestitem);
+}
+
+QModelIndex CTestOutModel::nextHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+QModelIndex CTestOutModel::previousHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+void CTestOutModel::appendOutputs(const QStringList &lines)
+{
+ foreach(const QString& line, lines) {
+ if (ctestStatusLineRegExp().exactMatch(line)) {
+ CTestOutItem* item = new CTestOutItem(line);
+ if (line.endsWith("Passed")) {
+ item->m_state = CTestOutItem::Passed;
+ } else if (line.endsWith("***Failed ")) {
+ item->m_state = CTestOutItem::Failed;
+ } else if (line.endsWith("***Timeout")) {
+ item->m_state = CTestOutItem::Timeout;
+ } else if (line.contains("***Exception: ")) {
+ item->m_state = CTestOutItem::Failed;
+ } else {
+ item->m_state = CTestOutItem::NotRun;
+ }
+ appendRow(item);
+ } else {
+ appendRow(new QStandardItem(line));
+ }
+ }
+}
+
+void CTestOutModel::appendErrors(const QStringList &lines)
+{
+ foreach(const QString& line, lines) {
+ appendRow(new QStandardItem(line));
+ }
+}
+
+void CTestOutModel::slotCompleted()
+{}
+
+void CTestOutModel::slotFailed()
+{
+ appendRow(new QStandardItem("Failed"));
+}
+
+void CTestOutModel::setTestRoot(const KUrl& root)
+{
+ m_testRoot = root;
+}
+
+#include "ctestoutmodel.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.h (revision 1522570)
@@ -0,0 +1,66 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTWRAPPER_CTESTJOB_H
+#define CTESTWRAPPER_CTESTJOB_H
+
+#include <outputview/outputjob.h>
+
+#include <KUrl>
+
+class CTestOutModel;
+class CTestOutDelegate;
+class KProcess;
+
+/*! Job class which runs ctest in a given directory */
+class CTestJob : public KDevelop::OutputJob
+{
+ Q_OBJECT
+
+public:
+ /*! @p parent controls colorization of items
+ * @p testRoot directory to run ctest in */
+ CTestJob(CTestOutDelegate *parent);
+ virtual ~CTestJob();
+
+ /*! Initialize the directory to run ctest in.
+ * This is typically the project's build directory
+ * @note Mandatory */
+ void setTestRoot(const KUrl& testRoot);
+
+ /*! Set extra flags and arguments passed to the ctest
+ * process */
+ void setCTestArguments(const QStringList& args);
+
+ virtual void start();
+
+protected:
+ CTestOutModel* model() const;
+
+private slots:
+ void done();
+
+private:
+ CTestOutDelegate* delegate() const;
+ KProcess* m_ctest;
+ KUrl m_testRoot;
+ QStringList m_ctestArgs;
+};
+
+#endif // CTESTWRAPPER_CTEST_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.h (revision 1522570)
@@ -0,0 +1,64 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTWRAPPER_CTESTLOGJOB_H
+#define CTESTWRAPPER_CTESTLOGJOB_H
+
+#include <outputview/outputjob.h>
+
+#include <KUrl>
+
+class CTestLogModel;
+class CTestLogDelegate;
+class CTestOutItem;
+
+/*! @short Job which extracts a certain relevant part of a full ctest output log
+ *
+ * This job is started when the users activates an item in the CTestOutModel.
+ * Only the ctest output for this item is shown. This ctest-log is typically
+ * stored in build-dir/Testing/Temporary/LastTests.log. Once extracted this
+ * test output is then shown in a kdevelop-outputview. */
+class CTestLogJob : public KDevelop::OutputJob
+{
+Q_OBJECT
+
+public:
+ /*! @p parent controls colorization of items
+ * @p testRoot directory ctest was run in
+ * @p test test-item from the ctestoutmodel that triggered this job.
+ * this job extracts output for this specific item from the global ctest log. */
+ CTestLogJob(CTestLogDelegate *delegate, CTestLogModel* model, const KUrl& testRoot, CTestOutItem* test);
+ virtual ~CTestLogJob();
+
+ virtual void start();
+
+protected:
+ CTestLogModel* model() const;
+
+private:
+ void readLog(const KUrl& file);
+
+private:
+ KUrl m_testRoot;
+ CTestOutItem* m_test;
+ CTestLogDelegate* m_delegate;
+ CTestLogModel* m_model;
+};
+
+#endif // CTESTWRAPPER_CTESTLOGJOB_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.cpp (revision 1522570)
@@ -0,0 +1,223 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "ctestplugin.h"
+
+#include <KAction>
+#include <KActionCollection>
+#include <KDebug>
+#include <KLocale>
+#include <KPluginFactory>
+#include <KPluginLoader>
+#include <KSelectAction>
+#include <KDialog>
+#include <KLineEdit>
+#include <KHistoryComboBox>
+#include <QComboBox>
+#include <QFrame>
+#include <QGridLayout>
+#include <QLabel>
+#include <KConfig>
+
+#include <interfaces/icore.h>
+#include <interfaces/iproject.h>
+#include <interfaces/idocument.h>
+#include <interfaces/iruncontroller.h>
+#include <project/projectmodel.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <project/interfaces/iprojectfilemanager.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/iprojectcontroller.h>
+#include <ktexteditor/document.h>
+
+#include "ctestoutdelegate.h"
+#include "ctestjob.h"
+
+using namespace KDevelop;
+
+K_PLUGIN_FACTORY(CTestPluginFactory, registerPlugin<CTestPlugin>();)
+K_EXPORT_PLUGIN(CTestPluginFactory("kdevctest"))
+
+CTestPlugin::CTestPlugin(QObject* parent, const QVariantList&)
+ : KDevelop::IPlugin( CTestPluginFactory::componentData(), parent )
+{
+ setXMLFile("kdevctest.rc");
+ m_runDelegate = new CTestOutDelegate(this);
+ KAction* run = actionCollection()->addAction("run_ctest");
+ run->setText(i18n("Run CTest"));
+ run->setShortcut( Qt::ALT| Qt::META | Qt::Key_R );
+ connect(run, SIGNAL(triggered()), this, SLOT(showDialog()));
+}
+
+CTestPlugin::~CTestPlugin()
+{
+}
+
+namespace
+{
+QString activeProject()
+{
+ ICore* core = ICore::self();
+ IDocumentController* dc = core->documentController();
+ IDocument* doc = dc->activeDocument();
+ if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
+ return QString();
+ }
+
+ // found an active document
+ IProjectController* pc = core->projectController();
+ IProject* proj = pc->findProjectForUrl( doc->url() );
+ if (!proj) {
+ return QString();
+ }
+ return proj->name();
+}
+}
+
+void CTestPlugin::showDialog()
+{
+ KDialog* dialog = new KDialog(0);
+ dialog->setButtonText(KDialog::Ok, i18n("&Run"));
+ dialog->setModal(true);
+ dialog->setSizeGripEnabled(false);
+
+ QFrame* main = new QFrame(dialog);
+ dialog->setMainWidget(main);
+ QGridLayout* lay = new QGridLayout();
+
+ QLabel* projLabel = new QLabel(dialog);
+ projLabel->setText(i18n("Project: "));
+ lay->addWidget(projLabel, 0, 0);
+
+ QComboBox* projSelection = new QComboBox(dialog);
+ projSelection->setObjectName("ProjectSelection");
+ projSelection->setDuplicatesEnabled(true);
+ QString activeProj = activeProject();
+ IProjectController* projCtrl = ICore::self()->projectController();
+ int i=0;
+ if (projCtrl->projects().count() == 0) return; // NO-OP if no project loaded
+ foreach(IProject* proj, projCtrl->projects()) {
+ projSelection->addItem(proj->name());
+ if (proj->name() == activeProj) {
+ projSelection->setCurrentIndex(i);
+ }
+ i++;
+ }
+ lay->addWidget(projSelection, 0, 1);
+
+ QLabel* argsLabel = new QLabel(dialog);
+ argsLabel->setText(i18n("Flags: "));
+ lay->addWidget(argsLabel, 0, 2);
+
+ KHistoryComboBox* argsInput = new KHistoryComboBox(true, dialog);
+ argsInput->setMaxCount(10);
+ argsInput->setDuplicatesEnabled( false );
+ argsInput->setMinimumContentsLength( 35 );
+ argsInput->setObjectName("CTestFlagsInput");
+
+ KConfigGroup cg = KGlobal::config()->group( "CTest" );
+ QStringList history = cg.readEntry<QStringList>("args", QStringList());
+ lay->addWidget(argsInput, 0, 3);
+ foreach(const QString& args, history) {
+ argsInput->addToHistory(args);
+ }
+
+ main->setLayout(lay);
+ connect(dialog, SIGNAL(okClicked()), SLOT(startRunJob()));
+ connect(dialog, SIGNAL(finished()), dialog, SLOT(deleteLater()));
+ dialog->show();
+}
+
+namespace
+{
+
+// helper for startRunJob()
+IProject* fetchProjectFrom(KDialog* dialog)
+{
+ Q_ASSERT(dialog->findChildren<QComboBox*>().count() == 2);
+ QList<QComboBox*> comboBoxes = dialog->findChildren<QComboBox*>();
+ QComboBox* projSelection = comboBoxes[0];
+ if (projSelection->objectName() != "ProjectSelection") {
+ projSelection = comboBoxes[1];
+ Q_ASSERT(projSelection->objectName() == "ProjectSelection");
+ }
+ QString projName = projSelection->itemText(projSelection->currentIndex());
+ IProjectController* projCtrl = ICore::self()->projectController();
+ IProject* project = projCtrl->findProjectByName(projName);
+ if (!project) {
+ kError() << "Failed to retrieve project " << projName << projSelection->currentIndex();
+ }
+ return project;
+}
+
+// helper for startRunJob()
+KUrl fetchBuildDirFor(IProject* project)
+{
+ if (!project->buildSystemManager()) {
+ // no buildsystem manager, so no build dir to run ctest in.
+ return KUrl();
+ }
+ IBuildSystemManager* builder = project->buildSystemManager();
+ ProjectFolderItem* root = project->projectItem();
+ return builder->buildDirectory(root);
+}
+
+// helper for startRunJob()
+QStringList fetchArgs(KDialog* dialog)
+{
+ Q_ASSERT(dialog->findChildren<KHistoryComboBox*>().count()==1);
+ KHistoryComboBox* argsBox = dialog->findChildren<KHistoryComboBox*>()[0];
+ Q_ASSERT(argsBox);
+ return argsBox->lineEdit()->text().split(" "); // do the right thing for escaped stuff
+}
+
+void writeArgsToConfig(KDialog* dialog)
+{
+ Q_ASSERT(dialog->findChildren<KHistoryComboBox*>().count()==1);
+ KHistoryComboBox* argsBox = dialog->findChildren<KHistoryComboBox*>()[0];
+ KConfigGroup cg = KGlobal::config()->group( "CTest" );
+ argsBox->addToHistory(argsBox->lineEdit()->text());
+ cg.writeEntry("args", argsBox->historyItems());
+}
+
+} // namespace
+
+void CTestPlugin::startRunJob()
+{
+ Q_ASSERT(sender());
+ KDialog* runDialog = qobject_cast<KDialog*>(sender());
+ Q_ASSERT(runDialog);
+
+ IProject* project = fetchProjectFrom(runDialog);
+ if (!project) return;
+ KUrl buildDir = fetchBuildDirFor(project);
+ if (!buildDir.isValid()) return;
+ QStringList args = fetchArgs(runDialog);
+ writeArgsToConfig(runDialog);
+
+ CTestJob* job = new CTestJob(m_runDelegate); // does not get deleted methinks
+ job->setTestRoot(buildDir);
+ kDebug() << "args" << args;
+ job->setCTestArguments(args);
+
+ ICore::self()->runController()->registerJob(job);
+}
+
+#include "ctestplugin.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,48 @@
+project(CTestWrapper)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CTestWrapper_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR})
+
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+enable_testing()
+
+include_directories(
+ ${QT_INCLUDES}
+ ${KDE4_INCLUDES}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR} )
+
+add_subdirectory(tests)
+
+########### next target ###############
+
+set(kdevctest_SRCS
+ ctestplugin.cpp
+ ctestjob.cpp
+ ctestoutdelegate.cpp
+ ctestoutmodel.cpp
+ ctestlogjob.cpp
+ ctestlogmodel.cpp
+ ctestlogdelegate.cpp)
+
+qt4_automoc(${kdevctest_SRCS})
+kde4_add_plugin(kdevctest ${kdevctest_SRCS})
+target_link_libraries(kdevctest
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDE4_KDEUI_LIBS}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
+ ${KDEVPLATFORM_UTIL_LIBRARIES})
+install(TARGETS kdevctest DESTINATION ${PLUGIN_INSTALL_DIR})
+
+########### install files ###############
+
+install( FILES kdevctest.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevctest.rc DESTINATION ${DATA_INSTALL_DIR}/kdevctest )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,34 @@
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+
+kde4_add_library(kdevctestlib
+ ../ctestoutmodel.cpp
+ ../ctestlogjob.cpp
+ ../ctestlogdelegate.cpp
+ ../ctestlogmodel.cpp)
+target_link_libraries(kdevctestlib
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDE4_KDEUI_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
+ ${KDEVPLATFORM_UTIL_LIBRARIES})
+
+kde4_add_unit_test(statusregextest statusregextest.cpp )
+target_link_libraries(statusregextest
+ kdevctestlib
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS})
+
+kde4_add_unit_test(locationregextest locationregextest.cpp )
+target_link_libraries(locationregextest
+ kdevctestlib
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS})
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp (revision 1522570)
@@ -0,0 +1,94 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "statusregextest.h"
+#include "../ctestoutmodel.h"
+#include <QtTest/QTest>
+
+void StatusRegExTest::assertMatch(const QString& line)
+{
+ QVERIFY2(ctestStatusLineRegExp().exactMatch(line), line.toLatin1());
+}
+
+void StatusRegExTest::assertNoMatch(const QString& line)
+{
+ QVERIFY2(!ctestStatusLineRegExp().exactMatch(line), line.toLatin1());
+}
+
+void StatusRegExTest::assertCaptured(const QString& text, const QString& testId, const QString& testName)
+{
+ QRegExp re = ctestStatusLineRegExp();
+ int id = re.indexIn(text);
+ QVERIFY(id!=-1);
+ QStringList capt = re.capturedTexts();
+ QVERIFY(capt.size() >= 3); // The whole match, testId & testName
+ QString actualId = capt[1].trimmed();
+ QString actualName = capt[2].trimmed();
+ QCOMPARE(testName, actualName);
+ QCOMPARE(testId, actualId);
+}
+
+void StatusRegExTest::isValid()
+{
+ QVERIFY(ctestStatusLineRegExp().isValid());
+}
+
+void StatusRegExTest::passed()
+{
+ assertMatch(" 3/ 10 Testing FooBar Passed");
+ assertMatch(" 3/ 10 Testing FooBar Passed ");
+ assertMatch(" 3/ 10 Testing FooBar Passed");
+ assertMatch(" 3/ 10 Testing FooBar Passed");
+ assertMatch(" 1/ 300 Testing FooBar Passed");
+}
+
+void StatusRegExTest::noMatch()
+{
+ assertNoMatch("FooBar");
+ assertNoMatch("abc/ 10 Testing FooBar Passed");
+ assertNoMatch(" 3/ edf Testing FooBar ***Failed");
+ assertNoMatch(" 3/ 10 AlloAllo FooBar Passed");
+ assertNoMatch(" 3 / 10 Testing FooBar Passed");
+}
+
+void StatusRegExTest::failed()
+{
+ assertMatch("10/ 30 Testing FooBar ***Failed");
+ assertMatch("10/ 30 Testing FooBar ***Failed ");
+}
+
+void StatusRegExTest::timeout()
+{
+ assertMatch("10/ 30 Testing FooBar ***Timeout");
+ assertMatch("10/ 30 Testing FooBar ***Timeout ");
+}
+
+void StatusRegExTest::capture()
+{
+ assertCaptured(" 3/ 10 Testing FooBar Passed", "3/ 10", "FooBar");
+}
+
+void StatusRegExTest::oneOne()
+{
+ assertMatch(" 1/ 1 Testing statusregextest Passed");
+ assertMatch(" 1/ 1 Testing statusregextest Passed"); // double space
+}
+
+#include "statusregextest.moc"
+QTEST_MAIN(StatusRegExTest)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/statusregextest.h (revision 1522570)
@@ -0,0 +1,45 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTWRAPPER_TEST_STATUSREGEXTEST_H
+#define CTESTWRAPPER_TEST_STATUSREGEXTEST_H
+
+#include <QtCore/QObject>
+
+/*! Tests regular expression that should match lines like:
+ * ' 4 / 50 Testing FooTest Passed' */
+class StatusRegExTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void isValid();
+ void passed();
+ void failed();
+ void timeout();
+ void noMatch();
+ void capture();
+ void oneOne();
+
+private:
+ void assertMatch(const QString& line);
+ void assertNoMatch(const QString& line);
+ void assertCaptured(const QString& text, const QString& testId, const QString& testName);
+};
+
+#endif // CTESTWRAPPER_TEST_STATUSREGEXTEST_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp (revision 1522570)
@@ -0,0 +1,81 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "locationregextest.h"
+#include <QtTest/QTest>
+#include <qtest_kde.h>
+#include "../ctestlogmodel.h"
+#include <KDebug>
+
+void LocationRegExTest::init()
+{
+}
+
+void LocationRegExTest::cleanup()
+{
+}
+
+void LocationRegExTest::assertLocationEquals(const QString& inputLine, const QString& expFile, int expLine)
+{
+ KUrl expFile_(expFile);
+ KUrl actualFile;
+ int actualLine;
+ bool isSrcLine = CTestLogModel::isSourceLocationLine(inputLine, actualFile, actualLine);
+ kDebug() << inputLine;
+ QVERIFY(isSrcLine);
+ QCOMPARE(expFile_, actualFile);
+ QCOMPARE(expLine, actualLine);
+}
+
+void LocationRegExTest::assertNoLocationLine(const QString& inputLine)
+{
+ KUrl foo; int line;
+ bool isSrcLine = CTestLogModel::isSourceLocationLine(inputLine, foo, line);
+ QVERIFY(!isSrcLine);
+}
+
+void LocationRegExTest::simpleLocation()
+{
+ // run-off-the-mill line
+ assertLocationEquals("[/path/to/file(5)]", "/path/to/file", 5);
+ assertLocationEquals("[/path/to/file(20)]", "/path/to/file", 20);
+ assertLocationEquals("[/path/file(10)]", "/path/file", 10);
+
+ // extra stuff in front should be ignored
+ assertLocationEquals(" Loc: [/foo/bar(5)]", "/foo/bar", 5);
+ // extension
+ assertLocationEquals("[/path/to/file.cpp(10)]", "/path/to/file.cpp", 10);
+ // top level file
+ assertLocationEquals("[/file(15)]", "/file", 15);
+
+ assertLocationEquals("[/path/to/file(0)]", "/path/to/file", 0);
+ assertLocationEquals("[/path/to/file(9)]", "/path/to/file", 9);
+}
+
+void LocationRegExTest::noMatch()
+{
+ assertNoLocationLine("foo bar");
+ // no '[ ]'
+ assertNoLocationLine("/path/to/file(20)");
+ // no number in '()'
+ assertNoLocationLine("[/path/to/file(foo)");
+}
+
+QTEST_MAIN( LocationRegExTest )
+#include "locationregextest.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/tests/locationregextest.h (revision 1522570)
@@ -0,0 +1,41 @@
+/* This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef QTEST_LOCATIONREGEXTEST_H_INCLUDED
+#define QTEST_LOCATIONREGEXTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+class LocationRegExTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void simpleLocation();
+ void noMatch();
+
+private:
+ void assertLocationEquals(const QString& inputLine, const QString& expFile, int expLine);
+ void assertNoLocationLine(const QString& inputLine);
+
+};
+
+#endif // QTEST_LOCATIONREGEXTEST_H_INCLUDED
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevctest.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutmodel.h (revision 1522570)
@@ -0,0 +1,82 @@
+/* KDevelop xUnit plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTOUTMODEL_H
+#define CTESTOUTMODEL_H
+
+#include <QStandardItemModel>
+#include <outputview/ioutputviewmodel.h>
+#include <KUrl>
+
+class QModelIndex;
+
+/*! Item of the CTestOut model. It represents a single
+ * ctest test status output line like:
+ * ' 4/ 50 Testing FooBar Passed'. */
+class CTestOutItem : public QStandardItem
+{
+public:
+ CTestOutItem(const QString &text);
+ ~CTestOutItem();
+ enum State { NotRun, /** Test did not finish yet */
+ Passed, Failed, Timeout };
+ virtual QVariant data(int role) const;
+ QString m_id; /** The '14/ 52' bit of a ctest output line */
+ QString m_name; /** The 'FooTest' bit of a ctest output line */
+ State m_state;
+ void extractNameAndNumber(); /** Fills m_id and m_name from the Qt::DisplayData ie a line of output */
+
+ enum { StateRole = QStandardItem::UserType+1 };
+};
+
+Q_DECLARE_METATYPE(CTestOutItem::State)
+
+/*! Matches lines like '2/ 40 Testing FooTest Passed'
+ * '3/ 40 Testing BarTest ***Failed' */
+QRegExp& ctestStatusLineRegExp();
+
+/*! Holds ctest-process output lines, to be shown in an outputview */
+class CTestOutModel : public QStandardItemModel, public KDevelop::IOutputViewModel
+{
+Q_OBJECT
+
+public:
+ explicit CTestOutModel(QObject *parent);
+ ~CTestOutModel();
+
+ void activate(const QModelIndex &idx);
+ QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
+ QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
+ QVariant data(const QModelIndex& index, int role) const;
+ void setTestRoot(const KUrl& root);
+ void startLogJobFor(CTestOutItem* item);
+
+public Q_SLOTS:
+ void appendOutputs(const QStringList &lines);
+ void appendErrors(const QStringList &lines);
+ void slotCompleted();
+ void slotFailed();
+
+private:
+ KUrl m_testRoot;
+};
+
+#endif // CTESTOUTMODEL_h
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp (revision 1522570)
@@ -0,0 +1,123 @@
+/* This file is part of KDevelop
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "ctestlogmodel.h"
+
+#include <QModelIndex>
+#include <KGlobalSettings>
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <ktexteditor/cursor.h>
+
+#include <QRegExp>
+
+using KDevelop::ICore;
+using KDevelop::IDocumentController;
+
+CTestLogItem::CTestLogItem(const QString &text)
+ : QStandardItem(text)
+{}
+
+CTestLogItem::~CTestLogItem()
+{}
+
+CTestLogModel::CTestLogModel(QObject *parent)
+ : QStandardItemModel(parent)
+{}
+
+CTestLogModel::~CTestLogModel()
+{}
+
+QVariant CTestLogModel::data(const QModelIndex& index, int role) const
+{
+ if (role != Qt::FontRole) {
+ return QStandardItemModel::data(index, role);
+ } else {
+ return KGlobalSettings::fixedFont();
+ }
+}
+
+namespace
+{
+ // locRe matches location references in verbose output like:
+ // [/path/to/foo.cpp(123)]
+ QRegExp g_locRe("\\[(([/].*)+)\\(([0-9]+)\\)\\]"); // TODO not quite portable
+}
+
+bool CTestLogModel::isSourceLocationLine(const QString& text, KUrl& file, int& line)
+{
+ Q_ASSERT(g_locRe.isValid());
+ QRegExp re = g_locRe;
+ if (-1 == re.indexIn(text)) return false;
+ // got a match
+ file = KUrl(re.cap(1));
+ line = re.cap(re.capturedTexts().size()-1).toInt();
+ return true;
+}
+
+void CTestLogModel::activate(const QModelIndex &idx)
+{
+ QString text = idx.data(Qt::DisplayRole).toString();
+ KUrl file;
+ int line;
+ bool isSrcLine = isSourceLocationLine(text, file, line);
+ if (isSrcLine) {
+ KTextEditor::Cursor loc(line-1, 0);
+ IDocumentController* docCtrl = ICore::self()->documentController();
+ docCtrl->openDocument(file, loc);
+ }
+}
+
+QModelIndex CTestLogModel::nextHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+QModelIndex CTestLogModel::previousHighlightIndex(const QModelIndex& currentIndex)
+{
+ Q_UNUSED(currentIndex);
+ return QModelIndex();
+}
+
+void CTestLogModel::appendOutputs(const QStringList &lines)
+{
+ foreach(const QString& line, lines) {
+ appendRow(new QStandardItem(line));
+ }
+}
+
+void CTestLogModel::appendErrors(const QStringList &lines)
+{
+ foreach(const QString& line, lines) {
+ appendRow(new QStandardItem(line));
+ }
+}
+
+void CTestLogModel::slotCompleted()
+{
+}
+
+void CTestLogModel::slotFailed()
+{
+ appendRow(new QStandardItem("Failed"));
+}
+
+#include "ctestlogmodel.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp (revision 1522570)
@@ -0,0 +1,65 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "ctestoutdelegate.h"
+#include "ctestoutmodel.h"
+#include <QtGui/QPainter>
+#include <QtCore/QModelIndex>
+#include <KDebug>
+
+CTestOutDelegate::CTestOutDelegate(QObject* parent)
+ : QItemDelegate(parent),
+ textBrush(KColorScheme::View, KColorScheme::NormalText),
+ errorBrush(KColorScheme::View, KColorScheme::NegativeText),
+ passBrush(KColorScheme::View, KColorScheme::PositiveText)
+{
+}
+
+void CTestOutDelegate::initStyleFor(const QVariant& stateVariant, QStyleOptionViewItem& style) const
+{
+ //CTestOutItem::State state = stateVariant.value<CTestOutItem::State>();
+ int state = stateVariant.toInt();
+ switch (state) {
+ case CTestOutItem::Failed:
+ case CTestOutItem::Timeout:
+ style.palette.setBrush(QPalette::Text, errorBrush.brush(style.palette));
+ break;
+ case CTestOutItem::Passed:
+ style.palette.setBrush(QPalette::Text, passBrush.brush(style.palette));
+ break;
+ default:
+ style.palette.setBrush(QPalette::Text, textBrush.brush(style.palette));
+ }
+}
+
+void CTestOutDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
+{
+ QStyleOptionViewItem opt = option;
+ QVariant state = index.data(CTestOutItem::StateRole);
+ if (state.isValid()) {
+ initStyleFor(state, opt);
+ } else {
+ opt.palette.setBrush(QPalette::Text, textBrush.brush(option.palette));
+ }
+ QItemDelegate::paint(painter, opt, index);
+}
+
+#include "ctestoutdelegate.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestplugin.h (revision 1522570)
@@ -0,0 +1,46 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTPLUGIN_H
+#define CTESTPLUGIN_H
+
+#include <QVariantList>
+#include <interfaces/iplugin.h>
+
+class CTestOutDelegate;
+
+class CTestPlugin : public KDevelop::IPlugin
+{
+Q_OBJECT
+
+public:
+ explicit CTestPlugin(QObject* parent, const QVariantList& = QVariantList());
+ virtual ~CTestPlugin();
+
+private slots:
+ void showDialog();
+ void startRunJob();
+
+private:
+ CTestOutDelegate* m_runDelegate; // controls colorization of items in the ctest-run outputview
+};
+
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h (revision 1522570)
@@ -0,0 +1,51 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef QTEST_QTESTOUTPUTDELEGATE_H
+#define QTEST_QTESTOUTPUTDELEGATE_H
+
+#include <QtGui/QItemDelegate>
+#include <kcolorscheme.h>
+
+/*! Is responsible for colorizing items in the primary ctest
+ * output view.
+ * eg:
+ * 2/ 20 Testing Foo Passed << this line is colored green
+ * 3/ 20 Testing Bar ***Failed << this one is red.
+ */
+class CTestOutDelegate : public QItemDelegate
+{
+Q_OBJECT
+
+public:
+ CTestOutDelegate(QObject*);
+ void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
+
+private:
+ void inline initStyleFor(const QVariant& state, QStyleOptionViewItem& style) const;
+
+private:
+ KStatefulBrush textBrush;
+ KStatefulBrush errorBrush;
+ KStatefulBrush passBrush;
+};
+
+#endif // QTEST_QTESTOUTPUTDELEGATE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogmodel.h (revision 1522570)
@@ -0,0 +1,71 @@
+/* KDevelop xUnit plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CTESTWRAPPER_CTESTLOGMODEL_H
+#define CTESTWRAPPER_CTESTLOGMODEL_H
+
+#include <QStandardItemModel>
+#include <outputview/ioutputviewmodel.h>
+
+class QModelIndex;
+class QRegExp;
+class KUrl;
+
+/*! A model item in the verbose model. This represents a single line
+ * of text in a ctest-log.*/
+class CTestLogItem : public QStandardItem
+{
+public:
+ CTestLogItem(const QString &text);
+ ~CTestLogItem();
+};
+
+/*! Holds ctest-log text lines, to be shown in an outputview. */
+class CTestLogModel : public QStandardItemModel, public KDevelop::IOutputViewModel
+{
+Q_OBJECT
+
+public:
+ explicit CTestLogModel(QObject *parent=0);
+ ~CTestLogModel();
+
+ void activate(const QModelIndex &idx);
+ QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
+ QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
+ QVariant data(const QModelIndex& index, int role) const;
+
+ /*! Matches lines like
+ * [/path/to/file(10)]
+ * where '10' is a linenumber
+ *
+ * If this matches with @p text, returns true and fills
+ * @p file and @p line
+ * Returns false if not matched. */
+ static bool isSourceLocationLine(const QString& text, KUrl& file, int& line);
+
+public Q_SLOTS:
+ void appendOutputs(const QStringList &lines);
+ void appendErrors(const QStringList &lines);
+ void slotCompleted();
+ void slotFailed();
+};
+
+#endif // CTESTWRAPPER_LOGMODEL_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestjob.cpp (revision 1522570)
@@ -0,0 +1,102 @@
+/* KDevelop xUnit plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com> *
+ * Copyright 2008 by Hamish Rodda <rodda@kde.org>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+// local
+#include "ctestjob.h"
+#include "ctestoutmodel.h"
+#include "ctestoutdelegate.h"
+
+// KDE
+#include <KLocale>
+#include <KDebug>
+#include <KProcess>
+
+// KDevPlatform
+#include <interfaces/icore.h>
+#include <util/processlinemaker.h>
+
+using KDevelop::OutputJob;
+using KDevelop::ProcessLineMaker;
+
+CTestJob::CTestJob(CTestOutDelegate* parent)
+ : OutputJob(parent), m_ctest(0)
+{}
+
+CTestJob::~CTestJob()
+{}
+
+void CTestJob::start()
+{
+ Q_ASSERT(m_testRoot.isValid()); Q_ASSERT(m_ctest == 0);
+
+ setToolTitle(i18n("CTest"));
+ setToolIcon(KIcon("dialog-ok-apply"));
+ setViewType(KDevelop::IOutputView::HistoryView);
+ setBehaviours(KDevelop::IOutputView::AutoScroll | KDevelop::IOutputView::AllowUserClose);
+ setViewType(KDevelop::IOutputView::OneView);
+
+ setModel(new CTestOutModel(delegate()), KDevelop::IOutputView::TakeOwnership);
+ model()->setTestRoot(m_testRoot);
+ setDelegate(delegate());
+
+ m_ctest = new KProcess(this);
+ m_ctest->setWorkingDirectory(m_testRoot.path());
+ m_ctest->setProgram("ctest", m_ctestArgs);
+ m_ctest->setOutputChannelMode(KProcess::MergedChannels);
+ ProcessLineMaker* plm = new ProcessLineMaker(m_ctest, this);
+
+ startOutput();
+ connect(plm, SIGNAL(receivedStdoutLines(QStringList)), model(), SLOT(appendOutputs(QStringList)));
+ connect(plm, SIGNAL(receivedStderrLines(QStringList)), model(), SLOT(appendErrors(QStringList)));
+ connect(m_ctest, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(done()));
+ m_ctest->start();
+}
+
+void CTestJob::done()
+{
+ model()->slotCompleted();
+ emitResult();
+}
+
+void CTestJob::setTestRoot(const KUrl& root)
+{
+ Q_ASSERT(root.isValid()); Q_ASSERT(!m_testRoot.isValid());
+ m_testRoot = root;
+}
+
+void CTestJob::setCTestArguments(const QStringList& args)
+{
+ Q_ASSERT(m_ctestArgs.isEmpty());
+ m_ctestArgs = args;
+}
+
+CTestOutDelegate* CTestJob::delegate() const
+{
+ return const_cast<CTestOutDelegate*>(static_cast<const CTestOutDelegate*>(parent()));
+}
+
+CTestOutModel* CTestJob::model() const
+{
+ return static_cast<CTestOutModel*>(OutputJob::model());
+}
+
+#include "ctestjob.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/kdevctest.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="kdevctest" version="1">
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp (revision 1522570)
@@ -0,0 +1,49 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "ctestlogdelegate.h"
+#include "ctestlogmodel.h"
+#include <QtGui/QPainter>
+#include <QtCore/QModelIndex>
+#include <KDebug>
+
+
+CTestLogDelegate::CTestLogDelegate(QObject* parent)
+ : QItemDelegate(parent),
+ textBrush(KColorScheme::View, KColorScheme::NormalText),
+ errorBrush(KColorScheme::View, KColorScheme::NegativeText),
+ passBrush(KColorScheme::View, KColorScheme::PositiveText)
+{
+}
+
+void CTestLogDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
+{
+ QString text = index.data(Qt::DisplayRole).toString();
+ QStyleOptionViewItem style(option);
+ if (text.startsWith("PASS")) { // QTestLib prints this in front of green commands
+ style.palette.setBrush(QPalette::Text, passBrush.brush(style.palette));
+ } else if (text.startsWith("FAIL!")) { // QTestLib specific output
+ style.palette.setBrush(QPalette::Text, errorBrush.brush(style.palette));
+ }
+ QItemDelegate::paint(painter, style, index);
+}
+
+#include "ctestlogdelegate.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp (revision 1522570)
@@ -0,0 +1,141 @@
+/* KDevelop xUnit plugin
+ * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
+ * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com> *
+ * Copyright 2008 by Hamish Rodda <rodda@kde.org>
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+// local
+#include "ctestlogjob.h"
+#include "ctestlogmodel.h"
+#include "ctestlogdelegate.h"
+#include "ctestoutmodel.h"
+
+// KDE/Qt
+#include <KLocale>
+#include <KDebug>
+#include <KProcess>
+#include <QFile>
+
+// KDevPlatform
+#include <interfaces/icore.h>
+
+using KDevelop::OutputJob;
+
+CTestLogJob::CTestLogJob(CTestLogDelegate* delegate, CTestLogModel* model, const KUrl& testRoot, CTestOutItem* test)
+ : OutputJob(0), m_testRoot(testRoot), m_test(test), m_delegate(delegate), m_model(model)
+{}
+
+CTestLogJob::~CTestLogJob()
+{}
+
+void CTestLogJob::start()
+{
+ Q_ASSERT(m_testRoot.isValid()); Q_ASSERT(m_test != 0);
+
+ setToolTitle(i18n("CTest"));
+ setToolIcon(KIcon("edit-find"));
+ setViewType(KDevelop::IOutputView::HistoryView);
+ setStandardToolView(KDevelop::IOutputView::TestView);
+ setBehaviours(KDevelop::IOutputView::AutoScroll | KDevelop::IOutputView::AllowUserClose);
+
+ setModel(m_model, KDevelop::IOutputView::TakeOwnership);
+ setDelegate(m_delegate, KDevelop::IOutputView::TakeOwnership);
+
+ KUrl ctestLogFile(m_testRoot, "Testing/Temporary/LastTest.log");
+ if (!ctestLogFile.isLocalFile()) {
+ kWarning() << "Only local CTest log files supported for now [" << ctestLogFile.path() << "]";
+ return;
+ }
+ if (!QFile::exists(ctestLogFile.path())) {
+ kWarning() << "CTest log file does not exist [" << ctestLogFile.path() << "]";
+ return;
+ }
+
+ startOutput();
+ readLog(ctestLogFile);
+ model()->slotCompleted();
+ emitResult();
+}
+
+void CTestLogJob::readLog(const KUrl& ctestLog)
+{
+ QFile f(ctestLog.path());
+ f.open(QIODevice::ReadOnly);
+ if (!f.isOpen()) {
+ kError() << "Failed to open test output file for reading [" << ctestLog.path() << "]";
+ return;
+ }
+ QTextStream stream(&f);
+
+ // skip until the start of m_test
+
+ // 4/52 Testing: duchaintest
+ // 4/52 Test: duchaintest
+ // Command: "/home/nix/KdeDev/kdevelop/build/languages/cpp/cppduchain/tests/duchaintest.shell"
+ // Directory: /home/nix/KdeDev/kdevelop/build/languages/cpp/cppduchain/tests
+ // "duchaintest" start time: Oct 28 16:26 CET
+ // Output:
+ //----------------------------------------------------------
+
+ QString marker("----------------------------------------------------------\n");
+ bool foundTestStart = false;
+ QString line;
+ while(!f.atEnd() && !foundTestStart) {
+ line = f.readLine();
+ if (line.startsWith(m_test->m_id)) {
+ kDebug(9003) << "found test id " << m_test->m_id << line;
+ // found '4/52' or the likes, now skip until '-----------------'
+ while (!f.atEnd() && !foundTestStart) {
+ line = f.readLine();
+ kDebug(9003) << line;
+ if (line == marker) foundTestStart = true;
+ }
+ }
+ }
+
+ if (f.atEnd()) {
+ kError() << "Failed to find output for" << m_test->m_name << "in ctest log [" << ctestLog.path() << "]";
+ return;
+ }
+
+ bool foundTestEnd = false;
+ QStringList lines;
+ while (!f.atEnd() && !foundTestEnd) {
+ lines.clear();
+ for (int i=0; i<1000 && !f.atEnd(); ++i) {
+ QString line = f.readLine();
+ if (line == marker) {
+ // another '-----------------'. this is a bit fragile as stopping criteria ...
+ foundTestEnd = true;
+ break;
+ }
+ line.chop(1);
+ //kDebug(9003) << "append ->" << line;
+ lines.append(line);
+ }
+ model()->appendOutputs(lines);
+ }
+}
+
+CTestLogModel* CTestLogJob::model() const
+{
+ return m_model;
+}
+
+#include "ctestlogjob.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h (revision 1522570)
@@ -0,0 +1,42 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef QTEST_QTESTOUTPUTDELEGATE_H
+#define QTEST_QTESTOUTPUTDELEGATE_H
+
+#include <QtGui/QItemDelegate>
+#include <kcolorscheme.h>
+
+class CTestLogDelegate : public QItemDelegate
+{
+Q_OBJECT
+
+public:
+ CTestLogDelegate(QObject* parent=0);
+ void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
+
+private:
+ KStatefulBrush textBrush;
+ KStatefulBrush errorBrush;
+ KStatefulBrush passBrush;
+};
+
+#endif // QTEST_QTESTOUTPUTDELEGATE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4 (revision 1522570)
@@ -0,0 +1,3 @@
+[Project]
+Name=ctest-wrapper
+Manager=KDevCMakeManager
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop (revision 1522570)
@@ -0,0 +1,72 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=This plugin displays a graphical view of the definition-use chain produced by the C++ support
+Comment[bs]=Ovaj dodatak prikazuje grafički prikaz definicije lanca upotrebe, izrađenog od strane C++ podrške
+Comment[ca]=Aquest connector mostra una vista gràfica de la cadena de definició-ús produïda per la implementació del llenguatge C++
+Comment[ca@valencia]=Aquest connector mostra una vista gràfica de la cadena de definició-ús produïda per la implementació del llenguatge C++
+Comment[de]=Dieses Modul zeigt eine grafische Ansicht der Definition-Use-Chain, die durch die Unterstützung für C++ erzeugt wurde.
+Comment[en_GB]=This plugin displays a graphical view of the definition-use chain produced by the C++ support
+Comment[es]=Este complemento muestra una vista gráfica de la cadena definición-uso producida por la implementación de C++
+Comment[et]=See plugin näitab graafiliselt C++ toetusel loodud definitsiooni-kasutuse ahelat.
+Comment[fr]=Ce module externe affiche une vue graphique de la chaîne définition-utilisation produite par la prise en charge du C++
+Comment[gl]=Este complemento mostra unha vista gráfica da cadea de definicións e usos producida pola compatibilidade con C++.
+Comment[it]=Questa estensione mostra graficamente la definition-use chain (DUChain) prodotta dal supporto per il linguaggio C++.
+Comment[nl]=Deze plugin geeft een grafische weergave van door C++ ondersteuning geproduceerde definition-use Chain
+Comment[pl]=Wtyczka ta wyświetla widok graficzny łańcucha definicji-użycia wyprodukowany przez obsługę C++
+Comment[pt]=Este 'plugin' apresenta uma vista gráfica sobre a sequência de definições-usos que é produzida pelo componente da linguagem C++
+Comment[pt_BR]=Este plugin apresenta uma vista gráfica sobre a sequência de definições-usos que é produzida pelo suporte ao C++
+Comment[sv]=Insticksprogrammet visar en grafisk vy av definition-användningskedjan skapad av C++ stödet.
+Comment[uk]=За допомогою цього додатка можна переглянути у графічному вигляді ланцюжок «Визначення-Використання», створений частиною, що відповідає за мову програмування C++.
+Comment[x-test]=xxThis plugin displays a graphical view of the definition-use chain produced by the C++ supportxx
+Name=DUChain View
+Name[bs]=DUChain pregled
+Name[ca]=Visualització de cadena DU
+Name[ca@valencia]=Visualització de cadena DU
+Name[de]=DUChain-Ansicht
+Name[en_GB]=DUChain View
+Name[es]=Vista DUChain
+Name[et]=DU-ahela vaade
+Name[fr]=Affichage DUChain
+Name[ga]=Amharc DUChain
+Name[gl]=Vista de DUChain
+Name[it]=Vista DUChain
+Name[nl]=DUChain weergave
+Name[pl]=Widok DUChain
+Name[pt]=Área de Definições-Usos
+Name[pt_BR]=Área de Definições-Usos
+Name[sk]=Prehliadať DUChain
+Name[sv]=Visning av definition-användningskedja
+Name[uk]=Перегляд ВВ-ланцюжка
+Name[x-test]=xxDUChain Viewxx
+GenericName=DUChain View
+GenericName[bs]=DUChain pregled
+GenericName[ca]=Visualització de cadena DU
+GenericName[ca@valencia]=Visualització de cadena DU
+GenericName[de]=DUChain-Ansicht
+GenericName[en_GB]=DUChain View
+GenericName[es]=Vista DUChain
+GenericName[et]=DU-ahela vaade
+GenericName[fr]=Afficheur DUChain
+GenericName[ga]=Amharc DUChain
+GenericName[gl]=Vista de DUChain
+GenericName[it]=Vista DUChain
+GenericName[ja]=DUChain ビュー
+GenericName[nds]=Dbkeed-Ansicht
+GenericName[nl]=DUChain weergave
+GenericName[pl]=Widok DUChain
+GenericName[pt]=Área de Definições-Usos
+GenericName[pt_BR]=Área de Definições-Usos
+GenericName[sk]=Prehliadať DUChain
+GenericName[sv]=Visning av definition-användningskedja
+GenericName[tr]=DUChain Görünümü
+GenericName[uk]=Перегляд ВВ-ланцюжка
+GenericName[x-test]=xxDUChain Viewxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevduchainview
+X-KDevelop-Version=7
+X-KDevelop-Category=Project
+X-KDE-PluginInfo-Name=kdevduchainview
+X-KDE-PluginInfo-Author=Hamish Rodda
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Mode=GUI
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp (revision 1522570)
@@ -0,0 +1,574 @@
+/*
+ * KDevelop DUChain viewer
+ *
+ * Copyright 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "duchainmodel.h"
+
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <ktemporaryfile.h>
+#include <kprocess.h>
+
+#include <interfaces/idocument.h>
+#include <interfaces/icore.h>
+#include <interfaces/ilanguagecontroller.h>
+#include <language/backgroundparser/backgroundparser.h>
+#include <language/backgroundparser/parsejob.h>
+
+#include <language/editor/hashedstring.h>
+
+#include <language/duchain/dumpdotgraph.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/use.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/duchainpointer.h>
+
+#include "duchainviewplugin.h"
+#include <language/duchain/functiondefinition.h>
+
+//#include "modeltest.h"
+
+using namespace KTextEditor;
+using namespace KDevelop;
+
+///When the context is a proxy-context, returns the assigned content-context.
+TopDUContext* getRealContext(TopDUContext* ctx) {
+ if(ctx && ctx->parsingEnvironmentFile() && ctx->parsingEnvironmentFile()->isProxyContext() && !ctx->importedParentContexts().isEmpty())
+ return dynamic_cast<TopDUContext*>(ctx->importedParentContexts()[0].context(0));
+ else
+ return ctx;
+}
+
+ProxyObject::ProxyObject(DUChainBase* _parent, DUChainBase* _object)
+: DUChainBase(_object->range())
+ , parent(_parent)
+ , object(_object)
+{
+ setSmartRange(_object->smartRange(), DUChainBase::DontOwn);
+}
+
+DUChainModel::DUChainModel(DUChainViewPlugin* parent)
+ : QAbstractItemModel(parent)
+ , m_chain(0)
+{
+ //new ModelTest(this);
+ connect( plugin()->core()->languageController()->backgroundParser(), SIGNAL(parseJobFinished(KDevelop::ParseJob*)), this, SLOT(parseJobFinished(KDevelop::ParseJob*)));
+
+ bool success = connect(DUChain::self()->notifier(), SIGNAL(branchAdded(KDevelop::DUContextPointer)), SLOT(branchAdded(KDevelop::DUContextPointer)), Qt::QueuedConnection);
+ Q_ASSERT(success);
+ #ifdef QT_NO_DEBUG
+ Q_UNUSED(success);
+ #endif
+}
+
+DUChainViewPlugin* DUChainModel::plugin() const {
+ return qobject_cast<DUChainViewPlugin*>(QObject::parent());
+}
+
+DUChainModel::~DUChainModel()
+{
+ qDeleteAll(m_knownObjects);
+}
+
+void DUChainModel::parseJobFinished(KDevelop::ParseJob* job)
+{
+ if( KUrl(job->document().str()) == m_document && job->duChain() ) {
+ setTopContext(TopDUContextPointer(job->duChain()->weakPointer()));
+ }
+
+}
+
+void DUChainModel::documentActivated(KDevelop::IDocument* document)
+{
+ if (document) {
+ DUChainReadLocker readLock(DUChain::lock());
+ TopDUContext* ptr = DUChain::self()->chainForDocument(document->url());
+ TopDUContextPointer chain(ptr);
+ if (chain && chain != m_chain)
+ setTopContext(chain);
+ else {
+ m_document = document->url();
+ }
+ }
+}
+
+void DUChainModel::setTopContext(TopDUContextPointer context)
+{
+ DUChainReadLocker readLock(DUChain::lock());
+
+ if( context )
+ m_document = KUrl(context->url().str());
+ else
+ m_document = KUrl();
+
+ context = TopDUContextPointer(getRealContext(context.data()));
+
+ if (m_chain != context)
+ m_chain = context;
+
+ qDeleteAll(m_proxyObjects);
+ m_proxyObjects.clear();
+
+ m_objectLists.clear();
+ m_modelRow.clear();
+
+ reset();
+}
+
+int DUChainModel::columnCount(const QModelIndex & parent) const
+{
+ Q_UNUSED(parent);
+
+ return 1;
+}
+
+DUChainBasePointer* DUChainModel::objectForIndex(const QModelIndex& index) const
+{
+ return static_cast<DUChainBasePointer*>(index.internalPointer());
+}
+
+QModelIndex DUChainModel::index(int row, int column, const QModelIndex & parent) const
+{
+ if (row < 0 || column < 0 || column > 0 || !m_chain)
+ return QModelIndex();
+
+ if (!parent.isValid()) {
+ if (parent.row() > 0 || parent.column() > 0)
+ return QModelIndex();
+
+ return createIndex(row,column,createPointerForObject(m_chain.data()));
+ }
+
+ DUChainReadLocker readLock(DUChain::lock());
+
+ DUChainBasePointer* base = objectForIndex(parent);
+ if (!base || !base->data())
+ return QModelIndex();
+
+ QList<DUChainBasePointer*>* items = childItems(base);
+
+ if (!items)
+ return QModelIndex();
+
+ if (row >= items->count())
+ return QModelIndex();
+
+ return createIndex(row, column, items->at(row));
+}
+
+QModelIndex DUChainModel::parent(const QModelIndex & index) const
+{
+ if (!index.isValid())
+ return QModelIndex();
+
+ DUChainReadLocker readLock(DUChain::lock());
+
+ DUChainBasePointer* basep = objectForIndex(index);
+ if (!basep || !basep->data())
+ return QModelIndex();
+
+ DUChainBase* base = basep->data();
+
+ if (ProxyObject* proxy = dynamic_cast<ProxyObject*>(base))
+ return createParentIndex(createPointerForObject(proxy->parent));
+
+ if (DUContext* context = dynamic_cast<DUContext*>(base))
+ {
+ if (context && context->parentContext())
+ return createParentIndex(createPointerForObject(context->parentContext()));
+ else
+ return QModelIndex();
+ }
+
+ if (Declaration* dec = dynamic_cast<Declaration*>(base))
+ return createParentIndex(createPointerForObject(dec->context()));
+
+// if (Use* use = dynamic_cast<Use*>(base))
+// return createParentIndex(createPointerForObject(use->declaration()));
+
+ // Shouldn't really hit this
+ //Q_ASSERT(false);
+ return QModelIndex();
+}
+
+QVariant DUChainModel::data(const QModelIndex& index, int role) const
+{
+ if (!index.isValid())
+ return QVariant();
+
+ DUChainReadLocker readLock(DUChain::lock());
+
+ DUChainBasePointer* basep = objectForIndex(index);
+ if (!basep || !basep->data())
+ return QVariant();
+
+ DUChainBase* base = basep->data();
+
+ ProxyObject* proxy = dynamic_cast<ProxyObject*>(base);
+ if (proxy)
+ base = proxy->object;
+
+ if(role == Qt::ToolTipRole)
+ return i18n("Range: %1:%2 -> %3 %4", base->range().start.line, base->range().start.column, base->range().end.line, base->range().start.column);
+
+ if (DUContext* context = dynamic_cast<DUContext*>(base)) {
+ switch (role) {
+ case Qt::DisplayRole:
+ if (proxy)
+ return i18n("Imported Context: %1", context->localScopeIdentifier().toString());
+ else if (context == m_chain.data())
+ return i18n("Top level context");
+ else
+ return i18n("Context: %1", context->localScopeIdentifier().toString());
+ }
+
+ } else if (Declaration* dec = dynamic_cast<Declaration*>(base)) {
+ switch (role) {
+ case Qt::DisplayRole: {
+ if(dynamic_cast<FunctionDefinition*>(dec) && static_cast<FunctionDefinition*>(dec)->declaration(m_chain.data()))
+ return i18n("Definition: %1", static_cast<FunctionDefinition*>(dec)->declaration(m_chain.data())->identifier().toString());
+ else
+ return i18n("Declaration: %1", dec->identifier().toString());
+ }
+ }
+
+ }/* else if (Use* use = dynamic_cast<Use*>(base)) {
+ switch (role) {
+ case Qt::DisplayRole:
+ return i18n("Use: %1", use->declaration() ? use->declaration()->identifier().toString() : i18n("[No definition found]"));
+ }
+
+ }*/ else {
+ switch (role) {
+ case Qt::DisplayRole:
+ return i18n("Unknown object.");
+ }
+ }
+
+ return QVariant();
+}
+
+int DUChainModel::rowCount(const QModelIndex & parent) const
+{
+ if (!m_chain)
+ return 0;
+
+ if (!parent.isValid())
+ return 1;
+
+ DUChainReadLocker readLock(DUChain::lock());
+
+ DUChainBasePointer* base = objectForIndex(parent);
+ if (!base || !base->data())
+ return 0;
+
+ QList<DUChainBasePointer*>* items = childItems(base);
+ if (!items)
+ return 0;
+
+ return items->count();
+}
+
+#define TEST_NEXT(iterator, index) \
+ if (!first.isValid()) { \
+ current = nextItem(iterator, firstInit); \
+ if (current.isValid() && (current < first || !first.isValid())) { \
+ first = current; \
+ found = index; \
+ } \
+ }
+
+QList<DUChainBasePointer*>* DUChainModel::childItems(DUChainBasePointer* parentp) const
+{
+ Q_ASSERT(parentp->data());
+
+ if (m_objectLists.contains(parentp))
+ return m_objectLists[parentp];
+
+ DUChainBase* parent = parentp->data();
+
+ ProxyObject* proxy = dynamic_cast<ProxyObject*>(parent);
+ if (proxy)
+ parent = proxy->object;
+
+ QList<DUChainBasePointer*>* list = 0;
+
+ if (DUContext* context = dynamic_cast<DUContext*>(parent)) {
+
+ QVector<DUContext*> importedParentContextsData;
+ ///@todo Think whether this can be called for top-contexts, and if it can, care about endless recursion because of loops.
+ foreach( const DUContext::Import &p, context->importedParentContexts() )
+ if( p.context(0) )
+ importedParentContextsData << p.context(0);
+
+ QVectorIterator<DUContext*> contexts = context->childContexts();
+ QVectorIterator<DUContext*> importedParentContexts = importedParentContextsData;
+ QVectorIterator<Declaration*> declarations = context->localDeclarations();
+// QListIterator<Use*> uses = context->uses();
+
+
+ bool firstInit = true;
+ forever {
+ DUChainBase* currentItem = 0;
+ Cursor first = Cursor::invalid(), current;
+ int found = 0;
+
+ TEST_NEXT(contexts, 1)
+ TEST_NEXT(importedParentContexts, 2)
+ TEST_NEXT(declarations, 3)
+
+ if (first.isValid()) {
+ switch (found) {
+ case 1:
+ currentItem = item(contexts);
+ break;
+ case 2:
+ currentItem = proxyItem(context, importedParentContexts);
+ break;
+ case 3:
+ currentItem = item(declarations);
+ break;
+ default:
+ Q_ASSERT(false);
+ break;
+ }
+
+ if (!list)
+ list = new QList<DUChainBasePointer*>();
+
+ DUChainBasePointer* currentPointer = createPointerForObject(currentItem);
+ m_modelRow[currentPointer] = list->count();
+ list->append(currentPointer);
+
+ first = Cursor::invalid();
+ } else {
+ break;
+ }
+
+ firstInit = false;
+ }
+
+ } else if (Declaration* dec = dynamic_cast<Declaration*>(parent)) {
+ if (!dec->isDefinition() && FunctionDefinition::definition(dec)) {
+ list = new QList<DUChainBasePointer*>();
+ list->append(createPointerForObject(FunctionDefinition::definition(dec)));
+ }
+
+// foreach (Use* use, dec->uses()) {
+// if (!list)
+// list = new QList<DUChainBasePointer*>();
+//
+// list->append(createPointerForObject(use));
+// }
+
+ } else {
+ // No child items for definitions or uses
+ //kDebug(9500) << "No child items for definitions or uses";
+ }
+
+ m_objectLists.insert(parentp, list);
+
+ return list;
+}
+
+/*bool DUChainModel::hasChildren(const QModelIndex & parent) const
+{
+ if (!parent.isValid())
+ return true;
+
+ DUChainReadLocker readLock(DUChain::lock());
+
+ DUChainBase* base = objectForIndex(parent);
+ if (!base)
+ return false;
+
+ if (m_objectLists.contains(base))
+ return !m_objectLists[base]->isEmpty();
+
+ ProxyObject* proxy = dynamic_cast<ProxyObject*>(base);
+ if (proxy)
+ base = proxy->object;
+
+ if (DUContext* context = dynamic_cast<DUContext*>(base))
+ return !context->childContexts().isEmpty() || !context->importedParentContexts().isEmpty() || !context->localDeclarations().isEmpty() || !context->localDefinitions().isEmpty() || !context->uses().isEmpty();
+
+ else if (Declaration* dec = dynamic_cast<Declaration*>(base))
+ return dec->definition() || !dec->uses().isEmpty();
+
+ return false;
+}*/
+
+void DUChainModel::branchAdded(DUContextPointer context)
+{
+ DUChainReadLocker readLock(DUChain::lock());
+
+ if (!context)
+ return;
+
+ if (!m_chain || !m_chain->parentContextOf(context.data()))
+ return;
+
+ DUChainBasePointer* parent = pointerForObject(context->parentContext());
+
+ if (!parent || !m_objectLists.contains(parent) || !m_modelRow.contains(parent))
+ // No entry for parent, ok - it will be created if the view interrogates for it
+ return;
+
+ QList<DUChainBasePointer*>* list = childItems(parent);
+
+ DUChainBasePointer* contextPointer = createPointerForObject(context.data());
+
+ int index = findInsertIndex(*list, context.data());
+
+ if (list->at(index) == contextPointer)
+ // Already added...
+ return;
+
+ beginInsertRows(createIndex(m_modelRow[parent], 0, parent), index, index);
+ list->insert(index, contextPointer);
+ endInsertRows();
+
+ // Don't worry about children, they will be queried for if the view needs it
+}
+
+/*switch (relationship) {
+ case DUChainObserver::ChildContexts:
+ switch (change) {
+ case DUChainObserver::Deletion:
+ case DUChainObserver::Removal: {
+ if (m_objectLists.contains(context)) {
+ m_objectLists.remove(context);
+ m_knownObjects.remove(ro->data());
+ delete ro;
+ }
+ // fallthrough
+ }
+ if( *context == m_chain ) {
+ //Top-context was deleted
+ setTopContext(TopDUContextPointer());
+ return;
+ }
+
+
+ case DUChainObserver::Change: {
+ int index = list->indexOf(ro);
+ Q_ASSERT(index != -1);
+ beginRemoveRows(createIndex(m_modelRow[context], 0, context), index, index);
+ list->removeAt(index);
+ endRemoveRows();
+ if (change == DUChainObserver::Removal || change == DUChainObserver::Deletion)
+ break;
+ // else fallthrough
+ }
+*/
+
+KDevelop::DUChainBasePointer* DUChainModel::pointerForObject(KDevelop::DUChainBase* object) const
+{
+ if (m_knownObjects.contains(object))
+ return m_knownObjects[object];
+
+ return 0L;
+}
+
+KDevelop::DUChainBasePointer* DUChainModel::createPointerForObject(KDevelop::DUChainBase* object) const
+{
+ KDevelop::DUChainBasePointer* ret = 0L;
+
+ if (!m_knownObjects.contains(object)) {
+ ret = new KDevelop::DUChainBasePointer(object->weakPointer());
+ m_knownObjects.insert(object, ret);
+
+ } else {
+ ret = m_knownObjects[object];
+ }
+
+ return ret;
+}
+
+QModelIndex DUChainModel::createParentIndex(DUChainBasePointer* type) const
+{
+ return createIndex(m_modelRow[type], 0, type);
+}
+
+int DUChainModel::findInsertIndex(QList<DUChainBasePointer*>& list, DUChainBase* object) const
+{
+ for (int i = 0; i < list.count(); ++i)
+ if (DUChainBase* at = list.at(i)->data())
+ if (at->range().textRange().start() > object->range().textRange().start())
+ return i;
+
+ return list.count();
+}
+
+void DUChainModel::doubleClicked ( const QModelIndex & index ) {
+ DUChainReadLocker readLock(DUChain::lock());
+ if( index.isValid() ) {
+ DUChainBase* base = objectForIndex(index)->data();
+ DUContext* ctx = dynamic_cast<DUContext*>(base);
+ if( base && !ctx && dynamic_cast<Declaration*>(base) )
+ ctx = static_cast<Declaration*>(base)->internalContext();
+
+ if(ctx) {
+ KTemporaryFile tempFile;
+
+ {
+ QString suffix = (dynamic_cast<TopDUContext*>(ctx) ?
+ static_cast<TopDUContext*>(ctx)->url().str()
+ : ctx->localScopeIdentifier().toString());
+ suffix = suffix.replace('/', '_');
+ suffix = suffix.replace(':', '.');
+ suffix = suffix.replace(' ', '_');
+ suffix += ".temp.dot";
+ tempFile.setSuffix( suffix );
+
+ if( !tempFile.open() ) {
+ readLock.unlock();
+ KMessageBox::error(0, i18n("Cannot create temporary file \"%1\" with suffix \"%2\"", tempFile.fileName(), suffix));
+ return;
+ }
+ DumpDotGraph dump;
+ tempFile.write( dump.dotGraph( ctx ).toLocal8Bit() ); //Shorten if it is a top-context, because it would become too much output
+ }
+
+ tempFile.setAutoRemove(false);
+ QString fileName = tempFile.fileName();
+ tempFile.close();
+ kDebug(9500) << "Wrote dot-graph of context " << ctx << " into " << fileName;
+ KProcess proc; ///@todo this is a simple hack. Maybe do it with mime-types etc.
+ proc << "kgraphviewer" << fileName;
+ if( !proc.startDetached() ) {
+ KProcess proc2;
+ proc2 << "dotty" << fileName;
+ if( !proc2.startDetached() ) {
+ readLock.unlock();
+ KMessageBox::error(0, i18n("Could not open %1 with kgraphviewer or dotty.", fileName));
+ }
+ }
+
+ }
+ }
+}
+
+#include "duchainmodel.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,35 @@
+project(duchainviewer)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${duchainviewer_SOURCE_DIR}/cmake)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9514 )
+
+
+########### next target ###############
+
+set(kdevduchainview_PART_SRCS
+ duchainmodel.cpp
+ duchainviewplugin.cpp
+ duchaintree.cpp
+)
+
+kde4_add_plugin(kdevduchainview ${kdevduchainview_PART_SRCS})
+target_link_libraries(kdevduchainview ${KDEVPLATFORM_LANGUAGE_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS})
+
+install(TARGETS kdevduchainview DESTINATION ${PLUGIN_INSTALL_DIR})
+
+
+########### install files ###############
+
+install(FILES kdevduchainview.desktop DESTINATION ${SERVICES_INSTALL_DIR})
+install(FILES kdevduchainview.rc DESTINATION ${DATA_INSTALL_DIR}/kdevduchainview)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevduchainviewer.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp (revision 1522570)
@@ -0,0 +1,93 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright 2006 Adam Treat <treat@kde.org>
+ * Copyright 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "duchainviewplugin.h"
+#include "duchainmodel.h"
+#include "duchaintree.h"
+
+#include <klocale.h>
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+#include <kaboutdata.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+#include <interfaces/idocumentcontroller.h>
+
+K_PLUGIN_FACTORY(KDevDUChainViewFactory, registerPlugin<DUChainViewPlugin>(); )
+K_EXPORT_PLUGIN(KDevDUChainViewFactory(KAboutData("kdevduchainview","kdevduchainviewer",ki18n("DUChain View"), "0.1", ki18n("A simple tool to view the raw DUChain"), KAboutData::License_GPL)))
+
+class DUChainViewFactory: public KDevelop::IToolViewFactory
+{
+public:
+ DUChainViewFactory(DUChainViewPlugin *plugin): mplugin(plugin) {}
+
+ virtual QWidget* create(QWidget *parent = 0)
+ {
+ QTreeView* view = new DUChainTree(parent, mplugin);
+ QObject::connect(view, SIGNAL(doubleClicked(const QModelIndex &)), mplugin->model(), SLOT(doubleClicked(const QModelIndex &)));
+ return view;
+ }
+
+ virtual Qt::DockWidgetArea defaultPosition()
+ {
+ return Qt::RightDockWidgetArea;
+ }
+
+ virtual QString id() const
+ {
+ return "org.kdevelop.DUChainView";
+ }
+
+private:
+ DUChainViewPlugin *mplugin;
+};
+
+DUChainViewPlugin::DUChainViewPlugin(QObject *parent,
+ const QVariantList&)
+ : KDevelop::IPlugin(KDevDUChainViewFactory::componentData(), parent)
+ , m_model(new DUChainModel(this))
+ , m_factory(new DUChainViewFactory(this))
+{
+ core()->uiController()->addToolView(i18n("DUChain Viewer"), m_factory);
+ setXMLFile( "kdevduchainview.rc" );
+
+ connect(core()->documentController(), SIGNAL(documentActivated(KDevelop::IDocument*)), m_model, SLOT(documentActivated(KDevelop::IDocument*)));
+}
+
+DUChainViewPlugin::~DUChainViewPlugin()
+{
+}
+
+void DUChainViewPlugin::unload()
+{
+ core()->uiController()->removeToolView(m_factory);
+}
+
+DUChainModel* DUChainViewPlugin::model() const
+{
+ return m_model;
+}
+
+#include "duchainviewplugin.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.h (revision 1522570)
@@ -0,0 +1,56 @@
+/*
+ * KDevelop DUChain viewer
+ *
+ * Copyright (c) 2007 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef DUCHAINTREE_H
+#define DUCHAINTREE_H
+
+#include <QtGui/QTreeView>
+
+#include <language/duchain/duchainbase.h>
+#include <language/duchain/duchainobserver.h>
+
+class DUChainViewPlugin;
+
+namespace KDevelop {
+ class TopDUContext;
+ class IDocument;
+}
+
+class DUChainTree : public QTreeView
+{
+ Q_OBJECT
+
+public:
+ DUChainTree(QWidget* parent, DUChainViewPlugin* plugin);
+ virtual ~DUChainTree();
+
+ class DUChainModel* model();
+
+private Q_SLOTS:
+ void contextActivated(const QModelIndex& index);
+
+private:
+ DUChainViewPlugin* mplugin;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width: 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h (revision 1522570)
@@ -0,0 +1,140 @@
+/*
+ * KDevelop DUChain viewer
+ *
+ * Copyright 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef DUCHAINMODEL_H
+#define DUCHAINMODEL_H
+
+#include <QtCore/QAbstractItemModel>
+#include <QtCore/QHash>
+
+#include <ktexteditor/cursor.h>
+#include <kurl.h>
+
+#include <language/duchain/duchainbase.h>
+#include <language/duchain/duchainobserver.h>
+
+class DUChainViewPlugin;
+
+namespace KDevelop {
+ class TopDUContext;
+ class IDocument;
+ class ParseJob;
+}
+
+class ProxyObject : public KDevelop::DUChainBase
+{
+public:
+ ProxyObject(KDevelop::DUChainBase* _parent, KDevelop::DUChainBase* _object);
+
+ virtual void preDelete() {};
+
+ KDevelop::DUChainBase* parent;
+ KDevelop::DUChainBase* object;
+};
+
+class DUChainModel : public QAbstractItemModel
+{
+ Q_OBJECT
+
+public:
+ DUChainModel(DUChainViewPlugin* parent);
+ virtual ~DUChainModel();
+
+ void setTopContext(KDevelop::TopDUContextPointer context);
+
+ KDevelop::DUChainBasePointer* objectForIndex(const QModelIndex& index) const;
+
+public Q_SLOTS:
+ void documentActivated(KDevelop::IDocument* document);
+ void parseJobFinished(KDevelop::ParseJob* job);
+
+public:
+ virtual int columnCount(const QModelIndex & parent = QModelIndex()) const;
+ virtual QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
+ virtual QModelIndex parent(const QModelIndex & index) const;
+ virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
+ virtual int rowCount(const QModelIndex & parent = QModelIndex()) const;
+ //virtual bool hasChildren(const QModelIndex & parent = QModelIndex()) const;
+
+private slots:
+ void doubleClicked ( const QModelIndex & index );
+
+ // Watch definition use chain changes
+ void branchAdded(KDevelop::DUContextPointer context);
+
+private:
+ DUChainViewPlugin* plugin() const;
+
+ int findInsertIndex(QList<KDevelop::DUChainBasePointer*>& list, KDevelop::DUChainBase* object) const;
+
+ QModelIndex createParentIndex(KDevelop::DUChainBasePointer* type) const;
+
+ template <typename T>
+ KTextEditor::Cursor nextItem(QVectorIterator<T*>& it, bool initialise) const
+ {
+ if (initialise)
+ if (it.hasNext())
+ it.next();
+
+ if (it.hasPrevious())
+ return it.peekPrevious()->range().textRange().start();
+
+ return KTextEditor::Cursor::invalid();
+ }
+
+ template <typename T>
+ KDevelop::DUChainBase* item(QVectorIterator<T*>& it) const
+ {
+ Q_ASSERT(it.hasPrevious());
+ KDevelop::DUChainBase* item = it.peekPrevious();
+ if (it.hasNext())
+ it.next();
+ else
+ // Make hasPrevious return false
+ it.toFront();
+
+ return item;
+ }
+
+ template <typename T>
+ KDevelop::DUChainBase* proxyItem(KDevelop::DUChainBase* parent, QVectorIterator<T*>& it) const
+ {
+ KDevelop::DUChainBase* target = item(it);
+ KDevelop::DUChainBase* proxy = new ProxyObject(parent, target);
+ m_proxyObjects.insert(target, createPointerForObject(proxy));
+ return proxy;
+ }
+
+ QList<KDevelop::DUChainBasePointer*>* childItems(KDevelop::DUChainBasePointer* parent) const;
+ KDevelop::DUChainBasePointer* pointerForObject(KDevelop::DUChainBase* object) const;
+ KDevelop::DUChainBasePointer* createPointerForObject(KDevelop::DUChainBase* object) const;
+
+ KDevelop::TopDUContextPointer m_chain;
+ KUrl m_document;
+ mutable QHash<KDevelop::DUChainBase*, KDevelop::DUChainBasePointer*> m_knownObjects;
+ mutable QHash<KDevelop::DUChainBasePointer*, QList<KDevelop::DUChainBasePointer*>* > m_objectLists;
+ mutable QHash<KDevelop::DUChainBasePointer*, int > m_modelRow;
+ mutable QHash<KDevelop::DUChainBase*, KDevelop::DUChainBasePointer*> m_proxyObjects;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h (revision 1522570)
@@ -0,0 +1,51 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright 2006 Adam Treat <treat@kde.org>
+ * Copyright 2006 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef DUCHAINVIEW_PART_H
+#define DUCHAINVIEW_PART_H
+
+#include <interfaces/iplugin.h>
+#include <QtCore/QVariant>
+
+class DUChainModel;
+
+class DUChainViewPlugin : public KDevelop::IPlugin
+{
+ Q_OBJECT
+
+public:
+ DUChainViewPlugin(QObject *parent, const QVariantList & = QVariantList() );
+ virtual ~DUChainViewPlugin();
+
+ // KDevelop::Plugin methods
+ virtual void unload();
+
+ DUChainModel* model() const;
+
+private:
+ DUChainModel* m_model;
+ class DUChainViewFactory* m_factory;
+};
+
+#endif // DUCHAINVIEW_PART_H
+
+// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp (revision 1522570)
@@ -0,0 +1,73 @@
+/*
+ * KDevelop DUChain viewer
+ *
+ * Copyright (c) 2007 Hamish Rodda <rodda@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "duchaintree.h"
+
+#include <QHeaderView>
+
+#include <klocale.h>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+#include <language/duchain/duchainbase.h>
+
+#include "duchainmodel.h"
+#include "duchainviewplugin.h"
+
+using namespace KDevelop;
+
+DUChainTree::DUChainTree(QWidget* parent, DUChainViewPlugin* plugin)
+ : QTreeView(parent)
+ , mplugin(plugin)
+{
+ setObjectName("DUChain Viewer Tree");
+ setWindowTitle(i18n("Definition-Use Chain"));
+ setModel(mplugin->model());
+ header()->hide();
+
+ connect(this, SIGNAL(activated(const QModelIndex&)), SLOT(contextActivated(const QModelIndex&)));
+}
+
+DUChainTree::~DUChainTree()
+{
+}
+
+DUChainModel* DUChainTree::model()
+{
+ return mplugin->model();
+}
+
+void DUChainTree::contextActivated(const QModelIndex& index)
+{
+ DUChainBasePointer* base = model()->objectForIndex(index);
+ if (base && base->data()) {
+ IDocument* doc = mplugin->core()->documentController()->activeDocument();
+ doc->textDocument()->activeView()->setSelection((*base)->range().textRange());
+ }
+}
+
+// kate: space-indent on; indent-width 2; tab-width: 4; replace-tabs on; auto-insert-doxygen on
+
+#include "duchaintree.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevDUChainView" version="8">
+</kpartgui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop (revision 1522570)
@@ -0,0 +1,77 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=This plugin provides a frontend for Erlang debugger
+Comment[bs]=Ovaj dodatak daje sučelje za Erlang debugger.
+Comment[ca]=Aquest connector proveeix d'un frontal pel depurador Erlang
+Comment[ca@valencia]=Aquest connector proveeix d'un frontal pel depurador Erlang
+Comment[de]=Dieses Modul stellt eine Oberfläche für den Erland-Debugger zur Verfügung
+Comment[en_GB]=This plugin provides a frontend for Erlang debugger
+Comment[es]=Este complemento proporciona una interfaz para el depurador de Erlang
+Comment[et]=Erlangi siluri kasutajaliidese plugin
+Comment[fr]=Ce module externe fournit une interface pour Erlang
+Comment[gl]=Este complemento fornece unha interface para o depurador de Erlang.
+Comment[it]=Questa estensione fornisce un'interfaccia per il debugger Erlang
+Comment[nl]=Deze plugin geeft een frontend voor de Erlang debugger
+Comment[pl]=Wtyczka ta dostarcza interfejs dla debugowania Erlang
+Comment[pt]=Este 'plugin' oferece uma interface para o depurador de Erlang
+Comment[pt_BR]=Este plugin fornece uma interface para o depurador Erlang
+Comment[sv]=Insticksprogrammet tillhandahåller ett gränssnitt för Erlang avlusare
+Comment[uk]=Цей додаток є оболонкою до зневадника Erlang
+Comment[x-test]=xxThis plugin provides a frontend for Erlang debuggerxx
+Name=Erlang Debugger Support
+Name[bs]=Podrška Erlang Debugger-u
+Name[ca]=Implementació del depurador Erlang
+Name[ca@valencia]=Implementació del depurador Erlang
+Name[de]=Sprachunterstützung für Erlang-Debugger
+Name[en_GB]=Erlang Debugger Support
+Name[es]=Implementación del depurador Erlang
+Name[et]=Erlangi siluri toetus
+Name[fr]=Prise en charge du débogueur Erlang
+Name[gl]=Compatibilidade co depurador de Erlang
+Name[it]=Supporto per debugger Erlang
+Name[nl]=Ondersteuning voor Erlang debugger
+Name[pl]=Obsługa debuggera Erlang
+Name[pt]=Suporte para o Depurador de Erlang
+Name[pt_BR]=Suporte para a depurador Erlang
+Name[sv]=Stöd för Erlang avlusare
+Name[uk]=Підтримка зневадника мови Erlang
+Name[x-test]=xxErlang Debugger Supportxx
+GenericName=Debugger Frontend
+GenericName[bs]=Korisničko okruženje za ispravljač grešaka
+GenericName[ca]=Frontal del depurador
+GenericName[ca@valencia]=Frontal del depurador
+GenericName[cs]=Rozhraní pro ladicí nástroj
+GenericName[de]=Oberfläche für Debugger
+GenericName[en_GB]=Debugger Frontend
+GenericName[es]=Interfaz del depurador
+GenericName[et]=Siluri kasutajaliides
+GenericName[fr]=Interface du débogueur
+GenericName[ga]=Comhéadan Dífhabhtóra
+GenericName[gl]=Interface para o depurador
+GenericName[hu]=Hibakereső előtétprogram
+GenericName[it]=Interfaccia debugger
+GenericName[ja]=デバッガのフロントエンド
+GenericName[nds]=Fehlersöker-Böversiet
+GenericName[nl]=Frontend voor debugger
+GenericName[pa]=ਡੀਬੱਗਰ ਫਰੰਟਐਂਡ
+GenericName[pl]=Interfejs do debuggera
+GenericName[pt]=Interface do Depurador
+GenericName[pt_BR]=Interface do depurador
+GenericName[sk]=Rozhranie debuggera
+GenericName[sv]=Avlusargränssnitt
+GenericName[tr]=Hata Ayıklayıcı Önucu
+GenericName[ug]=سازلىغۇچ ئالدى ئۇچى
+GenericName[uk]=Клієнтська програма зневадника
+GenericName[x-test]=xxDebugger Frontendxx
+
+Icon=debugger
+X-KDE-Library=kdeverldebug
+X-KDevelop-Category=Global
+X-KDevelop-Version=10
+X-KDE-PluginInfo-Name=kdeverldebug
+X-KDE-PluginInfo-License=GPL
+ServiceTypes=KDevelop/Plugin
+X-KDevelop-Interfaces=org.kdevelop.IRunProvider
+X-KDevelop-IRequired=org.kdevelop.IExecutePlugin
+X-KDevelop-Mode=GUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_config.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_config.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_config.ui (revision 1522570)
@@ -0,0 +1,174 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ErlangDebugConfigDialog</class>
+ <widget class="QWidget" name="ErlangDebugConfigDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>438</width>
+ <height>496</height>
+ </rect>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>200</width>
+ <height>200</height>
+ </size>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <property name="sizeConstraint">
+ <enum>QLayout::SetDefaultConstraint</enum>
+ </property>
+ <property name="fieldGrowthPolicy">
+ <enum>QFormLayout::ExpandingFieldsGrow</enum>
+ </property>
+ <property name="rowWrapPolicy">
+ <enum>QFormLayout::WrapLongRows</enum>
+ </property>
+ <item row="1" column="0" colspan="2">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>Interpretable Modules:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" colspan="2">
+ <widget class="QTreeWidget" name="interpretableTreeWidget">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="acceptDrops">
+ <bool>false</bool>
+ </property>
+ <property name="alternatingRowColors">
+ <bool>false</bool>
+ </property>
+ <attribute name="headerVisible">
+ <bool>true</bool>
+ </attribute>
+ <attribute name="headerVisible">
+ <bool>true</bool>
+ </attribute>
+ <column>
+ <property name="text">
+ <string>Module</string>
+ </property>
+ </column>
+ </widget>
+ </item>
+ <item row="3" column="0" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <property name="sizeConstraint">
+ <enum>QLayout::SetMaximumSize</enum>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_3">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="layoutDirection">
+ <enum>Qt::LeftToRight</enum>
+ </property>
+ <property name="text">
+ <string>Library include directories:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Expanding</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>100</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QToolButton" name="toolButton_2">
+ <property name="text">
+ <string>...</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="4" column="0" colspan="2">
+ <widget class="QListWidget" name="includeLibraryListWidget"/>
+ </item>
+ <item row="0" column="1">
+ <widget class="QGroupBox" name="groupBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="title">
+ <string>Entry Point</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout_3">
+ <item row="0" column="0" colspan="2">
+ <layout class="QFormLayout" name="formLayout_2">
+ <item row="0" column="0">
+ <widget class="QLabel" name="moduleNameLabel">
+ <property name="text">
+ <string>Module name:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="moduleNameLineEdit"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="moduleFunctionLabel">
+ <property name="text">
+ <string>Module function:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="moduleFunctionLineEdit"/>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="functionArgumentsLabel">
+ <property name="text">
+ <string>Function Arguments</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="functionArgumentsLineEdit"/>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl (revision 1522570)
@@ -0,0 +1,170 @@
+-module(debug_interpreter).
+
+-export([start/0, start_loop/0]).
+
+-define(DEBUG(Text,Parameters), io:format( [0] ++ "---" ++ Text ++ [0], Parameters )).
+-define(OUTPUT(Text, Parameters), io:format([0] ++ Text ++ [0] , Parameters )).
+
+
+start() ->
+ application:start(sasl),
+ ?DEBUG("starting debug system on: ~w",[self()]),
+ ?DEBUG("erlang:register: [~w]", [erlang:register(internal_meta, spawn(fun() -> start_loop() end))]),
+ ?DEBUG("erlang:register: [~w]", [erlang:register(input_reader_proc, spawn(fun() -> input_reader_sync() end))]).
+
+input_reader_sync() ->
+ receive
+ started ->
+ input_reader()
+ end.
+
+input_reader() ->
+ case io:read("") of
+ eof ->
+ ok;
+ { error, Reason } ->
+ ?DEBUG("ERROR INPUT ~w", [Reason]);
+ { ok, Term } ->
+ ?DEBUG("Readed term ~w",[Term]),
+ internal_meta ! { user_input, Term }
+ end,
+ input_reader().
+
+start_loop() ->
+ ?DEBUG("Starting debug loop", []),
+ ?DEBUG("Starting int: [~w]", [int:start()]),
+ ?DEBUG("Subscribe: ~w", [int:subscribe()]),
+ %?DEBUG("Stack trace: ~w", [int:stack_trace(all)]),
+ input_reader_proc ! started,
+ loop().
+
+process_user_input({ interpret , Module }) ->
+ ?DEBUG("Trying to interpret module [~w]", [Module]),
+ case int:i(Module) of
+ { module, M } ->
+ ?OUTPUT("interpret|ok|~w", [M]);
+ error ->
+ ?OUTPUT("interpret|error|~w }", [Module])
+ end;
+
+process_user_input({launch, { Module, Function, Parameters }}) ->
+ ?DEBUG("Trying launch function [~w] from module [~w] and parameters ~w", [Module, Function, Parameters] ),
+ ?DEBUG("spawn result: [~w]", [spawn(Module, Function, Parameters)]);
+
+process_user_input({ action, Action, Pid }) ->
+ PID = list_to_pid(Pid),
+ ?DEBUG("Sending action [~w] to pid [~w]:[~w]", [Action, PID, int:meta(PID, Action)]);
+
+process_user_input({ var_list , Meta }) ->
+ ?DEBUG("Trying to convert to meta pid: [~s]", [Meta]),
+ META = list_to_pid(Meta),
+ ?DEBUG("Trying to get variable list for MetaProcess [~w]", [META]),
+ VariablesList = int:meta(META, bindings, nostack),
+ ?DEBUG("Variable list is : ~w",[VariablesList]),
+ ParsedData = start_parsing_variables(VariablesList),
+ ?DEBUG("Parsed data is : ~s", [ParsedData]),
+ ?OUTPUT("variables_list|~s", [ParsedData]);
+
+process_user_input({ break_remove , Module , Line }) ->
+ ?DEBUG("Trying remove a breakpoint for module [~w] on line [~p] ", [Module, Line] ),
+ ?OUTPUT("break_remove|~w|~w|~p", [int:delete_break(Module, Line), Module, Line]);
+
+process_user_input({ break , Module , Line }) ->
+ ?DEBUG("Trying create a breakpoint for module [~s] on line [~p] ", [Module, Line] ),
+ case int:break(Module, Line) of
+ ok ->
+ ?OUTPUT("break_set|ok|~w", [Module]);
+ { error, break_exists } ->
+ ?OUTPUT("break_set|ok|~w", [Module])
+ end.
+
+%%% Message handling
+
+handle({ user_input , UserInput }) ->
+ process_user_input(UserInput);
+
+handle({int, {new_process, { Process , FunctionInfo , Status , Info} } }) ->
+ ?DEBUG("Trapped a new process info, trying to attach it to debugger... [~w] [~w] [~w]", [FunctionInfo, Status, Info]),
+ case int:attached(Process) of
+ { ok, Meta } ->
+ ?DEBUG("Got MetaProcess [~w] for process [~w]", [Meta, Process]),
+ ?OUTPUT("meta|~w|~w", [ Process, Meta ] );
+ error ->
+ ignore
+ end;
+
+handle({ int, { new_status, Process ,break, { Module, Line } } }) ->
+ ?DEBUG("Trapped a break on module [~w] and line [~w]", [Module, Line ]),
+ {ok, Meta} = dbg_iserver:call({get_meta, Process}),
+% TODO: check problems with variable controller
+% VariablesList = int:meta(Meta, bindings, nostack),
+% ?DEBUG("Variable list is : ~w", [VariablesList]),
+% ParsedData = start_parsing(VariablesList),
+% ?DEBUG("Parsed data is : ~s", [ParsedData]),
+% ?OUTPUT("variables_list|~s", [ParsedData]),
+ Backtrace = int:meta(Meta, backtrace, 40),
+ ?DEBUG("backtrace message is: [~w]", [Backtrace]),
+ ?OUTPUT("stack_trace|~w|~s", [ Process, start_parsing_stack(Meta, Backtrace)]),
+ ?OUTPUT("break|~s|~w|~w",[int:file(Module), Line, Process]);
+
+handle({ int, { new_status, Process , exit, Info } }) ->
+ ?DEBUG("Trapped a process exit for process [~w] and info [~w]", [ Process, Info]),
+ ?OUTPUT("process_status_update|~w|~w|~w",[Process, exit, Info]);
+
+handle({ int, { new_status, _ , _ , _ } }) -> ok;
+
+handle(Unknown) -> ok.
+
+%%%%%%%%%%%%%%%%%%%%%%%% STACK TRACE PARSING %%%%%%%%%%%%%%%%%%%%%%
+
+start_parsing_stack(Meta, [ { SP , { Module, Function, _ } } | T ]) ->
+ Item = int:meta(Meta, stack_frame, { up , SP + 1 }),
+ ?DEBUG("Item is: [~w]", [Item]),
+ { _ , { _ , Line } , _ } = Item,
+ Name = case int:file(Module) of
+ { error, _ } -> "";
+ Ok -> Ok
+ end,
+ io_lib:format("~p,~s:~s,~s,~p ", [ SP, Module, Function, Name, Line ]) ++ start_parsing_stack(Meta, T);
+
+start_parsing_stack( _ , [ ]) -> "".
+
+%%%%%%%%%%%%%%%%%%%%%%%% STACK TRACE PARSING END %%%%%%%%%%%%%%%%%%%%%%
+
+%%%%%%%%%%% VARIABLE LIST TO XML CONVERSION %%%%%%%%%%%%%%%%%%
+
+start_parsing_variables(Data) ->
+ io_lib:format("<variables>~s</variables>" , [ parse(Data) ]).
+
+parse([]) -> "";
+
+parse([H|T]) ->
+ parse(H) ++ parse(T);
+
+parse({ VariableName , Variable }) ->
+ io_lib:format("<variable name=\"~s\"><raw_value><![CDATA[~w]]></raw_value>~s</variable>",[erlang:atom_to_list(VariableName), Variable, parse_variable(Variable)]).
+
+parse_variable(RawValue) when is_list(RawValue) ->
+ io_lib:format("<item kind=\"list\"><raw_value><![CDATA[~w]]></raw_value>~s</item>",[RawValue, parse_list_items(RawValue)]);
+
+parse_variable( RawValue ) when is_tuple(RawValue) ->
+ io_lib:format("<item kind=\"tuple\"><raw_value><![CDATA[~w]]></raw_value>~s</item>",[RawValue, parse_list_items(erlang:tuple_to_list(RawValue))]);
+
+parse_variable( Other )->
+ io_lib:format("<value><![CDATA[~w]]></value>", [Other]).
+
+parse_list_items([]) -> "";
+
+parse_list_items([ H | T ]) ->
+ parse_variable(H) ++ parse_list_items(T).
+
+%%%%%%%%%%% END VARIABLE LIST TO XML CONVERSION %%%%%%%%%%%%%%%%%%
+
+%%% End message handling
+
+loop() ->
+ receive
+ Data ->
+ handle(Data),
+ loop()
+ end.
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.h (revision 1522570)
@@ -0,0 +1,123 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef DEBUGSESSION_H
+#define DEBUGSESSION_H
+
+#include <debugger/interfaces/idebugsession.h>
+#include <debugger/interfaces/iframestackmodel.h>
+
+#include <interfaces/ilaunchconfiguration.h>
+
+#include <kconfiggroup.h>
+
+#include <QPointer>
+#include <QQueue>
+
+namespace ErlangDebugPlugin
+{
+class ErlangCommand;
+class ErlangDebugger;
+class ErlangDebugger;
+class ErlangOutput;
+class BreakpointOutput;
+class VariableListOutput;
+class StackTraceOutput;
+
+static QString erlangShellExecPath = "Erlang ERTS Path";
+static QString rebuildDebuggerInterface = "Rebuild erlang debugger interface prior staring";
+static QString interpretedModules = "List of modules to be interpreted";
+static QString projectDir = "Current project directory";
+static QString libraryPaths = "Libraries folder to be added on debug runtime";
+static QString callableFunction = "function to be called when debugging";
+static QString callableModule = "module to be called when debugging";
+static QString callableArguments = "function arguments to be called when debugging";
+
+class DebugCallbackBase
+{
+public:
+ virtual void execute(ErlangOutput&) = 0;
+
+ virtual ~DebugCallbackBase() { }
+};
+
+class DebugSession : public KDevelop::IDebugSession
+{
+ Q_OBJECT
+public:
+ DebugSession();
+ void requestVariables(DebugCallbackBase* callback);
+ void startDebugger(KDevelop::ILaunchConfiguration* cfg);
+ void sendBreakpoint(QString location, int line);
+ void interpretMoule(QString module);
+ void spawn(QString module, QString function, QString arguments);
+ void removeBreakpoint(QString module, int line);
+
+Q_SIGNALS:
+ void breakpointUpdate(BreakpointOutput*);
+ void variableListUpdate(VariableListOutput*);
+ void stackTraceUpdate(StackTraceOutput*);
+ void stdoutReceived(QString data);
+
+public Q_SLOTS:
+ ///called when user selects a different process (not thread) on our stack model
+ virtual void updateCurrentActiveProcess(QString processID);
+
+
+ virtual void stepOut();
+ virtual void stepOverInstruction();
+ virtual void stepInto();
+ virtual void stepIntoInstruction();
+ virtual void stepOver();
+ virtual void jumpToCursor();
+ virtual void runToCursor();
+ virtual void run();
+ virtual void interruptDebugger();
+ virtual void stopDebugger();
+ virtual void restartDebugger();
+ virtual bool restartAvaliable() const;
+ virtual KDevelop::IDebugSession::DebuggerState state() const;
+
+private slots:
+
+ void executeCmd();
+ void handleDebuggerCommand(ErlangOutput* command);
+
+protected:
+ virtual KDevelop::IFrameStackModel* createFrameStackModel();
+
+private:
+ QPointer<ErlangDebugger> m_erlDebugger;
+ QQueue<ErlangCommand*> m_commands;
+
+ ///Stores information about metaprocesses and its relation to
+ ///real processes
+ QMap<QString, QString> m_processToMeta;
+ QMap<qlonglong, DebugCallbackBase* > m_callbacks;
+
+ QList<QString> m_interpretedModules;
+
+ QString m_currentProcess;
+
+ qlonglong m_requestID;
+};
+
+}
+#endif // DEBUGSESSION_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp (revision 1522570)
@@ -0,0 +1,109 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include <QXmlStreamReader>
+
+#include <KDebug>
+
+#include "framestackmodel.h"
+#include "messages.h"
+
+namespace ErlangDebugPlugin {
+
+void FrameStackModel::fetchThreads()
+{
+}
+
+/*
+void FrameStackModel::handleStack(const QDomDocument &xml)
+{
+ Q_ASSERT(xml.documentElement().attribute("command") == "stack_get");
+
+ QList<KDevelop::FrameStackModel::FrameItem> frames;
+ QDomElement el = xml.documentElement().firstChildElement("stack");
+ while (!el.isNull()) {
+ KDevelop::FrameStackModel::FrameItem f;
+ f.nr = el.attribute("level").toInt();
+ f.name = el.attribute("where");
+ f.file = el.attribute("filename");
+ f.line = el.attribute("lineno").toInt() - 1;
+ frames << f;
+ el = el.nextSiblingElement("stack");
+ }
+ setFrames(0, frames);
+ setHasMoreFrames(0, false);
+}*/
+
+void FrameStackModel::fetchFrames(int threadNumber, int from, int to)
+{
+ Q_UNUSED(from); //we fetch always everything
+ Q_UNUSED(to);
+}
+
+void FrameStackModel::handleStackList(StackTraceOutput* output)
+{
+ QList<KDevelop::FrameStackModel::FrameItem> frames;
+
+ foreach(StackInfo item, output->getStackTrace())
+ {
+ KDevelop::FrameStackModel::FrameItem f;
+ f.name = item.function_name;
+ f.line = item.line;
+ f.nr = item.stack_pos;
+ f.file = item.filename;
+
+ frames << f;
+ }
+
+ int threadID;
+ if (m_processToThreadID.contains(output->getProcess()))
+ {
+ threadID = m_processToThreadID[output->getProcess()];
+ }
+ else
+ {
+ threadID = m_processToThreadID[output->getProcess()] = m_threadID++;
+ }
+
+ QList<KDevelop::FrameStackModel::ThreadItem> threads;
+ QMap<QString, int>::iterator it = m_processToThreadID.begin();
+
+ for (; it != m_processToThreadID.end(); ++it)
+ {
+ KDevelop::FrameStackModel::ThreadItem item;
+ item.name = it.key();
+ item.nr = it.value();
+ threads << item;
+ }
+
+ setThreads(threads);
+
+ setFrames(threadID, frames);
+ setHasMoreFrames(threadID, false);
+ setCurrentThread(threadID);
+}
+
+FrameStackModel::FrameStackModel(DebugSession* session) :
+ KDevelop::FrameStackModel(session) , m_threadID(0)
+{
+ connect(session, SIGNAL(stackTraceUpdate(StackTraceOutput*)), this, SLOT(handleStackList(StackTraceOutput*)));
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h (revision 1522570)
@@ -0,0 +1,57 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANG_FRAMESTACKMODEL_H
+#define ERLANG_FRAMESTACKMODEL_H
+
+#include <debugger/framestack/framestackmodel.h>
+
+#include "debugsession.h"
+#include "messages.h"
+
+class QDomDocument;
+namespace ErlangDebugPlugin {
+
+class FrameStackModel : public KDevelop::FrameStackModel
+{
+ Q_OBJECT
+public:
+ FrameStackModel(DebugSession* session) ;
+
+public:
+ DebugSession* session() { return static_cast<DebugSession*>(KDevelop::FrameStackModel::session()); }
+
+
+protected slots:
+ void handleStackList(StackTraceOutput*);
+
+protected: // KDevelop::FrameStackModel overrides
+ virtual void fetchThreads();
+ virtual void fetchFrames(int threadNumber, int from, int to);
+
+ QMap< QString, int > m_processToThreadID;
+ int m_threadID;
+private:
+ //void handleStack(const QDomDocument &xml);
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.cpp (revision 1522570)
@@ -0,0 +1,259 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "messages.h"
+#include "kdebug.h"
+#include <QXmlReader>
+#include <QString>
+
+namespace ErlangDebugPlugin
+{
+
+ErlangOutput::ErlangOutput(const QStringList& rawData, ErlangDebugPlugin::OutputCommandType command)
+ : m_rawData(rawData)
+ , m_command(command)
+{
+}
+
+OutputCommandType ErlangOutput::getCommandType()
+{
+ return m_command;
+}
+
+ErlangOutput::~ErlangOutput()
+{
+}
+
+void BreakpointOutput::parse()
+{
+}
+
+QString BreakpointOutput::getProcess()
+{
+ return m_rawData[3];
+}
+
+int BreakpointOutput::getLine()
+{
+ return m_rawData[2].toInt();
+}
+
+QString BreakpointOutput::getModule()
+{
+ return m_rawData[1];
+}
+
+ErlangCommand::ErlangCommand(QString meta, InterpreterCommand::InterpreterCommand command)
+ : m_meta(meta)
+,m_command(command)
+{
+}
+
+QString MetaProcessOutput::getMeta()
+{
+ return m_rawData[2];
+}
+
+QString MetaProcessOutput::getProcess()
+{
+ return m_rawData[1];
+}
+
+void MetaProcessOutput::parse()
+{
+}
+
+ErlangCommand::~ErlangCommand()
+{
+}
+
+StepCommand::StepCommand(QString meta): ErlangCommand(meta, InterpreterCommand::STEP)
+{
+}
+
+QString StepCommand::getCommand()
+{
+ return QString("{ action, step , \"%1\" }.").arg(m_meta);
+}
+
+ContinueCommand::ContinueCommand(QString meta) :
+ ErlangCommand(meta, InterpreterCommand::CONTINUE)
+{
+}
+
+QString ContinueCommand::getCommand()
+{
+ return QString("{ action, continue , \"%1\" }.").arg(m_meta);
+}
+
+QString ProcessStatusUpdateOutput::getProcess()
+{
+ return m_rawData[1];
+}
+
+QString ProcessStatusUpdateOutput::getProcessAdditionalInfo()
+{
+ return m_rawData[3];
+}
+
+ErlangProcessStatus::status ProcessStatusUpdateOutput::getProcessStatus()
+{
+ if (m_rawData[2] == "running")
+ return ErlangProcessStatus::Running;
+ else if (m_rawData[2] == "exit")
+ return ErlangProcessStatus::Exit;
+ else
+ return ErlangProcessStatus::Idle;
+}
+
+void ProcessStatusUpdateOutput::parse()
+{
+}
+
+QList< StackInfo >& StackTraceOutput::getStackTrace()
+{
+ return m_stackTrace;
+}
+
+void StackTraceOutput::parse()
+{
+ m_process = m_rawData[1];
+
+ QStringList frames = m_rawData[2].trimmed().split(" ");
+
+ foreach(QString frame, frames)
+ {
+ QStringList frame_itens = frame.split(",");
+ StackInfo info;
+
+ info.stack_pos = frame_itens[0].toInt();
+ info.function_name = frame_itens[1];
+ info.filename = frame_itens[2];
+ info.line = frame_itens[3].toInt() - 1;
+
+ m_stackTrace.append(info);
+ }
+}
+
+QString& StackTraceOutput::getProcess()
+{
+ return m_process;
+}
+
+BreakCommand::BreakCommand(QString module, unsigned int line):
+ ErlangCommand("", InterpreterCommand::BREAK)
+ ,m_module(module)
+ ,m_line(line)
+{
+}
+
+NextCommand::NextCommand(QString meta):
+ ErlangCommand(meta, InterpreterCommand::NEXT)
+{
+}
+
+QString NextCommand::getCommand()
+{
+ return QString("{ action, next, \"%1\" }.").arg(m_meta);
+}
+
+QString BreakCommand::getCommand()
+{
+ return QString("{ break, %1, %2 }.").arg(m_module).arg(m_line);
+}
+
+
+QDomDocument& VariableListOutput::getDocument()
+{
+ return m_document;
+}
+
+void VariableListOutput::parse()
+{
+ QString errorMsg;
+ int errorLine;
+ int errorColumn;
+
+ if (!m_document.setContent(m_rawData[1], &errorMsg, &errorLine, &errorColumn))
+ {
+ kError() << "Error parsing variables list on line " << errorLine << " and column " << errorColumn << ": " << errorMsg;
+ }
+
+ //kDebug() << m_document.toString(2);
+}
+
+FinishCommand::FinishCommand(QString meta):
+ ErlangCommand(meta, InterpreterCommand::FINISH)
+{
+}
+
+QString FinishCommand::getCommand()
+{
+ return QString("{ action, finish, \"%1\" }.").arg(m_meta);
+}
+
+QString InterpretModuleCommand::getCommand()
+{
+ return QString("{ interpret, %1 }.").arg(m_module);
+}
+
+InterpretModuleCommand::InterpretModuleCommand(QString moduleName)
+ : ErlangCommand("", InterpreterCommand::INTERPRET)
+ , m_module(moduleName)
+{
+}
+
+QString VariablesInContextCommand::getCommand()
+{
+ return QString("{ var_list, \"%1\" }.").arg(m_meta);
+}
+
+VariablesInContextCommand::VariablesInContextCommand(QString meta)
+ : ErlangCommand("",InterpreterCommand::VARIABLE_LIST) , m_meta(meta)
+{
+}
+
+SpawnFunctionCommand::SpawnFunctionCommand(QString module, QString function, QString parameters)
+ : ErlangCommand("", InterpreterCommand::SPAWN_FUNCTION)
+ , m_module(module)
+ , m_function(function)
+ , m_parameters(parameters)
+{
+}
+
+QString SpawnFunctionCommand::getCommand()
+{
+ return QString("{ launch , { %1 , %2, [ %3 ] } }.").arg(m_module).arg(m_function).arg(m_parameters);
+}
+
+QString RemoveBreakpoint::getCommand()
+{
+ return QString("{ break_remove, %1 , %2 }.").arg(m_module).arg(m_line);
+}
+
+RemoveBreakpoint::RemoveBreakpoint(QString module, unsigned int line)
+: ErlangCommand("", InterpreterCommand::REMOVE_BREAKPOINT),
+ m_module(module),
+ m_line(line)
+{
+}
+
+
+}
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/messages.h (revision 1522570)
@@ -0,0 +1,256 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGCOMMAND_H
+#define ERLANGCOMMAND_H
+
+#include <QString>
+#include <QStringList>
+#include <QDomDocument>
+
+namespace ErlangDebugPlugin
+{
+
+namespace InterpreterCommand
+{
+enum InterpreterCommand
+{
+ BREAK,
+ CONDITIONAL_BREAK,
+ CONTINUE,
+ STEP,
+ NEXT,
+ FINISH,
+ INTERPRET,
+ VARIABLE_LIST,
+ SPAWN_FUNCTION,
+ REMOVE_BREAKPOINT
+};
+
+}
+
+enum OutputCommandType
+{
+ VariableListOutputType,
+ BreakpointOutputType,
+ MetaOutputType,
+ ProcessStatusUpdateType,
+ StackTraceOutputType
+};
+
+namespace ErlangProcessStatus
+{
+enum status
+{
+ Running,
+ Idle,
+ Exit
+};
+
+}
+
+class ErlangOutput
+{
+public:
+ ErlangOutput(const QStringList& rawData, OutputCommandType command);
+ virtual void parse() = 0;
+
+ OutputCommandType getCommandType();
+
+ virtual ~ErlangOutput();
+protected:
+ QStringList m_rawData;
+ OutputCommandType m_command;
+};
+
+class VariableListOutput : public ErlangOutput
+{
+ public:
+ VariableListOutput(const QStringList& rawData)
+ : ErlangOutput(rawData, VariableListOutputType)
+ {
+ }
+ void parse();
+
+ QDomDocument& getDocument();
+
+ protected:
+ QDomDocument m_document;
+};
+
+struct StackInfo
+{
+ QString function_name;
+ QString filename;
+ int line;
+ int stack_pos;
+};
+
+class StackTraceOutput : public ErlangOutput
+{
+ public:
+ StackTraceOutput(const QStringList& rawData)
+ : ErlangOutput(rawData, StackTraceOutputType)
+ {
+ }
+ void parse();
+
+ QList<StackInfo>& getStackTrace();
+ QString& getProcess();
+ protected:
+ QString m_process;
+ QList<StackInfo> m_stackTrace;
+};
+
+class MetaProcessOutput : public ErlangOutput
+{
+ public:
+ MetaProcessOutput(const QStringList& rawData)
+ : ErlangOutput(rawData, MetaOutputType)
+ {
+ }
+
+ void parse();
+ QString getProcess();
+ QString getMeta();
+};
+
+class BreakpointOutput : public ErlangOutput
+{
+public:
+ BreakpointOutput(const QStringList& rawData)
+ : ErlangOutput(rawData, BreakpointOutputType)
+ {
+ }
+
+ void parse();
+ QString getModule();
+ int getLine();
+ QString getProcess();
+};
+
+class ProcessStatusUpdateOutput : public ErlangOutput
+{
+public:
+ ProcessStatusUpdateOutput(const QStringList& rawData)
+ : ErlangOutput(rawData, ProcessStatusUpdateType)
+ {
+ }
+
+ void parse();
+ QString getProcess();
+ ErlangProcessStatus::status getProcessStatus();
+ QString getProcessAdditionalInfo();
+};
+
+class ErlangCommand
+{
+public:
+ ErlangCommand(QString meta, InterpreterCommand::InterpreterCommand command);
+ virtual QString getCommand() = 0;
+ virtual ~ErlangCommand();
+protected:
+ QString m_meta;
+ InterpreterCommand::InterpreterCommand m_command;
+};
+
+class StepCommand : public ErlangCommand
+{
+public:
+ StepCommand(QString meta);
+
+ virtual QString getCommand();
+};
+
+class ContinueCommand : public ErlangCommand
+{
+public:
+ ContinueCommand(QString meta);
+ virtual QString getCommand();
+};
+
+class NextCommand : public ErlangCommand
+{
+public:
+ NextCommand (QString meta);
+ virtual QString getCommand();
+};
+
+class FinishCommand : public ErlangCommand
+{
+public:
+ FinishCommand (QString meta);
+ virtual QString getCommand();
+};
+
+class InterpretModuleCommand : public ErlangCommand
+{
+public:
+ InterpretModuleCommand (QString moduleName);
+ virtual QString getCommand();
+protected:
+ QString m_module;
+};
+
+
+class SpawnFunctionCommand : public ErlangCommand
+{
+public:
+ SpawnFunctionCommand(QString module, QString function, QString parameters);
+ virtual QString getCommand();
+protected:
+ QString m_function;
+ QString m_module;
+ QString m_parameters;
+};
+
+class VariablesInContextCommand : public ErlangCommand
+{
+public:
+ VariablesInContextCommand (QString meta);
+ virtual QString getCommand();
+
+protected:
+ QString m_meta;
+};
+
+class RemoveBreakpoint : public ErlangCommand
+{
+public:
+ RemoveBreakpoint(QString module, unsigned int line);
+ virtual QString getCommand();
+protected:
+ unsigned int m_line;
+ QString m_module;
+};
+
+class BreakCommand : public ErlangCommand
+{
+public:
+ BreakCommand(QString module, unsigned int line);
+ virtual QString getCommand();
+protected:
+ QString m_module;
+ unsigned int m_line;
+};
+
+}
+
+#endif // ERLANGCOMMAND_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.cpp (revision 1522570)
@@ -0,0 +1,231 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "debugger.h"
+
+#include "debugsession.h"
+#include "kdebug.h"
+#include <kstandarddirs.h>
+
+namespace ErlangDebugPlugin
+{
+
+void ErlangDebugger::start(QString runDir, const KConfigGroup& config)
+{
+ KUrl erlangdebuggerUrl = config.readEntry(ErlangDebugPlugin::erlangShellExecPath, KUrl());
+ if (erlangdebuggerUrl.isEmpty()) {
+ m_erlShellBinary = "/usr/bin/erl";
+ } else {
+ // FIXME: verify its' a local path.
+ m_erlShellBinary = erlangdebuggerUrl.toLocalFile(KUrl::RemoveTrailingSlash);
+ }
+
+ m_erlShellProcess = new KProcess(this);
+ m_erlShellProcess->setWorkingDirectory(runDir);
+
+ m_erlShellProcess->setOutputChannelMode( KProcess::SeparateChannels );
+ connect(m_erlShellProcess, SIGNAL(readyReadStandardOutput()),
+ SLOT(readyReadStandardOutput()));
+
+ connect(m_erlShellProcess, SIGNAL(readyReadStandardError()),
+ SLOT(readyReadStandardError()));
+
+ connect(m_erlShellProcess,
+ SIGNAL(finished(int, QProcess::ExitStatus)),
+ SLOT(processFinished(int, QProcess::ExitStatus)));
+
+ connect(m_erlShellProcess, SIGNAL(error(QProcess::ProcessError)),
+ SLOT(processErrored(QProcess::ProcessError)));
+
+ QString debuggerInterpreterBeamPath = KStandardDirs::locateLocal("data", "kdeverlangsupport/debug_interpreter.beam");
+ QString debuggerInterpreterFolder = KStandardDirs::locateLocal("data", "kdeverlangsupport/");
+ Q_ASSERT(KStandardDirs::exists(debuggerInterpreterFolder));
+
+ //if we dont have the precompiled beam, invoke erlc to build it
+ if (!KStandardDirs::exists(debuggerInterpreterBeamPath) ||
+ (config.hasKey(rebuildDebuggerInterface) && config.readEntry(rebuildDebuggerInterface, false)))
+ {
+ kDebug() << "Trying to build debugger interpreter source... ";
+
+ QString debuggerInterpreterErlPath = KStandardDirs::locate("data", "kdeverlangsupport/debug_interpreter.erl");
+
+ Q_ASSERT(KStandardDirs::exists(debuggerInterpreterErlPath));
+
+ KProcess erlcProcess;
+ erlcProcess << "/usr/bin/erlc" << "-o" << debuggerInterpreterFolder << debuggerInterpreterErlPath ;
+ erlcProcess.execute();
+ erlcProcess.waitForFinished();
+
+ kDebug() << "process exit code: " << erlcProcess.exitCode();
+
+ kDebug() << "erlc stdout: " << erlcProcess.readAll();
+ kDebug() << "erlc stderr: " << erlcProcess.readAllStandardError();
+ }
+
+
+ //Passing as ERL_FLAGS since somehow the KProcess isn't providing them to the erlang shell
+ QStringList arguments;
+ arguments << "-noshell" << "-eval \"debug_interpreter:start()\"" << "-pa" << debuggerInterpreterFolder;
+
+ QStringList libraryIncludePaths = config.readEntry(ErlangDebugPlugin::libraryPaths, QStringList());
+
+ foreach(QString path, libraryIncludePaths)
+ {
+ arguments << "-pa" << path;
+ }
+
+ kDebug() << "ERL_FLAGS are: " << arguments.join(" ");
+
+ m_erlShellProcess->setEnv("ERL_FLAGS", arguments.join(" "), true);
+
+ m_erlShellProcess->setProgram(m_erlShellBinary);
+ m_erlShellProcess->start();
+
+ kDebug() << "Erlang shell PID is: " << m_erlShellProcess->pid();
+ kDebug() << "STARTING ERLANG SHELL\n";
+}
+
+void ErlangDebugger::processErrored(QProcess::ProcessError )
+{
+ kDebug() << "erlang shell process error: " << m_erlShellProcess->readAllStandardError();
+}
+
+void ErlangDebugger::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
+{
+ kDebug() << "erlang shell process finished: " << ((exitCode == 0) ? m_erlShellProcess->readAllStandardOutput() : m_erlShellProcess->readAllStandardError());
+}
+
+void ErlangDebugger::readyReadStandardError()
+{
+ kDebug() << "erlang shell process error: " << m_erlShellProcess->readAllStandardError();
+}
+
+void ErlangDebugger::readyReadStandardOutput()
+{
+ m_erlShellProcess->setReadChannel(QProcess::StandardOutput);
+ m_buffer += m_erlShellProcess->readAll();
+ int i;
+ for (;;)
+ {
+ i = m_buffer.indexOf('\0');
+ if (i == -1 || i && i > 0)
+ {
+ if (m_buffer.size())
+ {
+ kDebug() << "Received standard output from processes. Signaling:" << m_buffer;
+ if (i > 0)
+ {
+ emit stdoutReceived(m_buffer.left(i).trimmed());
+ m_buffer = m_buffer.mid(i);
+ }
+ else
+ {
+ emit stdoutReceived(QString(m_buffer).trimmed());
+ m_buffer.clear();
+ }
+ }
+
+ if (i == -1)
+ break;
+ }
+ else
+ {
+ if ((i = m_buffer.indexOf('\0', i + 1)) >= 0)
+ {
+ QByteArray reply(m_buffer.left(i));
+ m_buffer = m_buffer.mid(i + 1);
+
+ reply.remove(0,1);
+ reply.remove(i - 1, 1);
+
+ processLine(reply);
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+}
+
+void ErlangDebugger::execute(ErlangCommand* command)
+{
+ QString cmdStr = command->getCommand();
+
+ kDebug() << "Sending command to erlang process: " << cmdStr;
+ m_erlShellProcess->write(cmdStr.toLatin1(), cmdStr.size());
+ m_erlShellProcess->write("\n");
+
+ delete command;
+}
+
+void ErlangDebugger::processLine(QByteArray data)
+{
+ if (data.contains("---"))
+ {
+ kDebug() << "Debug information from erlang debugger process: " << data;
+ }
+ else
+ {
+ kDebug() << "Received command: " << data;
+ QString command(data);
+
+ QStringList items = command.split("|");
+
+ //todo: shared ptrs?
+ ErlangOutput* output = 0;
+
+ if (items[0] == "break")
+ {
+ output = new BreakpointOutput(items);
+ }
+ else if (items[0] == "meta")
+ {
+ output = new MetaProcessOutput(items);
+ }
+ else if (items[0] == "process_status_update")
+ {
+ output = new ProcessStatusUpdateOutput(items);
+ }
+ else if (items[0] == "variables_list")
+ {
+ output = new VariableListOutput(items);
+ }
+ else if (items[0] == "stack_trace")
+ {
+ output = new StackTraceOutput(items);
+ }
+
+ if (output)
+ {
+ output->parse();
+ emit outputCommand(output);
+ }
+
+ delete output;
+ }
+}
+
+void ErlangDebugger::stop()
+{
+ m_erlShellProcess->kill();
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp (revision 1522570)
@@ -0,0 +1,276 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "debugsession.h"
+
+#include "debugger.h"
+#include "messages.h"
+#include "breakpointcontroller.h"
+#include "variablecontroller.h"
+#include "framestackmodel.h"
+
+#include <kdebug.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/iplugincontroller.h>
+#include <execute/iexecuteplugin.h>
+#include <QFileInfo>
+
+namespace ErlangDebugPlugin
+{
+
+KDevelop::IFrameStackModel* DebugSession::createFrameStackModel()
+{
+ return new FrameStackModel(this);
+}
+
+void DebugSession::requestVariables(ErlangDebugPlugin::DebugCallbackBase* callback)
+{
+ m_callbacks.insert(m_requestID++, callback);
+ m_commands.enqueue(new VariablesInContextCommand(m_processToMeta[m_currentProcess]));
+ executeCmd();
+}
+
+void DebugSession::removeBreakpoint(QString module, int line)
+{
+ m_commands.enqueue(new RemoveBreakpoint(module,line));
+ executeCmd();
+}
+
+void DebugSession::interpretMoule(QString module)
+{
+ if (!m_interpretedModules.contains(module))
+ {
+ m_interpretedModules.append(module);
+ m_commands.enqueue(new InterpretModuleCommand(module));
+ executeCmd();
+ }
+}
+
+void DebugSession::spawn(QString module, QString function, QString arguments)
+{
+ m_commands.enqueue(new SpawnFunctionCommand(module,function, arguments));
+ executeCmd();
+}
+
+void DebugSession::startDebugger(KDevelop::ILaunchConfiguration* config)
+{
+ IExecutePlugin* iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
+ Q_ASSERT(iface);
+
+ // Only dummy err here, actual erros have been checked already in the job and we don't get here if there were any
+ QString err;
+ QString executable = iface->executable(config, err).toLocalFile();
+ QString envgrp = iface->environmentGroup(config);
+
+ QStringList arguments = iface->arguments(config, err);
+ // Change the "Working directory" to the correct one
+ QString dir = iface->workingDirectory(config).toLocalFile();
+ if (dir.isEmpty() || !KUrl(dir).isValid())
+ {
+ dir = QFileInfo(executable).absolutePath();
+ }
+
+ kDebug() << "current directory is: " << dir;
+
+ m_erlDebugger = new ErlangDebugger();
+
+ connect(m_erlDebugger, SIGNAL(outputCommand(ErlangOutput*)), this, SLOT(handleDebuggerCommand(ErlangOutput*)));
+ connect(m_erlDebugger, SIGNAL(stdoutReceived(QString)), this, SIGNAL(stdoutReceived(QString)));
+
+ m_erlDebugger->start(dir, config->config());
+
+ stateChanged(KDevelop::IDebugSession::StartingState);
+
+ QStringList to_be_interpreted = config->config().readEntry(interpretedModules,QStringList());
+
+ kDebug() << "interpreted modules: " << to_be_interpreted;
+
+ foreach(QString module, to_be_interpreted)
+ {
+ interpretMoule(module);
+ }
+
+ QString module = config->config().readEntry(callableModule,"");
+ QString function = config->config().readEntry(callableFunction,"");
+ QString functionArguments = config->config().readEntry(callableArguments,"");
+
+ spawn(module, function, functionArguments);
+}
+
+void DebugSession::stepOut()
+{
+ m_commands.enqueue(new FinishCommand(m_processToMeta[m_currentProcess]));
+ executeCmd();
+}
+
+void DebugSession::updateCurrentActiveProcess(QString processID)
+{
+ m_currentProcess = processID;
+}
+
+void DebugSession::stepOverInstruction()
+{
+}
+
+DebugSession::DebugSession() : m_requestID(0)
+{
+ m_breakpointController = new ErlangBreakpointController(this);
+ m_variableController = new VariableController(this);
+}
+
+void DebugSession::sendBreakpoint(QString location, int line)
+{
+ if (!m_interpretedModules.contains(location))
+ {
+ m_commands.enqueue(new InterpretModuleCommand(location));
+ m_interpretedModules.append(location);
+ executeCmd();
+ }
+
+ m_commands.enqueue(new BreakCommand(location, line));
+ executeCmd();
+}
+
+void DebugSession::stepInto()
+{
+ m_commands.enqueue(new StepCommand(m_processToMeta[m_currentProcess]));
+ executeCmd();
+}
+
+void DebugSession::stepIntoInstruction()
+{
+
+}
+
+void DebugSession::stepOver()
+{
+ m_commands.enqueue(new NextCommand(m_processToMeta[m_currentProcess]));
+ executeCmd();
+}
+
+void DebugSession::jumpToCursor()
+{
+
+}
+
+void DebugSession::runToCursor()
+{
+
+}
+
+void DebugSession::run()
+{
+ m_commands.enqueue(new ContinueCommand(m_processToMeta[m_currentProcess]));
+ executeCmd();
+}
+
+void DebugSession::interruptDebugger()
+{
+
+}
+
+void DebugSession::stopDebugger()
+{
+ if (m_erlDebugger)
+ {
+ m_erlDebugger->stop();
+ delete m_erlDebugger;
+ }
+
+ emit stateChanged(KDevelop::IDebugSession::EndedState);
+}
+
+void DebugSession::restartDebugger()
+{
+
+}
+
+bool DebugSession::restartAvaliable() const
+{
+ return false;
+}
+
+KDevelop::IDebugSession::DebuggerState DebugSession::state() const
+{
+ return KDevelop::IDebugSession::ActiveState;
+}
+
+void DebugSession::executeCmd()
+{
+ m_erlDebugger->execute(m_commands.dequeue());
+}
+
+void DebugSession::handleDebuggerCommand(ErlangOutput* command)
+{
+ switch (command->getCommandType())
+ {
+ case BreakpointOutputType:
+ {
+ BreakpointOutput* i_cmd = static_cast<BreakpointOutput*>(command);
+
+ m_currentProcess = i_cmd->getProcess();
+
+ emit breakpointUpdate(i_cmd);
+ emit showStepInSource(KUrl::fromPath(i_cmd->getModule()), i_cmd->getLine() - 1);
+
+ stateChanged(KDevelop::IDebugSession::PausedState);
+ raiseEvent(program_state_changed);
+ }
+ break;
+ case MetaOutputType:
+ {
+ MetaProcessOutput* i_cmd = static_cast<MetaProcessOutput*>(command);
+ m_processToMeta[i_cmd->getProcess()] = i_cmd->getMeta();
+ }
+ break;
+ case ProcessStatusUpdateType:
+ {
+ ProcessStatusUpdateOutput* i_cmd = static_cast<ProcessStatusUpdateOutput*>(command);
+ if (i_cmd->getProcessStatus() == ErlangProcessStatus::Running)
+ {
+ emit stateChanged(KDevelop::IDebugSession::ActiveState);
+ raiseEvent(program_state_changed);
+ }
+ }
+ break;
+ case VariableListOutputType:
+ {
+ VariableListOutput* i_cmd = static_cast<VariableListOutput*>(command);
+
+ foreach(DebugCallbackBase* callback, m_callbacks)
+ {
+ callback->execute(*command);
+ }
+
+ m_callbacks.clear();
+
+ emit variableListUpdate(i_cmd);
+ }
+ break;
+ case StackTraceOutputType:
+ {
+ StackTraceOutput* i_cmd = static_cast<StackTraceOutput*>(command);
+ emit stackTraceUpdate(i_cmd);
+ }
+ }
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.cpp (revision 1522570)
@@ -0,0 +1,150 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "variable.h"
+#include "debugsession.h"
+
+#include <QXmlStreamReader>
+
+#include <interfaces/icore.h>
+#include <debugger/interfaces/ivariablecontroller.h>
+#include <debugger/interfaces/iframestackmodel.h>
+#include "messages.h"
+#include "debugsession.h"
+
+namespace ErlangDebugPlugin
+{
+
+static bool hasStartedSession()
+{
+ KDevelop::IDebugSession *session = KDevelop::ICore::self()->debugController()->currentSession();
+ if ( !session )
+ return false;
+
+ KDevelop::IDebugSession::DebuggerState s = session->state();
+ return s != KDevelop::IDebugSession::NotStartedState
+ && s != KDevelop::IDebugSession::EndedState;
+}
+
+Variable::Variable ( KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
+ const QString& expression, const QString& display )
+ : KDevelop::Variable ( model, parent, expression, display )
+{
+}
+
+Variable::~Variable()
+{
+}
+
+class VariableListCallback : public DebugCallbackBase
+{
+public:
+ VariableListCallback ( Variable *variable, QObject *callback, const char *callbackMethod )
+ : m_variable ( variable ), m_callback ( callback ), m_callbackMethod ( callbackMethod ) {}
+
+ virtual void execute ( ErlangOutput &output )
+ {
+ if ( !m_variable )
+ return;
+
+ VariableListOutput* v_output = static_cast<VariableListOutput*> ( &output );
+
+ QDomDocument doc = v_output->getDocument();
+ QDomNodeList lst = doc.firstChild().childNodes();
+
+
+ for ( int i = 0; i < lst.size(); ++i )
+ {
+ QDomNode node = lst.at ( i );
+ if ( node.attributes().namedItem ( "name" ).nodeValue() == m_variable->expression() &&
+ m_variable->handleProperty ( node ) )
+ {
+ QMetaObject::invokeMethod ( m_callback, m_callbackMethod, Q_ARG ( bool, true ) );
+ break;
+ }
+ }
+ }
+
+private:
+ QPointer<Variable> m_variable;
+ QObject *m_callback;
+ const char *m_callbackMethod;
+};
+
+void Variable::attachMaybe ( QObject *callback, const char *callbackMethod )
+{
+ if ( hasStartedSession() )
+ {
+ KDevelop::IDebugSession* is = KDevelop::ICore::self()->debugController()->currentSession();
+ DebugSession* s = static_cast<DebugSession*>(is);
+ s->requestVariables(new VariableListCallback(this, callback, callbackMethod));
+ }
+}
+
+void Variable::fetchMoreChildren()
+{
+}
+
+bool Variable::handleProperty ( QDomNode variable )
+{
+ setInScope ( true );
+
+ QDomNodeList lst = variable.childNodes();
+ QString var_name;
+
+ for ( int i = 0; i < lst.size(); ++i )
+ {
+ QDomNode node = lst.item ( i );
+ QString node_name = node.nodeName();
+
+ if ( node_name == "item" )
+ {
+ QString data = node.firstChildElement ( "raw_value" ).firstChild().toCDATASection().data();
+
+ Variable* v = new Variable ( model(), this, data);
+ appendChild ( v, false );
+ v->handleProperty ( node );
+ }
+ else if ( node_name == "value" )
+ {
+ QString data = node.firstChild().toCDATASection().data();
+
+ if ( variable.attributes().contains ( "kind" ) )
+ {
+ Variable* v = new Variable ( model(), this, data );
+ appendChild ( v, false );
+ }
+ else
+ {
+ setValue(data);
+ }
+ }
+ }
+
+ return true;
+}
+
+QString Variable::fullName() const
+{
+ return m_fullName;
+}
+
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp (revision 1522570)
@@ -0,0 +1,134 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "variablecontroller.h"
+
+#include <QXmlStreamReader>
+
+#include <debugger/variable/variablecollection.h>
+#include <debugger/breakpoint/breakpointmodel.h>
+#include <interfaces/icore.h>
+#include <interfaces/idebugcontroller.h>
+#include <debugger/interfaces/iframestackmodel.h>
+
+#include "debugsession.h"
+#include "variable.h"
+#include "stringhelpers.h"
+#include "messages.h"
+#include "variable.h"
+
+namespace ErlangDebugPlugin {
+
+VariableController::VariableController(DebugSession* parent)
+ : KDevelop::IVariableController(parent) , m_currentVarList(0)
+{
+ Q_ASSERT(parent);
+ //connect(parent, SIGNAL(variableListUpdate(VariableListOutput*)), SLOT(handleLocals(VariableListOutput*)));
+}
+
+void VariableController::handleLocals(VariableListOutput* variableList)
+{
+ /*
+ TODO: check with someone if there's a way to make this work
+
+ m_currentVarList = new VariableListOutput(*variableList);
+
+ QDomDocument& document = variableList->getDocument();
+
+ QStringList updatable;
+
+ QDomNodeList lst = document.firstChildElement().elementsByTagName("variable");
+
+ for (int i = 0; i < lst.size(); ++i)
+ {
+ updatable << lst.at(i).attributes().namedItem("name").nodeValue();
+ kDebug() << "Updating: " << updatable;
+
+ QList<KDevelop::Variable*> locals = KDevelop::ICore::self()->debugController()->variableCollection()->locals()->updateLocals(updatable);
+
+ Q_ASSERT(locals.size() == 1);
+ static_cast<Variable*>(locals.at(0))->handleProperty(lst.at(i));
+ updatable.clear();
+ }*/
+}
+
+DebugSession *VariableController::debugSession() const
+{
+ return static_cast<DebugSession*>(const_cast<QObject*>(QObject::parent()));
+}
+
+void VariableController::update()
+{
+ variableCollection()->watches()->reinstall();
+}
+
+QString VariableController::expressionUnderCursor(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor)
+{
+ QString line = doc->line(cursor.line());
+ int index = cursor.column();
+ QChar c = line[index];
+ if (!c.isLetterOrNumber() && c != '_' && c != '$')
+ return QString();
+
+ int start = Utils::expressionAt(line, index);
+ int end = index;
+ for (; end < line.size(); ++end) {
+ QChar c = line[end];
+ if (!(c.isLetterOrNumber() || c == '_' || c == '$'))
+ break;
+ }
+ if (!(start < end))
+ return QString();
+
+ QString expression(line.mid(start, end-start));
+ expression = expression.trimmed();
+ return expression;
+}
+
+
+void VariableController::addWatch(KDevelop::Variable* variable)
+{
+ if (Variable *v = dynamic_cast<Variable*>(variable)) {
+ variableCollection()->watches()->add(v->fullName());
+ }
+}
+
+void VariableController::addWatchpoint(KDevelop::Variable* variable)
+{
+ if (Variable *v = dynamic_cast<Variable*>(variable)) {
+ KDevelop::ICore::self()->debugController()->breakpointModel()->addWatchpoint(v->fullName());
+ }
+}
+
+KDevelop::Variable* VariableController::
+createVariable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
+ const QString& expression, const QString& display)
+{
+ return new Variable(model, parent, expression, display);
+}
+
+void VariableController::handleEvent(KDevelop::IDebugSession::event_t event)
+{
+ IVariableController::handleEvent(event);
+}
+
+}
+
+#include "variablecontroller.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variable.h (revision 1522570)
@@ -0,0 +1,58 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGVARIABLE_H
+#define ERLANGVARIABLE_H
+
+#include <QtCore/QMap>
+
+#include <debugger/variable/variablecollection.h>
+
+
+namespace ErlangDebugPlugin
+{
+class VariableListOutput;
+class VariableListCallback;
+
+class Variable : public KDevelop::Variable
+{
+public:
+ Variable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
+ const QString& expression,
+ const QString& display = "");
+
+ ~Variable();
+public: // Variable overrides
+ virtual void attachMaybe(QObject *callback = 0, const char *callbackMethod = 0);
+ virtual void fetchMoreChildren();
+ QString fullName() const;
+ bool handleProperty(QDomNode variable);
+
+private: // Internal
+ friend class VariableListCallback;
+ QString m_fullName;
+
+ QObject* m_callback;
+ const char* m_callbackMethod;
+ unsigned int m_iter;
+};
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp (revision 1522570)
@@ -0,0 +1,183 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "launchconfig.h"
+
+#include "debugplugin.h"
+#include "debugjob.h"
+#include "debugsession.h"
+
+#include <execute/iexecuteplugin.h>
+#include <debugger/util/pathmappings.h>
+#include <interfaces/ilaunchconfiguration.h>
+#include <interfaces/iproject.h>
+
+#include <klocale.h>
+#include <kdebug.h>
+
+#include <QBoxLayout>
+#include <KIcon>
+#include <KLocalizedString>
+#include <qheaderview.h>
+#include <project/projectmodel.h>
+
+#include <kmimetype.h>
+#include <kconfiggroup.h>
+#include <QFileInfo>
+#include <QListView>
+
+namespace ErlangDebugPlugin
+{
+
+KDevelop::LaunchConfigurationPage* ConfigPageFactory::createWidget( QWidget* parent )
+{
+ return new ConfigPage( parent );
+}
+
+ConfigPage::ConfigPage( QWidget* parent )
+ : LaunchConfigurationPage(parent)
+{
+ setupUi(this);
+}
+
+KIcon ConfigPage::icon() const
+{
+ return KIcon();
+}
+
+void ConfigPage::loadFromConfiguration( const KConfigGroup& cfg, KDevelop::IProject* project )
+{
+ KMimeType::Ptr mimetype =KMimeType::mimeType("text/x-erlang");
+
+ QStringList itens = cfg.readEntry(ErlangDebugPlugin::interpretedModules, QStringList());
+ QStringList includeLibraryPaths = cfg.readEntry(ErlangDebugPlugin::libraryPaths, QStringList());
+
+ foreach(KDevelop::ProjectFileItem* item, project->files())
+ {
+ if (KMimeType::findByUrl(item->fileName())->name() == mimetype->name())
+ {
+ QFileInfo module(item->fileName());
+ QString basename = module.baseName();
+ QTreeWidgetItem* i = new QTreeWidgetItem(interpretableTreeWidget, QStringList(basename));
+ i->setCheckState(0, itens.contains(basename) ? Qt::Checked : Qt::Unchecked);
+ }
+ }
+
+ foreach(QString path, includeLibraryPaths)
+ {
+ includeLibraryListWidget->addItem(path);
+ }
+
+ if (includeLibraryPaths.empty())
+ {
+ includeLibraryListWidget->addItem(project->folder().path() + "ebin/");
+ }
+
+ QString moduleName = cfg.readEntry(ErlangDebugPlugin::callableModule, QString());
+ QString moduleFunction = cfg.readEntry(ErlangDebugPlugin::callableFunction, QString());
+ QString arguments = cfg.readEntry(ErlangDebugPlugin::callableArguments, QString());
+
+ moduleNameLineEdit->setText(moduleName);
+ moduleFunctionLineEdit->setText(moduleFunction);
+ functionArgumentsLineEdit->setText(arguments);
+}
+
+void ConfigPage::saveToConfiguration( KConfigGroup cfg, KDevelop::IProject* project ) const
+{
+ QStringList to_be_interpreted;
+
+ for(int i = 0; i < interpretableTreeWidget->topLevelItemCount(); ++i)
+ {
+ QTreeWidgetItem* w_item = interpretableTreeWidget->topLevelItem(i);
+ if (w_item->checkState(0) == Qt::Checked)
+ to_be_interpreted << w_item->text(0);
+ }
+
+ QStringList libraryPaths;
+
+ for(int i = 0; i < includeLibraryListWidget->count(); ++i)
+ {
+ if (QFileInfo(includeLibraryListWidget->item(i)->text()).exists())
+ {
+ libraryPaths << includeLibraryListWidget->item(i)->text();
+ }
+ }
+
+ cfg.writeEntry(ErlangDebugPlugin::interpretedModules, to_be_interpreted);
+ cfg.writeEntry(ErlangDebugPlugin::rebuildDebuggerInterface, true);
+ cfg.writeEntry(ErlangDebugPlugin::libraryPaths, libraryPaths);
+
+ cfg.writeEntry(ErlangDebugPlugin::callableModule, moduleNameLineEdit->text());
+ cfg.writeEntry(ErlangDebugPlugin::callableFunction, moduleFunctionLineEdit->text());
+ cfg.writeEntry(ErlangDebugPlugin::callableArguments, functionArgumentsLineEdit->text());
+}
+
+QString ConfigPage::title() const
+{
+ return i18n( "Erlang Configuration" );
+}
+
+ErlangLauncher::ErlangLauncher(ErlangDebuggerPlugin* plugin)
+ : m_plugin(plugin)
+{
+ factoryList << new ConfigPageFactory();
+}
+
+KJob* ErlangLauncher::start(const QString& launchMode, KDevelop::ILaunchConfiguration* cfg)
+{
+ Q_ASSERT(cfg);
+ if( !cfg )
+ {
+ return 0;
+ }
+ if( launchMode == "debug" )
+ {
+ return new ErlangDebugJob( m_plugin->createSession(), cfg, m_plugin);
+ }
+ kWarning() << "Unknown launch mode" << launchMode << "for config:" << cfg->name();
+ return 0;
+}
+
+QList< KDevelop::LaunchConfigurationPageFactory* > ErlangLauncher::configPages() const
+{
+ return factoryList;
+}
+
+QStringList ErlangLauncher::supportedModes() const
+{
+ return QStringList() << "debug";
+}
+
+QString ErlangLauncher::description() const
+{
+ return i18n("Executes a erlang application in debug mode");
+}
+
+QString ErlangLauncher::name() const
+{
+ return i18n("Erlang");
+}
+
+QString ErlangLauncher::id()
+{
+ return "erlang";
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp (revision 1522570)
@@ -0,0 +1,70 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+#include "debugplugin.h"
+
+#include <interfaces/icore.h>
+#include <interfaces/idebugcontroller.h>
+#include <kpluginfactory.h>
+#include <klocalizedstring.h>
+#include <kaboutdata.h>
+
+#include <execute/iexecuteplugin.h>
+#include <interfaces/launchconfigurationtype.h>
+#include <interfaces/icore.h>
+#include <interfaces/iplugincontroller.h>
+
+#include "debugsession.h"
+#include "launchconfig.h"
+
+namespace ErlangDebugPlugin
+{
+K_PLUGIN_FACTORY(ErlangDebuggerFactory, registerPlugin<ErlangDebuggerPlugin>(); )
+K_EXPORT_PLUGIN(ErlangDebuggerFactory(KAboutData("kdeverldebug","kdeverldebug", ki18n("Erlang debug support"), "0.1", ki18n("Support for debugging erlang apps"), KAboutData::License_GPL)))
+
+
+ErlangDebuggerPlugin::ErlangDebuggerPlugin(QObject* parent, const QVariantList& ): IPlugin(ErlangDebuggerFactory::componentData(), parent )
+{
+ {
+ IExecutePlugin* iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
+ Q_ASSERT(iface);
+ KDevelop::LaunchConfigurationType* type = core()->runController()->launchConfigurationTypeForId( iface->nativeAppConfigTypeId() );
+ Q_ASSERT(type);
+ type->addLauncher( new ErlangLauncher( this ) );
+ }
+}
+
+DebugSession* ErlangDebuggerPlugin::createSession() const
+{
+ DebugSession *session = new DebugSession();
+ KDevelop::ICore::self()->debugController()->addSession(session);
+ //connect(session, SIGNAL(showMessage(QString,int)), SLOT(controllerMessage(QString,int)));
+ //connect(session, SIGNAL(reset()), SIGNAL(reset()));
+ connect(session, SIGNAL(finished()), SLOT(slotFinished()));
+ //connect(session, SIGNAL(raiseOutputViews()), SIGNAL(raiseOutputViews()));
+ //connect(session, SIGNAL(raiseVariableViews()), SIGNAL(raiseVariableViews()));
+ return session;
+}
+
+ErlangDebuggerPlugin::~ErlangDebuggerPlugin()
+{
+
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp (revision 1522570)
@@ -0,0 +1,153 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+
+#include "debugjob.h"
+
+#include <QFileInfo>
+#include <QDesktopServices>
+
+#include <KProcess>
+#include <kconfiggroup.h>
+#include <kicon.h>
+#include <klocale.h>
+#include <kshell.h>
+#include <KMessageBox>
+#include <KParts/MainWindow>
+
+#include <outputview/outputmodel.h>
+#include <interfaces/ilaunchconfiguration.h>
+#include <util/environmentgrouplist.h>
+#include <execute/iexecuteplugin.h>
+#include <interfaces/iproject.h>
+#include <project/interfaces/iprojectbuilder.h>
+#include <project/builderjob.h>
+#include <interfaces/iuicontroller.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <util/executecompositejob.h>
+#include <interfaces/iplugincontroller.h>
+#include <interfaces/icore.h>
+#include <util/processlinemaker.h>
+
+#include "debugsession.h"
+#include "debugplugin.h"
+
+#include <kdebug.h>
+
+namespace ErlangDebugPlugin {
+
+ErlangDebugJob::ErlangDebugJob( DebugSession* session, KDevelop::ILaunchConfiguration* cfg, QObject* parent)
+ : m_proc(0), m_session(session), m_launchConfig(cfg)
+{
+ setCapabilities(Killable);
+
+ connect(m_session, SIGNAL(stdoutReceived(QString)), SLOT(stdoutReceived(QString)));
+
+ setObjectName(cfg->name());
+
+
+}
+
+void ErlangDebugJob::start()
+{
+ setBehaviours(KDevelop::IOutputView::AllowUserClose | KDevelop::IOutputView::AutoScroll);
+ setStandardToolView(KDevelop::IOutputView::DebugView);
+ setModel( new KDevelop::OutputModel(), KDevelop::IOutputView::TakeOwnership );
+
+ KDevelop::EnvironmentGroupList l(KGlobal::config());
+ IExecutePlugin * iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
+
+ Q_ASSERT(iface);
+ QString err;
+ QString envgrp = iface->environmentGroup( m_launchConfig );
+
+ if( envgrp.isEmpty() )
+ {
+ kWarning() << i18n("No environment group specified, looks like a broken "
+ "configuration, please check run configuration '%1'. "
+ "Using default environment group.", m_launchConfig->name() );
+ envgrp = l.defaultGroup();
+ }
+
+ QStringList arguments = iface->arguments( m_launchConfig, err );
+
+ if( !err.isEmpty() )
+ {
+ setError( -1 );
+ setErrorText( err );
+ }
+
+ if( error() != 0 )
+ {
+ emitResult();
+ return;
+ }
+
+ startOutput();
+
+ m_session->startDebugger(m_launchConfig);
+}
+
+bool ErlangDebugJob::doKill()
+{
+ kDebug();
+ if (m_session) m_session->stopDebugger();
+ return true;
+}
+
+void ErlangDebugJob::processFinished( int exitCode , QProcess::ExitStatus status )
+{
+ emitResult();
+
+ if (m_session) delete m_session;
+}
+
+void ErlangDebugJob::processError( QProcess::ProcessError error )
+{
+ if( error == QProcess::FailedToStart )
+ {
+ setError( -1 );
+ QString errmsg = i18n("Could not start program '%1'. Make sure that the "
+ "path is specified correctly.", m_proc->property("executable").toString() );
+ KMessageBox::error( KDevelop::ICore::self()->uiController()->activeMainWindow(), errmsg, i18n("Could not start application") );
+ setErrorText( errmsg );
+ emitResult();
+ }
+ kDebug() << "Process error";
+
+ if (m_session) delete m_session;
+}
+
+KDevelop::OutputModel* ErlangDebugJob::model()
+{
+ return dynamic_cast<KDevelop::OutputModel*>( KDevelop::OutputJob::model() );
+}
+
+void ErlangDebugJob::stdoutReceived(QString data)
+{
+ if (KDevelop::OutputModel* m = model()) {
+ m->appendLine(data);
+ }
+}
+
+
+}
+
+#include "debugjob.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugjob.h (revision 1522570)
@@ -0,0 +1,67 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+#ifndef ERLANG_DEBUG_JOB_H_
+#define ERLANG_DEBUG_JOB_H_
+
+#include <QProcess>
+#include <KUrl>
+
+#include <outputview/outputjob.h>
+
+class KProcess;
+namespace KDevelop
+{
+class OutputModel;
+class ILaunchConfiguration;
+class ProcessLineMaker;
+}
+
+namespace ErlangDebugPlugin
+{
+
+class DebugSession;
+
+class ErlangDebugJob : public KDevelop::OutputJob
+{
+Q_OBJECT
+public:
+ ErlangDebugJob( DebugSession* session, KDevelop::ILaunchConfiguration*, QObject* parent = 0 );
+ virtual void start();
+
+protected:
+ virtual bool doKill();
+
+private slots:
+ void processError(QProcess::ProcessError);
+ void processFinished(int, QProcess::ExitStatus);
+ void stdoutReceived(QString data);
+
+private:
+ KDevelop::ILaunchConfiguration* m_launchConfig;
+
+ KDevelop::OutputModel* model();
+ KProcess* m_proc;
+ QPointer<DebugSession> m_session;
+};
+
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugger.h (revision 1522570)
@@ -0,0 +1,63 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGDEBUGGER_H
+#define ERLANGDEBUGGER_H
+
+#include <kconfiggroup.h>
+#include <QString>
+#include <kprocess.h>
+#include "messages.h"
+
+namespace ErlangDebugPlugin
+{
+class ErlangCommand;
+
+class ErlangDebugger : public QObject
+{
+ Q_OBJECT
+public:
+
+ void start(QString runDir, const KConfigGroup& config);
+ void execute(ErlangCommand* command);
+ void stop();
+
+signals:
+ void outputCommand(ErlangOutput* ouput);
+ void stdoutReceived(QString data);
+
+protected:
+ QString m_erlShellBinary;
+ KProcess* m_erlShellProcess;
+ QByteArray m_buffer;
+
+ void processLine(QByteArray data);
+
+private Q_SLOTS:
+ void readyReadStandardOutput();
+ void readyReadStandardError();
+ void processFinished(int exitCode, QProcess::ExitStatus exitStatus);
+ void processErrored(QProcess::ProcessError);
+
+};
+
+}
+
+#endif // ERLANGDEBUGGER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp (revision 1522570)
@@ -0,0 +1,86 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "breakpointcontroller.h"
+
+#include "debugsession.h"
+#include <kdebug.h>
+#include <debugger/breakpoint/breakpointmodel.h>
+#include "messages.h"
+
+namespace ErlangDebugPlugin
+{
+
+DebugSession* ErlangBreakpointController::debugSession()
+{
+ return static_cast<DebugSession*>(KDevelop::IBreakpointController::debugSession());
+}
+
+ErlangBreakpointController::ErlangBreakpointController(DebugSession* parent): IBreakpointController(parent)
+{
+ connect(parent, SIGNAL(stateChanged(KDevelop::IDebugSession::DebuggerState)),
+ SLOT(stateChanged(KDevelop::IDebugSession::DebuggerState)));
+
+ connect(parent, SIGNAL(breakpointUpdate(BreakpointOutput*)),
+ SLOT(hitBreakpoint(BreakpointOutput*)));
+}
+
+void ErlangBreakpointController::sendMaybe(KDevelop::Breakpoint* breakpoint)
+{
+ if (breakpoint->kind() == KDevelop::Breakpoint::CodeBreakpoint)
+ {
+ QString module = breakpoint->url().fileName().split(".")[0];
+ if (breakpoint->deleted())
+ {
+ debugSession()->removeBreakpoint(module, breakpoint->line() + 1);
+ if (m_ids.contains(breakpoint))
+ m_ids.remove(breakpoint);
+ }
+ else if (!m_ids.contains(breakpoint))
+ {
+ debugSession()->sendBreakpoint(module, breakpoint->line() + 1);
+ m_ids[breakpoint] = breakpoint->url().path() + ":" + QString::number(breakpoint->line());
+ }
+ }
+}
+
+void ErlangBreakpointController::stateChanged(KDevelop::IDebugSession::DebuggerState state)
+{
+ kDebug() << state;
+ if (state == KDevelop::IDebugSession::StartingState) {
+ m_ids.clear();
+ sendMaybeAll();
+ }
+}
+
+void ErlangBreakpointController::hitBreakpoint(BreakpointOutput* breakpoint)
+{
+ QString id = breakpoint->getModule() + ":" + QString::number(breakpoint->getLine());
+
+ KDevelop::Breakpoint* b = m_ids.key(id);
+
+ if (b)
+ {
+ b = breakpointModel()->addCodeBreakpoint(KUrl::fromPath(breakpoint->getModule()), breakpoint->getLine() - 1);
+ hit(b);
+ }
+}
+
+}
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h (revision 1522570)
@@ -0,0 +1,63 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANG_VARIABLECONTROLLER_H
+#define ERLANG_VARIABLECONTROLLER_H
+
+#include <debugger/interfaces/ivariablecontroller.h>
+
+class QDomDocument;
+namespace KDevelop {
+class Locals;
+}
+namespace ErlangDebugPlugin {
+
+class Variable;
+class DebugSession;
+class VariableListOutput;
+
+class VariableController : public KDevelop::IVariableController
+{
+ Q_OBJECT
+
+public:
+ VariableController(DebugSession* parent);
+
+ KDevelop::Variable* createVariable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
+ const QString& expression,
+ const QString& display = "");
+
+ virtual QString expressionUnderCursor(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor);
+ virtual void addWatch(KDevelop::Variable* variable);
+ virtual void addWatchpoint(KDevelop::Variable* variable);
+ virtual void update();
+
+private slots:
+ void handleLocals(VariableListOutput*);
+
+private:
+ DebugSession* debugSession() const;
+ void handleEvent(KDevelop::IDebugSession::event_t event);
+ VariableListOutput* m_currentVarList;
+};
+
+}
+
+#endif // GDBDEBUGGER_VARIABLECONTROLLER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h (revision 1522570)
@@ -0,0 +1,50 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGBREAKPOINTCONTROLLER_H
+#define ERLANGBREAKPOINTCONTROLLER_H
+
+#include <debugger/interfaces/ibreakpointcontroller.h>
+#include <debugger/interfaces/idebugsession.h>
+
+namespace ErlangDebugPlugin
+{
+class DebugSession;
+class BreakpointOutput;
+
+class ErlangBreakpointController : public KDevelop::IBreakpointController
+{
+ Q_OBJECT
+public:
+ ErlangBreakpointController(DebugSession* parent);
+ virtual void sendMaybe(KDevelop::Breakpoint* breakpoint);
+
+private slots:
+ void stateChanged(KDevelop::IDebugSession::DebuggerState state);
+ void hitBreakpoint(BreakpointOutput* breakpoint);
+
+private:
+ DebugSession *debugSession();
+ QMap<KDevelop::Breakpoint*, QString> m_ids;
+
+};
+
+}
+#endif // ERLANGBREAKPOINTCONTROLLER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp (revision 1522570)
@@ -0,0 +1,67 @@
+/*
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "debuggertests.h"
+#include "../debugger.h"
+#include "../debugsession.h"
+
+#include <QApplication>
+
+#include <KSharedConfig>
+#include <kglobal.h>
+
+#include <KDebug>
+#include <KProcess>
+#include <KConfig>
+#include <qtest_kde.h>
+#include <tests/testcore.h>
+#include <tests/autotestshell.h>
+
+#include <QTest>
+
+QTEST_MAIN(DebuggerTests)
+
+void DebuggerTests::debuggerIntegration()
+{
+ ErlangDebugPlugin::ErlangDebugger debugger;
+
+ KConfigGroup grp(KGlobal::config(), "Erlang Debugger");
+
+ grp.writeEntry(ErlangDebugPlugin::erlangShellExecPath,"");
+ grp.writeEntry(ErlangDebugPlugin::rebuildDebuggerInterface, true);
+
+ debugger.start(grp);
+
+ QApplication::exec();
+}
+
+DebuggerTests::DebuggerTests()
+{
+
+}
+
+void DebuggerTests::initTestCase()
+{
+ KDevelop::AutoTestShell::init();
+ m_core = new KDevelop::TestCore();
+ m_core->initialize(KDevelop::Core::NoUi);
+}
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h (revision 1522570)
@@ -0,0 +1,47 @@
+/*
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef DEBUGGERTESTS_H
+#define DEBUGGERTESTS_H
+
+#include <QObject>
+
+namespace KDevelop
+{
+ class TestCore;
+}
+
+class DebuggerTests : public QObject
+{
+ Q_OBJECT
+
+public:
+ DebuggerTests();
+
+private Q_SLOTS:
+ void debuggerIntegration();
+
+ virtual void initTestCase();
+
+protected:
+ KDevelop::TestCore* m_core;
+};
+
+#endif // DEBUGGERTESTS_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h (revision 1522570)
@@ -0,0 +1,35 @@
+/*
+ Copyright 2007 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef __STRINGHELPERS_H__
+#define __STRINGHELPERS_H__
+
+class QString;
+class QChar;
+class QStringList;
+
+namespace Utils {
+
+/**
+ * Copied from kdevelop-3.4, should be redone
+ * @param index should be the index BEHIND the expression
+ * */
+int expressionAt( const QString& contents, int index );
+
+}
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/launchconfig.h (revision 1522570)
@@ -0,0 +1,78 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGLAUNCHCONFIG_H
+#define ERLANGLAUNCHCONFIG_H
+
+#include <interfaces/ilauncher.h>
+#include <interfaces/launchconfigurationpage.h>
+#include <QTreeWidget>
+
+#include "ui_debug_config.h"
+
+namespace KDevelop {
+ class PathMappingsWidget;
+}
+
+namespace ErlangDebugPlugin
+{
+class ErlangDebuggerPlugin;
+
+class ConfigPageFactory : public KDevelop::LaunchConfigurationPageFactory
+{
+public:
+ virtual KDevelop::LaunchConfigurationPage* createWidget(QWidget* parent);
+};
+
+class ConfigPage : public KDevelop::LaunchConfigurationPage , public Ui::ErlangDebugConfigDialog
+{
+Q_OBJECT
+public:
+ ConfigPage( QWidget* parent = 0 );
+ virtual KIcon icon() const;
+ virtual void loadFromConfiguration(const KConfigGroup& cfg, KDevelop::IProject* = 0);
+ virtual void saveToConfiguration(KConfigGroup, KDevelop::IProject* = 0 ) const;
+ virtual QString title() const;
+private:
+ KDevelop::PathMappingsWidget *m_pathMappings;
+ QTreeView* m_treeView;
+};
+
+
+class ErlangLauncher : public KDevelop::ILauncher
+{
+public:
+ ErlangLauncher(ErlangDebugPlugin::ErlangDebuggerPlugin* plugin);
+
+ virtual KJob* start(const QString& launchMode, KDevelop::ILaunchConfiguration* cfg);
+ virtual QList< KDevelop::LaunchConfigurationPageFactory* > configPages() const;
+ virtual QStringList supportedModes() const;
+ virtual QString description() const;
+ virtual QString name() const;
+ virtual QString id();
+
+private:
+ QList<KDevelop::LaunchConfigurationPageFactory*> factoryList;
+ ErlangDebuggerPlugin* m_plugin;
+};
+
+}
+
+#endif // ERLANGLAUNCHCONFIG_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/debugplugin.h (revision 1522570)
@@ -0,0 +1,43 @@
+/*
+ Erlang Debugger support for KDevelop
+ Copyright (C) 2010 Victor Vicente de Carvalho
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef ERLANGDEBUGPLUGIN_H
+#define ERLANGDEBUGPLUGIN_H
+
+#include <interfaces/iplugin.h>
+#include <debugger/interfaces/idebugsession.h>
+
+namespace ErlangDebugPlugin
+{
+class DebugSession;
+
+class ErlangDebuggerPlugin : public KDevelop::IPlugin
+{
+ Q_OBJECT
+public:
+ ErlangDebuggerPlugin( QObject* parent, const QVariantList & = QVariantList() );
+ ~ErlangDebuggerPlugin();
+
+ DebugSession* createSession() const;
+};
+
+}
+
+#endif // ERLANGDEBUGPLUGIN_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp (revision 1522570)
@@ -0,0 +1,106 @@
+/*
+ Copyright 2007 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include <language/duchain/stringhelpers.h>
+#include <language/duchain/safetycounter.h>
+#include <QString>
+#include <QChar>
+#include <QStringList>
+
+namespace Utils {
+
+enum { T_ACCESS, T_PAREN, T_BRACKET, T_IDE, T_UNKNOWN, T_TEMP };
+
+int expressionAt( const QString& text, int index ) {
+
+ if( index == 0 )
+ return 0;
+
+ int last = T_UNKNOWN;
+ int start = index;
+ --index;
+
+ while ( index > 0 ) {
+ while ( index > 0 && text[ index ].isSpace() ) {
+ --index;
+ }
+
+ QChar ch = text[ index ];
+ QString ch2 = text.mid( index - 1, 2 );
+ if ( ( last != T_IDE ) && ( ch.isLetterOrNumber() || ch == '_' || ch == '$' ) ) {
+ while ( index > 0 && ( text[ index ].isLetterOrNumber() || text[ index ] == '_' || text[ index ] == '$' ) ) {
+ --index;
+ }
+ last = T_IDE;
+ } else if ( last != T_IDE && ch == ')' ) {
+ int count = 0;
+ while ( index > 0 ) {
+ QChar ch = text[ index ];
+ if ( ch == '(' ) {
+ ++count;
+ } else if ( ch == ')' ) {
+ --count;
+ }
+ --index;
+ if ( count == 0 ) {
+ //index;
+ last = T_PAREN;
+ break;
+ }
+ }
+ } else if ( ch == ']' ) {
+ int count = 0;
+ while ( index > 0 ) {
+ QChar ch = text[ index ];
+ if ( ch == '[' ) {
+ ++count;
+ } else if ( ch == ']' ) {
+ --count;
+ } else if ( count == 0 ) {
+ //--index;
+ last = T_BRACKET;
+ break;
+ }
+ --index;
+ }
+ } else if ( ch2 == "::" ) {
+ index -= 2;
+ last = T_ACCESS;
+ } else if ( ch2 == "->" ) {
+ index -= 2;
+ last = T_ACCESS;
+ } else {
+ if ( start > index ) {
+ ++index;
+ }
+ last = T_UNKNOWN;
+ break;
+ }
+ }
+
+ ///If we're at the first item, the above algorithm cannot be used safely,
+ ///so just determine whether the sign is valid for the beginning of an expression, if it isn't reject it.
+ if ( index == 0 && start > index && !( text[ index ].isLetterOrNumber() || text[ index ] == '_' || text[ index ] == '$' || text[ index ] == ':' ) ) {
+ ++index;
+ }
+
+ return index;
+}
+
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,75 @@
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9046 )
+
+enable_testing()
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${QT4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+)
+
+########### next target ###############
+
+set(kdeverldebugcore_PART_SRCS
+ debugger.cpp
+ debugsession.cpp
+ debugjob.cpp
+ framestackmodel.cpp
+ breakpointcontroller.cpp
+ messages.cpp
+ launchconfig.cpp
+ variablecontroller.cpp
+ variable.cpp
+ stringhelpers.cpp
+)
+
+set(kdeverldebug_PART_SRCS
+ debugplugin.cpp
+ launchconfig.cpp
+ #launchconfigurationpage.cpp
+)
+
+set(kdevelerlang_UI_PARTS
+ debug_config.ui)
+
+kde4_add_ui_files(kdeverldebugcore_PART_SRCS ${kdevelerlang_UI_PARTS})
+kde4_add_plugin(kdeverldebug ${kdeverldebugcore_PART_SRCS} ${kdeverldebug_PART_SRCS})
+
+target_link_libraries(kdeverldebug
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_DEBUGGER_LIBRARIES}
+ ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES}
+ ${KDEVPLATFORM_UTIL_LIBRARIES}
+)
+
+install(TARGETS kdeverldebug DESTINATION ${PLUGIN_INSTALL_DIR})
+install(FILES debug_interpreter.erl DESTINATION ${DATA_INSTALL_DIR}/kdeverlangsupport)
+
+
+########### next target ###############
+
+set(erlangdebuggertests_SRCS
+ tests/debuggertests.cpp
+)
+
+kde4_add_unit_test(erlangdebuggertests ${erlangdebuggertests_SRCS} ${kdeverldebugcore_PART_SRCS} ${kdeverldebug_PART_SRCS})
+
+target_link_libraries(erlangdebuggertests
+ ${kdeverldebug}
+ ${QT_QTTEST_LIBRARY}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_TESTSHELL_LIBRARIES}
+ ${KDEVPLATFORM_DEBUGGER_LIBRARIES}
+ ${KDEVPLATFORM_TESTS_LIBRARIES}
+)
+
+
+
+########### install files ###############
+
+install(FILES kdeverldebug.desktop DESTINATION ${SERVICES_INSTALL_DIR})
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop (revision 1522570)
@@ -0,0 +1,75 @@
+[Desktop Entry]
+Encoding=UTF-8
+Type=Service
+Exec=blubb
+Comment=Erlang Language Support
+Comment[bs]=Erlang jezička podrška
+Comment[ca]=Implementació de llenguatge Erlang
+Comment[ca@valencia]=Implementació de llenguatge Erlang
+Comment[de]=Sprachunterstützung für Erlang
+Comment[en_GB]=Erlang Language Support
+Comment[es]=Implementación de lenguaje Erlang
+Comment[et]=Erlangi keele toetus
+Comment[fr]=Prise en charge du langage Erlang
+Comment[gl]=Compatibilidade coa linguaxe Erlang
+Comment[hu]=Erlang nyelvi támogatás
+Comment[it]=Supporto per il linguaggio Erlang
+Comment[nl]=Ondersteuning voor de taal Erlang
+Comment[pl]=Erlang Language Support
+Comment[pt]=Suporte para a Linguagem Erlang
+Comment[pt_BR]=Suporte para a linguagem Erlang
+Comment[sv]=Stöd för språket Erlang
+Comment[uk]=Підтримка мови Erlang
+Comment[x-test]=xxErlang Language Supportxx
+Name=Erlang Support
+Name[bs]=Podrška Erlanga
+Name[ca]=Implementació d'Erlang
+Name[ca@valencia]=Implementació d'Erlang
+Name[de]=Unterstützung für Erlang
+Name[en_GB]=Erlang Support
+Name[es]=Implementación de Erlang
+Name[et]=Erlangi toetus
+Name[fr]=Prise en charge de Erlang
+Name[ga]=Tacaíocht Erlang
+Name[gl]=Compatibilidade con Erlang
+Name[hu]=Erlang támogatás
+Name[it]=Supporto per Erlang
+Name[nl]=Ondersteuning voor Erlang
+Name[pl]=Obsługa Erlang
+Name[pt]=Suporte a Erlang
+Name[pt_BR]=Suporte à Erlang
+Name[sk]=Podpora Erlang
+Name[sv]=Erlang-stöd
+Name[uk]=Підтримка Erlang
+Name[x-test]=xxErlang Supportxx
+GenericName=Erlang Support
+GenericName[bs]=Podrška Erlanga
+GenericName[ca]=Implementació d'Erlang
+GenericName[ca@valencia]=Implementació d'Erlang
+GenericName[de]=Unterstützung für Erlang
+GenericName[en_GB]=Erlang Support
+GenericName[es]=Implementación de Erlang
+GenericName[et]=Erlangi toetus
+GenericName[fr]=Prise en charge de Erlang
+GenericName[ga]=Tacaíocht Erlang
+GenericName[gl]=Compatibilidade con Erlang
+GenericName[hu]=Erlang támogatás
+GenericName[it]=Supporto per Erlang
+GenericName[nl]=Ondersteuning voor Erlang
+GenericName[pl]=Obsługa Erlang
+GenericName[pt]=Suporte a Erlang
+GenericName[pt_BR]=Suporte à Erlang
+GenericName[sk]=Podpora Erlang
+GenericName[sv]=Erlang-stöd
+GenericName[uk]=Підтримка Erlang
+GenericName[x-test]=xxErlang Supportxx
+ServiceTypes=KDevelop/Plugin
+Icon=source
+X-KDE-Library=kdeverlanglanguagesupport
+X-KDevelop-Version=10
+X-KDevelop-Language=Erlang
+X-KDevelop-Args=Erlang
+X-KDevelop-Interfaces=ILanguageSupport
+X-KDevelop-SupportedMimeTypes=text/x-erlang
+X-KDE-PluginInfo-Name=KDevErlangSupport
+X-KDevelop-Mode=NoGUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp (revision 1522570)
@@ -0,0 +1,146 @@
+/*****************************************************************************
+ * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
+ * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "parsesession.h"
+
+#include "kdev-pg-memory-pool.h"
+#include "kdev-pg-token-stream.h"
+
+#include <QFile>
+#include <QTextCodec>
+#include "erlangast.h"
+
+namespace erlang
+{
+
+ParseSession::ParseSession()
+ : m_debug(false),
+ m_pool(new KDevPG::MemoryPool()),
+ m_tokenStream(new TokenStream())
+{
+}
+ParseSession::~ParseSession()
+{
+ delete m_pool;
+ delete m_tokenStream;
+}
+
+QString ParseSession::contents() const
+{
+ return m_contents;
+}
+
+void ParseSession::setContents(const QString& contents)
+{
+ m_contents = contents;
+}
+
+void ParseSession::setCurrentDocument(const QString& filename)
+{
+ m_currentDocument = filename;
+}
+
+bool ParseSession::readFile(const QString& filename, const char* codec)
+{
+ m_currentDocument = filename;
+
+ QFile f(filename);
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ kDebug() << "Couldn't open project file:" << filename;
+ return false;
+ }
+ QTextStream s(&f);
+ if (codec)
+ s.setCodec(QTextCodec::codecForName(codec));
+ m_contents = s.readAll();
+ return true;
+}
+void ParseSession::setDebug(bool debug)
+{
+ m_debug = debug;
+}
+
+TokenStream* ParseSession::tokenStream() const
+{
+ return m_tokenStream;
+}
+
+
+Parser* ParseSession::createParser(int initialState)
+{
+ Parser* parser = new Parser;
+ parser->setTokenStream(m_tokenStream);
+ parser->setMemoryPool(m_pool);
+ parser->setDebug(m_debug);
+ parser->setCurrentDocument(m_currentDocument);
+
+ parser->tokenize(m_contents, initialState);
+ return parser;
+}
+
+bool ParseSession::parse(erlang::FormAst** ast)
+{
+ Parser* parser = createParser();
+ FormAst* erlangAst;
+ bool matched = parser->parseForm(&erlangAst);
+ if (matched) {
+ kDebug() << "Successfully parsed";
+ *ast = erlangAst;
+ } else {
+ *ast = 0;
+ parser->expectedSymbol(AstNode::FormKind, "module declaration");
+ kDebug() << "Couldn't parse content";
+ }
+ m_problems = parser->problems();
+ delete parser;
+ return matched;
+}
+
+KDevelop::SimpleCursor ParseSession::positionAt(qint64 offset) const
+{
+ qint64 line, column;
+ m_tokenStream->locationTable()->positionAt(offset, &line, &column);
+ return KDevelop::SimpleCursor(line, column);
+}
+
+QString ParseSession::symbol(qint64 token) const
+{
+ const TokenStream::Token& tok = m_tokenStream->at(token);
+ return m_contents.mid(tok.begin, tok.end - tok.begin + 1);
+}
+
+QString ParseSession::symbol(AstNode* node) const
+{
+ const TokenStream::Token& startTok = m_tokenStream->at(node->startToken);
+ const TokenStream::Token& endTok = m_tokenStream->at(node->endToken);
+ return m_contents.mid(startTok.begin, endTok.end - startTok.begin + 1);
+}
+
+QString ParseSession::docComment(qint64 token) const
+{
+ const TokenStream::Token& tok = m_tokenStream->at(token);
+ if (!tok.docCommentEnd) return QString();
+ return m_contents.mid(tok.docCommentBegin, tok.docCommentEnd - tok.docCommentBegin + 1);
+}
+
+QList<KDevelop::ProblemPointer> ParseSession::problems()
+{
+ return m_problems;
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/main.cpp (revision 1522570)
@@ -0,0 +1,201 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
+ * Copyright 2009 Milian Wolff <mail@milianw.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "parsesession.h"
+#include "erlanglexer.h"
+#include "erlangparser.h"
+//#include "cssdebugvisitor.h"
+#include "erlangast.h"
+//#include "csstokentext.h"
+
+#include <QFile>
+#include <QString>
+#include <QStringList>
+#include <QDebug>
+#include <iostream>
+#include <QTextCodec>
+
+using namespace erlang;
+
+void showUsage(char**);
+
+QTextStream qout(stdout);
+QTextStream qerr(stderr);
+QTextStream qin(stdin);
+
+class ErlangParser {
+public:
+ ErlangParser(const bool debug, const bool printTokens)
+ : m_debug(debug), m_printTokens(printTokens)
+ {
+ m_session.setDebug(debug);
+ }
+
+ /// parse contents of a file
+ void parseFile( const QString &fileName )
+ {
+ if (!m_session.readFile(fileName, "utf-8")) {
+ qerr << "Can't open file " << fileName << endl;
+ exit(255);
+ } else {
+ qout << "Parsing file " << fileName << endl;
+ }
+ runSession();
+ }
+
+ /// parse code directly
+ void parseCode( const QString &code )
+ {
+ m_session.setContents(code);
+
+ qout << "Parsing input" << endl;
+ runSession();
+ }
+
+private:
+ /**
+ * actually run the parse session
+ */
+ void runSession()
+ {
+ if (m_printTokens) {
+ erlang::TokenStream tokenStream;
+
+ Lexer lexer(&tokenStream, m_session.contents());
+ int token;
+ while ((token = lexer.nextTokenKind())) {
+ Parser::Token &t = tokenStream.push();
+ //t.begin = lexer.tokenBegin();
+ //t.end = lexer.tokenEnd();
+ t.kind = token;
+ printToken(token, lexer);
+ }
+ printToken(token, lexer);
+ if ( tokenStream.size() > 0 ) {
+ qint64 line;
+ qint64 column;
+ tokenStream.endPosition(tokenStream.size() - 1, &line, &column);
+ qDebug() << "last token endPosition: line" << line << "column" << column;
+ } else {
+ qDebug() << "empty token stream";
+ }
+ }
+
+ erlang::FormAst* ast = 0;
+ if (!m_session.parse(&ast)) {
+ qerr << "parse error" << endl;
+ exit(255);
+ } else {
+ if (m_debug) {
+ //erlang::DebugVisitor debugVisitor(m_session.tokenStream(), m_session.contents());
+ //debugVisitor.visitStart(ast);
+ }
+ qout << "successfully parsed" << endl;
+ }
+ }
+
+ void printToken(int token, const Lexer& lexer) const
+ {
+ /* int begin = lexer.tokenBegin();
+ int end = lexer.tokenEnd();
+ qout << m_session.contents().mid(begin, end - begin + 1).replace('\n', "\\n")
+ << " "+ tokenText(token) << endl;*/
+ }
+
+ erlang::ParseSession m_session;
+ const bool m_debug;
+ const bool m_printTokens;
+};
+
+int main(int argc, char* argv[])
+{
+ qout.setCodec("UTF-8");
+ qin.setCodec("UTF-8");
+
+ QStringList files;
+ bool debug = false;
+ bool printTokens = false;
+ QStringList code;
+ for (int i = 1; i < argc; i++) {
+ QString arg(argv[i]);
+ if (arg.startsWith(QString("--"))) {
+ arg = arg.mid(2);
+ if (arg == "help") {
+ showUsage(argv);
+ return 0;
+ } else if (arg == "debug") {
+ debug = true;
+ } else if (arg == "print-tokens") {
+ printTokens = true;
+ } else if (arg == "code") {
+ for (int j = i + 1; j < argc; ++j ) {
+ code << argv[j];
+ }
+ if ( code.isEmpty() ) {
+ qerr << "no code given" << endl;
+ showUsage(argv);
+ return 1;
+ }
+ break;
+ } else {
+ qerr << "unknown option: " << endl;
+ showUsage(argv);
+ return 1;
+ }
+ } else {
+ files << arg;
+ }
+ }
+
+ ErlangParser parser(debug, printTokens);
+
+ if ( !code.isEmpty() ) {
+ parser.parseCode( code.join(" ").replace("\\n", "\n") );
+ } else if ( files.isEmpty() ) {
+ files << "-";
+ }
+
+ foreach(const QString &fileName, files) {
+ if ( fileName == "-" ) {
+ if ( isatty(STDIN_FILENO) ) {
+ qerr << "no STDIN given" << endl;
+ return 255;
+ }
+ parser.parseCode( qin.readAll().toUtf8() );
+ } else {
+ parser.parseFile(fileName);
+ }
+
+ }
+ return 0;
+}
+
+void showUsage(char** argv)
+{
+ qout << "Usage: " << argv[0] << " [options] FILE" << endl;
+ qout << "" << endl;
+ qout << "--print-tokens Print all found tokens" << endl;
+ qout << "--debug Print AST" << endl;
+ qout << "--code ... All following arguments will be interpreted as CSS code." << endl
+ << " Hence put this option at the end of the list." << endl;
+ qout << "" << endl;
+ qout << "If FILE is empty or -, read from STDIN." << endl;
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp (revision 1522570)
@@ -0,0 +1,102 @@
+/* This file is part of KDevelop
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "editorintegrator.h"
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/smartrange.h>
+#include <ktexteditor/smartinterface.h>
+
+#include <language/editor/documentrange.h>
+#include <language/editor/documentrangeobject.h>
+
+#include "erlangast.h"
+#include "parsesession.h"
+
+using namespace KTextEditor;
+using namespace erlang;
+
+EditorIntegrator::EditorIntegrator()
+ : m_session(0)
+{
+}
+
+void EditorIntegrator::setParseSession(ParseSession* session)
+{
+ m_session = session;
+}
+
+KDevelop::SimpleCursor EditorIntegrator::findPosition(qint64 token, Edge edge) const
+{
+ const KDevPG::TokenStream::Token& t = m_session->tokenStream()->at(token);
+ return findPosition(t, edge);
+}
+
+KDevelop::SimpleCursor EditorIntegrator::findPosition(const KDevPG::TokenStream::Token & token, Edge edge) const
+{
+ if (edge == BackEdge) {
+ // Apparently KTE expects a range to go until _after_ the last character that should be included
+ // however the parser calculates endCol as the index _before_ the last included character, so adjust here
+ return m_session->positionAt(token.end + 1);
+ } else {
+ return m_session->positionAt(token.begin);
+ }
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(AstNode * node, RangeEdge edge)
+{
+ Q_UNUSED(edge);
+ return KDevelop::SimpleRange(findPosition(node->startToken, FrontEdge), findPosition(node->endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(qint64 token)
+{
+ return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(qint64 startToken, qint64 endToken)
+{
+ return KDevelop::SimpleRange(findPosition(startToken, FrontEdge), findPosition(endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(AstNode* from, AstNode* to)
+{
+ return KDevelop::SimpleRange(findPosition(from->startToken, FrontEdge), findPosition(to->endToken, BackEdge));
+}
+
+KDevelop::SimpleRange EditorIntegrator::findRange(const KDevPG::TokenStream::Token & token)
+{
+ return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
+}
+
+QString EditorIntegrator::tokenToString(qint64 token) const
+{
+ return m_session->symbol(token);
+}
+
+QString EditorIntegrator::nodeToString(AstNode* node) const
+{
+ return m_session->symbol(node);
+}
+
+
+ParseSession * EditorIntegrator::parseSession() const
+{
+ return m_session;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlang.g
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlang.g (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlang.g (revision 1522570)
@@ -0,0 +1,698 @@
+-------------------------------------------------------------------------------
+-- Copyright (c) 2010 Victor Vicente de Carvalho <victor.v.carvalho at gmail.com>
+--
+-- This grammar 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 grammar 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
+-- Lesser 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.
+-----------------------------------------------------------
+
+
+-----------------------------------------------------------
+-- Grammar for Erlang
+-- Parts taken from KDevelop PHP Grammar, based on
+--- erl_parse.yrl found on erlang otp source code
+-----------------------------------------------------------
+
+
+[:
+
+
+namespace KDevelop
+{
+ class DUContext;
+}
+
+:]
+
+%parser_declaration_header "QtCore/QString"
+%parser_declaration_header "kdebug.h"
+%parser_declaration_header "language/interfaces/iproblem.h"
+%parser_declaration_header "parser/tokenstream.h"
+%parser_declaration_header "parser/erlanglexer.h"
+
+------------------------------------------------------------
+-- Export macro to use the parser in a shared lib
+------------------------------------------------------------
+%export_macro "KDEVERLANGPARSER_EXPORT"
+%export_macro_header "parser/parserexport.h"
+
+------------------------------------------------------------
+-- Ast Node class members
+------------------------------------------------------------
+%ast_extra_members
+[:
+ KDevelop::DUContext* ducontext;
+
+ virtual ~AstNode() { }
+:]
+
+------------------------------------------------------------
+-- Parser class members
+------------------------------------------------------------
+
+%parserclass (public declaration)
+[:
+ /**
+ * Transform the raw input into tokens.
+ * When this method returns, the parser's token stream has been filled
+ * and any parse*() method can be called.
+ */
+ void tokenize(const QString& contents, int initialState = Lexer::DefaultState);
+
+ enum ProblemType {
+ Error,
+ Warning,
+ Info
+ };
+
+
+
+ void reportProblem( Parser::ProblemType type, const QString& message );
+ QList<KDevelop::ProblemPointer> problems() {
+ return m_problems;
+ }
+ QString tokenText(qint64 begin, qint64 end);
+ void setDebug(bool debug);
+ void setCurrentDocument(QString url);
+
+ enum InitialLexerState {
+ HtmlState = 0,
+ DefaultState = 1
+ };
+
+:]
+
+%parserclass (private declaration)
+[:
+ enum VarExpressionState {
+ Normal,
+ OnlyVariable,
+ OnlyNewObject
+ };
+
+ struct ParserState {
+ VarExpressionState varExpressionState;
+ bool varExpressionIsVariable;
+ };
+
+ QString m_contents;
+ bool m_debug;
+ QString m_currentDocument;
+ QList<KDevelop::ProblemPointer> m_problems;
+
+
+ ParserState m_state;
+:]
+
+%parserclass (constructor)
+[:
+ m_state.varExpressionState = Normal;
+ m_state.varExpressionIsVariable = false;
+:]
+
+
+%token_stream TokenStream ;;
+
+-----------------------------------------------------------
+-- List of defined tokens
+-----------------------------------------------------------
+-- keywords:
+%token AFTER("after"), BEGIN("begin"), CASE("case"), CATCH("catch"), COND("cond"),
+ END("end"), FUN("fun"), IF("if"), LET("let"), OF("of"), QUERY("query"),
+ RECEIVE("receive"), WHEN("when"), SPEC("spec"), TRY("try");;
+
+-- seperators:
+%token LBRACKET ("["), RBRACKET ("]"), LPAREN ("("),
+ RPAREN (")"), LBRACE ("{"), RBRACE ("}"),
+ COMMA (","), LEADS_TO("->"), QUESTION("?"),
+ PIPE("|"), DOUBLE_PIPE("||"), POUND_SIGN("#"), DOT("."),
+ SEMICOLON (";"), COLON(":"),DOUBLE_COLON("::"), UNDERLINE("_"),
+ BINARY_OPEN("<<"), BINARY_CLOSE(">>");;
+
+-- operators:
+%token IS_EQUAL ("=="), IS_NOT_EQUAL ("/="), EXACT_EQUATIONAL ("=:="),
+ EXACT_NOT_EQUATIONAL ("=/="), IS_SMALLER ("<"), IS_GREATER (">"),
+ IS_SMALLER_OR_EQUAL ("=<"), IS_GREATER_OR_EQUAL (">="),
+ ASSIGN ("="), PLUS ("+"), MINUS("-"),
+ LIST_ADDITION ("++"), LIST_DIFFERENCE ("--"),
+ BIT_OR("bor"), BIT_XOR ("bxor"), XOR("xor"), OR("or"),
+ SL ("bsl"), SR ("bsr"), MUL("*"), FORWARD_SLASH("/"), MOD ("%"),
+ INT_DIV("div"), INT_REM("rem"), BIT_AND("band"), AND("and"), BIT_NOT("bnot"),
+ NOT("not"), EXCLAMATION("!"), LIST_COMPREHENSION_LEADS_TO("<-"),
+ ORELSE("orelse"), ANDALSO("andalso");;
+
+-- literals and identifiers:
+%token CHAR_LITERAL("char_literal"), COMMENT("comment"),
+ WHITESPACE ("whitespace"), VARIABLE ("variable"),
+ NUM_STRING ("num string"), INTEGER_LITERAL("integer literal"),
+ STRING_LITERAL ("string literal"), ATOM_LITERAL("atom literal"),
+ HALT_COMPILER ("halt compiler");;
+
+--macros
+
+%token INCLUDE_DIRECTIVE("include"), IMPORT_DIRECTIVE("import"),
+ FILE_DIRECTIVE("file directive"), COMPILE_DIRECTIVE("compile directive"),
+ DEFINE_DIRECTIVE("define"), MODULE_DIRECTIVE("module"),
+ RECORD_DIRECTIVE("record"), UNDEF("undef"),
+ IFDEF_DIRECTIVE("ifdef macro directive"),
+ IFNDEF_DIRECTIVE("ifndef macro directive"),
+ ELSE_DIRECTIVE("else macro directive"),
+ ENDIF_DIRECTIVE("endif macro directive"), INCLUDE_LIB("include"),
+ EXPORT_DIRECTIVE("exported functions"),
+ BEHAVIOUR_DIRECTIVE("module behaviour"),
+ FLOAT_LITERAL("float literal");;
+
+-- token that makes the parser fail in any case:
+%token INVALID ("invalid token") ;;
+
+-- The actual grammar starts here.
+
+ attribute=attribute DOT form_next=form
+ | functions=functionOrRule DOT form_next=form
+ | 0
+-> form;;
+
+ MINUS ( SPEC type_spec=typeSpec
+ | module_declaration=moduleDeclaration
+ | export_declaration=exportDeclaration
+ | import_declaration=importDeclaration
+ | record_declaration=recordDeclaration
+ | file_declaration=fileDeclaration
+ | define_declaration=defineDeclaration
+ | behaviour_declaration=behaviourDeclaration
+ | attribute_declaration=attributeDeclaration
+ | include_declaration=includeDeclaration )
+-> attribute;;
+
+ MODULE_DIRECTIVE LPAREN module_name=ATOM_LITERAL RPAREN
+-> moduleDeclaration;;
+
+ BEHAVIOUR_DIRECTIVE LPAREN behaviour=ATOM_LITERAL RPAREN
+-> behaviourDeclaration;;
+
+
+ EXPORT_DIRECTIVE LPAREN LBRACKET (#exported_functions=functionSlashArity @ COMMA | 0) RBRACKET RPAREN
+-> exportDeclaration;;
+
+ function_name=ATOM_LITERAL FORWARD_SLASH function_arity=INTEGER_LITERAL
+-> functionSlashArity;;
+
+ IMPORT_DIRECTIVE LPAREN module_name=ATOM_LITERAL COMMA #imported_functions=functionSlashArity @ COMMA RPAREN
+-> importDeclaration;;
+
+ RECORD_DIRECTIVE LPAREN record_name=ATOM_LITERAL COMMA type_record_fields=typedRecordFields RPAREN
+-> recordDeclaration;;
+
+ FILE_DIRECTIVE LPAREN file_name=STRING_LITERAL COMMA line=INTEGER_LITERAL RPAREN
+-> fileDeclaration;;
+
+ DEFINE_DIRECTIVE LPAREN define_name=VARIABLE (argument_list=argumentList | 0 ) COMMA expression=expr RPAREN
+-> defineDeclaration;;
+
+ ATOM_LITERAL LPAREN name=STRING_LITERAL COMMA line=INTEGER_LITERAL RPAREN
+-> attributeDeclaration;;
+
+ INCLUDE_DIRECTIVE LPAREN STRING_LITERAL RPAREN
+-> includeDeclaration;;
+
+ SPEC
+ | literal=ATOM_LITERAL
+-> atom1;;
+
+ expr=expr ( COMMA LBRACE typed_exprs=typedExprs RBRACE | DOUBLE_COLON top_type=topType)
+-> typedAttrVal;;
+
+ try/rollback(LPAREN expr=expr COMMA exprs=exprs RPAREN)
+ catch(expr=expr ( COMMA exprs=exprs | 0 ))
+-> attrVal;;
+
+ (LPAREN | 0) spec_fun=specFun types_sigs=typeSigs (RPAREN | 0)
+-> typeSpec;;
+
+ atom1 ( COLON ATOM_LITERAL | 0 )
+-> specFun;;
+
+ #e=exprOrTypedExpr @ COMMA
+-> typedExprs;;
+
+ typed_expr=typedExpr
+ | expr=expr
+-> exprOrTypedExpr;;
+
+ LBRACE typed_exprs=typedExprs RBRACE
+-> typedRecordFields;;
+
+ DOUBLE_COLON top_type=topType
+-> typedExpr;;
+
+ #ts=typeSig @ SEMICOLON
+->typeSigs;;
+
+ fun_type=funType (WHEN type_guards=typeGuards | 0)
+-> typeSig;;
+
+ #tg=typeGuard @ COMMA
+-> typeGuards;;
+
+ atom1 LPAREN top_type=topTypes RPAREN
+-> typeGuard;;
+
+ #tt=topType @ COMMA
+-> topTypes;;
+
+ (VARIABLE DOUBLE_COLON | 0) top_type100=topType100
+-> topType;;
+
+ type=type ( PIPE top_type100=topType100 | 0 )
+->topType100;;
+
+ LPAREN top_type=topType RPAREN
+ | VARIABLE
+ | atom1 ( LPAREN (top_types=topTypes | 0) RPAREN
+ | COLON atom1 LPAREN (top_types=topTypes | 0) RPAREN
+ | 0)
+ | LBRACKET (top_type=topType (COMMA DOT DOT DOT | 0) | 0) RBRACKET
+ | LBRACE (top_types=topTypes | 0 ) RBRACE
+ | POUND_SIGN atom1 LBRACE (field_types=fieldTypes | 0 ) RBRACE
+ | binary_type=binaryType
+ | INTEGER_LITERAL ( DOT DOT INTEGER_LITERAL | 0 )
+ | FUN LPAREN (fun_type100=funType100 | 0) RPAREN
+-> type;;
+
+ LPAREN (DOT DOT DOT | (top_types=topTypes | 0)) RPAREN LEADS_TO top_type=topType
+-> funType100;;
+
+ LPAREN (top_types=topTypes | 0) RPAREN LEADS_TO top_type=topType
+-> funType;;
+
+ #ft=fieldType @ COMMA
+-> fieldTypes;;
+
+ atom1 DOUBLE_COLON top_type=topType
+-> fieldType;;
+
+ BINARY_OPEN ( VARIABLE COLON ( INTEGER_LITERAL ( COMMA bin_unit_type=binUnitType | 0) | bin_unit_type=binUnitType ) | 0 ) BINARY_CLOSE
+-> binaryType;;
+
+ VARIABLE COLON
+-> binBaseType;;
+
+ VARIABLE MUL INTEGER_LITERAL
+-> binUnitType;;
+
+ #fc=functionOrRuleClause @ SEMICOLON
+-> functionOrRule;;
+
+ function_name=atom1 clause_args=clauseArgs clause_guard=clauseGuard (body=clauseBody | rule_body=ruleBody)
+->functionOrRuleClause;;
+
+ clause_list=clauseList
+-> clauseArgs;;
+
+ LPAREN (arg_exprs=argExprs | 0) RPAREN
+-> clauseList;;
+
+ #arg=expr @ COMMA
+-> argExprs;;
+
+ WHEN (#guards=guard @ SEMICOLON) | 0
+-> clauseGuard;;
+
+ LEADS_TO exprs=exprs
+-> clauseBody;;
+
+%< expr700
+%pre CATCH 50
+%bin ASSIGN 100 %right
+%bin EXCLAMATION 100 %right
+%bin ORELSE 150 %right
+%bin ANDALSO 160 %right
+%bin ?[: compAllowed :] IS_EQUAL [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] IS_GREATER [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] IS_GREATER_OR_EQUAL [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] IS_NOT_EQUAL [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] IS_SMALLER [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] IS_SMALLER_OR_EQUAL [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] EXACT_NOT_EQUATIONAL [: compAllowed = false; :] 200 %left
+%bin ?[: compAllowed :] EXACT_EQUATIONAL [: compAllowed = false; :] 200 %left
+%bin LIST_ADDITION 300 %right
+%bin LIST_DIFFERENCE 300 %right
+%bin PLUS 400 %right
+%bin MINUS 400 %right
+%bin BIT_OR 400 %right
+%bin BIT_XOR 400 %right
+%bin SL 400 %right
+%bin SR 400 %right
+%bin OR 400 %right
+%bin XOR 400 %right
+%bin FORWARD_SLASH 500 %right
+%bin MUL 500 %right
+%bin INT_DIV 500 %right
+%bin INT_REM 500 %right
+%bin BIT_AND 500 %right
+%bin AND 500 %right
+%pre ?[: preAllowed :] PLUS [: preAllowed = false; :] 600
+%pre ?[: preAllowed :] MINUS [: preAllowed = false; :] 600
+%pre ?[: preAllowed :] BIT_NOT [: preAllowed = false; :] 600
+%pre ?[: preAllowed :] NOT [: preAllowed = false; :] 600
+%> expr [:
+ bool preAllowed = true;
+ bool compAllowed = true;
+:];;
+
+ PLUS
+ | MINUS
+ | BIT_NOT
+ | NOT
+-> prefixOp ;;
+
+ try/rollback(record_expr=recordExpr)
+ catch(try/rollback(functionCall=functionCall)
+ catch(expr800=expr800))
+-> expr700;;
+
+ expr900=expr900 ( COLON expr_max=exprMax | 0)
+-> expr800;;
+
+ DOT atom1 expr900a=expr900a
+ | expr_max=exprMax
+-> expr900;;
+
+ DOT atom1 expr900a=expr900a | expr_max=exprMax expr900a=expr900a | 0
+-> expr900a;;
+
+ var=variable
+ | atomic=atomic
+ | try/rollback(binary=binary)
+ catch(binary_comprehension=binaryComprehension)
+ | try/rollback(LBRACKET (expr=expr tail=tail | RBRACKET))
+ catch(list_comprehension=listComprehension)
+ | tuple=tuple
+ | LPAREN expr=expr RPAREN
+ | BEGIN exprs=exprs END
+ | if_expr=ifExpr
+ | case_expr=caseExpr
+ | receive_expr=receiveExpr
+ | fun_expr=funExpr
+ | try_expr=tryExpr
+ | query_expr=queryExpr
+ | QUESTION define_name=VARIABLE (define_function=argumentList | 0)
+-> exprMax;;
+
+ literal=VARIABLE | UNDERLINE
+-> variable;;
+
+ RBRACKET
+ | PIPE expr=expr RBRACKET
+ | COMMA expr=expr tail=tail
+-> tail;;
+
+ BINARY_OPEN ( bin_elements=binElements | 0 ) BINARY_CLOSE
+-> binary;;
+
+ #be=binElement @ COMMA
+-> binElements;;
+
+ bit_expr=bitExpr opt_bit_size_expr=optBitSizeExpr opt_bit_type_list=optBitTypeList
+-> binElement;;
+
+ (prefix_op=prefixOp | 0) expr_max=exprMax
+-> bitExpr;;
+
+ COLON bit_size_expr=bitSizeExpr | 0
+-> optBitSizeExpr;;
+
+ FORWARD_SLASH bit_type_list=bitTypeList | 0
+-> optBitTypeList;;
+
+ bit_type=bitType (MINUS bit_type_list=bitTypeList | 0 )
+-> bitTypeList;;
+
+ atom1 (COLON INTEGER_LITERAL | 0)
+-> bitType;;
+
+ expr_max=exprMax
+-> bitSizeExpr;;
+
+ LBRACKET expr=expr DOUBLE_PIPE lc_exprs=lcExprs RBRACKET
+-> listComprehension;;
+
+ BINARY_OPEN binary=binary DOUBLE_PIPE lc_exprs=lcExprs BINARY_CLOSE
+-> binaryComprehension;;
+
+ #lc=lcExpr @ COMMA
+-> lcExprs;;
+
+
+ try/rollback(expr=expr (LIST_COMPREHENSION_LEADS_TO expr=expr | 0))
+ catch(binary=binary LIST_COMPREHENSION_LEADS_TO expr=expr)
+-> lcExpr;;
+
+ LBRACE (exprs | 0 ) RBRACE
+-> tuple;;
+
+ POUND_SIGN atom1 ( DOT atom1 | record_tuple=recordTuple )
+ | expr_max=exprMax POUND_SIGN atom1 ( DOT atom1 | record_tuple=recordTuple )
+-> recordExpr;;
+
+ LBRACE (record_fields=recordFields | 0 ) RBRACE
+-> recordTuple;;
+
+ #rf=recordField @ COMMA
+-> recordFields;;
+
+ VARIABLE ASSIGN expr=expr
+ | atom1 ASSIGN expr=expr
+-> recordField;;
+
+ expr800=expr800 argument_list=argumentList
+-> functionCall;;
+
+ IF if_clauses=ifClauses END
+-> ifExpr;;
+
+ #ic=ifClause @ SEMICOLON
+-> ifClauses;;
+
+ guard=guard clause_body=clauseBody
+-> ifClause;;
+
+ CASE expr=expr OF cr_clauses=crClauses END
+-> caseExpr;;
+
+ #cc=crClause @ SEMICOLON
+-> crClauses;;
+
+ expr clause_guard=clauseGuard clause_body=clauseBody
+-> crClause;;
+
+ RECEIVE (cr_clauses=crClauses | 0) (AFTER expr=expr clause_body=clauseBody | 0) END
+-> receiveExpr;;
+
+ FUN (atom1 (FORWARD_SLASH INTEGER_LITERAL | COLON atom1 FORWARD_SLASH INTEGER_LITERAL)
+ | funClauses END)
+-> funExpr;;
+
+ #fc=funClause @ SEMICOLON
+-> funClauses;;
+
+ argument_list=argumentList clause_guard=clauseGuard clause_body=clauseBody
+-> funClause;;
+
+ TRY exprs=exprs (OF cr_clauses=crClauses | 0 ) try_catch=tryCatch
+-> tryExpr;;
+
+ CATCH try_clauses=tryClauses (AFTER exprs=exprs | 0) END
+ | AFTER exprs=exprs END
+-> tryCatch;;
+
+ #tc=tryClause @ SEMICOLON
+-> tryClauses;;
+
+-- Using LA(2) to remove ambiguities with expr
+ (?[:LA(2).kind == Token_COLON:] atom1 COLON expr=expr | ?[:LA(2).kind == Token_COLON:] VARIABLE COLON expr=expr | expr=expr) clause_guard=clauseGuard clause_body=clauseBody
+-> tryClause;;
+
+ QUERY list_comprehension=listComprehension END
+-> queryExpr;;
+
+ LPAREN (exprs=exprs | 0) RPAREN
+-> argumentList;;
+
+ #e=expr @ COMMA
+-> exprs;;
+
+ #guard=exprs
+-> guard;;
+
+ CHAR_LITERAL
+ | (PLUS|MINUS|0) INTEGER_LITERAL
+ | FLOAT_LITERAL
+ | ATOM_LITERAL
+ | #strings=STRING_LITERAL
+-> atomic;;
+
+ #rc=ruleClause @ SEMICOLON
+-> ruleClauses;;
+
+ atom1 clause_args=clauseArgs clause_guard=clauseGuard rule_body=ruleBody
+-> ruleClause;;
+
+ COLON MINUS lc_exprs=lcExprs
+-> ruleBody;;
+
+-----------------------------------------------------------------
+-- Code segments copied to the implementation (.cpp) file.
+-- If existent, kdevelop-pg's current syntax requires this block
+-- to occur at the end of the file.
+-----------------------------------------------------------------
+
+[:
+
+#include <QtCore/QDebug>
+#include <KTextEditor/Range>
+
+namespace erlang
+{
+
+void Parser::tokenize(const QString& contents, int initialState)
+{
+ m_contents = contents;
+ Lexer lexer(tokenStream, contents, initialState);
+ int kind = Parser::Token_EOF;
+ int lastDocCommentBegin;
+ int lastDocCommentEnd;
+
+ do
+ {
+ lastDocCommentBegin = 0;
+ lastDocCommentEnd = 0;
+ kind = lexer.nextTokenKind();
+ while (kind == Parser::Token_WHITESPACE || kind == Parser::Token_COMMENT) {
+ kind = lexer.nextTokenKind();
+ }
+ if ( !kind ) // when the lexer returns 0, the end of file is reached
+ {
+ kind = Parser::Token_EOF;
+ }
+ Parser::Token &t = tokenStream->push();
+ t.begin = lexer.tokenBegin();
+ t.end = lexer.tokenEnd();
+ t.kind = kind;
+ if ( m_debug ) qDebug() << kind << tokenText(t.begin,t.end) << t.begin << t.end;
+ }
+ while ( kind != Parser::Token_EOF );
+
+ yylex(); // produce the look ahead token
+}
+
+QString Parser::tokenText(qint64 begin, qint64 end)
+{
+ return m_contents.mid(begin,end-begin+1);
+}
+
+void Parser::reportProblem( Parser::ProblemType type, const QString& message )
+{
+ if (type == Error)
+ qDebug() << "** ERROR:" << message;
+ else if (type == Warning)
+ qDebug() << "** WARNING:" << message;
+ else if (type == Info)
+ qDebug() << "** Info:" << message;
+
+ qint64 sLine;
+ qint64 sCol;
+ qint64 index = tokenStream->index()-1;
+ tokenStream->startPosition(index, &sLine, &sCol);
+ qint64 eLine;
+ qint64 eCol;
+ tokenStream->endPosition(index, &eLine, &eCol);
+ KDevelop::Problem *p = new KDevelop::Problem();
+ p->setSource(KDevelop::ProblemData::Parser);
+ switch ( type ) {
+ case Error:
+ p->setSeverity(KDevelop::ProblemData::Error);
+ break;
+ case Warning:
+ p->setSeverity(KDevelop::ProblemData::Warning);
+ break;
+ case Info:
+ p->setSeverity(KDevelop::ProblemData::Hint);
+ break;
+ }
+ p->setDescription(message);
+ p->setFinalLocation(KDevelop::DocumentRange(m_currentDocument, KTextEditor::Range(sLine, sCol, eLine, eCol+1)));
+ m_problems << KDevelop::ProblemPointer(p);
+}
+
+
+// custom error recovery
+void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
+{
+ reportProblem( Parser::Error, QString("Expected token \"%1\"").arg(name));
+}
+
+void Parser::expectedSymbol(int /*expectedSymbol*/, const QString& name)
+{
+ qint64 line;
+ qint64 col;
+ qint64 index = tokenStream->index()-1;
+ Token &token = tokenStream->at(index);
+ kDebug() << "token starts at:" << token.begin;
+ kDebug() << "index is:" << index;
+ tokenStream->startPosition(index, &line, &col);
+ QString tokenValue = tokenText(token.begin, token.end);
+ qint64 eLine;
+ qint64 eCol;
+ tokenStream->endPosition(index, &eLine, &eCol);
+ reportProblem( Parser::Error,
+ QString("Expected symbol \"%1\" (current token: \"%2\" [%3] at %4:%5 - %6:%7)")
+ .arg(name)
+ .arg(token.kind != 0 ? tokenValue : "EOF")
+ .arg(token.kind)
+ .arg(line)
+ .arg(col)
+ .arg(eLine)
+ .arg(eCol));
+}
+
+void Parser::setDebug( bool debug )
+{
+ m_debug = debug;
+}
+
+void Parser::setCurrentDocument(QString url)
+{
+ m_currentDocument = url;
+}
+
+Parser::ParserState *Parser::copyCurrentState()
+{
+ ParserState *state = new ParserState();
+ state->varExpressionState = m_state.varExpressionState;
+ state->varExpressionIsVariable = m_state.varExpressionIsVariable;
+ return state;
+}
+
+void Parser::restoreState( Parser::ParserState* state)
+{
+ m_state.varExpressionState = state->varExpressionState;
+ m_state.varExpressionIsVariable = state->varExpressionIsVariable;
+}
+
+} // end of namespace erlang
+
+:]
+
+-- kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp (revision 1522570)
@@ -0,0 +1,503 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "erlanglexer.h"
+
+#include "erlanglexer.h"
+#include "tokenstream.h"
+#include <erlangparser.h>
+
+#include <QtCore/QString>
+#include <QtCore/QStringList>
+#include <QtCore/QRegExp>
+#include <QtCore/QDebug>
+
+#include <iostream>
+
+namespace erlang
+{
+
+Lexer::Lexer(TokenStream* tokenStream, const QString& content, int initialState):
+ m_content(content), m_tokenStream(tokenStream),
+ m_curpos(0), m_contentSize(m_content.size()),
+ m_tokenBegin(0), m_tokenEnd(0), m_haltCompiler(0)
+{
+ pushState(ErrorState);
+ pushState(initialState);
+}
+
+int Lexer::state(int deepness) const
+{
+ return m_state.at(m_state.size() - deepness - 1);
+}
+void Lexer::printState()
+{
+ int s = state();
+ if (s == ErrorState)
+ qDebug() << "ErrorState";
+ else if (s == DefaultState)
+ qDebug() << "DefaultState";
+ else if (s == String)
+ qDebug() << "String";
+}
+
+void Lexer::pushState(int state)
+{
+ m_state.push(state);
+}
+
+void Lexer::popState()
+{
+ m_state.pop();
+}
+
+bool Lexer::processCharLiteral(QChar* it)
+{
+ return it->unicode() != '\n';
+}
+
+bool Lexer::isValidNumeric(QChar* it, bool isExponential, bool hasRadix, bool hasPoint, bool& hasUnusable)
+{
+ unsigned int nextValidChar = 1;
+
+ bool nextIsValid = m_curpos + 1 < m_contentSize;
+
+ while (nextIsValid && (
+ (it + nextValidChar)->isSpace()
+ || (it + nextValidChar)->unicode() == '\t'
+ || (it + nextValidChar)->unicode() == '\n'))
+ {
+ nextValidChar++;
+ nextIsValid = nextValidChar < m_contentSize;
+ hasUnusable = true;
+ }
+
+ return it->isDigit()
+ || (it->unicode() == '.' && nextIsValid && (it + 1)->isDigit())
+ || (it->unicode() == '#' && nextIsValid && (it + 1)->isDigit())
+ || ((it->unicode() == '-' || it->unicode() == '+') && nextIsValid && (it + nextValidChar)->isDigit())
+ || (nextIsValid && isExponential && hasPoint && (it->unicode() == '+' || it->unicode() == '-') && (it + nextValidChar)->isDigit())
+ || (hasRadix && !hasPoint && (it->toLower() == 'a' || it->toLower() == 'b' ||
+ it->toLower() == 'c' || it->toLower() == 'd' ||
+ it->toLower() == 'e' || it->toLower() == 'f'));
+
+}
+
+int Lexer::nextTokenKind()
+{
+ int token = Parser::Token_INVALID;
+ if (m_curpos >= m_contentSize) {
+ m_tokenBegin = -1;
+ m_tokenEnd = -1;
+ createNewline(m_curpos);
+ return 0;
+ }
+ QChar* it = m_content.data();
+ it += m_curpos;
+ m_tokenBegin = m_curpos;
+
+ if (it->isSpace())
+ {
+ token = Parser::Token_WHITESPACE;
+ while (m_curpos < m_contentSize && it->isSpace())
+ {
+ if (it->unicode() == '\n')
+ {
+ createNewline(m_curpos);
+ }
+ it++;
+ m_curpos++;
+ }
+ m_curpos--;
+ }
+ else if (it->isDigit())
+ {
+ QRegExp regex("\\d+\\.\\d+|\\d+\\.\\d+|\\d+\\.\\d+e-?\\d+|\\d+\\.\\d+e-?\\d+|[\\dABCDEF]+#\\d{1,2}|\\d+");
+
+ if ( regex.indexIn(m_content, m_curpos) != -1)
+ {
+ kDebug() << "Matched: " << regex.cap();
+
+ m_curpos += regex.matchedLength() - 1;
+ token = Parser::Token_INTEGER_LITERAL;
+ }
+ }
+ else if (it->unicode() == '-')
+ {
+ if ((it + 1)->unicode() == '>')
+ {
+ m_curpos++;
+ token = Parser::Token_LEADS_TO;
+ }
+ else if ((it + 1)->unicode() == '-')
+ {
+ m_curpos++;
+ token = Parser::Token_LIST_DIFFERENCE;
+ }
+ else
+ {
+ token = Parser::Token_MINUS;
+ }
+ }
+ else if (it->unicode() == '+')
+ {
+ if ((it + 1)->unicode() == '+')
+ {
+ m_curpos++;
+ token = Parser::Token_LIST_ADDITION;
+ }
+ else
+ {
+ token = Parser::Token_PLUS;
+ }
+ }
+ else if (it->unicode() == '$' && processCharLiteral(it + 1))
+ {
+ token = Parser::Token_CHAR_LITERAL;
+ }
+ else if (it->unicode() == '}')
+ {
+ token = Parser::Token_RBRACE;
+ if (state() == Tuple)
+ {
+ popState();
+ }
+ }
+ else if (it->unicode() == '_')
+ {
+ token = Parser::Token_UNDERLINE;
+ }
+ else if (it->unicode() == '{')
+ {
+ token = Parser::Token_LBRACE;
+ pushState(Tuple);
+ }
+ else if (it->unicode() == ')')
+ {
+ token = Parser::Token_RPAREN;
+ }
+ else if (it->unicode() == '(')
+ {
+ token = Parser::Token_LPAREN;
+ }
+ else if (it->unicode() == ']')
+ {
+ token = Parser::Token_RBRACKET;
+ }
+ else if (it->unicode() == '[')
+ {
+ token = Parser::Token_LBRACKET;
+ }
+ else if (it->unicode() == ',')
+ {
+ token = Parser::Token_COMMA;
+ }
+ else if (it->unicode() == '#')
+ {
+ token = Parser::Token_POUND_SIGN;
+ }
+ else if (it->unicode() == '!')
+ {
+ token = Parser::Token_EXCLAMATION;
+ }
+ else if (it->unicode() == '<')
+ {
+ if ( (it + 1)->unicode() == '-')
+ {
+ m_curpos += 1;
+ token = Parser::Token_LIST_COMPREHENSION_LEADS_TO;
+ }
+ else if ( (it + 1)->unicode() == '<' )
+ {
+ m_curpos += 1;
+ token = Parser::Token_BINARY_OPEN;
+ }
+ else
+ {
+ token = Parser::Token_IS_SMALLER;
+ }
+ }
+ else if (it->unicode() == '>')
+ {
+ if ((it + 1)->unicode() == '=')
+ {
+ m_curpos++;
+ token = Parser::Token_IS_GREATER_OR_EQUAL;
+ }
+ else if ( (it + 1)->unicode() == '>' )
+ {
+ m_curpos += 1;
+ token = Parser::Token_BINARY_CLOSE;
+ }
+ else
+ {
+ token = Parser::Token_IS_GREATER;
+ }
+ }
+ else if (it->unicode() == '?')
+ {
+ token = Parser::Token_QUESTION;
+ }
+ else if (it->unicode() == '%')
+ {
+ token = Parser::Token_COMMENT;
+ while (it->unicode() != '\n')
+ {
+ m_curpos++;
+ it++;
+ }
+ createNewline(m_curpos);
+ }
+ else if (it->unicode() == '/')
+ {
+ if ((it + 1)->unicode() == '=')
+ {
+ token = Parser::Token_IS_NOT_EQUAL;
+ }
+ else
+ {
+ token = Parser::Token_FORWARD_SLASH;
+ }
+ }
+ else if (it->unicode() == '*')
+ {
+ token = Parser::Token_MUL;
+ }
+ else if (it->unicode() == '|')
+ {
+ if ((it + 1)->unicode() == '|')
+ {
+ m_curpos++;
+ token = Parser::Token_DOUBLE_PIPE;
+ }
+ else
+ {
+ token = Parser::Token_PIPE;
+ }
+ }
+ else if (it->unicode() == ':')
+ {
+ if ( (it + 1)->unicode() == ':')
+ {
+ m_curpos += 1;
+ token = Parser::Token_DOUBLE_COLON;
+ }
+ else
+ {
+ token = Parser::Token_COLON;
+ }
+ }
+ else if (it->unicode() == '.')
+ {
+ token = Parser::Token_DOT;
+ }
+ else if (it->unicode() == ';')
+ {
+ token = Parser::Token_SEMICOLON;
+ }
+ else if (it->unicode() == '\'')
+ {
+ token = Parser::Token_ATOM_LITERAL;
+ it++;
+ m_curpos++;
+ int startPos = m_curpos;
+ while (m_curpos < m_contentSize
+ && (it->unicode() != '\'')) {
+ if (it->unicode() == '\n') createNewline(m_curpos);
+ it++;
+ m_curpos++;
+ }
+ // if the string is never terminated, make sure we don't overflow the boundaries
+ if ( m_curpos == m_contentSize ) {
+ --m_curpos;
+ }
+ }
+ else if (it->unicode() == '"')
+ {
+ token = Parser::Token_STRING_LITERAL;
+ it++;
+ m_curpos++;
+ while (m_curpos < m_contentSize
+ && (it->unicode() != '\"')) {
+ if (it->unicode() == '\n') createNewline(m_curpos);
+ it++;
+ m_curpos++;
+ }
+ // if the string is never terminated, make sure we don't overflow the boundaries
+ if ( m_curpos == m_contentSize ) {
+ --m_curpos;
+ }
+ }
+ else if (it->unicode() == '=')
+ {
+ if ((it + 1)->unicode() == '=')
+ {
+ m_curpos++;
+ token = Parser::Token_IS_EQUAL;
+ }
+ else if ((it + 1)->unicode() == '<') {
+ m_curpos++;
+ token = Parser::Token_IS_SMALLER_OR_EQUAL;
+ }
+ else if ((it + 1)->unicode() == ':' && (it + 2)->unicode() == '=')
+ {
+ m_curpos += 2;
+ token = Parser::Token_EXACT_EQUATIONAL;
+ }
+ else if ((it + 1)->unicode() == '/' && (it + 2)->unicode() == '=')
+ {
+ m_curpos += 2;
+ token = Parser::Token_EXACT_NOT_EQUATIONAL;
+ }
+ else
+ {
+ token = Parser::Token_ASSIGN;
+ }
+ }
+ else if (it->isLetter() && it->isUpper())
+ {
+ QString name;
+ while (m_curpos < m_contentSize && (isValidVariableIdentifier(it))) {
+ name.append(*it);
+ it++;
+ m_curpos++;
+ }
+ m_curpos--;
+ token = Parser::Token_VARIABLE;
+ }
+ else if (it->isLetter() && it->isLower())
+ {
+ QString name;
+ while (m_curpos < m_contentSize && (isValidVariableIdentifier(it))) {
+ name.append(*it);
+ it++;
+ m_curpos++;
+ }
+
+ m_curpos--;
+
+ if (name == "after") {
+ token = Parser::Token_AFTER;
+ } else if (name == "begin") {
+ token = Parser::Token_BEGIN;
+ } else if (name == "case") {
+ token = Parser::Token_CASE;
+ } else if (name == "if") {
+ token = Parser::Token_IF;
+ } else if (name == "catch") {
+ token = Parser::Token_CATCH;
+ } else if (name == "cond") {
+ token = Parser::Token_COND;
+ } else if (name == "end") {
+ token = Parser::Token_END;
+ } else if (name == "fun") {
+ token = Parser::Token_FUN;
+ } else if (name == "let") {
+ token = Parser::Token_LET;
+ } else if (name == "of") {
+ token = Parser::Token_OF;
+ } else if (name == "catch") {
+ token = Parser::Token_CATCH;
+ } else if (name == "receive") {
+ token = Parser::Token_RECEIVE;
+ } else if (name == "when") {
+ token = Parser::Token_WHEN;
+ } else if (name == "div") {
+ token = Parser::Token_INT_DIV;
+ } else if (name == "rem") {
+ token = Parser::Token_INT_REM;
+ } else if (name == "or") {
+ token = Parser::Token_OR;
+ } else if (name == "xor") {
+ token = Parser::Token_XOR;
+ } else if (name == "bor") {
+ token = Parser::Token_BIT_OR;
+ } else if (name == "bxor") {
+ token = Parser::Token_BIT_XOR;
+ } else if (name == "query") {
+ token = Parser::Token_QUERY;
+ } else if (name == "bsl") {
+ token = Parser::Token_SL;
+ } else if (name == "bsr") {
+ token = Parser::Token_SR;
+ } else if (name == "and") {
+ token = Parser::Token_AND;
+ } else if (name == "band") {
+ token = Parser::Token_BIT_AND;
+ } else if (name == "not") {
+ token = Parser::Token_NOT;
+ } else if (name == "bnot") {
+ token = Parser::Token_BIT_NOT;
+ } else if (name == "orelse") {
+ token = Parser::Token_ORELSE;
+ } else if (name == "andalso") {
+ token = Parser::Token_ANDALSO;
+ } else if (name == "module") {
+ token = Parser::Token_MODULE_DIRECTIVE;
+ } else if (name == "include") {
+ token = Parser::Token_INCLUDE_DIRECTIVE;
+ } else if (name == "export") {
+ token = Parser::Token_EXPORT_DIRECTIVE;
+ } else if (name == "file") {
+ token = Parser::Token_FILE_DIRECTIVE;
+ } else if (name == "record") {
+ token = Parser::Token_RECORD_DIRECTIVE;
+ } else if (name == "include") {
+ token = Parser::Token_INCLUDE_DIRECTIVE;
+ } else if (name == "behaviour"){
+ token = Parser::Token_BEHAVIOUR_DIRECTIVE;
+ } else if (name == "define"){
+ token = Parser::Token_DEFINE_DIRECTIVE;
+ }
+ else
+ {
+ token = Parser::Token_ATOM_LITERAL;
+ }
+ }
+
+ m_tokenEnd = m_curpos;
+ m_curpos++;
+
+ return token;
+}
+
+qint64 Lexer::tokenBegin() const
+{
+ return m_tokenBegin;
+}
+
+qint64 Lexer::tokenEnd() const
+{
+ return m_tokenEnd;
+}
+
+bool Lexer::isValidVariableIdentifier(QChar* it)
+{
+ return it->isLetter() || it->isDigit() || it->unicode() == '_' || it->unicode() == '@';
+}
+
+void Lexer::createNewline(int pos)
+{
+ if (m_tokenStream) m_tokenStream->locationTable()->newline(pos);
+}
+
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h (revision 1522570)
@@ -0,0 +1,29 @@
+#ifndef ERLANG_PARSERTEST_H
+#define ERLANG_PARSERTEST_H
+
+#include <QObject>
+
+namespace erlang
+{
+
+class TestParser : public QObject
+{
+ Q_OBJECT
+
+public:
+ TestParser();
+
+private Q_SLOTS:
+ /*void functionDeclaration();
+ void functionClausesDeclaration();
+ void list();
+ void testVariable();
+ void testRecord();
+ void testDefine();*/
+ void testNumeric();
+ void textExport();
+};
+
+}
+
+#endif
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp (revision 1522570)
@@ -0,0 +1,192 @@
+#include "parsertest.h"
+
+#include <QTest>
+
+#include "../parsesession.h"
+#include "../editorintegrator.h"
+
+QTEST_MAIN(erlang::TestParser)
+
+namespace erlang
+{
+
+TestParser::TestParser()
+{
+}
+
+#ifdef disabled
+void TestParser::functionDeclaration()
+{
+ erlang::ParseSession session;
+ session.setContents("my_func(VariableA, atom_b) -> ok.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+}
+
+void TestParser::functionClausesDeclaration()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\n my_func(VariableA, atom_b) -> ok; my_func(VariableA, atom_c) -> then.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\n my_func(VariableA, atom_b) -> ok; my_func() -> other_func().");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+}
+#endif
+
+void TestParser::textExport()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\n -export([start/0, start_loop/0]). function() -> ok.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+}
+
+#ifdef disabled
+void TestParser::list()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_list() -> X = [].");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ /*TODO: problempointer is crashing?
+ {
+ erlang::ParseSession session;
+ FormAst* ast = 0;
+ session.setContents("-module(test).\ntest_list() -> X = []].");
+ QVERIFY(session.parse(&ast) == false);
+ }*/
+
+ {
+ erlang::ParseSession session;
+ FormAst* ast = 0;
+
+ session.setContents("-module(test).\ntest_list() -> X = [[]].");
+ QVERIFY(session.parse(&ast) == true);
+ }
+}
+
+void TestParser::testDefine()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\n-define(MACRO, io:format(\"teste\",[])).\ntest_func() -> ?MACRO, ?MACRO, ?MACRO.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+}
+#endif
+
+void TestParser::testNumeric()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(teste_sup). \n teste(- 1 ) -> ok.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_list() -> X = 1.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_list() -> X = 11234512345235634745745623543244523.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_list() -> X = - 11234512345235634745745623543244523.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_list() -> X = 1..");
+ FormAst* ast = 0;
+
+ //QVERIFY(session.parse(&ast) == false);
+ }
+
+}
+
+#if defined disabled
+void TestParser::testVariable()
+{
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_variable() -> X = 123, @10 = 1.");
+ FormAst* ast = 0;
+
+ //QVERIFY(session.parse(&ast) == false);
+ }
+}
+
+void TestParser::testRecord()
+{
+ /*{
+ erlang::ParseSession session;
+ session.setContents("-module(test).\n-record(test, { a, b, c = 1, d = gb_trees::new() }).");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_record() -> X = #record_definition{}.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_record() -> X = #record_definition{ r_var1 = val1, r_var2 = Y }.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }
+
+ {
+ erlang::ParseSession session;
+ session.setContents("-module(test).\ntest_record() -> X = Y#record_definition.value.");
+ FormAst* ast = 0;
+
+ QVERIFY(session.parse(&ast));
+ }*/
+
+}
+#endif
+
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,34 @@
+#add_subdirectory(test)
+
+set(parser_STAT_SRCS
+ erlanglexer.cpp
+ editorintegrator.cpp
+ parsesession.cpp
+ )
+
+kdevpgqt_generate(_kdevpgList erlang NAMESPACE erlang TOKEN_TEXT
+ "${erlang_SOURCE_DIR}/parser/erlang.g"
+ "${erlang_SOURCE_DIR}/parser/erlanglexer.h"
+)
+
+set( parser_SRCS
+ ${_kdevpgList}
+)
+
+kde4_add_library( kdev4erlangparser SHARED ${parser_SRCS} ${parser_STAT_SRCS} )
+target_link_libraries( kdev4erlangparser
+ ${KDE4_KDECORE_LIBS}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+ ${KDE4_KTEXTEDITOR_LIBS}
+)
+
+kde4_add_executable( erlang-parser main.cpp )
+target_link_libraries(erlang-parser ${QT_QTCORE_LIBRARY} kdev4erlangparser)
+
+install(TARGETS kdev4erlangparser DESTINATION ${INSTALL_TARGETS_DEFAULT_ARGS})
+
+### next target
+set(parsertest_SRCS tests/parsertest.cpp)
+kde4_add_unit_test(parsertest ${parsertest_SRCS})
+target_link_libraries(parsertest kdev4erlangparser ${QT_QTTEST_LIBRARY})
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h (revision 1522570)
@@ -0,0 +1,91 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef ERLANGLEXER_H
+#define ERLANGLEXER_H
+
+#include <QtCore/QStack>
+#include <QtCore/QString>
+
+#include "parserexport.h"
+
+class QString;
+
+namespace KDevPG
+{
+class TokenStream;
+}
+
+namespace erlang
+{
+class TokenStream;
+
+/**
+ * Hand-written Lexer that generates the same tokens as php uses.
+ * This includes also a whitespace and comment token.
+ *
+ * For debugging output can be compared to php-tokens using the
+ * test/test-tokenize.php script
+ **/
+class KDEVERLANGPARSER_EXPORT Lexer
+{
+public:
+ Lexer(TokenStream *tokenStream, const QString& contents, int initialState = DefaultState);
+
+ int nextTokenKind();
+ qint64 tokenBegin() const;
+ qint64 tokenEnd() const;
+ bool isValidNumeric(QChar* it, bool isExponential, bool hasRadix, bool hasPoint, bool& hasSpaces);
+
+private:
+ QString m_content;
+ TokenStream* m_tokenStream;
+ int m_curpos;
+ int m_contentSize;
+ qint64 m_tokenBegin;
+ qint64 m_tokenEnd;
+
+ int state(int deepness = 0) const;
+ void pushState(int state);
+ void popState();
+ void printState();
+
+ bool isValidVariableIdentifier(QChar* it);
+ void createNewline(int pos);
+ bool processCharLiteral(QChar* arg1);
+
+ QStack<int> m_state;
+
+ QString m_heredocIdentifier;
+ int m_haltCompiler;
+public:
+ enum State {
+ ErrorState = -1,
+ DefaultState = 1,
+ String = 2,
+ Tuple = 3
+ };
+};
+
+}
+
+#endif
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h (revision 1522570)
@@ -0,0 +1,129 @@
+/* This file is part of KDevelop
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef ERLANGEDITORINTEGRATOR_H
+#define ERLANGEDITORINTEGRATOR_H
+
+#include <language/editor/editorintegrator.h>
+#include <language/editor/simplerange.h>
+#include "parsesession.h"
+
+#include <erlangast.h>
+#include "parserexport.h"
+#include "kdev-pg-token-stream.h"
+
+namespace erlang
+{
+
+class ParseSession;
+class AstNode;
+
+
+/**
+ * Provides facilities for easy integration of a text editor component with
+ * the information parsed from a source file.
+ *
+ * Uses a disguised singleton + stateful design.
+ *
+ * \todo introduce stacks for the state?
+ */
+class KDEVERLANGPARSER_EXPORT EditorIntegrator : public KDevelop::EditorIntegrator
+{
+public:
+ EditorIntegrator();
+ void setParseSession(ParseSession* session);
+ ParseSession* parseSession() const;
+
+ /**
+ * Finds the location and \a file where the given \a token was parsed from. This function
+ * does not change any of the EditorIntegrator's state.
+ *
+ * \param token token to locate
+ * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
+ *
+ * \returns the requested cursor relating to the start or end of the given token.
+ */
+ KDevelop::SimpleCursor findPosition(const KDevPG::TokenStream::Token& token, Edge edge = BackEdge) const;
+
+ /**
+ * Finds the location and \a file where the given \a token was parsed from.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \param token token to locate
+ * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
+ *
+ * \returns the requested cursor relating to the start or end of the given token.
+ */
+ KDevelop::SimpleCursor findPosition(qint64 token, Edge edge = BackEdge) const;
+
+ using KDevelop::EditorIntegrator::createRange;
+
+ /**
+ * Create a range encompassing the given AstNode \a node.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(AstNode* node, RangeEdge = OuterEdge);
+
+ /**
+ * Create a range encompassing the given AstNode \a nodes.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(AstNode* from, AstNode* to);
+
+ /**
+ * Create a range encompassing the given AstNode \a token.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(const KDevPG::TokenStream::Token& token);
+
+ /**
+ * Create a range encompassing the given AstNode \a token.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(qint64 token);
+
+ /**
+ * Create a range encompassing the given AstNode \a tokens.
+ * This function does not change any of the EditorIntegrator's state.
+ *
+ * \overload
+ */
+ KDevelop::SimpleRange findRange(qint64 start_token, qint64 end_token);
+
+ /**
+ * Retrieve the string represented by a token.
+ */
+ QString tokenToString(qint64 token) const;
+ QString nodeToString(AstNode *node) const;
+
+private:
+ ParseSession* m_session;
+};
+
+}
+
+#endif // PHPEDITORINTEGRATOR_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/.directory
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/.directory (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/.directory (revision 1522570)
@@ -0,0 +1,3 @@
+[Dolphin]
+Timestamp=2010,3,8,18,38,35
+ViewMode=1
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tokenstream.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tokenstream.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/tokenstream.h (revision 1522570)
@@ -0,0 +1,41 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef PHPTOKENSTREAM_H
+#define PHPTOKENSTREAM_H
+
+#include <kdev-pg-token-stream.h>
+
+namespace erlang
+{
+
+class Token : public KDevPG::Token
+{
+public:
+ qint64 docCommentBegin;
+ qint64 docCommentEnd;
+};
+
+class TokenStream : public KDevPG::TokenStreamBase<Token>
+{
+};
+
+}
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parserexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parserexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parserexport.h (revision 1522570)
@@ -0,0 +1,40 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef PARSEREXPORT_H
+#define PARSEREXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+
+#ifndef KDEVERLANGPARSER_EXPORT
+# ifdef MAKE_KDEV4PHPPARSER_LIB
+# define KDEVERLANGPARSER_EXPORT KDE_EXPORT
+# else
+# define KDEVERLANGPARSER_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif
+
+//kate: space-indent on; indent-width 4; replace-tabs on; auto-insert-doxygen on; indent-mode cstyle;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parser/parsesession.h (revision 1522570)
@@ -0,0 +1,94 @@
+/*****************************************************************************
+ * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
+ * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef ERLANG_PARSESESSION_H
+#define ERLANG_PARSESESSION_H
+
+#include <QtCore/QString>
+#include <language/editor/simplecursor.h>
+#include "erlangparser.h"
+#include "parserexport.h"
+
+namespace KDevPG
+{
+class MemoryPool;
+}
+namespace KDevelop
+{
+class SimpleCursor;
+}
+namespace erlang
+{
+class TokenStream;
+
+typedef QPair<KDevelop::DUContextPointer, KDevelop::SimpleRange> SimpleUse;
+
+class KDEVERLANGPARSER_EXPORT ParseSession
+{
+public:
+ ParseSession();
+ ~ParseSession();
+
+ void setContents(const QString& contents);
+ void setCurrentDocument(const QString& filename);
+ bool readFile(const QString& filename, const char* charset = 0);
+ void setDebug(bool);
+ TokenStream* tokenStream() const;
+ QString contents() const;
+
+ bool parse(erlang::FormAst** ast);
+ Parser* createParser(int initialState = Parser::HtmlState);
+
+ QString symbol(qint64 token) const;
+ QString symbol(AstNode* node) const;
+
+ /**
+ * Return the DocBlock before this token, if any
+ */
+ QString docComment(qint64 token) const;
+
+ /**
+ * Return the position (\a line%, \a column%) of the \a offset in the file.
+ *
+ * \note the line starts from 0.
+ */
+ KDevelop::SimpleCursor positionAt(qint64 offset) const;
+
+ QList<KDevelop::ProblemPointer> problems();
+
+ /// @TODO implement this
+ void mapAstUse(AstNode* node, const SimpleUse& use)
+ {
+ Q_UNUSED(node);
+ Q_UNUSED(use);
+ }
+
+private:
+ QString m_contents;
+ bool m_debug;
+ QString m_currentDocument;
+ KDevPG::MemoryPool* m_pool;
+ TokenStream* m_tokenStream;
+ QList<KDevelop::ProblemPointer> m_problems;
+};
+
+}
+
+#endif
+
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc -o -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cpp` -o $podir/kdeverlang.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp (revision 1522570)
@@ -0,0 +1,73 @@
+/*
+* This file is part of KDevelop
+*
+* Copyright 2010 Victor Vicente de Carvalho
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+#include "objecttype.h"
+
+#include <language/duchain/types/typeregister.h>
+
+using namespace KDevelop;
+
+namespace erlang {
+
+REGISTER_TYPE(ObjectType);
+
+ObjectType::ObjectType()
+ :KDevelop::StructureType(createData<ObjectType>())
+{
+}
+
+ObjectType::ObjectType(const ObjectType& rhs)
+ :KDevelop::StructureType(copyData<ObjectType>(*rhs.d_func()))
+{
+}
+
+ObjectType::ObjectType(ObjectTypeData& data)
+ :KDevelop::StructureType(data)
+{
+}
+
+KDevelop::AbstractType* ObjectType::clone() const
+{
+ return new ObjectType(*this);
+}
+
+uint ObjectType::hash() const
+{
+ return 8 * KDevelop::StructureType::hash();
+}
+
+QString ObjectType::toString() const
+{
+ return d_func()->m_prettyName;
+}
+
+void ObjectType::setPrettyName(const QString& name)
+{
+ d_func_dynamic()->setPrettyName(name);
+}
+
+void ObjectTypeData::setPrettyName(QString arg1)
+{
+ m_prettyName = arg1;
+}
+
+
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h (revision 1522570)
@@ -0,0 +1,64 @@
+/*
+* This file is part of KDevelop
+*
+* Copyright 2010 Victor Vicente de Carvalho
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+#ifndef OBJECTTYPE_H
+#define OBJECTTYPE_H
+
+#include <language/duchain/types/structuretype.h>
+
+namespace erlang {
+
+class ObjectTypeData: public KDevelop::StructureTypeData {
+public:
+ ObjectTypeData(): KDevelop::StructureTypeData() { }
+ ObjectTypeData(const ObjectTypeData& rhs): KDevelop::StructureTypeData(rhs) { }
+ void setPrettyName(QString arg1);
+ QString m_prettyName;
+};
+
+class ObjectType: public KDevelop::StructureType {
+public:
+ typedef TypePtr<ObjectType> Ptr;
+
+ /// Default constructor
+ ObjectType();
+ /// Copy constructor. \param rhs type to copy
+ ObjectType(const ObjectType& rhs);
+ /// Constructor using raw data. \param data internal data.
+ ObjectType(ObjectTypeData& data);
+
+ virtual AbstractType* clone() const;
+ virtual QString toString() const;
+ virtual uint hash() const;
+ void setPrettyName(const QString& name);
+ enum {
+ Identity = 60
+ };
+
+ typedef ObjectTypeData Data;
+ typedef KDevelop::StructureType BaseType;
+
+protected:
+ TYPE_DECLARE_DATA(ObjectType);
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h (revision 1522570)
@@ -0,0 +1,59 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef DECLARATIONBUILDER_H
+#define DECLARATIONBUILDER_H
+
+#include "contextbuilder.h"
+#include <language/duchain/builders/abstractdeclarationbuilder.h>
+#include <erlangast.h>
+#include <language/duchain/builders/abstractdeclarationbuilder.h>
+#include "typebuilder.h"
+
+namespace KDvelop
+{
+class Declaration;
+}
+namespace erlang
+{
+class ParseSession;
+class EditorIntegrator;
+class ClassDeclaration;
+class FunctionDeclaration;
+
+typedef KDevelop::AbstractDeclarationBuilder<AstNode, AstNode, TypeBuilder > DeclarationBuilderBase;
+
+class DeclarationBuilder : public DeclarationBuilderBase
+{
+public:
+ DeclarationBuilder(EditorIntegrator* editor);
+ DeclarationBuilder();
+
+protected:
+ virtual void visitExprMax(ExprMaxAst* node);
+ virtual void visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node);
+
+ virtual void updateCurrentType();
+};
+
+}
+
+#endif // DECLARATIONBUILDER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp (revision 1522570)
@@ -0,0 +1,78 @@
+/*
+* This file is part of KDevelop
+*
+* Copyright 2010 Victor Vicente de Carvalho
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+#include "typebuilder.h"
+
+#include <language/duchain/types/functiontype.h>
+#include "../types/objecttype.h"
+
+namespace erlang {
+
+TypeBuilder::TypeBuilder(): TypeBuilderBase()
+{
+}
+
+
+void TypeBuilder::visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node)
+{
+ KDevelop::FunctionType::Ptr functionType = KDevelop::FunctionType::Ptr(new KDevelop::FunctionType());
+ openType(functionType);
+ KDevelop::AbstractType::Ptr returnType(new ObjectType());
+ functionType->setReturnType(returnType);
+
+ TypeBuilderBase::visitFunctionOrRuleClause(node);
+
+ updateCurrentType();
+ closeType();
+
+}
+
+void TypeBuilder::visitArgExprs(ArgExprsAst* node)
+{
+ if (hasCurrentType())
+ {
+ KDevelop::DelayedType::Ptr type(new KDevelop::DelayedType());
+ QString id = editor()->parseSession()->symbol(node);
+
+
+ //We have to prevent automatic parsing and splitting by QualifiedIdentifier and Identifier
+ KDevelop::Identifier idd;
+ idd.setIdentifier(id);
+
+ KDevelop::QualifiedIdentifier ident;
+ ident.push(idd);
+
+ type->setIdentifier( KDevelop::IndexedTypeIdentifier(ident) );
+
+ openType<KDevelop::DelayedType>(type);
+ closeType();
+
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+ TypePtr<KDevelop::FunctionType> ctype = currentType<KDevelop::FunctionType>();
+ ctype->addArgument(TypePtr<KDevelop::AbstractType>::staticCast(type));
+ }
+}
+
+void TypeBuilder::updateCurrentType()
+{
+ //reimplemented in DeclarationBuilder
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp (revision 1522570)
@@ -0,0 +1,146 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "contextbuilder.h"
+
+
+
+#include <language/duchain/duchain.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/classdeclaration.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/ilanguagecontroller.h>
+#include <interfaces/icompletionsettings.h>
+
+#include <klocalizedstring.h>
+
+#include "../../parser/parsesession.h"
+#include "../../parser/editorintegrator.h"
+#include "erlangast.h"
+
+namespace erlang
+{
+
+ContextBuilder::ContextBuilder() : m_reportErrors(true)
+{
+}
+
+ContextBuilder::~ContextBuilder()
+{
+}
+
+KDevelop::QualifiedIdentifier ContextBuilder::identifierForNode(erlang::AstNode* id)
+{
+ Atom1Ast* atom = 0;
+ VariableAst* variable = 0;
+ if (( atom = dynamic_cast<Atom1Ast*>(id)) != 0)
+ {
+ return KDevelop::QualifiedIdentifier(editor()->parseSession()->symbol(atom->literal));
+ }
+ else if ((variable = dynamic_cast<VariableAst*>(id)) != 0)
+ {
+ return KDevelop::QualifiedIdentifier(editor()->parseSession()->symbol(variable->literal));
+ }
+ else
+ {
+ return KDevelop::QualifiedIdentifier();
+ }
+}
+
+KDevelop::ReferencedTopDUContext ContextBuilder::build(const KDevelop::IndexedString& url, AstNode* node,
+ KDevelop::ReferencedTopDUContext updateContext, bool useSmart)
+{
+ if ( KDevelop::ICore::self() ) {
+ m_reportErrors = KDevelop::ICore::self()->languageController()->completionSettings()->highlightSemanticProblems();
+ }
+ return ContextBuilderBase::build(url, node, updateContext, useSmart);
+}
+
+void ContextBuilder::setEditor(EditorIntegrator* editor)
+{
+ ContextBuilderBase::setEditor(editor, false);
+}
+
+KDevelop::TopDUContext* ContextBuilder::newTopContext(const KDevelop::SimpleRange& range, KDevelop::ParsingEnvironmentFile* file)
+{
+ if (!file) {
+ file = new KDevelop::ParsingEnvironmentFile(editor()->currentUrl());
+ file->setLanguage(KDevelop::IndexedString("Erlang"));
+ }
+ return new KDevelop::TopDUContext(editor()->currentUrl(), range, file);
+}
+
+void ContextBuilder::setContextOnNode(AstNode* node, KDevelop::DUContext* ctx)
+{
+ if (node)
+ {
+ node->ducontext = ctx;
+ }
+}
+
+KDevelop::DUContext* ContextBuilder::contextFromNode(erlang::AstNode* node)
+{
+ if (node)
+ {
+ return node->ducontext;
+ }
+
+ return NULL;
+}
+
+EditorIntegrator* ContextBuilder::editor() const
+{
+ return static_cast<EditorIntegrator*>(ContextBuilderBase::editor());
+}
+
+KTextEditor::Range ContextBuilder::editorFindRange(AstNode* fromRange, AstNode* toRange)
+{
+ return editor()->findRange(fromRange, toRange).textRange();
+}
+
+KDevelop::SimpleCursor ContextBuilder::startPos(AstNode* node)
+{
+ return editor()->findPosition(node->startToken, KDevelop::EditorIntegrator::FrontEdge);
+}
+
+void ContextBuilder::startVisiting(AstNode* node)
+{
+ visitNode(node);
+}
+
+void ContextBuilder::visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node)
+{
+ if (node->function_name)
+ {
+ openContext(node, editorFindRange(node, node), KDevelop::DUContext::Function, node->function_name);
+ DefaultVisitor::visitFunctionOrRuleClause(node);
+ closeContext();
+ }
+ else
+ {
+ DefaultVisitor::visitFunctionOrRuleClause(node);
+ }
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp (revision 1522570)
@@ -0,0 +1,85 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "declarationbuilder.h"
+
+#include <interfaces/icore.h>
+#include <language/duchain/functiondeclaration.h>
+
+#include "erlangast.h"
+#include "../../parser/parsesession.h"
+#include "../../parser/editorintegrator.h"
+#include "../declarations/functiondeclaration.h"
+#include "../declarations/variabledeclaration.h"
+
+using namespace KTextEditor;
+using namespace KDevelop;
+namespace erlang
+{
+DeclarationBuilder::DeclarationBuilder(EditorIntegrator* editor)
+{
+ setEditor(editor);
+}
+
+DeclarationBuilder::DeclarationBuilder()
+{
+}
+
+void DeclarationBuilder::visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node)
+{
+ if (node->function_name)
+ {
+ FunctionDeclaration* func = openDeclaration<FunctionDeclaration>(node->function_name, node->body);
+ func->setDeclarationIsDefinition(true);
+ func->setKind(KDevelop::Declaration::Type);
+
+ DeclarationBuilderBase::visitFunctionOrRuleClause(node);
+ closeDeclaration();
+ }
+ else
+ {
+ DeclarationBuilderBase::visitFunctionOrRuleClause(node);
+ }
+}
+
+void DeclarationBuilder::visitExprMax(ExprMaxAst* node)
+{
+ if (node->var)
+ {
+ SimpleRange range = editorFindRange(node->var, node->var);
+ VariableDeclaration *dec = openDeclaration<VariableDeclaration>(identifierForNode(node->var), range);
+ dec->setKind(Declaration::Instance);
+ eventuallyAssignInternalContext();
+ closeDeclaration();
+ }
+ else
+ {
+ DeclarationBuilderBase::visitExprMax(node);
+ }
+}
+
+void DeclarationBuilder::updateCurrentType()
+{
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+ currentDeclaration()->setAbstractType(currentAbstractType());
+}
+
+
+}
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h (revision 1522570)
@@ -0,0 +1,44 @@
+/*
+* This file is part of KDevelop
+*
+* Copyright 2010 Victor Vicente de Carvalho
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+#ifndef TYPEBUILDER_H
+#define TYPEBUILDER_H
+
+#include "contextbuilder.h"
+
+#include <language/duchain/builders/abstracttypebuilder.h>
+
+namespace erlang {
+
+typedef KDevelop::AbstractTypeBuilder<AstNode, AstNode, ContextBuilder> TypeBuilderBase;
+
+class TypeBuilder: public TypeBuilderBase {
+public:
+ TypeBuilder();
+
+protected:
+ virtual void visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node);
+ virtual void visitArgExprs(ArgExprsAst* node);
+ virtual void updateCurrentType();
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h (revision 1522570)
@@ -0,0 +1,68 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef CONTEXTBUILDER_H
+#define CONTEXTBUILDER_H
+
+#include "erlangdefaultvisitor.h"
+#include <language/duchain/builders/abstractcontextbuilder.h>
+#include <parser/editorintegrator.h>
+
+namespace erlang
+{
+class EditorIntegrator;
+class ParseSession;
+
+typedef KDevelop::AbstractContextBuilder<AstNode, AstNode> ContextBuilderBase;
+
+class ContextBuilder : public ContextBuilderBase, public DefaultVisitor
+{
+ public:
+
+ ContextBuilder();
+ virtual ~ContextBuilder();
+
+ void setEditor(EditorIntegrator* editor);
+ virtual KDevelop::ReferencedTopDUContext build(const KDevelop::IndexedString& url, AstNode* node,
+ KDevelop::ReferencedTopDUContext updateContext
+ = KDevelop::ReferencedTopDUContext(), bool useSmart = true);
+
+ protected:
+ EditorIntegrator* editor() const;
+ virtual void visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node);
+ void startVisiting(AstNode* node);
+
+ virtual KDevelop::QualifiedIdentifier identifierForNode(AstNode* id);
+
+ virtual KDevelop::TopDUContext* newTopContext(const KDevelop::SimpleRange& range, KDevelop::ParsingEnvironmentFile* file = 0);
+
+ virtual void setContextOnNode(AstNode* node, KDevelop::DUContext* ctx);
+ virtual KDevelop::DUContext* contextFromNode(AstNode* node);
+ virtual KTextEditor::Range editorFindRange(AstNode* fromRange, AstNode* toRange);
+ /// Find Cursor for start of a node, useful to limit findLocalDeclarations() searches.
+ KDevelop::SimpleCursor startPos(AstNode* node);
+
+ /// Whether semantic problems should get reported
+ bool m_reportErrors;
+};
+
+}
+#endif // CONTEXTBUILDER_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h (revision 1522570)
@@ -0,0 +1,76 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Milian Wolff <mail@milianw.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef ERLANG_FUNCTIONDECLARATION_H
+#define ERLANG_FUNCTIONDECLARATION_H
+
+#include <language/duchain/functiondeclaration.h>
+
+#include <language/duchain/declaration.h>
+#include <language/duchain/declarationdata.h>
+#include <language/duchain/indexedstring.h>
+
+
+namespace erlang
+{
+
+class FunctionDeclarationData : public KDevelop::FunctionDeclarationData
+{
+public:
+ FunctionDeclarationData()
+ : KDevelop::FunctionDeclarationData() {}
+
+ FunctionDeclarationData(const FunctionDeclarationData& rhs)
+ : KDevelop::FunctionDeclarationData(rhs)
+ {
+ prettyName = rhs.prettyName;
+ }
+
+ ~FunctionDeclarationData() {}
+
+ KDevelop::IndexedString prettyName;
+};
+
+class FunctionDeclaration : public KDevelop::FunctionDeclaration
+{
+public:
+ FunctionDeclaration(const FunctionDeclaration &rhs);
+ FunctionDeclaration(const KDevelop::SimpleRange &range, KDevelop::DUContext *context);
+ FunctionDeclaration(FunctionDeclarationData &data);
+ FunctionDeclaration(FunctionDeclarationData &data, const KDevelop::SimpleRange &range, KDevelop::DUContext *context);
+ ~FunctionDeclaration();
+
+ virtual QString toString() const;
+
+ void setPrettyName(const KDevelop::IndexedString& name);
+ KDevelop::IndexedString prettyName() const;
+
+ enum {
+ Identity = 86
+ };
+
+ virtual KDevelop::Declaration* clonePrivate() const;
+private:
+ DUCHAIN_DECLARE_DATA(FunctionDeclaration)
+};
+
+}
+
+#endif // PHP_FUNCTIONDECLARATION_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h (revision 1522570)
@@ -0,0 +1,77 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef VARIABLEDECLARATION_H
+#define VARIABLEDECLARATION_H
+
+#include <language/duchain/declaration.h>
+#include <language/duchain/declarationdata.h>
+
+namespace erlang
+{
+
+class VariableDeclarationData : public KDevelop::DeclarationData
+{
+public:
+ VariableDeclarationData()
+ : KDevelop::DeclarationData(), m_isSuperglobal(false) {
+ }
+
+ VariableDeclarationData(const VariableDeclarationData& rhs)
+ : KDevelop::DeclarationData(rhs) {
+ m_isSuperglobal = rhs.m_isSuperglobal;
+ }
+
+ ~VariableDeclarationData() {
+ }
+
+bool m_isSuperglobal;
+};
+
+/**
+ * Declaration used for Php variables eg. $a = 0;
+ */
+class VariableDeclaration : public KDevelop::Declaration
+{
+public:
+ VariableDeclaration(const VariableDeclaration& rhs);
+ VariableDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context);
+ VariableDeclaration(VariableDeclarationData& data);
+ VariableDeclaration(VariableDeclarationData& data, const KDevelop::SimpleRange&);
+ virtual ~VariableDeclaration();
+
+ bool isSuperglobal() const;
+ void setSuperglobal(bool superglobal);
+
+ virtual uint additionalIdentity() const;
+ virtual KDevelop::DeclarationId id(bool forceDirect = false) const;
+
+ enum {
+ Identity = 83
+ };
+ typedef KDevelop::Declaration Base;
+
+private:
+ DUCHAIN_DECLARE_DATA(VariableDeclaration)
+};
+
+}
+
+#endif // VARIABLEDECLARATION_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp (revision 1522570)
@@ -0,0 +1,89 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Milian Wolff <mail@milianw.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "functiondeclaration.h"
+
+#include <language/duchain/duchainregister.h>
+#include <language/duchain/types/functiontype.h>
+
+namespace erlang {
+REGISTER_DUCHAIN_ITEM(FunctionDeclaration);
+
+FunctionDeclaration::FunctionDeclaration(const FunctionDeclaration& rhs)
+ : KDevelop::FunctionDeclaration(*new FunctionDeclarationData(*rhs.d_func()))
+{
+ setSmartRange(rhs.smartRange(), DocumentRangeObject::DontOwn);
+}
+
+FunctionDeclaration::FunctionDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
+ : KDevelop::FunctionDeclaration(*new FunctionDeclarationData, range)
+{
+ d_func_dynamic()->setClassId(this);
+ if (context) {
+ setContext(context);
+ }
+}
+
+FunctionDeclaration::FunctionDeclaration(FunctionDeclarationData& data)
+ : KDevelop::FunctionDeclaration(data)
+{
+}
+
+FunctionDeclaration::FunctionDeclaration(FunctionDeclarationData& data, const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
+ : KDevelop::FunctionDeclaration(data, range)
+{
+ if (context) {
+ setContext(context);
+ }
+}
+
+FunctionDeclaration::~FunctionDeclaration()
+{
+}
+
+KDevelop::Declaration* FunctionDeclaration::clonePrivate() const
+{
+ return new FunctionDeclaration(*this);
+}
+
+KDevelop::IndexedString FunctionDeclaration::prettyName() const
+{
+ return d_func()->prettyName;
+}
+
+void FunctionDeclaration::setPrettyName( const KDevelop::IndexedString& name )
+{
+ d_func_dynamic()->prettyName = name;
+}
+
+QString FunctionDeclaration::toString() const
+{
+ if( !abstractType() )
+ return Declaration::toString();
+
+ TypePtr<KDevelop::FunctionType> function = type<KDevelop::FunctionType>();
+ Q_ASSERT(function);
+
+ return QString("%1 %2 %3").arg(function->partToString( KDevelop::FunctionType::SignatureReturn ))
+ .arg(prettyName().str())
+ .arg(function->partToString( KDevelop::FunctionType::SignatureArguments ));
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp (revision 1522570)
@@ -0,0 +1,82 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "variabledeclaration.h"
+
+#include <language/duchain/ducontext.h>
+#include <language/duchain/duchainregister.h>
+
+using namespace KDevelop;
+namespace erlang
+{
+REGISTER_DUCHAIN_ITEM(VariableDeclaration);
+
+VariableDeclaration::VariableDeclaration(VariableDeclarationData& data) : KDevelop::Declaration(data)
+{
+}
+
+VariableDeclaration::VariableDeclaration(VariableDeclarationData& data, const KDevelop::SimpleRange& range)
+ : KDevelop::Declaration(data, range)
+{
+}
+
+VariableDeclaration::VariableDeclaration(const VariableDeclaration& rhs)
+ : KDevelop::Declaration(*new VariableDeclarationData(*rhs.d_func()))
+{
+ setSmartRange(rhs.smartRange(), DocumentRangeObject::DontOwn);
+}
+
+VariableDeclaration::VariableDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
+ : KDevelop::Declaration(*new VariableDeclarationData, range)
+{
+ d_func_dynamic()->setClassId(this);
+ if (context)
+ setContext(context);
+}
+VariableDeclaration::~VariableDeclaration()
+{
+}
+
+uint VariableDeclaration::additionalIdentity() const
+{
+ return 2;
+}
+
+KDevelop::DeclarationId VariableDeclaration::id(bool forceDirect) const
+{
+ Q_UNUSED(forceDirect);
+ //always forceDirect, because there can exist multiple declarations with the
+ //same identifier within one context, and uses wouldn't work correctly else
+ return KDevelop::Declaration::id(true);
+}
+
+bool VariableDeclaration::isSuperglobal() const
+{
+ DUCHAIN_D(VariableDeclaration);
+ return d->m_isSuperglobal;
+}
+
+void VariableDeclaration::setSuperglobal(bool superglobal)
+{
+ DUCHAIN_D_DYNAMIC(VariableDeclaration);
+ d->m_isSuperglobal = superglobal;
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h (revision 1522570)
@@ -0,0 +1,38 @@
+/*
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#ifndef TESTERLANGDUCHAIN_H
+#define TESTERLANGDUCHAIN_H
+
+#include "duchaintestbase.h"
+
+namespace erlang
+{
+
+class TestDUChain : public DUChainTestBase
+{
+ Q_OBJECT
+
+private slots:
+ void testDuchain();
+};
+
+}
+#endif // TESTERLANGDUCHAIN_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp (revision 1522570)
@@ -0,0 +1,96 @@
+/* This file is part of KDevelop
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+ Copyright 2008 Niko Sams <niko.sams@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#include "duchaintestbase.h"
+
+#include <QtTest/QtTest>
+
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/indexedstring.h>
+#include <kstandarddirs.h>
+#include <kcomponentdata.h>
+
+#include "../../parser/parsesession.h"
+#include "../builders/declarationbuilder.h"
+
+namespace erlang
+{
+
+DUChainTestBase::DUChainTestBase()
+{
+ KComponentData kd("kdeverlangsupport");
+}
+
+void DUChainTestBase::initTestCase()
+{
+ KDevelop::DUChain::self()->disablePersistentStorage();
+}
+
+KDevelop::TopDUContext* DUChainTestBase::parse(const QByteArray& unit, DumpAreas dump, QString url)
+{
+ if (dump)
+ kDebug() << "==== Beginning new test case...:" << endl << unit;
+
+ ParseSession* session = new ParseSession();
+ session->setContents(unit);
+ FormAst* ast = 0;
+ if (!session->parse(&ast)) {
+ kDebug() << "Parse failed:";
+ foreach(KDevelop::ProblemPointer p, session->problems())
+ {
+ kDebug() << p;
+ }
+
+ return 0;
+ }
+
+ if (dump & DumpAST) {
+ kDebug() << "===== AST:";
+ //DebugVisitor debugVisitor(session->tokenStream(), session->contents());
+ //debugVisitor.visitNode(ast);
+ }
+
+ static int testNumber = 0;
+ if (url.isEmpty()) url = QString("file:///internal/%1").arg(testNumber++);
+
+ EditorIntegrator editor;
+ editor.setParseSession(session);
+ DeclarationBuilder builder(&editor);
+ KDevelop::TopDUContext* top = builder.build(KDevelop::IndexedString(url), ast);
+
+ if (dump & DumpDUChain) {
+ kDebug() << "===== DUChain:";
+
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+ dumper.dump(top);
+ }
+
+ if (dump)
+ kDebug() << "===== Finished test case.";
+
+ delete session;
+
+ return top;
+}
+}
+
+#include "duchaintestbase.moc"
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp (revision 1522570)
@@ -0,0 +1,49 @@
+/*
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+*/
+
+#include "duchain.h"
+
+#include <QtTest/QtTest>
+
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/declaration.h>
+
+QTEST_MAIN(erlang::TestDUChain)
+
+namespace erlang
+{
+
+void TestDUChain::testDuchain()
+{
+ // 012345678901234
+ QByteArray function("myfunc() -> ok.");
+
+ KDevelop::TopDUContext* top = parse(function, DumpAll);
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+
+ QCOMPARE(top->childContexts().count(), 1);
+ KDevelop::DUContext *dec = top->childContexts().at(0);
+ QVERIFY(top->childContexts().first()->range() == KDevelop::SimpleRange(0, 0, 0, 5));
+}
+
+}
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h (revision 1522570)
@@ -0,0 +1,77 @@
+/* This file is part of KDevelop
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+ Copyright 2008,2010 Niko Sams <niko.sams@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef DUCHAINTESTBASE_H
+#define DUCHAINTESTBASE_H
+
+#include <QObject>
+#include <QByteArray>
+#include <QTest>
+#include <language/duchain/dumpchain.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+
+namespace KDevelop
+{
+class TopDUContext;
+}
+
+namespace erlang
+{
+/**
+ * Manage pointer to TopDUContexts and release them properly, even if a test fails
+ */
+struct DUChainReleaser {
+ DUChainReleaser(KDevelop::TopDUContext* top) : m_top(top) {}
+ ~DUChainReleaser() {
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+ KDevelop::DUChain::self()->removeDocumentChain(m_top);
+ }
+ KDevelop::TopDUContext* m_top;
+};
+
+class DUChainTestBase : public QObject
+{
+ Q_OBJECT
+
+public:
+ DUChainTestBase();
+
+public:
+ enum DumpArea {
+ DumpNone = 0,
+ DumpAST = 1,
+ DumpDUChain = 2,
+ DumpAll = 3
+ };
+ Q_DECLARE_FLAGS(DumpAreas, DumpArea)
+
+public slots:
+ void initTestCase();
+
+protected:
+ KDevelop::TopDUContext* parse(const QByteArray& unit, DumpAreas dump = static_cast<DumpAreas>(DumpAST | DumpDUChain), QString fileName = QString());
+
+ KDevelop::DumpChain dumper;
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(DUChainTestBase::DumpAreas)
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,106 @@
+PROJECT(erlang)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${erlang_SOURCE_DIR}/cmake)
+
+enable_testing()
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${QT4_INCLUDES}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+)
+
+#Don't error out if the FindXXX are missing for these two
+find_package(KDevelop-PG-Qt REQUIRED)
+
+include_directories(
+ ${CMAKE_BINARY_DIR}/parser
+ ${KDEVPGQT_INCLUDE_DIR}
+)
+
+add_subdirectory(parser)
+add_subdirectory(app_templates)
+
+set(kdeverlanglanguagesupport_PART_SRCS
+ erlanglanguagesupport.cpp
+ #completion/model.cpp
+ #completion/contentassistdata.cpp
+ parsejob.cpp
+ duchain/builders/contextbuilder.cpp
+ duchain/builders/declarationbuilder.cpp
+ duchain/builders/typebuilder.cpp
+ duchain/declarations/functiondeclaration.cpp
+ duchain/declarations/variabledeclaration.cpp
+ duchain/types/objecttype.cpp
+ #navigation/fieldnavigationcontext.cpp
+ #navigation/navigationwidget.cpp
+ #navigation/valuenavigationcontext.cpp
+)
+
+kde4_add_plugin(kdeverlanglanguagesupport ${kdeverlanglanguagesupport_PART_SRCS})
+
+target_link_libraries(kdeverlanglanguagesupport
+ ${KDE4_KDEUI_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ kdev4erlangparser
+)
+
+install(TARGETS kdeverlanglanguagesupport DESTINATION ${PLUGIN_INSTALL_DIR})
+
+install(FILES kdeverlangsupport.desktop DESTINATION ${SERVICES_INSTALL_DIR})
+
+### next target
+#set(completionmodeltest_SRCS
+# completion/test/modeltest.cpp
+# completion/model.cpp
+# completion/contentassistdata.cpp
+# )
+# kde4_add_unit_test(completionmodeltest ${completionmodeltest_SRCS})
+# target_link_libraries(completionmodeltest
+# kdev4erlangparser
+# ${KDE4_KDEUI_LIBS}
+# ${KDE4_KTEXTEDITOR_LIBS}
+# ${QT_QTGUI_LIBRARY}
+# ${QT_QTTEST_LIBRARY}
+# )
+#
+#
+### next target
+set(duchaintest_SRCS
+ duchain/tests/duchain.cpp
+ duchain/tests/duchaintestbase.cpp
+ duchain/builders/contextbuilder.cpp
+ duchain/builders/declarationbuilder.cpp
+)
+kde4_add_unit_test(duchaintest ${duchaintest_SRCS})
+
+target_link_libraries(duchaintest
+ kdev4erlangparser
+ ${KDE4_KDEUI_LIBS}
+ ${KDE4_KTEXTEDITOR_LIBS}
+ ${QT_QTGUI_LIBRARY}
+ ${QT_QTTEST_LIBRARY}
+)
+
+#
+#
+# ### next target
+# set(parsejobtest_SRCS
+# duchain/tests/parsejobtest.cpp
+# )
+# kde4_add_unit_test(parsejobtest ${parsejobtest_SRCS})
+# target_link_libraries(parsejobtest
+# ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+# ${KDEVPLATFORM_TESTS_LIBRARIES}
+# ${QT_QTTEST_LIBRARY}
+# )
+
+add_subdirectory(debug)
+# add_subdirectory(completion)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.cpp (revision 1522570)
@@ -0,0 +1,215 @@
+/*****************************************************************************
+ * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
+ * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
+ * Copyright (c) 2010 Milian Wolff <mail@milianw.de> *
+ * *
+ * 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "parsejob.h"
+
+#include <QFile>
+#include <QReadWriteLock>
+#include <QtCore/QReadLocker>
+#include <QtCore/QThread>
+
+#include <kdebug.h>
+#include <KMimeType>
+
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/dumpchain.h>
+#include <language/backgroundparser/urlparselock.h>
+
+#include <interfaces/ilanguage.h>
+#include <language/highlighting/codehighlighting.h>
+#include <interfaces/icore.h>
+#include <interfaces/ilanguagecontroller.h>
+
+#include "parser/parsesession.h"
+#include "erlanglanguagesupport.h"
+#include "duchain/builders/declarationbuilder.h"
+#include "parser/editorintegrator.h"
+
+#include <QtCore/QReadLocker>
+#include <QtCore/QThread>
+
+using namespace KDevelop;
+
+namespace erlang
+{
+
+extern int debugArea();
+#define debug() kDebug(debugArea())
+
+ParseJob::ParseJob ( const KUrl &url )
+ : KDevelop::ParseJob ( url )
+{
+ kDebug();
+}
+
+ParseJob::~ParseJob()
+{
+ kDebug();
+}
+
+LanguageSupport *ParseJob::erlang() const
+{
+ return LanguageSupport::self();
+}
+
+
+void ParseJob::run()
+{
+ KDevelop::UrlParseLock urlLock ( document() );
+
+ if ( ! ( minimumFeatures() & KDevelop::TopDUContext::ForceUpdate ) )
+ {
+ KDevelop::DUChainReadLocker lock ( KDevelop::DUChain::lock() );
+ bool needsUpdate = true;
+ foreach ( const KDevelop::ParsingEnvironmentFilePointer &file, KDevelop::DUChain::self()->allEnvironmentFiles ( document() ) )
+ {
+ if ( file->needsUpdate() )
+ {
+ needsUpdate = true;
+ break;
+ }
+ else
+ {
+ needsUpdate = false;
+ }
+ }
+ if ( !needsUpdate )
+ {
+ debug() << "Already up to date" << document().str();
+ return;
+ }
+ }
+
+ debug() << "parsing" << document().str();
+
+ bool readFromDisk = !contentsAvailableFromEditor();
+
+ QString contents;
+
+ if ( readFromDisk )
+ {
+ QFile file ( document().str() );
+
+ if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) )
+ {
+ /*
+ KDevelop::ProblemPointer p(new KDevelop::Problem());
+ p->setSource(KDevelop::ProblemData::Disk);
+ p->setDescription(i18n("Could not open file '%1'", document().str()));
+ switch (file.error()) {
+ case QFile::ReadError:
+ p->setExplanation(i18n("File could not be read from."));
+ break;
+ case QFile::OpenError:
+ p->setExplanation(i18n("File could not be opened."));
+ break;
+ case QFile::PermissionsError:
+ p->setExplanation(i18n("File permissions prevent opening for read."));
+ break;
+ default:
+ break;
+ }
+ p->setFinalLocation(KDevelop::DocumentRange(document().str(), KTextEditor::Cursor(0, 0), KTextEditor::Cursor(0, 0)));
+ // TODO addProblem(p);
+ */
+ kWarning() << "Could not open file" << document().str();
+ return abortJob();
+ }
+
+ QTextStream s ( &file );
+ contents = s.readAll();
+ file.close();
+ }
+ else
+ {
+ contents = contentsFromEditor();
+ }
+
+ KDevelop::ReferencedTopDUContext top;
+ {
+ KDevelop::DUChainReadLocker lock ( KDevelop::DUChain::lock() );
+ top = KDevelop::DUChain::self()->chainForDocument ( document() );
+ }
+ if ( top )
+ {
+ debug() << "re-compiling" << document().str();
+ KDevelop::DUChainWriteLocker lock ( KDevelop::DUChain::lock() );
+ top->clearImportedParentContexts();
+ top->parsingEnvironmentFile()->clearModificationRevisions();
+ top->clearProblems();
+ }
+ else
+ {
+ debug() << "compiling" << document().str();
+ }
+
+ QReadLocker parseLock ( erlang()->language()->parseLock() );
+ FormAst* formAst = 0;
+ ParseSession parseSession;
+ parseSession.setContents ( contents );
+ parseSession.setCurrentDocument ( document().str() );
+
+ bool matched = parseSession.parse ( &formAst );
+
+ EditorIntegrator editor;
+ editor.setParseSession(&parseSession);
+ DeclarationBuilder builder;
+ builder.setEditor ( &editor );
+ top = builder.build ( document(), formAst, top );
+ kDebug() << top;
+ Q_ASSERT ( top );
+
+ setDuChain ( top );
+
+ KDevelop::DUChainWriteLocker lock ( KDevelop::DUChain::lock() );
+
+ if ( !matched )
+ {
+ foreach ( const ProblemPointer &p, parseSession.problems() )
+ {
+ top->addProblem ( p );
+ }
+ }
+
+ cleanupSmartRevision();
+
+ top->setFeatures ( minimumFeatures() );
+ KDevelop::ParsingEnvironmentFilePointer file = top->parsingEnvironmentFile();
+
+ QFileInfo fileInfo ( document().str() );
+ QDateTime lastModified = fileInfo.lastModified();
+ if ( readFromDisk )
+ {
+ file->setModificationRevision ( KDevelop::ModificationRevision ( lastModified ) );
+ }
+ else
+ {
+ file->setModificationRevision ( KDevelop::ModificationRevision ( lastModified, revisionToken() ) );
+ }
+ KDevelop::DUChain::self()->updateContextEnvironment ( top->topContext(), file.data() );
+
+ cleanupSmartRevision();
+}
+
+}
+
+#include "parsejob.moc"
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile (revision 1522570)
@@ -0,0 +1,3 @@
+
+
+{"src/*",[debug_info, {outdir, "ebin"}]}.
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl (revision 1522570)
@@ -0,0 +1,19 @@
+-module(%{APPNAME}_app).
+
+-behaviour(application).
+
+-export([start/2,stop/1]).
+
+start(Type, StartArgs) ->
+ case %{APPNAME}_sup:start_link() of
+ {ok, Pid} ->
+ {ok, Pid};
+ Error ->
+ Error
+ end.
+
+shutdown() ->
+ application:stop(%{APPNAME}_app).
+
+stop(State) ->
+ ok.
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl (revision 1522570)
@@ -0,0 +1,15 @@
+-module(%{APPNAME}_sup).
+
+-behaviour(supervisor).
+
+-export([start_link/0]).
+-export([init/1]).
+
+-define(SERVER, ?MODULE).
+
+start_link() ->
+ supervisor:start_link({local, ?SERVER}, ?MODULE, []).
+
+init([]) ->
+ %%Your code here
+ {ok,{{one_for_all,0,1}, []}}.
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4 (revision 1522570)
@@ -0,0 +1,4 @@
+[Project]
+Name=%{APPNAME}
+Manager=KDevCustomMakeManager
+VersionControl=%{VERSIONCONTROLPLUGIN}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate (revision 1522570)
@@ -0,0 +1,39 @@
+# KDE Config File
+[General]
+Name=Simple Erlang Application
+Name[ca]=Aplicació Erlang senzilla
+Name[ca@valencia]=Aplicació Erlang senzilla
+Name[en_GB]=Simple Erlang Application
+Name[es]=Aplicación Erlang sencilla
+Name[et]=Lihtne Erlang rakendus
+Name[fr]=Application Erlang simple
+Name[nds]=Eenfach Erlang-Programm
+Name[nl]=Eenvoudig Erlang-programma
+Name[pl]=Prosty program w Erlang
+Name[pt]=Aplicação Simples em Erlang
+Name[pt_BR]=Aplicativo Erlang simples
+Name[ro]=Aplicație Erlang simplă
+Name[sv]=Ett enkelt Erlang-program
+Name[uk]=Проста програма мовою Erlang
+Name[x-test]=xxSimple Erlang Applicationxx
+Name[zh_CN]=简单的 Erlang 应用程序
+Name[zh_TW]=簡單的 Erlang 應用程式
+Category=Erlang
+Comment=Generate filestructure to start a Erlang application
+Comment[ca]=Genera l'estructura de fitxer per iniciar una aplicació Erlang
+Comment[ca@valencia]=Genera l'estructura de fitxer per iniciar una aplicació Erlang
+Comment[en_GB]=Generate filestructure to start a Erlang application
+Comment[es]=Generar una estructura de archivos para iniciar una aplicación Erlang
+Comment[et]=Failistruktuuri genereerimine Erlang rakenduse tarbeks
+Comment[fr]=Génère une structure de fichiers pour démarrer une application Erlang
+Comment[nds]=Dateiopbuu för't Starten vun en Erlang-Programm opstellen
+Comment[nl]=Een bestandsstructuur genereren om een Erlang-programma te starten
+Comment[pl]=Generuje strukturę plików do uruchomienia programu w Erlang
+Comment[pt]=Gerar a estrutura de ficheiros para iniciar uma aplicação em Erlang
+Comment[pt_BR]=Gera a estrutura de arquivos para iniciar um aplicativo Erlang
+Comment[sv]=Skapa filstruktur för att påbörja ett Erlang-program
+Comment[uk]=Створити початкову файлову структуру програми мовою Erlang
+Comment[x-test]=xxGenerate filestructure to start a Erlang applicationxx
+Comment[zh_CN]=生成 Erlang 应用程序的文件结构
+Comment[zh_TW]=開始寫一個 Erlang 應用程式的一般檔案結構
+ShowFilesAfterGeneration=%{dest}/%{APPNAMELC}.erl
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,5 @@
+set(apptemplate_DIRS
+ simple_erlangapp
+)
+
+kdevplatform_add_app_templates(${apptemplate_DIRS})
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h (revision 1522570)
@@ -0,0 +1,71 @@
+/*****************************************************************************
+ * Copyright (c) 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef KDEVERLANGLANGUAGESUPPORT_H
+#define KDEVERLANGLANGUAGESUPPORT_H
+
+#include <interfaces/iplugin.h>
+#include <language/interfaces/ilanguagesupport.h>
+#include <QtCore/QVariant>
+#include <QReadWriteLock>
+
+#include <language/duchain/indexedstring.h>
+
+namespace KDevelop
+{
+class IDocument;
+class IProject;
+class CodeHighlighting;
+class ReferencedTopDUContext;
+class ParseJob;
+}
+
+
+namespace erlang
+{
+
+class Highlighting;
+
+class LanguageSupport : public KDevelop::IPlugin, public KDevelop::ILanguageSupport
+{
+ Q_OBJECT
+ Q_INTERFACES(KDevelop::ILanguageSupport)
+
+public:
+ explicit LanguageSupport(QObject *parent, const QVariantList& args = QVariantList());
+
+ virtual ~LanguageSupport()
+ {
+ }
+
+ /*Name Of the Language*/
+ QString name() const;
+ /*Parsejob used by background parser to parse given Url*/
+ KDevelop::ParseJob *createParseJob(const KUrl &url);
+
+ static LanguageSupport* self();
+ /*the code highlighter*/
+ //const KDevelop::ICodeHighlighting* codeHighlighting() const;
+private:
+ static LanguageSupport* m_self;
+};
+
+}
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlang.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlang.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlang.kdev4 (revision 1522570)
@@ -0,0 +1,4 @@
+[Project]
+Name=erlang
+Manager=KDevCMakeManager
+VersionControl=
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/COPYING
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/COPYING (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/COPYING (revision 1522570)
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp (revision 1522570)
@@ -0,0 +1,82 @@
+/*****************************************************************************
+ * Copyright (c) 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "erlanglanguagesupport.h"
+
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+#include <kaboutdata.h>
+#include <KTextEditor/Document>
+
+#include <language/codecompletion/codecompletion.h>
+#include <interfaces/idocument.h>
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+
+//#include "completion/model.h"
+#include "parsejob.h"
+//#include "navigation/navigationwidget.h"
+#include "parser/parsesession.h"
+
+K_PLUGIN_FACTORY(KDevErlangSupportFactory, registerPlugin<erlang::LanguageSupport>();)
+K_EXPORT_PLUGIN(KDevErlangSupportFactory(KAboutData("kdeverlangsupport","kdeverlang", ki18n("Erlang Support"), "0.1", ki18n("Support for Erlang Language"), KAboutData::License_GPL)
+ .addAuthor(ki18n("Victor Vicente de Carbalho"), ki18n("Author"), "victor.v.carvalho@gmail.com", "")
+))
+
+namespace erlang
+{
+LanguageSupport* LanguageSupport::m_self = 0;
+
+#if KDE_VERSION > KDE_MAKE_VERSION(4, 3, 80)
+int debugArea() { static int s_area = KDebug::registerArea("kdeverlangsupport"); return s_area; }
+#else
+int debugArea() { return 1; }
+#endif
+
+LanguageSupport::LanguageSupport(QObject* parent, const QVariantList& /*args*/)
+ : KDevelop::IPlugin(KDevErlangSupportFactory::componentData(), parent),
+ KDevelop::ILanguageSupport()
+{
+ KDEV_USE_EXTENSION_INTERFACE(KDevelop::ILanguageSupport)
+
+ m_self = this;
+
+ //CodeCompletionModel* ccModel = new CodeCompletionModel(this);
+ //new KDevelop::CodeCompletion(this, ccModel, name());
+}
+
+QString LanguageSupport::name() const
+{
+ return "Erlang";
+}
+
+KDevelop::ParseJob *LanguageSupport::createParseJob(const KUrl &url)
+{
+ kDebug(debugArea()) << url;
+ return new ParseJob(url);
+}
+
+LanguageSupport *LanguageSupport::self()
+{
+ return m_self;
+}
+}
+
+#include "erlanglanguagesupport.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/erlang/parsejob.h (revision 1522570)
@@ -0,0 +1,56 @@
+/*****************************************************************************
+ * Copyright (c) 2010 Victor Vicente de Carvalho *
+ * <victor.v.carvalho@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef ERLANG_PARSEJOB_H
+#define ERLANG_PARSEJOB_H
+
+#include <language/backgroundparser/parsejob.h>
+
+// from the parser subdirectory
+#include "erlangast.h"
+
+#include <QStringList>
+
+#include <ksharedptr.h>
+#include <ktexteditor/range.h>
+
+namespace erlang
+{
+
+class AstNode;
+class LanguageSupport;
+class EditorIntegrator;
+
+class ParseJob : public KDevelop::ParseJob
+{
+ Q_OBJECT
+
+public:
+ explicit ParseJob(const KUrl &url);
+ virtual ~ParseJob();
+
+ LanguageSupport* erlang() const;
+
+protected:
+ virtual void run();
+
+};
+}
+
+#endif
+// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop (revision 1522570)
@@ -0,0 +1,67 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=Insert dummies according to RFC 3092
+Comment[bs]=Ubacite makete saglasno sa RFC 3092
+Comment[ca]=Insereix elements de simulació d'accord a la RFC 3092
+Comment[ca@valencia]=Insereix elements de simulació d'accord a la RFC 3092
+Comment[de]=Fügt Dummies nach RFC 3092 ein
+Comment[en_GB]=Insert dummies according to RFC 3092
+Comment[es]=Insertar términos que sigan la RFC 3092
+Comment[et]=Libade sisestamine vastavalt RFC 3092-le
+Comment[fr]=Insère des paramètres fictifs selon la RFC 3092
+Comment[gl]=Inserir datos de exemplo de acordo co RFC 3092.
+Comment[nl]=Voegt dummies volgens RFC 3092 toe
+Comment[pl]=Wstaw dummies według RFC 3092
+Comment[pt]=Insere valores de testes de acordo com o RFC 3092
+Comment[pt_BR]=Inserir valores fictícios de acordo com a RFC 3092
+Comment[sv]=Infoga platsmarkörer enligt RFC 3092
+Comment[uk]=Вставка тестових фрагментів відповідно до RFC 3092
+Comment[x-test]=xxInsert dummies according to RFC 3092xx
+Name=Foobar
+Name[bs]=Foobar
+Name[ca]=Foobar
+Name[ca@valencia]=Foobar
+Name[de]=Foobar
+Name[en_GB]=Foobar
+Name[es]=Foobar
+Name[et]=Foobar
+Name[fr]=Barre fictive
+Name[gl]=Foobar
+Name[nl]=Foobar
+Name[pl]=Foobar
+Name[pt]=XPTO
+Name[pt_BR]=Foobar
+Name[sk]=Foobar
+Name[sv]=Flärp
+Name[uk]=Щось там
+Name[x-test]=xxFoobarxx
+GenericName=Foobar
+GenericName[bs]=Foobar
+GenericName[ca]=Foobar
+GenericName[ca@valencia]=Foobar
+GenericName[de]=Foobar
+GenericName[en_GB]=Foobar
+GenericName[es]=Foobar
+GenericName[et]=Foobar
+GenericName[fr]=Barre fictive
+GenericName[gl]=Foobar
+GenericName[nl]=Foobar
+GenericName[pl]=Foobar
+GenericName[pt]=XPTO
+GenericName[pt_BR]=Foobar
+GenericName[sk]=Foobar
+GenericName[sv]=Flärp
+GenericName[uk]=Щось там
+GenericName[x-test]=xxFoobarxx
+Icon=kdevelop
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevfoobar
+X-KDE-PluginInfo-Name=kdevfoobar
+X-KDE-PluginInfo-Author=Jonathan Schmidt-Dominé (The User)
+X-KDE-PluginInfo-Email=devel@the-user.org
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=10
+X-KDevelop-Mode=GUI
+X-KDevelop-Category=Global
+# X-KDevelop-Language=C++
Index: tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/foobar/kdevfoobar.rc (revision 1522570)
@@ -0,0 +1,6 @@
+<!DOCTYPE kpartgui>
+<kpartplugin name="kdevfoobar" library="libkdevfoobar" version="1">
+<Menu name="ktexteditor_popup">
+ <Action name="kdevfoobar_insertfoobar" group="popup_operations"/>
+</Menu>
+</kpartplugin>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.cpp (revision 1522570)
@@ -0,0 +1,126 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Foobar-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "foobarplugin.h"
+
+#include <KPluginFactory>
+#include <KPluginLoader>
+#include <KAboutData>
+#include <KDebug>
+#include <KActionCollection>
+#include <KAction>
+#include <KLocale>
+
+#include <kdevplatform/interfaces/icore.h>
+#include <kdevplatform/interfaces/idocument.h>
+#include <kdevplatform/interfaces/idocumentcontroller.h>
+#include <kdevplatform/language/duchain/duchain.h>
+#include <kdevplatform/language/duchain/ducontext.h>
+#include <kdevplatform/language/duchain/parsingenvironment.h>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+
+#include <QVector>
+
+K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<KDevFoobarPlugin>();)
+K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("kdevfoobar","kdevfoobar", ki18n ("Foo, Bar, Baz creation"), "0.1", ki18n ("Insert dummies according to RFC 3092"), KAboutData::License_GPL)))
+
+KDevFoobarPlugin::KDevFoobarPlugin (QObject *parent, const QVariantList &)
+:IPlugin (KdevPlugFactory::componentData(), parent)
+{
+ setXMLFile ("kdevfoobar.rc");
+
+ m_actionInsert = actionCollection()->addAction ("kdevfoobar_insertfoobar");
+ m_actionInsert->setText (i18n ("Insert Foobar"));
+ connect (m_actionInsert, SIGNAL (triggered (bool)), this, SLOT (insert()));
+ m_actionInsert->setToolTip (i18n ("Insert the Current File"));
+}
+
+KDevFoobarPlugin::~KDevFoobarPlugin()
+{
+}
+
+#define NC(...) __VA_ARGS__
+
+static bool declExists(const QString& name)
+{
+ foreach(NC(const ParsingEnvironmentFilePointer &env), NC(DUChain::self()->allEnvironmentFiles(IndexedString((ICore::self()->documentController()->activeDocument()->url())))))
+ {
+ TopDUContext* top = env->topContext();
+ if(!top) continue;
+ if(!top->findDeclarations(QualifiedIdentifier(name)).isEmpty())
+ return true;
+ }
+ return false;
+}
+
+void KDevFoobarPlugin::insert()
+{
+ static QString foos[] = {
+ "foo", "bar", "baz", "qux", "quux", "corge", "grault",
+ "garply", "waldo", "fred", "plugh", "xyzzy", "thud"
+ };
+ static const int size = 13;
+ QString name;
+ for(int num = 1; ; ++num)
+ {
+ QVector<int> vec(num, -1);
+ int idx = 0;
+ bool used[size] = {};
+ while(idx != -1)
+ {
+ while(++vec[idx] != size)
+ {
+ kDebug() << num << idx << vec[idx];
+ if(!used[vec[idx]])
+ {
+ used[vec[idx]] = true;
+ ++idx;
+ if(idx == num)
+ {
+ for(int i = 0; i != num; ++i)
+ name += foos[vec[i]];
+ kDebug() << "Check: " << name;
+ if(!declExists(name))
+ goto done;
+ name = "";
+ --idx;
+ }
+ else
+ goto next;
+ }
+ }
+ used[vec[idx]] = false;
+ vec[idx] = -1;
+ --idx;
+ next:
+ ;
+ }
+ if(num == size)
+ {
+ // fail, seems to be impossible, you'd need _a lot_ of usages :D
+ Q_ASSERT(0);
+ return;
+ }
+ }
+ done:;
+ KTextEditor::Document *d = ICore::self()->documentController()->activeDocument()->textDocument();
+ d->insertText(d->activeView()->cursorPosition(), name);
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/foobar/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/foobar/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/foobar/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,21 @@
+project(KDevPreprocessor)
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+)
+
+set(foobar_SRCS foobarplugin.cpp)
+
+kde4_add_plugin(kdevfoobar ${foobar_SRCS})
+
+target_link_libraries(kdevfoobar
+ -lQtCore -lkdevplatforminterfaces
+ -lkdevplatformutil -lkdevplatformlanguage -lkdecore -lkparts
+ ${KDE4_KTEXTEDITOR_LIBS})
+
+install(TARGETS kdevfoobar DESTINATION ${PLUGIN_INSTALL_DIR})
+install(FILES kdevfoobar.desktop DESTINATION ${SERVICES_INSTALL_DIR})
+install(FILES kdevfoobar.rc DESTINATION ${DATA_INSTALL_DIR}/kdevfoobar)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/foobar/foobarplugin.h (revision 1522570)
@@ -0,0 +1,50 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Foobar-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef FOOBARPLUGIN_H
+#define FOOBARPLUGIN_H
+
+#include <interfaces/iplugin.h>
+
+#include <QVariantList>
+
+class KAction;
+
+using namespace KDevelop;
+
+namespace KDevelop
+{
+ class Declaration;
+ class DUContext;
+ class ClassDeclaration ;
+ class ClassMemberDeclaration ;
+}
+
+class KDevFoobarPlugin : public KDevelop::IPlugin
+{
+ Q_OBJECT
+ public:
+ KDevFoobarPlugin (QObject *parent, const QVariantList & = QVariantList());
+ ~KDevFoobarPlugin();
+ private slots:
+ void insert();
+ private:
+ KAction *m_actionInsert;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop (revision 1522570)
@@ -0,0 +1,74 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=Generate reader-writer / getter-setter properties
+Comment[bs]=Generiši čitač-pisač/"dostavljač"-postavljač svojstava
+Comment[ca]=Genera propietats reader-writer / getter-setter
+Comment[ca@valencia]=Genera propietats reader-writer / getter-setter
+Comment[de]=Reader-Writer/Getter-Setter-Eigenschaften erzeugen
+Comment[en_GB]=Generate reader-writer / getter-setter properties
+Comment[es]=Generar propiedades de lectura-escritura / obtener-fijar
+Comment[et]=Lugeja-kirjutaja / tagastaja-seadja omaduste genereerimine
+Comment[fr]=Génère les propriétés des méthodes lecteur-scripteur / accesseur-mutateur
+Comment[gl]=Xerar propiedades de lectura e escritura
+Comment[hu]=Olvasó-író / lekérő-beállító tulajdonságok előállítása
+Comment[it]=Genera proprietà reader-writer / getter-setter
+Comment[nl]=Genereert lees-schrijf / getter-setter eigenschappen
+Comment[pl]=Generuj właściwości programu czytająco-zapisującego / pobierająco-ustawiającego
+Comment[pt]=Gerar propriedades de leitura-escrita / 'get'-'set'
+Comment[pt_BR]=Gerar propriedades de leitura-escrita / 'get'-'set'
+Comment[sk]=Vygenerovať vlastnosti čítača-zapisovača / gettera-settera
+Comment[sv]=Skapa läs-skriv och hämta-tilldela egenskaper
+Comment[uk]=Створення записів властивостей читання-запису / отримання-встановлення
+Comment[x-test]=xxGenerate reader-writer / getter-setter propertiesxx
+Name=Getter & Setter
+Name[bs]="čitač"-postavljač
+Name[ca]=Getter i Setter
+Name[ca@valencia]=Getter i Setter
+Name[de]=Getter & Setter
+Name[en_GB]=Getter & Setter
+Name[es]=«Getter» y «setter»
+Name[et]=Getter ja Setter
+Name[fr]=Accesseur et mutateur
+Name[gl]=Lector e escritor
+Name[hu]=Lekérő és beállító
+Name[it]=Getter e Setter
+Name[nl]=Getter & Setter
+Name[pl]=Pobieranie & Ustawianie
+Name[pt]='Get' & 'Set'
+Name[pt_BR]='Get' & 'Set'
+Name[sv]=&Hämta-tilldela
+Name[uk]=Отримання і встановлення
+Name[x-test]=xxGetter & Setterxx
+GenericName=Generate reader-writer / getter-setter properties
+GenericName[bs]=Generiši čitač-pisač/"preuzimač-postavljač svojstava
+GenericName[ca]=Genera propietats reader-writer / getter-setter
+GenericName[ca@valencia]=Genera propietats reader-writer / getter-setter
+GenericName[de]=Reader-Writer/Getter-Setter-Eigenschaften erzeugen
+GenericName[en_GB]=Generate reader-writer / getter-setter properties
+GenericName[es]=Generar propiedades de lectura-escritura / obtener-fijar
+GenericName[et]=Lugeja-kirjutaja / tagastaja-seadja omaduste genereerimine
+GenericName[fr]=Génère les propriétés des méthodes lecteur-scripteur / accesseur-mutateur
+GenericName[gl]=Xerar propiedades de lectura e escritura
+GenericName[hu]=Olvasó-író / lekérő-beállító tulajdonságok előállítása
+GenericName[it]=Genera proprietà reader-writer / getter-setter
+GenericName[nl]=Genereert lees-schrijf / getter-setter eigenschappen
+GenericName[pl]=Generuj właściwości programu czytająco-zapisującego / pobierająco-ustawiającego
+GenericName[pt]=Gerar propriedades de leitura-escrita / 'get'-'set'
+GenericName[pt_BR]=Gerar propriedades de leitura-escrita / 'get'-'set'
+GenericName[sk]=Vygenerovať vlastnosti čítača-zapisovača / gettera-settera
+GenericName[sv]=Skapa läs-skriv och hämta-tilldela egenskaper
+GenericName[uk]=Створення записів властивостей читання-запису / отримання-встановлення
+GenericName[x-test]=xxGenerate reader-writer / getter-setter propertiesxx
+Icon=kdevelop
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevgettersetter
+X-KDE-PluginInfo-Name=kdevgettersetter
+X-KDE-PluginInfo-Author=Ruan Strydom
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=8
+X-KDevelop-Category=Global
+X-KDevelop-Mode=GUI
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.h (revision 1522570)
@@ -0,0 +1,113 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#ifndef PROPERTYNODE_H
+#define PROPERTYNODE_H
+
+#include <QtGui/QIcon>
+#include <language/duchain/declaration.h>
+
+
+using namespace KDevelop;
+
+
+/** Stores info about an property.
+ * @todo This should keep a handle to the Declaration. Rather than a bunch of members.
+ * This represents a row in the table of PropertiesDialog and PropertyModel.
+ */
+class PropertyNode
+{
+public:
+ PropertyNode ();
+ virtual ~PropertyNode();
+
+
+ virtual const QString& getterName() const { return m_getterName; }
+
+ virtual void setGetterName ( const QString& rn ) { m_getterName = rn; }
+
+ virtual bool createGetter() const { return m_createGetter; }
+
+ virtual void setCreateGetter ( bool cr ) { m_createGetter = cr; }
+
+ virtual bool canCreateGetter() const { return m_canCreateGetter; }
+
+ virtual void setCanCreateGetter ( bool ccr ) { m_canCreateGetter = ccr; }
+
+ virtual const QString& getterAccess() const { return m_getterAccess; }
+
+ virtual void setGetterAccess ( const QString& ra ) { m_getterAccess = ra; }
+
+ virtual const QString& setterName() const { return m_setterName; }
+
+ virtual void setSetterName ( const QString& wn ) { m_setterName = wn; }
+
+ virtual bool createSetter() const { return m_createSetter; }
+
+ virtual void setCreateSetter ( bool cw ) { m_createSetter = cw; }
+
+ virtual bool canCreateSetter() const { return m_canCreateSetter; }
+
+ virtual void setCanCreateSetter ( bool ccw ) { m_canCreateSetter = ccw; }
+
+ virtual const QString& setterAccess() const { return m_setterAccess; }
+
+ virtual void setSetterAccess ( const QString& wa ) { m_setterAccess = wa; }
+
+ virtual const QString& name() const { return m_name; }
+
+ virtual void setName ( const QString& n ) { m_name = n; }
+
+ virtual const QIcon& icon() const { return m_icon; }
+
+ virtual void setIcon ( const QIcon& i ) { m_icon = i; }
+
+ virtual const QString& type() const { return m_type; }
+
+ virtual void setType ( const QString& t ) { m_type = t; }
+
+ virtual const QString& resolvedType() const { return m_resolvedType; }
+
+ virtual void setResolvedType ( const QString& rt ) { m_resolvedType = rt; }
+
+ virtual KDevelop::AbstractType::WhichType whichType() const { return m_whichType; }
+
+ virtual void setWhichType ( KDevelop::AbstractType::WhichType wt ) { m_whichType = wt; }
+
+protected:
+ QString m_getterName;
+ bool m_createGetter;
+ bool m_canCreateGetter;
+ QString m_getterAccess;
+
+ QString m_setterName;
+ bool m_createSetter;
+ bool m_canCreateSetter;
+ QString m_setterAccess;
+
+ QString m_name;
+ QIcon m_icon;
+
+ QString m_type;
+ QString m_resolvedType;
+ AbstractType::WhichType m_whichType;
+};
+
+#endif // PROPERTYNODE_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp (revision 1522570)
@@ -0,0 +1,231 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#include "gettersetterplugin.h"
+
+#include <interfaces/icore.h>
+#include <interfaces/contextmenuextension.h>
+#include <interfaces/context.h>
+#include <interfaces/idocument.h>
+#include <interfaces/iuicontroller.h>
+#include <interfaces/idocumentcontroller.h>
+
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainutils.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/classdeclaration.h>
+#include <language/duchain/classmemberdeclaration.h>
+#include <shell/sourceformattercontroller.h>
+#include <interfaces/isourceformatter.h>
+
+#include <KPluginFactory>
+#include <KPluginLoader>
+#include <KLocalizedString>
+#include <KAboutData>
+#include <KTextEditor/Document>
+#include <KDebug>
+#include <KMessageBox>
+#include <KActionCollection>
+#include <KAction>
+#include <KTextEditor/SmartCursor>
+
+#include <QtCore/QPair>
+#include <QtCore/QList>
+
+#include "propertiesdialog.h"
+#include "propertymodel.h"
+#include "cpppropertycreator.h"
+#include "javapropertycreator.h"
+#include "csharppropertycreator.h"
+
+
+#define ERROR_MESSAGE ({KMessageBox::error(NULL, i18n(QString("An error occured while parsing the class. Please log a report. File: %1 Line: %2").arg(__FILE__).arg(__LINE__).toAscii().constData()));});
+
+K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<GetterSetterPlugin>();)
+K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("GetterSetter","GetterSetter", ki18n ("Generate reader-writer / getter-setter properties"), "0.1", ki18n ("Generate reader-writer / getter-setter properties"), KAboutData::License_GPL)))
+
+GetterSetterPlugin::GetterSetterPlugin (QObject *parent, const QVariantList &)
+ :IPlugin (KdevPlugFactory::componentData(), parent)
+{
+ setXMLFile ("gettersetter.rc");
+
+ m_action = actionCollection()->addAction ("generate_gettersetter");
+ //m_action->setIcon (KIcon ("kdevelop"));
+ m_action->setText (i18n ("Generate properties.."));
+ m_action->setShortcut (KShortcut ("Ctrl+Alt+p"));
+ connect (m_action, SIGNAL (triggered (bool)), this, SLOT (slotCreateProperties()));
+ m_action->setToolTip (i18n ("Generate reader-writer/getter-setter properties"));
+ m_action->setWhatsThis (i18n ("<b>GetterSetter</b><p> Generate reader-writer/getter-setter properties"));
+ m_action->setEnabled (false);
+}
+
+GetterSetterPlugin::~GetterSetterPlugin()
+{
+}
+
+void GetterSetterPlugin::slotCreateProperties()
+{
+ DUChainReadLocker lock (DUChain::lock());
+
+ QList<Declaration*> decls = cursorItemDeclarations();
+ if (decls.size() < 1)
+ {
+ KMessageBox::information (0, i18n ("No valid declaration in selection.\nIt is possible that the parser is still busy."));
+ return;
+ }
+
+ createProperties (decls);
+}
+
+void GetterSetterPlugin::createProperties (QList<Declaration*> decls)
+{
+ DUChainReadLocker lock (DUChain::lock());
+ static PropertiesDialog *d = ({
+ PropertiesDialog *d = new PropertiesDialog ( (QWidget *) ICore::self()->uiController()->activeMainWindow());
+ connect (d, SIGNAL (okClicked()), this, SLOT (slotWriteProperties()));
+ d;
+ });
+ static PropertyModel *m = new PropertyModel;
+
+ if (d->isVisible())
+ return;
+
+ if(decls.size() == 0)
+ return;
+
+ IDocument* doc = ICore::self()->documentController()->documentForUrl ( decls[0]->url().toUrl() );
+ if ( !doc )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ PropertyCreator * pc = creatorForMime(doc->mimeType());
+ if(!pc)
+ return;
+
+ if(!pc->parse (m, decls))
+ return;
+
+ d->setCaption (i18n ("Class: ") + m->klass()->identifier().toString());
+ d->setModal (false);
+ d->show (m);
+}
+
+void GetterSetterPlugin::slotWriteProperties()
+{
+ PropertiesDialog *d = dynamic_cast<PropertiesDialog *> (this->sender());
+ if (!d)
+ {
+ ERROR_MESSAGE
+ kDebug() << "sender() not instance of PropertiesDialog";
+ return;
+ }
+ IDocument* doc = ICore::self()->documentController()->documentForUrl ( d->model()->klass()->url().toUrl() );
+ if ( !doc )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ PropertyCreator * pc = creatorForMime(doc->mimeType());
+ if(!pc)
+ return;
+ pc->create (d->model());
+}
+
+ContextMenuExtension GetterSetterPlugin::contextMenuExtension (Context* context)
+{
+ Q_UNUSED (context);
+
+ DUChainReadLocker lock (DUChain::lock());
+ ContextMenuExtension ext;
+ m_action->setEnabled (false);
+ QList<Declaration *> decls = cursorItemDeclarations();
+ if (decls.size() > 0) {
+ m_action->setEnabled (true);
+ ext.addAction (ContextMenuExtension::EditGroup, m_action);
+ }
+ return ext;
+}
+
+QList<Declaration*> GetterSetterPlugin::cursorItemDeclarations()
+{
+ QList<Declaration*> list;
+ IDocument* doc = ICore::self()->documentController()->activeDocument();
+ if (!doc)
+ return list;
+
+ if(!creatorForMime(doc->mimeType())) {
+ return list;
+ }
+
+ KTextEditor::Document* textDoc = doc->textDocument();
+ if (!textDoc)
+ return list;
+
+ KTextEditor::View* view = textDoc->activeView();
+ if (!view)
+ return list;
+
+ if(view->selection()) {
+ KTextEditor::Range r = view->selectionRange();
+ TopDUContext * tc = DUChainUtils::standardContextForUrl(doc->url());
+ for(int i = r.start().line(); i <= r.end().line(); i++) {
+ Declaration *d = DUChainUtils::declarationInLine(SimpleCursor(i,0),tc);
+ if (d && d->kind() == Declaration::Instance && !d->isFunctionDeclaration() &&
+ d->context() && d->context()->type() == DUContext::Class)
+ {
+ list.append(d);
+ }
+ }
+ } else {
+ SimpleCursor c (view->cursorPosition());
+ Declaration* d = DUChainUtils::itemUnderCursor (doc->url(), c);
+ if (d && d->kind() == Declaration::Instance && !d->isFunctionDeclaration() &&
+ d->context() && d->context()->type() == DUContext::Class)
+ list.append(d);
+ else if (d && d->internalContext() && d->internalContext()->type() == DUContext::Class)
+ list.append(d);
+ }
+ return list;
+}
+
+
+PropertyCreator* GetterSetterPlugin::creatorForMime(const KMimeType::Ptr& mime)
+{
+ static CppPropertyCreator cpp;
+ static JavaPropertyCreator java;
+ static CSharpPropertyCreator csharp;
+ if(mime->is("text/x-c++src") || mime->is("text/x-c++hdr") || mime->is("text/x-chdr")) {
+ return &cpp;
+ }
+ if(mime->is("text/x-java")) {
+ return &java;
+ }
+ if(mime->is("text/x-csharp")) {
+ return &csharp;
+ }
+ return NULL;
+}
+
+
+#include "gettersetterplugin.moc"
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp (revision 1522570)
@@ -0,0 +1,228 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#include "propertymodel.h"
+
+#include <QtGui/QColor>
+#include <KMessageBox>
+#include <KLocalizedString>
+
+PropertyModel::PropertyModel (QObject* parent) : QAbstractTableModel (parent)
+{
+ Q_UNUSED (parent);
+ m_hasQObject = false;
+ m_createQtProperties = false;
+ m_modifier = FINAL;
+}
+
+
+PropertyModel::~PropertyModel()
+{
+
+}
+
+
+Qt::ItemFlags PropertyModel::flags (const QModelIndex& index) const
+{
+ if (!index.isValid())
+ return Qt::ItemIsEnabled;
+
+ const PropertyNode &n = m_nodes[index.row() ];
+ switch (index.column())
+ {
+ case 1:
+ if (n.canCreateGetter())
+ return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
+ else
+ return Qt::ItemIsUserCheckable;
+ case 2:
+ if (n.canCreateGetter())
+ return QAbstractTableModel::flags (index) | Qt::ItemIsEditable;
+ else
+ return Qt::NoItemFlags;
+ case 3:
+ if (n.canCreateGetter())
+ QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
+ else
+ return Qt::NoItemFlags;
+ case 4:
+ if (n.canCreateSetter())
+ return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
+ else
+ return Qt::ItemIsUserCheckable;
+ case 5:
+ if (n.canCreateSetter())
+ return QAbstractTableModel::flags (index) | Qt::ItemIsEditable;
+ else
+ return Qt::NoItemFlags;
+ case 6:
+ if (n.canCreateSetter())
+ QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
+ else
+ return Qt::NoItemFlags;
+ }
+
+ return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
+}
+
+
+QVariant PropertyModel::headerData (int section, Qt::Orientation orientation, int role) const
+{
+ if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
+ {
+ switch (section)
+ {
+ case 0:
+ return i18n("Member");
+ //case 1:
+ // return QString();
+ case 2:
+ return i18n("Getter Access");
+ case 3:
+ return i18n("Getter Name");
+ //case 4:
+ // return QString();
+ case 5:
+ return i18n("Setter Access");
+ case 6:
+ return i18n("Setter Name");
+ default:
+ return QVariant();
+ }
+ }
+
+ return QAbstractTableModel::headerData (section, orientation, role);
+}
+
+
+bool PropertyModel::setData (const QModelIndex& index, const QVariant& value, int role)
+{
+ if (index.row() > m_nodes.size()-1 || index.column() > columnCount())
+ return false;
+
+ PropertyNode &n = m_nodes[index.row() ];
+
+ if (role == Qt::CheckStateRole)
+ {
+ switch (index.column())
+ {
+ case 1:
+ n.setCreateGetter (value.toInt() == Qt::Checked ? true : false);
+ break;
+ case 4:
+ n.setCreateSetter (value.toInt() == Qt::Checked ? true : false);
+ break;
+ }
+ return true;
+ }
+
+ if (role == Qt::EditRole)
+ {
+ switch (index.column())
+ {
+ case 2:
+ n.setGetterAccess (value.toString());
+ break;
+ case 5:
+ n.setSetterAccess (value.toString());
+ break;
+ }
+ return true;
+ }
+
+ return false;
+}
+
+QVariant PropertyModel::data (const QModelIndex& index, int role) const
+{
+ if (index.row() > m_nodes.size() -1 || index.column() > columnCount())
+ return QVariant();
+
+ const PropertyNode &n = m_nodes[index.row() ];
+
+ if (role == Qt::CheckStateRole)
+ {
+ switch (index.column())
+ {
+ case 1:
+ return n.createGetter() ? Qt::Checked : Qt::Unchecked;
+ case 4:
+ return n.createSetter() ? Qt::Checked : Qt::Unchecked;
+ }
+ return QVariant();
+ }
+
+ if (role == Qt::EditRole)
+ {
+ switch (index.column())
+ {
+ case 1:
+ return n.createGetter() ? Qt::Checked : Qt::Unchecked;
+ case 2:
+ return n.getterAccess();
+ case 4:
+ return n.createSetter() ? Qt::Checked : Qt::Unchecked;
+ case 5:
+ return n.setterAccess();
+ }
+ return QVariant();
+ }
+
+ if (role == Qt::DecorationRole)
+ {
+ switch (index.column())
+ {
+ case 0:
+ return n.icon();
+ }
+ return QVariant();
+ }
+
+ if (role == Qt::ForegroundRole)
+ {
+ if (index.column() < 1)
+ return QColor (128,128,128);
+ }
+
+ if (role == Qt::DisplayRole)
+ {
+ switch (index.column())
+ {
+ case 0:
+ return n.name() + ":" + n.type();
+ case 1:
+ return QString();
+ case 2:
+ return n.getterAccess();
+ case 3:
+ return n.getterName();
+ case 4:
+ return QString();
+ case 5:
+ return n.setterAccess();
+ case 6:
+ return n.setterName();
+ }
+ }
+
+ return QVariant();
+}
+
+#include "propertymodel.moc"
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp (revision 1522570)
@@ -0,0 +1,31 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "csharppropertycreator.h"
+
+void CSharpPropertyCreator::create(PropertyModel* m)
+{
+ Q_UNUSED(m)
+}
+
+bool CSharpPropertyCreator::parse(PropertyModel* m, QList< KDevelop::Declaration* > selection)
+{
+ Q_UNUSED(m)
+ Q_UNUSED(selection)
+ return false;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h (revision 1522570)
@@ -0,0 +1,61 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef KDEVGETTERSETTERPLUGIN_H_
+#define KDEVGETTERSETTERPLUGIN_H_
+
+#include <interfaces/iplugin.h>
+
+#include <QVariantList>
+#include <KMimeType>
+
+class PropertyCreator;
+class KAction;
+
+using namespace KDevelop;
+
+namespace KDevelop
+{
+class Declaration;
+class DUContext;
+class ClassDeclaration ;
+class ClassMemberDeclaration ;
+}
+
+//kind = Type
+class GetterSetterPlugin: public KDevelop::IPlugin
+{
+ Q_OBJECT
+public:
+ GetterSetterPlugin (QObject *parent, const QVariantList & = QVariantList());
+ ~GetterSetterPlugin();
+ KDevelop::ContextMenuExtension contextMenuExtension (Context* context);
+ void createProperties (QList<Declaration*> decls);
+private slots:
+ void slotCreateProperties();
+ void slotWriteProperties();
+
+private:
+ static PropertyCreator * creatorForMime(const KMimeType::Ptr &mime);
+ static QList<Declaration*> cursorItemDeclarations();
+ //kind = Instance
+ KAction *m_action;
+};
+
+#endif //KDEVGETTERSETTERPLUGIN_H_
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp (revision 1522570)
@@ -0,0 +1,31 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "javapropertycreator.h"
+
+void JavaPropertyCreator::create(PropertyModel* m)
+{
+ Q_UNUSED(m)
+}
+
+bool JavaPropertyCreator::parse(PropertyModel* m, QList< KDevelop::Declaration* > selection)
+{
+ Q_UNUSED(m)
+ Q_UNUSED(selection)
+ return false;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp (revision 1522570)
@@ -0,0 +1,647 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#include "cpppropertycreator.h"
+#include "propertynode.h"
+#include "propertymodel.h"
+
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/classdeclaration.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainutils.h>
+#include <language/duchain/classfunctiondeclaration.h>
+#include <language/duchain/types/functiontype.h>
+#include <interfaces/idocument.h>
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+
+#include <KTextEditor/View>
+#include <KTextEditor/Document>
+#include <interfaces/isourceformattercontroller.h>
+#include <interfaces/isourceformatter.h>
+#include <interfaces/ilanguagecontroller.h>
+#include <interfaces/ilanguage.h>
+#include <language/interfaces/ilanguagesupport.h>
+#include <language/duchain/types/typeutils.h>
+#include <KLocalizedString>
+
+#define ERROR_MESSAGE ({KMessageBox::error(NULL, i18n(QString("An error occured while parsing the class. Please log a report. File: %1 Line: %2").arg(__FILE__).arg(__LINE__).toAscii().constData()));});
+#include <KDE/KMessageBox>
+
+CppPropertyCreator::CodeRange* CppPropertyCreator::getRange ( const QString& name )
+{
+ //There is only a small number so a loop should be fine
+ for ( int i = 0; i < m_ranges.size(); i++ )
+ {
+ if ( m_ranges.at ( i ).name == name )
+ return & ( m_ranges[i] );
+ }
+ return NULL;
+}
+
+
+int CppPropertyCreator::getRangeIndex ( const QString& name )
+{
+ //There is only a small number so a loop should be fine
+ for ( int i = 0; i < m_ranges.size(); i++ )
+ {
+ if ( m_ranges.at ( i ).name == name )
+ return i;
+ }
+ return -1;
+}
+
+
+
+void CppPropertyCreator::create ( PropertyModel* m )
+{
+ DUChainReadLocker lock ( DUChain::lock() );
+
+ ClassDeclaration * cd = m->klass();
+
+ IDocument* doc = ICore::self()->documentController()->documentForUrl ( cd->topContext()->url().toUrl() );
+ if ( !doc )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ KTextEditor::Document* textDoc = doc->textDocument();
+ if ( !textDoc )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ KTextEditor::View* view = textDoc->activeView();
+ if ( !view )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ //Turn on clumsy code TODO needs refactoring
+
+ QString text = textDoc->text ( m->klass()->internalContext()->range().textRange() );
+
+ //Used to see where we at in the file
+ int lineCount = m->klass()->internalContext()->range().start.line;
+ int *end = &lineCount;
+
+ //Find indentation etc in the text
+ static QRegExp publicExp ( "^(\\s*)public\\s*:.*" );
+ static QRegExp protectedExp ( "^(\\s*)protected\\s*:.*" );
+ static QRegExp privateExp ( "^(\\s*)private\\s*:.*" );
+ //A list of qt_properites to make sure we dont create them twice
+ QStringList qtProperties;
+ static QRegExp propertyExp ( "^.*Q_PROPERTY.*([\\w\\d_]+)\\s+(READ|WRITE).*" );
+ //Used for indentation when adding/inserting text
+ QString indent = "";
+ QString accessIndent = "";
+ static QRegExp indentExp ( "^(\\s+)\\w+.*" );
+
+ m_ranges.clear();
+ m_ranges.append ( CodeRange ( "head", lineCount, lineCount ) );
+ end = & ( getRange ( "head" )->lineEnd );
+
+ QStringList lines = text.split ( '\n' );
+ foreach ( const QString &line, lines )
+ {
+ //Single tab or space or \r or something
+ if(line.size() < 2) {
+ lineCount++;
+ continue;
+ }
+
+ //Skip inline classes
+ DUContext *duc = m->klass()->internalContext()->findContextAt ( SimpleCursor ( lineCount, 0 ) );
+ if ( duc && duc != m->klass()->internalContext() )
+ {
+ lineCount++;
+ continue;
+ }
+
+ if ( publicExp.exactMatch ( line ) )
+ {
+ if ( !getRange ( "public" ) )
+ m_ranges.append ( CodeRange ( "public" ) );
+ getRange ( "public" )->lineStart = lineCount;
+ *end = lineCount;
+ end = & ( getRange ( "public" )->lineEnd );
+ accessIndent = publicExp.cap ( 1 );
+ }
+ else if ( protectedExp.exactMatch ( line ) )
+ {
+ if ( !getRange ( "protected" ) )
+ m_ranges.append ( CodeRange ( "protected" ) );
+ getRange ( "protected" )->lineStart = lineCount;
+ *end = lineCount;
+ end = & ( getRange ( "protected" )->lineEnd );
+ accessIndent = protectedExp.cap ( 1 );
+ } else if ( privateExp.exactMatch ( line ) )
+ {
+ if ( !getRange ( "private" ) )
+ m_ranges.append ( CodeRange ( "private" ) );
+ getRange ( "private" )->lineStart = lineCount;
+ *end = lineCount;
+ end = & ( getRange ( "private" )->lineEnd );
+ accessIndent = privateExp.cap ( 1 );
+ } else if (propertyExp.exactMatch(line))
+ {
+ qtProperties.append(propertyExp.cap(1));
+ } else if ( indentExp.exactMatch ( line ) )
+ {
+ indent = indentExp.cap ( 1 );
+ }
+
+ lineCount++;
+ }
+ lineCount--;
+ *end = m->klass()->internalContext()->range().end.line;
+
+ foreach ( const PropertyNode &n, m->nodes() )
+ {
+ //GETTER
+ if ( n.createGetter() && n.canCreateGetter() )
+ {
+ QStringList itext ( "" );
+ QString text = QString ( "%1 %2() const { return %3; }" ).arg ( getterType ( n.type(), n.resolvedType(), n.whichType() ), n.getterName(), n.name() );
+
+ switch ( m->modifier() )
+ {
+ case PropertyModel::VIRTUAL:
+ text = QString ( "virtual " ) + text;
+ break;
+ case PropertyModel::PURE_VIRTUAL:
+ text = QString ( "virtual %1 %2() const = 0;" ).arg ( getterType ( n.type(), n.resolvedType(), n.whichType() ), n.getterName() );
+ break;
+ case PropertyModel::INLINE:
+ text = QString ( "inline " ) + text;
+ break;
+ }
+
+ CodeRange *range = getRange ( n.getterAccess() );
+ if ( !range )
+ {
+ m_ranges.append ( CodeRange ( n.getterAccess(), lineCount, lineCount ) );
+ range = getRange ( n.getterAccess() );
+ appendText ( doc, range, QStringList ( QString ( "%1:" ).arg ( n.getterAccess() ) ), accessIndent, &lineCount );
+ }
+
+ if ( m->createDocumentation() )
+ {
+ itext.append ( QString ( "/** Get method for %1." ).arg ( n.name() ) );
+ itext.append ( QString ( " * @see %1" ).arg ( n.name() ) );
+ itext.append ( QString ( " * @return %1" ).arg ( n.name() ) );
+ itext.append ( " */" );
+ }
+ itext.append ( text );
+ appendText ( doc, range, itext, indent, &lineCount );
+ }
+
+ //SETTER
+ if ( n.createSetter() && n.canCreateSetter() )
+ {
+ QStringList itext ( "" );
+ QString text = QString ( "void %1( %2 %4 ) { %3 = %4; }" ).arg ( n.setterName(), setterType ( n.type(), n.resolvedType(), n.whichType() ), n.name(), propertyAlias ( n.name() ) );
+
+ //We cant asign arrays, it needs a memcpy or something
+ if ( n.whichType() == AbstractType::TypeArray )
+ {
+ static QRegExp e ( "(.*)(\\[(\\d*)\\])" ); //ie int [255]
+ e.exactMatch ( n.type() );
+ text = QString ( "void %1( const %2 %3%4 ) { /*TODO*/ for(int i; i<%5; i++) %6[i] = %3[i]; }" ).arg ( n.setterName(), e.cap ( 1 ), propertyAlias ( n.name() ), e.cap ( 2 ), e.cap ( 3 ), n.name() );
+ }
+
+ switch ( m->modifier() )
+ {
+ case PropertyModel::VIRTUAL:
+ text = QString ( "virtual " ) + text;
+ break;
+ case PropertyModel::PURE_VIRTUAL:
+ text = QString ( "virtual void %1( %2 %3 ) = 0;" ).arg ( n.setterName(), setterType ( n.type(), n.resolvedType(), n.whichType() ), propertyAlias ( n.name() ) );
+ //We cant asign arrays, it needs a memcpy or something
+ if ( n.whichType() == AbstractType::TypeArray )
+ {
+ static QRegExp e ( "(.*)(\\[\\d*\\])" ); //ie int [255]
+ e.exactMatch ( n.type() );
+ text = QString ( "void %1( const %2 %3%4 ) = 0;" ).arg ( n.setterName(), e.cap ( 1 ), propertyAlias ( n.name() ), e.cap ( 2 ) );
+ }
+ break;
+ case PropertyModel::INLINE:
+ text = QString ( "inline " ) + text;
+ break;
+ }
+
+ CodeRange *range = getRange ( n.setterAccess() );
+ if ( !range )
+ {
+ m_ranges.append ( CodeRange ( n.setterAccess(), lineCount, lineCount ) );
+ range = getRange ( n.setterAccess() );
+ appendText ( doc, range, QStringList ( QString ( "%1:" ).arg ( n.setterAccess() ) ), accessIndent, &lineCount );
+ }
+
+ if ( m->createDocumentation() )
+ {
+ itext.append ( QString ( "/** Set method for %1." ).arg ( n.name() ) );
+ itext.append ( QString ( " * @see %1" ).arg ( n.name() ) );
+ itext.append ( QString ( " * @param %1 Value for %2." ).arg ( propertyAlias ( n.name() ), n.name() ) );
+ itext.append ( " */" );
+ }
+
+ itext.append ( text );
+ appendText ( doc, range, itext, indent, &lineCount );
+ }
+
+ //Q_PROPERTY
+ if ( m->hasQObject() &&
+ m->createQtProperties() &&
+ ( n.createGetter() || n.createSetter() ) &&
+ !qtProperties.contains(propertyName(n.name())))
+ {
+ QStringList itext;
+ QString type = qPropertyType ( n.type(), n.resolvedType(), n.whichType() );
+ if ( !type.isNull() )
+ {
+ QString text = QString ( "Q_PROPERTY(%1 %2%3%4)" ).arg ( type,
+ propertyName ( n.name() ),
+ n.createGetter() && n.createGetter() ? QString ( " READ %1" ).arg ( getterName ( n.name() ) ) : "",
+ n.createSetter() && n.createSetter() ? QString ( " WRITE %1" ).arg ( setterName ( n.name() ) ) : "" );
+ CodeRange *range = getRange ( "head" );
+ itext.append ( text );
+ appendText ( doc, range, itext, indent, &lineCount );
+ }
+ }
+ }
+
+ //TODO while(true) { Turn off clumsy code!! }
+}
+
+
+void CppPropertyCreator::appendText ( IDocument *doc, CodeRange *range, const QStringList &text, const QString &indent, int *lineCount )
+{
+ if ( !doc || !range )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+ KTextEditor::Document* textDoc = doc->textDocument();
+ if ( !textDoc )
+ {
+ ERROR_MESSAGE
+ return;
+ }
+
+ QStringList itext;
+
+ if ( ICore::self() )
+ {
+ QString t = ICore::self()->sourceFormatterController()->formatterForUrl ( doc->url() )->formatSource ( text.join ( "\n" ) ,doc->mimeType() );
+ itext = t.split ( "\n" );
+ }
+ while ( itext.last().size() == 0 || itext.last() == "\n" )
+ itext.removeLast();
+
+ for ( int i= 0; i < itext.size(); i++ )
+ {
+ textDoc->insertLine ( range->lineEnd, indent + itext[i] );
+ range->lineEnd+=1;
+ if ( lineCount )
+ *lineCount = *lineCount + 1;
+ }
+ for ( int i = getRangeIndex ( range->name ) + 1; i < m_ranges.size(); i++ )
+ {
+ m_ranges[i].lineStart += itext.size();
+ m_ranges[i].lineEnd += itext.size();
+ }
+}
+
+bool CppPropertyCreator::parse ( PropertyModel* m, QList<Declaration*> selection )
+{
+ DUChainReadLocker lock ( DUChain::lock() );
+ QList<PropertyNode> nodes;
+
+ //Damn - just making sure we get a class.
+ ClassDeclaration *klass = NULL;
+ foreach ( Declaration* decl, selection )
+ {
+ if ( decl && decl->context() && decl->context()->type() == DUContext::Class )
+ {
+ klass = dynamic_cast<ClassDeclaration *> ( decl->context()->owner() );
+ if ( klass ) break;
+ }
+ else if ( decl && decl->internalContext() && decl->internalContext()->type() == DUContext::Class )
+ {
+ klass = dynamic_cast<ClassDeclaration *> ( decl->internalContext()->owner() );
+ if ( klass ) break;
+ }
+ klass = dynamic_cast<ClassDeclaration *> ( decl );
+ if ( klass ) break;
+ }
+
+ //We did not?
+ if ( !klass )
+ {
+ ERROR_MESSAGE
+ return false;
+ }
+
+ m->setKlass ( klass );
+
+ foreach ( Declaration* decl, klass->internalContext()->localDeclarations() )
+ {
+ ClassMemberDeclaration* memDecl = dynamic_cast<ClassMemberDeclaration*> ( decl );
+ if ( !memDecl )
+ continue;
+
+ if ( ! ( !memDecl->isFunctionDeclaration() && memDecl->kind() == Declaration::Instance ) )
+ continue;
+
+ //TODO This depends on staticMetaObject being at the begining of the loop
+ if ( memDecl->identifier().toString() == "staticMetaObject" )
+ {
+ m->setHasQObject ( true );
+ continue;
+ }
+
+ PropertyNode n;
+ n.setName ( memDecl->identifier().toString() );
+ n.setType ( memDecl->abstractType()->toString() );
+ AbstractType::Ptr aptr = TypeUtils::unAliasedType ( memDecl->abstractType() );
+ n.setResolvedType ( aptr->toString() );
+ n.setWhichType ( aptr->whichType() );
+ n.setGetterName ( getterName ( n.name() ) );
+ n.setSetterName ( setterName ( n.name() ) );
+
+ /*(The users selection) NOTE I dont know if comparing the pointers is valid?
+ But the duchain was locked before calling this routine so its should be.
+ */
+ foreach ( Declaration* decl, selection )
+ {
+ if ( memDecl == decl )
+ {
+ n.setCreateGetter ( true );
+ n.setCreateSetter ( true );
+ }
+ }
+
+ //ie: const int& TODO get modifier from duchain rather
+ if ( ( n.whichType() == AbstractType::TypeReference || n.whichType() == AbstractType::TypeArray ) &&
+ ( n.type().contains ( "const" ) || n.resolvedType().contains ( "const" ) ) )
+ {
+ n.setCanCreateSetter ( false );
+ n.setCreateSetter ( false );
+ }
+
+ foreach ( Declaration * d, klass->internalContext()->localDeclarations() )
+ {
+ ClassFunctionDeclaration * dm = dynamic_cast<ClassFunctionDeclaration*> ( d );
+ if ( !dm )
+ continue;
+
+ FunctionType::Ptr ft = dm->abstractType().cast<FunctionType>();
+ if ( !ft )
+ continue;
+ if ( !ft->returnType() )
+ continue;
+
+ QString access = "default";
+ switch ( dm->accessPolicy() )
+ {
+ case Declaration::Public:
+ access = "public";
+ break;
+ case Declaration::Protected:
+ access = "protected";
+ break;
+ case Declaration::Private:
+ access = "private";
+ break;
+ }
+
+ if ( dm->identifier().toString() == n.getterName() &&
+ ft->arguments().size() == 0 &&
+ ft->modifiers() & AbstractType::ConstModifier )
+ {
+ n.setCanCreateGetter ( false );
+ n.setCreateGetter ( true );
+ n.setGetterAccess ( access );
+ continue;
+ }
+
+ if ( dm->identifier().toString() == n.setterName() &&
+ ft->returnType()->toString() == "void" &&
+ ft->arguments().size() == 1 &&
+ ft->arguments() [0]->toString() == setterType ( n.type(), n.resolvedType(), n.whichType() ) )
+ {
+ n.setCanCreateSetter ( false );
+ n.setCreateSetter ( true );
+ n.setSetterAccess ( access );
+ continue;
+ }
+ }
+ nodes.append ( n );
+ }
+
+ m->setNodes ( nodes );
+
+ return true;
+}
+
+
+QString CppPropertyCreator::propertyAlias ( const QString& property )
+{
+ if ( property.isNull() )
+ {
+ ERROR_MESSAGE
+ return "null";
+ }
+
+ QString p = propertyName ( property );
+ QString r = "";
+ r += p[0];
+ bool kase = false;
+ for ( int i = 1; i < p.size(); i++ )
+ {
+ if ( p[i].isUpper() && kase == false )
+ {
+ r += p[i].toLower();
+ kase = true;
+ }
+ if ( p[i].isLower() && kase == true )
+ kase = false;
+ if ( p[i] == '_' && i < p.size() - 1 )
+ r += p[i+1];
+ }
+
+ if ( r == property )
+ r = QString ( "_%1" ).arg ( r );
+ return r;
+}
+
+
+QString CppPropertyCreator::propertyName ( const QString& property )
+{
+ if ( property.isNull() )
+ {
+ ERROR_MESSAGE
+ return "null";
+ }
+
+ QString n = QString ( "%1" ).arg ( property );
+ if ( property.size() > 1 && property[0] == 'm' && property[1].isUpper() )
+ n = n.remove ( ( {static QRegExp e ( "(^m_)|(^m)|(^_+)" ); e;} ) );
+ else
+ n = n.remove ( ( {static QRegExp e ( "(^m_)|(^_+)" ); e;} ) );
+ n[0] = n[0].toLower();
+ return n;
+}
+
+QString CppPropertyCreator::getterName ( const QString& property )
+{
+ if ( property.isNull() )
+ {
+ ERROR_MESSAGE
+ return "null";
+ }
+
+ QString n = propertyName ( property );
+ if ( n == property )
+ {
+ n[0] = n[0].toUpper();
+ n = QString ( "get%1" ).arg ( n );
+ }
+ return n;
+}
+
+QString CppPropertyCreator::setterName ( const QString& property )
+{
+ if ( property.isNull() )
+ {
+ ERROR_MESSAGE
+ return QString();
+ }
+
+ QString n = propertyName ( property );
+ n[0] = n[0].toUpper();
+ return QString ( "set%1" ).arg ( n );
+}
+
+QString CppPropertyCreator::qPropertyType ( const QString& abstractType, const QString& resolvedType, AbstractType::WhichType type )
+{
+ if ( abstractType.isNull() || resolvedType.isNull() )
+ {
+ ERROR_MESSAGE
+ return QString();
+ }
+
+ bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
+
+ /*
+ 1 cant create property for pointer has to be const * ie:
+ - int * t must be const int * t; -> Q_PROPERTY ( const int * t3 READ getT3 WRITE setT3 )
+ 2 array must have const int *
+ - int t4[100]; Q_PROPERTY ( const int* t4 READ getT4 WRITE setT4 )
+ */
+
+ //Arrays
+ if ( type == AbstractType::TypeArray )
+ {
+ if ( hasConst )
+ return QString ( "%1*" ).arg ( QString ( resolvedType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
+ return QString ( "const %1*" ).arg ( QString ( resolvedType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
+ }
+
+ if ( type == AbstractType::TypePointer )
+ {
+ if ( !hasConst )
+ return QString();
+ return resolvedType;
+ }
+
+ return QString ( resolvedType ).remove ( ( {static QRegExp e ( "(const)|([&]*)" ); e; }) );
+}
+
+QString CppPropertyCreator::getterType ( const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type )
+{
+ if ( abstractType.isNull() || resolvedType.isNull() )
+ {
+ ERROR_MESSAGE
+ return QString();
+ }
+
+ //TODO This could and probably should come from the DUChain 'modifier'
+ bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
+
+ //Primitives
+ if ( type == AbstractType::TypeIntegral || type == AbstractType::TypeEnumeration )
+ return QString ( abstractType ).remove ( "const" );
+
+ //Array's see writerType() //ie int [255]
+ if ( type == AbstractType::TypeArray )
+ {
+ if ( hasConst )
+ return QString ( "%1*" ).arg ( QString ( abstractType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
+ return QString ( "const %1*" ).arg ( QString ( abstractType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
+ }
+
+ //References and pointer
+ if ( type == AbstractType::TypePointer || type == AbstractType::TypeReference )
+ {
+ if ( hasConst )
+ return QString ( abstractType );
+ return QString ( "const %1" ).arg ( abstractType );
+ }
+
+ //Whats left
+ if ( hasConst )
+ return QString ( "%1&" ).arg ( abstractType );
+ return QString ( "const %1&" ).arg ( abstractType );
+}
+
+QString CppPropertyCreator::setterType ( const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type )
+{
+ if ( abstractType.isNull() || resolvedType.isNull() )
+ {
+ ERROR_MESSAGE
+ return QString();
+ }
+
+ //TODO This could and probably should come from the DUChain 'modifier'
+ bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
+
+ //Arrays need a special implementation, this is only used to compare parameters //ie const int [255]
+ if ( type == AbstractType::TypeArray )
+ return QString ( "const %1" ).arg ( abstractType );
+
+ //Primitives
+ if ( type == AbstractType::TypeIntegral || type == AbstractType::TypeEnumeration )
+ return QString ( abstractType ).remove ( "const" );
+
+ //References and pointer
+ if ( type == AbstractType::TypePointer || type == AbstractType::TypeReference )
+ return QString ( "%1" ).arg ( abstractType );
+
+ //Whats left
+ if ( hasConst )
+ return QString ( "%1&" ).arg ( abstractType );
+ return QString ( "const %1&" ).arg ( abstractType );
+}
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on; replace-tabs on; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertymodel.h (revision 1522570)
@@ -0,0 +1,141 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#ifndef PROPERTYMODEL_H
+#define PROPERTYMODEL_H
+
+#include <QtCore/QAbstractTableModel>
+#include <QtCore/QModelIndex>
+#include <QtCore/QVariant>
+#include <QtCore/QString>
+
+
+#include "propertynode.h"
+
+using namespace KDevelop;
+
+namespace KDevelop
+{
+class ClassDeclaration ;
+class ClassMemberDeclaration ;
+}
+
+class PropertiesDialog;
+
+/** Stores property selection/display info and a handle to the class in question.
+ * Use PropertyCreator to populate and ProperiesDialog to display.
+ */
+class PropertyModel : public QAbstractTableModel
+{
+ Q_OBJECT
+
+ friend class PropertiesDialog;
+public:
+
+ PropertyModel (QObject *parent = 0);
+ ~PropertyModel();
+
+ enum Modifier {FINAL, VIRTUAL, PURE_VIRTUAL, INLINE};
+
+ virtual int columnCount (const QModelIndex& parent = QModelIndex()) const
+ {
+ Q_UNUSED (parent);
+ return 7;
+ }
+
+ virtual QVariant data (const QModelIndex& index, int role = Qt::DisplayRole) const;
+
+ virtual bool setData (const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
+
+ virtual int rowCount (const QModelIndex& parent = QModelIndex()) const
+ {
+ Q_UNUSED (parent);
+ return m_nodes.size();
+ }
+
+ virtual QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+
+
+ virtual Qt::ItemFlags flags (const QModelIndex& index) const;
+
+ virtual bool createQtProperties() const
+ {
+ return m_createQtProperties;
+ }
+
+ virtual bool hasQObject() const
+ {
+ return m_hasQObject;
+ }
+
+ const QList< PropertyNode >& nodes() const
+ {
+ return m_nodes;
+ }
+
+ void setNodes (const QList< PropertyNode > &n)
+ {
+ m_nodes = n;
+ }
+
+ void setHasQObject (bool hq)
+ {
+ m_hasQObject = hq;
+ }
+
+ void setCreateQtProperties (bool cqp)
+ {
+ m_createQtProperties = cqp;
+ }
+
+ Modifier modifier() const
+ {
+ return m_modifier;
+ }
+
+ void setModifier (Modifier m)
+ {
+ m_modifier = m;
+ }
+
+ bool createDocumentation() const
+ {
+ return m_createDocumentation;
+ }
+
+ void setCreateDocumentation (bool cd)
+ {
+ m_createDocumentation = cd;
+ }
+
+
+ virtual KDevelop::ClassDeclaration* klass() const { return m_klass; }
+
+ virtual void setKlass ( KDevelop::ClassDeclaration* k ) { m_klass = k; }
+protected:
+ QList<PropertyNode> m_nodes;
+ bool m_hasQObject;
+ bool m_createQtProperties;
+ bool m_createDocumentation;
+ Modifier m_modifier;
+ ClassDeclaration * m_klass;
+};
+
+#endif // PROPERTYMODEL_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h (revision 1522570)
@@ -0,0 +1,30 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef CSHARPPROPERTYCREATOR_H
+#define CSHARPPROPERTYCREATOR_H
+
+#include <propertcreator.h>
+
+
+class CSharpPropertyCreator : public PropertyCreator
+{
+ virtual void create(PropertyModel* m);
+ virtual bool parse(PropertyModel* m, QList< KDevelop::Declaration* > selection);
+};
+
+#endif // CSHARPPROPERTYCREATOR_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h (revision 1522570)
@@ -0,0 +1,31 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef JAVAPROPERTYCREATOR_H
+#define JAVAPROPERTYCREATOR_H
+
+#include <propertcreator.h>
+
+#include <QString>
+
+class JavaPropertyCreator : public PropertyCreator
+{
+ virtual void create(PropertyModel* m);
+ virtual bool parse(PropertyModel* m, QList< KDevelop::Declaration* > selection);
+};
+
+#endif // JAVAPROPERTYCREATOR_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h (revision 1522570)
@@ -0,0 +1,109 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef CPPPROPERTYCREATOR_H
+#define CPPPROPERTYCREATOR_H
+
+#include "propertcreator.h"
+#include <QString>
+#include <QList>
+#include <KMessageBox>
+#include <language/duchain/types/abstracttype.h>
+
+namespace KDevelop
+{
+ class IDocument;
+ class DUContext;
+ class Declaration;
+}
+
+class PropertyNode;
+
+class CppPropertyCreator : public PropertyCreator
+{
+public:
+ bool parse (PropertyModel * m, QList<Declaration*> selection);
+ void create (PropertyModel * m);
+
+private:
+ /** Used to block head, public, protected, private int the text.<br/>
+ * @todo This works only on lines and not columns, the same for the regular expressions to find these blocks.
+ */
+ class CodeRange
+ {
+ public:
+ CodeRange() : lineStart (0), lineEnd (0) {}
+ CodeRange(const CodeRange& o) : name(o.name), lineStart (o.lineStart), lineEnd (o.lineEnd) {}
+ CodeRange (const QString & n) : name (n), lineStart (0), lineEnd (0) {}
+ CodeRange (const QString & n, int s, int e) : name (n), lineStart (s), lineEnd (e) {}
+ virtual ~CodeRange() {}
+ QString name;
+ int lineStart;
+ int lineEnd;
+ };
+
+ /** Used to block head, public, protected, private in the text.<br/>
+ * @todo This works only on lines and not columns, the same for the regular expressions to find these blocks.
+ */
+ QList<CodeRange> m_ranges;
+
+ /** Return a range identified by a QString.
+ * @see CppPropertyCreator::CodeRange
+ */
+ CodeRange *getRange (const QString &name);
+
+ /** Return a range index into m_ranges identified by a QString.
+ * @see CppPropertyCreator::CodeRange
+ */
+ int getRangeIndex (const QString &name);
+
+ /** Append text at the end of a range.
+ */
+ void appendText(IDocument *doc, CodeRange *range, const QStringList &text, const QString &indent = "", int *lineCount = NULL);
+
+ /** Returns a name like getSomeValue for someValue.
+ */
+ QString getterName (const QString &property);
+
+ /** Returns a name like setSomeValue for someValue.
+ */
+ QString setterName (const QString &property);
+
+ /** Returns a name like someValue for m_someValue.
+ */
+ QString propertyName (const QString &property);
+
+ /** Returns a name like sv for m_someValue.
+ */
+ QString propertyAlias (const QString &property);
+
+ /** Try's to return the correct type for QT_PROPERTY's.
+ */
+ QString qPropertyType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
+
+ /** Try's to return the correct type for the reader ie const QString & when the type is QString.
+ */
+ QString getterType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
+
+ /** Try's to return the correct type for the writer ie const QString & when the type is QString.
+ */
+ QString setterType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
+};
+
+#endif //CPPPROPERTYCREATOR_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp (revision 1522570)
@@ -0,0 +1,141 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#include "propertiesdialog.h"
+
+#include "propertymodel.h"
+#include "ui_propertiesform.h"
+#include "propertydelegate.h"
+
+PropertiesDialog::PropertiesDialog (QWidget* parent, Qt::WFlags flags) :
+ KDialog (parent, flags),
+ m_form (0),
+ m_model (0)
+{
+ QWidget * w = new QWidget (this);
+ m_form = new Ui::propertiesForm;
+ m_form->setupUi (w);
+
+ m_form->comboBoxModifier->addItem ("default", PropertyModel::FINAL);
+ m_form->comboBoxModifier->addItem ("virtual", PropertyModel::VIRTUAL);
+ m_form->comboBoxModifier->addItem ("pure virtual", PropertyModel::PURE_VIRTUAL);
+ m_form->comboBoxModifier->addItem ("inline", PropertyModel::INLINE);
+
+ m_form->tableView->setItemDelegateForColumn (2, new AccessListDelegate (m_form->tableView));
+ m_form->tableView->setItemDelegateForColumn (5, new AccessListDelegate (m_form->tableView));
+ m_form->tableView->horizontalHeader()->setResizeMode (QHeaderView::Interactive);
+
+ connect (m_form->buttonSelectAll, SIGNAL (clicked()), this, SLOT (selectAll()));
+ connect (m_form->buttonDeselectAll, SIGNAL (clicked()), this, SLOT (deselectAll()));
+ connect (m_form->checkBoxQtProp, SIGNAL (clicked (bool)), this, SLOT (createQtProperties (bool)));
+ connect (m_form->checkBoxDocumentation, SIGNAL (clicked (bool)), this, SLOT (createDocumentation (bool)));
+ connect (m_form->comboBoxModifier, SIGNAL (currentIndexChanged (int)), this, SLOT (changeModifier (int)));
+
+ setMainWidget (w);
+ resize (600,350);
+}
+
+PropertiesDialog::~PropertiesDialog()
+{
+ delete m_form;
+}
+
+
+void PropertiesDialog::setModel (PropertyModel* model)
+{
+ m_form->tableView->setModel (0);
+ m_form->tableView->reset();
+
+ m_model = model;
+
+ if (!m_model->m_hasQObject)
+ {
+ m_form->checkBoxQtProp->setEnabled (false);
+ m_form->checkBoxQtProp->setVisible (false);
+ m_model->m_createQtProperties = false;
+ }
+ else
+ {
+ m_form->checkBoxQtProp->setEnabled (true);
+ m_form->checkBoxQtProp->setVisible (true);
+ m_model->m_createQtProperties = m_form->checkBoxQtProp->checkState() == Qt::Checked;
+ }
+
+ m_model->m_createDocumentation = m_form->checkBoxDocumentation->checkState() == Qt::Checked;
+
+ m_model->setModifier ( (PropertyModel::Modifier) m_form->comboBoxModifier->itemData (m_form->comboBoxModifier->currentIndex()).toInt());
+
+ m_form->tableView->setModel (m_model);
+ m_form->tableView->reset();
+ m_form->tableView->resizeColumnsToContents();
+}
+
+void PropertiesDialog::show (PropertyModel * model)
+{
+ setModel (model);
+ KDialog::show();
+}
+
+
+void PropertiesDialog::deselectAll()
+{
+ for (int i = 0; i < m_model->m_nodes.size(); i++)
+ {
+ PropertyNode &node = m_model->m_nodes[i];
+ if (node.canCreateGetter())
+ node.setCreateGetter (false);
+ if (node.canCreateSetter())
+ node.setCreateSetter (false);
+ }
+ m_form->tableView->reset();
+}
+
+
+void PropertiesDialog::selectAll()
+{
+ for (int i = 0; i < m_model->m_nodes.size(); i++)
+ {
+ PropertyNode &node = m_model->m_nodes[i];
+ if (node.canCreateGetter())
+ node.setCreateGetter (true);
+ if (node.canCreateSetter())
+ node.setCreateSetter (true);
+ }
+ m_form->tableView->reset();
+}
+
+void PropertiesDialog::createQtProperties (bool create)
+{
+ m_model->m_createQtProperties = create;
+}
+
+
+void PropertiesDialog::createDocumentation (bool create)
+{
+ m_model->m_createDocumentation = create;
+}
+
+void PropertiesDialog::changeModifier (int index)
+{
+ m_model->setModifier ( (PropertyModel::Modifier) m_form->comboBoxModifier->itemData (index).toInt());
+}
+
+
+#include "propertiesdialog.moc"
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp (revision 1522570)
@@ -0,0 +1,90 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#include "propertydelegate.h"
+
+AccessListDelegate::AccessListDelegate (QObject *parent) : QItemDelegate (parent)
+{
+}
+
+QWidget * AccessListDelegate::createEditor (QWidget *parent, const QStyleOptionViewItem &option,
+ const QModelIndex &index) const
+{
+ Q_UNUSED (index);
+ Q_UNUSED (option);
+ QComboBox * box = new QComboBox (parent);
+ populateList (box);
+ box->setAutoFillBackground (true);
+ return box;
+}
+
+void AccessListDelegate::setEditorData (QWidget *editor, const QModelIndex &index) const
+{
+ QComboBox * box = dynamic_cast<QComboBox *> (editor);
+ if (!box)
+ {
+ kDebug() << "Null editor";
+ return;
+ }
+
+ //Selected
+ QVariant sel = index.model()->data (index, Qt::EditRole);
+ box->setCurrentIndex (box->findData (sel, Qt::DisplayRole));
+
+}
+void AccessListDelegate::setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
+{
+ QComboBox * box = dynamic_cast<QComboBox *> (editor);
+ if (!box)
+ {
+ kDebug() << "Null editor";
+ return;
+ }
+
+ QVariant var = box->itemData (box->currentIndex(), Qt::DisplayRole);
+ if (!var.isValid())
+ return;
+
+ model->setData (index, var, Qt::EditRole);
+}
+
+void AccessListDelegate::updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
+{
+ Q_UNUSED (index);
+ QComboBox * box = dynamic_cast<QComboBox *> (editor);
+ if (!box)
+ {
+ kDebug() << "Null editor";
+ return;
+ }
+ QRect r = option.rect;
+ r.setWidth (box->contentsRect().width());
+ box->setGeometry (r);
+}
+
+void AccessListDelegate::populateList (QComboBox * box) const
+{
+ box->insertItem (0,"public");
+ box->setItemData (0, "public", Qt::DisplayRole);
+ box->insertItem (1,"protected");
+ box->setItemData (1, "protected", Qt::DisplayRole);
+ box->insertItem (2,"private");
+ box->setItemData (2, "private", Qt::DisplayRole);
+}
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertcreator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertcreator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertcreator.h (revision 1522570)
@@ -0,0 +1,43 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef PROPERTYCREATOR_H
+#define PROPERTYCREATOR_H
+
+#include <QtCore/QList>
+
+class PropertyModel;
+
+namespace KDevelop
+{
+class DUContext;
+class Declaration;
+}
+
+using namespace KDevelop;
+
+class PropertyCreator
+{
+public:
+ virtual ~PropertyCreator() {};
+ virtual bool parse (PropertyModel * m, QList<Declaration*> selection) = 0;
+ virtual void create (PropertyModel * m) = 0;
+};
+
+#endif //PROPERTYCREATOR_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h (revision 1522570)
@@ -0,0 +1,55 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#ifndef PROPERTIESDIALOG_H
+#define PROPERTIESDIALOG_H
+
+#include <KDialog>
+
+class PropertyModel;
+namespace Ui
+{
+class propertiesForm;
+}
+class PropertiesDialog : public KDialog
+{
+ Q_OBJECT
+
+public:
+ explicit PropertiesDialog (QWidget* parent = 0, Qt::WFlags flags = 0);
+ virtual ~PropertiesDialog();
+ void show (PropertyModel * model);
+ void setModel (PropertyModel * model);
+ PropertyModel * model()
+ {
+ return m_model;
+ }
+public slots:
+ void selectAll();
+ void deselectAll();
+ void createQtProperties (bool create);
+ void createDocumentation (bool create);
+ void changeModifier (int index);
+protected:
+ Ui::propertiesForm * m_form;
+ PropertyModel *m_model;
+};
+
+#endif // PROPERTIESDIALOG_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertydelegate.h (revision 1522570)
@@ -0,0 +1,48 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+#ifndef ACCESSITEMDELEGATE_H
+#define ACCESSITEMDELEGATE_H
+
+#include <QtGui/QItemDelegate>
+#include <QtCore/QModelIndex>
+#include <QtGui/QStyleOptionViewItem>
+#include <QtGui/QComboBox>
+#include <QtCore/QAbstractItemModel>
+#include <KDebug>
+
+class AccessListDelegate : public QItemDelegate
+{
+public:
+ AccessListDelegate (QObject *parent = 0);
+
+ QWidget *createEditor (QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
+
+ void setEditorData (QWidget *editor, const QModelIndex &index) const;
+
+ void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
+
+ void updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
+
+private:
+
+ void populateList (QComboBox * box) const;
+};
+
+#endif // ACCESSITEMDELEGATE_H
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertynode.cpp (revision 1522570)
@@ -0,0 +1,49 @@
+/*****************************************************************************
+ * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 3 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ *****************************************************************************/
+
+
+#include "propertynode.h"
+#include "propertymodel.h"
+
+#include <QtCore/QRegExp>
+
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainutils.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/classdeclaration.h>
+#include <language/duchain/classmemberdeclaration.h>
+#include <KMessageBox>
+
+PropertyNode::PropertyNode ()
+{
+ m_createGetter = false;
+ m_createSetter = false;
+ m_canCreateGetter = true;
+ m_canCreateSetter = true;
+ m_getterAccess = "public";
+ m_setterAccess = "public";
+}
+
+PropertyNode::~PropertyNode()
+{
+
+}
+
+
+
+// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,45 @@
+PROJECT(kdevgettersetter)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${kdevgettersetter_SOURCE_DIR}/cmake)
+
+add_definitions(-DKDE_DEFAULT_DEBUG_AREA=9525)
+
+set(KDE_MIN_VERSION "4.2.0")
+
+
+find_package(KDE4 4.2.0 REQUIRED)
+find_package(KDevPlatform 0.9.95 REQUIRED)
+
+include (KDE4Defaults)
+
+add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS} -DHAVE_CONFIG_H=1)
+
+include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR} )
+
+set(kdevgettersetter_PART_SRCS
+ gettersetterplugin.cpp
+ propertynode.cpp
+ propertymodel.cpp
+ propertiesdialog.cpp
+ propertydelegate.cpp
+ cpppropertycreator.cpp
+ javapropertycreator.cpp
+ csharppropertycreator.cpp
+)
+kde4_add_ui_files( kdevgettersetter_PART_SRCS propertiesform.ui )
+
+kde4_add_plugin(kdevgettersetter ${kdevgettersetter_PART_SRCS})
+
+
+target_link_libraries(kdevgettersetter
+ ${KDE4_KDEUI_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+)
+
+install(TARGETS kdevgettersetter DESTINATION ${PLUGIN_INSTALL_DIR} )
+
+
+########### install files ###############
+install( FILES kdevgettersetter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevgettersetter.rc DESTINATION ${DATA_INSTALL_DIR}/kdevgettersetter )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevgettersetter.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesform.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesform.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/propertiesform.ui (revision 1522570)
@@ -0,0 +1,128 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>propertiesForm</class>
+ <widget class="QWidget" name="propertiesForm">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>600</width>
+ <height>350</height>
+ </rect>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>500</width>
+ <height>200</height>
+ </size>
+ </property>
+ <property name="windowTitle">
+ <string>Properties</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QComboBox" name="comboBoxModifier">
+ <property name="insertPolicy">
+ <enum>QComboBox::InsertAtBottom</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="checkBoxDocumentation">
+ <property name="text">
+ <string>Documentation</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="checkBoxQtProp">
+ <property name="text">
+ <string notr="true">QT_PROPERTY's</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonSelectAll">
+ <property name="text">
+ <string>Select All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonDeselectAll">
+ <property name="text">
+ <string>Deselect All</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QTableView" name="tableView">
+ <property name="editTriggers">
+ <set>QAbstractItemView::AllEditTriggers</set>
+ </property>
+ <property name="alternatingRowColors">
+ <bool>true</bool>
+ </property>
+ <property name="selectionMode">
+ <enum>QAbstractItemView::NoSelection</enum>
+ </property>
+ <property name="selectionBehavior">
+ <enum>QAbstractItemView::SelectRows</enum>
+ </property>
+ <property name="showGrid">
+ <bool>false</bool>
+ </property>
+ <property name="sortingEnabled">
+ <bool>false</bool>
+ </property>
+ <property name="wordWrap">
+ <bool>false</bool>
+ </property>
+ <attribute name="horizontalHeaderVisible">
+ <bool>true</bool>
+ </attribute>
+ <attribute name="horizontalHeaderCascadingSectionResizes">
+ <bool>false</bool>
+ </attribute>
+ <attribute name="horizontalHeaderDefaultSectionSize">
+ <number>25</number>
+ </attribute>
+ <attribute name="horizontalHeaderMinimumSectionSize">
+ <number>25</number>
+ </attribute>
+ <attribute name="horizontalHeaderShowSortIndicator" stdset="0">
+ <bool>false</bool>
+ </attribute>
+ <attribute name="horizontalHeaderStretchLastSection">
+ <bool>false</bool>
+ </attribute>
+ <attribute name="verticalHeaderVisible">
+ <bool>false</bool>
+ </attribute>
+ <attribute name="verticalHeaderHighlightSections">
+ <bool>false</bool>
+ </attribute>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc (revision 1522570)
@@ -0,0 +1,9 @@
+<!DOCTYPE kpartgui>
+<kpartgui name="kdevgettersetter" version="1">
+<MenuBar>
+ <Menu name="edit" >
+ <text context="@title:menu">Edit</text>
+ <Action name="generate_gettersetter" group="edit_formatting"/>
+ </Menu>
+</MenuBar>
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop (revision 1522570)
@@ -0,0 +1,68 @@
+[Desktop Entry]
+Type=Service
+Comment=This plugin helps you to remove unneeded include directives
+Comment[bs]=Ovaj dodatak vam pomaže da uklonite nepotrebne trenutno uključene direktive.
+Comment[ca]=Aquest connector us ajuda a eliminar les directives d'inclusió no necessàries
+Comment[ca@valencia]=Aquest connector vos ajuda a eliminar les directives d'inclusió no necessàries
+Comment[de]=Diese Modul hilft beim Entfernen unnötiger Include-Anweisungen
+Comment[en_GB]=This plugin helps you to remove unneeded include directives
+Comment[es]=Este complemento le ayuda a eliminar directivas include no necesarias
+Comment[et]=See plugin aitab eemaldada ebavajalikud kaasamisdirektiivid
+Comment[fr]=Ce module externe vous aide à supprimer des directives d'inclusion non nécessaires
+Comment[gl]=Este complemento axúdao a retirar directivas de inclusión innecesarias.
+Comment[it]=Questa estensione ti aiuta a rimuovere le direttive include non necessarie
+Comment[nl]=Deze plugin helpt u met het verwijderen van onnodige include directives
+Comment[pl]=Wtyczka ta pomaga tobie usunąć niepotrzebne dyrektywy plików dołączanych
+Comment[pt]=Este 'plugin' ajuda-o a remover as directivas de inclusão desnecessárias
+Comment[pt_BR]=Este plugin ajuda-o a remover as diretivas de inclusão desnecessárias
+Comment[sv]=Insticksprogrammet hjälper till att ta bort onödiga inkluderingsdirektivInkludera kommentarer
+Comment[uk]=За допомогою цього додатка ви зможете вилучити непотрібні команди include
+Comment[x-test]=xxThis plugin helps you to remove unneeded include directivesxx
+Name=Include Manager
+Name[bs]=Menadžer uključivanja.
+Name[ca]=Gestor d'inclusió
+Name[ca@valencia]=Gestor d'inclusió
+Name[de]=Include-Verwaltung
+Name[en_GB]=Include Manager
+Name[es]=Gestor de inclusiones
+Name[et]=Päisehaldur
+Name[fr]=Gestionnaire d'inclusions
+Name[gl]=Xestor de inclusións
+Name[it]=Include Manager
+Name[nl]=Include-beheer
+Name[pl]=Menadżer dołączania
+Name[pt]=Gestor de Inclusões
+Name[pt_BR]=Gerenciador de inclusões
+Name[sk]=Správca rozšírení
+Name[sv]=Inkluderingshanterare
+Name[uk]=Керування включеннями
+Name[x-test]=xxInclude Managerxx
+GenericName=Include Manager
+GenericName[bs]=Menadžer uključivanja.
+GenericName[ca]=Gestor d'inclusió
+GenericName[ca@valencia]=Gestor d'inclusió
+GenericName[de]=Include-Verwaltung
+GenericName[en_GB]=Include Manager
+GenericName[es]=Gestor de inclusiones
+GenericName[et]=Päisehaldur
+GenericName[fr]=Gestionnaire d'inclusions
+GenericName[gl]=Xestor de inclusións
+GenericName[it]=Gestore Include
+GenericName[nl]=Include-beheer
+GenericName[pl]=Menadżer dołączania
+GenericName[pt]=Gestor de Inclusões
+GenericName[pt_BR]=Gerenciador de inclusões
+GenericName[sk]=Správca rozšírení
+GenericName[sv]=Inkluderingshanterare
+GenericName[uk]=Керування включеннями
+GenericName[x-test]=xxInclude Managerxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevincludemanagerplugin
+X-KDE-PluginInfo-Name=kdevincludemanagerplugin
+X-KDE-PluginInfo-Author=Aleix Pol
+X-KDE-PluginInfo-Email=aleixpol@kde.org
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=11
+X-KDevelop-Category=Global
+X-KDevelop-Mode=NoGUI
+X-KDevelop-LoadMode=AlwaysOn
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.cpp (revision 1522570)
@@ -0,0 +1,88 @@
+/* This file is part of KDevelop
+ Copyright 2010 Aleix Pol <aleixpol@kde.org>
+
+ 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.
+*/
+
+#include "includemanager.h"
+
+#include <language/duchain/use.h>
+#include <language/duchain/ducontext.h>
+#include <language/duchain/declaration.h>
+#include <interfaces/idocument.h>
+#include <language/duchain/duchain.h>
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <language/duchain/duchainlock.h>
+
+using namespace KDevelop;
+
+QList<const Use*> usesForCtx(const DUContext* ctx)
+{
+ QList<const Use*> ret;
+ for(int i=0; i<ctx->usesCount(); ++i) {
+ ret += &ctx->uses()[i];
+ }
+
+ foreach(const DUContext* child, ctx->childContexts()) {
+ ret += usesForCtx(child);
+ }
+
+ return ret;
+}
+QList<IncludeProblemItem> IncludeManager::includes(const KDevelop::ReferencedTopDUContext& top)
+{
+ DUChainReadLocker lock(DUChain::lock());
+ QVector< DUContext::Import > imported=top->importedParentContexts();
+ if(imported.isEmpty())
+ return QList<IncludeProblemItem>();
+
+ IndexedDUContext ctx(imported[0].indexedContext());
+ QSet<Declaration*> decls;
+
+ IndexedTopDUContext topctx(ctx.topContextIndex());
+
+ QList<const Use*> uses=usesForCtx(ctx.data());
+ Q_FOREACH(const Use* use, uses) {
+ Declaration* decl=use->usedDeclaration(topctx.data());
+
+ if(decl && decl->context()!=ctx.data()) //let's just add the ones that are not declared in the same file
+ decls.insert(decl);
+ }
+
+ QList<IncludeProblemItem> ret;
+
+ imported.remove(0);
+ qDebug() << "hoooooooow" << imported.size();
+ foreach(const DUContext::Import& import, imported) {
+ IndexedDUContext ctx = import.indexedContext();
+
+ Declaration* which=0;
+ foreach(Declaration* d, decls) {
+ if(ctx.data()->imports(d->context())) {
+ which=d;
+ }
+ }
+
+ qDebug() << "fiiiiiirst" << validInclude << ctx.data()->url().toUrl() << (which ? which->toString(): "<null>");
+ if(!which) {
+ IndexedString inc=ctx.context()->url();
+ ret << IncludeProblemItem(inc.toUrl(), import.position);
+ }
+ }
+ return ret;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp (revision 1522570)
@@ -0,0 +1,153 @@
+/* This file is part of KDevelop
+ Copyright 2010 Aleix Pol <aleixpol@kde.org>
+
+ 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.
+*/
+
+#include "includemanagerplugin.h"
+#include <kpluginfactory.h>
+#include <QDebug>
+#include <QPalette>
+#include <QTreeView>
+#include <KAboutData>
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+#include <kaction.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/ilanguagecontroller.h>
+#include <interfaces/ilanguage.h>
+#include <language/interfaces/ilanguagesupport.h>
+#include <language/backgroundparser/backgroundparser.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/duchain.h>
+#include <language/backgroundparser/parsejob.h>
+#include "includemanager.h"
+#include <QHeaderView>
+
+K_PLUGIN_FACTORY(IncludeManagerFactory, registerPlugin<IncludeManagerPlugin>(); )
+K_EXPORT_PLUGIN(IncludeManagerFactory(
+ KAboutData("kdevvcsprojectintegration","kdevvcsprojectintegration",
+ ki18n("Include Manager"), "0.1", ki18n("Helps to manage include directories"), KAboutData::License_GPL)))
+
+using namespace KDevelop;
+
+class KDevIncludeManagerFactory: public KDevelop::IToolViewFactory
+{
+ public:
+ KDevIncludeManagerFactory( IncludeManagerPlugin *plugin ): mplugin( plugin ) {}
+
+ virtual QWidget* create( QWidget *parent = 0 )
+ {
+ QTreeView* view=new QTreeView(parent);
+
+ QAction* reloadAction = new QAction(KIcon("reload"), i18n("Reload"), view);
+ QObject::connect(reloadAction, SIGNAL(triggered()), mplugin, SLOT(reloadAll()));
+
+ view->setModel(mplugin->model());
+ view->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ view->setSortingEnabled(true);
+ view->addAction(reloadAction);
+ QObject::connect(view, SIGNAL(activated(QModelIndex)), mplugin, SLOT(activated(QModelIndex)));
+ return view;
+ }
+
+ virtual Qt::DockWidgetArea defaultPosition() { return Qt::LeftDockWidgetArea; }
+
+ virtual QString id() const { return "org.kdevelop.IncludeManagerPlugin"; }
+
+ private:
+ IncludeManagerPlugin *mplugin;
+};
+
+IncludeManagerPlugin::IncludeManagerPlugin(QObject* parent, const QVariantList&)
+ : KDevelop::IPlugin(IncludeManagerFactory::componentData(), parent)
+{
+ m_model=new QStandardItemModel(this);
+ m_model->setHeaderData(0, Qt::Vertical, i18n("File"), Qt::DisplayRole);
+ core()->uiController()->addToolView(i18n("Include Manager"), new KDevIncludeManagerFactory(this));
+ connect(core()->languageController()->backgroundParser(), SIGNAL(parseJobFinished(KDevelop::ParseJob* )),
+ this, SLOT(parsingFinished(KDevelop::ParseJob* )));
+}
+
+void IncludeManagerPlugin::parsingFinished(KDevelop::ParseJob* job)
+{
+ KUrl url=job->document().toUrl();
+ QStandardItem* root=0;
+
+ ReferencedTopDUContext top;
+ {
+ DUChainReadLocker lock(DUChain::lock());
+ top=job->duChain();
+ }
+
+ if(!top)
+ top=core()->languageController()->languagesForUrl(url).first()->languageSupport()->standardContext(url);
+
+ QList< QStandardItem* > items = m_model->findItems(url.prettyUrl());
+ if(items.isEmpty()) {
+ root=new QStandardItem(url.prettyUrl());
+ root->setData(QUrl(url));
+ m_model->appendRow(root);
+ } else {
+ root = items.first();
+ root->removeRows(0, root->rowCount());
+ }
+
+ if(!top || top->features()<TopDUContext::AllDeclarationsContextsAndUses) {
+ root->setIcon(KIcon("unknown"));
+ root->setEnabled(true);
+ return;
+ }
+
+ if(top) {
+ QList<IncludeProblemItem> includes = IncludeManager::includes(top);
+ Q_FOREACH(const IncludeProblemItem &include, includes) {
+ QStandardItem* incItem=new QStandardItem(include.url.prettyUrl());
+ incItem->setIcon(KIcon("dialog-error"));
+ root->appendRow(incItem);
+
+ DUChainWriteLocker lock(DUChain::lock());
+ ProblemPointer p(new Problem);
+ p->setRange(RangeInRevision(include.cursor, include.cursor));
+ p->setFinalLocation(DocumentRange(IndexedString(url), p->range().castToSimpleRange()));
+ p->setDescription(i18n("Unused import '%1'", include.url.prettyUrl()));
+ p->setSeverity(KDevelop::ProblemData::Hint);
+ p->setSource(KDevelop::ProblemData::SemanticAnalysis); //?
+ top->addProblem(p);
+ }
+ }
+
+ bool hasproblems = root->rowCount()>0;
+ root->setEnabled(hasproblems);
+ root->setIcon(hasproblems ? KIcon("dialog-error") : KIcon("dialog-ok"));
+}
+
+void IncludeManagerPlugin::activated(const QModelIndex& idx)
+{
+ QUrl docUrl=idx.data().toUrl();
+ core()->documentController()->openDocument(docUrl);
+}
+
+void IncludeManagerPlugin::reloadAll()
+{
+ for(int i=0; i<m_model->rowCount(); i++) {
+ QUrl url = m_model->item(i)->data().toUrl();
+
+// TopDUContext* chain = DUChain::self()->chainForDocument(url);
+// if(!chain || chain->features()!=KDevelop::TopDUContext::AllDeclarationsContextsAndUses)
+ core()->languageController()->backgroundParser()->addDocument(url, KDevelop::TopDUContext::AllDeclarationsContextsAndUses, 10);
+ }
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h (revision 1522570)
@@ -0,0 +1,55 @@
+/* This file is part of KDevelop
+ Copyright 2010 Aleix Pol <aleixpol@kde.org>
+
+ 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.
+*/
+
+#ifndef INCLUDEMANAGERPLUGIN_H
+#define INCLUDEMANAGERPLUGIN_H
+
+#include <interfaces/iplugin.h>
+#include <QVariant>
+#include <QStandardItemModel>
+
+class QModelIndex;
+class KUrl;
+class KJob;
+
+namespace KDevelop
+{
+ class IProject;
+ class IDocument;
+ class ParseJob;
+}
+
+class IncludeManagerPlugin : public KDevelop::IPlugin
+{
+ Q_OBJECT
+ public:
+ IncludeManagerPlugin(QObject *parent, const QVariantList & args);
+
+ QAbstractItemModel* model() const { return m_model; }
+
+ public slots:
+ void parsingFinished(KDevelop::ParseJob*);
+ void activated(const QModelIndex& idx);
+ void reloadAll();
+
+ private:
+ QStandardItemModel* m_model;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp (revision 1522570)
@@ -0,0 +1,127 @@
+/* This file is part of KDevelop
+ Copyright 2010 Niko Sams <niko.sams@gmail.com>
+
+ 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.
+*/
+#include "includemanagertest.h"
+
+#include <qtest_kde.h>
+
+#include <tests/autotestshell.h>
+#include <tests/testcore.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <includemanager.h>
+
+QTEST_KDEMAIN(IncludeManagerTest, GUI)
+
+void IncludeManagerTest::init()
+{
+ KDevelop::AutoTestShell::init();
+ m_core = new KDevelop::TestCore();
+ m_core->initialize(KDevelop::Core::NoUi);
+}
+
+void IncludeManagerTest::cleanup()
+{
+ m_core->cleanup();
+ delete m_core;
+}
+
+
+void IncludeManagerTest::testUsed()
+{
+ KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
+
+ TestFile f1("class xy {}; ", "xyXXXXXXX.h");
+
+ QByteArray c;
+ c += "#include \"";
+ c += QDir::currentPath() + "/" + f1.fileName();
+ c+= "\"\nvoid main() { xy i; } ";
+ TestFile f2(c, "XXXXXX.cpp");
+ f2.parse(features);
+ f2.waitForParsed();
+
+ QList<IncludeProblemItem> includes = IncludeManager::includes(f2.topContext());
+ QCOMPARE(includes.count(), 1);
+ QCOMPARE(includes.first().url, KUrl(QDir::currentPath() + "/" + f1.fileName()));
+}
+
+void IncludeManagerTest::testUnused()
+{
+ KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
+
+ TestFile f1("class xy {}; ", "xyXXXXXXX.h");
+
+ QByteArray c;
+ c += "#include \"";
+ c += QDir::currentPath() + "/" + f1.fileName();
+ c+= "\"\nvoid main() { } ";
+ TestFile f2(c, "XXXXXX.cpp");
+ f2.parse(features);
+ f2.waitForParsed();
+
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+
+ QList<IncludeProblemItem> includes = IncludeManager::includes(f2.topContext());
+ QCOMPARE(includes.count(), 0);
+}
+
+void IncludeManagerTest::testIndirectUsed()
+{
+ KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
+
+ TestFile f1("class xy {}; ", "xyXXXXXXX.h");
+ QByteArray c;
+ c += "#include \"";
+ c += QDir::currentPath() + "/" + f1.fileName();
+ c += "\"\n";
+ TestFile f2(c, "xyXXXXXXX.h");
+
+ QByteArray c2;
+ c2 += "#include \"";
+ c2 += QDir::currentPath() + "/" + f2.fileName();
+ c2 += "\"\nvoid main() { xy i; } ";
+ TestFile f3(c2, "XXXXXX.cpp");
+ f3.parse(features);
+ f3.waitForParsed();
+
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+
+ QList<IncludeProblemItem> includes = IncludeManager::includes(f3.topContext());
+ QCOMPARE(includes.count(), 1);
+ QCOMPARE(includes.first().url, KUrl(QDir::currentPath() + "/" + f2.fileName()));
+}
+TestFile::~TestFile() {
+ if (m_topContext) {
+ KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
+ KDevelop::DUChain::self()->removeDocumentChain(m_topContext.data());
+ }
+}
+void TestFile::parse(KDevelop::TopDUContext::Features features) {
+ KDevelop::DUChain::self()->updateContextForUrl(KDevelop::IndexedString(m_file.fileName()), features, this);
+}
+void TestFile::waitForParsed() {
+ QTime t;
+ t.start();
+ while (!m_ready) {
+ Q_ASSERT(t.elapsed() < 60000);
+ QTest::qWait(10);
+ }
+}
+
+#include "moc_includemanagertest.cpp"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h (revision 1522570)
@@ -0,0 +1,94 @@
+/* This file is part of KDevelop
+ Copyright 2010 Niko Sams <niko.sams@gmail.com>
+
+ 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.
+*/
+
+
+#ifndef INCLUDEMANAGERTEST_H
+#define INCLUDEMANAGERTEST_H
+
+#include <QObject>
+#include <language/duchain/topducontext.h>
+#include <QTemporaryFile>
+
+namespace KDevelop {
+ class TestCore;
+}
+class IncludeManagerTest : public QObject
+{
+ Q_OBJECT
+
+public:
+ virtual ~IncludeManagerTest() {}
+private slots:
+ void init();
+ void cleanup();
+
+ void testUsed();
+ void testUnused();
+ void testIndirectUsed();
+
+private:
+ KDevelop::TestCore* m_core;
+};
+
+class TestFile : public QObject
+{
+ Q_OBJECT
+public:
+ TestFile(QByteArray contents, const QString &fileName)
+ : m_file(fileName), m_ready(false)
+ {
+ m_file.open();
+ m_file.write(contents);
+ m_file.close();
+ }
+
+ ~TestFile();
+
+
+ void parse(KDevelop::TopDUContext::Features features);
+
+ void waitForParsed();
+
+ QString fileName()
+ {
+ return m_file.fileName();
+ }
+
+ KDevelop::ReferencedTopDUContext topContext()
+ {
+ waitForParsed();
+ return m_topContext;
+ }
+
+public slots:
+ void updateReady(KDevelop::IndexedString url, KDevelop::ReferencedTopDUContext topContext)
+ {
+ Q_ASSERT(url.str() == m_file.fileName());
+ m_ready = true;
+ m_topContext = topContext;
+ }
+
+private:
+ QTemporaryFile m_file;
+ bool m_ready;
+ KDevelop::ReferencedTopDUContext m_topContext;
+};
+
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.h (revision 1522570)
@@ -0,0 +1,51 @@
+/* This file is part of KDevelop
+ Copyright 2010 Aleix Pol <aleixpol@kde.org>
+
+ 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.
+*/
+
+
+#ifndef INCLUDEMANAGER_H
+#define INCLUDEMANAGER_H
+
+#include <QList>
+#include <QPair>
+
+#include <KUrl>
+#include <language/editor/cursorinrevision.h>
+
+namespace KDevelop {
+ class ReferencedTopDUContext;
+ class IndexedDUContext;
+ class Declaration;
+}
+
+struct IncludeProblemItem
+{
+ IncludeProblemItem(const KUrl& url, KDevelop::CursorInRevision cursor) : url(url), cursor(cursor) {}
+ KUrl url;
+
+ KDevelop::CursorInRevision cursor;
+};
+
+class IncludeManager
+{
+public:
+ static QList<IncludeProblemItem> includes(const KDevelop::ReferencedTopDUContext &top);
+ static bool canReach(const KDevelop::IndexedDUContext& includer, const KDevelop::Declaration* included);
+};
+
+#endif // INCLUDEMANAGER_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,32 @@
+project(includemanager)
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
+ ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules
+)
+
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDE4_INCLUDES}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}
+)
+
+#add_definitions(-DKDE_DEFAULT_DEBUG_AREA=)
+
+set(includemanager_SRCS
+ includemanagerplugin.cpp
+ includemanager.cpp
+)
+
+kde4_add_plugin(kdevincludemanagerplugin ${includemanager_SRCS})
+target_link_libraries(kdevincludemanagerplugin ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_LANGUAGE_LIBRARIES})
+
+install(TARGETS kdevincludemanagerplugin DESTINATION ${PLUGIN_INSTALL_DIR})
+
+install(FILES kdevincludemanager.desktop DESTINATION ${SERVICES_INSTALL_DIR})
+
+add_subdirectory(tests)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager/includemanager.kdev4 (revision 1522570)
@@ -0,0 +1,3 @@
+[Project]
+Manager=KDevCMakeManager
+Name=includemanager
Index: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/includemanager (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/includemanager (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/includemanager
___________________________________________________________________
Added: svn:ignore
## -0,0 +1 ##
+.kdev4
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop (revision 1522570)
@@ -0,0 +1,71 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=C/C++ Preprocessing
+Comment[bs]=C/C++ preobrade
+Comment[ca]=Preprocessament C/C++
+Comment[ca@valencia]=Preprocessament C/C++
+Comment[de]=C/C++ Vorverarbeitung
+Comment[en_GB]=C/C++ Preprocessing
+Comment[es]=Preproceso de C/C++
+Comment[et]=C/C++ eelprotsessor
+Comment[fr]=Prétraitement du C / C++
+Comment[gl]=Pre-procesamento de C/C++
+Comment[hu]=C/C++ előfeldolgozás
+Comment[it]=Preprocessazione C/C++
+Comment[nl]=C/C++ Preprocessing
+Comment[pl]=C/C++ Preprocessing
+Comment[pt]=Pré-Processamento de C/C++
+Comment[pt_BR]=Pré-Processamento de C/C++
+Comment[sv]=C och C++ preprocessor
+Comment[uk]=Попередня обробка C/C++
+Comment[x-test]=xxC/C++ Preprocessingxx
+Name=C/C++ Preprocessor
+Name[bs]=C/C++ preobrade
+Name[ca]=Preprocessador C/C++
+Name[ca@valencia]=Preprocessador C/C++
+Name[de]=C/C++ Preprocessor
+Name[en_GB]=C/C++ Preprocessor
+Name[es]=Preprocesador de C/C++
+Name[et]=C/C++ eelprotsessor
+Name[fr]=Préprocesseur C / C++
+Name[gl]=Pre-procesador de C/C++
+Name[hu]=C/C++ előfeldolgozó
+Name[it]=Preprocessore C/C++
+Name[nl]=C/C++ Preprocessor
+Name[pl]=C/C++ Preprocessor
+Name[pt]=Pré-processador de C/C++
+Name[pt_BR]=Pré-processador de C/C++
+Name[sv]=C/C++ preprocessor
+Name[uk]=Попередня обробка у C/C++
+Name[x-test]=xxC/C++ Preprocessorxx
+GenericName=C/C++ Preprocessor
+GenericName[bs]=C/C++ preobrade
+GenericName[ca]=Preprocessador C/C++
+GenericName[ca@valencia]=Preprocessador C/C++
+GenericName[de]=C/C++ Preprocessor
+GenericName[en_GB]=C/C++ Preprocessor
+GenericName[es]=Preprocesador de C/C++
+GenericName[et]=C/C++ eelprotsessor
+GenericName[fr]=Préprocesseur C / C++
+GenericName[gl]=Pre-procesador de C/C++
+GenericName[hu]=C/C++ előfeldolgozó
+GenericName[it]=Preprocessore C/C++
+GenericName[nl]=C/C++ Preprocessor
+GenericName[pl]=C/C++ Preprocessor
+GenericName[pt]=Pré-processador de C/C++
+GenericName[pt_BR]=Pré-processador de C/C++
+GenericName[sv]=C/C++ preprocessor
+GenericName[uk]=Попередня обробка у C/C++
+GenericName[x-test]=xxC/C++ Preprocessorxx
+Icon=kdevelop
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevpreprocessor
+X-KDE-PluginInfo-Name=kdevpreprocessor
+X-KDE-PluginInfo-Author=Jonathan Schmidt-Dominé (The User)
+X-KDE-PluginInfo-Email=devel@the-user.org
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=9
+X-KDevelop-Mode=GUI
+X-KDevelop-Category=Global
+X-KDevelop-Language=C++
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp (revision 1522570)
@@ -0,0 +1,180 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Preprocessor-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "preprocessorview.h"
+
+#include <QStringList>
+#include <KTextEditor/View>
+#include <KTextEditor/Document>
+#include <KTextEditor/MarkInterface>
+#include <KTextEditor/Editor>
+#include <KLocale>
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+#include <interfaces/iprojectcontroller.h>
+#include <interfaces/iproject.h>
+#include <project/projectmodel.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <util/commandexecutor.h>
+#include <KDebug>
+
+using namespace KDevelop;
+using namespace KTextEditor;
+
+PreprocessorView::PreprocessorView(QObject* parent, bool showIncludedFiles) : QObject(parent), state(showIncludedFiles ? WithIncludedFiles : InFile), document (KTextEditor::editor ("katepart")->createDocument(this)), view(document->createView (0))
+{
+ view->setWindowTitle(i18n("Preprocessor Output"));
+ view->setWindowFlags(Qt::Window);
+ view->setAttribute(Qt::WA_DeleteOnClose);
+ connect(view, SIGNAL(destroyed()), this, SLOT(deleteMe()));
+
+ document->setHighlightingMode("cpp");
+ IDocument *doc;
+ if((doc = ICore::self()->documentController()->activeDocument()) == 0)
+ return;
+ QString command = "g++";
+ QStringList args;
+ args << "-E";
+ args << (file = doc->url().path());
+ QString builddir;
+ if(IProject *project = ICore::self()->projectController()->findProjectForUrl(doc->url()))
+ {
+ if(IBuildSystemManager *buildsystem = project->buildSystemManager())
+ {
+ builddir = buildsystem->buildDirectory(project->projectItem()).path();
+ foreach(const KUrl& include, buildsystem->includeDirectories(project->projectItem()))
+ args << "-I" + include.url();
+ }
+ }
+ if(builddir.isEmpty())
+ {
+ builddir = doc->url().path();
+ size_t x = builddir.lastIndexOf('/');
+ if(x < 1)
+ builddir = '.';
+ else
+ builddir.remove(x, builddir.length() - x);
+ }
+ args << "-I.";
+ kDebug() << command << " in " << builddir;
+ CommandExecutor *cmd = new CommandExecutor (command, this);
+ connect(cmd, SIGNAL(receivedStandardOutput(const QStringList&)),
+ this, SLOT(addLines(const QStringList&) ), Qt::DirectConnection );
+ connect(cmd, SIGNAL(receivedStandardError(const QStringList&)),
+ this, SLOT(addErrorLines(const QStringList&) ), Qt::DirectConnection );
+ cmd->setWorkingDirectory( builddir );
+ cmd->setArguments( args );
+ connect( cmd, SIGNAL( failed() ), this, SLOT( failed() ), Qt::DirectConnection );
+ connect( cmd, SIGNAL( completed() ), this, SLOT( completed() ), Qt::DirectConnection );
+ view->setWindowState(Qt::WindowMaximized | Qt::WindowActive);
+ view->show();
+ cmd->start();
+}
+
+PreprocessorView::~PreprocessorView()
+{
+ if(view)
+ delete view;
+}
+
+void PreprocessorView::deleteMe()
+{
+ view = 0;
+ delete this;
+}
+
+void PreprocessorView::failed()
+{
+ document->insertLine(document->lines(), i18n("*FAILED*"));
+ qobject_cast<MarkInterface*>(document)->setMark(document->lines() - 1, MarkInterface::Execution | MarkInterface::Error);
+}
+
+void PreprocessorView::completed()
+{
+ document->insertLine(document->lines(), i18n("*SUCCEEDED*"));
+ qobject_cast<MarkInterface*>(document)->setMark(document->lines() - 1, MarkInterface::Execution);
+}
+
+void PreprocessorView::addErrorLines(const QStringList& list)
+{
+ MarkInterface *mi = qobject_cast<MarkInterface*>(document);
+ foreach(const QString& line, list)
+ {
+ document->insertLine(document->lines(), line);
+ mi->setMark(document->lines() - 1, MarkInterface::Warning);
+ }
+}
+
+inline bool subStartsWith(const QString& str, const QString& pattern, int pos)
+{
+ int end = pattern.size() + pos;
+ if(end >= str.size())
+ return false;
+ for(int i = 0; pos != end; ++pos, ++i)
+ if(str[pos] != pattern[i])
+ return false;
+ return true;
+}
+
+inline bool matching(const QString& line, const QString& file)
+{
+ int pos = line.indexOf(' ');
+ if(pos > 0)
+ {
+ pos = line.indexOf(' ', pos + 1);
+ return pos > 0
+ && line.length() > pos + 3
+ && line[++pos] == '"'
+ && subStartsWith(line, file, ++pos)
+ && line[pos + file.length()] == '"';
+ }
+ return false;
+}
+
+void PreprocessorView::addLines(const QStringList& list)
+{
+ if(state == WithIncludedFiles)
+ {
+ foreach(const QString& line, list)
+ document->insertLine(document->lines(), line);
+ }
+ else
+ {
+ foreach(const QString& line, list)
+ {
+ if(state == InFile)
+ {
+ if(line[0] == '#')
+ {
+ if(!matching(line, file))
+ state = InAnotherFile;
+ }
+ else
+ document->insertLine(document->lines(), line);
+ }
+ else
+ {
+ if(line[0] == '#' && matching(line, file))
+ state = InFile;
+ }
+ }
+ }
+}
+
+#include "preprocessorview.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp (revision 1522570)
@@ -0,0 +1,69 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Preprocessor-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#include "preprocessorplugin.h"
+
+#include "preprocessorview.h"
+
+#include <KPluginFactory>
+#include <KPluginLoader>
+#include <KAboutData>
+#include <KDebug>
+#include <KActionCollection>
+#include <KAction>
+#include <KLocale>
+
+K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<PreprocessorPlugin>();)
+K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("kdevpreprocessor","kdevpreprocessor", ki18n ("Preprocess the Current File"), "0.1", ki18n ("Preprocess the Current File"), KAboutData::License_GPL)))
+
+PreprocessorPlugin::PreprocessorPlugin (QObject *parent, const QVariantList &)
+:IPlugin (KdevPlugFactory::componentData(), parent)
+{
+ setXMLFile ("kdevpreprocessor.rc");
+
+ m_actionPreprocess = actionCollection()->addAction ("file_preprocess");
+ m_actionPreprocess->setIcon (KIcon ("circle2"));
+ m_actionPreprocess->setText (i18n ("Preprocess File"));
+ m_actionPreprocess->setShortcut (KShortcut ("Ctrl+Alt+Shift+p"));
+ connect (m_actionPreprocess, SIGNAL (triggered (bool)), this, SLOT (preprocess()));
+ m_actionPreprocess->setToolTip (i18n ("Preprocess the Current File"));
+ m_actionPreprocess->setWhatsThis (i18n ("<b>Preprocessor</b><p> View the preprocessor ouput, the content of included files will not be displayed</p>"));
+
+ m_actionPreprocessWithIncludes = actionCollection()->addAction ("file_preprocess_with_includes");
+ m_actionPreprocessWithIncludes->setIcon (KIcon ("circle"));
+ m_actionPreprocessWithIncludes->setText (i18n ("Preprocess File (with included content)"));
+ m_actionPreprocessWithIncludes->setWhatsThis (i18n ("<b>Preprocessor</b><p> View the preprocessor output including all included files</p>"));
+ connect (m_actionPreprocessWithIncludes, SIGNAL (triggered (bool)), this, SLOT (preprocessWithIncludes()));
+ m_actionPreprocessWithIncludes->setToolTip (i18n ("Preprocess the Current File and Display the Content of Included Files"));
+}
+
+PreprocessorPlugin::~PreprocessorPlugin()
+{
+}
+
+void PreprocessorPlugin::preprocess()
+{
+ new PreprocessorView(this, false);
+}
+
+void PreprocessorPlugin::preprocessWithIncludes()
+{
+ new PreprocessorView(this, true);
+}
+
+#include "preprocessorplugin.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorview.h (revision 1522570)
@@ -0,0 +1,50 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Preprocessor-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef PREPROCESSORVIEW_H
+#define PREPROCESSORVIEW_H
+
+#include <QObject>
+#include <QStringList>
+
+namespace KTextEditor
+{
+ class View;
+ class Document;
+}
+
+class PreprocessorView : public QObject
+{
+ Q_OBJECT
+ public:
+ PreprocessorView(QObject* parent, bool showIncludedFiles);
+ ~PreprocessorView();
+ private slots:
+ void addLines(const QStringList& output);
+ void addErrorLines(const QStringList& output);
+ void completed();
+ void failed();
+ void deleteMe();
+ private:
+ enum { WithIncludedFiles, InFile, InAnotherFile } state;
+ KTextEditor::Document *document;
+ KTextEditor::View *view;
+ QString file;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h (revision 1522570)
@@ -0,0 +1,51 @@
+/***************************************************************************
+ * This file is part of the KDevelop-Preprocessor-Plugin *
+ * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
+ * *
+ * This program is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU General Public License as *
+ * published by the Free Software Foundation; either version 3 of *
+ * the License or (at your option) any later version accepted. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. *
+ ***************************************************************************/
+
+#ifndef PREPROCESSORPLUGIN_H
+#define PREPROCESSORPLUGIN_H
+
+#include <interfaces/iplugin.h>
+
+#include <QVariantList>
+
+class KAction;
+
+using namespace KDevelop;
+
+namespace KDevelop
+{
+ class Declaration;
+ class DUContext;
+ class ClassDeclaration ;
+ class ClassMemberDeclaration ;
+}
+
+class PreprocessorPlugin : public KDevelop::IPlugin
+{
+ Q_OBJECT
+ public:
+ PreprocessorPlugin (QObject *parent, const QVariantList & = QVariantList());
+ ~PreprocessorPlugin();
+ private slots:
+ void preprocess();
+ void preprocessWithIncludes();
+ private:
+ KAction *m_actionPreprocess, *m_actionPreprocessWithIncludes;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,19 @@
+project(KDevPreprocessor)
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+include_directories(
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${KDE4_INCLUDES}
+ ${KDevPreprocessor_BINARY_DIR}
+)
+
+set(pp_SRCS preprocessorplugin.cpp preprocessorview.cpp)
+
+kde4_add_plugin(kdevpreprocessor ${pp_SRCS})
+
+target_link_libraries(kdevpreprocessor ${KDE4_KDECORE_LIBS} ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_UTIL_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES})
+
+install(TARGETS kdevpreprocessor DESTINATION ${PLUGIN_INSTALL_DIR})
+install(FILES kdevpreprocessor.desktop DESTINATION ${SERVICES_INSTALL_DIR})
+install(FILES kdevpreprocessor.rc DESTINATION ${DATA_INSTALL_DIR}/kdevpreprocessor)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc (revision 1522570)
@@ -0,0 +1,11 @@
+<!DOCTYPE kpartgui>
+<kpartplugin name="kdevpreprocessor" library="libkdevpreprocessor" version="7">
+<MenuBar>
+ <Menu name="project">
+ <Action name="file_preprocess"
+ group="build_operations"/>
+ <Action name="file_preprocess_with_includes"
+ group="build_operations"/>
+ </Menu>
+</MenuBar>
+</kpartplugin>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop (revision 1522570)
@@ -0,0 +1,75 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=GUI Builder based on Qt Designer
+Comment[bs]=GUI Builder baziran na Qt Designer-u.
+Comment[ca]=Constructor d'IGU basat en Qt Designer
+Comment[ca@valencia]=Constructor d'IGU basat en Qt Designer
+Comment[de]=GUI-Designer auf der Basis vom Qt-Designer
+Comment[en_GB]=GUI Builder based on Qt Designer
+Comment[es]=Constructor de interfaces gráficas basado en QtDesigner
+Comment[et]=GUI ehitaja Qt Disaineri põhjal
+Comment[fr]=Constructeur d'interfaces graphiques fondé sur Qt Designer
+Comment[gl]=Construtor de interfaces gráficas baseado en Qt Designer.
+Comment[it]=Creatore di interfacce basato su Qt Designer
+Comment[nl]=GUI Builder gebaseerd op Qt Designer
+Comment[pl]=Program budujący GUI oparty o projektanta Qt
+Comment[pt]=Construtor de GUI, baseado no Qt Designer
+Comment[pt_BR]=Construtor de GUI baseado no Qt Designer
+Comment[sv]=Grafisk gränssnittskonstruktion baserad på Qt Designer
+Comment[uk]=Створення графічного інтерфейсу з Дизайнера Qt
+Comment[x-test]=xxGUI Builder based on Qt Designerxx
+Name=Qt Designer Integration
+Name[bs]=Qt Dizajnerska integracija
+Name[ca]=Integració del Qt Designer
+Name[ca@valencia]=Integració del Qt Designer
+Name[de]=Qt-Designer-Integration
+Name[en_GB]=Qt Designer Integration
+Name[es]=Integración del Diseñador Qt
+Name[et]=Qt Disaineri lõimimine
+Name[fr]=Intégration de Qt Designer
+Name[ga]=Comhtháthú Qt Designer
+Name[gl]=Integración con Qt Designer
+Name[it]=integrazione di Qt Designer
+Name[nds]=QtDesigner-Inbinnen
+Name[nl]=Qt Designer Integratie
+Name[pl]=Integracja projektanta Qt
+Name[pt]=Integração com o Qt Designer
+Name[pt_BR]=Integração com o Qt Designer
+Name[sv]=Integrering med Qt Designer
+Name[tr]=Qt tasarımcı Bütünleşmesi
+Name[ug]=Qt لايىھىلىگۈچ يۈرۈشلەشتۈرۈلۈشى
+Name[uk]=Інтеграція Дизайнера Qt
+Name[x-test]=xxQt Designer Integrationxx
+GenericName=GUI Designer Integration
+GenericName[bs]=Qt Dizajnerska integracija
+GenericName[ca]=Integració del dissenyador d'IGU
+GenericName[ca@valencia]=Integració del dissenyador d'IGU
+GenericName[de]=GUI-Designer-Integration
+GenericName[en_GB]=GUI Designer Integration
+GenericName[es]=Integración del diseñador de interfaces gráficas
+GenericName[et]=Graafilise Disaineri lõimine
+GenericName[fr]=Intégration du concepteur d'interfaces graphiques
+GenericName[gl]=Funcionalidade de deseño de interfaces gráficas
+GenericName[it]=Integrazione di GUI Designer
+GenericName[nds]=Böversietmaker-Inbinnen
+GenericName[nl]=GUI Designer Integratie
+GenericName[pl]=Integracja projektanta GUI
+GenericName[pt]=Integração com o Desenhador de GUI's
+GenericName[pt_BR]=Integração com o Desenhador de GUI's
+GenericName[sv]=Integrering med grafisk gränssnittskonstruktion
+GenericName[tr]=Arayüz Tasarlayıcı Bütünleşmesi
+GenericName[ug]=GUI لايىھىلىگۈچ يۈرۈشلەشتۈرۈلۈشى
+GenericName[uk]=Інтеграція дизайнера графічного інтерфейсу
+GenericName[x-test]=xxGUI Designer Integrationxx
+icon=kdevelop
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevqtdesigner
+X-KDE-PluginInfo-Name=kdevqtdesigner
+X-KDE-PluginInfo-Author=Matt Rogers
+X-KDE-PluginInfo-Email=mattr@kde.org
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=9
+X-KDevelop-SupportedMimeTypes=application/x-designer
+X-KDevelop-Mode=GUI
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp (revision 1522570)
@@ -0,0 +1,258 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+/****************************************************************************
+**
+** Copyright 1992-2006 Trolltech AS. All rights reserved.
+**
+** This file is part of the Qt Designer of the Qt Toolkit.
+**
+** This file may be used under the terms of the GNU General Public
+** License version 2.0 as published by the Free Software Foundation
+** and appearing in the file LICENSE.GPL included in the packaging of
+** this file. Please review the following information to ensure GNU
+** General Public Licensing requirements will be met:
+** http://www.trolltech.com/products/qt/opensource.html
+**
+** If you are unsure which license is appropriate for your use, please
+** review the following information:
+** http://www.trolltech.com/products/qt/licensing.html or contact the
+** sales department at sales@trolltech.com.
+**
+** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
+** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+**
+****************************************************************************/
+
+#include "qtdesignerdocument.h"
+
+#include <QtDesigner/QDesignerFormWindowManagerInterface>
+#include <QtDesigner/QDesignerFormWindowInterface>
+#include <QtDesigner/QDesignerFormEditorInterface>
+#include <QtGui/QMdiArea>
+#include <QtGui/QMdiSubWindow>
+#include <QtCore/QFile>
+#include <QApplication>
+#include <KMessageBox>
+#include <KLocale>
+
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+#include <interfaces/idocumentcontroller.h>
+#include <sublime/view.h>
+#include <sublime/area.h>
+#include <sublime/controller.h>
+
+#include "qtdesignerview.h"
+#include "qtdesignerplugin.h"
+
+QtDesignerDocument::QtDesignerDocument( const KUrl& url , KDevelop::ICore* core )
+ : Sublime::UrlDocument(core->uiController()->controller(), url),
+ KDevelop::IDocument(core), m_state(KDevelop::IDocument::Clean)
+{
+
+}
+
+KSharedPtr<KMimeType> QtDesignerDocument::mimeType() const
+{
+ return KMimeType::mimeType("application/x-designer");
+}
+
+KParts::Part* QtDesignerDocument::partForView(QWidget*) const
+{
+ return 0;
+}
+
+KTextEditor::Document* QtDesignerDocument::textDocument() const
+{
+ return 0;
+}
+
+bool QtDesignerDocument::save(KDevelop::IDocument::DocumentSaveMode mode)
+{
+ if (mode & Discard)
+ return true;
+
+ kDebug(9038) << "Going to Save";
+ if( m_state == KDevelop::IDocument::Clean )
+ return false;
+ if( !m_form )
+ return false;
+ QFile f(url().toLocalFile());
+ if( !f.open( QIODevice::WriteOnly ) )
+ {
+ kDebug(9038) << "Couldn't open file:" << f.error();
+ return false;
+ }
+ QTextStream s(&f);
+ s << m_form->contents();
+ s.flush();
+ f.close();
+ m_state = KDevelop::IDocument::Clean;
+ notifySaved();
+ return true;
+}
+
+void QtDesignerDocument::reload()
+{
+ QFile uiFile(url().toLocalFile());
+ m_form->setContents(&uiFile);
+ m_state = KDevelop::IDocument::Clean;
+ notifyStateChanged();
+}
+
+bool QtDesignerDocument::close(KDevelop::IDocument::DocumentSaveMode mode)
+{
+ kDebug() << "form:" << m_form;
+ if (!(mode & Discard)) {
+ if (mode & Silent) {
+ if (!save(mode))
+ return false;
+
+ } else {
+ if (state() == IDocument::Modified) {
+ int code = KMessageBox::warningYesNoCancel(
+ qApp->activeWindow(),
+ i18n("The document \"%1\" has unsaved changes. Would you like to save them?", url().toLocalFile()),
+ i18n("Close Document"));
+
+ if (code == KMessageBox::Yes) {
+ if (!save(mode))
+ return false;
+
+ } else if (code == KMessageBox::Cancel) {
+ return false;
+ }
+
+ } else if (state() == IDocument::DirtyAndModified) {
+ if (!save(mode))
+ return false;
+ }
+ }
+ }
+
+ //close all views and then delete ourself
+ ///@todo test this
+ foreach (Sublime::Area *area,
+ KDevelop::ICore::self()->uiController()->controller()->allAreas())
+ {
+ QList<Sublime::View*> areaViews = area->views();
+ foreach (Sublime::View *view, areaViews) {
+ if (views().contains(view)) {
+ kDebug() << "form before:" << m_form;
+ kDebug() << "closing view" << view;
+ kDebug() << "form after:" << m_form;
+ area->removeView(view);
+ delete view;
+ }
+ }
+ }
+
+// kDebug() << "removing" << m_form << "from window manager";
+ // m_designerPlugin->designer()->formWindowManager()->removeFormWindow(m_form);
+
+ KDevelop::ICore::self()->documentController()->notifyDocumentClosed(this);
+
+ // Here we go...
+ deleteLater();
+
+ return true;
+}
+
+bool QtDesignerDocument::isActive() const
+{
+ QDesignerFormWindowInterface* activeWin =
+ m_designerPlugin->designer()->formWindowManager()->activeFormWindow();
+ if( activeWin == m_form )
+ return true;
+ return false;
+}
+
+KDevelop::IDocument::DocumentState QtDesignerDocument::state() const
+{
+ return m_state;
+}
+
+void QtDesignerDocument::setCursorPosition(const KTextEditor::Cursor&)
+{
+ return;
+}
+
+void QtDesignerDocument::setTextSelection(const KTextEditor::Range &)
+{
+}
+
+void QtDesignerDocument::activate(Sublime::View* view, KParts::MainWindow*)
+{
+ m_designerPlugin->designer()->formWindowManager()->setActiveFormWindow( m_form );
+ notifyActivated();
+}
+
+void QtDesignerDocument::setDesignerPlugin(QtDesignerPlugin* plugin)
+{
+ m_designerPlugin = plugin;
+}
+
+Sublime::View *QtDesignerDocument::newView(Sublime::Document* doc)
+{
+ if( qobject_cast<QtDesignerDocument*>( doc ) ) {
+ QFile uiFile(url().toLocalFile());
+ uiFile.open(QIODevice::ReadOnly | QIODevice::Text);
+
+ m_form = designerPlugin()->designer()->formWindowManager()->createFormWindow();
+ kDebug(9038) << "now we have" << m_form->core()->formWindowManager()->formWindowCount() << "formwindows";
+ m_form->setFileName(url().toLocalFile());
+ m_form->setContents(&uiFile);
+ connect( m_form, SIGNAL(changed()), this, SLOT(formChanged()));
+ designerPlugin()->designer()->formWindowManager()->setActiveFormWindow(m_form);
+ return new QtDesignerView( this );
+ }
+ return 0;
+}
+
+QDesignerFormWindowInterface* QtDesignerDocument::form()
+{
+ return m_form;
+}
+
+void QtDesignerDocument::formChanged()
+{
+ m_state = KDevelop::IDocument::Modified;
+ notifyStateChanged();
+}
+
+KTextEditor::Cursor QtDesignerDocument::cursorPosition( ) const
+{
+ return KTextEditor::Cursor();
+}
+
+QtDesignerPlugin* QtDesignerDocument::designerPlugin()
+{
+ return m_designerPlugin;
+}
+
+
+bool QtDesignerDocument::closeDocument()
+{
+ return close();
+}
+
+
+#include "qtdesignerdocument.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h (revision 1522570)
@@ -0,0 +1,72 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef QTDESIGNERDOCUMENT_H
+#define QTDESIGNERDOCUMENT_H
+
+#include <QtCore/QList>
+
+#include <sublime/urldocument.h>
+#include <interfaces/idocument.h>
+
+namespace KDevelop
+{
+ class ICore;
+}
+
+class QtDesignerPlugin;
+class QDesignerFormWindowInterface;
+class QMdiArea;
+
+class QtDesignerDocument : public Sublime::UrlDocument, public KDevelop::IDocument
+{
+ Q_OBJECT
+public:
+ QtDesignerDocument( const KUrl&, KDevelop::ICore* );
+
+ KUrl url() const { return Sublime::UrlDocument::url(); }
+
+ virtual KSharedPtr<KMimeType> mimeType() const;
+ virtual KParts::Part* partForView(QWidget*) const;
+ virtual KTextEditor::Document* textDocument() const;
+ virtual bool save(KDevelop::IDocument::DocumentSaveMode = KDevelop::IDocument::Default);
+ virtual void reload();
+ virtual bool close(KDevelop::IDocument::DocumentSaveMode = KDevelop::IDocument::Default);
+ virtual bool isActive() const;
+ virtual DocumentState state() const;
+ virtual void setCursorPosition(const KTextEditor::Cursor&);
+ virtual void setTextSelection(const KTextEditor::Range &range);
+ virtual void activate(Sublime::View*, KParts::MainWindow*);
+ virtual KTextEditor::Cursor cursorPosition() const;
+ void setDesignerPlugin(QtDesignerPlugin*);
+ QtDesignerPlugin* designerPlugin();
+ QDesignerFormWindowInterface* form();
+ virtual bool closeDocument();
+private slots:
+ void formChanged();
+ Sublime::View* newView( Sublime::Document* d );
+private:
+ QtDesignerPlugin* m_designerPlugin;
+ KDevelop::IDocument::DocumentState m_state;
+ QDesignerFormWindowInterface* m_form;
+};
+
+#endif
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,32 @@
+project(qtdesigner)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${qtdesigner_SOURCE_DIR}/cmake/)
+
+find_package(KDE4 4.2.0 REQUIRED)
+find_package(KDevPlatform 0.9.93 REQUIRED)
+
+include_directories( ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR})
+include_directories( ${qtdesigner_SOURCE_DIR} ${qtdesigner_BINARY_DIR})
+
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9038 )
+
+########### next target ###############
+
+SET(kdevqtdesigner_PART_SRCS
+qtdesignerplugin.cpp
+qtdesignerdocument.cpp
+qtdesignerview.cpp
+qtdesignerwidget.cpp
+)
+
+
+
+kde4_add_plugin(kdevqtdesigner ${kdevqtdesigner_PART_SRCS})
+
+TARGET_LINK_LIBRARIES(kdevqtdesigner ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${QT_QTDESIGNER_LIBRARY} ${QT_QTDESIGNERCOMPONENTS_LIBRARY} ${KDEVPLATFORM_SUBLIME_LIBRARIES})
+install(TARGETS kdevqtdesigner DESTINATION ${PLUGIN_INSTALL_DIR})
+
+
+########### install files ###############
+
+install(FILES kdevqtdesigner.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install(FILES kdevqtdesigner.rc DESTINATION ${DATA_INSTALL_DIR}/kdevqtdesigner )
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp (revision 1522570)
@@ -0,0 +1,164 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "qtdesignerwidget.h"
+
+#include <QtDesigner/QDesignerFormWindowInterface>
+#include <QtDesigner/QDesignerFormWindowManagerInterface>
+#include <QtDesigner/QDesignerFormEditorInterface>
+#include <QtDesigner/QDesignerFormEditorPluginInterface>
+#include <QtCore/QPluginLoader>
+#include <QtGui/QMdiSubWindow>
+
+#include <kdebug.h>
+#include <klocale.h>
+#include <kaction.h>
+#include <kstandardaction.h>
+#include <kactioncollection.h>
+
+#include <sublime/view.h>
+
+#include "qtdesignerdocument.h"
+#include "qtdesignerplugin.h"
+
+QtDesignerWidget::QtDesignerWidget( QWidget* parent, QtDesignerDocument* document )
+ : QMdiArea( parent ), KXMLGUIClient(), m_document( document )
+{
+ // area->setScrollBarsEnabled( true ); //FIXME commented just to make it compile with the new qt-copy
+ // area->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
+ // area->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
+
+ QDesignerFormWindowInterface* form = m_document->form();
+
+ setComponentData( m_document->designerPlugin()->componentData() );
+ setXMLFile( "kdevqtdesigner.rc" );
+
+ QMdiSubWindow* window = addSubWindow(form, Qt::Window | Qt::WindowShadeButtonHint | Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
+ const QSize containerSize = form->mainContainer()->size();
+ const QSize containerMinimumSize = form->mainContainer()->minimumSize();
+ const QSize containerMaximumSize = form->mainContainer()->maximumSize();
+ const QSize decorationSize = window->geometry().size() - window->contentsRect().size();
+ window->resize(containerSize+decorationSize);
+ window->setMinimumSize(containerMinimumSize+decorationSize);
+ if( containerMaximumSize == QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) )
+ window->setMaximumSize(containerMaximumSize);
+ else
+ window->setMaximumSize(containerMaximumSize+decorationSize);
+ window->setWindowTitle( form->mainContainer()->windowTitle() );
+
+ setupActions();
+}
+
+void QtDesignerWidget::setupActions()
+{
+
+ QDesignerFormWindowManagerInterface* manager = m_document->form()->core()->formWindowManager();
+ KActionCollection* ac = actionCollection();
+
+ KStandardAction::save( this, SLOT( save() ), ac);
+ ac->addAction( "adjust_size", manager->actionAdjustSize() );
+ ac->addAction( "break_layout", manager->actionBreakLayout() );
+ ac->addAction( "designer_cut", manager->actionCut() );
+ ac->addAction( "designer_copy", manager->actionCopy() );
+ ac->addAction( "designer_paste", manager->actionPaste() );
+ ac->addAction( "designer_delete", manager->actionDelete() );
+ ac->addAction( "layout_grid", manager->actionGridLayout() );
+ ac->addAction( "layout_horiz", manager->actionHorizontalLayout() );
+ ac->addAction( "layout_vertical", manager->actionVerticalLayout() );
+ ac->addAction( "layout_split_horiz", manager->actionSplitHorizontal() );
+ ac->addAction( "layout_split_vert", manager->actionSplitVertical() );
+ ac->addAction( "designer_undo", manager->actionUndo() );
+ ac->addAction( "designer_redo", manager->actionRedo() );
+ ac->addAction( "designer_select_all", manager->actionSelectAll() );
+ KAction* action = ac->addAction( "widgeteditor" );
+ action->setCheckable( true );
+ action->setChecked( true );
+ action->setText( i18n("Edit Widgets") );
+ connect( action, SIGNAL(triggered()), SLOT(editWidgets()));
+ foreach (QObject *plugin, QPluginLoader::staticInstances())
+ {
+ if ( !plugin )
+ continue;
+
+ kDebug() << "checking plugin:" << plugin;
+ QDesignerFormEditorPluginInterface *fep;
+
+ if ( (fep = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) )
+ {
+ // action name may have '&', remove them
+ QString actionText = fep->action()->text();
+ actionText = actionText.remove('&');
+
+ fep->action()->setCheckable(true);
+ if( actionText == "Edit Signals/Slots" ) {
+ connect(fep->action(), SIGNAL(triggered()), SLOT(editSignals()));
+ actionCollection()->addAction("signaleditor", fep->action());
+ }
+ if( actionText == "Edit Buddies" ) {
+ connect(fep->action(), SIGNAL(triggered()), SLOT(editBuddys()));
+ actionCollection()->addAction("buddyeditor", fep->action());
+ }
+ if( actionText == "Edit Tab Order" ) {
+ connect(fep->action(), SIGNAL(triggered()), SLOT(editTabOrder()));
+ actionCollection()->addAction("tabordereditor", fep->action());
+ }
+
+ kDebug(9038) << "Added action:" << fep->action()->objectName() << "|" << fep->action()->text();
+ }
+ }
+}
+
+void QtDesignerWidget::editWidgets()
+{
+ QDesignerFormWindowInterface* form = m_document->form();
+ form->editWidgets();
+ actionCollection()->action("signaleditor")->setChecked(false);
+ actionCollection()->action("buddyeditor")->setChecked(false);
+ actionCollection()->action("tabordereditor")->setChecked(false);
+}
+
+void QtDesignerWidget::editBuddys()
+{
+ actionCollection()->action("widgeteditor")->setChecked(false);
+ actionCollection()->action("signaleditor")->setChecked(false);
+ actionCollection()->action("tabordereditor")->setChecked(false);
+}
+
+void QtDesignerWidget::editSignals()
+{
+ actionCollection()->action("widgeteditor")->setChecked(false);
+ actionCollection()->action("buddyeditor")->setChecked(false);
+ actionCollection()->action("tabordereditor")->setChecked(false);
+}
+
+void QtDesignerWidget::editTabOrder()
+{
+ actionCollection()->action("widgeteditor")->setChecked(false);
+ actionCollection()->action("buddyeditor")->setChecked(false);
+ actionCollection()->action("signaleditor")->setChecked(false);
+}
+
+void QtDesignerWidget::save()
+{
+ m_document->save();
+}
+
+#include "qtdesignerwidget.moc"
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevqtdesigner.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h (revision 1522570)
@@ -0,0 +1,45 @@
+/***************************************************************************
+* This file is part of KDevelop *
+* Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
+* *
+* This program 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 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 Library General Public *
+* License along with this program; if not, write to the *
+* Free Software Foundation, Inc., *
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+***************************************************************************/
+
+#ifndef QTDESIGNERWIDGET_H
+#define QTDESIGNERWIDGET_H
+
+#include <QtGui/QMdiArea>
+#include <kxmlguiclient.h>
+
+class QtDesignerDocument;
+
+class QtDesignerWidget : public QMdiArea, public KXMLGUIClient
+{
+ Q_OBJECT
+ public:
+ QtDesignerWidget( QWidget* parent, QtDesignerDocument* document );
+ private slots:
+ void save();
+ void editWidgets();
+ void editBuddys();
+ void editSignals();
+ void editTabOrder();
+ private:
+ void setupActions();
+ QtDesignerDocument* m_document;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc (revision 1522570)
@@ -0,0 +1,58 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<gui name="guibuilder" version="7">
+<MenuBar>
+ <Menu name="file">
+ <text context="@title:menu">File</text>
+ <Action name="file_save" group="save_merge"/>
+ </Menu>
+
+ <Menu name="edit">
+ <text context="@title:menu">Edit</text>
+ <Action name="designer_undo" group="edit_undo_merge"/>
+ <Action name="designer_redo" group="edit_undo_merge"/>
+ <Action name="designer_cut" group="edit_paste_merge"/>
+ <Action name="designer_copy" group="edit_paste_merge"/>
+ <Action name="designer_paste" group="edit_paste_merge"/>
+ </Menu>
+
+ <Menu name="layout">
+ <text context="@title:menu">Form</text>
+ <Action name="layout_horiz"/>
+ <Action name="layout_vertical"/>
+ <Action name="layout_split_horiz"/>
+ <Action name="layout_split_vert"/>
+ <Action name="layout_grid"/>
+ <Action name="break_layout"/>
+ <Separator/>
+ <Action name="adjust_size"/>
+ <Separator/>
+ <Action name="widgeteditor"/>
+ <Action name="signaleditor"/>
+ <Action name="buddyeditor"/>
+ <Action name="tabordereditor"/>
+ </Menu>
+</MenuBar>
+
+<ToolBar name="mainToolBar"><text>Main Toolbar</text>
+ <Action name="file_save" group="file_operations"/>
+ <Action name="designer_undo" group="edit_operations"/>
+ <Action name="designer_redo" group="edit_operations"/>
+ <Action name="designer_cut" group="edit_operations"/>
+ <Action name="designer_copy" group="edit_operations"/>
+ <Action name="designer_paste" group="edit_operations"/>
+</ToolBar>
+
+<ToolBar name="designerToolbar" noMerge="1"><text>Designer Layout Toolbar</text>
+ <Action name="layout_horiz"/>
+ <Action name="layout_vertical"/>
+ <Action name="layout_split_horiz"/>
+ <Action name="layout_split_vert"/>
+ <Action name="layout_grid"/>
+ <Action name="break_layout"/>
+ <Separator/>
+ <Action name="adjust_size"/>
+</ToolBar>
+
+</gui>
+
+<!-- kate: space-indent on; indent-width 4; replace-tabs on; -->
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp (revision 1522570)
@@ -0,0 +1,277 @@
+/***************************************************************************
+ * Copyright 2005 Roberto Raggi <roberto@kdevelop.org> *
+ * Copyright 2005 Harald Fernengel <harry@kdevelop.org> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "qtdesignerplugin.h"
+
+#include <QObject>
+#include <QAction>
+#include <QFile>
+#include <QTextStream>
+#include <QtDesigner/QtDesigner>
+#include <QtDesigner/QDesignerComponents>
+#include <QPluginLoader>
+#include <QWorkspace>
+
+#include <kaboutdata.h>
+#include <kaction.h>
+#include <kmimetype.h>
+#include <kxmlguiwindow.h>
+#include <kpluginfactory.h>
+#include <kpluginloader.h>
+#include <kparts/mainwindow.h>
+#include <kparts/partmanager.h>
+#include <ksavefile.h>
+#include <kstandardaction.h>
+#include <kicon.h>
+#include <kactioncollection.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/iuicontroller.h>
+#include "qtdesignerdocument.h"
+#include "internals/qdesigner_integration_p.h"
+
+K_PLUGIN_FACTORY(QtDesignerPluginFactory, registerPlugin<QtDesignerPlugin>(); )
+K_EXPORT_PLUGIN(QtDesignerPluginFactory(KAboutData("kdevqtdesigner","kdevqtdesigner", ki18n("Qt Designer"), "0.1", ki18n("A GUI form designer for the Qt toolkit"), KAboutData::License_GPL)))
+
+class QtDesignerDocumentFactory : public KDevelop::IDocumentFactory
+{
+public:
+ QtDesignerDocumentFactory(QtDesignerPlugin* plugin)
+ : KDevelop::IDocumentFactory(), m_plugin(plugin)
+ {
+ }
+
+ KDevelop::IDocument* create( const KUrl& url, KDevelop::ICore* core)
+ {
+ kDebug(9038) << "creating doc for designer?";
+ KMimeType::Ptr mimetype = KMimeType::findByUrl(url);
+ kDebug(9038) << "mimetype for" << url << "is" << mimetype->name();
+ if( mimetype->name() == "application/x-designer" )
+ {
+ QtDesignerDocument* d = new QtDesignerDocument(url, core);
+ d->setDesignerPlugin(m_plugin);
+// m_plugin->activateDocument(d);
+ return d;
+ }
+ return 0;
+ }
+ private:
+ QtDesignerPlugin* m_plugin;
+};
+
+class QtDesignerToolViewFactory : public KDevelop::IToolViewFactory
+{
+public:
+ enum Type
+ {
+ WidgetBox,
+ PropertyEditor,
+ ActionEditor,
+ ObjectInspector,
+ SignalSlotEditor,
+ ResourceEditor
+ };
+ QtDesignerToolViewFactory( QtDesignerPlugin* plugin, Type typ )
+ : IToolViewFactory(), m_plugin(plugin), m_type(typ)
+ {
+ }
+
+ virtual QWidget* create(QWidget *parent = 0)
+ {
+ if( m_type == WidgetBox )
+ return m_plugin->designer()->widgetBox();
+ else if( m_type == PropertyEditor )
+ return m_plugin->designer()->propertyEditor();
+ else if( m_type == ActionEditor )
+ return m_plugin->designer()->actionEditor();
+ else if( m_type == ObjectInspector )
+ return m_plugin->designer()->objectInspector();
+ else if( m_type == SignalSlotEditor )
+ return QDesignerComponents::createSignalSlotEditor(m_plugin->designer(), 0);
+ else if( m_type == ResourceEditor )
+ return QDesignerComponents::createResourceEditor(m_plugin->designer(), 0);
+ kDebug(9038) << "Type not found:" << m_type;
+ return 0;
+ }
+ virtual Qt::DockWidgetArea defaultPosition()
+ {
+ if( m_type == WidgetBox )
+ return Qt::LeftDockWidgetArea;
+ else if( m_type == PropertyEditor )
+ return Qt::RightDockWidgetArea;
+ else if( m_type == ActionEditor )
+ return Qt::RightDockWidgetArea;
+ else if( m_type == ObjectInspector )
+ return Qt::RightDockWidgetArea;
+ else if( m_type == SignalSlotEditor )
+ return Qt::BottomDockWidgetArea;
+ else if( m_type == ResourceEditor )
+ return Qt::BottomDockWidgetArea;
+ kDebug(9038) << "Type not found:" << m_type;
+ return Qt::TopDockWidgetArea;
+ }
+
+ virtual QString id() const
+ {
+ if( m_type == WidgetBox )
+ return "org.kevelop.qtdesigner.WidgetBox";
+ else if( m_type == PropertyEditor )
+ return "org.kevelop.qtdesigner.PropertyEditor";
+ else if( m_type == ActionEditor )
+ return "org.kevelop.qtdesigner.ActionEditor";
+ else if( m_type == ObjectInspector )
+ return "org.kevelop.qtdesigner.ObjectInspector";
+ else if( m_type == SignalSlotEditor )
+ return "org.kevelop.qtdesigner.SignalSlotEditor";
+ else if( m_type == ResourceEditor )
+ return "org.kevelop.qtdesigner.ResourceEditor";
+ return QString();
+ }
+
+private:
+ QtDesignerPlugin* m_plugin;
+ Type m_type;
+};
+
+QtDesignerPlugin::QtDesignerPlugin(QObject *parent, const QVariantList &args)
+ : KDevelop::IPlugin(QtDesignerPluginFactory::componentData(),parent),
+ m_docFactory(new QtDesignerDocumentFactory(this)),
+ m_widgetBoxFactory(0), m_propertyEditorFactory(0),
+ m_objectInspectorFactory(0), m_actionEditorFactory(0)
+{
+ Q_UNUSED(args)
+ QDesignerComponents::initializeResources();
+// connect( idc, SIGNAL( documentActivated( KDevelop::IDocument* ) ),
+// this, SLOT( activateDocument( KDevelop::IDocument* ) ) );
+
+ QDesignerFormEditorInterface* formeditor = QDesignerComponents::createFormEditor(this);
+ QDesignerComponents::initializePlugins( formeditor );
+
+ kDebug(9038) << "integration:" << formeditor->integration();
+
+ //TODO apaku: if multiple mainwindows exist, this needs to be changed on mainwindow-change
+ formeditor->setTopLevel(core()->uiController()->activeMainWindow());
+
+ formeditor->setWidgetBox(QDesignerComponents::createWidgetBox(formeditor, 0));
+
+// load the standard widgets
+ formeditor->widgetBox()->setFileName(QLatin1String(":/trolltech/widgetbox/widgetbox.xml"));
+ formeditor->widgetBox()->load();
+
+ formeditor->setPropertyEditor(QDesignerComponents::createPropertyEditor(formeditor, 0));
+ formeditor->setActionEditor(QDesignerComponents::createActionEditor(formeditor, 0));
+ formeditor->setObjectInspector(QDesignerComponents::createObjectInspector(formeditor, 0));
+
+ m_designer = new qdesigner_internal::QDesignerIntegration(formeditor, this);
+ qdesigner_internal::QDesignerIntegration::initializePlugins( formeditor );
+
+ kDebug() << "integration now:" << formeditor->integration();
+
+ m_designer->core()->widgetBox()->setObjectName( i18n("Widget Box") );
+ m_designer->core()->propertyEditor()->setObjectName( i18n("Property Editor") );
+ m_designer->core()->actionEditor()->setObjectName( i18n("Action Editor") );
+ m_designer->core()->objectInspector()->setObjectName( i18n("Object Inspector") );
+
+
+ foreach (QObject *plugin, QPluginLoader::staticInstances())
+ {
+ QDesignerFormEditorPluginInterface *fep;
+
+ if ( (fep = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) )
+ {
+ fep->initialize(designer());
+ }
+ }
+ m_widgetBoxFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::WidgetBox );
+ m_propertyEditorFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::PropertyEditor);
+ m_actionEditorFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::ActionEditor);
+ m_objectInspectorFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::ObjectInspector);
+ m_signalSlotEditorFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::SignalSlotEditor);
+ m_resourceEditorFactory = new QtDesignerToolViewFactory( this,
+ QtDesignerToolViewFactory::ResourceEditor);
+
+ core()->uiController()->addToolView("Widget Box", m_widgetBoxFactory );
+ core()->uiController()->addToolView("Property Editor", m_propertyEditorFactory );
+ core()->uiController()->addToolView("Action Editor", m_actionEditorFactory );
+ core()->uiController()->addToolView("Object Inspector", m_objectInspectorFactory );
+ core()->uiController()->addToolView("Signal/Slot Editor", m_signalSlotEditorFactory );
+ core()->uiController()->addToolView("Resource Editor", m_resourceEditorFactory );
+
+ KDevelop::IDocumentController* idc = core()->documentController();
+ idc->registerDocumentForMimetype("application/x-designer", m_docFactory);
+}
+
+QtDesignerPlugin::~QtDesignerPlugin()
+{
+ delete m_designer;
+ delete m_docFactory;
+}
+
+QDesignerFormEditorInterface *QtDesignerPlugin::designer() const
+{
+ return m_designer->core();
+}
+
+// bool QtDesignerPlugin::saveFile()
+// {
+// KSaveFile uiFile( localFilePath() );
+// //FIXME: find a way to return an error. KSaveFile
+// //doesn't use the KIO error codes
+// if ( !uiFile.open() )
+// return false;
+//
+// QTextStream stream ( &uiFile );
+// QByteArray windowXml = m_window->contents().toUtf8();
+// stream << windowXml;
+//
+// if ( !uiFile.finalize() )
+// return false;
+//
+// m_window->setDirty(false);
+// setModified(false);
+// return true;
+// }
+/*
+void QtDesignerPlugin::saveActiveDocument()
+{
+ kDebug(9038) << "going to save:" << m_activeDoc;
+ if( m_activeDoc )
+ {
+ m_activeDoc->save( KDevelop::IDocument::Default );
+ }
+}
+
+void QtDesignerPlugin::activateDocument( KDevelop::IDocument* doc )
+{
+ if( doc->mimeType()->is( "application/x-designer" ) )
+ {
+ kDebug(9038) << "Doc activated:" << doc;
+ m_activeDoc = doc;
+ }
+}*/
+
+#include "qtdesignerplugin.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h (revision 1522570)
@@ -0,0 +1,87 @@
+/***************************************************************************
+ * Copyright 2005 Roberto Raggi <roberto@kdevelop.org> *
+ * Copyright 2005 Harald Fernengel <harry@kdevelop.org> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef QTDESIGNER_PLUGIN_H
+#define QTDESIGNER_PLUGIN_H
+
+#include <QHash>
+#include <QtCore/QPointer>
+#include <interfaces/iplugin.h>
+#include <QtCore/QVariant>
+
+class QAction;
+class QDesignerIntegrationInterface;
+class QDesignerFormEditorInterface;
+class QtDesignerDocumentFactory;
+class QtDesignerToolViewFactory;
+
+namespace KDevelop
+{
+ class IDocument;
+}
+
+template<class T> class QList;
+
+typedef QHash<QAction*, QAction*> DesignerActionHash;
+
+
+/**
+ * This is a plugin that embeds Qt designer into a kdevplatform application
+ *
+ * TODO: - fix moving of form contents via mouse
+ * TODO: - properly enable/disable save button
+ * TODO: - detect external changes by using QFileSystemWatcher (more reliable implementation than KDirWatch)
+ * TODO: - fix other ui bugs, like having to double-click in a menubar to edit it
+ */
+class QtDesignerPlugin: public KDevelop::IPlugin
+{
+ Q_OBJECT
+public:
+ QtDesignerPlugin(QObject *parent, const QVariantList &args = QVariantList() );
+ virtual ~QtDesignerPlugin();
+
+// virtual bool openFile();
+// virtual bool saveFile();
+
+ QDesignerFormEditorInterface *designer() const;
+public Q_SLOTS:
+// void activateDocument( KDevelop::IDocument* );
+protected:
+
+private:
+
+private Q_SLOTS:
+// void saveActiveDocument();
+private:
+ QDesignerIntegrationInterface* m_designer;
+
+// KDevelop::IDocument* m_activeDoc;
+ QtDesignerDocumentFactory* m_docFactory;
+ QtDesignerToolViewFactory* m_widgetBoxFactory;
+ QtDesignerToolViewFactory* m_propertyEditorFactory;
+ QtDesignerToolViewFactory* m_objectInspectorFactory;
+ QtDesignerToolViewFactory* m_actionEditorFactory;
+ QtDesignerToolViewFactory* m_signalSlotEditorFactory;
+ QtDesignerToolViewFactory* m_resourceEditorFactory;
+};
+
+#endif // QTDESIGNER_PART_H
+//kate: space-indent on; indent-width 2; replace-tabs on; indent-mode cstyle;
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h (revision 1522570)
@@ -0,0 +1,96 @@
+/****************************************************************************
+**
+** Copyright 1992-2007 Trolltech ASA. All rights reserved.
+**
+** This file is part of the Qt Designer of the Qt Toolkit.
+**
+** This file may be used under the terms of the GNU General Public
+** License version 2.0 as published by the Free Software Foundation
+** and appearing in the file LICENSE.GPL included in the packaging of
+** this file. Please review the following information to ensure GNU
+** General Public Licensing requirements will be met:
+** http://www.trolltech.com/products/qt/opensource.html
+**
+** If you are unsure which license is appropriate for your use, please
+** review the following information:
+** http://www.trolltech.com/products/qt/licensing.html or contact the
+** sales department at sales@trolltech.com.
+**
+** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
+** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+**
+****************************************************************************/
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of Qt Designer. This header
+// file may change from version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef QDESIGNER_INTEGRATION_H
+#define QDESIGNER_INTEGRATION_H
+
+#include "shared_global_p.h"
+#include <QtDesigner/QDesignerIntegrationInterface>
+
+#include <QtCore/QObject>
+
+class QDesignerFormEditorInterface;
+class QDesignerFormWindowInterface;
+class QDesignerFormWindowManagerInterface;
+
+class QVariant;
+class QWidget;
+
+namespace qdesigner_internal {
+
+struct Selection;
+
+class QDESIGNER_SHARED_EXPORT QDesignerIntegration: public QDesignerIntegrationInterface
+{
+ Q_OBJECT
+public:
+ QDesignerIntegration(QDesignerFormEditorInterface *core, QObject *parent = 0);
+ virtual ~QDesignerIntegration();
+
+ virtual QWidget *containerWindow(QWidget *widget) const;
+
+ // Load plugins into widget database and factory.
+ static void initializePlugins(QDesignerFormEditorInterface *formEditor);
+
+signals:
+ void propertyChanged(QDesignerFormWindowInterface *formWindow, const QString &name, const QVariant &value);
+
+public slots:
+ //virtual void updateProperty(const QString &name, const QVariant &value);
+ // Additional signals of designer property editor
+ virtual void updatePropertyComment(const QString &name, const QString &value);
+ virtual void resetProperty(const QString &name);
+ virtual void addDynamicProperty(const QString &name, const QVariant &value);
+ virtual void removeDynamicProperty(const QString &name);
+
+
+ virtual void updateActiveFormWindow(QDesignerFormWindowInterface *formWindow);
+ virtual void setupFormWindow(QDesignerFormWindowInterface *formWindow);
+ virtual void updateSelection();
+ virtual void updateGeometry();
+ virtual void activateWidget(QWidget *widget);
+
+ void updateCustomWidgetPlugins();
+
+private:
+ void initialize();
+ void getSelection(Selection &s);
+ QObject *propertyEditorObject();
+
+ QDesignerFormWindowManagerInterface *m_formWindowManager;
+};
+
+} // namespace qdesigner_internal
+
+#endif // QDESIGNER_INTEGRATION_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h (revision 1522570)
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright 1992-2006 Trolltech AS. All rights reserved.
+**
+** This file is part of the Qt Designer of the Qt Toolkit.
+**
+** This file may be used under the terms of the GNU General Public
+** License version 2.0 as published by the Free Software Foundation
+** and appearing in the file LICENSE.GPL included in the packaging of
+** this file. Please review the following information to ensure GNU
+** General Public Licensing requirements will be met:
+** http://www.trolltech.com/products/qt/opensource.html
+**
+** If you are unsure which license is appropriate for your use, please
+** review the following information:
+** http://www.trolltech.com/products/qt/licensing.html or contact the
+** sales department at sales@trolltech.com.
+**
+** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
+** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+**
+****************************************************************************/
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of Qt Designer. This header
+// file may change from version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef SHARED_GLOBAL_H
+#define SHARED_GLOBAL_H
+
+#include <QtCore/qglobal.h>
+
+#ifdef QT_DESIGNER_STATIC
+#define QDESIGNER_SHARED_EXTERN
+#define QDESIGNER_SHARED_IMPORT
+#else
+#define QDESIGNER_SHARED_EXTERN Q_DECL_EXPORT
+#define QDESIGNER_SHARED_IMPORT Q_DECL_IMPORT
+#endif
+
+#ifndef QT_NO_SHARED_EXPORT
+# ifdef QDESIGNER_SHARED_LIBRARY
+# define QDESIGNER_SHARED_EXPORT QDESIGNER_SHARED_EXTERN
+# else
+# define QDESIGNER_SHARED_EXPORT QDESIGNER_SHARED_IMPORT
+# endif
+#else
+# define QDESIGNER_SHARED_EXPORT
+#endif
+
+#endif // SHARED_GLOBAL_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp (revision 1522570)
@@ -0,0 +1,43 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#include "qtdesignerview.h"
+
+#include <QtDesigner/QDesignerFormWindowInterface>
+
+#include "qtdesignerdocument.h"
+#include "qtdesignerwidget.h"
+
+QtDesignerView::QtDesignerView( QtDesignerDocument* doc )
+ : Sublime::View( doc ), m_widget( 0 )
+{
+}
+
+QtDesignerView::~QtDesignerView()
+{
+}
+
+QWidget* QtDesignerView::createWidget( QWidget* parent )
+{
+ return new QtDesignerWidget( parent, qobject_cast<QtDesignerDocument*>( document() ) );
+}
+
+#include "qtdesignerview.moc"
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h (revision 1522570)
@@ -0,0 +1,43 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef QTDESIGNERVIEW_H
+#define QTDESIGNERVIEW_H
+
+#include <sublime/view.h>
+
+class QtDesignerDocument;
+class QtDesignerWidget;
+class QDesignerFormWindowInterface;
+
+class QtDesignerView : public Sublime::View
+{
+ Q_OBJECT
+public:
+ QtDesignerView( QtDesignerDocument* );
+ ~QtDesignerView();
+ QWidget* createWidget( QWidget* parent = 0 );
+private:
+ QDesignerFormWindowInterface* m_form;
+ QtDesignerWidget* m_widget;
+};
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/qtdesigner
___________________________________________________________________
Added: svn:ignore
## -0,0 +1,4 ##
+.libs
+Makefile
+Makefile.in
+*.moc
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.desktop (revision 1522570)
@@ -0,0 +1,71 @@
+[Desktop Entry]
+Type=Service
+Icon=kdevelop
+Exec=blubb
+Comment=SLOC
+Comment[bs]=SLOC
+Comment[ca]=SLOC
+Comment[ca@valencia]=SLOC
+Comment[cs]=SLOC
+Comment[de]=SLOC
+Comment[el]=SLOC
+Comment[en_GB]=SLOC
+Comment[es]=SLOC
+Comment[et]=SLOC
+Comment[fr]=SLOC
+Comment[ga]=SLOC
+Comment[gl]=SLOC
+Comment[hne]=एसएलओसी
+Comment[hu]=SLOC
+Comment[it]=SLOC
+Comment[ja]=SLOC
+Comment[nds]=Bornkoderegen
+Comment[nl]=SLOC
+Comment[pa]=SLOC
+Comment[pl]=SLOC
+Comment[pt]=SLOC
+Comment[pt_BR]=SLOC
+Comment[si]=SLOC
+Comment[sk]=SLOC
+Comment[sv]=Antal källkodsrader
+Comment[tr]=SLOC
+Comment[ug]=SLOC
+Comment[uk]=SLOC
+Comment[x-test]=xxSLOCxx
+
+Name=SLOC report
+Name[bs]=SLOC izvještaj
+Name[ca]=Informe d'SLOC
+Name[ca@valencia]=Informe d'SLOC
+Name[cs]=Hlášení SLOC
+Name[de]=SLOC-Bericht
+Name[el]=Αναφορά SLOC
+Name[en_GB]=SLOC report
+Name[es]=Informe SLOC
+Name[et]=SLOC-i aruanne
+Name[fr]=Statistiques sur les lignes de code source (SLOC)
+Name[ga]=Tuairisc SLOC
+Name[gl]=Informe de SLOC
+Name[hu]=SLOC jelentés
+Name[it]=Resoconto SLOC
+Name[ja]=SLOC レポート
+Name[nds]=Bornregenbericht
+Name[nl]=SLOC-rapport
+Name[pa]=SLOC ਰਿਪੋਰਟ
+Name[pl]=Sprawozdanie SLOC
+Name[pt]=Relatório de SLOC's
+Name[pt_BR]=Relatório SLOC
+Name[sk]=Správa SLOC
+Name[sv]=Rapport av antal källkodsrader
+Name[tr]=SLOC bildirimi
+Name[uk]=Звіт SLOC
+Name[x-test]=xxSLOC reportxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevsloc
+X-KDE-PluginInfo-Name=kdevsloc
+X-KDE-PluginInfo-Author=Manuel Breugelmans
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=LGPL
+X-KDevelop-Version=7
+X-KDevelop-Category=Global
+X-KDevelop-Properties=GlobalFileManagement
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.cpp (revision 1522570)
@@ -0,0 +1,114 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "slocplugin.h"
+
+#include <KAction>
+#include <KActionCollection>
+#include <KDebug>
+#include <KLocale>
+#include <KPluginFactory>
+#include <KPluginLoader>
+
+#include <project/projectmodel.h>
+#include <project/interfaces/ibuildsystemmanager.h>
+#include <project/interfaces/iprojectfilemanager.h>
+
+#include <interfaces/context.h>
+#include <interfaces/contextmenuextension.h>
+#include <interfaces/iproject.h>
+
+#include <QTreeView>
+#include <QHeaderView>
+#include <QSortFilterProxyModel>
+
+#include "clocparser.h"
+#include "reportmodel.h"
+
+using namespace KDevelop;
+
+K_PLUGIN_FACTORY(SlocPluginFactory, registerPlugin<SlocPlugin>();)
+K_EXPORT_PLUGIN(SlocPluginFactory("kdevsloc"))
+
+SlocPlugin::SlocPlugin(QObject* parent, const QVariantList&)
+ : KDevelop::IPlugin( SlocPluginFactory::componentData(), parent )
+{
+ setXMLFile("kdevsloc.rc");
+ m_report = actionCollection()->addAction("spawn_sloc");
+ m_report->setText(i18n("SLOC Report"));
+ connect(m_report, SIGNAL(triggered()), this, SLOT(startParser()));
+ m_watcher = new QFutureWatcher<QList<QStandardRow> >(this);
+ connect(m_watcher, SIGNAL(finished()), SLOT(spawnReport()));
+}
+
+SlocPlugin::~SlocPlugin()
+{}
+
+#include <QtConcurrentRun>
+#include <QFutureWatcher>
+
+void SlocPlugin::startParser()
+{
+ ClocParser* parser = new ClocParser;
+ QFuture<QList< QStandardRow> > rows = QtConcurrent::run(parser, &ClocParser::parse, m_folder);
+ m_watcher->setFuture(rows);
+}
+
+void SlocPlugin::spawnReport()
+{
+ QList<QStandardRow> rows = m_watcher->future().result();
+ QStandardItemModel* model = new QStandardItemModel();
+ model->setHorizontalHeaderLabels(QStringList() << i18nc("Source file", "File") << i18n("Code") << i18n("Comments") << i18nc("Programming language", "Language"));
+ foreach(QStandardRow row, rows) {
+ model->appendRow(row);
+ }
+ QTreeView* view = new QTreeView();
+ view->header()->setMovable(false);
+ view->setUniformRowHeights(true);
+ QSortFilterProxyModel* proxy = new QSortFilterProxyModel;
+ proxy->setSourceModel(model);
+ proxy->setSortRole(Sloc::SortRole);
+ view->setModel(proxy);
+ view->setSortingEnabled(true);
+ view->show();
+}
+
+ContextMenuExtension SlocPlugin::contextMenuExtension(Context* context)
+{
+ ContextMenuExtension cm;
+ if (context->type() != Context::ProjectItemContext) {
+ return cm; // NO-OP
+ }
+ ProjectItemContext *pc = dynamic_cast<ProjectItemContext*>(context);
+ if (!pc) {
+ kWarning() << "Context::ProjectItemContext but cast failed. Not good.";
+ return cm;
+ }
+ QList<ProjectBaseItem*> bl = pc->items();
+ if (!bl.count() || !bl[0] || !bl[0]->folder()) {
+ return cm; // only show Sloc menu action on folders
+ }
+ m_folder = bl[0]->folder()->url();
+ cm.addAction(ContextMenuExtension::ExtensionGroup, m_report);
+
+ return cm;
+}
+
+#include "slocplugin.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,32 @@
+project(sloc)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${sloc_SOURCE_DIR}/cmake/)
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+
+include_directories(
+ ${QT_INCLUDES}
+ ${KDE4_INCLUDES}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR} )
+
+########### next target ###############
+
+set(kdevsloc_SRCS reportmodel.cpp reportwidget.cpp slocplugin.cpp clocparser.cpp)
+qt4_automoc(${kdevsloc_SRCS})
+kde4_add_plugin(kdevsloc ${kdevsloc_SRCS})
+target_link_libraries(kdevsloc
+ ${QT_QTCORE_LIBRARY}
+ ${QT_QTGUI_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDE4_KDEUI_LIBS}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_PROJECT_LIBRARIES})
+install(TARGETS kdevsloc DESTINATION ${PLUGIN_INSTALL_DIR})
+
+########### install files ###############
+
+install( FILES kdevsloc.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevsloc.rc DESTINATION ${DATA_INSTALL_DIR}/kdevsloc )
+install( PROGRAMS cloc-1.04.pl DESTINATION ${BIN_INSTALL_DIR} )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevsloc.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.h (revision 1522570)
@@ -0,0 +1,55 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <QStandardItem>
+#include <KUrl>
+
+namespace Sloc
+{
+
+enum
+{
+ FileType = QStandardItem::UserType+1
+};
+
+enum
+{
+ SortRole = Qt::UserRole+1
+};
+
+}
+
+class SlocFileItem : public QStandardItem
+{
+public:
+ SlocFileItem(const KUrl& location) : QStandardItem(location.path()), m_location(location) {
+ setData(location.path(), Sloc::SortRole);
+ setEditable(false);
+ }
+ virtual ~SlocFileItem() {}
+ virtual int type() const { return Sloc::FileType; }
+ virtual void truncate(const KUrl& prefix) {
+ if (!prefix.isParentOf(m_location)) return;
+ setData(KUrl::relativeUrl(prefix, m_location), Qt::DisplayRole);
+ }
+
+private:
+ KUrl m_location;
+};
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.cpp (revision 1522570)
@@ -0,0 +1,132 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "clocparser.h"
+#include "reportmodel.h"
+
+#include <KProcess>
+#include <KUrl>
+#include <KDebug>
+
+namespace
+{
+
+QMap<QString, QString> extensions()
+{
+/*./cloc-1.04.pl --show-ext
+abap -> ABAP
+ac -> m4
+ada -> Ada
+adb -> Ada
+ads -> Ada
+adso -> ADSO/IDSM
+am -> make
+ample -> AMPLE */
+
+ KProcess cloc;
+ QStringList argv;
+ cloc.setProgram("cloc-1.04.pl", QStringList() << "--show-ext");
+ cloc.setOutputChannelMode(KProcess::SeparateChannels);
+ cloc.start();
+ cloc.waitForFinished(-1);
+ QString out(cloc.readAllStandardOutput());
+ QMap<QString,QString> results;
+ foreach(QString line, out.split("\n")) {
+ QStringList spl = line.split("->");
+ if (spl.count() != 2) continue;
+ results[spl[0].simplified()] = spl[1].simplified();
+ }
+ return results;
+}
+
+QString executeCloc(const KUrl& directory)
+{
+ KProcess cloc;
+ QStringList argv;
+ argv << "--by-file" << "--exclude-dir=.svn,build" << "--no3" << "--quiet" << "--csv" << directory.path();
+ cloc.setProgram("cloc-1.04.pl", argv);
+ cloc.setOutputChannelMode(KProcess::SeparateChannels);
+ cloc.start();
+ cloc.waitForFinished(-1);
+ return cloc.readAllStandardOutput();
+}
+
+}
+
+QStandardRow ClocParser::parseLine(const QString& line, const Languages& languages)
+{
+ QStandardRow row;
+ if (line.isEmpty() || line.startsWith(",,")) return row;
+ QStringList spl = line.split(",");
+ if (spl.count() != 5) return row;
+
+ QString file = spl[0];
+ QString extension = file.split(".").value(file.split(".").count()-1);
+ QString language = (languages.contains(extension)) ? languages[extension] : "unknown";
+ int blank = spl[2].toInt();
+ int comment = spl[3].toInt();
+ int code = spl[4].toInt();
+ kDebug() << file << blank << comment << code;
+
+ SlocFileItem* fileItem = new SlocFileItem(file);
+ fileItem->truncate(m_root);
+ QStandardItem* languageItem = new QStandardItem(language);
+ languageItem->setData(language, Sloc::SortRole);
+ languageItem->setEditable(false);
+// QStandardItem* blankItem = new QStandardItem(QString::number(blank));
+// blankItem->setSortRole(blank, Sloc::SortRole)
+// blankItem->setEditable(false);
+ QStandardItem* commentItem = new QStandardItem(QString::number(comment));
+ commentItem->setData(comment, Sloc::SortRole);
+ commentItem->setEditable(false);
+ QStandardItem* codeItem = new QStandardItem(QString::number(code));
+ codeItem->setData(code, Sloc::SortRole);
+ codeItem->setEditable(false);
+
+ return row << fileItem << codeItem << commentItem << languageItem;
+}
+
+QList<QStandardRow> ClocParser::parse(const KUrl& directory)
+{
+
+// ./cloc-1.04.pl --by-file --exclude-dir=build --no3 --quiet --csv .
+//
+// ,,blank,comment,code,"http://cloc.sourceforge.net v 1.04 T=0.5 s (18.0 files/s, 13034.0 lines/s)"
+// ./slocplugin.cpp,1,13,19,61
+// ./slocproxymodel.cpp,1,11,18,34
+// ./clocparser.cpp,1,8,9,34
+// ./slocplugin.h,1,9,19,25
+// ./slocproxymodel.h,1,9,19,20
+
+ if (directory.isEmpty()) return QList<QStandardRow>();
+ m_root = directory;
+
+ QMap<QString,QString> languages = extensions();
+ QString out = executeCloc(directory);
+ QList<QStandardRow> rows;
+
+ foreach(QString line, out.split("\n")) {
+ QStandardRow row = parseLine(line, languages);
+ if (!row.isEmpty()) rows << row;
+ }
+
+ return rows;
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/clocparser.h (revision 1522570)
@@ -0,0 +1,43 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef CLOCPARSER_H
+#define CLOCPARSER_H
+
+#include <QStandardItem>
+#include <KUrl>
+
+typedef QList<QStandardItem*> QStandardRow;
+typedef QMap<QString, QString> Languages;
+
+class ClocParser
+{
+public:
+ /*! Execute CLOC process and parse output into a QStandardItem tree.
+ * @param directory compute sloc for this dir, recursivly
+ * @return top rows */
+ QList<QStandardRow> parse(const KUrl& directory);
+
+private:
+ QStandardRow parseLine(const QString& line, const Languages& languages);
+ KUrl m_root;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocplugin.h (revision 1522570)
@@ -0,0 +1,57 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef SLOCPLUGIN_H
+#define SLOCPLUGIN_H
+
+#include <QVariantList>
+#include <KUrl>
+#include <interfaces/iplugin.h>
+#include <QFutureWatcher>
+#include "clocparser.h"
+
+namespace KDevelop
+{
+class ContextMenuExtension;
+class Context;
+}
+class KAction;
+
+class SlocPlugin : public KDevelop::IPlugin
+{
+Q_OBJECT
+
+public:
+ explicit SlocPlugin(QObject* parent, const QVariantList& = QVariantList());
+ virtual ~SlocPlugin();
+ KDevelop::ContextMenuExtension contextMenuExtension(KDevelop::Context* context);
+
+private slots:
+ void startParser();
+ void spawnReport();
+
+private:
+ KUrl m_folder;
+ KAction* m_report;
+ QFutureWatcher<QList<QStandardRow> >* m_watcher;
+};
+
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportwidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportwidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportwidget.cpp (revision 1522570)
@@ -0,0 +1,19 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp (revision 1522570)
@@ -0,0 +1,19 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/slocproxymodel.h (revision 1522570)
@@ -0,0 +1,19 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/reportmodel.cpp (revision 1522570)
@@ -0,0 +1,19 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cloc-1.04.pl
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cloc-1.04.pl (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cloc-1.04.pl (revision 1522570)
@@ -0,0 +1,5787 @@
+#!/usr/bin/env perl
+# cloc -- Count Lines of Code {{{1
+# Copyright (C) 2006-2008 Northrop Grumman Corporation
+# Author: Al Danial <al.danial@gmail.com>
+# First release August 2006
+#
+# Includes code from:
+# - SLOCCount v2.26
+# http://www.dwheeler.com/sloccount/
+# by David Wheeler.
+# - Regexp::Common v2.120
+# http://search.cpan.org/~abigail/Regexp-Common-2.120/lib/Regexp/Common.pm
+# by Damian Conway and Abigail
+# - Win32::Autoglob
+# http://search.cpan.org/~sburke/Win32-Autoglob-1.01/Autoglob.pm
+# by Sean M. Burke
+# - Algorithm::Diff
+# http://search.cpan.org/~tyemq/Algorithm-Diff-1.1902/lib/Algorithm/Diff.pm
+# by Tye McQueen
+#
+# 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:
+# http://www.gnu.org/licenses/gpl.txt
+#
+# 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
+# 1}}}
+my $VERSION = 1.04;
+require 5.006;
+# use modules {{{1
+use warnings;
+use strict;
+use Getopt::Long;
+use File::Basename;
+use File::Temp qw { tempfile tempdir };
+use File::Find;
+use File::Path;
+use IO::File;
+
+# Digest::MD5 isn't in the standard distribution. Use it only if installed.
+my $HAVE_Digest_MD5 = 0;
+eval "use Digest::MD5;";
+if (defined $Digest::MD5::VERSION) {
+ $HAVE_Digest_MD5 = 1;
+} else {
+ warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
+}
+
+my $HAVE_Rexexp_Common;
+# Regexp::Common isn't in the standard distribution. It will
+# be installed in a temp directory if necessary.
+BEGIN {
+ if (eval "use Regexp::Common;") {
+ $HAVE_Rexexp_Common = 1;
+ } else {
+ $HAVE_Rexexp_Common = 0;
+ }
+}
+
+my $HAVE_Algorith_Diff = 0;
+# Algorithm::Diff isn't in the standard distribution. It will
+# be installed in a temp directory if necessary.
+eval "use Algorithm::Diff;";
+if (defined $Algorithm::Diff::VERSION) {
+ $HAVE_Algorith_Diff = 1;
+} else {
+ Install_Algorithm_Diff();
+}
+# print "HAVE_Algorith_Diff = $HAVE_Algorith_Diff\n";
+# test_alg_diff("cloc-0.80.pl", "cloc-0.90.pl", ); die;
+
+# Uncomment next two lines when building Windows executable with perl2exe
+# or if running on a system that already has Regexp::Common.
+#use Regexp::Common;
+#$HAVE_Rexexp_Common = 1;
+
+#perl2exe_include "Regexp/Common/whitespace.pm"
+#perl2exe_include "Regexp/Common/URI.pm"
+#perl2exe_include "Regexp/Common/URI/fax.pm"
+#perl2exe_include "Regexp/Common/URI/file.pm"
+#perl2exe_include "Regexp/Common/URI/ftp.pm"
+#perl2exe_include "Regexp/Common/URI/gopher.pm"
+#perl2exe_include "Regexp/Common/URI/http.pm"
+#perl2exe_include "Regexp/Common/URI/pop.pm"
+#perl2exe_include "Regexp/Common/URI/prospero.pm"
+#perl2exe_include "Regexp/Common/URI/news.pm"
+#perl2exe_include "Regexp/Common/URI/tel.pm"
+#perl2exe_include "Regexp/Common/URI/telnet.pm"
+#perl2exe_include "Regexp/Common/URI/tv.pm"
+#perl2exe_include "Regexp/Common/URI/wais.pm"
+#perl2exe_include "Regexp/Common/CC.pm"
+#perl2exe_include "Regexp/Common/SEN.pm"
+#perl2exe_include "Regexp/Common/number.pm"
+#perl2exe_include "Regexp/Common/delimited.pm"
+#perl2exe_include "Regexp/Common/profanity.pm"
+#perl2exe_include "Regexp/Common/net.pm"
+#perl2exe_include "Regexp/Common/zip.pm"
+#perl2exe_include "Regexp/Common/comment.pm"
+#perl2exe_include "Regexp/Common/balanced.pm"
+#perl2exe_include "Regexp/Common/lingua.pm"
+#perl2exe_include "Regexp/Common/list.pm"
+#perl2exe_include "File/Glob.pm"
+
+use Text::Tabs qw { expand };
+use Cwd qw { cwd };
+# 1}}}
+# Usage information, options processing. {{{1
+my $script = basename $0;
+my $usage = "
+Usage: $script [options] <file(s)/dir(s)> | <report files>
+
+ Count physical lines of source code in the given files and/or
+ recursively below the given directories.
+
+ Options:
+ --by-file Report results for every source file encountered
+ in addition to reporting by language.
+ --categorized=<file> Save names of categorized files to <file>.
+ --counted=<file> Save names of processed source files to <file>.
+ --exclude-dir=<D1>[,D2,] Exclude the given comma separated directories
+ D1, D2, D3, et cetera, from being scanned. For
+ example --exclude-dir=.cvs,.svn will skip
+ all files that have /.cvs/ or /.svn/ as part of
+ their path.
+ --exclude-lang=<L1>[,L2,] Exclude the given comma separated languages
+ L1, L2, L3, et cetera, from being counted.
+ --extract-with=<cmd> Use <cmd> to extract binary archive files (e.g.:
+ .tar.gz, .zip, .Z). Use the literal '>FILE<' as
+ a stand-in for the actual file(s) to be
+ extracted. For example, to count lines of code
+ in the input files
+ gcc-4.2.tar.gz perl-5.8.8.tar.gz
+ on Unix use
+ --extract-with='gzip -dc >FILE< | tar xf -'
+ or, if you have GNU tar,
+ --extract-with='tar zxf >FILE<'
+ and on Windows use:
+ --extract-with=\"\\\"c:\\Program Files\\WinZip\\WinZip32.exe\\\" -e -o >FILE< .\"
+ (if WinZip is installed there).
+ --force-lang=<lang>[,<ext>]
+ Process all files that have a <ext> extension
+ with the counter for language <lang>. For
+ example, to count all .f files with the
+ Fortran 90 counter (which expects files to
+ end with .f90) instead of the default Fortran 77
+ counter, use
+ --force-lang=\"Fortran 90\",f
+ If <ext> is omitted, every file will be counted
+ with the <lang> counter. This option can be
+ specified multiple times (but that is only
+ useful when <ext> is given each time).
+ See also --script-lang.
+ --found=<file> Save names of every file found to <file>.
+ --ignored=<file> Save names of ignored files and the reason they
+ were ignored to <file>.
+ --no3 Suppress third-generation language output.
+ This option can cause report summation to fail
+ if some reports were produced with this option
+ while others were produced without it.
+ --print-filter-stages Print to STDOUT processed source code before and
+ after each filter is applied.
+ --progress-rate=<n> Show progress update after every <n> files are
+ processed (default <n>=100). Set <n> to 0 to
+ suppress progress output (useful when redirecting
+ output to STDOUT).
+ --quiet Suppress all information messages except for
+ the final report.
+ --report-file=<file> Write the results to <file> instead of STDOUT.
+ --read-lang-def=<file> Load from <file> the language processing filters.
+ (see also --write-lang-def) then use these filters
+ instead of the built-in filters.
+ --script-lang=<lang>,<s> Process all files that invoke <s> as a #!
+ scripting language with the counter for language
+ <lang>. For example, files that begin with
+ #!/usr/local/bin/perl5.8.8
+ will be counted with the Perl counter by using
+ --script-lang=Perl,perl5.8.8
+ The language name is case insensitive but the
+ name of the script language executable, <s>,
+ must have the right case. This option can be
+ specified multiple times. See also --force-lang.
+ --sdir=<dir> Use <dir> as the scratch directory instead of
+ letting File::Temp chose the location. Files
+ written to this location are not removed at
+ the end of the run (as they are with File::Temp).
+ --show-ext[=<ext>] Print information about all known (or just the
+ given) file extensions and exit.
+ --show-lang[=<lang>] Print information about all known (or just the
+ given) languages and exit.
+ --strip-comments=<ext> For each file processed, write to the current
+ directory a version of the file which has blank
+ lines and comments removed. The name of each
+ stripped file is the original file name with
+ .<ext> appended to it.
+ --sum-reports Input arguments are report files previously
+ created with the --report-file option. Makes
+ a cumulative set of results containing the
+ sum of data from the individual report files.
+ --unicode Check binary files to see if they contain Unicode
+ expanded ASCII text. This causes performance to
+ drop noticably.
+ --write-lang-def=<file> Writes to <file> the language processing filters
+ then exits. Useful as a first step to creating
+ custom language definitions (see --read-lang-def).
+ -v[=<n>] Verbose switch (optional numeric value).
+ --version Print the version of this program and exit.
+ --csv Write the results as comma separated values.
+ --xml Write the results in XML.
+ --yaml Write the results in YAML.
+
+";
+# Help information for options not yet implemented:
+# --diff Shows counts of code and comment changes between
+# successive pairs of inputs:
+# delta(FD_1, FD_2), delta(FD_2, FD_3), etc
+# (FD means 'file, archive, or directory')
+# --html Create HTML files of each input file showing
+# comment and code lines in different colors.
+
+$| = 1; # flush STDOUT
+my $start_time = time();
+my (
+ $opt_categorized ,
+ $opt_found ,
+ @opt_force_lang ,
+ @opt_script_lang ,
+ $opt_diff ,
+ $opt_html ,
+ $opt_ignored ,
+ $opt_counted ,
+ $opt_show_ext ,
+ $opt_show_lang ,
+ $opt_progress_rate ,
+ $opt_print_filter_stages ,
+ $opt_v ,
+ $opt_version ,
+ $opt_exclude_lang ,
+ $opt_exclude_dir ,
+ $opt_read_lang_def ,
+ $opt_write_lang_def ,
+ $opt_strip_comments ,
+ $opt_quiet ,
+ $opt_report_file ,
+ $opt_sdir ,
+ $opt_sum_reports ,
+ $opt_unicode ,
+ $opt_no3 ,
+ $opt_extract_with ,
+ $opt_by_file ,
+ $opt_xml ,
+ $opt_yaml ,
+ $opt_csv ,
+ );
+GetOptions(
+ "by_file|by-file" => \$opt_by_file ,
+ "categorized=s" => \$opt_categorized ,
+ "counted=s" => \$opt_counted ,
+ "exclude_lang|exclude-lang=s" => \$opt_exclude_lang ,
+ "exclude_dir|exclude-dir=s" => \$opt_exclude_dir ,
+ "extract_with|extract-with=s" => \$opt_extract_with ,
+ "found=s" => \$opt_found ,
+ "diff" => \$opt_diff ,
+ "html" => \$opt_html ,
+ "ignored=s" => \$opt_ignored ,
+ "quiet" => \$opt_quiet ,
+ "read_lang_def|read-lang-def=s" => \$opt_read_lang_def ,
+ "show_ext|show-ext:s" => \$opt_show_ext ,
+ "show_lang|show-lang:s" => \$opt_show_lang ,
+ "progress_rate|progress-rate=i" => \$opt_progress_rate ,
+ "print_filter_stages|print-filter-stages" => \$opt_print_filter_stages ,
+ "report_file|report-file=s" => \$opt_report_file ,
+ "script_lang|script-lang=s" => \@opt_script_lang ,
+ "sdir=s" => \$opt_sdir ,
+ "strip_comments|strip-comments=s" => \$opt_strip_comments ,
+ "sum_reports|sum-reports" => \$opt_sum_reports ,
+ "unicode" => \$opt_unicode ,
+ "no3" => \$opt_no3 ,
+ "v:i" => \$opt_v ,
+ "version" => \$opt_version ,
+ "write_lang_def|write-lang-def=s" => \$opt_write_lang_def ,
+ "xml" => \$opt_xml ,
+ "force_lang|force-lang=s" => \@opt_force_lang ,
+ "yaml" => \$opt_yaml ,
+ "csv" => \$opt_csv ,
+ );
+
+my %Exclude_Language = ();
+ %Exclude_Language = map { $_ => 1 } split(/,/, $opt_exclude_lang)
+ if $opt_exclude_lang;
+my %Exclude_Dir = ();
+ %Exclude_Dir = map { $_ => 1 } split(/,/, $opt_exclude_dir )
+ if $opt_exclude_dir ;
+# Options defaults:
+$opt_progress_rate = 100 unless defined $opt_progress_rate;
+$opt_v = 0 unless defined $opt_v;
+die $usage unless defined $opt_version or
+ defined $opt_show_lang or
+ defined $opt_show_ext or
+ defined $opt_write_lang_def or
+ scalar @ARGV >= 1;
+die "--diff requires at least two arguments\n"
+ if $opt_diff and scalar @ARGV < 2;
+# 1}}}
+# Step 1: Initialize global constants. {{{1
+#
+my $ON_WINDOWS = 0;
+ $ON_WINDOWS = 1 if ($^O =~ /^MSWin/) or ($^O eq "Windows_NT");
+ $ON_WINDOWS = 0 if $ENV{'SHELL'}; # make Cygwin look like Unix
+
+my $nFiles_Found = 0; # updated in make_file_list
+my (%Language_by_Extension, %Language_by_Script,
+ %Filters_by_Language, %Not_Code_Extension, %Not_Code_Filename,
+ %Language_by_File, %Scale_Factor, %Known_Binary_Archives,
+ );
+my %Error_Codes = ( 'Unable to read' => -1,
+ 'Neither file nor directory' => -2, );
+if ($opt_read_lang_def) {
+ read_lang_def(
+ $opt_read_lang_def , # Sample values:
+ \%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
+ \%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
+ \%Language_by_File , # Language_by_File{makefile} = 'make'
+ \%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
+ # [ 'remove_matches' , '^\s*#' ]
+ \%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
+ \%Not_Code_Filename , # Not_Code_Filename{README} = 1
+ \%Scale_Factor , # Scale_Factor{Perl} = 4.0
+ );
+} else {
+ set_constants( #
+ \%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
+ \%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
+ \%Language_by_File , # Language_by_File{makefile} = 'make'
+ \%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
+ # [ 'remove_matches' , '^\s*#' ]
+ \%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
+ \%Not_Code_Filename , # Not_Code_Filename{README} = 1
+ \%Scale_Factor , # Scale_Factor{Perl} = 4.0
+ \%Known_Binary_Archives, # Known_Binary_Archives{.tar} = 1
+ );
+}
+
+# Process command line provided extention-to-language mapping overrides.
+# Make a hash of known languages in lower case for easier matching.
+my %Recognized_Language_lc = (); # key = language name in lc, value = true name
+foreach my $language (keys %Filters_by_Language) {
+ my $lang_lc = lc $language;
+ $Recognized_Language_lc{$lang_lc} = $language;
+}
+my %Forced_Extension = (); # file name extensions which user wants to count
+my $All_One_Language = 0; # set to !0 if --force-lang's <ext> is missing
+foreach my $pair (@opt_force_lang) {
+ my ($lang, $extension) = split(',', $pair);
+ my $lang_lc = lc $lang;
+ if (defined $extension) {
+ $Forced_Extension{$extension} = $lang;
+
+ die_unknown_lang($lang, "--force-lang")
+ unless $Recognized_Language_lc{$lang_lc};
+
+ $Language_by_Extension{$extension} = $Recognized_Language_lc{$lang_lc};
+ } else {
+ # the scary case--count everything as this language
+ $All_One_Language = $Recognized_Language_lc{$lang_lc};
+ }
+}
+
+foreach my $pair (@opt_script_lang) {
+ my ($lang, $script_name) = split(',', $pair);
+ my $lang_lc = lc $lang;
+ if (!defined $script_name) {
+ die "The --script-lang option requires a comma separated pair of ".
+ "strings.\n";
+ }
+
+ die_unknown_lang($lang, "--script-lang")
+ unless $Recognized_Language_lc{$lang_lc};
+
+ $Language_by_Script{$script_name} = $Recognized_Language_lc{$lang_lc};
+}
+# invert %Language_by_Script hash to get an easy-to-look-up list of known
+# scripting languages
+my %Script_Language = map { $_ => 1 } values %Language_by_Script ;
+# 1}}}
+# Step 2: Early exits for display, summation. {{{1
+#
+if ($opt_version) {
+ printf "%.2f\n", $VERSION;
+ exit;
+}
+print_extension_info($opt_show_ext ) if defined $opt_show_ext ;
+print_language_info( $opt_show_lang) if defined $opt_show_lang;
+exit if (defined $opt_show_ext) or (defined $opt_show_lang);
+
+# Windows doesn't expand wildcards. Use code from Sean M. Burke's
+# Win32::Autoglob module to do this.
+#print "Before glob have [", join(",", @ARGV), "]\n";
+@ARGV = map {;
+ ( defined($_) and m/[\*\?]/ ) ? sort(glob($_)) : $_
+ } @ARGV if $ON_WINDOWS;
+;
+#print "after glob have [", join(",", @ARGV), "]\n";
+
+if ($opt_sum_reports) {
+ my %Results = ();
+ foreach my $type( "by language", "by report file" ) {
+ my $found_lang = combine_results(\@ARGV,
+ $type,
+ \%{$Results{ $type }},
+ \%Filters_by_Language );
+ next unless %Results;
+ my $end_time = time();
+ my @results = generate_report($VERSION, $end_time - $start_time,
+ $type,
+ \%{$Results{ $type }}, \%Scale_Factor);
+ if ($opt_report_file) {
+ my $ext = ".lang";
+ $ext = ".file" unless $type eq "by language";
+ next if !$found_lang and $ext eq ".lang";
+ write_file($opt_report_file . $ext, @results);
+ } else {
+ print "\n", join("\n", @results), "\n";
+ }
+ }
+ exit;
+}
+if ($opt_write_lang_def) {
+ write_lang_def($opt_write_lang_def ,
+ \%Language_by_Extension,
+ \%Language_by_Script ,
+ \%Language_by_File ,
+ \%Filters_by_Language ,
+ \%Not_Code_Extension ,
+ \%Not_Code_Filename ,
+ \%Scale_Factor ,
+ );
+ exit;
+}
+# 1}}}
+# Step 3: Create a list of files to consider. {{{1
+# a) If inputs are binary archives, first cd to a temp
+# directory, expand the archive with the user-given
+# extraction tool, then add the temp directory to
+# the list of dirs to process.
+# b) Create a list of every file that might contain source
+# code. Ignore binary files, zero-sized files, and
+# any file in a directory the user says to exclude.
+# c) Determine the language for each file in the list.
+#
+my @binary_archive = ();
+if ($opt_extract_with) {
+ my $cwd = cwd();
+#print "cwd main = [$cwd]\n";
+ my @extract_location = ();
+ foreach my $bin_file (@ARGV) {
+ my $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+ chdir $extract_dir;
+ print "Using temp dir [$extract_dir] to extract $bin_file\n"
+ if $opt_v;
+ my $bin_file_full_path = "";
+ if (File::Spec->file_name_is_absolute( $bin_file )) {
+ $bin_file_full_path = $bin_file;
+#print "bin_file_full_path (was ful) = [$bin_file_full_path]\n";
+ } else {
+ $bin_file_full_path = File::Spec->catfile( $cwd, $bin_file );
+#print "bin_file_full_path (was rel) = [$bin_file_full_path]\n";
+ }
+ (my $extract_cmd = $opt_extract_with )
+ =~ s/>FILE</$bin_file_full_path/g;
+ print $extract_cmd, "\n";
+ system $extract_cmd;
+ push @extract_location, $extract_dir;
+ chdir $cwd;
+ }
+ # It is possible that the binary archive itself contains additional
+ # files compressed the same way (true for Java .ear files). Go
+ # through all the files that were extracted, see if they are binary
+ # archives and try to extract them. Lather, rinse, repeat.
+ my $binary_archives_exist = 1;
+ my $count_binary_archives = 0;
+ my $previous_count = 0;
+ while ($binary_archives_exist) {
+ @binary_archive = ();
+ foreach my $dir (@extract_location) {
+ find(\&archive_files, $dir); # populates global @binary_archive
+ }
+ foreach my $archive (@binary_archive) {
+ (my $extract_cmd = $opt_extract_with )
+ =~ s/>FILE</$archive/g;
+ my $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+ chdir $extract_dir;
+ print $extract_cmd, "\n";
+ system $extract_cmd;
+ push @extract_location, $extract_dir;
+ unlink $archive; # otherwise will be extracting it forever
+ }
+ $count_binary_archives = scalar @binary_archive;
+ if ($count_binary_archives == $previous_count) {
+ $binary_archives_exist = 0;
+ }
+ $previous_count = $count_binary_archives;
+ }
+ chdir $cwd;
+
+ @ARGV = @extract_location;
+}
+# 1}}}
+my @Errors = ();
+my @file_list = (); # global variable updated in files()
+my %Ignored = (); # files that are not counted (language not recognized or
+ # problems reading the file)
+if ($opt_diff) {
+# Step 4: Separate code from non-code files. {{{1
+my @fh;
+my @files_for_set = ();
+# make file lists for each separate argument
+for (my $i = 0; $i < scalar @ARGV; $i++) {
+ push @fh,
+ make_file_list([ $ARGV[$i] ], \%Error_Codes, \@Errors, \%Ignored);
+ @{$files_for_set[$i]} = @file_list;
+ @file_list = ();
+}
+# 1}}}
+# Step 5: Remove duplicate files. {{{1
+#
+my %Language = ();
+my %unique_source_file = ();
+my $n_set = 0;
+foreach my $FH (@fh) { # loop over each pair of file sets
+ ++$n_set;
+ remove_duplicate_files($FH,
+ \%{$Language{$FH}} ,
+ \%{$unique_source_file{$FH}} ,
+ \%Error_Codes ,
+ \@Errors ,
+ \%Ignored );
+ printf "%2d: %8d unique file%s. \n",
+ $n_set,
+ plural_form(scalar keys %unique_source_file)
+ unless $opt_quiet;
+}
+# 1}}}
+# Step 6: Count code, comments, blank lines. {{{1
+#
+my %n_Files_Same = ();
+my %n_Files_Added = ();
+my %n_Files_Removed = ();
+my %n_Files_Changed = ();
+my %Results_by_Language = ();
+my %Results_by_File = ();
+foreach (my $F = 0; $F < scalar @fh - 1; $F++) {
+ # loop over file sets; do diff between set $F to $F+1
+
+ my $nCounted = 0;
+
+ my @changed_file_pairs = ();
+ align_by_pairs(\%{$unique_source_file{$fh[$F ]}}, # in
+ \%{$unique_source_file{$fh[$F+1]}}, # in
+ \$n_Files_Same{$fh[$F]} , # out
+ \$n_Files_Added{$fh[$F]} , # out
+ \$n_Files_Removed{$fh[$F]} , # out
+ \$n_Files_Changed{$fh[$F]} , # out
+ \@changed_file_pairs , # out
+ );
+
+ foreach my $pair (@changed_file_pairs) {
+ my $file_L = $pair->[0];
+ my $file_R = $pair->[1];
+#print "main step 6 file_L=$file_L file_R=$file_R\n";
+ ++$nCounted;
+ printf "Counting: %d\r", $nCounted
+ unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
+ next if $Ignored{$file_L};
+
+ if ($Exclude_Language{$Language{$fh[$F ]}{$file_L}} or
+ $Exclude_Language{$Language{$fh[$F+1]}{$file_R}}
+ ) {
+ $Ignored{$file_L} = "--exclude_lang=$Language{$fh[$F ]}{$file_L}";
+ $Ignored{$file_R} = "--exclude_lang=$Language{$fh[$F+1]}{$file_R}";
+ next;
+ }
+ if (!defined @{$Filters_by_Language{$Language{$fh[$F ]}{$file_L}} } or
+ !defined @{$Filters_by_Language{$Language{$fh[$F+1]}{$file_R}} }
+ ) {
+ if (($Language{$fh[$F ]}{$file_L} eq "(unknown)") or
+ ($Language{$fh[$F+1]}{$file_R} eq "(unknown)")
+ ) {
+ $Ignored{$fh[$F ]}{$file_L} = "language unknown (#1)";
+ $Ignored{$fh[$F+1]}{$file_R} = "language unknown (#1)";
+ } else {
+ $Ignored{$fh[$F ]}{$file_L} = "missing Filters_by_Language{$Language{$file_L}}";
+ $Ignored{$fh[$F+1]}{$file_R} = "missing Filters_by_Language{$Language{$file_R}}";
+ }
+ next;
+ }
+
+print "DIFF($file_L, $file_R)\n";
+ # step 1: identify comments in both files
+ chomp ( my @lines_L = read_file($file_L) );
+ my @original_minus_blanks_L
+ = rm_blanks( \@lines_L, $Language{$fh[$F]}{$file_L});
+ @lines_L = @original_minus_blanks_L;
+ @lines_L = rm_comments(\@lines_L, $Language{$fh[$F]}{$file_L}, $file_L);
+
+ chomp ( my @lines_R = read_file($file_R) );
+ my @original_minus_blanks_R
+ = rm_blanks( \@lines_R, $Language{$fh[$F+1]}{$file_R});
+ @lines_R = @original_minus_blanks_R;
+ @lines_R = rm_comments(\@lines_R, $Language{$fh[$F+1]}{$file_R}, $file_R);
+
+ my (@diff_LL, @diff_LR, %count_L);
+ file_diff(\@original_minus_blanks_L , # in
+ \@lines_L , # in
+ "comment" , # in
+ \@diff_LL, \@diff_LR, \%count_L); # out
+
+ my (@diff_RL, @diff_RR, %count_R);
+ file_diff(\@original_minus_blanks_R , # in
+ \@lines_R , # in
+ "comment" , # in
+ \@diff_RL, \@diff_RR, \%count_R); # out
+
+#use Data::Dumper;
+#print Dumper("diff_LL", \@diff_LL, "diff_LR", \@diff_LR, "count", \%count_L);
+#print Dumper("diff_RL", \@diff_RL, "diff_RR", \@diff_RR, "count", \%count_R);
+
+#v# my ($all_line_count,
+#v# $blank_count ,
+#v# $comment_count ,
+#v# ) = call_counter($file_L, $Language{$file_L});
+#v# my $code_count = $all_line_count - $blank_count - $comment_count;
+#v# if ($opt_by_file) {
+#v# $Results_by_File{$file_L}{'code' } = $code_count ;
+#v# $Results_by_File{$file_L}{'blank' } = $blank_count ;
+#v# $Results_by_File{$file_L}{'comment'} = $comment_count ;
+#v# $Results_by_File{$file_L}{'lang' } = $Language{$file_L};
+#v# $Results_by_File{$file_L}{'nFiles' } = 1;
+#v# }
+#v#
+#v# $Results_by_Language{$Language{$file_L}}{'nFiles'}++;
+#v# $Results_by_Language{$Language{$file_L}}{'code'} += $code_count ;
+#v# $Results_by_Language{$Language{$file_L}}{'blank'} += $blank_count ;
+#v# $Results_by_Language{$Language{$file_L}}{'comment'} += $comment_count;
+ }
+#v# my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
+#v# write_file($opt_ignored, @ignored_reasons ) if $opt_ignored;
+#v# write_file($opt_counted, sort keys %Language) if $opt_counted;
+}
+# 1}}}
+# Step 7: Print results. {{{1
+#
+my $end_time = time();
+printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
+ unless $opt_quiet;
+print_errors(\%Error_Codes, \@Errors) if @Errors;
+exit unless %Results_by_Language;
+
+#use YAML; print YAML::Dump(\%Results_by_Language); die;
+
+my @results = ();
+unless ($opt_by_file) {
+ @results = generate_report( $VERSION, $end_time - $start_time,
+ "by language",
+ \%Results_by_Language, \%Scale_Factor);
+ if ($opt_report_file) { write_file($opt_report_file, @results); }
+ else { print "\n", join("\n", @results), "\n"; }
+} else {
+ @results = generate_report( $VERSION, $end_time - $start_time,
+ "by file",
+ \%Results_by_File, \%Scale_Factor);
+ if ($opt_report_file) { write_file($opt_report_file, @results); }
+ else { print "\n", join("\n", @results), "\n"; }
+}
+# 1}}}
+} else {
+# Step 4: Separate code from non-code files. {{{1
+my $fh = make_file_list(\@ARGV, \%Error_Codes, \@Errors, \%Ignored);
+# make_file_list populates global variable @file_list via call to
+# File::Find's find() which in turn calls files()
+# 1}}}
+# Step 5: Remove duplicate files. {{{1
+#
+my %Language = ();
+my %unique_source_file = ();
+remove_duplicate_files($fh,
+ \%Language ,
+ \%unique_source_file ,
+ \%Error_Codes ,
+ \@Errors ,
+ \%Ignored );
+printf "%8d unique file%s. \n",
+ plural_form(scalar keys %unique_source_file)
+ unless $opt_quiet;
+# 1}}}
+# Step 6: Count code, comments, blank lines. {{{1
+#
+
+my %Results_by_Language = ();
+my %Results_by_File = ();
+my $nCounted = 0;
+foreach my $file (sort keys %unique_source_file) {
+ ++$nCounted;
+ printf "Counting: %d\r", $nCounted
+ unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
+ next if $Ignored{$file};
+ if ($Exclude_Language{$Language{$file}}) {
+ $Ignored{$file} = "--exclude_lang=$Language{$file}";
+ next;
+ }
+ if (!defined @{$Filters_by_Language{$Language{$file}} }) {
+ if ($Language{$file} eq "(unknown)") {
+ $Ignored{$file} = "language unknown (#1)";
+ } else {
+ $Ignored{$file} = "missing Filters_by_Language{$Language{$file}}";
+ }
+ next;
+ }
+
+ my ($all_line_count,
+ $blank_count ,
+ $comment_count ,
+ ) = call_counter($file, $Language{$file});
+ my $code_count = $all_line_count - $blank_count - $comment_count;
+ if ($opt_by_file) {
+ $Results_by_File{$file}{'code' } = $code_count ;
+ $Results_by_File{$file}{'blank' } = $blank_count ;
+ $Results_by_File{$file}{'comment'} = $comment_count ;
+ $Results_by_File{$file}{'lang' } = $Language{$file};
+ $Results_by_File{$file}{'nFiles' } = 1;
+ }
+
+ $Results_by_Language{$Language{$file}}{'nFiles'}++;
+ $Results_by_Language{$Language{$file}}{'code'} += $code_count ;
+ $Results_by_Language{$Language{$file}}{'blank'} += $blank_count ;
+ $Results_by_Language{$Language{$file}}{'comment'} += $comment_count;
+}
+my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
+write_file($opt_ignored, @ignored_reasons ) if $opt_ignored;
+write_file($opt_counted, sort keys %Language) if $opt_counted;
+# 1}}}
+# Step 7: Print results. {{{1
+#
+my $end_time = time();
+printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
+ unless $opt_quiet;
+print_errors(\%Error_Codes, \@Errors) if @Errors;
+exit unless %Results_by_Language;
+
+#use YAML; print YAML::Dump(\%Results_by_Language); die;
+
+my @results = ();
+unless ($opt_by_file) {
+ @results = generate_report( $VERSION, $end_time - $start_time,
+ "by language",
+ \%Results_by_Language, \%Scale_Factor);
+ if ($opt_report_file) { write_file($opt_report_file, @results); }
+ else { print "\n", join("\n", @results), "\n"; }
+} else {
+ @results = generate_report( $VERSION, $end_time - $start_time,
+ "by file",
+ \%Results_by_File, \%Scale_Factor);
+ if ($opt_report_file) { write_file($opt_report_file, @results); }
+ else { print "\n", join("\n", @results), "\n"; }
+}
+# 1}}}
+}
+
+sub combine_results { # {{{1
+ # returns 1 if the inputs are categorized by language
+ # 0 if no identifiable language was found
+ my ($ra_report_files, # in
+ $report_type , # in "by language" or "by report file"
+ $rhh_count , # out count{TYPE}{nFiles|code|blank|comment|scaled}
+ $rhaa_Filters_by_Language , # in
+ ) = @_;
+
+ my $found_language = 0;
+
+ foreach my $file (@{$ra_report_files}) {
+ my $IN = new IO::File $file, "r";
+ if (!defined $IN) {
+ warn "Unable to read $file; ignoring.\n";
+ next;
+ }
+ while (<$IN>) {
+ next if /^(http|Language|SUM|-----)/;
+ if (m{^(.*?)\s+ # language
+ (\d+)\s+ # files
+ (\d+)\s+ # blank
+ (\d+)\s+ # comments
+ (\d+)\s+ # code
+ ( # next four entries missing with -nno3
+ x\s+ # x
+ \d+\.\d+\s+ # scale
+ =\s+ # =
+ (\d+\.\d+)\s* # scaled code
+ )?
+ $}x) {
+ if ($report_type eq "by language") {
+ next unless defined %{$rhaa_Filters_by_Language->{$1}};
+ # above test necessary to avoid trying to sum reports
+ # of reports (which have no language breakdown).
+ $found_language = 1;
+ $rhh_count->{$1 }{'nFiles' } += $2;
+ $rhh_count->{$1 }{'blank' } += $3;
+ $rhh_count->{$1 }{'comment'} += $4;
+ $rhh_count->{$1 }{'code' } += $5;
+ $rhh_count->{$1 }{'scaled' } += $7 unless $opt_no3;
+ } else {
+ $rhh_count->{$file}{'nFiles' } += $2;
+ $rhh_count->{$file}{'blank' } += $3;
+ $rhh_count->{$file}{'comment'} += $4;
+ $rhh_count->{$file}{'code' } += $5;
+ $rhh_count->{$file}{'scaled' } += $7 unless $opt_no3;
+ }
+ }
+ }
+ }
+ return $found_language;
+
+} # 1}}}
+sub generate_report { # {{{1
+ # returns an array of lines containing the results
+ my ($version , # in
+ $elapsed_sec, # in
+ $report_type, # in "by language" | "by report file" | "by file"
+ $rhh_count , # in count{TYPE}{nFiles|code|blank|comment|scaled}
+ $rh_scale , # in
+ ) = @_;
+
+ my @results = ();
+
+ my $languages = ();
+
+ my $sum_files = 0;
+ my $sum_code = 0;
+ my $sum_blank = 0;
+ my $sum_comment = 0;
+ foreach my $language (keys %{$rhh_count}) {
+ $sum_files += $rhh_count->{$language}{'nFiles'} ;
+ $sum_blank += $rhh_count->{$language}{'blank'} ;
+ $sum_comment += $rhh_count->{$language}{'comment'};
+ $sum_code += $rhh_count->{$language}{'code'} ;
+ }
+ my $sum_lines = $sum_blank + $sum_comment + $sum_code;
+ $elapsed_sec = 0.5 unless $elapsed_sec;
+
+ my $spacing_1 = 13;
+ my $spacing_2 = 9;
+ my $spacing_3 = 17;
+ if ($opt_no3) {
+ $spacing_1 = 19;
+ $spacing_2 = 14;
+ $spacing_3 = 28;
+ }
+ my %Format = (
+ '1' => { 'xml' => 'name="%s" ',
+ 'txt' => '%-23s ' ,
+ },
+ '2' => { 'xml' => 'name="%s" ',
+ 'txt' => "\%-${spacing_3}s ",
+ },
+ '3' => { 'xml' => 'files_count="%d" ',
+ 'txt' => '%5d ',
+ },
+ '4' => { 'xml' => 'blank="%d" comment="%d" code="%d" ',
+ 'txt' => "\%${spacing_2}d \%${spacing_2}d \%${spacing_2}d",
+ },
+ '5' => { 'xml' => 'factor="%.2f" scaled="%.2f" ',
+ 'txt' => ' x %6.2f = %14.2f',
+ },
+ );
+ my $Style = "txt";
+ $Style = "xml" if $opt_xml ;
+ $Style = "xml" if $opt_yaml; # not a typo; just set to anything but txt
+ $Style = "xml" if $opt_csv ; # not a typo; just set to anything but txt
+
+ my $URL = "http://cloc.sourceforge.net";
+ my $hyphen_line = sprintf "%s", '-' x 79;
+ my $data_line = "";
+ my $first_column;
+ my $BY_LANGUAGE = 0;
+ my $BY_FILE = 0;
+ if ($report_type eq "by language") {
+ $first_column = "Language";
+ $BY_LANGUAGE = 1;
+ } elsif ($report_type eq "by file") {
+ $first_column = "File";
+ $BY_FILE = 1;
+ } else {
+ $first_column = "Report File";
+ }
+
+ my $header_line = sprintf "%s v %4.2f", $URL, $version;
+ $header_line .= sprintf(" T=%.1f s (%.1f files/s, %.1f lines/s)",
+ $elapsed_sec ,
+ $sum_files/$elapsed_sec,
+ $sum_lines/$elapsed_sec) unless $opt_sum_reports;
+ if ($opt_xml) {
+ push @results, "<?xml version=\"1.0\"?>";
+ push @results, "<results>";
+ push @results, "<header>$header_line</header>";
+ if ($BY_FILE) {
+ push @results, "<files>";
+ } else {
+ push @results, "<languages>";
+ }
+ } elsif ($opt_yaml) {
+ push @results, "---\n# $header_line";
+ } elsif ($opt_csv) {
+ # append the header to the end of the column headers
+ # to keep the output a bit cleaner from a spreadsheet
+ # perspective
+ } else {
+ push @results, $header_line;
+ push @results, $hyphen_line;
+ }
+
+ if ($Style eq "txt") {
+ # column headers
+ $data_line = sprintf "%-${spacing_1}s ", $first_column;
+ if ($BY_FILE) {
+ $data_line .= sprintf "%${spacing_2}s " , " " ;
+ } else {
+ $data_line .= sprintf "%${spacing_2}s " , "files";
+ }
+ $data_line .= sprintf "%${spacing_2}s %${spacing_2}s %${spacing_2}s",
+ "blank" ,
+ "comment" ,
+ "code";
+ $data_line .= sprintf " %8s %14s",
+ "scale" ,
+ "3rd gen. equiv"
+ unless $opt_no3;
+ push @results, $data_line;
+ push @results, $hyphen_line;
+ }
+ if ($opt_csv) {
+ my $header2 = " ,";
+ $header2 = " ,files" unless $BY_FILE;
+ $header2 .= ",blank,comment,code";
+ $header2 .= ",scale,3rd gen. equiv" unless $opt_no3;
+ $header2 .= ',"' . $header_line . '"';
+ push @results, $header2;
+ }
+
+ my $sum_scaled = 0;
+ foreach my $lang_or_file (sort {
+ $rhh_count->{$b}{'code'} <=>
+ $rhh_count->{$a}{'code'}
+ }
+ keys %{$rhh_count}) {
+ my ($factor, $scaled);
+ if ($BY_LANGUAGE or $BY_FILE) {
+ $factor = 1;
+ if ($BY_LANGUAGE) {
+ if (defined $rh_scale->{$lang_or_file}) {
+ $factor = $rh_scale->{$lang_or_file};
+ } else {
+ warn "No scale factor for $lang_or_file; using 1.00";
+ }
+ } else { # by individual code file
+ $factor = $rh_scale->{$rhh_count->{$lang_or_file}{'lang'}};
+ }
+ $scaled = $factor*$rhh_count->{$lang_or_file}{'code'};
+ } else {
+ if (!defined $rhh_count->{$lang_or_file}{'scaled'}) {
+ $opt_no3 = 1;
+ # If we're summing together files previously generated
+ # with --no3 then rhh_count->{$lang_or_file}{'scaled'}
+ # this variable will be undefined. That should only
+ # happen when summing together by file however.
+ } elsif ($BY_LANGUAGE) {
+ warn "Missing scaled language info for $lang_or_file\n";
+ }
+ unless ($opt_no3) {
+ $scaled = $rhh_count->{$lang_or_file}{'scaled'};
+ $factor = $scaled/$rhh_count->{$lang_or_file}{'code'};
+ }
+ }
+
+ if ($BY_FILE) {
+ $data_line = sprintf $Format{'1'}{$Style}, $lang_or_file;
+ } else {
+ $data_line = sprintf $Format{'2'}{$Style}, $lang_or_file;
+ }
+ $data_line .= sprintf $Format{3}{$Style} ,
+ $rhh_count->{$lang_or_file}{'nFiles'} unless $BY_FILE;
+ $data_line .= sprintf $Format{4}{$Style} ,
+ $rhh_count->{$lang_or_file}{'blank'} ,
+ $rhh_count->{$lang_or_file}{'comment'},
+ $rhh_count->{$lang_or_file}{'code'} ;
+ $data_line .= sprintf $Format{5}{$Style} ,
+ $factor ,
+ $scaled unless $opt_no3;
+ $sum_scaled += $scaled unless $opt_no3;
+
+ if ($opt_xml) {
+ if (defined $rhh_count->{$lang_or_file}{'lang'}) {
+ my $lang = $rhh_count->{$lang_or_file}{'lang'};
+ if (!defined $languages->{$lang}) {
+ $languages->{$lang} = $lang;
+ }
+ $data_line.=' language="' . $lang . '" ';
+ }
+ if ($BY_FILE) {
+ push @results, "<file " . $data_line . "/>";
+ } else {
+ push @results, "<language " . $data_line . "/>";
+ }
+ } elsif ($opt_yaml) {
+ push @results, $lang_or_file . ":";
+ push @results, " nFiles: " .$rhh_count->{$lang_or_file}{'nFiles'} ;
+ push @results, " blank: " .$rhh_count->{$lang_or_file}{'blank'} ;
+ push @results, " comment: ".$rhh_count->{$lang_or_file}{'comment'};
+ push @results, " code: " .$rhh_count->{$lang_or_file}{'code'}
+ unless $BY_FILE;
+ if (!$opt_no3) {
+ push @results, " scaled: " . $scaled;
+ push @results, " factor: " . $factor;
+ }
+ } elsif ($opt_csv) {
+ my $extra_3 = "";
+ $extra_3 = ",$factor,$scaled" unless $opt_no3;
+ push @results, $lang_or_file . "," .
+ $rhh_count->{$lang_or_file}{'nFiles'} . "," .
+ $rhh_count->{$lang_or_file}{'blank'} . "," .
+ $rhh_count->{$lang_or_file}{'comment'}. "," .
+ $rhh_count->{$lang_or_file}{'code'} .
+ $extra_3;
+ } else {
+ push @results, $data_line;
+ }
+ }
+ my $avg_scale = 1; # weighted average of scale factors
+ $avg_scale = sprintf("%.2f", $sum_scaled / $sum_code)
+ if $sum_code and !$opt_no3;
+
+ if ($opt_xml) {
+ $data_line = "";
+ if (!$BY_FILE) {
+ $data_line .= sprintf "sum_files=\"%d\" ", $sum_files;
+ }
+ $data_line .= sprintf $Format{'4'}{$Style},
+ $sum_blank ,
+ $sum_comment ,
+ $sum_code ;
+ $data_line .= sprintf $Format{'5'}{$Style},
+ $avg_scale ,
+ $sum_scaled unless $opt_no3;
+ push @results, "<total " . $data_line . "/>";
+
+ if ($BY_FILE) {
+ push @results, "</files>";
+ } else {
+ foreach my $language (keys %{$languages}) {
+ push @results, '<language name="' . $language . '"/>';
+ }
+ push @results, "</languages>";
+ }
+
+ push @results, "</results>";
+ } elsif ($opt_yaml) {
+ push @results, "SUM:";
+ push @results, " blank: " . $sum_blank ;
+ push @results, " code: " . $sum_code ;
+ push @results, " comment: ". $sum_comment;
+ push @results, " nFiles: " . $sum_files unless $BY_FILE;
+ if (!$opt_no3) {
+ push @results, " scaled: " . $sum_scaled;
+ push @results, " factor: " . $avg_scale ;
+ }
+ } elsif ($opt_csv) {
+ # do nothing
+ } else {
+
+ if ($BY_FILE) {
+ $data_line = sprintf "%-23s ", "SUM:" ;
+ } else {
+ $data_line = sprintf "%-${spacing_1}s ", "SUM:" ;
+ $data_line .= sprintf "%${spacing_2}d ", $sum_files;
+ }
+ $data_line .= sprintf $Format{'4'}{$Style},
+ $sum_blank ,
+ $sum_comment ,
+ $sum_code ;
+ $data_line .= sprintf $Format{'5'}{$Style},
+ $avg_scale ,
+ $sum_scaled unless $opt_no3;
+ push @results, $hyphen_line if $sum_files > 1;
+ push @results, $data_line if $sum_files > 1;
+ push @results, $hyphen_line;
+ }
+ return @results;
+} # 1}}}
+sub print_errors { # {{{1
+ my ($rh_Error_Codes, # in
+ $raa_errors , # in
+ ) = @_;
+
+ my %error_string = reverse(%{$rh_Error_Codes});
+ my $nErrors = scalar @{$raa_errors};
+ printf "\n%d error%s:\n", plural_form(scalar @Errors);
+ for (my $i = 0; $i < $nErrors; $i++) {
+ printf "%s: %s\n",
+ $error_string{ $raa_errors->[$i][0] },
+ $raa_errors->[$i][1] ;
+ }
+ print "\n";
+
+} # 1}}}
+sub write_lang_def { # {{{1
+ my ($file ,
+ $rh_Language_by_Extension , # in
+ $rh_Language_by_Script , # in
+ $rh_Language_by_File , # in
+ $rhaa_Filters_by_Language , # in
+ $rh_Not_Code_Extension , # in
+ $rh_Not_Code_Filename , # in
+ $rh_Scale_Factor , # in
+ ) = @_;
+
+ my $OUT = new IO::File $file, "w";
+ die "Unable to write to $file\n" unless defined $OUT;
+
+ foreach my $language (sort keys %{$rhaa_Filters_by_Language}) {
+ next if $language eq "MATLAB/Objective C/MUMPS";
+ printf $OUT "%s\n", $language;
+ foreach my $filter (@{$rhaa_Filters_by_Language->{$language}}) {
+ printf $OUT " filter %s", $filter->[0];
+ printf $OUT " %s", $filter->[1] if defined $filter->[1];
+ print $OUT "\n";
+ }
+ foreach my $ext (sort keys %{$rh_Language_by_Extension}) {
+ if ($language eq $rh_Language_by_Extension->{$ext}) {
+ printf $OUT " extension %s\n", $ext;
+ }
+ }
+ foreach my $filename (sort keys %{$rh_Language_by_File}) {
+ if ($language eq $rh_Language_by_File->{$filename}) {
+ printf $OUT " filename %s\n", $filename;
+ }
+ }
+ foreach my $script_exe (sort keys %{$rh_Language_by_Script}) {
+ if ($language eq $rh_Language_by_Script->{$script_exe}) {
+ printf $OUT " script_exe %s\n", $script_exe;
+ }
+ }
+ printf $OUT " 3rd_gen_scale %.2f\n", $rh_Scale_Factor->{$language};
+ }
+
+ $OUT->close;
+} # 1}}}
+sub read_lang_def { # {{{1
+ my ($file ,
+ $rh_Language_by_Extension , # out
+ $rh_Language_by_Script , # out
+ $rh_Language_by_File , # out
+ $rhaa_Filters_by_Language , # out
+ $rh_Not_Code_Extension , # out
+ $rh_Not_Code_Filename , # out
+ $rh_Scale_Factor , # out
+ ) = @_;
+
+ my $IN = new IO::File $file, "r";
+ die "Unable to read $file.\n" unless defined $IN;
+
+ my $language = "";
+ while (<$IN>) {
+ next if /^\s*#/ or /^\s*$/;
+
+ if (/^(\w+.*?)\s*$/) {
+ $language = $1;
+ next;
+ }
+ die "Missing computer language name, line $. of $file\n"
+ unless $language;
+
+ if (/^ filter\s+(\w+)\s*$/) {
+ push @{$rhaa_Filters_by_Language->{$language}}, [ $1 ]
+
+ } elsif (/^ filter\s+(\w+)\s+(.*?)\s*$/) {
+ push @{$rhaa_Filters_by_Language->{$language}}, [ $1 , $2 ]
+
+ } elsif (/^ extension\s+(\S+)\s*$/) {
+ if (defined $rh_Language_by_Extension->{$1}) {
+ die "File extension collision: $1 ",
+ "maps to languages '$rh_Language_by_Extension->{$1}' ",
+ "and '$language'\n" ,
+ "Edit $file and remove $1 from one of these two ",
+ "language definitions.\n";
+ }
+ $rh_Language_by_Extension->{$1} = $language;
+
+ } elsif (/^ filename\s+(\S+)\s*$/) {
+ $rh_Language_by_File->{$1} = $language;
+
+ } elsif (/^ script_exe\s+(\S+)\s*$/) {
+ $rh_Language_by_Script->{$1} = $language;
+
+ } elsif (/^ 3rd_gen_scale\s+(\S+)\s*$/) {
+ $rh_Scale_Factor->{$language} = $1;
+
+ } else {
+ die "Unexpected data line $. of $file:\n$_\n";
+ }
+
+ }
+ $IN->close;
+} # 1}}}
+sub print_extension_info { # {{{1
+ my ($extension,) = @_;
+ if ($extension) { # show information on this extension
+ foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+ # Language_by_Extension{f} = 'Fortran 77'
+ printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext}
+ if $ext =~ m{$extension}i;
+ }
+ } else { # show information on all extensions
+ foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+ # Language_by_Extension{f} = 'Fortran 77'
+ printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext};
+ }
+ }
+} # 1}}}
+sub print_language_info { # {{{1
+ my ($language,) = @_;
+ my %extensions = (); # the subset matched by the given $language value
+ if ($language) { # show information on this language
+ foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+ # Language_by_Extension{f} = 'Fortran 77'
+ push @{$extensions{$Language_by_Extension{$ext}} }, $ext
+ if $Language_by_Extension{$ext} =~ m{$language}i;
+ }
+ } else { # show information on all languages
+ foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
+ # Language_by_Extension{f} = 'Fortran 77'
+ push @{$extensions{$Language_by_Extension{$ext}} }, $ext
+ }
+ }
+
+ # add exceptions (one file extension mapping to multiple languages)
+ if (!$language or
+ $language =~ /^(Objective C|MATLAB|MUMPS)$/i) {
+ push @{$extensions{'Objective C'}}, "m";
+ push @{$extensions{'MATLAB'}} , "m";
+ push @{$extensions{'MUMPS'}} , "m";
+ delete $extensions{'MATLAB/Objective C/MUMPS'};
+ }
+
+ if (%extensions) {
+ foreach my $lang (sort {lc $a cmp lc $b } keys %extensions) {
+ printf "%-26s (%s)\n", $lang, join(", ", @{$extensions{$lang}});
+ }
+ }
+} # 1}}}
+sub make_file_list { # {{{1
+ my ($ra_arg_list, # in file and/or directory names to examine
+ $rh_Err , # in hash of error codes
+ $raa_errors , # out errors encountered
+ $rh_ignored , # out files not recognized as computer languages
+ ) = @_;
+
+ my ($fh, $filename);
+ if ($opt_categorized) {
+ $filename = $opt_categorized;
+ $fh = new IO::File $filename, "+>"; # open for read/write
+ die "Unable to write to $filename: $!\n" unless defined $fh;
+ } elsif ($opt_sdir) {
+ # write to the user-defined scratch directory
+ $filename = $opt_sdir . '/cloc_file_list.txt';
+ $fh = new IO::File $filename, "+>"; # open for read/write
+ die "Unable to write to $filename: $!\n" unless defined $fh;
+ } else {
+ # let File::Temp create a suitable temporary file
+ ($fh, $filename) = tempfile(UNLINK => 1); # delete file on exit
+ print "Using temp file list [$filename]\n" if $opt_v;
+ }
+
+ my @dir_list = ();
+ foreach my $file_or_dir (@{$ra_arg_list}) {
+#print "make_file_list file_or_dir=$file_or_dir\n";
+ my $size_in_bytes = 0;
+ if (!-r $file_or_dir) {
+ push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file_or_dir];
+ next;
+ }
+ if (is_file($file_or_dir)) {
+ if (!(-s $file_or_dir)) { # 0 sized file, named pipe, socket
+ $rh_ignored->{$file_or_dir} = 'zero sized file';
+ next;
+ } elsif (-B $file_or_dir) { # avoid binary files
+ if ($opt_unicode) {
+ # only ignore if not a Unicode file w/trivial
+ # ASCII transliteration
+ if (!unicode_file($file_or_dir)) {
+ $rh_ignored->{$file_or_dir} = 'binary file';
+ next;
+ }
+ } else {
+ $rh_ignored->{$file_or_dir} = 'binary file';
+ next;
+ }
+ }
+ push @file_list, "$file_or_dir";
+ } elsif (is_dir ($file_or_dir)) {
+ push @dir_list, $file_or_dir;
+ } else {
+ push @{$raa_errors}, [$rh_Err->{'Neither file nor directory'} , $file_or_dir];
+ $rh_ignored->{$file_or_dir} = 'not file, not directory';
+ }
+ }
+ foreach my $dir (@dir_list) {
+#print "make_file_list dir=$dir\n";
+ find(\&files, $dir); # populates global variable @file_list
+ }
+ $nFiles_Found = scalar @file_list;
+ printf "%8d text file%s.\n", plural_form($nFiles_Found) unless $opt_quiet;
+ write_file($opt_found, sort @file_list) if $opt_found;
+
+ my $nFiles_Categorized = 0;
+ foreach my $file (@file_list) {
+ printf "classifying $file\n" if $opt_v > 2;
+
+ my $basename = basename $file;
+ if ($Not_Code_Filename{$basename}) {
+ $rh_ignored->{$file} = "listed in " . '$' .
+ "Not_Code_Filename{$basename}";
+ next;
+ } elsif ($basename =~ m{~$}) {
+ $rh_ignored->{$file} = "temporary editor file";
+ next;
+ }
+
+ my $size_in_bytes = (stat $file)[7];
+ my $language = "";
+ if ($All_One_Language) {
+ # user over-rode auto-language detection by using
+ # --force-lang with just a language name (no extension)
+ $language = $All_One_Language;
+ } else {
+ $language = classify_file($file ,
+ $rh_Err ,
+ $raa_errors,
+ $rh_ignored);
+ }
+die "make_file_list($file) undef size" unless defined $size_in_bytes;
+die "make_file_list($file) undef lang" unless defined $language;
+ printf $fh "%d,%s,%s\n", $size_in_bytes, $language, $file;
+ ++$nFiles_Categorized;
+ #printf "classified %d files\n", $nFiles_Categorized
+ # unless (!$opt_progress_rate or
+ # ($nFiles_Categorized % $opt_progress_rate));
+ }
+ printf "classified %d files\n", $nFiles_Categorized
+ if !$opt_quiet and $nFiles_Categorized > 1;
+
+ return $fh; # handle to the file containing the list of files to process
+} # 1}}}
+sub remove_duplicate_files { # {{{1
+ my ($fh , # in
+ $rh_Language , # out
+ $rh_unique_source_file, # out
+ $rh_Err , # in
+ $raa_errors , # out errors encountered
+ $rh_ignored , # out
+ ) = @_;
+
+ # Check for duplicate files by comparing file sizes.
+ # Where files are equally sized, compare their MD5 checksums.
+
+ my $n = 0;
+ my %files_by_size = (); # files_by_size{ # bytes } = [ list of files ]
+ seek($fh, 0, 0); # rewind to beginning of the temp file
+ while (<$fh>) {
+ ++$n;
+ my ($size_in_bytes, $language, $file) = split(/,/, $_, 3);
+ chomp($file);
+ $rh_Language->{$file} = $language;
+ push @{$files_by_size{$size_in_bytes}}, $file;
+ }
+ if ($opt_progress_rate and ($n > $opt_progress_rate)) {
+ printf "Duplicate file check %d files (%d known unique)\r",
+ $n, scalar keys %files_by_size;
+ }
+ $n = 0;
+ foreach my $bytes (sort {$a <=> $b} keys %files_by_size) {
+ ++$n;
+ printf "Unique: %8d files \r",
+ $n unless (!$opt_progress_rate or ($n % $opt_progress_rate));
+ $rh_unique_source_file->{$files_by_size{$bytes}[0]} = 1;
+ next unless scalar @{$files_by_size{$bytes}} > 1;
+ foreach my $F (different_files(\@{$files_by_size{$bytes}},
+ $rh_Err ,
+ $raa_errors ,
+ $rh_ignored ) ) {
+ $rh_unique_source_file->{$F} = 1;
+ }
+ }
+} # 1}}}
+sub files { # {{{1
+ # invoked by File::Find's find() Populates global variable @file_list
+ if ($opt_exclude_dir) {
+ my $return = 0;
+ foreach my $skip_dir (keys %Exclude_Dir) {
+ if ($File::Find::dir =~ m{/$skip_dir(/|$)} ) {
+ $Ignored{$File::Find::name} = "--exclude_dir=$skip_dir";
+ $return = 1;
+ last;
+ }
+ }
+ return if $return;
+ }
+ my $nBytes = -s $_ ;
+ if (!$nBytes and $opt_v > 5) {
+ printf "files(%s) zero size\n", $File::Find::name;
+ }
+ return unless $nBytes ; # attempting other tests w/pipe or socket will hang
+ my $is_dir = is_dir($_);
+ my $is_bin = -B $_ ;
+ printf "files(%s) size=%d is_dir=%d -B=%d\n",
+ $File::Find::name, $nBytes, $is_dir, $is_bin if $opt_v > 5;
+ $is_bin = 0 if $opt_unicode and unicode_file($_);
+ return if $is_dir or $is_bin;
+ ++$nFiles_Found;
+ printf "%8d files\r", $nFiles_Found
+ unless (!$opt_progress_rate or ($nFiles_Found % $opt_progress_rate));
+ push @file_list, $File::Find::name;
+} # 1}}}
+sub archive_files { # {{{1
+ # invoked by File::Find's find() Populates global variable @binary_archive
+ foreach my $ext (keys %Known_Binary_Archives) {
+ push @binary_archive, $File::Find::name
+ if $File::Find::name =~ m{$ext$};
+ }
+} # 1}}}
+sub is_file { # {{{1
+ # portable method to test if item is a file
+ # (-f doesn't work in ActiveState Perl on Windows)
+ my $item = shift @_;
+
+ if ($ON_WINDOWS) {
+ my $mode = (stat $item)[2];
+ $mode = 0 unless $mode;
+ if ($mode & 0100000) { return 1; }
+ else { return 0; }
+ } else {
+ return (-f $item); # works on Unix, Linux, CygWin, z/OS
+ }
+} # 1}}}
+sub is_dir { # {{{1
+ # portable method to test if item is a directory
+ # (-d doesn't work in ActiveState Perl on Windows)
+ my $item = shift @_;
+
+ if ($ON_WINDOWS) {
+ my $mode = (stat $item)[2];
+ $mode = 0 unless $mode;
+ if ($mode & 0040000) { return 1; }
+ else { return 0; }
+ } else {
+ return (-d $item); # works on Unix, Linux, CygWin, z/OS
+ }
+} # 1}}}
+sub classify_file { # {{{1
+ my ($full_file , # in
+ $rh_Err , # in hash of error codes
+ $raa_errors , # out
+ $rh_ignored , # out
+ ) = @_;
+
+ print "-> classify_file($full_file)\n" if $opt_v > 2;
+ my $language = "(unknown)";
+
+ my $look_at_first_line = 0;
+ my $file = basename $full_file;
+ return $language if $Not_Code_Filename{$file}; # (unknown)
+ return $language if $file =~ m{~$}; # a temp edit file (unknown)
+
+ if ($file =~ /\.(\w+)$/) { # has an extension
+ print "$full_file extension=[$1]\n" if $opt_v > 2;
+ my $extension = $1;
+ if ($Not_Code_Extension{$extension} and
+ !$Forced_Extension{$extension}) {
+ # If .1 (for example) is an extention that would ordinarily be
+ # ignored but the user has insisted this be counted with the
+ # --force-lang option, then go ahead and count it.
+ $rh_ignored->{$full_file} =
+ 'listed in $Not_Code_Extension{' . $extension . '}';
+ return $language;
+ }
+ if (defined $Language_by_Extension{$extension}) {
+ if ($Language_by_Extension{$extension} eq
+ 'MATLAB/Objective C/MUMPS') {
+ my $lang_M_or_O = "";
+ matlab_or_objective_C($full_file ,
+ $rh_Err ,
+ $raa_errors,
+ \$lang_M_or_O);
+ if ($lang_M_or_O) {
+ return $lang_M_or_O;
+ } else { # an error happened in matlab_or_objective_C()
+ $rh_ignored->{$full_file} =
+ 'failure in matlab_or_objective_C()';
+ return $language; # (unknown)
+ }
+ } else {
+ return $Language_by_Extension{$extension};
+ }
+ } else { # has an unmapped file extension
+ $look_at_first_line = 1;
+ }
+ } elsif (defined $Language_by_File{lc $file}) {
+ return $Language_by_File{lc $file};
+ } else { # no file extension
+ $look_at_first_line = 1;
+ }
+
+ if ($look_at_first_line) {
+ # maybe it is a shell/Perl/Python/Ruby/etc script that
+ # starts with pound bang:
+ # #!/usr/bin/perl
+ # #!/usr/bin/env perl
+ my $script_language = peek_at_first_line($full_file ,
+ $rh_Err ,
+ $raa_errors);
+ if (!$script_language) {
+ $rh_ignored->{$full_file} = "language unknown (#2)";
+ # returns (unknown)
+ }
+ if (defined $Language_by_Script{$script_language}) {
+ if (defined $Filters_by_Language{
+ $Language_by_Script{$script_language}}) {
+ $language = $Language_by_Script{$script_language};
+ } else {
+ $rh_ignored->{$full_file} =
+ "undefined: Filters_by_Language{" .
+ $Language_by_Script{$script_language} .
+ "} for scripting language $script_language";
+ # returns (unknown)
+ }
+ } else {
+ $rh_ignored->{$full_file} = "language unknown (#3)";
+ # returns (unknown)
+ }
+ }
+ print "<- classify_file($full_file)\n" if $opt_v > 2;
+ return $language;
+} # 1}}}
+sub peek_at_first_line { # {{{1
+ my ($file , # in
+ $rh_Err , # in hash of error codes
+ $raa_errors , # out
+ ) = @_;
+
+ print "-> peek_at_first_line($file)\n" if $opt_v > 2;
+
+ my $script_language = "";
+ if (!-r $file) {
+ push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+ return $script_language;
+ }
+ my $IN = new IO::File $file, "r";
+ if (!defined $IN) {
+ push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+ print "<- peek_at_first_line($file)\n" if $opt_v > 2;
+ return $script_language;
+ }
+ chomp(my $first_line = <$IN>);
+ if (defined $first_line) {
+#print "peek_at_first_line of [$file] first_line=[$first_line]\n";
+ if ($first_line =~ /^#\!\s*(\S.*?)$/) {
+#print "peek_at_first_line 1=[$1]\n";
+ my @pound_bang = split(' ', $1);
+#print "peek_at_first_line basename 0=[", basename($pound_bang[0]), "]\n";
+ if (basename($pound_bang[0]) eq "env" and
+ scalar @pound_bang > 1) {
+ $script_language = $pound_bang[1];
+#print "peek_at_first_line pound_bang A $pound_bang[1]\n";
+ } else {
+ $script_language = basename $pound_bang[0];
+#print "peek_at_first_line pound_bang B $script_language\n";
+ }
+ }
+ }
+ $IN->close;
+ print "<- peek_at_first_line($file)\n" if $opt_v > 2;
+ return $script_language;
+} # 1}}}
+sub different_files { # {{{1
+ # See which of the given files are unique by computing each file's MD5
+ # sum. Return the subset of files which are unique.
+ my ($ra_files , # in
+ $rh_Err , # in
+ $raa_errors , # out
+ $rh_ignored , # out
+ ) = @_;
+
+ print "-> different_files(@{$ra_files})\n" if $opt_v > 2;
+ my %file_hash = (); # file_hash{ md5 hash } = file name
+ foreach my $F (@{$ra_files}) {
+ next if is_dir($F); # needed for Windows
+ my $IN = new IO::File $F, "r";
+ if (!defined $IN) {
+ push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $F];
+ $rh_ignored->{$F} = 'cannot read';
+ } else {
+ if ($HAVE_Digest_MD5) {
+ binmode $IN;
+ $file_hash{ Digest::MD5->new->addfile($IN)->hexdigest } = $F;
+ } else {
+ # all files treated unique
+ $file_hash{ $F } = $F;
+ }
+ $IN->close;
+ }
+ }
+ my @unique = values %file_hash;
+ print "<- different_files(@unique)\n" if $opt_v > 2;
+ return @unique;
+} # 1}}}
+sub call_counter { # {{{1
+ my ($file , # in
+ $language, # in
+ ) = @_;
+
+ # Logic: pass the file through the following filters:
+ # 1. remove blank lines
+ # 2. remove comments using each filter defined for this language
+ # (example: SQL has two, remove_starts_with(--) and
+ # remove_c_comments() )
+ # 3. compute comment lines as
+ # total lines - blank lines - lines left over after all
+ # comment filters have been applied
+
+ print "-> call_counter($file, $language)\n" if $opt_v > 2;
+#print "call_counter: ", Dumper(@routines), "\n";
+
+ my @lines = ();
+ my $ascii = "";
+ if (-B $file and $opt_unicode) {
+ # was binary so must be unicode
+
+ $/ = undef;
+ my $IN = new IO::File $file, "r";
+ my $bin_text = <$IN>;
+ $IN->close;
+ $/ = "\n";
+
+ $ascii = unicode_to_ascii( $bin_text );
+ @lines = split("\n", $ascii );
+ foreach (@lines) { $_ = "$_\n"; }
+
+ } else {
+ # regular text file
+ @lines = read_file($file);
+ $ascii = join('', @lines);
+ }
+
+ my @original_lines = @lines;
+ my $total_lines = scalar @lines;
+
+ print_lines($file, "Original file:", \@lines) if $opt_print_filter_stages;
+ @lines = rm_blanks(\@lines, $language); # remove blank lines
+ my $blank_lines = $total_lines - scalar @lines;
+ print_lines($file, "Blank lines removed:", \@lines)
+ if $opt_print_filter_stages;
+
+ @lines = rm_comments(\@lines, $language, $file);
+
+ my $comment_lines = $total_lines - $blank_lines - scalar @lines;
+ if ($opt_strip_comments) {
+ my $stripped_file = basename $file . ".$opt_strip_comments";
+ write_file($stripped_file, @lines);
+ }
+ if ($opt_html) {
+ chomp(@original_lines); # includes blank lines, comments
+ chomp(@lines); # no blank lines, no comments
+
+ my (@diff_L, @diff_R, %count);
+
+ # remove blank lines to get better quality diffs; count
+ # blank lines separately
+ my @original_lines_minus_white = ();
+ # however must keep track of how many blank lines were removed and
+ # where they were removed so that the HTML display can include it
+ my %blank_line = ();
+ my $insert_line = 0;
+ foreach (@original_lines) {
+ if (/^\s*$/) {
+ ++$count{blank}{same};
+ ++$blank_line{ $insert_line };
+ } else {
+ ++$insert_line;
+ push @original_lines_minus_white, $_;
+ }
+ }
+
+ file_diff(\@original_lines_minus_white , # in
+ \@lines , # in
+ "comment" , # in
+ \@diff_L, \@diff_R, \%count); # out
+ write_comments_to_html($file, \@diff_L, \@diff_R, \%blank_line);
+#print Dumper("count", \%count);
+ }
+
+ print "<- call_counter($total_lines, $blank_lines, $comment_lines)\n"
+ if $opt_v > 2;
+ return ($total_lines, $blank_lines, $comment_lines);
+} # 1}}}
+sub write_file { # {{{1
+ my ($file , # in
+ @lines , # in
+ ) = @_;
+
+ print "-> write_file($file)\n" if $opt_v > 2;
+
+ # Create the destination directory if it doesn't already exist.
+ my $abs_file_path = File::Spec->rel2abs( $file );
+ my ($volume, $directories, $filename) = File::Spec->splitpath( $abs_file_path );
+ mkpath($volume . $directories, 1, 0777);
+
+ my $OUT = new IO::File $file, "w";
+ if (defined $OUT) {
+ chomp(@lines);
+ print $OUT join("\n", @lines), "\n";
+ $OUT->close;
+ } else {
+ warn "Unable to write to $file\n";
+ }
+ print "Wrote $file\n";
+
+ print "<- write_file\n" if $opt_v > 2;
+} # 1}}}
+sub read_file { # {{{1
+ my ($file, ) = @_;
+
+ print "-> read_file($file)\n" if $opt_v > 2;
+ my @lines = ();
+ my $IN = new IO::File $file, "r";
+ if (defined $IN) {
+ @lines = <$IN>;
+ $IN->close;
+ # Some files don't end with a new line. Force this:
+ $lines[$#lines] .= "\n" unless $lines[$#lines] =~ m/\n$/;
+ } else {
+ warn "Unable to read $file\n";
+ }
+ print "<- read_file\n" if $opt_v > 2;
+ return @lines;
+} # 1}}}
+sub rm_blanks { # {{{1
+ my ($ra_in, $language) = @_;
+
+ my @out = ();
+ if ($language eq "COBOL") {
+ @out = remove_cobol_blanks($ra_in);
+ } else {
+ @out = remove_matches($ra_in, '^\s*$'); # removes blank lines
+ }
+ return @out;
+} # 1}}}
+sub rm_comments { # {{{1
+ my ($ra_lines , # in, must be free of blank lines
+ $language , # in
+ $file , # in (some language counters, eg Haskell, need
+ # access to the original file)
+ ) = @_;
+ my @routines = @{$Filters_by_Language{$language}};
+ my @lines = @{$ra_lines};
+ my @original_lines = @{$ra_lines};
+
+ foreach my $call_string (@routines) {
+ my $subroutine = $call_string->[0];
+ if (! defined &{$subroutine}) {
+ warn "rm_comments undefined subroutine $subroutine for $file\n";
+ next;
+ }
+ print "rm_comments file=$file sub=$subroutine\n" if $opt_v > 1;
+ my @args = @{$call_string};
+ shift @args; # drop the subroutine name
+ if (@args and $args[0] eq '>filename<') {
+ shift @args;
+ unshift @args, $file;
+ }
+
+ no strict 'refs';
+ @lines = &{$subroutine}(\@lines, @args); # apply filter...
+
+ print_lines($file, "After $subroutine(@args)", \@lines)
+ if $opt_print_filter_stages;
+ @lines = remove_matches(\@lines, '^\s*$'); # then remove blank lines
+
+ print_lines($file, "post $subroutine(@args) blank cleanup:", \@lines)
+ if $opt_print_filter_stages;
+ }
+ # Exception for scripting languages: treat the first #! line as code.
+ # Will need to add it back in if it was removed earlier.
+ if ($Script_Language{$language} and
+ $original_lines[0] =~ /^#!/ and
+ $lines[0] ne $original_lines[0]) {
+ unshift @lines, $original_lines[0]; # add the first line back
+ }
+ return @lines;
+} # 1}}}
+sub remove_f77_comments { # {{{1
+ my ($ra_lines, ) = @_;
+ print "-> remove_f77_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ foreach (@{$ra_lines}) {
+ next if m{^[*cC]};
+ push @save_lines, $_;
+ }
+
+ print "<- remove_f77_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_f90_comments { # {{{1
+ # derived from SLOCCount
+ my ($ra_lines, ) = @_;
+ print "-> remove_f90_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ foreach (@{$ra_lines}) {
+ # a comment is m/^\s*!/
+ # an empty line is m/^\s*$/
+ # a HPF statement is m/^\s*!hpf\$/i
+ # an Open MP statement is m/^\s*!omp\$/i
+ if (! m/^(\s*!|\s*$)/ || m/^\s*!(hpf|omp)\$/i) {
+ push @save_lines, $_;
+ }
+ }
+
+ print "<- remove_f90_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_matches { # {{{1
+ my ($ra_lines, # in
+ $pattern , # in Perl regular expression (case insensitive)
+ ) = @_;
+ print "-> remove_matches(pattern=$pattern)\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ foreach (@{$ra_lines}) {
+#chomp; print "remove_matches [$pattern] [$_]\n";
+ next if m{$pattern}i;
+ push @save_lines, $_;
+ }
+
+ print "<- remove_matches\n" if $opt_v > 2;
+#print "remove_matches returning\n ", join("\n ", @save_lines), "\n";
+ return @save_lines;
+} # 1}}}
+sub remove_above { # {{{1
+ my ($ra_lines, $marker, ) = @_;
+ print "-> remove_above(marker=$marker)\n" if $opt_v > 2;
+
+ # Make two passes through the code:
+ # 1. check if the marker exists
+ # 2. remove anything above the marker if it exists,
+ # do nothing if the marker does not exist
+
+ # Pass 1
+ my $found_marker = 0;
+ for (my $line_number = 1;
+ $line_number <= scalar @{$ra_lines};
+ $line_number++) {
+ if ($ra_lines->[$line_number-1] =~ m{$marker}) {
+ $found_marker = $line_number;
+ last;
+ }
+ }
+
+ # Pass 2 only if needed
+ my @save_lines = ();
+ if ($found_marker) {
+ my $n = 1;
+ foreach (@{$ra_lines}) {
+ push @save_lines, $_
+ if $n >= $found_marker;
+ ++$n;
+ }
+ } else { # marker wasn't found; save all lines
+ foreach (@{$ra_lines}) {
+ push @save_lines, $_;
+ }
+ }
+
+ print "<- remove_above\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_below { # {{{1
+ my ($ra_lines, $marker, ) = @_;
+ print "-> remove_below(marker=$marker)\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ foreach (@{$ra_lines}) {
+ last if m{$marker};
+ push @save_lines, $_;
+ }
+
+ print "<- remove_below\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_between { # {{{1
+ my ($ra_lines, $marker, ) = @_;
+ # $marker must contain one of the balanced pairs understood
+ # by Regexp::Common::balanced, namely
+ # '{}' '()' '[]' or '<>'
+
+ print "-> remove_between(marker=$marker)\n" if $opt_v > 2;
+ my %acceptable = ('{}'=>1, '()'=>1, '[]'=>1, '<>'=>1, );
+ die "remove_between: invalid delimiter '$marker'\n",
+ "the delimiter must be one of these four pairs:\n",
+ "{} () [] <>\n" unless
+ $acceptable{$marker};
+
+ Install_Regexp_Common() unless $HAVE_Rexexp_Common;
+
+ my $all_lines = join("", @{$ra_lines});
+
+ no strict 'vars';
+ # otherwise get:
+ # Global symbol "%RE" requires explicit package name at cloc line xx.
+ if ($all_lines =~ m/$RE{balanced}{-parens => $marker}/) {
+ no warnings;
+ $all_lines =~ s/$1//g;
+ }
+
+ print "<- remove_between\n" if $opt_v > 2;
+ return split("\n", $all_lines);
+} # 1}}}
+sub remove_cobol_blanks { # {{{1
+ # subroutines derived from SLOCCount
+ my ($ra_lines, ) = @_;
+
+ my $free_format = 0; # Support "free format" source code.
+ my @save_lines = ();
+
+ foreach (@{$ra_lines}) {
+ next if m/^\s*$/;
+ my $line = expand($_); # convert tabs to equivalent spaces
+ $free_format = 1 if $line =~ m/^......\$.*SET.*SOURCEFORMAT.*FREE/i;
+ if ($free_format) {
+ push @save_lines, $_;
+ } else {
+ push @save_lines, $_ unless m/^\d{6}\s*$/ or
+ ($line =~ m/^\d{6}\s{66}/);
+ }
+ }
+ return @save_lines;
+} # 1}}}
+sub remove_cobol_comments { # {{{1
+ # subroutines derived from SLOCCount
+ my ($ra_lines, ) = @_;
+
+ my $free_format = 0; # Support "free format" source code.
+ my @save_lines = ();
+
+ foreach (@{$ra_lines}) {
+ if (m/^......\$.*SET.*SOURCEFORMAT.*FREE/i) {$free_format = 1;}
+ if ($free_format) {
+ push @save_lines, $_ unless m{^\s*\*};
+ } else {
+ push @save_lines, $_ unless m{^......\*} or m{^\*};
+ }
+ }
+ return @save_lines;
+} # 1}}}
+sub remove_jcl_comments { # {{{1
+ my ($ra_lines, ) = @_;
+
+ print "-> remove_jcl_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ my $in_comment = 0;
+ foreach (@{$ra_lines}) {
+ next if /^\s*$/;
+ next if m{^\s*//\*};
+ last if m{^\s*//\s*$};
+ push @save_lines, $_;
+ }
+
+ print "<- remove_jcl_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_jsp_comments { # {{{1
+ # JSP comment is <%-- body of comment --%>
+ my ($ra_lines, ) = @_;
+
+ print "-> remove_jsp_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ my $in_comment = 0;
+ foreach (@{$ra_lines}) {
+
+ next if /^\s*$/;
+ s/<\%\-\-.*?\-\-\%>//g; # strip one-line comments
+ next if /^\s*$/;
+ if ($in_comment) {
+ if (/\-\-\%>/) {
+ s/^.*?\-\-\%>//;
+ $in_comment = 0;
+ }
+ }
+ next if /^\s*$/;
+ $in_comment = 1 if /^(.*?)<\%\-\-/;
+ next if defined $1 and $1 =~ /^\s*$/;
+ next if ($in_comment);
+ push @save_lines, $_;
+ }
+
+ print "<- remove_jsp_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub remove_html_comments { # {{{1
+ # HTML comment is <!-- body of comment -->
+ # Need to use my own routine until the HTML comment regex in
+ # the Regexp::Common module can handle <!-- -- -->
+ my ($ra_lines, ) = @_;
+
+ print "-> remove_html_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ my $in_comment = 0;
+ foreach (@{$ra_lines}) {
+
+ next if /^\s*$/;
+ s/<!\-\-.*?\-\->//g; # strip one-line comments
+ next if /^\s*$/;
+ if ($in_comment) {
+ if (/\-\->/) {
+ s/^.*?\-\->//;
+ $in_comment = 0;
+ }
+ }
+ next if /^\s*$/;
+ $in_comment = 1 if /^(.*?)<!\-\-/;
+ next if defined $1 and $1 =~ /^\s*$/;
+ next if ($in_comment);
+ push @save_lines, $_;
+ }
+
+ print "<- remove_html_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub determine_lit_type { # {{{1
+ my ($file) = @_;
+
+ open (FILE, $file);
+ while (<FILE>) {
+ if (m/^\\begin{code}/) { close FILE; return 2; }
+ if (m/^>\s/) { close FILE; return 1; }
+ }
+
+ return 0;
+} # 1}}}
+sub remove_haskell_comments { # {{{1
+ # Bulk of code taken from SLOCCount's haskell_count script.
+ # Strips out {- .. -} and -- comments and counts the rest.
+ # Pragmas, {-#...}, are counted as SLOC.
+ # BUG: Doesn't handle strings with embedded block comment markers gracefully.
+ # In practice, that shouldn't be a problem.
+ my ($ra_lines, $file, ) = @_;
+
+ print "-> remove_haskell_comments\n" if $opt_v > 2;
+
+ my @save_lines = ();
+ my $in_comment = 0;
+ my $incomment = 0;
+ my ($literate, $inlitblock) = (0,0);
+
+ $literate = 1 if $file =~ /\.lhs$/;
+ if($literate) { $literate = determine_lit_type($file) }
+
+ foreach (@{$ra_lines}) {
+ if ($literate == 1) {
+ if (!s/^>//) { s/.*//; }
+ } elsif ($literate == 2) {
+ if ($inlitblock) {
+ if (m/^\\end{code}/) { s/.*//; $inlitblock = 0; }
+ } elsif (!$inlitblock) {
+ if (m/^\\begin{code}/) { s/.*//; $inlitblock = 1; }
+ else { s/.*//; }
+ }
+ }
+
+ if ($incomment) {
+ if (m/\-\}/) { s/^.*?\-\}//; $incomment = 0;}
+ else { s/.*//; }
+ }
+ if (!$incomment) {
+ s/--.*//;
+ s!{-[^#].*?-}!!g;
+ if (m/{-/ && (!m/{-#/)) {
+ s/{-.*//;
+ $incomment = 1;
+ }
+ }
+ if (m/\S/) { push @save_lines, $_; }
+ }
+# if ($incomment) {print "ERROR: ended in comment in $ARGV\n";}
+
+ print "<- remove_haskell_comments\n" if $opt_v > 2;
+ return @save_lines;
+} # 1}}}
+sub print_lines { # {{{1
+ my ($file , # in
+ $title , # in
+ $ra_lines , # in
+ ) = @_;
+ printf "->%-30s %s\n", $file, $title;
+ for (my $i = 0; $i < scalar @{$ra_lines}; $i++) {
+ printf "%5d | %s", $i+1, $ra_lines->[$i];
+ print "\n" unless $ra_lines->[$i] =~ m{\n$}
+ }
+} # 1}}}
+sub set_constants { # {{{1
+ my ($rh_Language_by_Extension , # out
+ $rh_Language_by_Script , # out
+ $rh_Language_by_File , # out
+ $rhaa_Filters_by_Language , # out
+ $rh_Not_Code_Extension , # out
+ $rh_Not_Code_Filename , # out
+ $rh_Scale_Factor , # out
+ $rh_Known_Binary_Archives , # out
+ ) = @_;
+# 1}}}
+%{$rh_Language_by_Extension} = ( # {{{1
+ 'abap' => 'ABAP' ,
+ 'ac' => 'm4' ,
+ 'ada' => 'Ada' ,
+ 'adb' => 'Ada' ,
+ 'ads' => 'Ada' ,
+ 'adso' => 'ADSO/IDSM' ,
+ 'am' => 'make' ,
+ 'ample' => 'AMPLE' ,
+ 'dofile' => 'AMPLE' ,
+ 'startup' => 'AMPLE' ,
+ 'asa' => 'ASP' ,
+ 'asax' => 'ASP.Net' ,
+ 'ascx' => 'ASP.Net' ,
+ 'asm' => 'Assembler' ,
+ 'asmx' => 'ASP.Net' ,
+ 'asp' => 'ASP' ,
+ 'aspx' => 'ASP.Net' ,
+ 'master' => 'ASP.Net' ,
+ 'sitemap' => 'ASP.Net' ,
+ 'awk' => 'awk' ,
+ 'bash' => 'Bourne Again Shell' ,
+ 'bas' => 'Visual Basic' ,
+ 'bat' => 'DOS Batch' ,
+ 'BAT' => 'DOS Batch' ,
+ 'cbl' => 'COBOL' ,
+ 'CBL' => 'COBOL' ,
+ 'c' => 'C' ,
+ 'C' => 'C++' ,
+ 'cc' => 'C++' ,
+ 'ccs' => 'CCS' ,
+ 'cfm' => 'ColdFusion' ,
+ 'cl' => 'Lisp' ,
+ 'cls' => 'Visual Basic' ,
+ 'cob' => 'COBOL' ,
+ 'COB' => 'COBOL' ,
+ 'config' => 'ASP.Net' ,
+ 'cpp' => 'C++' ,
+ 'cs' => 'C#' ,
+ 'csh' => 'C Shell' ,
+ 'css' => "CSS" ,
+ 'cxx' => 'C++' ,
+ 'da' => 'DAL' ,
+ 'def' => 'Teamcenter def' ,
+ 'dmap' => 'NASTRAN DMAP' ,
+ 'dpr' => 'Pascal' ,
+ 'dtd' => 'DTD' ,
+ 'ec' => 'C' ,
+ 'el' => 'Lisp' ,
+ 'exp' => 'Expect' ,
+ 'f77' => 'Fortran 77' ,
+ 'F77' => 'Fortran 77' ,
+ 'f90' => 'Fortran 90' ,
+ 'F90' => 'Fortran 90' ,
+ 'f95' => 'Fortran 95' ,
+ 'F95' => 'Fortran 95' ,
+ 'f' => 'Fortran 77' ,
+ 'F' => 'Fortran 77' ,
+ 'fmt' => 'Oracle Forms' ,
+ 'focexec' => 'Focus' ,
+ 'frm' => 'Visual Basic' ,
+ 'gnumakefile' => 'make' ,
+ 'Gnumakefile' => 'make' ,
+ 'h' => 'C/C++ Header' ,
+ 'H' => 'C/C++ Header' ,
+ 'hh' => 'C/C++ Header' ,
+ 'hpp' => 'C/C++ Header' ,
+ 'hs' => 'Haskell' ,
+ 'htm' => 'HTML' ,
+ 'html' => 'HTML' ,
+ 'i3' => 'Modula3' ,
+ 'idl' => 'IDL' ,
+ 'ig' => 'Modula3' ,
+ 'il' => 'SKILL' ,
+ 'ils' => 'SKILL++' ,
+ 'inc' => 'inc' , # might be PHP
+ 'itk' => 'Tcl/Tk' ,
+ 'java' => 'Java' ,
+ 'jcl' => 'JCL' , # IBM Job Control Lang.
+ 'jl' => 'Lisp' ,
+ 'js' => 'Javascript' ,
+ 'jsp' => 'JSP' , # Java server pages
+ 'ksh' => 'Korn Shell' ,
+ 'lhs' => 'Haskell' ,
+ 'l' => 'lex' ,
+ 'lsp' => 'Lisp' ,
+ 'lua' => 'Lua' ,
+ 'm3' => 'Modula3' ,
+ 'm4' => 'm4' ,
+ 'makefile' => 'make' ,
+ 'Makefile' => 'make' ,
+ 'met' => 'Teamcenter met' ,
+ 'mg' => 'Modula3' ,
+ 'mli' => 'ML' ,
+ 'ml' => 'ML' ,
+ 'm' => 'MATLAB/Objective C/MUMPS' ,
+ 'wdproj' => 'MSBuild scripts' ,
+ 'csproj' => 'MSBuild scripts' ,
+ 'mps' => 'MUMPS' ,
+ 'mth' => 'Teamcenter mth' ,
+ 'oscript' => 'LiveLink OScript' ,
+ 'pad' => 'Ada' , # Oracle Ada preprocessor
+ 'pas' => 'Pascal' ,
+ 'pcc' => 'C++' , # Oracle C++ preprocessor
+ 'perl' => 'Perl' ,
+ 'pfo' => 'Fortran 77' ,
+ 'pgc' => 'C' , # Postgres embedded C/C++
+ 'php3' => 'PHP' ,
+ 'php4' => 'PHP' ,
+ 'php5' => 'PHP' ,
+ 'php' => 'PHP' ,
+ 'plh' => 'Perl' ,
+ 'pl' => 'Perl' ,
+ 'PL' => 'Perl' ,
+ 'plx' => 'Perl' ,
+ 'pm' => 'Perl' ,
+ 'p' => 'Pascal' ,
+ 'pp' => 'Pascal' ,
+ 'psql' => 'SQL' ,
+ 'py' => 'Python' ,
+ 'rb' => 'Ruby' ,
+ # 'resx' => 'ASP.Net' ,
+ 'rex' => 'Oracle Reports' ,
+ 'rexx' => 'Rexx' ,
+ 's' => 'Assembler' ,
+ 'S' => 'Assembler' ,
+ 'sbl' => 'Softbridge Basic' ,
+ 'SBL' => 'Softbridge Basic' ,
+ 'sc' => 'Lisp' ,
+ 'scm' => 'Lisp' ,
+ 'sed' => 'sed' ,
+ 'ses' => 'Patran Command Language' ,
+ 'pcl' => 'Patran Command Language' ,
+ 'sh' => 'Bourne Shell' ,
+ 'sql' => 'SQL' ,
+ 'SQL' => 'SQL' ,
+ 'tcl' => 'Tcl/Tk' ,
+ 'tcsh' => 'C Shell' ,
+ 'tk' => 'Tcl/Tk' ,
+ 'vba' => 'Visual Basic' ,
+ 'VBA' => 'Visual Basic' ,
+ # 'vbp' => 'Visual Basic' , # .vbp - autogenerated
+ 'vb' => 'Visual Basic' ,
+ 'VB' => 'Visual Basic' ,
+ # 'vbw' => 'Visual Basic' , # .vbw - autogenerated
+ 'vbs' => 'Visual Basic' ,
+ 'VBS' => 'Visual Basic' ,
+ 'webinfo' => 'ASP.Net' ,
+ 'xml' => 'XML' ,
+ 'XML' => 'XML' ,
+ 'build' => 'NAnt scripts' ,
+ 'vim' => 'vim script' ,
+ 'xsd' => 'XSD' ,
+ 'XSD' => 'XSD' ,
+ 'xslt' => 'XSLT' ,
+ 'XSLT' => 'XSLT' ,
+ 'xsl' => 'XSLT' ,
+ 'XSL' => 'XSLT' ,
+ 'y' => 'yacc' ,
+ 'yaml' => 'YAML' ,
+ 'yml' => 'YAML' ,
+ );
+# 1}}}
+%{$rh_Language_by_Script} = ( # {{{1
+ 'awk' => 'awk' ,
+ 'bash' => 'Bourne Again Shell' ,
+ 'bc' => 'bc' ,# calculator
+ 'csh' => 'C Shell' ,
+ 'idl' => 'IDL' ,
+ 'ksh' => 'Korn Shell' ,
+ 'lua' => 'Lua' ,
+ 'make' => 'make' ,
+ 'octave' => 'Octave' ,
+ 'perl5' => 'Perl' ,
+ 'perl' => 'Perl' ,
+ 'ruby' => 'Ruby' ,
+ 'sed' => 'sed' ,
+ 'sh' => 'Bourne Shell' ,
+ 'tcl' => 'Tcl/Tk' ,
+ 'tclsh' => 'Tcl/Tk' ,
+ 'tcsh' => 'C Shell' ,
+ 'wish' => 'Tcl/Tk' ,
+ );
+# 1}}}
+%{$rh_Language_by_File} = ( # {{{1
+ 'Makefile' => 'make' ,
+ 'makefile' => 'make' ,
+ 'gnumakefile' => 'make' ,
+ 'Gnumakefile' => 'make' ,
+ );
+# 1}}}
+%{$rhaa_Filters_by_Language} = ( # {{{1
+ 'ABAP' => [ [ 'remove_matches' , '^\*' ], ],
+ 'ASP' => [ [ 'remove_matches' , '^\s*\47'], ], # \47 = '
+ 'ASP.Net' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'Ada' => [ [ 'remove_matches' , '^\s*--' ], ],
+ 'ADSO/IDSM' => [ [ 'remove_matches' , '^\s*\*[\+\!]' ], ],
+ 'AMPLE' => [ [ 'remove_matches' , '^\s*//' ], ],
+ 'Assembler' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'remove_matches' , '^\s*;' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'awk' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'bc' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'C' => [
+ [ 'remove_matches' , '^\s*//' ], # C99
+ [ 'call_regexp_common' , 'C' ], ],
+ 'C++' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'C/C++ Header' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ], ],
+ 'C#' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'CCS' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'CSS' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'COBOL' => [ [ 'remove_cobol_comments', ], ],
+ 'ColdFusion' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'Crystal Reports' => [ [ 'remove_matches' , '^\s*//' ], ],
+ 'DAL' => [ [ 'remove_between' , '[]', ], ],
+ 'NASTRAN DMAP' => [ [ 'remove_matches' , '^\s*\$' ], ],
+ 'DOS Batch' => [ [ 'remove_matches' , '^\s*rem', ], ],
+ 'DTD' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'Expect' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Focus' => [ [ 'remove_matches' , '^\s*\-\*' ], ],
+ 'Fortran 77' => [ [ 'remove_f77_comments' , ], ],
+ 'Fortran 90' => [ [ 'remove_f77_comments' , ],
+ [ 'remove_f90_comments' , ], ],
+ 'Fortran 95' => [ [ 'remove_f77_comments' , ],
+ [ 'remove_f90_comments' , ], ],
+ 'HTML' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'Haskell' => [ [ 'remove_haskell_comments', '>filename<' ], ],
+ 'IDL' => [ [ 'remove_matches' , '^\s*;' ], ],
+ 'JSP' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ],
+ [ 'remove_jsp_comments', ], ],
+ 'Java' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'Javascript' => [
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'JCL' => [ [ 'remove_jcl_comments' , ], ],
+ 'Lisp' => [ [ 'remove_matches' , '^\s*;' ], ],
+ 'LiveLink OScript' => [ [ 'remove_matches' , '^\s*//' ], ],
+# 'Lua' => [ [ 'call_regexp_common' , 'lua' ], ],
+ 'Lua' => [ [ 'remove_matches' , '^\s*\-\-' ], ],
+ 'make' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'MATLAB' => [ [ 'remove_matches' , '^\s*%' ], ],
+ 'Modula3' => [ [ 'call_regexp_common' , 'Pascal' ], ],
+ # Modula 3 comments are (* ... *) so applying the Pascal filter
+ # which also treats { ... } as a comment is not really correct.
+ 'Objective C' => [ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ], ],
+ 'MATLAB/Objective C/MUMPS' => [ [ 'die' , ], ], # never called
+ 'MUMPS' => [ [ 'remove_matches' , '^\s*;' ], ],
+ 'Octave' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Oracle Forms' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'Oracle Reports' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'Pascal' => [ [ 'call_regexp_common' , 'Pascal' ], ],
+ 'Patran Command Language'=> [
+ [ 'remove_matches' , '^\s*#' ],
+ [ 'remove_matches' , '^\s*\$#' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'Perl' => [ [ 'remove_below' , '^__(END|DATA)__'],
+ [ 'remove_matches' , '^\s*#' ], ],
+ 'Python' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'PHP' => [
+ [ 'remove_matches' , '^\s*#' ],
+ [ 'remove_matches' , '^\s*//' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'Rexx' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'Ruby' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'SKILL' => [
+ [ 'remove_matches' , '^\s*;' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'SKILL++' => [
+ [ 'remove_matches' , '^\s*;' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'SQL' => [
+ [ 'remove_matches' , '^\s*--' ],
+ [ 'call_regexp_common' , 'C' ],
+ ],
+ 'sed' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Bourne Again Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Bourne Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'm4' => [ [ 'remove_matches' , '^dnl ' ], ],
+ 'C Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Korn Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Tcl/Tk' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Teamcenter def' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Teamcenter met' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'Teamcenter mth' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'Softbridge Basic' => [ [ 'remove_above' , '^\s*Attribute\s+VB_Name\s+=' ],
+ [ 'remove_matches' , '^\s*Attribute\s+'],
+ [ 'remove_matches' , '^\s*\47'], ], # \47 = '
+ 'vim script' => [ [ 'remove_matches' , '^\s*"' ], ],
+ 'Visual Basic' => [ [ 'remove_above' , '^\s*Attribute\s+VB_Name\s+=' ],
+ [ 'remove_matches' , '^\s*Attribute\s+'],
+ [ 'remove_matches' , '^\s*\47'], ], # \47 = '
+ 'yacc' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'YAML' => [ [ 'remove_matches' , '^\s*#' ], ],
+ 'lex' => [ [ 'call_regexp_common' , 'C' ], ],
+ 'XML' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'XSD' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'XSLT' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'NAnt scripts' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ 'MSBuild scripts' => [ [ 'remove_html_comments', ],
+ [ 'call_regexp_common' , 'HTML' ], ],
+ );
+# 1}}}
+%{$rh_Not_Code_Extension} = ( # {{{1
+ '1' => 1, # Man pages (documentation):
+ '2' => 1,
+ '3' => 1,
+ '4' => 1,
+ '5' => 1,
+ '6' => 1,
+ '7' => 1,
+ '8' => 1,
+ '9' => 1,
+ 'a' => 1, # Static object code.
+ 'ad' => 1, # X application default resource file.
+ 'afm' => 1, # font metrics
+ 'arc' => 1, # arc(1) archive
+ 'arj' => 1, # arj(1) archive
+ 'au' => 1, # Audio sound filearj(1) archive
+ 'bak' => 1, # Backup files - we only want to count the "real" files.
+ 'bdf' => 1,
+ 'bmp' => 1,
+ 'bz2' => 1, # bzip2(1) compressed file
+ 'csv' => 1, # comma separated values
+ 'desktop' => 1,
+ 'dic' => 1,
+ 'doc' => 1,
+ 'elc' => 1,
+ 'eps' => 1,
+ 'fig' => 1,
+ 'gif' => 1,
+ 'gz' => 1,
+ 'hdf' => 1, # hierarchical data format
+ 'in' => 1, # Debatable.
+ 'jpg' => 1,
+ 'kdelnk' => 1,
+ 'man' => 1,
+ 'mf' => 1,
+ 'mp3' => 1,
+ 'n' => 1,
+ 'o' => 1, # Object code is generated from source code.
+ 'pbm' => 1,
+ 'pdf' => 1,
+ 'pfb' => 1,
+ 'png' => 1,
+ 'po' => 1,
+ 'ps' => 1, # Postscript is _USUALLY_ generated automatically.
+ 'sgm' => 1,
+ 'sgml' => 1,
+ 'so' => 1, # Dynamically-loaded object code.
+ 'Tag' => 1,
+ 'tex' => 1,
+ 'text' => 1,
+ 'tfm' => 1,
+ 'tgz' => 1, # gzipped tarball
+ 'tiff' => 1,
+ 'txt' => 1,
+ 'vf' => 1,
+ 'wav' => 1,
+ 'xbm' => 1,
+ 'xpm' => 1,
+ 'Y' => 1, # file compressed with "Yabba"
+ 'Z' => 1, # file compressed with "compress"
+ 'zip' => 1, # zip archive
+); # 1}}}
+%{$rh_Not_Code_Filename} = ( # {{{1
+ 'AUTHORS' => 1,
+ 'README' => 1,
+ 'Readme' => 1,
+ 'readme' => 1,
+ 'README.tk' => 1, # used in kdemultimedia, it's confusing.
+ 'Changelog' => 1,
+ 'ChangeLog' => 1,
+ 'Repository' => 1,
+ 'CHANGES' => 1,
+ 'Changes' => 1,
+ '.cvsignore' => 1,
+ 'Root' => 1, # CVS
+ 'BUGS' => 1,
+ 'TODO' => 1,
+ 'COPYING' => 1,
+ 'MAINTAINERS' => 1,
+ 'Entries' => 1,
+ 'iconfig.h' => 1, # Skip "iconfig.h" files; they're used in Imakefiles
+ # (used in xlockmore):
+);
+# 1}}}
+%{$rh_Scale_Factor} = ( # {{{1
+ '1032/af' => 5.00,
+ '1st generation default' => 0.25,
+ '2nd generation default' => 0.75,
+ '3rd generation default' => 1.00,
+ '4th generation default' => 4.00,
+ '5th generation default' => 16.00,
+ 'aas macro' => 0.88,
+ 'abap/4' => 5.00,
+ 'ABAP' => 5.00,
+ 'accel' => 4.21,
+ 'access' => 2.11,
+ 'actor' => 3.81,
+ 'acumen' => 2.86,
+ 'Ada' => 0.52,
+ 'Ada 83' => 1.13,
+ 'Ada 95' => 1.63,
+ 'adr/dl' => 2.00,
+ 'adr/ideal/pdl' => 4.00,
+ 'ads/batch' => 4.00,
+ 'ads/online' => 4.00,
+ 'ADSO/IDSM' => 3.00,
+ 'advantage' => 2.11,
+ 'ai shell default' => 1.63,
+ 'ai shells' => 1.63,
+ 'algol 68' => 0.75,
+ 'algol w' => 0.75,
+ 'ambush' => 2.50,
+ 'aml' => 1.63,
+ 'AMPLE' => 2.00,
+ 'amppl ii' => 1.25,
+ 'ansi basic' => 1.25,
+ 'ansi cobol 74' => 0.75,
+ 'ansi cobol 85' => 0.88,
+ 'SQL' => 6.15,
+ 'answer/db' => 6.15,
+ 'apl 360/370' => 2.50,
+ 'apl default' => 2.50,
+ 'apl*plus' => 2.50,
+ 'applesoft basic' => 0.63,
+ 'application builder' => 4.00,
+ 'application manager' => 2.22,
+ 'aps' => 0.96,
+ 'aps' => 4.71,
+ 'apt' => 1.13,
+ 'aptools' => 4.00,
+ 'arc' => 1.63,
+ 'ariel' => 0.75,
+ 'arity' => 1.63,
+ 'arity prolog' => 1.25,
+ 'art' => 1.63,
+ 'art enterprise' => 1.74,
+ 'artemis' => 2.00,
+ 'artim' => 1.74,
+ 'as/set' => 4.21,
+ 'asi/inquiry' => 6.15,
+ 'ask windows' => 1.74,
+'asa' => 1.29,
+'ASP' => 1.29,
+'ASP.Net' => 1.29,
+'aspx' => 1.29,
+#'resx' => 1.29,
+'asax' => 1.29,
+'ascx' => 1.29,
+'asmx' => 1.29,
+'config' => 1.29,
+'webinfo' => 1.29,
+'CCS' => 5.33,
+
+# 'assembler (basic)' => 0.25,
+ 'Assembler' => 0.25,
+
+ 'assembler (macro)' => 0.51,
+ 'associative default' => 1.25,
+ 'autocoder' => 0.25,
+ 'awk' => 3.81,
+ 'aztec c' => 0.63,
+ 'balm' => 0.75,
+ 'base sas' => 1.51,
+ 'basic' => 0.75,
+ 'basic a' => 0.63,
+# 'basic assembly' => 0.25,
+ 'bc' => 1.50,
+ 'berkeley pascal' => 0.88,
+ 'better basic' => 0.88,
+ 'bliss' => 0.75,
+ 'bmsgen' => 2.22,
+ 'boeingcalc' => 13.33,
+ 'bteq' => 6.15,
+
+ 'C' => 0.77,
+
+ 'c set 2' => 0.88,
+
+ 'C#' => 1.36,
+
+ 'C++' => 1.51,
+
+ 'c86plus' => 0.63,
+ 'cadbfast' => 2.00,
+ 'caearl' => 2.86,
+ 'cast' => 1.63,
+ 'cbasic' => 0.88,
+ 'cdadl' => 4.00,
+ 'cellsim' => 1.74,
+'ColdFusion' => 4.00,
+ 'chili' => 0.75,
+ 'chill' => 0.75,
+ 'cics' => 1.74,
+ 'clarion' => 1.38,
+ 'clascal' => 1.00,
+ 'cli' => 2.50,
+ 'clipper' => 2.05,
+ 'clipper db' => 2.00,
+ 'clos' => 3.81,
+ 'clout' => 2.00,
+ 'cms2' => 0.75,
+ 'cmsgen' => 4.21,
+ 'COBOL' => 1.04,
+ 'COBOL ii' => 0.75,
+ 'COBOL/400' => 0.88,
+ 'cobra' => 4.00,
+ 'codecenter' => 2.22,
+ 'cofac' => 2.22,
+ 'cogen' => 2.22,
+ 'cognos' => 2.22,
+ 'cogo' => 1.13,
+ 'comal' => 1.00,
+ 'comit ii' => 1.25,
+ 'common lisp' => 1.25,
+ 'concurrent pascal' => 1.00,
+ 'conniver' => 1.25,
+ 'cool:gen/ief' => 2.58,
+ 'coral 66' => 0.75,
+ 'corvet' => 4.21,
+ 'corvision' => 5.33,
+ 'cpl' => 0.50,
+ 'Crystal Reports' => 4.00,
+ 'csl' => 1.63,
+ 'csp' => 1.51,
+ 'cssl' => 1.74,
+
+'CSS' => 1.0,
+
+ 'culprit' => 1.57,
+ 'cxpert' => 1.63,
+ 'cygnet' => 4.21,
+ 'DAL' => 1.50,
+ 'data base default' => 2.00,
+ 'dataflex' => 2.00,
+ 'datatrieve' => 4.00,
+ 'dbase iii' => 2.00,
+ 'dbase iv' => 1.54,
+ 'dcl' => 0.38,
+ 'decision support default' => 2.22,
+ 'decrally' => 2.00,
+ 'delphi' => 2.76,
+ 'dl/1' => 2.00,
+ 'NASTRAN DMAP' => 2.35,
+ 'dna4' => 4.21,
+ 'DOS Batch' => 0.63,
+ 'dsp assembly' => 0.50,
+ 'dtabl' => 1.74,
+ 'dtipt' => 1.74,
+ 'dyana' => 1.13,
+ 'dynamoiii' => 1.74,
+ 'easel' => 2.76,
+ 'easy' => 1.63,
+ 'easytrieve+' => 2.35,
+ 'eclipse' => 1.63,
+ 'eda/sql' => 6.67,
+ 'edscheme 3.4' => 1.51,
+ 'eiffel' => 3.81,
+ 'enform' => 1.74,
+ 'englishbased default' => 1.51,
+ 'ensemble' => 2.76,
+ 'epos' => 4.00,
+ 'erlang' => 2.00,
+ 'esf' => 2.00,
+ 'espadvisor' => 1.63,
+ 'espl/i' => 1.13,
+ 'euclid' => 0.75,
+ 'excel' => 1.74,
+ 'excel 12' => 13.33,
+ 'excel 34' => 13.33,
+ 'excel 5' => 13.33,
+ 'express' => 2.22,
+ 'exsys' => 1.63,
+ 'extended common lisp' => 1.43,
+ 'eznomad' => 2.22,
+ 'facets' => 4.00,
+ 'factorylink iv' => 2.76,
+ 'fame' => 2.22,
+ 'filemaker pro' => 2.22,
+ 'flavors' => 2.76,
+ 'flex' => 1.74,
+ 'flexgen' => 2.76,
+ 'Focus' => 1.90,
+ 'foil' => 1.51,
+ 'forte' => 4.44,
+ 'forth' => 1.25,
+ 'Fortran 66' => 0.63,
+ 'Fortran 77' => 0.75,
+ 'Fortran 90' => 1.00,
+ 'Fortran 95' => 1.13,
+ 'Fortran II' => 0.63,
+ 'foundation' => 2.76,
+ 'foxpro' => 2.29,
+ 'foxpro 1' => 2.00,
+ 'foxpro 2.5' => 2.35,
+ 'framework' => 13.33,
+ 'g2' => 1.63,
+ 'gamma' => 5.00,
+ 'genascript' => 2.96,
+ 'gener/ol' => 6.15,
+ 'genexus' => 5.33,
+ 'genifer' => 4.21,
+ 'geode 2.0' => 5.00,
+ 'gfa basic' => 2.35,
+ 'gml' => 1.74,
+ 'golden common lisp' => 1.25,
+ 'gpss' => 1.74,
+ 'guest' => 2.86,
+ 'guru' => 1.63,
+ 'gw basic' => 0.82,
+ 'Haskell' => 2.11,
+ 'high c' => 0.63,
+ 'hlevel' => 1.38,
+ 'hp basic' => 0.63,
+
+'HTML' => 1.90 ,
+'XML' => 1.90 ,
+'XSLT' => 1.90 ,
+'DTD' => 1.90 ,
+'XSD' => 1.90 ,
+'NAnt scripts' => 1.90 ,
+'MSBuild scripts' => 1.90 ,
+
+ 'HTML 2' => 5.00,
+ 'HTML 3' => 5.33,
+ 'huron' => 5.00,
+ 'ibm adf i' => 4.00,
+ 'ibm adf ii' => 4.44,
+ 'ibm advanced basic' => 0.82,
+ 'ibm cics/vs' => 2.00,
+ 'ibm compiled basic' => 0.88,
+ 'ibm vs cobol' => 0.75,
+ 'ibm vs cobol ii' => 0.88,
+ 'ices' => 1.13,
+ 'icon' => 1.00,
+ 'ideal' => 1.54,
+ 'idms' => 2.00,
+ 'ief' => 5.71,
+ 'ief/cool:gen' => 2.58,
+ 'iew' => 5.71,
+ 'ifps/plus' => 2.50,
+ 'imprs' => 2.00,
+ 'informix' => 2.58,
+ 'ingres' => 2.00,
+ 'inquire' => 6.15,
+ 'insight2' => 1.63,
+ 'install/1' => 5.00,
+ 'intellect' => 1.51,
+ 'interlisp' => 1.38,
+ 'interpreted basic' => 0.75,
+ 'interpreted c' => 0.63,
+ 'iqlisp' => 1.38,
+ 'iqrp' => 6.15,
+ 'j2ee' => 1.60,
+ 'janus' => 1.13,
+ 'Java' => 1.36,
+'Javascript' => 1.48,
+'JSP' => 1.48,
+ 'JCL' => 1.67,
+ 'joss' => 0.75,
+ 'jovial' => 0.75,
+ 'jsp' => 1.36,
+ 'kappa' => 2.00,
+ 'kbms' => 1.63,
+ 'kcl' => 1.25,
+ 'kee' => 1.63,
+ 'keyplus' => 2.00,
+ 'kl' => 1.25,
+ 'klo' => 1.25,
+ 'knowol' => 1.63,
+ 'krl' => 1.38,
+ 'Korn Shell' => 3.81,
+ 'ladder logic' => 2.22,
+ 'lambit/l' => 1.25,
+ 'lattice c' => 0.63,
+ 'liana' => 0.63,
+ 'lilith' => 1.13,
+ 'linc ii' => 5.71,
+ 'Lisp' => 1.25,
+ 'LiveLink OScript' => 3.5 ,
+ 'loglisp' => 1.38,
+ 'loops' => 3.81,
+ 'lotus 123 dos' => 13.33,
+ 'lotus macros' => 0.75,
+ 'lotus notes' => 3.64,
+ 'lucid 3d' => 13.33,
+ 'lyric' => 1.51,
+ 'm4' => 1.00,
+ 'm' => 5.00,
+ 'macforth' => 1.25,
+ 'mach1' => 2.00,
+ 'machine language' => 0.13,
+ 'maestro' => 5.00,
+ 'magec' => 5.00,
+ 'magik' => 3.81,
+ 'Lake' => 3.81,
+ 'make' => 2.50,
+ 'mantis' => 2.96,
+ 'mapper' => 0.99,
+ 'mark iv' => 2.00,
+ 'mark v' => 2.22,
+ 'mathcad' => 16.00,
+ 'mdl' => 2.22,
+ 'mentor' => 1.51,
+ 'mesa' => 0.75,
+ 'microfocus cobol' => 1.00,
+ 'microforth' => 1.25,
+ 'microsoft c' => 0.63,
+ 'microstep' => 4.00,
+ 'miranda' => 2.00,
+ 'model 204' => 2.11,
+ 'modula 2' => 1.00,
+ 'mosaic' => 13.33,
+ # 'ms c ++ v. 7' => 1.51,
+ 'ms compiled basic' => 0.88,
+ 'msl' => 1.25,
+ 'mulisp' => 1.25,
+ 'MUMPS' => 4.21,
+ 'Nastran' => 1.13,
+ 'natural' => 1.54,
+ 'natural 1' => 1.51,
+ 'natural 2' => 1.74,
+ 'natural construct' => 3.20,
+ 'natural language' => 0.03,
+ 'netron/cap' => 4.21,
+ 'nexpert' => 1.63,
+ 'nial' => 1.63,
+ 'nomad2' => 2.00,
+ 'nonprocedural default' => 2.22,
+ 'notes vip' => 2.22,
+ 'nroff' => 1.51,
+ 'object assembler' => 1.25,
+ 'object lisp' => 2.76,
+ 'object logo' => 2.76,
+ 'object pascal' => 2.76,
+ 'object star' => 5.00,
+ 'Objective C' => 2.96,
+ 'objectoriented default' => 2.76,
+ 'objectview' => 3.20,
+ 'ogl' => 1.00,
+ 'omnis 7' => 2.00,
+ 'oodl' => 2.76,
+ 'ops' => 1.74,
+ 'ops5' => 1.38,
+ 'oracle' => 2.76,
+ 'Oracle Reports' => 2.76,
+ 'Oracle Forms' => 2.67,
+ 'Oracle Developer/2000' => 3.48,
+ 'oscar' => 0.75,
+ 'pacbase' => 1.67,
+ 'pace' => 2.00,
+ 'paradox/pal' => 2.22,
+ 'Pascal' => 0.88,
+ 'Patran Command Language' => 2.50,
+ 'pc focus' => 2.22,
+ 'pdl millenium' => 3.81,
+ 'pdp11 ade' => 1.51,
+ 'peoplesoft' => 2.50,
+ 'Perl' => 4.00,
+ 'persistance object builder' => 3.81,
+ 'pilot' => 1.51,
+ 'pl/1' => 1.38,
+ 'pl/m' => 1.13,
+ 'pl/s' => 0.88,
+ 'pl/sql' => 2.58,
+ 'planit' => 1.51,
+ 'planner' => 1.25,
+ 'planperfect 1' => 11.43,
+ 'plato' => 1.51,
+ 'polyforth' => 1.25,
+ 'pop' => 1.38,
+ 'poplog' => 1.38,
+ 'power basic' => 1.63,
+ 'powerbuilder' => 3.33,
+ 'powerhouse' => 5.71,
+ 'ppl (plus)' => 2.00,
+ 'problemoriented default' => 1.13,
+ 'proc' => 2.96,
+ 'procedural default' => 0.75,
+ 'professional pascal' => 0.88,
+ 'program generator default' => 5.00,
+ 'progress v4' => 2.22,
+ 'proiv' => 1.38,
+ 'prolog' => 1.25,
+ 'prose' => 0.75,
+ 'proteus' => 0.75,
+ 'qbasic' => 1.38,
+ 'qbe' => 6.15,
+ 'qmf' => 5.33,
+ 'qnial' => 1.63,
+ 'quattro' => 13.33,
+ 'quattro pro' => 13.33,
+ 'query default' => 6.15,
+ 'quick basic 1' => 1.25,
+ 'quick basic 2' => 1.31,
+ 'quick basic 3' => 1.38,
+ 'quick c' => 0.63,
+ 'quickbuild' => 2.86,
+ 'quiz' => 5.33,
+ 'rally' => 2.00,
+ 'ramis ii' => 2.00,
+ 'rapidgen' => 2.86,
+ 'ratfor' => 0.88,
+ 'rdb' => 2.00,
+ 'realia' => 1.74,
+ 'realizer 1.0' => 2.00,
+ 'realizer 2.0' => 2.22,
+ 'relate/3000' => 2.00,
+ 'reuse default' => 16.00,
+ 'Rexx' => 1.19,
+ 'Rexx (mvs)' => 1.00,
+ 'Rexx (os/2)' => 1.74,
+ 'rm basic' => 0.88,
+ 'rm cobol' => 0.75,
+ 'rm fortran' => 0.75,
+ 'rpg i' => 1.00,
+ 'rpg ii' => 1.63,
+ 'rpg iii' => 1.63,
+ 'rtexpert 1.4' => 1.38,
+ 'sabretalk' => 0.90,
+ 'sail' => 0.75,
+ 'sapiens' => 5.00,
+ 'sas' => 1.95,
+ 'savvy' => 6.15,
+ 'sbasic' => 0.88,
+ 'sceptre' => 1.13,
+ 'scheme' => 1.51,
+ 'screen painter default' => 13.33,
+ 'sequal' => 6.67,
+ 'Bourne Shell' => 3.81,
+ 'Bourne Again Shell' => 3.81,
+ 'ksh' => 3.81,
+ 'C Shell' => 3.81,
+ 'siebel tools ' => 6.15,
+ 'simplan' => 2.22,
+ 'simscript' => 1.74,
+ 'simula' => 1.74,
+ 'simula 67' => 1.74,
+ 'simulation default' => 1.74,
+ 'SKILL' => 2.00,
+ 'SKILL++' => 2.00,
+ 'slogan' => 0.98,
+ 'smalltalk' => 2.50,
+ 'smalltalk 286' => 3.81,
+ 'smalltalk 80' => 3.81,
+ 'smalltalk/v' => 3.81,
+ 'snap' => 1.00,
+ 'snobol24' => 0.63,
+ 'softscreen' => 5.71,
+ 'Softbridge Basic' => 2.76,
+ 'solo' => 1.38,
+ 'speakeasy' => 2.22,
+ 'spinnaker ppl' => 2.22,
+ 'splus' => 2.50,
+ 'spreadsheet default' => 13.33,
+ 'sps' => 0.25,
+ 'spss' => 2.50,
+ 'SQL' => 2.29,
+ 'sqlwindows' => 6.67,
+ 'statistical default' => 2.50,
+ 'strategem' => 2.22,
+ 'stress' => 1.13,
+ 'strongly typed default' => 0.88,
+ 'style' => 1.74,
+ 'superbase 1.3' => 2.22,
+ 'surpass' => 13.33,
+ 'sybase' => 2.00,
+ 'symantec c++' => 2.76,
+ 'symbolang' => 1.25,
+ 'synchroworks' => 4.44,
+ 'synon/2e' => 4.21,
+ 'systemw' => 2.22,
+ 'tandem access language' => 0.88,
+ 'Tcl/Tk' => 4.00,
+ 'Teamcenter def' => 1.00,
+ 'Teamcenter met' => 1.00,
+ 'Teamcenter mth' => 1.00,
+ 'telon' => 5.00,
+ 'tessaract' => 2.00,
+ 'the twin' => 13.33,
+ 'themis' => 6.15,
+ 'tiief' => 5.71,
+ 'topspeed c++' => 2.76,
+ 'transform' => 5.33,
+ 'translisp plus' => 1.43,
+ 'treet' => 1.25,
+ 'treetran' => 1.25,
+ 'trs80 basic' => 0.63,
+ 'true basic' => 1.25,
+ 'turbo c' => 0.63,
+ # 'turbo c++' => 1.51,
+ 'turbo expert' => 1.63,
+ 'turbo pascal >5' => 1.63,
+ 'turbo pascal 14' => 1.00,
+ 'turbo pascal 45' => 1.13,
+ 'turbo prolog' => 1.00,
+ 'turing' => 1.00,
+ 'tutor' => 1.51,
+ 'twaice' => 1.63,
+ 'ucsd pascal' => 0.88,
+ 'ufo/ims' => 2.22,
+ 'uhelp' => 2.50,
+ 'uniface' => 5.00,
+ # 'unix shell scripts' => 3.81,
+ 'vax acms' => 1.38,
+ 'vax ade' => 2.00,
+ 'vbscript' => 2.35,
+ 'vectran' => 0.75,
+ 'vhdl ' => 4.21,
+ 'vim script' => 3.00,
+ 'visible c' => 1.63,
+ 'visible cobol' => 2.00,
+ 'visicalc 1' => 8.89,
+ 'visual 4.0' => 2.76,
+ 'visual basic' => 1.90,
+ 'visual basic 1' => 1.74,
+ 'visual basic 2' => 1.86,
+ 'visual basic 3' => 2.00,
+ 'visual basic 4' => 2.22,
+ 'visual basic 5' => 2.76,
+ 'Visual Basic' => 2.76,
+ 'visual basic dos' => 2.00,
+ 'visual c++' => 2.35,
+ 'visual cobol' => 4.00,
+ 'visual objects' => 5.00,
+ 'visualage' => 3.81,
+ 'visualgen' => 4.44,
+ 'vpf' => 0.84,
+ 'vsrexx' => 2.50,
+ 'vulcan' => 1.25,
+ 'vz programmer' => 2.22,
+ 'warp x' => 2.00,
+ 'watcom c' => 0.63,
+ 'watcom c/386' => 0.63,
+ 'waterloo c' => 0.63,
+ 'waterloo pascal' => 0.88,
+ 'watfiv' => 0.94,
+ 'watfor' => 0.88,
+ 'web scripts' => 5.33,
+ 'whip' => 0.88,
+ 'wizard' => 2.86,
+ 'xlisp' => 1.25,
+ 'yacc' => 1.51,
+ 'yacc++' => 1.51,
+ 'YAML' => 0.90,
+ 'zbasic' => 0.88,
+ 'zim' => 4.21,
+ 'zlisp' => 1.25,
+
+'Expect' => 2.00,
+'C/C++ Header' => 1.00,
+'inc' => 1.00,
+'lex' => 1.00,
+'MATLAB' => 4.00,
+'IDL' => 3.80,
+'Octave' => 4.00,
+'ML' => 3.00,
+'Modula3' => 2.00,
+'PHP' => 3.50,
+'Python' => 4.20,
+'Ruby' => 4.20,
+'sed' => 4.00,
+'Lua' => 4.00,
+);
+# 1}}}
+%{$rh_Known_Binary_Archives} = ( # {{{1
+ '.tar' => 1 ,
+ '.tar.Z' => 1 ,
+ '.tar.gz' => 1 ,
+ '.tar.bz2' => 1 ,
+ '.zip' => 1 ,
+ '.Zip' => 1 ,
+ '.ZIP' => 1 ,
+ '.ear' => 1 , # Java
+ '.war' => 1 , # contained within .ear
+ );
+# 1}}}
+} # end sub set_constants()
+sub Install_Regexp_Common { # {{{1
+ # Installs portions of Damian Conway's & Abigail's Regexp::Common
+ # module, v2.120, into a temporary directory for the duration of
+ # this run.
+
+ my %Regexp_Common_Contents = ();
+$Regexp_Common_Contents{'Common'} = <<'EOCommon'; # {{{2
+package Regexp::Common;
+
+use 5.00473;
+use strict;
+
+local $^W = 1;
+
+use vars qw /$VERSION %RE %sub_interface $AUTOLOAD/;
+
+($VERSION) = q $Revision: 2.120 $ =~ /([\d.]+)/;
+
+
+sub _croak {
+ require Carp;
+ goto &Carp::croak;
+}
+
+sub _carp {
+ require Carp;
+ goto &Carp::carp;
+}
+
+sub new {
+ my ($class, @data) = @_;
+ my %self;
+ tie %self, $class, @data;
+ return \%self;
+}
+
+sub TIEHASH {
+ my ($class, @data) = @_;
+ bless \@data, $class;
+}
+
+sub FETCH {
+ my ($self, $extra) = @_;
+ return bless ref($self)->new(@$self, $extra), ref($self);
+}
+
+# Modification for cloc: only need a few modules from Regexp::Common.
+my %imports = map {$_ => "Regexp::Common::$_"}
+ qw /balanced comment delimited /;
+#my %imports = map {$_ => "Regexp::Common::$_"}
+# qw /balanced CC comment delimited lingua list
+# net number profanity SEN URI whitespace
+# zip/;
+
+sub import {
+ shift; # Shift off the class.
+ tie %RE, __PACKAGE__;
+ {
+ no strict 'refs';
+ *{caller() . "::RE"} = \%RE;
+ }
+
+ my $saw_import;
+ my $no_defaults;
+ my %exclude;
+ foreach my $entry (grep {!/^RE_/} @_) {
+ if ($entry eq 'pattern') {
+ no strict 'refs';
+ *{caller() . "::pattern"} = \&pattern;
+ next;
+ }
+ # This used to prevent $; from being set. We still recognize it,
+ # but we won't do anything.
+ if ($entry eq 'clean') {
+ next;
+ }
+ if ($entry eq 'no_defaults') {
+ $no_defaults ++;
+ next;
+ }
+ if (my $module = $imports {$entry}) {
+ $saw_import ++;
+ eval "require $module;";
+ die $@ if $@;
+ next;
+ }
+ if ($entry =~ /^!(.*)/ && $imports {$1}) {
+ $exclude {$1} ++;
+ next;
+ }
+ # As a last resort, try to load the argument.
+ my $module = $entry =~ /^Regexp::Common/
+ ? $entry
+ : "Regexp::Common::" . $entry;
+ eval "require $module;";
+ die $@ if $@;
+ }
+
+ unless ($saw_import || $no_defaults) {
+ foreach my $module (values %imports) {
+ next if $exclude {$module};
+ eval "require $module;";
+ die $@ if $@;
+ }
+ }
+
+ my %exported;
+ foreach my $entry (grep {/^RE_/} @_) {
+ if ($entry =~ /^RE_(\w+_)?ALL$/) {
+ my $m = defined $1 ? $1 : "";
+ my $re = qr /^RE_${m}.*$/;
+ while (my ($sub, $interface) = each %sub_interface) {
+ next if $exported {$sub};
+ next unless $sub =~ /$re/;
+ {
+ no strict 'refs';
+ *{caller() . "::$sub"} = $interface;
+ }
+ $exported {$sub} ++;
+ }
+ }
+ else {
+ next if $exported {$entry};
+ _croak "Can't export unknown subroutine &$entry"
+ unless $sub_interface {$entry};
+ {
+ no strict 'refs';
+ *{caller() . "::$entry"} = $sub_interface {$entry};
+ }
+ $exported {$entry} ++;
+ }
+ }
+}
+
+sub AUTOLOAD { _croak "Can't $AUTOLOAD" }
+
+sub DESTROY {}
+
+my %cache;
+
+my $fpat = qr/^(-\w+)/;
+
+sub _decache {
+ my @args = @{tied %{$_[0]}};
+ my @nonflags = grep {!/$fpat/} @args;
+ my $cache = get_cache(@nonflags);
+ _croak "Can't create unknown regex: \$RE{"
+ . join("}{",@args) . "}"
+ unless exists $cache->{__VAL__};
+ _croak "Perl $] does not support the pattern "
+ . "\$RE{" . join("}{",@args)
+ . "}.\nYou need Perl $cache->{__VAL__}{version} or later"
+ unless ($cache->{__VAL__}{version}||0) <= $];
+ my %flags = ( %{$cache->{__VAL__}{default}},
+ map { /$fpat\Q$;\E(.*)/ ? ($1 => $2)
+ : /$fpat/ ? ($1 => undef)
+ : ()
+ } @args);
+ $cache->{__VAL__}->_clone_with(\@args, \%flags);
+}
+
+use overload q{""} => \&_decache;
+
+
+sub get_cache {
+ my $cache = \%cache;
+ foreach (@_) {
+ $cache = $cache->{$_}
+ || ($cache->{$_} = {});
+ }
+ return $cache;
+}
+
+sub croak_version {
+ my ($entry, @args) = @_;
+}
+
+sub pattern {
+ my %spec = @_;
+ _croak 'pattern() requires argument: name => [ @list ]'
+ unless $spec{name} && ref $spec{name} eq 'ARRAY';
+ _croak 'pattern() requires argument: create => $sub_ref_or_string'
+ unless $spec{create};
+
+ if (ref $spec{create} ne "CODE") {
+ my $fixed_str = "$spec{create}";
+ $spec{create} = sub { $fixed_str }
+ }
+
+ my @nonflags;
+ my %default;
+ foreach ( @{$spec{name}} ) {
+ if (/$fpat=(.*)/) {
+ $default{$1} = $2;
+ }
+ elsif (/$fpat\s*$/) {
+ $default{$1} = undef;
+ }
+ else {
+ push @nonflags, $_;
+ }
+ }
+
+ my $entry = get_cache(@nonflags);
+
+ if ($entry->{__VAL__}) {
+ _carp "Overriding \$RE{"
+ . join("}{",@nonflags)
+ . "}";
+ }
+
+ $entry->{__VAL__} = bless {
+ create => $spec{create},
+ match => $spec{match} || \&generic_match,
+ subs => $spec{subs} || \&generic_subs,
+ version => $spec{version},
+ default => \%default,
+ }, 'Regexp::Common::Entry';
+
+ foreach (@nonflags) {s/\W/X/g}
+ my $subname = "RE_" . join ("_", @nonflags);
+ $sub_interface{$subname} = sub {
+ push @_ => undef if @_ % 2;
+ my %flags = @_;
+ my $pat = $spec{create}->($entry->{__VAL__},
+ {%default, %flags}, \@nonflags);
+ if (exists $flags{-keep}) { $pat =~ s/\Q(?k:/(/g; }
+ else { $pat =~ s/\Q(?k:/(?:/g; }
+ return exists $flags {-i} ? qr /(?i:$pat)/ : qr/$pat/;
+ };
+
+ return 1;
+}
+
+sub generic_match {$_ [1] =~ /$_[0]/}
+sub generic_subs {$_ [1] =~ s/$_[0]/$_[2]/}
+
+sub matches {
+ my ($self, $str) = @_;
+ my $entry = $self -> _decache;
+ $entry -> {match} -> ($entry, $str);
+}
+
+sub subs {
+ my ($self, $str, $newstr) = @_;
+ my $entry = $self -> _decache;
+ $entry -> {subs} -> ($entry, $str, $newstr);
+ return $str;
+}
+
+
+package Regexp::Common::Entry;
+# use Carp;
+
+local $^W = 1;
+
+use overload
+ q{""} => sub {
+ my ($self) = @_;
+ my $pat = $self->{create}->($self, $self->{flags}, $self->{args});
+ if (exists $self->{flags}{-keep}) {
+ $pat =~ s/\Q(?k:/(/g;
+ }
+ else {
+ $pat =~ s/\Q(?k:/(?:/g;
+ }
+ if (exists $self->{flags}{-i}) { $pat = "(?i)$pat" }
+ return $pat;
+ };
+
+sub _clone_with {
+ my ($self, $args, $flags) = @_;
+ bless { %$self, args=>$args, flags=>$flags }, ref $self;
+}
+#
+# Copyright (c) 2001 - 2005, Damian Conway and Abigail. All Rights
+# Reserved. This module is free software. It may be used, redistributed
+# and/or modified under the terms of the Perl Artistic License
+# (see http://www.perl.com/perl/misc/Artistic.html)
+EOCommon
+# 2}}}
+$Regexp_Common_Contents{'Common/comment'} = <<'EOC'; # {{{2
+# $Id: comment.pm,v 2.116 2005/03/16 00:00:02 abigail Exp $
+
+package Regexp::Common::comment;
+
+use strict;
+local $^W = 1;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+use vars qw /$VERSION/;
+
+($VERSION) = q $Revision: 2.116 $ =~ /[\d.]+/g;
+
+my @generic = (
+ {languages => [qw /ABC Forth/],
+ to_eol => ['\\\\']}, # This is for just a *single* backslash.
+
+ {languages => [qw /Ada Alan Eiffel lua/],
+ to_eol => ['--']},
+
+ {languages => [qw /Advisor/],
+ to_eol => ['#|//']},
+
+ {languages => [qw /Advsys CQL Lisp LOGO M MUMPS REBOL Scheme
+ SMITH zonefile/],
+ to_eol => [';']},
+
+ {languages => ['Algol 60'],
+ from_to => [[qw /comment ;/]]},
+
+ {languages => [qw {ALPACA B C C-- LPC PL/I}],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw /awk fvwm2 Icon mutt Perl Python QML R Ruby shell Tcl/],
+ to_eol => ['#']},
+
+ {languages => [[BASIC => 'mvEnterprise']],
+ to_eol => ['[*!]|REM']},
+
+ {languages => [qw /Befunge-98 Funge-98 Shelta/],
+ id => [';']},
+
+ {languages => ['beta-Juliet', 'Crystal Report', 'Portia'],
+ to_eol => ['//']},
+
+ {languages => ['BML'],
+ from_to => [['<?_c', '_c?>']],
+ },
+
+ {languages => [qw /C++/, 'C#', qw /Cg ECMAScript FPL Java JavaScript/],
+ to_eol => ['//'],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw /CLU LaTeX slrn TeX/],
+ to_eol => ['%']},
+
+ {languages => [qw /False/],
+ from_to => [[qw !{ }!]]},
+
+ {languages => [qw /Fortran/],
+ to_eol => ['!']},
+
+ {languages => [qw /Haifu/],
+ id => [',']},
+
+ {languages => [qw /ILLGOL/],
+ to_eol => ['NB']},
+
+ {languages => [qw /INTERCAL/],
+ to_eol => [q{(?:(?:PLEASE(?:\s+DO)?|DO)\s+)?(?:NOT|N'T)}]},
+
+ {languages => [qw /J/],
+ to_eol => ['NB[.]']},
+
+ {languages => [qw /Nickle/],
+ to_eol => ['#'],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw /Oberon/],
+ from_to => [[qw /(* *)/]]},
+
+ {languages => [[qw /Pascal Delphi/], [qw /Pascal Free/], [qw /Pascal GPC/]],
+ to_eol => ['//'],
+ from_to => [[qw !{ }!], [qw !(* *)!]]},
+
+ {languages => [[qw /Pascal Workshop/]],
+ id => [qw /"/],
+ from_to => [[qw !{ }!], [qw !(* *)!], [qw !/* */!]]},
+
+ {languages => [qw /PEARL/],
+ to_eol => ['!'],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw /PHP/],
+ to_eol => ['#', '//'],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw !PL/B!],
+ to_eol => ['[.;]']},
+
+ {languages => [qw !PL/SQL!],
+ to_eol => ['--'],
+ from_to => [[qw {/* */}]]},
+
+ {languages => [qw /Q-BAL/],
+ to_eol => ['`']},
+
+ {languages => [qw /Smalltalk/],
+ id => ['"']},
+
+ {languages => [qw /SQL/],
+ to_eol => ['-{2,}']},
+
+ {languages => [qw /troff/],
+ to_eol => ['\\\"']},
+
+ {languages => [qw /vi/],
+ to_eol => ['"']},
+
+ {languages => [qw /*W/],
+ from_to => [[qw {|| !!}]]},
+);
+
+my @plain_or_nested = (
+ [Caml => undef, "(*" => "*)"],
+ [Dylan => "//", "/*" => "*/"],
+ [Haskell => "-{2,}", "{-" => "-}"],
+ [Hugo => "!(?!\\\\)", "!\\" => "\\!"],
+ [SLIDE => "#", "(*" => "*)"],
+);
+
+#
+# Helper subs.
+#
+
+sub combine {
+ local $_ = join "|", @_;
+ if (@_ > 1) {
+ s/\(\?k:/(?:/g;
+ $_ = "(?k:$_)";
+ }
+ $_
+}
+
+sub to_eol ($) {"(?k:(?k:$_[0])(?k:[^\\n]*)(?k:\\n))"}
+sub id ($) {"(?k:(?k:$_[0])(?k:[^$_[0]]*)(?k:$_[0]))"} # One char only!
+sub from_to {
+ local $^W = 1;
+ my ($begin, $end) = @_;
+
+ my $qb = quotemeta $begin;
+ my $qe = quotemeta $end;
+ my $fe = quotemeta substr $end => 0, 1;
+ my $te = quotemeta substr $end => 1;
+
+ "(?k:(?k:$qb)(?k:(?:[^$fe]+|$fe(?!$te))*)(?k:$qe))";
+}
+
+
+my $count = 0;
+sub nested {
+ local $^W = 1;
+ my ($begin, $end) = @_;
+
+ $count ++;
+ my $r = '(??{$Regexp::Common::comment ['. $count . ']})';
+
+ my $qb = quotemeta $begin;
+ my $qe = quotemeta $end;
+ my $fb = quotemeta substr $begin => 0, 1;
+ my $fe = quotemeta substr $end => 0, 1;
+
+ my $tb = quotemeta substr $begin => 1;
+ my $te = quotemeta substr $end => 1;
+
+ use re 'eval';
+
+ my $re;
+ if ($fb eq $fe) {
+ $re = qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
+ }
+ else {
+ local $" = "|";
+ my @clauses = "(?>[^$fb$fe]+)";
+ push @clauses => "$fb(?!$tb)" if length $tb;
+ push @clauses => "$fe(?!$te)" if length $te;
+ push @clauses => $r;
+ $re = qr /(?:$qb(?:@clauses)*$qe)/;
+ }
+
+ $Regexp::Common::comment [$count] = qr/$re/;
+}
+
+#
+# Process data.
+#
+
+foreach my $info (@plain_or_nested) {
+ my ($language, $mark, $begin, $end) = @$info;
+ pattern name => [comment => $language],
+ create =>
+ sub {my $re = nested $begin => $end;
+ my $prefix = defined $mark ? $mark . "[^\n]*\n|" : "";
+ exists $_ [1] -> {-keep} ? qr /($prefix$re)/
+ : qr /$prefix$re/
+ },
+ version => 5.006,
+ ;
+}
+
+
+foreach my $group (@generic) {
+ my $pattern = combine +(map {to_eol $_} @{$group -> {to_eol}}),
+ (map {from_to @$_} @{$group -> {from_to}}),
+ (map {id $_} @{$group -> {id}}),
+ ;
+ foreach my $language (@{$group -> {languages}}) {
+ pattern name => [comment => ref $language ? @$language : $language],
+ create => $pattern,
+ ;
+ }
+}
+
+
+
+#
+# Other languages.
+#
+
+# http://www.pascal-central.com/docs/iso10206.txt
+pattern name => [qw /comment Pascal/],
+ create => '(?k:' . '(?k:[{]|[(][*])'
+ . '(?k:[^}*]*(?:[*][^)][^}*]*)*)'
+ . '(?k:[}]|[*][)])'
+ . ')'
+ ;
+
+# http://www.templetons.com/brad/alice/language/
+pattern name => [qw /comment Pascal Alice/],
+ create => '(?k:(?k:[{])(?k:[^}\n]*)(?k:[}]))'
+ ;
+
+
+# http://westein.arb-phys.uni-dortmund.de/~wb/a68s.txt
+pattern name => [qw (comment), 'Algol 68'],
+ create => q {(?k:(?:#[^#]*#)|} .
+ q {(?:\bco\b(?:[^c]+|\Bc|\bc(?!o\b))*\bco\b)|} .
+ q {(?:\bcomment\b(?:[^c]+|\Bc|\bc(?!omment\b))*\bcomment\b))}
+ ;
+
+
+# See rules 91 and 92 of ISO 8879 (SGML).
+# Charles F. Goldfarb: "The SGML Handbook".
+# Oxford: Oxford University Press. 1990. ISBN 0-19-853737-9.
+# Ch. 10.3, pp 390.
+pattern name => [qw (comment HTML)],
+ create => q {(?k:(?k:<!)(?k:(?:--(?k:[^-]*(?:-[^-]+)*)--\s*)*)(?k:>))},
+ ;
+
+
+pattern name => [qw /comment SQL MySQL/],
+ create => q {(?k:(?:#|-- )[^\n]*\n|} .
+ q {/\*(?:(?>[^*;"']+)|"[^"]*"|'[^']*'|\*(?!/))*(?:;|\*/))},
+ ;
+
+# Anything that isn't <>[]+-.,
+# http://home.wxs.nl/~faase009/Ha_BF.html
+pattern name => [qw /comment Brainfuck/],
+ create => '(?k:[^<>\[\]+\-.,]+)'
+ ;
+
+# Squeak is a variant of Smalltalk-80.
+# http://www.squeak.
+# http://mucow.com/squeak-qref.html
+pattern name => [qw /comment Squeak/],
+ create => '(?k:(?k:")(?k:[^"]*(?:""[^"]*)*)(?k:"))'
+ ;
+
+#
+# Scores of less than 5 or above 17....
+# http://www.cliff.biffle.org/esoterica/beatnik.html
+@Regexp::Common::comment::scores = (1, 3, 3, 2, 1, 4, 2, 4, 1, 8,
+ 5, 1, 3, 1, 1, 3, 10, 1, 1, 1,
+ 1, 4, 4, 8, 4, 10);
+pattern name => [qw /comment Beatnik/],
+ create => sub {
+ use re 'eval';
+ my ($s, $x);
+ my $re = qr {\b([A-Za-z]+)\b
+ (?(?{($s, $x) = (0, lc $^N);
+ $s += $Regexp::Common::comment::scores
+ [ord (chop $x) - ord ('a')] while length $x;
+ $s >= 5 && $s < 18})XXX|)}x;
+ $re;
+ },
+ version => 5.008,
+ ;
+
+
+# http://www.cray.com/craydoc/manuals/007-3692-005/html-007-3692-005/
+# (Goto table of contents/3.3 Source Form)
+# Fortran, in fixed format. Comments start with a C, c or * in the first
+# column, or a ! anywhere, but the sixth column. Then end with a newline.
+pattern name => [qw /comment Fortran fixed/],
+ create => '(?k:(?k:(?:^[Cc*]|(?<!^.....)!))(?k:[^\n]*)(?k:\n))'
+ ;
+
+
+# http://www.csis.ul.ie/cobol/Course/COBOLIntro.htm
+# Traditionally, comments in COBOL were indicated with an asteriks in
+# the seventh column. Modern compilers may be more lenient.
+pattern name => [qw /comment COBOL/],
+ create => '(?<=^......)(?k:(?k:[*])(?k:[^\n]*)(?k:\n))',
+ version => '5.008',
+ ;
+
+1;
+#
+# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+# This module is free software. It may be used, redistributed
+# and/or modified under the terms of the Perl Artistic License
+# (see http://www.perl.com/perl/misc/Artistic.html)
+EOC
+# 2}}}
+$Regexp_Common_Contents{'Common/balanced'} = <<'EOB'; # {{{2
+package Regexp::Common::balanced; {
+
+use strict;
+local $^W = 1;
+
+use vars qw /$VERSION/;
+($VERSION) = q $Revision: 2.101 $ =~ /[\d.]+/g;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+
+my %closer = ( '{'=>'}', '('=>')', '['=>']', '<'=>'>' );
+my $count = -1;
+my %cache;
+
+sub nested {
+ local $^W = 1;
+ my ($start, $finish) = @_;
+
+ return $Regexp::Common::balanced [$cache {$start} {$finish}]
+ if exists $cache {$start} {$finish};
+
+ $count ++;
+ my $r = '(??{$Regexp::Common::balanced ['. $count . ']})';
+
+ my @starts = map {s/\\(.)/$1/g; $_} grep {length}
+ $start =~ /([^|\\]+|\\.)+/gs;
+ my @finishes = map {s/\\(.)/$1/g; $_} grep {length}
+ $finish =~ /([^|\\]+|\\.)+/gs;
+
+ push @finishes => ($finishes [-1]) x (@starts - @finishes);
+
+ my @re;
+ local $" = "|";
+ foreach my $begin (@starts) {
+ my $end = shift @finishes;
+
+ my $qb = quotemeta $begin;
+ my $qe = quotemeta $end;
+ my $fb = quotemeta substr $begin => 0, 1;
+ my $fe = quotemeta substr $end => 0, 1;
+
+ my $tb = quotemeta substr $begin => 1;
+ my $te = quotemeta substr $end => 1;
+
+ use re 'eval';
+
+ my $add;
+ if ($fb eq $fe) {
+ push @re =>
+ qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
+ }
+ else {
+ my @clauses = "(?>[^$fb$fe]+)";
+ push @clauses => "$fb(?!$tb)" if length $tb;
+ push @clauses => "$fe(?!$te)" if length $te;
+ push @clauses => $r;
+ push @re => qr /(?:$qb(?:@clauses)*$qe)/;
+ }
+ }
+
+ $cache {$start} {$finish} = $count;
+ $Regexp::Common::balanced [$count] = qr/@re/;
+}
+
+
+pattern name => [qw /balanced -parens=() -begin= -end=/],
+ create => sub {
+ my $flag = $_[1];
+ unless (defined $flag -> {-begin} && length $flag -> {-begin} &&
+ defined $flag -> {-end} && length $flag -> {-end}) {
+ my @open = grep {index ($flag->{-parens}, $_) >= 0}
+ ('[','(','{','<');
+ my @close = map {$closer {$_}} @open;
+ $flag -> {-begin} = join "|" => @open;
+ $flag -> {-end} = join "|" => @close;
+ }
+ my $pat = nested @$flag {qw /-begin -end/};
+ return exists $flag -> {-keep} ? qr /($pat)/ : $pat;
+ },
+ version => 5.006,
+ ;
+
+}
+
+1;
+#
+# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+# This module is free software. It may be used, redistributed
+# and/or modified under the terms of the Perl Artistic License
+# (see http://www.perl.com/perl/misc/Artistic.html)
+EOB
+# 2}}}
+$Regexp_Common_Contents{'Common/delimited'} = <<'EOD'; # {{{2
+# $Id: delimited.pm,v 2.104 2005/03/16 00:22:45 abigail Exp $
+
+package Regexp::Common::delimited;
+
+use strict;
+local $^W = 1;
+
+use Regexp::Common qw /pattern clean no_defaults/;
+use vars qw /$VERSION/;
+
+($VERSION) = q $Revision: 2.104 $ =~ /[\d.]+/g;
+
+sub gen_delimited {
+
+ my ($dels, $escs) = @_;
+ # return '(?:\S*)' unless $dels =~ /\S/;
+ if (length $escs) {
+ $escs .= substr ($escs, -1) x (length ($dels) - length ($escs));
+ }
+ my @pat = ();
+ my $i;
+ for ($i=0; $i < length $dels; $i++) {
+ my $del = quotemeta substr ($dels, $i, 1);
+ my $esc = length($escs) ? quotemeta substr ($escs, $i, 1) : "";
+ if ($del eq $esc) {
+ push @pat,
+ "(?k:$del)(?k:[^$del]*(?:(?:$del$del)[^$del]*)*)(?k:$del)";
+ }
+ elsif (length $esc) {
+ push @pat,
+ "(?k:$del)(?k:[^$esc$del]*(?:$esc.[^$esc$del]*)*)(?k:$del)";
+ }
+ else {
+ push @pat, "(?k:$del)(?k:[^$del]*)(?k:$del)";
+ }
+ }
+ my $pat = join '|', @pat;
+ return "(?k:$pat)";
+}
+
+sub _croak {
+ require Carp;
+ goto &Carp::croak;
+}
+
+pattern name => [qw( delimited -delim= -esc=\\ )],
+ create => sub {my $flags = $_[1];
+ _croak 'Must specify delimiter in $RE{delimited}'
+ unless length $flags->{-delim};
+ return gen_delimited (@{$flags}{-delim, -esc});
+ },
+ ;
+
+pattern name => [qw( quoted -esc=\\ )],
+ create => sub {my $flags = $_[1];
+ return gen_delimited (q{"'`}, $flags -> {-esc});
+ },
+ ;
+
+
+1;
+#
+# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
+# This module is free software. It may be used, redistributed
+# and/or modified under the terms of the Perl Artistic License
+# (see http://www.perl.com/perl/misc/Artistic.html)
+EOD
+# 2}}}
+ my $problems = 0;
+ $HAVE_Rexexp_Common = 0;
+ my $dir = "";
+ if ($opt_sdir) {
+ # write to the user-defined scratch directory
+ $dir = $opt_sdir;
+ } else {
+ # let File::Temp create a suitable temporary directory
+ $dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+ }
+ print "Using temp dir [$dir] to install Regexp::Common\n" if $opt_v;
+ my $Regexp_dir = "$dir/Regexp";
+ my $Regexp_Common_dir = "$dir/Regexp/Common";
+ mkdir $Regexp_dir ;
+ mkdir $Regexp_Common_dir;
+
+ foreach my $module_file (keys %Regexp_Common_Contents) {
+ my $OUT = new IO::File "$dir/Regexp/${module_file}.pm", "w";
+ if (defined $OUT) {
+ print $OUT $Regexp_Common_Contents{$module_file};
+ $OUT->close;
+ } else {
+ warn "Failed to install Regexp::${module_file}.pm\n";
+ $problems = 1;
+ }
+ }
+
+ push @INC, $dir;
+ eval "use Regexp::Common qw /comment RE_comment_HTML balanced/";
+ $HAVE_Rexexp_Common = 1 unless $problems;
+} # 1}}}
+sub Install_Algorithm_Diff { # {{{1
+ # Installs Tye McQueen's Algorithm::Diff module, v1.1902, into a
+ # temporary directory for the duration of this run.
+
+my $Algorithm_Diff_Contents = <<'EOAlgDiff'; # {{{2
+package Algorithm::Diff;
+# Skip to first "=head" line for documentation.
+use strict;
+
+use integer; # see below in _replaceNextLargerWith() for mod to make
+ # if you don't use this
+use vars qw( $VERSION @EXPORT_OK );
+$VERSION = 1.19_02;
+# ^ ^^ ^^-- Incremented at will
+# | \+----- Incremented for non-trivial changes to features
+# \-------- Incremented for fundamental changes
+require Exporter;
+*import = \&Exporter::import;
+@EXPORT_OK = qw(
+ prepare LCS LCSidx LCS_length
+ diff sdiff compact_diff
+ traverse_sequences traverse_balanced
+);
+
+# McIlroy-Hunt diff algorithm
+# Adapted from the Smalltalk code of Mario I. Wolczko, <mario@wolczko.com>
+# by Ned Konz, perl@bike-nomad.com
+# Updates by Tye McQueen, http://perlmonks.org/?node=tye
+
+# Create a hash that maps each element of $aCollection to the set of
+# positions it occupies in $aCollection, restricted to the elements
+# within the range of indexes specified by $start and $end.
+# The fourth parameter is a subroutine reference that will be called to
+# generate a string to use as a key.
+# Additional parameters, if any, will be passed to this subroutine.
+#
+# my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
+
+sub _withPositionsOfInInterval
+{
+ my $aCollection = shift; # array ref
+ my $start = shift;
+ my $end = shift;
+ my $keyGen = shift;
+ my %d;
+ my $index;
+ for ( $index = $start ; $index <= $end ; $index++ )
+ {
+ my $element = $aCollection->[$index];
+ my $key = &$keyGen( $element, @_ );
+ if ( exists( $d{$key} ) )
+ {
+ unshift ( @{ $d{$key} }, $index );
+ }
+ else
+ {
+ $d{$key} = [$index];
+ }
+ }
+ return wantarray ? %d : \%d;
+}
+
+# Find the place at which aValue would normally be inserted into the
+# array. If that place is already occupied by aValue, do nothing, and
+# return undef. If the place does not exist (i.e., it is off the end of
+# the array), add it to the end, otherwise replace the element at that
+# point with aValue. It is assumed that the array's values are numeric.
+# This is where the bulk (75%) of the time is spent in this module, so
+# try to make it fast!
+
+sub _replaceNextLargerWith
+{
+ my ( $array, $aValue, $high ) = @_;
+ $high ||= $#$array;
+
+ # off the end?
+ if ( $high == -1 || $aValue > $array->[-1] )
+ {
+ push ( @$array, $aValue );
+ return $high + 1;
+ }
+
+ # binary search for insertion point...
+ my $low = 0;
+ my $index;
+ my $found;
+ while ( $low <= $high )
+ {
+ $index = ( $high + $low ) / 2;
+
+ # $index = int(( $high + $low ) / 2); # without 'use integer'
+ $found = $array->[$index];
+
+ if ( $aValue == $found )
+ {
+ return undef;
+ }
+ elsif ( $aValue > $found )
+ {
+ $low = $index + 1;
+ }
+ else
+ {
+ $high = $index - 1;
+ }
+ }
+
+ # now insertion point is in $low.
+ $array->[$low] = $aValue; # overwrite next larger
+ return $low;
+}
+
+# This method computes the longest common subsequence in $a and $b.
+
+# Result is array or ref, whose contents is such that
+# $a->[ $i ] == $b->[ $result[ $i ] ]
+# foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
+
+# An additional argument may be passed; this is a hash or key generating
+# function that should return a string that uniquely identifies the given
+# element. It should be the case that if the key is the same, the elements
+# will compare the same. If this parameter is undef or missing, the key
+# will be the element as a string.
+
+# By default, comparisons will use "eq" and elements will be turned into keys
+# using the default stringizing operator '""'.
+
+# Additional parameters, if any, will be passed to the key generation
+# routine.
+
+sub _longestCommonSubsequence
+{
+ my $a = shift; # array ref or hash ref
+ my $b = shift; # array ref or hash ref
+ my $counting = shift; # scalar
+ my $keyGen = shift; # code ref
+ my $compare; # code ref
+
+ if ( ref($a) eq 'HASH' )
+ { # prepared hash must be in $b
+ my $tmp = $b;
+ $b = $a;
+ $a = $tmp;
+ }
+
+ # Check for bogus (non-ref) argument values
+ if ( !ref($a) || !ref($b) )
+ {
+ my @callerInfo = caller(1);
+ die 'error: must pass array or hash references to ' . $callerInfo[3];
+ }
+
+ # set up code refs
+ # Note that these are optimized.
+ if ( !defined($keyGen) ) # optimize for strings
+ {
+ $keyGen = sub { $_[0] };
+ $compare = sub { my ( $a, $b ) = @_; $a eq $b };
+ }
+ else
+ {
+ $compare = sub {
+ my $a = shift;
+ my $b = shift;
+ &$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
+ };
+ }
+
+ my ( $aStart, $aFinish, $matchVector ) = ( 0, $#$a, [] );
+ my ( $prunedCount, $bMatches ) = ( 0, {} );
+
+ if ( ref($b) eq 'HASH' ) # was $bMatches prepared for us?
+ {
+ $bMatches = $b;
+ }
+ else
+ {
+ my ( $bStart, $bFinish ) = ( 0, $#$b );
+
+ # First we prune off any common elements at the beginning
+ while ( $aStart <= $aFinish
+ and $bStart <= $bFinish
+ and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
+ {
+ $matchVector->[ $aStart++ ] = $bStart++;
+ $prunedCount++;
+ }
+
+ # now the end
+ while ( $aStart <= $aFinish
+ and $bStart <= $bFinish
+ and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
+ {
+ $matchVector->[ $aFinish-- ] = $bFinish--;
+ $prunedCount++;
+ }
+
+ # Now compute the equivalence classes of positions of elements
+ $bMatches =
+ _withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
+ }
+ my $thresh = [];
+ my $links = [];
+
+ my ( $i, $ai, $j, $k );
+ for ( $i = $aStart ; $i <= $aFinish ; $i++ )
+ {
+ $ai = &$keyGen( $a->[$i], @_ );
+ if ( exists( $bMatches->{$ai} ) )
+ {
+ $k = 0;
+ for $j ( @{ $bMatches->{$ai} } )
+ {
+
+ # optimization: most of the time this will be true
+ if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
+ {
+ $thresh->[$k] = $j;
+ }
+ else
+ {
+ $k = _replaceNextLargerWith( $thresh, $j, $k );
+ }
+
+ # oddly, it's faster to always test this (CPU cache?).
+ if ( defined($k) )
+ {
+ $links->[$k] =
+ [ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
+ }
+ }
+ }
+ }
+
+ if (@$thresh)
+ {
+ return $prunedCount + @$thresh if $counting;
+ for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
+ {
+ $matchVector->[ $link->[1] ] = $link->[2];
+ }
+ }
+ elsif ($counting)
+ {
+ return $prunedCount;
+ }
+
+ return wantarray ? @$matchVector : $matchVector;
+}
+
+sub traverse_sequences
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref
+ my $callbacks = shift || {};
+ my $keyGen = shift;
+ my $matchCallback = $callbacks->{'MATCH'} || sub { };
+ my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
+ my $finishedACallback = $callbacks->{'A_FINISHED'};
+ my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
+ my $finishedBCallback = $callbacks->{'B_FINISHED'};
+ my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
+
+ # Process all the lines in @$matchVector
+ my $lastA = $#$a;
+ my $lastB = $#$b;
+ my $bi = 0;
+ my $ai;
+
+ for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
+ {
+ my $bLine = $matchVector->[$ai];
+ if ( defined($bLine) ) # matched
+ {
+ &$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
+ &$matchCallback( $ai, $bi++, @_ );
+ }
+ else
+ {
+ &$discardACallback( $ai, $bi, @_ );
+ }
+ }
+
+ # The last entry (if any) processed was a match.
+ # $ai and $bi point just past the last matching lines in their sequences.
+
+ while ( $ai <= $lastA or $bi <= $lastB )
+ {
+
+ # last A?
+ if ( $ai == $lastA + 1 and $bi <= $lastB )
+ {
+ if ( defined($finishedACallback) )
+ {
+ &$finishedACallback( $lastA, @_ );
+ $finishedACallback = undef;
+ }
+ else
+ {
+ &$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
+ }
+ }
+
+ # last B?
+ if ( $bi == $lastB + 1 and $ai <= $lastA )
+ {
+ if ( defined($finishedBCallback) )
+ {
+ &$finishedBCallback( $lastB, @_ );
+ $finishedBCallback = undef;
+ }
+ else
+ {
+ &$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
+ }
+ }
+
+ &$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
+ &$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
+ }
+
+ return 1;
+}
+
+sub traverse_balanced
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref
+ my $callbacks = shift || {};
+ my $keyGen = shift;
+ my $matchCallback = $callbacks->{'MATCH'} || sub { };
+ my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
+ my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
+ my $changeCallback = $callbacks->{'CHANGE'};
+ my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
+
+ # Process all the lines in match vector
+ my $lastA = $#$a;
+ my $lastB = $#$b;
+ my $bi = 0;
+ my $ai = 0;
+ my $ma = -1;
+ my $mb;
+
+ while (1)
+ {
+
+ # Find next match indices $ma and $mb
+ do {
+ $ma++;
+ } while(
+ $ma <= $#$matchVector
+ && !defined $matchVector->[$ma]
+ );
+
+ last if $ma > $#$matchVector; # end of matchVector?
+ $mb = $matchVector->[$ma];
+
+ # Proceed with discard a/b or change events until
+ # next match
+ while ( $ai < $ma || $bi < $mb )
+ {
+
+ if ( $ai < $ma && $bi < $mb )
+ {
+
+ # Change
+ if ( defined $changeCallback )
+ {
+ &$changeCallback( $ai++, $bi++, @_ );
+ }
+ else
+ {
+ &$discardACallback( $ai++, $bi, @_ );
+ &$discardBCallback( $ai, $bi++, @_ );
+ }
+ }
+ elsif ( $ai < $ma )
+ {
+ &$discardACallback( $ai++, $bi, @_ );
+ }
+ else
+ {
+
+ # $bi < $mb
+ &$discardBCallback( $ai, $bi++, @_ );
+ }
+ }
+
+ # Match
+ &$matchCallback( $ai++, $bi++, @_ );
+ }
+
+ while ( $ai <= $lastA || $bi <= $lastB )
+ {
+ if ( $ai <= $lastA && $bi <= $lastB )
+ {
+
+ # Change
+ if ( defined $changeCallback )
+ {
+ &$changeCallback( $ai++, $bi++, @_ );
+ }
+ else
+ {
+ &$discardACallback( $ai++, $bi, @_ );
+ &$discardBCallback( $ai, $bi++, @_ );
+ }
+ }
+ elsif ( $ai <= $lastA )
+ {
+ &$discardACallback( $ai++, $bi, @_ );
+ }
+ else
+ {
+
+ # $bi <= $lastB
+ &$discardBCallback( $ai, $bi++, @_ );
+ }
+ }
+
+ return 1;
+}
+
+sub prepare
+{
+ my $a = shift; # array ref
+ my $keyGen = shift; # code ref
+
+ # set up code ref
+ $keyGen = sub { $_[0] } unless defined($keyGen);
+
+ return scalar _withPositionsOfInInterval( $a, 0, $#$a, $keyGen, @_ );
+}
+
+sub LCS
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref or hash ref
+ my $matchVector = _longestCommonSubsequence( $a, $b, 0, @_ );
+ my @retval;
+ my $i;
+ for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
+ {
+ if ( defined( $matchVector->[$i] ) )
+ {
+ push ( @retval, $a->[$i] );
+ }
+ }
+ return wantarray ? @retval : \@retval;
+}
+
+sub LCS_length
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref or hash ref
+ return _longestCommonSubsequence( $a, $b, 1, @_ );
+}
+
+sub LCSidx
+{
+ my $a= shift @_;
+ my $b= shift @_;
+ my $match= _longestCommonSubsequence( $a, $b, 0, @_ );
+ my @am= grep defined $match->[$_], 0..$#$match;
+ my @bm= @{$match}[@am];
+ return \@am, \@bm;
+}
+
+sub compact_diff
+{
+ my $a= shift @_;
+ my $b= shift @_;
+ my( $am, $bm )= LCSidx( $a, $b, @_ );
+ my @cdiff;
+ my( $ai, $bi )= ( 0, 0 );
+ push @cdiff, $ai, $bi;
+ while( 1 ) {
+ while( @$am && $ai == $am->[0] && $bi == $bm->[0] ) {
+ shift @$am;
+ shift @$bm;
+ ++$ai, ++$bi;
+ }
+ push @cdiff, $ai, $bi;
+ last if ! @$am;
+ $ai = $am->[0];
+ $bi = $bm->[0];
+ push @cdiff, $ai, $bi;
+ }
+ push @cdiff, 0+@$a, 0+@$b
+ if $ai < @$a || $bi < @$b;
+ return wantarray ? @cdiff : \@cdiff;
+}
+
+sub diff
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref
+ my $retval = [];
+ my $hunk = [];
+ my $discard = sub {
+ push @$hunk, [ '-', $_[0], $a->[ $_[0] ] ];
+ };
+ my $add = sub {
+ push @$hunk, [ '+', $_[1], $b->[ $_[1] ] ];
+ };
+ my $match = sub {
+ push @$retval, $hunk
+ if 0 < @$hunk;
+ $hunk = []
+ };
+ traverse_sequences( $a, $b,
+ { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
+ &$match();
+ return wantarray ? @$retval : $retval;
+}
+
+sub sdiff
+{
+ my $a = shift; # array ref
+ my $b = shift; # array ref
+ my $retval = [];
+ my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
+ my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
+ my $change = sub {
+ push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
+ };
+ my $match = sub {
+ push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
+ };
+ traverse_balanced(
+ $a,
+ $b,
+ {
+ MATCH => $match,
+ DISCARD_A => $discard,
+ DISCARD_B => $add,
+ CHANGE => $change,
+ },
+ @_
+ );
+ return wantarray ? @$retval : $retval;
+}
+
+########################################
+my $Root= __PACKAGE__;
+package Algorithm::Diff::_impl;
+use strict;
+
+sub _Idx() { 0 } # $me->[_Idx]: Ref to array of hunk indices
+ # 1 # $me->[1]: Ref to first sequence
+ # 2 # $me->[2]: Ref to second sequence
+sub _End() { 3 } # $me->[_End]: Diff between forward and reverse pos
+sub _Same() { 4 } # $me->[_Same]: 1 if pos 1 contains unchanged items
+sub _Base() { 5 } # $me->[_Base]: Added to range's min and max
+sub _Pos() { 6 } # $me->[_Pos]: Which hunk is currently selected
+sub _Off() { 7 } # $me->[_Off]: Offset into _Idx for current position
+sub _Min() { -2 } # Added to _Off to get min instead of max+1
+
+sub Die
+{
+ require Carp;
+ Carp::confess( @_ );
+}
+
+sub _ChkPos
+{
+ my( $me )= @_;
+ return if $me->[_Pos];
+ my $meth= ( caller(1) )[3];
+ Die( "Called $meth on 'reset' object" );
+}
+
+sub _ChkSeq
+{
+ my( $me, $seq )= @_;
+ return $seq + $me->[_Off]
+ if 1 == $seq || 2 == $seq;
+ my $meth= ( caller(1) )[3];
+ Die( "$meth: Invalid sequence number ($seq); must be 1 or 2" );
+}
+
+sub getObjPkg
+{
+ my( $us )= @_;
+ return ref $us if ref $us;
+ return $us . "::_obj";
+}
+
+sub new
+{
+ my( $us, $seq1, $seq2, $opts ) = @_;
+ my @args;
+ for( $opts->{keyGen} ) {
+ push @args, $_ if $_;
+ }
+ for( $opts->{keyGenArgs} ) {
+ push @args, @$_ if $_;
+ }
+ my $cdif= Algorithm::Diff::compact_diff( $seq1, $seq2, @args );
+ my $same= 1;
+ if( 0 == $cdif->[2] && 0 == $cdif->[3] ) {
+ $same= 0;
+ splice @$cdif, 0, 2;
+ }
+ my @obj= ( $cdif, $seq1, $seq2 );
+ $obj[_End] = (1+@$cdif)/2;
+ $obj[_Same] = $same;
+ $obj[_Base] = 0;
+ my $me = bless \@obj, $us->getObjPkg();
+ $me->Reset( 0 );
+ return $me;
+}
+
+sub Reset
+{
+ my( $me, $pos )= @_;
+ $pos= int( $pos || 0 );
+ $pos += $me->[_End]
+ if $pos < 0;
+ $pos= 0
+ if $pos < 0 || $me->[_End] <= $pos;
+ $me->[_Pos]= $pos || !1;
+ $me->[_Off]= 2*$pos - 1;
+ return $me;
+}
+
+sub Base
+{
+ my( $me, $base )= @_;
+ my $oldBase= $me->[_Base];
+ $me->[_Base]= 0+$base if defined $base;
+ return $oldBase;
+}
+
+sub Copy
+{
+ my( $me, $pos, $base )= @_;
+ my @obj= @$me;
+ my $you= bless \@obj, ref($me);
+ $you->Reset( $pos ) if defined $pos;
+ $you->Base( $base );
+ return $you;
+}
+
+sub Next {
+ my( $me, $steps )= @_;
+ $steps= 1 if ! defined $steps;
+ if( $steps ) {
+ my $pos= $me->[_Pos];
+ my $new= $pos + $steps;
+ $new= 0 if $pos && $new < 0;
+ $me->Reset( $new )
+ }
+ return $me->[_Pos];
+}
+
+sub Prev {
+ my( $me, $steps )= @_;
+ $steps= 1 if ! defined $steps;
+ my $pos= $me->Next(-$steps);
+ $pos -= $me->[_End] if $pos;
+ return $pos;
+}
+
+sub Diff {
+ my( $me )= @_;
+ $me->_ChkPos();
+ return 0 if $me->[_Same] == ( 1 & $me->[_Pos] );
+ my $ret= 0;
+ my $off= $me->[_Off];
+ for my $seq ( 1, 2 ) {
+ $ret |= $seq
+ if $me->[_Idx][ $off + $seq + _Min ]
+ < $me->[_Idx][ $off + $seq ];
+ }
+ return $ret;
+}
+
+sub Min {
+ my( $me, $seq, $base )= @_;
+ $me->_ChkPos();
+ my $off= $me->_ChkSeq($seq);
+ $base= $me->[_Base] if !defined $base;
+ return $base + $me->[_Idx][ $off + _Min ];
+}
+
+sub Max {
+ my( $me, $seq, $base )= @_;
+ $me->_ChkPos();
+ my $off= $me->_ChkSeq($seq);
+ $base= $me->[_Base] if !defined $base;
+ return $base + $me->[_Idx][ $off ] -1;
+}
+
+sub Range {
+ my( $me, $seq, $base )= @_;
+ $me->_ChkPos();
+ my $off = $me->_ChkSeq($seq);
+ if( !wantarray ) {
+ return $me->[_Idx][ $off ]
+ - $me->[_Idx][ $off + _Min ];
+ }
+ $base= $me->[_Base] if !defined $base;
+ return ( $base + $me->[_Idx][ $off + _Min ] )
+ .. ( $base + $me->[_Idx][ $off ] - 1 );
+}
+
+sub Items {
+ my( $me, $seq )= @_;
+ $me->_ChkPos();
+ my $off = $me->_ChkSeq($seq);
+ if( !wantarray ) {
+ return $me->[_Idx][ $off ]
+ - $me->[_Idx][ $off + _Min ];
+ }
+ return
+ @{$me->[$seq]}[
+ $me->[_Idx][ $off + _Min ]
+ .. ( $me->[_Idx][ $off ] - 1 )
+ ];
+}
+
+sub Same {
+ my( $me )= @_;
+ $me->_ChkPos();
+ return wantarray ? () : 0
+ if $me->[_Same] != ( 1 & $me->[_Pos] );
+ return $me->Items(1);
+}
+
+my %getName;
+BEGIN {
+ %getName= (
+ same => \&Same,
+ diff => \&Diff,
+ base => \&Base,
+ min => \&Min,
+ max => \&Max,
+ range=> \&Range,
+ items=> \&Items, # same thing
+ );
+}
+
+sub Get
+{
+ my $me= shift @_;
+ $me->_ChkPos();
+ my @value;
+ for my $arg ( @_ ) {
+ for my $word ( split ' ', $arg ) {
+ my $meth;
+ if( $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/
+ || not $meth= $getName{ lc $2 }
+ ) {
+ Die( $Root, ", Get: Invalid request ($word)" );
+ }
+ my( $base, $name, $seq )= ( $1, $2, $3 );
+ push @value, scalar(
+ 4 == length($name)
+ ? $meth->( $me )
+ : $meth->( $me, $seq, $base )
+ );
+ }
+ }
+ if( wantarray ) {
+ return @value;
+ } elsif( 1 == @value ) {
+ return $value[0];
+ }
+ Die( 0+@value, " values requested from ",
+ $Root, "'s Get in scalar context" );
+}
+
+
+my $Obj= getObjPkg($Root);
+no strict 'refs';
+
+for my $meth ( qw( new getObjPkg ) ) {
+ *{$Root."::".$meth} = \&{$meth};
+ *{$Obj ."::".$meth} = \&{$meth};
+}
+for my $meth ( qw(
+ Next Prev Reset Copy Base Diff
+ Same Items Range Min Max Get
+ _ChkPos _ChkSeq
+) ) {
+ *{$Obj."::".$meth} = \&{$meth};
+}
+
+1;
+# This version released by Tye McQueen (http://perlmonks.org/?node=tye).
+#
+# =head1 LICENSE
+#
+# Parts Copyright (c) 2000-2004 Ned Konz. All rights reserved.
+# Parts by Tye McQueen.
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the same terms as Perl.
+#
+# =head1 MAILING LIST
+#
+# Mark-Jason still maintains a mailing list. To join a low-volume mailing
+# list for announcements related to diff and Algorithm::Diff, send an
+# empty mail message to mjd-perl-diff-request@plover.com.
+# =head1 CREDITS
+#
+# Versions through 0.59 (and much of this documentation) were written by:
+#
+# Mark-Jason Dominus, mjd-perl-diff@plover.com
+#
+# This version borrows some documentation and routine names from
+# Mark-Jason's, but Diff.pm's code was completely replaced.
+#
+# This code was adapted from the Smalltalk code of Mario Wolczko
+# <mario@wolczko.com>, which is available at
+# ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
+#
+# C<sdiff> and C<traverse_balanced> were written by Mike Schilli
+# <m@perlmeister.com>.
+#
+# The algorithm is that described in
+# I<A Fast Algorithm for Computing Longest Common Subsequences>,
+# CACM, vol.20, no.5, pp.350-353, May 1977, with a few
+# minor improvements to improve the speed.
+#
+# Much work was done by Ned Konz (perl@bike-nomad.com).
+#
+# The OO interface and some other changes are by Tye McQueen.
+#
+EOAlgDiff
+# 2}}}
+ my $problems = 0;
+ $HAVE_Algorith_Diff = 0;
+ my $dir = "";
+ if ($opt_sdir) {
+ # write to the user-defined scratch directory
+ $dir = $opt_sdir;
+ } else {
+ # let File::Temp create a suitable temporary directory
+ $dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
+ }
+ print "Using temp dir [$dir] to install Algorithm::Diff\n" if $opt_v;
+ my $Algorithm_dir = "$dir/Algorithm";
+ my $Algorithm_Diff_dir = "$dir/Algorithm/Diff";
+ mkdir $Algorithm_dir ;
+ mkdir $Algorithm_Diff_dir;
+
+ my $OUT = new IO::File "$dir/Algorithm/Diff.pm", "w";
+ if (defined $OUT) {
+ print $OUT $Algorithm_Diff_Contents;
+ $OUT->close;
+ } else {
+ warn "Failed to install Algorithm/Diff.pm\n";
+ $problems = 1;
+ }
+
+ push @INC, $dir; # between this & Regexp::Common only need to do once
+ eval "use Algorithm::Diff qw / sdiff /";
+ $HAVE_Algorith_Diff = 1 unless $problems;
+} # 1}}}
+sub call_regexp_common { # {{{1
+ my ($ra_lines, $language ) = @_;
+ print "-> call_regexp_common\n" if $opt_v > 2;
+
+ Install_Regexp_Common() unless $HAVE_Rexexp_Common;
+
+ my $all_lines = join("", @{$ra_lines});
+
+ no strict 'vars';
+ # otherwise get:
+ # Global symbol "%RE" requires explicit package name at cloc line xx.
+ if ($all_lines =~ $RE{comment}{$language}) {
+ # Suppress "Use of uninitialized value in regexp compilation" that
+ # pops up when $1 is undefined--happens if there's a bug in the $RE
+ # This Pascal comment will trigger it:
+ # (* This is { another } test. **)
+ # Curiously, testing for "defined $1" breaks the substitution.
+ no warnings;
+ # remove comments
+ $all_lines =~ s/$1//g;
+ }
+ # a bogus use of %RE to avoid:
+ # Name "main::RE" used only once: possible typo at cloc line xx.
+ print scalar keys %RE if $opt_v < -20;
+#?#print "$all_lines\n";
+ print "<- call_regexp_common\n" if $opt_v > 2;
+ return split("\n", $all_lines);
+} # 1}}}
+sub plural_form { # {{{1
+ # For getting the right plural form on some English nouns.
+ my $n = shift @_;
+ if ($n == 1) { return ( 1, "" ); }
+ else { return ($n, "s"); }
+} # 1}}}
+sub matlab_or_objective_C { # {{{1
+ # Decide if code is MATLAB, Objective C, or MUMPS
+ my ($file , # in
+ $rh_Err , # in hash of error codes
+ $raa_errors , # out
+ $rs_language , # out
+ ) = @_;
+
+ print "-> matlab_or_objective_C\n" if $opt_v > 2;
+ # matlab markers:
+ # first line starts with "function"
+ # some lines start with "%"
+ # high marks for lines that start with [
+ #
+ # Objective C markers:
+ # must have at least two brace characters, { }
+ # has /* ... */ style comments
+ # some lines start with @
+ # some lines start with #include
+ #
+ # MUMPS:
+ # has ; comment markers
+ # do not match: \w+\s*=\s*\w
+ # lines begin with \s*\.?\w+\s+\w
+ # high marks for lines that start with \s*K\s+ or \s*Kill\s+
+
+ ${$rs_language} = "";
+ my $IN = new IO::File $file, "r";
+ if (!defined $IN) {
+ push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
+ return;
+ }
+
+ my $matlab_points = 0;
+ my $objective_C_points = 0;
+ my $mumps_points = 0;
+ my $has_braces = 0;
+ while (<$IN>) {
+ ++$has_braces if m/[{}]/;
+ ++$mumps_points if $. == 1 and m{^[A-Z]};
+ if (m{^\s*/\*}) { # /*
+ ++$objective_C_points;
+ --$matlab_points;
+ } elsif (m{^\s*\w+\s*=\s*}) { # definitely not MUMPS
+ --$mumps_points;
+ } elsif (m{^\s*\.?\w\s+\w}) {
+ ++$mumps_points;
+ } elsif (m{^\s*;}) {
+ ++$mumps_points;
+ } elsif (m{^\s*#include}) {
+ ++$objective_C_points;
+ --$matlab_points;
+ } elsif (m{^\s*@(interface|implementation|protocol|public|protected|private|end)\s}o) {
+ # Objective C without a doubt
+ $objective_C_points = 1;
+ $matlab_points = 0;
+ last;
+ } elsif (m{^\s*\[}) { # line starts with [ -- very matlab
+ $matlab_points += 5;
+ } elsif (m{^\sK(ill)?\s+}) {
+ $mumps_points += 5;
+ } elsif (m{^\s*function}) {
+ --$objective_C_points;
+ ++$matlab_points;
+ } elsif (m{^\s*%}) { # %
+ --$objective_C_points;
+ ++$matlab_points;
+ ++$mumps_points;
+ }
+ }
+ $IN->close;
+
+ print "<- matlab_or_objective_C(matlab=$matlab_points, C=$objective_C_points, mumps=$mumps_points)\n"
+ if $opt_v > 2;
+ $objective_C_points = -9.9e20 unless $has_braces >= 2;
+ if (($matlab_points > $objective_C_points) and
+ ($matlab_points > $mumps_points) ) {
+ ${$rs_language} = "MATLAB";
+ } elsif (($mumps_points > $objective_C_points) and
+ ($mumps_points > $matlab_points) ) {
+ ${$rs_language} = "MUMPS";
+ } else {
+ ${$rs_language} = "Objective C";
+ }
+
+} # 1}}}
+sub html_colored_text { # {{{1
+ # http://www.pagetutor.com/pagetutor/makapage/pics/net216-2.gif
+ my ($color, $text) = @_;
+#?#die "html_colored_text($text)";
+ if ($color =~ /^red$/i) {
+ $color = "#ff0000";
+ } elsif ($color =~ /^green$/i) {
+ $color = "#00ff00";
+ } elsif ($color =~ /^blue$/i) {
+ $color = "#0000ff";
+ } elsif ($color =~ /^grey$/i) {
+ $color = "#cccccc";
+ }
+# return "" unless $text;
+ return '<font color="' . $color . '">' . html_metachars($text) . "</font>";
+} # 1}}}
+sub html_metachars { # {{{1
+ # Replace HTML metacharacters with their printable forms.
+ # Future: use HTML-Encoder-0.00_04/lib/HTML/Encoder.pm
+ # from Fabiano Reese Righetti's HTML::Encoder module if
+ # this subroutine proves to be too simplistic.
+ my ($string, ) = shift @_;
+
+ my @in_chars = split(//, $string);
+ my @out_chars = ();
+ foreach my $c (@in_chars) {
+ if ($c eq '<') {
+ push @out_chars, '&lt;'
+ } elsif ($c eq '>') {
+ push @out_chars, '&gt;'
+ } elsif ($c eq '&') {
+ push @out_chars, '&amp;'
+ } else {
+ push @out_chars, $c;
+ }
+ }
+ return join "", @out_chars;
+} # 1}}}
+#x#sub diff_two_strings { # {{{1
+#x# # Compute the difference between two strings and return
+#x# # the strings with special markers prefixing characters
+#x# # that differ.
+#x# my ($text_1,
+#x# $text_2,
+#x# ) = @_;
+#x# my $MARKER = "\cA";
+#x#
+#x# my @chars_1 = split '', $text_1;
+#x# my @chars_2 = split '', $text_2;
+#x# my %changed_1 = ();
+#x# my %changed_2 = ();
+#x# my $diff = Algorithm::Diff->new ( \@chars_1, \@chars_2 );
+#x# while( $diff->Next() ) {
+#x# next if $diff->Same();
+#x# my $sep = "";
+#x# if ( ! $diff->Items(2) ) {
+#x# my ($a, $b, $c ) = $diff->Get(qw( Min1 Max1 Max2 ));
+#x# foreach ($a..$b) { $changed_1{$_} = 1; }
+#x# $changed_2{$c} = 1;
+#x# } elsif ( ! $diff->Items(1) ) {
+#x# my ($a, $b, $c ) = $diff->Get(qw( Max1 Min2 Max2 ));
+#x# $changed_1{$a} = 1;
+#x# foreach ($b..$c) { $changed_2{$_} = 1; }
+#x# } else {
+#x# $sep = "---\n";
+#x# my ($a, $b, $c, $d ) = $diff->Get(qw( Min1 Max1 Min2 Max2 ));
+#x# foreach ($a..$b) { $changed_1{$_} = 1; }
+#x# foreach ($c..$d) { $changed_2{$_} = 1; }
+#x# }
+#x# }
+#x# for (my $i = 0; $i < scalar @chars_1; $i++) {
+#x# $chars_1[$i] = $MARKER . $chars_1[$i];
+#x# }
+#x# for (my $i = 0; $i < scalar @chars_2; $i++) {
+#x# $chars_2[$i] = $MARKER . $chars_2[$i];
+#x# }
+#x# my $new_1 = join "", @chars_1;
+#x# my $new_2 = join "", @chars_2;
+#x# return ($new_1, $new_2);
+#x#} # 1}}}
+sub diff_two_arrays { # {{{1
+ my ($ra_lines_1 ,
+ $ra_lines_2 )
+ = @_;
+ # returns $raa_diff_1[0..n] = [ u | c | + | - , text ]
+ # $raa_diff_2[0..n] = [ u | c | + | - , text ]
+ # u = unchanged
+ # c = changed
+ # + = added
+ # - = removed
+ my ($raa_diff_1, $raa_diff_2);
+
+ my $n_no_change = 0;
+ my $n_modified = 0;
+ my $n_added = 0;
+ my $n_deleted = 0;
+ my @min_sdiff = ();
+my $NN = chr(27) . "[0m"; # normal
+my $BB = chr(27) . "[1m"; # bold
+
+ my @sdiffs = sdiff( $ra_lines_1, $ra_lines_2 );
+ foreach my $entry (@sdiffs) {
+ my ($out_1, $out_2) = ('', '');
+ if ($entry->[0] eq 'u') {
+ ++$n_no_change;
+ push @{$raa_diff_1}, [ 'u', $entry->[1]];
+ push @{$raa_diff_2}, [ 'u', $entry->[1]];
+ next;
+ }
+ if ($entry->[0] eq 'c') {
+ ++$n_modified;
+ push @{$raa_diff_1}, [ 'c', $entry->[1]];
+ push @{$raa_diff_2}, [ 'c', $entry->[2]];
+ } elsif ($entry->[0] eq '+') {
+ ++$n_added;
+ push @{$raa_diff_1}, [ '+', $entry->[1]];
+ push @{$raa_diff_2}, [ '+', $entry->[2]];
+ } elsif ($entry->[0] eq '-') {
+ ++$n_deleted;
+ push @{$raa_diff_1}, [ '-', $entry->[1]];
+ push @{$raa_diff_2}, [ '-', $entry->[2]];
+ } elsif ($entry->[0] eq 'u') {
+ } else { die "diff_two_arrays unknown entry->[0]=[$entry->[0]]\n"; }
+ }
+
+ return ($raa_diff_1, $raa_diff_2);
+} # 1}}}
+#x#sub test_alg_diff { # {{{1
+#x# my ($file_1 ,
+#x# $file_2 )
+#x# = @_;
+#x# my $fh_1 = new IO::File $file_1, "r";
+#x# die "Unable to read $file_1: $!\n" unless defined $fh_1;
+#x# chomp(my @lines_1 = <$fh_1>);
+#x# $fh_1->close;
+#x#
+#x# my $fh_2 = new IO::File $file_2, "r";
+#x# die "Unable to read $file_2: $!\n" unless defined $fh_2;
+#x# chomp(my @lines_2 = <$fh_2>);
+#x# $fh_2->close;
+#x#
+#x# my $n_no_change = 0;
+#x# my $n_modified = 0;
+#x# my $n_added = 0;
+#x# my $n_deleted = 0;
+#x# my @min_sdiff = ();
+#x#my $NN = chr(27) . "[0m"; # normal
+#x#my $BB = chr(27) . "[1m"; # bold
+#x#
+#x# my @sdiffs = sdiff( \@lines_1, \@lines_2 );
+#x# foreach my $entry (@sdiffs) {
+#x# my ($out_1, $out_2) = ('', '');
+#x# if ($entry->[0] eq 'u') {
+#x# ++$n_no_change;
+#x# # $out_1 = $entry->[1];
+#x# # $out_2 = $entry->[2];
+#x# next;
+#x# }
+#x## push @min_sdiff, $entry;
+#x# if ($entry->[0] eq 'c') {
+#x# ++$n_modified;
+#x# ($out_1, $out_2) = diff_two_strings($entry->[1], $entry->[2]);
+#x# $out_1 =~ s/\cA(\w)/${BB}$1${NN}/g;
+#x# $out_2 =~ s/\cA(\w)/${BB}$1${NN}/g;
+#x# # $out_1 =~ s/\cA//g;
+#x# # $out_2 =~ s/\cA//g;
+#x# } elsif ($entry->[0] eq '+') {
+#x# ++$n_added;
+#x# $out_1 = $entry->[1];
+#x# $out_2 = $entry->[2];
+#x# } elsif ($entry->[0] eq '-') {
+#x# ++$n_deleted;
+#x# $out_1 = $entry->[1];
+#x# $out_2 = $entry->[2];
+#x# } elsif ($entry->[0] eq 'u') {
+#x# } else { die "unknown entry->[0]=[$entry->[0]]\n"; }
+#x# printf "%-80s | %s\n", $out_1, $out_2;
+#x# }
+#x#
+#x## foreach my $entry (@min_sdiff) {
+#x## printf "DIFF: %s %s %s\n", @{$entry};
+#x## }
+#x#} # 1}}}
+sub write_comments_to_html { # {{{1
+ my ($filename , # in
+ $rah_diff_L , # in see routine file_diff() for explanation
+ $rah_diff_R , # in see routine file_diff() for explanation
+ $rh_blank , # in location and counts of blank lines
+ ) = @_;
+
+ print "-> write_comments_to_html($filename)\n" if $opt_v > 2;
+ my $file = $filename . ".html";
+#use Data::Dumper;
+#print Dumper("rah_diff_L", $rah_diff_L, "rah_diff_R", $rah_diff_R);
+ my $OUT = new IO::File $file, "w";
+ if (!defined $OUT) {
+ warn "Unable to write to $file\n";
+ print "<- write_comments_to_html\n" if $opt_v > 2;
+ return;
+ }
+
+ my $html_out = html_header($filename);
+
+ my $comment_line_number = 0;
+ for (my $i = 0; $i < scalar @{$rah_diff_R}; $i++) {
+ if (defined $rh_blank->{$i}) {
+ foreach (1..$rh_blank->{$i}) {
+ $html_out .= "<!-- blank -->\n";
+ }
+ }
+ my $line_num = "";
+ my $pre = "";
+ my $post = "</span>";
+die "undef rah_diff_R[$i]{type} " unless defined $rah_diff_R->[$i]{type};
+ if ($rah_diff_R->[$i]{type} eq 'nonexist') {
+ ++$comment_line_number;
+ $line_num = '<span class="clinenum">' . $comment_line_number . $post;
+ $pre = '<span class="comment">';
+ $html_out .= $line_num;
+ $html_out .= $pre .
+ html_metachars($rah_diff_L->[$i]{char}) .
+ $post . "\n";
+ next;
+ }
+ if ($rah_diff_R->[$i]{type} eq 'code' and
+ $rah_diff_R->[$i]{desc} eq 'same') {
+ # entire line remains as-is
+ $line_num = '<span class="linenum">' .
+ $rah_diff_R->[$i]{lnum} . $post;
+ $pre = '<span class="normal">';
+ $html_out .= $line_num;
+ $html_out .= $pre .
+ html_metachars($rah_diff_R->[$i]{char}) . $post;
+ } elsif ($rah_diff_R->[$i]{type} eq 'code') { # code+comments
+
+ $line_num = '<span class="linenum">' .
+ $rah_diff_R->[$i]{lnum} . $post;
+ $html_out .= $line_num;
+
+ my @strings = @{$rah_diff_R->[$i]{char}{strings}};
+ my @type = @{$rah_diff_R->[$i]{char}{type}};
+ for (my $i = 0; $i < scalar @strings; $i++) {
+ if ($type[$i] eq 'u') {
+ $pre = '<span class="normal">';
+ } else {
+ $pre = '<span class="comment">';
+ }
+ $html_out .= $pre . html_metachars($strings[$i]) . $post;
+ }
+# print Dumper(@strings, @type); die;
+
+ } elsif ($rah_diff_R->[$i]{type} eq 'comment') {
+ $line_num = '<span class="clinenum">' . $comment_line_number . $post;
+ # entire line is a comment
+ $pre = '<span class="comment">';
+ $html_out .= $pre .
+ html_metachars($rah_diff_R->[$i]{char}) . $post;
+ }
+#printf "%-30s %s %-30s\n", $line_1, $separator, $line_2;
+ $html_out .= "\n";
+ }
+
+ $html_out .= html_end();
+
+ my $out_file = "$filename.html";
+ open OUT, ">$out_file" or die "Cannot write to $out_file $!\n";
+ print OUT $html_out;
+ close OUT;
+ print "Wrote $out_file\n" unless $opt_quiet;
+ $OUT->close;
+
+ print "<- write_comments_to_html\n" if $opt_v > 2;
+} # 1}}}
+sub file_diff { # {{{1
+ my ($ra_lines_L , # in array of lines in Left file (no blank lines)
+ $ra_lines_R , # in array of lines in Right file (no blank lines)
+ $mode , # in "comment" | "revision"
+ $rah_diff_L , # in/out if mode = 'revision'
+ # out if mode = 'comment'
+ $rah_diff_R , # in/out if mode = 'revision'
+ # out if mode = 'comment'
+ $rh_count , # out count{X}{Y} = number of lines
+ # X = code | comment | blank
+ # Y = values of {desc} in rah_diff
+ # (= same | added | removed | modified)
+ # when mode = 'comment', only Y=same is used
+ ) = @_;
+
+ # This routine operates in two ways:
+ # A. Computes diffs of the same file with and without comments.
+ # This is used to classify lines as code, comments, or blank.
+ # B. Computes diffs of two revisions of a file. This method
+ # requires a prior run of method A using the older version
+ # of the file because it needs lines to be classified.
+
+ # $rah_diff structure:
+ # An array with n entries where n equals the number of lines in
+ # an sdiff of the two files. Each entry in the array describes
+ # the contents of the corresponding line in file Left and file Right:
+ # diff[]{type} = blank | code | code+comment | comment | nonexist
+ # {lnum} = line number within the original file (1-based)
+ # {desc} = same | added | removed | modified
+ # {char} = the input line unless {desc} = 'modified' in
+ # which case
+ # {char}{strings} = [ substrings ]
+ # {char}{type} = [ disposition (added, removed, etc)]
+ #
+
+ print "-> file_diff()\n" if $opt_v > 2;
+
+ my @sdiffs = sdiff($ra_lines_L, $ra_lines_R);
+#print Dumper(@sdiffs);
+#print Dumper("sdiffs", \@sdiffs);
+ my $COMMENT_MODE = 0;
+ $COMMENT_MODE = 1 if $mode eq "comment";
+
+ my $n_L = 0;
+ my $n_R = 0;
+ my $n_sdiff = 0; # index to $rah_diff_L, $rah_diff_R
+ if ($COMMENT_MODE) {
+ @{$rah_diff_L} = ();
+ @{$rah_diff_R} = ();
+ }
+ foreach my $triple (@sdiffs) {
+ my $flag = $triple->[0];
+ my $line_L = $triple->[1];
+ my $line_R = $triple->[2];
+ $rah_diff_L->[$n_sdiff]{char} = $line_L;
+ $rah_diff_R->[$n_sdiff]{char} = $line_R;
+ if ($flag eq 'u') { # u = unchanged
+ ++$n_L;
+ ++$n_R;
+ if ($COMMENT_MODE) {
+ # line exists in both with & without comments, must be code
+ $rah_diff_L->[$n_sdiff]{type} = "code";
+ $rah_diff_R->[$n_sdiff]{type} = "code";
+ }
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
+ $rah_diff_L->[$n_sdiff]{desc} = "same";
+ $rah_diff_R->[$n_sdiff]{desc} = "same";
+ $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+ $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+ } elsif ($flag eq 'c') { # c = changed
+ ++$n_L;
+ ++$n_R;
+
+ if ($COMMENT_MODE) {
+ # line has text both with & without comments;
+ # count as code
+ $rah_diff_L->[$n_sdiff]{type} = "code";
+ $rah_diff_R->[$n_sdiff]{type} = "code";
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
+ } else {
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{modified};
+ }
+
+ my @chars_L = split '', $line_L;
+ my @chars_R = split '', $line_R;
+ my @inline_sdiffs = sdiff( \@chars_L, \@chars_R );
+#use Data::Dumper::Simple;
+#if ($n_R == 6 or $n_R == 1 or $n_R == 2) {
+#print "L=[$line_L]\n";
+#print "R=[$line_R]\n";
+#print Dumper(@chars_L, @chars_R, @inline_sdiffs);
+#}
+ my @index = ();
+ foreach my $il_triple (@inline_sdiffs) {
+ # make an array of u|c|+|- corresponding
+ # to each character
+ push @index, $il_triple->[0];
+ }
+#print Dumper(@index); die;
+ # expect problems if arrays @index and $inline_sdiffs[1];
+ # (@{$inline_sdiffs->[1]} are the characters of line_L)
+ # aren't the same length
+ my $prev_type = $index[0];
+ my @strings = (); # blocks of consecutive code or comment
+ my @type = (); # u (=code) or c (=comment)
+ my $j_str = 0;
+ $strings[$j_str] .= $chars_L[0];
+ $type[$j_str] = $prev_type;
+ for (my $i = 1; $i < scalar @chars_L; $i++) {
+ if ($index[$i] ne $prev_type) {
+ ++$j_str;
+#print "change at j_str=$j_str type=$index[$i]\n";
+ $type[$j_str] = $index[$i];
+ $prev_type = $index[$i];
+ }
+ $strings[$j_str] .= $chars_L[$i];
+ }
+# print Dumper(@strings, @type); die;
+ delete $rah_diff_R->[$n_sdiff]{char};
+ @{$rah_diff_R->[$n_sdiff]{char}{strings}} = @strings;
+ @{$rah_diff_R->[$n_sdiff]{char}{type}} = @type;
+ $rah_diff_L->[$n_sdiff]{desc} = "modified";
+ $rah_diff_R->[$n_sdiff]{desc} = "modified";
+ $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+ $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+
+ } elsif ($flag eq '+') { # + = added
+ ++$n_R;
+ if ($COMMENT_MODE) {
+ # should never get here
+ warn "file_diff: diff failure (diff says the\n";
+ warn "comment-free file has added lines).\n";
+ warn "$n_sdiff $line_L\n";
+ last;
+ }
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{added};
+ $rah_diff_L->[$n_sdiff]{type} = "nonexist";
+ $rah_diff_L->[$n_sdiff]{desc} = "removed";
+ $rah_diff_R->[$n_sdiff]{desc} = "added";
+ $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
+ } elsif ($flag eq '-') { # - = removed
+ ++$n_L;
+ if ($COMMENT_MODE) {
+ # line must be comment because blanks already gone
+ $rah_diff_L->[$n_sdiff]{type} = "comment";
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
+ } else {
+ ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{removed};
+ }
+ $rah_diff_R->[$n_sdiff]{type} = "nonexist";
+ $rah_diff_R->[$n_sdiff]{desc} = "removed";
+ $rah_diff_L->[$n_sdiff]{desc} = "added";
+ $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
+ }
+#printf "%-30s %s %-30s\n", $line_L, $separator, $line_R;
+ ++$n_sdiff;
+ }
+
+ print "<- file_diff\n" if $opt_v > 2;
+} # 1}}}
+sub align_by_pairs { # {{{1
+ my ($rh_file_list_L , # in
+ $rh_file_list_R , # in
+ $rs_nFiles_same , # out
+ $rs_nFiles_added , # out
+ $rs_nFiles_removed , # out
+ $rs_nFiles_modified , # out
+ $ra_modified_file_list , # out
+ ) = @_;
+ @{$ra_modified_file_list} = ();
+
+ my @files_L = keys %{$rh_file_list_L};
+ my @files_R = keys %{$rh_file_list_R};
+ push @{$ra_modified_file_list}, [ $files_L[0], $files_R[0] ];
+} # 1}}}
+sub html_header { # {{{1
+ my ($title , ) = @_;
+
+ print "-> html_header\n" if $opt_v > 2;
+ return
+'<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<meta name="GENERATOR" content="cloc http://cloc.sourceforge.net">
+' .
+"
+<!-- Created by $script v$VERSION -->
+<title>$title</title>
+" .
+'
+<style TYPE="text/css">
+<!--
+ body {
+ color: black;
+ background-color: white;
+ font-family: monospace
+ }
+
+ .whitespace {
+ background-color: gray;
+ }
+
+ .comment {
+ color: gray;
+ font-style: italic;
+ }
+
+ .clinenum {
+ color: red;
+ }
+
+ .linenum {
+ color: green;
+ }
+ -->
+</style>
+</head>
+<body>
+<pre><tt>
+';
+ print "<- html_header\n" if $opt_v > 2;
+} # 1}}}
+sub html_end { # {{{1
+return
+'</tt></pre>
+</body>
+</html>
+';
+} # 1}}}
+sub die_unknown_lang { # {{{1
+ my ($lang, $option_name) = @_;
+ die "Unknown language '$lang' used with $option_name option. " .
+ "The command\n $script --show-lang\n" .
+ "will print all recognized languages.\n" ;
+} # 1}}}
+sub unicode_file { # {{{1
+ my $file = shift @_;
+
+ return 0 if (-s $file > 2_000_000);
+ # don't bother trying to test binary files bigger than 2 MB
+
+ my $IN = new IO::File $file, "r";
+ if (!defined $IN) {
+ warn "Unable to read $file; ignoring.\n";
+ return 0;
+ }
+ my @lines = <$IN>;
+ $IN->close;
+
+ if (unicode_to_ascii( join('', @lines) )) {
+ return 1;
+ } else {
+ return 0;
+ }
+
+} # 1}}}
+sub unicode_to_ascii { # {{{1
+ my $string = shift @_;
+
+ # A trivial attempt to convert Microsoft Windows style Unicode
+ # files into ASCII. These files exhibit the following byte
+ # sequence:
+ # byte 1: 255
+ # byte 2: 254
+ # byte 3: ord of ASCII character
+ # byte 4: 0
+ # byte 3+i: ord of ASCII character
+ # byte 4+i: 0
+
+ my @ascii = ();
+ my $looks_like_unicode = 1;
+ my $length = length $string;
+# print "length=$length\n";
+ if ($length <= 3) {
+ $looks_like_unicode = 0;
+ return '';
+ }
+ my @unicode = split(//, $string);
+
+ for (my $i = 2; $i < $length; $i += 2) {
+# print "examining [$unicode[$i]] ord ", ord($unicode[$i]), "\n";
+ if (32 <= ord($unicode[$i]) and ord($unicode[$i]) <= 127
+ or ord($unicode[$i]) == 13
+ or ord($unicode[$i]) == 10
+ or ord($unicode[$i]) == 9
+ ) {
+ push @ascii, $unicode[$i];
+# print "adding [$unicode[$i]]\n";
+ } else {
+ $looks_like_unicode = 0;
+ last;
+ }
+ if ($i+1 < $length) {
+ if (!$unicode[$i+1]) {
+ $looks_like_unicode = 0;
+ last;
+ }
+ }
+ }
+ if ($looks_like_unicode) {
+ return join("", @ascii);
+ } else {
+ return '';
+ }
+} # 1}}}
+
+# subroutines copied from SLOCCount
+my %lex_files = (); # really_is_lex()
+my %expect_files = (); # really_is_expect()
+my %pascal_files = (); # really_is_pascal(), really_is_incpascal()
+my %php_files = (); # really_is_php()
+sub really_is_lex { # {{{1
+# Given filename, returns TRUE if its contents really is lex.
+# lex file must have "%%", "%{", and "%}".
+# In theory, a lex file doesn't need "%{" and "%}", but in practice
+# they all have them, and requiring them avoid mislabeling a
+# non-lexfile as a lex file.
+
+ my $filename = shift;
+ chomp($filename);
+
+ my $is_lex = 0; # Value to determine.
+ my $percent_percent = 0;
+ my $percent_opencurly = 0;
+ my $percent_closecurly = 0;
+
+ # Return cached result, if available:
+ if ($lex_files{$filename}) { return $lex_files{$filename};}
+
+ open(LEX_FILE, "<$filename") ||
+ die "Can't open $filename to determine if it's lex.\n";
+ while(<LEX_FILE>) {
+ $percent_percent++ if (m/^\s*\%\%/);
+ $percent_opencurly++ if (m/^\s*\%\{/);
+ $percent_closecurly++ if (m/^\s*\%\}/);
+ }
+ close(LEX_FILE);
+
+ if ($percent_percent && $percent_opencurly && $percent_closecurly)
+ {$is_lex = 1;}
+
+ $lex_files{$filename} = $is_lex; # Store result in cache.
+
+ return $is_lex;
+} # 1}}}
+sub really_is_expect { # {{{1
+# Given filename, returns TRUE if its contents really are Expect.
+# Many "exp" files (such as in Apache and Mesa) are just "export" data,
+# summarizing something else # (e.g., its interface).
+# Sometimes (like in RPM) it's just misc. data.
+# Thus, we need to look at the file to determine
+# if it's really an "expect" file.
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it's Expect _IF_ it:
+# 1. has "load_lib" command and either "#" comments or {}.
+# 2. {, }, and one of: proc, if, [...], expect
+
+ my $is_expect = 0; # Value to determine.
+
+ my $begin_brace = 0; # Lines that begin with curly braces.
+ my $end_brace = 0; # Lines that begin with curly braces.
+ my $load_lib = 0; # Lines with the Load_lib command.
+ my $found_proc = 0;
+ my $found_if = 0;
+ my $found_brackets = 0;
+ my $found_expect = 0;
+ my $found_pound = 0;
+
+ # Return cached result, if available:
+ if ($expect_files{$filename}) { return expect_files{$filename};}
+
+ open(EXPECT_FILE, "<$filename") ||
+ die "Can't open $filename to determine if it's expect.\n";
+ while(<EXPECT_FILE>) {
+
+ if (m/#/) {$found_pound++; s/#.*//;}
+ if (m/^\s*\{/) { $begin_brace++;}
+ if (m/\{\s*$/) { $begin_brace++;}
+ if (m/^\s*\}/) { $end_brace++;}
+ if (m/\};?\s*$/) { $end_brace++;}
+ if (m/^\s*load_lib\s+\S/) { $load_lib++;}
+ if (m/^\s*proc\s/) { $found_proc++;}
+ if (m/^\s*if\s/) { $found_if++;}
+ if (m/\[.*\]/) { $found_brackets++;}
+ if (m/^\s*expect\s/) { $found_expect++;}
+ }
+ close(EXPECT_FILE);
+
+ if ($load_lib && ($found_pound || ($begin_brace && $end_brace)))
+ {$is_expect = 1;}
+ if ( $begin_brace && $end_brace &&
+ ($found_proc || $found_if || $found_brackets || $found_expect))
+ {$is_expect = 1;}
+
+ $expect_files{$filename} = $is_expect; # Store result in cache.
+
+ return $is_expect;
+} # 1}}}
+sub really_is_pascal { # {{{1
+# Given filename, returns TRUE if its contents really are Pascal.
+
+# This isn't as obvious as it seems.
+# Many ".p" files are Perl files
+# (such as /usr/src/redhat/BUILD/ispell-3.1/dicts/czech/glob.p),
+# others are C extractions
+# (such as /usr/src/redhat/BUILD/linux/include/linux/umsdos_fs.p
+# and some files in linuxconf).
+# However, test files in "p2c" really are Pascal, for example.
+
+# Note that /usr/src/redhat/BUILD/ucd-snmp-4.1.1/ov/bitmaps/UCD.20.p
+# is actually C code. The heuristics determine that they're not Pascal,
+# but because it ends in ".p" it's not counted as C code either.
+# I believe this is actually correct behavior, because frankly it
+# looks like it's automatically generated (it's a bitmap expressed as code).
+# Rather than guess otherwise, we don't include it in a list of
+# source files. Let's face it, someone who creates C files ending in ".p"
+# and expects them to be counted by default as C files in SLOCCount needs
+# their head examined. I suggest examining their head
+# with a sucker rod (see syslogd(8) for more on sucker rods).
+
+# This heuristic counts as Pascal such files such as:
+# /usr/src/redhat/BUILD/teTeX-1.0/texk/web2c/tangleboot.p
+# Which is hand-generated. We don't count woven documents now anyway,
+# so this is justifiable.
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it's Pascal _IF_ it has all of the following
+# (ignoring {...} and (*...*) comments):
+# 1. "^..program NAME" or "^..unit NAME",
+# 2. "procedure", "function", "^..interface", or "^..implementation",
+# 3. a "begin", and
+# 4. it ends with "end.",
+#
+# Or it has all of the following:
+# 1. "^..module NAME" and
+# 2. it ends with "end.".
+#
+# Or it has all of the following:
+# 1. "^..program NAME",
+# 2. a "begin", and
+# 3. it ends with "end.".
+#
+# The "end." requirements in particular filter out non-Pascal.
+#
+# Note (jgb): this does not detect Pascal main files in fpc, like
+# fpc-1.0.4/api/test/testterminfo.pas, which does not have "program" in
+# it
+
+ my $is_pascal = 0; # Value to determine.
+
+ my $has_program = 0;
+ my $has_unit = 0;
+ my $has_module = 0;
+ my $has_procedure_or_function = 0;
+ my $found_begin = 0;
+ my $found_terminating_end = 0;
+ my $has_begin = 0;
+
+ # Return cached result, if available:
+ if ($pascal_files{$filename}) { return pascal_files{$filename};}
+
+ open(PASCAL_FILE, "<$filename") ||
+ die "Can't open $filename to determine if it's pascal.\n";
+ while(<PASCAL_FILE>) {
+ s/\{.*?\}//g; # Ignore {...} comments on this line; imperfect, but effective.
+ s/\(\*.*?\*\)//g; # Ignore (*...*) comments on this line; imperfect, but effective.
+ if (m/\bprogram\s+[A-Za-z]/i) {$has_program=1;}
+ if (m/\bunit\s+[A-Za-z]/i) {$has_unit=1;}
+ if (m/\bmodule\s+[A-Za-z]/i) {$has_module=1;}
+ if (m/\bprocedure\b/i) { $has_procedure_or_function = 1; }
+ if (m/\bfunction\b/i) { $has_procedure_or_function = 1; }
+ if (m/^\s*interface\s+/i) { $has_procedure_or_function = 1; }
+ if (m/^\s*implementation\s+/i) { $has_procedure_or_function = 1; }
+ if (m/\bbegin\b/i) { $has_begin = 1; }
+ # Originally I said:
+ # "This heuristic fails if there are multi-line comments after
+ # "end."; I haven't seen that in real Pascal programs:"
+ # But jgb found there are a good quantity of them in Debian, specially in
+ # fpc (at the end of a lot of files there is a multiline comment
+ # with the changelog for the file).
+ # Therefore, assume Pascal if "end." appears anywhere in the file.
+ if (m/end\.\s*$/i) {$found_terminating_end = 1;}
+# elsif (m/\S/) {$found_terminating_end = 0;}
+ }
+ close(PASCAL_FILE);
+
+ # Okay, we've examined the entire file looking for clues;
+ # let's use those clues to determine if it's really Pascal:
+
+ if ( ( ($has_unit || $has_program) && $has_procedure_or_function &&
+ $has_begin && $found_terminating_end ) ||
+ ( $has_module && $found_terminating_end ) ||
+ ( $has_program && $has_begin && $found_terminating_end ) )
+ {$is_pascal = 1;}
+
+ $pascal_files{$filename} = $is_pascal; # Store result in cache.
+
+ return $is_pascal;
+} # 1}}}
+sub really_is_incpascal { # {{{1
+# Given filename, returns TRUE if its contents really are Pascal.
+# For .inc files (mainly seen in fpc)
+
+ my $filename = shift;
+ chomp($filename);
+
+# The heuristic is as follows: it is Pacal if any of the following:
+# 1. really_is_pascal returns true
+# 2. Any usual reserverd word is found (program, unit, const, begin...)
+
+ # If the general routine for Pascal files works, we have it
+ if (&really_is_pascal ($filename)) {
+ $pascal_files{$filename} = 1;
+ return 1;
+ }
+
+ my $is_pascal = 0; # Value to determine.
+ my $found_begin = 0;
+
+ open(PASCAL_FILE, "<$filename") ||
+ die "Can't open $filename to determine if it's pascal.\n";
+ while(<PASCAL_FILE>) {
+ s/\{.*?\}//g; # Ignore {...} comments on this line; imperfect, but effective.
+ s/\(\*.*?\*\)//g; # Ignore (*...*) comments on this line; imperfect, but effective.
+ if (m/\bprogram\s+[A-Za-z]/i) {$is_pascal=1;}
+ if (m/\bunit\s+[A-Za-z]/i) {$is_pascal=1;}
+ if (m/\bmodule\s+[A-Za-z]/i) {$is_pascal=1;}
+ if (m/\bprocedure\b/i) {$is_pascal = 1; }
+ if (m/\bfunction\b/i) {$is_pascal = 1; }
+ if (m/^\s*interface\s+/i) {$is_pascal = 1; }
+ if (m/^\s*implementation\s+/i) {$is_pascal = 1; }
+ if (m/\bconstant\s+/i) {$is_pascal=1;}
+ if (m/\bbegin\b/i) { $found_begin = 1; }
+ if ((m/end\.\s*$/i) && ($found_begin = 1)) {$is_pascal = 1;}
+ if ($is_pascal) {
+ last;
+ }
+ }
+
+ close(PASCAL_FILE);
+ $pascal_files{$filename} = $is_pascal; # Store result in cache.
+ return $is_pascal;
+} # 1}}}
+sub really_is_php { # {{{1
+# Given filename, returns TRUE if its contents really is php.
+
+ my $filename = shift;
+ chomp($filename);
+
+ my $is_php = 0; # Value to determine.
+ # Need to find a matching pair of surrounds, with ending after beginning:
+ my $normal_surround = 0; # <?; bit 0 = <?, bit 1 = ?>
+ my $script_surround = 0; # <script..>; bit 0 = <script language="php">
+ my $asp_surround = 0; # <%; bit 0 = <%, bit 1 = %>
+
+ # Return cached result, if available:
+ if ($php_files{$filename}) { return $php_files{$filename};}
+
+ open(PHP_FILE, "<$filename") ||
+ die "Can't open $filename to determine if it's php.\n";
+ while(<PHP_FILE>) {
+ if (m/\<\?/) { $normal_surround |= 1; }
+ if (m/\?\>/ && ($normal_surround & 1)) { $normal_surround |= 2; }
+ if (m/\<script.*language="?php"?/i) { $script_surround |= 1; }
+ if (m/\<\/script\>/i && ($script_surround & 1)) { $script_surround |= 2; }
+ if (m/\<\%/) { $asp_surround |= 1; }
+ if (m/\%\>/ && ($asp_surround & 1)) { $asp_surround |= 2; }
+ }
+ close(PHP_FILE);
+
+ if ( ($normal_surround == 3) || ($script_surround == 3) ||
+ ($asp_surround == 3)) {
+ $is_php = 1;
+ }
+
+ $php_files{$filename} = $is_php; # Store result in cache.
+
+ return $is_php;
+} # 1}}}
+__END__
+mode values (stat $item)[2]
+ Unix Windows
+file: 33188 33206
+dir : 16832 16895
+link: 33261 33206
+pipe: 4544 null
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/cloc-1.04.pl
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4 (revision 1522570)
@@ -0,0 +1,3 @@
+[Project]
+Name=SlocPlugin
+Manager=KDevCMakeManager
Index: tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/sloc/kdevsloc.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevSloc" version="1">
+</kpartgui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop (revision 1522570)
@@ -0,0 +1,77 @@
+[Desktop Entry]
+Type=Service
+Exec=blubb
+Comment=This plugin allows collaboration
+Comment[bs]=Ovaj dodatak omogućava sarađivanje
+Comment[ca]=Aquest connector permet la col·laboració
+Comment[ca@valencia]=Aquest connector permet la col·laboració
+Comment[de]=Dieses Modul ermöglicht die Zusammenarbeit
+Comment[en_GB]=This plugin allows collaboration
+Comment[es]=Este complemento permite colaboración
+Comment[et]=See plugin võimaldab koostööd
+Comment[fr]=Ce module externe permet de travailler en collaboration
+Comment[gl]=Este complemento permite traballar colaborativamente.
+Comment[hu]=Ez a bővítmény lehetővé teszi az együttműködést
+Comment[it]=Questa estensione consente la collaborazione
+Comment[nl]=Deze plugin maakt samenwerken mogelijk
+Comment[pl]=Wtyczka ta pozwala na kolaborację
+Comment[pt]=Este 'plugin' permite a colaboração
+Comment[pt_BR]=Este plugin permite a colaboração
+Comment[sv]=Insticksprogrammet tillhandahåller stöd för samarbete
+Comment[uk]=За допомогою цього додатка можна здійснювати співпрацю
+Comment[x-test]=xxThis plugin allows collaborationxx
+Name=Teamwork
+Name[bs]=Timski rad
+Name[ca]=Treball en equip
+Name[ca@valencia]=Treball en equip
+Name[de]=Zusammenarbeit
+Name[en_GB]=Teamwork
+Name[es]=Trabajo en equipo
+Name[et]=Meeskonnatöö
+Name[fr]=Équipe de travail
+Name[ga]=Cur Le Chéile
+Name[gl]=Traballo en equipo
+Name[hu]=Csapatmunka
+Name[it]=Lavoro di squadra
+Name[nl]=Teamwork
+Name[pl]=Teamwork
+Name[pt]=Trabalho em Equipa
+Name[pt_BR]=Trabalho em equipe
+Name[sk]=Tímová práca
+Name[sv]=Lagarbete
+Name[ug]=ھەمكارلىشىپ ئىشلەش
+Name[uk]=Командна робота
+Name[x-test]=xxTeamworkxx
+GenericName=Teamwork
+GenericName[bs]=Timski rad
+GenericName[ca]=Treball d'equip
+GenericName[ca@valencia]=Treball d'equip
+GenericName[de]=Zusammenarbeit
+GenericName[en_GB]=Teamwork
+GenericName[es]=Trabajo en equipo
+GenericName[et]=Meeskonnatöö
+GenericName[fr]=L'équipe de travail
+GenericName[ga]=Cur Le Chéile
+GenericName[gl]=Equipo de traballo
+GenericName[hu]=Csapatmunka
+GenericName[it]=Lavoro di squadra
+GenericName[nds]=Koppelarbeit
+GenericName[nl]=Teamwork
+GenericName[pl]=Teamwork
+GenericName[pt]=Trabalho em equipa
+GenericName[pt_BR]=Trabalho em equipe
+GenericName[sk]=Tímová práca
+GenericName[sv]=Lagarbete
+GenericName[tr]=Takım çalışması
+GenericName[ug]=ھەمكارلىشىپ ئىشلەش
+GenericName[uk]=Командна робота
+GenericName[x-test]=xxTeamworkxx
+ServiceTypes=KDevelop/Plugin
+X-KDE-Library=kdevteamwork
+X-KDE-PluginInfo-Name=kdevteamwork
+X-KDE-PluginInfo-Author=David Nolden
+X-KDE-PluginInfo-Version=0.15
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=7
+X-KDevelop-Category=Global
+X-KDevelop-Mode=GUI
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.cpp (revision 1522570)
@@ -0,0 +1,1214 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "editpatch.h"
+
+#include <kmimetype.h>
+#include <klineedit.h>
+#include <kmimetypechooser.h>
+#include <kmimetypetrader.h>
+#include <k3process.h>
+#include <krandom.h>
+#include <QTabWidget>
+#include <QMenu>
+#include <QFile>
+#include <QTimer>
+#include <QMutexLocker>
+#include <QPersistentModelIndex>
+//#include <lib/kdevappintterface.h>
+#include "patchesmanager.h"
+#include <kfiledialog.h>
+#include "kdevteamwork.h"
+#include <interfaces/idocument.h>
+//#include "kdevdiffinterface.h"
+#include "kdevteamworkplugin.h"
+#include "collaborationmanager.h"
+#include <QStandardItemModel>
+#include <interfaces/icore.h>
+#include "serializationutils.h"
+#include "kdevteamwork_user.h"
+#include "messagemanager.h"
+#include "lib/network/messagetypeset.h"
+#include "kdevteamwork_helpers.h"
+#include "teamworkfoldermanager.h"
+#include <kde_terminal_interface.h>
+#include <kparts/part.h>
+#include <kparts/factory.h>
+#include <kservice.h>
+#include <kdialog.h>
+
+#include "lib/libdiff2/komparemodellist.h"
+#include "lib/libdiff2/kompare.h"
+#include <kmessagebox.h>
+#include <QMetaType>
+#include <QVariant>
+#include "lib/libdiff2/diffsettings.h"
+#include <ktexteditor/cursor.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+#include <ktexteditor/markinterface.h>
+#include <ktexteditor/smartinterface.h>
+#include <interfaces/idocumentcontroller.h>
+
+#include "kdevteamwork_client.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+///Whether arbitrary exceptions that occurred while diff-parsing within the library should be caught
+#define CATCHLIBDIFF
+
+using namespace KDevelop;
+
+QString getDefaultExtension( const QStringList& patterns );
+
+Q_DECLARE_METATYPE( const Diff2::DiffModel* )
+
+EditPatch::EditPatch( PatchesManager* parent, LocalPatchSourcePointer patch, bool local ) : QObject( parent ), SafeLogger( parent->teamwork() ->logger(), "EditPatch: " ), m_actionState( LocalPatchSource::Unknown ), m_parent( parent ), m_editingPatch( patch ), m_editPatchLocal( local ), m_editDlg( 0 ), m_reversed( false ), m_started( false ), m_isSource( false ) {
+ m_updateKompareTimer = new QTimer( this );
+ m_updateKompareTimer->setSingleShot( true );
+ connect( m_updateKompareTimer, SIGNAL( timeout() ), this, SLOT( updateKompareModel() ) );
+ showEditDialog();
+ if ( m_editingPatch )
+ fillEditFromPatch();
+ m_started = true;
+}
+
+EditPatch::~EditPatch() {
+ removeHighlighting();
+}
+
+void EditPatch::slotEditOk() {
+
+ LocalPatchSourcePointer p = patchFromEdit();
+
+ if ( p && !m_parent->hasPatch( p ) )
+ m_parent->addPatch( p );
+ //emit dialogClosed( this );
+ emit stateChanged( this );
+}
+
+void EditPatch::slotEditCancel() {
+ //emit dialogClosed( this );
+}
+
+LocalPatchSourcePointer EditPatch::patchFromEdit() {
+ if ( !m_editDlg )
+ return 0;
+ LocalPatchSourcePointer::Locked ps;
+
+ if ( m_editingPatch )
+ ps = m_editingPatch;
+ else {
+ ps = new LocalPatchSource();
+ ps->userIdentity = m_parent->teamwork() ->currentUserIdentity();
+ }
+
+ if ( !ps ) {
+ err() << "could not lock edited patch";
+ return 0;
+ }
+
+ LocalPatchSource& ls( *ps );
+ ls.name = ~m_editPatch.name->text();
+ ls.unApplyCommand = ~m_editPatch.unapplyCommand->text();
+ ls.type = ~m_editPatch.type->text();
+ if( !m_editPatch.filename->url().toLocalFile().isEmpty() )
+ ls.filename = ~TeamworkFolderManager::teamworkRelative( ( m_editPatch.filename->url() ) );
+ else
+ ls.filename = "";
+ ls.description = ~m_editPatch.description->toPlainText();
+ ls.dependencies = ~m_editPatch.dependencies->text();
+ ls.command = ~m_editPatch.command->text();
+ ls.applyCommand = ~m_editPatch.applyCommand->text();
+ ls.state = editState();
+ ls.author = ~m_editPatch.author->text();
+ QString txt = m_editPatch.accessRights->currentText();
+
+ ls.access = LocalPatchSource::accessFromString( ~txt );
+
+ m_editingPatch = ps;
+ return ps;
+}
+
+void EditPatch::fillEditFromPatch() {
+ out( Logger::Debug ) << "filling edit from patch";
+
+ LocalPatchSourcePointer _patch = m_editingPatch;
+ bool local = m_editPatchLocal;
+ LocalPatchSourcePointer::Locked l = _patch;
+ if ( !m_editDlg || !_patch || !l )
+ return ;
+ LocalPatchSource& patch( *l );
+ m_editPatchLocal = local;
+
+ m_editPatch.name->setText( ~patch.name );
+ m_editPatch.unapplyCommand->setText( ~patch.unApplyCommand );
+ m_editPatch.type->setText( ~patch.type );
+ if( !patch.filename.empty() )
+ m_editPatch.filename->setUrl( TeamworkFolderManager::teamworkAbsolute( ~patch.filename ) );
+ else
+ m_editPatch.filename->setUrl( KUrl() );
+ m_editPatch.description->setText( ~patch.description );
+ m_editPatch.dependencies->setText( ~patch.dependencies );
+ m_editPatch.command->setText( ~patch.command );
+ m_editPatch.applyCommand->setText( ~patch.applyCommand );
+ m_editPatch.author->setText( ~patch.author );
+
+ int stateIndex = 0;
+
+ switch ( patch.state ) {
+ case LocalPatchSource::Applied:
+ stateIndex = 1;
+ break;
+ case LocalPatchSource::NotApplied:
+ stateIndex = 2;
+ break;
+ default:
+ stateIndex = 0;
+ }
+
+ m_editPatch.state->setCurrentIndex( stateIndex );
+ slotStateChanged();
+
+ if ( !patch.filename.empty() )
+ m_editPatch.tabWidget->setCurrentIndex( m_editPatch.tabWidget->indexOf( m_editPatch.fileTab ) );
+ else
+ m_editPatch.tabWidget->setCurrentIndex( m_editPatch.tabWidget->indexOf( m_editPatch.commandTab ) );
+
+ m_editPatch.accessRights->setEditText( ~patch.accessAsString() );
+
+ UserIdentity id = l->userIdentity;
+ if ( id ) {
+ m_editPatch.userButton->setEnabled( true );
+ m_editPatch.userButton->setText( ~id.name() );
+ } else {
+ m_editPatch.userButton->setEnabled( false );
+ }
+
+ updateByType();
+ m_updateKompareTimer->start( 400 );
+}
+
+void EditPatch::slotFileNameEdited() {
+ m_updateKompareTimer->start( 100 );
+}
+
+void EditPatch::slotCommandEdited() {
+ m_updateKompareTimer->start( 100 );
+}
+
+void EditPatch::slotEditMimeType( const QString& /*str*/ ) {
+ if ( !m_started )
+ return ;
+ m_editingPatch = patchFromEdit();
+ updateByType();
+ m_updateKompareTimer->start( 100 );
+}
+
+void EditPatch::slotEditCommandChanged( const QString& /*str*/ ) {
+ if ( !m_started )
+ return ;
+ m_editPatch.filename->setUrl( QString( "" ) );
+ emit stateChanged( this );
+
+ //m_updateKompareTimer->start( 100 );
+}
+
+void EditPatch::slotUserButton() {
+ LocalPatchSourcePointer::Locked patch = patchFromEdit();
+ try {
+ if ( !patch )
+ throw "could not lock patch";
+ UserPointer u;
+ {
+ TeamworkClientPointer::Locked client = m_parent->teamwork() ->client();
+ if ( !client )
+ throw "no client";
+ u = client->findUser( patch->userIdentity );
+ }
+ if ( !u )
+ throw "could not get user";
+ if ( !u.cast<KDevTeamworkUser>() )
+ throw "user has wrong type";
+
+ m_parent->teamwork() ->showUserInfo( u.cast<KDevTeamworkUser>() );
+ } catch ( const QString & str ) {
+ err() << "slotUserButton():" << str;
+ } catch ( const char * str ) {
+ err() << "slotUserButton():" << str;
+ }
+}
+
+void EditPatch::slotApplyEditPatch() {
+ LocalPatchSourcePointer patch = patchFromEdit();
+ if ( m_editPatchLocal ) {
+ LocalPatchSourcePointer::Locked l = m_editingPatch;
+ if ( !m_parent->hasPatch( patch ) )
+ m_parent->addPatch( patch );
+
+ if ( l && l->filename.empty() ) {
+ ///The patch has to be serialized first before it can be applied
+
+ SafeSharedPtr<PatchMessage>::Locked l = getPatchMessage( PatchRequestData::Apply );
+ if ( !l )
+ throw "could not get the patch-message";
+ m_parent->processMessage( l.data() );
+ } else {
+ apply();
+ fillEditFromPatch();
+ }
+ } else {
+ ///Request the patch from the peer and apply it
+ try {
+ LocalPatchSourcePointer::Locked lpatch = patch;
+ if ( !lpatch )
+ throw "could not lock patch-source";
+
+ UserPointer::Locked user = lpatch->user();
+ if ( !user )
+ throw "the patch has no associated user";
+ if ( !user->online() )
+ throw "the user is not online";
+
+ SessionPointer session = user->online().session();
+ if ( !session )
+ throw "the session could not be acquired";
+
+ MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork(), PatchRequestData::Apply );
+ session.unsafe() ->send( mp );
+ m_parent->teamwork() ->addMessageToList( mp );
+ } catch ( const char * str ) {
+ err() << "error in slotApplyEditPatch:" << str;
+ }
+ }
+ emit stateChanged( this );
+}
+
+void EditPatch::slotUnapplyEditPatch() {
+ if ( !m_editPatchLocal )
+ return ;
+
+ LocalPatchSourcePointer patch = patchFromEdit();
+ if ( !m_parent->hasPatch( patch ) )
+ m_parent->addPatch( patch );
+ LocalPatchSourcePointer::Locked l = patch;
+ if ( l ) {
+ if ( !l->command.empty() ) {
+ int result = KMessageBox::warningContinueCancel( m_editDlg, i18n( "You are about to unapply a dynamic patch created by the command \"%1\". That can be very dangerous. If the same command will not produce the same text after the unapply, the patch cannot be reapplied and all data may be lost. \nRecommendation: Make the patch a file-patch before unapplying it.", l->command.c_str() ), i18n("Warning") );
+ if ( result != KMessageBox::Continue )
+ return ;
+ }
+ }
+ apply( true );
+ fillEditFromPatch();
+
+ emit stateChanged( this );
+}
+
+SafeSharedPtr<PatchMessage> EditPatch::getPatchMessage( PatchRequestData::RequestType /*type*/ ) {
+ try {
+ LocalPatchSourcePointer::Locked lpatch = patchFromEdit();
+ if ( !lpatch )
+ throw "could not lock patch";
+
+ UserPointer::Locked fakeUser( new KDevTeamworkUser( UserPointer::Locked( new User( "local" ) ) ) );
+ SafeSharedPtr<Teamwork::FakeSession>::Locked fakeSession( new Teamwork::FakeSession( fakeUser, m_parent->teamwork() ->logger(), globalMessageTypeSet(), 0 ) );
+ fakeUser->setSession( ( SessionInterface* ) fakeSession );
+
+ SafeSharedPtr<PatchRequestMessage>::Locked request = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork() );
+
+ request->info().setSession( ( SessionInterface* ) fakeSession );
+
+ m_parent->processMessage( request.data() );
+
+ MessagePointer::Locked msg = fakeSession->getFirstMessage();
+ if ( !msg.cast<PatchMessage>() ) {
+ if ( KDevSystemMessagePointer::Locked l = msg.cast<KDevSystemMessage>() ) {
+ throw QString( "Requesting the message from self failed: %1: %2" ).arg( l->messageAsString() ).arg( l->text() );
+ } else {
+ throw QString( "answer-message is not of type PatchMessage: " ) + ( msg ? msg->name() : "" );
+ }
+ }
+
+ return msg.cast<PatchMessage>().data();
+ } catch ( const char * str ) {
+ err() << "getPatchMessage: error:" << str;
+ } catch ( const QString & str ) {
+ err() << "getPatchMessage: error:" << str;
+ } catch ( const TeamworkError & error ) {
+ err() << "getPatchMessage: failed to serialize and deserialize the patch locally:" << error.what();
+ }
+ return 0;
+}
+
+KUrl EditPatch::getPatchFile( bool temp ) {
+ try {
+ LocalPatchSourcePointer patch = patchFromEdit();
+ if ( !m_parent->hasPatch( patch ) )
+ m_parent->addPatch( patch );
+ SafeSharedPtr<PatchMessage> smsg = getPatchMessage( PatchRequestData::View );
+ SafeSharedPtr<PatchMessage>::Locked msg = smsg;
+ if ( !msg )
+ throw QString( "could not serialize patch-message" );
+ LocalPatchSourcePointer::Locked patchInfo = m_editingPatch;
+ if ( !patchInfo )
+ throw QString( "could not lock patchi-info" );
+
+ QString mimeName = ~patchInfo->type;
+ if ( mimeName.trimmed().isEmpty() )
+ mimeName = "text/x-diff";
+
+ KMimeType::Ptr mime = KMimeType::mimeType( mimeName );
+ if ( !mime )
+ throw QString( "Error in kdelibs: could not create mime-type" ); ///according to the documentation this should never happen, but it does
+
+ QString fileName = ~patchInfo->name;
+ if ( !patchInfo->filename.empty() )
+ fileName += "_" + QFileInfo( ~patchInfo->filename ).fileName();
+ else
+ fileName += getDefaultExtension( mime->patterns() );
+
+ out( Logger::Debug ) << "getPatchFile() creating file for patch:" << fileName;
+
+ QString subFolder = "local";
+ if ( temp )
+ subFolder = "temp";
+
+ KUrl filePath = TeamworkFolderManager::createUniqueFile( "patches/" + subFolder, fileName );
+ if ( temp )
+ TeamworkFolderManager::registerTempItem( filePath );
+
+ {
+ ///@todo use NetAccess
+ QFile file( filePath.toLocalFile() );
+
+ file.open( QIODevice::WriteOnly );
+ if ( !file.isOpen() )
+ throw QString( "could not open %1" ).arg( filePath.toLocalFile() );
+
+ if ( file.write( msg->data() ) != msg->data().size() )
+ throw "writing the file " + filePath.toLocalFile() + " failed";
+ }
+ return filePath;
+ } catch ( const QString & str ) {
+ err() << "getPatchFile(" << temp << ") failed:" << str;
+ return QString();
+ } catch ( const char * str ) {
+ err() << "getPatchFile(" << temp << ") failed:" << str;
+ return QString();
+ }
+}
+void EditPatch::slotShowEditPatch() {
+ LocalPatchSourcePointer patch = patchFromEdit();
+ if ( !m_parent->hasPatch( patch ) )
+ m_parent->addPatch( patch );
+ try {
+
+ if ( m_editPatchLocal ) {
+ SafeSharedPtr<PatchMessage>::Locked l = getPatchMessage( PatchRequestData::View );
+ if ( !l )
+ throw "could not get the patch-message";
+ m_parent->processMessage( l.data() );
+ } else {
+ ///Request the patch from the peer and show it
+ LocalPatchSourcePointer::Locked lpatch = patch;
+ if ( !lpatch )
+ throw "could not lock patch-source";
+
+ UserPointer::Locked user = lpatch->user();
+ if ( !user )
+ throw "the patch has no associated user";
+ if ( !user->online() )
+ throw "the user is not online";
+
+ SessionPointer session = user->online().session();
+ if ( !session )
+ throw "the session could not be acquired";
+
+ MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork() );
+ session.unsafe() ->send( mp );
+ m_parent->teamwork() ->addMessageToList( mp );
+ }
+ } catch ( const QString & str ) {
+ err() << "error in slotShowEditPatch:" << str;
+ } catch ( const char * str ) {
+ err() << "error in slotShowEditPatch:" << str;
+ }
+}
+
+void EditPatch::slotStateChanged() {
+ if ( !m_started )
+ return ;
+ if ( !m_editDlg )
+ return ;
+ patchFromEdit();
+
+ switch ( editState() ) {
+ case LocalPatchSource::Unknown:
+ m_editPatch.applyButton->setEnabled( true );
+ m_editPatch.unApplyButton->setEnabled( true );
+ break;
+ case LocalPatchSource::Applied:
+ m_editPatch.applyButton->setEnabled( false );
+ m_editPatch.unApplyButton->setEnabled( true );
+ break;
+ case LocalPatchSource::NotApplied:
+ m_editPatch.applyButton->setEnabled( true );
+ m_editPatch.unApplyButton->setEnabled( false );
+ break;
+ }
+
+ if ( !m_editPatchLocal ) {
+ m_editPatch.unApplyButton->setEnabled( false );
+ }
+
+ m_updateKompareTimer->start( 100 );
+
+ updateByType();
+ emit stateChanged( this );
+}
+
+void EditPatch::slotEditFileNameChanged( const QString& str ) {
+ if ( !m_editDlg || !m_started )
+ return ;
+ QString txt;
+
+ KSharedPtr<KMimeType> mt = KMimeType::findByUrl( KUrl( str ) );
+
+ if ( !str.isEmpty() ) {
+ txt = "mime-type: " + mt->name();
+ m_editPatch.type->setText( mt->name() );
+ }
+
+ m_editPatch.mimetype->setPixmap( m_parent->teamwork() ->icons().getIcon( mt->iconName(), KIconLoader::Desktop ).pixmap( 16, 16 ) );
+
+ m_editPatch.mimetype->setText( txt );
+ m_editPatch.command->setText( "" );
+ emit stateChanged( this );
+
+ //m_updateKompareTimer->start( 100 );
+}
+
+void EditPatch::slotEditDialogFinished( int /*result*/ ) {
+ if ( !m_started )
+ return ;
+ LocalPatchSourcePointer patch = patchFromEdit();
+
+ m_editDlg = 0;
+ emit dialogClosed( this );
+}
+
+void EditPatch::slotChooseType() {
+ if ( !m_started )
+ return ;
+ if ( !m_editDlg )
+ return ;
+
+ QString text = "Select the MimeType for this item.";
+ QStringList list;
+ list << m_editPatch.type->text();
+ KMimeTypeChooserDialog *d = new KMimeTypeChooserDialog( text, "", list , "text", QStringList(), KMimeTypeChooser::Comments | KMimeTypeChooser::Patterns | KMimeTypeChooser::EditButton, m_editDlg );
+ if ( d->exec() == QDialog::Accepted ) {
+ if ( !d->chooser() ->mimeTypes().isEmpty() ) {
+ ///It would be perfect to have a mime-type-chooser that allows only one choice.
+ if ( d->chooser() ->mimeTypes().back() == m_editPatch.type->text() ) {
+ m_editPatch.type->setText( d->chooser() ->mimeTypes().front() );
+ } else {
+ m_editPatch.type->setText( d->chooser() ->mimeTypes().back() );
+ }
+ }
+ }
+
+ delete d;
+ updateByType();
+}
+
+std::string EditPatch::logPrefix() {
+ LocalPatchSourcePointer::Locked l = m_editingPatch;
+ if ( !l )
+ return "EditPatch: ";
+ else
+ return "EditPatch(" + l->name + "): ";
+}
+
+void EditPatch::slotToFile() {
+ LocalPatchSourcePointer::Locked l = patchFromEdit();
+ if ( !l ) {
+ err() << "slotToFile() could not lock edited patch";
+ return ;
+ }
+ KUrl f = getPatchFile();
+ if ( f.isEmpty() ) {
+ err() << "slotToFile() could not get create patch-file";
+ return ;
+ }
+ out( Logger::Debug ) << "converting patch with command \"" << l->command << "\" to file \"" << f.prettyUrl() << "\"";
+ if( !f.isEmpty() )
+ l->setFileName( ~TeamworkFolderManager::teamworkRelative( f ) );
+ else
+ l->setFileName( "" );
+
+ m_editPatch.tabWidget->setCurrentIndex( 0 );
+ m_editPatch.filename->setUrl( f );
+ fillEditFromPatch();
+}
+
+
+void EditPatch::slotDetermineState() {
+ m_parent->determineState( patchFromEdit() );
+ fillEditFromPatch();
+ emit stateChanged( this );
+}
+
+void EditPatch::dialogDestroyed() {
+ m_editDlg = 0;
+ EditPatchPointer p = this;
+ emit dialogClosed( this );
+}
+
+void EditPatch::updateByType() {
+ LocalPatchSourcePointer::Locked l = m_editingPatch;
+ if ( !l )
+ return ;
+ l->applyCommand = ~m_editPatch.applyCommand->text();
+ l->unApplyCommand = ~m_editPatch.unapplyCommand->text();
+ l->type = ~m_editPatch.type->text();
+
+ if ( l->type == "text/x-diff" ) {
+ if ( l->state == LocalPatchSource::Applied ) {
+ m_editPatch.filesGroup->show();
+ } else {
+ m_editPatch.filesGroup->hide();
+ }
+ if ( l->patchTool( false ) == "patch" && l->patchTool( true ) == "patch" ) {
+ m_editPatch.determineState->setEnabled( true );
+ } else {
+ m_editPatch.determineState->setEnabled( false );
+ }
+ } else {
+ m_editPatch.determineState->setEnabled( false );
+ m_editPatch.filesGroup->hide();
+ }
+}
+
+void EditPatch::showEditDialog() {
+ if ( m_editDlg ) {
+ out( Logger::Warning ) << "there is still another edit-dialog open";
+ return ;
+ }
+
+
+ m_editDlg = new QDialog( m_parent->teamwork() ->widget() );
+
+ connect( m_editDlg, SIGNAL( destroyed( QObject* ) ), this, SLOT( dialogDestroyed() ) );
+ m_editPatch.setupUi( m_editDlg );
+
+ m_filesModel = new QStandardItemModel( m_editPatch.filesList );
+ m_editPatch.filesList->setModel( m_filesModel );
+
+ connect( m_editPatch.previousHunk, SIGNAL( clicked( bool ) ), this, SLOT( prevHunk() ) );
+ connect( m_editPatch.nextHunk, SIGNAL( clicked( bool ) ), this, SLOT( nextHunk() ) );
+ connect( m_editPatch.filesList, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( fileDoubleClicked( const QModelIndex& ) ) );
+ connect( m_editPatch.filesList->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( fileSelectionChanged() ) );
+ connect( m_editPatch.okButton, SIGNAL( pressed() ), this, SLOT( slotEditOk() ) );
+ //connect( m_editPatch.cancelButton, SIGNAL( pressed() ), this, SLOT( slotEditCancel() ) );
+
+ connect( m_editPatch.highlightFiles, SIGNAL( clicked( bool ) ), this, SLOT( highlightFile() ) );
+ connect( m_editPatch.applyButton, SIGNAL( pressed() ), this, SLOT( slotApplyEditPatch() ) );
+ connect( m_editPatch.unApplyButton, SIGNAL( pressed() ), this, SLOT( slotUnapplyEditPatch() ) );
+ connect( m_editPatch.showButton, SIGNAL( pressed() ), this, SLOT( slotShowEditPatch() ) );
+
+ connect( m_editPatch.type, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditMimeType( const QString& ) ) );
+ connect( m_editPatch.chooseType, SIGNAL( pressed() ), this, SLOT( slotChooseType() ) );
+ connect( m_editDlg, SIGNAL( finished( int ) ), this, SLOT( slotEditDialogFinished( int ) ) );
+ connect( m_editPatch.filename, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditFileNameChanged( const QString& ) ) );
+ connect( m_editPatch.command, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditCommandChanged( const QString& ) ) );
+ connect( m_editPatch.state, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotStateChanged() ) );
+ connect( m_editPatch.determineState, SIGNAL( clicked( bool ) ), this, SLOT( slotDetermineState() ) );
+ connect( m_editPatch.commandToFile, SIGNAL( clicked( bool ) ), this, SLOT( slotToFile() ) );
+
+ connect( m_editPatch.filename->lineEdit(), SIGNAL( returnPressed() ), this, SLOT( slotFileNameEdited() ) );
+ connect( m_editPatch.filename->lineEdit(), SIGNAL( editingFinished() ), this, SLOT( slotFileNameEdited() ) );
+ connect( m_editPatch.filename, SIGNAL( urlSelected( const QString& ) ), this, SLOT( slotCommandEdited() ) );
+ connect( m_editPatch.command, SIGNAL( editingFinished() ), this, SLOT( slotCommandEdited() ) );
+ connect( m_editPatch.command, SIGNAL( returnPressed() ), this, SLOT( slotCommandEdited() ) );
+ connect( m_editPatch.command, SIGNAL( () ), this, SLOT( slotCommandEdited() ) );
+
+ connect( m_editPatch.userButton, SIGNAL( clicked( bool ) ), this, SLOT( slotUserButton() ) );
+ connect( m_editPatch.applyCommand, SIGNAL( textEdited( const QString& ) ), this, SLOT( updateByType() ) );
+ connect( m_editPatch.unapplyCommand, SIGNAL( textEdited( const QString& ) ), this, SLOT( updateByType() ) );
+
+ bool blocked = blockSignals( true );
+ m_editPatch.accessRights->insertItem( 0, ~LocalPatchSource::accessToString( Public ) );
+ m_editPatch.accessRights->insertItem( 1, ~LocalPatchSource::accessToString( ConnectedOnly ) );
+ m_editPatch.accessRights->insertItem( 2, ~LocalPatchSource::accessToString( Ask ) );
+ m_editPatch.accessRights->insertItem( 3, ~LocalPatchSource::accessToString( Private ) );
+
+ m_editPatch.state->insertItem( 0, "Unknown" );
+ m_editPatch.state->insertItem( 1, "Applied" );
+ m_editPatch.state->insertItem( 2, "Not Applied" );
+
+
+ m_editPatch.filename->fileDialog() ->setUrl( TeamworkFolderManager::workspaceDirectory() );
+
+ m_editPatch.type->setText( "text/x-diff" );
+
+ m_editDlg->show();
+ blockSignals( blocked );
+}
+
+void EditPatch::hideEditDialog() {
+ if ( !m_editDlg )
+ return ;
+ m_editDlg->close();
+ delete m_editDlg;
+ m_editDlg = 0;
+}
+
+void EditPatch::editPatchReadOnly() {
+ if ( !m_editDlg )
+ return ;
+
+ m_editPatch.applyCommand->setReadOnly( true );
+ m_editPatch.unapplyCommand->setReadOnly( true );
+ m_editPatch.name->setReadOnly( true );
+ m_editPatch.dependencies->setReadOnly( true );
+ m_editPatch.command->setReadOnly( true );
+ m_editPatch.accessRights->setEditable( false );
+ if ( m_editPatch.accessRights->lineEdit() )
+ m_editPatch.accessRights->lineEdit() ->setReadOnly( true );
+ m_editPatch.type->setReadOnly( true );
+ /*if( m_editPatch.type->lineEdit() )
+ m_editPatch.type->lineEdit()->setReadOnly( true );*/
+ m_editPatch.description->setReadOnly( true );
+ if ( m_editPatch.filename->lineEdit() )
+ m_editPatch.filename->lineEdit() ->setReadOnly( true );
+ if ( m_editPatch.filename->comboBox() )
+ m_editPatch.filename->comboBox() ->setEditable( false );
+ if ( m_editPatch.filename->lineEdit() )
+ m_editPatch.filename->lineEdit() ->setReadOnly( true );
+ /*m_editPatch.applyButton->setEnabled( false );
+ m_editPatch.unApplyButton->setEnabled( false );
+ m_editPatch.showButton->setEnabled( false );*/
+ if ( !m_editPatchLocal ) {
+ m_editPatch.unApplyButton->setEnabled( true );
+ m_editPatch.applyButton->setEnabled( true );
+ m_editPatch.showButton->setEnabled( true );
+ }
+ // m_editPatch.cancelButton->setEnabled( false );
+}
+
+LocalPatchSource::State EditPatch::editState() {
+ if ( !m_editDlg )
+ return LocalPatchSource::Unknown;
+ switch ( m_editPatch.state->currentIndex() ) {
+ case 0:
+ return LocalPatchSource::Unknown;
+ case 1:
+ return LocalPatchSource::Applied;
+ default:
+ return LocalPatchSource::NotApplied;
+ }
+}
+
+LocalPatchSourcePointer EditPatch::patch() const {
+ return m_editingPatch;
+}
+
+const QString terminalSuccessMarker = "TERMINAL_ACTION_SUCCESSFUL";
+const QString reversedMarker = "Reversed (or previously applied) patch detected";
+
+void EditPatch::apply( bool reverse, const QString& _fileName ) {
+ try {
+ if ( m_lastDataTime.isValid() ) {
+ if ( m_lastDataTime.msecsTo( QTime::currentTime() ) < 100 ) {
+ m_editPatch.konsoleDock->showNormal();
+ throw "terminal is still in use";
+ }
+ }
+ LocalPatchSourcePointer::Locked patch = patchFromEdit();
+ if ( !patch )
+ throw "could not lock patch";
+
+ QString fileName = _fileName;
+ if ( fileName.trimmed().isEmpty() )
+ fileName = ( ~patch->filename ).trimmed();
+
+ if ( fileName.isEmpty() )
+ throw "cannot apply patch without a filename";
+
+ out() << "Applying patch" << patch->name << "from file" << fileName;
+
+ if ( ( !reverse && patch->state == LocalPatchSource::Applied ) )
+ throw QString( "tried to apply an already applied patch: %1" ).arg( ~patch->name );
+ if ( ( reverse && patch->state == LocalPatchSource::NotApplied ) )
+ throw QString( "tried to unapply a not applied patch: %1" ).arg( ~patch->name );
+
+ KPluginFactory* factory = 0;
+ KService::Ptr service = KService::serviceByDesktopName("konsolepart");
+ if (service) {
+ factory = KPluginLoader(service->library()).factory();
+ }
+ if ( factory == 0L )
+ throw "no factory for konsolepart available";
+
+ KParts::Part* p;
+ if ( !m_konsolePart ) {
+ p = static_cast<KParts::Part*>( factory->create( ( QObject* ) m_editDlg ) );
+ } else {
+ p = m_konsolePart;
+ }
+
+ if ( !p )
+ throw "could not create konsole-part";
+
+ p->widget() ->setFocusPolicy( Qt::WheelFocus );
+ p->widget() ->setFocus();
+
+ if ( QFrame * frame = qobject_cast<QFrame*>( p->widget() ) )
+ frame->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+
+ m_konsolePart = p;
+
+ TerminalInterface* terminal = static_cast<TerminalInterface*>( p->qt_metacast( "TerminalInterface" ) );
+ if ( !terminal )
+ throw "could not get terminal-interface";
+
+ m_editPatch.konsoleDock->show();
+ m_editPatch.konsoleDock->setWidget( p->widget() );
+ p->widget() ->show();
+ m_editPatch.konsoleDock->showNormal();
+
+ m_reversed = false;
+
+ QString params = ~patch->patchParams( reverse );
+
+ bool hadFile = params.indexOf( "$FILE" ) != -1;
+ //params.replace( "$FILE", fileName );
+
+ if ( !hadFile ) {
+ if ( patch->patchTool( reverse ) == "patch" )
+ params += " -i";
+ params += " " + fileName;
+ }
+ QString command = "FILE=" + fileName + " " + ~patch->patchTool( reverse ) + " " + params + " && echo " + QString( terminalSuccessMarker ) + "\n";
+
+ ///@todo not working with remove directories
+ terminal->showShellInDir( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
+
+ if ( reverse )
+ m_actionState = LocalPatchSource::NotApplied;
+ else
+ m_actionState = LocalPatchSource::Applied;
+
+ connect( p, SIGNAL( receivedData( const QString& ) ), this, SLOT( receivedTerminalData( const QString& ) ) );
+
+ patch->state = LocalPatchSource::Unknown;
+
+ m_lastTerminalData.clear();
+ terminal->sendInput( command );
+ //terminal->startProgram( ~patch->patchTool( reverse ), l );
+
+ fillEditFromPatch();
+ } catch ( const QString & str ) {
+ err() << QString( "error in applyPatch(reverse = %1): %2" ).arg( reverse ).arg( str );
+ } catch ( const char * str ) {
+ err() << QString( "error in applyPatch(reverse = %1): %2" ).arg( reverse ).arg( str );
+ }
+}
+
+///This ugly hacking is necerssary because the status-output cannot be retrieved anymore
+void EditPatch::receivedTerminalData( const QString& s ) {
+ m_lastDataTime = QTime::currentTime();
+ m_lastTerminalData += s;
+ if ( m_lastTerminalData.contains( reversedMarker ) )
+ m_reversed = true;
+
+ if ( m_lastTerminalData.contains( terminalSuccessMarker ) ) {
+ m_lastTerminalData.replace( "echo " + terminalSuccessMarker, "" );
+ if ( m_lastTerminalData.contains( terminalSuccessMarker ) ) {
+ LocalPatchSourcePointer::Locked l = patchFromEdit();
+ if ( !l )
+ return ;
+ m_editPatch.konsoleDock->hide();
+ if ( m_reversed ) {
+ if ( m_actionState == LocalPatchSource::Applied )
+ m_actionState = LocalPatchSource::NotApplied;
+ else if ( m_actionState == LocalPatchSource::NotApplied )
+ m_actionState = LocalPatchSource::Applied;
+ }
+ l->state = m_actionState;
+ fillEditFromPatch();
+ emit stateChanged( this );
+ }
+ }
+
+ m_lastTerminalData = m_lastTerminalData.right( terminalSuccessMarker.length() + reversedMarker.length() );
+}
+
+void EditPatch::nextHunk() {
+ updateKompareModel();
+ seekHunk( true, m_isSource );
+}
+
+void EditPatch::prevHunk() {
+ updateKompareModel();
+ seekHunk( false, m_isSource );
+}
+
+void EditPatch::seekHunk( bool forwards, bool isSource, const QString& fileName ) {
+ try {
+ QModelIndexList il = m_editPatch.filesList->selectionModel() ->selectedIndexes();
+ if ( il.isEmpty() )
+ throw "selection is empty";
+ if ( !m_modelList.get() )
+ throw "no model";
+
+ for ( QModelIndexList::iterator it = il.begin(); it != il.end(); ++it ) {
+ QVariant v = m_filesModel->data( *it, Qt::UserRole );
+ if ( !v.canConvert<const Diff2::DiffModel*>() )
+ continue;
+ const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
+ if ( !model || !model->differences() )
+ continue;
+
+ KUrl file = TeamworkFolderManager::workspaceDirectory();
+ if ( isSource ) {
+ file.addPath( model->sourcePath() );
+ file.addPath( model->sourceFile() );
+ } else {
+ file.addPath( model->destinationPath() );
+ file.addPath( model->destinationFile() );
+ }
+ if ( !fileName.isEmpty() && fileName != file.toLocalFile() )
+ continue;
+
+ //out( Logger::Debug ) << "highlighting" << file.toLocalFile();
+
+ IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( file );
+
+ if ( doc ) {
+ KDevTeamworkPlugin::staticDocumentController()->activateDocument( doc );
+ if ( doc->textDocument() ) {
+ KTextEditor::View * v = doc->textDocument() ->activeView();
+ int bestLine = -1;
+ if ( v ) {
+ KTextEditor::Cursor c = v->cursorPosition();
+ for ( Diff2::DifferenceList::const_iterator it = model->differences() ->begin(); it != model->differences() ->end(); ++it ) {
+ int line;
+ Diff2::Difference* diff = *it;
+ if ( isSource )
+ line = diff->sourceLineNumber();
+ else
+ line = diff->destinationLineNumber();
+ if ( line > 0 )
+ line -= 1;
+
+ if ( forwards ) {
+ if ( line > c.line() && ( bestLine == -1 || line < bestLine ) )
+ bestLine = line;
+ } else {
+ if ( line < c.line() && ( bestLine == -1 || line > bestLine ) )
+ bestLine = line;
+ }
+ }
+ if ( bestLine != -1 ) {
+ v->setCursorPosition( KTextEditor::Cursor( bestLine, 0 ) );
+ return ;
+ }
+ }
+ }
+ }
+ }
+
+ } catch ( const QString & str ) {
+ err() << "seekHunk():" << str;
+ } catch ( const char * str ) {
+ err() << "seekHunk():" << str;
+ }
+ out() << "no matching hunk found";
+}
+
+void EditPatch::highlightFile() {
+ updateKompareModel();
+ try {
+ QModelIndexList il = m_editPatch.filesList->selectionModel() ->selectedIndexes();
+ if ( il.isEmpty() )
+ throw "selection is empty";
+ if ( !m_modelList.get() )
+ throw "no model";
+
+ for ( QModelIndexList::iterator it = il.begin(); it != il.end(); ++it ) {
+ QVariant v = m_filesModel->data( *it, Qt::UserRole );
+ if ( !v.canConvert<const Diff2::DiffModel*>() )
+ continue;
+ const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
+ if ( !model )
+ continue;
+
+ KUrl file = TeamworkFolderManager::workspaceDirectory();
+ if ( m_isSource ) {
+ file.addPath( model->sourcePath() );
+ file.addPath( model->sourceFile() );
+ } else {
+ file.addPath( model->destinationPath() );
+ file.addPath( model->destinationFile() );
+ }
+
+ out( Logger::Debug ) << "highlighting" << file.toLocalFile();
+
+ IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( file );
+
+ if ( !doc ) {
+ doc = KDevTeamworkPlugin::staticDocumentController() ->openDocument( file, KTextEditor::Cursor() );
+ seekHunk( true, m_isSource, file.toLocalFile() );
+ }
+ removeHighlighting( file.toLocalFile() );
+
+ m_highlighters[ file.toLocalFile() ] = new DocumentHighlighter( model, doc, m_isSource );
+ }
+
+ } catch ( const QString & str ) {
+ err() << "highlightFile():" << str;
+ } catch ( const char * str ) {
+ err() << "highlightFile():" << str;
+ }
+}
+
+void EditPatch::fileDoubleClicked( const QModelIndex& i ) {
+ try {
+ if ( !m_modelList.get() )
+ throw "no model";
+ QVariant v = m_filesModel->data( i, Qt::UserRole );
+ if ( !v.canConvert<const Diff2::DiffModel*>() )
+ throw "cannot convert";
+ const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
+ if ( !model )
+ throw "bad model-value";
+
+ KUrl file = TeamworkFolderManager::workspaceDirectory();
+ if ( m_isSource ) {
+ file.addPath( model->sourcePath() );
+ file.addPath( model->sourceFile() );
+ } else {
+ file.addPath( model->destinationPath() );
+ file.addPath( model->destinationFile() );
+ }
+
+ out( Logger::Debug ) << "opening" << file.toLocalFile();
+
+ KDevTeamworkPlugin::staticDocumentController() ->openDocument( file, KTextEditor::Cursor() );
+
+ seekHunk( true, m_isSource, file.toLocalFile() );
+ } catch ( const QString & str ) {
+ err() << "fileDoubleClicked():" << str;
+ } catch ( const char * str ) {
+ err() << "fileDoubleClicked():" << str;
+ }
+}
+
+void EditPatch::fileSelectionChanged() {
+ QModelIndexList i = m_editPatch.filesList->selectionModel() ->selectedIndexes();
+ m_editPatch.nextHunk->setEnabled( false );
+ m_editPatch.previousHunk->setEnabled( false );
+ m_editPatch.highlightFiles->setEnabled( false );
+ if ( !m_modelList.get() )
+ return ;
+ for ( QModelIndexList::iterator it = i.begin(); it != i.end(); ++it ) {
+ QVariant v = m_filesModel->data( *it, Qt::UserRole );
+ if ( v.canConvert<const Diff2::DiffModel*>() ) {
+ const Diff2::DiffModel * model = v.value<const Diff2::DiffModel*>();
+ if ( model ) {
+ if ( model->differenceCount() != 0 ) {
+ m_editPatch.nextHunk->setEnabled( true );
+ m_editPatch.previousHunk->setEnabled( true );
+ m_editPatch.highlightFiles->setEnabled( true );
+ }
+ }
+ }
+ }
+}
+
+DocumentHighlighter::DocumentHighlighter( const Diff2::DiffModel* model, IDocument* kdoc, bool isSource ) throw( QString ) : m_doc( kdoc ) {
+// connect( kdoc, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
+ connect( kdoc->textDocument(), SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
+ connect( model, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
+
+ KTextEditor::Document* doc = kdoc->textDocument();
+ if ( doc->lines() == 0 )
+ return ;
+ if( doc->activeView() == 0 ) return;
+
+ if ( !model->differences() )
+ return ;
+ KTextEditor::SmartInterface* smart = dynamic_cast<KTextEditor::SmartInterface*>( doc );
+ if ( !smart )
+ throw QString( "no smart-interface" );
+
+ QMutexLocker lock(smart->smartMutex());
+
+ KTextEditor::SmartRange* topRange = smart->newSmartRange(doc->documentRange(), 0, KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight);
+
+ for ( Diff2::DifferenceList::const_iterator it = model->differences() ->begin(); it != model->differences() ->end(); ++it ) {
+ Diff2::Difference* diff = *it;
+ int line, lineCount;
+ if ( isSource ) {
+ line = diff->sourceLineNumber();
+ lineCount = diff->sourceLineCount();
+ } else {
+ line = diff->destinationLineNumber();
+ lineCount = diff->destinationLineCount();
+ }
+ if ( line > 0 )
+ line -= 1;
+
+ KTextEditor::Cursor c( line, 0 );
+ KTextEditor::Cursor endC( line + lineCount, 0 );
+ if ( doc->lines() <= c.line() )
+ c.setLine( doc->lines() - 1 );
+ if ( doc->lines() <= endC.line() )
+ endC.setLine( doc->lines() - 1 );
+ endC.setColumn( doc->lineLength( endC.line() ) ) ;
+
+ if ( endC.isValid() && c.isValid() ) {
+ KTextEditor::SmartRange * r = smart->newSmartRange( c, endC );
+ r->setParentRange(topRange);
+ KSharedPtr<KTextEditor::Attribute> t( new KTextEditor::Attribute() );
+
+ t->setProperty( QTextFormat::BackgroundBrush, QBrush( QColor( 200, 200, 255 ) ) );
+ r->setAttribute( t );
+ }
+ }
+
+ m_ranges << topRange;
+
+ smart->addHighlightToDocument(topRange);
+}
+
+DocumentHighlighter::~DocumentHighlighter() {
+ for ( QList<KTextEditor::SmartRange*>::iterator it = m_ranges.begin(); it != m_ranges.end(); ++it )
+ delete *it;
+
+ m_ranges.clear();
+}
+
+IDocument* DocumentHighlighter::doc() {
+ return m_doc;
+}
+
+void DocumentHighlighter::documentDestroyed() {
+ m_ranges.clear();
+}
+
+void EditPatch::removeHighlighting( const QString& file ) {
+ if ( file.isEmpty() ) {
+ ///Remove all highlighting
+ for ( HighlightMap::iterator it = m_highlighters.begin(); it != m_highlighters.end(); ++it ) {
+ delete *it;
+ }
+ m_highlighters.clear();
+ } else {
+ HighlightMap::iterator it = m_highlighters.find( file );
+ if ( it != m_highlighters.end() ) {
+ delete * it;
+ m_highlighters.erase( it );
+ }
+ }
+}
+
+
+void EditPatch::updateKompareModel() {
+ try {
+ LocalPatchSourcePointer::Locked l = m_editingPatch;
+ if ( l ) {
+ if ( l->state != LocalPatchSource::Applied )
+ return ;
+ if ( l->type != "text/x-diff" )
+ return ;
+ if ( l->command == ~m_lastModelCommand && l->filename == ~m_lastModelFile && m_modelList.get() )
+ return ; ///We already have the correct model
+ m_lastModelCommand = ~l->command;
+ m_lastModelFile = ~l->filename;
+ }
+
+
+ m_modelList.reset( 0 );
+ qRegisterMetaType<const Diff2::DiffModel*>( "const Diff2::DiffModel*" );
+ if ( m_diffSettings )
+ delete m_diffSettings;
+ m_diffSettings = new DiffSettings( m_editDlg );
+ m_kompareInfo.reset( new Kompare::Info() );
+ removeHighlighting();
+ m_modelList.reset( new Diff2::KompareModelList( m_diffSettings, *m_kompareInfo, ( QObject* ) this ) );
+ KUrl diffFile = getPatchFile( true );
+ if ( diffFile.isEmpty() )
+ return ;
+ try {
+ ///@todo does not work with remote URLs
+ if ( !m_modelList->openDirAndDiff( TeamworkFolderManager::workspaceDirectory().toLocalFile(), diffFile.toLocalFile() ) )
+ throw "could not open diff " + diffFile.toLocalFile();
+ } catch ( const QString & str ) {
+ throw;
+ } catch ( ... ) {
+ throw QString( "lib/libdiff2 crashed, memory may be corrupted. Please restart kdevelop." );
+ }
+ m_filesModel->clear();
+ m_filesModel->insertColumns( 0, 1 );
+
+ const Diff2::DiffModelList* models = m_modelList->models();
+ if ( !models )
+ throw "no diff-models";
+ Diff2::DiffModelList::const_iterator it = models->begin();
+ while ( it != models->end() ) {
+ Diff2::DifferenceList * diffs = ( *it ) ->differences();
+ int cnt = 0;
+ if ( diffs )
+ cnt = diffs->count();
+
+ KUrl file;
+ if ( m_isSource ) {
+ file.addPath( ( *it ) ->sourcePath() );
+ file.addPath( ( *it ) ->sourceFile() );
+ } else {
+ file.addPath( ( *it ) ->destinationPath() );
+ file.addPath( ( *it ) ->destinationFile() );
+ }
+
+ m_filesModel->insertRow( 0 );
+ QModelIndex i = m_filesModel->index( 0, 0 );
+ if ( i.isValid() ) {
+ //m_filesModel->setData( i, file, Qt::DisplayRole );
+ m_filesModel->setData( i, QString( "%1 (%2 hunks)" ).arg( file.toLocalFile() ).arg( cnt ), Qt::DisplayRole );
+ QVariant v;
+ v.setValue<const Diff2::DiffModel*>( *it );
+ m_filesModel->setData( i, v, Qt::UserRole );
+ }
+ ++it;
+ }
+ fileSelectionChanged();
+ return ;
+ } catch ( const QString & str ) {
+ err() << "updateKompareModel:" << str;
+ } catch ( const char * str ) {
+ err() << "updateKompareModel:" << str;
+ }
+ m_modelList.reset( 0 );
+ delete m_diffSettings;
+ m_kompareInfo.reset( 0 );
+}
+
+#include "editpatch.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,108 @@
+project(teamwork)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${teamwork_SOURCE_DIR}/cmake/)
+
+
+find_package(KDE4 REQUIRED)
+include (KDE4Defaults)
+find_package(KDevPlatform REQUIRED)
+
+find_package(Threads REQUIRED)
+macro_optional_find_package(Commoncpp)
+
+macro_log_feature(COMMONCPP_FOUND "CommonCpp" "KDevelop4 extra plugin teamwork" "http://TODO" FALSE "" "")
+
+if (COMMONCPP_FOUND)
+find_package(Boost 1.34.0 COMPONENTS iostreams serialization REQUIRED)
+#if(COMMONCPP2_FOUND AND Boost_FOUND)
+# macro_optional_add_subdirectory(teamwork)
+# endif(COMMONCPP2_FOUND AND Boost_FOUND)
+# macro_log_feature( COMMONCPP2_FOUND "Common C++2" "Support for Teamwork plugin integration" "http://ftp.gnu.org/pub/gnu/commoncpp/" FALSE "1.5.9" "The commoncpp2 libraries are needed for the Teamwork plugin" )
+# macro_log_feature( Boost_FOUND "Boost" "Support for Teamwork plugin integration" "http://www.boost.org/" FALSE "1.34.0" "The iostreams and serialization components of the boost C++ libraries are needed for the Teamwork plugin" )
+
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9523 )
+
+include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${KDE4_INCLUDES} )
+
+include_directories(
+ ${COMMONCPP2_INCLUDE_DIRS}
+ ${Boost_INCLUDE_DIRS}
+ ${KDEVPLATFORM_INCLUDE_DIR}
+ )
+
+add_subdirectory(lib)
+
+########### next target ###############
+
+set(kdevteamwork_PART_SRCS
+ kdevteamwork.cpp
+ kdevteamworkplugin.cpp
+ kdevteamwork_client.cpp
+ kdevteamwork_messages.cpp
+ kdevteamwork_user.cpp
+ patchesmanager.cpp
+ utils.cpp
+ collaborationmanager.cpp
+ patchmessage.cpp
+ messagemanager.cpp
+ conversationmanager.cpp
+ guimessagehistory.cpp
+ messagehistorymanager.cpp
+ kdevteamwork_messageshower.cpp
+ filecollaborationmessages.cpp
+ filecollaborationmanager.cpp
+ filecollaborationsession.cpp
+ filecollaboration.cpp
+ kdevutils.cpp
+ documentwrapper.cpp
+ indocumentmessage.cpp
+ indocumentreference.cpp
+ kdevteamwork_helpers.cpp
+ helpers.cpp
+ messageusertab.cpp
+ verify.cpp
+ filesynchronizemessage.cpp
+ vectortimestampeditor.cpp
+ qdynamictext.cpp
+ teamworkfoldermanager.cpp
+ editpatch.cpp
+ messagesendmanager.cpp
+ safelogger.cpp
+ safesignaller.cpp
+)
+
+set (
+ kdevteamwork_UI
+ kdevteamwork_editpatch.ui
+ kdevteamwork_managepatches.ui
+ kdevteamwork_filecollaborationsession.ui
+ kdevteamwork_indocumentcontextlines.ui
+ kdevteamwork_messagehistory.ui
+ kdevteamwork_indocumentmessagebuttons.ui
+ kdevteamwork_textmessage.ui
+ kdevteamwork_indocumentmessagestate.ui
+ kdevteamwork_timestampwidget.ui
+ kdevteamwork_interface.ui
+ kdevteamwork_userinfo.ui
+ kdevteamwork_internalmessage.ui
+ kdevteamwork_vectortimestampwidget.ui
+ kdevteamwork_list.ui
+)
+
+
+#ADD_DEFINITIONS(${KDE4_ENABLE_EXCEPTIONS} -Wall -fno-inline)
+ADD_DEFINITIONS(${KDE4_ENABLE_EXCEPTIONS} -Wall)
+
+kde4_add_ui_files(kdevteamwork_PART_SRCS ${kdevteamwork_UI} )
+kde4_add_plugin(kdevteamwork ${kdevteamwork_PART_SRCS})
+
+target_link_libraries(kdevteamwork ${KDE4_KDEUI_LIBS} ${KDE4_KHTML_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} kdevteamwork_network kdevteamwork_dynamictext kdevteamwork_diff2 ${KDE4_KDE3SUPPORT_LIBS} ${KDE4_KTEXTEDITOR_LIBS})
+
+install(TARGETS kdevteamwork DESTINATION ${PLUGIN_INSTALL_DIR} )
+
+########### install files ###############
+
+install( FILES kdevteamwork.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES kdevteamwork.rc DESTINATION ${DATA_INSTALL_DIR}/kdevteamwork )
+
+endif()
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake (revision 1522570)
@@ -0,0 +1,59 @@
+# - Try to find libcommoncpp2
+#
+# COMMONCPP2_FOUND - system has libcommoncpp2
+# COMMONCPP2_INCLUDE_DIRS - the commoncpp2 include directory
+# COMMONCPP2_LIBRARIES - The libraries needed to use commoncpp2
+
+
+IF(COMMONCPP2_INCLUDE_DIRS AND COMMONCPP2_LIBRARIES)
+ # Already in cache, be silent
+ SET(Commoncpp_FIND_QUIETLY TRUE)
+ENDIF(COMMONCPP2_INCLUDE_DIRS AND COMMONCPP2_LIBRARIES)
+
+IF( NOT WIN32 )
+ INCLUDE(UsePkgConfig)
+ PKGCONFIG(libccgnu2 _Libccgnu2IncDir _Libccgnu2LinkDir _Libccgnu2LinkFlags _Libccgnu2Cflags)
+ SET(LIBCCGNU2_DEFINITIONS ${_Libccgnu2Cflags})
+ PKGCONFIG(libccext2 _Libccext2IncDir _Libccext2LinkDir _Libccext2LinkFlags _Libccext2Cflags)
+ SET(LIBCCEXT2_DEFINITIONS ${_Libccext2Cflags})
+ SET(COMMONCPP2_DEFINTIONS ${LIBCCGNU2_DEFINITIONS} ${LIBCCEXT2_DEFINITIONS})
+ENDIF( NOT WIN32 )
+
+FIND_PATH(COMMONCPP2_INCLUDE_DIRS cc++/network.h
+ PATHS
+ ${_Libccgnu2IncDir}
+ PATH_SUFFIX cc++
+)
+
+FIND_LIBRARY(LIBCCGNU2_LIBRARY NAMES ccgnu2 libccgnu2
+ PATHS
+ ${_Libccext2LinkDir}
+)
+
+FIND_LIBRARY(LIBCCEXT2_LIBRARY NAMES ccext2 libccext2
+ PATHS
+ ${_Libccext2LinkDir}
+)
+
+IF(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
+ SET(COMMONCPP2_FOUND TRUE)
+ SET(COMMONCPP2_LIBRARIES ${LIBCCGNU2_LIBRARY} ${LIBCCEXT2_LIBRARY})
+ELSE(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
+ SET(COMMONCPP2_FOUND FALSE)
+ENDIF(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
+
+IF(COMMONCPP2_FOUND)
+ IF(NOT Commoncpp_FIND_QUIETLY)
+ MESSAGE(STATUS "Found libccgnu2 and libccext2 ${COMMONCPP2_LIBRARIES}")
+ ENDIF(NOT Commoncpp_FIND_QUIETLY)
+ELSE(COMMONCPP2_FOUND)
+ IF(Commoncpp_FIND_REQUIRED)
+ MESSAGE(FATAL_ERROR "Could not find libccgnu2 or libccext2")
+ ELSE(Commoncpp_FIND_REQUIRED)
+ MESSAGE(STATUS "Could not find libccgnu2 or libccext2, teamwork plugin disabled")
+ ENDIF(Commoncpp_FIND_REQUIRED)
+ENDIF(COMMONCPP2_FOUND)
+
+SET(COMMONCPP2_LIBRARIES ${COMMONCPP2_LIBRARIES} CACHE String "All libraries of Common C++")
+
+MARK_AS_ADVANCED( COMMONCPP2_INCLUDE_DIRS LIBCCGNU2_LIBRARY LIBCCEXT2_LIBRARY COMMONCPP2_LIBRARIES )
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h (revision 1522570)
@@ -0,0 +1,568 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef POINTER_H
+#define POINTER_H
+
+//Needed for AtomicCounter
+#include <cc++/thread.h>
+
+#include "sharedptr.h"
+#include "mutexinterface.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/nvp.hpp>
+#include "networkexport.h"
+
+#define MILLI_TO_NANO 1000000
+#define SEC_TO_NANO 1000000000
+
+using namespace std;
+
+#ifndef SAFESHAREDPTR_HAVE_DEFAULT
+#define SAFESHAREDPTR_HAVE_DEFAULT
+template<class Type, class Serialization = NormalSerialization>
+class SafeSharedPtr;
+#endif
+
+/** Derive your classes from SafeShared if you want to use thread-safe reference-counting.
+ * It can either be used with SafeSharedPtr to also control access to the function, or with SharedPtr
+ * to only do thread-safe reference-counting.
+ * */
+class NETWORK_EXPORT SafeShared : public MutexInterfaceImpl {
+ public:
+ /**
+ * Standard constructor. This will initialize the reference count
+ * on this object to 0.
+ */
+ inline SafeShared() : count( 0 ) { }
+
+ /**
+ * Copy constructor. This will @em not actually copy the objects
+ * but it will initialize the reference count on this object to 0.
+ */
+ inline SafeShared( const SafeShared & ) : MutexInterfaceImpl(), count( 0 ) { }
+
+ /**
+ * Overloaded assignment operator.
+ */
+ inline SafeShared &operator=( const SafeShared & ) {
+ return * this;
+ }
+
+ /**
+ * Increases the reference count by one.
+ */
+ void _Shared_ref() const {
+ ++count;
+ }
+
+ /**
+ * Releases a reference (decreases the reference count by one). If
+ * the count goes to 0, this object will delete itself.
+ */
+ void _Shared_unref() const {
+ if ( !--count ) {
+ const_cast<SafeShared*>( this ) ->prepareDeletion();
+ if ( !count )
+ delete this;
+ }
+ }
+
+ /**
+ * Return the current number of references held.
+ *
+ * @return Number of references
+ */
+ inline int _Shared_count() const {
+ return count;
+ }
+
+ protected:
+ virtual ~SafeShared() { }
+ private:
+ mutable ost::AtomicCounter count;
+ ///This little additional effort is necessary to support weak pointers.
+ virtual void prepareDeletion() {}
+};
+
+
+/**A shared pointer that is locked. The mutex will not be freed until this object is deleted.
+ As long as this object exists, the data pointed to can be used exclusively. The data may also be 0 (invalid)! */
+#ifndef USE_NEW_LOCKED
+template <class Item>
+class NETWORK_EXPORT LockedSharedPtr : protected SharedPtr<Item> {
+ private:
+ void release() {
+ if ( *this )
+ this->data() ->lockCountDown();
+ *( ( SharedPtr<Item>* ) this ) = 0;
+ }
+
+ void inc() {
+ if ( *this )
+ this->data() ->lockCountUp();
+ }
+
+ ///tries to increase the lock-count with a given timeout in nanoseconds, if ti fails sets itself to zero.
+ void inc( uint64 timeout ) {
+ if ( *this )
+ if ( !this->data() ->tryLockCountUp( timeout ) )
+ SharedPtr<Item>::operator=( 0 );
+ }
+
+ public:
+ inline LockedSharedPtr() : SharedPtr<Item>() {
+ inc();
+ }
+
+ template <class Serialization>
+ inline LockedSharedPtr( const SharedPtr<Item, Serialization>& item ) : SharedPtr<Item>( item ) {
+ inc();
+ }
+
+ inline LockedSharedPtr( Item* item ) : SharedPtr<Item>( item ) {
+ inc();
+ }
+
+ ///timeout in nanoseconds
+ template <class Serialization>
+ inline LockedSharedPtr( const SharedPtr<Item, Serialization>& item, uint64 timeout ) : SharedPtr<Item>( item ) {
+ inc( timeout );
+ }
+
+ inline LockedSharedPtr( const LockedSharedPtr<Item>& rhs ) : SharedPtr<Item>( rhs ) {
+ inc();
+ }
+
+ template <class Target>
+ inline LockedSharedPtr<Target> cast() {
+ return LockedSharedPtr<Target>( dynamic_cast<Target*>( this->data() ) );
+ }
+
+ template <class Target>
+ inline Target* freeCast() {
+ return dynamic_cast<Target*>( this->data() );
+ }
+
+
+ LockedSharedPtr<Item>& operator = ( const LockedSharedPtr<Item>& rhs ) {
+ if ( rhs.data() == this->data() )
+ return * this;
+ release();
+ SharedPtr<Item>::operator=( rhs );
+ inc();
+ return *this;
+ }
+
+ inline ~LockedSharedPtr() {
+ release();
+ }
+
+ using SharedPtr<Item>::operator->;
+ using SharedPtr<Item>::operator*;
+
+ inline bool operator ! () const {
+ return !( bool ) * ( ( SharedPtr<Item>* ) this );
+ }
+
+ inline operator bool () const {
+ return ( bool ) * ( ( SharedPtr<Item>* ) this );
+ }
+
+ inline operator const Item* () const {
+ return data();
+ }
+
+ inline operator Item* () {
+ return data();
+ }
+
+ template <class Item2>
+ bool valueSmaller( const LockedSharedPtr<Item2>& rhs ) const {
+ if ( this->data() ) {
+ if ( rhs.data() ) {
+ return ( this->data() ) ->operator<( *( rhs.data() ) );
+ } else {
+ return true;
+ }
+ } else {
+ if ( rhs.data() ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ struct ValueSmallerCompare {
+ inline bool operator() ( const LockedSharedPtr<Item>& lhs, const LockedSharedPtr<Item>& rhs ) const {
+ return lhs.valueSmaller( rhs );
+ }
+ };
+
+ using SharedPtr<Item>::data;
+};
+#else
+template <class Item>
+class NETWORK_EXPORT LockedSharedPtr : protected SharedPtr<Item> {
+ private:
+ void release() {
+ if ( *this )
+ this->data() ->lockCountDown();
+ *( ( SharedPtr<Item>* ) this ) = 0;
+ }
+
+ void inc() {
+ if ( *this )
+ this->data() ->lockCountUp();
+ }
+
+ ///tries to increase the lock-count with a given timeout in nanoseconds, if ti fails sets itself to zero.
+ void inc( uint64 timeout ) {
+ if ( *this )
+ if ( !this->data() ->tryLockCountUp( timeout ) )
+ SharedPtr<Item, Serialization>::operator=( 0 );
+ }
+
+ using SharedPtr<Item, Serialization>::serialize;
+
+ public:
+ inline LockedSharedPtr() : SharedPtr<Item, Serialization>() {
+ inc();
+ };
+
+ template <class Serialization2>
+ inline LockedSharedPtr( const SharedPtr<Item, Serialization2>& item ) : SharedPtr<Item, Serialization>( const_cast<Item*>( item.data() ) ) {
+ inc();
+ };
+
+ inline LockedSharedPtr( Item* item ) : SharedPtr<Item, Serialization>( item ) {
+ inc();
+ };
+
+ ///timeout in nanoseconds
+ template <class Serialization2>
+ inline LockedSharedPtr( const SharedPtr<Item, Serialization2>& item, uint64 timeout ) : SharedPtr<Item, Serialization>( const_cast<Item*>( item.data() ) ) {
+ inc( timeout );
+ };
+
+ template <class Serialization2>
+ inline LockedSharedPtr( const LockedSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( const_cast<Item*>( rhs.data() ) ) {
+ inc();
+ }
+
+ template <class Target>
+ inline LockedSharedPtr<Target> cast() {
+ return LockedSharedPtr<Target>( dynamic_cast<Target*>( this->data() ) );
+ }
+
+ template <class Target>
+ inline Target* freeCast() {
+ return dynamic_cast<Target*>( this->data() );
+ }
+
+
+ LockedSharedPtr<Item, Serialization>& operator = ( const LockedSharedPtr<Item, Serialization>& rhs ) {
+ release();
+ SharedPtr<Item, Serialization>::operator=( rhs );
+ inc();
+ return *this;
+ }
+
+ inline ~LockedSharedPtr() {
+ release();
+ }
+
+ using SharedPtr<Item, Serialization>::operator->;
+ using SharedPtr<Item, Serialization>::operator*;
+
+ inline bool operator ! () const {
+ return !( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
+ }
+
+ inline operator bool () const {
+ return ( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
+ }
+
+ inline operator const Item* () const {
+ return data();
+ }
+
+ inline operator Item* () {
+ return data();
+ }
+
+ template <class Item2, class Serialization2>
+ bool valueSmaller( const LockedSharedPtr<Item2, Serialization2>& rhs ) const {
+ if ( this->data() ) {
+ if ( rhs.data() ) {
+ return ( this->data() ) ->operator<( *( rhs.data() ) );
+ } else {
+ return true;
+ }
+ } else {
+ if ( rhs.data() ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+
+ struct ValueSmallerCompare {
+ inline bool operator() ( const LockedSharedPtr<Item, Serialization>& lhs, const LockedSharedPtr<Item, Serialization>& rhs ) const {
+ return lhs.valueSmaller( rhs );
+ }
+ };
+
+ using SharedPtr<Item, Serialization>::data;
+};
+#endif
+
+///five seconds of default-timeout
+const uint64 SafeSharedLockTimeout = (uint64) SEC_TO_NANO * (uint64) 5;
+
+template <class Item, class Serialization>
+class NETWORK_EXPORT SafeSharedPtr : protected SharedPtr<Item, Serialization> {
+ public:
+ typedef SharedPtr<Item, Serialization> Precursor;
+
+ typedef LockedSharedPtr<Item> Locked;
+
+ template <class Serialization2>
+ inline SafeSharedPtr( const SharedPtr<Item, Serialization2>& i ) : SharedPtr<Item, Serialization>( i ) {}
+
+ inline SafeSharedPtr() : SharedPtr<Item, Serialization>() {
+ };
+
+ inline SafeSharedPtr( Item* i ) : SharedPtr<Item, Serialization>( i ) {}
+
+ inline SafeSharedPtr( const SafeSharedPtr<Item, Serialization>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
+
+ template <class Item2, class Serialization2>
+ inline SafeSharedPtr( const SafeSharedPtr<Item2, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
+
+ template <class Serialization2>
+ inline SafeSharedPtr( SafeSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
+#ifndef USE_NEW_LOCKED
+
+ inline SafeSharedPtr( LockedSharedPtr<Item>& rhs ) : SharedPtr<Item, Serialization>( rhs.data() ) {}
+#else
+ /*template<class Serialization2>
+ inline SafeSharedPtr( LockedSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.data() ) {
+ }*/
+#endif
+
+ ///This function returns the locked pointer. This type of locking never returns zero, except the value of this pointer is zero..
+ inline Locked lock ()
+ const throw() {
+ return Locked( *( Precursor* ) this );
+ }
+
+ ///The locking may fail, the result may be zero. @param timeout the locking-timeout in nanoseconds
+ inline Locked tryLock( uint64 timeout = 0 ) const throw() {
+ return Locked( *( Precursor* ) this, timeout );
+ }
+
+ template <class Type>
+ inline operator SafeSharedPtr<Type, Serialization>() {
+ return SafeSharedPtr<Type, Serialization>( static_cast<Type*>( this->data() ) );
+ }
+
+ /// tries to lock with the default-timeout defined by SafeSharedLockTimeout
+ inline operator Locked() const {
+ //if( SafeSharedLockTimeout ) {
+ return Locked( *( Precursor* ) this, SafeSharedLockTimeout );
+ /*} else {
+ return Locked( *(Precursor*)this );
+ }*/
+ }
+
+ template <class TargetType>
+ inline SafeSharedPtr<TargetType, Serialization> cast() const {
+ return SafeSharedPtr<TargetType, Serialization>( dynamic_cast<TargetType*>( const_cast<Item*>( this->data() ) ) );
+ }
+
+ ///This omits locking the mutex, and must only be used to call functions that are thread-safe
+ inline Item* unsafe() const {
+ return const_cast<Item*>( this->data() );
+ }
+
+
+ inline SafeSharedPtr<Item, Serialization>& operator = ( const SafeSharedPtr<Item, Serialization>& rhs ) {
+ SharedPtr<Item, Serialization>::operator=( const_cast<Item*>( rhs.unsafe() ) );
+ return *this;
+ };
+
+ template <class Item2, class Serialization2>
+ inline SafeSharedPtr<Item, Serialization>& operator = ( const SafeSharedPtr<Item2, Serialization2>& rhs ) {
+ SharedPtr<Item, Serialization>::operator=( const_cast<Item2*>( rhs.unsafe() ) );
+ return *this;
+ }
+
+ inline operator bool () const {
+ return ( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
+ }
+
+ inline bool operator !() const {
+ return !( ( bool ) * this );
+ }
+
+ template <class Archive>
+ void load( Archive& arch, uint /*version*/ ) {
+ *this = 0;
+ Serialization::template load<Item>
+ ( *this, arch, 0 );
+ }
+
+ template <class Archive>
+ void save( Archive& arch, uint /*version*/ ) const {
+ Locked l = lock ()
+ ;
+ Serialization::template save<Item>
+ ( *this, arch, 0 );
+ }
+
+ template <class Serialization2>
+ inline bool operator == ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
+ return this->data() == rhs.data();
+ }
+
+ template <class Serialization2>
+ inline bool operator < ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
+ return this->data() < rhs.data();
+ }
+
+ /**This uses non-timed locks, so there is a deadlock-danger. */
+ template <class Item2, class Serialization2>
+ bool valueSmaller( const SafeSharedPtr<Item2, Serialization2>& rhs ) const {
+ if ( this->data() ) {
+ if ( rhs.data() ) {
+ Locked l = lock ()
+ ;
+ typename SafeSharedPtr<Item2, Serialization2>::Locked lr = rhs.lock();
+ return ( this->data() ) ->operator<( *( rhs.data() ) );
+ } else {
+ return true;
+ }
+ } else {
+ if ( rhs.data() ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+ template <class Item2, class Serialization2>
+ bool valueSame( const SafeSharedPtr<Item2, Serialization2>& rhs ) const {
+ bool a = !this->data(), b = !rhs.data();
+
+ if ( a && b )
+ return true;
+ else if ( a || b )
+ return false;
+
+ if ( this->data() ) {
+ if ( rhs.data() ) {
+ Locked l = lock ()
+ ;
+ typename SafeSharedPtr<Item2, Serialization2>::Locked lr = rhs.lock();
+ return ( this->data() ) ->operator==( *( rhs.data() ) );
+ } else {
+ return true;
+ }
+ }
+ return false;
+ }
+ /*
+ template <class OT>
+ bool operator < ( const SafeSharedPtr<OT>& rhs ) const {
+ if( this->data() ) {
+ if( rhs.data() ) {
+ Locked l = lock();
+ typename SafeSharedPtr<OT>::Locked lr = rhs.lock();
+ return (this->data())->operator<(*(rhs.data()) );
+ } else {
+ return true;
+ }
+ } else {
+ if( rhs.data() ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ template <class OT>
+ bool operator < ( const SharedPtr<OT>& rhs ) const {
+ if( this->data() ) {
+ if( rhs.data() ) {
+ Locked l = lock();
+ return (this->data())->operator<(*(rhs.data()) );
+ } else {
+ return true;
+ }
+ } else {
+ if( rhs.data() ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ template <class OT>
+ bool operator < ( const OT& rhs ) const {
+ if( this->data() ) {
+ Locked l = lock();
+ return (this->data())->operator<(rhs);
+ } else {
+ return true;
+ }
+ }*/
+
+ struct ValueSmallerCompare {
+ inline bool operator() ( const SafeSharedPtr<Item, Serialization>& lhs, const SafeSharedPtr<Item, Serialization>& rhs ) const {
+ return lhs.valueSmaller( rhs );
+ }
+ };
+
+ struct ValueIdentCompare {
+ inline bool operator() ( const SafeSharedPtr<Item, Serialization>& lhs, const SafeSharedPtr<Item, Serialization>& rhs ) const {
+ return lhs.valueSame( rhs );
+ }
+ };
+
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+};
+
+namespace boost {
+namespace serialization {
+template <class T, class B >
+struct implementation_level< SafeSharedPtr<T, B> > {
+ typedef mpl::integral_c_tag tag;
+ typedef mpl::int_< boost::serialization::object_serializable > type;
+ BOOST_STATIC_CONSTANT(
+ int,
+ value = implementation_level::type::value
+ );
+};
+}
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp (revision 1522570)
@@ -0,0 +1,356 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "messageimpl.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include "serialization.h"
+#include "messagetypeset.h"
+#include "helpers.h"
+#include "basicsession.h"
+#include "teamworkmessages.h"
+#include "teamworkservermessages.h"
+#include "messagesendhelper.h"
+#include <boost/serialization/vector.hpp>
+#include <boost/serialization/list.hpp>
+
+
+
+
+namespace Teamwork {
+
+ MessageConstructionInfo::MessageConstructionInfo( const std::string& name, const MessageTypeSet& typeSet ) : name_(name), typeSet_(typeSet) {
+ }
+
+ MessageConstructionInfo::MessageConstructionInfo( const MessageTypeSet& rhs ) : typeSet_( rhs ) {
+ }
+
+ const MessageTypeSet& MessageConstructionInfo::typeSet() const {
+ return typeSet_;
+ }
+
+ const std::string MessageConstructionInfo::name() const {
+ return name_;
+ }
+
+ MessageInfo MessageConstructionInfo::messageInfo() const {
+ return typeSet_.messageInfo( name_.c_str() );
+ }
+
+ MessageConstructionInfo::MessageConstructionInfo( const MessageConstructionInfo& rhs ) : name_( rhs.name_ ), typeSet_( rhs.typeSet_ ) {
+ }
+
+ MessageConstructionInfo& MessageConstructionInfo::operator=( const MessageConstructionInfo& ) {
+ return *this;
+ }
+
+ template<class Archive>
+ void MessageType::serialize( Archive& target, const uint /*version*/ ) {
+ target & idList_;
+ packFastId();
+ }
+
+ MessageInfo::MessageInfo( const MessageInfo& rhs ) {
+ operator=( rhs );
+ }
+
+ MessageInfo& MessageInfo::operator = ( const MessageInfo& rhs ) {
+ id_ = rhs.id_;
+ uniqueId_ = rhs.uniqueId_;
+ session_ = rhs.session_;
+ user_ = rhs.user_;
+ replyToMessage_ = rhs.replyToMessage_;
+ isReplyTo_ = rhs.isReplyTo_;
+ deserialized_ = rhs.deserialized_;
+ return *this;
+ }
+
+
+ MessageInfo::MessageInfo( InArchive& arch ) : id_( arch ), deserialized_( true ) {
+ //cout << "deserializing message-info";
+ arch & isReplyTo_;
+ arch & uniqueId_;
+ }
+
+ const MessageType& MessageInfo::type() const {
+ return id_;
+ }
+
+ void MessageInfo::serialize( OutArchive& arch, const uint version ) {
+ id_.serialize( arch, version );
+ arch & isReplyTo_;
+ arch & uniqueId_;
+ }
+
+ UniqueMessageId MessageInfo::isReplyTo() const {
+ return isReplyTo_;
+ }
+
+ void MessageInfo::setReply( UniqueMessageId replyId ) {
+ isReplyTo_ = replyId;
+ }
+
+ void MessageInfo::setId( const MessageType& id ) {
+ id_ = id;
+ }
+
+ void MessageInfo::makePersistent() {
+ setSession( 0 );
+ }
+
+ bool MessageInfo::isIncoming() const {
+ return deserialized_;
+ }
+
+ void MessageInfo::setIsIncoming( bool b ) {
+ deserialized_ = b;
+ }
+
+ MessageInterface::~MessageInterface() {}
+
+ const char* MessageInterface::name() {
+ return staticName();
+ }
+
+ const char* MessageInterface::staticName() {
+ return "MessageInterface";
+ }
+
+ const MessageType& MessageInterface::type() const {
+ return info().type();
+ }
+
+ UniqueMessageId MessageInterface::uniqueId() const {
+ return info().uniqueId();
+ }
+
+
+ bool MessageInterface::needReply() const {
+ return false;
+ }
+
+ MessageInterface::ReplyResult::ReplyResult( bool messageHandled_ , bool awaitingMore_ ) : messageHandled( messageHandled_ ), awaitingMore( awaitingMore_ ) {}
+
+ MessageInterface::ReplyResult MessageInterface::gotReply( const MessagePointer& /*p*/ ) {
+ return false;
+ }
+
+
+//By making this a static function, it is sure that the object is initialized when first used
+MessageTypeSet& globalMessageTypeSet() {
+ static MessageTypeSet allMessages;
+ return allMessages;
+}
+
+MessageSendHelper& globalMessageSendHelper() {
+ static MessageSendHelper globalSendHelper;
+ return globalSendHelper;
+}
+
+void registerDefaultMessages( MessageTypeSet& target ) {
+ target.registerMessageType<RawMessage, MessageInterface>( );
+ target.registerMessageType<TextMessage, RawMessage>( );
+}
+
+
+RawMessage::RawMessage( const MessageConstructionInfo& info, const DataVector& data ) : body_( data ) {
+ info_ = info.messageInfo();
+}
+
+///This should be used to indicate that this message is a reply to the other message(replyTarget)
+void RawMessage::setReply( MessageInterface* replyTarget ) {
+ info_.setReply( replyTarget->info().uniqueId() );
+}
+
+RawMessage::RawMessage( InArchive& from, const MessageInfo& info ) : info_( info ) {
+ from & body_;
+}
+
+void RawMessage::serialize( OutArchive& target ) {
+ target & body_;
+}
+
+const MessageInfo& RawMessage::info() const {
+ return info_;
+}
+
+MessageInfo& RawMessage::info() {
+ return info_;
+}
+
+/**This is called once a message has been tried to be sent, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
+ */
+void RawMessage::result( bool /*success*/ ) {
+}
+
+/**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
+DataVector& RawMessage::body() {
+ return body_;
+}
+
+/**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
+const DataVector& RawMessage::body() const {
+ return body_;
+}
+
+
+TextMessage::TextMessage( const MessageConstructionInfo& info, const std::string& text ) : RawMessage( info(this), DataVector() ) {
+ if ( text.length() == 0 )
+ return ;
+ body().resize( text.length() + 1 );
+
+ memcpy( ( char* ) & ( body() [ 0 ] ), text.c_str(), text.length() + 1 );
+}
+
+TextMessage::TextMessage( InArchive& from, const MessageInfo& info ) : RawMessage( from, info ) {}
+
+std::string TextMessage::text() const {
+ if ( body().size() == 0 )
+ return std::string();
+ return std::string( &( body() [ 0 ] ) );
+}
+
+SystemMessage::SystemMessage( const MessageConstructionInfo& info, Message msg, const string& ptext ) : TextMessage( info(this), ptext ), msg_( msg ) {}
+
+SystemMessage::SystemMessage( InArchive& arch, const MessageInfo& info ) : TextMessage( arch, info ) {
+ serial( arch );
+}
+
+void SystemMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+
+SystemMessage::Message SystemMessage::message() {
+ return msg_;
+}
+
+string SystemMessage::messageAsString() {
+ switch ( msg_ ) {
+ case LoginSuccess:
+ return "LoginSuccess";
+ case LoginFailedUnknown:
+ return "LoginFailedUnknown";
+ case BadAuthentication:
+ return "BadAuthentication";
+ case ServerBusy:
+ return "SeverBusy";
+ case Kicked:
+ return "Kicked";
+ case BadTarget:
+ return "BadTarget";
+ case StoredOnServer:
+ return "StoredOnServer";
+ case AlreadyLoggedIn:
+ return "AlreadyLoggedIn";
+ case GetUserList:
+ return "GetUserList";
+ case NoMessage:
+ return "NoMessage";
+ case SerializationFailed:
+ return "SerializationFailed";
+ };
+ return "";
+}
+
+
+TeamworkMessage::TeamworkMessage( const MessageConstructionInfo& info ) : RawMessage( info(this), DataVector() ) {}
+TeamworkMessage::TeamworkMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {}
+
+IdentificationMessage::IdentificationMessage( const MessageConstructionInfo& info, const User& user ) : TeamworkMessage( info(this) ), user_( user ) {}
+
+IdentificationMessage::IdentificationMessage( InArchive& arch, const MessageInfo& info ) : TeamworkMessage( arch, info ) {
+ serial( arch );
+}
+
+IdentificationMessage::operator User() {
+ return user_;
+}
+
+void IdentificationMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+
+
+ForwardMessage::ForwardMessage( const MessageConstructionInfo& info, MessageInterface* messageToForward, const User& source, const User& targ ) : RawMessage( info(this), DataVector( ) ), source_( source ), target_( targ ) {
+ serializeMessageToBuffer( body(), *messageToForward );
+ source_.stripForTarget( target_ );
+ target_.stripForIdentification();
+}
+
+ForwardMessage::ForwardMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {
+ serial( arch );
+}
+
+void ForwardMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch ) ;
+ serial( arch );
+}
+
+User& ForwardMessage::source() {
+ return source_;
+}
+
+User& ForwardMessage::target() {
+ return target_;
+}
+
+MessagePointer ForwardMessage::deserializeContained( MessageTypeSet& messageTypes ) {
+ try {
+ return buildMessageFromBuffer( body(), messageTypes, info().session() );
+ } catch ( ... ) {
+ return MessagePointer();
+ }
+}
+
+bool ForwardMessage::storeOnServer() {
+ return false;
+}
+
+UserListMessage::UserListMessage( const MessageConstructionInfo& info, list<UserPointer> inUsers, const UserPointer& targetUser ) : TeamworkMessage( info(this) ) {
+ for ( list<UserPointer>::iterator it = inUsers.begin(); it != inUsers.end(); ++it ) {
+ if ( *it == targetUser )
+ continue;
+
+ UserPointer::Locked l = *it;
+ if ( l ) {
+ if( !l->online() ) continue;
+ users.push_back( *l );
+ users.back().stripForPublic();
+ } else {
+ cout << "could not lock a user-pointer";
+ }
+ }
+}
+
+UserListMessage::UserListMessage( InArchive& arch, const MessageInfo& info ) : TeamworkMessage( arch, info ) {
+ serial( arch );
+}
+
+void UserListMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+
+INSTANTIATE_SERIALIZATION_FUNCTIONS( MessageType )
+
+REGISTER_MESSAGE( RawMessage )
+REGISTER_MESSAGE( TextMessage )
+REGISTER_MESSAGE( TeamworkMessage )
+REGISTER_MESSAGE( IdentificationMessage )
+REGISTER_MESSAGE( ForwardMessage )
+REGISTER_MESSAGE( SystemMessage )
+REGISTER_MESSAGE( UserListMessage )
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h (revision 1522570)
@@ -0,0 +1,207 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 is the file you should include when you only want to handle messages
+ *
+ * */
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "networkexport.h"
+#include <vector>
+#include <string>
+
+#ifndef MESSAGEINTERFACE_H
+#define MESSAGEINTERFACE_H
+
+namespace Teamwork {
+
+///UniqueMessageId represents the identity of a single message
+typedef uint64_t UniqueMessageId;
+
+///MessageType represents the Message-Type
+class NETWORK_EXPORT MessageType {
+ public:
+ typedef std::vector<unsigned char> IdList;
+ private:
+ IdList idList_;
+ unsigned int fastId_; ///can only be used when the idList has <= 4 entries
+ bool useFastId;
+ UniqueMessageId uniqueId_; ///This is only filled when the MessageType belongs to a Message(0 means invalid)
+ void packFastId();
+ public:
+ MessageType( IdList IDs = IdList() );
+
+ MessageType( InArchive& from );
+
+ template<class Archive>
+ void serialize( Archive& target, const uint /*version*/ = 0 );
+
+ ///Only compares the type-id, not the uniqueId
+ bool operator == ( const MessageType& rhs ) const;
+
+ bool operator < ( const MessageType& rhs ) const;
+
+ bool startsWith( const MessageType& rhs ) const;
+
+ ///Returns the length of the id
+ int length() const;
+
+ MessageType& operator += ( unsigned char append );
+
+ MessageType& operator -- ();
+
+ operator bool() const;
+
+ std::string desc() const;
+
+ operator const unsigned char*() const;
+};
+
+///this class holds information about the instance of a message(it's id and an optional pointer to the session/user it was created in/for)
+class NETWORK_EXPORT MessageInfo {
+ MessageType id_;
+ SessionPointer session_;
+ UserPointer user_;
+ MessagePointer replyToMessage_;
+ UniqueMessageId isReplyTo_;
+ UniqueMessageId uniqueId_;
+ bool deserialized_;
+ public:
+
+ //Only for temporary usage
+ MessageInfo();
+
+ MessageInfo( InArchive& arch );
+ MessageInfo( const MessageType& type, UniqueMessageId id );
+ MessageInfo( const MessageType& type, UniqueMessageId id, const SessionPointer& session, UniqueMessageId isReplyTo = 0 );
+ MessageInfo( const MessageInfo& rhs );
+ MessageInfo& operator = ( const MessageInfo& rhs );
+ ~MessageInfo();
+
+ ///The session this message was received through/has been sent through.(whether received or sent: see isIncoming() )
+ SessionPointer session() const;
+
+ ///The user this message is related to.
+ UserPointer user() const;
+
+ ///Sets the session, and invalidates the user. If the session has an associated user, the user is used instead.
+ void setSession( const SessionPointer& sess );
+
+ ///Sets the user and invalidates the session. All session()-calls will be redirected to the session associated to the user.
+ void setUser( const UserPointer& sess );
+
+ const MessageType& type() const;
+
+ void serialize( OutArchive& arch, const uint version = 0 );
+
+ /**The unique id is the identity of a message-instance, not of the message-type */
+ UniqueMessageId uniqueId() const;
+
+ /**Since the uniqueId is not used for sorting this casts away constness so the id of a MessageType that is used as Key in a Map can be changed */
+ void setUniqueId( UniqueMessageId newId ) const;
+
+ /** if the message is a reply to another message, this should be the uniqueId of the other message.
+ this function is thread-safe.(because after creation, this value should not be changed anymore) */
+ UniqueMessageId isReplyTo() const;
+
+ /** to make one message a reply to another while sending(to the other side), this is enough. To mark the message for local use, setReplyMessage(...) should be set too.*/
+ void setReply( UniqueMessageId replyId );
+
+ /** this does not automatically set the reply-id, it just sets a message-pointer. */
+ void setReplyMessage( const MessagePointer& msg );
+
+ ///If the reply is not handled directly by the message that the reply has gone to, the message this is a reply to is stored here.(The message with the id isReplyTo() ), may be invalid
+ const MessagePointer& replyToMessage() const;
+
+ void setId( const MessageType& id );
+
+ /**Removes all kept references to important objects like sessions(those might keep the sessions alive too long)
+ this should be called before a message is stored permanently */
+
+ void makePersistent();
+
+ ///Returns whether the message was constructed from a stream(if false, it was created locally)
+ bool isIncoming() const;
+
+ ///This can be used to set the isIncoming()-flag. The application or messages may use the flag as indication whether the message is incoming or outgoing.
+ void setIsIncoming( bool b );
+};
+
+/**Since messages can have different IDs in different Message-Sets, the id's cannot be hardcoded and must be given with each creation.
+That is simplified by using MessageTypeSet::create which directly fills the correct id
+To create and use an own message there's three things to do:
+1. Implement a message based on MessageInterface(or simpler based on RawMessage)
+2. Within the class-declaration, use the DECLARE_MESSAGE(name, parent, subindex)-macro to define the inheritance used in the message-tree
+3. Register the message to the used MessageTypeSet, to register it to globalMessageTypeSet() simply use the REGISTER_MESSAGE(Message)-macro(within an implementation-file).
+Now the message can be sent and received. */
+
+class NETWORK_EXPORT MessageInterface : public SafeShared /*, public virtual Serializable*/ {
+ public:
+
+ virtual void serialize( OutArchive& target ) = 0;
+
+ ///this function must be thread-safe(so the message does not need to be locked when it is called)
+ virtual MessageInfo& info() = 0;
+
+ virtual const MessageInfo& info() const = 0;
+
+ /**This is called once a message has been tried to be send, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
+ */
+ virtual void result( bool success ) = 0;
+
+ virtual ~MessageInterface();
+
+ ///This function is thread-safe
+ virtual const char* name();
+
+ ///This function must be implemented for all messages, it is atomatically cared about by the DECLARE_MESSAGE(..) macros etc.
+ static const char* staticName();
+
+ ///This is just a convenience-function that redirects to info().type()
+ const MessageType& type() const;
+
+ ///This is just a convenience-function that redirects to info().uniqueId()
+ UniqueMessageId uniqueId() const;
+
+ ///This should return "true" when the message wants a reply. gotReply will then be called once a reply has been received. The default-implementation returns false.
+ virtual bool needReply() const;
+
+ struct NETWORK_EXPORT ReplyResult {
+ bool messageHandled; ///This should indicate that the message was used locally and should not be handled on by higher instances
+ bool awaitingMore; ///whether the message is awaiting more replies.(if this is true, the message will not be deleted and needReply will be called again as soon as another reply arrives)
+ ReplyResult( bool messageHandled_ = false, bool awaitingMore_ = false );
+ }
+ ;
+ /** p can be invalid, that means that the reply timed out. It is not guaranteed that this function is called. See the description of ReplyResult. */
+ virtual ReplyResult gotReply( const MessagePointer& p );
+};
+}
+
+/**This class is used to derive messages from each other, it automatically creates some necessary entries for building static message-trees
+each message must have an explicit sub-id. You still have to care about
+the correct constructors.
+To create messages even easier and safer, see easymessage.h */
+
+#define DECLARE_MESSAGE( Name, parent, subindex ) \
+ public: \
+ inline static const char* staticName() { return #Name; } \
+ typedef parent Precursor; \
+ enum { \
+ preferredIndex = subindex \
+ }; \
+ virtual const char* name() { return staticName(); }; \
+ /*This little helper-functions returns true when the type as which the function is called is the real type of the message*/ \
+ inline bool isDerived() { return strcmp( #Name, name() ) != 0; } \
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt (revision 1522570)
@@ -0,0 +1,13 @@
+To build, this project needs:
+- Common C++
+- Boost iostream library
+- Boost serialization library
+
+Under Debian/Ubuntu, found below their respective package names:
+- libcommoncpp2-dev
+- libboost-iostreams-dev
+- libboost-serialization-dev
+
+Although this is located within the kdevelop-tree,
+kdevelop is no dependency of this code.
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,47 @@
+################################################################################################
+# This library needs to build without KDE4, please don't add KDE4 specific cmake stuff in here #
+################################################################################################
+
+PROJECT(network)
+
+SET(libfiles
+ serverconfig.cpp
+ message.cpp
+ basicserver.cpp
+ basicsession.cpp
+ messageimpl.cpp
+ helpers.cpp
+ teamworkserver.cpp
+ multisession.cpp
+ user.cpp
+ teamworkclient.cpp
+ forwardsession.cpp
+ logger.cpp
+ sessioninterface.cpp
+ dynamicmessagedispatcher.cpp
+ )
+
+SET(testfiles main.cpp )
+
+#add definitions, compiler switches, etc.
+
+#ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions -finline)
+#ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions -fno-inline)
+ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions)
+#list all source files here
+
+###### First Target ##########
+# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
+ADD_LIBRARY( kdevteamwork_network SHARED ${libfiles} )
+TARGET_LINK_LIBRARIES( kdevteamwork_network ${COMMONCPP2_LIBRARIES} ${Boost_SERIALIZATION_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${QT_QTCORE_LIBRARY})
+
+INSTALL(TARGETS kdevteamwork_network ${INSTALL_TARGETS_DEFAULT_ARGS})
+
+###### Next Target ##########
+
+ADD_EXECUTABLE( kdevteamwork_server ${testfiles} )
+TARGET_LINK_LIBRARIES( kdevteamwork_server ${QT_QTCORE_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} kdevteamwork_network ${COMMONCPP2_LIBRARIES} ${ZLIB_LIBRARIES} dl )
+
+INSTALL(TARGETS kdevteamwork_server ${INSTALL_TARGETS_DEFAULT_ARGS})
+
+#ADD_DEPENDENCIES( kdevteamwork_server network )
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp (revision 1522570)
@@ -0,0 +1,335 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "basicserver.h"
+#include "basicsession.h"
+#include "teamworkserver.h"
+#include "messageimpl.h"
+#include "teamworkclient.h"
+#include "dynamicmessagedispatcher.h"
+#include <assert.h>
+#include <vector>
+#include <list>
+#include "handler.h"
+#include "serverconfig.h"
+#include "defines.h"
+
+using namespace Teamwork;
+#define USE_DYNAMIC_DISPATCHER
+
+#define CHECKARGS(b) if( !(b) ) { cout << "wrong argument-count"; return 3; }
+#define NEXTARG if( argc > 0 ) arg = argv[0]; else arg = ""; --argc;
+
+int changeSettings( int argc, char * argv[] ) {
+ /*NEXTARG;
+ NEXTARG;*/
+ std::string arg = argv[1];
+ cout << "\n\n\n\n";
+ if( arg == "--help" || arg == "--info" || arg == "?" ) {
+ cout << "possible commands configuration-manipulation-commands(everything within the [] is optional): \n";
+ cout << "--adduser username [password] | Add the user to the list of known users\n";
+ cout << "--serverpassword [password] | Change the server-wide password which is used for users without an own password. If empty, access is made public.\n";
+ cout << "--servername name | Change the name of the server\n";
+ cout << "--deluser username | delete a user from the list of known users\n";
+ cout << "--list | list all registered users\n";
+ cout << "--show | show current settings of the server\n";
+ cout << "--setrights username [banned][admin][trusted] | change the rights of the user(no argument for normal user-rights)\n";
+ cout << "--setport [port] | change the port the server is opened on(if the port is left away the default-port("<<STANDARDPORT<<") is used)\n";
+ cout << "--setbind [address] | change the address the server is bound to(if it is left away the default(0.0.0.0) is used)\n";
+ cout << "\nAll these commands manipulate the configuration-file created in the run-directory. \nThe settings will then apply for the next start of the server.\n";
+ cout << "only one of the commands can be called at one time.\n";
+ return 0;
+ }
+
+ ServerConfiguration conf;
+ if( !Teamwork::loadServerConfiguration( conf ) ) {
+ cout << "could not load the configuration-file" << endl;
+ }
+ bool changed = false;
+
+ if( arg == "--setport" ) {
+ NEXTARG;
+ if( argc > 2 ) {
+ conf.port = strtol( argv[2], 0, 10 );
+ } else {
+ conf.port = STANDARDPORT;
+ }
+ cout << "changed the port to " << conf.port << endl;
+ changed = true;
+ }
+ if( arg == "--setbind" ) {
+ if( argc > 2 ) {
+ conf.bind = argv[2];
+ } else {
+ conf.bind = "0.0.0.0";
+ }
+ cout << "changed the bound address to " << conf.bind << endl;
+ changed = true;
+ }
+
+ if( arg == "--setrights" ) {
+ CHECKARGS( argc > 2 );
+ std::string username = argv[2];
+
+ int rights = User::UserRights;
+
+ for( int n = 3; n < argc; n++ ) {
+ if( argv[n] == std::string( "admin" ) ) rights |= User::AdminRights;
+ if( argv[n] == std::string( "trusted" ) ) rights |= User::TrustedRights;
+ }
+
+ for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
+ //UserPointer::Locked l = *it;
+ if( it->name() == username ) {
+ User u = *it;
+ const_cast<User&>(*it).setRights( rights );
+ changed = true;
+ cout << "successfully set rights for " << it->name() << ": " << it->rightsAsString() << endl;
+ break;
+ }
+ }
+ if( !changed )
+ cout << "could not find user \"" << username << "\"" << endl;
+ }
+
+ if( arg == "--show" ) {
+ cout << "server-name: \"" << conf.serverName << "\"\n";
+ cout << "server-password: \"" << conf.serverPassword << "\"\n";
+ cout << "count of registered users: " << conf.registeredUsers.size() << endl;
+ cout << "locally bound to address: " << conf.bind << " on port:" << conf.port << endl;
+ }
+
+ if( arg == "--list" ) {
+ cout << "users:" << endl;
+ for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
+ //UserPointer::Locked l = *it;
+ cout << it->name();
+ if( !it->password().empty() )
+ cout << " (has password)";
+ cout << " rights: " << it->rightsAsString();
+ cout << endl;
+ }
+ }
+
+ if( arg == "--adduser" ) {
+ CHECKARGS( argc > 2 );
+ std::string username = argv[2];
+ std::string password;
+ if( argc > 3 )
+ password = argv[3];
+
+ bool passwordChanged = false;
+
+ for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
+ //UserPointer::Locked l = *it;
+ if( it->name() == username ) {
+ if( !password.empty() ) {
+ const_cast<User&>(*it).setPassword( password );
+ passwordChanged = true;
+ break;
+ } else {
+ cout << "the user named \"" << username << "\" already exists" << endl;
+ return 1;
+ }
+ }
+ }
+
+ if( passwordChanged ) {
+ cout << "\"" << username << "\"'s password changed to: \"" << password << "\""<< endl;
+ } else {
+ cout << "user \"" << username << "\" added, password: \"" << password << "\""<< endl;
+ conf.registeredUsers.insert( Teamwork::User( username, password ) );
+ }
+ changed = true;
+ }
+
+ if( arg == "--deluser" ) {
+ CHECKARGS( argc > 2 );
+ std::string username = argv[2];
+ std::string password;
+ if( argc > 3 )
+ password = argv[3];
+
+ bool found = false;
+ for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
+ //UserPointer::Locked l = *it;
+ if( it->name() == username ) {
+ found = true;
+ conf.registeredUsers.erase( it );
+ break;
+ }
+ }
+
+ if( found ) {
+ changed = true;
+ cout << "user \"" << username << "\" removed" << endl;
+ } else {
+ cout << "user \"" << username << "\" is not registered" << endl;
+ return 4;
+ }
+ }
+
+ if( arg == "--serverpassword" ) {
+ if( argc > 2 ) {
+ conf.serverPassword = std::string( argv[2] );
+ cout << "server-password changed to \"" << conf.serverPassword << "\"" << endl;
+ } else {
+ if( conf.serverPassword.empty() ) {
+ cout << "server-password already was disabled" << endl;
+ } else {
+ conf.serverPassword = "";
+ cout << "server-password disabled" << endl;
+ }
+ }
+ changed = true;
+ }
+
+ if( arg == "--servername" ) {
+ CHECKARGS( argc > 2 );
+ conf.serverName = std::string( argv[2] );
+ changed = true;
+ cout << "server-name changed to \"" << conf.serverName << "\"" << endl;
+ }
+
+ if( arg == "--servername" ) {
+ CHECKARGS( argc > 2 );
+ conf.serverName = std::string( argv[2] );
+ changed = true;
+ }
+
+
+ if( changed ) {
+ if( !Teamwork::saveServerConfiguration( conf ) ) {
+ cout << "failed to save the configuration-file" << endl;
+ return 2;
+ }
+ } else {
+ cout << "bad arguments, see --help" << endl;
+ }
+
+ return 1;
+}
+
+using namespace Teamwork;
+
+#ifndef USE_DYNAMIC_DISPATCHER
+
+///Version that uses the static message-dispatcher
+class StandaloneServer : public Teamwork::Server {
+ typedef Binder< RawMessage > :: Append< TextMessage > :: Result MessagesToDispatch;
+ public:
+ StandaloneServer( int port, std::string bind ) : Teamwork::Server( ServerInformation( bind, port ), new Logger() ) {
+ }
+ virtual ~StandaloneServer() {}
+
+ int receiveMessage( TextMessage* msg ) {
+ out() << "standalone-server got text-message: " << msg->text() << " real message-type: " << msg->name();
+ return 1;
+ }
+
+ int receiveMessage( MessageInterface* msg ) {
+ UserPointer::Locked lu = msg->info().user();
+ out() << "standalone-server got unknown message: " << msg->name() << " from: " << (lu ? lu->name() : "unknown user" );
+ return 1;
+ }
+
+ virtual bool handleMessage( MessagePointer m ) throw() {
+ MessageDispatcher< StandaloneServer, MessagesToDispatch > dispatcher(*this);
+ dispatcher( m.lock ().data() );
+ return Teamwork::Server::handleMessage( m );
+ }
+};
+
+#else
+
+///Version that uses the dynamic message-dispatcher (use these as examples)
+class StandaloneServer : public Teamwork::Server {
+ DynamicMessageDispatcher dispatcher_;
+ public:
+ StandaloneServer( int port, std::string bind ) : Teamwork::Server( ServerInformation( bind, port ), new Logger() ) {
+ dispatcher_.registerCallback<TextMessage>( this, &StandaloneServer::receiveTextMessage );
+ dispatcher_.registerCallback<MessageInterface>( this, &StandaloneServer::receiveUnknownMessage );
+ }
+ virtual ~StandaloneServer() {}
+
+ int receiveTextMessage( const SafeSharedPtr<TextMessage>& smsg ) {
+ LockedSharedPtr<TextMessage> msg = smsg;
+ out() << "standalone-server got text-message: " << msg->text() << " real message-type: " << msg->name();
+ return 1;
+ }
+
+ int receiveUnknownMessage( const SafeSharedPtr<MessageInterface>& smsg ) {
+ LockedSharedPtr<MessageInterface> msg = smsg;
+ UserPointer::Locked lu = msg->info().user();
+ out() << "standalone-server got unknown message: " << msg->name() << " from: " << (lu ? lu->name() : "unknown user" );
+ return 1;
+ }
+
+ virtual bool handleMessage( MessagePointer m ) throw() {
+ if( dispatcher_( m ) )
+ return true;
+ return Teamwork::Server::handleMessage( m );
+ }
+};
+
+#endif
+
+int server() {
+ ServerConfiguration conf;
+ if( !Teamwork::loadServerConfiguration( conf ) ) {
+ cout << "could not load the configuration-file, using defaults" << endl;
+ }
+
+ SafeSharedPtr<StandaloneServer> serv = new StandaloneServer( conf.port, conf.bind );
+ serv.unsafe()->setConfiguration( conf );
+ serv.unsafe() ->start();
+ serv.unsafe() ->allowIncoming( true );
+ cout << "server running on port " << conf.port << endl;
+
+ serv.unsafe() ->join();
+ return 0;
+}
+
+
+void test2() {
+ globalMessageTypeSet().stats();
+ SafeSharedPtr<Client> client1 = new Client( ServerInformation( "0.0.0.0", 8155 ) );
+ client1.unsafe() ->allowIncoming( true );
+ client1.unsafe() ->start();
+ SafeSharedPtr<Client> client2 = new Client( ServerInformation( "0.0.0.0", 8156 ) );
+ client2.unsafe() ->allowIncoming( true );
+ client2.unsafe() ->start();
+ {
+ SafeSharedPtr<Client>::Locked l = client1;
+ l->connectToServer( ServerInformation( "127.0.0.1", 8156 ), new User( "david", "honk", "I am a user" ) );
+ }
+
+ client2.unsafe() ->join();
+}
+
+
+int main( int argc, char * argv[] ) {
+ if( argc > 1 ) {
+ if( strcmp(argv[1], "test") != 0 ) {
+ return changeSettings( argc, argv );
+ } else {
+ test2();
+ }
+ }
+ server();
+
+ return EXIT_SUCCESS;
+}
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h (revision 1522570)
@@ -0,0 +1,347 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef WEAKPOINTER_H
+#define WEAKPOINTER_H
+
+#include "safesharedptr.h"
+#include "networkexport.h"
+
+class WeakSafeShared;
+class WeakShared;
+
+#ifndef WEAKSAFESHAREDPTR_HAVE_DEFAULT
+#define WEAKSAFESHAREDPTR_HAVE_DEFAULT
+template<class Type, class Serialization = NormalSerialization>
+class WeakSafeSharedPtr;
+#endif
+
+
+class NETWORK_EXPORT WeakReference : public SafeShared {
+ WeakSafeShared* pointer_;
+ friend class WeakSafeShared;
+
+ void invalidate() {
+ pointer_ = 0;
+ };
+ public:
+ WeakReference( WeakSafeShared* pointer ) : pointer_( pointer ) {}
+ WeakSafeShared* pointer() {
+ return pointer_;
+ }
+};
+
+class NETWORK_EXPORT WeakSafeShared : protected SafeShared {
+ SafeSharedPtr<WeakReference> ref_;
+
+ virtual void prepareDeletion() {
+ LockedSharedPtr<WeakReference> l = ref_.lock();
+ if ( l )
+ l->invalidate();
+ }
+
+ public:
+ WeakSafeShared() : ref_( new WeakReference( this ) ) {}
+
+ inline WeakSafeShared &operator=( const WeakSafeShared & ) {
+ return * this;
+ }
+
+ const SafeSharedPtr<WeakReference>& _WeakSafeShared_getRef() const {
+ return ref_;
+ }
+
+ using SafeShared::lockCountUp;
+
+ using SafeShared::tryLockCountUp;
+
+ using SafeShared::lockCountDown;
+
+ using SafeShared::_Shared_count;
+
+ using SafeShared::_Shared_ref;
+
+ using SafeShared::_Shared_unref;
+};
+
+/** This header gives an additional type of pointer with a higher level. It's functionality is similar to that of QPointer.
+ Holding a pointer of type WeakSafeShared, does not increase the reference-count of the pointed object. If the object is deleted,
+ the pointer is set to zero. This comes with additional cost. The pointed object must be based on WeakSafeShared, and for each creation of
+ that type one additional allocation of an internal SafeShared-object(especially a mutex) is done.
+
+ WeakSafeSharedPtr itself does not consume more memory than SafeSharedPtr, but locking-operations are more costly, because two locks are done instead of one.
+ */
+
+template <class Item, class Serialization>
+class NETWORK_EXPORT WeakSafeSharedPtr {
+ SafeSharedPtr<WeakReference> ref_;
+ public:
+ WeakSafeSharedPtr() {}
+
+ template <class Input>
+ WeakSafeSharedPtr( const Input& ptr ) {
+ set
+ ( ptr );
+ }
+
+ SafeSharedPtr<Item, Serialization> get
+ () const {
+ typename SafeSharedPtr<WeakReference>::Locked l = ref_;
+ if ( !l )
+ return 0;
+ return SafeSharedPtr<Item, Serialization>( dynamic_cast<Item*>( l->pointer() ) );
+ }
+
+ template <class Item2, class Serialization2>
+ void set
+ ( const SafeSharedPtr<Item2, Serialization2>& item ) {
+ typename SafeSharedPtr<Item2, Serialization2>::Locked l = item;
+ if ( !l ) {
+ ref_ = 0;
+ return ;
+ } else {
+ ref_ = static_cast<Item*>( l.data() ) ->_WeakSafeShared_getRef(); ///The item must be compatible
+ }
+ }
+
+ void set
+ ( const Item* item ) {
+ if ( !item )
+ ref_ = 0;
+ else
+ ref_ = item->_WeakSafeShared_getRef();
+ }
+
+ WeakSafeSharedPtr<Item, Serialization> operator = ( const Item* item ) {
+ set
+ ( item );
+ return *this;
+ }
+
+ template <class Item2, class Serialization2>
+ WeakSafeSharedPtr<Item, Serialization> operator = ( const SafeSharedPtr<Item2, Serialization2> item ) {
+ set
+ ( item );
+ return *this;
+ }
+
+ ///Using this is same as locking a SafeSharedPtr, it uses the default-timeout.
+ operator LockedSharedPtr<Item> () const {
+ Item * p;
+ {
+ LockedSharedPtr<WeakReference> l = ref_;
+ if ( !l )
+ return 0;
+ p = reinterpret_cast<Item*>( l->pointer() );
+ }
+ return LockedSharedPtr<Item>( SharedPtr<Item>( p ), SafeSharedLockTimeout );
+ }
+
+ template <class Serialization2>
+ inline bool operator == ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
+ if ( !rhs && !ref_ )
+ return true;
+ typename SafeSharedPtr<WeakReference>::Locked l = ref_;
+ if ( !l )
+ return false;
+
+ return l->pointer() == ( WeakSafeShared* ) rhs.unsafe();
+ }
+
+ inline bool operator == ( const LockedSharedPtr<Item>& rhs ) const {
+ if ( !rhs && !ref_ )
+ return true;
+ LockedSharedPtr<WeakReference> l = ref_;
+ if ( !l )
+ return false;
+
+ return l->pointer() == ( WeakSafeShared* ) rhs.unsafe();
+ }
+
+ template <class Serialization2>
+ inline bool operator == ( const SharedPtr<Item, Serialization2>& rhs ) const {
+ if ( !rhs && !ref_ )
+ return true;
+ LockedSharedPtr<WeakReference> l = ref_;
+ if ( !l )
+ return false;
+
+ return l->pointer() == ( WeakSafeShared* ) rhs.data();
+ }
+
+ inline bool operator == ( const Item* rhs ) const {
+ if ( !rhs && !ref_ )
+ return true;
+ LockedSharedPtr<WeakReference> l = ref_;
+ if ( !l )
+ return false;
+
+ return l->pointer() == ( WeakSafeShared* ) rhs;
+ }
+};
+
+class NETWORK_EXPORT NormalWeakReference : public Shared {
+ WeakShared* pointer_;
+ friend class WeakShared;
+
+ void invalidate() {
+ pointer_ = 0;
+ };
+ public:
+ NormalWeakReference( WeakShared* pointer ) : pointer_( pointer ) {}
+ WeakShared* pointer() {
+ return pointer_;
+ }
+ const WeakShared* pointer() const {
+ return pointer_;
+ }
+};
+
+/** To use WeakSharedPtr on an object, that object must be based this type.
+ */
+
+class NETWORK_EXPORT WeakShared : private Shared {
+ SharedPtr<NormalWeakReference> ref_;
+
+ virtual void prepareDeletion() {
+ ref_->invalidate();
+ }
+
+ public:
+ WeakShared() : ref_( new NormalWeakReference( this ) ) {}
+
+ inline WeakShared &operator=( const WeakShared & ) {
+ return * this;
+ }
+
+ const SharedPtr<NormalWeakReference>& _WeakShared_getRef() const {
+ return ref_;
+ }
+
+ using Shared::_Shared_count;
+
+ using Shared::_Shared_ref;
+
+ using Shared::_Shared_unref;
+};
+
+template <class Item, class Serialization = NormalSerialization>
+class NETWORK_EXPORT WeakSharedPtr {
+ SharedPtr<NormalWeakReference> ref_;
+ public:
+ WeakSharedPtr() {}
+
+ template <class Input>
+ WeakSharedPtr( const Input& ptr ) {
+ set
+ ( ptr );
+ }
+
+ Item* get
+ () {
+ if ( !ref_ )
+ return 0;
+ return ( Item* ) ref_->pointer();
+ }
+
+ Item* get
+ () const {
+ if ( !ref_ )
+ return 0;
+ return ( Item* ) const_cast<WeakShared*>( ref_->pointer() );
+ }
+
+ void set
+ ( const Item* item ) {
+ if ( !item )
+ ref_ = 0;
+ else
+ ref_ = item->_WeakShared_getRef();
+ }
+
+ /*WeakSharedPtr<Item, Serialization> operator = ( const Item* item ) {
+ set
+ ( item );
+ return *this;
+ }*/
+
+ WeakSharedPtr<Item, Serialization> operator = ( const WeakSharedPtr<Item, Serialization>& item ) {
+ set
+ ( item );
+ return *this;
+ }
+
+ /*operator SharedPtr<Item>() const {
+ return get();
+ }*/
+
+ operator Item*() {
+ return get
+ ();
+ }
+
+ operator Item*() const {
+ return const_cast<Item*>( get
+ () );
+ }
+
+ Item* operator ->() {
+ return get
+ ();
+ }
+
+ ///This leads to another order than sorting equivalent normal pointers
+ bool operator < ( const WeakSharedPtr<Item, Serialization>& rhs ) const {
+ return ref_ < rhs.ref_;
+ }
+
+ operator bool() const {
+ return ( bool ) get
+ ();
+ }
+
+ const Item* operator ->() const {
+ return get
+ ();
+ }
+
+ operator SharedPtr<Item, Serialization>() const {
+ return SharedPtr<Item, Serialization>( get() );
+ }
+
+ bool operator == ( const Item* rhs ) const {
+ if ( !rhs && !ref_ )
+ return true;
+ if ( !ref_ )
+ return false;
+
+ return ref_->pointer() == ( WeakShared* ) rhs;
+ }
+
+ bool operator == ( const WeakSharedPtr<Item, Serialization>& rhs ) const {
+ return ref_ == rhs.ref_;
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, int /*version*/ ) {
+ SharedPtr<Item, Serialization> it( get
+ () );
+ arch & it;
+ set
+ ( it );
+ }
+};
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h (revision 1522570)
@@ -0,0 +1,189 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef EASYMESSAGE
+#define EASYMESSAGE
+#include "messagetypeset.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/base_object.hpp>
+
+/**
+This header offers by far the easiest way of declaring a message.
+The Macro
+EASY_DECLARE_MESSAGE( Name, Parent, index, Data, paramSplitPosition )
+Declares a complete Message named "Name", derived from "Parent", and also derived on a custom data-structure called "Data".
+That Data-structure should implement a classic boost "template<class Archive> void serialize( Archive& arch )"-function,
+and should have a default-constructor to create the structure while loading.
+Also it can have a normal constructor with arbitrary count of arguments. That Argument-count must be given in the last
+macro-parameter called "paramSplitPosition". Then, all parameters given to the function-constructor up to the specified count will
+be given to the Data-constructor, and all other parameters to the Parent.
+Unlike the rest of the messaging-system, the Data-structure may use the standard boost-serialization versioning-system.
+
+EASY_IMPLEMENT_MESSAGE(MessageName) must be used in a source-file to implement the message.
+EASY_IMPLEMENT_MESSAGE also calls REGISTER_MESSAGE, so that doesn't have to be done separately when this system is used.
+
+The constructors can be specialized to fit special needs(see EASY_CONSTRUCTOR_...)
+
+If you want to override virtual functions or want to access protected members, use
+EASY_DECLARE_MESSAGE_BEGIN(...)
+override your functions here(this is inside of the classes body)
+END()
+
+
+*/
+
+//These are class-initialization-declarations for with different redirections to Data / Parent
+//First: Total count of parameters, second: how many of them go into Data
+#define PARAMETER_SPLIT_0_0(Data, Parent) Data(), Parent( info(this) )
+#define PARAMETER_SPLIT_0_1(Data, Parent) Data(), Parent( info(this) )
+#define PARAMETER_SPLIT_0_2(Data, Parent) Data(), Parent( info(this) )
+#define PARAMETER_SPLIT_0_3(Data, Parent) Data(), Parent( info(this) )
+#define PARAMETER_SPLIT_0_4(Data, Parent) Data(), Parent( info(this) )
+#define PARAMETER_SPLIT_0_5(Data, Parent) Data(), Parent( info(this) )
+
+#define PARAMETER_SPLIT_1_0(Data, Parent) Data(), Parent( info(this), p1 )
+#define PARAMETER_SPLIT_1_1(Data, Parent) Data( p1 ), Parent( info(this) )
+#define PARAMETER_SPLIT_1_2(Data, Parent) Data( p1 ), Parent( info(this) )
+#define PARAMETER_SPLIT_1_3(Data, Parent) Data( p1 ), Parent( info(this) )
+#define PARAMETER_SPLIT_1_4(Data, Parent) Data( p1 ), Parent( info(this) )
+#define PARAMETER_SPLIT_1_5(Data, Parent) Data( p1 ), Parent( info(this) )
+
+#define PARAMETER_SPLIT_2_0(Data, Parent) Data(), Parent( info(this), p1, p2 )
+#define PARAMETER_SPLIT_2_1(Data, Parent) Data(p1), Parent( info(this), p2 )
+#define PARAMETER_SPLIT_2_2(Data, Parent) Data(p1, p2), Parent( info(this) )
+#define PARAMETER_SPLIT_2_3(Data, Parent) Data(p1, p2), Parent( info(this) )
+#define PARAMETER_SPLIT_2_4(Data, Parent) Data(p1, p2), Parent( info(this) )
+#define PARAMETER_SPLIT_2_5(Data, Parent) Data(p1, p2), Parent( info(this) )
+
+#define PARAMETER_SPLIT_3_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3 )
+#define PARAMETER_SPLIT_3_1(Data, Parent) Data(p1), Parent( info(this), p2, p3 )
+#define PARAMETER_SPLIT_3_2(Data, Parent) Data(p1, p2), Parent( info(this), p3 )
+#define PARAMETER_SPLIT_3_3(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
+#define PARAMETER_SPLIT_3_4(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
+#define PARAMETER_SPLIT_3_5(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
+
+#define PARAMETER_SPLIT_4_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3, p4 )
+#define PARAMETER_SPLIT_4_1(Data, Parent) Data(p1), Parent( info(this), p2, p3, p4 )
+#define PARAMETER_SPLIT_4_2(Data, Parent) Data(p1, p2), Parent( info(this), p3, p4 )
+#define PARAMETER_SPLIT_4_3(Data, Parent) Data(p1, p2, p3), Parent( info(this), p4 )
+#define PARAMETER_SPLIT_4_4(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this) )
+#define PARAMETER_SPLIT_4_5(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this) )
+
+#define PARAMETER_SPLIT_5_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3, p4, p5 )
+#define PARAMETER_SPLIT_5_1(Data, Parent) Data(p1), Parent( info(this), p2, p3, p4, p5 )
+#define PARAMETER_SPLIT_5_2(Data, Parent) Data(p1, p2), Parent( info(this), p3, p4, p5 )
+#define PARAMETER_SPLIT_5_3(Data, Parent) Data(p1, p2, p3), Parent( info(this), p4, p5 )
+#define PARAMETER_SPLIT_5_4(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this), p5 )
+#define PARAMETER_SPLIT_5_5(Data, Parent) Data(p1, p2, p3, p4, p5), Parent( info(this) )
+
+#define EASY_CONSTRUCTOR(Name, Parent, index, Data, SplitPosition) \
+inline Name( const Teamwork::MessageConstructionInfo& info ) : Data(), Parent( info(this) ) { \
+} \
+template<class Param1> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1 ) : PARAMETER_SPLIT_ ## 1 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1> \
+Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1 ) : PARAMETER_SPLIT_ ## 1 ## _ ## SplitPosition (Data,Parent) { \
+} \
+\
+template<class Param1, class Param2> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2> \
+Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, const Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2> \
+Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, const Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
+} \
+\
+template<class Param1, class Param2, class Param3> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3> \
+Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, const Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3> \
+Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, const Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
+} \
+\
+template<class Param1, class Param2, class Param3, class Param4> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3, Param4& p4 ) : PARAMETER_SPLIT_ ## 4 ## _ ## SplitPosition (Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3, class Param4> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, const Param3& p3, const Param4& p4 ) : PARAMETER_SPLIT_ ## 4 ## _ ## SplitPosition(Data,Parent) { \
+} \
+template<class Param1, class Param2, class Param3, class Param4, class Param5> \
+Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3, Param4& p4, Param5& p5 ) : PARAMETER_SPLIT_ ## 5 ## _ ## SplitPosition(Data,Parent) { \
+} \
+/**/
+
+
+//The first 4 lines of the following macros are used to store the values for the implementation, so they must not be given to the implementation again
+#define EASY_DECLARE_MESSAGE_BEGIN( Name, Parent, index, Data, paramSplitPosition ) \
+class Name : public Data, public Parent { \
+DECLARE_MESSAGE( Name, Parent, index ); \
+typedef Data DataType; \
+ public: \
+ \
+EASY_CONSTRUCTOR ( Name, Parent, index, Data, paramSplitPosition ) \
+virtual void serialize( OutArchive& arch ); \
+Name( InArchive& arch, const Teamwork::MessageInfo& info ); \
+/**/
+
+#define EASY_IMPLEMENT_MESSAGE(Name) \
+ void Name :: serialize( OutArchive& arch ) { \
+ Precursor::serialize( arch ); \
+ /*static_cast<DataType&>(*this).serialize( arch, 0 );*/ \
+ arch & boost::serialization::base_object<DataType>(*this); \
+} \
+Name :: Name ( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) { \
+ /*static_cast<DataType&>(*this).serialize( arch, 0 );*/ \
+ arch & boost::serialization::base_object<DataType>(*this); \
+} \
+REGISTER_MESSAGE(Name) \
+/**/
+
+
+#define END() \
+}
+
+#define EASY_DECLARE_MESSAGE( Name, Parent, index, Data, paramSplitPosition ) \
+EASY_DECLARE_MESSAGE_BEGIN( Name, Parent, index, Data, paramSplitPosition ) \
+END()
+
+///Can be used as a dummy for EASY_DECLARE_MESSAGE, if no data is wished
+struct NoData {
+ template <class Archive>
+ void serialize( Archive& /*arch*/, unsigned int /*version*/ ) {}
+}
+;
+
+template <class T = int>
+struct NoDataB {
+ template <class Archive>
+ void serialize( Archive& /*arch*/, unsigned int /*version*/ ) {}
+}
+;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h (revision 1522570)
@@ -0,0 +1,36 @@
+/*
+ This file is part of the KDevelop platform
+ Copyright 2006 Matt Rogers <mattr@kde.org>
+ Copyright 2004 Jarosław Staniek <staniek@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef NETWORKEXPORT_H
+#define NETWORKEXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+#ifndef NETWORK_XPORT
+# ifdef MAKE_NETWORK_LIB
+# define NETWORK_EXPORT KDE_EXPORT
+# else
+# define NETWORK_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif /* NETWORKEXPORT_H*/
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h (revision 1522570)
@@ -0,0 +1,148 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+//#define NO_SEND_HELPER
+
+#ifndef MESSAGESENDHELPER_H
+#define MESSAGESENDHELPER_H
+
+#include "networkfwd.h"
+#include "sessioninterface.h"
+#include "messageinterface.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+ class MessageTypeSet;
+
+///A little helper-class that allows creating types with less writing(can be imported into any class by inheritance)
+class NETWORK_EXPORT MessageSendHelper {
+ MessageTypeSet& types_;
+ public:
+ MessageSendHelper( MessageTypeSet& types = globalMessageTypeSet() ) : types_( types ) {}
+
+#ifndef NO_SEND_HELPER
+
+ /**The following is a set of little helper-functions that are used to reduce the mass of code.
+ * They are used to send message, which includes their construction.
+ * */
+ template <class MessageType>
+ inline bool send( SessionInterface* s ) {
+ return s->send( new MessageType( types_ ) );
+ }
+
+ template <class MessageType, class ParamType1>
+ inline bool send( SessionInterface* s, const ParamType1& param ) {
+ return s->send( new MessageType( types_, param ) );
+ }
+ template <class MessageType, class ParamType1, class ParamType2>
+ inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2 ) {
+ return s->send( new MessageType( types_, param, param2 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2>
+ inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2 ) {
+ return s->send( new MessageType( types_, param, param2 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
+ inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3 ) {
+ return s->send( new MessageType( types_, param, param2, param3 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
+ inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3 ) {
+ return s->send( new MessageType( types_, param, param2, param3 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
+ inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4 ) {
+ return s->send( new MessageType( types_, param, param2, param3, param4 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
+ inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4 ) {
+ return s->send( new MessageType( types_, param, param2, param3, param4 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
+ inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4, const ParamType5& param5 ) {
+ return s->send( new MessageType( types_, param, param2, param3, param4, param5 ) );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
+ inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4, ParamType5& param5 ) {
+ return s->send( new MessageType( types_, param, param2, param3, param4, param5 ) );
+ }
+
+ template <class MessageType>
+ inline bool sendReply( MessageInterface* replyTo ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_ ), replyTo );
+ }
+
+ template <class MessageType, class ParamType1>
+ inline bool sendReply( MessageInterface* replyTo, const ParamType1& param ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param ), replyTo );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2>
+ inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2 ), replyTo );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2>
+ inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2 ), replyTo );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
+ inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2, ParamType3& param3 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3 ), replyTo );
+ }
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
+ inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2, const ParamType3& param3 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3 ), replyTo );
+ }
+
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
+ inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3, param4 ), replyTo );
+ }
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
+ inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4 ) {
+ if ( !replyTo->info().session() )
+ return false;
+ return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3, param4 ), replyTo );
+ }
+#endif
+};
+
+///This can be used to simply send messages using the global message-type-set, @todo remove this
+NETWORK_EXPORT MessageSendHelper& globalMessageSendHelper();
+}
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h (revision 1522570)
@@ -0,0 +1,75 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef MESSAGETYPESETINTERNAL_H
+#define MESSAGETYPESETINTERNAL_H
+
+#include "statictree.h"
+#include "messageinterface.h"
+#include <string>
+#include "networkexport.h"
+
+#define DISABLEWARNINGS
+
+namespace Teamwork {
+using namespace Tree;
+class MessageInfo;
+struct NETWORK_EXPORT MessageFactoryInterface {
+ virtual MessagePointer buildMessage( InArchive& from , const MessageInfo& inf ) = 0;
+ virtual std::string identify() = 0;
+#ifdef DISABLEWARNINGS
+ virtual ~MessageFactoryInterface() {}
+#endif
+}
+;
+
+template <class MessageType>
+struct NETWORK_EXPORT MessageFactory : public MessageFactoryInterface {
+ virtual MessagePointer buildMessage( InArchive& from, const MessageInfo& inf ) {
+ return MessagePointer( new MessageType( from, inf ) );
+ }
+ virtual std::string identify() {
+ return MessageType::staticName();
+ }
+
+#ifdef DISABLEWARNINGS
+ virtual ~MessageFactory() {}
+#endif
+}
+;
+
+template < class Type, class Target >
+struct NETWORK_EXPORT RegisterAllTypes {
+ static void reg( Target& targ ) {
+ targ.Error_Bad_Type_List();
+ };
+};
+
+template < class Type, class Parent, uchar preferredSubId, class Target >
+struct NETWORK_EXPORT RegisterAllTypes< Chain< Type, Parent, preferredSubId >, Target > {
+ static void reg( Target& targ ) {
+ targ.template registerMessageType< Type, Parent > ( preferredSubId );
+ };
+};
+
+template < class Side1, class Side2, class Target >
+struct NETWORK_EXPORT RegisterAllTypes< Binder< Side1, Side2 >, Target > {
+ static void reg( Target& targ ) {
+ RegisterAllTypes< Side2, Target >::reg( targ );
+ RegisterAllTypes< Side1, Target >::reg( targ );
+ };
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h (revision 1522570)
@@ -0,0 +1,57 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef MUTEXINTERFACE_H
+#define MUTEXINTERFACE_H
+
+#include <QMutex>
+#include "networkexport.h"
+
+class NETWORK_EXPORT MutexInterfaceImpl {
+ mutable QMutex m_;
+ public:
+ MutexInterfaceImpl( const MutexInterfaceImpl& /*rhs*/ ) : m_(QMutex::Recursive) {
+ }
+
+ const MutexInterfaceImpl& operator=( const MutexInterfaceImpl& /*rhs*/ ) {
+ return *this;
+ }
+
+ MutexInterfaceImpl() {}
+
+ void lockCountUp() const {
+ m_.lock();
+ }
+
+ bool tryLockCountUp() const {
+ return m_.tryLock();
+ }
+
+ ///timeout in nanoseconds, may have a significant delay, so it shouldn't be used too much
+ bool tryLockCountUp( int timeout ) const {
+ if(timeout) {
+ timeout /= 1000000; //nanoseconds -> milliseconds
+ if(timeout)
+ timeout = 1;
+ }
+ return m_.tryLock( timeout );
+ }
+
+ void lockCountDown() const {
+ m_.lock();
+ };
+
+ ~MutexInterfaceImpl() {}
+};
+
+typedef MutexInterfaceImpl MutexInterface;
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h (revision 1522570)
@@ -0,0 +1,399 @@
+/* This file is part of the KDE libraries
+Copyright 1999 Waldo Bastian <bastian@kde.org>
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License version 2 as published by the Free Software Foundation.
+
+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.
+*/
+#ifndef SharedPTR_H
+#define SharedPTR_H
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/split_member.hpp>
+#include "networkexport.h"
+
+/**
+ * Warning: Not thread-safe: use SafeShared for thread-safe reference-counting.
+ * Reference counting for shared objects. If you derive your object
+ * from this class, then you may use it in conjunction with
+ * SharedPtr to control the lifetime of your object.
+ *
+ * Specifically, all classes that derive from Shared have an internal
+ * counter keeping track of how many other objects have a reference to
+ * their object. If used with SharedPtr, then your object will
+ * not be deleted until all references to the object have been
+ * released.
+ *
+ * You should probably not ever use any of the methods in this class
+ * directly -- let the SharedPtr take care of that. Just derive
+ * your class from Shared and forget about it.
+ *
+ * @author Waldo Bastian <bastian@kde.org>
+ */
+class NETWORK_EXPORT Shared {
+ public:
+ /**
+ * Standard constructor. This will initialize the reference count
+ * on this object to 0.
+ */
+ Shared() : count( 0 ) { }
+
+ /**
+ * Copy constructor. This will @em not actually copy the objects
+ * but it will initialize the reference count on this object to 0.
+ */
+ Shared( const Shared & ) : count( 0 ) { }
+
+ /**
+ * Overloaded assignment operator.
+ */
+ Shared &operator=( const Shared & ) {
+ return * this;
+ }
+
+ /**
+ * Increases the reference count by one.
+ */
+ void _Shared_ref() const {
+ count++;
+ }
+
+ /**
+ * Releases a reference (decreases the reference count by one). If
+ * the count goes to 0, this object will delete itself.
+ */
+ void _Shared_unref() const {
+ if ( !--count )
+ delete this;
+ }
+
+ /**
+ * Return the current number of references held.
+ *
+ * @return Number of references
+ */
+ int _Shared_count() const {
+ return count;
+ }
+
+ protected:
+ virtual ~Shared() { }
+ private:
+ mutable int count;
+};
+
+///NormaSerialization serializes the object in a primitive way by just calling the objects serialization-method.
+
+struct NETWORK_EXPORT NormalSerialization {
+ template <class Type, class Archive, class Target>
+ static void load( Target& t, Archive& arch, int /*version*/ ) {
+ bool b = false;
+ arch >> b;
+ if ( b ) {
+ t = new Type();
+ t->serialize( arch, 0 );
+ } else {
+ t = 0;
+ }
+ }
+
+ template <class Type, class Archive, class Target>
+ static void save( Target& t, Archive& arch, int /*version*/ ) {
+ if ( t ) {
+ bool b = true;
+ arch << b;
+ const_cast<Type&>( *t ).serialize( arch, 0 );
+ } else {
+ bool b = false;
+ arch << b;
+ }
+ }
+};
+
+
+template <class Type, class Container>
+struct extractItemUnsafe {
+ static Type* extract( const Container& cont ) {
+ return const_cast<Type*>( cont.unsafe() );
+ }
+};
+
+
+/**BoostSerialization relies on boost's pointer-serialization(Which includes tracking, versioning, etc.).
+ * Objects serialized this way must be registered to the boost serialization-system.
+*/
+struct NETWORK_EXPORT BoostSerialization {
+ template <class Type, class Archive, class Target>
+ static void load( Target& t, Archive& arch, int /*version*/ ) {
+ bool b = false;
+ arch >> b; //boost::serialization::make_nvp("valid",b);
+ if ( b ) {
+ Type * pnt = 0;
+ arch & pnt;
+ t = pnt;
+ } else {
+ t = 0;
+ }
+ }
+
+ template <class Type, class Archive, class Target>
+ static void save( Target& t, Archive& arch, int /*version*/ ) {
+ if ( t ) {
+ bool b = true;
+ arch << b; //boost::serialization::make_nvp("valid",b);
+ const Type* pnt = extractItemUnsafe<Type, Target>::extract( t );
+ arch & pnt;
+ } else {
+ bool b = false;
+ arch << b; //boost::serialization::make_nvp("valid",b);
+ }
+ }
+};
+
+struct BoostSerializationNormal {
+ template <class Type, class Archive, class Target>
+ static void load( Target& t, Archive& arch, int /*version*/ ) {
+ bool b = false;
+ arch >> b; //boost::serialization::make_nvp("valid",b);
+ if ( b ) {
+ Type * pnt = 0;
+ arch & pnt;
+ t = pnt;
+ } else {
+ t = 0;
+ }
+ }
+
+ template <class Type, class Archive, class Target>
+ static void save( Target& t, Archive& arch, int /*version*/ ) {
+ if ( t ) {
+ bool b = true;
+ arch << b; //boost::serialization::make_nvp("valid",b);
+ const Type* pnt = t.data();
+ arch & pnt;
+ } else {
+ bool b = false;
+ arch << b; //boost::serialization::make_nvp("valid",b);
+ }
+ }
+};
+/**
+ * Can be used to control the lifetime of an object that has derived
+ * Shared. As long a someone holds a SharedPtr on some Shared
+ * object it won't become deleted but is deleted once its reference
+ * count is 0. This struct emulates C++ pointers virtually perfectly.
+ * So just use it like a simple C++ pointer.
+ *
+ * Shared and SharedPtr are preferred over QShared / QSharedPtr
+ * since they are more safe.
+ *
+ * WARNING: Please note that this class template provides an implicit
+ * conversion to T*. Do *not* change this pointer or the pointee (don't
+ * call delete on it, for instance) behind SharedPtr's back.
+ *
+ * @author Waldo Bastian <bastian@kde.org>
+ */
+
+template < class T, class Serialization = NormalSerialization >
+class NETWORK_EXPORT SharedPtr {
+ public:
+ friend class NormalSerialization;
+ /**
+ * Creates a null pointer.
+ */
+ inline SharedPtr()
+ : ptr( 0 ) { }
+ /**
+ * Creates a new pointer.
+ * @param t the pointer
+ */
+ inline SharedPtr( T* t )
+ : ptr( t ) {
+ if ( ptr )
+ ptr->_Shared_ref();
+ }
+
+ /**
+ * Copies a pointer.
+ * @param p the pointer to copy
+ */
+ inline SharedPtr( const SharedPtr& p )
+ : ptr( p.ptr ) {
+ if ( ptr )
+ ptr->_Shared_ref();
+ }
+
+ /**
+ * Unreferences the object that this pointer points to. If it was
+ * the last reference, the object will be deleted.
+ */
+ inline ~SharedPtr() {
+ if ( ptr )
+ ptr->_Shared_unref();
+ }
+
+ SharedPtr<T, Serialization>& operator= ( const SharedPtr<T, Serialization>& p ) {
+ if ( ptr == p.ptr )
+ return * this;
+ if ( ptr )
+ ptr->_Shared_unref();
+ ptr = p.ptr;
+ if ( ptr )
+ ptr->_Shared_ref();
+ return *this;
+ }
+
+ template <class Serialization2>
+ SharedPtr<T, Serialization>& operator= ( const SharedPtr<T, Serialization2>& p ) {
+ if ( ptr == p.ptr )
+ return * this;
+ if ( ptr )
+ ptr->_Shared_unref();
+ ptr = p.ptr;
+ if ( ptr )
+ ptr->_Shared_ref();
+ return *this;
+ }
+
+ SharedPtr<T, Serialization>& operator= ( T* p ) {
+ if ( ptr == p )
+ return * this;
+ if ( ptr )
+ ptr->_Shared_unref();
+ ptr = p;
+ if ( ptr )
+ ptr->_Shared_ref();
+ return *this;
+ }
+ template <class Serialization2>
+ inline bool operator== ( const SharedPtr<T, Serialization2>& p ) const {
+ return ( ptr == p.ptr );
+ }
+ template <class Serialization2>
+ inline bool operator!= ( const SharedPtr<T, Serialization2>& p ) const {
+ return ( ptr != p.ptr );
+ }
+ inline bool operator== ( const T* p ) const {
+ return ( ptr == p );
+ }
+ inline bool operator!= ( const T* p ) const {
+ return ( ptr != p );
+ }
+ inline bool operator!() const {
+ return ( ptr == 0 );
+ }
+ inline operator T*() const {
+ return ptr;
+ }
+
+ /**
+ * Returns the pointer.
+ * @return the pointer
+ */
+ inline T* data() {
+ return ptr;
+ }
+
+ /**
+ * Returns the pointer.
+ * @return the pointer
+ */
+ inline const T* data() const {
+ return ptr;
+ }
+
+ /* inline const T& operator*() const {
+ return * ptr;
+ }*/
+ inline T& operator*() {
+ return * ptr;
+ }
+ inline T& operator*() const {
+ return * const_cast<T*>( ptr );
+ }
+ /*inline const T* operator->() const {
+ return ptr;
+ }*/
+ inline T* operator->() const {
+ return const_cast<T*>( ptr ); ///That a reference to a pointer is constant does not mean that the pointed-to object is constant(to me)
+ }
+
+ template <class Archive>
+ void load( Archive& arch, int /*version*/ ) {
+ Serialization::template load<T>
+ ( *this, arch, 0 );
+ }
+
+ template <class Archive>
+ void save( Archive& arch, int /*version*/ ) const {
+ Serialization::template save<T>
+ ( *this, arch, 0 );
+ }
+ /*
+ ///pointers without target are sorted as lowest
+ template <class OT>
+ bool operator < ( const SharedPtr<OT>& rhs ) const {
+ if( ptr ) {
+ if( rhs.ptr ) {
+ return *ptr < *rhs.ptr;
+ } else {
+ return true;
+ }
+ } else {
+ if( rhs.ptr ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ template <class OT>
+ bool operator < ( const OT& rhs ) const {
+ if( ptr ) {
+ return *ptr < rhs;
+ } else {
+ return true;
+ }
+ }*/
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+
+ /**
+ * Returns the number of references.
+ * @return the number of references
+ */
+ inline int count() const {
+ return ptr->_Shared_count();
+ } // for debugging purposes
+ private:
+ T* ptr;
+};
+
+
+template <class Type, class Serialization>
+struct extractItemUnsafe<Type, SharedPtr<Type, Serialization> > {
+ static Type* extract( const SharedPtr<Type, Serialization>& cont ) {
+ return const_cast<Type*>( cont.data() );
+ }
+};
+
+/*template<class Type, class Serialization>
+Type* extractItemUnsafe( const SharedPtr< Type, Serialization >& cont ) {
+return const_cast<Type*>( cont.data() );
+}*/
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h (revision 1522570)
@@ -0,0 +1,97 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MULTISESSION_H
+#define MULTISESSION_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "serialization.h"
+#include "messagetypeset.h"
+#include "safesharedptr.h"
+#include "basicserver.h"
+#include "basicsession.h"
+#include <string>
+#include <list>
+#include <map>
+#include <set>
+#include "sharedptr.h"
+#include "teamworkmessages.h"
+#include "teamworkservermessages.h"
+#include "user.h"
+#include "messagesendhelper.h"
+//#include "forwardsession.h"
+#include "serverconfig.h"
+
+
+namespace Teamwork {
+class ServerInformation;
+/** MultiSession extends BasicTCPSession with the ability to manage virtual sub-sessions to users reachable through a forwarding server.
+ * It is created by Teamwork::Server and Teamwork::Client
+* */
+
+class NETWORK_EXPORT MultiSession : public BasicTCPSession {
+ bool incoming_;
+ typedef std::map<UserPointer, ForwardSessionPointer, UserPointer::ValueSmallerCompare> ForwardSessionMap;
+ ForwardSessionMap forwardSessions_;
+ std::list<ForwardSessionPointer> garbageSessions_;
+
+ protected:
+
+ void deleteForwardSessions();
+
+ virtual void final();
+
+ public:
+ MultiSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger );
+
+ MultiSession( const ServerInformation& server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
+
+ bool operator < ( const MultiSession& rhs ) const {
+ return this < ( &rhs );
+ }
+
+ ///true if the session is an incoming one(connected to the local server), else returns false
+ bool incoming() {
+ return incoming_;
+ }
+
+ virtual bool think();
+
+ virtual ~MultiSession();
+
+ void registerForwardSession( const UserPointer& peer, const ForwardSessionPointer& sess );
+
+ virtual bool handleMessage( MessagePointer msg ) throw();
+
+ ForwardSessionPointer getForwardSession( const UserPointer& user ) {
+ ForwardSessionMap::const_iterator it = forwardSessions_.find( user );
+ if ( it != forwardSessions_.end() )
+ return ( *it ).second;
+ else
+ return 0;
+ }
+
+ list<UserPointer> getUserList() {
+ list<UserPointer> ret;
+ for ( ForwardSessionMap::const_iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ++it ) {
+ ret.push_back( ( *it ).first );
+ }
+ return ret;
+ }
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h (revision 1522570)
@@ -0,0 +1,265 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGE_H
+#define MESSAGE_H
+
+#include "networkfwd.h"
+#include <map>
+#include <string>
+#include <iostream>
+#include "messagetypesetinternal.h"
+
+#include "messageinterface.h"
+#include "networkexport.h"
+
+#define MAXMESSAGESIZE 50000000
+#define DISABLEWARNINGS
+
+#define USE_RTTI
+
+template <class Message>
+const char* staticMessageName() {
+ return Message::staticName();
+}
+
+namespace Teamwork {
+
+using namespace Tree;
+
+/**This allows multiple differing dispatch-targets(like the server + the thread). */
+class NETWORK_EXPORT MessageTypeSet {
+ //protected:
+ ///this should be optimized, and all the no more necessary template dispatch-code above removed
+ typedef std::map<MessageType, MessageFactoryInterface* > TypeMap;
+ typedef std::map<std::string, MessageType> TypeNameMap;
+ TypeMap types_; ///would be more efficient to build a tree from the Chains and walk through that
+ TypeNameMap ids_;
+
+ ///this should walk through the messages upwards until it finds the best match
+ TypeMap::iterator search( const MessageType& id );
+
+ MessageType allocateSubId( const MessageType& id, int preferredSubId = 0 );
+
+ mutable UniqueMessageId currentUniqueMessageId_;
+
+ ///Changes the given id to the matching one
+ MessageFactoryInterface* findFactory( MessageType& id ) const;
+ public:
+ MessageTypeSet();
+
+ MessagePointer buildMessage( InArchive& from, const MessageInfo& inf ) const;
+
+ ~MessageTypeSet();
+
+ //Returns the message-type mapped to a message-name. A message-name in rtti (typeid(Message).name()) format is also accepted for messages derived from MessageInterface
+ const MessageType& idFromName( const std::string& name ) const;
+
+ std::string stats() const;
+
+ ///returns the class-name of the message(the most specialized one registered in this type-set)
+ std::string identify( MessageInterface* msg ) const;
+
+ ///Register a static list of message-types to this type-set. Not yet registered parent-messages are automatically registered too.
+ template < class Types >
+ void registerMessageTypes() {
+ RegisterAllTypes< typename Tree::MakeComplete< typename Tree::ExtractChains< Types >::Result, MessageInterface > ::Result, MessageTypeSet >::reg ( *this );
+ }
+
+ /** registers a type as slave of another given type, for simlicity registerMessageTypes should be used instead, together with a whole list of types */
+ template <class Message, class ParentMessage>
+ MessageType registerMessageType( int preferredSubId = 0 ) {
+ if ( ids_.find( staticMessageName<Message>() ) != ids_.end() )
+ return ids_[ staticMessageName<Message>() ];
+
+ MessageType parentId = type<ParentMessage>();
+ MessageType myId = allocateSubId( parentId, preferredSubId );
+ if ( !parentId && typeid( ParentMessage ) != typeid( MessageInterface ) )
+ std::cout << "while registering \"" << staticMessageName<Message>() << "\" the id of \"" << staticMessageName<ParentMessage>() << "\" could not be allocated!" << endl;
+ if ( myId ) {
+ //std::cout << "registering message-type " << staticMessageName<Message>() << " with id " << myId.desc() << endl;
+ ids_[ staticMessageName<Message>() ] = myId;
+ ids_[ typeid(Message).name() ] = myId;
+ if ( types_.find( myId ) != types_.end() )
+ delete types_[ myId ];
+ types_[ myId ] = new MessageFactory<Message>();
+ } else {
+ std::cout << "could not allocate id for message-type " << staticMessageName<Message>() << endl;
+ ///No ID could be allocated
+ }
+ return myId;
+ }
+
+ template <class Type>
+ inline const MessageType& type() {
+ return idFromName( staticMessageName<Type>() );
+ }
+
+// MessageInterface* changeUniqueId( MessageInterface* msg ) {
+// msg->info().setUniqueId( currentUniqueMessageId_++ );
+// return msg;
+// }
+
+ /** Returns a new correctly filled MessageInfo-structure, that also contains a vald UniqueId.
+ * */
+ template<class Message>
+ MessageInfo messageInfo() const {
+ return MessageInfo( idFromName( staticMessageName<MessageType>() ), currentUniqueMessageId_++ );
+ }
+
+ /**Returns a new correctly filled MessageInfo-structure, that also contains a vald UniqueId,
+ * by the name as which the message is registered, or by the message's rtti-name.
+ * */
+ MessageInfo messageInfo(const char* name) const {
+ return MessageInfo( idFromName( name ), currentUniqueMessageId_++ );
+ }
+ /*
+ //For now the following is disabled to test whether it can be conveniently replaced with something that isn't that bad for executable-size
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType>
+ inline MessageType* create() {
+ return (MessageType*) changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ) ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1>
+ inline MessageType* create( ParamType1 param ) {
+ return (MessageType*) changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1, class ParamType2>
+ inline MessageType* create( ParamType1 param, ParamType2 param2 ) {
+ return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2 ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
+ inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3 ) {
+ return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3 ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
+ inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4 ) {
+ return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4 ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
+ inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5 ) {
+ return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4, param5 ) );
+ }
+ ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
+ template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5, class ParamType6>
+ inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5, ParamType6 param6 ) {
+ return (MessageType*)setUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4, param5, param6 ) );
+ }
+ */
+};
+
+/**This is a message-type-set dedicated only to dispatching a chosen set of message-types
+to a chosen dispatch-target. It delivers the given message as the most special type the message
+is based on, by calling "TargetType::receiveMessage( MessageType* )".
+ * @param TargetType must be the type the messages should be delivered to
+ * @param Messages must be the list of messages(without any inheritance-info)*/
+template <class TargetType, class Messages>
+class NETWORK_EXPORT MessageDispatcher {
+ TargetType& targ_;
+
+ struct EntryTemplate {
+ template <class MessageType>
+ struct Entry {
+ int dispatch( TargetType& targ, MessageInterface* msg ) const {
+ //std::cout << "dispatching as " << staticMessageName<MessageType>() << endl;
+ ///Do the dispatch from the MessageDispatcher, so it can be declared friend and the dispatch-functions can be private.
+ return MessageDispatcher<TargetType, Messages>::template dispatch<MessageType>
+ ( targ, msg );
+ }
+ };
+ };
+
+ struct Action {
+ TargetType& targ;
+ MessageInterface* msg;
+ int ret;
+
+ Action( TargetType& target, MessageInterface* mesg ) : targ( target ), msg( mesg ), ret( 0 ) {}
+ template <class Type, class Node>
+ void operator () ( const Node& node ) {
+ ret = node.dispatch( targ, msg );
+ }
+ };
+
+ typedef Tree::TreeMasterNode< MessageInterface, Messages, EntryTemplate > Nodes;
+ Nodes nodes_;
+ public:
+ MessageDispatcher( TargetType& targ ) : targ_( targ ) {}
+
+ ///dispatches the message to the target that was given while construction
+ int operator () ( MessageInterface* msg ) {
+ Action act( targ_, msg );
+ nodes_.find( msg->type(), act );
+ return act.ret;
+ }
+
+ template <class Out>
+ void print( Out& out ) {
+#ifdef USE_RTTI
+ out << "Full Tree of " << typeid( *this ).name() << "\n";
+ nodes_.print( out );
+#else
+ out << "cannot print Message-Tree because RTTI is disabled" << "\n";
+#endif
+ }
+
+ template < class MessageType >
+ static int dispatch( TargetType& targ, MessageInterface* msg ) {
+ if ( dynamic_cast<MessageType*>( msg ) ) //this is just a security-check, which should hopefully never trigger
+ return targ.receiveMessage( ( MessageType* ) msg );
+ else
+ cerr << "serious error in the message-type-system!";
+ return 0;
+ }
+};
+
+
+///This message-type-set contains all messages that were registered by a call to REGISTER_MESSAGE, and may be used instead of the local type-sets, for simplicity. That way messages can be serialized/deserialized without the core-parts being aware that they exist.
+MessageTypeSet& NETWORK_EXPORT globalMessageTypeSet();
+
+template <class MessageType>
+class NETWORK_EXPORT RegisterMessageTypeInternal {
+ public:
+ RegisterMessageTypeInternal() {
+ globalMessageTypeSet().registerMessageTypes<MessageType>();
+ }
+};
+
+/**This should be used directly from outside to globally register new message-types.
+The messages should have used the DECLARE_MESSAGE(...)-macro.
+*/
+#define REGISTER_MESSAGE(TYPE) \
+struct registerType##TYPE { \
+ RegisterMessageTypeInternal<TYPE> msgReg;\
+ registerType##TYPE() : msgReg() {} \
+}; \
+registerType##TYPE register##TYPE; \
+
+}
+
+#ifndef USE_RTTI
+
+BOOST_CLASS_IMPLEMENTATION( Teamwork::MessageInfo, boost::serialization::object_serializable );
+
+#endif
+
+#endif
+
+#include "user.h"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/handler.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/handler.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/handler.h (revision 1522570)
@@ -0,0 +1,48 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef HANDLER_H
+#define HANDLER_H
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+class NETWORK_EXPORT HandlerInterface : public SafeShared {
+ public:
+ virtual ~HandlerInterface() {}
+ /**When the handler is multithreaded, this function must be thread-safe by just queueing the Message to a secure list and processing later.
+ No locking must be done within this function, since it may cause deadlocks as the handler itself tries to lock the message-sender */
+ virtual bool handleMessage( MessagePointer msg ) = 0;
+};
+
+template <class Target>
+struct NETWORK_EXPORT HandlerProxy : public HandlerInterface {
+ WeakSafeSharedPtr<Target> handler_;
+ HandlerProxy( const SafeSharedPtr<Target>& targ ) : handler_( targ ) {}
+
+ virtual bool handleMessage( MessagePointer msg ) {
+ SafeSharedPtr<Target> targ = handler_.get();
+ if ( targ )
+ return targ.unsafe() ->handleMessage( msg );
+ else
+ return false;
+ }
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/handler.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h (revision 1522570)
@@ -0,0 +1,100 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 file needs to be included into any file where boost-serialization takes place
+ * */
+
+#ifndef SERIALIZATION_H
+#define SERIALIZATION_H
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+
+#include "networkfwd.h"
+
+#ifdef USE_TEXT_ARCHIVE
+#include <boost/archive/text_iarchive.hpp>
+#include <boost/archive/text_oarchive.hpp>
+#endif
+
+#ifdef USE_POLYMORPHIC_ARCHIVE
+#include <boost/archive/polymorphic_iarchive.hpp>
+#include <boost/archive/polymorphic_oarchive.hpp>
+#endif
+
+#ifdef USE_BINARY_ARCHIVE
+#include <boost/archive/binary_iarchive.hpp>
+#include <boost/archive/binary_oarchive.hpp>
+#endif
+
+#ifdef USE_XML_ARCHIVE
+#include <boost/archive/xml_iarchive.hpp>
+#include <boost/archive/xml_oarchive.hpp>
+#endif
+
+
+//#include <boost/serialization/base_object.hpp>
+#include <boost/serialization/extended_type_info.hpp>
+//#include <boost/serialization/utility.hpp>
+//#include <boost/serialization/list.hpp>
+//#include <boost/serialization/vector.hpp>
+#include <boost/serialization/level.hpp>
+#include <vector>
+#include "networkexport.h"
+
+namespace Teamwork {
+
+ class NETWORK_EXPORT TeamworkError : public std::exception {
+ std::string str_;
+ public:
+ TeamworkError( const std::string& str ) {
+ str_ = str;
+ }
+ virtual ~TeamworkError() throw() {}
+
+ virtual const char* what ( ) const throw () {
+ return str_.c_str();
+ }
+ };
+
+ ///This error may be thrown while serialization and it will only stop the message from being sent, it will not close the session.
+ struct NETWORK_EXPORT NonFatalSerializationError : public TeamworkError {
+ NonFatalSerializationError( const std::string& str ) : TeamworkError( "non-fatal serialization-error: " + str ) {}
+ }
+ ;
+
+ /**Normally while debugging, all messages are tested by serializing,
+ *then rebuilding, serializing the rebuilt message, and comparing the
+ *created streams. If this test fails, the message is not sent. in some
+ *cases that behavior is not appropriate. Then this exception can be thrown
+ *while reserializing or rebuilding the message, to make clear that the
+ *message should be sent anyway. */
+ struct NETWORK_EXPORT CannotReserialize : public NonFatalSerializationError {
+ CannotReserialize() : NonFatalSerializationError( "the message cannot be serialized after being deserialized" ) {}
+ }
+ ;
+
+ class NETWORK_EXPORT StreamError : public TeamworkError {
+ public:
+ StreamError( const std::string& str ) : TeamworkError( "Stream-Error: " + str ) {}
+ }
+ ;
+}
+
+/**Because gcc does not support the export-keyword template-functions that are not in the header need to be explicitly instantiated.
+ * This is a convenience-macro to instantiate the two default serialization-functions(for InArchive and OutArchive)
+ * */
+#define INSTANTIATE_SERIALIZATION_FUNCTIONS(Class) \
+template void Class::serialize( InArchive& arch, const uint ); \
+template void Class::serialize( OutArchive& arch, const uint );
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h (revision 1522570)
@@ -0,0 +1,164 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef BASICSESSION
+#define BASICSESSION
+
+#include <cc++/socket.h>
+#include <vector>
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "safelist.h"
+#include "logger.h"
+#include "sessioninterface.h"
+#include <map>
+#include "networkexport.h"
+
+namespace Teamwork {
+
+ class NETWORK_EXPORT SessionReplyManager {
+ typedef std::map<uint, MessagePointer> WaitingMap;
+ MutexInterfaceImpl* selfMutex_;
+ WaitingMap waitingMessages_; ///here, all messages that wait for a reply are stored, mapped to their unique-ids.
+ protected:
+ SessionReplyManager( MutexInterfaceImpl* selfMutex );
+
+ void addWaitingMessage( MessageInterface* msg );
+
+ bool handleMessageWaiting( MessagePointer & msg );
+
+ void removeAllMessages();
+
+ virtual ~SessionReplyManager();
+};
+
+class NETWORK_EXPORT BasicTCPSession : protected ost::TCPSession, /*public virtual SafeShared,*/ public SessionInterface, public SessionReplyManager {
+ public:
+ using Thread::setName;
+ using Thread::getName;
+
+ ///Used by the server to construct a session
+ BasicTCPSession( ost::TCPSocket &server, HandlerPointer handler_, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
+
+ ///Used by the client to connect to a server
+ BasicTCPSession( const ost::InetHostAddress &host, ost::tpport_t port, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
+
+ virtual ~BasicTCPSession();
+
+ virtual bool isOk();
+
+ virtual void startSession();
+
+ /**After this function was called, the thread is going to exit soon.
+ once isRunning() returns false, it can be deleted(better call join()).*/
+ virtual void stopRunning();
+
+ ///This should get some tolerance in future
+ virtual void stopRunningNow();
+
+ ///THREAD-SAFE
+ virtual bool send( MessageInterface* msg );
+
+ ///Returns whether the thread is running
+ virtual bool isRunning();
+
+ ///Starts the thread, should be called after the thread was constructed
+ using Thread::start;
+
+ using Thread::join;
+
+ using Socket::isPending;
+
+ virtual string peerDesc();
+
+ virtual string localDesc();
+
+ virtual SessionDirection sessionDirection();
+
+ protected:
+
+ virtual LoggerPrinter err( int prio = 0 );
+
+ virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
+
+ /**This can be reimplemented to decompress/decrypt the message.*/
+ virtual void processIncomingMessage( std::vector<char>& /*data*/ ) {}
+ ;
+
+ /**This can be reimplemented to add compression or encryption. The data can be changed however desired.
+ It is called just before the message is sent. */
+ virtual void processOutgoingMessage( std::vector<char>& /*data*/ ) {}
+ ;
+
+ /**This can be overridden to possibly handle messages directly in this object.
+ The default-implementation just sends the messages to the handler which created this session.*/
+ virtual bool handleMessage( MessagePointer msg ) throw() ;
+
+ ///This can be overridden to do some work on a regular basis. Returns whether more time is needed.
+ virtual bool think() {
+ return false;
+ }
+
+ ///This can be overridden to do final cleanup, store settings/state etc.
+ virtual void final( void );
+
+ virtual void initial();
+
+ ///After this is called, the object may well be deleted
+ void clearSelfPointer();
+
+ virtual void initName( const string& namePrefix );
+
+ private:
+ virtual void run();
+
+ void removeAllMessages();
+
+ bool inputOutput();
+
+ void serializeMessage();
+
+ ///Takes all Data that was written away from the std::vector, throws StreamError
+ template <class DataType>
+ u32 writeData( std::vector<DataType>& from, u32 max );
+
+ ///Appends the data to the given std::vector, throws StreamError
+ template <class DataType>
+ u32 getData( std::vector<DataType>& to, u32 max );
+
+ void failed( std::string reason = "" );
+
+ void sendingResult( bool result );
+
+ bool dataToSend();
+
+ SessionDirection myDirection;
+ static const int ConnectionTimeout;
+ bool exit_, failed_, running_, hadFinal_;
+ uint receivingSize_;
+ HandlerPointer handler_;
+ LoggerPointer logger_;
+ MessageTypeSet& messages_;
+ std::vector<char> lookBack_;
+ SafeList<MessagePointer> messagesToSend_;
+ std::vector<char> sendData_;
+ MessagePointer sendingMessage_; ///when sendData_ is not empty, this holds the message that is currently sent.
+ std::vector<char> receivingData_;
+ SafeSharedPtr<BasicTCPSession> selfPointer_; ///This is necessary to avoid deletion of the object before the thread has completed running
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h (revision 1522570)
@@ -0,0 +1,123 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef BASICSERVER_H
+#define BASICSERVER_H
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "weaksafesharedptr.h"
+#include "safelist.h"
+#include "logger.h"
+#include "networkexport.h"
+
+#include <cc++/socket.h>
+
+namespace Teamwork {
+template <class Target>
+struct HandlerProxy;
+
+class NETWORK_EXPORT BasicTCPSocket : public ost::TCPSocket {
+ protected:
+ bool onAccept( const ost::InetHostAddress &ia, ost::tpport_t port );
+
+ public:
+ BasicTCPSocket( ost::InetAddress &ia, int port );
+};
+
+/**This class runs the server as the run()-method is called in the same ost::Thread.
+This class never deletes itself, it can be deleted from outside once isRunning() returns false or the threads are joined, or it can be deleted through a SharedPtr/SafeSharedPtr.
+For each client that connects, it creates a session derived from BasicSession, which can also be
+created by a derived class.
+ */
+class NETWORK_EXPORT BasicServer : protected ost::Thread, public WeakSafeShared {
+ public:
+ BasicServer( const char* str, int port, MessageTypeSet& messageTypes, LoggerPointer logger, bool openServer = true );
+
+ virtual ~BasicServer();
+
+ virtual bool isOk();
+
+ ///returns the reference to a synchronized list of messages that are waiting for being processed. Processed messages should be removed from that list.
+ SafeList<MessagePointer>& messages();
+
+ /**After this function was called, the ost::Thread is going to exit soon.
+ once isRunning() returns false, it can be deleted.*/
+ void stopRunning();
+
+ ///Returns whether the ost::Thread is running
+ using ost::Thread::isRunning;
+
+ ///Starts the ost::Thread, should be called after the ost::Thread was constructed
+ using ost::Thread::start;
+
+ using ost::Thread::join;
+
+ ///This can be used to allow/disallow incoming connections. Already connected clients are not kicked on deactivation.
+ void allowIncoming( bool allow );
+
+ protected:
+
+ ///this one is called from within another Thread, so it is more useful to override processMessage(...) in the teamwork-server than this one
+ virtual bool handleMessage( MessagePointer msg ) throw();
+
+ virtual LoggerPrinter err();
+
+ virtual LoggerPrinter out( Logger::Level level = Logger::Info );
+
+ virtual void run();
+
+ /**This is called once at the beginning of the Thread*/
+ virtual void initial();
+
+ /**Gets called regularly from within the server-Thread
+ should be overridden, can return whether it needs more cpu-time*/
+ virtual bool think();
+
+ /**This is called once at end of the Thread*/
+ virtual void final( void );
+
+ /**In this function, the derived class should take the ownership of the session. If it refuses the ownership, it can return false.
+ once it has the ownership, it also has to care about proper
+ Must be ovverridden. */
+ virtual bool registerSession( SessionPointer /*session*/ );
+
+ ///Returns a logger object that allows logging to the correct places
+ LoggerPointer& logger();
+ protected:
+ MessageTypeSet& messageTypes_;
+ private:
+ ///This object is possible deleted during this call
+ void clearSelfPointer();
+
+ friend class HandlerProxy<BasicServer>;
+ ost::BroadcastAddress addr;
+ LoggerPointer logger_;
+ bool failed_, exit_, allowIncoming_;
+ BasicTCPSocket* server_;
+ int port_;
+ SafeList<MessagePointer> messagesToHandle_;
+ SafeSharedPtr< BasicServer > selfPointer_;
+
+ void buildSocket();
+
+ void closeSocket();
+
+ /**can be overridden to create own types derived from BasicTCPSession, can return 0(reject connection). Not called for forwarded sessions.*/
+ virtual SessionPointer createSession( BasicTCPSocket* sock );
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h (revision 1522570)
@@ -0,0 +1,108 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef NETWORKFWD_H
+#define NETWORKFWD_H
+
+#include "networkexport.h"
+
+//#define USE_POLYMORPHIC_ARCHIVE
+#define USE_TEXT_ARCHIVE
+
+class MessageSerialization;
+class NormalSerialization;
+class BoostSerialization;
+
+#ifndef SAFESHAREDPTR_HAVE_DEFAULT
+#define SAFESHAREDPTR_HAVE_DEFAULT
+template<class Type, class Serialization = NormalSerialization>
+class SafeSharedPtr;
+#endif
+
+#ifndef WEAKSAFESHAREDPTR_HAVE_DEFAULT
+#define WEAKSAFESHAREDPTR_HAVE_DEFAULT
+template<class Type, class Serialization = NormalSerialization>
+class WeakSafeSharedPtr;
+#endif
+
+namespace boost {
+ namespace archive {
+ class binary_oarchive;
+ class binary_iarchive;
+
+ class text_oarchive;
+ class text_iarchive;
+
+ class xml_oarchive;
+ class xml_iarchive;
+
+ class polymorphic_iarchive;
+ class polymorphic_oarchive;
+ }
+}
+
+namespace Teamwork {
+ class HandlerInterface;
+ class BasicTCPSession;
+ class SessionInterface;
+ class MultiSession;
+ class ForwardSession;
+ class BasicServer;
+ class MessageInterface;
+ class User;
+ class UserIdentity;
+ class Logger;
+ class LoggerPrinter;
+ class MessageTypeSet;
+
+ class ClientSessionDesc;
+ class ServerInformation;
+ class Server;
+
+ typedef SafeSharedPtr<HandlerInterface> HandlerPointer;
+ typedef SafeSharedPtr<SessionInterface> SessionPointer;
+ typedef SafeSharedPtr<BasicServer> ServerPointer;
+ typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
+ typedef SafeSharedPtr<User, BoostSerialization> UserPointer;
+ typedef SafeSharedPtr<Logger> LoggerPointer;
+ typedef SafeSharedPtr<MultiSession> MultiSessionPointer;
+ typedef SafeSharedPtr<ForwardSession> ForwardSessionPointer;
+
+ typedef WeakSafeSharedPtr<SessionInterface> WeakSessionPointer;
+
+ #ifdef USE_BINARY_ARCHIVE
+ typedef boost::archive::binary_oarchive OutArchive;
+ typedef boost::archive::binary_iarchive InArchive;
+ #endif
+
+ #ifdef USE_POLYMORPHIC_ARCHIVE
+ typedef boost::archive::polymorphic_oarchive OutArchive;
+ typedef boost::archive::polymorphic_iarchive InArchive;
+ #endif
+
+ #ifdef USE_TEXT_ARCHIVE
+ typedef boost::archive::text_oarchive OutArchive;
+ typedef boost::archive::text_iarchive InArchive;
+ #endif
+
+ #ifdef USE_XML_ARCHIVE
+ typedef boost::archive::xml_iarchive InArchive;
+ typedef boost::archive::xml_oarchive OutArchive;
+ #endif
+
+ NETWORK_EXPORT MessageTypeSet& globalMessageTypeSet();
+}
+
+typedef unsigned int u32;
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h (revision 1522570)
@@ -0,0 +1,122 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef FORWARDSESSION_H
+#define FORWARDSESSION_H
+
+#include "handler.h"
+#include "sessioninterface.h"
+#include "basicsession.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+ class ForwardMessage;
+ ///A virtual session that uses another session to forward messages through it to a specified user
+ class NETWORK_EXPORT ForwardSession : public SessionInterface, public SessionReplyManager {
+ friend class MultiSession;
+ MultiSessionPointer session_;
+ UserPointer targetUser_;
+ UserPointer sourceUser_;
+ LoggerPointer logger_;
+ bool notRunning_;
+ MessageTypeSet& messageTypes_;
+ HandlerPointer handler_;
+
+
+ virtual LoggerPrinter err( int prio = 0 );
+
+ virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
+
+ public:
+ ForwardSession( const UserPointer& sourceUser, const UserPointer& targetUser, const MultiSessionPointer& session, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler = 0 );
+
+ ~ForwardSession();
+
+ virtual bool isOk();
+
+ virtual bool isRunning();
+
+ virtual bool send( MessageInterface* msg );
+
+ virtual void stopRunning();
+
+ virtual void stopRunningNow();
+
+ virtual bool think();
+
+ virtual void startSession();
+
+ UserPointer target();
+
+ virtual SessionDirection sessionDirection();
+
+ ///Must only be called from within session_!
+ bool handleForwardMessage( const SafeSharedPtr<ForwardMessage>& msg );
+
+ ///Must only be called from within session_!
+ virtual bool handleMessage( MessagePointer msg ) throw();
+
+ virtual SessionType sessionType();
+
+ protected:
+ virtual void final();
+ };
+
+ ///This is a class that implements the session-interface, and just stores the messages that should be sent in a list. It can be used for debugging.
+ class NETWORK_EXPORT FakeSession : public SessionInterface {
+ LoggerPointer logger_;
+ MessageTypeSet& messageTypes_;
+ HandlerPointer handler_;
+ std::list<MessagePointer> receivedMessages_;
+
+ virtual LoggerPrinter err( int prio = 0 );
+
+ virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
+
+ public:
+ FakeSession( const UserPointer& targetUser, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler = 0 );
+
+ virtual bool isOk();
+
+ virtual bool isRunning();
+
+ virtual bool send( MessageInterface* msg );
+
+ virtual void stopRunning();
+
+ virtual void stopRunningNow();
+
+ virtual bool think();
+
+ virtual void startSession();
+
+ virtual SessionDirection sessionDirection();
+
+ ///Must only be called from within session_!
+ virtual bool handleMessage( MessagePointer msg ) throw();
+
+ virtual SessionType sessionType();
+
+ std::list<MessagePointer>& sentMessages();
+
+
+ /**This takes the first message off the stack of sent messages, serializes and deserializes it, and then returns the deserialized message.
+ All exceptions from the serialization- and deserialization-process are passed by, additionally errors are indicated by throwing a const char*.
+ */
+ MessagePointer::Locked getFirstMessage() throw( const char* );
+ };
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.h (revision 1522570)
@@ -0,0 +1,172 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef TEAMWORK_USER_H
+#define TEAMWORK_USER_H
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/nvp.hpp>
+#include <string>
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "weaksafesharedptr.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+///when a user is flagged as online that means that there is a session to that user. It does not mean that that session is really functional.
+class NETWORK_EXPORT OnlineInformation {
+ friend class User;
+ SafeSharedPtr<SessionInterface> session_;
+ //SessionPointer session_;
+
+ void setSession( const SessionPointer& sess );
+
+ OnlineInformation( const OnlineInformation& rhs );
+ OnlineInformation& operator = ( const OnlineInformation& rhs );
+ public:
+ OnlineInformation();
+ ~OnlineInformation();
+
+ ///When a user is reported as online, it is guaranteed that the session is valid.
+ operator bool();
+
+ const SessionPointer& session();
+};
+
+///This represents the identity of a user, it can be used to store it persistently.
+class NETWORK_EXPORT UserIdentity {
+ std::string name_;
+ friend class User;
+
+ public:
+ UserIdentity( const std::string& name ) {
+ name_ = name;
+ }
+ UserIdentity() {}
+
+ const std::string& name() const {
+ return name_;
+ }
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & boost::serialization::make_nvp( "name", name_ );
+ }
+
+ bool operator == ( const UserIdentity& rhs ) const {
+ return name_ == rhs.name_;
+ }
+
+ bool operator < ( const UserIdentity& rhs ) const {
+ return name_ < rhs.name_;
+ }
+
+ operator bool() const {
+ return !name_.empty();
+ }
+ bool operator !() const {
+ return name_.empty();
+ }
+};
+
+
+class NETWORK_EXPORT User : public WeakSafeShared {
+ std::string name_;
+ std::string password_;
+ std::string description_;
+ std::string email_;
+ int rights_;
+ OnlineInformation online_;
+ public:
+ enum Rights {
+ UserRights = 1,
+ TrustedRights = 2,
+ AdminRights = 4,
+ BannedRights = 8
+ };
+
+ User( const UserIdentity& identity );
+
+ User( const User* user );
+
+ explicit User( std::string name = "", std::string password = "", std::string description = "" );
+
+ virtual ~User();
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint /*version*/ );
+
+ bool matchRight( int right );
+
+ ///this function is used for authentication. The given user should be the one trying to connect.
+ virtual bool match( const User& u );
+
+ virtual bool matchIdentity( const User& u );
+
+ ///this function strips all information that is not necessary for correct authentication/identification at the given target-user
+ virtual void stripForTarget( const User& /*target*/ );
+
+ ///strips away all information that should stay private, but leaves things like description etc.
+ virtual void stripForPublic();
+
+ ///this function strips all information that is not necessary to generally identify a user(this might strip away more than stripForTarget, and removes passwords and such). It should not be called on derived classes, because the User-class is enough for simple Identification.
+ void stripForIdentification();
+
+ ///the structure can be changed through this.
+ OnlineInformation& online();
+
+ ///To set the user offline, this should be called with a zero-pointer
+ virtual void setSession( const SessionPointer& sess );
+
+ virtual std::string description() const;
+
+ bool operator < ( const User& rhs ) const;
+
+ bool operator < ( const std::string& rhs ) const;
+
+ bool operator < ( const UserIdentity& rhs ) const;
+
+ const std::string& name() const;
+
+ int rights() const;
+
+ void setRights( int rights );
+
+ std::string rightsAsString() const;
+
+ std::string email() const;
+
+ void setEmail( const std::string& );
+
+ ///This function is thread-safe(no locking must be done before calling it)
+ std::string safeName() const;
+
+ const std::string& password() const;
+
+ void ban( bool banned );
+
+ bool banned() const;
+
+ void setPassword( const std::string& password );
+
+ ///Creates a lightweigth-structure for identification which may be used for persistent storage.
+ UserIdentity identity();
+};
+
+typedef SafeSharedPtr<User, BoostSerialization> UserPointer;
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.h (revision 1522570)
@@ -0,0 +1,75 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef LOGGER_H
+#define LOGGER_H
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include <string>
+#include <iostream>
+#include <sstream>
+
+#include "networkexport.h"
+
+namespace Teamwork {
+
+///WARNING: The functions in this class will be called from many different threads, but only from one thread at a time(due to mutex-locking)
+struct NETWORK_EXPORT Logger : public SafeShared {
+ enum Level {
+ Debug = 1,
+ Info = 2,
+ Warning = 4,
+ Error = 8
+ };
+
+ std::string levelToString( Level lv );
+
+ ///This can be overridden for custom logging
+ virtual void log( const std::string& str , Level lv );
+
+ ///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
+ virtual void safeErrorLog( const std::string& str, Level lv );
+};
+
+///this class represents one line of logger-output. On its destruction the line is given to the logger. When it is copied, the copy-source is invalidated.
+class NETWORK_EXPORT LoggerPrinter {
+ public:
+ explicit LoggerPrinter( const LoggerPointer& logger, Logger::Level level = Logger::Info );
+
+ LoggerPrinter( const LoggerPrinter& rhs );
+
+ template <class ItemType>
+ LoggerPrinter& operator << ( const ItemType& item ) {
+ if ( out_ )
+ * out_ << item;
+ else
+ std::cout << item; //"invalidated logger is being used" << endl;*/
+
+ return *this;
+ }
+
+ ~LoggerPrinter();
+ private:
+ LoggerPointer logger_;
+ std::ostringstream* out_;
+ Logger::Level level_;
+
+ void invalidate();
+ LoggerPrinter& operator = ( const LoggerPrinter& /*rhs*/ );
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h (revision 1522570)
@@ -0,0 +1,180 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+/** @Todo hide all this behind an interface
+ * */
+
+#ifndef TEAMWORKSERVER_H
+#define TEAMWORKSERVER_H
+
+#include <string>
+#include <map>
+#include <set>
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "sessioninterface.h"
+#include "messageinterface.h"
+#include "basicserver.h"
+#include "user.h"
+#include "messagesendhelper.h"
+#include "serverconfig.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+class Server;
+class IdentificationMessage;
+class ServerInformation;
+
+class SystemMessage;
+class ForwardMessage;
+class IdentificationMessage;
+class TextMessage;
+
+class ForwardSession;
+typedef SafeSharedPtr<ForwardSession> ForwardSessionPointer;
+
+class MultiSession;
+typedef SafeSharedPtr<MultiSession> MultiSessionPointer;
+typedef WeakSafeSharedPtr<MultiSession> WeakMultiSessionPointer;
+
+class NETWORK_EXPORT Server : public BasicServer, public MessageSendHelper {
+ typedef std::map< SessionPointer, UserPointer > SessionMap;
+ typedef std::set< MultiSessionPointer > SessionSet;
+
+ UserPointer ident_;
+
+ public:
+ typedef std::set< UserPointer, UserPointer::ValueSmallerCompare > UserSet;
+
+ Server( const ServerInformation& inf, const LoggerPointer& logger );
+ ~Server();
+
+ ///If the server-name in the configuration is not empty, and there currently is no local identity std::set, the local identity is std::set to that name.
+ void setConfiguration( const ServerConfiguration& conf );
+
+ const ServerConfiguration& configuration() const;
+
+
+ ///The following two functions can be used to make UserPointers consistent through a longer session where the server may be closed/opened multiple times:
+ void getUserSet( UserSet& users );
+
+ ///Insert the given user-std::set into the server's own.
+ void insertUserSet( const UserSet& users );
+
+
+ ///If the user is not registered yet, the user is either created, copied and returned, or zero is returned.
+ virtual UserPointer getUser( const UserPointer& user );
+
+ ///Creates and registers a user with that identity if it does not already exist. May return zero on conflict.
+ virtual UserPointer getUser( const UserIdentity& user );
+
+ MessageTypeSet& messageTypes();
+
+ ///These two should be overridden to use derived user-classes.
+ virtual UserPointer createUser( IdentificationMessage* msg );
+ virtual UserPointer createUser( const User* user );
+
+
+ int receiveMessage( SystemMessage* msg );
+ int receiveMessage( ForwardMessage* msg );
+ int receiveMessage( IdentificationMessage* msg );
+ int receiveMessage( TextMessage* msg );
+ int receiveMessage( MessageInterface* msg );
+
+ ///Tries to find the user(together with appropriately filled online-information) among connected users, servers, and users available through another connected server
+ UserPointer findUser( const UserPointer& user );
+
+ UserPointer findUser( const UserIdentity& user );
+
+ ///Returns the user associated with the given session, may return invalid pointer.
+ virtual UserPointer findSessionUser( const SessionPointer& session );
+
+ virtual void closeSession( const SessionPointer& session );
+
+ virtual void closeAllIncomingSessions();
+
+ /**Associate this client with a user-identity. May be invalid( is initialized as such ).
+ Without this identity correctly std::set, forwarded messages can not be dispatched. The identity will also be broadcasted to new clients that connect to the server, but not to already connected ones */
+ void setIdentity( const UserPointer& user );
+ ///Returns the user-identity currently associated with this client. May be invalid.
+ virtual UserPointer identity() const;
+
+ protected:
+
+ virtual SessionPointer createSession( BasicTCPSocket* sock );
+
+ virtual bool registerSession( SessionPointer session );
+
+ ///Internally maps the given user to his session. Fails if the user already has a session
+ virtual bool registerSessionUser( const UserPointer& user );
+
+ virtual void initial( void );
+
+ virtual bool think();
+
+ virtual void final( void );
+
+ virtual void processMessage( MessageInterface* msg );
+
+ ///this is called whenever a new user successfully logged into the server, or when a connected server has sent an identification-message
+ virtual void userConnected( const UserPointer& /*user*/ ) {}
+
+ ///called whenever a user leaves the server(or connection to a server that had an identification is lost)
+ virtual void userDisconnected( const UserPointer& /*user*/ ) {}
+
+ private:
+ SessionMap sessions_;
+ SessionSet unknownSessions_;
+ UserSet users_;
+
+ ServerConfiguration configuration_;
+
+ bool userListDirty_;
+
+ void sendUserLists();
+
+ void addUser( UserPointer user );
+};
+
+///Encapsulates information about a server to connect to
+class NETWORK_EXPORT ServerInformation {
+ std::string addr_;
+ int port_;
+ public:
+ explicit ServerInformation( const std::string& addr = "", int port = 0 ) {
+ addr_ = addr;
+ port_ = port;
+ }
+ bool operator < ( const ServerInformation& rhs ) const {
+ return addr_ < rhs.addr_ || ( addr_ == rhs.addr_ && port_ < rhs.port_ );
+ }
+
+ const std::string& addr() const {
+ return addr_;
+ }
+ int port() const {
+ return port_;
+ }
+
+ std::string desc() const {
+ std::stringstream s;
+ s << addr_ << ":" << port_;
+ return s.str();
+ }
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h (revision 1522570)
@@ -0,0 +1,102 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef TEAMWORKMESSAGES_H
+#define TEAMWORKMESSAGES_H
+
+#include "networkfwd.h"
+#include "user.h"
+#include "messageimpl.h"
+#include "binder.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+
+/*
+vector<char> messageToData( MessageInterface* msg ) {
+ vector<char> vec;
+ serializeToBuffer( vec, *msg );
+ return vec;
+}*/
+
+/** Abstract message for all messages that have to do with the teamwork-stuff */
+
+class NETWORK_EXPORT TeamworkMessage : public RawMessage {
+ DECLARE_MESSAGE( TeamworkMessage, RawMessage, 1 );
+ public:
+ TeamworkMessage( const MessageConstructionInfo& messageTypes );
+ TeamworkMessage( InArchive& arch, const MessageInfo& info );
+};
+
+class NETWORK_EXPORT IdentificationMessage : public TeamworkMessage {
+ DECLARE_MESSAGE( IdentificationMessage, TeamworkMessage, 1 );
+ User user_;
+
+ template <class Arch>
+ void serial( Arch& arch ) {
+ arch & user_;
+ }
+
+ public:
+
+ IdentificationMessage( const MessageConstructionInfo& messageTypes, const User& user );
+
+ IdentificationMessage( InArchive& arch, const MessageInfo& info );
+
+ operator User();
+
+ virtual void serialize( OutArchive& arch );
+};
+
+typedef TextMessage MaintenanceMessage;
+typedef Chain< MaintenanceMessage, TextMessage, 15> MaintenanceMessageChain;
+
+
+class NETWORK_EXPORT ForwardMessage : public RawMessage {
+ DECLARE_MESSAGE( ForwardMessage, RawMessage, 2 );
+ User source_;
+ User target_;
+ public:
+ ForwardMessage( const MessageConstructionInfo& messageTypes, MessageInterface* messageToForward, const User& source, const User& targ );
+
+ ForwardMessage( InArchive& arch, const MessageInfo& info );
+
+ template <class Arch>
+ void serial( Arch& arch ) {
+ arch & source_;
+ arch & target_;
+ }
+
+ virtual void serialize( OutArchive& arch );
+
+ User& source();
+
+ User& target();
+
+ MessagePointer deserializeContained( MessageTypeSet& messageTypes );
+
+ ///Through this variable, messages should state that they should be stored on the server until the target-user is online if it cannot be reached
+ virtual bool storeOnServer();
+};
+
+
+typedef Binder< TeamworkMessage >
+::Append< IdentificationMessage >::Result
+//::Append< MaintenanceMessageChain >::Result
+::Append< ForwardMessage >::Result
+TeamworkMessages;
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h (revision 1522570)
@@ -0,0 +1,86 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef MESSAGESERIALIZATION_H
+#define MESSAGESERIALIZATION_H
+
+///This header defines a serialization-class that can be used as template-parameter to SafeSharedPtr so it uses the message-serialization-system and the MessageTypeSet to serialize and deserialize messages(it stores and loads the messages as vectors). It automatically uses the global message-set stored in globalMessageTypeSet(). A hard lock is done while saving. Warning: May throw exceptions on errors
+
+#include "serialization.h"
+#include "messagetypeset.h"
+#include "helpers.h"
+#include <vector>
+
+#define USE_BUFFER_SERIALIZATION
+
+struct NETWORK_EXPORT MessageSerialization {
+ template <class Type, class Archive, class Target>
+ static void load( Target& t, Archive& arch, int /*version*/ ) {
+ bool b = false;
+ arch >> boost::serialization::make_nvp( "valid", b );
+ if ( b ) {
+#ifdef USE_BUFFER_SERIALIZATION
+#ifdef USE_TEXT_ARCHIVE
+ std::string s;
+ arch & boost::serialization::make_nvp( "data", s );
+ std::vector<char> v;
+ v.resize( s.length() + 1 );
+ memcpy( &v[ 0 ], s.c_str(), s.length() + 1 );
+#else
+ std::vector<char> v;
+ arch & boost::serialization::make_nvp( "data", v );
+#endif
+
+ t = ( ( Teamwork::MessagePointer ) Teamwork::buildMessageFromBuffer( v, Teamwork::globalMessageTypeSet(), 0 ) ).cast<Type>();
+#else
+ t = ( ( ( Teamwork::MessagePointer ) Teamwork::buildMessageFromArchive( arch, Teamwork::globalMessageTypeSet(), 0 ) ).cast<Type>();
+#endif
+ }
+ else {
+ t = 0;
+ }
+ }
+
+ template <class Type, class Archive, class Target>
+ static void save( Target& t, Archive& arch, int /*version*/ ) {
+ if ( t ) {
+ bool b = true;
+#ifdef USE_BUFFER_SERIALIZATION
+
+ arch << boost::serialization::make_nvp( "valid", b );
+ std::vector<char> v;
+ Teamwork::serializeMessageToBuffer( v, *t.unsafe() );
+
+#ifdef USE_TEXT_ARCHIVE
+
+ std::string s;
+ if ( v.size() )
+ s = &v[ 0 ];
+
+ arch & boost::serialization::make_nvp( "data", s );
+#else
+ arch & boost::serialization::make_nvp( "data", v );
+#endif
+
+#else
+ Teamwork::serializeMessageToArchive( arch, *t.unsafe() );
+#endif
+ } else {
+ bool b = false;
+ arch << boost::serialization::make_nvp( "valid", b );
+ }
+ }
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h (revision 1522570)
@@ -0,0 +1,46 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SERVERCONFIG_H
+#define SERVERCONFIG_H
+
+#include "user.h"
+#include <string>
+#include <set>
+#include "networkexport.h"
+
+namespace Teamwork {
+struct NETWORK_EXPORT ServerConfiguration {
+ std::string serverName;
+ std::string serverPassword; ///A password that is used for users that don't have an own password set
+
+ int port;
+ std::string bind;
+
+ typedef std::set<User> UserSet;
+
+ ServerConfiguration();
+
+ std::set<User> registeredUsers;
+
+ template<class Archive>
+ void serialize( Archive& arch, const unsigned int /*version*/ );
+};
+
+NETWORK_EXPORT bool loadServerConfiguration( ServerConfiguration& conf );
+NETWORK_EXPORT bool saveServerConfiguration( ServerConfiguration& conf );
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h (revision 1522570)
@@ -0,0 +1,105 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+///WARNING: This is not tested yet
+
+/** This class works similar to MessageDispatcher, except that it is not static.
+ * Callback-functions can be registered at runtime, and
+ * there is less dynamically generated code.
+ *
+ * The target-classes must be based on WeakSafeShared.
+ * That way nobody has to care about unregistering targets, because DynamicMessageDispatcher will disconnect
+ * destroyed targets automatically..
+ *
+ * Also the target must be kept alive by a SafeSharedPtr.
+ * (else they would get destructed as soon as the reference-count gets increased and decreased once)
+ *
+ *
+ * The downside is that it's slower, the callback-functions need to be registered on runtime,
+ * it's probably more error-prone, and what's happening is not absolutely clear on compile-time.
+ *
+ * It should be preferred over MessageDispatcher either when the message-delivery should be more
+ * flexible, or when several(maybe unknown) targets should be allowed to register callback-functions on their own, like plugins.
+ *
+ * This class is not suitable for handling many(above 50) dispatch-target.
+ *
+ * The order of message-delivery:
+ * When receiveMessage(...) is called, the order of message-delivery is defined this way:
+ * 1. Deliver first to the best specialized targets
+ * 2. Among targets that match equally well, the last registered targets will get the message first.
+ *
+ * Once any delivery-function returns a nonzero return-value, the message-deliverey will be stopped and the
+ * return-value returned by the receiveMessage(...) -function.
+**/
+
+#ifndef DYNAMICMESSAGEDISPATCHER_H
+#define DYNAMICMESSAGEDISPATCHER_H
+
+#include <vector>
+#include "networkexport.h"
+#include "dynamicmessagedispatcher_internal.h"
+#include "messagetypeset.h" //needed so the message-type-description can be extracted while registering
+
+namespace Teamwork {
+
+ ///The message-dispatcher:
+class NETWORK_EXPORT DynamicMessageDispatcher {
+ public:
+ DynamicMessageDispatcher( MessageTypeSet& messageTypes = globalMessageTypeSet() );
+ ~DynamicMessageDispatcher();
+
+ /**
+ * Use this to register your class for receiving all messages based on a given one.
+ *
+ * When a callback is registered using this function, the target will be locked before the target-function is called.
+ *
+ * @param Message(template-param 1) The message-type your class should receive
+ * @param target a weak-pointer to the target the message should be delivered to(the weak pointer makes it safe to register and later delete the object without notification)
+ * @param function pointer to a member-function of the taget-class, that must have the signature "int function( const SafeSharedPtr<Message>& )"
+ *
+ * For an example see main.cpp, there's a version of StandaloneServer that uses this.
+ * */
+ template<class Message, class TargetClass>
+ void registerCallback( TargetClass* target, int (TargetClass::*function) (const SafeSharedPtr<Message>&) ) {
+ addDeliverer( new MessageDeliverer<Message, TargetClass> ( target, function, m_messageTypes.type<Message>(), true ) );
+ }
+
+ /**
+ * Same as above, except that the target will not be locked before the callback is called
+ * */
+ template<class Message, class TargetClass, class Serialization>
+ void registerUnsafeCallback( TargetClass* target, typename MessageDeliverer<Message, TargetClass>::FunctionType function ) {
+ addDeliverer( new MessageDeliverer<Message, TargetClass> ( target, function, m_messageTypes.type<Message>(), false ) );
+ }
+
+ /** Call this to dispatch the message to the registered targets
+ * @return 0 if there is no fitting target, or the value returned by the target's dispatch-function
+ */
+ int operator() ( const MessagePointer& msg );
+
+ protected:
+ /** Call this to dispatch the message to the registered targets. It is the same as operator(), but looks cleaner when called from an inherited class.
+ * @return 0 if there is no fitting target, or the value returned by the target's dispatch-function
+ */
+ int dispatch( const MessagePointer& msg );
+
+ void addDeliverer( MessageDelivererBase* );
+
+ private:
+ typedef std::vector<MessageDelivererBase*> DelivererList;
+ DelivererList m_deliverers;
+ MessageTypeSet& m_messageTypes;
+};
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h (revision 1522570)
@@ -0,0 +1,52 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef TEAMWORK_HELPERS
+#define TEAMWORK_HELPERS
+
+#include "networkfwd.h"
+#include <vector>
+#include <string>
+#include <cstdlib>
+#include "networkexport.h"
+
+namespace Teamwork {
+
+ class BasicTCPSession;
+
+ NETWORK_EXPORT MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages, SessionPointer sess );
+
+ ///May throw several exceptions
+ NETWORK_EXPORT void serializeMessageToArchive( OutArchive& arch, MessageInterface& message );
+
+ ///May throw several exceptions
+ NETWORK_EXPORT void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message );
+ NETWORK_EXPORT MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages, SessionPointer sess );
+ NETWORK_EXPORT MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages);
+}
+
+template <class VecType, class Vec2Type>
+std::vector<VecType>& operator += ( std::vector<VecType>& lhs, const std::vector<Vec2Type>& rhs ) {
+ uint osize = lhs.size();
+ lhs.resize( lhs.size() + ( (rhs.size() * sizeof( Vec2Type )) / sizeof(VecType)) );
+ memcpy( &lhs[osize], &rhs[0], sizeof(Vec2Type) * rhs.size() );
+ return lhs;
+}
+
+std::string formatInt( int i );
+
+std::vector<char> binaryInt( int num );
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h (revision 1522570)
@@ -0,0 +1,108 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SESSIONINTERFACE_H
+#define SESSIONINTERFACE_H
+
+#include <string>
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+ class NETWORK_EXPORT SessionInterface : public /*Weak*/SafeShared {
+ public:
+ virtual void startSession();
+
+ virtual ~SessionInterface();
+ /**After this function was called, the thread is going to exit soon.
+ once isRunning() returns false, it can be deleted(better call join()).*/
+ virtual void stopRunning() = 0;
+
+ virtual void stopRunningNow() = 0;
+
+ /** Use this to send a message to the other side.
+ *
+ * This is thread-safe.
+ * */
+ virtual bool send( MessageInterface* msg ) = 0;
+
+ /** Use this to send a message to the other side, that is correctly marked as
+ * a reply to the message given by @param replyTo. This is just a convenience-function.
+ *
+ * @param msg The message to be sent. It will be changed so its info().replyTo() etc. will be filled correctly
+ * @param replyTo The message to reply to. It does not need to be locked.
+ *
+ * This is thread-safe.
+ * */
+ virtual bool sendReply( MessageInterface* msg, MessageInterface* replyTo );
+
+ ///Returns true if no errors occurred and the session was not ended. Must be thread-safe.
+ virtual bool isOk() = 0;
+
+ ///Returns whether the thread is running. Must be thread-safe.
+ virtual bool isRunning() = 0;
+
+ virtual std::string sessionName();
+
+ virtual void setSessionName( const std::string& name );
+
+ virtual std::string peerDesc();
+
+ virtual std::string localDesc();
+
+ enum SessionType {
+ Direct,
+ Forwarded
+ };
+
+ ///this function is thread-safe
+ virtual SessionType sessionType();
+
+ enum SessionDirection {
+ Outgoing,
+ Incoming
+ };
+
+ ///this function is thread-safe
+ virtual SessionDirection sessionDirection() = 0;
+
+ ///This function is thread-safe. The user is not necessarily filled.
+ UserPointer safeUser() const;
+
+ ///This must never be called again once it has been set on a session, to make it thread-safe.
+ void setUser( const UserPointer& user );
+
+ private:
+ std::string sessionName_;
+ UserPointer user_;
+ //UserPointer user_;
+ ///override standard-functions
+ SessionInterface& operator= ( const SessionInterface& rhs );
+ SessionInterface( const SessionInterface& rhs );
+
+ protected:
+ SessionInterface();
+
+ /**This can be overridden to possibly handle messages directly in this object.
+ The default-implementation just sends the messages to the handler which created this session.*/
+ virtual bool handleMessage( MessagePointer msg ) throw();
+
+ ///This can be overridden to do some work on a regular basis. Returns whether more time is needed.
+ virtual bool think() = 0;
+
+ ///This can be overridden to do some cleanup-work within the session-thread. By default it tries to lock the associated user, and call setSession(this) so the user has a chance to notice the difference.
+ virtual void final();
+ };
+}
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h (revision 1522570)
@@ -0,0 +1,171 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGEIMPL_H
+#define MESSAGEIMPL_H
+
+#include "networkfwd.h"
+#include "messageinterface.h"
+#include "binder.h"
+#include "networkexport.h"
+///Since objects must have external linkage to be usable as template-arguments, these must be defined here.
+
+namespace Teamwork {
+
+typedef std::vector<char> DataVector;
+
+/** Example for a custom Message:
+class CustomMessage : public RawMessage {
+ DECLARE_MESSAGE( CustomMessage, RawMessage, 83 );
+ typedef vector<MyType> MyDataType;
+ MyDataType myData;
+
+ template<class Arch>
+ void serial( Arch& arch ) {
+ arch & myData;
+}
+ public:
+
+ CustomMessage( const MessageConstructionInfo& info, MyDataType& data ) : RawMessage( info(this) ), myData( data ) {
+}
+
+ CustomMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {
+ serial( arch );
+}
+
+ virtual void serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+};
+ */
+
+ class MessageConstructionInfo;
+ /**MessageConstructionInfo is a class used while constructing messages, that makes sure that the name of the most derived message will be passed on to RawMessage.
+ *Use it by simply passing the this-pointer of each constructed message while passing it to the parent-message. */
+
+ class NETWORK_EXPORT MessageConstructionInfo {
+ public:
+ //This is the constructor you are supposed to use when creating a message(use the automatic conversion from MessageTypeSet&)
+ MessageConstructionInfo( const MessageTypeSet& rhs );
+
+ //Use this to pass MessageConstructionInfo up to the parent, giving "this" as argument.
+ template<class Message>
+ MessageConstructionInfo operator() (Message* ) const {
+ return MessageConstructionInfo( name_.empty() ? Message::staticName() : name_, typeSet_ );
+ }
+
+ const MessageTypeSet& typeSet() const;
+
+ const std::string name() const;
+
+ MessageInfo messageInfo() const;
+
+ //operator () must be used when passing the construction-info to the parent
+ MessageConstructionInfo( const MessageConstructionInfo& rhs );
+
+ private:
+ MessageConstructionInfo( const std::string& name, const MessageTypeSet& typeSet_ );
+ MessageConstructionInfo& operator=( const MessageConstructionInfo& );
+ std::string name_;
+ const MessageTypeSet& typeSet_;
+ };
+
+ class NETWORK_EXPORT RawMessage : public MessageInterface
+ {
+ DECLARE_MESSAGE( RawMessage, MessageInterface, 1 );
+
+ MessageInfo info_;
+ DataVector body_;
+
+ public:
+
+ RawMessage( const MessageConstructionInfo& messageTypes, const DataVector& data );
+
+ ///This should be used to indicate that this message is a reply to the other message(replyTarget)
+ void setReply( MessageInterface* replyTarget );
+
+ RawMessage( InArchive& from, const MessageInfo& info );
+
+ virtual void serialize( OutArchive& target );
+
+ virtual const MessageInfo& info() const;
+
+ virtual MessageInfo& info();
+
+ /**This is called once a message has been tried to be sent, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
+ */
+ virtual void result( bool success );
+
+ /**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
+ DataVector& body();
+
+ /**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
+ const DataVector& body() const;
+ };
+
+
+ class NETWORK_EXPORT TextMessage : public RawMessage {
+ DECLARE_MESSAGE( TextMessage, RawMessage, 3 );
+ public:
+ explicit TextMessage( const MessageConstructionInfo& messageTypes, const std::string& text = "" );
+
+ TextMessage( InArchive& from, const MessageInfo& info );
+
+ std::string text() const;
+ };
+
+ struct NETWORK_EXPORT SystemMessage : public TextMessage
+ {
+ DECLARE_MESSAGE( SystemMessage, TextMessage, 2 );
+ public:
+ enum Message {
+ NoMessage,
+ LoginSuccess,
+ LoginFailedUnknown,
+ BadAuthentication,
+ ServerBusy,
+ Kicked,
+ BadTarget,
+ StoredOnServer,
+ AlreadyLoggedIn,
+ GetUserList,
+ SerializationFailed
+ };
+ private:
+ Message msg_;
+
+ template<class Arch>
+ void serial( Arch& arch ) {
+ arch & msg_;
+ }
+ public:
+ SystemMessage( const MessageConstructionInfo& messageTypes, Message msg, const string& ptext="" );
+
+ SystemMessage( InArchive& arch, const MessageInfo& info );
+
+ virtual void serialize( OutArchive& arch );
+
+ Message message();
+
+ string messageAsString();
+ };
+
+ typedef Binder< RawMessage > ::
+ Append< TextMessage >
+ ::Result::Append<SystemMessage>::Result StandardMessageTypes;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h (revision 1522570)
@@ -0,0 +1,44 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef TEAMWORKSERVERMESSAGES_H
+#define TEAMWORKSERVERMESSAGES_H
+
+#include "teamworkmessages.h"
+#include "user.h"
+#include "networkexport.h"
+#include <list>
+
+namespace Teamwork {
+
+struct NETWORK_EXPORT UserListMessage : public TeamworkMessage {
+ DECLARE_MESSAGE( UserListMessage, TeamworkMessage, 2 );
+ std::list<User> users;
+
+ UserListMessage( const MessageConstructionInfo& messageTypes, std::list<UserPointer> inUsers, const UserPointer& targetUser );
+
+ UserListMessage( InArchive& arch, const MessageInfo& info );
+
+ template <class Arch>
+ void serial( Arch& arch ) {
+ arch & users;
+ }
+
+ virtual void serialize( OutArchive& arch );
+};
+
+typedef UserListMessage TeamworkServerMessages;
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h (revision 1522570)
@@ -0,0 +1,98 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef TEAMWORK_CLIENT_H
+#define TEAMWORK_CLIENT_H
+
+#include <list>
+#include <map>
+
+#include "networkfwd.h"
+#include "safesharedptr.h"
+#include "teamworkserver.h"
+#include "user.h"
+#include "networkexport.h"
+
+namespace Teamwork {
+
+class ClientSessionHandler;
+class UserListMessage;
+
+struct NETWORK_EXPORT ClientSessionDesc {
+ UserPointer loginUser; ///user as which we are logged in
+ SessionPointer session;
+ ClientSessionDesc( const UserPointer& asUser = UserPointer(), const SessionPointer& _session = SessionPointer() ) {
+ loginUser = asUser;
+ session = _session;
+ }
+};
+/* typedef Binder< AllTeamworkServerMessages >::Append< UserListMessage >::Result
+ AllTeamworkClientMessages;*/
+
+struct NETWORK_EXPORT SessionPointerCompare {
+public:
+ bool operator () ( const SessionPointer& s1, const SessionPointer& s2 ) const {
+ return s1.unsafe() < s2.unsafe();
+ }
+};
+
+/// A teamwork-client generally is the same as a teamwork-server, except it not only supports incoming connections, but also outgoing ones and connections forwarded through a server, and may be associated with a user-identity.
+class NETWORK_EXPORT Client : public Server {
+ typedef map< ServerInformation, ClientSessionDesc > ClientSessionMap;
+ ClientSessionMap clientSessions_;
+ friend class ClientSessionHandler;
+ bool needUserUpdate_;
+
+ protected:
+ virtual bool think();
+
+ ///Is called whenever a connected server sends its list of connected users
+ virtual void gotUserList( const std::list<UserPointer>& /*users*/ );
+
+ ///this could be used to create a custom session deriven from MultiSession
+ virtual SessionPointer createSession( BasicTCPSocket* sock );
+
+ virtual bool registerSession( SessionPointer session );
+
+ virtual void userDisconnected( const Teamwork::UserPointer& user );
+
+ ///this is called whenever a connection is successfully established to a server
+ virtual void connectedToServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ );
+ ///this is called whenever the client disconnects from a connected server in any way
+ virtual void disconnectedFromServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ );
+
+ virtual void processMessage( MessageInterface* msg );
+
+ public:
+ explicit Client( ServerInformation serverInfo, LoggerPointer logger = new Logger() );
+
+ virtual ~Client();
+
+ ///when no user is given, the identity-user is used. If that is not set, the connect fails.
+ void connectToServer( const ServerInformation& server, const UserPointer& asUser = UserPointer() ) ;
+ void disconnectFromServer( const ServerInformation& server ) ;
+ void disconnectAllServers () ;
+
+ bool isConnectedToServer( const ServerInformation& server ) ;
+ ///may return invalid pointer when connectedToServer(...) == false
+ MultiSessionPointer sessionToServer( const ServerInformation& server ) ;
+
+ //int receiveMessage( IdentificationMessage* msg );
+ int receiveMessage( ForwardMessage* msg );
+ int receiveMessage( MessageInterface* msg ) ;
+ int receiveMessage( UserListMessage* msg );
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/COPYING
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/COPYING (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/COPYING (revision 1522570)
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/COPYING
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h (revision 1522570)
@@ -0,0 +1,890 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 include-file contains most of the meta-programming code used in this network-library.
+ * The biggest part of it is management of simple type-lists(like adding a type, removing a type, finding one, etc.)
+ * and building a static tree for message-dispatching. Unfortunately it's a bit hard to overview. :)
+ */
+
+#ifndef STATICTREE
+#define STATICTREE
+
+#include "binder.h"
+#include <string>
+#include <cstring>
+
+typedef unsigned char uchar;
+namespace Tree {
+
+template <class Out>
+void printId( Out& out, const uchar* const id ) {
+ for ( uint i = 0; i < std::strlen( ( char* ) id ); ++i ) {
+ if ( i )
+ out << ".";
+ out << ( int ) id[ i ];
+ }
+}
+
+template < int Condition, class Then, class Else >
+struct If {
+ typedef Then Result;
+};
+
+template < class Then, class Else >
+struct If <0, Then, Else> {
+ typedef Else Result;
+};
+
+struct Fail {
+ enum {
+ value = 0
+ };
+};
+
+struct Success {
+ enum {
+ value = 1
+ };
+};
+
+template < class Compare1, class Compare2, class Then, class Else >
+struct IfSame {
+ typedef Else Result;
+};
+
+template < class Compare, class Then, class Else >
+struct IfSame<Compare, Compare, Then, Else> {
+ typedef Then Result;
+};
+
+template <class Chain>
+struct Count {
+ enum {
+ value = 1
+ };
+};
+
+template <>
+struct Count<Empty> {
+ enum {
+ value = 0
+ };
+};
+
+template <int Condition>
+struct Assert {
+ typedef Empty OK;
+};
+
+template <>
+struct Assert<0> {}
+;
+
+template <class Side1, class Side2>
+struct Count<Binder<Side1, Side2> > {
+ enum {
+ value = Count<Side1>::value + Count<Side2>::value
+ };
+};
+
+template <int number, class Chain>
+struct GetListItem {
+ ///The item does not exist
+};
+
+template <class Side1, class Side2>
+struct GetListItem<0, Binder<Side1, Side2> > {
+ typedef typename GetListItem< 0, Side1>::Result Result;
+};
+
+template <class Item>
+struct GetListItem<0, Item> {
+ typedef Item Result;
+};
+
+template <int number, class Side1, class Side2>
+struct GetListItem< number, Binder<Side1, Side2> > {
+ ///If you get an error here which says that GetListItem<-1, ...> has no type named "Result",
+ ///that probably means that the searched Item is not in the list. For the CrossMap it means that
+ ///a key-type was used which is not in the list.
+ typedef typename If < ( Count<Side1>::value > number ), GetListItem< number, Side1>, GetListItem< number - Count<Side1>::value, Side2 > > ::Result::Result Result;
+};
+
+
+
+
+
+template <class Type, uchar preferredSubId>
+class Entry {}
+;
+
+template <class Stuff, class Item>
+struct GetSlaves {
+ typedef Entry<Empty, 0> Result;
+};
+
+template <class Stuff, class Item>
+struct GetParents {
+ typedef Entry<Empty, 0> Result;
+};
+
+template <class Item1, class Item2>
+struct AddResults {
+ typedef Binder<Item1, Item2> Result;
+};
+
+template <class Item1>
+struct AddResults<Empty, Item1> {
+ typedef Item1 Result;
+};
+
+template <class Item1>
+struct AddResults<Item1, Empty> {
+ typedef Item1 Result;
+};
+
+template <>
+struct AddResults<Empty, Empty> {
+ typedef Empty Result;
+};
+
+template <class Item1, uchar a>
+struct AddResults<Entry<Empty, a>, Item1> {
+ typedef Item1 Result;
+};
+
+template <class Item1, uchar a>
+struct AddResults<Item1, Entry<Empty, a> > {
+ typedef Item1 Result;
+};
+
+template <uchar a, uchar b>
+struct AddResults<Entry<Empty, a>, Entry<Empty, b> > {
+ typedef Entry<Empty, 0> Result;
+};
+
+///TODO!
+template <class Stuff>
+struct SortResultByIndex {
+ typedef Stuff Result;
+};
+
+template <class Chain1, class Chain2, class Item>
+struct GetParents< Binder<Chain1, Chain2>, Item > {
+ typedef typename AddResults< typename GetParents<Chain1, Item>::Result, typename GetParents<Chain2, Item>::Result >::Result Result;
+};
+
+template <class Chain1, class Chain2, class Item>
+struct GetSlaves< Binder<Chain1, Chain2>, Item > {
+ typedef typename AddResults< typename GetSlaves<Chain1, Item>::Result, typename GetSlaves<Chain2, Item>::Result >::Result Result;
+};
+
+template <class Item1, class Item, uchar preferredSubId>
+struct GetSlaves< Chain< Item1, Item, preferredSubId >, Item> {
+ typedef Entry<Item1, preferredSubId> Result;
+};
+
+template <class Item1, class Item, uchar preferredSubId>
+struct GetParents< Chain< Item1, Item, preferredSubId >, Item1> {
+ typedef Entry<Item, preferredSubId> Result;
+};
+
+template <class Container >
+struct ExtractItem {
+ typedef Container Result;
+};
+
+template <class Item, uchar preferredSubId>
+struct ExtractItem< Entry< Item, preferredSubId > > {
+ typedef Item Result;
+};
+
+template < class Side1, class Side2 >
+struct ExtractItem < Binder< Side1, Side2 > > {
+ typedef typename ExtractItem< Side1 >::Result Result;
+};
+
+template <class Slaves, class Stuff, class EntryTemplate, uchar currentNum >
+struct TreeNodeSlaves {
+ enum ID {
+ id = 0
+ };
+ template <class Action>
+ inline uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
+ return 0;
+ }
+ template < class Out >
+ inline void print( Out& out, std::string prefix ) {
+ out << prefix + "deadnode1\n";
+ }
+};
+
+template <class Item1, class Item2>
+struct BindTogether {
+ typedef Binder<Item1, Item2> Result;
+};
+
+template < class Item >
+struct BindTogether<Empty, Item> {
+ typedef Item Result;
+};
+template < class Item >
+struct BindTogether<Item, Empty> {
+ typedef Item Result;
+};
+
+template <>
+struct BindTogether<Empty, Empty> {
+ typedef Empty Result;
+};
+
+///Action must have a member-template called Action, that has a typedef called Result. Action will be applied to each item, and the result bound together.
+template<class Action, class List>
+struct ForEachInList {
+ typedef typename Action::template Action<List>::Result Result;
+};
+
+template<class Action, class List1, class List2>
+struct ForEachInList< Action, Binder<List1, List2> > {
+ typedef typename BindTogether< typename ForEachInList< Action, List1 >::Result, typename ForEachInList< Action, List2 >::Result >::Result Result;
+};
+
+template <class Item>
+struct IsEmpty {
+ enum {
+ result = 0
+ };
+};
+
+
+template <>
+struct IsEmpty<Empty> {
+ enum {
+ result = 1
+ };
+};
+
+template <>
+struct IsEmpty<Binder<Empty, Empty> > {
+ enum {
+ result = 1
+ };
+};
+
+template <class Item>
+struct Weight {
+ enum {
+ Result = 1
+ };
+};
+
+template <class Left, class Right>
+struct Weight<Binder<Left, Right> > {
+ enum {
+ Result = Weight<Left>::Result + Weight<Right>::Result
+ };
+};
+
+template <class Item>
+struct Balance {
+ enum {
+ RightOverweight = 0,
+ LeftOverweight = 0
+ };
+};
+
+template <class Left, class Right>
+struct Balance<Binder<Left, Right> > {
+ enum {
+ RightOverweight = Weight<Left>::Result < Weight<Right>::Result - 1 ? 1 : 0,
+ LeftOverweight = Weight<Left>::Result > Weight<Right>::Result + 1 ? 1 : 0
+ };
+};
+
+
+template <class From>
+struct RemoveOneLeft {
+ typedef Empty Result;
+};
+
+template <class Left, class Right>
+struct RemoveOneLeft<Binder<Left, Right> > {
+ typedef typename RemoveOneLeft<Left>::Result LeftRemoved;
+ typedef typename IfSame<LeftRemoved, Empty, Right, typename BindTogether< LeftRemoved, Right >::Result >::Result Result;
+};
+
+template <class From>
+struct GetOneLeft {
+ typedef From Result;
+};
+
+template <class Left, class Right>
+struct GetOneLeft<Binder<Left, Right> > {
+ typedef typename GetOneLeft<Left>::Result Result;
+};
+
+template <class From>
+struct RemoveOneRight {
+ typedef Empty Result;
+};
+
+template <class Left, class Right>
+struct RemoveOneRight<Binder<Left, Right> > {
+ typedef typename RemoveOneRight<Right>::Result RightRemoved;
+ typedef typename IfSame<RightRemoved, Empty, Left, typename BindTogether< Left, RightRemoved >::Result >::Result Result;
+};
+
+template <class From>
+struct GetOneRight {
+ typedef From Result;
+};
+
+template <class Left, class Right>
+struct GetOneRight<Binder<Left, Right> > {
+ typedef typename GetOneRight<Right>::Result Result;
+};
+
+template <class Into, class Item>
+struct InsertOneLeft {
+ typedef Binder<Item, Into> Result;
+};
+
+template <class Left, class Right, class Item>
+struct InsertOneLeft< Binder<Left, Right>, Item> {
+ typedef Binder<InsertOneLeft<Left, Item>, Right> Result;
+};
+
+template <class Into, class Item>
+struct InsertOneRight {
+ typedef Binder<Into, Item> Result;
+};
+
+template <class Left, class Right, class Item>
+struct InsertOneRight< Binder<Left, Right>, Item> {
+ typedef Binder<Left, InsertOneRight<Right, Item> > Result;
+};
+
+template <class Left, class Right, int LeftOverweight, int RightOverweight>
+struct BalanceNow {
+ typedef Binder<Left, Right> Result;
+};
+
+template <class Left, class Right>
+struct BalanceNow<Left, Right, 1, 0> { ///Take one element from left to right side, and recurse
+ typedef typename RemoveOneRight<Left>::Result NewLeft;
+ typedef typename InsertOneLeft<Right, GetOneRight<Left> >::Result NewRight;
+ typedef typename BalanceNow< NewLeft, NewRight, Balance< Binder<NewLeft, NewRight> >::LeftOverweight, Balance< Binder<NewLeft, NewRight> >::RightOverweight >::Result Result;
+};
+
+template <class Left, class Right>
+struct BalanceNow<Left, Right, 0, 1> { ///Take one element from left to right side, and recurse
+ typedef typename InsertOneRight<Left, GetOneLeft<Right> >::Result NewLeft;
+ typedef typename RemoveOneLeft<Right>::Result NewRight;
+ typedef typename BalanceNow< NewLeft, NewRight, Balance< Binder<NewLeft, NewRight> >::LeftOverweight, Balance< Binder<NewLeft, NewRight> >::RightOverweight >::Result Result;
+};
+
+
+template <class Stuff>
+struct Rebalance {
+ typedef Stuff Result;
+};
+
+template <class Left, class Right>
+struct Rebalance<Binder<Left, Right> > {
+ typedef typename BalanceNow<Left, Right, Balance< Binder<Left, Right> >::LeftOverweight, Balance< Binder<Left, Right> >::RightOverweight >::Result Result;
+};
+
+template <class Item>
+struct Consider {}
+;
+
+class TreeNodeDataInterface {
+ public:
+};
+
+template <class Type, class EntryTemplate>
+class TreeNodeData : public TreeNodeDataInterface, public EntryTemplate::template Entry <Type> {
+ public:
+ TreeNodeData() {}
+}
+;
+
+template < class Stuff, uchar cnum, uchar preferredSubId , class EntryTemplate>
+struct TreeNodeSlaves<Consider<Entry<Empty, preferredSubId> >, Stuff, EntryTemplate, cnum > {
+ enum ID {
+ id = 0
+ };
+ template <class Action>
+ inline uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
+ return 0;
+ }
+
+ template < class Out >
+ inline void print( Out& /*out*/, std::string /*prefix*/ ) {
+ }
+
+ inline void buildFullId( const std::string& /*pre*/ ) {
+ }
+};
+
+template < class Stuff, uchar cnum, class EntryTemplate >
+struct TreeNodeSlaves<Consider<Empty >, Stuff, EntryTemplate, cnum > {
+ enum ID {
+ id = 0
+ };
+ template <class Action>
+ uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
+ return 0;
+ }
+ template < class Out >
+ inline void print( Out& /*out*/, std::string /*prefix*/ ) {
+ }
+
+ inline void buildFullId( const std::string& /*pre*/ ) {
+ }
+};
+
+template <class Stuff>
+struct SortByIndex {
+ typedef Stuff Result;
+};
+
+template <class Item>
+struct EntryIndex {
+ ///The argument-type is wrong
+};
+
+template <class Type, uchar index>
+struct EntryIndex< Entry<Type, index> > {
+ enum Result {
+ result = index
+ };
+};
+
+template <int w>
+struct StaticAssert {
+ typedef Empty Ok;
+};
+
+template <>
+struct StaticAssert<0> {}
+;
+
+
+template <class Left, class Right>
+struct Merge {
+ typedef typename GetOneLeft<Left>::Result LeftFirst;
+ typedef typename GetOneLeft<Right>::Result RightFirst;
+
+ typedef typename RemoveOneLeft<Left>::Result LeftTail;
+ typedef typename RemoveOneLeft<Right>::Result RightTail;
+
+ typedef typename StaticAssert < ( int ) EntryIndex<LeftFirst>::result != ( int ) EntryIndex<RightFirst>::result > ::Ok notSame;
+
+ //typedef typename If<typename IsEmpty<LeftFirst>::Result, Right, typename If<typename IsEmpty<RightFirst>::Result, Left, typename MergeImpl<LeftFirst, RightFirst, LeftTail, RightTail>::Result >::Result>::Result Result;
+ typedef typename If < ( int ) EntryIndex<LeftFirst>::result <= ( int ) EntryIndex<RightFirst>::result,
+ Binder< LeftFirst, typename Merge< LeftTail, Binder<RightFirst, RightTail> >::Result >,
+ Binder< RightFirst, typename Merge< Binder<LeftFirst, LeftTail>, RightTail >::Result > > ::Result Result;
+};
+
+template <class Only>
+struct Merge<Only, Empty> {
+ typedef Only Result;
+};
+
+template <class Only>
+struct Merge<Empty, Only> {
+ typedef Only Result;
+};
+
+
+template <class Left, class Right>
+struct Merge<Binder<Empty, Left>, Right> {
+ typedef typename Merge<Left, Right>::Result Result;
+};
+
+template <class Left, class Right>
+struct Merge<Binder<Empty, Left>, Binder<Empty, Right> > {
+ typedef typename Merge<Left, Right>::Result Result;
+};
+
+template <class Left, class Right>
+struct Merge<Left, Binder<Empty, Right> > {
+ typedef typename Merge<Left, Right>::Result Result;
+};
+
+template <class Left, class Right>
+struct SortByIndex<Binder<Left, Right> > {
+ typedef typename Merge< typename SortByIndex<Left>::Result, typename SortByIndex<Right>::Result >::Result Result;
+};
+
+template <class CurrentType, class Stuff, class EntryTemplate>
+class TreeNode : public TreeNodeData<CurrentType, EntryTemplate> {
+ //typedef TreeNode<CurrentType, Stuff> TreeNodeType;
+ typedef TreeNodeSlaves< Consider< typename SortByIndex< typename GetSlaves<Stuff, CurrentType>::Result>::Result > , Stuff, EntryTemplate, 1 > Slaves;
+
+ Slaves slaves;
+
+ ///This walks the tree until it cannot go on, then applies the given Action to the current node(additionally giving the type at the node as template-argument), and gives back the return-type(Action::ReturnType).
+ public:
+
+ inline void buildFullId( const std::string& pre ) {
+ slaves.buildFullId( pre );
+ }
+
+ template < class Out >
+ void print( Out& out, std::string prefix = "" ) {
+ //out << prefix + " " << typeid( CurrentType ).name() << "\n";
+ out << "no rtti";
+ slaves.template print<Out>( out, prefix );
+ }
+
+ ///Searches the tree. Returns 0 if the action could be applied to no node, 1 if the action was applied but not to the searched leaf, and 2 if it was applied to the exact searched target
+ template <class Action>
+ inline uchar find( const uchar*const id, Action& act ) const {
+ const uchar c = id[ 0 ];
+ if ( c ) {
+ uchar r = slaves.Slaves::template find<Action>
+ ( c, id + 1, act );
+ if ( !r ) {
+ act.template operator() <CurrentType> ( *this );
+ ;
+ return 1;
+ } else {
+ return r;
+ }
+ } else {
+ act.template operator() <CurrentType> ( *this );
+ ;
+ return 2;
+ }
+ }
+};
+
+struct StandardEntryTemplate {
+ template <class Type>
+ class Entry {}
+ ;
+};
+
+template < class Class >
+struct GetBase {
+ typedef typename Class::Precursor Result;
+};
+
+struct All {}
+;
+
+template <class Stuff>
+struct ExtractChains {
+ typedef Chain< Stuff, typename GetBase< Stuff >::Result, Stuff::preferredIndex> Result;
+};
+
+template < class Side1, class Side2 >
+struct ExtractChains< Binder< Side1, Side2 > > {
+ typedef typename BindTogether< typename ExtractChains< Side1 >::Result, typename ExtractChains<Side2>::Result >::Result Result;
+};
+
+template < class Side2 >
+struct ExtractChains< Binder< Empty, Side2 > > {
+ typedef typename ExtractChains<Side2>::Result Result;
+};
+
+template < class Side2 >
+struct ExtractChains< Binder< Side2, Empty > > {
+ typedef typename ExtractChains<Side2>::Result Result;
+};
+
+template <class A, class B, uchar C>
+struct ExtractChains< Chain< A, B, C > > {
+ typedef Chain< A, B, C > Result;
+};
+
+
+template < class Item, class Master, class Stuff >
+struct WhatIsMissing {
+ typedef typename Item::Template_Error_Wrong_Input_Should_Be_Chain Error;
+};
+
+template <class Stuff, class Item>
+struct Contains {
+ enum {
+ Result = 0
+ };
+};
+
+template < class Item, class Parent, uchar C >
+struct Contains< Chain< Item, Parent, C >, Item > {
+ enum {
+ Result = 1
+ };
+};
+
+template <class Side1, class Side2, class Item>
+struct Contains< Binder< Side1, Side2 >, Item > {
+ enum {
+ Result = Contains< Side1, Item >::Result | Contains< Side2, Item> :: Result
+ };
+};
+
+
+template < class Item, class Parent, uchar C, class Master, class Stuff>
+struct WhatIsMissing< Chain< Item, Parent, C >, Master, Stuff > {
+ enum {
+ Result = !Contains< Stuff, Parent >::Result
+ };
+ typedef typename If< Result, Parent, Empty >::Result Items;
+};
+
+template < class Item, uchar C, class Master, class Stuff>
+struct WhatIsMissing< Chain< Item, Master, C >, Master, Stuff > {
+ enum {
+ Result = 0
+ };
+ typedef Empty Items;
+};
+
+template < class Side1, class Side2, class Master, class Stuff >
+struct WhatIsMissing< Binder< Side1, Side2 > , Master, Stuff > {
+ enum {
+ Result = WhatIsMissing<Side1, Master, Stuff>::Result | WhatIsMissing<Side2, Master, Stuff>::Result
+ };
+
+ ///Only return one by one, because multiple items might be missing the same parent and we don't want them multiple times
+ typedef typename If< WhatIsMissing<Side1, Master, Stuff>::Result, typename WhatIsMissing<Side1, Master, Stuff>::Items, typename WhatIsMissing<Side2, Master, Stuff>::Items >::Result Items;
+ //typedef BindTogether< typename WhatIsMissing<Side1, Master, Stuff>::Items, WhatIsMissing<Side2, Master, Stuff>::Items >::Items Items;
+};
+
+template <class Stuff, class Master, class Missing = typename WhatIsMissing<Stuff, Master, Stuff>::Items >
+struct MakeCompleteImpl {
+ typedef typename MakeCompleteImpl< typename BindTogether< Stuff, typename ExtractChains< Missing >::Result >::Result , Master >::Result Result;
+};
+
+template <class Stuff, class Master >
+struct MakeCompleteImpl< Stuff, Master, Empty > {
+ typedef Stuff Result;
+};
+
+///Makes sure that the chains for all necessary parent-nodes are available
+template < class Stuff, class Master >
+struct MakeComplete {
+ typedef typename MakeCompleteImpl< Stuff, Master >::Result Result;
+};
+
+/**Stuff is the list of types that define the tree
+in form of multiple Chain<Type, Parent-Type, int preferredIndex>, and EntryTemplate is a class which embeds
+a template-class called "Entry" which will be inherited by every single node, with the current type of the node as template-parameter(See StandardEntryTemplate).
+Instead of using the explicit Chain<...>-notation, just a type can be used, and the chain will be extracted by using the type's Precursor"-Typedef, and it's preferredIndex constant/enum. Every item MUST have an explicit sub-id, the automatic generation of ID's was abandoned to make building partial trees easiert.
+Stuff is a set of "Chain"'s or Types, bound together with "Binder". It can be incomplete, only the important leafs have to be there, and the tree leading to them is extracted automatically.
+ */
+template < class Master, class Stuff, class EntryTemplate = StandardEntryTemplate >
+struct TreeMasterNode : public TreeNode < Master, /* typename Rebalance<*/ typename MakeComplete< typename ExtractChains< Stuff >::Result, Master >::Result /*>::Result*/, EntryTemplate > {
+ typedef TreeNode < Master, /*typename Rebalance<*/ typename MakeComplete< typename ExtractChains< Stuff >::Result, Master >::Result /*>::Result*/, EntryTemplate > Base;
+
+ template < class Out >
+ void print( Out& out ) {
+ Base::buildFullId( "" );
+ Base::print( out );
+ }
+
+ template <class Action>
+ uchar find( const uchar*const id, Action& act ) const {
+ return Base::find( id, act );
+ }
+
+};
+/*
+ template< class Item, class Stuff, class EndItem, int real >
+ struct IsOnWay {
+ };*/
+
+template <class Type>
+struct GetResultValue {
+ enum {
+ Result = Type::Result
+ };
+};
+
+template <class Item>
+struct BaseItem {
+ typedef Empty Result;
+};
+
+template <class Item1, class Item2>
+struct BaseItem< Binder< Item1, Item2 > > {
+ typedef typename BaseItem<Item1>::Result Result;
+};
+
+template <class Base, class Parent, uchar preferredSubId>
+struct BaseItem< Chain< Base, Parent, preferredSubId > > {
+ typedef Base Result;
+};
+
+
+/* template<class Item>
+ struct GetParentHighLevel {
+ typedef typename BaseItem<typename GetParents< typename MakeComplete< typename ExtractChains< Stuff >::Result >::Result>::Result>::Result Result;
+};*/
+
+template < class Item, class Stuff, class EndItem >
+struct IsOnWay {
+ enum {
+ Result = GetResultValue< IsOnWay< Item, Stuff, typename GetParents< Stuff, EndItem >::Result > >::Result
+ };
+};
+
+template < class Item, class Stuff >
+struct IsOnWay< Item, Stuff, Item > {
+ enum {
+ Result = 1
+ };
+};
+
+template < class Item, class Stuff >
+struct IsOnWay < Item, Stuff, Empty > {
+ enum {
+ Result = 0
+ };
+};
+
+template < class Item, class Stuff, class Leaf >
+struct IsNecessary {
+ enum {
+ Result = IsOnWay< Item, Stuff, Leaf>::Result
+ };
+};
+
+template < class Item, class Stuff >
+struct IsNecessary<Item, Stuff, All> {
+ enum {
+ Result = 1
+ };
+};
+
+template < class Item, class Stuff, class Side1, class Side2 >
+struct IsNecessary<Item, Stuff, Binder< Side1, Side2 > > {
+ enum {
+ Result = IsNecessary< Item, Stuff, Side1 >::Result | IsNecessary< Item, Stuff, Side2 >::Result
+ };
+};
+
+template <int necessary, class SlaveType, class Stuff, uchar id_, uchar preferredSubId, class EntryTemplate>
+struct TreeSlaveData {
+ enum ID {
+ id = id_ > preferredSubId ? id_ : preferredSubId
+ };
+ std::string fullId;
+ TreeNode<SlaveType, Stuff, EntryTemplate> slave;
+
+ TreeSlaveData() {}
+
+ template < class Out >
+ inline void print( Out& out, std::string prefix ) {
+ prefix += "-";
+ out << prefix + " ";
+ if ( !fullId.empty() )
+ printId( out, ( uchar* ) & fullId[ 0 ] );
+ else
+ out << "invalid-id";
+ out << "\n";
+ slave.print( out, prefix );
+ }
+
+ inline void buildFullId( const std::string& pre ) {
+ fullId = pre;
+ fullId.push_back( id );
+ slave.buildFullId( fullId );
+ }
+};
+
+/// It would be useful not to create this type at all, but currently it must be done for numbering-consistency
+template <class SlaveType, class Stuff, uchar id_, uchar preferredSubId, class EntryTemplate>
+struct TreeSlaveData< 0, SlaveType, Stuff, id_, preferredSubId, EntryTemplate> {
+ enum {
+ id = id_ > preferredSubId ? id_ : preferredSubId
+ };
+
+ inline void buildFullId( const std::string& pre ) {}
+
+ ///dummies:
+ struct DummySlave {
+ template <class Action>
+ inline uchar find( const uchar*const /*id*/, Action& /*act*/ ) const {
+ return 0;
+ }
+ };
+ DummySlave slave;
+
+ template < class Out >
+ inline void print( Out& out, std::string prefix ) {}
+
+}
+;
+
+///IsNecessary<Slave, Stuff, ExtractLeafs>::Result
+template <class Slave, class Stuff, uchar cnum, uchar preferredSubId, class EntryTemplate>
+struct TreeNodeSlaves< Consider<Entry<Slave, preferredSubId> >, Stuff, EntryTemplate, cnum> : public TreeSlaveData<1, Slave, Stuff, cnum, preferredSubId, EntryTemplate> {
+ typedef TreeSlaveData<1, Slave, Stuff, cnum, preferredSubId, EntryTemplate> Base;
+ inline void buildFullId( const std::string& pre ) {
+ Base::buildFullId( pre );
+ }
+
+ template <class Action>
+ inline uchar find( const uchar c, const uchar*const id, Action& act ) const {
+ if ( c == Base::id ) {
+ return Base::slave.template find<Action>( id, act );
+ } else {
+ return 0;
+ }
+ }
+
+ template < class Out >
+ inline void print( Out& out, std::string prefix ) {
+ Base::print( out, prefix );
+ }
+};
+
+template <class Slave1, class Slave2, class Stuff, uchar cnum, class EntryTemplate>
+struct TreeNodeSlaves< Consider<Binder<Slave1, Slave2> >, Stuff, EntryTemplate, cnum> : private TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum>, private TreeNodeSlaves < Consider<Slave2>, Stuff, EntryTemplate, TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum>::id + 1 > {
+ typedef TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum> Side1;
+ typedef TreeNodeSlaves < Consider<Slave2>, Stuff, EntryTemplate, Side1::id + 1 > Side2;
+ enum {
+ begin = cnum,
+ middle = Side1::id,
+ id = Side2::id
+ };
+
+ inline void buildFullId( const std::string& pre ) {
+ Side1::buildFullId( pre );
+ Side2::buildFullId( pre );
+ };
+
+ template <class Action>
+ inline uchar find( const uchar c, const uchar*const id, Action& act ) const {
+ if ( c > middle ) {
+ return Side2::find( c, id, act );
+ } else {
+ return Side1::find( c, id, act );
+ }
+ }
+ template < class Out >
+ inline void print( Out& out, std::string prefix ) {
+ Side1::print( out, prefix );
+ Side2::print( out, prefix );
+ }
+};
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp (revision 1522570)
@@ -0,0 +1,460 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "teamworkserver.h"
+#include "serialization.h"
+#include "messageimpl.h"
+#include "teamworkmessages.h"
+#include "teamworkservermessages.h"
+#include "forwardsession.h"
+#include "multisession.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+namespace Teamwork {
+using namespace std;
+
+BIND_LIST_4( TeamworkServerDispatchMessages, SystemMessage, ForwardMessage, IdentificationMessage, TextMessage )
+
+template <class From, class To, class Compare>
+list<To> mapValues( map<From, To, Compare> mp ) {
+ list<To> ret;
+ for ( typename map<From, To, Compare>::iterator it = mp.begin(); it != mp.end(); ++it ) {
+ ret.push_back( ( *it ).second );
+ }
+ return ret;
+}
+
+void Server::setIdentity( const UserPointer& user ) {
+ ident_ = user;
+}
+
+UserPointer Server::identity() const {
+ return ident_;
+}
+
+Server::Server( const ServerInformation& inf, const LoggerPointer& logger ) : BasicServer( inf.addr().c_str(), inf.port(), globalMessageTypeSet(), logger ), MessageSendHelper( globalMessageTypeSet() ), userListDirty_( false ) {
+ //dispatcher_.print( cout );
+}
+
+void Server::getUserSet( UserSet& users ) {
+ users = users_;
+}
+
+void Server::insertUserSet( const UserSet& users ) {
+ users_.insert( users.begin(), users.end() );
+}
+
+Server::~Server() {
+ for ( UserSet::iterator it = users_.begin(); it != users_.end(); ++it ) {
+ UserPointer::Locked l = *it;
+ if ( l ) {
+ l->setSession( 0 );
+ } else {
+ err() << "could not lock a UserPointer while destruction";
+ }
+ }
+}
+
+SessionPointer Server::createSession( BasicTCPSocket* sock ) {
+ return new MultiSession( *sock, new HandlerProxy<BasicServer>( this ), globalMessageTypeSet(), logger() );
+ ///check yet whether this is thread-safe, if not give some kind of safe pointers
+}
+
+bool Server::registerSession( SessionPointer session ) {
+ MultiSessionPointer s = session.cast<MultiSession>();
+ if ( s ) {
+ unknownSessions_.insert( s );
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool Server::registerSessionUser( const UserPointer& user ) {
+ UserPointer::Locked l = user;
+ if( !l ) return false;
+ if( !l->online().session() ) return false;
+ sessions_[ l->online().session() ] = user ;
+ return true;
+}
+
+void Server::sendUserLists() {
+ out( Logger::Debug ) << "broadcasting user-list";
+ list<UserPointer> users = mapValues( sessions_ );
+ for ( SessionMap::iterator it = sessions_.begin(); it != sessions_.end(); ++it ) {
+ send<UserListMessage>( ( *it ).first.unsafe(), users, ( *it ).second );
+ }
+}
+
+void Server::initial( void ) {
+ return BasicServer::initial();
+}
+
+UserPointer Server::findUser( const UserPointer& user ) {
+ UserSet::iterator it = users_.find( user );
+ if ( it != users_.end() )
+ return * it;
+ else
+ return 0;
+}
+
+UserPointer Server::findUser( const UserIdentity& user ) {
+ UserSet::iterator it = users_.find( new User( user ) );
+ if ( it != users_.end() )
+ return * it;
+ else
+ return 0;
+}
+
+bool Server::think() {
+ ///identify dead sessions and free pointers to them so they are deleted by reference-counting
+ for ( SessionSet::iterator it = unknownSessions_.begin(); it != unknownSessions_.end(); ) {
+ if ( !( *it ).unsafe() ->isRunning() ) {
+ out() << "deleting unknown incoming session";
+ SessionSet::iterator itb = it;
+ ++it;
+ unknownSessions_.erase( itb );
+ } else
+ ++it;
+ }
+
+ for ( SessionMap::iterator it = sessions_.begin(); it != sessions_.end(); ) {
+ if ( !( *it ).first.unsafe() ->isRunning() ) {
+ SessionMap::iterator itb = it;
+ ++it;
+ UserPointer::Locked l = ( *itb ).second;
+ if ( l ) {
+ l->setSession( 0 );
+ } else {
+ err() << "could not lock user-data, reference to session can not be cleared";
+ }
+
+ closeSession( ( *itb ).first );
+ /*userDisconnected( (*itb).second );
+ sessions_.erase( itb );*/
+ out() << "deleting incoming session";
+ } else
+ ++it;
+ }
+
+ while ( !messages().empty() ) {
+ MessagePointer::Locked l = ( MessagePointer ) messages().front();
+ if ( l ) {
+ processMessage( l.data() );
+ } else {
+ out() << "a message from the incoming queue could not be locked";
+ }
+ messages().pop_front();
+ }
+
+ if ( userListDirty_ ) {
+ sendUserLists();
+ userListDirty_ = false;
+ }
+
+ return BasicServer::think();
+}
+
+void Server::final( void ) {
+ return BasicServer::final();
+}
+
+void Server::closeAllIncomingSessions() {
+ int c = 0;
+ while ( !sessions_.empty() && ++c < 50000 ) {
+ closeSession( ( *sessions_.begin() ).first );
+ }
+}
+
+void Server::closeSession( const SessionPointer& session ) {
+ if(!session)
+ return;
+ bool haveSession = false;
+ {
+ SessionMap::iterator it = sessions_.find( session );
+ if ( it != sessions_.end() ) {
+ UserPointer::Locked l = (*it).second;
+ haveSession = true;
+
+ if ( l && l->online().session() == session ) {
+ l->setSession( 0 );
+ } else
+ out() << "error locking user";
+ }
+ }
+
+ session.unsafe() ->stopRunning();
+ if ( haveSession ) {
+ userDisconnected( sessions_[ session ] );
+ userListDirty_ = true;
+ }
+ unknownSessions_.erase( session.cast<MultiSession>() ); //do this before the next line, because the session may already be deleted
+ sessions_.erase( session );
+}
+
+MessageTypeSet& Server::messageTypes() {
+ return globalMessageTypeSet();
+}
+
+UserPointer Server::createUser( IdentificationMessage* msg ) {
+ return new User( *msg );
+}
+
+UserPointer Server::createUser( const User* user ) {
+ return new User( user );
+}
+
+void Server::addUser( UserPointer user ) {
+ out() << "adding new user: \"" << user.unsafe() ->safeName() << "\"";
+ users_.insert( user );
+}
+
+UserPointer Server::getUser( const UserPointer& user ) {
+ UserPointer ret = findUser( user );
+ if ( !ret ) {
+ UserPointer::Locked l = user;
+ if ( l ) {
+ UserPointer u = createUser( l );
+ addUser( u );
+ return u;
+ } else {
+ return 0;
+ }
+ } else {
+ return ret;
+ }
+}
+
+UserPointer Server::getUser( const UserIdentity& user ) {
+ UserPointer ret = findUser( user );
+ if ( !ret ) {
+ UserPointer u = createUser( LockedSharedPtr<User>( new User( user ) ) );
+ addUser( u );
+ return u;
+ } else {
+ return ret;
+ }
+}
+
+int Server::receiveMessage( IdentificationMessage* msg ) {
+ string username = "unknown user";
+ MultiSessionPointer theSession;
+ try {
+ MultiSessionPointer session = msg->info().session().cast<MultiSession>();
+ if ( !session )
+ throw TeamworkError( "failed to cast server-session" );
+ theSession = session;
+
+ MultiSessionPointer::Locked l = session;
+ if ( !l )
+ throw TeamworkError( "failed to lock source-session" );
+
+ UserPointer user = createUser( msg );
+ if ( !user )
+ throw TeamworkError( "could not create user" );
+
+ UserPointer::Locked ul = user;
+ if ( !ul )
+ throw TeamworkError( "failed to lock user" );
+
+ UserSet::iterator it = users_.find( user );
+
+ username = ul->name();
+
+ UserPointer::Locked id = identity();
+ if ( id ) {
+ if ( id->matchIdentity( *ul ) ) {
+ throw TeamworkError( "a user tried to login with the identity of the local server" );
+ }
+ }
+
+ if ( it == users_.end() ) {
+ if( configuration_.serverPassword.empty() || ul->password() == configuration_.serverPassword ) {
+ out() << "adding new user: " << ul->name();
+ addUser( user );
+ } else {
+ throw TeamworkError( "server-password mismatched" );
+ }
+ } else {
+ UserPointer::Locked nul = *it;
+ if ( !nul )
+ throw TeamworkError( "failed to lock user" );
+ if ( !nul->match( *ul ) ) {
+ ostringstream str;
+ str << "authentication failed, names: \"" << nul->name() << "\" \"" << ul->name() << "\", banned: " << nul->banned();
+ throw TeamworkError( str.str() );
+ }
+ ul = nul;
+ user = *it;
+ }
+
+ l->setSessionName( ul->name() + "_" + l->sessionName() );
+ l->setUser( user );
+
+ if ( ul->online() ) {
+ string peerDesc = "unknown peer";
+ SessionPointer::Locked ll = ul->online().session();
+ if ( ll )
+ peerDesc = ll->peerDesc();
+ out() << "the user " + ul->name() + " logged in twice, the first one from " << peerDesc << " is disconnected";
+ send<SystemMessage>( ul->online().session().unsafe(), SystemMessage::BadAuthentication, "another use with the name " + ul->name() + " logged in" );
+ send<SystemMessage>( msg->info().session().unsafe(), SystemMessage::AlreadyLoggedIn, "the user " + ul->name() + " was already logged in" );
+ closeSession( ul->online().session() );
+ }
+
+ ul->setSession( msg->info().session() );
+ sessions_[ session.cast<SessionInterface>() ] = user;
+ unknownSessions_.erase( session );
+ out() << "login successful: \"" << user.unsafe() ->name() << "\"";
+ send<SystemMessage>( l, SystemMessage::LoginSuccess, string( "welcome to this teamwork-server" ) );
+ userConnected( user );
+
+ userListDirty_ = true;
+ } catch ( exception & exc ) {
+ string addrInfo;
+ MultiSessionPointer::Locked l = theSession;
+ if ( l )
+ addrInfo = "from " + l->peerDesc() + " ";
+ ;
+
+ if ( theSession )
+ unknownSessions_.erase( theSession );
+
+ out() << "login of user \"" << username << "\" " << addrInfo << "failed: " << exc.what();
+
+ msg->info().session().unsafe()->send( new SystemMessage( messageTypes_ , SystemMessage::LoginFailedUnknown, "reason: " + string( exc.what() ) ) );
+
+ }
+ return 0;
+}
+
+int Server::receiveMessage( TextMessage* msg ) {
+ out() << "got text-message: " << msg->text();
+ return 0;
+}
+
+int Server::receiveMessage( MessageInterface* /*msg*/ ) {
+ out() << "got unknown message-type";
+ return 0;
+}
+
+int Server::receiveMessage( SystemMessage* msg ) {
+ out() << "got system-message: " << msg->messageAsString() << ": " << msg->text();
+ switch ( msg->message() ) {
+ case SystemMessage::GetUserList: {
+ //SessionPointer::Locked l = msg->info().session();
+ if ( msg->info().session() ) {
+ list<UserPointer> users = mapValues( sessions_ );
+ if ( identity() )
+ users.push_back( identity() );
+
+ out() << "sending user-list of size " << users.size();
+
+ sendReply<UserListMessage>( msg, users, msg->info().user() );
+ }
+ };
+ break;
+ default:
+ break;
+ }
+ return 0;
+}
+
+UserPointer Server::findSessionUser( const SessionPointer& session ) {
+ SessionMap::iterator it = sessions_.find( session );
+ if ( it == sessions_.end() )
+ return UserPointer();
+ else
+ return ( *it ).second;
+}
+}
+
+int Teamwork::Server::receiveMessage( ForwardMessage * msg ) {
+ out( Logger::Debug ) << "forwarding message";
+
+ UserPointer u( new User( msg->target() ) );
+ UserSet::iterator it = users_.find( u );
+
+ MultiSession* sess = msg->info().session().cast<MultiSession>().unsafe();
+ if ( !sess ) {
+ out() << "got forward-message from unknown session";
+ return 0;
+ }
+
+ try {
+ if ( it != users_.end() ) {
+ ///@todo check if the given session (user) is authorized to send data to the given target(check for connection), and check whether the source-user-information in the message fits the real source
+ UserPointer::Locked l = *it;
+ if ( l ) {
+ if ( l->online() && l->online().session() ) {
+ out( Logger::Debug ) << "forwarding a message from " << msg->source().name() << " to " << msg->target().name();
+ l->online().session().unsafe() ->send( msg );
+ } else {
+ if ( msg->storeOnServer() ) {
+ out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << ", storing it on the server";
+ sendReply<SystemMessage>( msg, SystemMessage::StoredOnServer, "" );
+ } else {
+ out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << " because the target is not online";
+ sendReply<SystemMessage>( msg, SystemMessage::BadTarget, "" );
+ }
+ }
+ } else {
+ err() << "internal error: could not lock user";
+ throw string( "internal error" );
+ }
+ } else {
+ throw string( "the target-user does not exist" );
+ }
+ } catch ( string s ) {
+ out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << " reason: " << s;
+ sendReply<SystemMessage>( msg, SystemMessage::BadTarget, s );
+ }
+
+ return 1;
+}
+
+void Teamwork::Server::setConfiguration( const ServerConfiguration& conf ) {
+ configuration_ = conf;
+ if( !configuration_.serverName.empty() && !identity() ) {
+ setIdentity( new User( conf.serverName ) );
+ }
+ for( ServerConfiguration::UserSet::iterator it = configuration_.registeredUsers.begin(); it != configuration_.registeredUsers.end(); ++it ) {
+ UserPointer::Locked u = new User( *it );
+ UserPointer ru = findUser( u );
+ if( ru ) {
+ ///The user already exists, update it
+ UserPointer::Locked rlu = ru;
+ if( rlu ) {
+ (*rlu) = *it;
+ rlu->setSession( rlu->online().session() ); ///Session is used to track the state of the user, so give a hint using that interface that something about the user changed.
+ }
+ } else {
+ addUser( createUser( u ) );
+ }
+ }
+}
+
+const Teamwork::ServerConfiguration& Teamwork::Server::configuration() const {
+ return configuration_;
+}
+
+void Teamwork::Server::processMessage( MessageInterface* msg ) {
+ MessageDispatcher< Server, TeamworkServerDispatchMessages > dispatcher(*this);
+ dispatcher( msg );
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp (revision 1522570)
@@ -0,0 +1,125 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "multisession.h"
+#include "teamworkserver.h"
+#include "forwardsession.h"
+
+namespace Teamwork {
+
+MultiSession::MultiSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger ) : BasicTCPSession( server, handler, messages, logger, "incoming_" ), incoming_( true ) {}
+
+MultiSession::MultiSession( const ServerInformation& server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : BasicTCPSession( server.addr().c_str() , server.port(), handler, messages, logger, namePrefix ), incoming_( false ) {}
+
+void MultiSession::deleteForwardSessions() {
+ for ( ForwardSessionMap::iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ++it ) {
+ ForwardSessionPointer::Locked l = ( *it ).second;
+ if ( l ) {
+ l->stopRunningNow();
+ l->final();
+ } else
+ err() << "could not lock a Forward-session for final";
+ }
+ for ( list<ForwardSessionPointer>::iterator it = garbageSessions_.begin(); it != garbageSessions_.end(); ++it ) {
+ ForwardSessionPointer::Locked l = ( *it );
+ if ( l ) {
+ l->stopRunningNow();
+ l->final();
+ } else
+ err() << "could not lock a garbage Forward-session for final";
+ }
+ forwardSessions_.clear();
+ garbageSessions_.clear();
+}
+
+void MultiSession::final() {
+ deleteForwardSessions();
+ BasicTCPSession::final();
+}
+
+bool MultiSession::think() {
+ bool ret = false;
+
+ for ( ForwardSessionMap::iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ) {
+ ForwardSessionMap::iterator it2 = it;
+ ++it;
+ ///This costs very much and should be optimized once it works perfectly
+ ForwardSessionPointer::Locked l = ( *it2 ).second;
+ if ( l ) {
+ if ( !( *it2 ).second.unsafe() ->isRunning() ) {
+ l->final();
+ forwardSessions_.erase( it2 );
+ } else {
+ l->think();
+ }
+ } else
+ out() << "could not lock a forward-session for think/final";
+ }
+
+ for ( list<ForwardSessionPointer>::iterator it = garbageSessions_.begin(); it != garbageSessions_.end(); ) {
+ list<ForwardSessionPointer>::iterator it2 = it;
+ ++it;
+ if ( !( *it2 ).unsafe() ->isRunning() ) {
+ ForwardSessionPointer::Locked l = ( *it2 );
+ if ( l ) {
+ l->final();
+ garbageSessions_.erase( it2 );
+ } else
+ out() << "could not lock a garbage Forward-session for final";
+ }
+ }
+
+ return BasicTCPSession::think() | ret;
+}
+
+template <class Type>
+ class FastLockHelper {}
+;
+
+MultiSession::~MultiSession() {
+ deleteForwardSessions();
+}
+
+void MultiSession::registerForwardSession( const UserPointer& peer, const ForwardSessionPointer& sess ) {
+ if ( forwardSessions_.find( peer ) != forwardSessions_.end() ) { ///finalize some older open session to the same target
+ UserPointer::Locked u = peer;
+ out() << "closing a duplicated indirect session to " << ( u ? u->name() : "not lockable" );
+ forwardSessions_[ peer ].unsafe() ->stopRunning();
+ garbageSessions_.push_back( forwardSessions_[ peer ] );
+ }
+
+ forwardSessions_[ peer ] = sess;
+}
+
+bool MultiSession::handleMessage( MessagePointer msg ) throw() {
+ MessagePointer mp = msg;
+ SafeSharedPtr<ForwardMessage> forward = mp.cast<ForwardMessage>();
+ if ( forward ) {
+ SafeSharedPtr<ForwardMessage>::Locked l = forward;
+ UserPointer u( new User( l->source() ) );
+ ForwardSessionMap::iterator it = forwardSessions_.find( u );
+ if ( it != forwardSessions_.end() ) {
+ ForwardSessionPointer::Locked l = ( *it ).second;
+ if ( l ) {
+ return l->handleForwardMessage( forward );
+ } else {
+ err() << "could not lock a forward-session to process an incoming forward-message";
+ }
+ }
+ }
+
+ return BasicTCPSession::handleMessage( msg );
+}
+
+}
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp (revision 1522570)
@@ -0,0 +1,225 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#include "basicserver.h"
+#include "serialization.h"
+
+#include "handler.h"
+#include "messageinterface.h"
+#include "basicsession.h"
+
+
+#define SLEEPTIME 50
+
+//#ifdef CCXX_NAMESPACES
+using namespace std;
+//#endif
+
+typedef char StandardDataType;
+
+
+namespace Teamwork {
+
+BasicTCPSocket::BasicTCPSocket( ost::InetAddress &ia, int port ) : ost::TCPSocket( ia, port ) {}
+
+bool BasicTCPSocket::onAccept( const ost::InetHostAddress &ia, ost::tpport_t port ) {
+ setCompletion( false );
+ cout << "accepting from: " << ia.getHostname() << ":" << port << endl;
+
+ return true;
+}
+
+/**The MessageType holds all information necessary to Identify a Message and build an Object from it.
+ The IdList is an inheritance-chain. Messages whose list begins with IDs of other Messages must be specializations of those, and the parent-types should be able to handle those too.
+*/
+
+void BasicServer::buildSocket() {
+ closeSocket();
+ failed_ = false;
+
+ try {
+ server_ = new BasicTCPSocket( addr, port_ );
+ out() << "server is listening on " << addr << ":" << port_;
+ } catch ( ost::Socket * socket ) {
+ failed_ = true;
+ ost::tpport_t port;
+ int erro = socket->getErrorNumber();
+ ost::InetAddress saddr = ( ost::InetAddress ) socket->getPeer( &port );
+ err() << "socket error " << saddr.getHostname() << ":" << port << " = " << erro;
+ if ( erro == ost::Socket::errBindingFailed ) {
+ err() << "bind failed; port busy";
+ } else {
+ err() << "client socket failed";
+ }
+ if ( server_ )
+ delete server_;
+ server_ = 0;
+ }
+}
+
+void BasicServer::run() {
+ lockCountUp();
+ out() << "server started";
+ bool needMore = false;
+ while ( !exit_ ) {
+ lockCountDown(); ///leave room time other threads that try to lock this one
+ if ( server_ && server_->isPendingConnection( needMore ? 1 : SLEEPTIME ) ) {
+ lockCountUp();
+ try {
+ ost::InetHostAddress next = server_->getRequest();
+ if ( !allowIncoming_ ) {
+ out() << "refusing session for client " << next;
+ server_->reject();
+ } else {
+ out() << "creating session for client " << next;
+ SessionPointer tcp = createSession( server_ );
+ if ( tcp ) {
+ out() << "session created" ;
+ if ( !registerSession( tcp ) ) {
+ server_->reject();
+ out() << "session rejected";
+ } else {
+ tcp.unsafe() ->startSession();
+ }
+ } else {
+ out() << "session was rejected";
+ server_->reject();
+ }
+ }
+ } catch ( ost::Socket * socket ) {
+ ost::tpport_t port;
+ int err = socket->getErrorNumber();
+ ost::InetAddress saddr = ( ost::InetAddress ) socket->getPeer( &port );
+ cerr << "socket error " << saddr.getHostname() << ":" << port << " = " << err << endl;
+ if ( err == ost::Socket::errBindingFailed )
+ cerr << "bind failed; port busy" << endl;
+ else
+ cerr << "client socket failed" << endl;
+ }
+ } else {
+ sleep( 10 );
+ lockCountUp();
+ }
+ needMore = think();
+
+ if ( _Shared_count() == 1 && selfPointer_ ) { ///The server is only referenced by itself, so it may be deleted
+ out() << "server is closing because the external reference-count reached zero";
+ exit_ = true;
+ }
+ }
+ closeSocket();
+
+ out() << "server exiting";
+ stopRunning();
+ exit();
+}
+
+void BasicServer::allowIncoming( bool allow ) {
+ if ( allow ) {
+ out() << "incoming connections activated, opening socket";
+ buildSocket();
+ } else {
+ out() << "incoming connections deactivated, closing socket";
+ closeSocket();
+ }
+ allowIncoming_ = allow;
+}
+
+void BasicServer::closeSocket() {
+ if ( server_ )
+ delete server_;
+ server_ = 0;
+}
+
+/**Should be overridden to create own types derived from BasicTCPSession, can return 0*/
+SessionPointer BasicServer::createSession( BasicTCPSocket* sock ) {
+ BasicTCPSession * s = new BasicTCPSession( *sock , new HandlerProxy<BasicServer>( this ), messageTypes_, logger_, "incoming_" );
+ return s;
+}
+
+bool BasicServer::handleMessage( MessagePointer msg ) throw() {
+ messagesToHandle_ << msg;
+ return true;
+}
+
+
+LoggerPrinter BasicServer::err() {
+ LoggerPrinter l( logger_, Logger::Error );
+ l << "server: ";
+ return l;
+}
+
+LoggerPrinter BasicServer::out( Logger::Level level ) {
+ LoggerPrinter l( logger_, level );
+ l << "server: ";
+ return l;
+}
+
+void BasicServer::run();
+
+void BasicServer::initial() {
+ Thread::initial();
+}
+
+bool BasicServer::think() {
+ //messagesToHandle_.clear();
+ return false;
+}
+
+void BasicServer::final( void ) {
+ stopRunning();
+ lockCountDown();
+ clearSelfPointer();
+}
+
+bool BasicServer::registerSession( SessionPointer /*session*/ ) {
+ return false;
+}
+
+void BasicServer::clearSelfPointer() {
+ SafeSharedPtr<BasicServer> s = selfPointer_;
+ selfPointer_ = 0;
+}
+
+LoggerPointer& BasicServer::logger() {
+ return logger_;
+}
+
+BasicServer::BasicServer( const char* str, int port, MessageTypeSet& messageTypes, LoggerPointer logger, bool openServer ) : Thread( ), messageTypes_( messageTypes ), logger_( logger ), failed_( false ), exit_( false ), allowIncoming_( openServer ), server_( 0 ), port_( port ), selfPointer_( this ) {
+ addr = str;
+
+ if( allowIncoming_ )
+ buildSocket();
+}
+
+BasicServer::~BasicServer() {
+ closeSocket();
+}
+
+bool BasicServer::isOk() {
+ return !exit_ && !failed_;
+}
+
+SafeList<MessagePointer>& BasicServer::messages() {
+ return messagesToHandle_;
+}
+
+void BasicServer::stopRunning() {
+ exit_ = true;
+}
+
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp (revision 1522570)
@@ -0,0 +1,634 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "basicsession.h"
+#include <boost/archive/archive_exception.hpp>
+
+#include "serialization.h"
+#include "logger.h"
+#include "handler.h"
+#include "messageimpl.h"
+#include "user.h"
+#include "messagetypeset.h"
+#include "helpers.h"
+#define MESSAGEDEBUG
+//#define DISABLETRYCATCH
+#define DISABLEUNIVERSALCATCH
+//#define DEBUGLOG(x) out( Logger::Debug ) << x
+//#define DEBUGLOG(x)
+#define DEBUGLOG( x ) cout << x
+
+namespace Teamwork {
+using namespace std;
+
+void compare( const std::vector<char>& buffer, const std::vector<char>& buffer2 ) {
+ std::vector<char> buf1=buffer;
+ buf1.push_back(0);
+ std::vector<char> buf2=buffer2;
+ buf2.push_back(0);
+ std::cout << "comparing buffers, first buffer:\n" << &buf1[0] << "\nsecond buffer:\n" << &buf2[0] << "\n";
+}
+
+SessionReplyManager::SessionReplyManager( MutexInterfaceImpl* selfMutex ) : selfMutex_( selfMutex ) {}
+
+void SessionReplyManager::addWaitingMessage( MessageInterface* msg ) {
+ waitingMessages_[ msg->uniqueId() ] = MessagePointer( msg );
+}
+
+bool SessionReplyManager::handleMessageWaiting( MessagePointer & msg ) {
+ if ( msg ) {
+ uint i = msg.unsafe() ->info().isReplyTo();
+ if ( i ) {
+ WaitingMap::iterator it = waitingMessages_.find( i );
+ if ( it != waitingMessages_.end() ) {
+ MessageInterface::ReplyResult ret;
+ MessagePointer::Locked l = ( *it ).second;
+ if ( l ) {
+ if ( selfMutex_ )
+ selfMutex_->lockCountDown();
+ ret = l->gotReply( msg );
+ if ( selfMutex_ )
+ selfMutex_->lockCountUp();
+ if ( !ret.messageHandled )
+ msg.unsafe() ->info().setReplyMessage( ( *it ).second );
+ } else {
+ //err() << "could not lock waiting message";
+ }
+
+ if ( !ret.awaitingMore )
+ waitingMessages_.erase( it );
+
+ return ret.messageHandled;
+ }
+ }
+ }
+ return false;
+}
+
+void SessionReplyManager::removeAllMessages() {
+ for ( WaitingMap::iterator it = waitingMessages_.begin(); it != waitingMessages_.end(); ++it ) {
+ MessagePointer::Locked l = ( *it ).second;
+ if ( l ) {
+ if ( selfMutex_ )
+ selfMutex_->lockCountDown();
+ l->gotReply( MessagePointer() );
+ if ( selfMutex_ )
+ selfMutex_->lockCountUp();
+ }
+ }
+
+ waitingMessages_.clear();
+}
+
+SessionReplyManager::~SessionReplyManager() {
+ removeAllMessages();
+}
+
+SessionInterface::SessionInterface() {
+}
+
+SessionInterface::~SessionInterface() {
+}
+
+UserPointer SessionInterface::safeUser() const {
+ return user_;
+}
+
+void SessionInterface::setUser( const UserPointer& user ) {
+ user_ = user;
+}
+
+void SessionInterface::final() {
+ /*UserPointer::Locked l = user_;
+ if( l )
+ l->setSession( this );*/
+}
+
+
+bool SessionInterface::handleMessage( MessagePointer /*msg*/ ) throw() {
+ return false;
+}
+
+string toString( std::vector<char>& v ) {
+ string ret;
+ for ( uint a = 0; a < v.size(); a++ )
+ ret += v[ a ];
+ return ret;
+}
+
+void BasicTCPSession::initial( void ) {
+ running_ = true;
+ out() << "connecting";
+ ost::TCPSession::initial();
+ if ( isConnected() ) {
+ out() << "connection successful";
+ } else {
+ err() << "connection failed";
+ }
+
+ if ( isActive() ) {}
+ else {
+ err() << "connection inactive";
+ }
+}
+
+bool BasicTCPSession::inputOutput() {
+ bool worked = false;
+#ifndef DISABLETRYCATCH
+ try {
+#endif
+ if ( isPending( pendingInput, 0 ) ) {
+ if ( !receivingSize_ ) {
+ std::vector<char> sz;
+ int cnt = getData( sz, 4 );
+ if ( cnt == 4 && sz.size() == 4 ) {
+ int s = ( *( int* ) ( &sz[ 0 ] ) );
+ if ( s >= 0 && s < MAXMESSAGESIZE ) {
+ receivingData_.clear();
+ receivingSize_ = s;
+ //out() << "receiving message of size " << receivingSize_;
+ } else {
+ throw StreamError( "message-header-integer is wrong: " + formatInt( s ) );
+ }
+ } else {
+ throw StreamError( "message-header-integer is wrong, count of bytes: " + formatInt( cnt ) + " size of buffer: " + formatInt( sz.size() ) );
+ }
+ DEBUGLOG( "receiving message of size " << receivingSize_ );
+ }
+
+ if ( isPending( pendingInput, 0 ) ) {
+ receivingSize_ -= getData( receivingData_, receivingSize_ );
+
+ if ( receivingSize_ <= 0 ) {
+ ///process a complete message
+ if ( !receivingData_.empty() ) {
+ processIncomingMessage( receivingData_ );
+ //out() << "got: " << toString( receivingData_ );
+ MessagePointer msg = buildMessageFromBuffer( receivingData_, messages_, this );
+ MessagePointer::Locked l = ( MessagePointer ) msg;
+ if ( l ) {
+ l->info().setSession( this );
+ DEBUGLOG( "handling message of size " << receivingData_.size() << " and type " << messages_.identify( l ) );
+ } else
+ out() << "handling not lockable message";
+
+ if ( msg ) {
+ if ( !handleMessageWaiting( msg ) )
+ handleMessage( msg );
+ } else {
+ err() << "a received message could not be reconstructed";
+ }
+ worked = true;
+ }
+
+ receivingSize_ = 0;
+ receivingData_.clear();
+ }
+ //out() << "received: " << receivingData_.size() << " yet needed: " << receivingSize_;
+ }
+ }
+ if ( sendData_.empty() ) {
+ //if( sendingMessage_ )
+ sendingResult( true );
+ serializeMessage();
+ }
+ if ( !sendData_.empty() ) {
+ //out() << "writing " << sendData_.size();
+ uint cnt = writeData( sendData_, sendData_.size() );
+ //DEBUGLOG( "wrote " << cnt << " left: " << sendData_.size() );
+ //if( sendData_.empty() )
+ if ( cnt )
+ worked = true;
+ }
+
+#ifndef DISABLETRYCATCH
+
+ } catch ( const StreamError & err ) {
+ failed( std::string( "stream-error in inputOuput: " ) + err.what() );
+ }
+ catch( const boost::archive::archive_exception& exc ) {
+ failed( std::string( "archive-exception while deserializing message: " + std::string( exc.what() ) ) );
+ }
+
+#ifndef DISABLEUNIVERSALCATCH
+ catch ( std::exception & err ) {
+ failed( std::string( "exception occurred in inputOuput: " ) + err.what() );
+ } catch ( ... ) {
+ failed( std::string( "unknown exception occurred in inputOuput" ) );
+ }
+#endif
+ #endif
+
+ return worked;
+}
+
+
+void BasicTCPSession::serializeMessage() {
+ if ( !messagesToSend_.empty() ) {
+ MessagePointer::Locked mp = messagesToSend_.front().lock();
+ if ( !mp )
+ err() << "could not lock message";
+ else {
+
+#ifndef DISABLETRYCATCH
+ try {
+#endif
+ sendingMessage_ = messagesToSend_.front();
+ if ( !tcp() )
+ throw StreamError( "tcp-stream missing" );
+ std::vector<char> buffer;
+ serializeMessageToBuffer( buffer, *mp );
+#ifdef MESSAGEDEBUG
+
+ MessagePointer clone;
+ try {
+ clone = buildMessageFromBuffer( buffer, messages_, 0 );
+ } catch ( const CannotReserialize& ) {
+ clone = 0;
+ }
+ catch( const boost::archive::archive_exception& e ) {
+ err() << "archive-exception while reconstructing message: " << e.what();
+ }
+ catch ( ... ) {
+ err() << "exception while reconstructing the message";
+ throw;
+ }
+ try {
+ if ( clone ) {
+ std::vector<char> buffer2;
+ serializeMessageToBuffer( buffer2, *clone.unsafe() );
+ if ( buffer2.size() == buffer.size() ) {
+ if ( memcmp( &buffer[ 0 ], &buffer2[ 0 ], buffer.size() ) != 0 )
+ err() << "the reconstruction of a message of type \"" << mp->name() << "\" is wrong, the serialized content does not match!" ;
+ compare( buffer, buffer2 );
+ } else {
+ err() << "the reconstruction of a message of type \"" << mp->name() << "\" is wrong!(mismatch in size: " << buffer.size() << " -> " << buffer2.size() << ")" ;
+ compare( buffer, buffer2 );
+ }
+ } else {
+ err() << "a message that is being sent could not be reconstructed for debugging: \"" << mp->name() << "\"";
+ }
+ } catch ( const CannotReserialize& )
+ {}
+ catch( const boost::archive::archive_exception& e ) {
+ err() << "archive-exception while reconstructing message: " << e.what();
+ }
+#ifndef DISABLEUNIVERSALCATCH
+
+ catch ( ... ) {
+ err() << "exception while serializing the reconstructed message";
+ throw;
+ }
+#endif
+#endif
+ processOutgoingMessage( buffer );
+ sendData_ = binaryInt( buffer.size() );
+ sendData_ += buffer;
+ //out() << "sending: " << toString( buffer );
+
+ DEBUGLOG( "serialized outgoing message of size " << sendData_.size() << " and type " << messages_.identify( mp ) );
+
+#ifndef DISABLETRYCATCH
+
+ } catch ( const NonFatalSerializationError & error ) {
+ err() << std::string( "could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( error.what() );
+ mp->result( false );
+ if ( mp->info().isReplyTo() ) {
+ MessageInterface * msg = new SystemMessage( messages_, SystemMessage::SerializationFailed, error.what() );
+ msg->info().setReply( mp->info().isReplyTo() );
+ messagesToSend_.pop_front();
+ messagesToSend_.push_front( msg );
+ return ;
+ }
+ }
+ catch( const boost::archive::archive_exception& exc ) {
+ err() << "archive-exception while reconstructing message: " << exc.what();
+ failed( std::string( "could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( exc.what() ) );
+ }
+#ifndef DISABLEUNIVERSALCATCH
+ catch ( const std::exception & exc ) {
+ failed( std::string( "error: could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( exc.what() ) );
+ } catch ( ... ) {
+ failed( "error: could not serialize message " + mp->name() );
+ }
+#endif
+#endif
+
+ }
+ messagesToSend_.pop_front();
+ }
+}
+
+template <class DataType>
+u32 BasicTCPSession::writeData( std::vector<DataType>& from, u32 max ) {
+ u32 count = 0;
+ if ( isPending( pendingOutput, 0 ) ) {
+ while ( isPending( pendingOutput, 0 ) && isOk() && count != max ) {
+ int Portion = 1000;
+ if ( max ) {
+ if ( count + Portion > max ) {
+ Portion = max - count;
+ }
+ }
+ u32 write = Socket::writeData( &from[ count ], Portion * sizeof( DataType ) );
+ //DEBUGLOG( "wrote portion of size " << write );
+ if ( write == 0 || write == 0xffffffff ) {
+ if ( isPending( pendingOutput, 0 ) ) {
+ throw StreamError( "writeData could not send" );
+ }
+
+ return count;
+ } else {
+ u32 units = write / sizeof( DataType );
+ if ( write % sizeof( DataType ) != 0 ) {
+ throw StreamError( "writeData wrote a wrong unit" );
+ }
+ count += units;
+ }
+ }
+ }
+ if ( count == from.size() ) {
+ from.clear();
+ } else {
+ std::vector<DataType> newVec;
+ newVec.resize( from.size() - count );
+ memcpy( &newVec[ 0 ], &from[ count ], ( from.size() - count ) * sizeof( DataType ) );
+ from = newVec;
+ }
+
+ return count;
+}
+
+template <class DataType>
+u32 BasicTCPSession::getData( std::vector<DataType>& to, u32 max ) {
+ u32 count = 0;
+ if ( isPending( pendingInput, 0 ) ) {
+ while ( isPending( pendingInput, 0 ) && isOk() && count != max ) {
+ u32 osize = to.size();
+ int Portion = 1000;
+ if ( max ) {
+ if ( count + Portion > max ) {
+ Portion = max - count;
+ }
+ }
+ to.resize( osize + Portion );
+ u32 read = Socket::readData( ( char* ) & to[ osize ], Portion * sizeof( DataType ) );
+ if ( read == 0 || read == 0xffffffff ) {
+ to.resize( osize );
+ if ( isPending( pendingInput, 0 ) ) {
+ throw StreamError( "could not get data" );
+ }
+
+ //DEBUGLOG( "got " << count );
+ return count;
+ } else {
+ u32 units = read / sizeof( DataType );
+ count += units;
+ to.resize( osize + units );
+ if ( read % sizeof( DataType ) != 0 ) {
+ throw StreamError( "getData got a wrong unit" );
+ }
+ }
+ }
+ }
+ //DEBUGLOG( "got " << count );
+ return count;
+}
+
+const int BasicTCPSession::ConnectionTimeout = 10000;
+
+
+BasicTCPSession::BasicTCPSession( const ost::InetHostAddress &host, ost::tpport_t port, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : ost::TCPSession( host, port ), SessionReplyManager( this ), myDirection( Outgoing ), exit_( false ), failed_( false ), running_( true ), hadFinal_(false), receivingSize_( 0 ), handler_( handler ), logger_( logger ), messages_( messages ), selfPointer_( this ) {
+ initName( namePrefix );
+}
+
+
+BasicTCPSession::BasicTCPSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : ost::TCPSession( server ), SessionReplyManager( this ), myDirection( Incoming ), exit_( false ), failed_( false ), running_( true ), hadFinal_(false), receivingSize_( 0 ), handler_( handler ), logger_( logger ), messages_( messages ), selfPointer_( this ) {
+ initName( namePrefix );
+}
+
+void BasicTCPSession::failed( std::string reason ) {
+ err() << "failed: " << reason.c_str();
+ sendingResult( false );
+ failed_ = true;
+ exit_ = true;
+}
+
+void BasicTCPSession::sendingResult( bool result ) {
+ if ( sendingMessage_ ) {
+ MessagePointer::Locked l = sendingMessage_;
+ if ( l ) {
+ lockCountDown();
+ l->result( result );
+ lockCountUp();
+ if ( result && l->needReply( ) ) {
+ addWaitingMessage( l );
+ }
+ } else {
+ err() << "could not lock message for sendingResult!";
+ }
+ sendingMessage_ = 0;
+ }
+}
+
+LoggerPrinter BasicTCPSession::err( int prio ) {
+ LoggerPrinter p ( logger_, Logger::Error );
+ if ( prio )
+ p << prio << ":";
+ p << "error in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+LoggerPrinter BasicTCPSession::out( Logger::Level lv ) {
+ LoggerPrinter p ( logger_, lv );
+ p << "in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+void BasicTCPSession::clearSelfPointer() {
+ SafeSharedPtr<BasicTCPSession> s = selfPointer_;
+ selfPointer_ = 0;
+}
+
+void BasicTCPSession::initName( const string& namePrefix ) {
+ static int currentNum = 1;
+ currentNum++;
+ ostringstream o;
+ o << currentNum;
+ setSessionName( namePrefix + o.str() );
+}
+
+bool BasicTCPSession::dataToSend() {
+ return !sendData_.empty();
+}
+
+void BasicTCPSession::run() {
+ lockCountUp();
+ while ( !exit_ ) {
+ think();
+ if ( !inputOutput() ) {
+ lockCountDown();
+ if ( !isPending( dataToSend() ? ( ost::Socket::Pending ) ( pendingInput | pendingOutput ) : pendingInput, 20 ) )
+ sleep( 10 );
+ lockCountUp();
+ } else {
+ lockCountDown();
+ ///window for external mutex-requests
+ lockCountUp();
+ }
+ if ( !isConnected() || !isActive() ) {
+ out() << "session is closing because the connection is lost";
+ exit_ = true;
+ }
+
+ if ( _Shared_count() == 1 && selfPointer_ ) { ///The session is only referenced by itself, so it may be deleted
+ out() << "session is closing because the external reference-count reached zero";
+ exit_ = true;
+ }
+ }
+
+ out() << "session exiting";
+ exit();
+}
+
+BasicTCPSession::~BasicTCPSession() {
+ stopRunningNow();
+ terminate();
+ removeAllMessages();
+}
+
+bool BasicTCPSession::isOk() {
+ return !exit_ && !failed_;
+}
+
+void BasicTCPSession::startSession() {
+ start();
+}
+
+void BasicTCPSession::final( void ) {
+ if( hadFinal_ ) return;
+ SessionInterface::final();
+ hadFinal_ = true;
+ DEBUGLOG( "final" );
+ removeAllMessages();
+ exit_ = true;
+ lockCountDown();
+ running_ = false;
+ endSocket(); /// think about how safe it is to call this
+ clearSelfPointer();
+}
+
+bool BasicTCPSession::handleMessage( MessagePointer msg ) throw() {
+ if ( handler_ ) {
+ lockCountDown();
+ bool ret = false;
+ {
+ HandlerPointer::Locked l = handler_;
+ if ( l ) {
+ DEBUGLOG( "giving message to handler" );
+ l->handleMessage( msg );
+ } else {
+ out() << "could not lock handler";
+ }
+ }
+ lockCountUp();
+ return ret;
+ } else {
+ out() << "no handler";
+ }
+ return false;
+}
+
+void BasicTCPSession::removeAllMessages() {
+ if ( sendingMessage_ ) {
+ MessagePointer::Locked l = sendingMessage_;
+ if ( l ) {
+ lockCountDown();
+ l->result( false );
+ lockCountUp();
+ }
+ sendingMessage_ = 0;
+ }
+
+ SessionReplyManager::removeAllMessages();
+
+ while ( messagesToSend_ ) {
+ MessagePointer::Locked l = messagesToSend_.front();
+ if ( l ) {
+ l->result( false );
+ } else {
+ err() << "could not lock messages while removing it from send-list";
+ }
+ messagesToSend_.pop_front();
+ }
+}
+
+bool BasicTCPSession::send( MessageInterface* msg ) {
+ msg->info().setSession( this );
+
+ //The following message indicates that the message's constructor does not correctly fill it's message-info. When this error happens, probably MessageConstructionInfo is not used correctly.
+ if( !(msg->info().type() == messages_.idFromName( msg->name() )) )
+ err() << "sending message that is flagged with an incorrect type, real type: " << msg->name() << " " << messages_.idFromName( msg->name() ).desc() << " flagged type: " << msg->info().type().desc();
+
+ if ( !exit_ && !failed_ ) {
+ messagesToSend_ << msg;
+ } else {
+ msg->result( false );
+ return false;
+ }
+ return true;
+}
+
+void BasicTCPSession::stopRunning() {
+ if ( !exit_ )
+ out( Logger::Debug ) << "stop running";
+ exit_ = true;
+}
+
+///This should get some tolerance in future
+void BasicTCPSession::stopRunningNow() {
+ stopRunning();
+ if ( !Thread::isThread() && Thread::isRunning() )
+ Thread::join();
+}
+
+///Returns whether the thread is running
+bool BasicTCPSession::isRunning() {
+ return running_ && Thread::isRunning();
+}
+
+string BasicTCPSession::peerDesc() {
+ ostringstream str;
+ ost::tpport_t port;
+
+ str << getPeer( &port ) << ":" << port;
+
+ return str.str();
+}
+
+string BasicTCPSession::localDesc() {
+ ostringstream str;
+ ost::tpport_t port;
+
+ str << getLocal( &port ) << ":" << port;
+
+ return str.str();
+}
+
+SessionInterface::SessionDirection BasicTCPSession::sessionDirection() {
+ return myDirection;
+}
+
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp (revision 1522570)
@@ -0,0 +1,300 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "teamworkclient.h"
+#include "forwardsession.h"
+#include "user.h"
+#include "teamworkmessages.h"
+#include "teamworkservermessages.h"
+#include "messagesendhelper.h"
+#include "multisession.h"
+
+
+namespace Teamwork {
+
+BIND_LIST_2( TeamworkClientDispatchMessages , ForwardMessage, UserListMessage )
+
+///Takes a list of SafeSharedPtr's, and returns a list of the same LockedSharedPtr's
+template <class Type, class Serialization>
+list< typename SafeSharedPtr<Type, Serialization>::Locked > lockList( const list< SafeSharedPtr<Type, Serialization> >& lst ) {
+ list< typename SafeSharedPtr<Type, Serialization>::Locked > ret;
+ for ( typename list< SafeSharedPtr<Type, Serialization> >::const_iterator it = lst.begin(); it != lst.end(); ++it ) {
+ ret.push_back( *it );
+ }
+
+ return ret;
+}
+
+void Client::userDisconnected( const Teamwork::UserPointer& /*user*/ ) {
+ needUserUpdate_ = true; ///The connected client may have been a client that created a direct connection to us, and which may still be reachable through an indirect connection, so an update is needed
+}
+
+
+///this is called whenever a connection is successfully established to a server
+void Client::connectedToServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ ) {}
+
+///this is called whenever the client disconnects from a connected server in any way
+void Client::disconnectedFromServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ ) {
+ needUserUpdate_ = true; ///The connected server may have been a client we created a direct connection to, and which is still reachable through an indirect connection, so an update is needed
+}
+
+
+bool Client::think() {
+ for ( ClientSessionMap::iterator it = clientSessions_.begin(); it != clientSessions_.end(); ) {
+ if ( !( *it ).second.session.unsafe() ->isRunning() ) {
+ out() << "closing outgoing session because it stopped running";
+ disconnectedFromServer( ( *it ).second, ( *it ).first );
+ ClientSessionMap::iterator itb = it;
+ ++it;
+ clientSessions_.erase( itb );
+ } else {
+ if ( needUserUpdate_ ) {
+ send<SystemMessage>( ( *it ).second.session.unsafe(), SystemMessage::GetUserList );
+ }
+ ++it;
+ }
+ }
+
+ needUserUpdate_ = false;
+
+ return Server::think();
+}
+
+void Client::connectToServer( const ServerInformation& server, const UserPointer& asUser ) {
+ if ( isConnectedToServer( server ) )
+ disconnectFromServer( server );
+
+ UserPointer p = asUser;
+ if ( !p )
+ p = identity();
+ if ( !p ) {
+ err() << "tried to connect to a server without having an identity";
+ return ;
+ }
+
+ SessionInterface* session = new MultiSession( server, new HandlerProxy<BasicServer>( this ), messageTypes(), logger() , server.desc() + "_outgoing_" );
+ clientSessions_[ server ] = ClientSessionDesc( p, session );
+ session->startSession();
+
+ UserPointer::Locked l = p;
+ if ( l )
+ send<IdentificationMessage>( clientSessions_[ server ].session.unsafe(), *l );
+ else
+ err() << "could not lock user";
+
+ connectedToServer( clientSessions_[ server ], server );
+}
+
+bool Client::isConnectedToServer( const ServerInformation& server ) {
+ return clientSessions_.find( server ) != clientSessions_.end();
+}
+
+MultiSessionPointer Client::sessionToServer( const ServerInformation& server ) {
+ ClientSessionMap::iterator it = clientSessions_.find( server );
+ if ( it == clientSessions_.end() )
+ return 0;
+ else
+ return ( *it ).second.session.cast<MultiSession>();
+}
+
+void Client::disconnectFromServer( const ServerInformation& server ) {
+ ClientSessionMap::iterator it = clientSessions_.find( server );
+ if ( it != clientSessions_.end() ) {
+ disconnectedFromServer( ( *it ).second, ( *it ).first );
+ ( *it ).second.session.unsafe() ->stopRunning();
+ clientSessions_.erase( it );
+ }
+}
+
+void Client::disconnectAllServers () {
+ int c = 0;
+ while ( !clientSessions_.empty() && ++c < 50000 ) {
+ disconnectFromServer( ( *clientSessions_.begin() ).first );
+ }
+}
+
+int Client::receiveMessage( UserListMessage* msg ) {
+ out( Logger::Debug ) << "handling user-list of size " << msg->users.size();
+ std::list<UserPointer> users;
+ {
+ std::set
+ <UserPointer::Locked, UserPointer::Locked::ValueSmallerCompare> allReceivedUsers;
+
+ MultiSessionPointer session = msg->info().session().cast<MultiSession>();
+
+ if ( !session ) {
+ out() << "got a user-list message on an indirect session, ignoring";
+ return 0;
+ }
+
+ MultiSessionPointer::Locked lsession = session;
+ if ( !lsession ) {
+ err() << "could not lock session while receiving user-list";
+ return 0;
+ }
+
+ UserPointer::Locked sUser = lsession->safeUser();
+
+ if ( !sUser )
+ out( Logger::Debug ) << "sender of the user-list has no user-identity";
+
+ ///compare the user-list received from the server and the slave-sessions registered to the session.
+ list<UserPointer::Locked> sessionUsers = lockList( lsession->getUserList() );
+
+ for ( list<User>::iterator it = msg->users.begin(); it != msg->users.end(); ++it ) {
+ UserPointer::Locked l = getUser( createUser( &( *it ) ) );
+ if ( !l ) {
+ err() << "could not get/create indirect user " << ( *it ).name();
+ continue;
+ }
+ if ( l->online() )
+ continue; ///The user is already online, maybe through a direct connection
+
+ ForwardSessionPointer s = lsession->getForwardSession( l );
+
+ allReceivedUsers.insert( l );
+
+ if ( s ) {
+ ///There already is an open session to the user
+ } else {
+ ///Create a new session to the user
+ users.push_back( l );
+
+ l->setSession( new ForwardSession( identity(), l, msg->info().session().cast<MultiSession>(), logger(), messageTypes(), new HandlerProxy<BasicServer>( this ) ) );
+ registerSessionUser( l ); ///Register the user together with its session, so it's noticed once the session is down.
+ }
+ }
+
+ ///now invalidate all users that the session has a forward-session to but that were not listed by the server, because those probably are offline.
+
+ for ( list<UserPointer::Locked>::iterator it = sessionUsers.begin(); it != sessionUsers.end(); ++it ) {
+ std::set
+ <UserPointer::Locked, UserPointer::Locked::ValueSmallerCompare>::iterator fnd = allReceivedUsers.find( *it );
+ if ( fnd == allReceivedUsers.end() ) {
+ ForwardSessionPointer p = lsession->getForwardSession( ( *it ).data() );
+ if ( p ) {
+ p.unsafe() ->stopRunning();
+ out( Logger::Debug ) << "closing secondary session because the user went offline";
+ }
+ }
+ }
+
+ }
+
+ //if( !users.empty() )
+ gotUserList( users );
+
+ return 1;
+}
+
+int Client::receiveMessage( MessageInterface* /*msg*/ ) {
+ return 0;
+}
+
+int Client::receiveMessage( ForwardMessage * msg ) {
+ out( Logger::Debug ) << "Client dispatching ForwardMessage";
+ if ( !identity() )
+ return 0;
+ UserPointer::Locked l = identity();
+ if ( !l ) {
+ err() << "could not identity while processing a forwarded message";
+ return 0;
+ }
+
+ if ( !l->matchIdentity( msg->target() ) )
+ return 0; ///the server should forward the message to the correct target
+
+ out() << "an indirect message from a not yet known client arrived";
+
+ if ( !msg->info().session().cast<MultiSession>() ) {
+ out() << "got a forward-message on an indirect session, ignoring";
+ return 0;
+ }
+
+ MessagePointer::Locked cl = msg->deserializeContained( messageTypes() );
+ if ( cl ) {
+ UserPointer::Locked user = getUser( createUser( &msg->source() ) );
+ if ( !user ) {
+ err() << "could not get/lock the user for a forward-message";
+ return 1;
+ }
+
+ ForwardSession* f = new ForwardSession( identity(), user, msg->info().session().cast<MultiSession>(), logger(), messageTypes(), new HandlerProxy<BasicServer>( this ) );
+ f->setUser( f->target() );
+ cl->info().setSession( f );
+
+ if ( user->online() ) {
+ out( Logger::Warning ) << "got indirect message from directly connected user " << user->name() << ", keeping communication indirect";
+ } else {
+ user->setSession( f );
+ }
+
+ processMessage( cl.data() );
+ } else {
+ out() << "could not handle a forwarded message";
+ }
+ return 1;
+}
+
+void Client::processMessage( MessageInterface* msg ) {
+ MessageDispatcher< Client, TeamworkClientDispatchMessages > dispatcher(*this);
+ if ( dispatcher( msg ) ) {
+ out( Logger::Debug ) << "handled message in the client-class";
+ } else {
+ out( Logger::Debug ) << "handing message from client-class to the server-class";
+ Server::processMessage( msg );
+ }
+}
+
+///Is called whenever a connected server sends its list of connected users
+void Client::gotUserList( const std::list<UserPointer>& /*users*/ ) {
+}
+
+///this could be used to create a custom session deriven from MultiSession
+SessionPointer Client::createSession( BasicTCPSocket* sock ) {
+ return Server::createSession( sock );
+}
+
+bool Client::registerSession( SessionPointer session ) {
+ if ( ! Server::registerSession( session ) )
+ return false;
+
+ if ( session.unsafe() ->sessionDirection() != SessionInterface::Incoming )
+ return true; ///Only send an identification-message to incoming connections, outgoing ones are sent directly while connecting
+
+ if ( identity() ) {
+ UserPointer::Locked l = identity();
+ if ( l )
+ send<IdentificationMessage>( session.unsafe(), *l );
+ else
+ err() << "could not lock user to send identifaction to a new client";
+ } else {
+ out() << "this server has no identity";
+ }
+
+ return true;
+}
+
+Client::Client( ServerInformation serverInfo, LoggerPointer logger ) : Server( serverInfo, logger ), needUserUpdate_( false ) {
+ // messageTypes().registerMessageTypes<AllTeamworkClientMessages> ();
+ //dispatcher_.print( cout );
+ allowIncoming( false );
+}
+
+Client::~Client() {
+ disconnectAllServers();
+}
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp (revision 1522570)
@@ -0,0 +1,272 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "forwardsession.h"
+#include "multisession.h"
+#include "helpers.h"
+
+namespace Teamwork {
+
+LoggerPrinter ForwardSession::err( int prio ) {
+ LoggerPrinter p ( logger_, Logger::Error );
+ if ( prio )
+ p << prio << ":";
+ p << "error in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+LoggerPrinter ForwardSession::out( Logger::Level lv ) {
+ LoggerPrinter p ( logger_, lv );
+ p << "in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+ForwardSession::ForwardSession( const UserPointer& sourceUser, const UserPointer& targetUser, const MultiSessionPointer& session, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler ) : SessionReplyManager( session.unsafe() ), session_( session ), targetUser_( targetUser ), sourceUser_( sourceUser ), logger_( logger ), notRunning_( false ), messageTypes_( messageTypes ), handler_( handler ) {
+ MultiSessionPointer::Locked l = session_;
+ if ( l ) {
+ l->registerForwardSession( targetUser_, this );
+ } else {
+ ///error
+ }
+ setUser( targetUser );
+ UserPointer::Locked lu = targetUser;
+ if ( lu ) {
+ setSessionName( "forward_" + lu->name() );
+ SessionPointer::Locked ls = lu->online().session();
+ if ( ls && ls->isRunning() ) {
+ out( Logger::Warning ) << "creating an indirect session to " << lu->name() << ", but there already is a direct session";
+ } else {
+ lu->setSession( this );
+ }
+
+ } else {
+ err() << "could not lock target-user of a forward-session";
+ }
+}
+
+ForwardSession::~ForwardSession() {
+}
+
+bool ForwardSession::isOk() {
+ MultiSessionPointer p = session_/*.get()*/;
+ if ( !notRunning_ && p )
+ return p.unsafe() ->isOk();
+ return false;
+}
+bool ForwardSession::isRunning() {
+ MultiSessionPointer p = session_/*.get()*/;
+ if ( !notRunning_ && p )
+ return p.unsafe() ->isRunning();
+ return false;
+}
+
+
+bool ForwardSession::send( MessageInterface* msg ) {
+ if ( !isRunning() )
+ return false;
+ MultiSessionPointer p = session_/*.get()*/;
+ if( !p ) return false;
+
+ msg->info().setSession( this );
+
+ UserPointer::Locked source = sourceUser_;
+ UserPointer::Locked target = targetUser_;
+
+ if ( msg && source && target ) {
+ if ( msg->needReply() )
+ addWaitingMessage( msg );
+ return p.unsafe() ->send( new ForwardMessage( messageTypes_, msg, *source, *target ) );
+ } else {
+ err() << "failed to do the necessary locks for sending a message(message and users)";
+ return false;
+ }
+}
+
+void ForwardSession::stopRunning() {
+ out( Logger::Debug ) << "forwardsession: stopRunning";
+ notRunning_ = true;
+ session_ = 0;
+}
+
+void ForwardSession::stopRunningNow() {
+ out( Logger::Debug ) << "forwardsession: stopRunningNow";
+ notRunning_ = true;
+ session_ = 0;
+}
+
+bool ForwardSession::think() {
+ return false;
+}
+
+void ForwardSession::startSession() {}
+
+UserPointer ForwardSession::target() {
+ return targetUser_;
+}
+
+SessionInterface::SessionDirection ForwardSession::sessionDirection() {
+ MultiSessionPointer::Locked l = session_;
+ if ( !l )
+ return Incoming;
+ return l->sessionDirection();
+}
+
+///Must only be called from within session_!
+bool ForwardSession::handleForwardMessage( const SafeSharedPtr<ForwardMessage>& msg ) {
+ out( Logger::Debug ) << "handling forward-message";
+ SafeSharedPtr<ForwardMessage>::Locked l = msg;
+ UserPointer::Locked lu = sourceUser_;
+
+ if ( l && lu ) {
+ if ( lu->match( l->target() ) ) {
+ MessagePointer message = l->deserializeContained( messageTypes_ );
+ MessagePointer::Locked lmessage = message;
+ if ( lmessage ) {
+ lmessage->info().setSession( this );
+ } else
+ err() << "ForwardSession: could not lock a deserialized message";
+
+ handleMessage( message );
+ return true;
+ }
+ } else {
+ out() << "could not lock forward-message or local user";
+ }
+
+ return false;
+}
+
+///Must only be called from within session_!
+bool ForwardSession::handleMessage( MessagePointer msg ) throw() {
+ if ( handleMessageWaiting( msg ) )
+ return true;
+ if ( handler_ )
+ return handler_.unsafe() ->handleMessage( msg );
+ return false;
+}
+
+SessionInterface::SessionType ForwardSession::sessionType() {
+ return Forwarded;
+}
+
+void ForwardSession::final() {
+ SessionInterface::final();
+}
+
+
+LoggerPrinter FakeSession::err( int prio ) {
+ LoggerPrinter p ( logger_, Logger::Error );
+ if ( prio )
+ p << prio << ":";
+ p << "error in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+LoggerPrinter FakeSession::out( Logger::Level lv ) {
+ LoggerPrinter p ( logger_, lv );
+ p << "in session " << "(" << sessionName() << "): ";
+ return p;
+}
+
+FakeSession::FakeSession( const UserPointer& targetUser, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler ) : logger_( logger ), messageTypes_( messageTypes ), handler_( handler ) {
+ setUser( targetUser );
+ UserPointer::Locked lu = targetUser;
+ if ( lu ) {
+ setSessionName( "session_fake_" + lu->name() );
+ } else {
+ setSessionName( "session_fake" );
+ err() << "FakeSession: could not lock target-user of a fake-session";
+ }
+}
+
+bool FakeSession::isOk() {
+ return true;
+}
+
+bool FakeSession::isRunning() {
+ return true;
+}
+
+bool FakeSession::send( MessageInterface* msg ) {
+ SafeSharedPtr<FakeSession>::Locked l( this );
+ if ( l ) {
+ msg->info().setSession( this );
+
+ ///Simulate sending the message by serializing and deserializing it within a local buffer
+ vector<char> vec;
+ serializeMessageToBuffer( vec, *msg );
+ MessagePointer nmsg = buildMessageFromBuffer( vec, globalMessageTypeSet(), 0 );
+ if ( !nmsg ) {
+ err() << "FakeSession: could not build message from buffer";
+ return false;
+ }
+ MessagePointer::Locked l = nmsg;
+ if ( !l ) {
+ err() << "FakeSession: could not lock created message";
+ return false;
+ }
+ l->info().setReplyMessage( msg->info().replyToMessage() );
+
+ receivedMessages_.push_back( nmsg );
+ return true;
+ } else {
+ err() << "FakeSession: lock-error";
+ }
+ return true;
+}
+
+void FakeSession::stopRunning() {
+ out( Logger::Debug ) << "FakeSession: stopRunning";
+}
+
+void FakeSession::stopRunningNow() {
+ out( Logger::Debug ) << "FakeSession: stopRunningNow";
+}
+
+bool FakeSession::think() {
+ return false;
+}
+
+void FakeSession::startSession() {}
+
+SessionInterface::SessionDirection FakeSession::sessionDirection() {
+ return Outgoing;
+}
+
+///Must only be called from within session_!
+bool FakeSession::handleMessage( MessagePointer msg ) throw() {
+ if ( handler_ )
+ return handler_.unsafe() ->handleMessage( msg );
+ return false;
+}
+
+SessionInterface::SessionType FakeSession::sessionType() {
+ return Direct;
+}
+
+std::list<MessagePointer>& FakeSession::sentMessages() {
+ return receivedMessages_;
+}
+
+
+/**This takes the first message off the stack of sent messages, serializes and deserializes it, and then returns the deserialized message.
+ All exceptions from the serialization- and deserialization-process are passed by, additionally errors are indicated by throwing a const char*.
+*/
+MessagePointer::Locked FakeSession::getFirstMessage() throw( const char* ) {
+ if ( receivedMessages_.empty() )
+ throw "FakeSession: no messages available";
+ return receivedMessages_.front();
+}
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp (revision 1522570)
@@ -0,0 +1,78 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "logger.h"
+#include <iostream>
+
+namespace Teamwork {
+
+std::string Logger::levelToString( Level lv ) {
+ switch ( lv ) {
+ case Debug:
+ return "debug";
+ case Info:
+ return "info";
+ case Warning:
+ return "warning";
+ case Error:
+ return "error";
+ }
+ return "unknown level";
+}
+
+///This can be overridden for custom logging
+void Logger::log( const std::string& str , Level lv ) {
+ std::cout << "log-level: \"" << levelToString( lv ) << "\" message: \"" << str << "\"" << endl;
+}
+
+///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
+void Logger::safeErrorLog( const std::string& str, Level lv ) {
+ std::cout << "problem while logging, statically logging: \"" << "log-level: \"" << levelToString( lv ) << "\" message: \"" << str << "\"" << endl;
+}
+
+void LoggerPrinter::invalidate() {
+ out_ = 0;
+ logger_ = 0;
+}
+LoggerPrinter& LoggerPrinter::operator = ( const LoggerPrinter& /*rhs*/ ) {
+ return * this;
+}
+LoggerPrinter::LoggerPrinter( const LoggerPointer& logger, Logger::Level level ) : logger_( logger ), out_( 0 ), level_( level ) {
+ /*if( logger_ )*/ out_ = new std::ostringstream();
+}
+
+LoggerPrinter::LoggerPrinter( const LoggerPrinter& rhs ) : logger_( rhs.logger_ ), out_( rhs.out_ ), level_ ( rhs.level_ ) {
+ ( const_cast<LoggerPrinter&>( rhs ) ).invalidate();
+}
+
+LoggerPrinter::~LoggerPrinter() {
+ if ( !out_ )
+ return ; ///the logger has been copied and thereby invalidated
+ std::string s = out_->str();
+ if ( s.length() ) {
+ if ( LoggerPointer::Locked l = logger_ ) {
+ l->log( s, level_ );
+ } else {
+ if ( logger_ ) {
+ logger_.unsafe() ->safeErrorLog( s, level_ );
+ } else {
+ cerr << "(bad logger): " << s << endl;
+ }
+ }
+ }
+ delete out_;
+}
+
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp (revision 1522570)
@@ -0,0 +1,318 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "serialization.h"
+#include "messagetypeset.h"
+#include "basicsession.h"
+#include "user.h"
+
+namespace Teamwork {
+
+MessageInfo::MessageInfo() : isReplyTo_( 0 ), uniqueId_( 0 ), deserialized_( false ) {
+}
+
+MessageInfo::MessageInfo( const MessageType& id, UniqueMessageId uniqueId ) : isReplyTo_( 0 ), uniqueId_( uniqueId ), deserialized_( false ) {
+ id_ = id;
+ // cout << "creating message-info normally";
+}
+
+MessageInfo::MessageInfo( const MessageType& id, UniqueMessageId uniqueId, const SessionPointer& session, UniqueMessageId isReplyTo ) : isReplyTo_( isReplyTo ), uniqueId_( uniqueId ), deserialized_( false ) {
+ id_ = id;
+ session_ = session;
+ // cout << "creating message-info normally";
+}
+
+MessageInfo::~MessageInfo() {
+}
+
+void MessageInfo::setReplyMessage( const MessagePointer& msg ) {
+ replyToMessage_ = msg;
+}
+
+const MessagePointer& MessageInfo::replyToMessage() const {
+ return replyToMessage_;
+}
+
+SessionPointer MessageInfo::session() const {
+ if ( !session_ ) {
+ UserPointer::Locked l = user_;
+ if ( l ) {
+ return l->online().session();
+ } else {
+ return 0;
+ }
+ } else {
+ return session_;
+ }
+}
+
+UserPointer MessageInfo::user() const {
+ if ( session_ ) {
+ return session_.unsafe() ->safeUser();
+ } else {
+ return user_;
+ }
+}
+
+void MessageInfo::setSession( const SessionPointer& sess ) {
+ if ( !sess ) {
+ session_ = 0;
+ user_ = 0;
+ return ;
+ }
+ if ( UserPointer p = sess.unsafe() ->safeUser() ) {
+ setUser( p );
+ } else {
+ session_ = sess;
+ user_ = 0;
+ }
+}
+
+void MessageInfo::setUser( const UserPointer& user ) {
+ user_ = user;
+ session_ = 0;
+}
+
+MessageFactoryInterface* MessageTypeSet::findFactory( MessageType& id ) const {
+ while ( id ) { ///walk up the tree until a matching maybe inherited message-type is found
+ TypeMap::const_iterator it = types_.find( id );
+ if ( it != types_.end() ) {
+ return ( *it ).second;
+ }
+ --id;
+ }
+ return 0;
+}
+
+MessagePointer MessageTypeSet::buildMessage( InArchive& from, const MessageInfo& inf ) const {
+ MessageType id = inf.type();
+
+ MessageFactoryInterface* i = findFactory( id );
+ if ( i ) {
+ MessageInfo info( inf );
+ info.setId( id );
+ return MessagePointer( i->buildMessage( from, info ) );
+ }
+
+ cout << "could not build message with id " << id.desc() << endl;
+ return MessagePointer();
+}
+
+void MessageType::packFastId() {
+ //return;
+ fastId_ = 0;
+ if ( idList_.size() > 4 ) {
+ useFastId = false;
+ } else {
+ useFastId = true;
+ int shift = 24;
+ for ( IdList::iterator it = idList_.begin(); it != idList_.end(); ++it ) {
+ fastId_ += *it << shift;
+ shift -= 8;
+ }
+ }
+}
+
+MessageType::MessageType( IdList IDs ) : idList_( IDs ), useFastId( false ) {
+ packFastId();
+}
+
+MessageType::MessageType( InArchive& from ) : useFastId( false ) {
+ serialize( from );
+}
+
+bool MessageType::operator == ( const MessageType& rhs ) const {
+ if ( useFastId && rhs.useFastId )
+ return fastId_ == rhs.fastId_;
+ int s1 = idList_.size();
+ int s2 = rhs.idList_.size();
+ if ( s1 != s2 )
+ return false;
+ for ( int a = 0; a < s1; a++ ) {
+ if ( idList_[ a ] != rhs.idList_[ a ] )
+ return false;
+ }
+
+ return true;
+}
+
+bool MessageType::operator < ( const MessageType& rhs ) const {
+ if ( useFastId && rhs.useFastId )
+ return fastId_ < rhs.fastId_;
+ int s1 = idList_.size();
+ int s2 = rhs.idList_.size();
+ int ms = s2 > s1 ? s1 : s2;
+ for ( int a = 0; a < ms; a++ ) {
+ if ( idList_[ a ] < rhs.idList_[ a ] ) {
+ return true;
+ }
+ if ( idList_[ a ] > rhs.idList_[ a ] ) {
+ return false;
+ }
+ }
+ if ( s1 < s2 ) {
+ return true;
+ }
+ if ( s1 > s2 ) {
+ return false;
+ }
+
+ return false;
+}
+
+int MessageType::length() const {
+ return idList_.size();
+}
+
+
+bool MessageType::startsWith( const MessageType& rhs ) const {
+ int s1 = idList_.size();
+ int s2 = rhs.idList_.size();
+ if ( s1 < s2 )
+ return false;
+
+ for ( int a = 0; a < s1; a++ ) {
+ if ( idList_[ a ] != rhs.idList_[ a ] )
+ return false;
+ }
+
+ return true;
+}
+
+MessageType& MessageType::operator += ( unsigned char append ) {
+ if ( !idList_.empty() )
+ idList_.pop_back();
+ idList_.push_back( append );
+ idList_.push_back( 0 );
+ packFastId();
+ return *this;
+}
+
+MessageType& MessageType::operator -- () {
+ if ( !idList_.empty() ) {
+ idList_.pop_back();
+ idList_.pop_back();
+ idList_.push_back( 0 );
+ }
+ packFastId();
+ return *this;
+}
+
+MessageType::operator bool() const {
+ return !idList_.empty();
+}
+
+std::string MessageType::desc() const {
+ if ( idList_.empty() )
+ return "'invalid id'";
+ std::ostringstream ret;
+ IdList::const_iterator end = idList_.end();
+ if ( end != idList_.begin() )
+ --end;
+ for ( IdList::const_iterator it = idList_.begin(); it != end; ++it )
+ ret << ( int ) * it << "-";
+ return ret.str();
+}
+
+MessageType::operator const unsigned char*() const {
+ if ( idList_.empty() ) {
+ return ( const uchar* ) "";
+ } else {
+ return ( const uchar* ) & ( idList_[ 0 ] );
+ }
+}
+
+UniqueMessageId MessageInfo::uniqueId() const {
+ return uniqueId_;
+}
+
+/**Since the uniqueId is not used for sorting this casts away constness so the id of a MessageType that is used as Key in a Map can be changed */
+void MessageInfo::setUniqueId( UniqueMessageId newId ) const {
+ const_cast<MessageInfo*>( this ) ->uniqueId_ = newId;
+}
+
+MessageTypeSet::TypeMap::iterator MessageTypeSet::search( const MessageType& id ) {
+ return types_.find( id );
+}
+
+MessageType MessageTypeSet::allocateSubId( const MessageType& id, int preferredSubId ) {
+ MessageType tempId = id;
+ if ( preferredSubId == 0 )
+ preferredSubId = 1;
+ for ( int a = preferredSubId; a < 255; a++ ) {
+ tempId += a;
+ if ( types_.find( tempId ) == types_.end() ) {
+ return tempId;
+ }
+ --tempId;
+ }
+
+ cout << "problem while allocating sub-id for " << id.desc() << ", all sub-id's seem to be taken" << endl;
+ ///This should not happen, but anyway try to allocate some id
+ if ( tempId ) {
+ return allocateSubId( allocateSubId( --tempId ), preferredSubId );
+ }
+
+ return MessageType();
+}
+MessageTypeSet::MessageTypeSet() {
+ srand( time( NULL ) );
+ currentUniqueMessageId_ = rand();
+ currentUniqueMessageId_ *= rand();
+ currentUniqueMessageId_ *= rand();
+ currentUniqueMessageId_ *= rand();
+}
+
+MessagePointer MessageTypeSet::buildMessage( InArchive& from, const MessageInfo& inf ) const;
+
+MessageTypeSet::~MessageTypeSet() {
+ for ( TypeMap::iterator it = types_.begin(); it != types_.end(); ++it ) {
+ delete ( *it ).second;
+ }
+ types_.clear();
+}
+
+const MessageType& MessageTypeSet::idFromName( const std::string& name ) const {
+ TypeNameMap::const_iterator it = ids_.find( name );
+ if ( it != ids_.end() ) {
+ return ( *it ).second;
+ } else if( name == "MessageInterface" ) {
+ return const_cast<TypeNameMap&>(ids_)[name]; //Automatically register MessageInterface with the zero-id
+ } else {
+ cout << "could not assign an ID to a message called \"" << name << "\", it seems not to be registered in the message-type-set" << endl;
+ return const_cast<TypeNameMap&>(ids_)[ name ];
+ }
+}
+
+std::string MessageTypeSet::stats() const {
+ ostringstream ret;
+ ret << "count of message-types: " << types_.size() << endl;
+ for ( TypeNameMap::const_iterator it = ids_.begin(); it != ids_.end(); ++it ) {
+ ret << "type: " << ( *it ).first << " id: " << ( *it ).second.desc() << endl;
+ }
+ return ret.str();
+}
+
+///returns the class-name of the message(the most specialized one registered in this type-set)
+std::string MessageTypeSet::identify( MessageInterface* msg ) const {
+ MessageType id = msg->info().type();
+ MessageFactoryInterface* i = findFactory( id );
+ if ( i ) {
+ return i->identify();
+ } else {
+ return "could not identify";
+ }
+}
+
+}
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/defines.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/defines.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/defines.h (revision 1522570)
@@ -0,0 +1,21 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef DEFINES_H
+#define DEFINES_H
+
+#define STANDARDPORT 8161
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/defines.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h (revision 1522570)
@@ -0,0 +1,29 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef INTERFACES_H
+#define INTERFACES_H
+//
+// #include "serialization.h"
+// #include "safesharedptr.h"
+//
+// class SafeShared;
+// struct MessageSerialization;
+//
+// namespace Teamwork {
+// typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
+// }
+//
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp (revision 1522570)
@@ -0,0 +1,90 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "serverconfig.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include "serialization.h"
+#include <boost/archive/polymorphic_xml_oarchive.hpp>
+#include <boost/archive/polymorphic_xml_iarchive.hpp>
+#include <boost/serialization/list.hpp>
+#include <boost/serialization/set.hpp>
+#include <fstream>
+#include "defines.h"
+#include <iostream>
+
+#ifdef USE_POLYMORPHIC_ARCHIVE
+// #include <boost/archive/polymorphic_xml_iarchive.hpp>
+// #include <boost/archive/polymorphic_xml_oarchive.hpp>
+// typedef boost::archive::polymorphic_xml_iarchive InternalIArchive;
+// typedef boost::archive::polymorphic_xml_oarchive InternalOArchive;
+
+typedef boost::archive::polymorphic_text_iarchive InternalIArchive;
+typedef boost::archive::polymorphic_text_oarchive InternalOArchive;
+#else
+typedef Teamwork::InArchive InternalIArchive;
+typedef Teamwork::OutArchive InternalOArchive;
+#endif
+
+namespace Teamwork {
+
+ServerConfiguration::ServerConfiguration() : port( STANDARDPORT ), bind( "0.0.0.0" ) {
+}
+
+bool loadServerConfiguration( ServerConfiguration& conf ) {
+ std::ifstream file( "teamwork.config", ios_base::in );
+ if( !file.good() ) {
+ cout << "could not open config-file" << endl;
+ return false;
+ }
+ InternalIArchive arch( file );
+ try {
+ } catch( ... ) {
+ cout << "error while reading the config-file" << endl;
+ return false;
+ }
+ arch & conf;
+ return true;
+}
+
+template<class Archive>
+void ServerConfiguration::serialize( Archive& arch, const unsigned int /*version*/ ) {
+ arch & serverName;
+ arch & serverPassword;
+ arch & port;
+ arch & bind;
+ arch & registeredUsers;
+}
+
+
+bool saveServerConfiguration( ServerConfiguration& conf ) {
+ std::ofstream file( "teamwork.config", ios_base::out );
+ if( !file.good() ) {
+ cout << "could not open config-file" << endl;
+ return false;
+ }
+ /*boost::archive::polymorphic_text_oarchive*/
+ InternalOArchive arch( file );
+ try {
+ } catch( ... ) {
+ cout << "error while loading the config-file" << endl;
+ return false;
+ }
+ arch & conf;
+ return true;
+}
+
+INSTANTIATE_SERIALIZATION_FUNCTIONS( ServerConfiguration )
+
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp (revision 1522570)
@@ -0,0 +1,82 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#include "dynamicmessagedispatcher.h"
+#include <map>
+#include <list>
+
+
+namespace Teamwork {
+
+DynamicMessageDispatcher::DynamicMessageDispatcher( MessageTypeSet& messageTypes ) : m_messageTypes(messageTypes) {
+
+}
+
+DynamicMessageDispatcher::~DynamicMessageDispatcher() {
+ for( DelivererList::iterator it = m_deliverers.begin(); it != m_deliverers.end(); ++it )
+ delete *it;
+}
+
+void DynamicMessageDispatcher::addDeliverer( MessageDelivererBase* d ) {
+ m_deliverers.push_back( d );
+}
+
+int DynamicMessageDispatcher::dispatch( const MessagePointer& msg ) {
+ return operator() ( msg );
+}
+
+
+///@todo optimize this, a search-tree should be used, similar to the static tree.
+int DynamicMessageDispatcher::operator ()( const MessagePointer& msg ) {
+
+ //Find the best matching targets:
+ typedef std::map<int, std::list<MessageDelivererBase*> > TargetMap;
+ TargetMap targets; //sort the targets by the match-depth
+ for( DelivererList::iterator it = m_deliverers.begin(); it != m_deliverers.end(); ++it ) {
+
+ //Find all targets that match
+ //Remove already deleted targets
+ while( it != m_deliverers.end() && !(*it)->isOk() ) {
+ delete *it;
+ it = m_deliverers.erase( it );
+ }
+ if( it == m_deliverers.end() )
+ break;
+
+ //If we have a match, put it into the list
+ if( msg.unsafe()->type().startsWith( (*it)->type() ) ) {
+ int orderPosition = -(*it)->type().length(); //minus so biggest become first
+ TargetMap::iterator targetIt = targets.find( orderPosition );
+ if( targetIt == targets.end() )
+ targetIt = targets.insert( std::make_pair( orderPosition, std::list<MessageDelivererBase*>() ) ).first;
+
+ (*targetIt).second.push_front( *it );
+ }
+ }
+
+
+ for( TargetMap::const_iterator it = targets.begin(); it != targets.end(); ++it ) {
+ for( std::list<MessageDelivererBase*>::const_iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); ++it2 ) {
+ int ret = (*it2)->tryDeliverMessage( msg );
+ if( ret != 0 ) {
+ return ret; //Message successfully delivered
+ }
+ }
+ }
+
+ return 0; //Message could not be delivered, or all fitting targets returned 0
+ }
+
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h (revision 1522570)
@@ -0,0 +1,83 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 file contains the implementation-details of DynamicMessageDeliverer
+ * */
+
+#ifndef DYNAMICMESSAGEDISPATCHER_INTERNAL_H
+#define DYNAMICMESSAGEDISPATCHER_INTERNAL_H
+
+#include "weaksafesharedptr.h"
+#include "networkfwd.h"
+#include "messageinterface.h"
+
+namespace Teamwork {
+
+ ///Some helper-classes for implementing the dispatcher, see below
+class MessageDelivererBase {
+ public:
+ virtual int tryDeliverMessage( const MessagePointer& msg ) = 0;
+ virtual ~MessageDelivererBase() {
+ }
+ virtual bool isOk() const = 0;
+ virtual const MessageType& type() const = 0;
+};
+
+template<class Message, class Target>
+ class MessageDeliverer : public MessageDelivererBase {
+ public:
+ typedef int (Target::*FunctionType)(const SafeSharedPtr<Message>& );
+
+ MessageDeliverer( const WeakSafeSharedPtr<Target>& target, FunctionType function, MessageType type, bool lockBeforeCall = true ) : m_function(function), m_target(target), m_lockBeforeCall( lockBeforeCall ), m_type(type) {
+ }
+
+ virtual bool isOk() const {
+ return m_target.get();
+ }
+
+ virtual const MessageType& type() const {
+ return m_type;
+ }
+
+ virtual int tryDeliverMessage( const MessagePointer& msg ) {
+ SafeSharedPtr<Message> myMsg = msg.cast<Message>();
+ if( myMsg ) {
+ if( m_lockBeforeCall ) {
+ //The message can be casted to the needed type, so it should be delivered.
+ LockedSharedPtr<Target> lockedTarget = m_target;
+ if( lockedTarget ) {
+ //Deliver the message
+ return (lockedTarget->*m_function) ( myMsg );
+ } else {
+ //Problem
+ }
+ } else {
+ //Do not lock the target before calling the callback-function
+ SafeSharedPtr<Target> ref = m_target.get(); //Make a normal safe-shared-pointer out of the weak one, so the target can not be deleted while the call
+ if( ref )
+ return (ref.unsafe()->*m_function) ( myMsg );
+ }
+ }
+ return 0;
+ };
+ virtual ~MessageDeliverer() {
+ }
+ private:
+ FunctionType m_function;
+ WeakSafeSharedPtr<Target> m_target;
+ bool m_lockBeforeCall;
+ MessageType m_type;
+ };
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp (revision 1522570)
@@ -0,0 +1,110 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "helpers.h"
+#include "serialization.h"
+#include "messagetypeset.h"
+#include "basicsession.h"
+#include "vector_stream.h"
+
+///We can choose an archive-type of our own
+#ifdef USE_POLYMORPHIC_ARCHIVE
+// #include <boost/archive/polymorphic_xml_iarchive.hpp>
+// #include <boost/archive/polymorphic_xml_oarchive.hpp>
+// typedef boost::archive::polymorphic_xml_iarchive InternalIArchive;
+// typedef boost::archive::polymorphic_xml_oarchive InternalOArchive;
+
+#include <boost/archive/polymorphic_text_iarchive.hpp>
+#include <boost/archive/polymorphic_text_oarchive.hpp>
+typedef boost::archive::polymorphic_text_iarchive InternalIArchive;
+typedef boost::archive::polymorphic_text_oarchive InternalOArchive;
+#else
+typedef Teamwork::InArchive InternalIArchive;
+typedef Teamwork::OutArchive InternalOArchive;
+#endif
+
+std::string formatInt( int i ) {
+ ostringstream o;
+ o << i;
+ return o.str();
+}
+
+std::vector<char> binaryInt( int num ) {
+ std::vector<char> ret;
+ ret.resize( 4 );
+ ( *( int* ) ( &ret[ 0 ] ) ) = num;
+ return ret;
+}
+
+namespace Teamwork {
+ MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages ) {
+ return buildMessageFromArchive( arch, messages, 0 );
+ }
+ MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages, SessionPointer sess ) {
+ MessageInfo inf( arch );
+ inf.setSession( sess );
+
+ return messages.buildMessage( arch, inf );
+ }
+
+ void serializeMessageToArchive( OutArchive& arch, MessageInterface& message ) {
+ message.info().serialize( arch );
+
+ message.serialize( arch ); ///it must be called like this, because the serialization would add type-information we don't want
+ }
+
+ MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages, SessionPointer sess ) {
+ vector_read_stream str( buf );
+ InternalIArchive arch( str );
+
+ return buildMessageFromArchive( arch, messages, sess );
+ }
+
+ void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message ) {
+ vector_stream str( buf );
+ InternalOArchive arch( str );
+
+ serializeMessageToArchive( arch, message );
+ }
+
+ /*
+ MessagePointer buildMessageFromBuffer( std::vector<char> buf, MessageTypeSet& messages, SessionPointer sess )
+ {
+ buf.push_back( 0 );
+ BinaryStreamBuf b( buf );
+ std::ifstream str;
+
+ str.rdbuf( &b );
+
+ InArchive arch( str );
+
+ MessageInfo inf( arch );
+ inf.setSession( sess );
+
+ return messages.buildMessage( arch, inf );
+ }
+
+ void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message ) {
+ BinaryStreamBuf b (buf );
+ std::ofstream str;
+ str.rdbuf( &b );
+ OutArchive arch( str );
+
+ message.info().serialize( arch );
+
+ message.serialize( arch ); ///it must be called like this, because the serialization would add type-information we don't want
+ }
+ */
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp (revision 1522570)
@@ -0,0 +1,53 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "sessioninterface.h"
+#include "user.h"
+#include "messageinterface.h"
+
+namespace Teamwork {
+ SessionInterface& SessionInterface::operator= ( const SessionInterface& /*rhs*/ ) {
+ return *this;
+ }
+
+ SessionInterface::SessionInterface( const SessionInterface& /*rhs*/ ) : SafeShared() {
+ }
+
+ void SessionInterface::startSession() {}
+
+ std::string SessionInterface::sessionName() {
+ return sessionName_;
+ }
+
+ bool SessionInterface::sendReply( MessageInterface* msg, MessageInterface* replyTo ) {
+ msg->info().setReply( replyTo->info().uniqueId() );
+ msg->info().setReplyMessage( replyTo );
+ return send( msg );
+ }
+
+ void SessionInterface::setSessionName( const std::string& name ) {
+ sessionName_ = name;
+ }
+
+ std::string SessionInterface::peerDesc() {
+ return std::string();
+ }
+
+ std::string SessionInterface::localDesc() {
+ return std::string();
+ }
+
+ SessionInterface::SessionType SessionInterface::sessionType() {
+ return Direct;
+ }
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h (revision 1522570)
@@ -0,0 +1,256 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef CROSSMAPIMPL_H
+#define CROSSMAPIMPL_H
+
+#include "metahelpers.h"
+
+namespace Utils {
+using namespace Meta;
+
+template <class Value, class Key, class KeyExtractor, int num, int relativeNum>
+struct KeyValue {
+ KeyValue( const Value& value ) : val( KeyExtractor::template Extractor<Key, relativeNum, Value>::getKey( value ) ) {}
+ Key val;
+};
+
+struct DummyChainEle {
+ template <class Type>
+ DummyChainEle( const Type& /*t*/ ) {}
+}
+;
+
+///KeyValueChain stores a copy of all key-values in the given list(and can extract them during the constructor from the Value-type)
+template <class Value, class Keys, class KeyExtractor, int num = 0, class AllKeys = Keys>
+struct KeyValueChain : public If < ( Count< Keys >::value > 1 ), KeyValueChain < Value, typename RemoveOneLeft<Keys>::Result, KeyExtractor, num + 1, AllKeys>, DummyChainEle>::Result, public KeyValue< Value, typename GetOneLeft<Keys>::Result, KeyExtractor, num, FindRelativeInList<typename GetOneLeft<Keys>::Result, AllKeys, num>::relativeIndex > {
+ typedef typename If< ( Count< Keys >::value > 1 ), KeyValueChain < Value, typename RemoveOneLeft<Keys>::Result, KeyExtractor, num + 1, AllKeys > , DummyChainEle > ::Result NextChain;
+ typedef KeyValue< Value, typename GetOneLeft<Keys>::Result, KeyExtractor, num, FindRelativeInList<typename GetOneLeft<Keys>::Result, AllKeys, num>::relativeIndex > KeyValueItem;
+
+ KeyValueChain( const Value& value ) : NextChain( value ), KeyValueItem( value ) {}
+ KeyValueChain() {}
+
+ ///Sets the value of the n'th key
+ template<int n>
+ void setValue( typename GetListItem< n, AllKeys >::Result& val ) {
+ typedef typename GetListItem< n, AllKeys >::Result KeyType;
+ static_cast<KeyValue< Value, KeyType, KeyExtractor, n, FindRelativeInList<KeyType, AllKeys, n>::relativeIndex >*>( this )->val = val;
+ }
+
+ ///Returns the value of the num'th key
+ template<int n>
+ typename GetListItem< n, AllKeys >::Result& getValue() {
+ typedef typename GetListItem< n, AllKeys >::Result KeyType;
+ return static_cast<KeyValue< Value, KeyType, KeyExtractor, n, FindRelativeInList<KeyType, AllKeys, n>::relativeIndex >*>( this )->val;
+ }
+};
+
+struct ExtractKeyType {
+ template<class Type>
+ struct Action {
+ typedef Type Result;
+ typedef False isContainer;
+ };
+};
+
+
+template <class Value, class Key, int num>
+struct CrossMapData {
+ enum {
+ number = num
+ };
+
+ typedef typename ExtractKeyType::template Action< Key >::Result RealKey;
+ typedef std::multimap< RealKey, uint > MapType;
+ typedef typename ExtractKeyType::template Action< Key >::isContainer IsContainer;
+
+ MapType map;
+
+ template<class KeyExtractor, int relativeNum>
+ void insert( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, const Value & /*value*/, const uint id ) {
+ insertInternal( keyVal.val, id, IsContainer() );
+ }
+
+ ///Not yet ported to the container-stuff
+ template <class KeyExtractor, int relativeNum, class Validator>
+ uint find( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, const Value & value, const Validator & validator ) {
+ return findInternal( keyVal.val, value, validator, IsContainer() );
+ }
+
+ template <class KeyExtractor, int relativeNum>
+ void remove( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, uint id ) {
+ removeInternal( keyVal.val, id, IsContainer() );
+ }
+
+ void clear() {
+ map.clear();
+ }
+
+ bool hasContent() const {
+ return !map.empty();
+ }
+
+ template <class Archive>
+ void serialize( Archive & arch, uint /*version*/ ) {
+ arch & map;
+ }
+
+ private:
+
+ template<class Validator>
+ uint findInternal( const Key& key, const Value & value, const Validator & validator, const True ) {
+ for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it ) {
+ uint ret = findInternal( *it, value, validator, False() );
+ if( ret ) return ret;
+ }
+ return 0;
+ }
+
+ template<class Validator>
+ uint findInternal( const RealKey& key, const Value & value, const Validator & validator, const False ) {
+ std::pair<typename MapType::iterator, typename MapType::iterator>
+ range = map.equal_range( key );
+
+ while ( range.first != range.second ) {
+ if ( validator.validateId( value, ( *range.first ).second ) )
+ return ( *range.first ).second;
+
+ ++range.first;
+ }
+
+ return 0;
+ }
+
+
+ void insertInternal( const Key& key, const uint id, const True ) {
+ for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it )
+ insertInternal( *it, id, False() );
+ }
+
+ void insertInternal( const RealKey& key, const uint id, const False ) {
+ map.insert( make_pair( key, id ) );
+ }
+
+ void removeInternal( const Key& key, const uint id, const True ) {
+ for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it )
+ removeInternal( *it, id, False() );
+ }
+
+ void removeInternal( const RealKey& key, const uint id, const False ) {
+ std::pair<typename MapType::iterator, typename MapType::iterator>
+ range = map.equal_range( key );
+
+
+ while ( range.first != range.second ) {
+ if ( id == ( *range.first ).second ) {
+ map.erase( range.first );
+ return ;
+ }
+
+ ++range.first;
+ }
+ }
+};
+
+struct CrossMapChainDummy {
+
+ template<class C, class D, class V>
+ uint find( const C&, const D&, const V& ) {
+ return 0;
+ }
+
+ template<class C>
+ void remove( const C&, uint ) {}
+
+ template<class C, class D>
+ void insert( const C&, const D&, uint ) {}
+
+ void clear() {}
+
+ bool hasContent() const {
+ return false;
+ }
+ template<class Archive>
+ void serialize( Archive & /*arch*/, uint /*version*/ ) {}
+};
+
+template<class Value, class Keys, int num>
+struct CrossMapChain : public If<( Count<Keys>::value > 1 ), CrossMapChain< Value, typename RemoveOneLeft<Keys>::Result, num + 1>, CrossMapChainDummy>::Result, public CrossMapData< Value, typename GetOneLeft<Keys>::Result, num >
+{
+ typedef typename If<( Count<Keys>::value > 1 ), CrossMapChain< Value, typename RemoveOneLeft<Keys>::Result, num + 1>, CrossMapChainDummy>::Result Next;
+ typedef CrossMapData< Value, typename GetOneLeft<Keys>::Result, num > Data;
+
+ template<class KeyExtractor, class AllKeys>
+ void insert( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys >& values, const Value & value, uint valueId ) {
+ Next::template insert( values, value, valueId )
+ ;
+ Data::template insert( values, value, valueId )
+ ;
+ }
+ template <class KeyExtractor, class AllKeys>
+ void remove( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys>& values, uint id ) {
+ Next::template remove( values, id )
+ ;
+ Data::template remove( values, id )
+ ;
+ }
+
+ template <class KeyExtractor, class AllKeys, class Validator>
+ uint find( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys>& values, const Value & value, const Validator & validator ) {
+ uint ret = Data::template find( values, value, validator )
+ ;
+ if ( ret )
+ return ret;
+
+ return Next::template find( values, value, validator )
+ ;
+ }
+
+ int hasContent() const {
+ bool a = Next::hasContent()
+ ;
+ bool b = Data::hasContent()
+ ;
+ if ( a != b && Count<Keys>::value >
+ 1 )
+ return 2;
+ else if ( a && b )
+ return 1;
+ else
+ return 0;
+ }
+
+ void clear() {
+ Next::clear();
+ Data::clear();
+ }
+
+ template <class Archive>
+ void serialize( Archive & arch, uint /*version*/ ) {
+ Data::serialize( arch, 0 );
+ Next::serialize( arch, 0 );
+ }
+};
+
+template <class Type>
+class CrossMapHashTraits {
+ enum {
+ hashable = 0
+ };
+};
+
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h (revision 1522570)
@@ -0,0 +1,91 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef METAHELPERS_H
+#define METAHELPERS_H
+
+#include "statictree.h"
+
+namespace Meta {
+using namespace Tree;
+
+///If the same type is in the list multiple times, wantOccurrences can be the index within the list of those types
+template <class Type, class List, int wantOccurrences = 0, int previousCount = 0, int hadOccurrences = 0>
+struct FindInList {
+ enum {
+ value = -1,
+ occurrences = hadOccurrences
+ };
+};
+
+template <class Type, int wantOccurrences, int previousCount, int hadOccurrences>
+struct FindInList< Type, Type, wantOccurrences, previousCount, hadOccurrences> {
+ enum {
+ value = previousCount,
+ occurrences = hadOccurrences + 1
+ };
+};
+
+template <class Type, class Side1, class Side2, int wantOccurrences, int previousCount, int hadOccurrences>
+struct FindInList< Type, Binder<Side1, Side2>, wantOccurrences, previousCount, hadOccurrences> {
+ typedef FindInList<Type, Side1, wantOccurrences, previousCount, hadOccurrences> Side1Find;
+ typedef typename If < Side1Find::value != -1 && Side1Find::occurrences - 1 == wantOccurrences, Side1Find, FindInList < Type, Side2, wantOccurrences, Count<Side1>::value + previousCount, hadOccurrences + Side1Find::occurrences > > ::Result EndFind;
+ enum {
+ value = EndFind::value,
+ occurrences = EndFind::occurrences
+ };
+};
+
+
+///Takes the absolute index of a type in the list, and converts it to an occurrence-index(only counting the same types)
+template <class Type, class List, int wantNumber = 0, int previousCount = 0, int hadOccurrences = 0>
+struct FindRelativeInList {
+ enum {
+ value = -1,
+ occurrences = hadOccurrences,
+ relativeIndex = occurrences - 1
+ };
+};
+
+template <class Type, int wantNumber, int previousCount, int hadOccurrences>
+struct FindRelativeInList< Type, Type, wantNumber, previousCount, hadOccurrences> {
+ enum {
+ value = previousCount,
+ occurrences = hadOccurrences + 1,
+ relativeIndex = occurrences - 1
+ };
+};
+
+template <class Type, class Side1, class Side2, int wantNumber, int previousCount, int hadOccurrences>
+struct FindRelativeInList< Type, Binder<Side1, Side2>, wantNumber, previousCount, hadOccurrences> {
+ typedef FindRelativeInList<Type, Side1, wantNumber, previousCount, hadOccurrences> Side1Find;
+ typedef typename If < Side1Find::value == wantNumber, Side1Find, FindRelativeInList < Type, Side2, wantNumber, Count<Side1>::value + previousCount, hadOccurrences + Side1Find::occurrences > > ::Result EndFind;
+ enum {
+ value = EndFind::value,
+ occurrences = EndFind::occurrences,
+ relativeIndex = occurrences - 1
+ };
+};
+
+template <int a, int b>
+struct AssertSame {
+ typedef typename Assert < a == b > ::OK OK;
+};
+
+struct True {};
+struct False{};
+
+}
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/binder.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/binder.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/binder.h (revision 1522570)
@@ -0,0 +1,86 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+/** How typelists work:
+ * Typelists are represented by the class Binder. That class is a container for only two types, but if one of
+ * those is of type Binder<..,..> itself, the types contained by the binder are interpreted as members of the list.
+ * That way lists off arbitrary size can be defined recursively.
+ *
+ * To make the whole thing look a little nicer, either the Append member of Binder(see below), or the BIND_LIST_X(..) macros can be used(see bottom).
+* */
+
+#ifndef BINDER_H
+#define BINDER_H
+
+#include "binder.h"
+
+
+/** This class is used to group multiple types together. They can be appended in a nicer looking manner
+then recursion, Example:
+Binder<Message1>::Append<Message2>::Append<Message3>::Result
+Would be the same as Binder<Binder<Message1, Message2>, Message3 >
+*/
+
+///In the type-lists, the class Empty is counted as non-existent
+class Empty {}
+;
+template <class Chain1, class Chain2 = Empty>
+struct Binder {
+ template <class NChain>
+ struct Append {
+ typedef Binder< Binder< Chain1, Chain2 >, NChain > Result;
+ };
+};
+
+template <class Item1>
+struct Binder<Empty, Item1> {
+ typedef Item1 Result;
+ template <class NChain>
+ struct Append {
+ typedef Binder< Item1, NChain > Result;
+ };
+};
+
+template <class Item1>
+struct Binder<Item1, Empty> {
+ typedef Item1 Result;
+ template <class NChain>
+ struct Append {
+ typedef Binder< Item1, NChain > Result;
+ };
+
+};
+
+template <>
+struct Binder<Empty, Empty> {
+ typedef Empty Result;
+ template <class NChain>
+ struct Append {
+ typedef Binder< NChain, Empty > Result;
+ };
+}
+;
+
+template <class Slave, class Parent = typename Slave::Precursor, unsigned char preferredSubId = Slave::preferredIndex>
+class Chain {};
+
+
+///This macro simplifies the syntax of defining a static type-list. The first parameter is the name of the new type, the other parameters are the types.
+#define BIND_LIST_1( name, x1 ) typedef Binder<x1> name;
+#define BIND_LIST_2( name, x1, x2 ) typedef Binder<x1>::Append<x2>::Result name;
+#define BIND_LIST_3( name, x1, x2, x3 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result name;
+#define BIND_LIST_4( name, x1, x2, x3, x4 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result name;
+#define BIND_LIST_5( name, x1, x2, x3, x4, x5 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result::Append<x5>::Result name;
+#define BIND_LIST_6( name, x1, x2, x3, x4, x5, x6 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result::Append<x5>::Result::Append<x6>::Result name;
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/binder.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp (revision 1522570)
@@ -0,0 +1,26 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include <boost/iostreams/stream.hpp>
+#include "mem_iostream.h"
+
+int main() {
+cout << "testing" << "\n";
+std::vector<char> v;
+ stream<vector_device> io(v);
+ char tv[4] = {0, 0, 0, 0};
+ io.write( (char*)tv, 4 );
+ io.flush();
+ cout << v.size() << endl;
+
+ return 1;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp (revision 1522570)
@@ -0,0 +1,40 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "vector_stream.h"
+#include <assert.h>
+
+
+int main() {
+ std::vector<char> testbuf;
+ for( int a = 0; a < 100000; a++ )
+ testbuf.push_back( a );
+
+ std::vector<char> testbuf2 = testbuf;///lesetest
+ std::vector<char> testbuf3;///schreibtest
+
+ vector_device readDevice( testbuf2 );
+ vector_device writeDevice( testbuf3 );
+
+ for( int a = 0; a < 100; a++ ) {
+ char buf[1000];
+ readDevice.read( buf, 1000 );
+ writeDevice.write( buf, 1000 );
+ }
+
+ for( int a = 0; a < 100000; a++ )
+ assert( testbuf[a] == testbuf2[a] && testbuf[a] == testbuf3[a] );
+
+ cout << "assert success\n";
+
+ return 0;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp (revision 1522570)
@@ -0,0 +1,196 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#include "user.h"
+#include "serialization.h"
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/nvp.hpp>
+#include <boost/serialization/string.hpp>
+#include <boost/serialization/export.hpp> //must be included after archive-headers
+
+#include "sessioninterface.h"
+#include "teamworkmessages.h"
+
+namespace Teamwork {
+
+void OnlineInformation::setSession( const SessionPointer& sess ) {
+ session_ = sess;
+}
+
+OnlineInformation::OnlineInformation( const OnlineInformation& /*rhs*/ ) {
+}
+
+OnlineInformation& OnlineInformation::operator = ( const OnlineInformation& /*rhs*/ ) {
+ return *this;
+}
+
+OnlineInformation::OnlineInformation() {}
+
+OnlineInformation::~OnlineInformation() {
+}
+
+const SessionPointer& OnlineInformation::session() {
+ return session_;
+}
+
+OnlineInformation::operator bool() {
+ return session_ && session_.unsafe() ->isOk();
+}
+
+User::User( const User* user ) {
+ *this = *user;
+}
+
+User::User( const UserIdentity& identity ) : name_ ( identity.name() ), rights_( UserRights ) {}
+
+User::User( string name, string password, string description ) : name_( name ), password_( password ), description_( description ), rights_( UserRights ) {}
+
+User::~User() {}
+
+int User::rights() const {
+ return rights_;
+}
+
+std::string User::email() const {
+ return email_;
+}
+
+void User::setEmail( const std::string& em ) {
+ email_ = em;
+}
+
+std::string User::rightsAsString() const {
+ std::string ret;
+ if( rights_ & (int)UserRights ) ret += "user, ";
+ if( rights_ & (int)TrustedRights ) ret += "trusted, ";
+ if( rights_ & (int)AdminRights ) ret += "admin, ";
+ if(!ret.empty() ) ret = ret.substr( 0, ret.length() - 2 );
+
+ return ret;
+}
+
+void User::setRights( int rights ) {
+ rights_ = rights;
+}
+
+bool User::matchRight( int right ) {
+ return right & rights_;
+}
+
+OnlineInformation& User::online() {
+ return online_;
+}
+
+template<class Archive>
+void User::serialize( Archive& arch, const uint /*version*/ ) {
+ arch & boost::serialization::make_nvp( "Name", name_ );
+ arch & boost::serialization::make_nvp( "password", password_ );
+ arch & boost::serialization::make_nvp( "description", description_ );
+ arch & boost::serialization::make_nvp( "rights", rights_ );
+ arch & boost::serialization::make_nvp( "email", email_ );
+}
+
+///this function is used for authentication. The given user should be the one trying to connect.
+bool User::match( const User& u ) {
+ if ( rights_ & BannedRights )
+ return false;
+ return ( password_.compare( u.password_ ) == 0 ) && ( name_.compare( u.name_ ) == 0 );
+}
+
+bool User::matchIdentity( const User& u ) {
+ return name_ == u.name_;
+}
+
+///this function strips all information that is not necessary for correct authentication/identification at the given target-user
+void User::stripForTarget( const User& /*target*/ ) {
+ password_ = "";
+ description_ = "";
+}
+
+///strips away all information that should stay private, but leaves things like description etc.
+void User::stripForPublic() {
+ password_ = "";
+}
+
+///this function strips all information that is not necessary to generally identify a user(this might strip away more than stripForTarget, and includes passwords and such)
+void User::stripForIdentification() {
+ password_ = "";
+ description_ = "";
+}
+
+UserIdentity User::identity() {
+ return UserIdentity( name_ );
+}
+
+
+string User::description() const {
+ return description_;
+}
+
+bool User::operator < ( const User& rhs ) const {
+ return name_ < rhs.name_;
+}
+
+bool User::operator < ( const string& rhs ) const {
+ return name_ < rhs;
+}
+
+bool User::operator < ( const UserIdentity& rhs ) const {
+ return name_ < rhs.name();
+}
+
+string User::safeName() const {
+ SafeSharedPtr<User>::Locked l = const_cast<User*>( this );
+ if ( l ) {
+ return name_;
+ } else {
+ return "unlockable_user";
+ }
+}
+
+void User::setSession( const SessionPointer& sess ) {
+ online_.setSession( sess );
+}
+
+const string& User::name() const {
+ return name_;
+}
+
+const string& User::password() const {
+ return password_;
+}
+
+void User::ban( bool banned ) {
+ if( banned )
+ rights_ |= BannedRights;
+ else if( rights_ & BannedRights )
+ rights_ -= BannedRights;
+}
+
+bool User::banned() const {
+ return rights_ & BannedRights;
+}
+
+void User::setPassword( const string& password ) {
+ password_ = password;
+}
+
+INSTANTIATE_SERIALIZATION_FUNCTIONS( User )
+}
+
+///This should be done for each class derived from User, so it can correctly be serialized from a pointer.
+BOOST_CLASS_EXPORT_GUID( Teamwork::User, "Teamwork::User" )
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h (revision 1522570)
@@ -0,0 +1,120 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef SAFELIST_H
+#define SAFELIST_H
+
+#include <list>
+#include <cc++/thread.h>
+#include "safesharedptr.h"
+
+namespace Teamwork {
+ template <class Type>
+ class SafeList {
+ class MutexLocker {
+ ost::Mutex& m_;
+ MutexLocker& operator=( const MutexLocker& /*rhs*/ ) {
+ return *this;
+ };
+
+ public:
+ MutexLocker( ost::Mutex& mutex ) : m_( mutex ) {
+ m_.enterMutex();
+ }
+
+ MutexLocker( MutexLocker& rhs ) : m_( rhs.m_ ) {
+ m_.enterMutex();
+ }
+
+ ~MutexLocker() {
+ m_.leaveMutex();
+ }
+ };
+ std::list<Type> list_;
+ mutable ost::Mutex m_;
+ public:
+ SafeList() {
+ }
+
+ void push_back( const Type& t ) {
+ MutexLocker l( m_ );
+ list_.push_back( t );
+ }
+
+ void push_front( const Type& t ) {
+ MutexLocker l( m_ );
+ list_.push_front( t );
+ }
+
+ void pop_back() {
+ MutexLocker l( m_ );
+ list_.pop_back();
+ }
+
+ void pop_front() {
+ MutexLocker l( m_ );
+ list_.pop_front();
+ }
+
+ Type& front() {
+ MutexLocker l( m_ );
+ return list_.front();
+ }
+
+ Type& back() {
+ MutexLocker l( m_ );
+ return list_.back();
+ }
+
+ const Type& front() const {
+ MutexLocker l( m_ );
+ return list_.front();
+ }
+
+ const Type& back() const {
+ MutexLocker l( m_ );
+ return list_.back();
+ }
+
+ SafeList& operator << ( const Type& item ) {
+ MutexLocker l( m_ );
+ push_back( item );
+ return *this;
+ }
+
+ bool empty() const {
+ MutexLocker l( m_ );
+ return list_.empty();
+ }
+
+ void clear() {
+ MutexLocker l( m_ );
+ list_.clear();
+ }
+
+ bool empty() {
+ MutexLocker l( m_ );
+ return list_.empty();
+ }
+
+ operator bool() const {
+ return !empty();
+ }
+
+ int size() const {
+ MutexLocker l( m_ );
+ return list_.size();
+ }
+ };
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h (revision 1522570)
@@ -0,0 +1,92 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include <boost/iostreams/categories.hpp> // seekable_device_tag
+#include <boost/iostreams/positioning.hpp>
+#include <boost/iostreams/stream.hpp>
+#include <streambuf>
+#include <vector>
+#include <stdio.h>
+#include <iostream>
+#include <memory.h>
+
+#ifndef VECTOR_STREAM_H
+#define VECTOR_STREAM_H
+
+using namespace boost::iostreams;
+using namespace std;
+
+class vector_device {
+ public:
+ typedef char char_type;
+ typedef bidirectional_device_tag category;
+
+ vector_device( std::vector<char>& vec ) : v_(vec), readPosition_(0) {
+ }
+
+ std::streamsize read(char* s, std::streamsize n)
+ {
+ if( n + readPosition_ > v_.size() )
+ n = v_.size() - readPosition_;
+
+ memcpy( s, &(v_[readPosition_]), n );
+ readPosition_ += n;
+
+ return n;
+ }
+
+ std::streamsize write(const char* s, std::streamsize n)
+ {
+ uint oldSize = v_.size();
+ v_.resize( oldSize + n );
+ memcpy( &(v_[oldSize]), s, n );
+ return n;
+ }
+
+ private:
+ std::vector<char>& v_;
+ uint readPosition_;
+};
+
+class vector_read_device {
+ public:
+ typedef char char_type;
+ typedef bidirectional_device_tag category;
+
+ vector_read_device( const std::vector<char>& vec ) : v_(vec), readPosition_(0) {
+ }
+
+ std::streamsize read(char* s, std::streamsize n)
+ {
+ if( n + readPosition_ > v_.size() )
+ n = v_.size() - readPosition_;
+
+ memcpy( s, &(v_[readPosition_]), n );
+ readPosition_ += n;
+
+ return n;
+ }
+
+ std::streamsize write(const char* /*s*/, std::streamsize /*n*/)
+ {
+ return 0;
+ }
+
+ private:
+ const std::vector<char>& v_;
+ uint readPosition_;
+};
+
+typedef boost::iostreams::stream<vector_device> vector_stream;
+typedef boost::iostreams::stream<vector_read_device> vector_read_stream;
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h (revision 1522570)
@@ -0,0 +1,729 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 file defines a multi-indexed set(called CrossMap) similar to boost's multi-index, but with simpler api, with support for index-lists, and less efficient.
+
+#ifndef CROSSMAP_H
+#define CROSSMAP_H
+
+
+#include "statictree.h"
+#include <map>
+#include <string>
+#include <ext/hash_map>
+#include <iostream>
+#include <list>
+#include "crossmapimpl.h"
+
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/hash_map.hpp>
+#include <boost/serialization/split_member.hpp>
+#include <boost/serialization/utility.hpp>
+#include <boost/serialization/map.hpp>
+
+namespace Utils {
+
+using namespace Meta;
+using namespace Tree;
+using namespace __gnu_cxx;
+using namespace std;
+//#define hash_map map
+
+///This can be specialized to get the keys non-intrusively.
+template <class KeyType, int number, class ItemType>
+KeyType getCrossMapKey( const ItemType& item ) {
+ return item.template getKey<KeyType, number>();
+}
+
+/**A similar structure may be given to CrossMap to extract the keys in a different way, or the
+ * Extractor-member may be specialized. Advantage: partial specialization is possible. */
+
+struct StandardCrossMapKeyExtractor {
+ template <class KeyType, int number, class ItemType>
+ struct Extractor {
+ static KeyType getKey( const ItemType& item ) {
+ return getCrossMapKey<KeyType, number, ItemType>( item );
+ }
+ };
+};
+
+///For the trivial identity no special extraction has to be specialized if StandardCrossMapKeyExtractor is used.
+template <class Type>
+struct StandardCrossMapKeyExtractor::Extractor< Type, 0, Type > {
+ static const Type& getKey( const Type& item ) {
+ return item;
+ }
+};
+
+/**For very simple cases, specialization of getCrossMapKey can be simplified by using this macro.
+ * For writing the expression the value is available as a const reference named "value", and the result
+ * of the expression is used as key.
+ * Example:
+ * CROSSMAP_KEY_EXTRACTOR( MyValueType, MyValueType::Id, 0, value.id() );
+ * */
+#define CROSSMAP_KEY_EXTRACTOR( ValueType, KeyType, Number, Expression ) \
+namespace Utils { \
+template <> \
+KeyType getCrossMapKey< KeyType, Number, ValueType>( const ValueType& value ) { \
+ return Expression; \
+} \
+} \
+
+
+/**This macro can be used to create small wrapper-types that hold another type,
+
+* to access the type in the crossmap in a unique way
+* @example:
+* NAMED_TYPE( UserId, uint );
+* ...;
+* User v = map.value<UserId>( 5 ); ///Gets the user with user-id 5*/
+
+#define NAMED_TYPE(Name, type) \
+struct Name { type value; operator type&() { return value; }; static const char* name() { return #Name; }; Name( const type& v ) : value(v) {}; /*Name& operator = ( const type& t ) { value = t; };*/ Name() {}; bool operator < ( const Name& rhs ) const { return value < rhs.value; } template<class T> Name( const T& t ) : value( t ) {} template<class T> bool operator == ( const T& rhs ) const { return value == rhs.value; } }
+
+
+/**This may be specialized to define own container-types that should not be used as keys directly, but from which subkeys should be extracted
+ * */
+
+#define CROSSMAP_DEFINE_CONTAINER( Cnt ) \
+namespace Utils { \
+template<class Type> \
+struct ExtractKeyType::Action<Cnt<Type> > { \
+ typedef Type Result; \
+ typedef True isContainer; \
+}; \
+} \
+
+
+template<class KeyList>
+struct RealKeys {
+ typedef typename ForEachInList<ExtractKeyType, KeyList>::Result Result;
+};
+
+
+///Not used yet, but should be
+#define SET_HASHABLE(Type) template<> Utils::CrossMapHashTraits<Type> { enum { hashable = 1 } };
+
+///This can be used to mark types that should be managed using a hash_multimap instead of a sorted multimap
+template <class Type>
+struct Hashed {}
+;
+
+class CrossMapId {
+ uint id_;
+ public:
+ CrossMapId() : id_( 0 ) {}
+
+ CrossMapId( uint id ) : id_( id ) {}
+
+ uint id() {
+ return id_;
+ }
+
+ bool operator == ( const CrossMapId & rhs ) const {
+ return id_ == rhs.id_;
+ }
+
+ CrossMapId& operator = ( const CrossMapId & rhs ) {
+ id_ = rhs.id_;
+ return *this;
+ }
+
+ bool operator < ( const CrossMapId & rhs ) const {
+ return id_ < rhs.id_;
+ }
+
+ bool operator <= ( const CrossMapId & rhs ) const {
+ return id_ <= rhs.id_;
+ }
+
+ template <class Archive>
+ void serialize( Archive & arch, uint version ) {
+ arch & id_;
+ }
+
+ operator uint() const {
+ return id_;
+ }
+};
+
+/**This is a kind of in-memory database that allows storing/sorting items by an arbitrary count of keys
+ * and key-types. The keys are extracted in
+ * the moment an item is inserted. If the keys change, update(..) should be called on the item.
+ *
+ *
+ * It is very similar to the boost multi-index, but the api is a bit easier.
+ *
+ * Advantage against boost's multi-index: One item can be reachable by many indices in the same category,
+ * by using CROSSMAP_DEFINE_CONTAINER(..) and giving such a key-container as to the key-list.
+ * Then the item will be searchable by each key in the list.
+ * (If the value-type is used as key, it will be filled with the key's value by default and no key-extractor needs to be defined for that case)
+ * (Example: multiple filenames may be associated to users, and it is possible to get a list of users for each filename)
+ *
+ * Disadvantage: Less efficient, bigger binary
+ *
+ * @param Value The value-type, should be a type with a default-constructor(is used as Dummy for Functions like operator[] if the key cannot be found)
+ * @param Keys a meta-list containing all keys(using BIND_LIST or Binder<...,...>
+ * @param KeyExtractor (optional) a class that helps extracting the keys from the values
+ * @param rebuildAfterLoad whether serialization should only store a list of values, without the additional maps and the cross-link-data etc.(then every key has to be re-extracted after the archive was loaded, and the structure may be different)
+ */
+
+template <class Value, class Keys, class KeyExtractor = StandardCrossMapKeyExtractor>
+class CrossMap {
+ typedef CrossMap< Value, Keys, KeyExtractor> Self;
+ typedef KeyValueChain< Value, Keys, KeyExtractor> KeyValues;
+ typedef typename RealKeys<Keys>::Result RealKeys;
+ typedef CrossMapId Id;
+
+ template <bool cacheKeys>
+ struct ValueStore {
+ Value value;
+ KeyValues keyValues;
+ ValueStore( const Value & v ) : value( v ), keyValues( v ) {}
+ ValueStore& operator = ( const Value & v ) {
+ value = v;
+ keyValues = KeyValues( v )
+ ;
+ return *this;
+ }
+
+ operator Value& () {
+ return value;
+ }
+ };
+
+ typedef ValueStore< true > MyValueStore;
+
+ bool rebuildAfterLoad_; ///@todo Not yet used
+
+ public:
+
+ typedef hash_map< uint, MyValueStore > ValueMap;
+
+ /**Special care has to be taken when a ValueEditor-object is copied: When a ValueEditor is copied,
+ * the source will not update the map on it's destruction, and all copies of a ValueEditor that does
+ * not update the map won't do it neither. So generally it's safer to use a ValueEditor in-place, without copying it around. */
+
+ class ValueEditor {
+ Id id_;
+ Self* map_;
+ Value* value_;
+ public:
+ ValueEditor( Self* map, const Id id, Value* value ) : id_( id ), map_( map ), value_( value ) {}
+
+ ValueEditor( const ValueEditor& e ) : id_( e.id_ ), map_( e.map_ ), value_( e.value_ ) {
+ const_cast<ValueEditor&>( e ).id_ = 0; ///This is done so the destruction of the other ValueEditor doesn't update the map
+ }
+
+ ValueEditor& operator = ( const ValueEditor& rhs ) {
+ map_ = rhs.map_;
+ value_ = rhs.value_;
+ id_ = rhs.id_;
+ const_cast<ValueEditor&>( rhs ).id_ = 0; ///This is done so the destruction of the other ValueEditor doesn't update the map
+ }
+
+ ~ValueEditor() {
+ if ( id_ )
+ map_->update( id_ );
+ }
+
+ ///It is safe to edit a value through this operator. It is not safe to take the address or reference for further use.
+ Value* operator ->() {
+ return value_;
+ }
+ };
+
+ ///An iterator represents a list of Items that can be iterated over. It depends on the map that created it.
+ class Iterator {
+ typedef std::list<uint> IdList;
+ public:
+ Iterator( Self * map = 0 ) : it_( ids_.begin() ), map_( map ) {}
+
+ operator bool() const {
+ return map_ && it_ != ids_.end();
+ }
+
+ Iterator& operator ++ () {
+ ++it_;
+ return *this;
+ }
+
+ const Value& operator *() const {
+ return map_->valueFromId( *it_ );
+ }
+
+ const Value* operator ->() const {
+ return & map_->valueFromId( *it_ );
+ }
+
+ /**Returns a ValueEditor-object that can be used to directly edit the values in-place comfortably and automatically update the map.
+ * @see ValueEditor::operator -> */
+ ValueEditor edit() {
+ return ValueEditor( map_, *it_, &map_->valueFromId( *it_ ) );
+ }
+
+ ///expensive
+ uint count() const {
+ return ids_.size();
+ }
+
+ Id id() const {
+ return * it_;
+ }
+
+ ///Must be called after the first ids are added, and can be called any time again to jump back to the beginning
+ void restart() {
+ it_ = ids_.begin();
+ }
+
+ operator Id() const {
+ return * it_;
+ }
+
+ ///Compares the current value pointed to
+ bool operator == ( const Iterator & rhs ) const {
+ bool end1 = it_ == ids_.end();
+ bool end2 = rhs.it_ == rhs.ids_.end();
+ if ( end1 != end2 )
+ return false;
+ if ( end1 )
+ return true;
+ return *it_ == *rhs.it_;
+ }
+
+ private:
+ void addId( uint id ) {
+ ids_.push_back( id );
+ }
+
+
+ IdList::const_iterator it_;
+ Self* map_;
+ IdList ids_;
+ friend class CrossMap< Value, Keys, KeyExtractor>;
+ };
+
+
+ /**
+ * @param rebuildAfterLoad Whether the set should be stored compact(only the values themselves, without all the helper-maps). Not used yet.
+ * */
+ CrossMap( bool rebuildAfterLoad = true ) : rebuildAfterLoad_( rebuildAfterLoad ), currentId_( 1 ) {}
+
+ /**The Functions that directly return a Value-Reference return a default-constructed dummy if the item cannot be found.
+ * These are very simple convenience-functions that directly return the first matching item. iterator is much more powerful.
+ * */
+ template <class KeyType>
+ const Value & operator[] ( const KeyType& key ) const {
+ return value<0, KeyType>( key );
+ }
+
+ /**This is an expensive convenience-function. It returns a temporary object that allows access to the value, and once that object is destroyed
+ * automatically updated the map. (That allows assignment-operations like mymap[5].name = "Honk").
+ * But it is very expensive since every time the temporary object is destroyed, all keys are reevaluated and all maps are updated.
+ * */
+
+ /*
+ template <class KeyType>
+ ValueEditor<Value> & operator[] ( const KeyType& key ) {
+
+ return value<0, KeyType>( key );
+ }*/
+
+
+ template <int keyNum, class KeyType>
+ const Value& value( const KeyType & key ) const {
+ typedef std::multimap<KeyType, uint> Map;
+ const Map& map = getMap<keyNum, KeyType>();
+ typename Map::const_iterator it = map.find( key );
+ if ( it != map.end() ) {
+ typename ValueMap::const_iterator itt = values_.find( ( *it ).second );
+ if ( itt != values_.end() ) {
+ return ( *itt ).second.value;
+ }
+ }
+ return dummy_;
+ }
+
+ Iterator values() const {
+ Iterator ret( const_cast<Self*>( this ) );
+ for ( typename ValueMap::const_iterator it = values_.begin(); it != values_.end(); ++it )
+ ret.addId( ( *it ).first );
+
+ ret.restart();
+ return ret;
+ };
+
+ template <int keyNum, class KeyType>
+ Iterator values( const KeyType & key ) const {
+ typedef std::multimap<KeyType, uint> Map;
+ const Map& map = getMap<keyNum, KeyType>();
+ std::pair<typename Map::const_iterator, typename Map::const_iterator> range = map.equal_range( key );
+ Iterator ret( const_cast<Self*>
+ ( this ) );
+
+ while ( range.first != range.second ) {
+ ret.addId( ( *range.first ).second )
+ ;
+ ++range.first;
+ }
+
+ ret.restart();
+ return ret;
+ }
+
+ template <class KeyType>
+ Iterator values( const KeyType & key ) const {
+ return values<0> ( key );
+ }
+
+ ///For none-hashed value-types, this is no additional expense agains unordered retrieval. Returns them ordered by the given key.
+ template <int keyNum, class KeyType>
+ Iterator orderedValues( const KeyType & key ) const {
+ typedef std::multimap<KeyType, uint> Map;
+ const Map& map = getMap<keyNum, KeyType>();
+ std::pair<typename Map::const_iterator, typename Map::const_iterator> range = map.equal_range( key );
+ Iterator ret( const_cast<Self*>
+ ( this ) );
+
+ while ( range.first != range.second ) {
+ ret.addId( ( *range.first ).second )
+ ;
+ ++range.first;
+ }
+
+ ret.restart();
+ return ret;
+ }
+
+ ///For none-hashed value-types, this is no additional expense agains unordered retrieval.
+ template <class KeyType>
+ Iterator orderedValues( const KeyType & key ) const {
+ return orderedValues<0> ( key );
+ }
+
+ template <int keyNum, class KeyType>
+ Iterator orderedValues() const {
+ Iterator ret( const_cast<Self*>( this ) );
+ typedef std::multimap<KeyType, uint> Map;
+
+ const Map& m = getMap<keyNum, KeyType>();
+ for( typename Map::const_iterator it = m.begin(); it != m.end(); ++it )
+ ret.addId( (*it).second );
+
+ ret.restart();
+ return ret;
+ }
+
+ template<class KeyType>
+ Iterator orderedValues() const {
+ return orderedValues<0, KeyType>();
+ }
+
+
+ const Value& valueFromId( Id id ) const {
+ typename ValueMap::const_iterator itt = values_.find( id );
+ if ( itt != values_.end()
+ )
+ return ( *itt ).second.value;
+ else
+ return dummy_;
+ }
+
+ template <class KeyType>
+ const Value& value( const KeyType & key ) const {
+ return value< 0, KeyType >( key );
+ }
+
+ ///Creates a copy of all key-values which can be used to reference items. This might be used to store a consistent representation of the keys a value was stored under.
+ static KeyValues copyKeyValues( const Value & value ) {
+ return KeyValues( value );
+ }
+
+ ///When KeyValues are given from outside, they do not have to be recomputed by using the KeyExtractor.
+ Id insert( const KeyValues & keyValues, const Value & value ) {
+ uint id = currentId_++;
+ values_.insert( make_pair( id, value ) );
+ insertToData( keyValues, value, id );
+ return id;
+ }
+
+ Id insert( const Value & value ) {
+ KeyValues keys( value );
+ return insert( keys, value );
+ }
+
+ ///Returns the Id of the removed Value, or zero on fail
+ Id remove
+ ( Id id ) {
+ if ( id ) {
+ typename ValueMap::iterator it = values_.find( id );
+ if ( it == values_.end() )
+ return 0;
+
+ removeFromData( ( *it ).second.keyValues, id );
+ values_.erase( id );
+ return id;
+ } else {
+ return 0;
+ }
+ }
+
+ ///Removes the item the iterator currently points at
+ bool remove
+ ( const Iterator& it ) {
+ if ( !it )
+ return false;
+ return ( bool ) remove
+ ( it.id() );
+ }
+
+ ///Removes all items the iterator iterates over
+ uint removeAll( const Iterator& it ) {
+ if ( !it )
+ return false;
+ Iterator i = it;
+ i.restart();
+ uint ret = 0;
+ while ( i ) {
+ if ( remove
+ ( i.id() ) ) ret++;
+ }
+ return ret;
+ }
+
+ ///Returns the Id of the removed Value, or zero on fail
+ Id remove
+ ( const KeyValues & keyValues, const Value & value ) {
+ Id id = find( keyValues, value );
+ return remove
+ ( id );
+ }
+
+ ///Returns the Id of the removed Value, or zero on fail
+ Id remove
+ ( const Value & value ) {
+ KeyValues keys( value );
+ return remove
+ ( keys, value );
+ }
+
+ ///@return 0 if the item was not found, else the id of a matching value */
+ Id find( const KeyValues & values, const Value & value ) {
+ return data_.template find( values, value, *this );
+ }
+
+ /**Tries to get the internal entry-Id of the Value by extracting the value's keys,
+ * searching, and using the identity-test to verify that the found value is the same.
+ * If all key-values changed since the item was inserted, or it changed in a way that
+ * the identity-test(operator ==) fails, it cannot be found.(For that reason
+ * it may be useful to choose an additional key above the really necessary ones,
+ * that never changes, as the first key.(For example the address of a pointer).
+ * @return 0 if the item was not found, else the id of a matching value */
+ Id find( const Value & value ) {
+ KeyValues keys( value );
+ return find( keys, value );
+ }
+
+ ///@return 0 if there is no content, 1 if there is content, and 2 if the set is inconsistent(some maps have content, others don't)
+ int hasContent() const {
+ return !values_.empty() && data_.hasContent();
+ }
+
+ bool empty() const {
+ return !hasContent();
+ }
+
+ void clear() {
+ values_.clear();
+ data_.clear();
+ }
+
+ uint count() const {
+ return values_.size();
+ }
+
+ ///@return if the given id is bound to the specified value
+ bool validateId( const Value & value, Id id ) const {
+ typename ValueMap::const_iterator it = values_.find( id );
+
+ if ( it != values_.end() && ( *it ).second.value == value )
+ return true;
+ return false;
+ }
+
+ template <class Archive>
+ void load( Archive & arch, uint version ) {
+ arch & rebuildAfterLoad_;
+ arch & currentId_;
+ arch & dummy_;
+ if ( rebuildAfterLoad_ ) {
+ uint size;
+ arch & size;
+ values_.clear();
+ data_.clear();
+ for ( uint a = 0; a < size; a++ ) {
+ typename ValueMap::value_type t;
+ arch & t;
+ values_.insert( t );
+ insertToData( t.second.keyValues, t.second.value, t.first );
+ }
+ } else {
+ arch & values_;
+ arch & data_;
+ }
+
+ }
+ template <class Archive>
+ void save( Archive & arch, uint version ) {
+ arch & rebuildAfterLoad_;
+ arch & currentId_;
+ arch & dummy_;
+ if ( rebuildAfterLoad_ ) {
+ uint size = values_.size();
+ arch & size;
+ for ( typename ValueMap::const_iterator it = values_.begin(); it != values_.end(); ++it ) {
+ arch & *it;
+ }
+ } else {
+ arch & values_;
+ arch & data_;
+ }
+ }
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+
+ /**If the Id is known, that should be used. "operator ==" is used while searching,
+ * so if something that affects that operator changed, the item cannot be found and updated.
+ * the value has to be findable with at least one of the keys. If all keys changed, it cannot be found.*/
+ bool update( const Value& value ) {
+ return update( find( value ) );
+ }
+
+ /**Tries to find oldValue, and replaces it with newValue. If oldValue is not found, the item is not inserted. */
+ bool update( const Value& oldValue, const Value& newValue ) {
+ Id i = find( value );
+ if ( !i )
+ return false;
+ remove
+ ( i );
+ insert( newValue );
+ }
+
+ ///Can be called after some keys changed
+ bool update( Id id ) {
+ if ( id.id() == 0 )
+ return false;
+ typename ValueMap::iterator it = values_.find( id )
+ ;
+ if ( it != values_.end() ) {
+ removeFromData( ( *it ).second.keyValues, id );
+ ( *it ).second.keyValues = KeyValues( ( *it ).second );
+ insertToData( ( *it ).second.keyValues, ( *it ).second, id );
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ typename ValueMap::iterator begin() {
+ return values_.begin();
+ }
+
+ typename ValueMap::iterator end() {
+ return values_.end();
+ }
+
+ typename ValueMap::const_iterator begin() const {
+ return values_.begin();
+ }
+
+ typename ValueMap::const_iterator end() const {
+ return values_.end();
+ }
+
+ private:
+ friend class Iterator;
+
+ Value& valueFromId( Id id ) {
+ typename ValueMap::iterator itt = values_.find( id );
+ if ( itt != values_.end()
+ )
+ return ( *itt ).second.value;
+ else
+ return dummy_;
+ }
+
+
+ void removeFromData( const KeyValues & keyValues, Id id ) {
+ data_.template remove
+ ( keyValues, id );
+ }
+
+ void insertToData( const KeyValues & keyValues, const Value & value, Id id ) {
+ data_.template insert( keyValues, value, id );
+ }
+
+ ///These functions allow efficient access to the underlying maps
+ template <int keyNum>
+ const std::multimap< typename GetListItem< keyNum, RealKeys >::Result, Value > & getMap() const {
+ return data_. CrossMapData< Value, typename GetListItem< keyNum, Keys >::Result, keyNum> :: map;
+ }
+
+ template <class KeyType>
+ const std::multimap< KeyType, uint >& getMap() const {
+ return data_. CrossMapData< Value, KeyType, FindInList<KeyType, Keys>::value > :: map;
+ }
+
+ template <int occurrenceNum, class KeyType>
+ const std::multimap< KeyType, uint >& getMap() const {
+ enum {
+ num = FindInList<KeyType, RealKeys, occurrenceNum>::value
+ };
+ return data_. CrossMapData< Value, typename GetListItem< num, Keys >::Result, num > :: map;
+ }
+
+ template <int keyNum>
+ std::multimap< typename GetListItem< keyNum, RealKeys >::Result, Value >& getMap() {
+ return data_. CrossMapData< Value, typename GetListItem< keyNum, Keys >::Result, keyNum> :: map;
+ }
+
+ template <class KeyType>
+ std::multimap< KeyType, uint >& getMap() {
+ return data_. CrossMapData< Value, KeyType, FindInList<KeyType, Keys>::value > :: map;
+ }
+
+ template <int occurrenceNum, class KeyType>
+ std::multimap< KeyType, uint >& getMap() {
+ enum {
+ num = FindInList<KeyType, RealKeys, occurrenceNum>::value
+ };
+ return data_. CrossMapData< Value, typename GetListItem< num, Keys >::Result, num > :: map;
+ }
+
+ uint currentId_;
+
+ Value dummy_;
+
+ ValueMap values_;
+
+ CrossMapChain< Value, Keys, 0 > data_;
+};
+
+}
+
+CROSSMAP_DEFINE_CONTAINER( std::list )
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile (revision 1522570)
@@ -0,0 +1,276 @@
+# Doxyfile 1.4.1-KDevelop
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+PROJECT_NAME = network.kdevelop
+PROJECT_NUMBER = $VERSION$
+OUTPUT_DIRECTORY =
+CREATE_SUBDIRS = NO
+OUTPUT_LANGUAGE = English
+USE_WINDOWS_ENCODING = NO
+BRIEF_MEMBER_DESC = YES
+REPEAT_BRIEF = YES
+ABBREVIATE_BRIEF = "The $name class" \
+ "The $name widget" \
+ "The $name file" \
+ is \
+ provides \
+ specifies \
+ contains \
+ represents \
+ a \
+ an \
+ the
+ALWAYS_DETAILED_SEC = NO
+INLINE_INHERITED_MEMB = NO
+FULL_PATH_NAMES = YES
+STRIP_FROM_PATH = /home/nolden/projekte/summer-of-code/work/kdevelop-teamwork/network/
+STRIP_FROM_INC_PATH =
+SHORT_NAMES = NO
+JAVADOC_AUTOBRIEF = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP = NO
+INHERIT_DOCS = YES
+DISTRIBUTE_GROUP_DOC = NO
+TAB_SIZE = 8
+ALIASES =
+OPTIMIZE_OUTPUT_FOR_C = NO
+OPTIMIZE_OUTPUT_JAVA = NO
+SUBGROUPING = YES
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL = NO
+EXTRACT_PRIVATE = NO
+EXTRACT_STATIC = NO
+EXTRACT_LOCAL_CLASSES = YES
+EXTRACT_LOCAL_METHODS = NO
+HIDE_UNDOC_MEMBERS = NO
+HIDE_UNDOC_CLASSES = NO
+HIDE_FRIEND_COMPOUNDS = NO
+HIDE_IN_BODY_DOCS = NO
+INTERNAL_DOCS = NO
+CASE_SENSE_NAMES = YES
+HIDE_SCOPE_NAMES = NO
+SHOW_INCLUDE_FILES = YES
+INLINE_INFO = YES
+SORT_MEMBER_DOCS = YES
+SORT_BRIEF_DOCS = NO
+SORT_BY_SCOPE_NAME = NO
+GENERATE_TODOLIST = YES
+GENERATE_TESTLIST = YES
+GENERATE_BUGLIST = YES
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS =
+MAX_INITIALIZER_LINES = 30
+SHOW_USED_FILES = YES
+SHOW_DIRECTORIES = YES
+FILE_VERSION_FILTER =
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET = NO
+WARNINGS = YES
+WARN_IF_UNDOCUMENTED = YES
+WARN_IF_DOC_ERROR = YES
+WARN_NO_PARAMDOC = NO
+WARN_FORMAT = "$file:$line: $text"
+WARN_LOGFILE =
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT = /home/nolden/projekte/summer-of-code/work/kdevelop-teamwork/network
+FILE_PATTERNS = *.c \
+ *.cc \
+ *.cxx \
+ *.cpp \
+ *.ocl \
+ *.c++ \
+ *.java \
+ *.ii \
+ *.ixx \
+ *.ipp \
+ *.i++ \
+ *.inl \
+ *.h \
+ *.hh \
+ *.hxx \
+ *.hpp \
+ *.h++ \
+ *.idl \
+ *.odl \
+ *.cs \
+ *.php \
+ *.php3 \
+ *.inc \
+ *.m \
+ *.mm \
+ *.dox \
+ *.C \
+ *.CC \
+ *.C++ \
+ *.II \
+ *.I++ \
+ *.H \
+ *.HH \
+ *.H++ \
+ *.CS \
+ *.PHP \
+ *.PHP3 \
+ *.M \
+ *.MM \
+ *.C \
+ *.H \
+ *.tlh \
+ *.diff \
+ *.patch \
+ *.moc \
+ *.xpm \
+ *.dox
+RECURSIVE = yes
+EXCLUDE =
+EXCLUDE_SYMLINKS = NO
+EXCLUDE_PATTERNS =
+EXAMPLE_PATH =
+EXAMPLE_PATTERNS = *
+EXAMPLE_RECURSIVE = NO
+IMAGE_PATH =
+INPUT_FILTER =
+FILTER_PATTERNS =
+FILTER_SOURCE_FILES = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER = NO
+INLINE_SOURCES = NO
+STRIP_CODE_COMMENTS = YES
+REFERENCED_BY_RELATION = YES
+REFERENCES_RELATION = YES
+VERBATIM_HEADERS = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX = NO
+COLS_IN_ALPHA_INDEX = 5
+IGNORE_PREFIX =
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML = YES
+HTML_OUTPUT = html
+HTML_FILE_EXTENSION = .html
+HTML_HEADER =
+HTML_FOOTER =
+HTML_STYLESHEET =
+HTML_ALIGN_MEMBERS = YES
+GENERATE_HTMLHELP = NO
+CHM_FILE =
+HHC_LOCATION =
+GENERATE_CHI = NO
+BINARY_TOC = NO
+TOC_EXPAND = NO
+DISABLE_INDEX = NO
+ENUM_VALUES_PER_LINE = 4
+GENERATE_TREEVIEW = NO
+TREEVIEW_WIDTH = 250
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX = YES
+LATEX_OUTPUT = latex
+LATEX_CMD_NAME = latex
+MAKEINDEX_CMD_NAME = makeindex
+COMPACT_LATEX = NO
+PAPER_TYPE = a4wide
+EXTRA_PACKAGES =
+LATEX_HEADER =
+PDF_HYPERLINKS = NO
+USE_PDFLATEX = NO
+LATEX_BATCHMODE = NO
+LATEX_HIDE_INDICES = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF = NO
+RTF_OUTPUT = rtf
+COMPACT_RTF = NO
+RTF_HYPERLINKS = NO
+RTF_STYLESHEET_FILE =
+RTF_EXTENSIONS_FILE =
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN = NO
+MAN_OUTPUT = man
+MAN_EXTENSION = .3
+MAN_LINKS = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML = yes
+XML_OUTPUT = xml
+XML_SCHEMA =
+XML_DTD =
+XML_PROGRAMLISTING = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD = NO
+PERLMOD_LATEX = NO
+PERLMOD_PRETTY = YES
+PERLMOD_MAKEVAR_PREFIX =
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING = YES
+MACRO_EXPANSION = NO
+EXPAND_ONLY_PREDEF = NO
+SEARCH_INCLUDES = YES
+INCLUDE_PATH =
+INCLUDE_FILE_PATTERNS =
+PREDEFINED =
+EXPAND_AS_DEFINED =
+SKIP_FUNCTION_MACROS = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+TAGFILES =
+GENERATE_TAGFILE = network.tag
+ALLEXTERNALS = NO
+EXTERNAL_GROUPS = YES
+PERL_PATH = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS = YES
+HIDE_UNDOC_RELATIONS = YES
+HAVE_DOT = NO
+CLASS_GRAPH = YES
+COLLABORATION_GRAPH = YES
+GROUP_GRAPHS = YES
+UML_LOOK = NO
+TEMPLATE_RELATIONS = NO
+INCLUDE_GRAPH = YES
+INCLUDED_BY_GRAPH = YES
+CALL_GRAPH = NO
+GRAPHICAL_HIERARCHY = YES
+DIRECTORY_GRAPH = YES
+DOT_IMAGE_FORMAT = png
+DOT_PATH =
+DOTFILE_DIRS =
+MAX_DOT_GRAPH_WIDTH = 1024
+MAX_DOT_GRAPH_HEIGHT = 1024
+MAX_DOT_GRAPH_DEPTH = 1000
+DOT_TRANSPARENT = NO
+DOT_MULTI_TARGETS = NO
+GENERATE_LEGEND = YES
+DOT_CLEANUP = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine
+#---------------------------------------------------------------------------
+SEARCHENGINE = NO
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/plan
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/plan (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/plan (revision 1522570)
@@ -0,0 +1,27 @@
+A client-server-system is needed, which will be implemented as a static C++-library.
+
+The library will provide classes and functions to:
+- run a client in a seperate thread.
+- run a server in a seperate thread.
+
+The final link between the program using the library and the library will be established by virtual member-functions.
+
+The library will then be used by kdevelop to connect to a server, or to open an own server. The whole library will only depend on STL and common-c++.
+Additionally a standalone server-program will be developed that opens a server using the library, independent from kdevelop.
+
+Objects that have the same number will share one implementation
+
+What the server implemented in the library has to do:
+- keep a list of (user, password, additional authentication-date, additional user-information, user-log) tuples
+- [2] store, manage, and use some options like whether anonymous users are allowed using a storage-class that allows simple changing, storing and restoring of the settings(the storage is done by the program that implements the server)
+- [3] provide a unified message-class for messages to either the server, or to other clients(the clients can communicate through the server or directly, but always moderated by the server). It will allow the clients sending each other messages of types the server does not know and would not understand.
+- provide a set of administrative messages for communications with clients.
+- store messages that are flagged to be safely delivered until the target-client comes online and gives a reply that it got the message
+
+What the client implemented in the library has to do:
+- keep a log of all interesting communication communication
+- keep and manage list of connected users
+- care about most of the implementation-details, and offer the client-program a simple interface to just override interesting high-level functions
+- [2] store, manage, etc. settings
+- [3] provide additional derived message-classes to communicate with other clients through the server
+- implementation of the client will be finished together with the kdevelop-plugin
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/network/plan
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,27 @@
+#@todo: this file needs to be worked over
+
+########### next target ###############
+
+set(diff2_PART_SRCS
+ kompareprocess.cpp
+ komparemodellist.cpp
+ diffmodellist.cpp
+ diffmodel.cpp
+ difference.cpp
+ diffhunk.cpp
+ levenshteintable.cpp
+ parser.cpp
+ parserbase.cpp
+ cvsdiffparser.cpp
+ diffparser.cpp
+ perforceparser.cpp
+ diffsettings.cpp
+ settingsbase.cpp )
+
+
+# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
+kde4_add_library(kdevteamwork_diff2 SHARED ${diff2_PART_SRCS})
+
+target_link_libraries(kdevteamwork_diff2 ${KDE4_KDEUI_LIBS} ${KDE4_KDE3SUPPORT_LIBS} )
+
+install(TARGETS kdevteamwork_diff2 ${INSTALL_TARGETS_DEFAULT_ARGS})
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp (revision 1522570)
@@ -0,0 +1,725 @@
+/**************************************************************************
+** parserbase.cpp
+** -------------------
+** begin : Sun Aug 4 15:05:35 2002
+** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "parserbase.h"
+#include <qobject.h>
+
+#include <kdebug.h>
+
+#include "diffmodel.h"
+#include "diffhunk.h"
+#include "difference.h"
+#include "komparemodellist.h"
+
+
+using namespace Diff2;
+
+ParserBase::ParserBase( const KompareModelList* list, const QStringList& diff ) :
+ m_diffLines( diff ),
+ m_currentModel( 0 ),
+ m_models( 0 ),
+ m_diffIterator( m_diffLines.begin() ),
+ m_singleFileDiff( false ),
+ m_list( list )
+{
+// kDebug(8101) << diff;
+// kDebug(8101) << m_diffLines;
+ m_models = new DiffModelList();
+
+ // used in contexthunkheader
+ m_contextHunkHeader1.setPattern( "\\*{15} ?(.*)\\n" ); // capture is for function name
+ m_contextHunkHeader2.setPattern( "\\*\\*\\* ([0-9]+),([0-9]+) \\*\\*\\*\\*\\n" );
+ // used in contexthunkbody
+ m_contextHunkHeader3.setPattern( "--- ([0-9]+),([0-9]+) ----\\n" );
+
+ m_contextHunkBodyRemoved.setPattern( "- (.*)" );
+ m_contextHunkBodyAdded.setPattern ( "\\+ (.*)" );
+ m_contextHunkBodyChanged.setPattern( "! (.*)" );
+ m_contextHunkBodyContext.setPattern( " (.*)" );
+ m_contextHunkBodyLine.setPattern ( "[-\\+! ] (.*)" );
+
+ // This regexp sucks... i'll see what happens
+ m_normalDiffHeader.setPattern( "diff (?:(?:-|--)[a-zA-Z0-9=\\\"]+ )*(?:|-- +)(.*) +(.*)\\n" );
+
+ m_normalHunkHeaderAdded.setPattern ( "([0-9]+)a([0-9]+)(|,[0-9]+)(.*)\\n" );
+ m_normalHunkHeaderRemoved.setPattern( "([0-9]+)(|,[0-9]+)d([0-9]+)(.*)\\n" );
+ m_normalHunkHeaderChanged.setPattern( "([0-9]+)(|,[0-9]+)c([0-9]+)(|,[0-9]+)(.*)\\n" );
+
+ m_normalHunkBodyRemoved.setPattern ( "< (.*)" );
+ m_normalHunkBodyAdded.setPattern ( "> (.*)" );
+ m_normalHunkBodyDivider.setPattern ( "---" );
+
+ m_unifiedDiffHeader1.setPattern ( "--- ([^\\t]+)\\t([^\\t]+)(?:\\t?)(.*)\\n" );
+ m_unifiedDiffHeader2.setPattern ( "\\+\\+\\+ ([^\\t]+)\\t([^\\t]+)(?:\\t?)(.*)\\n" );
+ m_unifiedHunkHeader.setPattern ( "@@ -([0-9]+)(|,([0-9]+)) \\+([0-9]+)(|,([0-9]+)) @@(?: ?)(.*)\\n" );
+ m_unifiedHunkBodyAdded.setPattern ( "\\+(.*)" );
+ m_unifiedHunkBodyRemoved.setPattern( "-(.*)" );
+ m_unifiedHunkBodyContext.setPattern( " (.*)" );
+ m_unifiedHunkBodyLine.setPattern ( "([-+ ])(.*)" );
+}
+
+ParserBase::~ParserBase()
+{
+ if ( m_models )
+ m_models = 0; // do not delete this, i pass it around...
+}
+
+enum Kompare::Format ParserBase::determineFormat()
+{
+ // Write your own format detection routine damn it :)
+ return Kompare::UnknownFormat;
+}
+
+DiffModelList* ParserBase::parse()
+{
+ switch( determineFormat() )
+ {
+ case Kompare::Context :
+ return parseContext();
+ case Kompare::Ed :
+ return parseEd();
+ case Kompare::Normal :
+ return parseNormal();
+ case Kompare::RCS :
+ return parseRCS();
+ case Kompare::Unified :
+ return parseUnified();
+ default: // Unknown and SideBySide for now
+ return 0L;
+ }
+}
+
+bool ParserBase::parseContextDiffHeader()
+{
+// kDebug(8101) << "ParserBase::parseContextDiffHeader()";
+ bool result = false;
+
+ while ( m_diffIterator != m_diffLines.end() )
+ {
+ if ( !m_contextDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
+ {
+ continue;
+ }
+// kDebug(8101) << "Matched length Header1 =" << m_contextDiffHeader1.matchedLength();
+// kDebug(8101) << "Matched string Header1 =" << m_contextDiffHeader1.cap( 0 );
+ if ( m_diffIterator != m_diffLines.end() && m_contextDiffHeader2.exactMatch( *m_diffIterator ) )
+ {
+// kDebug(8101) << "Matched length Header2 =" << m_contextDiffHeader2.matchedLength();
+// kDebug(8101) << "Matched string Header2 =" << m_contextDiffHeader2.cap( 0 );
+
+ m_currentModel = new DiffModel( m_contextDiffHeader1.cap( 1 ), m_contextDiffHeader2.cap( 1 ) );
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_currentModel->setSourceTimestamp ( m_contextDiffHeader1.cap( 2 ) );
+ m_currentModel->setSourceRevision ( m_contextDiffHeader1.cap( 4 ) );
+ m_currentModel->setDestinationTimestamp( m_contextDiffHeader2.cap( 2 ) );
+ m_currentModel->setDestinationRevision ( m_contextDiffHeader2.cap( 4 ) );
+
+ ++m_diffIterator;
+ result = true;
+
+ break;
+ }
+ else
+ {
+ // We're screwed, second line does not match or is not there...
+ break;
+ }
+ // Do not inc the Iterator because the second line might be the first line of
+ // the context header and the first hit was a fluke (impossible imo)
+ // maybe we should return false here because the diff is broken ?
+ }
+
+ return result;
+}
+
+bool ParserBase::parseEdDiffHeader()
+{
+ return false;
+}
+
+bool ParserBase::parseNormalDiffHeader()
+{
+// kDebug(8101) << "ParserBase::parseNormalDiffHeader()";
+ bool result = false;
+
+ while ( m_diffIterator != m_diffLines.end() )
+ {
+ if ( m_normalDiffHeader.exactMatch( *m_diffIterator ) )
+ {
+// kDebug(8101) << "Matched length Header =" << m_normalDiffHeader.matchedLength();
+// kDebug(8101) << "Matched string Header =" << m_normalDiffHeader.cap( 0 );
+
+ m_currentModel = new DiffModel();
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_currentModel->setSourceFile ( m_normalDiffHeader.cap( 1 ) );
+ m_currentModel->setDestinationFile ( m_normalDiffHeader.cap( 2 ) );
+
+ result = true;
+
+ ++m_diffIterator;
+ break;
+ }
+ else
+ {
+ kDebug(8101) << "No match for:" << ( *m_diffIterator );
+ }
+ ++m_diffIterator;
+ }
+
+ if ( result == false )
+ {
+ // Set this to the first line again and hope it is a single file diff
+ m_diffIterator = m_diffLines.begin();
+ m_currentModel = new DiffModel();
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_singleFileDiff = true;
+ }
+
+ return result;
+}
+
+bool ParserBase::parseRCSDiffHeader()
+{
+ return false;
+}
+
+bool ParserBase::parseUnifiedDiffHeader()
+{
+// kDebug(8101) << "ParserBase::parseUnifiedDiffHeader()";
+ bool result = false;
+
+ while ( m_diffIterator != m_diffLines.end() ) // do not assume we start with the diffheader1 line
+ {
+ if ( !m_unifiedDiffHeader1.exactMatch( *m_diffIterator ) )
+ {
+ ++m_diffIterator;
+ continue;
+ }
+// kDebug(8101) << "Matched length Header1 =" << m_unifiedDiffHeader1.matchedLength();
+// kDebug(8101) << "Matched string Header1 =" << m_unifiedDiffHeader1.cap( 0 );
+ ++m_diffIterator;
+ if ( m_diffIterator != m_diffLines.end() && m_unifiedDiffHeader2.exactMatch( *m_diffIterator ) )
+ {
+ m_currentModel = new DiffModel( m_unifiedDiffHeader1.cap( 1 ), m_unifiedDiffHeader2.cap( 1 ) );
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_currentModel->setSourceTimestamp( m_unifiedDiffHeader1.cap( 2 ) );
+ m_currentModel->setSourceRevision( m_unifiedDiffHeader1.cap( 4 ) );
+ m_currentModel->setDestinationTimestamp( m_unifiedDiffHeader2.cap( 2 ) );
+ m_currentModel->setDestinationRevision( m_unifiedDiffHeader2.cap( 4 ) );
+
+ ++m_diffIterator;
+ result = true;
+
+ break;
+ }
+ else
+ {
+ // We're screwed, second line does not match or is not there...
+ break;
+ }
+ }
+
+ return result;
+}
+
+bool ParserBase::parseContextHunkHeader()
+{
+// kDebug(8101) << "ParserBase::parseContextHunkHeader()";
+
+ if ( m_diffIterator == m_diffLines.end() )
+ return false;
+
+ if ( !m_contextHunkHeader1.exactMatch( *(m_diffIterator) ) )
+ return false; // big fat trouble, aborting...
+
+ ++m_diffIterator;
+
+ if ( m_diffIterator == m_diffLines.end() )
+ return false;
+
+ if ( !m_contextHunkHeader2.exactMatch( *(m_diffIterator) ) )
+ return false; // big fat trouble, aborting...
+
+ ++m_diffIterator;
+
+ return true;
+}
+
+bool ParserBase::parseEdHunkHeader()
+{
+ return false;
+}
+
+bool ParserBase::parseNormalHunkHeader()
+{
+// kDebug(8101) << "ParserBase::parseNormalHunkHeader()";
+ if ( m_diffIterator != m_diffLines.end() )
+ {
+// kDebug(8101) << "Header =" << *m_diffIterator;
+ if ( m_normalHunkHeaderAdded.exactMatch( *m_diffIterator ) )
+ {
+ m_normalDiffType = Difference::Insert;
+ }
+ else if ( m_normalHunkHeaderRemoved.exactMatch( *m_diffIterator ) )
+ {
+ m_normalDiffType = Difference::Delete;
+ }
+ else if ( m_normalHunkHeaderChanged.exactMatch( *m_diffIterator ) )
+ {
+ m_normalDiffType = Difference::Change;
+ }
+ else
+ return false;
+
+ ++m_diffIterator;
+ return true;
+ }
+
+ return false;
+}
+
+bool ParserBase::parseRCSHunkHeader()
+{
+ return false;
+}
+
+bool ParserBase::parseUnifiedHunkHeader()
+{
+// kDebug(8101) << "ParserBase::parseUnifiedHunkHeader()";
+ if( m_diffIterator == m_diffLines.end() ) return false;
+
+ if ( m_unifiedHunkHeader.exactMatch( *m_diffIterator ) )
+ {
+ ++m_diffIterator;
+ return true;
+ }
+ else
+ {
+// kDebug(8101) << "This is not a unified hunk header :" << (*m_diffIterator);
+ return false;
+ }
+
+}
+
+bool ParserBase::parseContextHunkBody()
+{
+// kDebug(8101) << "ParserBase::parseContextHunkBody()";
+
+ // Storing the src part of the hunk for later use
+ QStringList oldLines;
+ for( ; m_diffIterator != m_diffLines.end() && m_contextHunkBodyLine.exactMatch( *m_diffIterator ); ++m_diffIterator ) {
+// kDebug(8101) << "Added old line:" << *m_diffIterator;
+ oldLines.append( *m_diffIterator );
+ }
+
+ if( !m_contextHunkHeader3.exactMatch( *m_diffIterator ) )
+ return false;
+
+ ++m_diffIterator;
+
+ // Storing the dest part of the hunk for later use
+ QStringList newLines;
+ for( ; m_diffIterator != m_diffLines.end() && m_contextHunkBodyLine.exactMatch( *m_diffIterator ); ++m_diffIterator ) {
+// kDebug(8101) << "Added new line:" << *m_diffIterator;
+ newLines.append( *m_diffIterator );
+ }
+
+ QString function = m_contextHunkHeader1.cap( 1 );
+// kDebug(8101) << "Captured function:" << function;
+ int linenoA = m_contextHunkHeader2.cap( 1 ).toInt();
+// kDebug(8101) << "Source line number:" << linenoA;
+ int linenoB = m_contextHunkHeader3.cap( 1 ).toInt();
+// kDebug(8101) << "Dest line number:" << linenoB;
+
+ DiffHunk* hunk = new DiffHunk( linenoA, linenoB, function );
+
+ m_currentModel->addHunk( hunk );
+
+ QStringList::Iterator oldIt = oldLines.begin();
+ QStringList::Iterator newIt = newLines.begin();
+
+ Difference* diff;
+ while( oldIt != oldLines.end() || newIt != newLines.end() )
+ {
+ if( oldIt != oldLines.end() && m_contextHunkBodyRemoved.exactMatch( *oldIt ) )
+ {
+// kDebug(8101) << "Delete:";
+ diff = new Difference( linenoA, linenoB );
+ diff->setType( Difference::Delete );
+ m_currentModel->addDiff( diff );
+// kDebug(8101) << "Difference added";
+ hunk->add( diff );
+ for( ; oldIt != oldLines.end() && m_contextHunkBodyRemoved.exactMatch( *oldIt ); ++oldIt )
+ {
+// kDebug(8101) << "" << m_contextHunkBodyRemoved.cap( 1 );
+ diff->addSourceLine( m_contextHunkBodyRemoved.cap( 1 ) );
+ linenoA++;
+ }
+ }
+ else if( newIt != newLines.end() && m_contextHunkBodyAdded.exactMatch( *newIt ) )
+ {
+// kDebug(8101) << "Insert:";
+ diff = new Difference( linenoA, linenoB );
+ diff->setType( Difference::Insert );
+ m_currentModel->addDiff( diff );
+// kDebug(8101) << "Difference added";
+ hunk->add( diff );
+ for( ; newIt != newLines.end() && m_contextHunkBodyAdded.exactMatch( *newIt ); ++newIt )
+ {
+// kDebug(8101) << "" << m_contextHunkBodyAdded.cap( 1 );
+ diff->addDestinationLine( m_contextHunkBodyAdded.cap( 1 ) );
+ linenoB++;
+ }
+ }
+ else if( ( oldIt == oldLines.end() || m_contextHunkBodyContext.exactMatch( *oldIt ) ) &&
+ ( newIt == newLines.end() || m_contextHunkBodyContext.exactMatch( *newIt ) ) )
+ {
+// kDebug(8101) << "Unchanged:";
+ diff = new Difference( linenoA, linenoB );
+ // Do not add this diff with addDiff to the model... no unchanged differences allowed in there...
+ diff->setType( Difference::Unchanged );
+ hunk->add( diff );
+ while( ( oldIt == oldLines.end() || m_contextHunkBodyContext.exactMatch( *oldIt ) ) &&
+ ( newIt == newLines.end() || m_contextHunkBodyContext.exactMatch( *newIt ) ) &&
+ ( oldIt != oldLines.end() || newIt != newLines.end() ) )
+ {
+ QString l;
+ if( oldIt != oldLines.end() )
+ {
+ l = m_contextHunkBodyContext.cap( 1 );
+// kDebug(8101) << "old:" << l;
+ ++oldIt;
+ }
+ if( newIt != newLines.end() )
+ {
+ l = m_contextHunkBodyContext.cap( 1 );
+// kDebug(8101) << "new:" << l;
+ ++newIt;
+ }
+ diff->addSourceLine( l );
+ diff->addDestinationLine( l );
+ linenoA++;
+ linenoB++;
+ }
+ }
+ else if( ( oldIt != oldLines.end() && m_contextHunkBodyChanged.exactMatch( *oldIt ) ) ||
+ ( newIt != newLines.end() && m_contextHunkBodyChanged.exactMatch( *newIt ) ) )
+ {
+// kDebug(8101) << "Changed:";
+ diff = new Difference( linenoA, linenoB );
+ diff->setType( Difference::Change );
+ m_currentModel->addDiff( diff );
+// kDebug(8101) << "Difference added";
+ hunk->add( diff );
+ while( oldIt != oldLines.end() && m_contextHunkBodyChanged.exactMatch( *oldIt ) )
+ {
+// kDebug(8101) << "" << m_contextHunkBodyChanged.cap( 1 );
+ diff->addSourceLine( m_contextHunkBodyChanged.cap( 1 ) );
+ linenoA++;
+ ++oldIt;
+ }
+ while( newIt != newLines.end() && m_contextHunkBodyChanged.exactMatch( *newIt ) )
+ {
+// kDebug(8101) << "" << m_contextHunkBodyChanged.cap( 1 );
+ diff->addDestinationLine( m_contextHunkBodyChanged.cap( 1 ) );
+ linenoB++;
+ ++newIt;
+ }
+ }
+ else
+ return false;
+ diff->determineInlineDifferences();
+ }
+
+ return true;
+}
+
+bool ParserBase::parseEdHunkBody()
+{
+ return false;
+}
+
+bool ParserBase::parseNormalHunkBody()
+{
+// kDebug(8101) << "ParserBase::parseNormalHunkBody";
+
+ QString type;
+
+ int linenoA = 0, linenoB = 0;
+
+ if ( m_normalDiffType == Difference::Insert )
+ {
+ linenoA = m_normalHunkHeaderAdded.cap( 1 ).toInt();
+ linenoB = m_normalHunkHeaderAdded.cap( 2 ).toInt();
+ }
+ else if ( m_normalDiffType == Difference::Delete )
+ {
+ linenoA = m_normalHunkHeaderRemoved.cap( 1 ).toInt();
+ linenoB = m_normalHunkHeaderRemoved.cap( 3 ).toInt();
+ }
+ else if ( m_normalDiffType == Difference::Change )
+ {
+ linenoA = m_normalHunkHeaderChanged.cap( 1 ).toInt();
+ linenoB = m_normalHunkHeaderChanged.cap( 3 ).toInt();
+ }
+
+ DiffHunk* hunk = new DiffHunk( linenoA, linenoB );
+ m_currentModel->addHunk( hunk );
+ Difference* diff = new Difference( linenoA, linenoB );
+ hunk->add( diff );
+ m_currentModel->addDiff( diff );
+
+ diff->setType( m_normalDiffType );
+
+ if ( m_normalDiffType == Difference::Change || m_normalDiffType == Difference::Delete )
+ for( ; m_diffIterator != m_diffLines.end() && m_normalHunkBodyRemoved.exactMatch( *m_diffIterator ); ++m_diffIterator )
+ {
+// kDebug(8101) << "Line =" << *m_diffIterator;
+ diff->addSourceLine( m_normalHunkBodyRemoved.cap( 1 ) );
+ }
+ if ( m_normalDiffType == Difference::Change )
+ if( m_diffIterator != m_diffLines.end() && m_normalHunkBodyDivider.exactMatch( *m_diffIterator ) )
+ {
+// kDebug(8101) << "Line =" << *m_diffIterator;
+ ++m_diffIterator;
+ }
+ else
+ return false;
+ if ( m_normalDiffType == Difference::Insert || m_normalDiffType == Difference::Change )
+ for( ; m_diffIterator != m_diffLines.end() && m_normalHunkBodyAdded.exactMatch( *m_diffIterator ); ++m_diffIterator )
+ {
+// kDebug(8101) << "Line =" << *m_diffIterator;
+ diff->addDestinationLine( m_normalHunkBodyAdded.cap( 1 ) );
+ }
+
+ return true;
+}
+
+bool ParserBase::parseRCSHunkBody()
+{
+ return false;
+}
+
+bool ParserBase::matchesUnifiedHunkLine( QString line ) const
+{
+ static const QChar context( ' ' );
+ static const QChar added ( '+' );
+ static const QChar removed( '-' );
+
+ QChar first = line[0];
+
+ return ( first == context || first == added || first == removed );
+}
+
+bool ParserBase::parseUnifiedHunkBody()
+{
+// kDebug(8101) << "ParserBase::parseUnifiedHunkBody";
+
+ int linenoA = 0, linenoB = 0;
+
+ // Fetching the stuff we need from the hunkheader regexp that was parsed in parseUnifiedHunkHeader();
+ linenoA = m_unifiedHunkHeader.cap( 1 ).toInt();
+ linenoB = m_unifiedHunkHeader.cap( 4 ).toInt();
+ QString function = m_unifiedHunkHeader.cap( 7 );
+ for ( int i = 0; i < 9; i++ )
+ {
+// kDebug(8101) << "Capture" << i << ":" << m_unifiedHunkHeader.cap( i );
+ }
+
+ DiffHunk* hunk = new DiffHunk( linenoA, linenoB, function );
+ m_currentModel->addHunk( hunk );
+
+ const QStringList::ConstIterator m_diffLinesEnd = m_diffLines.end();
+
+ const QString context = QString( " " );
+ const QString added = QString( "+" );
+ const QString removed = QString( "-" );
+
+ while( m_diffIterator != m_diffLinesEnd && matchesUnifiedHunkLine( *m_diffIterator ) )
+ {
+ Difference* diff = new Difference( linenoA, linenoB );
+ hunk->add( diff );
+
+ if( (*m_diffIterator).startsWith( context ) )
+ { // context
+ for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( context ); ++m_diffIterator )
+ {
+ diff->addSourceLine( QString( *m_diffIterator ).remove( 0, 1 ) );
+ diff->addDestinationLine( QString( *m_diffIterator ).remove( 0, 1 ) );
+ linenoA++;
+ linenoB++;
+ }
+ }
+ else
+ { // This is a real difference, not context
+ for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( removed ); ++m_diffIterator )
+ {
+ diff->addSourceLine( QString( *m_diffIterator ).remove( 0, 1 ) );
+ linenoA++;
+ }
+ for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( added ); ++m_diffIterator )
+ {
+ diff->addDestinationLine( QString( *m_diffIterator ).remove( 0, 1 ) );
+ linenoB++;
+ }
+ if ( diff->sourceLineCount() == 0 )
+ {
+ diff->setType( Difference::Insert );
+// kDebug(8101) << "Insert difference";
+ }
+ else if ( diff->destinationLineCount() == 0 )
+ {
+ diff->setType( Difference::Delete );
+// kDebug(8101) << "Delete difference";
+ }
+ else
+ {
+ diff->setType( Difference::Change );
+// kDebug(8101) << "Change difference";
+ }
+ diff->determineInlineDifferences();
+ m_currentModel->addDiff( diff );
+ }
+ }
+
+ return true;
+}
+
+DiffModelList* ParserBase::parseContext()
+{
+ while ( parseContextDiffHeader() )
+ {
+ while ( parseContextHunkHeader() )
+ parseContextHunkBody();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ m_models->sort();
+
+ if ( m_models->count() > 0 )
+ {
+ return m_models;
+ }
+ else
+ {
+ delete m_models;
+ return 0L;
+ }
+}
+
+DiffModelList* ParserBase::parseEd()
+{
+ while ( parseEdDiffHeader() )
+ {
+ while ( parseEdHunkHeader() )
+ parseEdHunkBody();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ m_models->sort();
+
+ if ( m_models->count() > 0 )
+ {
+ return m_models;
+ }
+ else
+ {
+ delete m_models;
+ return 0L;
+ }
+}
+
+DiffModelList* ParserBase::parseNormal()
+{
+ while ( parseNormalDiffHeader() )
+ {
+ while ( parseNormalHunkHeader() )
+ parseNormalHunkBody();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ if ( m_singleFileDiff )
+ {
+ while ( parseNormalHunkHeader() )
+ parseNormalHunkBody();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ m_models->sort();
+
+ if ( m_models->count() > 0 )
+ {
+ return m_models;
+ }
+ else
+ {
+ delete m_models;
+ return 0L;
+ }
+}
+
+DiffModelList* ParserBase::parseRCS()
+{
+ while ( parseRCSDiffHeader() )
+ {
+ while ( parseRCSHunkHeader() )
+ parseRCSHunkBody();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ m_models->sort();
+
+ if ( m_models->count() > 0 )
+ {
+ return m_models;
+ }
+ else
+ {
+ delete m_models;
+ return 0L;
+ }
+}
+
+DiffModelList* ParserBase::parseUnified()
+{
+ while ( parseUnifiedDiffHeader() )
+ {
+ while ( parseUnifiedHunkHeader() )
+ parseUnifiedHunkBody();
+// kDebug(8101) << "New model ready to be analyzed...";
+// kDebug(8101) << "differenceCount() ==" << m_currentModel->differenceCount();
+ if ( m_currentModel->differenceCount() > 0 )
+ m_models->append( m_currentModel );
+ }
+
+ m_models->sort();
+
+ if ( m_models->count() > 0 )
+ {
+ return m_models;
+ }
+ else
+ {
+ delete m_models;
+ return 0L;
+ }
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp (revision 1522570)
@@ -0,0 +1,407 @@
+/***************************************************************************
+ diffmodel.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "diffmodel.h"
+#include <qregexp.h>
+#include <q3valuelist.h>
+
+#include <kdebug.h>
+#include <klocale.h>
+
+#include "difference.h"
+#include "diffhunk.h"
+
+using namespace Diff2;
+
+/** */
+DiffModel::DiffModel( const QString& source, const QString& destination ) :
+ m_source( source ),
+ m_destination( destination ),
+ m_sourcePath( "" ),
+ m_destinationPath( "" ),
+ m_sourceFile( "" ),
+ m_destinationFile( "" ),
+ m_sourceTimestamp( "" ),
+ m_destinationTimestamp( "" ),
+ m_sourceRevision( "" ),
+ m_destinationRevision( "" ),
+ m_appliedCount( 0 ),
+ m_modified( false ),
+ m_diffIndex( 0 ),
+ m_selectedDifference( 0 ),
+ m_blended( false )
+{
+ splitSourceInPathAndFileName();
+ splitDestinationInPathAndFileName();
+}
+
+DiffModel::DiffModel() :
+ m_source( "" ),
+ m_destination( "" ),
+ m_sourcePath( "" ),
+ m_destinationPath( "" ),
+ m_sourceFile( "" ),
+ m_destinationFile( "" ),
+ m_sourceTimestamp( "" ),
+ m_destinationTimestamp( "" ),
+ m_sourceRevision( "" ),
+ m_destinationRevision( "" ),
+ m_appliedCount( 0 ),
+ m_modified( false ),
+ m_diffIndex( 0 ),
+ m_selectedDifference( 0 ),
+ m_blended( false )
+{
+}
+
+/** */
+DiffModel::~DiffModel()
+{
+}
+
+void DiffModel::splitSourceInPathAndFileName()
+{
+ int pos;
+
+ if( ( pos = m_source.lastIndexOf( "/" ) ) >= 0 )
+ m_sourcePath = m_source.mid( 0, pos+1 );
+
+ if( ( pos = m_source.lastIndexOf( "/" ) ) >= 0 )
+ m_sourceFile = m_source.mid( pos+1, m_source.length() - pos );
+ else
+ m_sourceFile = m_source;
+
+ kDebug(8101) << m_source << "was split into" << m_sourcePath << "and" << m_sourceFile;
+}
+
+void DiffModel::splitDestinationInPathAndFileName()
+{
+ int pos;
+
+ if( ( pos = m_destination.lastIndexOf( "/" ) )>= 0 )
+ m_destinationPath = m_destination.mid( 0, pos+1 );
+
+ if( ( pos = m_destination.lastIndexOf( "/" ) ) >= 0 )
+ m_destinationFile = m_destination.mid( pos+1, m_destination.length() - pos );
+ else
+ m_destinationFile = m_source;
+
+ kDebug(8101) << m_destination << "was split into" << m_destinationPath << "and" << m_destinationFile;
+}
+
+DiffModel& DiffModel::operator=( const DiffModel& model )
+{
+ if ( &model != this ) // Guard from self-assignment
+ {
+ m_source = model.m_source;
+ m_destination = model.m_destination;
+ m_sourcePath = model.m_sourcePath;
+ m_sourceFile = model.m_sourceFile;
+ m_sourceTimestamp = model.m_sourceTimestamp;
+ m_sourceRevision = model.m_sourceRevision;
+ m_destinationPath = model.m_destinationPath;
+ m_destinationFile = model.m_destinationFile;
+ m_destinationTimestamp = model.m_destinationTimestamp;
+ m_destinationRevision = model.m_destinationRevision;
+ m_appliedCount = model.m_appliedCount;
+ m_modified = model.m_modified;
+
+ m_diffIndex = model.m_diffIndex;
+ m_selectedDifference = model.m_selectedDifference;
+ }
+
+ return *this;
+}
+
+bool DiffModel::operator<( const DiffModel& model )
+{
+ if ( localeAwareCompareSource( model ) < 0 )
+ return true;
+ return false;
+}
+
+int DiffModel::localeAwareCompareSource( const DiffModel& model )
+{
+ int result = m_sourcePath.localeAwareCompare( model.m_sourcePath );
+
+ if ( result == 0 )
+ return m_sourceFile.localeAwareCompare( model.m_sourceFile );
+
+ return result;
+}
+
+QString DiffModel::recreateDiff() const
+{
+ // For now we'll always return a diff in the diff format
+ QString diff;
+
+ // recreate header
+ QString tab = QString::fromLatin1( "\t" );
+ QString nl = QString::fromLatin1( "\n" );
+ diff += QString::fromLatin1( "--- %1\t%2" ).arg( m_source ).arg( m_sourceTimestamp );
+ if ( !m_sourceRevision.isEmpty() )
+ diff += tab + m_sourceRevision;
+ diff += nl;
+ diff += QString::fromLatin1( "+++ %1\t%2" ).arg( m_destination ).arg( m_destinationTimestamp );
+ if ( !m_destinationRevision.isEmpty() )
+ diff += tab + m_destinationRevision;
+ diff += nl;
+
+ // recreate body by iterating over the hunks
+ DiffHunkListConstIterator hunkIt = m_hunks.begin();
+ DiffHunkListConstIterator hEnd = m_hunks.end();
+
+ for ( ; hunkIt != hEnd; ++hunkIt )
+ {
+ if ((*hunkIt)->type() != DiffHunk::AddedByBlend)
+ diff += (*hunkIt)->recreateHunk();
+ }
+
+ return diff;
+}
+
+DifferenceList* DiffModel::allDifferences()
+{
+ if ( m_hunks.count() != 0 )
+ {
+ DiffHunkListConstIterator hunkIt = m_hunks.begin();
+ DiffHunkListConstIterator hEnd = m_hunks.end();
+
+ for ( ; hunkIt != hEnd; ++hunkIt )
+ {
+ DiffHunk* hunk = *hunkIt;
+
+ DifferenceListConstIterator diffIt = hunk->differences().begin();
+ DifferenceListConstIterator dEnd = hunk->differences().end();
+
+ for ( ; diffIt != dEnd; ++diffIt )
+ {
+ m_allDifferences.append( *diffIt );
+ }
+ }
+ return &m_allDifferences;
+ }
+ else
+ {
+ DifferenceList *diffList = new DifferenceList;
+ return diffList;
+ }
+}
+
+Difference* DiffModel::firstDifference()
+{
+ kDebug( 8101 ) << "DiffModel::firstDifference()";
+ m_diffIndex = 0;
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+
+ m_selectedDifference = m_differences[ m_diffIndex ];
+
+ return m_selectedDifference;
+}
+
+Difference* DiffModel::lastDifference()
+{
+ kDebug( 8101 ) << "DiffModel::lastDifference()";
+ m_diffIndex = m_differences.count() - 1;
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+
+ m_selectedDifference = m_differences[ m_diffIndex ];
+
+ return m_selectedDifference;
+}
+
+Difference* DiffModel::prevDifference()
+{
+ kDebug( 8101 ) << "DiffModel::prevDifference()";
+ if ( --m_diffIndex < m_differences.count() )
+ {
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+ m_selectedDifference = m_differences[ m_diffIndex ];
+ }
+ else
+ {
+ m_selectedDifference = 0;
+ m_diffIndex = 0;
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+ }
+
+ return m_selectedDifference;
+}
+
+Difference* DiffModel::nextDifference()
+{
+ kDebug( 8101 ) << "DiffModel::nextDifference()";
+ if ( ++m_diffIndex < m_differences.count() )
+ {
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+ m_selectedDifference = m_differences[ m_diffIndex ];
+ }
+ else
+ {
+ m_selectedDifference = 0;
+ m_diffIndex = 0; // just for safety...
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+ }
+
+ return m_selectedDifference;
+}
+
+const QString DiffModel::sourceFile() const
+{
+ return m_sourceFile;
+}
+
+const QString DiffModel::destinationFile() const
+{
+ return m_destinationFile;
+}
+
+const QString DiffModel::sourcePath() const
+{
+ return m_sourcePath;
+}
+
+const QString DiffModel::destinationPath() const
+{
+ return m_destinationPath;
+}
+
+void DiffModel::setSourceFile( const QString& path )
+{
+ m_source = path;
+ splitSourceInPathAndFileName();
+}
+
+void DiffModel::setDestinationFile( const QString& path )
+{
+ m_destination = path;
+ splitDestinationInPathAndFileName();
+}
+
+void DiffModel::setSourceTimestamp( const QString& timestamp )
+{
+ m_sourceTimestamp = timestamp;
+}
+
+void DiffModel::setDestinationTimestamp( const QString& timestamp )
+{
+ m_destinationTimestamp = timestamp;
+}
+
+void DiffModel::setSourceRevision( const QString& revision )
+{
+ m_destinationRevision = revision;
+}
+
+void DiffModel::setDestinationRevision( const QString& revision )
+{
+ m_destinationRevision = revision;
+}
+
+void DiffModel::addHunk( DiffHunk* hunk )
+{
+ m_hunks.append( hunk );
+}
+
+void DiffModel::addDiff( Difference* diff )
+{
+ m_differences.append( diff );
+}
+
+void DiffModel::applyDifference( bool apply )
+{
+ if ( apply && !m_selectedDifference->applied() )
+ m_appliedCount++;
+ else if ( !apply && m_selectedDifference->applied() )
+ m_appliedCount--;
+
+ bool modified;
+
+ // Not setting the m_modified yet so i can still query the current
+ // modified status from the slot that is connected to the signal
+ if ( m_appliedCount == 0 )
+ modified = false;
+ else
+ modified = true;
+
+ emit setModified( modified );
+
+ m_modified = modified;
+
+ m_selectedDifference->apply( apply );
+}
+
+void DiffModel::applyAllDifferences( bool apply )
+{
+ bool modified;
+
+ // Not setting the m_modified yet so i can still query the current
+ // modified status from the slot that is connected to the signal
+ if ( apply )
+ {
+ m_appliedCount = m_differences.count();
+ modified = true;
+ }
+ else
+ {
+ m_appliedCount = 0;
+ modified = false;
+ }
+
+ emit setModified( modified );
+
+ m_modified = modified;
+
+ DifferenceListIterator diffIt = m_differences.begin();
+ DifferenceListIterator dEnd = m_differences.end();
+
+ for ( ; diffIt != dEnd; ++diffIt )
+ {
+ (*diffIt)->apply( apply );
+ }
+}
+
+void DiffModel::slotSetModified( bool modified )
+{
+ // Not setting the m_modified yet so i can still query the current
+ // modified status from the slot that is connected to the signal
+ emit setModified( modified );
+
+ m_modified = modified;
+}
+
+bool DiffModel::setSelectedDifference( Difference* diff )
+{
+ kDebug(8101) << "diff =" << diff;
+ kDebug(8101) << "m_selectedDifference =" << m_selectedDifference;
+
+ if ( diff != m_selectedDifference )
+ {
+ if ( ( findItem( diff, m_differences ) ) == -1 )
+ return false;
+ // Do not set m_diffIndex if it cant be found
+ m_diffIndex = findItem( diff, m_differences );
+ kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
+ m_selectedDifference = diff;
+ }
+
+ return true;
+}
+
+#include "diffmodel.moc"
+
+/* vim: set ts=4 sw=4 noet: */
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h (revision 1522570)
@@ -0,0 +1,66 @@
+/***************************************************************************
+ diffsettings.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef DIFFSETTINGS_H
+#define DIFFSETTINGS_H
+
+#include <qstringlist.h>
+#include <qwidget.h>
+
+#include "kompare.h"
+#include "settingsbase.h"
+
+#include "diffexport.h"
+
+class DIFF2_EXPORT DiffSettings : public SettingsBase
+{
+Q_OBJECT
+public:
+ DiffSettings( QWidget* parent );
+ virtual ~DiffSettings();
+public:
+ // some virtual functions that will be overloaded from the base class
+ virtual void loadSettings( KConfig* config );
+ virtual void saveSettings( KConfig* config );
+
+public:
+ QString m_diffProgram;
+ int m_linesOfContext;
+ Kompare::Format m_format;
+ bool m_largeFiles; // -H
+ bool m_ignoreWhiteSpace; // -b
+ bool m_ignoreAllWhiteSpace; // -w
+ bool m_ignoreEmptyLines; // -B
+ bool m_ignoreChangesDueToTabExpansion; // -E
+ bool m_createSmallerDiff; // -d
+ bool m_ignoreChangesInCase; // -i
+ bool m_showCFunctionChange; // -p
+ bool m_convertTabsToSpaces; // -t
+ bool m_ignoreRegExp; // -I
+ QString m_ignoreRegExpText; // the RE for -I
+ QStringList m_ignoreRegExpTextHistory;
+ bool m_recursive; // -r
+ bool m_newFiles; // -N
+// bool m_allText; // -a
+ bool m_excludeFilePattern; // -x
+ QStringList m_excludeFilePatternList; // The list of patterns for -x
+ bool m_excludeFilesFile; // -X
+ QString m_excludeFilesFileURL; // The filename to -X
+ QStringList m_excludeFilesFileHistoryList; // The history list of filenames
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h (revision 1522570)
@@ -0,0 +1,223 @@
+/***************************************************************************
+ difference.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef DIFFERENCE_H
+#define DIFFERENCE_H
+
+#include <q3valuelist.h>
+#include <q3valuevector.h>
+
+#include <kdebug.h>
+
+#include "diffexport.h"
+
+class QString;
+
+namespace Diff2
+{
+
+class LevenshteinTable;
+
+class Marker
+{
+public:
+ enum Type { Start = 0, End = 1 };
+
+public:
+ Marker()
+ {
+ m_type = Marker::Start;
+ m_offset = 0;
+ }
+ Marker( enum Marker::Type type, unsigned int offset )
+ {
+ m_type = type;
+ m_offset = offset;
+ }
+ ~Marker() {}
+
+public:
+ enum Marker::Type type() const { return m_type; }
+ unsigned int offset() const { return m_offset; }
+
+ void setType ( enum Marker::Type type ) { m_type = type; }
+ void setOffset( unsigned int offset ) { m_offset = offset; }
+
+private:
+ enum Marker::Type m_type;
+ unsigned int m_offset;
+};
+
+typedef Q3ValueList<Marker*> MarkerList;
+typedef Q3ValueList<Marker*>::iterator MarkerListIterator;
+typedef Q3ValueList<Marker*>::const_iterator MarkerListConstIterator;
+
+class DifferenceString
+{
+public:
+ DifferenceString()
+ {
+// kDebug(8101) << "DifferenceString::DifferenceString()";
+ }
+ explicit DifferenceString( const QString& string, const MarkerList& markerList = MarkerList() ) :
+ m_string( string ),
+ m_markerList( markerList )
+ {
+// kDebug(8101) << "DifferenceString::DifferenceString( " << string << ", " << markerList << " )";
+ calculateHash();
+ }
+ DifferenceString( const DifferenceString& ds ) :
+ m_string( ds.m_string ),
+ m_conflict( ds.m_conflict ),
+ m_hash( ds.m_hash ),
+ m_markerList( ds.m_markerList )
+ {
+// kDebug(8101) << "DifferenceString::DifferenceString( const DifferenceString& " << ds << " )";
+ }
+ ~DifferenceString() {}
+
+public:
+ const QString& string() const
+ {
+ return m_string;
+ }
+ const QString& conflictString() const
+ {
+ return m_conflict;
+ }
+ const MarkerList& markerList()
+ {
+ return m_markerList;
+ }
+ void setString( const QString& string )
+ {
+ m_string = string;
+ calculateHash();
+ }
+ void setConflictString( const QString& conflict )
+ {
+ m_conflict = conflict;
+ }
+ void setMarkerList( const MarkerList& markerList )
+ {
+ m_markerList = markerList;
+ }
+ void prepend( Marker* marker )
+ {
+ m_markerList.prepend( marker );
+ }
+ bool operator==( const DifferenceString& ks )
+ {
+ if ( m_hash != ks.m_hash )
+ return false;
+ return m_string == ks.m_string;
+ }
+
+protected:
+ void calculateHash()
+ {
+ unsigned short const* str = reinterpret_cast<unsigned short const*>( m_string.unicode() );
+ const unsigned int len = m_string.length();
+
+ m_hash = 1315423911;
+
+ for ( unsigned int i = 0; i < len; i++ )
+ {
+ m_hash ^= ( m_hash << 5 ) + str[i] + ( m_hash >> 2 );
+ }
+ }
+
+private:
+ QString m_string;
+ QString m_conflict;
+ unsigned int m_hash;
+ MarkerList m_markerList;
+};
+
+typedef Q3ValueVector<DifferenceString*> DifferenceStringList;
+typedef Q3ValueVector<DifferenceString*>::iterator DifferenceStringListIterator;
+typedef Q3ValueVector<DifferenceString*>::const_iterator DifferenceStringListConstIterator;
+
+class DIFF2_EXPORT Difference
+{
+public:
+ enum Type { Change, Insert, Delete, Unchanged };
+
+public:
+ Difference( int sourceLineNo, int destinationLineNo, int type = Difference::Unchanged );
+ ~Difference();
+
+public:
+ int type() const { return m_type; };
+
+ int sourceLineNumber() const { return m_sourceLineNo; }
+ int destinationLineNumber() const { return m_destinationLineNo; }
+
+ int sourceLineCount() const;
+ int destinationLineCount() const;
+
+ DifferenceString* sourceLineAt( int i ) { return m_sourceLines[ i ]; }
+ DifferenceString* destinationLineAt( int i ) { return m_destinationLines[ i ]; }
+
+ const DifferenceStringList sourceLines() const { return m_sourceLines; }
+ const DifferenceStringList destinationLines() const { return m_destinationLines; }
+
+ bool hasConflict() const
+ {
+ return m_conflicts;
+ }
+ void setConflict( bool conflicts )
+ {
+ m_conflicts = conflicts;
+ }
+
+ void apply( bool apply );
+ bool applied() const { return m_applied; }
+
+ void setType( int type ) { m_type = type; }
+
+ void addSourceLine( const QString& line );
+ void addDestinationLine( const QString& line );
+
+ /** This method will calculate the differences between the individual strings and store them as Markers */
+ void determineInlineDifferences();
+
+ QString recreateDifference() const;
+
+private:
+ int m_type;
+
+ int m_sourceLineNo;
+ int m_destinationLineNo;
+
+ DifferenceStringList m_sourceLines;
+ DifferenceStringList m_destinationLines;
+
+ bool m_applied;
+ bool m_conflicts;
+
+ LevenshteinTable* m_table;
+};
+
+typedef Q3ValueList<Difference*> DifferenceList;
+typedef Q3ValueList<Difference*>::iterator DifferenceListIterator;
+typedef Q3ValueList<Difference*>::const_iterator DifferenceListConstIterator;
+
+} // End of namespace Diff2
+
+#endif
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h (revision 1522570)
@@ -0,0 +1,175 @@
+/***************************************************************************
+ diffmodel.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef DIFFMODEL_H
+#define DIFFMODEL_H
+
+#include <qobject.h>
+#include <qstringlist.h>
+
+#include "diffhunk.h"
+#include "kompare.h"
+
+#include "diffexport.h"
+
+namespace Diff2
+{
+
+ template<class Container, class Item>
+ int findItem( const Item& item, const Container* container ) {
+ int i = 0;
+ foreach( Item it, *container ) {
+ if( it == item )
+ return i;
+ i++;
+ }
+ return -1;
+ }
+
+template<class Pointer>
+int findItem( const Pointer* item, const DifferenceList& container ) {
+ int i = 0;
+ foreach( Difference* it, container ) {
+ if( it == item )
+ return i;
+ i++;
+ }
+ return -1;
+}
+
+class DiffHunk;
+class Difference;
+
+class DIFF2_EXPORT DiffModel : public QObject
+{
+Q_OBJECT
+public:
+
+ DiffModel( const QString& srcBaseURL, const QString& destBaseURL );
+ DiffModel();
+ DiffModel( const DiffModel& ) : QObject() {};
+ ~DiffModel();
+
+ int parseDiff( enum Kompare::Format format, const QStringList& list );
+
+ QString recreateDiff() const;
+
+ int hunkCount() const { return m_hunks.count(); }
+ int differenceCount() const { return m_differences.count(); }
+ int appliedCount() const { return m_appliedCount; }
+
+ DiffHunk* hunkAt( int i ) { return *( m_hunks.at( i ) ); }
+ const Difference* differenceAt( int i ) { return *( m_differences.at( i ) ); }
+
+ DiffHunkList* hunks() { return &m_hunks; }
+ const DiffHunkList* hunks() const { return &m_hunks; }
+ DifferenceList* differences() { return &m_differences; }
+ const DifferenceList* differences() const { return &m_differences; }
+
+ DifferenceList* allDifferences();
+
+ int findDifference( Difference* diff ) const {
+ return findItem( diff, m_differences );
+ }
+ //return m_differences.( diff ); }
+
+ Difference* firstDifference();
+ Difference* lastDifference();
+ Difference* prevDifference();
+ Difference* nextDifference();
+
+ const QString source() const { return m_source; }
+ const QString destination() const { return m_destination; }
+ const QString sourceFile() const;
+ const QString destinationFile() const;
+ const QString sourcePath() const;
+ const QString destinationPath() const;
+ const QString sourceTimestamp() const { return m_sourceTimestamp; }
+ const QString destinationTimestamp() const { return m_destinationTimestamp; }
+ const QString sourceRevision() const { return m_sourceRevision; }
+ const QString destinationRevision() const { return m_destinationRevision; }
+
+ void setSourceFile( const QString& path );
+ void setDestinationFile( const QString& path );
+ void setSourceTimestamp( const QString& timestamp );
+ void setDestinationTimestamp( const QString& timestamp );
+ void setSourceRevision( const QString& revision );
+ void setDestinationRevision( const QString& revision );
+
+ void addHunk( DiffHunk* hunk );
+ void addDiff( Difference* diff );
+ bool isModified() const { return m_modified; }
+
+ const int diffIndex( void ) const { return m_diffIndex; }
+ void setDiffIndex( int diffIndex ) { m_diffIndex = diffIndex; }
+
+ void applyDifference( bool apply );
+ void applyAllDifferences( bool apply );
+
+ bool setSelectedDifference( Difference* diff );
+
+ DiffModel& operator=( const DiffModel& model );
+ bool operator<( const DiffModel& model );
+
+ int localeAwareCompareSource( const DiffModel& model );
+
+ bool isBlended() const { return m_blended; }
+ void setBlended( bool blended ) { m_blended = blended; }
+
+signals:
+ void setModified( bool modified );
+
+public slots:
+ void slotSetModified( bool modified );
+
+private:
+ void splitSourceInPathAndFileName();
+ void splitDestinationInPathAndFileName();
+
+private:
+ QString m_source;
+ QString m_destination;
+
+ QString m_sourcePath;
+ QString m_destinationPath;
+
+ QString m_sourceFile;
+ QString m_destinationFile;
+
+ QString m_sourceTimestamp;
+ QString m_destinationTimestamp;
+
+ QString m_sourceRevision;
+ QString m_destinationRevision;
+
+ DiffHunkList m_hunks;
+ DifferenceList m_differences;
+ DifferenceList m_allDifferences;
+
+ int m_appliedCount;
+ bool m_modified;
+
+ unsigned int m_diffIndex;
+ Difference* m_selectedDifference;
+
+ bool m_blended;
+};
+
+} // End of namespace Diff2
+
+#endif
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h (revision 1522570)
@@ -0,0 +1,37 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef DIFFEXPORT_H
+#define DIFFEXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+#ifndef DIFF2_EXPORT
+# ifdef MAKE_DIFF2_LIB
+# define DIFF2_EXPORT KDE_EXPORT
+# else
+# define DIFF2_EXPORT KDE_IMPORT
+# endif
+#endif
+
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h (revision 1522570)
@@ -0,0 +1,213 @@
+/***************************************************************************
+ komparemodellist.h - description
+ -------------------
+ begin : Tue Jun 26 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KOMPAREMODELLIST_H
+#define KOMPAREMODELLIST_H
+
+#include <qobject.h>
+
+#include "diffmodel.h"
+#include "diffmodellist.h"
+#include "kompare.h"
+
+#include "diffexport.h"
+
+class QFile;
+
+class KAction;
+class KDirWatch;
+class K3TempFile;
+
+class DiffSettings;
+class KompareProcess;
+
+namespace Diff2
+{
+
+class DIFF2_EXPORT KompareModelList : public QObject
+{
+ Q_OBJECT
+public:
+ KompareModelList( DiffSettings* diffSettings, struct Kompare::Info& info, QObject* parent = 0, const char* name = 0 );
+ ~KompareModelList();
+
+public:
+ // Swap source with destination and show differences
+ void swap();
+
+ /* Comparing methods */
+ bool compare( const QString& source, const QString& destination );
+
+ bool compareFiles( const QString& source, const QString& destination );
+ bool compareDirs( const QString& source, const QString& destination );
+
+ bool openDiff( const QString& diff );
+
+ bool openFileAndDiff( const QString& file, const QString& diff );
+ bool openDirAndDiff( const QString& dir, const QString& diff );
+
+ bool saveDiff( const QString& url, const QString& directory, DiffSettings* diffSettings );
+ bool saveAll();
+
+ bool saveDestination( DiffModel* model );
+
+ void setEncoding( const QString& encoding );
+
+ QString recreateDiff() const;
+
+ // This parses the difflines and creates new models
+ int parseDiffOutput( const QString& diff );
+
+ // Call this to emit the signals to the rest of the "world" to show the diff
+ void show();
+
+ // This will blend the original URL (dir or file) into the diffmodel,
+ // this is like patching but with a twist
+ bool blendOriginalIntoModelList( const QString& localURL );
+
+ enum Kompare::Mode mode() const { return m_info.mode; };
+ const DiffModelList* models() const { return m_models; };
+
+ int modelCount() const;
+ int differenceCount() const;
+ int appliedCount() const;
+
+ const DiffModel* modelAt( int i ) const { return *( m_models->at( i ) ); };
+ int findModel( DiffModel* model ) const { return findItem( model, m_models ); };
+
+ bool isModified() const;
+
+ int currentModel() const { return findItem( m_selectedModel, m_models ); };
+ int currentDifference() const { return m_selectedModel ? m_selectedModel->findDifference( m_selectedDifference ) : -1; };
+
+ const DiffModel* selectedModel() const { return m_selectedModel; };
+ const Difference* selectedDifference() const { return m_selectedDifference; };
+
+ void clear();
+
+private:
+ Diff2::DiffModel* firstModel();
+ Diff2::DiffModel* lastModel();
+ Diff2::DiffModel* prevModel();
+ Diff2::DiffModel* nextModel();
+
+ bool setSelectedModel( Diff2::DiffModel* model );
+
+ void updateModelListActions();
+
+protected:
+ bool blendFile( DiffModel* model, const QString& lines );
+
+signals:
+ void status( Kompare::Status status );
+ void setStatusBarModelInfo( int modelIndex, int differenceIndex, int modelCount, int differenceCount, int appliedCount );
+ void error( QString error );
+ void modelsChanged( const Diff2::DiffModelList* models );
+ void setSelection( const Diff2::DiffModel* model, const Diff2::Difference* diff );
+ void setSelection( const Diff2::Difference* diff );
+ void applyDifference( bool apply );
+ void applyAllDifferences( bool apply );
+ void applyDifference( const Diff2::Difference* diff, bool apply );
+
+ // Emits true when m_noOfModified > 0, false when m_noOfModified == 0
+ void setModified( bool modified );
+
+public slots:
+ void slotSelectionChanged( const Diff2::DiffModel* model, const Diff2::Difference* diff );
+ void slotSelectionChanged( const Diff2::Difference* diff );
+
+ void slotApplyDifference( bool apply );
+ void slotApplyAllDifferences( bool apply );
+ void slotPreviousModel();
+ void slotNextModel();
+ void slotPreviousDifference();
+ void slotNextDifference();
+
+ // This slot is called by the diffmodels whenever their status changes to modified or unmodified
+ void slotSetModified( bool modified );
+
+protected slots:
+ void slotDiffProcessFinished( bool success );
+ void slotWriteDiffOutput( bool success );
+
+ void slotActionApplyDifference();
+ void slotActionUnApplyDifference();
+ void slotActionApplyAllDifferences();
+ void slotActionUnapplyAllDifferences();
+
+ /** Save the currently selected destination in a multi-file diff,
+ or the single destination if a single file diff. */
+ void slotSaveDestination();
+
+private slots:
+ void slotDirectoryChanged( const QString& );
+ void slotFileChanged( const QString& );
+
+private: // Helper methods
+ bool isDirectory( const QString& url ) const;
+ bool isDiff( const QString& mimetype ) const;
+ QString readFile( const QString& fileName );
+
+ bool hasPrevModel() const;
+ bool hasNextModel() const;
+ bool hasPrevDiff() const;
+ bool hasNextDiff() const;
+
+ QStringList split( const QString& diff );
+
+private:
+ K3TempFile* m_diffTemp;
+ QString m_diffURL;
+
+ KompareProcess* m_diffProcess;
+
+ DiffSettings* m_diffSettings;
+
+ DiffModelList* m_models;
+
+ QString m_source;
+ QString m_destination;
+
+ DiffModel* m_selectedModel;
+ Difference* m_selectedDifference;
+
+ KDirWatch* m_dirWatch;
+ KDirWatch* m_fileWatch;
+
+ int m_noOfModified;
+ unsigned int m_modelIndex;
+
+ struct Kompare::Info& m_info;
+
+ KAction* m_applyDifference;
+ KAction* m_unApplyDifference;
+ KAction* m_applyAll;
+ KAction* m_unapplyAll;
+ KAction* m_previousFile;
+ KAction* m_nextFile;
+ KAction* m_previousDifference;
+ KAction* m_nextDifference;
+
+ KAction* m_save;
+
+ QString m_encoding;
+ QTextCodec* m_textCodec;
+};
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp (revision 1522570)
@@ -0,0 +1,1424 @@
+/***************************************************************************
+ komparemodellist.cpp - description
+ -------------------
+ begin : Tue Jun 26 2001
+ copyright : (C) 2001-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "komparemodellist.h"
+#include <qfile.h>
+#include <qdir.h>
+#include <qregexp.h>
+#include <qtextcodec.h>
+#include <q3valuelist.h>
+#include <QTextStream>
+
+#include <kaction.h>
+#include <kcharsets.h>
+#include <kdebug.h>
+#include <kdirwatch.h>
+#include <kio/netaccess.h>
+#include <klocale.h>
+#include <kmimetype.h>
+#include <k3tempfile.h>
+#include <kstdaction.h>
+
+#include "difference.h"
+#include "diffhunk.h"
+#include "diffmodel.h"
+#include "diffmodellist.h"
+#include "kompareprocess.h"
+#include "parser.h"
+#include <assert.h>
+
+//#include "kompareplugin.h"
+
+using namespace Diff2;
+
+KompareModelList::KompareModelList( DiffSettings* diffSettings, struct Kompare::Info& info, QObject* parent, const char* name )
+ : QObject( parent ),
+ m_diffProcess( 0 ),
+ m_diffSettings( diffSettings ),
+ m_models( 0 ),
+ m_selectedModel( 0 ),
+ m_selectedDifference( 0 ),
+ m_noOfModified( 0 ),
+ m_modelIndex( 0 ),
+ m_info( info ),
+ m_textCodec( 0 )
+{
+ m_applyDifference = m_unApplyDifference = m_applyAll = m_unapplyAll = m_previousFile = m_nextFile = m_previousDifference = m_nextDifference = m_save = 0;
+/* m_applyDifference = new KAction( i18n("&Apply Difference"), "1rightarrow", Qt::Key_Space,
+ this, SLOT(slotActionApplyDifference()),
+ (( KomparePart* )parent)->actionCollection(), "difference_apply" );
+ m_unApplyDifference = new KAction( i18n("Un&apply Difference"), "1leftarrow", Qt::Key_Backspace,
+ this, SLOT(slotActionUnApplyDifference()),
+ (( KomparePart* )parent)->actionCollection(), "difference_unapply" );
+ m_applyAll = new KAction( i18n("App&ly All"), "2rightarrow", Qt::CTRL + Qt::Key_A,
+ this, SLOT(slotActionApplyAllDifferences()),
+ (( KomparePart* )parent)->actionCollection(), "difference_applyall" );
+ m_unapplyAll = new KAction( i18n("&Unapply All"), "2leftarrow", Qt::CTRL + Qt::Key_U,
+ this, SLOT(slotActionUnapplyAllDifferences()),
+ (( KomparePart* )parent)->actionCollection(), "difference_unapplyall" );
+ m_previousFile = new KAction( i18n("P&revious File"), "2uparrow", Qt::CTRL + Qt::Key_PageUp,
+ this, SLOT(slotPreviousModel()),
+ (( KomparePart* )parent)->actionCollection(), "difference_previousfile" );
+ m_nextFile = new KAction( i18n("N&ext File"), "2downarrow", Qt::CTRL + Qt::Key_PageDown,
+ this, SLOT(slotNextModel()),
+ (( KomparePart* )parent)->actionCollection(), "difference_nextfile" );
+ m_previousDifference = new KAction( i18n("&Previous Difference"), "1uparrow", Qt::CTRL + Qt::Key_Up,
+ this, SLOT(slotPreviousDifference()),
+ (( KomparePart* )parent)->actionCollection(), "difference_previous" );
+ m_nextDifference = new KAction( i18n("&Next Difference"), "1downarrow", Qt::CTRL + Qt::Key_Down,
+ this, SLOT(slotNextDifference()),
+ (( KomparePart* )parent)->actionCollection(), "difference_next" );
+ m_previousDifference->setEnabled( false );
+ m_nextDifference->setEnabled( false );*/
+
+/* m_save = KStdAction::save( this, SLOT(slotSaveDestination()), ((KomparePart*)parent)->actionCollection() );
+ m_save->setEnabled( false );*/
+
+ updateModelListActions();
+}
+
+KompareModelList::~KompareModelList()
+{
+}
+
+bool KompareModelList::isDirectory( const QString& url ) const
+{
+ QFileInfo fi( url );
+ if ( fi.isDir() )
+ return true;
+ else
+ return false;
+}
+
+bool KompareModelList::isDiff( const QString& mimeType ) const
+{
+ if ( mimeType == "text/x-diff" )
+ return true;
+ else
+ return false;
+}
+
+bool KompareModelList::compare( const QString& source, const QString& destination )
+{
+ bool result = false;
+
+ bool sourceIsDirectory = isDirectory( source );
+ bool destinationIsDirectory = isDirectory( source );
+
+ if ( sourceIsDirectory && destinationIsDirectory )
+ {
+ m_info.mode = Kompare::ComparingDirs;
+ result = compareDirs( source, destination );
+ }
+ else if ( !sourceIsDirectory && !destinationIsDirectory )
+ {
+ QFile sourceFile( source );
+ sourceFile.open( QIODevice::ReadOnly );
+ QString sourceMimeType = ( KMimeType::findByContent( sourceFile.readAll() ) )->name();
+ sourceFile.close();
+ kDebug(8101) << "Mimetype source :" << sourceMimeType;
+
+ QFile destinationFile( destination );
+ destinationFile.open( QIODevice::ReadOnly );
+ QString destinationMimeType = ( KMimeType::findByContent( destinationFile.readAll() ) )->name();
+ destinationFile.close();
+ kDebug(8101) << "Mimetype destination:" << destinationMimeType;
+
+ // Not checking if it is a text file/something diff can even compare, we'll let diff handle that
+ if ( !isDiff( sourceMimeType ) && isDiff( destinationMimeType ) )
+ {
+ kDebug(8101) << "Blending destination into source...";
+ m_info.mode = Kompare::BlendingFile;
+ result = openFileAndDiff( source, destination );
+ }
+ else if ( isDiff( sourceMimeType ) && !isDiff( destinationMimeType ) )
+ {
+ kDebug(8101) << "Blending source into destination...";
+ m_info.mode = Kompare::BlendingFile;
+ result = openFileAndDiff( destination, source );
+ }
+ else
+ {
+ kDebug(8101) << "Comparing source with destination";
+ m_info.mode = Kompare::ComparingFiles;
+ result = compareFiles( source, destination );
+ }
+ }
+ else if ( sourceIsDirectory && !destinationIsDirectory )
+ {
+ m_info.mode = Kompare::BlendingDir;
+ result = openDirAndDiff( source, destination );
+ }
+ else
+ {
+ m_info.mode = Kompare::BlendingDir;
+ result = openDirAndDiff( destination, source );
+ }
+
+ return result;
+}
+
+bool KompareModelList::compareFiles( const QString& source, const QString& destination )
+{
+ m_source = source;
+ m_destination = destination;
+
+ clear(); // Destroy the old models...
+
+// m_fileWatch = new KDirWatch( this, "filewatch" );
+// m_fileWatch->addFile( m_source );
+// m_fileWatch->addFile( m_destination );
+
+// connect( m_fileWatch, SIGNAL( dirty( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
+// connect( m_fileWatch, SIGNAL( created( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
+// connect( m_fileWatch, SIGNAL( deleted( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
+
+// m_fileWatch->startScan();
+ m_diffProcess = new KompareProcess( m_diffSettings, Kompare::Custom, m_source, m_destination );
+ m_diffProcess->setEncoding( m_encoding );
+
+ connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
+ this, SLOT(slotDiffProcessFinished( bool )) );
+
+ emit status( Kompare::RunningDiff );
+ m_diffProcess->start();
+
+ return true;
+}
+
+bool KompareModelList::compareDirs( const QString& source, const QString& destination )
+{
+ m_source = source;
+ m_destination = destination;
+
+ clear(); // Destroy the old models...
+
+// m_dirWatch = new KDirWatch( this, "dirwatch" );
+ // Watch files in the dirs and watch the dirs recursively
+// m_dirWatch->addDir( m_source, true, true );
+// m_dirWatch->addDir( m_destination, true, true );
+
+// connect( m_dirWatch, SIGNAL( dirty ( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
+// connect( m_dirWatch, SIGNAL( created( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
+// connect( m_dirWatch, SIGNAL( deleted( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
+
+// m_dirWatch->startScan();
+ m_diffProcess = new KompareProcess( m_diffSettings, Kompare::Custom, m_source, m_destination );
+ m_diffProcess->setEncoding( m_encoding );
+
+ connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
+ this, SLOT(slotDiffProcessFinished( bool )) );
+
+ emit status( Kompare::RunningDiff );
+ m_diffProcess->start();
+
+ return true;
+}
+
+bool KompareModelList::openFileAndDiff( const QString& file, const QString& diff )
+{
+ clear();
+
+ if ( parseDiffOutput( readFile( diff ) ) != 0 )
+ {
+ emit error( i18n( "<qt>No models or no differences, this file: <b>%1</b>, is not a valid diff file.</qt>", diff ) );
+ return false;
+ }
+
+ // Do our thing :)
+ if ( !blendOriginalIntoModelList( file ) )
+ {
+ kDebug(8101) << "Oops cant blend original file into modellist :" << file;
+ emit( i18n( "<qt>There were problems applying the diff <b>%1</b> to the file <b>%2</b>.</qt>", diff, file ) );
+ return false;
+ }
+
+ updateModelListActions();
+ show();
+
+ return true;
+}
+
+bool KompareModelList::openDirAndDiff( const QString& dir, const QString& diff )
+{
+ clear();
+
+ if ( parseDiffOutput( readFile( diff ) ) != 0 )
+ {
+ emit error( i18n( "<qt>No models or no differences, this file: <b>%1</b>, is not a valid diff file.</qt>", diff ) );
+ return false;
+ }
+
+ // Do our thing :)
+ if ( !blendOriginalIntoModelList( dir ) )
+ {
+ // Trouble blending the original into the model
+ kDebug(8101) << "Oops cant blend original dir into modellist :" << dir;
+ emit error( i18n( "<qt>There were problems applying the diff <b>%1</b> to the folder <b>%2</b>.</qt>", diff, dir ) );
+ return false;
+ }
+
+ updateModelListActions();
+ show();
+
+ return true;
+}
+
+void KompareModelList::slotSaveDestination()
+{
+ if ( m_selectedModel )
+ {
+ saveDestination( m_selectedModel );
+ }
+}
+
+bool KompareModelList::saveDestination( DiffModel* model )
+{
+ kDebug(9500) << "KompareModelList::saveDestination:";
+
+ if( !model->isModified() )
+ return true;
+
+ K3TempFile* temp = new K3TempFile();
+
+ if( temp->status() != 0 ) {
+ emit error( i18n( "Could not open a temporary file." ) );
+ temp->unlink();
+ delete temp;
+ return false;
+ }
+
+ QTextStream* stream = temp->textStream();
+ QStringList list;
+
+ DiffHunkListConstIterator hunkIt = model->hunks()->begin();
+ DiffHunkListConstIterator hEnd = model->hunks()->end();
+
+ for( ; hunkIt != hEnd; ++hunkIt )
+ {
+ DiffHunk* hunk = *hunkIt;
+
+ DifferenceListConstIterator diffIt = hunk->differences().begin();
+ DifferenceListConstIterator dEnd = hunk->differences().end();
+
+ Difference* diff;
+ for( ; diffIt != dEnd; ++diffIt )
+ {
+ diff = *diffIt;
+ if( !diff->applied() )
+ {
+ DifferenceStringListConstIterator stringIt = diff->destinationLines().begin();
+ DifferenceStringListConstIterator sEnd = diff->destinationLines().end();
+ for ( ; stringIt != sEnd; ++stringIt )
+ {
+ list.append( ( *stringIt )->string() );
+ }
+ }
+ else
+ {
+ DifferenceStringListConstIterator stringIt = diff->sourceLines().begin();
+ DifferenceStringListConstIterator sEnd = diff->sourceLines().end();
+ for ( ; stringIt != sEnd; ++stringIt )
+ {
+ list.append( ( *stringIt )->string() );
+ }
+ }
+ }
+ }
+
+ // kDebug( 8101 ) << "Everything:"<< list.join( "\n" );
+
+ if( list.count() > 0 )
+ *stream << list.join( "" );
+
+ temp->close();
+ if( temp->status() != 0 ) {
+ emit error( i18n( "<qt>Could not write to the temporary file <b>%1</b>, deleting it.</qt>", temp->name() ) );
+ temp->unlink();
+ delete temp;
+ return false;
+ }
+
+ bool result = false;
+
+ if ( m_info.mode == Kompare::ComparingDirs )
+ {
+ QString destination = model->destinationPath() + model->destinationFile();
+ kDebug(8101) << "Tempfilename :" << temp->name();
+ kDebug(8101) << "DestinationURL :" << destination;
+ KIO::UDSEntry entry;
+ if ( !KIO::NetAccess::stat( KUrl( destination ).toLocalFile(), entry, (QWidget*)parent() ) )
+ {
+ if ( !KIO::NetAccess::mkdir( KUrl( destination ).toLocalFile(), (QWidget*)parent() ) )
+ {
+ emit error( i18n( "<qt>Could not create destination directory <b>%1</b>.\nThe file has not been saved.</qt>", destination ) );
+ return false;
+ }
+ }
+ result = KIO::NetAccess::upload( temp->name(), KUrl( destination ), (QWidget*)parent() );
+ }
+ else
+ {
+ kDebug(8101) << "Tempfilename :" << temp->name();
+ kDebug(8101) << "DestinationURL :" << m_destination;
+ result = KIO::NetAccess::upload( temp->name(), KUrl( m_destination ), (QWidget*)parent() );
+ }
+
+ if ( !result )
+ {
+ emit error( i18n( "<qt>Could not upload the temporary file to the destination location <b>%1</b>. The temporary file is still available under: <b>%2</b>. You can manually copy it to the right place.</qt>", m_destination, temp->name() ) );
+ }
+ else
+ {
+ //model->slotSetModified( false );
+ temp->unlink();
+ delete temp;
+ }
+
+ return true;
+}
+
+bool KompareModelList::saveAll()
+{
+ if ( !m_models )
+ return false;
+
+ DiffModelListIterator it = m_models->begin();
+ DiffModelListIterator end = m_models->end();
+ for ( ; it != end; ++it )
+ {
+ if( !saveDestination( *it ) )
+ return false;
+ }
+ return true;
+}
+
+void KompareModelList::setEncoding( const QString& encoding )
+{
+ m_encoding = encoding;
+ kDebug(9500) << "Encoding :" << encoding;
+ m_textCodec = KGlobal::charsets()->codecForName( encoding.toLatin1() );
+ kDebug(9500) << "TextCodec:" << m_textCodec;
+ if ( !m_textCodec )
+ m_textCodec = QTextCodec::codecForLocale();
+ kDebug(9500) << "TextCodec:" << m_textCodec;
+}
+
+void KompareModelList::slotDiffProcessFinished( bool success )
+{
+ if ( success )
+ {
+ emit status( Kompare::Parsing );
+ if ( parseDiffOutput( m_diffProcess->diffOutput() ) != 0 )
+ {
+ emit error( i18n( "Could not parse diff output." ) );
+ }
+ else
+ {
+ if ( m_info.mode != Kompare::ShowingDiff )
+ {
+ kDebug(9500) << "Blend this crap please and do not gimme any conflicts...";
+ blendOriginalIntoModelList( m_info.localSource );
+ }
+ updateModelListActions();
+ show();
+ }
+ emit status( Kompare::FinishedParsing );
+ }
+ else if ( m_diffProcess->process()->exitStatus() == QProcess::NormalExit )
+ {
+ emit error( i18n( "The files are identical." ) );
+ }
+ else
+ {
+ emit error( m_diffProcess->stdErr() );
+ }
+
+ delete m_diffProcess;
+ m_diffProcess = 0;
+}
+
+void KompareModelList::slotDirectoryChanged( const QString& /*dir*/ )
+{
+ // some debug output to see if watching works properly
+ kDebug(8101) << "Yippie directories are being watched !!! :)";
+ if ( m_diffProcess )
+ {
+ emit status( Kompare::ReRunningDiff );
+ m_diffProcess->start();
+ }
+}
+
+void KompareModelList::slotFileChanged( const QString& /*file*/ )
+{
+ // some debug output to see if watching works properly
+ kDebug(8101) << "Yippie files are being watched !!! :)";
+ if ( m_diffProcess )
+ {
+ emit status( Kompare::ReRunningDiff );
+ m_diffProcess->start();
+ }
+}
+
+QStringList KompareModelList::split( const QString& fileContents )
+{
+ QString contents = fileContents;
+ QStringList list;
+
+ int pos = 0;
+ unsigned int oldpos = 0;
+ // split that does not strip the split char
+#ifdef QT_OS_MAC
+ const char split = '\r';
+#else
+ const char split = '\n';
+#endif
+ while ( ( pos = contents.indexOf( split, oldpos ) ) >= 0 )
+ {
+ list.append( contents.mid( oldpos, pos - oldpos + 1 ) );
+ oldpos = pos + 1;
+ }
+
+ if ( contents.length() > oldpos )
+ {
+ list.append( contents.right( contents.length() - oldpos ) );
+ }
+
+ return list;
+}
+
+QString KompareModelList::readFile( const QString& fileName )
+{
+ QStringList list;
+
+ QFile file( fileName );
+ file.open( QIODevice::ReadOnly );
+
+ QTextStream stream( &file );
+ kDebug(9500) << "Codec =" << m_textCodec;
+
+ if ( !m_textCodec )
+ m_textCodec = QTextCodec::codecForLocale();
+
+ stream.setCodec( m_textCodec );
+
+ QString contents = stream.readAll();
+
+ file.close();
+
+ return contents;
+}
+
+bool KompareModelList::openDiff( const QString& diffFile )
+{
+ kDebug(8101) << "Stupid :) Url =" << diffFile;
+
+ if ( diffFile.isEmpty() )
+ return false;
+
+ QString diff = readFile( diffFile );
+
+ clear(); // Clear the current models
+
+ emit status( Kompare::Parsing );
+
+ if ( parseDiffOutput( diff ) != 0 )
+ {
+ emit error( i18n( "Could not parse diff output." ) );
+ return false;
+ }
+
+ updateModelListActions();
+ show();
+
+ emit status( Kompare::FinishedParsing );
+
+ return true;
+}
+
+QString KompareModelList::recreateDiff() const
+{
+ QString diff;
+
+ DiffModelListConstIterator modelIt = m_models->begin();
+ DiffModelListConstIterator mEnd = m_models->end();
+
+ for ( ; modelIt != mEnd; ++modelIt )
+ {
+ diff += (*modelIt)->recreateDiff();
+ }
+ return diff;
+}
+
+bool KompareModelList::saveDiff( const QString& url, const QString& directory, DiffSettings* diffSettings )
+{
+ kDebug(9500) << "KompareModelList::saveDiff:";
+
+ m_diffTemp = new K3TempFile();
+ m_diffURL = url;
+
+ if( m_diffTemp->status() != 0 ) {
+ emit error( i18n( "Could not open a temporary file." ) );
+ m_diffTemp->unlink();
+ delete m_diffTemp;
+ m_diffTemp = 0;
+ return false;
+ }
+
+ m_diffProcess = new KompareProcess( diffSettings, Kompare::Custom, m_source, m_destination, directory );
+ m_diffProcess->setEncoding( m_encoding );
+
+ connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
+ this, SLOT(slotWriteDiffOutput( bool )) );
+
+ emit status( Kompare::RunningDiff );
+ m_diffProcess->start();
+ return m_diffProcess->process()->waitForStarted();
+}
+
+void KompareModelList::slotWriteDiffOutput( bool success )
+{
+ kDebug(8101) << "Success =" << success;
+
+ if( success )
+ {
+ QTextStream* stream = m_diffTemp->textStream();
+
+ *stream << m_diffProcess->diffOutput();
+
+ m_diffTemp->close();
+
+ if( m_diffTemp->status() != 0 )
+ {
+ emit error( i18n( "Could not write to the temporary file." ) );
+ }
+
+ KIO::NetAccess::upload( m_diffTemp->name(), KUrl( m_diffURL ), (QWidget*)parent() );
+
+ emit status( Kompare::FinishedWritingDiff );
+ }
+
+ m_diffURL.truncate( 0 );
+ m_diffTemp->unlink();
+
+ delete m_diffTemp;
+ m_diffTemp = 0;
+
+ delete m_diffProcess;
+ m_diffProcess = 0;
+}
+
+void KompareModelList::slotSelectionChanged( const Diff2::DiffModel* model, const Diff2::Difference* diff )
+{
+// This method will signal all the other objects about a change in selection,
+// it will emit setSelection( const DiffModel*, const Difference* ) to all who are connected
+ kDebug(8101) << "KompareModelList::slotSelectionChanged(" << model << "," << diff << ")";
+// kDebug(8101) << "Sender is :" << sender()->className();
+// kDebug(8101) << kBacktrace();
+
+ m_selectedModel = const_cast<DiffModel*>(model);
+ m_modelIndex = findItem( m_selectedModel, m_models );
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+ m_selectedDifference = const_cast<Difference*>(diff);
+
+ m_selectedModel->setSelectedDifference( m_selectedDifference );
+
+ // setSelected* search for the argument in the lists and return false if not found
+ // if found they return true and set the m_selected*
+ if ( !setSelectedModel( m_selectedModel ) )
+ {
+ // Backup plan
+ m_selectedModel = firstModel();
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+ else if ( !m_selectedModel->setSelectedDifference( m_selectedDifference ) )
+ {
+ // Another backup plan
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+
+ emit setSelection( model, diff );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+
+ updateModelListActions();
+}
+
+void KompareModelList::slotSelectionChanged( const Diff2::Difference* diff )
+{
+// This method will emit setSelection( const Difference* ) to whomever is listening
+// when for instance in kompareview the selection has changed
+ kDebug(8101) << "KompareModelList::slotSelectionChanged(" << diff << ")";
+// kDebug(8101) << "Sender is :" << sender()->className();
+
+ m_selectedDifference = const_cast<Difference*>(diff);
+
+ if ( !m_selectedModel->setSelectedDifference( m_selectedDifference ) )
+ {
+ // Backup plan
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+
+ emit setSelection( diff );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+
+ updateModelListActions();
+}
+
+void KompareModelList::slotPreviousModel()
+{
+ if ( ( m_selectedModel = prevModel() ) != 0 )
+ {
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+ else
+ {
+ m_selectedModel = firstModel();
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+}
+
+void KompareModelList::slotNextModel()
+{
+ if ( ( m_selectedModel = nextModel() ) != 0 )
+ {
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+ else
+ {
+ m_selectedModel = lastModel();
+ m_selectedDifference = m_selectedModel->firstDifference();
+ }
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+}
+
+DiffModel* KompareModelList::firstModel()
+{
+ kDebug( 8101 ) << "KompareModelList::firstModel()";
+ m_modelIndex = 0;
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+
+ m_selectedModel = m_models->first();
+
+ return m_selectedModel;
+}
+
+DiffModel* KompareModelList::lastModel()
+{
+ kDebug( 8101 ) << "KompareModelList::lastModel()";
+ m_modelIndex = m_models->count() - 1;
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+
+ m_selectedModel = m_models->last();
+
+ return m_selectedModel;
+}
+
+DiffModel* KompareModelList::prevModel()
+{
+ kDebug( 8101 ) << "KompareModelList::prevModel()";
+ if ( --m_modelIndex < m_models->count() )
+ {
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+ m_selectedModel = (*m_models)[ m_modelIndex ];
+ }
+ else
+ {
+ m_selectedModel = 0;
+ m_modelIndex = 0;
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+ }
+
+ return m_selectedModel;
+}
+
+DiffModel* KompareModelList::nextModel()
+{
+ kDebug( 8101 ) << "KompareModelList::nextModel()";
+ if ( ++m_modelIndex < m_models->count() )
+ {
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+ m_selectedModel = (*m_models)[ m_modelIndex ];
+ }
+ else
+ {
+ m_selectedModel = 0;
+ m_modelIndex = 0;
+ kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
+ }
+
+ return m_selectedModel;
+}
+
+void KompareModelList::slotPreviousDifference()
+{
+ kDebug(8101) << "slotPreviousDifference called";
+ if ( ( m_selectedDifference = m_selectedModel->prevDifference() ) != 0 )
+ {
+ emit setSelection( m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+ return;
+ }
+
+ kDebug(8101) << "**** no previous difference... ok lets find the previous model...";
+
+ if ( ( m_selectedModel = prevModel() ) != 0 )
+ {
+ m_selectedDifference = m_selectedModel->lastDifference();
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+ return;
+ }
+
+
+ kDebug(8101) << "**** !!! No previous model, ok backup plan activated...";
+
+ // Backup plan
+ m_selectedModel = firstModel();
+ m_selectedDifference = m_selectedModel->firstDifference();
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+}
+
+void KompareModelList::slotNextDifference()
+{
+ kDebug(8101) << "slotNextDifference called";
+ if ( ( m_selectedDifference = m_selectedModel->nextDifference() ) != 0 )
+ {
+ emit setSelection( m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+ return;
+ }
+
+ kDebug(8101) << "**** no next difference... ok lets find the next model...";
+
+ if ( ( m_selectedModel = nextModel() ) != 0 )
+ {
+ m_selectedDifference = m_selectedModel->firstDifference();
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+ return;
+ }
+
+ kDebug(8101) << "**** !!! No next model, ok backup plan activated...";
+
+ // Backup plan
+ m_selectedModel = lastModel();
+ m_selectedDifference = m_selectedModel->lastDifference();
+
+ emit setSelection( m_selectedModel, m_selectedDifference );
+ emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
+ updateModelListActions();
+}
+
+void KompareModelList::slotApplyDifference( bool apply )
+{
+ m_selectedModel->applyDifference( apply );
+ emit applyDifference( apply );
+}
+
+void KompareModelList::slotApplyAllDifferences( bool apply )
+{
+ m_selectedModel->applyAllDifferences( apply );
+ emit applyAllDifferences( apply );
+}
+
+int KompareModelList::parseDiffOutput( const QString& diff )
+{
+ kDebug(8101) << "KompareModelList::parseDiffOutput";
+
+ QStringList diffLines = split( diff );
+
+ Parser* parser = new Parser( this );
+ m_models = parser->parse( diffLines );
+
+ m_info.generator = parser->generator();
+ m_info.format = parser->format();
+
+ delete parser;
+
+ if ( m_models )
+ {
+ m_selectedModel = firstModel();
+ kDebug(8101) << "Ok there are differences...";
+ m_selectedDifference = m_selectedModel->firstDifference();
+ emit setStatusBarModelInfo( 0, 0, modelCount(), differenceCount(), 0);
+ }
+ else
+ {
+ // Wow trouble, no models, so no differences...
+ kDebug(8101) << "Now i'll be damned, there should be models here !!!";
+ return -1;
+ }
+
+ return 0;
+}
+
+bool KompareModelList::blendOriginalIntoModelList( const QString& localURL )
+{
+ kDebug(9500) << "Hurrah we are blending...";
+ QFileInfo fi( localURL );
+
+ bool result = false;
+ DiffModel* model;
+
+ QString fileContents;
+
+ if ( fi.isDir() )
+ { // is a dir
+ kDebug(9500) << "Blend Dir";
+// QDir dir( localURL, QString(), QDir::Name|QDir::DirsFirst, QDir::TypeMask );
+ DiffModelListIterator modelIt = m_models->begin();
+ DiffModelListIterator mEnd = m_models->end();
+ for ( ; modelIt != mEnd; ++modelIt )
+ {
+ model = *modelIt;
+ kDebug(8101) << "Model :" << model;
+ QString filename = model->sourcePath() + model->sourceFile();
+ if ( !filename.startsWith( localURL ) ) {
+ KUrl u( localURL );
+ u.addPath( filename );
+ filename = u.toLocalFile();
+ }
+ QFileInfo fi2( filename );
+ if ( fi2.exists() )
+ {
+ kDebug(8101) << "Reading from:" << filename;
+ fileContents = readFile( filename );
+ result = blendFile( model, fileContents );
+ }
+ else
+ {
+ kDebug(8101) << "File" << filename << "does not exist !";
+ kDebug(8101) << "Assume empty file !";
+ fileContents.truncate( 0 );
+ result = blendFile( model, fileContents );
+ }
+ }
+ kDebug(9500) << "End of Blend Dir";
+ }
+ else if ( fi.isFile() )
+ { // is a file
+ kDebug(9500) << "Blend File";
+ kDebug(8101) << "Reading from:" << localURL;
+ fileContents = readFile( localURL );
+
+ result = blendFile( (*m_models)[ 0 ], fileContents );
+ kDebug(9500) << "End of Blend File";
+ }
+
+ return result;
+}
+
+bool KompareModelList::blendFile( DiffModel* model, const QString& fileContents )
+{
+ if ( !model )
+ {
+ kDebug(9500) << "**** model is null :(";
+ return false;
+ }
+
+ model->setBlended( true );
+
+ int srcLineNo = 1, destLineNo = 1;
+
+ QStringList lines = split( fileContents );
+
+ QStringList::ConstIterator linesIt = lines.begin();
+ QStringList::ConstIterator lEnd = lines.end();
+
+ DiffHunkList* hunks = model->hunks();
+ kDebug(8101) << "Hunks in hunklist:" << hunks->count();
+ DiffHunkListIterator hunkIt = hunks->begin();
+
+ DiffHunk* newHunk = 0;
+ Difference* newDiff = 0;
+
+ // FIXME: this approach is not very good, we should first check if the hunk applies cleanly
+ // and without offset and if not use that new linenumber with offset to compare against
+ // This will only work for files we just diffed with kompare but not for blending where
+ // file(s) to patch has/have potentially changed
+
+ for ( ; hunkIt != hunks->end(); ++hunkIt )
+ {
+ // Do we need to insert a new hunk before this one ?
+ DiffHunk* hunk = *hunkIt;
+ if ( srcLineNo < hunk->sourceLineNumber() )
+ {
+ newHunk = new DiffHunk( srcLineNo, destLineNo, "", DiffHunk::AddedByBlend );
+
+ hunks->insert( hunkIt, newHunk );
+
+ newDiff = new Difference( srcLineNo, destLineNo,
+ Difference::Unchanged );
+
+ newHunk->add( newDiff );
+
+ while ( srcLineNo < hunk->sourceLineNumber() && linesIt != lEnd )
+ {
+ newDiff->addSourceLine( *linesIt );
+ newDiff->addDestinationLine( *linesIt );
+ srcLineNo++;
+ destLineNo++;
+ ++linesIt;
+ }
+ }
+
+ // Now we add the linecount difference for the hunk that follows
+ int size = hunk->sourceLineCount();
+
+ for ( int i = 0; i < size; ++i )
+ {
+ if( linesIt == lEnd ) {
+ kDebug(9500) << "kompare error";
+ return false;
+ }
+ ++linesIt;
+ }
+
+ srcLineNo += size;
+ destLineNo += (*hunkIt)->destinationLineCount();
+ }
+
+ if ( linesIt != lEnd )
+ {
+ newHunk = new DiffHunk( srcLineNo, destLineNo, "", DiffHunk::AddedByBlend );
+
+ model->addHunk( newHunk );
+
+ newDiff = new Difference( srcLineNo, destLineNo, Difference::Unchanged );
+
+ newHunk->add( newDiff );
+
+ while ( linesIt != lEnd )
+ {
+ newDiff->addSourceLine( *linesIt );
+ newDiff->addDestinationLine( *linesIt );
+ ++linesIt;
+ }
+ }
+#if 0
+ DifferenceList hunkDiffList = (*hunkIt)->differences();
+ DifferenceListIterator diffIt = hunkDiffList.begin();
+ DifferenceListIterator dEnd = hunkDiffList.end();
+ kDebug(9500) << "Number of differences in hunkDiffList =" << diffList.count();
+
+ DifferenceListIterator tempIt;
+ Difference* diff;
+
+ for ( ; diffIt != dEnd; ++diffIt )
+ {
+ diff = *diffIt;
+ kDebug(9500) << "*(Diff it) =" << diff;
+ // Check if there are lines in the original file before the difference
+ // that are not yet in the diff. If so create new Unchanged diff
+ if ( srcLineNo < diff->sourceLineNumber() )
+ {
+ newDiff = new Difference( srcLineNo, destLineNo,
+ Difference::Unchanged | Difference::AddedByBlend );
+ newHunk->add( newDiff );
+ while ( srcLineNo < diff->sourceLineNumber() && linesIt != lEnd )
+ {
+// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *linesIt;
+ newDiff->addSourceLine( *linesIt );
+ newDiff->addDestinationLine( *linesIt );
+ srcLineNo++;
+ destLineNo++;
+ ++linesIt;
+ }
+ }
+ // Now i've got to add that diff
+ switch ( diff->type() )
+ {
+ case Difference::Unchanged:
+ kDebug(8101) << "Unchanged";
+ for ( int i = 0; i < diff->sourceLineCount(); i++ )
+ {
+ if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
+ {
+ kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
+ kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
+
+ // Do conflict resolution (well sort of)
+ diff->sourceLineAt( i )->setConflictString( *linesIt );
+ diff->setConflict( true );
+ }
+// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *linesIt;
+// kDebug(8101) << "DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
+ srcLineNo++;
+ destLineNo++;
+ ++linesIt;
+ }
+
+ tempIt = diffIt;
+ --diffIt;
+ diffList.remove( tempIt );
+ newHunk->add( diff );
+
+ break;
+ case Difference::Change:
+ kDebug(8101) << "Change";
+
+ //QStringListConstIterator saveIt = linesIt;
+
+ for ( int i = 0; i < diff->sourceLineCount(); i++ )
+ {
+ if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
+ {
+ kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
+ kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
+
+ // Do conflict resolution (well sort of)
+ diff->sourceLineAt( i )->setConflictString( *linesIt );
+ diff->setConflict( true );
+ }
+ srcLineNo++;
+ destLineNo++;
+ ++linesIt;
+ }
+
+ destLineNo += diff->destinationLineCount();
+
+ tempIt = diffIt;
+ --diffIt;
+ diffList.remove( tempIt );
+ newHunk->add( diff );
+ newModel->addDiff( diff );
+
+ break;
+ case Difference::Insert:
+ kDebug(8101) << "Insert";
+ destLineNo += diff->destinationLineCount();
+ tempIt = diffIt;
+ --diffIt;
+ diffList.remove( tempIt );
+ newHunk->add( diff );
+ newModel->addDiff( diff );
+ break;
+ case Difference::Delete:
+ kDebug(8101) << "Delete";
+ kDebug(8101) << "Number of lines in Delete:" << diff->sourceLineCount();
+ for ( int i = 0; i < diff->sourceLineCount(); i++ )
+ {
+ if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
+ {
+ kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
+ kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
+
+ // Do conflict resolution (well sort of)
+ diff->sourceLineAt( i )->setConflictString( *linesIt );
+ diff->setConflict( true );
+ }
+
+// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *it;
+// kDebug(8101) << "DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
+ srcLineNo++;
+ ++linesIt;
+ }
+
+ tempIt = diffIt;
+ --diffIt;
+ diffList.remove( tempIt );
+ newHunk->add( diff );
+ newModel->addDiff( diff );
+ break;
+ default:
+ kDebug(8101) << "****, some diff type we do not know about ???";
+ }
+ }
+ }
+#endif
+
+/*
+ diffList = newModel->differences();
+
+ diff = diffList.first();
+ kDebug(8101) << "Count =" << diffList.count();
+ for ( diff = diffList.first(); diff; diff = diffList.next() )
+ {
+ kDebug(8101) << "sourcelinenumber =" << diff->sourceLineNumber();
+ }
+*/
+
+ m_selectedModel = firstModel();
+
+ m_selectedDifference = m_selectedModel->firstDifference();
+
+ return true;
+}
+
+void KompareModelList::show()
+{
+ kDebug(9500) << "KompareModelList::Show Number of models =" << m_models->count();
+ emit modelsChanged( m_models );
+ emit setSelection( m_selectedModel, m_selectedDifference );
+}
+
+void KompareModelList::clear()
+{
+ if ( m_models )
+ m_models->clear();
+
+ emit modelsChanged( m_models );
+}
+
+void KompareModelList::swap()
+{
+ QString source = m_source;
+ QString destination = m_destination;
+ if ( m_info.mode == Kompare::ComparingFiles )
+ compareFiles( destination, source );
+ else if ( m_info.mode == Kompare::ComparingDirs )
+ compareDirs( destination, source );
+}
+
+bool KompareModelList::isModified() const
+{
+ if ( m_noOfModified > 0 )
+ return true;
+ return false;
+}
+
+int KompareModelList::modelCount() const
+{
+ return m_models ? m_models->count() : 0;
+}
+
+int KompareModelList::differenceCount() const
+{
+ return m_selectedModel ? m_selectedModel->differenceCount() : -1;
+}
+
+int KompareModelList::appliedCount() const
+{
+ return m_selectedModel ? m_selectedModel->appliedCount() : -1;
+}
+
+void KompareModelList::slotSetModified( bool modified )
+{
+ kDebug(8101) << "KompareModelList::slotSetModified(" << modified << ");";
+ kDebug(8101) << "Before: m_noOfModified =" << m_noOfModified;
+
+ // If selectedModel emits its signal setModified it does not set the model
+ // internal m_modified bool yet, it only does that after the emit.
+ if ( modified && !m_selectedModel->isModified() )
+ m_noOfModified++;
+ else if ( !modified && m_selectedModel->isModified() )
+ m_noOfModified--;
+
+ kDebug(8101) << "After : m_noOfModified =" << m_noOfModified;
+
+ if ( m_noOfModified < 0 )
+ {
+ kDebug(8101) << "Wow something is ****ed up...";
+ }
+ else if ( m_noOfModified == 0 )
+ {
+ emit setModified( false );
+ }
+ else // > 0 :-)
+ {
+ emit setModified( true );
+ }
+}
+
+bool KompareModelList::setSelectedModel( DiffModel* model )
+{
+ kDebug(8101) << "KompareModelList::setSelectedModel(" << model << ")";
+
+ if ( model != m_selectedModel )
+ {
+ if ( findItem( model , m_models ) == -1 )
+ return false;
+ kDebug(8101) << "m_selectedModel (was) =" << m_selectedModel;
+ m_modelIndex = findItem( model , m_models );
+ kDebug(8101) << "m_selectedModel (is) =" << m_selectedModel;
+ m_selectedModel = model;
+ }
+
+ updateModelListActions();
+
+ return true;
+}
+
+void KompareModelList::updateModelListActions()
+{/*
+ if ( m_models && m_selectedModel && m_selectedDifference )
+ {
+ if ( ( ( KomparePart* )parent() )->isReadWrite() )
+ {
+ if ( m_selectedModel->appliedCount() != m_selectedModel->differenceCount() )
+ m_applyAll->setEnabled( true );
+ else
+ m_applyAll->setEnabled( false );
+
+ if ( m_selectedModel->appliedCount() != 0 )
+ m_unapplyAll->setEnabled( true );
+ else
+ m_unapplyAll->setEnabled( false );
+
+ m_applyDifference->setEnabled( true );
+ m_unApplyDifference->setEnabled( true );
+ m_save->setEnabled( m_selectedModel->isModified() );
+ }
+ else
+ {
+ m_applyDifference->setEnabled ( false );
+ m_unApplyDifference->setEnabled( false );
+ m_applyAll->setEnabled ( false );
+ m_unapplyAll->setEnabled ( false );
+ m_save->setEnabled ( false );
+ }
+
+ m_previousFile->setEnabled ( hasPrevModel() );
+ m_nextFile->setEnabled ( hasNextModel() );
+ m_previousDifference->setEnabled( hasPrevDiff() );
+ m_nextDifference->setEnabled ( hasNextDiff() );
+ }
+ else
+ {
+ m_applyDifference->setEnabled ( false );
+ m_unApplyDifference->setEnabled ( false );
+ m_applyAll->setEnabled ( false );
+ m_unapplyAll->setEnabled ( false );
+
+ m_previousFile->setEnabled ( false );
+ m_nextFile->setEnabled ( false );
+ m_previousDifference->setEnabled( false );
+ m_nextDifference->setEnabled ( false );
+ m_save->setEnabled ( false );
+ }*/
+}
+
+bool KompareModelList::hasPrevModel() const
+{
+ kDebug(8101) << "KompareModelList::hasPrevModel()";
+
+ if ( m_modelIndex > 0 )
+ {
+// kDebug(8101) << "has prev model";
+ return true;
+ }
+
+// kDebug(8101) << "doesn't have a prev model, this is the first one...";
+
+ return false;
+}
+
+bool KompareModelList::hasNextModel() const
+{
+ kDebug(8101) << "KompareModelList::hasNextModel()";
+
+ if ( ( unsigned int )m_modelIndex < ( m_models->count() - 1 ) )
+ {
+// kDebug(8101) << "has next model";
+ return true;
+ }
+
+// kDebug(8101) << "doesn't have a next model, this is the last one...";
+ return false;
+}
+
+bool KompareModelList::hasPrevDiff() const
+{
+// kDebug(8101) << "KompareModelList::hasPrevDiff()";
+ int index = m_selectedModel->diffIndex();
+
+ if ( index > 0 )
+ {
+// kDebug(8101) << "has prev difference in same model";
+ return true;
+ }
+
+ if ( hasPrevModel() )
+ {
+// kDebug(8101) << "has prev difference but in prev model";
+ return true;
+ }
+
+// kDebug(8101) << "doesn't have a prev difference, not even in the previous model because there is no previous model";
+
+ return false;
+}
+
+bool KompareModelList::hasNextDiff() const
+{
+// kDebug(8101) << "KompareModelList::hasNextDiff()";
+ int index = m_selectedModel->diffIndex();
+
+ if ( index < ( m_selectedModel->differenceCount() - 1 ) )
+ {
+// kDebug(8101) << "has next difference in same model";
+ return true;
+ }
+
+ if ( hasNextModel() )
+ {
+// kDebug(8101) << "has next difference but in next model";
+ return true;
+ }
+
+// kDebug(8101) << "doesn't have a next difference, not even in next model because there is no next model";
+
+ return false;
+}
+
+void KompareModelList::slotActionApplyDifference()
+{
+ if ( !m_selectedDifference->applied() )
+ slotApplyDifference( true );
+ slotNextDifference();
+ updateModelListActions();
+}
+
+void KompareModelList::slotActionUnApplyDifference()
+{
+ if ( m_selectedDifference->applied() )
+ slotApplyDifference( false );
+ slotPreviousDifference();
+ updateModelListActions();
+}
+
+void KompareModelList::slotActionApplyAllDifferences()
+{
+ slotApplyAllDifferences( true );
+ updateModelListActions();
+}
+
+void KompareModelList::slotActionUnapplyAllDifferences()
+{
+ slotApplyAllDifferences( false );
+ updateModelListActions();
+}
+
+#include "komparemodellist.moc"
+
+/* vim: set ts=4 sw=4 noet: */
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp (revision 1522570)
@@ -0,0 +1,138 @@
+/**************************************************************************
+** parser.cpp
+** -------------------
+** begin : Sun Aug 4 15:05:35 2002
+** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "parser.h"
+#include <kdebug.h>
+
+#include "cvsdiffparser.h"
+#include "diffparser.h"
+#include "perforceparser.h"
+#include "diffmodel.h"
+
+using namespace Diff2;
+
+Parser::Parser( const KompareModelList* list ) :
+ m_list( list )
+{
+}
+
+Parser::~Parser()
+{
+}
+
+int Parser::cleanUpCrap( QStringList& diffLines )
+{
+ QStringList::Iterator it = diffLines.begin();
+
+ int nol = 0;
+
+ QString noNewLine( "\\ No newline" );
+
+ for ( ; it != diffLines.end(); ++it )
+ {
+ if ( (*it).startsWith( noNewLine ) )
+ {
+ it = diffLines.erase( it );
+ // correcting the advance of the iterator because of the remove
+ --it;
+ QString temp( *it );
+ temp.truncate( temp.indexOf( '\n' ) );
+ *it = temp;
+ ++nol;
+ }
+ }
+
+ return nol;
+}
+
+DiffModelList* Parser::parse( QStringList& diffLines )
+{
+ /* Basically determine the generator then call the parse method */
+ ParserBase* parser;
+
+ m_generator = determineGenerator( diffLines );
+
+ int nol = cleanUpCrap( diffLines );
+ kDebug(8101) << "Cleaned up" << nol << "line(s) of crap from the diff...";
+
+ switch( m_generator )
+ {
+ case Kompare::CVSDiff :
+ kDebug(8101) << "It is a CVS generated diff...";
+ parser = new CVSDiffParser( m_list, diffLines );
+ break;
+ case Kompare::Diff :
+ kDebug(8101) << "It is a diff generated diff...";
+ parser = new DiffParser( m_list, diffLines );
+ break;
+ case Kompare::Perforce :
+ kDebug(8101) << "It is a Perforce generated diff...";
+ parser = new PerforceParser( m_list, diffLines );
+ break;
+ default:
+ // Nothing to delete, just leave...
+ return 0L;
+ }
+
+ m_format = parser->format();
+ DiffModelList* modelList = parser->parse();
+ if ( modelList )
+ {
+ kDebug(8101) << "Modelcount:" << modelList->count();
+ DiffModelListIterator modelIt = modelList->begin();
+ DiffModelListIterator mEnd = modelList->end();
+ for ( ; modelIt != mEnd; ++modelIt )
+ {
+ kDebug(8101) << "Hunkcount:" << (*modelIt)->hunkCount();
+ kDebug(8101) << "Diffcount:" << (*modelIt)->differenceCount();
+ }
+ }
+
+ delete parser;
+
+ return modelList;
+}
+
+enum Kompare::Generator Parser::determineGenerator( const QStringList& diffLines )
+{
+ // Shit have to duplicate some code with this method and the ParserBase derived classes
+ QString cvsDiff ( "Index: " );
+ QString perforceDiff( "==== " );
+
+ QStringList::ConstIterator it = diffLines.begin();
+ QStringList::ConstIterator linesEnd = diffLines.end();
+
+ while ( it != linesEnd )
+ {
+ if ( ( *it ).startsWith( cvsDiff ) )
+ {
+ kDebug(8101) << "Diff is a CVSDiff";
+ return Kompare::CVSDiff;
+ }
+ else if ( ( *it ).startsWith( perforceDiff ) )
+ {
+ kDebug(8101) << "Diff is a Perforce Diff";
+ return Kompare::Perforce;
+ }
+ ++it;
+ }
+
+ kDebug(8101) << "We'll assume it is a diff Diff";
+
+ // For now we'll assume it is a diff file diff, later we might
+ // try to really determine if it is a diff file diff.
+ return Kompare::Diff;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp (revision 1522570)
@@ -0,0 +1,113 @@
+/***************************************************************************
+ diffhunk.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+
+#include "diffhunk.h"
+#include "difference.h"
+
+using namespace Diff2;
+
+DiffHunk::DiffHunk( int sourceLine, int destinationLine, const QString& function, Type type ) :
+ m_sourceLine( sourceLine ),
+ m_destinationLine( destinationLine ),
+ m_function( function ),
+ m_type( type )
+{
+}
+
+DiffHunk::~DiffHunk()
+{
+}
+
+void DiffHunk::add( Difference* diff )
+{
+ m_differences.append( diff );
+}
+
+int DiffHunk::sourceLineCount() const
+{
+ DifferenceListConstIterator diffIt = m_differences.begin();
+ DifferenceListConstIterator dEnd = m_differences.end();
+
+ int lineCount = 0;
+
+ for ( ; diffIt != dEnd; ++diffIt )
+ lineCount += (*diffIt)->sourceLineCount();
+
+ return lineCount;
+}
+
+int DiffHunk::destinationLineCount() const
+{
+ DifferenceListConstIterator diffIt = m_differences.begin();
+ DifferenceListConstIterator dEnd = m_differences.end();
+
+ int lineCount = 0;
+
+ for ( ; diffIt != dEnd; ++diffIt )
+ lineCount += (*diffIt)->destinationLineCount();
+
+ return lineCount;
+}
+
+QString DiffHunk::recreateHunk() const
+{
+ QString hunk;
+ QString differences;
+
+ // recreate body
+ DifferenceListConstIterator diffIt = m_differences.begin();
+ DifferenceListConstIterator dEnd = m_differences.end();
+
+ int slc = 0; // source line count
+ int dlc = 0; // destination line count
+ for ( ; diffIt != dEnd; ++diffIt )
+ {
+ switch ( (*diffIt)->type() )
+ {
+ case Difference::Unchanged:
+ case Difference::Change:
+ slc += (*diffIt)->sourceLineCount();
+ dlc += (*diffIt)->destinationLineCount();
+ break;
+ case Difference::Insert:
+ dlc += (*diffIt)->destinationLineCount();
+ break;
+ case Difference::Delete:
+ slc += (*diffIt)->sourceLineCount();
+ break;
+ }
+ differences += (*diffIt)->recreateDifference();
+ }
+
+ // recreate header
+ hunk += QString::fromLatin1( "@@ -%1,%3 +%2,%4 @@" )
+ .arg( m_sourceLine )
+ .arg( m_destinationLine )
+ .arg( slc )
+ .arg( dlc );
+
+ if ( !m_function.isEmpty() )
+ hunk += ' ' + m_function;
+
+ hunk += QString::fromLatin1( "\n" );
+
+ hunk += differences;
+
+ kDebug( 8101 ) << hunk;
+ return hunk;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp (revision 1522570)
@@ -0,0 +1,159 @@
+/**************************************************************************
+** cvsdiffparser.cpp
+** -----------------
+** begin : Sun Aug 4 15:05:35 2002
+** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+#include "cvsdiffparser.h"
+#include <qregexp.h>
+
+#include <kdebug.h>
+
+
+#include "komparemodellist.h"
+
+
+using namespace Diff2;
+
+CVSDiffParser::CVSDiffParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
+{
+ // The regexps needed for context cvs diff parsing, the rest is the same as in parserbase.cpp
+ // third capture in header1 is non optional for cvs diff, it is the revision
+ m_contextDiffHeader1.setPattern( "\\*\\*\\* ([^\\t]+)\\t([^\\t]+)\\t(.*)\\n" );
+ m_contextDiffHeader2.setPattern( "--- ([^\\t]+)\\t([^\\t]+)(|\\t(.*))\\n" );
+
+ m_normalDiffHeader.setPattern( "Index: (.*)\\n" );
+}
+
+CVSDiffParser::~CVSDiffParser()
+{
+}
+
+enum Kompare::Format CVSDiffParser::determineFormat()
+{
+// kDebug(8101) << "Determining the format of the CVSDiff";
+
+ QRegExp normalRE ( "[0-9]+[0-9,]*[acd][0-9]+[0-9,]*" );
+ QRegExp unifiedRE( "^--- [^\\t]+\\t" );
+ QRegExp contextRE( "^\\*\\*\\* [^\\t]+\\t" );
+ QRegExp rcsRE ( "^[acd][0-9]+ [0-9]+" );
+ QRegExp edRE ( "^[0-9]+[0-9,]*[acd]" );
+
+ QStringList::ConstIterator it = m_diffLines.begin();
+
+ while( it != m_diffLines.end() )
+ {
+ if( (*it).indexOf( normalRE, 0 ) == 0 )
+ {
+// kDebug(8101) << "Difflines are from a Normal diff...";
+ return Kompare::Normal;
+ }
+ else if( (*it).indexOf( unifiedRE, 0 ) == 0 )
+ {
+// kDebug(8101) << "Difflines are from a Unified diff...";
+ return Kompare::Unified;
+ }
+ else if( (*it).indexOf( contextRE, 0 ) == 0 )
+ {
+// kDebug(8101) << "Difflines are from a Context diff...";
+ return Kompare::Context;
+ }
+ else if( (*it).indexOf( rcsRE, 0 ) == 0 )
+ {
+// kDebug(8101) << "Difflines are from a RCS diff...";
+ return Kompare::RCS;
+ }
+ else if( (*it).indexOf( edRE, 0 ) == 0 )
+ {
+// kDebug(8101) << "Difflines are from an ED diff...";
+ return Kompare::Ed;
+ }
+ ++it;
+ }
+// kDebug(8101) << "Difflines are from an unknown diff...";
+ return Kompare::UnknownFormat;
+}
+
+bool CVSDiffParser::parseNormalDiffHeader()
+{
+ kDebug(8101) << "CVSDiffParser::parseNormalDiffHeader()";
+ bool result = false;
+
+ QStringList::ConstIterator diffEnd = m_diffLines.end();
+
+ while ( m_diffIterator != diffEnd )
+ {
+ if ( m_normalDiffHeader.exactMatch( *m_diffIterator ) )
+ {
+ kDebug(8101) << "Matched length Header =" << m_normalDiffHeader.matchedLength();
+ kDebug(8101) << "Matched string Header =" << m_normalDiffHeader.cap( 0 );
+
+ m_currentModel = new DiffModel();
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_currentModel->setSourceFile ( m_normalDiffHeader.cap( 1 ) );
+ m_currentModel->setDestinationFile ( m_normalDiffHeader.cap( 1 ) );
+
+ result = true;
+
+ ++m_diffIterator;
+ break;
+ }
+ else
+ {
+ kDebug(8101) << "No match for:" << ( *m_diffIterator );
+ }
+ ++m_diffIterator;
+ }
+
+ if ( result == false )
+ {
+ // Set this to the first line again and hope it is a single file diff
+ m_diffIterator = m_diffLines.begin();
+ m_currentModel = new DiffModel();
+ QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
+ m_singleFileDiff = true;
+ }
+
+ return result;
+}
+
+
+bool CVSDiffParser::parseEdDiffHeader()
+{
+ return false;
+}
+
+bool CVSDiffParser::parseRCSDiffHeader()
+{
+ return false;
+}
+
+bool CVSDiffParser::parseEdHunkHeader()
+{
+ return false;
+}
+
+bool CVSDiffParser::parseRCSHunkHeader()
+{
+ return false;
+}
+
+bool CVSDiffParser::parseEdHunkBody()
+{
+ return false;
+}
+
+bool CVSDiffParser::parseRCSHunkBody()
+{
+ return false;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp (revision 1522570)
@@ -0,0 +1,141 @@
+/***************************************************************************
+ difference.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "difference.h"
+#include "levenshteintable.h"
+
+using namespace Diff2;
+
+Difference::Difference( int sourceLineNo, int destinationLineNo, int type ) :
+ m_type( type ),
+ m_sourceLineNo( sourceLineNo ),
+ m_destinationLineNo( destinationLineNo ),
+ m_applied( false ),
+ m_table( new LevenshteinTable() )
+{
+}
+
+Difference::~Difference()
+{
+ delete m_table;
+}
+
+void Difference::addSourceLine( const QString& line )
+{
+ m_sourceLines.append( new DifferenceString( line ) );
+}
+
+void Difference::addDestinationLine( const QString& line )
+{
+ m_destinationLines.append( new DifferenceString( line ) );
+}
+
+int Difference::sourceLineCount() const
+{
+ return m_sourceLines.count();
+}
+
+int Difference::destinationLineCount() const
+{
+ return m_destinationLines.count();
+}
+
+void Difference::apply( bool apply )
+{
+ m_applied = apply;
+}
+
+void Difference::determineInlineDifferences()
+{
+ if ( m_type != Difference::Change )
+ return;
+
+ // Do nothing for now when the slc != dlc
+ // One could try to find the closest matching destination string for any
+ // of the source strings but this is compute intensive
+ if ( sourceLineCount() != destinationLineCount() )
+ return;
+
+ int slc = sourceLineCount();
+
+ for ( int i = 0; i < slc; ++i )
+ {
+ DifferenceString* sl = sourceLineAt( i );
+ DifferenceString* dl = destinationLineAt( i );
+
+ // FIXME: If the table cant be created do not do the rest
+ m_table->createTable( sl, dl );
+
+ m_table->createListsOfMarkers();
+ }
+
+ // No longer needed, if we ever need to recalculate the inline differences we should
+ // simply recreate the table
+ delete m_table;
+ m_table = 0;
+}
+
+QString Difference::recreateDifference() const
+{
+ QString difference;
+
+ // source
+ DifferenceStringListConstIterator stringIt = m_sourceLines.begin();
+ DifferenceStringListConstIterator sEnd = m_sourceLines.end();
+
+ for ( ; stringIt != sEnd; ++stringIt )
+ {
+ switch ( m_type )
+ {
+ case Change:
+ case Delete:
+ difference += '-';
+ break;
+ default:
+ // Insert but this is not possible in source
+ // Unchanged will be handled in destination
+ // since they are the same
+// kDebug( 8101 ) << "Go away, nothing to do for you in source...";
+ continue;
+ }
+ difference += (*stringIt)->string();
+ }
+
+ //destination
+ stringIt = m_destinationLines.begin();
+ sEnd = m_destinationLines.end();
+
+ for ( ; stringIt != sEnd; ++stringIt )
+ {
+ switch ( m_type )
+ {
+ case Change:
+ case Insert:
+ difference += '+';
+ break;
+ case Unchanged:
+ difference += ' ';
+ break;
+ default: // Delete but this is not possible in destination
+// kDebug( 8101 ) << "Go away, nothing to do for you in destination...";
+ continue;
+ }
+ difference += (*stringIt)->string();
+ }
+
+ return difference;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp (revision 1522570)
@@ -0,0 +1,331 @@
+/*******************************************************************************
+**
+** Filename : levenshteintable.cpp
+** Created on : 08 november, 2003
+** Copyright : (c) 2003 Otto Bruggeman <bruggie@home.nl>
+**
+*******************************************************************************/
+
+/*******************************************************************************
+**
+** 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.
+**
+*******************************************************************************/
+
+#include "levenshteintable.h"
+#include <iostream>
+
+#include <qstring.h>
+
+#include <kdebug.h>
+#include <kglobal.h>
+
+
+#include "difference.h"
+
+using namespace Diff2;
+
+LevenshteinTable::LevenshteinTable()
+ : m_width( 256 ),
+ m_height( 256 ),
+ m_size( m_height * m_width ),
+ m_table( new unsigned int[ m_size ] ),
+ m_source( 0 ),
+ m_destination( 0 )
+{
+}
+
+LevenshteinTable::LevenshteinTable( unsigned int width, unsigned int height )
+ : m_width( width ),
+ m_height( height ),
+ m_size( m_width * m_height ),
+ m_table( new unsigned int[ m_size ] ),
+ m_source( 0 ),
+ m_destination( 0 )
+{
+}
+
+LevenshteinTable::~LevenshteinTable()
+{
+ delete[] m_table;
+ m_source = 0;
+ m_destination = 0;
+}
+
+int LevenshteinTable::getContent( unsigned int posX, unsigned int posY ) const
+{
+// kDebug(8101) << "Width =" << m_width << ", height =" << m_height << ", posX =" << posX << ", posY =" << posY;
+ return m_table[ posY * m_width + posX ];
+}
+
+int LevenshteinTable::setContent( unsigned int posX, unsigned int posY, int value )
+{
+ m_table[ posY * m_width + posX ] = value;
+
+ return 0;
+}
+
+bool LevenshteinTable::setSize( unsigned int width, unsigned int height )
+{
+ // Set a limit of 16.7 million entries, will be about 64 MB of ram, that should be plenty
+ if ( ( ( width ) * ( height ) ) > ( 256 * 256 * 256 ) )
+ return false;
+
+ if ( ( ( width ) * ( height ) ) > m_size )
+ {
+ delete[] m_table;
+
+ m_size = width * height;
+ m_table = new unsigned int[ m_size ];
+ }
+
+ m_width = width;
+ m_height = height;
+
+ return true;
+}
+
+void LevenshteinTable::dumpLevenshteinTable()
+{
+ for ( unsigned int i = 0; i < m_height; ++i )
+ {
+ for ( unsigned int j = 0; j < m_width; ++j )
+ {
+ std::cout.width( 3 );
+ std::cout << getContent( j, i );
+ }
+ std::cout << std::endl;
+ }
+}
+
+unsigned int LevenshteinTable::createTable( DifferenceString* source, DifferenceString* destination )
+{
+ m_source = source;
+ m_destination = destination;
+
+ QString s = ' ' + source->string(); // Optimization, so i do not have to subtract 1 from the indexes every
+ QString d = ' ' + destination->string(); // single time and add 1 to the width and height of the table
+
+ unsigned int m = s.length();
+ unsigned int n = d.length();
+
+ const QChar* sq = s.unicode();
+ const QChar* dq = d.unicode();
+
+ if ( m == 1 )
+ return --n;
+
+ if ( n == 1 )
+ return --m;
+
+ if ( !setSize( m, n ) )
+ return 0;
+
+ unsigned int i;
+ unsigned int j;
+
+ // initialize first row
+ for ( i = 0; i < m; ++i )
+ setContent( i, 0, i );
+ // initialize first column
+ for ( j = 0; j < n; ++j )
+ setContent( 0, j, j );
+
+ int cost = 0, north = 0, west = 0, northwest = 0;
+
+ ushort si, dj;
+ // Optimization, calculate row wise instead of column wise, wont trash the cache so much with large strings
+ for ( j = 1; j < n; ++j )
+ {
+ dj = QString(dq[ j ]).toInt();
+
+ for ( i = 1; i < m; ++i )
+ {
+ si = QString(sq[ i ]).toInt();
+ if ( si == dj )
+ cost = 0;
+ else
+ cost = 1;
+
+ north = getContent( i, j-1 ) + 1;
+ west = getContent( i-1, j ) + 1;
+ northwest = getContent( i-1, j-1 ) + cost;
+
+ setContent( i, j, qMin( north, qMin( west, northwest ) ) );
+ }
+ }
+
+ return getContent( m-1, n-1 );
+}
+
+int LevenshteinTable::chooseRoute( int c1, int c2, int c3 )
+{
+// kDebug(8101) << "c1 =" << c1 << ", c2 =" << c2 << ", c3 =" << c3;
+ // preference order: c2, c3, c1, hopefully this will work out for me
+ if ( c2 <= c1 && c2 <= c3 )
+ return 1;
+
+ if ( c3 <= c2 && c3 <= c1 )
+ return 2;
+
+ return 0;
+}
+
+void LevenshteinTable::createListsOfMarkers()
+{
+// std::cout << source.latin1() << std::endl;
+// std::cout << destination.latin1() << std::endl;
+// dumpLevenshteinTable();
+
+ unsigned int x = m_width-1;
+ unsigned int y = m_height-1;
+
+ Marker* c = 0;
+
+ int n, nw, w, direction, currentValue;
+ while ( x > 0 && y > 0 )
+ {
+ currentValue = getContent( x, y );
+
+ nw = getContent( x - 1, y - 1 );
+ n = getContent( x, y - 1 );
+ w = getContent( x - 1, y );
+
+ direction = chooseRoute( n, nw, w );
+
+ switch ( direction )
+ {
+ case 0: // north
+// kDebug(8101) << "Picking north";
+// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
+
+ if ( !m_destination->markerList().isEmpty() )
+ c = m_destination->markerList().first();
+ else
+ c = 0;
+
+ if ( c && c->type() == Marker::End )
+ {
+// kDebug(8101) << "CurrentValue:" << currentValue;
+ if ( n == currentValue )
+ m_destination->prepend( new Marker( Marker::Start, y ) );
+ // else: the change continues, do not do anything
+ }
+ else
+ {
+// kDebug(8101) << "CurrentValue:" << currentValue;
+ if ( n < currentValue )
+ m_destination->prepend( new Marker( Marker::End, y ) );
+ }
+
+ --y;
+ break;
+ case 1: // northwest
+// kDebug(8101) << "Picking northwest";
+// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
+
+ if ( !m_destination->markerList().isEmpty() )
+ c = m_destination->markerList().first();
+ else
+ c = 0;
+
+ if ( c && c->type() == Marker::End )
+ {
+// kDebug(8101) << "End found: CurrentValue:" << currentValue;
+ if ( nw == currentValue )
+ m_destination->prepend( new Marker( Marker::Start, y ) );
+ // else: the change continues, do not do anything
+ }
+ else
+ {
+// kDebug(8101) << "CurrentValue:" << currentValue;
+ if ( nw < currentValue )
+ m_destination->prepend( new Marker( Marker::End, y ) );
+ }
+
+ if ( !m_source->markerList().isEmpty() )
+ c = m_source->markerList().first();
+ else
+ c = 0;
+
+ if ( c && c->type() == Marker::End )
+ {
+// kDebug(8101) << "End found: CurrentValue:" << currentValue;
+ if ( nw == currentValue )
+ m_source->prepend( new Marker( Marker::Start, x ) );
+ // else: the change continues, do not do anything
+ }
+ else
+ {
+// kDebug(8101) << "CurrentValue:" << currentValue;
+ if ( nw < currentValue )
+ m_source->prepend( new Marker( Marker::End, x ) );
+ }
+
+ --y;
+ --x;
+ break;
+ case 2: // west
+// kDebug(8101) << "Picking west";
+// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
+
+ if ( !m_source->markerList().isEmpty() )
+ c = m_source->markerList().first();
+ else
+ c = 0;
+
+ if ( c && c->type() == Marker::End )
+ {
+// kDebug(8101) << "End found: CurrentValue:" << currentValue;
+ if ( w == currentValue )
+ m_source->prepend( new Marker( Marker::Start, x ) );
+ // else: the change continues, do not do anything
+ }
+ else
+ {
+// kDebug(8101) << "CurrentValue:" << currentValue;
+ if ( w < currentValue )
+ m_source->prepend( new Marker( Marker::End, x ) );
+ }
+
+ --x;
+ break;
+ }
+ }
+
+// kDebug(8101) << "Source string:" << m_source->string();
+// c = m_source->markerList()->first();
+// QStringList list;
+// unsigned int prevValue = 0;
+// for ( ; c; c = m_source->markerList()->next() )
+// {
+// kDebug(8101) << "Source Marker Entry : Type:" << c->type() << ", Offset:" << c->offset();
+// list.append( m_source->string().mid( prevValue, c->offset() - prevValue ) );
+// prevValue = c->offset();
+// }
+// if ( prevValue < m_source->string().length() - 1 )
+// {
+// list.append( m_source->string().mid( prevValue, m_source->string().length() - prevValue ) );
+// }
+// kDebug(8101) << "Source Resulting stringlist :" << list.join("\n");
+
+// list.clear();
+// prevValue = 0;
+
+// kDebug(8101) << "Destination string:" << m_destination->string();
+// for ( ; c; c = m_destination->markerList()->next() )
+// {
+// kDebug(8101) << "Destination Marker Entry : Type:" << c->type() << ", Offset:" << c->offset();
+// list.append( m_destination->string().mid( prevValue, c->offset() - prevValue ) );
+// prevValue = c->offset();
+// }
+// if ( prevValue < m_destination->string().length() - 1 )
+// {
+// list.append( m_destination->string().mid( prevValue, m_destination->string().length() - prevValue ) );
+// }
+// kDebug(8101) << "Destination Resulting string :" << list.join("\n");
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp (revision 1522570)
@@ -0,0 +1,268 @@
+/***************************************************************************
+ kompareprocess.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "kompareprocess.h"
+#include <qdir.h>
+#include <qstringlist.h>
+#include <qtextcodec.h>
+//Added by qt3to4:
+#include <Q3ValueList>
+#include <Q3CString>
+
+#include <kcharsets.h>
+#include <kdebug.h>
+#include <kglobal.h>
+
+#include "diffsettings.h"
+
+
+KompareProcess::KompareProcess( DiffSettings* diffSettings, enum Kompare::DiffMode mode, const QString& source, const QString& destination, const QString& dir )
+ : m_diffSettings( diffSettings ),
+ m_mode( mode ),
+ m_textDecoder( 0 ),
+ m_proc(new QProcess)
+{
+
+ // connect the stdout and stderr signals
+ connect( m_proc, SIGNAL( readyReadStandardOutput() ),
+ SLOT ( slotReceivedStdout( ) ) );
+ connect( this, SIGNAL( readyReadStandardError() ),
+ SLOT ( slotReceivedStderr( ) ) );
+
+ // connect the signal that indicates that the proces has exited
+ connect( this, SIGNAL( finished( int, QProcess::ExitStatus ) ),
+ SLOT ( slotProcessExited( int, QProcess::ExitStatus ) ) );
+
+ m_env << "LANG=C";
+
+ // Write command and options
+ if( m_mode == Kompare::Default )
+ {
+ writeDefaultCommandLine();
+ }
+ else
+ {
+ writeCommandLine();
+ }
+
+ if( !dir.isEmpty() ) {
+ m_proc->setWorkingDirectory( dir );
+ }
+
+ // Write file names
+ m_args << "--";
+ m_args << constructRelativePath( dir, source );
+ m_args << constructRelativePath( dir, destination );
+}
+
+void KompareProcess::writeDefaultCommandLine()
+{
+ if ( !m_diffSettings || m_diffSettings->m_diffProgram.isEmpty() )
+ {
+ m_prog = "diff";
+ m_args << "-dr";
+ }
+ else
+ {
+ m_prog = m_diffSettings->m_diffProgram;
+ m_args << "-dr";
+ }
+
+ m_args << "-U" << QString::number( m_diffSettings->m_linesOfContext );
+}
+
+void KompareProcess::writeCommandLine()
+{
+ // load the executable into the K3Process
+ if ( m_diffSettings->m_diffProgram.isEmpty() )
+ {
+ kDebug(8101) << "Using the first diff in the path...";
+ m_prog = "diff";
+ }
+ else
+ {
+ kDebug(8101) << "Using a user specified diff, namely:" << m_diffSettings->m_diffProgram;
+ m_prog = m_diffSettings->m_diffProgram;
+ }
+
+ switch( m_diffSettings->m_format ) {
+ case Kompare::Unified :
+ m_args << "-U" << QString::number( m_diffSettings->m_linesOfContext );
+ break;
+ case Kompare::Context :
+ m_args << "-C" << QString::number( m_diffSettings->m_linesOfContext );
+ break;
+ case Kompare::RCS :
+ m_args << "-n";
+ break;
+ case Kompare::Ed :
+ m_args << "-e";
+ break;
+ case Kompare::SideBySide:
+ m_args << "-y";
+ break;
+ case Kompare::Normal :
+ case Kompare::UnknownFormat :
+ default:
+ break;
+ }
+
+ if ( m_diffSettings->m_largeFiles
+// default diff does not have -H on OpenBSD
+// so don't pass this option unless the user overrode the default program
+#if defined(__OpenBSD__) //krazy:exclude=cpp
+ && !m_diffSettings->m_diffProgram.isEmpty()
+#endif
+ )
+ {
+ m_args << "-H";
+ }
+
+ if ( m_diffSettings->m_ignoreWhiteSpace )
+ {
+ m_args << "-b";
+ }
+
+ if ( m_diffSettings->m_ignoreAllWhiteSpace )
+ {
+ m_args << "-w";
+ }
+
+ if ( m_diffSettings->m_ignoreEmptyLines )
+ {
+ m_args << "-B";
+ }
+
+ if ( m_diffSettings->m_ignoreChangesDueToTabExpansion )
+ {
+ m_args << "-E";
+ }
+
+ if ( m_diffSettings->m_createSmallerDiff )
+ {
+ m_args << "-d";
+ }
+
+ if ( m_diffSettings->m_ignoreChangesInCase )
+ {
+ m_args << "-i";
+ }
+
+ if ( m_diffSettings->m_ignoreRegExp && !m_diffSettings->m_ignoreRegExpText.isEmpty() )
+ {
+ m_args << "-I" << m_diffSettings->m_ignoreRegExpText;
+ }
+
+ if ( m_diffSettings->m_showCFunctionChange )
+ {
+ m_args << "-p";
+ }
+
+ if ( m_diffSettings->m_convertTabsToSpaces )
+ {
+ m_args << "-t";
+ }
+
+ if ( m_diffSettings->m_recursive )
+ {
+ m_args << "-r";
+ }
+
+ if ( m_diffSettings->m_newFiles )
+ {
+ m_args << "-N";
+ }
+
+// This option is more trouble than it is worth... please do not ever enable it unless you want really weird crashes
+// if ( m_diffSettings->m_allText )
+// {
+// *this << "-a";
+// }
+
+ if ( m_diffSettings->m_excludeFilePattern )
+ {
+ QStringList::ConstIterator it = m_diffSettings->m_excludeFilePatternList.begin();
+ QStringList::ConstIterator end = m_diffSettings->m_excludeFilePatternList.end();
+ for ( ; it != end; ++it )
+ {
+ m_args << "-x" << *it ;
+ }
+ }
+
+ if ( m_diffSettings->m_excludeFilesFile && !m_diffSettings->m_excludeFilesFileURL.isEmpty() )
+ {
+ m_args << "-X" << m_diffSettings->m_excludeFilesFileURL;
+ }
+}
+
+KompareProcess::~KompareProcess()
+{
+ delete m_proc;
+}
+
+void KompareProcess::setEncoding( const QString& encoding )
+{
+ QTextCodec* textCodec = KGlobal::charsets()->codecForName( encoding.toLatin1() );
+ if ( textCodec )
+ m_textDecoder = textCodec->makeDecoder();
+ else
+ {
+ kDebug(8101) << "Using locale codec as backup...";
+ textCodec = QTextCodec::codecForLocale();
+ m_textDecoder = textCodec->makeDecoder();
+ }
+}
+
+void KompareProcess::slotReceivedStdout( )
+{
+ m_stdout += m_proc->readAllStandardOutput();
+}
+
+void KompareProcess::slotReceivedStderr( )
+{
+ m_stderr += m_proc->readAllStandardError();
+}
+
+void KompareProcess::start()
+{
+#ifndef NDEBUG
+ QString cmdLine;
+ QStringList::ConstIterator it = m_args.begin();
+ for (; it != m_args.end(); ++it )
+ cmdLine += "\"" + (*it) + "\" ";
+ kDebug(8101) << cmdLine;
+#endif
+ m_proc->setEnvironment(m_env);
+ m_proc->start(m_prog, m_args);
+}
+
+QProcess* KompareProcess::process()
+{
+ return m_proc;
+}
+
+void KompareProcess::slotProcessExited( int code, QProcess::ExitStatus status )
+{
+ // exit status of 0: no differences
+ // 1: some differences
+ // 2: error but there may be differences !
+ kDebug(8101) << "Exited with exit status :" << status;
+ emit diffHasFinished( code == 0 && status != QProcess::CrashExit );
+}
+
+#include "kompareprocess.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp (revision 1522570)
@@ -0,0 +1,222 @@
+/**************************************************************************
+** perforceparser.cpp
+** ------------------
+** begin : Sun Aug 4 15:05:35 2002
+** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "perforceparser.h"
+#include <qregexp.h>
+
+#include <kdebug.h>
+
+
+using namespace Diff2;
+
+PerforceParser::PerforceParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
+{
+ m_contextDiffHeader1.setPattern( "==== (.*) - (.*) ====\\n" );
+ m_contextDiffHeader1.setMinimal( true );
+ m_normalDiffHeader.setPattern ( "==== (.*) - (.*) ====\\n" );
+ m_normalDiffHeader.setMinimal ( true );
+ m_rcsDiffHeader.setPattern ( "==== (.*) - (.*) ====\\n" );
+ m_rcsDiffHeader.setMinimal ( true );
+ m_unifiedDiffHeader1.setPattern( "==== (.*) - (.*) ====\\n" );
+ m_unifiedDiffHeader1.setMinimal( true );
+}
+
+PerforceParser::~PerforceParser()
+{
+}
+
+enum Kompare::Format PerforceParser::determineFormat()
+{
+ kDebug(8101) << "Determining the format of the Perforce Diff";
+
+ QRegExp unifiedRE( "^@@" );
+ QRegExp contextRE( "^\\*{15}" );
+ QRegExp normalRE ( "^\\d+(|,\\d+)[acd]\\d+(|,\\d+)" );
+ QRegExp rcsRE ( "^[acd]\\d+ \\d+" );
+ // Summary is not supported since it gives no useful parsable info
+
+ QStringList::ConstIterator it = m_diffLines.begin();
+
+ while( it != m_diffLines.end() )
+ {
+ if( (*it).indexOf( unifiedRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Unified diff...";
+ return Kompare::Unified;
+ }
+ else if( (*it).indexOf( contextRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Context diff...";
+ return Kompare::Context;
+ }
+ else if( (*it).indexOf( normalRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Normal diff...";
+ return Kompare::Normal;
+ }
+ else if( (*it).indexOf( rcsRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a RCS diff...";
+ return Kompare::RCS;
+ }
+ ++it;
+ }
+ kDebug(8101) << "Difflines are from an unknown diff...";
+ return Kompare::UnknownFormat;
+}
+
+bool PerforceParser::parseContextDiffHeader()
+{
+// kDebug(8101) << "ParserBase::parseContextDiffHeader()";
+ bool result = false;
+
+ QStringList::ConstIterator itEnd = m_diffLines.end();
+
+ QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
+ QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
+
+ while ( m_diffIterator != itEnd )
+ {
+ if ( m_contextDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
+ {
+// kDebug(8101) << "Matched length Header1 =" << m_contextDiffHeader1.matchedLength();
+// kDebug(8101) << "Matched string Header1 =" << m_contextDiffHeader1.cap( 0 );
+// kDebug(8101) << "First capture Header1 =" << m_contextDiffHeader1.cap( 1 );
+// kDebug(8101) << "Second capture Header1 =" << m_contextDiffHeader1.cap( 2 );
+
+ m_currentModel = new DiffModel();
+ sourceFileRE.exactMatch( m_contextDiffHeader1.cap( 1 ) );
+ destinationFileRE.exactMatch( m_contextDiffHeader1.cap( 2 ) );
+ kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
+ kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
+ kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
+ kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
+ kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
+ kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
+ m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
+ m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
+
+ result = true;
+
+ break;
+ }
+ else
+ {
+ kDebug(8101) << "Matched length =" << m_contextDiffHeader1.matchedLength();
+ kDebug(8101) << "Captured texts =" << m_contextDiffHeader1.capturedTexts();
+ }
+ }
+
+ return result;
+}
+
+bool PerforceParser::parseNormalDiffHeader()
+{
+ bool result = false;
+
+ QStringList::ConstIterator itEnd = m_diffLines.end();
+
+ QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
+ QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
+
+ while ( m_diffIterator != itEnd )
+ {
+ kDebug(8101) << "Line =" << *m_diffIterator;
+ kDebug(8101) << "String length =" << (*m_diffIterator).length();
+ if ( m_normalDiffHeader.exactMatch( *(m_diffIterator)++ ) )
+ {
+ kDebug(8101) << "Matched length Header1 =" << m_normalDiffHeader.matchedLength();
+ kDebug(8101) << "Matched string Header1 =" << m_normalDiffHeader.cap( 0 );
+ kDebug(8101) << "First capture Header1 = \"" << m_normalDiffHeader.cap( 1 ) << "\"";
+ kDebug(8101) << "Second capture Header1 = \"" << m_normalDiffHeader.cap( 2 ) << "\"";
+
+ m_currentModel = new DiffModel();
+ sourceFileRE.exactMatch( m_normalDiffHeader.cap( 1 ) );
+ destinationFileRE.exactMatch( m_normalDiffHeader.cap( 2 ) );
+ kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
+ kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
+ kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
+ kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
+ kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
+ kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
+ m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
+ m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
+
+ result = true;
+
+ break;
+ }
+ else
+ {
+ kDebug(8101) << "Matched length =" << m_normalDiffHeader.matchedLength();
+ kDebug(8101) << "Captured texts =" << m_normalDiffHeader.capturedTexts();
+ }
+ }
+
+ return result;
+}
+
+bool PerforceParser::parseRCSDiffHeader()
+{
+ return false;
+}
+
+bool PerforceParser::parseUnifiedDiffHeader()
+{
+ bool result = false;
+
+ QStringList::ConstIterator itEnd = m_diffLines.end();
+
+ QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
+ QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
+
+ while ( m_diffIterator != itEnd )
+ {
+// kDebug(8101) << "Line =" << *m_diffIterator;
+// kDebug(8101) << "String length =" << (*m_diffIterator).length();
+ if ( m_unifiedDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
+ {
+// kDebug(8101) << "Matched length Header1 =" << m_unifiedDiffHeader1.matchedLength();
+// kDebug(8101) << "Matched string Header1 =" << m_unifiedDiffHeader1.cap( 0 );
+// kDebug(8101) << "First capture Header1 = \"" << m_unifiedDiffHeader1.cap( 1 ) << "\"";
+// kDebug(8101) << "Second capture Header1 = \"" << m_unifiedDiffHeader1.cap( 2 ) << "\"";
+
+ m_currentModel = new DiffModel();
+ sourceFileRE.exactMatch( m_unifiedDiffHeader1.cap( 1 ) );
+ destinationFileRE.exactMatch( m_unifiedDiffHeader1.cap( 2 ) );
+// kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
+// kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
+// kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
+// kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
+// kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
+// kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
+ m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
+ m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
+
+ result = true;
+
+ break;
+ }
+ else
+ {
+// kDebug(8101) << "Matched length =" << m_unifiedDiffHeader1.matchedLength();
+// kDebug(8101) << "Captured texts =" << m_unifiedDiffHeader1.capturedTexts();
+ }
+ }
+
+ return result;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp (revision 1522570)
@@ -0,0 +1,80 @@
+/**************************************************************************
+** diffparser.cpp
+** --------------
+** begin : Sun Aug 4 15:05:35 2002
+** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "diffparser.h"
+#include <qregexp.h>
+
+#include <kdebug.h>
+
+
+using namespace Diff2;
+
+DiffParser::DiffParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
+{
+ // The regexps needed for context diff parsing, the rest is the same as in parserbase.cpp
+ m_contextDiffHeader1.setPattern( "\\*\\*\\* ([^\\t]+)\\t([^\\t]+)\\n" );
+ m_contextDiffHeader2.setPattern( "--- ([^\\t]+)\\t([^\\t]+)\\n" );
+}
+
+DiffParser::~DiffParser()
+{
+}
+
+enum Kompare::Format DiffParser::determineFormat()
+{
+ kDebug(8101) << "Determining the format of the diff Diff";
+
+ QRegExp normalRE ( "[0-9]+[0-9,]*[acd][0-9]+[0-9,]*" );
+ QRegExp unifiedRE( "^--- " );
+ QRegExp contextRE( "^\\*\\*\\* " );
+ QRegExp rcsRE ( "^[acd][0-9]+ [0-9]+" );
+ QRegExp edRE ( "^[0-9]+[0-9,]*[acd]" );
+
+ QStringList::ConstIterator it = m_diffLines.begin();
+
+ while( it != m_diffLines.end() )
+ {
+ kDebug(8101) << (*it);
+ if( (*it).indexOf( normalRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Normal diff...";
+ return Kompare::Normal;
+ }
+ else if( (*it).indexOf( unifiedRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Unified diff...";
+ return Kompare::Unified;
+ }
+ else if( (*it).indexOf( contextRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from a Context diff...";
+ return Kompare::Context;
+ }
+ else if( (*it).indexOf( rcsRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from an RCS diff...";
+ return Kompare::RCS;
+ }
+ else if( (*it).indexOf( edRE, 0 ) == 0 )
+ {
+ kDebug(8101) << "Difflines are from an ED diff...";
+ return Kompare::Ed;
+ }
+ ++it;
+ }
+ kDebug(8101) << "Difflines are from an unknown diff...";
+ return Kompare::UnknownFormat;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp (revision 1522570)
@@ -0,0 +1,107 @@
+/***************************************************************************
+ diffsettings.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2004 Otto Bruggeman <otto.bruggeman@home.nl>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+****************************************************************************/
+
+#include "diffsettings.h"
+#include <kconfig.h>
+
+
+DiffSettings::DiffSettings( QWidget* parent )
+ : SettingsBase( parent ),
+ m_linesOfContext( 0 ),
+ m_format( Kompare::Unified ),
+ m_largeFiles( false ),
+ m_ignoreWhiteSpace( false ),
+ m_ignoreAllWhiteSpace( false ),
+ m_ignoreEmptyLines( false ),
+ m_ignoreChangesDueToTabExpansion( false ),
+ m_createSmallerDiff( false ),
+ m_ignoreChangesInCase( false ),
+ m_showCFunctionChange( false ),
+ m_convertTabsToSpaces( false ),
+ m_ignoreRegExp( false ),
+ m_recursive( false ),
+ m_newFiles( false ),
+ m_excludeFilePattern( false ),
+ m_excludeFilesFile( false )
+{
+}
+
+DiffSettings::~DiffSettings()
+{
+}
+
+void DiffSettings::loadSettings( KConfig* config )
+{/*
+ KConfigGroup group( config, "Diff Options" );
+ m_diffProgram = group.readEntry ( "DiffProgram", "" );
+ m_linesOfContext = group.readEntry( "LinesOfContext", QVariant(3) ).asInt();
+ m_largeFiles = group.readBoolEntry( "LargeFiles", true );
+ m_ignoreWhiteSpace = group.readBoolEntry( "IgnoreWhiteSpace", false );
+ m_ignoreAllWhiteSpace = group.readBoolEntry( "IgnoreAllWhiteSpace", false );
+ m_ignoreEmptyLines = group.readBoolEntry( "IgnoreEmptyLines", false );
+ m_ignoreChangesDueToTabExpansion = group.readBoolEntry( "IgnoreChangesDueToTabExpansion", false );
+ m_ignoreChangesInCase = group.readBoolEntry( "IgnoreChangesInCase", false );
+ m_ignoreRegExp = group.readBoolEntry( "IgnoreRegExp", false );
+ m_ignoreRegExpText = group.readEntry ( "IgnoreRegExpText", "" );
+ m_ignoreRegExpTextHistory = group.readListEntry( "IgnoreRegExpTextHistory" );
+ m_createSmallerDiff = group.readBoolEntry( "CreateSmallerDiff", true );
+ m_convertTabsToSpaces = group.readBoolEntry( "ConvertTabsToSpaces", false );
+ m_showCFunctionChange = group.readBoolEntry( "ShowCFunctionChange", false );
+ m_recursive = group.readBoolEntry( "CompareRecursively", true );
+ m_newFiles = group.readBoolEntry( "NewFiles", true );
+
+ m_format = static_cast<Kompare::Format>( group.readNumEntry( "Format", Kompare::Unified ) );
+
+ KConfigGroup group2 ( config, "Exclude File Options" );
+ m_excludeFilePattern = group2.readBoolEntry( "Pattern", false );
+ m_excludeFilePatternList = group2.readListEntry( "PatternList" );
+ m_excludeFilesFile = group2.readBoolEntry( "File", false );
+ m_excludeFilesFileURL = group2.readEntry ( "FileURL", "" );
+ m_excludeFilesFileHistoryList = group2.readListEntry( "FileHistoryList" );*/
+}
+
+void DiffSettings::saveSettings( KConfig* config )
+{/*
+ KConfigGroup group( config, "Diff Options" );
+ group.writeEntry( "DiffProgram", m_diffProgram );
+ group.writeEntry( "LinesOfContext", m_linesOfContext );
+ group.writeEntry( "Format", QString(m_format) );
+ group.writeEntry( "LargeFiles", m_largeFiles );
+ group.writeEntry( "IgnoreWhiteSpace", m_ignoreWhiteSpace );
+ group.writeEntry( "IgnoreAllWhiteSpace", m_ignoreAllWhiteSpace );
+ group.writeEntry( "IgnoreEmptyLines", m_ignoreEmptyLines );
+ group.writeEntry( "IgnoreChangesInCase", m_ignoreChangesInCase );
+ group.writeEntry( "IgnoreChangesDueToTabExpansion", m_ignoreChangesDueToTabExpansion );
+ group.writeEntry( "IgnoreRegExp", m_ignoreRegExp );
+ group.writeEntry( "IgnoreRegExpText", m_ignoreRegExpText );
+ group.writeEntry( "IgnoreRegExpTextHistory", m_ignoreRegExpTextHistory );
+ group.writeEntry( "CreateSmallerDiff", m_createSmallerDiff );
+ group.writeEntry( "ConvertTabsToSpaces", m_convertTabsToSpaces );
+ group.writeEntry( "ShowCFunctionChange", m_showCFunctionChange );
+ group.writeEntry( "CompareRecursively", m_recursive );
+ group.writeEntry( "NewFiles", m_newFiles );
+ group.setDirty( true );
+
+ KConfigGroup group2( config, "Exclude File Options" );
+ group2.writeEntry( "Pattern", m_excludeFilePattern );
+ group2.writeEntry( "PatternList", m_excludeFilePatternList );
+ group2.writeEntry( "File", m_excludeFilesFile );
+ group2.writeEntry( "FileURL", m_excludeFilesFileURL );
+ group2.writeEntry( "FileHistoryList", m_excludeFilesFileHistoryList );
+ group2.setDirty( true );*/
+}
+
+#include "diffsettings.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README (revision 1522570)
@@ -0,0 +1 @@
+This library is mainly a slightly modified copy from kompare's libdiff2. Maybe both should be merged to one reusable library some time.
\ No newline at end of file
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h (revision 1522570)
@@ -0,0 +1,57 @@
+/**************************************************************************
+** parser.h
+** --------
+** begin : Tue Jul 30 23:53:52 2002
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef _DIFF2_PARSER_H
+#define _DIFF2_PARSER_H
+
+#include "diffmodellist.h"
+#include "kompare.h"
+
+namespace Diff2
+{
+
+class DiffModel;
+class KompareModelList;
+
+class Parser
+{
+public:
+ Parser( const KompareModelList* list );
+ ~Parser();
+
+public:
+ DiffModelList* parse( QStringList& diffLines );
+
+ enum Kompare::Generator generator() const { return m_generator; };
+ enum Kompare::Format format() const { return m_format; };
+
+private:
+ /** Which program was used to generate the output */
+ enum Kompare::Generator determineGenerator( const QStringList& diffLines );
+
+ int cleanUpCrap( QStringList& diffLines );
+
+private:
+ enum Kompare::Generator m_generator;
+ enum Kompare::Format m_format;
+
+ const KompareModelList* m_list;
+};
+
+} // End of namespace Diff2
+
+#endif
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h (revision 1522570)
@@ -0,0 +1,68 @@
+/*******************************************************************************
+**
+** Filename : levenshteintable.h
+** Created on : 08 november, 2003
+** Copyright : (c) 2003 Otto Bruggeman <bruggie@home.nl>
+**
+*******************************************************************************/
+
+/*******************************************************************************
+**
+** 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.
+**
+*******************************************************************************/
+
+#ifndef _LEVENSHTEIN_H
+#define _LEVENSHTEIN_H
+
+#include "difference.h"
+
+class QString;
+
+namespace Diff2 {
+
+class Marker;
+
+class LevenshteinTable
+{
+public:
+ LevenshteinTable();
+ LevenshteinTable( unsigned int width, unsigned int height );
+ ~LevenshteinTable();
+
+public:
+ int getContent( unsigned int posX, unsigned int posY ) const;
+ int setContent( unsigned int posX, unsigned int posY, int value );
+ bool setSize ( unsigned int width, unsigned int height );
+
+ unsigned int width() const { return m_width; };
+ unsigned int height() const { return m_height; };
+
+ /** Debug method to check if the table is properly filled */
+ void dumpLevenshteinTable( void );
+
+ /** This will calculate the levenshtein distance of 2 strings */
+ unsigned int createTable( DifferenceString* s, DifferenceString* d );
+
+ void createListsOfMarkers( void );
+ int chooseRoute( int c1, int c2, int c3 );
+
+protected:
+ LevenshteinTable( const LevenshteinTable& table );
+ const LevenshteinTable& operator = ( const LevenshteinTable& table );
+
+private:
+ unsigned int m_width;
+ unsigned int m_height;
+ unsigned int m_size;
+ unsigned int* m_table;
+ DifferenceString* m_source;
+ DifferenceString* m_destination;
+};
+
+} // namespace Diff2
+
+#endif // _LEVENSHTEIN_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h (revision 1522570)
@@ -0,0 +1,72 @@
+/***************************************************************************
+ kompareprocess.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef KOMPAREPROCESS_H
+#define KOMPAREPROCESS_H
+
+#include "kompare.h"
+#include <QtCore/QProcess>
+
+class QTextCodec;
+class QTextDecoder;
+class QProcess;
+
+class DiffSettings;
+
+class KompareProcess : public QObject, public KompareFunctions
+{
+ Q_OBJECT
+
+public:
+ KompareProcess( DiffSettings* diffSettings, enum Kompare::DiffMode mode, const QString& source, const QString& destination, const QString& directory = QString() );
+ ~KompareProcess();
+
+ void start();
+
+ QProcess* process();
+
+ QString diffOutput() { return m_stdout; }
+ QString stdOut() { return m_stdout; }
+ QString stdErr() { return m_stderr; }
+
+ void setEncoding( const QString& encoding );
+
+signals:
+ void diffHasFinished( bool finishedNormally );
+
+protected:
+ void writeDefaultCommandLine();
+ void writeCommandLine();
+
+protected slots:
+ void slotReceivedStdout( );
+ void slotReceivedStderr( );
+ void slotProcessExited( int, QProcess::ExitStatus );
+
+private:
+ DiffSettings* m_diffSettings;
+ enum Kompare::DiffMode m_mode;
+ QString m_stdout;
+ QString m_stderr;
+ QTextDecoder* m_textDecoder;
+ QProcess* m_proc;
+ QStringList m_env;
+ QStringList m_args;
+ QString m_prog;
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp (revision 1522570)
@@ -0,0 +1,28 @@
+/*******************************************************************************
+**
+** Filename : diffmodellist.cpp
+** Created on : 26 march, 2004
+** Copyright : (c) 2004 Otto Bruggeman <bruggie@home.nl>
+**
+*******************************************************************************/
+
+/*******************************************************************************
+**
+** 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.
+**
+*******************************************************************************/
+
+#include "diffmodellist.h"
+#include <kdebug.h>
+#include <q3tl.h>
+
+using namespace Diff2;
+
+void DiffModelList::sort()
+{
+ qHeapSort(*this);
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h (revision 1522570)
@@ -0,0 +1,43 @@
+/**************************************************************************
+** perforceparser.h
+** -------------------
+** begin : Sun Sep 8 20:58:59 2002
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef _PERFORCE_PARSER_H
+#define _PERFORCE_PARSER_H
+
+#include "parserbase.h"
+
+namespace Diff2
+{
+
+class PerforceParser : public ParserBase
+{
+public:
+ PerforceParser( const KompareModelList* list, const QStringList& diff );
+ virtual ~PerforceParser();
+
+protected:
+ virtual bool parseContextDiffHeader();
+ virtual bool parseNormalDiffHeader();
+ virtual bool parseRCSDiffHeader();
+ virtual bool parseUnifiedDiffHeader();
+
+protected:
+ virtual enum Kompare::Format determineFormat();
+};
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h (revision 1522570)
@@ -0,0 +1,37 @@
+/**************************************************************************
+** diffparser.h
+** -----------------
+** begin : Sun Aug 4 15:05:35 2002
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef _DIFF_PARSER_H
+#define _DIFF_PARSER_H
+
+#include "parserbase.h"
+
+namespace Diff2
+{
+
+class DiffParser : public ParserBase
+{
+public:
+ DiffParser( const KompareModelList* list, const QStringList& diff );
+ virtual ~DiffParser();
+
+protected:
+ virtual enum Kompare::Format determineFormat();
+};
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h (revision 1522570)
@@ -0,0 +1,40 @@
+/***************************************************************************
+ settingsbase.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef SETTINGSBASE_H
+#define SETTINGSBASE_H
+
+#include <qobject.h>
+
+#include "kompare.h"
+
+class QWidget;
+class KConfig;
+
+class SettingsBase : public QObject
+{
+Q_OBJECT
+public:
+ SettingsBase( QWidget* parent );
+ ~SettingsBase();
+
+public:
+ virtual void loadSettings( KConfig* config );
+ virtual void saveSettings( KConfig* config );
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h (revision 1522570)
@@ -0,0 +1,141 @@
+/***************************************************************************
+ kompare.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef KOMPARE_H
+#define KOMPARE_H
+
+#include <kurl.h>
+
+namespace Kompare
+{
+ enum Format {
+ Context = 0,
+ Ed = 1,
+ Normal = 2,
+ RCS = 3,
+ Unified = 4,
+ SideBySide = 5,
+ UnknownFormat = -1
+ };
+
+ enum Generator {
+ CVSDiff = 0,
+ Diff = 1,
+ Perforce = 2,
+ SubVersion = 3,
+ Reserved2 = 4,
+ Reserved3 = 5,
+ Reserved4 = 6,
+ Reserved5 = 7,
+ Reserved6 = 8,
+ Reserved7 = 9,
+ UnknownGenerator = -1
+ };
+
+ enum Mode {
+ ComparingFiles, // compareFiles
+ ComparingDirs, // compareDirs
+ ShowingDiff, // openDiff
+ BlendingDir, // openDirAnfDiff
+ BlendingFile, // openFileAndDiff
+ UnknownMode // Used to initialize the Infoi struct
+ };
+
+ enum DiffMode {
+ Default,
+ Custom,
+ UnknownDiffMode // Use to initialize the Info struct
+ };
+
+ enum Status {
+ RunningDiff,
+ Parsing,
+ FinishedParsing,
+ FinishedWritingDiff,
+ ReRunningDiff // When a change has been detected after diff has run
+ };
+
+ enum Target {
+ Source,
+ Destination
+ };
+
+ struct Info {
+ Info (
+ enum Mode _mode = UnknownMode,
+ enum DiffMode _diffMode = UnknownDiffMode,
+ enum Format _format = UnknownFormat,
+ enum Generator _generator = UnknownGenerator,
+ KUrl _source = KUrl(),
+ KUrl _destination = KUrl(),
+ QString _localSource = "",
+ QString _localDestination = ""
+ )
+ {
+ mode = _mode;
+ diffMode = _diffMode;
+ format = _format;
+ generator = _generator;
+ source = _source;
+ destination = _destination;
+ localSource = _localSource;
+ localDestination = _localDestination;
+ }
+ enum Mode mode;
+ enum DiffMode diffMode;
+ enum Format format;
+ enum Generator generator;
+ KUrl source;
+ KUrl destination;
+ QString localSource;
+ QString localDestination;
+ };
+} // End of namespace Kompare
+
+/*
+** This should be removed and put somewhere else
+*/
+class KompareFunctions
+{
+public:
+ static QString constructRelativePath( const QString& from, const QString& to )
+ {
+ KUrl fromURL( from );
+ KUrl toURL( to );
+ KUrl root;
+ int upLevels = 0;
+
+ // Find a common root.
+ root = from;
+ while( root.isValid() && !root.isParentOf( toURL ) ) {
+ root = root.upUrl();
+ upLevels++;
+ }
+
+ if( !root.isValid() ) return to;
+
+ QString relative;
+ for( ; upLevels > 0; upLevels-- ) {
+ relative += "../";
+ }
+
+ relative += QString( to ).replace( 0, root.path( KUrl::LeaveTrailingSlash ).length(), "" );
+ return relative;
+ }
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h (revision 1522570)
@@ -0,0 +1,69 @@
+/***************************************************************************
+ diffhunk.h - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef DIFFHUNK_H
+#define DIFFHUNK_H
+
+#include "difference.h"
+//Added by qt3to4:
+#include <Q3ValueList>
+
+namespace Diff2
+{
+
+class Difference;
+
+class DiffHunk
+{
+public:
+ enum Type { Normal, AddedByBlend };
+
+public:
+ DiffHunk( int sourceLine, int destinationLine, const QString& function = QString(), Type type = Normal );
+ ~DiffHunk();
+
+ const DifferenceList& differences() const { return m_differences; };
+ const QString& function() const { return m_function; };
+
+ int sourceLineNumber() const { return m_sourceLine; };
+ int destinationLineNumber() const { return m_destinationLine; };
+
+ int sourceLineCount() const;
+ int destinationLineCount() const;
+
+ const Type type() const { return m_type; }
+ void setType( Type type ) { m_type = type; }
+
+ void add( Difference* diff );
+
+ QString recreateHunk() const;
+
+private:
+ int m_sourceLine;
+ int m_destinationLine;
+ DifferenceList m_differences;
+ QString m_function;
+ Type m_type;
+};
+
+typedef Q3ValueList<DiffHunk*> DiffHunkList;
+typedef Q3ValueList<DiffHunk*>::iterator DiffHunkListIterator;
+typedef Q3ValueList<DiffHunk*>::const_iterator DiffHunkListConstIterator;
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h (revision 1522570)
@@ -0,0 +1,60 @@
+/**************************************************************************
+** cvsdiffparser.h
+** -----------------
+** begin : Sun Aug 4 15:05:35 2002
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef _CVSDIFF_PARSER_H
+#define _CVSDIFF_PARSER_H
+
+#include <qregexp.h>
+
+#include "parserbase.h"
+
+namespace Diff2
+{
+
+class KompareModelList;
+
+class CVSDiffParser : public ParserBase
+{
+public:
+ CVSDiffParser( const KompareModelList* list, const QStringList& diff );
+ virtual ~CVSDiffParser();
+
+protected:
+ virtual enum Kompare::Format determineFormat();
+
+protected:
+// virtual bool parseContextDiffHeader();
+ virtual bool parseEdDiffHeader();
+ virtual bool parseNormalDiffHeader();
+ virtual bool parseRCSDiffHeader();
+// virtual bool parseUnifiedDiffHeader();
+
+// virtual bool parseContextHunkHeader();
+ virtual bool parseEdHunkHeader();
+// virtual bool parseNormalHunkHeader();
+ virtual bool parseRCSHunkHeader();
+// virtual bool parseUnifiedHunkHeader();
+
+// virtual bool parseContextHunkBody();
+ virtual bool parseEdHunkBody();
+// virtual bool parseNormalHunkBody();
+ virtual bool parseRCSHunkBody();
+// virtual bool parseUnifiedHunkBody();
+};
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h (revision 1522570)
@@ -0,0 +1,48 @@
+/*******************************************************************************
+**
+** Filename : diffmodellist.h
+** Created on : 24 januari, 2004
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+*******************************************************************************/
+
+/*******************************************************************************
+**
+** 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.
+**
+*******************************************************************************/
+
+#ifndef DIFFMODELLIST_H
+#define DIFFMODELLIST_H
+
+#include <q3valuelist.h> // include for the base class
+
+#include "diffmodel.h"
+
+namespace Diff2
+{
+
+typedef Q3ValueListIterator<DiffModel*> DiffModelListIterator;
+typedef Q3ValueListConstIterator<DiffModel*> DiffModelListConstIterator;
+
+class DiffModelList : public Q3ValueList<DiffModel*>
+{
+public:
+ DiffModelList() {}
+ DiffModelList( const DiffModelList &list ) : Q3ValueList<DiffModel*>( list ) {}
+ virtual ~DiffModelList()
+ {
+ clear();
+ }
+
+public:
+ virtual void sort();
+
+}; // End of class DiffModelList
+
+} // End of Namespace Diff2
+
+#endif // DIFFMODELLIST_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp (revision 1522570)
@@ -0,0 +1,40 @@
+/***************************************************************************
+ settingsbase.cpp - description
+ -------------------
+ begin : Sun Mar 4 2001
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+ copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
+****************************************************************************/
+
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#include "settingsbase.h"
+#include <qwidget.h>
+
+
+SettingsBase::SettingsBase( QWidget* parent ) : QObject( parent )
+{
+
+}
+
+SettingsBase::~SettingsBase()
+{
+
+}
+
+void SettingsBase::loadSettings( KConfig* /* config */ )
+{
+}
+
+void SettingsBase::saveSettings( KConfig* /* config */ )
+{
+}
+
+#include "settingsbase.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-c++src
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h (revision 1522570)
@@ -0,0 +1,132 @@
+/**************************************************************************
+** parserbase.h
+** -------------------
+** begin : Tue Jul 30 23:53:52 2002
+ copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
+**
+***************************************************************************/
+/***************************************************************************
+**
+** 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.
+**
+***************************************************************************/
+
+#ifndef _DIFF2_PARSERBASE_H
+#define _DIFF2_PARSERBASE_H
+
+#include <qregexp.h>
+
+#include "kompare.h"
+#include "difference.h"
+#include "diffmodellist.h"
+
+class QStringList;
+class QString;
+
+namespace Diff2
+{
+
+class KompareModelList;
+
+class ParserBase
+{
+public:
+ ParserBase( const KompareModelList* list, const QStringList& diff );
+ virtual ~ParserBase();
+
+public:
+ enum Kompare::Format format() { return determineFormat(); };
+ DiffModelList* parse();
+
+protected:
+ virtual bool parseContextDiffHeader();
+ virtual bool parseEdDiffHeader();
+ virtual bool parseNormalDiffHeader();
+ virtual bool parseRCSDiffHeader();
+ virtual bool parseUnifiedDiffHeader();
+
+ virtual bool parseContextHunkHeader();
+ virtual bool parseEdHunkHeader();
+ virtual bool parseNormalHunkHeader();
+ virtual bool parseRCSHunkHeader();
+ virtual bool parseUnifiedHunkHeader();
+
+ virtual bool parseContextHunkBody();
+ virtual bool parseEdHunkBody();
+ virtual bool parseNormalHunkBody();
+ virtual bool parseRCSHunkBody();
+ virtual bool parseUnifiedHunkBody();
+
+ virtual DiffModelList* parseContext();
+ virtual DiffModelList* parseEd();
+ virtual DiffModelList* parseNormal();
+ virtual DiffModelList* parseRCS();
+ virtual DiffModelList* parseUnified();
+
+protected: // Helper methods to speed things up
+ bool matchesUnifiedHunkLine( QString line ) const;
+
+protected:
+ /** What is format of the diff */
+ virtual enum Kompare::Format determineFormat();
+
+protected:
+ // Regexps for context parsing
+ QRegExp m_contextDiffHeader1;
+ QRegExp m_contextDiffHeader2;
+
+ QRegExp m_contextHunkHeader1;
+ QRegExp m_contextHunkHeader2;
+ QRegExp m_contextHunkHeader3;
+
+ QRegExp m_contextHunkBodyRemoved;
+ QRegExp m_contextHunkBodyAdded;
+ QRegExp m_contextHunkBodyChanged;
+ QRegExp m_contextHunkBodyContext;
+ QRegExp m_contextHunkBodyLine; // Added for convenience
+
+ // Regexps for normal parsing
+ QRegExp m_normalDiffHeader;
+
+ QRegExp m_normalHunkHeaderAdded;
+ QRegExp m_normalHunkHeaderRemoved;
+ QRegExp m_normalHunkHeaderChanged;
+
+ QRegExp m_normalHunkBodyRemoved;
+ QRegExp m_normalHunkBodyAdded;
+ QRegExp m_normalHunkBodyDivider;
+
+ enum Difference::Type m_normalDiffType;
+
+ // RegExps for rcs parsing
+ QRegExp m_rcsDiffHeader;
+
+ // Regexps for unified parsing
+ QRegExp m_unifiedDiffHeader1;
+ QRegExp m_unifiedDiffHeader2;
+
+ QRegExp m_unifiedHunkHeader;
+
+ QRegExp m_unifiedHunkBodyAdded;
+ QRegExp m_unifiedHunkBodyRemoved;
+ QRegExp m_unifiedHunkBodyContext;
+ QRegExp m_unifiedHunkBodyLine; // Added for convenience
+
+protected:
+ const QStringList& m_diffLines;
+ DiffModel* m_currentModel;
+ DiffModelList* m_models;
+ QStringList::ConstIterator m_diffIterator;
+
+ bool m_singleFileDiff;
+
+protected:
+ const KompareModelList* m_list;
+};
+
+} // End of namespace Diff2
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
Added: svn:mime-type
## -0,0 +1 ##
+text/x-chdr
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2 (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/libdiff2
___________________________________________________________________
Added: svn:ignore
## -0,0 +1,8 ##
+*.moc
+.libs
+CMakeFiles
+DartTestfile.txt
+Makefile
+Makefile.in
+cmake_install.cmake
+install_icons.cmake
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,37 @@
+################################################################################################
+# This library needs to build without KDE4, please don't add KDE4 specific cmake stuff in here #
+################################################################################################
+
+PROJECT( dynamictext )
+
+#if you don't want the full compiler output, remove the following line
+#SET(CMAKE_VERBOSE_MAKEFILE ON)
+
+SET( dynamictext_SRCS
+ dynamictext.cpp
+ vectortimestamp.cpp
+ offsetutils.cpp
+ sumtree.cpp
+)
+
+#add definitions, compiler switches, etc.
+#ADD_DEFINITIONS(-Wall -g -fno-inline -fexceptions)
+#ADD_DEFINITIONS(-Wall -os -finline -fexceptions)
+#ADD_DEFINITIONS(-Wall -o3 -g -fexceptions)
+
+ADD_DEFINITIONS(-Wall ${KDE4_ENABLE_EXCEPTIONS})
+
+#list all source files here
+
+######## next target ########
+
+# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
+ADD_LIBRARY( kdevteamwork_dynamictext SHARED ${dynamictext_SRCS} )
+TARGET_LINK_LIBRARIES( kdevteamwork_dynamictext ${COMMONCPP2_LIBRARIES} ${Boost_THREAD_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} ${QT_QTCORE_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
+install(TARGETS kdevteamwork_dynamictext ${INSTALL_TARGETS_DEFAULT_ARGS})
+
+ADD_EXECUTABLE( testexec main.cpp)
+TARGET_LINK_LIBRARIES( testexec kdevteamwork_dynamictext ${Boost_THREAD_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} dl ${ZLIB_LIBRARIES} )
+
+#ADD_DEPENDENCIES( testexec, dynamictext )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp (revision 1522570)
@@ -0,0 +1,842 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "offsetutils.h"
+#include <assert.h>
+#include "sumtree.h"
+
+#define CNT 500
+#define SMALLCNT 50
+#define CYCLES 1
+
+#define private public
+#include "dynamictext.h"
+#include "flexibletext.h"
+#include <time.h>
+#include <sstream>
+
+typedef std::list<std::string> StringList;
+
+std::list<std::string> splitString( const std::string& text ) {
+ std::list<std::string> ret;
+ uint len = text.length();
+ int currentStart = 0;
+
+ for ( uint a = 0; a < len; a++ ) {
+ if ( text[ a ] == '\n' ) {
+ ret.push_back( std::string( text.substr( currentStart, a - currentStart ) ) );
+ currentStart = a + 1;
+ }
+ }
+ //if ( currentStart != len )
+ ret.push_back( std::string( text.substr( currentStart, len - currentStart ) ) );
+
+ return ret;
+}
+
+
+std::string compareText( const std::string& str1, const std::string& str2 ) {
+ std::ostringstream os;
+ StringList l1 = splitString( str1 );
+ StringList l2 = splitString( str2 );
+ uint size = l1.size();
+ if ( l2.size() > size )
+ size = l2.size();
+
+ StringList::iterator it1 = l1.begin();
+ StringList::iterator it2 = l2.begin();
+ int cnt1 = 0;
+ int cnt2 = 0;
+ os << "total length: " << str1.length() << " " << str2.length() << endl;
+
+ for ( uint a = 0; a < size; a++ ) {
+ std::string text1 = "empty";
+ std::string text2 = "empty";
+
+ if ( it1 != l1.end() )
+ text1 = "\"" + *it1 + "\"";
+
+ if ( it2 != l2.end() )
+ text2 = "\"" + *it2 + "\"";
+
+ os << a << "(total counts " << cnt1 << ":" << cnt2 << "): " << text1 << " : " << text2 << "(length " << ( text1 == "empty" ? 0 : it1->length() ) << ":" << ( text2 == "empty" ? 0 : it2->length() ) << ") " << ( text1 == text2 ? "match" : "MISMATCH" ) << "\n" ;
+
+ if ( it1 != l1.end() ) {
+ cnt1 += it1->length() + 1;
+ ++it1;
+ }
+ if ( it2 != l2.end() ) {
+ cnt2 += it2->length() + 1;
+ ++it2;
+ }
+ }
+ return os.str();
+ //": \nflexText:\"" << flexText.text() << "\"\nstring: \n\"" << string << "\"" << endl
+}
+
+struct doubleText {
+ SumTree::FlexibleText<std::string> flexText;
+ std::string string;
+ clock_t flexClock;
+ clock_t stringClock;
+ doubleText( const std::string& str ) : flexText( str ), string( str ), flexClock( 0 ), stringClock( 0 ) {}
+ int lastActionType;
+ int lastPosition;
+ std::string lastText;
+ int lastLength;
+
+ void insert( int position, std::string text ) {
+ lastActionType = 0;
+ lastPosition = position;
+ lastText = text;
+
+ //flexText.rebuildTree();
+ clock_t c = clock();
+ flexText.insert( position, text );
+ flexClock += clock() - c;
+ c = clock();
+ string.insert( position, text );
+ stringClock += clock() - c;
+ //compare();
+ }
+ void remove
+ ( int position, int length ) {
+ lastActionType = 1;
+ lastPosition = position;
+ lastLength = length;
+
+ clock_t c = clock();
+ flexText.erase( position, length );
+ flexClock += clock() - c;
+ c = clock();
+ string.erase( position, length );
+ stringClock += clock() - c;
+ //compare();
+ }
+ void compare() {
+ bool fail = false;
+
+
+ if ( flexText.text().length() != string.length() )
+ fail = true;
+
+ if( flexText.length() < 10000 ) {
+ //As long as the text is not big, check for line/column conversion consistency
+ int len = flexText.length();
+ for( int a = 0; a < len; a++ ) {
+ int line, column;
+ flexText.linearToLineColumn( a, line, column );
+ if( flexText.lineColumnToLinear( line, column ) != a ) {
+ cout << "linear to line/column-check: back-conversion failed at position " << a << endl;
+ fail = false;
+ }
+ }
+ }
+
+ if( fail ){
+ cout << "error, last action: " << ( lastActionType ? "removal " : "insertion " ) << " of \"";
+ if ( lastActionType )
+ cout << lastLength;
+ else
+ cout << lastText;
+ cout << "\" at " << lastPosition << " comparing flexText(left) to string(right): \n" << compareText( flexText.text(), string );
+ }
+
+ DYN_VERIFY_SAME( flexText.text().length(), string.length() );
+ //cout << "length: " << flexText.text().length() << " " << string.length() << endl;
+ DYN_VERIFY_SAME( flexText.text(), string );
+ }
+ void showClock() {
+ cout << "\\flexible: " << float( flexClock ) / float( CLOCKS_PER_SEC ) << endl << "\\string: " << float( stringClock ) / float( CLOCKS_PER_SEC ) << endl;
+ }
+};
+
+typedef SumTree::FlexibleText<std::string> Text;
+void verifyFlexibleText() {
+ std::list<std::string> bla;
+ bla.push_back( "hallo" );
+ bla.push_back( "Ich bin der David" );
+
+ {
+ /*Text:
+a (length 2, total 2)
+b (length 3, total 5)
+ccc (length 4, total 9)
+ (length 1, total 10)
+dddd (length 5, total 15)
+
+ */
+ Text text( "a\nbb\nccc\n\ndddd\n" );
+ int line, column;
+ text.linearToLineColumn( 0, line, column );
+ DYN_VERIFY_SAME( line, 0 ); DYN_VERIFY_SAME( column, 0 );
+
+ text.linearToLineColumn( 1, line, column );
+ DYN_VERIFY_SAME( line, 0 ); DYN_VERIFY_SAME( column, 1 );
+
+ text.linearToLineColumn( 2, line, column );
+ DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 0 );
+
+ text.linearToLineColumn( 4, line, column );
+ DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 2 );
+
+ text.linearToLineColumn( 5, line, column );
+ DYN_VERIFY_SAME( line, 2 ); DYN_VERIFY_SAME( column, 0 );
+
+ text.remove( 3, 1 );
+ text.linearToLineColumn( 3, line, column );
+ DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 1 );
+
+ text.linearToLineColumn( 4, line, column );
+ DYN_VERIFY_SAME( line, 2 ); DYN_VERIFY_SAME( column, 0 );
+ cout << "Line-wrap tested ok" << endl;
+ };
+
+ Text text( "hallo\nIch bin der David" );
+ cout << text.text() << endl;
+ text.erase( 1, 1, 2 );
+ text.erase( 0, 6 );
+ text.insert( text.length() - 1, "ende!\naber" );
+ text.insert( text.length() - 1, "\n" );
+ cout << text.text() << endl;
+
+ char inputs[ 44 ] = {'a', 'b', 'c', 'd', ' ', 'f', 'g', 'h', 'i', 'j', '\n', 'a', 'b', ' ', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'q', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'q'};
+
+ std::string input;
+
+ for ( int a = 0; a < rand() % 1000 + 50; a++ ) {
+ input += inputs[ rand() % 44 ];
+ }
+
+ doubleText d( input );
+ int cnt = 0;
+
+ for ( int b = 0; b < 100000; b++ ) {
+ ///remove a random small range
+ if ( d.string.size() != 0 ) {
+ uint remSize = rand() % 5;
+ uint remPos = rand() % d.string.size();
+ if ( remPos + remSize > d.string.size() )
+ remSize = d.string.size() - remPos;
+ d.remove( remPos, remSize );
+ }
+
+ uint addSize = rand() % 10;
+ uint addPos = rand() % ( d.string.size() + 1 );
+ std::string input;
+ for ( uint a = 0; a < addSize; a++ ) {
+ input += inputs[ rand() % 44 ];
+ }
+ d.insert( addPos, input );
+ ++cnt;
+ if ( cnt == 1000 ) {
+ cnt = 0;
+ d.showClock();
+ cout << "size: " << d.string.size() << endl;
+ d.compare();
+ }
+
+ ///Copy the text and remove some part, to make sure that the tree stays consistent
+ Text f( d.flexText );
+ if ( d.string.size() != 0 ) {
+ uint remSize = rand() % 5;
+ uint remPos = rand() % d.string.size();
+ if ( remPos + remSize > d.string.size() )
+ remSize = d.string.size() - remPos;
+ f.remove( remPos, remSize );
+ }
+ //d.compare();
+ }
+ //cout << "\n" << d.flexText.dumpTree() << "\n";
+
+}
+
+void verifySumTree() {
+
+ try {
+ SumTree::Map tree;
+ tree.insertRange( 0, 10, 1 );
+ for( int a = 0; a < 10; a++ ) {
+ DYN_VERIFY_SAME( tree.indexValue( 0 ), 1 );
+ DYN_VERIFY_SAME( tree.index( a ), a );
+ SumTree::IndexAndSum r;
+ tree.indexAndSum( a, r );
+ DYN_VERIFY_SAME( r.index, a );
+ DYN_VERIFY_SAME( r.sum, a );
+ cout << a << ": " << tree.indexValue( a ) << " "<< tree.sum( a ) << endl;
+ }
+ DYN_VERIFY_SAME( tree.sum( 10 ), 10 );
+ DYN_VERIFY_SAME( tree.sum( 11 ), 10 );
+ tree.setIndexValue( 1, 0 );
+ for( int a = 0; a < 10; a++ )
+ cout << a << ": " << tree.indexValue( a ) << " " << tree.sum( a ) << endl;
+ DYN_VERIFY_SAME( tree.sum( 10 ), 9 );
+ DYN_VERIFY_SAME( tree.sum( 11 ), 9 );
+ DYN_VERIFY_SAME( tree.indexValue( 1 ), 0 );
+ DYN_VERIFY_SAME( tree.indexValue( 2 ), 1 );
+ tree.changeIndexValue( 1, 1 );
+ DYN_VERIFY_SAME( tree.indexValue( 1 ), 1 );
+ DYN_VERIFY_SAME( tree.indexValue( 2 ), 1 );
+ tree.insertIndex( 3, 0 );
+ DYN_VERIFY_SAME( tree.indexValue( 3 ), 0 );
+ DYN_VERIFY_SAME( tree.sum( 5 ), 4 );
+ tree.removeIndex( 0 );
+ tree.removeIndex( 0 );
+ tree.removeIndex( 0 );
+ DYN_VERIFY_SAME( tree.indexValue( 0 ), 0 );
+
+ } catch ( DynamicTextError err ) {
+ cout << "remove-index-test failed: " << err.what() << endl;
+ terminate();
+ }
+
+ int cycles = 3;
+ for ( int a = 0; a < cycles; a++ ) {
+ cout << "testing cycle " << a + 1 << endl;
+ std::vector<int > summands;
+ //srand ( time(NULL) );
+ int count = rand() % 20000;
+ summands.resize( count );
+
+ for ( int a = 0; a < count; a++ ) {
+ summands[ a ] = rand() % 2000 + 1;
+ }
+
+ try {
+ SumTree::Map tree( summands );
+ int sum = tree.sum( 5 );
+/* int nsum = tree.sum( 6 );*/
+ DYN_VERIFY_SAME( tree.index( sum ), 5 );
+ tree.setIndexValue( 5, 0 );
+ // DYN_VERIFY_SAME( tree.index( sum ), 6 ); ///Reactivate in time!
+ } catch ( DynamicTextError err ) {
+ cout << "custom test failed: " << err.what() << endl;
+ terminate();
+ }
+
+ //uint t = timeGetTime();
+ try {
+ SumTree::Map tree( summands );
+ DYN_VERIFY_SAME( tree.indexCount(), count );
+ } catch ( DynamicTextError err ) {
+ cout << "count-invariance failed: " << err.what() << endl;
+ terminate();
+ }
+ //cout << "count-invariance elapsed time: " << timeGetTime() - t << endl;
+
+ int a = 0;
+ try {
+ SumTree::Map tree( summands );
+ int sum = 0;
+ for ( a = 0; a < count; a++ ) {
+ int s = tree.sum( a );
+ DYN_VERIFY_SAME( s, sum );
+ sum += summands[ a ];
+ int ind = tree.index( s );
+ DYN_VERIFY_SAME( ind, a );
+ }
+
+ } catch ( DynamicTextError err ) {
+ cout << "sum-test failed: " << err.what() << endl;
+ terminate();
+ }
+
+ //cout << "sum-test elapsed time: " << time(NULL) - t << endl;
+
+ try {
+ SumTree::Map tree( summands );
+/* int sum = 0;*/
+ for ( int a = 0; a < count; a++ ) {
+ int s = tree.indexValue( a );
+ DYN_VERIFY_SAME( s, summands[ a ] );
+ }
+
+ } catch ( DynamicTextError err ) {
+ cout << "index-value failed: " << err.what() << endl;
+ terminate();
+ }
+
+ try {
+ SumTree::Map tree( summands );
+ for ( int a = 0; a < count; a++ ) {
+ tree.setIndexValue( a, a );
+ DYN_VERIFY_SAME( a, tree.indexValue( a ) );
+ }
+
+ } catch ( DynamicTextError err ) {
+ cout << "set-index-value failed: " << err.what() << endl;
+ terminate();
+ }
+
+ try {
+ SumTree::Map tree( summands );
+ for ( int a = 0; a < count; a++ ) {
+ int v = tree.indexValue( a );
+ DYN_VERIFY_SAME( v + a, tree.changeIndexValue( a, a ) );
+ }
+
+ } catch ( DynamicTextError err ) {
+ cout << "change-index-value failed: " << err.what() << endl;
+ terminate();
+ }
+
+ try {
+ SumTree::Map tree( summands );
+ for ( int a = 0; a < count; a += 2 ) {
+ int v = tree.indexValue( a );
+ tree.insertIndex( a, a );
+ DYN_VERIFY_SAME( tree.indexValue( a ), a );
+ DYN_VERIFY_SAME( tree.indexValue( a + 1 ), v );
+ }
+ } catch ( DynamicTextError err ) {
+ cout << "insert-index-test failed: " << err.what() << endl;
+ terminate();
+ }
+ try {
+ SumTree::Map tree( summands );
+ for ( int a = count / 10; a >= 0; a-- ) {
+ int r = tree.removeIndex( a * 9 );
+ DYN_VERIFY_SAME( r, summands[ a * 9 ] );
+ }
+ } catch ( DynamicTextError err ) {
+ cout << "remove-index-test failed: " << err.what() << endl;
+ terminate();
+ }
+ }
+
+
+}
+
+///@todo create so automatic testing-algorithm that tests the system more intensively
+
+void verifyDynamicText() {
+ cout << "testing replacement-system" << endl;
+
+ try {
+ DynamicText t;
+ cout << "test 0.1: \n";
+ VectorTimestamp a5 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
+ VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 1, "a", "" ) );
+ VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 2, "b", "" ) );
+ VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 3, "a", "" ) );
+
+ cout << t.state().print() << "text: " << t.text() << endl;
+
+ VectorTimestamp v( t.state() );
+ v.setStamp( 0, 0 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+ DYN_VERIFY_SAME( t.text().text(), "b" );
+
+ v.setStamp( 0, 1 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+ DYN_VERIFY_SAME( t.text().text(), "ab" );
+
+ v.setStamp( 0, 2 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+ DYN_VERIFY_SAME( t.text().text(), "aab" );
+
+ v.setStamp( 0, 3 );
+ t.changeState( v );
+ DYN_VERIFY_SAME( t.text().text(), "aaba" );
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ terminate();
+ }
+
+ try {
+ DynamicText t;
+ cout << "test 4: \n";
+ VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "i", "" ) );
+ VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 0, "d", "" ) );
+ VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 0, "v", "" ) ); ///!
+ VectorTimestamp b2 = t.insert( 1, SimpleReplacement( 0, "d", "" ) );
+ VectorTimestamp a3 = t.insert( 0, SimpleReplacement( t.text().length(), "r", "" ) );
+ //VectorTimestamp a4 = t.insert( 0, SimpleReplacement( 0, " ", "" ) );
+ VectorTimestamp a5 = t.insert( 0, SimpleReplacement( 0, "q", "" ) ); ///!
+ VectorTimestamp a6 = t.insert( 0, SimpleReplacement( 1, "v", "" ) );
+
+ cout << t.state().print() << "text: " << t.text() << endl;
+ VectorTimestamp v( t.state() );
+ v.setStamp( 1, 0 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+
+ v = t.state();
+ v.setStamp( 0, 1 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ terminate();
+ }
+
+ try {
+ DynamicText t;
+ cout << "test 2: \n";
+ VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
+ VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 1, "b", "" ) );
+ VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 2, "c", "" ) );
+ VectorTimestamp b2 = t.insert( 1, SimpleReplacement( 3, "d", "" ) );
+ VectorTimestamp a3 = t.insert( 0, SimpleReplacement( 4, "e", "" ) );
+
+ cout << t.state().print() << "text: " << t.text() << endl;
+ VectorTimestamp v( t.state() );
+ v.setStamp( 1, 1 );
+ t.changeState( v );
+ cout << t.state().print() << "text: " << t.text() << endl;
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ terminate();
+ }
+
+ try {
+ DynamicText t;
+ cout << "test 1.1: \n";
+ t.insert( 0, SimpleReplacement( 0, "a", "" ) );
+ t.insert( 0, SimpleReplacement( 1, "b", "" ) );
+ t.insert( 1, SimpleReplacement( 1, "q", "" ) );
+ t.insert( 1, SimpleReplacement( 2, "q", "" ) );
+
+ cout << t.state().print() << "text: " << t.text() << endl;
+ VectorTimestamp v( t.state() );
+ v.setStamp( 0, 1 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+ /*
+ v = t.state();
+ v.setStamp( 0, 1 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;*/
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ terminate();
+ }
+
+ try {
+ cout << "test:\n";
+ DynamicText t;
+ VectorTimestamp start = t.insert( 0, SimpleReplacement( 0, "HalloichbinderDavid", "" ) );
+ VectorTimestamp u0r1 = t.insert( 0, SimpleReplacement( 0, "Ahoiiiiii", "Hallo" ) );
+ VectorTimestamp u1r1( 1, start );
+ t.insert( u1r1, SimpleReplacement( 5, "ja", "ich" ) );
+ VectorTimestamp u2r1( 2, start );
+ t.insert( u2r1, SimpleReplacement( 8, "jsem", "bin" ) );
+ t.changeState();
+ cout << t.state().print() << "text: " << t.text() << endl;
+ VectorTimestamp u1r2( 1, t.state() );
+ t.insert( u1r2, SimpleReplacement( 18, "Davidek", "David" ) );
+ t.changeState();
+ VectorTimestamp mix = t.state();
+ mix.setStamp( 0, 1 );
+ t.changeState( mix );
+ cout << t.state().print() << " text: " << t.text() << endl;
+ t.changeState( u1r1 );
+ cout << t.state().print() << "text: " << t.text() << endl;
+ t.changeState( start );
+ ReplacementPointer r = t.replacement( 0, 2 );
+ assert( r );
+ r->setEnabled( false );
+ r = t.replacement( 2, 1 );
+ assert( r );
+ r->setEnabled( false );
+ t.changeState();
+
+ cout << t.state().print() << ", some disabled, text: " << t.text() << endl;
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ }
+
+ {
+ cout << "test:\n";
+ std::string text = "hallo";
+ std::string text2 = text;
+ OffsetMap om;
+ ReplacementPointer r = new Replacement( VectorTimestamp(), SimpleReplacement( 1, "BLA", "al" ) );
+ ReplacementPointer r2 = new Replacement( VectorTimestamp(), SimpleReplacement( 4, "HeHe", "lo" ) );
+ ReplacementPointer r3 = new Replacement( VectorTimestamp(), SimpleReplacement( 2, "Ne nee neee", "LAHe" ) );
+ //r->setEnabled( false );
+ r->apply( text2, OffsetMap(), om );
+ r2->apply( text2, OffsetMap(), om );
+ r3->apply( text2, OffsetMap(), om );
+
+ std::string text3 = text2;
+ om.printMap();
+ cout << endl;
+
+ r3->unApply( text3, OffsetMap(), om );
+ r2->unApply( text3, OffsetMap(), om );
+ r->unApply( text3, OffsetMap(), om );
+ cout << "before apply: \"" << text << "\", after: \"" << text2 << "\" after unapply: \"" << text3 << "\"" << endl;
+ cout << "offset-map: ";
+ om.printMap();
+ cout << endl;
+ }
+
+ cout << "testing document-manager" << endl;
+ VectorTimestamp ts( 0, VectorTimestamp() );
+
+ try {
+ DynamicText t;
+ cout << "test 1.2: \n";
+ VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
+ VectorTimestamp c1 = t.insert( 2, SimpleReplacement( 0, "w", "" ) );
+ VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 1, "b", "" ) );
+ VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 1, "q", "" ) );
+
+#define VERIFY_OFFSET( index, from, to ) \
+ { OffsetMap om = t.offset( to, from ); \
+ cout << "verifying offset from " << from.print() << " to " << to.print() << " at index " << index << " map is: " << om.print() << cout; \
+ t.changeState( from ); \
+ cout << "text in state " << from.print() << ": " << t.text() << endl; \
+ char c = t.text()[index]; \
+ t.changeState( to ); \
+ cout << "text in state " << to.print() << ": " << t.text() << endl; \
+ cout << "index: " << index << " mapped index: " << om(index) << " values: " << c << " " << t.text()[ om( index ) ] << endl; \
+ DYN_VERIFY_SAME( c, t.text()[ om( index ) ] ); \
+ OffsetMap om2 = t.offset( from, to ); DYN_VERIFY_SAME( om2( om( index ) ), index ); \
+ } \
+
+ VERIFY_OFFSET( 2, a2, a1 );
+
+ VERIFY_OFFSET( 2, b1, a2 );
+
+ t.changeState();
+ cout << t.state().print() << "text: " << t.text() << endl;
+ VectorTimestamp v( t.state() );
+ v.setStamp( 2, 0 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+
+ v.setStamp( 0, 1 );
+ t.changeState( v );
+ cout << t.state().print() << v << " text: " << t.text() << endl;
+
+ } catch ( DynamicTextError err ) {
+ cout << "error: " << err.what();
+ terminate();
+ }
+
+ DynamicText t;
+
+ t.insert( ts, SimpleReplacement( 0, "aabb", "" ) );
+ t.changeState( ts );
+
+
+ VectorTimestamp ts1( 1, ts );
+ VectorTimestamp ts2( 0, ts );
+ t.insert( ts1, SimpleReplacement( 1, "a_b", "ab" ) );
+ t.insert( ts2, SimpleReplacement( 3, "cc", "b" ) );
+ VectorTimestamp v( 1, ts1 );
+ v.maximize( ts2 );
+
+ t.insert( v, SimpleReplacement( 0, "dd", "a" ) );
+ t.changeState();
+
+
+ cout << "text: " << t.text() << endl;
+ VectorTimestamp ss( 0 );
+ ss.setStamp( 0, 1 );
+ ss.setStamp( 1, 2 );
+ t.changeState( ss );
+ cout << "text on 1,2: " << t.text() << endl;
+
+ t.changeState();
+ /*VectorTimestamp nv( 0, t.state() );
+ t.insert( nv, SimpleReplacement( 0, "ey", "dda" ) );
+ t.changeState();*/
+
+ cout << "end text: " << t.text() << endl;
+
+ VectorTimestamp ns( 0, t.state() );
+ t.insert( ns, SimpleReplacement( 5, "hihi", "c" ) );
+ t.changeState();
+
+ cout << "whole end text: " << t.text() << endl;
+ /*
+ ns.setStamp( 1, 0 );
+
+ t.changeState( ns );*/
+
+ cout << "text edited by 1: " << t.text() << endl;
+
+ ss.setStamp( 1, 0 );
+
+ cout << "ready" << endl;
+}
+
+
+void verifyOffsets() {
+ {
+ //srand ( time( NULL ) );
+ OffsetMap o;
+ o %= OffsetMap( 3, 1 );
+ o %= OffsetMap( 6, 2 );
+ assert( o( 0 ) == 0 );
+ assert( o( 1 ) == 1 );
+ assert( o( 2 ) == 2 );
+ assert( o( 3 ) == 4 );
+ assert( o( 6 ) == 9 );
+ assert( o( 7 ) == 10 );
+
+
+ cout << "verifying offset-map\\m";
+
+ for ( int b = 0; b < 1000; b++ ) {
+ try {
+ {
+ int pos1 = rand() % 10;
+ int off1 = rand() % 10;
+ if( off1 < -pos1 ) off1 = pos1;
+
+ int pos2 = rand() % 10;
+ int off2 = rand() % 10;
+ if( off2 < -pos2 ) off2 = pos2;
+
+ OffsetMap om( pos1, off1);
+ OffsetMap om2( pos2, off2 );
+ OffsetMap om3 = om2 % om;
+ OffsetMap om3Inv = ~om3;
+ for ( int a = 0; a < 10; a++ ) {
+ DYN_VERIFY_SAME( om2( om( a ) ), om3( a ) );
+ /*int om3A = om3(a);
+ int om3Invom3A = om3Inv( om3A );
+ int result = om3( om3Invom3A );
+ DYN_VERIFY_SAME( result, om3A );*/
+ }
+ }
+ } catch ( const DynamicTextError & error ) {
+ cout << "verifyOffsets error: " << error.what() << endl;
+ terminate();
+ }
+ }
+ cout << "success\n";
+ }
+
+
+ cout << "building map 1" << endl;
+ OffsetMap o;
+ OffsetMap o2;
+ for ( int a = 0; a < SMALLCNT; a++ ) {
+ float f = ( float( rand() ) / RAND_MAX ) * CNT;
+ int of = (int)( ( float( rand() ) / RAND_MAX ) * 100 ) - 50;
+ if ( of ) {
+ OffsetMap in( ( uint ) f, of );
+ if ( o.isCompatible( in ) )
+ o %= in;
+ }
+ }
+ cout << "ready" << endl;
+
+ cout << "building map 2" << endl;
+ for ( int a = 0; a < SMALLCNT; a++ ) {
+ float f = ( float( rand() ) / RAND_MAX ) * CNT;
+ int of = (int)( ( float( rand() ) / RAND_MAX ) * 100 ) - 50;
+ if ( of ) {
+ OffsetMap in( ( uint ) f, of );
+ if ( o.isCompatible( in ) )
+ o %= in;
+ /* else
+ cout << "incompatible: " << (uint)f << " " << of << endl;*/
+ }
+ }
+ cout << "ready" << endl;
+ /*
+ o %= OffsetMap( 3, 1 );
+ o %= OffsetMap( 5, 1 );
+ o %= OffsetMap( 10, -2 );
+ o %= OffsetMap( 15, 3 );
+
+ o2 %= OffsetMap( 1, 1 );
+ o2 %= OffsetMap( 8, -2 );
+// o2 % OffsetMap( 5, 1 );
+// o2 % OffsetMap( 10, -2 );
+// o2 % OffsetMap( 15, 3 );
+
+ //cout << "map 1: ";
+ o.printMap();
+ //cout << "map 2: ";
+ o2.printMap();
+ if ( !o.isCompatible( o2 ) ) {
+ cout << "map 2 is not compatible" << endl;
+ return ;
+ }*/
+ OffsetMap o3 = o % o2;
+ //cout << "combined: ";
+ o3.printMap();
+
+ /* cout << "inversion-test: ";
+ OffsetMap oInv(o);
+ ~oInv;
+ oInv.printMap();
+ cout << endl;
+ for( int a = 5; a < CNT; a++ ) {
+ int oa = o(a);
+ cout << a << " == " << oInv( oa );
+ cout << " (" << oa << ")" << endl;
+ assert( oInv( o(a) ) == a );
+ }
+ cout << "success "<< endl;*/
+
+
+ cout << "testing o(o2(x)) == o3(x) ( with o3 = o % o2 )" << endl;
+ for ( int a = 0; a < CNT; a++ ) {
+ if ( o2( a ) < 0 || o( a ) < 0 )
+ continue;
+ if ( !o( o2( a ) ) == o3( a ) )
+ cout << "error for a " << a << ": " << o( a ) << " " << o2( a ) << " : " << o( o2( a ) ) << " != " << o3( a ) << endl;
+ assert( o( o2( a ) ) == o3( a ) );
+ }
+ cout << "success" << endl;
+
+ o3 = o3 % ( ~o2 );
+
+ cout << "testing (o % o2) % (~o2) == o2" << endl;
+ for ( int a = 0; a < CNT; a++ ) {
+ if ( o2( a ) < 0 || o( a ) < 0 )
+ continue;
+ int val1 = o3( a );
+ int val2 = o( a );
+ if ( val1 != val2 )
+ cout << "error for a " << a << ": " << o( a ) << " " << o3( a ) << " : " << val1 << " != " << val2 << endl;
+ assert( val1 == val2 );
+ }
+ cout << "success" << endl;
+
+}
+
+
+int main( int /* argc */, char** /*argv*/ ) {
+ verifyDynamicText();
+ verifySumTree();
+ verifyFlexibleText();
+ verifyOffsets();
+
+ //printf("testing\n");
+ // for( int q = 0; q < CYCLES; q++ ) {
+ // }
+
+
+ return EXIT_SUCCESS;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h (revision 1522570)
@@ -0,0 +1,495 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef FLEXIBLETEXT_H
+#define FLEXIBLETEXT_H
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/split_member.hpp>
+#include <boost/serialization/deque.hpp>
+#include <boost/serialization/string.hpp>
+#include <iostream>
+#include <list>
+#include <sstream>
+#include <deque>
+
+#include "sumtree.h"
+#include "flexibletextnotifier.h"
+#include "dynamictextexport.h"
+
+namespace SumTree {
+
+template<class Tp>
+class DYNAMICTEXT_EXPORT TemporaryExchange {
+ public:
+ TemporaryExchange( Tp& target, Tp newValue ) : target_(target), oldValue_(target) {
+ target_ = newValue;
+ }
+ ~TemporaryExchange() {
+ target_ = oldValue_;
+ }
+ private:
+ Tp& target_;
+ Tp oldValue_;
+};
+///This is just a little helper that autmatically deleted unremoved members of a string-list on exceptions etc.
+///If they should be used on elsewhere, they must be removed from this list.
+template <class StringList>
+struct DYNAMICTEXT_EXPORT ManagedStringList {
+ ManagedStringList( const StringList& rhs ) : list( rhs ) {}
+
+ void delete_front() {
+ delete list.front();
+ list.pop_front();
+ }
+
+ ~ManagedStringList() {
+ for ( typename StringList::iterator it = list.begin(); it != list.end(); ++it ) {
+ delete *it;
+ }
+ }
+
+ StringList* operator -> () {
+ return & list;
+ }
+ StringList list;
+};
+
+/**This is a class that simulates a normal string, but is much more flexible and allows access using line/column- and index-information.
+ * For big documents that are edited it is much more efficient than a string, because much less allocation has to be done, since the
+ * document is internally stored within smaller units(divided into lines).
+ *
+ * Any function in this class may throw DynamicTextError on error!
+ * */
+
+template <class String, class Char = char, Char lineBreak = '\n'>
+class DYNAMICTEXT_EXPORT FlexibleText {
+ typedef std::deque<String*> StringVector;
+ public:
+ typedef std::list<String*> StringList;
+
+ FlexibleText( const String& text = "" ) : notify_(0) {
+ build( text );
+ }
+
+ ~FlexibleText() {
+ deleteText();
+ }
+
+// template <class StringListType>
+// FlexibleText( const StringListType& text ) {
+// build( text );
+// }
+
+ FlexibleText( const FlexibleText& rhs ) : notify_(0) {
+ operator=( rhs );
+ }
+
+ FlexibleText& operator = ( const FlexibleText& rhs ) {
+ deleteText();
+ for( typename StringVector::const_iterator it = rhs.text_.begin(); it != rhs.text_.end(); ++it ) {
+ text_.push_back( new String( **it ) );
+ }
+ lineColMap_ = rhs.lineColMap_;
+ return *this;
+ }
+
+ void linearToLineColumn( int position, int& line, int& column ) const {
+ SumTree::IndexAndSum s;
+ lineColMap_.indexAndSum( position, s );
+ line = s.index;
+ column = position - s.sum;
+ }
+
+ int lineColumnToLinear( int line, int column ) const {
+ return lineColMap_.sum( line ) + column;
+ }
+
+ String substr( int position, int count ) const {
+ SumTree::IndexAndSum s;
+ lineColMap_.indexAndSum( position, s );
+ return substr( s.index, position - s.sum, count );
+ }
+
+
+ void replace( int position, int length, const String& replacement )
+ {
+ ///Maybe implement this more efficiently as a single action
+ if( notify_ )
+ notify_->notifyFlexibleTextReplace( position, length, replacement );
+ TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
+
+ SumTree::IndexAndSum s;
+ lineColMap_.indexAndSum( position, s );
+ int column = position - s.sum;
+ erase( s.index, column, length );
+ insert( s.index, column, replacement );
+ }
+
+ void insert( int position, const String& text )
+ {
+ if( notify_ )
+ notify_->notifyFlexibleTextInsert( position, text );
+ TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
+
+ SumTree::IndexAndSum s;
+ lineColMap_.indexAndSum( position, s );
+ insert( s.index, position - s.sum, text );
+ }
+
+ ///Remove 'length' charateres at position 'position'. remove and erase do the same, they are provided for compatibility with Qt and STL.
+ void remove( int position, int length ) {
+ return erase( position, length );
+ }
+
+ ///Remove 'length' charateres at position 'position'. remove and erase do the same, they are provided for compatibility with Qt and STL.
+ void erase( int position, int length )
+ {
+ if( notify_ )
+ notify_->notifyFlexibleTextErase( position, length );
+ TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
+
+ SumTree::IndexAndSum s;
+ lineColMap_.indexAndSum( position, s );
+ erase ( s.index, position - s.sum, length );
+ }
+
+ String substr( int line, int column, int count ) const {
+ String ret;
+ int currentColumn = column;
+ int currentLine = line;
+ uint size = text_.size();
+ while ( count > 0 ) {
+ if ( currentLine >= (int)size )
+ return ret;
+ int get
+ = min( text_[ currentLine ] ->length() - column, count );
+ ret += text_[ currentLine ] ->substr( column, get
+ );
+ count -= get
+ ;
+ if ( count != 0 ) {
+ ret.append( "\n" );
+ count -= 1;
+ }
+ currentLine++;
+ currentColumn = 0;
+ }
+ return ret;
+ }
+
+ int length() const {
+ int s = lineColMap_.sum();
+ DYN_VERIFY_SMALLER( 0, s );
+ return s - 1;
+ }
+
+ ///SHould be called time by time(for efficiency), especially if many insertions have been done.
+ void rebuildTree() {
+ //lineColMap_ = lineColMap_.rebuild();
+ }
+
+ void checkConsistency() {
+#ifdef EXTREMEDEBUG
+ int sum = 0;
+ int num = 0;
+ int sz = text_.size();
+ for ( typename StringVector::iterator it = text_.begin(); it != text_.end(); ++it ) {
+ int lineColSum = lineColMap_.sum( num );
+ if( lineColMap_.indexValue( num ) != (*it)->length() + 1 || sum != lineColSum ) {
+ cout << "consistency-fail: at line " << num << " text: \n" << dump() << "offsets-tree: " << lineColMap_.dump() << endl;
+ }
+
+ DYN_VERIFY_SAME( lineColMap_.indexValue( num ), (*it)->length() + 1 );
+ DYN_VERIFY_SAME( sum, lineColSum );
+ num++;
+ sum += ( *it ) ->length() + 1;
+ }
+#endif
+ };
+
+ ///Returns the whole text as the normal string-representation
+ String text() const {
+ return substr( 0, 0, length() );
+ }
+
+ /*operator String() const {
+ return substr( 0, 0, length() );
+ }*/
+
+ std::string dump() const {
+ String ret;
+ int line = 0;
+ for( typename StringVector::const_iterator it = text_.begin(); it != text_.end(); ++it ) {
+ std::ostringstream os; os << "line " << line << "(len " << (*it)->length() << "): \"" << **it << "\"\n";
+ ret += os.str();
+ line++;
+ }
+ return ret;
+ }
+
+ std::string dumpTree() const {
+ return lineColMap_.dump();
+ }
+
+ template<class Archive>
+ void save( Archive& arch, const uint ) const {
+ int lines = text_.size();
+ arch << lines;
+ for( typename StringVector::const_iterator it = text_.begin(); it != text_.end(); ++it ) {
+ arch << **it;
+ }
+ }
+
+ template<class Archive>
+ void load( Archive& arch, const uint ) {
+ deleteText();
+
+ int lines;
+ arch >> lines;
+
+ for( int a = 0; a < lines; a++ ) {
+ String* s = new String();
+ arch >> *s;
+ text_.push_back( s );
+ }
+ rebuildTree();
+ }
+
+ ///Very inefficient, ranges should be used whenever possible
+ Char operator [] ( uint offset ) const {
+ IndexAndSum s;
+ lineColMap_.indexAndSum( offset, s );
+ return (*text_[s.index])[offset - s.sum];
+ }
+
+ /** Register a notifier that will be notified with ANY change to the text, exactly before the change is applied */
+ void registerNotifier( FlexibleTextNotifier<String>* notifier ) const {
+ notify_ = notifier;
+ };
+
+ /** unregister a previously registered notifier */
+ void unregisterNotifier() const {
+ notify_ = 0;
+ }
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+ private:
+
+ ///Erase and insert could be public, the only problem is that the change-notification would become more complicated(currently notification is done in linear measure)
+
+ void insert( int line, int column, const String& text ) {
+#ifdef EXTREMDEBUG
+ cout << "insertion at " << line << ":" << column << " length " << text.length() << " of \"" << text << "\"" << endl;
+ checkConsistency();
+#endif
+ uint len = text.length();
+ if( len == 0 ) return;
+ int currentStart = 0;
+ bool nobreak = true;
+ String endAppend; ///Needs to be appended to the last line inserted
+ int l = line + 1;
+
+ for ( uint a = 0; a < len; a++ ) {
+ if ( text[ a ] == lineBreak ) {
+ if( nobreak ) {
+ ///It is the first line, put it into the insertion-line and break.
+ int insertLength = a - currentStart;
+ String& curLine( *text_[line] );
+ int removeLength = curLine.length() - column;
+ DYN_VERIFY_SMALLERSAME( 0, removeLength );
+ ///Copy the last part of the line it is inserted to, and append it to the last line inserted.
+ endAppend = curLine.substr( column, removeLength );
+
+ ///Replace the removed part of the inserted-to line with the first inserted line
+ lineColMap_.changeIndexValue( line, insertLength - removeLength );
+ text_[ line ] ->replace( column, removeLength, text, currentStart, insertLength );
+ } else {
+ ///Now insert all other lines behind "line"
+ text_.insert( text_.begin() + l, new String( text, currentStart, a - currentStart ) );
+ lineColMap_.insertIndex( l, a - currentStart + 1 );
+ l++;
+ }
+
+ currentStart = a + 1;
+ nobreak = false;
+ }
+ }
+
+ if( nobreak ) {
+ text_[ line ] ->insert( column, text );
+ lineColMap_.changeIndexValue( line, len );
+#ifdef EXTREMDEBUG
+ checkConsistency();
+#endif
+ } else {
+ ///insert the last part
+ String* s = new String( text, currentStart, len - currentStart );
+ s->append( endAppend );
+ text_.insert( text_.begin() + l, s );
+ lineColMap_.insertIndex( l, s->length() + 1 );
+ }
+
+#ifdef EXTREMEDEBUG
+ cout << "text after: \n" << dump() << "offsets after: " << lineColMap_.dump() << endl;
+ checkConsistency();
+#endif
+ }
+
+ ///Remove 'length' characters in line 'line', starting at column 'column'. If the length is longer than the rest of the line, this will continue deleting in the next line.
+ void erase( int line, int column, int length ) {
+#ifdef EXTREMEDEBUG
+ cout << "erasing " << line << ":" << column << " length " << length << endl;
+ cout << "text before: \n" << dump() << "offsets before: " << lineColMap_.dump() << endl;
+ checkConsistency();
+#endif
+
+ if ( length == 0 )
+ return ;
+
+#ifdef EXTREMEDEBUG
+ DYN_VERIFY_SMALLERSAME( 0, removeLength );
+ DYN_VERIFY_SAME( text_[ line ] ->length() + 1, lineColMap_.indexValue( line ) );
+ DYN_VERIFY_SMALLER( 0, lineColMap_.indexValue( line ) );
+#endif
+ int removeLength = min( length, text_[ line ] ->length() - column );
+ int lengthLeft = length - removeLength;
+ lineColMap_.changeIndexValue( line, -removeLength );
+ text_[ line ] ->erase( column, removeLength );
+ bool broken = true;
+
+ if ( lengthLeft )
+ lengthLeft -= 1; ///Count one character for the linebreak, because it is removed and the next line pushed up
+ else
+ return ;
+
+ ///First find out what exactly has to be removed
+ int currentLine = line;
+
+ while ( lengthLeft > 0 ) {
+ currentLine++;
+ lengthLeft -= text_[ currentLine ] ->length();
+ if ( lengthLeft > 0 ) {
+ broken = true;
+ lengthLeft -= 1; ///If the whole line is removed, also count the linebreak.
+ } else {
+ broken = false;
+ }
+ }
+
+ ///Add the rest of the line that caused the stop to the beginning line
+ if ( lengthLeft != 0 ) {
+ ///Add the last -lengthLeft characters to text_[line]
+ text_[ line ] ->append( text_[ currentLine ] ->substr( text_[ currentLine ] ->length() + lengthLeft, -lengthLeft ) );
+ lineColMap_.changeIndexValue( line, -lengthLeft );
+ } else if ( broken ) {
+ ///Move the next unaffected line up
+ if ( (int)text_.size() > currentLine + 1 ) {
+ currentLine++;
+ uint len = text_[ currentLine ] ->length();
+ text_[ line ] ->append( *text_[ currentLine ] );
+ lineColMap_.changeIndexValue( line, len );
+ }
+ }
+
+ ///Remove all unneeded lines
+ for ( int a = line + 1; a <= currentLine; a++ ) {
+ delete text_[ a ];
+ lineColMap_.removeIndex( line + 1 );
+ }
+
+ text_.erase( text_.begin() + line + 1, text_.begin() + currentLine + 1 );
+
+#ifdef EXTREMDEBUG
+ checkConsistency();
+#endif
+ }
+
+ void deleteText() {
+ for( typename StringVector::iterator it = text_.begin(); it != text_.end(); ++it ) {
+ delete *it;
+ }
+ text_.clear();
+ }
+ StringList split( const String& text ) {
+ StringList ret;
+ uint len = text.length();
+ int currentStart = 0;
+
+ for ( uint a = 0; a < len; a++ ) {
+ if ( text[ a ] == lineBreak ) {
+ ret.push_back( new String( text.substr( currentStart, a - currentStart ) ) );
+ currentStart = a + 1;
+ }
+ }
+ //if ( currentStart != len )
+ ret.push_back( new String( text.substr( currentStart, len - currentStart ) ) );
+
+ return ret;
+ }
+ template <class StringListType>
+ void build( const StringListType& lines ) {
+ std::vector<int> length;
+ int size = lines.size();
+ length.resize( size );
+
+ int a = 0;
+ for ( typename StringListType::const_iterator i = lines.begin(); i != lines.end(); i++ ) {
+ length[ a ] = i->length() + 1; ///Plus one for the next-line character
+ text_.push_back( new String( *i ) );
+ a++;
+ }
+
+ //length[ size - 1 ] -= 1; ///The last line should not get the linebreak.
+ lineColMap_ = SumTree::Map( length );
+ }
+
+ void build( const String& text ) {
+ std::vector<int> length;
+ ManagedStringList<StringList> lines( split( text ) );
+ int size = lines->size();
+ length.resize( size );
+
+ int a = 0;
+ while( !lines->empty() ) {
+ length[ a ] = lines->front()->length() + 1; ///Plus one for the next-line character
+ text_.push_back( lines->front() );
+ lines->pop_front();
+ a++;
+ }
+
+ //length[ size - 1 ] -= 1; ///The last line should not get the linebreak.
+ lineColMap_ = SumTree::Map( length );
+ }
+
+ inline static int min( int a, int b ) {
+ return a < b ? a : b;
+ }
+
+ mutable FlexibleTextNotifier<String>* notify_;
+ StringVector text_; ///Not the most intelligent solution(some combination of maps and offset-maps would be perfect)
+ SumTree::Map lineColMap_;
+};
+}
+
+template <class String, class Char, Char lineBreak>
+std::ostream& operator << ( std::ostream& o, const SumTree::FlexibleText<String, Char, lineBreak>& rhs ) {
+ o << rhs.text();
+ return o;
+}
+
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp (revision 1522570)
@@ -0,0 +1,707 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "sumtree.h"
+#include <string>
+#include <sstream>
+#include <algorithm>
+#include "verify.h"
+#include <limits.h>
+
+///Must be less than SPLIT_NODES_THRESHOLD and more than JOIN_NODES_THRESHOLD
+#define PREFERRED_NODES 4
+
+#define SPLIT_NODES_THRESHOLD 8
+
+///Must be less than PREFERRED_NODES
+#define JOIN_NODES_THRESHOLD 2
+
+namespace SumTree {
+
+void mult( ostream& os, int count, const char* c ) {
+ for ( int a = 0; a < count; a++ )
+ os << c;
+}
+
+Node::Node( bool isLeaf, Node* parent ) : parent_( parent ), nodeCount_( 0 ), sum_( 0 ), indexCount_( 0 ), isLeaf_( isLeaf ) {}
+
+Node* Node::makeOwn( Node* parent ) {
+ //Node * myParent = parent_ get();
+ if ( _Shared_count() == 1 ) {
+ parent_ = parent;
+ return this;
+ }
+
+ return ( new Node( *this ) ) ->setParent( parent );
+}
+
+Node* Node::setParent( Node* parent ) {
+ //DYN_VERIFY_SAME( parent, 0 ); //reactive if WeakSharedPtr is used again
+
+ parent_ = parent;
+ return this;
+}
+
+int Map::sum( int index ) const {
+ return tree_->sum( index );
+}
+
+int Map::sum() const {
+ return tree_->sum();
+}
+
+bool Map::hasIndex( int index ) const {
+ return tree_->hasIndex( index );
+}
+
+void Map::indexAndSum( int sum, IndexAndSum& targ ) const {
+ targ.index = 0;
+ targ.sum = 0;
+ tree_->indexAndSum( sum, targ );
+}
+
+int Map::index( int sum ) const {
+ return tree_->index( sum );
+}
+
+Map::Map( const SumVector& summands ) {
+ tree_ = new Node( false, 0 );
+ int cnt = build( summands.begin(), summands.end(), tree_ );
+ DYN_VERIFY_SAME( (int)cnt, (int)summands.size() );
+}
+
+Map::~Map() {}
+
+Map::Map( const Map& rhs ) : WeakShared(), tree_ ( new Node( *rhs.tree_ ) ) {}
+
+Map& Map::operator = ( const Map& rhs ) {
+ tree_ = new Node( *rhs.tree_ );
+ return *this;
+}
+
+void Node::addNode( Node* node ) {
+ nodes_.push_back( node );
+ ++nodeCount_;
+}
+
+bool Node::hasIndex( int indicesNeeded ) const {
+ ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it != nodes_.end() ) {
+ ///Ask the next one for the summ
+ return ( *it ) ->hasIndex( indicesNeeded );
+ }
+
+ if( !isRange() )
+ if( indicesNeeded == 0 ) return true;
+ else
+ if( indicesNeeded < indexCount_ ) return true;
+
+ return false;
+}
+
+int Node::indexValue( int indicesNeeded ) const {
+ ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it != nodes_.end() ) {
+ ///Ask the next one for the summ
+ return ( *it ) ->indexValue( indicesNeeded );
+ }
+
+ if( !isRange() ) {
+ DYN_VERIFY_SAME( indicesNeeded, 0 );
+ return sum_;
+ } else {
+ DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
+ return sum_ / indexCount_;
+ }
+}
+
+int Node::setIndexValue( int indicesNeeded, int value ) {
+ ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it != nodes_.end() ) {
+ ///Ask the next one for the summ
+ ( *it ) = ( *it ) ->makeOwn( this );
+ return ( *it ) ->setIndexValue( indicesNeeded, value );
+ }
+
+ if( !isRange() ) {
+ DYN_VERIFY_SAME( indicesNeeded, 0 );
+ DYN_VERIFY( isLeaf_ );
+
+ int ret = sum_;
+ update( value - ret, 0 );
+ return ret;
+ } else {
+ DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
+ ///It is a Range, split it up into two new ranges and one normal value-node which we can change.
+ int eachValue = sum_ / indexCount_;
+ if( eachValue == value ) return value; ///No need to split up
+ Node * n = new Node( true, this );
+ update( -eachValue, -1 );
+ splitRange( indicesNeeded, n );
+ n->update( value, 1 );
+ updateStructure();
+ return eachValue;
+ }
+}
+
+int Node::changeIndexValue( int indicesNeeded, int value ) {
+ ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ ListType::iterator end = nodes_.end();
+
+ for ( ; it != end && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it != end ) {
+ NodePointer& n( *it );
+ ///Ask the next one for the summ
+ n = n->makeOwn( this );
+ return n->changeIndexValue( indicesNeeded, value );
+ }
+
+ if( !isRange() ) {
+ DYN_VERIFY_SAME( indicesNeeded, 0 );
+ DYN_VERIFY( isLeaf_ );
+
+ update( value, 0 );
+ return sum_;
+ } else {
+ DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
+ ///It is a Range, split it into two new ranges and one normal value-node which we can change.
+ int eachValue = sum_ / indexCount_;
+ Node * n = new Node( true, this );
+ update( -eachValue, -1 );
+ splitRange( indicesNeeded, n );
+ n->update( value + eachValue, 1 );
+ updateStructure();
+ return value + eachValue;
+ }
+}
+
+void Node::updateStructure() {
+ if ( isLeaf_ )
+ return ;
+ DYN_VERIFY_SAME( (int)nodes_.size(), (int)nodeCount_ );
+
+ int dif = nodeCount_ - PREFERRED_NODES;
+ if ( dif > 0 ) {
+ ///split sub-nodes into a usable count of parts
+ int splitAway = dif + 1;
+ ///Algorithm: find the "splitAway" nodes with the lowest index-count-sum, and export them to a container-node
+
+ int cnt = 0; ///The count of nodes that are summed to "indices"
+ int indices = 0; ///Their count of indices
+ ListType::iterator first = nodes_.begin(); ///The last node of the group that sums to "indices"
+
+ ListType::iterator best = nodes_.end();
+ ListType::iterator bestLast;
+ int bestIndices = INT_MAX;
+
+ ListType::iterator it;
+ for ( it = nodes_.begin(); it != nodes_.end(); ++it ) {
+ if ( cnt == splitAway ) {
+ if ( indices < bestIndices ) {
+ best = first;
+ bestLast = it;
+ bestIndices = indices;
+ }
+ indices -= ( *first ) ->indexCount();
+ ++first;
+ } else {
+ cnt++;
+ }
+ indices += ( *it ) ->indexCount();
+ }
+ if ( indices < bestIndices ) {
+ best = first;
+ bestLast = it;
+ bestIndices = indices;
+ }
+
+ ///now create an own group for (best -> bestLast)
+ if ( best != nodes_.end() ) {
+ NodePointer branch = new Node( false, this );
+ branch->nodes_.insert( branch->nodes_.begin(), best, bestLast );
+ DYN_VERIFY_SAME( (int)branch->nodes_.size(), (int)cnt );
+ branch->nodeCount_ = cnt;
+
+ it = best;
+ while ( it != bestLast ) {
+ //(*best)->setParent( branch );
+ branch->sum_ += ( *it ) ->sum_;
+ branch->indexCount_ += ( *it ) ->indexCount_;
+ ++it;
+ }
+
+ nodeCount_ += 1;
+ nodes_.insert( best, branch );
+ DYN_VERIFY_SAME( (int)nodeCount_, (int)nodes_.size() );
+
+ nodeCount_ -= cnt;
+ nodes_.erase( best, bestLast );
+ DYN_VERIFY_SAME( (int)nodeCount_, (int)nodes_.size() );
+
+ } else {
+ DYN_VERIFY( 0 );
+ }
+
+ } else if ( nodeCount_ <= JOIN_NODES_THRESHOLD ) {
+ if ( parent_ ) {
+ ///Remove empty non-leaf-nodes
+ if ( nodeCount_ == 0 ) {
+ if( indexCount_ == 0 ) {
+ parent_->removeChild( this );
+ } else {
+ ///It is a range, leave it alone.
+ }
+ } else {
+ ///Move all own children to the parent
+ for ( ListType::iterator it = parent_->nodes_.begin(); it != parent_->nodes_.end(); ++it ) {
+ if ( it->data() == this ) {
+ parent_->nodes_.insert( it, nodes_.begin(), nodes_.end() );
+ parent_->nodeCount_ += nodeCount_;
+ NodePointer n = this; ///To prevent too early deletion
+ parent_->removeChild( this );
+ parent_->updateStructure();
+ nodeCount_ = 0;
+ break;
+ }
+ }
+ }
+ ///Move child-nodes up to the parent
+ } else {}
+ }
+}
+
+void Node::insertIndex( int indicesNeeded, int value ) {
+ ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it == nodes_.end() || ( *it ) ->isLeaf() ) {
+
+ bool range = isRange();
+
+ if ( indicesNeeded <= 1 || range ) {
+ Node * n = new Node( true, this );
+ if( range ) {
+ splitRange( indicesNeeded, n );
+ } else {
+ ///We have reached the end, insert the index
+ nodes_.insert( it, NodePointer( n ) );
+ ++nodeCount_;
+ }
+ n->update( value, 1 );
+ } else {
+ ///There are still indices missing, they could be filled with zeroes by using insertRange
+ DYN_VERIFY( 0 );
+ }
+ } else {
+ ( *it ) = ( *it ) ->makeOwn( this );
+ ( *it ) ->insertIndex( indicesNeeded, value );
+ }
+ updateStructure();
+}
+
+void Node::splitRange( int indicesNeeded, Node* insertNode ) {
+ DYN_VERIFY_SMALLERSAME( indicesNeeded, indexCount_ );
+ int eachValue = sum_ / indexCount_;
+ DYN_VERIFY_SAME( eachValue*indexCount_, sum_ );
+ int r1Size = indicesNeeded;
+ int r2Size = indexCount_ - indicesNeeded;
+
+ update( -sum_, -indexCount_ ); /*This should be done more efficiently with only one single update*/
+ DYN_VERIFY_SAME( sum_, 0 );
+ DYN_VERIFY_SAME( indexCount_, 0 );
+ ///This makes this range-node a normal node.
+
+ Node * n;
+// Add the first split-range
+ if( r1Size ) {
+ n = new Node( false, this );
+ nodes_.insert( nodes_.end(), NodePointer( n ) );
+ ++nodeCount_;
+ n->update( eachValue * r1Size, r1Size );
+ }
+
+ nodes_.insert( nodes_.end(), NodePointer( insertNode ) );
+ ++nodeCount_;
+
+ ///Add the second split-range
+ if( r2Size ) {
+ n = new Node( false, this );
+ nodes_.insert( nodes_.end(), NodePointer( n ) );
+ ++nodeCount_;
+ n->update( eachValue * r2Size, r2Size );
+ }
+
+ DYN_VERIFY( !isRange() );
+}
+
+void Node::insertRange( int indicesNeeded, int size, int value ) {
+ ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if ( it == nodes_.end() || ( *it ) ->isLeaf() ) {
+ bool range = isRange();
+ if ( indicesNeeded <= 1 || range ) {
+ Node * n = new Node( false, this );
+
+ if( range ) {
+ /**This is a range, and needs to be made a normal inner node with a split up slave-range. */
+ DYN_VERIFY( it == nodes_.end() );
+ splitRange( indicesNeeded, n );
+ } else {
+ /**We have reached the end, insert the range*/
+ nodes_.insert( it, NodePointer( n ) );
+ ++nodeCount_;
+ }
+
+ n->update( value*size, size );
+ } else {
+ ///There are still indices missing, they could be filled with zeroes
+ DYN_VERIFY( 0 );
+ }
+ } else {
+ ( *it ) = ( *it ) ->makeOwn( this );
+ ( *it ) ->insertRange( indicesNeeded, size, value );
+ }
+ updateStructure();
+}
+
+void Node::removeChild( Node* n ) {
+ for ( ListType::iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
+ if ( ( *it ).data() == n ) {
+ nodes_.erase( it );
+ --nodeCount_;
+ return ;
+ }
+ }
+}
+
+int Node::removeIndex( int indicesNeeded ) {
+ ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ for ( ; it != nodes_.end() && indicesNeeded >= 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if( it != nodes_.end() && indicesNeeded == 0 && ( *it ) ->isLeaf() ) {
+ ///Remove the leaf-node
+ int ret = ( *it ) ->sum();
+ nodes_.erase( it );
+ --nodeCount_;
+ update( -ret, -1 );
+
+ updateStructure();
+ return ret;
+ } else if( isRange() ) {
+ DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
+ int ret = sum_ / indexCount_;
+ update( -ret, -1 );
+ updateStructure();
+ return ret;
+ } else {
+ DYN_VERIFY( it != nodes_.end() );
+ ( *it ) = ( *it ) ->makeOwn( this );
+ return ( *it ) ->removeIndex( indicesNeeded );
+ }
+}
+
+int Map::setIndexValue( int index, int value ) {
+ return tree_->setIndexValue( index, value );
+}
+
+int Map::changeIndexValue( int index, int diff ) {
+ return tree_->changeIndexValue( index, diff );
+}
+
+int Map::indexValue( int indicesNeeded ) const {
+ return tree_->indexValue( indicesNeeded );
+}
+
+void Map::insertRange( int position, int size, int value ) {
+ tree_->insertRange( position, size, value );
+}
+
+///Inserts an index at position "index" with the value "value"
+void Map::insertIndex( int index, int value ) {
+ tree_->insertIndex( index, value );
+}
+
+int Map::removeIndex( int index ) {
+ return tree_->removeIndex( index );
+}
+
+int Map::indexCount() const {
+ return tree_->indexCount();
+}
+
+int Node::sum( int index ) const {
+ if ( index == 0 )
+ return 0;
+ int summ = 0;
+ int indicesNeeded = index;
+
+ ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ ListType::const_iterator end = nodes_.end();
+ for ( ; it != end && indicesNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->indexCount();
+ if ( itCount <= indicesNeeded ) {
+ summ += ( *it ) ->sum();
+ indicesNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+
+ if( indicesNeeded > 0 ) {
+ if ( it != end ) {
+ ///Ask the next one for the summ
+ summ += ( *it ) ->sum( indicesNeeded );
+ } else if( isRange() ) {
+ int eachValue = sum_ / indexCount_;
+ int cnt = indicesNeeded;
+ if( cnt > indexCount_ ) cnt = indexCount_;
+ summ += cnt * eachValue;
+ }
+ }
+
+ return summ;
+}
+/*
+int Node::index( int sum ) const {
+ ListType::const_iterator end = nodes_.end();
+ int index = 0;
+ for( ListType::const_iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
+ int cnt = (*it)->sum();
+ if( cnt <= sum ) {
+ index -= cnt;
+ } else {
+ return index + (*it)->index( sum );
+ }
+ }
+ return index;
+ if( isLeaf_ && sum == 0 ) {
+ return 0;
+ } else {
+ cout << nodes_.size() << endl;
+
+ DYN_VERIFY( isLeaf_ && sum == 0 );
+ }
+}*/
+
+int Node::index( int sum ) const {
+ if ( isLeaf_ )
+ return 0;
+ int ind = 0;
+ int sumNeeded = sum;
+
+ ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
+ ListType::const_iterator end = nodes_.end();
+ for ( ; it != end && sumNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->sum();
+ if ( itCount <= sumNeeded ) {
+ ind += ( *it ) ->indexCount();
+ sumNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+ if ( it != end ) {
+ if ( sumNeeded > 0 ) {
+ ///Ask the next one for the summ
+ ind += ( *it ) ->index( sumNeeded );
+ } else {
+ ///Jump over all indices that have a size of zero, because those
+ ///might steal the map from the index behind(it should not be possible to map to them).
+ while ( it != end && ( *it ) ->sum() == 0 ) {
+ ind += ( *it ) ->indexCount();
+
+ ++it;
+ }
+ }
+ } else if( sumNeeded > 0 && isRange() ) {
+ int eachValue = sum_ / indexCount_;
+ ind += ( sumNeeded / eachValue );
+ }
+
+ return ind;
+}
+
+void Node::indexAndSum( int sum, IndexAndSum& targ ) const {
+ if ( isLeaf_ )
+ return;
+ int sumNeeded = sum;
+
+ ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as targ.indexex(they are completely in)
+ ListType::const_iterator end = nodes_.end();
+ for ( ; it != end && sumNeeded > 0 ; ++it ) {
+ int itCount = ( *it ) ->sum();
+ if ( itCount <= sumNeeded ) {
+ targ.index += ( *it ) ->indexCount();
+ targ.sum += itCount;
+ sumNeeded -= itCount;
+ } else {
+ break;
+ }
+ }
+ if ( it != end ) {
+ if ( sumNeeded > 0 ) {
+ ///Ask the next one for the summ
+ ( *it ) ->indexAndSum( sumNeeded, targ );
+ } else {
+ ///Jump over all targ.indexices that have a size of zero, because those
+ ///might steal the map from the targ.indexex behtarg.index(it should not be possible to map to them).
+ while ( it != end && ( *it ) ->sum() == 0 ) {
+ targ.index += ( *it ) ->indexCount();
+
+ ++it;
+ }
+ }
+ } else if( sumNeeded > 0 && isRange() ) {
+ int eachValue = sum_ / indexCount_;
+ int cnt = ( sumNeeded / eachValue );
+ targ.index += cnt;
+ targ.sum += cnt * eachValue;
+ }
+}
+
+int Map::build( const SumVector::const_iterator& begin, const SumVector::const_iterator& end, Node* parent ) {
+ if ( begin == end )
+ return 0;
+
+ SumVector::const_iterator it = begin;
+ ++it;
+ if ( it == end ) {
+ ///It is the only item
+ NodePointer ret = new Node( true, parent );
+
+ ret->update( *begin, 1 );
+ parent->addNode( ret );
+ return 1;
+ }
+ it = begin;
+ int count = 0;
+ for ( SumVector::const_iterator i = begin; i != end; ++i )
+ ++count;
+
+ int threshold = count / PREFERRED_NODES;
+ if ( threshold == 0 )
+ threshold = 1;
+
+ SumVector::const_iterator currentItem = begin;
+ it = begin;
+ count = 0;
+ int totalCount = 0;
+ NodePointer branch = new Node( false, parent );
+ parent->addNode( branch );
+
+ while ( 1 ) {
+ if ( it == end || ( count >= threshold && it != currentItem ) ) {
+ totalCount += build( currentItem, it, branch );
+ currentItem = it;
+ count = 0;
+
+ if ( it == end )
+ break;
+ }
+ ++count;
+
+ ++it;
+ }
+ return totalCount;
+}
+/*
+Map Map::rebuild() {
+ std::vector<int> vecs;
+ tree_->fillValues( vecs );
+ return Map( vecs );
+}*/
+
+std::string Node::dump( int indexOffset, int depth ) const {
+ std::ostringstream os;
+ mult( os, depth, " " );
+ os << "depth: " << depth << ( isLeaf_ ? " leaf " : " helper " ) << "sum: " << sum_ << " ";
+
+ if ( !isLeaf_ ) {
+ os << "index-count " << indexCount_ << " (nodes: " << nodes_.size() << ")\n";
+ for ( ListType::const_iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
+ os << ( *it ) ->dump( indexOffset, depth + 1 );
+ indexOffset += ( *it ) ->indexCount();
+ }
+ } else {
+ os << "index: " << indexOffset << "\n";
+ }
+
+ return os.str();
+}
+
+std::string Map::dump() const {
+ return tree_->dump( 0, 0 );
+}
+
+
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp (revision 1522570)
@@ -0,0 +1,204 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "vectortimestamp.h"
+#include <iostream>
+#include <ext/hash_map>
+#include <sstream>
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+std::ostream& operator << ( std::ostream& str, const VectorTimestamp& timestamp ) {
+ str << timestamp.print();
+ return str;
+}
+
+namespace __gnu_cxx {
+template <>
+struct hash<VectorTimestamp> {
+ size_t operator() ( const VectorTimestamp& x ) {
+ return x.hash();
+ }
+};
+}
+
+///Maximizes every stamp with the other side
+void VectorTimestamp::maximize( const VectorTimestamp& rhs ) {
+ if ( rhs.m_state.size() > m_state.size() )
+ m_state.resize( rhs.m_state.size(), 0 );
+ for ( uint a = 0; a < rhs.m_state.size(); a++ ) {
+ if ( rhs.m_state[ a ] > m_state[ a ] )
+ m_state[ a ] = rhs.m_state[ a ];
+ }
+}
+
+bool VectorTimestamp::isZero() const {
+ for ( uint a = 0; a < m_state.size(); a++ )
+ if ( m_state[ a ] != 0 )
+ return false;
+ return true;
+}
+
+
+
+///copies the timestamp and increases on the given index by one
+VectorTimestamp::VectorTimestamp( int primaryIndex, const VectorTimestamp& rhs ) : m_state( rhs.m_state ), m_primaryIndex( 0 ) {
+ setPrimaryIndex( primaryIndex );
+ increase();
+}
+
+Timestamp VectorTimestamp::primaryStamp() const {
+ if ( m_state.size() <= m_primaryIndex )
+ return 0;
+ return ( *this ) [ m_primaryIndex ];
+}
+/**
+ * @return whether every timestamp is smaller than the according index of rhs
+* */
+bool VectorTimestamp::smaller( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ if ( sz == 0 )
+ return false;
+
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 < s2 )
+ continue;
+ else
+ return false;
+ }
+ return true;
+}
+
+/**
+ * @return whether every timestamp is smaller than or same as the according index of rhs
+* */
+bool VectorTimestamp::smallerOrSame( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 <= s2 )
+ continue;
+ else
+ return false;
+ }
+ return true;
+}
+
+bool VectorTimestamp::isOneBigger( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 > s2 )
+ return true;
+ }
+ return false;
+}
+
+bool VectorTimestamp::isOneSmaller( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 < s2 )
+ return true;
+ }
+ return false;
+}
+
+size_t VectorTimestamp::hash() const {
+ size_t s = 0;
+ uint sz = m_state.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ s += ( a * 17 ) * m_state[ a ];
+ }
+ return s;
+}
+
+bool VectorTimestamp::operator == ( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ if ( ( *this ) [ a ] != rhs[ a ] )
+ return false;
+ }
+ return true;
+}
+
+///The following two are useful for sorting in a map
+///Very inefficient
+bool VectorTimestamp::operator < ( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 < s2 )
+ return true;
+ else if ( s1 > s2 )
+ return false;
+ }
+ return false;
+}
+
+///Very inefficient
+bool VectorTimestamp::operator <= ( const VectorTimestamp& rhs ) const {
+ uint sz = size();
+ if ( rhs.size() > sz )
+ sz = rhs.size();
+ for ( uint a = 0; a < sz; a++ ) {
+ Timestamp s1 = ( *this ) [ a ];
+ Timestamp s2 = rhs[ a ];
+ if ( s1 < s2 )
+ return true;
+ else if ( s1 > s2 )
+ return false;
+ }
+ return true;
+}
+
+void VectorTimestamp::setPrimaryIndex( const uint index ) {
+ m_primaryIndex = index;
+ if ( m_state.size() < index + 1 )
+ m_state.resize( index + 1, 0 );
+}
+
+std::string VectorTimestamp::print() const {
+ std::string ret = "[";
+ for ( std::vector<Timestamp>::const_iterator it = m_state.begin(); it != m_state.end(); ++it ) {
+ if ( it != m_state.begin() )
+ ret += ", ";
+ std::ostringstream o;
+ o << *it;
+ ret += o.str();
+ }
+ ret += "]";
+
+ return ret;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h (revision 1522570)
@@ -0,0 +1,125 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef VECTORTIMESTAMP_H
+#define VECTORTIMESTAMP_H
+
+#include <vector>
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/level.hpp>
+#include <iosfwd>
+#include "dynamictextexport.h"
+
+typedef int Timestamp;
+
+class DYNAMICTEXT_EXPORT VectorTimestamp {
+ std::vector<Timestamp> m_state;
+ uint m_primaryIndex;
+ public:
+ VectorTimestamp( int primaryIndex = 0 ) : m_primaryIndex( 0 ) {
+ setPrimaryIndex( primaryIndex );
+ }
+
+ ///copies the timestamp and increases on the given index by one
+ VectorTimestamp( int primaryIndex, const VectorTimestamp& rhs );
+
+ Timestamp primaryStamp() const;
+
+ Timestamp operator[] ( const uint index ) const {
+ if ( index < m_state.size() ) {
+ return m_state[ index ];
+ } else {
+ return 0;
+ }
+ }
+
+ void setStamp( uint index, int value ) {
+ if ( index >= m_state.size() ) {
+ m_state.resize( index + 1, 0 );
+ }
+
+ m_state[ index ] = value;
+ }
+
+ ///Maximizes every stamp with the other side
+ void maximize( const VectorTimestamp& rhs );
+
+ bool isZero() const;
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & m_state;
+ arch & m_primaryIndex;
+ }
+
+ /**
+ * @return whether every timestamp is smaller than the according index of rhs
+ * */
+ bool smaller( const VectorTimestamp& rhs ) const ;
+
+ /**
+ * @return whether every timestamp is smaller than or same as the according index of rhs
+ * */
+ bool smallerOrSame( const VectorTimestamp& rhs ) const ;
+
+ bool isOneBigger( const VectorTimestamp& rhs ) const ;
+
+ bool isOneSmaller( const VectorTimestamp& rhs ) const ;
+
+ size_t hash() const ;
+
+ bool operator == ( const VectorTimestamp& rhs ) const ;
+
+ inline bool operator != ( const VectorTimestamp& rhs ) const {
+ return ! operator==( rhs );
+ }
+
+ ///The following two are useful for sorting in a map
+ ///Very inefficient
+ bool operator < ( const VectorTimestamp& rhs ) const ;
+
+ ///Very inefficient
+ bool operator <= ( const VectorTimestamp& rhs ) const ;
+
+ void setPrimaryIndex( const uint index );
+
+ uint primaryIndex() const {
+ return m_primaryIndex;
+ }
+
+ void decrease() {
+ --m_state[ m_primaryIndex ];
+ }
+
+ void increase() {
+ ++m_state[ m_primaryIndex ];
+ }
+
+ void resize( uint sz ) {
+ m_state.resize( sz, 0 );
+ }
+
+ uint size() const {
+ return m_state.size();
+ }
+
+ std::string print() const;
+};
+
+DYNAMICTEXT_EXPORT std::ostream& operator << ( std::ostream& str, const VectorTimestamp& timestamp );
+
+BOOST_CLASS_IMPLEMENTATION(VectorTimestamp, object_serializable)
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h (revision 1522570)
@@ -0,0 +1,36 @@
+/*
+ This file is part of the KDevelop platform
+ Copyright 2006 Matt Rogers <mattr@kde.org>
+ Copyright 2004 Jarosław Staniek <staniek@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef DYNAMICTEXTEXPORT_H
+#define DYNAMICTEXTEXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+#ifndef DYNAMICTEXT_XPORT
+# ifdef MAKE_DYNAMICTEXT_LIB
+# define DYNAMICTEXT_EXPORT KDE_EXPORT
+# else
+# define DYNAMICTEXT_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif /* DYNAMICTEXTEXPORT_H*/
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h (revision 1522570)
@@ -0,0 +1,223 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef DYNAMICTEXT_H
+#define DYNAMICTEXT_H
+#include <string>
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/split_member.hpp>
+
+typedef std::string String;
+
+#include "../network/crossmap.h"
+#include "../network/safesharedptr.h"
+#include "../network/weaksafesharedptr.h"
+#include "vectortimestamp.h"
+#include "offsetutils.h"
+
+#include "dynamictextexport.h"
+#include "dynamictexthelpers.h"
+#include "flexibletext.h"
+using namespace Tree;
+
+#define INVALID_POSITION -1000000
+
+struct DYNAMICTEXT_EXPORT OffsetRequest {
+ VectorTimestamp from;
+ VectorTimestamp to;
+ OffsetRequest( const VectorTimestamp& f, const VectorTimestamp& t ) : from(f), to(t) {
+ }
+ bool operator == ( const OffsetRequest& rhs ) const {
+ return from == rhs.from && to == rhs.to;
+ }
+};
+
+namespace __gnu_cxx {
+template<>
+struct hash<OffsetRequest> {
+ size_t operator () ( const OffsetRequest& req ) const {
+ return req.from.hash() + 3*req.to.hash();
+ }
+};
+}
+
+/** DynamicText is a class that manages a dynamic document that is
+ * created by an arbitrary count of parallel sources by timestamped replacements.
+ *
+ * It allows to create any state that is possible without conflicts(allows for example
+ * to undo all changes done by one user, or even only specific changes by disabling them
+ * one for one.)
+ *
+ * currently, every function may throw DynamicTextError on problems
+ * */
+class DYNAMICTEXT_EXPORT DynamicText : public SafeShared {
+
+ public:
+ typedef std::string String;
+
+ typedef SumTree::FlexibleText<String> Text;
+
+ /**
+ * @param initialState the state which will be used as zero-state.
+ * */
+ explicit DynamicText( const VectorTimestamp& initialState = VectorTimestamp(), const String& initialText = String() );
+
+ /**Does the replacement precisely, considering the timestamp. Jumps back to the current state after inserting.
+ * @param stamp The timestamp in whose context the replacement has to be done
+ * @param replacement The replacement to do in the given timestamp. It will be stored.. */
+ bool insert( const VectorTimestamp& stamp, const SimpleReplacement& replacement );
+
+ /**Inserts the replacement in the current context, using the given index, and returning the resulting identifying timestamp.
+ * */
+ VectorTimestamp insert( uint index, const SimpleReplacement& replacement );
+
+ /**The current state the text is in
+ * */
+ VectorTimestamp state() const;
+
+ /**The highest state possible
+ * */
+ VectorTimestamp tailState() const;
+
+ VectorTimestamp initialState() const;
+
+ const Text& text() const;
+
+ const String& initialText() const;
+ /**
+ * @param state The state which the text should have after the change. The default-parameter changes to the current state.
+ * If force is enabled, conflicts will be ignored instead of stopping.(The resulting text may be damaged)
+ */
+ bool changeState( const VectorTimestamp& state = VectorTimestamp(), bool force = false );
+
+ /**
+ * Removes everything above the current state.
+ * */
+ void cut();
+
+ /**rewinds to a position that is smaller/same than state in every index
+ * @param state the state of the document will be smaller than that state
+ * */
+ bool rewind( const VectorTimestamp& state );
+ ///The given state must be bigger/same than the current state in every stamp
+ bool advance( const VectorTimestamp& state );
+
+ void dump() const;
+
+ /** @return the first replacement with the given primary index, or zero */
+ ReplacementPointer first( uint index ) const;
+
+ /** @return the first replacement with the given primary index, that is currently not applied to the text(its primary stamp is higher than the current state's stamp on that index), or zero */
+ ReplacementPointer firstUnapplied( uint index ) const;
+
+ /** @return the last replacement with the given primary index, or zero */
+ ReplacementPointer last( uint index ) const;
+
+ /** @return the last replacement with the given primary index, that is currently applied to the text(its primary stamp is same as the current state's stamp on that index), or zero */
+ ReplacementPointer lastApplied( uint index ) const;
+
+ /**
+ * @return the highest stamp with that index
+ * */
+ Timestamp highestStamp( uint index ) const;
+
+ /**Returns the internal replacement-objects that can be used for example to disable
+ * a single replacement. This is dangerous, they should not be altered.
+ * @param primaryIndex index(user?)
+ * @param stamp timestamp for that index
+ * */
+ ReplacementPointer replacement( uint primaryIndex, Timestamp stamp );
+
+ template<class Archive>
+ void load( Archive& arch, const uint version ) {
+ standardSerialize( arch, version );
+ m_allReplacements.clear();
+ for( uint a = 0; a < m_applied.size(); a++ ) {
+ ReplacementPointer p = m_applied[0].first;
+ if( p == 0 ) p = m_unApplied[0].first;
+ while( p != 0 ) {
+ hashReplacement( p );
+ p = p->next();
+ }
+ }
+ }
+
+ template<class Archive>
+ void save( Archive& arch, const uint version ) const {
+ const_cast<DynamicText*>( this ) ->standardSerialize( arch, version );
+ }
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+
+ private:
+ template<class Archive>
+ void standardSerialize( Archive& arch, const uint ) {
+ arch & m_text;
+ arch & m_state;
+ arch & m_initialState;
+ arch & m_currentOffset;
+ arch & m_dummy;
+ arch & m_applied;
+ arch & m_unApplied;
+ arch & m_initialText;
+ }
+
+ VectorTimestamp insertInternal( uint index, const SimpleReplacement& replacement );
+
+ bool changeStateInternal( const VectorTimestamp& state = VectorTimestamp(), bool force = false );
+
+ bool rewindInternal( const VectorTimestamp& state );
+ ///The given state must be bigger/same than the current state in every stamp
+ bool advanceInternal( const VectorTimestamp& state );
+
+ ///The following are notification-functions that can be overridden by derived classes
+ ///To get notified about exact string-changes you can register a notifier to the FlexibleText returned by text().
+ virtual void notifyInserted( const ReplacementPointer& rep );
+ virtual void notifyStateChanged();
+
+ ///@todo check which keys are really necessary
+ BIND_LIST_3( ReplacementKeys, WeakReplacementPointer, VectorTimestamp, ReplacementId )
+ typedef Utils::CrossMap< WeakReplacementPointer, ReplacementKeys > ReplacementSet;
+ ReplacementSet m_allReplacements;
+ friend class Advancer;
+
+ ///This contains the chains from the beginning until(including) the last item that is applied.
+ std::vector<ReplacementChain> m_applied;
+ ///This contains the chains that were temporarily unapplied
+ std::vector<ReplacementChain> m_unApplied;
+
+ typedef __gnu_cxx::hash_map< OffsetRequest, OffsetMap > OffsetCache;
+ OffsetCache m_offsetCache;
+
+ Text m_text;
+ String m_initialText;
+ VectorTimestamp m_state;
+ VectorTimestamp m_initialState;
+ OffsetMap m_currentOffset; ///This offset-map represents all replacements that should have been applied(according to m_state), but are not.
+
+ void hashReplacement( const ReplacementPointer& rep );
+ void unHashReplacement( const ReplacementPointer& rep );
+
+ ///Returns the offset from the 'from' position to the 'to' one. If position is set, all replacements that are behind that position(given in from-space) will be excluded while computation.
+ OffsetMap offset( VectorTimestamp from, VectorTimestamp to, int position = INVALID_POSITION );
+
+ ReplacementPointer m_dummy;
+
+ ///Changes the state to the newest one available
+ bool toTail();
+};
+
+typedef SharedPtr<DynamicText, BoostSerialization> DynamicTextPointer;
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h (revision 1522570)
@@ -0,0 +1,145 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#define private public
+
+#ifndef DYNAMICTEXT_HELPERS
+#define DYNAMICTEXT_HELPERS
+
+#include <iosfwd>
+
+#include "offsetutils.h"
+#include "verify.h"
+#include "../network/sharedptr.h"
+#include "../network/weaksafesharedptr.h"
+#include "vectortimestamp.h"
+#include "dynamictextexport.h"
+
+///Check whether these are useful for something or should be completely removed
+//#define USELINKS
+
+class DynamicText;
+class Replacement;
+class Advancer;
+typedef SharedPtr<Replacement, BoostSerializationNormal> ReplacementPointer;
+typedef WeakSharedPtr<Replacement, BoostSerializationNormal> WeakReplacementPointer;
+
+struct DYNAMICTEXT_EXPORT SimpleReplacement {
+ uint m_position;
+ std::string m_oldText;
+ std::string m_newText;
+ SimpleReplacement() : m_position( 0 ) {
+ }
+ SimpleReplacement( uint position, const std::string& newText, const std::string& oldText ) : m_position( position ), m_oldText( oldText ), m_newText( newText ) {}
+
+ operator bool() const {
+ return m_oldText.length() != 0 || m_newText.length() != 0;
+ }
+ template<class Archive>
+ void serialize( Archive& arch, const uint ) {
+ arch & m_position & m_oldText & m_newText;
+ }
+};
+
+DYNAMICTEXT_EXPORT std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs );
+
+class DYNAMICTEXT_EXPORT Replacement : public WeakShared {
+ public:
+
+ Replacement( const VectorTimestamp& state, const SimpleReplacement& repl ) : m_state( state ), m_replacement( repl ), m_enabled(true) {}
+ Replacement() : m_enabled(true) {}
+
+ ///Returns a map that simulates applying the replacement. of( x -> y ) with x pre-state of this state, and y state of this.
+ OffsetMap offset( const OffsetMap& ofs = OffsetMap() );
+
+ ReplacementPointer next() const;
+ ReplacementPointer prev() const;
+
+ bool enabled() const;
+
+ ///These only compare the primary stamp
+ bool operator < ( const Replacement& rhs ) const throw(DynamicTextError);
+ bool operator <= ( const Replacement& rhs ) const throw(DynamicTextError);
+
+ uint primaryIndex() const;
+ Timestamp primaryStamp() const;
+
+ const VectorTimestamp& vectorStamp() const;
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint ) {
+ arch & m_state & m_replacement & m_next & m_prev & m_enabled;
+ }
+
+ const SimpleReplacement& replacement() const {
+ return m_replacement;
+ }
+
+ ///This must only be changed in an unapplied state. Else it will lead to corruption of the document.
+ void setEnabled( bool e );
+
+ private:
+ void setNext( ReplacementPointer next );
+ void setPrev( ReplacementPointer prev );
+
+ template<class TextType>
+ bool apply( TextType& text, const OffsetMap& offset, OffsetMap& staticOffset );
+ template<class TextType>
+ bool unApply( TextType& text, const OffsetMap& offset, OffsetMap& staticOffset );
+
+#ifdef USE_LINKS
+ ///Checks whether "link" should be put into the "links"-map. If it should
+ void updateLink( uint index, ReplacementPointer link );
+#endif
+
+ friend class DynamicText;
+ VectorTimestamp m_state; ///Each Replacement has a unique primary stamp, m_next has the same plus 1, m_prev the same minus one.
+
+ SimpleReplacement m_replacement;
+
+ ///One is weak one is not, so a chain of replacements cannot keep itself alive. Once the first is lost, all are lost.
+ ReplacementPointer m_next;
+ WeakReplacementPointer m_prev;
+
+#ifdef USELINKS
+ std::vector<WeakReplacementPointer> m_links; ///This maps the index-numbers of other Collaborators to their first replacement that uses the timestamp of this Replacement.
+#endif
+
+ bool m_enabled;
+};
+
+struct DYNAMICTEXT_EXPORT ReplacementChain {
+ ReplacementPointer first, last;
+ template<class Archive>
+ void serialize( Archive& arch, const uint ) {
+ arch & first & last;
+ }
+};
+
+struct DYNAMICTEXT_EXPORT ReplacementId {
+ uint primaryIndex;
+ Timestamp stamp;
+ ReplacementId( uint i = 0, Timestamp st = 0 ) : primaryIndex( i ), stamp( st ) {}
+ ReplacementId( ReplacementPointer p ) : primaryIndex( p->primaryIndex() ), stamp( p->primaryStamp() ) {}
+ bool operator < ( const ReplacementId& rhs ) const {
+ return primaryIndex < rhs.primaryIndex || ( primaryIndex == rhs.primaryIndex && stamp < rhs.stamp );
+ }
+ template<class Archive>
+ void serialize( Archive& arch, const uint version ) {
+ arch & primaryIndex & stamp;
+ }
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp (revision 1522570)
@@ -0,0 +1,929 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#define NOCATCH
+
+#include "dynamictext.h"
+#include "../network/serialization.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/export.hpp>
+#include <ostream>
+#include "verify.h"
+
+#ifndef NOCATCH
+typedef DynamicTextError CatchedDynamicTextError;
+#else
+typedef DynamicTextErrorDummy CatchedDynamicTextError;
+#endif
+
+std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs ) {
+ o << "( at " << rhs.m_position << ": '" << rhs.m_oldText << "' -> '" << rhs.m_newText << "' )";
+ return o;
+}
+
+CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, WeakReplacementPointer, 0, value )
+CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, VectorTimestamp, 0, value->vectorStamp() )
+CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, ReplacementId, 0, ReplacementId( value->primaryIndex(), value->primaryStamp() ) )
+
+namespace __gnu_cxx {
+template <>
+struct hash<ReplacementId> {
+ size_t operator() ( const ReplacementId& x ) {
+ return x.primaryIndex * 17 + x.stamp;
+ }
+};
+}
+
+DynamicTextError::DynamicTextError( const String& fun, int l, const String& f, const String& exp, const String& realExp ) : function( fun ), line( l ), file( f ), expression( exp ), realExpression( realExp ) {
+ cout << what() << endl;
+}
+String DynamicTextError::what() const {
+ std::ostringstream os;
+ os << "DynamicTextError in " << function << ", " << file << ":" << line;
+ if ( !expression.empty() )
+ os << ", expression \"" << expression << "\" failed";
+ if ( !realExpression.empty() )
+ os << ", values: " << realExpression;
+ return os.str();
+}
+
+OffsetMap Replacement::offset( const OffsetMap& ofs ) {
+ return OffsetMap( ofs( m_replacement.m_position ), int( m_replacement.m_newText.length() ) - int( m_replacement.m_oldText.length() ) );
+}
+
+void Replacement::setEnabled( bool e ) {
+ m_enabled = e;
+}
+
+
+template <class TextType>
+bool Replacement::apply( TextType& text, const OffsetMap& outerOffset, OffsetMap& staticOffset ) {
+ if ( m_enabled ) {
+ std::cout << "applying replacement " << replacement() << "\noffset: " << outerOffset.print() << "\nstaticOffset: " << staticOffset.print() << endl;
+ int pos = outerOffset( staticOffset( m_replacement.m_position ) );
+ DYN_VERIFY_SMALLERSAME( 0, pos );
+ DYN_VERIFY_SMALLERSAME( (int)pos, (int)text.length() );
+ DYN_VERIFY_SAME( text.substr( pos, m_replacement.m_oldText.length() ), m_replacement.m_oldText );
+
+ text.replace( pos, m_replacement.m_oldText.length(), m_replacement.m_newText );
+ } else {
+ staticOffset %= ~offset( outerOffset );
+ }
+
+ return true;
+}
+
+template <class TextType>
+bool Replacement::unApply( TextType& text, const OffsetMap& outerOffset, OffsetMap& staticOffset ) {
+ if ( m_enabled ) {
+ int pos = outerOffset( staticOffset( m_replacement.m_position ) );
+ DYN_VERIFY_SMALLERSAME( 0, pos );
+ DYN_VERIFY_SMALLERSAME( (int)pos, (int)text.length() );
+ DYN_VERIFY_SAME( text.substr( pos, m_replacement.m_newText.length() ), m_replacement.m_newText );
+
+ text.replace( pos, m_replacement.m_newText.length(), m_replacement.m_oldText );
+ } else {
+ staticOffset %= offset( outerOffset );
+ }
+
+ return true;
+}
+
+void Replacement::setNext( ReplacementPointer next ) {
+ m_next = next;
+ /* if ( m_next ) {
+ m_next->m_prev = next;
+ DYN_VERIFY( !next->m_next );
+ next->m_next = m_next;
+ }
+ m_next = next;
+ m_next->m_prev = this;*/
+}
+
+void Replacement::setPrev( ReplacementPointer prev ) {
+ m_prev = prev;
+ /* if ( m_prev ) {
+ m_prev->m_next = prev;
+ }
+ m_prev = prev;
+ m_prev->m_next = this;*/
+}
+
+bool Replacement::operator < ( const Replacement& rhs ) const throw( DynamicTextError ) {
+ DYN_VERIFY_SAME( rhs.primaryIndex(), primaryIndex() );
+ return primaryStamp() < rhs.primaryStamp();
+}
+
+bool Replacement::operator <= ( const Replacement& rhs ) const throw( DynamicTextError ) {
+ DYN_VERIFY_SAME( rhs.primaryIndex(), primaryIndex() );
+ return primaryStamp() <= rhs.primaryStamp();
+}
+
+uint Replacement::primaryIndex() const {
+ return m_state.primaryIndex();
+}
+
+const VectorTimestamp& Replacement::vectorStamp() const {
+ return m_state;
+}
+
+Timestamp Replacement::primaryStamp() const {
+ return m_state.primaryStamp();
+}
+
+ReplacementPointer Replacement::next() const {
+ return m_next;
+}
+
+ReplacementPointer Replacement::prev() const {
+ return m_prev;
+}
+
+bool Replacement::enabled() const {
+ return m_enabled;
+}
+
+#ifdef USE_LINKS
+void Replacement::updateLink( uint index, ReplacementPointer link ) {
+ if ( m_links.size() <= index )
+ m_links.resize( index + 1 );
+ if ( !m_links[ index ] || m_links[ index ] ->primaryStamp() > link->primaryStamp() )
+ m_links[ index ] = link;
+}
+#endif
+
+const DynamicText::Text& DynamicText::text() const {
+ return m_text;
+}
+
+const String& DynamicText::initialText() const {
+ return m_initialText;
+}
+
+bool DynamicText::insert( const VectorTimestamp& stamp, const SimpleReplacement& replacement ) {
+ DYN_VERIFY( !m_allReplacements.values( stamp ) ); ///Make sure a same stamp has not been inserted already
+ DYN_VERIFY( !stamp.isZero() );
+
+ VectorTimestamp currentState = m_state;
+ VectorTimestamp s = stamp;
+ s.decrease();
+
+ if ( s.size() > m_state.size() ) {
+ m_state.resize( s.size() );
+ m_unApplied.resize( s.size() );
+ m_applied.resize( s.size() );
+ }
+
+ {
+ ///Make sure that all wished pre-stamps are available
+ for ( uint a = 0; a < stamp.size(); a++ ) {
+ if ( stamp[ a ] != 0 ) {
+ Timestamp max = highestStamp( a );
+ if ( a == stamp.primaryIndex() ) {
+ DYN_VERIFY_SAME( s[ a ], max ); ///Make sure no higher entries exist
+ } else {
+ DYN_VERIFY_SMALLERSAME( s[ a ], max ); ///Make sure that no non-existent states are referenced
+ }
+
+ }
+ }
+ }
+
+ try {
+ DYN_VERIFY( changeStateInternal( s ) );
+
+ insertInternal( stamp.primaryIndex(), replacement );
+
+ DYN_VERIFY( changeStateInternal( currentState ) );
+ } catch ( const CatchedDynamicTextError & err ) {
+ if ( m_state != currentState )
+ notifyStateChanged();
+ throw;
+ }
+
+ return true;
+}
+
+ReplacementPointer DynamicText::first( uint index ) const {
+ if ( m_applied.size() > index && m_applied[ index ].first )
+ return m_applied[ index ].first;
+
+ if ( m_unApplied.size() > index && m_unApplied[ index ].first )
+ return m_unApplied[ index ].first;
+
+ return 0;
+}
+
+ReplacementPointer DynamicText::firstUnapplied( uint index ) const {
+ if ( m_unApplied.size() > index && m_unApplied[ index ].first )
+ return m_unApplied[ index ].first;
+
+ return 0;
+}
+
+ReplacementPointer DynamicText::last( uint index ) const {
+ if ( m_unApplied.size() > index && m_unApplied[ index ].last )
+ return m_unApplied[ index ].last;
+
+ if ( m_applied.size() > index && m_applied[ index ].last )
+ return m_applied[ index ].last;
+ return 0;
+}
+
+ReplacementPointer DynamicText::lastApplied( uint index ) const {
+ if ( m_applied.size() > index && m_applied[ index ].last )
+ return m_applied[ index ].last;
+ return 0;
+}
+
+Timestamp DynamicText::highestStamp( uint a ) const {
+ Timestamp max = 0;
+
+ if ( m_unApplied.size() > a && m_unApplied[ a ].last )
+ max = m_unApplied[ a ].last->primaryStamp();
+ else if ( m_applied.size() > a && m_applied[ a ].last )
+ max = m_applied[ a ].last->primaryStamp();
+
+ if ( m_initialState[ a ] > max )
+ max = m_initialState[ a ];
+
+ return max;
+}
+
+VectorTimestamp DynamicText::insert( uint index, const SimpleReplacement& replacement ) {
+ VectorTimestamp state = m_state;
+ VectorTimestamp ret;
+ try {
+ ret = insertInternal( index, replacement );
+ } catch ( const CatchedDynamicTextError & err ) {
+ if ( state != m_state )
+ notifyStateChanged();
+ throw;
+ }
+
+ if ( state != m_state )
+ notifyStateChanged();
+ return ret;
+}
+
+VectorTimestamp DynamicText::insertInternal( uint index, const SimpleReplacement& replacement ) {
+ VectorTimestamp stamp( index, m_state );
+ DYN_VERIFY( !m_allReplacements.values( stamp ) ); ///Make sure a same stamp has not been inserted already
+ DYN_VERIFY( !stamp.isZero() );
+
+ VectorTimestamp s = stamp;
+ s.decrease();
+
+ DYN_VERIFY_SAME( s, m_state );
+
+ if ( stamp.size() > m_state.size() || stamp.size() > m_unApplied.size() ) {
+ m_state.resize( stamp.size() );
+ m_unApplied.resize( stamp.size() );
+ m_applied.resize( stamp.size() );
+ }
+
+ DYN_VERIFY_SAME( m_unApplied[ index ].first, 0 /*Make sure there isn't already a replacement with that primary index*/ );
+
+ ReplacementPointer rep = new Replacement( stamp, replacement );
+
+ DYN_VERIFY( rep->apply( m_text, OffsetMap(), m_currentOffset ) );
+
+ if ( s.primaryStamp() != 0 ) {
+ ReplacementPointer prev = this->replacement( s.primaryIndex(), s.primaryStamp() );
+ if ( prev ) { ///Since the collaboration can start in any state, we don't have to insist on this
+ DYN_VERIFY_SAME( prev, m_applied[ s.primaryIndex() ].last );
+ prev->setNext( rep );
+ rep->setPrev( prev );
+ }
+ }
+ if ( m_applied.size() <= s.primaryIndex() )
+ m_applied.resize( s.primaryIndex() + 1 );
+ m_applied[ s.primaryIndex() ].last = rep;
+ if ( m_applied[ s.primaryIndex() ].first == 0 )
+ m_applied[ s.primaryIndex() ].first = rep;
+
+#ifdef USE_LINKS
+ ///Set the m_links-member of all previous-stamped items
+ for ( int a = 0; a < m_applied.size(); a++ ) {
+ if ( a != stamp.primaryIndex() ) {
+ if ( s[ a ] != 0 ) {
+ ReplacementPointer p = this->replacement( a, s[ a ] );
+ DYN_VERIFY( p );
+
+ p->updateLink( stamp.primaryIndex(), rep );
+ }
+ }
+ }
+#endif
+
+ m_state.setPrimaryIndex( stamp.primaryIndex() );
+ m_state.increase();
+
+
+ DYN_VERIFY_SAME( stamp, m_state );
+
+ hashReplacement( rep );
+
+ notifyInserted( rep );
+
+ return stamp;
+}
+
+void DynamicText::dump() const {}
+
+VectorTimestamp DynamicText::state() const {
+ return m_state;
+}
+
+VectorTimestamp DynamicText::initialState() const {
+ return m_initialState;
+}
+
+struct SafetyCounter {
+ uint m_cnt;
+ uint m_maxCnt;
+public:
+
+ SafetyCounter( uint max = 10000 ) : m_cnt( 0 ), m_maxCnt( max ) {}
+
+ operator bool() {
+ ++m_cnt;
+ return m_cnt < m_maxCnt;
+ }
+};
+
+VectorTimestamp DynamicText::tailState() const {
+ VectorTimestamp target( m_state );
+ for ( uint a = 0; a < m_unApplied.size(); a++ ) {
+ if ( m_unApplied[ a ].last )
+ target.maximize( m_unApplied[ a ].last->vectorStamp() );
+ }
+
+ return target;
+}
+
+///Changes the state to the newest one available
+bool DynamicText::toTail() {
+ VectorTimestamp target( m_state );
+ for ( uint a = 0; a < m_unApplied.size(); a++ ) {
+ if ( m_unApplied[ a ].last )
+ target.maximize( m_unApplied[ a ].last->vectorStamp() );
+ }
+
+ if ( !target.isZero() )
+ changeStateInternal( target );
+ return true;
+}
+
+OffsetMap DynamicText::offset( VectorTimestamp from, VectorTimestamp to, int position ) {
+ if ( from == to )
+ return OffsetMap();
+
+ OffsetRequest request( from, to );
+
+// OffsetCache::iterator it = m_offsetCache.find( request );
+//
+// if ( it != m_offsetCache.end() ) {
+// return ( *it ).second;
+// }
+
+ uint sz = m_applied.size();
+
+ DYN_VERIFY_SMALLERSAME( to.size(), sz );
+ DYN_VERIFY_SMALLERSAME( from.size(), sz );
+
+ std::vector<ReplacementPointer> chains( sz );
+ std::vector<ReplacementPointer> next( sz ); ///Contains the next replacement into the direction from -> to
+ for ( uint a = 0; a < sz; a++ ) {
+ chains[ a ] = replacement( a, from[ a ] );
+ if ( chains[ a ] ) {
+ DYN_VERIFY_SAME( chains[ a ] ->primaryStamp(), from[ a ] );
+ }
+ if ( to[ a ] < from[ a ] )
+ next[ a ] = replacement( a, from[ a ] - 1 );
+ else if ( to[ a ] > from[ a ] )
+ next[ a ] = replacement( a, from[ a ] + 1 );
+ }
+
+ //VectorTimestamp currentState = from;
+
+ SafetyCounter s( 10000 );
+
+ bool waited = false;
+ bool first = true;
+
+ while ( waited || first ) {
+ DYN_VERIFY( s );
+ first = false;
+
+ bool force = false;
+ if ( waited ) { ///If there is an inheritance-chain, break it by just applying the first one.
+ force = true;
+ waited = false;
+ }
+
+ for ( uint a = 0; a < chains.size(); a++ ) {
+ if ( from[ a ] != to[ a ] ) {
+ bool unapply = from[ a ] > to[ a ];
+ if ( !force ) {
+ ///Find out if there's another one that can be unapplied, and that should be unapplied before this one. If there is one, wait.
+ bool wait = false;
+ for ( uint b = 0; b < chains.size(); b++ ) {
+ if ( b == a )
+ continue;
+
+ if ( !chains[ b ] )
+ continue;
+
+ const VectorTimestamp& s2( chains[ b ] ->vectorStamp() );
+ if ( from[ b ] >= s2[ b ] && s2[ b ] > to[ b ] ) {
+ DYN_VERIFY( chains[ a ] );
+ ///The other replacement has to be unapplied
+ if ( unapply ) {
+ ///Should the replacement b be unapplied before a is unapplied?
+ if ( chains[ a ] ->vectorStamp() [ b ] < s2[ b ] || s2[ a ] >= from[ a ] ) {
+ ///a expects b not to be applied || b expects a to be applied
+ wait = true;
+ break;
+ }
+ } else {
+ ///Should the replacement b be unapplied before a is applied?
+ DYN_VERIFY( next[ a ] );
+ if ( next[ a ] ->vectorStamp() [ b ] < s2[ b ] || s2[ a ] < from[ a ] + 1 ) {
+ ///next a expects b not to be applied || b expects next a not to be applied
+ wait = true;
+ break;
+ }
+ }
+ }
+
+ if ( from[ b ] < s2[ b ] && s2[ b ] <= to[ b ] ) {
+ DYN_VERIFY( next[ b ] );
+
+ if ( unapply ) {
+ ///Should the replacement b be applied before a is unapplied?
+ if ( chains[ a ] ->vectorStamp() [ b ] >= next[ b ] ->primaryStamp() || next[ b ] ->vectorStamp() [ a ] >= from[ a ] ) {
+ ///a expects next b to be applied || next b expects a to be applied
+ wait = true;
+ break;
+ }
+ } else {
+ ///Should the replacement b be applied before a is applied?
+ DYN_VERIFY( next[ a ] );
+ if ( next[ a ] ->vectorStamp() [ b ] > next[ b ] ->primaryStamp() || next[ b ] ->vectorStamp() [ a ] < from[ a ] + 1 ) {
+ ///next a expects next b to be applied || next b expects next a not to be applied
+ wait = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if ( wait ) {
+ waited = true;
+ continue;
+ }
+ } else {
+ force = false;
+ }
+
+ VectorTimestamp preNextStamp;
+ VectorTimestamp nextStamp;
+ VectorTimestamp intermediate;
+ OffsetMap ret;
+
+ if ( to[ a ] < from[ a ] ) {
+ VectorTimestamp n = from;
+ n.setPrimaryIndex( a );
+ n.decrease(); ///n = the intermediate state we are stepping to
+
+ VectorTimestamp prev = chains[a]->vectorStamp();
+ prev.decrease(); ///prev = the state the replacement in chains[a] was applied to
+
+ ///The position-checking needs to be done to avoid endless recursion
+ OffsetMap innerOffset = ~offset( prev, n, chains[a]->replacement().m_position );
+ ret = offset( n, to );
+ if( position != INVALID_POSITION && position < innerOffset( chains[a]->replacement().m_position ) )
+ return ret;
+ ret = chains[a]->offset( innerOffset ) % ret;
+ } else {
+ VectorTimestamp n = from;
+ n.setPrimaryIndex( a );
+ n.increase();
+ VectorTimestamp prev = next[a]->vectorStamp();
+ prev.decrease();
+ OffsetMap innerOffset = ~offset( prev, from, next[a]->replacement().m_position );
+ ret = offset( n, to );
+ if( position != INVALID_POSITION && position < innerOffset( next[a]->replacement().m_position ) )
+ return ret;
+ ret = ~next[a]->offset( innerOffset ) % ret;
+ }
+
+ /// Now: ret = offset( preNextStamp, nextStamp )
+
+ /**chains[a]->offset() = of( v( chains[a].state ) -> chains[a].state )
+ * with v(chains[a].state) = pre-state of chains[a].state (stamp at position primaryStamp decrease by one)
+ *
+ * Simple case: of( from -> to )(x) = of( next -> to )( ( of( from -> next )(x) )
+ *
+ * Problem: What if the current state does not exactly match the state created by the item to remove?
+ * of( chains[a].prevStamp -> chains[a].stamp ) = chains[a]->offset()
+ * of[ from -> to ](x) = of[chains[a].stamp -> to ]( of[ chains[a].prevStamp -> chains[a].stamp ] ( of[ from -> chains[a].prevStamp ](x) ) )
+ **/
+
+ m_offsetCache.insert( OffsetCache::value_type( request, ret ) );
+ return ret;
+ }
+ }
+ }
+
+ DYN_VERIFY( 0 );
+}
+
+bool DynamicText::rewindInternal( const VectorTimestamp& state ) {
+ SafetyCounter s( 10000 );
+
+ bool applied = true;
+ bool waited = false;
+
+ while ( applied || waited ) {
+ DYN_VERIFY( s );
+
+ bool force = false;
+ if ( waited && !applied ) { ///If there is an inheritance-chain, break it by just applying the first one.
+ force = true;
+ waited = false;
+ }
+ applied = false;
+ waited = false;
+
+
+ for ( uint a = 0; a < m_applied.size(); a++ ) {
+ if ( state[ a ] > m_state[ a ] )
+ continue;
+ ReplacementChain& r( m_applied[ a ] );
+ if ( !r.first && !r.last )
+ continue;
+ DYN_VERIFY( r.last );
+ const VectorTimestamp& s( r.last->vectorStamp() );
+
+ if ( s.primaryStamp() > state[ s.primaryIndex() ] ) {
+
+ if ( !force ) {
+ ///Find out if there's another one that can be unapplied, and that should be unapplied before this one. If there is one, wait.
+ bool wait = false;
+ for ( uint b = 0; b < m_applied.size(); b++ ) {
+ if ( b == a )
+ continue;
+
+ ReplacementChain& r2( m_applied[ b ] );
+ if ( !r2.first && !r2.last )
+ continue;
+ const VectorTimestamp& s2( r2.last->vectorStamp() );
+
+ if ( s2.primaryStamp() > state[ s2.primaryIndex() ] && m_state[ s2.primaryIndex() ] >= s2.primaryStamp() ) {
+ ///The other replacement has to be unapplied
+ if ( s[ b ] < s2.primaryStamp() || s2[ a ] >= s.primaryStamp() ) {
+ ///The other replacement should be unapplied before this one
+ wait = true;
+ break;
+ }
+ }
+ }
+
+ if ( wait ) {
+ waited = true;
+ continue;
+ }
+ } else {
+ force = false;
+ }
+
+ //It can be unapplied now
+ /*VectorTimestamp prev( s );
+ prev.decrease();*/
+
+
+ VectorTimestamp prevCurrent = m_state;
+ prevCurrent.setPrimaryIndex( a );
+ DYN_VERIFY_NOTSAME( prevCurrent.primaryStamp(), 0 );
+
+ //prevCurrent.decrease();
+
+ VectorTimestamp prev( s );
+ //prev.decrease();
+ OffsetMap offset;
+ offset = ~this->offset( prev, prevCurrent, r.first->replacement().m_position - 1 ); ///@todo -1 or not?
+
+ DYN_VERIFY( r.last->unApply( m_text, offset, m_currentOffset ) );
+
+ m_state.setPrimaryIndex( s.primaryIndex() );
+ m_state.decrease();
+
+ applied = true;
+
+ if ( m_unApplied.size() <= a )
+ m_unApplied.resize( a + 1 );
+
+ if ( m_unApplied[ a ].first ) {
+ DYN_VERIFY_SAME( r.last, m_unApplied[ a ].first->prev() );
+ m_unApplied[ a ].first = r.last;
+ } else {
+ m_unApplied[ a ].first = m_unApplied[ a ].last = r.last;
+ }
+ if ( r.last->prev() ) {
+ r.last = r.last->prev();
+ } else {
+ r.first = r.last = 0;
+ }
+ }
+ }
+ }
+
+ DYN_VERIFY( m_state.smallerOrSame( state ) );
+
+ return true;
+}
+/*
+// ReplacementPointer DynamicText::findBound( const VectorTimestamp& stamp ) {
+// }
+
+OffsetMap DynamicText::backwardsOffset( const VectorTimestamp& to ) {
+DYN_VERIFY( to.smallerOrSame( m_state ) );
+DYN_VERIFY( m_allReplacements.iterator( to ) );
+
+bool applied = true;
+
+int sz = m_applied.size();
+
+DYN_VERIFY_SMALLERSAME( to.size(), sz );
+DYN_VERIFY_SMALLERSAME( m_state.size(), sz );
+//DYN_VERIFY( sz >= to.size() && sz >= m_state.size() );
+
+std::vector<ReplacementPointer> chains( sz );
+for ( int a = 0; a < sz; a++ ) {
+ chains[ a ] = m_applied[ a ].last;
+ if ( chains[ a ] )
+ DYN_VERIFY( chains[ a ] ->primaryIndex() == a );
+}
+
+OffsetMap offset = m_currentOffset;
+VectorTimestamp currentState = m_state;
+
+SafetyCounter s( 10000 );
+
+while ( applied ) {
+ DYN_VERIFY( s );
+ applied = false;
+ for ( int a = 0; a < sz; a++ ) {
+ if ( !chains[ a ] )
+ continue;
+ DYN_VERIFY ( to[ a ] <= currentState[ a ] );
+ DYN_VERIFY( chains[ a ] );
+
+ VectorTimestamp s = chains[ a ] ->vectorStamp();
+ //s.decrease();
+
+ if ( !( currentState == to ) && s == currentState ) {
+ offset = offset % ( ~chains[ a ] ->offset() );
+ applied = true;
+ chains[ a ] = chains[ a ] ->prev();
+ s.decrease();
+ currentState = s;
+ }
+ }
+}
+
+DYN_VERIFY( currentState == to );
+return offset;
+}*/
+
+bool DynamicText::advanceInternal( const VectorTimestamp& state ) {
+ DYN_VERIFY( m_state.smallerOrSame( state ) );
+ if ( state.isZero() )
+ return true;
+
+ uint sz = m_applied.size();
+ /*
+ DYN_VERIFY_SMALLERSAME( sz, state.size() );
+ DYN_VERIFY_SMALLERSAME( sz, m_state.size() );*/
+
+ if ( m_unApplied.size() < m_applied.size() )
+ m_unApplied.resize( m_applied.size() );
+
+ bool applied = true;
+ bool waited = false;
+
+ SafetyCounter s( 10000 );
+
+ while ( applied || waited ) {
+ DYN_VERIFY( s );
+
+ bool force = false;
+ if ( waited && !applied ) { ///If there is an inheritance-chain, break it by just applying the first one.
+ force = true;
+ waited = false;
+ }
+ applied = false;
+ waited = false;
+
+ //Apply all replacements that can be applied to the current state, and need to be applied.
+ for ( uint a = 0; a < sz; a++ ) {
+ DYN_VERIFY_SMALLERSAME ( m_state[ a ], state[ a ] );
+ ReplacementChain& r( m_unApplied[ a ] );
+ if ( !r.first && !r.last )
+ continue;
+ DYN_VERIFY( r.first );
+ const VectorTimestamp& s( r.first->vectorStamp() );
+
+ if ( s.primaryStamp() <= state[ s.primaryIndex() ] ) {
+
+ if ( !force ) {
+ ///Find out if there's another one that can be applied, and that should be applied before this one. If there is one, wait.
+ bool wait = false;
+ for ( uint b = 0; b < sz; b++ ) {
+ if ( b == a )
+ continue;
+
+ ReplacementChain& r2( m_unApplied[ b ] );
+ if ( !r2.first && !r2.last )
+ continue;
+ const VectorTimestamp& s2( r2.first->vectorStamp() );
+
+ if ( s2.primaryStamp() <= state[ s2.primaryIndex() ] && m_state[ s2.primaryIndex() ] < s2.primaryStamp() ) {
+ ///The other replacement has to be applied
+ if ( s[ b ] >= s2.primaryStamp() || s2[ a ] < s.primaryStamp() ) {
+ ///The other replacement should be applied before this one
+ wait = true;
+ break;
+ }
+ }
+ }
+
+ if ( wait ) {
+ waited = true;
+ continue;
+ }
+ } else {
+ force = false;
+ }
+
+ //It can be applied now
+ VectorTimestamp prev( s );
+ prev.decrease();
+ OffsetMap offset;
+ offset = ~this->offset( prev, m_state, r.first->replacement().m_position-1 );
+
+ DYN_VERIFY( r.first->apply( m_text, offset, m_currentOffset ) );
+
+ m_state.setPrimaryIndex( s.primaryIndex() );
+ m_state.increase();
+
+ applied = true;
+ if ( m_applied[ a ].last ) {
+ DYN_VERIFY_SAME( m_applied[ a ].last, r.first->prev() );
+ m_applied[ a ].last = r.first;
+ } else {
+ m_applied[ a ].last = m_applied[ a ].first = r.first;
+ }
+ if ( r.first->next() ) {
+ r.first = r.first->next();
+ } else {
+ r.last = r.first = 0;
+ }
+ }
+ }
+ }
+
+ DYN_VERIFY_SAME( m_state, state );
+ return m_state == state;
+}
+
+bool DynamicText::rewind( const VectorTimestamp& state ) {
+ VectorTimestamp v = m_state;
+ try {
+ rewindInternal( state );
+ } catch ( const CatchedDynamicTextError & err ) {
+ if ( v != m_state )
+ notifyStateChanged();
+ throw;
+ }
+
+
+ if ( v != m_state )
+ notifyStateChanged();
+ return true;
+}
+
+///The given state must be bigger/same than the current state in every stamp
+bool DynamicText::advance( const VectorTimestamp& state ) {
+ VectorTimestamp v = m_state;
+ try {
+ advanceInternal( state );
+ } catch ( const CatchedDynamicTextError & err ) {
+
+ if ( v != m_state )
+ notifyStateChanged();
+ throw;
+ }
+
+ if ( v != m_state )
+ notifyStateChanged();
+ return true;
+}
+
+bool DynamicText::changeState( const VectorTimestamp& state, bool force ) {
+ VectorTimestamp v = m_state;
+ bool ret;
+ try {
+ ret = changeStateInternal( state, force );
+ } catch ( const CatchedDynamicTextError & err ) {
+ if ( v != m_state )
+ notifyStateChanged();
+ throw;
+ }
+
+ if ( v != m_state )
+ notifyStateChanged();
+ return ret;
+}
+
+bool DynamicText::changeStateInternal( const VectorTimestamp& state, bool /*force*/ ) {
+ if ( state.isZero() )
+ return toTail();
+ if ( state == m_state )
+ return true;
+ ///First some verification
+
+ for ( uint a = 0; a < m_applied.size(); a++ ) {
+ if ( m_applied[ a ].last == 0 )
+ continue;
+ DYN_VERIFY_SAME( m_applied[ a ].last->primaryIndex(), a );
+ DYN_VERIFY_SAME( m_applied[ a ].last->primaryStamp(), m_state[ a ] );
+ }
+
+ DYN_VERIFY( rewindInternal( state ) );
+
+ DYN_VERIFY( advanceInternal( state ) );
+
+
+ return true;
+}
+
+void DynamicText::cut() {
+ for ( uint a = 0; a < m_applied.size(); a++ ) {
+ if ( m_applied[ a ].last )
+ m_applied[ a ].last->setNext( 0 );
+ }
+ for ( uint a = 0; a < m_unApplied.size(); a++ ) {
+ m_unApplied[ a ].first = 0;
+ m_unApplied[ a ].last = 0;
+ }
+}
+
+DynamicText::DynamicText( const VectorTimestamp& initialState, const String& initialText ) : m_text( initialText ), m_initialText( initialText ), m_state( initialState ), m_initialState( initialState ) {
+ m_dummy = new Replacement();
+}
+
+ReplacementPointer DynamicText::replacement( uint primaryIndex, Timestamp stamp ) {
+ ReplacementSet::Iterator it = m_allReplacements.values( ReplacementId( primaryIndex, stamp ) );
+ if ( it && *it ) {
+ return ( *it ).get();
+ } else {
+ return 0;
+ }
+}
+
+void DynamicText::hashReplacement( const ReplacementPointer& rep ) {
+ DYN_VERIFY( !m_allReplacements.find( rep ) );
+ m_allReplacements.insert( rep );
+}
+
+void DynamicText::unHashReplacement( const ReplacementPointer& rep ) {
+ m_allReplacements.remove( rep );
+}
+
+void DynamicText::notifyInserted( const ReplacementPointer& /*rep*/ ) {}
+
+void DynamicText::notifyStateChanged() {}
+
+//BOOST_CLASS_EXPORT_GUID( DynamicText, "DynamicText" )
+
+template bool Replacement::unApply( DynamicText::Text& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
+template bool Replacement::apply( DynamicText::Text& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
+
+///For testing
+template bool Replacement::unApply( std::string& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
+template bool Replacement::apply( std::string& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h (revision 1522570)
@@ -0,0 +1,188 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SUMTREE_H
+#define SUMTREE_H
+
+#include <list>
+#include <vector>
+
+#include "../network/safesharedptr.h"
+#include "../network/weaksafesharedptr.h"
+
+#include "verify.h"
+#include "dynamictextexport.h"
+
+namespace SumTree {
+class Node;
+class EndIndexCompare;
+typedef SharedPtr<Node> NodePointer;
+typedef WeakSharedPtr<Node> WeakNodePointer;
+
+
+///A pair that contains an index and the sum of all values before that index
+struct DYNAMICTEXT_EXPORT IndexAndSum {
+ int index;
+ int sum;
+};
+
+///Everything may throw DynamicTextError. Every pointer to Nodes, except those from parent-node to slave-node, must be weak-pointers.(because the ref-count is important for ownership-stuff)
+class DYNAMICTEXT_EXPORT Node : public Shared {
+ typedef std::list<NodePointer> ListType;
+ public:
+ Node( bool isLeaf, Node* parent );
+
+ ///If this node is already owned by parent, returns this. Else creates a copy owned by parent.
+ inline Node* makeOwn( Node* parent );
+ Node* setParent( Node* parent );
+
+ ///Can be used to add/subtract a value from the sum(should only be directly called on end-items without children, and the index-range is only expanded, never shrinked.)
+ inline void update( const int sumDif, const int indexCountDif ) {
+ sum_ += sumDif;
+ indexCount_ += indexCountDif;
+
+ // DYN_VERIFY_SMALLER( sum_, 1000000 );
+ Node* parent = parent_/*.get()*/;
+ if( parent && (sumDif != 0 || indexCountDif != 0 ) )
+ parent_->update( sumDif, indexCountDif );
+ }
+
+ void addNode( Node* node );
+
+ ///The sum is counted until that index, not including it.
+ int sum( int index ) const;
+
+ int index( int sum ) const;
+
+ int sum() const {
+ return sum_;
+ }
+ int indexCount() const {
+ return indexCount_;
+ }
+
+ void indexAndSum( int sum, IndexAndSum& targ ) const;
+
+ std::string dump( int offset,int depth ) const;
+
+ template<class Container>
+ void fillValues( Container& c ) {
+ if( isLeaf_ ) {
+ c.push_back( sum_ );
+ }else {
+ for( ListType::iterator it = nodes_.begin(); it != nodes_.end(); ++it )
+ (*it)->fillValues( c );
+ }
+ }
+
+ bool hasIndex( int index ) const;
+
+ int indexValue( int index ) const;
+
+ int setIndexValue( int index, int value );
+
+ int changeIndexValue( int index, int diff );
+
+ void insertIndex( int index, int value );
+
+ void insertRange( int position, int size, int value );
+
+ int removeIndex( int index );
+
+ bool isLeaf() const {
+ return isLeaf_;
+ }
+
+ bool isRange() const {
+ return !isLeaf_ && nodeCount_ == 0 && indexCount_ != 0;
+ }
+
+ void updateStructure();
+
+ private:
+ void splitRange( int splitPosition, Node* insertNode );
+
+ void removeChild( Node* n );
+
+ friend class EndIndexCompare;
+ /*WeakNodePointer*/Node* parent_; ///if this is zero, the node is available for taking, else it must be copied.
+ ListType nodes_;
+ int nodeCount_; ///Cache for nodes_.size()
+ int sum_; ///Sum over all sub-elements
+ int indexCount_; ///The count of indices this node and all subnodes cover
+ bool isLeaf_;
+};
+
+///This object can be copied around and changed at will, no other instances of it will be affected, while still staying efficient(Because of implicit node-sharing)
+class DYNAMICTEXT_EXPORT Map : public WeakShared {
+ public:
+ typedef std::vector< int > SumVector; ///Pairs of (index, sum-value). Muss dicht sein.
+ ///preferredOrder says how many slave-nodes one node should ideally have. Higher values -> faster manipulation, lower values -> faster lookup
+ Map( const SumVector& summands = SumVector() );
+ Map( const Map& rhs );
+ ~Map();
+
+ Map& operator = ( const Map& rhs );
+
+ ///Returns the sum over all indices
+ int sum() const;
+ ///Returns the values of all indices up to(not including) index summed together
+ int sum( int index ) const;
+
+ ///Returns the index that the given sum falls into. Warning: indices that have a value of zero cannot be mapped back with this function.
+ int index( int sum ) const;
+
+ void indexAndSum( int sum, IndexAndSum& targ ) const;
+
+ bool hasIndex( int index ) const;
+ // Map rebuild();
+
+ ///Complexity: O(1)
+ int indexCount()const ;
+
+ ///Returns the value of that specified index
+ int indexValue( int index ) const;
+
+ ///Returns the previous value of that index. The value must not be zero, because that would not allow consistent mapping back(exception is thrown)
+ int setIndexValue( int index, int value );
+
+ ///Returns the new value of that index. If the value becomes zero, the index cannot be mapped back through index(..) anymore.
+ int changeIndexValue( int index, int diff );
+
+ ///Inserts an index at position "index" with the value "value"
+ void insertIndex( int index, int value = 0 ) ;
+
+ /**Efficiently inserts a range of indices with
+ * same value(may be zero) into the tree.
+ * @param position Starting-position of the range
+ * @param size Count of indices the range will occupy
+ * @param value The value each index of the range will get(the whole range will have the sum size*range)
+ * $
+ */
+ void insertRange( int position, int size, int eachValue = 0 );
+
+ ///Removes one index at position index, returns the personal sum that index had associated
+ int removeIndex( int index );
+
+ std::string dump() const;
+
+ private:
+ int build( const SumVector::const_iterator& begin, const SumVector::const_iterator& end, Node* parent );
+ NodePointer tree_;
+};
+
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h (revision 1522570)
@@ -0,0 +1,56 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef DYNAMICTEXT_VERIFY_H
+#define DYNAMICTEXT_VERIFY_H
+
+#include <string>
+#include <sstream>
+#include "dynamictextexport.h"
+
+struct DynamicTextErrorDummy {
+ std::string what() const {
+ return "";
+ }
+};
+
+struct DYNAMICTEXT_EXPORT DynamicTextError {
+ std::string function;
+ int line;
+ std::string file;
+ std::string expression;
+ std::string realExpression;
+ DynamicTextError( const std::string& fun, int l = 0, const std::string& f = "", const std::string& exp = "", const std::string& realExp = "" );
+ std::string what() const;
+};
+
+#define DYN_VERIFY( x ) if( x ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #x ); }
+#define DYN_VERIFY_SAME( a, b ) if( a == b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, "\"" + toText( a ) + std::string( "\" == \"" ) + toText( b ) + "\"" ); }
+#define DYN_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, "\"" + toText( a ) + std::string( "\" < \"" ) + toText( b ) + "\"" ); }
+#define DYN_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, "\"" + toText( a ) + std::string( "\" <= \"" ) + toText( b ) + "\"" ); }
+#define DYN_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, "\"" + toText( a ) + std::string( "\" != \"" ) + toText( b ) + "\"" ); }
+
+
+
+#ifndef HAVE_TOTEXT
+#define HAVE_TOTEXT
+template <class Item>
+std::string toText( const Item& it ) {
+ ostringstream os;
+ os << it;
+ return os.str();
+}
+#endif
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h (revision 1522570)
@@ -0,0 +1,99 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef OFFSETUTILS_H
+#define OFFSETUTILS_H
+
+#include <map>
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/map.hpp>
+#include <string>
+#include <iosfwd>
+#include "dynamictextexport.h"
+
+typedef int OffsetPosition;
+
+using namespace std;
+
+///Can be thrown by OffsetMap.
+struct OffsetMapError {
+ enum Type {
+ Inconsistent
+ };
+ Type t;
+
+ OffsetMapError( Type type );
+
+ const char* asText() const;
+};
+
+///@todo there's a lot of room for optimizations in this.. but first make sure everything works correctly. Everything may throw DynamicTextError
+
+class DYNAMICTEXT_EXPORT OffsetMap {
+ public:
+ void clear();
+
+ OffsetMap( OffsetPosition position, int offset );
+
+ OffsetMap();
+
+ /**Returns true if the given map can be inserted without making the map inconsistent
+ * */
+ bool isCompatible( const OffsetMap& rhs ) const;
+
+ /**Insert the given offset-map into this one(while transforming it through this one).
+ * corresponds to the mathematical function-operator o (like g o f).
+ * Let the function for the current map be f(x), the inserted be g(x), and the resulting map be h(x).
+ * Then h(x) = f(g(x))
+ *
+ * This function may throw OffsetMapError if the insertion would make the map inconsistent.
+ *
+ * */
+ OffsetMap operator %( const OffsetMap& rhs ) const;
+
+ OffsetMap& operator %=( const OffsetMap& rhs );
+
+ /**Inverts the offset-map(like the mathematical inversion of a function)
+ * */
+ OffsetMap operator ~() const;
+
+ OffsetMap engInvert() const;
+
+ void printMap() const;
+
+ std::string print() const;
+
+ ///Applies the function defined by this offset-map to the given parameter
+ int operator () ( const OffsetPosition position ) const;
+
+ template <class Archive>
+ void serialize( Archive& arch, const OffsetPosition ) {
+ arch & m_offsets;
+ }
+ private:
+ typedef std::map<OffsetPosition, int> OffsetInternalMap;
+
+ ///Iterator may get deleted
+ void makeConsistent( OffsetInternalMap::iterator position );
+
+ int getOffset( OffsetPosition position ) const;
+
+ void addOffset( OffsetPosition position, int offset );
+ void mergeOffset( OffsetPosition position, int offset );
+
+ OffsetInternalMap m_offsets;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp (revision 1522570)
@@ -0,0 +1,250 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "offsetutils.h"
+#include <iostream>
+#include <sstream>
+#include "verify.h"
+
+OffsetMapError::OffsetMapError( Type type ) : t( type ) {}
+
+const char* OffsetMapError::asText() const {
+ switch ( t ) {
+ case Inconsistent:
+ return "the map is inconsistent";
+ default:
+ return "unknown";
+ }
+}
+
+void OffsetMap::clear() {
+ m_offsets.clear();
+}
+
+OffsetMap::OffsetMap( OffsetPosition position, int offset ) {
+ addOffset( position, offset );
+}
+
+OffsetMap::OffsetMap() {}
+
+/**Returns true if the given map can be inserted without making the map inconsistent
+ * */
+bool OffsetMap::isCompatible( const OffsetMap& rhs ) const {
+ OffsetMap rhsInv = ~rhs;
+
+ if ( m_offsets.empty() )
+ return true;
+
+ for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
+ OffsetPosition i = rhsInv( ( *it ).first );
+ if ( rhs( i ) != ( *it ).first )
+ return false;
+ }
+
+ for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it ) {
+ int endPos = ( *it ).first + ( *it ).second;
+ if ( endPos < 0 )
+ return false;
+
+ std::map< OffsetPosition, int >::const_iterator it2 = m_offsets.lower_bound( ( OffsetPosition ) endPos );
+
+ if ( it2 != m_offsets.begin() ) {
+ --it2;
+ if ( ( *it2 ).second + ( *it2 ).first > endPos )
+ return false;
+ }
+ }
+ return true;
+}
+
+OffsetMap OffsetMap::operator %( const OffsetMap& rhs ) const {
+ OffsetMap ret;
+ OffsetMap rhsInv = ~rhs;
+
+ for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
+ OffsetPosition i = rhsInv( ( *it ).first ); // - rhs.getOffset( ( *it ).first );
+ ret.m_offsets[ i ] = ( *it ).second;
+ }
+
+ for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it )
+ ret.addOffset( ( *it ).first, ( *it ).second );
+ return ret;
+}
+
+OffsetMap& OffsetMap::operator %=( const OffsetMap& rhs ) {
+ OffsetMap rhsInv = ~rhs;
+ std::map<OffsetPosition, int> oldOffsets;
+ oldOffsets.swap( m_offsets );
+
+ for ( std::map<OffsetPosition, int>::const_iterator it = oldOffsets.begin(); it != oldOffsets.end(); ++it ) {
+ OffsetPosition i = rhsInv( ( *it ).first );
+ DYN_VERIFY_SAME( rhs( i ), ( *it ).first );
+ m_offsets[ i ] = ( *it ).second;
+ }
+
+ for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it )
+ addOffset( ( *it ).first, ( *it ).second );
+ return *this;
+}
+
+/**Inverts the offset-map(like the mathematical inversion of a function)
+ * */
+OffsetMap OffsetMap::operator ~() const {
+ OffsetMap ret;
+ std::map<OffsetPosition, int>& newMap( ret.m_offsets );
+ for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
+ if( (*it).second > 0 ) {
+ for( int a = 1; a <= (*it).second; ++a ) {
+ int npos = ( *it ).first + a;
+ std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
+ if ( it2 == newMap.end() ) {
+ newMap[ npos ] = -1;
+ } else {
+ ( *it2 ).second -= 1;
+ }
+ }
+ } else {
+ for( int a = -1; a >= (*it).second; --a ) {
+ int npos = ( *it ).first + a;
+ std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
+ if ( it2 == newMap.end() ) {
+ newMap[ npos ] = -a;
+ } else {
+ ( *it2 ).second -= a;
+ }
+ }
+ }
+
+ /*int npos = ( *it ).first + ( *it ).second;
+ std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
+ if ( it2 == newMap.end() ) {
+ newMap[ npos ] = -( *it ).second;
+ } else {
+ ( *it2 ).second -= ( *it ).second;
+ }*/
+ }
+
+ //cout << "inverting. old map size: " << newMap.size() << " new map size: " << m_offsets.size() << endl;
+ return ret;
+}
+
+OffsetMap OffsetMap::engInvert() const {
+ OffsetMap ret;
+ std::map<OffsetPosition, int>& newMap( ret.m_offsets );
+ for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
+
+ int npos = ( *it ).first;
+ if( ( *it ).second < 0 )
+ --npos;
+ else if( ( *it ).second > 0 )
+ ++npos;
+
+ std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
+ if ( it2 == newMap.end() ) {
+ newMap[ npos ] = -( *it ).second;
+ } else {
+ ( *it2 ).second -= ( *it ).second;
+ }
+ }
+
+ //cout << "inverting. old map size: " << newMap.size() << " new map size: " << m_offsets.size() << endl;
+ return ret;
+}
+
+void OffsetMap::printMap() const {
+ cout << "offsets: " << print() << endl;
+}
+
+std::string OffsetMap::print() const {
+ ostringstream o;
+ for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it )
+ o << "(" << ( *it ).first << ": " << ( *it ).second << ") ";
+ return o.str();
+}
+
+int OffsetMap::getOffset( OffsetPosition position ) const {
+
+ std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin();
+
+ int ret = 0;
+ while ( it != m_offsets.end() && ( *it ).first <= position ) {
+ ret += ( *it ).second;
+ ++it;
+ }
+ return ret;
+}
+
+int OffsetMap::operator () ( const OffsetPosition position ) const {
+ return getOffset( position ) + position;
+}
+
+void OffsetMap::addOffset( OffsetPosition position, int offset ) {
+ /*if ( ( offset + int( position ) ) < 0 || offset == 0 )
+ return ;*/
+ //cout << "inserting offset " << offset << " at position " << position << endl;
+ OffsetInternalMap::iterator it = m_offsets.find( position );
+ if ( it == m_offsets.end() ) {
+ it = m_offsets.insert( OffsetInternalMap::value_type( position, offset ) ).first;
+ } else {
+ (*it).second += offset;
+ if ( (*it).second == 0 )
+ m_offsets.erase( it );
+ }
+}
+
+void OffsetMap::mergeOffset( OffsetPosition position, int offset ) {
+ OffsetInternalMap::iterator it = m_offsets.find( ( OffsetPosition ) position );
+ if( it != m_offsets.end() ) {
+ (*it).second += offset;
+ makeConsistent( it );
+ } else {
+ makeConsistent( m_offsets.insert( OffsetInternalMap::value_type( position, offset ) ).first );
+ }
+}
+
+void OffsetMap::makeConsistent( OffsetInternalMap::iterator position ) {
+ std::map< OffsetPosition, int >::iterator it = position;
+ bool forward = (*position).second > 0;
+
+ OffsetPosition until = (*position).first + (*position).second;
+
+ if( forward ) {
+ ///seek forwards and include all overlapped offets into this one
+ ++it;
+ while( it != m_offsets.end() && (*it).first <= until ) {
+ (*position).second += (*it).second;
+ m_offsets.erase( it++ );
+ }
+ } else {
+ ///seek backwards and include this one into any overlapped offset, deleting this one.
+
+ if( it != m_offsets.begin() ) {
+ --it;
+ while( (*it).first >= until ) {
+ (*it).second += (*position).second;
+ m_offsets.erase( position );
+ position = it;
+ if( it != m_offsets.begin() )
+ --it;
+ else
+ break;
+ }
+ }
+ }
+
+ if( (*position).second == 0 )
+ m_offsets.erase( position );
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h (revision 1522570)
@@ -0,0 +1,32 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef FLEXIBLETEXT_NOTIFIER
+#define FLEXIBLETEXT_NOTIFIER
+
+namespace SumTree {
+
+ ///Override this so you are able to register your class to be notified of changes in a FlexibleText
+ ///All of these functions are called by FlexibleText immediately BEFORE the replacement is done
+ ///Only one of those notifications is called, even though a replacement may internally be implemented by erasing and inserting.
+ ///These are allowed to throw DynamicTextError
+ template<class StringType>
+ class FlexibleTextNotifier {
+ public:
+ virtual void notifyFlexibleTextErase( int position, int length ) = 0;
+ virtual void notifyFlexibleTextInsert( int position, const StringType& text ) = 0;
+ virtual void notifyFlexibleTextReplace( int position, int length, const StringType& replacement ) = 0;
+ virtual ~FlexibleTextNotifier(){};
+ };
+}
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,3 @@
+add_subdirectory(dynamictext)
+add_subdirectory(libdiff2)
+add_subdirectory(network)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/Messages.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/Messages.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/Messages.sh (revision 1522570)
@@ -0,0 +1,4 @@
+#!/bin/sh
+$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
+$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevteamwork.pot
+rm -f rc.cpp
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui (revision 1522570)
@@ -0,0 +1,321 @@
+<ui version="4.0" >
+ <class>UserInfo</class>
+ <widget class="QWidget" name="UserInfo" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>419</width>
+ <height>202</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="2" column="0" >
+ <widget class="QFrame" name="frame" >
+ <property name="frameShape" >
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>1</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="menuButton" >
+ <property name="text" >
+ <string>Menu</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>121</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="historyButton" >
+ <property name="text" >
+ <string>History</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <widget class="QGroupBox" name="groupBox" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="font" >
+ <font>
+ <family>Sans Serif</family>
+ <pointsize>9</pointsize>
+ <weight>75</weight>
+ <italic>false</italic>
+ <bold>true</bold>
+ <underline>false</underline>
+ <strikeout>false</strikeout>
+ </font>
+ </property>
+ <property name="title" >
+ <string>Description</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QLabel" name="description" >
+ <property name="font" >
+ <font>
+ <family>Sans Serif</family>
+ <pointsize>9</pointsize>
+ <weight>50</weight>
+ <italic>false</italic>
+ <bold>false</bold>
+ <underline>false</underline>
+ <strikeout>false</strikeout>
+ </font>
+ </property>
+ <property name="text" >
+ <string comment="KDE::DoNotExtract" >TextLabel</string>
+ </property>
+ <property name="wordWrap" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="QFrame" name="frame_2" >
+ <property name="frameShape" >
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="icon" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="name_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Name&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="name" >
+ <property name="text" >
+ <string>Name</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="email_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">E-Mail&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="email" >
+ <property name="text" >
+ <string>E-Mail</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0" >
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QLabel" name="state_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">State&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="3" >
+ <widget class="QLabel" name="ipadress" >
+ <property name="text" >
+ <string>IP-Address</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1" >
+ <widget class="QLabel" name="state" >
+ <property name="text" >
+ <string>State</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2" >
+ <widget class="QLabel" name="ipadress_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">IP-Adress&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="rights_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Rights&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="rights" >
+ <property name="text" >
+ <string>Rights</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp (revision 1522570)
@@ -0,0 +1,552 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "guimessagehistory.h"
+#include "messagemanager.h"
+#include <QMetaObject>
+#include <QStandardItemModel>
+#include "messagehistorymanager.h"
+#include <QTimer>
+#include "kdevteamwork_client.h"
+#include "kdevteamwork.h"
+#include "utils.h"
+#include <QMenu>
+#include <QHeaderView>
+#include "kdevteamwork_messageshower.h"
+#include <kdialog.h>
+
+using namespace Teamwork;
+
+Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
+Q_DECLARE_METATYPE( HistoryMessagePointer )
+Q_DECLARE_METATYPE( Teamwork::MessageType )
+
+GuiMessageHistory::GuiMessageHistory( MessageManager* manager, UserList users, const QString& context ) : SafeLogger( manager->teamwork() ->logger() ), m_manager( manager ), m_defaultContext( context ) {
+ foreach( const KDevTeamworkUserPointer &user, users )
+ addUser( user );
+
+ if ( users.isEmpty() )
+ m_allUsers = true;
+
+ m_dialog = new KDialog( manager->teamwork() ->widget() );
+ m_dialog->setButtons( KDialog::Close );
+ m_widgetData.setupUi( m_dialog->mainWidget() );
+
+ m_developersModel = new QStandardItemModel( 0, 1, m_widgetData.developers );
+ m_widgetData.developers->setModel( m_developersModel );
+ m_widgetData.developers->setSelectionMode( QAbstractItemView::MultiSelection );
+
+ m_messagesModel = new QStandardItemModel( 0, 1, m_widgetData.messages );
+ m_widgetData.messages->setModel( m_messagesModel );
+
+ m_updateTimer = new QTimer( this );
+ m_userIconUpdateTimer = new QTimer( this );
+ m_updateTimer->setSingleShot( true );
+ m_userIconUpdateTimer->setSingleShot( true );
+ //m_widgetData.messages->header()->hide();
+
+
+ qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
+ qRegisterMetaType<HistoryMessagePointer>( "HistoryMessagePointer" );
+ qRegisterMetaType<Teamwork::MessageType>( "Teamwork::MessageType" );
+
+ connect( m_widgetData.developers->selectionModel(), SIGNAL( selectionChanged ( const QItemSelection &, const QItemSelection & ) ), this, SLOT( slotSelectionChanged() ) );
+ connect( m_widgetData.untilDate, SIGNAL( dateChanged ( const QDate & ) ), this, SLOT( slotSelectionChanged() ) );
+ connect( m_widgetData.fromDate, SIGNAL( dateChanged ( const QDate & ) ), this, SLOT( slotSelectionChanged() ) );
+ connect( m_widgetData.allMessagesButton, SIGNAL( clicked( bool ) ), this, SLOT( slotAllMessages() ) );
+ connect( m_widgetData.allDevelopersButton, SIGNAL( clicked( bool ) ), this, SLOT( slotAllDevelopers() ) );
+ connect( m_widgetData.typeFilter, SIGNAL( currentIndexChanged ( int ) ), this, SLOT( typeFilterChanged( int ) ) );
+ connect( m_widgetData.contextFilter, SIGNAL( currentIndexChanged ( int ) ), this, SLOT( contextFilterChanged( int ) ) );
+
+ connect( &m_manager->historyManager(), SIGNAL( newMessage( HistoryMessagePointer ) ), this, SLOT( slotNewMessage( const HistoryMessagePointer& ) ), Qt::QueuedConnection );
+ connect( m_updateTimer, SIGNAL( timeout() ), this, SLOT( slotUpdateMessages() ) );
+ connect( m_userIconUpdateTimer, SIGNAL( timeout() ), this, SLOT( updateMessageUserIcons() ) );
+// connect( m_widgetData.exitButton, SIGNAL( clicked( bool ) ), this, SLOT( slotExit() ) );
+ connect( m_dialog, SIGNAL( finished() ), this, SLOT( slotExit() ) );
+ connect( m_widgetData.messages, SIGNAL( clicked ( const QModelIndex & ) ), this, SLOT( messageItemClicked( const QModelIndex& ) ) );
+
+
+ m_widgetData.messages->setAlternatingRowColors( true );
+ m_widgetData.messages->setSelectionBehavior( QAbstractItemView::SelectItems );
+ m_widgetData.messages->setRootIsDecorated( false );
+ m_widgetData.messages->setIndentation( 0 );
+ m_widgetData.messages->header() ->setResizeMode( QHeaderView::Stretch );
+
+ slotAllMessages();
+ fillDeveloperList();
+ m_dialog->show();
+}
+
+GuiMessageHistory::~GuiMessageHistory() {
+ delete m_dialog;
+}
+
+void GuiMessageHistory::showMessage( const HistoryMessagePointer& msg ) {
+ HistoryMessagePointer::Locked l = msg;
+ if ( l ) {
+ if ( m_messagesModel->columnCount() == 0 ) {
+ /*if( m_widget ) {
+ m_widgetData.messages->header()->show();
+ }*/
+ m_messagesModel->insertColumns( 0, ColumnCount );
+
+ m_messagesModel->setHeaderData( TimeColumn, Qt::Horizontal, QString( "Time" ) );
+ m_messagesModel->setHeaderData( UserColumn, Qt::Horizontal, QString( "User" ) );
+ m_messagesModel->setHeaderData( TypeColumn, Qt::Horizontal, QString( "Type" ) );
+ m_messagesModel->setHeaderData( TextColumn, Qt::Horizontal, QString( "Text" ) );
+ }
+ m_messagesModel->insertRow( 0 );
+
+ ///Time
+ {
+ UserPointer::Locked lu = l->info().user();
+ QString userName;
+
+ QModelIndex index = m_messagesModel->index( 0, TimeColumn );
+
+ m_messagesModel->setData( index, l->creationTime().toString( Qt::LocalDate ), Qt::DisplayRole );
+ //m_messagesModel->setData( index, l->messageIcon(), Qt::DecorationRole );
+
+ QVariant v;
+ v.setValue( msg );
+ m_messagesModel->setData( index, v, Qt::UserRole );
+ }
+
+ ///Message-Type
+ {
+ UserPointer::Locked lu = l->info().user();
+ QString userName;
+
+ QModelIndex index = m_messagesModel->index( 0, TypeColumn );
+ if ( lu ) {
+ userName = ~lu->name();
+ } else {
+ userName = "unknown user";
+ }
+
+ m_messagesModel->setData( index, l->shortName(), Qt::DisplayRole );
+ m_messagesModel->setData( index, l->messageIcon(), Qt::DecorationRole );
+
+ QVariant v;
+ v.setValue( msg );
+ m_messagesModel->setData( index, v, Qt::UserRole );
+ }
+
+ ///User
+ {
+ UserPointer::Locked lu = l->info().user();
+ QString userName;
+
+ QModelIndex index = m_messagesModel->index( 0, UserColumn );
+ if ( lu ) {
+ userName = ~lu->name();
+ } else {
+ userName = "unknown";
+ }
+
+ m_messagesModel->setData( index, userName, Qt::DisplayRole );
+
+ if ( lu.cast<KDevTeamworkUser>() )
+ m_messagesModel->setData( index, lu.cast<KDevTeamworkUser>() ->icon(), Qt::DecorationRole );
+
+ QVariant v;
+ v.setValue( l->info().user() );
+ m_messagesModel->setData( index, v, Qt::UserRole );
+ }
+
+
+ ///Text
+ {
+ QModelIndex index = m_messagesModel->index( 0, TextColumn );
+
+ m_messagesModel->setData( index, ~l->text(), Qt::DisplayRole );
+
+ QVariant v;
+ v.setValue( msg );
+ m_messagesModel->setData( index, v, Qt::UserRole );
+ }
+ } else {
+ ///error
+ err() << "could not lock Message in showMessage";
+ }
+}
+
+void GuiMessageHistory::updateMessageUserIcons() {
+ QMap<KDevTeamworkUserPointer, KDevTeamworkUserPointer::Locked> lockedUsers;
+ foreach( KDevTeamworkUserPointer u, m_changedUsers ) {
+ KDevTeamworkUserPointer::Locked l = u;
+ lockedUsers[ u ] = l;
+ }
+
+ for ( int a = 0; a < m_messagesModel->rowCount(); a++ ) {
+ QModelIndex i = m_messagesModel->index( a, UserColumn );
+ if ( i.isValid() ) {
+ QVariant v = m_messagesModel->data( i , Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ QMap<KDevTeamworkUserPointer, KDevTeamworkUserPointer::Locked>::iterator it = lockedUsers.find( v.value<UserPointer>().cast<KDevTeamworkUser>() );
+ if ( it != lockedUsers.end() ) {
+ if ( *it ) {
+ m_messagesModel->setData( i, ( *it ) ->icon(), Qt::DecorationRole );
+ } else {
+ m_messagesModel->setData( i, QIcon(), Qt::DecorationRole );
+ }
+ }
+
+ }
+ }
+ }
+ m_changedUsers.clear();
+}
+
+
+void GuiMessageHistory::messageItemClicked( const QModelIndex& index ) {
+ QVariant v = m_messagesModel->data( index, Qt::UserRole );
+
+ if ( v.canConvert<UserPointer>() ) {
+ KDevTeamworkUserPointer::Locked lu = v.value<UserPointer>().cast<KDevTeamworkUser>();
+ if ( lu ) {
+ QWidget * w = m_widgetData.messageFrame->widget();
+ m_widgetData.messageFrame->setWidget( 0 );
+ if ( w )
+ delete w;
+
+ w = new QWidget( m_widgetData.messageFrame );
+ new KDevTeamworkUserInfoShower( lu, w, m_manager->teamwork() );
+ m_widgetData.messageFrame->setWidget( w );
+
+ /*QMenu* menu = new QMenu( m_dialog );
+ m_manager->teamwork()->fillUserMenu( menu, lu.data() );
+ menu->exec( QCursor::pos() );*/
+ } else {
+ err() << "could not lock user in messageItemClicked";
+ }
+ }
+
+ if ( v.canConvert<HistoryMessagePointer>() ) {
+ HistoryMessagePointer::Locked lmsg = v.value<HistoryMessagePointer>();
+ if ( lmsg ) {
+ QWidget * w = m_widgetData.messageFrame->widget();
+ m_widgetData.messageFrame->setWidget( 0 );
+ if ( w )
+ delete w;
+
+ AbstractGUIMessage* gmsg = lmsg.freeCast<AbstractGUIMessage>();
+ if ( gmsg ) {
+ w = new QWidget( m_widgetData.messageFrame );
+ gmsg->showInWidget( w, m_manager->teamwork() );
+ m_widgetData.messageFrame->setWidget( w );
+ }
+
+ /*QMenu* menu = new QMenu( m_dialog );
+ m_manager->fillMessageMenu( menu, lmsg.data() );
+ menu->exec( QCursor::pos() );*/
+ } else {
+ err() << "could not lock message in messageItemClicked";
+ }
+ }
+}
+
+
+bool GuiMessageHistory::fitMessageDate( const HistoryMessagePointer& msg ) {
+ HistoryMessagePointer::Locked l = msg;
+
+ if ( l ) {
+ return m_widgetData.fromDate->date() <= l->creationTime().date() && m_widgetData.untilDate->date() >= l->creationTime().date();
+ } else {
+ err() << "could not lock Message in fitMessageDate";
+ return false;
+ }
+}
+
+void GuiMessageHistory::slotExit() {
+ deleteLater();
+}
+
+void GuiMessageHistory::slotAllMessages() {
+ m_widgetData.fromDate->setDate( QDate( 2000, 1, 1 ) );
+ m_widgetData.untilDate->setDate( QDate::currentDate() );
+ slotSelectionChanged();
+}
+
+
+void GuiMessageHistory::slotAllDevelopers() {
+ if ( selectedUsers().isEmpty() ) {
+ m_users.clear();
+ m_allUsers = true;
+ }
+
+ m_widgetData.developers->selectionModel() ->clear();
+ slotSelectionChanged();
+}
+
+void GuiMessageHistory::slotNewMessage( const HistoryMessagePointer& msg ) {
+ HistoryMessagePointer::Locked l = msg;
+ if ( l ) {
+ UserPointer u = userFromSession( l->info().session() );
+ if ( m_users.contains( u.cast<KDevTeamworkUser>() ) || m_allUsers ) {
+ if ( fitMessageDate( msg ) ) {
+ showMessage( msg );
+ applyFilters( 1 );
+ }
+ }
+ } else {
+ m_manager->log( "GuiMessageHistory: could not lock a new message", Error );
+ }
+}
+
+void GuiMessageHistory::typeFilterChanged( int /*index*/ ) {
+ applyFilters();
+}
+
+
+void GuiMessageHistory::contextFilterChanged( int /*index*/ ) {
+ applyFilters();
+}
+
+
+void GuiMessageHistory::clearFilters() {
+ m_widgetData.typeFilter->clear();
+ m_widgetData.contextFilter->clear();
+}
+
+
+void GuiMessageHistory::applyFilters( int firstN ) {
+ QString type = m_widgetData.typeFilter->currentText();
+ Teamwork::MessageType id;
+
+ if ( m_widgetData.typeFilter->currentIndex() != -1 ) {
+ QVariant v = m_widgetData.typeFilter->itemData( m_widgetData.typeFilter->currentIndex() );
+ if ( v.canConvert<Teamwork::MessageType>() ) {
+ id = v.value<Teamwork::MessageType>();
+ }
+ }
+ QString context = m_widgetData.contextFilter->currentText();
+
+ int count = m_messagesModel->rowCount();
+ if ( firstN != 0 && firstN < count )
+ count = firstN;
+
+ for ( int a = 0; a < count; a++ ) {
+ QModelIndex index = m_messagesModel->index( a, TypeColumn );
+ bool typeFits = false;
+ bool contextFits = false;
+
+ QVariant v = m_messagesModel->data( index, Qt::UserRole );
+ if ( HistoryMessagePointer::Locked lmsg = v.value<HistoryMessagePointer>() ) {
+ if ( !type.isEmpty() ) {
+ if ( lmsg->info().type().startsWith( id ) )
+ typeFits = true;
+ } else {
+ typeFits = true;
+ }
+
+ if ( context.isEmpty() ) {
+ contextFits = true;
+ } else {
+ InDocumentMessage* dmsg = lmsg.freeCast< InDocumentMessage >();
+ if ( dmsg && dmsg->context() == context )
+ contextFits = true;
+ }
+ } else {
+ typeFits = true;
+ contextFits = true;
+ }
+
+ m_widgetData.messages->setRowHidden( a, QModelIndex(), !typeFits || !contextFits );
+ }
+}
+
+
+void GuiMessageHistory::slotSelectionChanged() {
+ ///Update the list of messages according to the selected users
+ m_updateTimer->start( 100 );
+}
+
+void GuiMessageHistory::slotUpdateMessages() {
+ fillMessages();
+}
+
+void GuiMessageHistory::slotUserStateChanged( const KDevTeamworkUserPointer& user ) {
+ m_changedUsers << user;
+ updateUserIcon( user );
+ m_userIconUpdateTimer->start( 100 );
+}
+
+void GuiMessageHistory::fillMessages() {
+ QString oldTypeFilter = m_widgetData.typeFilter->currentText();
+ QString oldContextFilter = m_widgetData.contextFilter->currentText();
+
+ clearFilters();
+
+ UserSet selected = selectedUsers();
+ m_messagesModel->clear();
+ if ( m_allUsers && selected.isEmpty() ) {
+ m_developersModel->clear();
+ clearUsers();
+ }
+
+ QMap<UserIdentity, bool> users;
+ for ( UserSet::iterator it = selected.begin(); it != selected.end(); ++it ) {
+ KDevTeamworkUserPointer::Locked l = it.key();
+ if ( l ) {
+ users[ l->identity() ] = true;
+ } else {
+ //error
+ err() << "failed to lock a user on slotUserStateChanged";
+ }
+ }
+
+ QMap<QString, bool> contexts;
+ QMap<QString, Teamwork::MessageType> types;
+ QMap<UserPointer, bool> grabbedUsers;
+
+ QList<HistoryMessagePointer> messages = m_manager->historyManager().getMessages( m_manager->teamwork() ->client(), m_widgetData.fromDate->date(), m_widgetData.untilDate->date(), users );
+
+ foreach( HistoryMessagePointer msg, messages ) {
+ showMessage( msg );
+
+ HistoryMessagePointer::Locked l = msg;
+ if ( l ) {
+ types[ QString( l->name() ) ] = l->info().type();
+ if ( InDocumentMessage * dmsg = l.freeCast<InDocumentMessage>() ) {
+ contexts[ dmsg->context() ] = true;
+ }
+ }
+
+ if ( m_allUsers ) {
+ HistoryMessagePointer::Locked l = msg;
+ if ( msg ) {
+ if ( l->info().user() ) {
+ grabbedUsers[ l->info().user() ] = true;
+ } else {
+ err() << "a message has no associated user";
+ }
+ } else {
+ err() << "a message cannot be locked";
+ }
+ }
+ }
+
+ if ( !grabbedUsers.isEmpty() ) {
+ TeamworkClientPointer::Locked l = m_manager->teamwork() ->client();
+ if ( l ) {
+ for ( QMap<UserPointer, bool>::iterator it = grabbedUsers.begin(); it != grabbedUsers.end(); ++it ) {
+
+ SafeSharedPtr<KDevTeamworkUser> user = it.key().cast<KDevTeamworkUser>();
+ if ( user ) {
+ addUser( user );
+ } else {
+ err() << "could not cast user to KDevTeamworkUSer";
+ }
+ }
+ } else {
+ err() << "could not lock client-session";
+ }
+ }
+
+ if ( ( m_allUsers || !grabbedUsers.isEmpty() ) && selected.isEmpty() )
+ fillDeveloperList();
+
+ m_widgetData.typeFilter->insertItem( 0, "" );
+ for ( QMap<QString, Teamwork::MessageType>::iterator it = types.begin(); it != types.end(); ++it ) {
+ m_widgetData.typeFilter->insertItem( m_widgetData.typeFilter->count(), it.key() );
+ QVariant v;
+ v.setValue( *it );
+ m_widgetData.typeFilter->setItemData( m_widgetData.typeFilter->count() - 1, v );
+ }
+
+ m_widgetData.contextFilter->insertItem( 0, m_defaultContext );
+ if ( !m_defaultContext.isEmpty() )
+ m_widgetData.contextFilter->insertItem( 1, "" );
+ for ( QMap<QString, bool>::iterator it = contexts.begin(); it != contexts.end(); ++it ) {
+ m_widgetData.contextFilter->insertItem( m_widgetData.contextFilter->count(), it.key() );
+ }
+
+ int i = m_widgetData.contextFilter->findText( oldContextFilter );
+ if ( i != -1 )
+ m_widgetData.contextFilter->setCurrentIndex( i );
+
+ i = m_widgetData.typeFilter->findText( oldTypeFilter );
+ if ( i != -1 )
+ m_widgetData.contextFilter->setCurrentIndex( i );
+
+ applyFilters();
+}
+
+GuiMessageHistory::UserSet GuiMessageHistory::selectedUsers() {
+ QModelIndexList selected = m_widgetData.developers->selectionModel() ->selectedIndexes();
+ if ( selected.isEmpty() ) {
+ return m_users;
+ } else {
+ UserSet ret;
+ foreach( QModelIndex index, selected ) {
+ QVariant v = m_developersModel->data( index, Qt::UserRole );
+ if ( v.canConvert<KDevTeamworkUserPointer>() )
+ ret[ v.value<KDevTeamworkUserPointer>() ] = true;
+ }
+ return ret;
+ }
+}
+
+void GuiMessageHistory::fillDeveloperList() {
+ m_developersModel->clear();
+ m_developersModel->insertColumn( 0 );
+ for ( UserSet::iterator it = m_users.begin(); it != m_users.end(); ++it ) {
+ m_developersModel->insertRow( 0 );
+ QModelIndex index = m_developersModel->index( 0, 0 );
+
+ KDevTeamworkUserPointer::Locked l = it.key();
+ if ( l ) {
+ m_developersModel->setData( index, ~l->User::name(), Qt::DisplayRole );
+
+ QVariant v;
+ v.setValue( it.key() );
+ m_developersModel->setData( index, v, Qt::UserRole );
+
+ m_developersModel->setData( index, l->icon(), Qt::DecorationRole );
+ } else {
+ m_developersModel->setData( index, QString( "lock_failed" ) );
+ }
+ }
+}
+
+void GuiMessageHistory::clearUsers() {
+ for ( UserSet::iterator it = m_users.begin(); it != m_users.end(); ++it ) {
+ disconnect( it.key().unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( slotUserStateChanged( const KDevTeamworkUserPointer& ) ) );
+ }
+ m_users.clear();
+}
+
+void GuiMessageHistory::addUser( const KDevTeamworkUserPointer& user ) {
+ m_users[ user ] = true;
+ connect( user.unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( slotUserStateChanged( const KDevTeamworkUserPointer& ) ), Qt::QueuedConnection );
+}
+
+void GuiMessageHistory::updateUserIcon( const KDevTeamworkUserPointer& user ) {
+ KDevTeamworkUserPointer::Locked l = user;
+ for ( int a = 0; a < m_developersModel->rowCount(); a++ ) {
+ QModelIndex index = m_developersModel->index( a, 0 );
+ if ( !index.isValid() )
+ break;
+ QVariant v = m_developersModel->data( index, Qt::UserRole );
+ if ( v.canConvert<KDevTeamworkUserPointer>() ) {
+ if ( user == v.value<KDevTeamworkUserPointer>() ) {
+ m_developersModel->setData( index, l->icon() , Qt::DecorationRole );
+ }
+ }
+ }
+}
+
+#include "guimessagehistory.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp (revision 1522570)
@@ -0,0 +1,385 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "kdevteamwork_messageshower.h"
+#include <QWidget>
+#include <QObject>
+#include "kdevteamwork_messages.h"
+#include "ui_kdevteamwork_textmessage.h"
+#include "ui_kdevteamwork_indocumentcontextlines.h"
+#include "ui_kdevteamwork_indocumentmessagebuttons.h"
+#include "ui_kdevteamwork_indocumentmessagestate.h"
+#include <klocalizedstring.h>
+#include <QPointer>
+#include "kdevteamwork.h"
+#include "utils.h"
+#include "kdevteamwork_user.h"
+#include "messagemanager.h"
+#include <QPixmap>
+#include <QMenu>
+#include "messagehistorymanager.h"
+#include <kdialog.h>
+#include <QMetaType>
+#include "conversationmanager.h"
+#include <qtextdocument.h>
+#include <krandom.h>
+
+
+KDevTeamworkMessageShower::KDevTeamworkMessageShower( KDevTeamworkTextMessage* msg, QWidget* widget, KDevTeamwork* teamwork ) : QObject( widget ), m_message( msg ), m_widget( widget ), m_teamwork( teamwork ) {
+ m_widgetData.setupUi( m_widget );
+
+ fill();
+
+ connect( m_widgetData.menuButton, SIGNAL( clicked() ), this, SLOT( menuButton() ) );
+ connect( m_widgetData.historyButton, SIGNAL( clicked() ), this, SLOT( historyButton() ) );
+ connect( m_widgetData.isReplyToButton, SIGNAL( clicked() ), this, SLOT( isReplyToButton() ) );
+ connect( teamwork->messageManager(), SIGNAL( messageUpdated( const MessagePointer& ) ), this, SLOT( messageUpdated( const MessagePointer& ) ) );
+}
+
+void KDevTeamworkMessageShower::fillData() {
+ fill();
+}
+
+void KDevTeamworkMessageShower::fill() {
+ LockedSharedPtr<KDevTeamworkTextMessage> msg = m_message;
+ if ( msg ) {
+ m_widgetData.text->setText( ~msg->text() );
+ m_widgetData.state->setText( QString( "ok" ) );
+ QString user = QString( "Unknown" );
+
+ if ( msg->info().user() ) {
+ user = ~msg->info().user().unsafe() ->safeName();
+ if ( msg->info().user().cast<KDevTeamworkUser>() ) {
+ connect( msg->info().user().cast<KDevTeamworkUser>().unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
+ }
+ }
+
+ LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
+ if ( l ) {
+ m_widget->setWindowIcon( l->messageIcon() );
+ }
+
+ m_widgetData.user->setText( QString( user ) );
+ m_widgetData.time->setText( QString( msg->creationTime().toString() ) );
+
+ QString direction;
+ if ( msg->info().isIncoming() )
+ direction = QString( "incoming" );
+ else
+ direction = QString( "outgoing" );
+
+
+ m_widgetData.direction->setText( QString( direction ) );
+
+ //m_widgetData.answerTo->setText( QString( "Answer to: %1" ).arg( msg->info().isReplyTo() ) );
+
+ if ( !msg->info().isReplyTo() ) {
+ m_widgetData.isReplyToButton->setEnabled( false );
+ }
+ }
+}
+
+void KDevTeamworkMessageShower::messageUpdated( const MessagePointer& msg ) {
+ if ( msg.unsafe() == m_message.unsafe() ) {
+ fillData();
+ }
+}
+
+
+void KDevTeamworkMessageShower::isReplyToButton() {
+ LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
+ if ( l ) {
+ if ( l->info().isReplyTo() ) {
+ MessagePointer repliedMessage = l->info().replyToMessage();
+ if ( !repliedMessage && m_teamwork )
+ repliedMessage = m_teamwork->messageManager() ->historyManager().getMessageFromId( l->info().isReplyTo() , m_teamwork->client() );
+
+ if ( LockedSharedPtr<KDevTeamworkTextMessage> lrep = repliedMessage.cast<KDevTeamworkTextMessage>() ) {
+ KDialog * dialog = new KDialog( m_widget );
+ dialog->setAttribute( Qt::WA_DeleteOnClose, true );
+ new KDevTeamworkMessageShower( lrep, dialog->mainWidget(), m_teamwork );
+ dialog->show();
+ }
+ }
+ } else {}
+}
+
+void KDevTeamworkMessageShower::menuButton() {
+ if ( m_teamwork && m_message ) {
+ QMenu * menu = new QMenu( m_widget );
+
+ m_teamwork->messageManager() ->fillMessageMenu( menu, m_message );
+
+ menu->exec( QCursor::pos() );
+ }
+}
+
+void KDevTeamworkMessageShower::historyButton() {
+ LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
+ if ( l && m_teamwork ) {
+ KDevTeamworkUserPointer u = l->info().user().cast<KDevTeamworkUser>();
+ if ( u ) {
+ QList<KDevTeamworkUserPointer> users;
+ users << u;
+ m_teamwork->messageManager() ->showMessageHistory( users );
+ } else {}
+ }
+}
+
+void KDevTeamworkMessageShower::userStateChanged() {
+ LockedSharedPtr<KDevTeamworkTextMessage> lmsg = m_message;
+ if ( lmsg ) {
+ LockedSharedPtr<KDevTeamworkUser> l = lmsg->info().user().cast<KDevTeamworkUser>();
+ if ( l ) {
+ m_widgetData.userIcon->setPixmap( l->icon().pixmap( 32, 32 ) );
+ return ;
+ }
+ }
+ m_widgetData.userIcon->setPixmap( QPixmap() );
+}
+
+
+KDevTeamworkUserInfoShower::KDevTeamworkUserInfoShower( KDevTeamworkUser* user, QWidget* widget, KDevTeamwork* teamwork ) : QObject( widget ), m_user( user ), m_widget( widget ), m_teamwork( teamwork ) {
+ m_widgetData.setupUi( m_widget );
+ m_widgetData.description->setText( ~user->description() );
+ m_widgetData.name->setText( ~( ( Teamwork::User* ) user ) ->name() );
+ m_widgetData.email->setText( QString( ~user->email() ) );
+ m_widgetData.rights->setText( QString( ~user->rightsAsString() ) );
+
+ setIp();
+ setStatus();
+ setIcon();
+
+ connect( m_widgetData.menuButton, SIGNAL( clicked(bool) ), this, SLOT( menuButton() ) );
+ connect( m_widgetData.historyButton, SIGNAL( clicked(bool) ), this, SLOT( historyButton() ) );
+ connect( m_user.unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
+}
+
+void KDevTeamworkUserInfoShower::menuButton() {
+ if ( m_teamwork && m_user ) {
+ QMenu * menu = new QMenu( m_widget );
+
+ m_teamwork->fillUserMenu( menu, m_user );
+
+ menu->exec( QCursor::pos() );
+ }
+}
+
+
+void KDevTeamworkUserInfoShower::userStateChanged() {
+ setIp();
+ setStatus();
+ setIcon();
+}
+
+
+void KDevTeamworkUserInfoShower::historyButton() {
+ if ( m_teamwork && m_user ) {
+ QList<KDevTeamworkUserPointer> users;
+ users << m_user;
+ m_teamwork->messageManager() ->showMessageHistory( users );
+ }
+}
+
+void KDevTeamworkUserInfoShower::setIp() {
+ LockedSharedPtr<KDevTeamworkUser> l = m_user;
+ QString address = QString( "Unknown" );
+ if ( l ) {
+ SessionPointer::Locked ls = l->online().session();
+ if ( ls )
+ address = ~ls->peerDesc();
+ }
+ m_widgetData.ipadress->setText( QString( address ) );
+}
+
+
+void KDevTeamworkUserInfoShower::setStatus() {
+ LockedSharedPtr<KDevTeamworkUser> l = m_user;
+ if ( l ) {
+ QStringList available;
+ if ( !l->online() ) {
+ available << QString( "not available" );
+ } else {
+ if ( l->online().session().unsafe() ->sessionType() == SessionInterface::Direct ) {
+ available << QString( "direct" );
+ } else {
+ available << QString( "indirect" );
+ }
+
+ if ( l->online().session().unsafe() ->sessionDirection() == SessionInterface::Incoming ) {
+ available << QString( "incoming" );
+ } else {
+ available << QString( "Outgoing" );
+ }
+ }
+
+ m_widgetData.state->setText( QString( available.join( ", " ) ) );
+ } else {
+ m_widgetData.state->setText( QString( "Lock Failed" ) );
+ }
+}
+
+
+void KDevTeamworkUserInfoShower::setIcon() {
+ LockedSharedPtr<KDevTeamworkUser> l = m_user;
+ if ( l ) {
+ m_widgetData.icon->setPixmap( l->icon().pixmap( 32, 32 ) );
+ m_widget->setWindowIcon( l->icon() );
+ } else {
+ m_widgetData.icon->setPixmap( QPixmap() );
+ m_widget->setWindowIcon( QIcon() );
+ }
+}
+
+struct InDocumentMessageShowerData {
+ Ui_InDocumentButtons buttons;
+ Ui_InDocumentContextLines contextLines;
+ Ui_InDocumentState state;
+ InDocumentMessageShowerData() : m_initialized( false ) {}
+ void initialize( Ui_TextMessageShower* widgetData ) {
+ if ( !m_initialized ) {
+
+ buttons.setupUi( widgetData->buttonSpace );
+ widgetData->buttonSpace->show();
+
+ contextLines.setupUi( widgetData->middleSpace );
+ widgetData->middleSpace->setMinimumHeight( widgetData->middleSpace->sizeHint().height() );
+ widgetData->middleSpace->show();
+
+ state.setupUi( widgetData->stateSpace );
+ widgetData->stateSpace->setMinimumHeight( widgetData->stateSpace->sizeHint().height() );
+ widgetData->stateSpace->show();
+
+ m_initialized = true;
+ }
+ }
+
+private:
+ bool m_initialized;
+};
+
+InDocumentMessageShower::InDocumentMessageShower( InDocumentMessage* msg, QWidget* widget, KDevTeamwork* teamwork ) : KDevTeamworkMessageShower( msg, widget, teamwork ), SafeLogger( teamwork->logger() , "InDocumentMessage: " ) {
+ m_data->initialize( &m_widgetData );
+ connect( m_data->state.file, SIGNAL( leftClickedUrl( const QString& ) ), this, SLOT( fileClicked() ) );
+ connect( m_data->state.context, SIGNAL( leftClickedUrl( const QString& ) ), this, SLOT( contextClicked() ) );
+ connect( m_data->buttons.jumpToPosition, SIGNAL( clicked() ), this, SLOT( fileClicked() ) );
+ fill();
+}
+
+void InDocumentMessageShower::fillData() {
+ KDevTeamworkMessageShower::fillData();
+ fill();
+}
+
+void InDocumentMessageShower::fileClicked() {
+ try {
+ if ( !m_teamwork )
+ throw "no teamwork";
+
+ LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
+ if ( !l )
+ throw "could not lock message";
+
+ InDocumentConversationPointer conv = m_teamwork->messageManager() ->conversationManager().getConversation( l );
+
+ if ( !conv )
+ throw "could not get conversation";
+
+ conv->selectMessage( l );
+ } catch ( QString str ) {
+ err() << str;
+ }
+}
+
+
+void InDocumentMessageShower::contextClicked() {
+ try {
+ if ( !m_teamwork )
+ throw "no teamwork";
+
+ LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
+ if ( !l )
+ throw "could not lock message";
+
+ m_teamwork->messageManager() ->showMessageHistory( QList<KDevTeamworkUserPointer>(), l->context() );
+ } catch ( QString str ) {
+ err() << str;
+ }
+}
+
+QString escapeWithoutLineBreaks( const QString& str ) {
+ const QStringList lines = str.split( '\n' );
+ QStringList ret;
+ foreach( const QString& line, lines ) {
+ ret << Qt::escape( line );
+ }
+ return ret.join( "<br>\n" );
+}
+
+void InDocumentMessageShower::fill() {
+ LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
+ if ( l ) {
+ int offset = l->contextLines().lineOffset();
+
+ QString marker1 = KRandom::randomString( 30 );
+ QString marker2 = KRandom::randomString( 30 );
+
+ QString lines = l->contextLines().text();
+ if ( l->start() && l->end() ) {
+ int startIndex = lineColToIndex( lines, l->start().line() - offset, l->start().col() );
+ int endIndex = lineColToIndex( lines, l->end().line() - offset, l->end().col() );
+ if ( startIndex != -1 && endIndex != -1 ) {
+ lines = lines.mid( 0, startIndex ) + marker1 + lines.mid( startIndex, endIndex - startIndex ) + marker2 + lines.mid( endIndex );
+ }
+ }
+
+ QString txt = escapeWithoutLineBreaks( lines );
+
+ txt = txt.replace( marker1, "<font color=\"red\">" );
+ txt = txt.replace( marker2, "</font>" );
+
+ m_data->contextLines.contextLines->setHtml( txt );
+ m_data->state.file->setText( l->document() );
+ m_data->state.context->setText( l->context() );
+ m_data->state.file->setUrl( "hallo" );
+ m_data->state.context->setUrl( "hallo" );
+
+ QString refType = "static";
+ if ( !l->start().isValid() ) {
+ refType = "invalid";
+ } else if ( l->start().isDynamic() ) {
+ refType = "dynamic";
+ if ( l->end().isValid() ) {
+ refType += " range";
+ }
+ } else {
+ refType = "static";
+ if ( l->end().isValid() ) {
+ refType += " range";
+ }
+ }
+
+ m_data->state.referenceType->setText( refType );
+
+ QString position = l->start().asText();
+ if ( l->end().isValid() )
+ position += " to " + l->end().asText();
+
+ m_data->state.position->setText( position );
+
+ } else {}
+}
+
+#include "kdevteamwork_messageshower.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp (revision 1522570)
@@ -0,0 +1,1871 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+///@todo the whole inclusion-structure needs a big cleanup
+
+
+#include "kdevteamwork.h"
+#include <list>
+
+#include <QtGui/QHeaderView>
+#include <QAction>
+#include <QTimer>
+#include <QCursor>
+#include <kdialog.h>
+#include <QPersistentModelIndex>
+#include <QWidget>
+
+#include <kdebug.h>
+#include <klocale.h>
+#include <ktexteditor/document.h>
+#include <kurl.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+
+#include "lib/network/messagetypeset.h"
+#include "lib/network/multisession.h"
+#include "kdevteamworkplugin.h"
+#include "kdevteamwork_messageshower.h"
+#include "kdevteamwork_user.h"
+#include "kdevteamwork_client.h"
+#include "teamworkfoldermanager.h"
+#include "helpers.h"
+#include "kdevteamwork_helpers.h"
+#include "messageusertab.h"
+#include "messagesendmanager.h"
+#include "conversationmanager.h"
+
+///@todo Make most of these managers independent
+#include "collaborationmanager.h"
+#include "messagemanager.h"
+#include "patchesmanager.h"
+
+#include "ui_kdevteamwork_list.h"
+#include "ui_kdevteamwork_interface.h"
+
+using namespace KDevelop;
+
+///@todo make sure fromUtf8(..) and toUtf8(..) is used everywhere, especially in all the messages
+
+const int messageSendTimeout = 3000;
+
+KDevTeamwork* KDevTeamwork::m_self = 0;
+
+//Q_DECLARE_METATYPE( UserPointer )
+Q_DECLARE_METATYPE( QPersistentModelIndex )
+Q_DECLARE_METATYPE( MessagePointer )
+Q_DECLARE_METATYPE( LocalPatchSourcePointer )
+Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
+
+
+LaterDeleter::LaterDeleter( const KDevTeamworkClientPointer& c ) : m_c( c ) {
+ deleteLater();
+}
+
+LaterDeleter::~LaterDeleter() {
+}
+
+std::string stringToAddr( const QString& txt );
+int stringToPort( const QString& txt );
+
+QIcon iconFromLevel( LogLevel level ) {
+ switch ( level ) {
+ case Error:
+ return IconCache::getIconStatic( "remove", KIconLoader::Small );
+ break;
+ case Info:
+ return IconCache::getIconStatic( "ok", KIconLoader::Small );
+ break;
+ case Warning:
+ return IconCache::getIconStatic( "fileclose", KIconLoader::Small );
+ break;
+ case Debug:
+ return IconCache::getIconStatic( "log", KIconLoader::Small );
+ break;
+ default:
+ return IconCache::getIconStatic( "unknown", KIconLoader::Small );
+ }
+}
+
+///Get rid of this
+void setValueMessage( QVariant& v, const MessagePointer& msg ) {
+ v.setValue( msg );
+}
+
+PatchesManager* KDevTeamwork::patchesManager() {
+ return m_patchesManager;
+}
+
+Ui::Teamwork& KDevTeamwork::widgets() {
+ return *m_widgets;
+}
+
+
+QWidget* KDevTeamwork::widget() {
+ return m_widget;
+}
+
+IconCache& KDevTeamwork::icons() {
+ return * m_icons;
+}
+
+
+SafeTeamworkEmitter::SafeTeamworkEmitter( KDevTeamwork* tw ) {
+ if ( !tw )
+ return ;
+ connect( this, SIGNAL( signalUpdateMessageInfo( MessagePointer ) ), tw, SLOT( updateMessageInfo( MessagePointer ) ), Qt::QueuedConnection );
+}
+
+template <class Type, class Helper>
+void forEachInModel( QStandardItemModel* model, Helper& hlp, const QModelIndex& parent = QModelIndex() ) {
+ for ( int a = 0; a < model->rowCount(); a++ ) {
+ QModelIndex i = model->index( a, 0, parent );
+ if ( i.isValid() ) {
+ QVariant v = model->data( i, Qt::UserRole );
+ if ( v.canConvert<Type>() ) {
+ Type t = v.value<Type>();
+ if ( !hlp( t, i, model ) )
+ return ;
+ } else {
+ ///Some warning-message
+ }
+ }
+ }
+}
+
+template <class Type>
+struct NormalIdentCompare {
+ bool operator() ( const Type& lhs, const Type& rhs ) {
+ return lhs == rhs;
+ }
+};
+
+template <class Type, class Compare>
+struct FindInHelper {
+ QModelIndex found;
+ Compare compare;
+ const Type& searching;
+ FindInHelper( const Type& s ) : searching( s ) {}
+
+ bool operator () ( const Type& t, QModelIndex i, QStandardItemModel* /*model*/ ) {
+ if ( compare( t, searching ) ) {
+ found = i;
+ return false;
+ }
+ return true;
+ }
+};
+
+template <class Type, class Compare >
+QModelIndex findInModel( QStandardItemModel* model, const Type& t, const QModelIndex& /*parent*/ = QModelIndex() ) {
+
+ FindInHelper<Type, Compare> h( t );
+
+ forEachInModel<Type>( model, h );
+
+ return h.found;
+}
+
+template <class Type >
+QModelIndex findInModelNormal( QStandardItemModel* model, const Type& t, const QModelIndex& parent = QModelIndex() ) {
+ return findInModel<Type, NormalIdentCompare<Type> > ( model, t, parent );
+}
+
+UserPointer KDevTeamwork::localUser() {
+ ///@todo care about real local user
+ return new User( "local" );
+}
+
+#define ADDFILTERMENUITEM(x) { QAction *action = filterMenu->addAction( #x ); action->setData( x ); action->setCheckable( true ); connect( action, SIGNAL( triggered() ), this, SLOT( uiFilterLog() ) ); action->setChecked( m_currentLogFilter & x ); };
+
+#define ADD_FILTER_MENU_ITEM(filterMenu, x, data, checked, slot) { QAction *action = filterMenu->addAction( #x ); action->setData( data ); action->setCheckable( true ); connect( action, SIGNAL( triggered() ), this, SLOT( slot() ) ); action->setChecked( checked ); };
+
+MessageManager* KDevTeamwork::messageManager() {
+ return m_messageManager.data();
+}
+
+
+KDevTeamwork::KDevTeamwork( const KUrl& workspaceDirectory, KDevTeamworkPlugin *plugin, QWidget *parent ) :
+m_folderManager( workspaceDirectory ),
+m_logger( new KDevTeamworkLogger( this ) ),
+m_destroyed( false ),
+m_plugin( plugin ),
+m_active( false ),
+m_serverActive( false ),
+m_patchesManager( this ),
+m_collaborationManager( this ),
+m_messageManager( this ),
+m_messageSendManager( *m_widgets ),
+m_currentLogFilter( ( LogLevel ) ( Error | Warning | Info ) )
+{
+ m_self = this;
+ m_widget = parent;
+
+ m_widgets->setupUi( parent );
+
+ m_widgets->logFilter->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
+ m_widgets->logFilter->setArrowType( Qt::DownArrow );
+ m_widgets->logFilter->setPopupMode( QToolButton::InstantPopup );
+
+ QMenu *filterMenu = new QMenu( i18n( "Filter" ), m_widgets->logFilter );
+
+ ADDFILTERMENUITEM( Debug );
+ ADDFILTERMENUITEM( Info );
+ ADDFILTERMENUITEM( Warning );
+ ADDFILTERMENUITEM( Error );
+
+ m_widgets->logFilter->setMenu( filterMenu );
+
+ m_widgets->answeringToButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
+ m_widgets->answeringToButton->setArrowType( Qt::DownArrow );
+ m_widgets->answeringToButton->setPopupMode( QToolButton::InstantPopup );
+
+ /*m_messageFilterMenu = new QMenu( i18n( "Filter" ), m_widgets->messageFilter );
+
+ m_widgets->messageFilter->setMenu( m_messageFilterMenu );*/
+
+ qRegisterMetaType<QPersistentModelIndex> ( "QPersistentModelIndex" );
+ qRegisterMetaType<LocalPatchSourcePointer> ( "LocalPatchSourcePointer" );
+ qRegisterMetaType<MessagePointer> ( "MessagePointer" );
+ qRegisterMetaType<UserPointer> ( "UserPointer" );
+
+
+ m_logModel = new QStandardItemModel( 0, 1, m_widgets->logList );
+ m_messagesModel = new QStandardItemModel( 0, 1, m_widgets->messageList );
+ m_clientsModel = new QStandardItemModel( 0, 1, m_widgets->connectedClients );
+ m_serversModel = new QStandardItemModel( 0, 1, m_widgets->connectedServers );
+ m_developersModel = new QStandardItemModel( 0, 1, m_widgets->availableDevelopers );
+
+ m_widgets->logList->setModel( m_logModel );
+ m_widgets->connectedClients->setModel( m_clientsModel );
+ m_widgets->connectedServers->setModel( m_serversModel );
+ m_widgets->messageList->setModel( m_messagesModel );
+ m_widgets->availableDevelopers->setModel( m_developersModel );
+ m_widgets->connectedDevelopers->setModel( m_collaborationManager->developersModel() );
+
+ m_widgets->availableDevelopers->setItemsExpandable( true );
+
+ m_widgets->availableDevelopers->header() ->hide();
+ m_widgets->connectedDevelopers->header() ->hide();
+
+ m_updateTimer = new QTimer( this );
+ m_updateTimer->setSingleShot( true );
+ m_updateAnswerTimer = new QTimer( this );
+ m_updateAnswerTimer->setSingleShot( true );
+
+ m_replyWaitingTimeout = new QTimer( this );
+ m_replyWaitingTimeout->setSingleShot( true );
+ connect( m_replyWaitingTimeout, SIGNAL( timeout() ), this, SLOT( messageReplyTimeout() ) );
+ connect( m_updateAnswerTimer, SIGNAL( timeout() ), this, SLOT( updateAnswerMenu() ) );
+
+ connect( m_widgets->allowIncoming, SIGNAL( stateChanged( int ) ), this, SLOT( allowIncomingChanged( int ) ) );
+ connect( m_widgets->enableCollaboration, SIGNAL( stateChanged( int ) ), this, SLOT( enableCollaborationChanged( int ) ) );
+ connect( m_widgets->connectServer, SIGNAL( clicked() ), this, SLOT( connectServer() ) );
+ connect( m_widgets->connectedServers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( serverClicked( const QModelIndex& ) ) );
+ connect( m_widgets->connectedServers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( serverDoubleClicked( const QModelIndex& ) ) );
+ connect( m_widgets->availableDevelopers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( developerClicked( const QModelIndex& ) ) );
+ connect( m_widgets->availableDevelopers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( developerDoubleClicked( const QModelIndex& ) ) );
+ connect( m_widgets->availableDevelopers, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT( developerContextMenu( const QPoint& ) ) );
+ connect( m_widgets->connectedClients, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( clientClicked( const QModelIndex& ) ) );
+ connect( m_widgets->connectedClients, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( clientDoubleClicked( const QModelIndex& ) ) );
+ connect( m_widgets->messageList, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( messageClicked( const QModelIndex& ) ) );
+ connect( m_widgets->messageList, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( messageDoubleClicked( const QModelIndex& ) ) );
+ connect( m_widgets->sendMessage, SIGNAL( clicked( ) ), this, SLOT( sendMessageButton( ) ) );
+ connect( m_widgets->clearLog, SIGNAL( clicked( ) ), this, SLOT( clearLogButton( ) ) );
+ connect( m_widgets->saveLog, SIGNAL( clicked( ) ), this, SLOT( saveLogButton( ) ) );
+ connect( m_updateTimer, SIGNAL( timeout() ), this, SLOT( updateTimeout( ) ) );
+ connect( m_widgets->messageType, SIGNAL( currentIndexChanged ( const int ) ), this, SLOT( messageTypeIndexChanged( const int ) ) );
+ connect( m_widgets->clearMessages, SIGNAL( clicked() ), this, SLOT( slotClearMessages() ) );
+ connect( m_widgets->messageHistory, SIGNAL( clicked() ), this, SLOT( slotMessageHistory() ) );
+ connect( m_widgets->messageTargetUser, SIGNAL( editTextChanged( const QString& ) ), this, SLOT( messageTargetUserChanged() ) );
+ connect( m_widgets->messageTargetUser, SIGNAL( currentIndexChanged( const QString& ) ), this, SLOT( messageTargetUserChanged() ) );
+ connect( m_widgets->clearMessageButton, SIGNAL( clicked() ), this, SLOT( slotClearMessageText() ) );
+ m_widgets->sendMessage->setDefault( true );
+
+ m_widgets->messageType->clear();
+ m_widgets->messageType->insertItem( 0, "Message" );
+ m_widgets->messageType->insertItem( 1, "Source-Message" );
+
+ sendMessageToUserAction = new QAction( i18n("Send Message"), this );
+ connect( sendMessageToUserAction, SIGNAL( triggered() ), this, SLOT( sendMessageToUser() ) );
+ sendMessageToUserAction->setToolTip( i18n("Send a text-message to the selected user.") );
+
+ sendAnswerAction = new QAction( i18n("Answer"), this );
+ connect( sendAnswerAction, SIGNAL( triggered() ), this, SLOT( sendAnswerMessage() ) );
+ sendAnswerAction->setToolTip( i18n("Send an answer to this message.") );
+
+ disconnectFromServerAction = new QAction( i18n("Disconnect"), this );
+ connect( disconnectFromServerAction, SIGNAL( triggered() ), this, SLOT( disconnectFromServer() ) );
+ disconnectFromServerAction ->setToolTip( i18n("Disconnect from the selected server.") );
+
+ disconnectAllServersAction = new QAction( i18n("Disconnect All"), this );
+ connect( disconnectAllServersAction, SIGNAL( triggered() ), this, SLOT( disconnectAllServers() ) );
+ disconnectAllServersAction->setToolTip( i18n("Disconnect from all connected servers.") );
+
+ kickClientAction = new QAction( i18n("Kick"), this );
+ connect( kickClientAction, SIGNAL( triggered() ), this, SLOT( kickClient() ) );
+ kickClientAction->setToolTip( i18n("Kick the selected client.") );
+
+ banClientAction = new QAction( i18n("Ban"), this );
+ connect( banClientAction, SIGNAL( triggered() ), this, SLOT( banClient() ) );
+ banClientAction->setToolTip( i18n("Ban the selected client (stop him from reconnecting).") );
+
+ kickAllClientsAction = new QAction( i18n("Disconnect All"), this );
+ connect( kickAllClientsAction, SIGNAL( triggered() ), this, SLOT( kickAllClients() ) );
+ kickAllClientsAction->setToolTip( i18n("Disconnect all connected clients from the local server.") );
+
+ m_userInfoAction = new QAction( i18n("User Info"), this );
+ connect( m_userInfoAction, SIGNAL( triggered() ), this, SLOT( uiUserInfo() ) );
+ m_userInfoAction->setToolTip( i18n("Show information about the user.") );
+
+ showPatchesAction = new QAction( i18n("Show Patches"), this );
+ connect( showPatchesAction, SIGNAL( triggered() ), this, SLOT( uiShowPatches() ) );
+ showPatchesAction->setToolTip( i18n("Show the available patches published by the selected user.") );
+
+ connect( m_messageManager.data(), SIGNAL( messageUpdated( const MessagePointer& ) ), this, SLOT( messageUpdated( const MessagePointer& ) ) );
+
+ emit init();
+
+ setActive( false );
+ m_updateAnswerTimer->start( 1000 );
+}
+
+KDevTeamwork::~KDevTeamwork() {
+ emit deInit();
+ delete m_updateTimer;
+ delete m_updateAnswerTimer;
+ delete m_replyWaitingTimeout;
+
+ if ( TeamworkClientPointer::Locked l = m_client ) {
+
+ l->invalidateTeamwork();
+ } else {
+ ///error
+ kDebug(9500) << "error while destruction of KDevTeamwork: could not lock client-pointer. Client cannot be destroyed.";
+ }
+
+ m_logger.lock() ->invalidate();
+ new LaterDeleter( m_client );
+ m_destroyed = true;
+}
+
+KDevTeamworkPlugin *KDevTeamwork::plugin() const {
+ return m_plugin;
+}
+
+KDevTeamworkUserPointer KDevTeamwork::currentTabUser() {
+ if ( !m_widget )
+ return 0;
+
+ QWidget* c = m_widgets->messageUsers->currentWidget();
+
+ for ( QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.begin(); it != m_userTabs.end(); ++it ) {
+ if ( ( *it ) ->widget() == c ) {
+ return ( *it ) ->user();
+ }
+ }
+
+ return 0;
+}
+
+void KDevTeamwork::slotClearMessageText() {
+ m_widgets->messageText->clear();
+}
+
+void KDevTeamwork::slotClearMessages() {
+ KDevTeamworkUserPointer current = currentTabUser();
+ if ( !current ) {
+ m_messagesModel->clear();
+ m_messagesModel->insertColumn( 0 );
+ } else {
+ m_userTabs.remove( current );
+ }
+}
+
+void KDevTeamwork::slotMessageHistory() {
+ KDevTeamworkUserPointer current = currentTabUser();
+ if ( !current ) {
+ m_messageManager->showMessageHistory();
+ } else {
+ QList<KDevTeamworkUserPointer> lst;
+ lst << current;
+ m_messageManager->showMessageHistory( lst );
+ }
+}
+
+bool KDevTeamwork::setActive( bool active ) {
+ cout << globalMessageTypeSet().stats();
+ if ( !m_active && active ) {
+ log( "GUI: starting collaboration" );
+ ///start the client
+ m_client = new KDevTeamworkClient( this );
+ {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ l->insertUserSet( m_persistentUsers );
+ } else {
+ log( "could not lock fresh created KDevTeamworkClient", Error );
+ }
+ }
+ m_client.unsafe() ->start();
+
+ allowIncomingChanged( m_widgets->allowIncoming->checkState() );
+ } else if ( m_client && !active ) {
+ ///close the client
+ log( "GUI: stopping collaboration" );
+ {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ l->getUserSet( m_persistentUsers );
+ l->invalidateTeamwork();
+ }
+ }
+ m_client = 0;
+ m_serversModel->clear();
+ m_serversModel->insertColumn( 0 );
+ m_developersModel->clear();
+ m_developersModel->insertColumn( 0 );
+ m_clientsModel->clear();
+ m_clientsModel->insertColumn( 0 );
+ m_widgets->messageTargetUser->clear();
+ m_actionMessage = 0;
+ }
+ m_active = active;
+
+ emit updateConnection( m_client );
+
+ enableActiveGUI( m_active );
+ m_updateAnswerTimer->start();
+
+ return m_active;
+}
+
+void KDevTeamwork::updateMessageInfo( MessagePointer msg ) {
+ if( m_destroyed ) return;
+
+ log( "updateMessageInfo", Debug );
+ messageManager() ->updateMessage( msg );
+}
+
+bool KDevTeamwork::setServerActive( bool active ) {
+ m_serverActive = active;
+ return m_serverActive;
+}
+
+void KDevTeamwork::documentActivated( KDevelop::IDocument* file ) {
+ Q_UNUSED( file );
+}
+
+void KDevTeamwork::popupContextMenu( const QPoint &pos ) {
+ Q_UNUSED( pos );
+}
+
+void KDevTeamwork::allowIncomingChanged( int state ) {
+ if ( TeamworkClientPointer::Locked l = m_client ) {
+ switch ( state ) {
+ case Qt::Checked:
+ l->allowIncoming( true );
+ break;
+ case Qt::Unchecked:
+ l->allowIncoming( false );
+ break;
+ }
+ } else {
+ err( "cannot lock client" );
+ }
+}
+
+void KDevTeamwork::enableCollaborationChanged( int state ) {
+ switch ( state ) {
+ case Qt::Checked:
+ setActive( true );
+ break;
+ case Qt::Unchecked:
+ setActive( false );
+ break;
+ }
+}
+
+void KDevTeamwork::uiFilterLog() {
+ QAction * action = qobject_cast<QAction*>( sender() );
+ LogLevel level = ( LogLevel ) action->data().toInt();
+
+ if ( action->isChecked() )
+ m_currentLogFilter = ( LogLevel ) ( m_currentLogFilter | level );
+ else
+ m_currentLogFilter = ( LogLevel ) ( m_currentLogFilter ^ level );
+
+ filterLog();
+}
+
+void KDevTeamwork::filterLog( int max ) {
+ int count = m_logModel->rowCount();
+ if ( max != 0 && count > max )
+ count = max;
+ for ( int a = 0; a < m_logModel->rowCount(); a++ ) {
+ QModelIndex i = m_logModel->index( a, 0 );
+ if ( i.isValid() ) {
+ QVariant v = m_logModel->data( i , Qt::UserRole );
+ LogLevel lv = ( LogLevel ) v.toInt();
+ m_widgets->logList->setRowHidden( a, !( bool ) ( lv & m_currentLogFilter ) );
+ }
+ }
+}
+
+void KDevTeamwork::uiShowPatches() {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ return ;
+
+ QVariant v = act->data();
+ if ( !v.canConvert<UserPointer>() ) {
+ err( "uiShowPatches: Cannot convert to UserPointer" );
+ return ;
+ }
+ UserPointer::Locked user = v.value<UserPointer>();
+ if ( !user || ! user->online().session() ) {
+ err( "failed to lock user in uiShowPatches or user is not online" );
+ return ;
+ }
+
+ globalMessageSendHelper().send<PatchesManagerMessage>( user->online().session().unsafe(), PatchesManagerMessage::GetPatchesList );
+}
+
+void KDevTeamwork::showUserInfo( const UserPointer& user ) {
+ try {
+ if ( !user )
+ throw QString( "no user given" );
+
+ UserPointer::Locked l = user;
+ if ( !l )
+ throw QString( "could not lock user" );
+
+ if ( !l.freeCast<KDevTeamworkUser>() )
+ throw QString( "bad user-type" );
+
+ KDialog* d = new KDialog( m_widget );
+ d->setAttribute( Qt::WA_DeleteOnClose, true );
+ KDevTeamworkUserInfoShower( l.freeCast<KDevTeamworkUser>(), d->mainWidget(), this );
+ d->show();
+ } catch ( QString str ) {
+ log( "error in showUserInfo:" + str, Error );
+ }
+
+}
+
+void KDevTeamwork::uiUserInfo() {
+ try {
+ UserPointer u = sendingUser();
+ if ( !u )
+ throw QString( "could not get sending-user" );
+
+ showUserInfo( u );
+ } catch ( QString str ) {
+ log( "error in uiUserInfo:" + str, Error );
+ }
+}
+
+void KDevTeamwork::connectionRequest( ConnectionRequestPointer request ) {
+ log( "got collaboration-request" );
+ addReceivedMessageToList( request );
+}
+
+void KDevTeamwork::connectServer() {
+ if ( !m_active )
+ return ;
+ QString txt = m_widgets->serverBox->currentText();
+ if ( !txt.isEmpty() ) {
+ log( "UI: connecting to server " + txt );
+ if ( m_client ) {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ kDebug(9500) << "connecting to \"" << toQ( stringToAddr( txt ) ) << "\":" << stringToPort( txt );
+
+ QString userName = m_widgets->loginName->text();
+
+ QString password = m_widgets->loginPassword->text();
+
+ UserPointer user;
+ if ( !userName.isEmpty() )
+ user = new User( userName.toUtf8().data(), password.toUtf8().data(), "a user" );
+ else
+ user = l->identity();
+ if ( user ) {
+ l->setIdentity( user );
+ l->connectToServer( ServerInformation( stringToAddr( txt ), stringToPort( txt ) ), user );
+ } else
+ err( "cannot connect to a server without having an identity" );
+ } else {
+ err( "could not lock client-thread" );
+ }
+ } else {
+ err( "error: client is not running" );
+ }
+ } else {
+ err( "UI: cannot connect to unidentified server" );
+ }
+}
+
+UserIdentity KDevTeamwork::currentUserIdentity() {
+ TeamworkClientPointer::Locked l = m_client;;
+ if( l ) {
+ UserPointer u = l->identity();
+ if( UserPointer::Locked lu = u ) {
+ return lu->identity();
+ }
+ }
+ return UserIdentity();
+}
+
+
+void KDevTeamwork::log( const QString & str, LogLevel level ) {
+ ///@todo assign an icon for each log-level, maybe allow filtering by level, and add a "clear-log" button
+ if( m_destroyed ) return;
+ //if( level == Debug ) return;
+ m_logModel->insertRow( 0 );
+ QModelIndex i = m_logModel->index( 0, 0 );
+ //m_logModel->insertColumn( 0, i );
+ QIcon icon;
+ ///choose an icon using the level
+ icon = iconFromLevel( level );
+
+ m_logModel->setData( i, str, Qt::DisplayRole );
+
+ QVariant lv( level );
+ m_logModel->setData( i, lv, Qt::UserRole );
+ m_logModel->setData( i, icon, Qt::DecorationRole );
+
+ /*if( ! (level & m_currentLogFilter) )
+ m_widgets->logList->setRowHidden( 0 , true );*/
+
+ filterLog( 3 );
+ //kDebug(9500) << "log: \"" << str << "\" level:" << level;
+}
+
+void KDevTeamwork::err( const QString& str ) {
+ if( m_destroyed ) return;
+ log( str, Error );
+}
+
+///Starts the update-timer for the developer-lists
+void KDevTeamwork::startUpdateTimer() {
+ if( m_destroyed ) return;
+ m_updateTimer->start( 300 );
+}
+
+TeamworkClientPointer& KDevTeamwork::client() {
+ return m_client;
+}
+PatchesManager* KDevTeamwork::patchesManager();
+
+CollaborationManager* KDevTeamwork::collaborationManager() {
+ return m_collaborationManager;
+}
+
+LoggerPointer KDevTeamwork::logger() {
+ return m_logger;
+}
+
+void KDevTeamwork::enableActiveGUI( bool active ) {
+ m_widgets->connectionTab->setEnabled( active );
+ m_widgets->availableLabel->setEnabled( active );
+ m_widgets->connectedLabel->setEnabled( active );
+ m_widgets->availableDevelopers->setEnabled( active );
+ m_widgets->connectedDevelopers->setEnabled( active );
+
+ enableMessageGUI( active );
+ if ( !active ) {
+ ///empty list of connected and available developers
+ }
+}
+
+void KDevTeamwork::enableMessageGUI( bool active ) {
+ m_widgets->messaging->setEnabled( active );
+}
+
+KDevTeamworkLogger::KDevTeamworkLogger( KDevTeamwork* tw ) : m_teamwork( tw ) {
+ // connect( this, SIGNAL( guiLog( QString, int ) ), m_teamwork, SLOT( guiLog( QString, int) ), Qt::QueuedConnection );
+}
+
+void KDevTeamworkLogger::log( const std::string& str , Level lv ) {
+ if ( m_teamwork ) {
+ LogLevel level;
+ switch ( lv ) {
+ case Info:
+ level = ::Info;
+ break;
+ case Warning:
+ level = ::Warning;
+ break;
+ case Error:
+ level = ::Error;
+ break;
+ case Debug:
+ level = ::Debug;
+ break;
+ default:
+ return ;
+ }
+
+ kDebug(9500) << "log-level: \"" << ~levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"";
+ QMetaObject::invokeMethod( m_teamwork, "guiLog", Qt::QueuedConnection, Q_ARG( QString, toQ( str ) ), Q_ARG( int, level ) );
+ } else {
+ kDebug(9500) << "log-level: \"" << ~levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"";
+ }
+}
+
+void KDevTeamworkLogger::safeErrorLog( const std::string& str, Level lv ) {
+
+ cout << levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"" << endl;
+}
+
+void KDevTeamwork::guiUserConnected( Teamwork::UserPointer user ) {
+ startUpdateTimer();
+
+ UserPointer::Locked l = user;
+ if ( !l ) {
+ err( "error" );
+ return ;
+ }
+ QString name = toQ( l->name() );
+
+ QStandardItemModel* model = m_clientsModel;
+ model->insertRow( 0 );
+ QModelIndex i = model->index( 0, 0 );
+
+ model->setData( i, name, Qt::DisplayRole );
+ QVariant v;
+ v.setValue( user );
+ model->setData( i, v, Qt::UserRole );
+
+ addDeveloper( user );
+}
+
+void KDevTeamwork::guiUserDisconnected( Teamwork::UserPointer user ) {
+ if( m_destroyed ) return;
+ startUpdateTimer();
+
+ UserPointer::Locked l = user;
+ if ( !l ) {
+ err( "failed to lock user-pointer" );
+ return ;
+ }
+
+ QString name = toQ( l->name() );
+
+ QStandardItemModel* model = m_clientsModel;
+ for ( int a = 0; a < model->rowCount(); a++ ) {
+ QModelIndex i = model->index( a, 0 );
+ QVariant v = model->data( i, Qt::DisplayRole );
+ if ( v.type() == QVariant::String ) {
+ if ( v.toString() == name ) {
+ model->removeRow( a );
+ }
+ }
+ }
+
+ ///remove the user from the target-user-list in the messaging-tab
+ QVariant v;
+ v.setValue( user );
+ int i = m_widgets->messageTargetUser->findData( v );
+ if ( i != -1 )
+ m_widgets->messageTargetUser->removeItem( i );
+
+
+ //kDebug(9500) << "disconnecting user is not in list:" << name;
+}
+
+void KDevTeamwork::guiServerConnected( Teamwork::ClientSessionDesc /*session*/, Teamwork::ServerInformation server ) {
+ if( m_destroyed ) return;
+ startUpdateTimer();
+
+ QString desc = toQ( server.desc() );
+
+ QStandardItemModel* model = m_serversModel;
+ model->insertRow( 0 );
+ QModelIndex i = model->index( 0, 0 );
+
+ model->setData( i, desc, Qt::DisplayRole );
+ QVariant v;
+ v.setValue( server );
+ model->setData( i, v, Qt::UserRole );
+}
+
+void KDevTeamwork::guiServerDisconnected( Teamwork::ClientSessionDesc /*session*/, Teamwork::ServerInformation server ) {
+ if( m_destroyed ) return;
+ startUpdateTimer();
+
+ QStandardItemModel* model = m_serversModel;
+
+ QString desc = toQ( server.desc() );
+
+ for ( int a = 0; a < model->rowCount(); a++ ) {
+ QModelIndex i = model->index( a, 0 );
+ QVariant v = model->data( i, Qt::DisplayRole );
+ if ( v.type() == QVariant::String ) {
+ if ( v.toString() == desc ) {
+ model->removeRow( a );
+ return ;
+ }
+ }
+ }
+
+ kDebug(9500) << "disconnecting server is not in list:" << desc;
+}
+
+QIcon KDevTeamwork::iconFromUser( User* user, KIconLoader::Group size ) {
+ KDevTeamworkUserPointer::Locked u( dynamic_cast<KDevTeamworkUser*>( user ) );
+ if ( !u )
+ return m_icons->getIcon( "remove", size );
+ return u->icon( size );
+}
+
+
+void KDevTeamwork::updateTimeout() {
+ if( m_destroyed ) return;
+
+ //log( "update-timer", Debug );
+ QStandardItemModel * model = m_developersModel;
+
+ for ( int a = model->rowCount() - 1; a >= 0; a-- ) {
+ QModelIndex i = model->index( a, 0 );
+ QVariant v = model->data( i, Qt::UserRole );
+ //QVariant v2 = model->data( i, Qt::DecorationRole );
+ QIcon icon;
+ /*Ü if( v2.canConvert<QIcon>() )
+ icon = v2.value<QIcon>();*/
+
+ if ( v.canConvert<UserPointer>( ) ) {
+ UserPointer p = v.value<UserPointer>();
+ UserPointer::Locked l = p;
+ if ( l ) {
+ SessionPointer s = l->online().session();
+
+ if ( s && s.unsafe() ->isOk() ) {
+ icon = iconFromUser( l, KIconLoader::Toolbar );
+ } else {
+ model->removeRow( a );
+ continue;
+ }
+
+ } else {
+ err( "user-pointer contained in developer-list could not be locked" );
+ icon = m_icons->getIcon( "filecose", KIconLoader::Toolbar );
+ }
+ } else {
+ err( "wrong data in the developers-list" );
+ icon = m_icons->getIcon( "filecose", KIconLoader::Toolbar );
+ }
+ model->setData( i, icon, Qt::DecorationRole );
+ }
+
+ QComboBox* cb = m_widgets->messageTargetUser;
+
+ for ( int a = cb->count(); a >= 0; a-- ) {
+ QVariant v = m_widgets->messageTargetUser->itemData( a );
+ if ( v.canConvert<UserPointer>() ) {
+ UserPointer::Locked lu = v.value<UserPointer>();
+ m_widgets->messageTargetUser->setItemData( a, iconFromUser( lu ), Qt::DecorationRole );
+ }
+ }
+
+ m_collaborationManager->updateList();
+
+ m_updateTimer->start( 3000 );
+}
+
+void KDevTeamwork::addDeveloper( const Teamwork::UserPointer& u ) {
+ QStandardItemModel * model = m_developersModel;
+
+ UserPointer::Locked l = u;
+ if ( l ) {
+ model->insertRow( 0 );
+ QModelIndex i = model->index( 0, 0 );
+
+ //log("adding user " + toQ( l->name() ) + " to list" );
+ model->setData( i, toQ( l->name() ), Qt::DisplayRole );
+
+ QVariant v;
+ v.setValue<UserPointer>( u );
+ model->setData( i, v, Qt::UserRole );
+ model->setData( i, iconFromUser( l ), Qt::DecorationRole );
+
+ } else {
+ err( "could not lock a user-pointer from a received list" );
+ }
+}
+
+void KDevTeamwork::registerPatches( PatchesListMessage* msg, QStandardItemModel* model ) {
+ SessionPointer::Locked lsession = msg->info().session();
+ log( "handing patches-list", Debug );
+
+ try {
+ if ( !lsession )
+ throw "no session";
+ UserPointer::Locked luser = lsession->safeUser();
+ if ( !luser )
+ throw "could not lock user, or wrong data in session";
+
+ QModelIndex i = findInModelNormal( model, ( UserPointer ) luser );
+ if ( i.isValid() ) {
+ if ( model->columnCount( i ) == 0 )
+ model->insertColumns( 0, 1, i );
+ else
+ model->removeRows( 0, model->rowCount( i ), i );
+
+ for ( list<LocalPatchSource>::iterator it = msg->patches.begin(); it != msg->patches.end(); ++it ) {
+ LocalPatchSourcePointer source = new LocalPatchSource( *it );
+ source.unsafe() ->setUser( luser );
+ QModelIndex ind = findInModel<LocalPatchSourcePointer, LocalPatchSourcePointer::ValueIdentCompare>( model, source, i );
+ if ( ind.isValid() )
+ model->removeRows( ind.row(), 1, i );
+
+ model->insertRows( 0, 1, i );
+ QModelIndex index = model->index( 0, 0, i );
+ model->setData( index, ~( *it ).name );
+ model->setData( index, ( *it ).getIcon( *m_icons ), Qt::DecorationRole );
+ QVariant v;
+ v.setValue<LocalPatchSourcePointer>( source );
+ model->setData( index, v, Qt::UserRole );
+ }
+ } else {
+ //throw "could not find the user in the developers-list";
+ }
+ } catch ( const char * str ) {
+ err( QString( "in handlePatchesList: " ) + str );
+ }
+}
+
+void KDevTeamwork::handlePatchesList( PatchesListMessage* msg ) {
+ registerPatches( msg, m_developersModel );
+ registerPatches( msg, m_collaborationManager->developersModel() );
+}
+
+void KDevTeamwork::guiUserList( std::list<UserPointer> users ) {
+
+ //log( QString("guiUserList : handling user-list of size %1").arg( users.size() ) );
+
+ for ( std::list<UserPointer>::iterator it = users.begin(); it != users.end(); ++it ) {
+ addDeveloper( *it );
+ }
+}
+
+void KDevTeamwork::fillUserMenu( QMenu* menu, const UserPointer& user ) {
+ UserPointer::Locked luser = user;
+ if ( luser && luser->online() ) {
+ QVariant v;
+ v.setValue( user );
+
+ sendMessageToUserAction->setData( v );
+ menu->addAction( sendMessageToUserAction );
+
+ showPatchesAction->setData( v );
+ //menu->addAction( showPatchesAction );
+ m_collaborationManager->fillUserMenu( menu, user );
+ m_userInfoAction->setData( v );
+ menu->addAction( m_userInfoAction );
+ }
+}
+
+void KDevTeamwork::fillMessageMenu( QMenu* menu, const MessagePointer& msg ) {
+ MessagePointer::Locked l = msg;
+ if ( l->info().session() && l->info().session().unsafe() ->isOk() && l->info().isIncoming() ) {
+ QVariant v;
+ v.setValue( msg );
+ sendAnswerAction->setData( v );
+ menu->addAction( sendAnswerAction );
+ }
+}
+
+void KDevTeamwork::sendAnswerMessage() {
+ MessagePointer::Locked msg = sendingMessage();
+ if ( msg ) {
+ guiSendMessageTo( msg->info().user(), msg );
+ } else {
+ log( "sendAnswerMessage: could not lock message to answer to ", Error );
+ }
+}
+
+void KDevTeamwork::sendMessageToUser() {
+ if ( sendingUser() )
+ QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, sendingUser() ) );
+}
+
+
+void KDevTeamwork::contextMenu( const QPoint& p, const QModelIndex& index ) {
+
+ if(!index.isValid() )
+ return;
+ QMenu menu;
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ fillUserMenu( &menu, v.value<UserPointer>() );
+ getPatchesList( v.value<UserPointer>() );
+
+ }
+
+ if ( v.canConvert<LocalPatchSourcePointer>() ) {
+ m_patchesManager->fillDeveloperActions( index, &menu );
+ }
+
+ menu.exec( p );
+}
+
+void KDevTeamwork::maybeDeveloperContextMenu() {
+ if ( m_contextMenuIndex.get() ) {
+ contextMenu( QCursor::pos(), *m_contextMenuIndex );
+ }
+}
+
+void KDevTeamwork::developerClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+
+ m_contextMenuIndex.reset( new QPersistentModelIndex( index ) );
+
+ QTimer::singleShot( 400, this, SLOT( maybeDeveloperContextMenu() ) );
+}
+
+void KDevTeamwork::developerContextMenu( const QPoint& p ) {
+
+ QModelIndex index = widgets().availableDevelopers->indexAt( p );
+ if ( !index.isValid() )
+ return ;
+
+ contextMenu( p, index );
+}
+
+void KDevTeamwork::getPatchesList( const UserPointer& user ) {
+ QVariant v;
+ v.setValue( user );
+ showPatchesAction->setData( v );
+ showPatchesAction->activate( QAction::Trigger );
+}
+
+void KDevTeamwork::developerDoubleClicked( const QModelIndex& index ) {
+ m_contextMenuIndex.reset( 0 );
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() )
+ QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, v.value<UserPointer>() ) );
+}
+
+void KDevTeamwork::serverClicked( const QModelIndex& index ) {
+ QMenu * menu = new QMenu( m_widget );
+
+ if ( !index.isValid() )
+ return ;
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<ServerInformation>() ) {
+ UserPointer user;
+ ServerInformation p = v.value<ServerInformation>();
+ MultiSessionPointer sess = l->sessionToServer( p );
+
+ if ( sess )
+ user = l->findSessionUser( sess );
+ else
+ log( "no session to the server is open", Warning );
+
+ if ( !user )
+ log( "the server has no associated user, no message can be sent", Warning );
+ else
+ fillUserMenu( menu, user );
+
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+ } else {
+ err( "could not lock the client-handler" );
+ }
+
+ menu->addAction( disconnectFromServerAction );
+ menu->addSeparator();
+ menu->addAction( disconnectAllServersAction );
+ menu->exec( QCursor::pos() );
+}
+
+void KDevTeamwork::serverDoubleClicked( const QModelIndex& index ) {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<ServerInformation>() ) {
+ UserPointer user;
+ ServerInformation p = v.value<ServerInformation>();
+ MultiSessionPointer::Locked sess = l->sessionToServer( p );
+ if ( sess )
+ user = l->findSessionUser( sess.cast<SessionInterface>().data() );
+ else
+ log( "no session to the server is open", Warning );
+
+ if ( !user )
+ log( "the server has no associated user, no message can be sent", Warning );
+ else
+ QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, user ) );
+ }
+ }
+}
+
+void KDevTeamwork:: messageClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+ QMenu menu( m_widget );
+
+ UserPointer user;
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert< MessagePointer >() ) {
+ MessagePointer::Locked l = v.value< MessagePointer >();
+ m_messageManager->fillMessageMenu( &menu, l );
+ } else {
+ err( "wrong information stored in the message-list-view" );
+ }
+
+ menu.exec( QCursor::pos() );
+}
+
+void KDevTeamwork::messageTargetUserChanged() {
+ m_updateAnswerTimer->start( 100 );
+}
+
+void KDevTeamwork::updateAnswerMenu() {
+ QMenu* menu = m_widgets->answeringToButton->menu();
+ if( menu == 0 ) menu = new QMenu( i18n( "Answer To" ), m_widget );
+ menu->clear();
+ KDevTeamworkUserPointer::Locked user = currentMessageTargetUser().cast<KDevTeamworkUser>();
+ if( !user ) return;
+
+ UserTabMap::iterator it = m_userTabs.find( user );
+ if( it != m_userTabs.end() ) {
+ QStandardItemModel* model = (*it)->model();
+ int maxSearch = model->rowCount();
+ if( maxSearch > 100 ) maxSearch = 100;
+ int count = 0;
+ for( int a = 0 ; a < maxSearch; a++ ) {
+ if( count > 10 ) break;
+ QModelIndex i = model->index( a, 0 );
+ if( i.isValid() ) {
+ MessagePointer::Locked m = model->data( i, Qt::UserRole ).value<MessagePointer>();
+ if( m ) {
+ KDevTeamworkTextMessage* tm = m.freeCast<KDevTeamworkTextMessage>();
+ AbstractGUIMessage* gm = m.freeCast<AbstractGUIMessage>();
+ if( gm && tm && m->info().isIncoming() && (!tm->answered() || m.data() == m_answerTo.unsafe() ) ) {
+ //gm->messageIcon()
+ QAction* a = new QAction( gm->messageText().left( 30 )+"...", menu );
+ QVariant v;
+ v.setValue<MessagePointer>( m );
+ a->setData( v );
+ a->setCheckable( true );
+ if( m.data() == m_answerTo.unsafe() ) a->setChecked( true );
+ menu->addAction( a );
+ connect( a, SIGNAL( toggled( bool ) ), this, SLOT( answerMenuToggled( bool ) ) );
+ connect( a, SIGNAL( triggered( bool ) ), this, SLOT( answerMenuTriggered( bool ) ) );
+ count++;
+ }
+ }
+ }
+ }
+ m_widgets->answeringToButton->setEnabled( model->rowCount() != 0 );
+ } else {
+ m_widgets->answeringToButton->setEnabled( false );
+ }
+ m_widgets->answeringToButton->setMenu( menu );
+}
+
+void KDevTeamwork::answerMenuToggled( bool state ) {
+ if( !m_widgets->answeringToButton->menu() ) return;
+ QAction* sender = qobject_cast<QAction*>( QObject::sender() );
+ QList<QAction*> actions = m_widgets->answeringToButton->menu()->findChildren<QAction*>();
+ ///Uncheck all except his one
+ for( QList<QAction*>::iterator it = actions.begin(); it != actions.end(); ++it ) {
+ if( *it != sender ) {
+ (*it)->setChecked( false );
+ }
+ }
+ if( !state ) {
+ m_answerTo = 0;
+ } else {
+ m_answerTo = sender->data().value<MessagePointer>();
+ }
+}
+
+void KDevTeamwork::answerMenuTriggered( bool ) {
+ MessagePointer m = sendingMessage();
+ if( !m ) return;
+ m_messageManager->showMessage( m );
+}
+
+void KDevTeamwork::messageDoubleClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+
+ UserPointer user;
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<MessagePointer>() ) {
+ MessagePointer::Locked l = v.value< MessagePointer >();
+ if ( l && l->info().session() ) {
+ UserPointer u = userFromSession( l->info().session() );
+ if ( u ) {
+ QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, u ) );
+ } else
+ log( "could not get user from message, or message has no session" );
+ } else {
+ err( "could not lock text-message from view" );
+ }
+ } else {
+ err( "wrong information stored in the message-list-view" );
+ }
+}
+
+void KDevTeamwork:: clientClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+
+ QMenu menu( m_widget );
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ fillUserMenu( &menu, v.value<UserPointer>() );
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+
+ menu.addSeparator();
+ menu.addAction( kickClientAction );
+ menu.addAction( banClientAction );
+ menu.addSeparator();
+ menu.addAction( kickAllClientsAction );
+ menu.exec( QCursor::pos() );
+}
+
+void KDevTeamwork:: clientDoubleClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, v.value<UserPointer>() ) );
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+}
+
+void KDevTeamwork::disconnectFromServer() {
+ QModelIndex index = m_widgets->connectedServers->currentIndex();
+ if ( !index.isValid() )
+ return ;
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<ServerInformation>() ) {
+ ServerInformation p = v.value<ServerInformation>();
+ l->disconnectFromServer( p );
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+ } else {
+ err( "could not lock the client-handler" );
+ }
+}
+
+void KDevTeamwork::disconnectAllServers() {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ l->disconnectAllServers();
+ } else {
+ err( "could not lock the client-handler" );
+ }
+}
+
+UserPointer KDevTeamwork::sendingUser() {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ return 0;
+
+ QVariant v = act->data();
+ if ( !v.canConvert<UserPointer>() ) {
+ return 0;
+ }
+ return v.value<UserPointer>();
+}
+
+MessagePointer KDevTeamwork::sendingMessage() {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ return 0;
+
+ QVariant v = act->data();
+ if ( !v.canConvert<MessagePointer>() ) {
+ return 0;
+ }
+ return v.value<MessagePointer>();
+}
+
+void KDevTeamwork::messageUpdated( const MessagePointer& msg ) {
+ try {
+ MessagePointer::Locked l = msg;
+ if ( !l )
+ throw QString( "could not lock a message to update" );
+
+ KDevTeamworkUserPointer user = l->info().user().cast<KDevTeamworkUser>();
+
+ if ( user ) {
+ UserTabMap::iterator it = m_userTabs.find( user );
+ if ( it != m_userTabs.end() ) {
+ ( *it ) ->messageUpdated( msg );
+ }
+ }
+
+ AbstractGUIMessage* guiMsg = l.freeCast<AbstractGUIMessage>();
+
+ if ( !guiMsg )
+ throw QString( "cannot update information for a non-gui-message" );
+
+ QPersistentModelIndex pi = guiMsg->data.value<QPersistentModelIndex>();
+ QModelIndex i( pi );
+
+ if ( !i.isValid() )
+ throw QString( "cannot update a message, the model-index is invalid" );
+
+ QAbstractItemModel* model = const_cast<QAbstractItemModel*>( i.model() );
+ model->setData( i, guiMsg->messageIcon(), Qt::DecorationRole ); ///The text is not updated right now
+ } catch ( QString str ) {
+ err( "in messageUpdated: " + str );
+ }
+}
+
+void KDevTeamwork::kickClient() {
+ QModelIndex index = m_widgets->connectedClients->currentIndex();
+ if ( !index.isValid() )
+ return ;
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ UserPointer p = v.value<UserPointer>();
+ UserPointer::Locked lu = p;
+ if ( lu ) {
+ if ( lu->online() ) {
+ l->closeSession( lu->online().session() );
+ } else {
+ err( "user to kick is not online" );
+ }
+ } else {
+ err( "could not lock user-pointer stored in the list-view" );
+ }
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+ } else {
+ err( "could not lock the client-handler" );
+ }
+}
+
+void KDevTeamwork::banClient() {
+ QModelIndex index = m_widgets->connectedClients->currentIndex();
+ if ( !index.isValid() )
+ return ;
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ UserPointer p = v.value<UserPointer>();
+ UserPointer::Locked lu = p;
+ if ( lu ) {
+ lu->ban( true );
+ if ( lu->online() ) {
+ l->closeSession( lu->online().session() );
+ } else {
+ err( "user to kick is not online" );
+ }
+ } else {
+ err( "could not lock user-pointer stored in the list-view" );
+ }
+ } else {
+ err( "wrong information stored in the list-view" );
+ }
+ } else {
+ err( "could not lock the client-handler" );
+ }
+}
+
+void KDevTeamwork::kickAllClients() {
+ TeamworkClientPointer::Locked l = m_client;
+ if ( l ) {
+ l->closeAllIncomingSessions();
+ } else {
+ err( "could not lock the client-handler" );
+ }
+}
+
+void KDevTeamwork::clearLogButton() {
+ m_logModel->clear();
+ m_logModel->insertColumn( 0 );
+}
+
+void KDevTeamwork::messageReplyTimeout() {
+ log( "messageReplyTimeout", Debug );
+ if( m_waitingForReply ) {
+ addMessageToList( new FailureMessage( "got no reply", m_waitingForReply ) );
+ unlockMessageGui();
+ }
+}
+
+void KDevTeamwork::lockMessageGui( const MessagePointer& msg ) {
+ //log( QString("lockMessageGui called, waiting for %1").arg( msg.unsafe() ), Debug );
+ m_waitingForReply = msg;
+ m_widgets->messageText->setEnabled( false );
+ m_widgets->clearMessageButton->setEnabled( false );
+ m_widgets->sendMessage->setEnabled( false );
+ m_replyWaitingTimeout->start( messageSendTimeout );
+}
+
+void KDevTeamwork::unlockMessageGui() {
+ log( "unlockMessageGui called", Debug );
+ m_waitingForReply = 0;
+ m_widgets->messageText->setEnabled( true );
+ m_widgets->clearMessageButton->setEnabled( true );
+ m_widgets->sendMessage->setEnabled( true );
+ m_replyWaitingTimeout->stop();
+}
+
+void KDevTeamwork::receiveMessage( SafeSharedPtr<KDevSystemMessage> msg ) {
+ SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
+ MessagePointer::Locked lv = m_waitingForReply;
+ if ( l ) {
+ if( m_waitingForReply == l->info().replyToMessage() ) {
+ if( l->message() == KDevSystemMessage::ActionSuccessful ) {
+ m_widgets->messageText->clear();
+ } else {
+ addMessageToList( new FailureMessage( QString( "could not send message: %1").arg( l->messageAsString() ), m_waitingForReply ) );
+ }
+ unlockMessageGui();
+ LockedSharedPtr<KDevTeamworkTextMessage> la = m_answerTo.cast<KDevTeamworkTextMessage>();
+ if( la ) {
+ la->setAnswered( true );
+ }
+ m_answerTo = 0;
+ m_updateAnswerTimer->start( 300 );
+ }
+
+ MessagePointer isReplyTo = l->info().replyToMessage();
+ switch ( l->message() ) {
+ case KDevSystemMessage::CollaborationAccepted: {
+ if ( !isReplyTo ) {
+ log( "got collaboration-accepted-message, but it was not requested", Warning );
+ break;
+ }
+ startUpdateTimer();
+ SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
+ log( "collaboration was accepted, reason: " + l->text() );
+ if ( l ) {
+ m_collaborationManager->addCollaboratingUser( userFromSession( l->info().session() ) );
+ } else {
+ log( "could not lock a KDevSystemMessage" );
+ }
+ break;
+ }
+ case KDevSystemMessage::CollaborationRefused:
+ log( "collaboration was refused, reason: " + l->text() );
+ break;
+ case KDevSystemMessage::CollaborationClosed: {
+ log( "peer stopped collaboration" );
+ SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
+ if ( l ) {
+ m_collaborationManager->removeCollaboratingUser( userFromSession( l->info().session() ) );
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+void KDevTeamwork::addSentMessageToList( const MessagePointer& smsg ) {
+ ///Put the message into the "All Users"-tab
+ addSentMessageToList( smsg, m_messagesModel );
+
+ ///Also put the message into the user-tab
+ MessagePointer::Locked msg = smsg;
+ if ( msg ) {
+ UserPointer::Locked lu = userFromSession( msg->info().session() );
+ if ( lu ) {
+ QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.find( lu.freeCast<KDevTeamworkUser>() );
+ if ( it != m_userTabs.end() ) {
+ addSentMessageToList( smsg, ( *it ) ->model() );
+ } else {
+ m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] = new MessageUserTab( this, lu.freeCast<KDevTeamworkUser>() );
+ addSentMessageToList( smsg, m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] ->model() );
+ }
+ } else {
+ log( "failed to lock user", Error );
+ }
+ } else {
+ log( "failed to lock message", Error );
+ }
+}
+
+void KDevTeamwork::addMessageToList( const MessagePointer& smsg ) {
+ MessagePointer::Locked l = smsg;
+ if( l ) {
+ if( l->info().isIncoming() ) {
+ addReceivedMessageToList( smsg );
+ } else {
+ addSentMessageToList( smsg );
+ }
+ } else {
+ err( "addMessageToList: could not lock message" );
+ }
+}
+
+void KDevTeamwork::addSentMessageToList( const MessagePointer& smsg, QStandardItemModel* model ) {
+ MessagePointer::Locked msg = smsg;
+ if ( msg ) {
+
+ AbstractGUIMessage * guiMsg = msg.freeCast<AbstractGUIMessage>();
+ if ( !guiMsg ) {
+ err( "cannot add non-gui-message to list" );
+ return ;
+ }
+ model->insertRow( 0 );
+ QModelIndex i = model->index( 0, 0 );
+
+ if ( model == m_messagesModel )
+ guiMsg->data.setValue( QPersistentModelIndex( i ) );
+
+ QString toUser, text = guiMsg->messageText();
+
+ UserPointer p = msg->info().user();
+ if ( p ) {
+ UserPointer::Locked lp = p;
+ if ( lp ) {
+ toUser = ~lp->name();
+ } else {
+ toUser = "not-lockable-user";
+ }
+ } else {
+ toUser = "not-connected-user";
+ }
+
+ if ( model != m_messagesModel ) {
+ text = text;
+ } else {
+ text = toUser + ": \"" + text + "\"";
+ }
+
+ model->setData( i, text, Qt::DisplayRole );
+ model->setData( i, guiMsg->messageIcon() , Qt::DecorationRole );
+
+ ///The whole message is stored, including all its information. That may become a problem, since it keeps references to all involved sessions.
+
+ QVariant v;
+ v.setValue( smsg );
+ model->setData( i, v, Qt::UserRole );
+
+ } else {
+ err( "could not lock incoming kdev-text-message" );
+ }
+ m_updateAnswerTimer->start( 300 );
+}
+
+void KDevTeamwork::addReceivedMessageToList( const MessagePointer& smsg ) {
+ ///Put the message into the "All Users"-tab
+ addReceivedMessageToList( smsg, m_messagesModel );
+
+ ///Also put the message into the user-tab
+ MessagePointer::Locked msg = smsg;
+ if ( msg ) {
+ UserPointer::Locked lu = userFromSession( msg->info().session() );
+ if ( lu ) {
+ QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.find( lu.freeCast<KDevTeamworkUser>() );
+ if ( it != m_userTabs.end() ) {
+ addReceivedMessageToList( smsg, ( *it ) ->model() );
+ } else {
+ m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] = new MessageUserTab( this, lu.freeCast<KDevTeamworkUser>() );
+ addReceivedMessageToList( smsg, m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] ->model() );
+ }
+ } else {
+ log( "failed to lock user", Error );
+ }
+ } else {
+ log( "failed to lock message", Error );
+ }
+}
+
+void KDevTeamwork::addReceivedMessageToList( const MessagePointer& smsg, QStandardItemModel* model ) {
+ MessagePointer::Locked msg = smsg;
+ if ( msg ) {
+ AbstractGUIMessage * guiMsg = msg.freeCast<AbstractGUIMessage>();
+
+ if ( !guiMsg ) {
+ err( "cannot add non-gui-message to list" );
+ return ;
+ }
+
+ model->insertRow( 0 );
+ QModelIndex i = model->index( 0, 0 );
+
+ if ( model == m_messagesModel )
+ guiMsg->data.setValue( QPersistentModelIndex( i ) );
+
+ QString fromUser, text = guiMsg->messageText();
+
+ UserPointer p = msg->info().user();
+ if ( p ) {
+ UserPointer::Locked lp = p;
+ if ( lp ) {
+ fromUser = toQ( lp->name() );
+ } else {
+ fromUser = "not-lockable-user";
+ }
+ } else {
+ fromUser = "missing-user-info";
+ }
+
+ if ( model != m_messagesModel ) {
+ text = text;
+ } else {
+ text = fromUser + ": \"" + text + "\"";
+ }
+
+ model->setData( i, text, Qt::DisplayRole );
+ model->setData( i, guiMsg->messageIcon() , Qt::DecorationRole );
+
+ ///The whole message is stored, including all its information. That may become a problem, since it keeps references to all sessions.
+
+ QVariant v;
+ v.setValue( smsg );
+ model->setData( i, v, Qt::UserRole );
+
+ } else {
+ err( "could not lock incoming kdev-text-message" );
+ }
+ m_updateAnswerTimer->start( 300 );
+}
+
+void KDevTeamwork::saveLogButton() {
+ ///open a save-dialog and store the content of logModel to a file
+ log( "not implemented yet", Warning );
+}
+
+void KDevTeamwork::guiSendMessageTo( const UserPointer& user, const MessagePointer& answerTo ) {
+ UserPointer::Locked lu = user;
+ if ( lu ) {
+ m_answerTo = answerTo;
+
+ m_widgets->toolBox->setCurrentWidget( m_widgets->messaging );
+ int item = -1;
+ QVariant v;
+ for ( int a = 0; a < m_widgets->messageTargetUser->count(); a++ ) {
+ v = m_widgets->messageTargetUser->itemData( a );
+ if ( v.canConvert<UserPointer>() ) {
+ if ( v.value<UserPointer>() == user ) {
+ item = a;
+ break;
+ }
+ }
+ }
+ v.setValue( user );
+ if ( item == -1 ) {
+ m_widgets->messageTargetUser->insertItem( 0, toQ( lu->name() ), v );
+ m_widgets->messageTargetUser->setItemData( 0, iconFromUser( lu ), Qt::DecorationRole );
+ item = 0;
+ } else {}
+ m_widgets->messageTargetUser->setCurrentIndex( item );
+
+ m_widgets->messageType->setCurrentIndex( NormalMessage );
+
+ if ( LockedSharedPtr<InDocumentMessage> l = answerTo.cast<InDocumentMessage>() ) {
+ m_widgets->messageType->setCurrentIndex( DocumentMessage );
+ m_widgets->context->setText( l->context() );
+ m_widgets->reference->clear();
+ }
+ m_widgets->messageText->clear();
+ } else {
+ err( "could not lock user-pointer stored in the list-view" );
+ }
+
+ startUpdateTimer();
+}
+
+void KDevTeamwork::messageTypeIndexChanged( const int index ) {
+ if( m_destroyed ) return;
+
+ switch ( index ) {
+ case Message:
+ m_widgets->reference->hide();
+ m_widgets->referenceLabel->hide();
+ m_widgets->contextLabel->hide();
+ m_widgets->context->hide();
+ break;
+ case SourceMessage:
+ m_widgets->reference->show();
+ m_widgets->referenceLabel->show();
+ m_widgets->contextLabel->show();
+ m_widgets->context->show();
+ break;
+ };
+}
+
+UserPointer KDevTeamwork::currentMessageTargetUser() {
+ UserPointer user;
+ if ( m_widgets->messageTargetUser->currentIndex() != -1 ) {
+ QVariant v = m_widgets->messageTargetUser->itemData( m_widgets->messageTargetUser->currentIndex() );
+ if ( v.canConvert<UserPointer>() )
+ user = v.value<UserPointer>();
+ }
+ QString uname = m_widgets->messageTargetUser->currentText();
+ if ( ( !user && uname.isEmpty() ) )
+ return 0;
+ if ( !user ) {
+ TeamworkClientPointer::Locked l = m_client;
+ if( !l )
+ return 0;
+ else
+ return l->findUser( UserIdentity( uname.toUtf8().data() ) );
+ }
+
+ return user;
+}
+
+void KDevTeamwork::sendMessageButton() {
+ //QString txt = m_widgets->messageText->toHtml();
+ QString txt = m_widgets->messageText->toPlainText();
+
+ MessagePointer::Locked lmsg = m_answerTo;
+
+ //Allow sending empty messages, which is useful for text-references
+
+ UserPointer user = currentMessageTargetUser();
+ if( !user ) {
+ log( "sendMessageButton(): target-user not available", Error );
+ }
+
+ if ( lmsg ) {
+ if ( !( lmsg->info().user() == user ) )
+ m_answerTo = 0;
+ }
+
+ TeamworkClientPointer::Locked l = m_client;
+
+ if ( l ) {
+ UserPointer::Locked ul = user;
+ MessagePointer::Locked msg;
+ if ( user && ul && ul->online() ) {
+ switch ( m_widgets->messageType->currentIndex() ) {
+ case Message: {
+ msg = new KDevTeamworkTextMessage( l->messageTypes(), txt );
+ break;
+ }
+ case SourceMessage: {
+ QString docText;
+ InDocumentReference ref( true, m_widgets->reference->text() );
+ InDocumentReference endRef( false, m_widgets->reference->text() );
+ KUrl docUrl = TeamworkFolderManager::workspaceAbsolute( ref.document() );
+
+ IDocument* doc = KDevTeamworkPlugin::staticCore()->documentController()->documentForUrl( docUrl );
+
+ if ( doc && doc->textDocument() ) {
+ docText = doc->textDocument() ->text();
+ ref.useText( docText );
+ if( endRef )
+ endRef.useText( docText );
+ } else {
+ log( "the document " + docUrl.url() + " is not open, weak-reference can not be computed. A simple line- and column-reference is created", Warning );
+ }
+ log( QString("created reference for: (%1, %2) : (%3, %4)").arg( ref.line() ).arg( ref.col() ).arg( endRef.line() ).arg( endRef.col() ), Debug );
+
+ msg = new InDocumentMessage( l->messageTypes(), txt, ref, endRef, m_widgets->context->text() );
+ msg.cast<InDocumentMessage>()->setConversation( m_messageManager->conversationManager().getConversation(msg.cast<InDocumentMessage>()) );
+
+
+ InDocumentMessage* dmsg = msg.freeCast<InDocumentMessage>();
+ if ( dmsg ) {
+ msg.freeCast<InDocumentMessage>() ->contextLines() = DocumentContextLines( dmsg->start(), dmsg->end(), docText );
+ } else {
+ log( "error: could not build InDocumentMessage", Error );
+ }
+ break;
+ }
+ }
+ if ( msg ) {
+ if ( m_answerTo ) {
+ MessagePointer::Locked la = m_answerTo;
+ if ( la ) {
+ msg->info().setReply( la->info().uniqueId() );
+ msg->info().setReplyMessage( m_answerTo );
+ }
+ }
+
+ ul->online().session().unsafe() ->send( msg );
+ addSentMessageToList( msg );
+ switch ( m_widgets->messageType->currentIndex() ) {
+ case SourceMessage: {}
+ }
+
+ lockMessageGui( msg );
+ m_messageManager->processMessage( msg.cast<KDevTeamworkTextMessage>() );
+ } else {
+ err( "could not create the message for sending" );
+ }
+
+ } else {
+ if ( user && !ul )
+ err( "could not lock the user" );
+ if ( ul && !ul->online() )
+ err( "no open session to user " + ~ul->name() );
+ if ( !user )
+ err( "target-user not existing" );
+ err( "sending the message failed" );
+ }
+ } else {
+ err( "could not lock the client-handler while sending message" );
+ }
+}
+
+
+void KDevTeamwork::handleTextMessage( SafeSharedPtr<KDevTeamworkTextMessage> smsg ) {
+ LockedSharedPtr<KDevTeamworkTextMessage> msg = smsg;
+ if ( msg ) {
+ if ( !m_messageManager->processMessage( msg ) )
+ addReceivedMessageToList( smsg );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful );
+ } else {
+ err( "could not lock incoming kdev-text-message" );
+ }
+}
+
+void KDevTeamwork::restorePartialProjectSession( const QDomElement* el ) {
+ m_patchesManager->restorePartialProjectSession( el );
+ m_collaborationManager->restorePartialProjectSession( el );
+ m_messageManager->restorePartialProjectSession( el );
+}
+
+void KDevTeamwork::savePartialProjectSession( QDomElement* el ) {
+ m_patchesManager->savePartialProjectSession( el );
+ m_collaborationManager->savePartialProjectSession( el );
+ m_messageManager->savePartialProjectSession( el );
+}
+
+KDevTeamwork* KDevTeamwork::self() {
+ return m_self;
+}
+
+#include "kdevteamwork.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp (revision 1522570)
@@ -0,0 +1,165 @@
+/*
+ * This file is part of KDevelop
+ *
+ * Copyright 2006 Adam Treat <treat@kde.org>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "kdevteamworkplugin.h"
+#include "kdevteamwork.h"
+
+#include <QMenu>
+#include <QAction>
+#include <QToolButton>
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+
+#include <kaction.h>
+#include <klocale.h>
+#include <kmimetype.h>
+#include <kaboutdata.h>
+#include <kiconloader.h>
+#include <kpluginfactory.h>
+#include <kaboutdata.h>
+#include <kpluginloader.h>
+#include <interfaces/icore.h>
+#include <interfaces/iprojectcontroller.h>
+#include <interfaces/iproject.h>
+#include <interfaces/iuicontroller.h>
+
+// #include <kplugininfo.h>
+
+KDevTeamworkPlugin* KDevTeamworkPlugin::m_self = 0;
+
+K_PLUGIN_FACTORY(KDevTeamworkFactory, registerPlugin<KDevTeamworkPlugin>(); )
+K_EXPORT_PLUGIN(KDevTeamworkFactory(KAboutData("kdevteamwork","kdevteamwork", ki18n("Teamwork"), "0.1", ki18n("Collaboration support"), KAboutData::License_GPL)))
+
+
+class KDevTeamworkViewFactory : public KDevelop::IToolViewFactory
+{
+public:
+ KDevTeamworkViewFactory(KDevTeamworkPlugin *plugin): m_plugin(plugin) {}
+
+ virtual QWidget* create(QWidget *parent = 0)
+ {
+ QWidget* view = new QWidget(parent);
+ view->setObjectName("Teamwork");
+ view->setWindowTitle(i18n("Teamwork"));
+ m_plugin->setView( view );
+ return view;
+ }
+
+ virtual Qt::DockWidgetArea defaultPosition()
+ {
+ return Qt::RightDockWidgetArea;
+ }
+
+ virtual QString id() const
+ {
+ return "org.kdevelop.Teamwork";
+ }
+
+private:
+ KDevTeamworkPlugin *m_plugin;
+};
+
+void KDevTeamworkPlugin::unload()
+{
+ core()->uiController()->removeToolView(m_factory);
+}
+
+KDevTeamworkPlugin::KDevTeamworkPlugin( QObject *parent,
+ const QVariantList& )
+ : KDevelop::IPlugin( KDevTeamworkFactory::componentData(), parent ), m_currentProject( 0 ), m_window(0), m_factory( new KDevTeamworkViewFactory(this) )
+{
+ m_self = this;
+ setXMLFile( "kdevteamwork.rc" );
+ core()->uiController()->addToolView(i18n("Teamwork"), m_factory);
+ m_window = 0;
+
+ connect( core()->projectController(), SIGNAL( projectOpened( KDevelop::IProject* ) ), this, SLOT( projectOpened( KDevelop::IProject* ) ) );
+ connect( core()->projectController(), SIGNAL( projectClosed( KDevelop::IProject* ) ), this, SLOT( projectClosed( KDevelop::IProject* ) ) );
+}
+
+KDevelop::ICore * KDevTeamworkPlugin::staticCore( )
+{
+ return m_self->core();
+}
+
+void KDevTeamworkPlugin::setView( QWidget* view ) {
+ KDevelop::IProject* oldProject = m_currentProject;
+ destroyTeamwork();
+ m_window = view;
+
+ if( oldProject )
+ startTeamwork( oldProject );
+}
+
+void KDevTeamworkPlugin::destroyTeamwork() {
+ delete m_teamwork;
+ m_teamwork = 0;
+ m_currentProject = 0;
+ if( m_window )
+ m_window->hide();
+}
+
+void KDevTeamworkPlugin::startTeamwork( KDevelop::IProject* project ) {
+ destroyTeamwork();
+ m_currentProject = project;
+ if( !m_window ) return;
+ m_teamwork = new KDevTeamwork( project->folder(), this, m_window );
+ m_window->show();
+}
+
+KDevelop::IDocumentController* KDevTeamworkPlugin::staticDocumentController() {
+ return staticCore()->documentController();
+}
+
+KDevTeamworkPlugin::~KDevTeamworkPlugin()
+{
+ destroyTeamwork();
+}
+
+QWidget* KDevTeamworkPlugin::pluginView() const
+{
+ return m_window;
+}
+
+void KDevTeamworkPlugin::import( RefreshPolicy /*policy*/ )
+{}
+
+void KDevTeamworkPlugin::restorePartialProjectSession(const QDomElement* el) {
+ m_teamwork->restorePartialProjectSession( el );
+}
+
+void KDevTeamworkPlugin::savePartialProjectSession(QDomElement* el) {
+ m_teamwork->savePartialProjectSession( el );
+}
+
+void KDevTeamworkPlugin::projectOpened( KDevelop::IProject* project ) {
+ if( !m_currentProject )
+ startTeamwork( project );
+}
+
+void KDevTeamworkPlugin::projectClosed( KDevelop::IProject* project ) {
+ if( project == m_currentProject )
+ destroyTeamwork();
+}
+
+
+#include "kdevteamworkplugin.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h (revision 1522570)
@@ -0,0 +1,87 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_PART_H
+#define KDEVTEAMWORK_PART_H
+
+#include <QtCore/QPointer>
+
+#include <interfaces/iplugin.h>
+#include <QtCore/QVariant>
+
+class KDevTeamworkViewFactory;
+class KUrl;
+class QModelIndex;
+class KDevTeamwork;
+class KDevTeamworkPluginFactory;
+
+namespace KDevelop {
+ class ICore;
+ class IDocumentController;
+ class IProject;
+}
+
+class KDevTeamworkPlugin: public KDevelop::IPlugin
+{
+ Q_OBJECT
+public:
+ enum RefreshPolicy
+ {
+ Refresh,
+ NoRefresh,
+ ForceRefresh
+ };
+
+public:
+ KDevTeamworkPlugin( QObject *parent, const QVariantList & = QVariantList() );
+ virtual ~KDevTeamworkPlugin();
+
+ //KDevPlugin methods
+ virtual QWidget* pluginView() const;
+
+ void import( RefreshPolicy policy = Refresh );
+
+ static KDevelop::ICore* staticCore();
+
+ static KDevelop::IDocumentController* staticDocumentController();
+
+ virtual void restorePartialProjectSession(const QDomElement* el);
+
+ virtual void savePartialProjectSession(QDomElement* el);
+
+ void setView( QWidget* view );
+
+ // KDevelop::Plugin methods
+ virtual void unload();
+
+ signals:
+ void refresh();
+
+private slots:
+ void projectOpened( KDevelop::IProject* );
+ void projectClosed( KDevelop::IProject* );
+
+private:
+ void destroyTeamwork();
+ void startTeamwork( KDevelop::IProject* );
+
+ KDevelop::IProject* m_currentProject;
+ static KDevTeamworkPlugin* m_self;
+ QPointer<KDevTeamwork> m_teamwork;
+ QPointer<QWidget> m_window;
+ KDevTeamworkViewFactory* m_factory;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.cpp (revision 1522570)
@@ -0,0 +1,25 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "helpers.h"
+#include "lib/network/networkfwd.h"
+#include "lib/network/sessioninterface.h"
+#include "lib/network/user.h"
+
+Teamwork::UserPointer userFromSession( const Teamwork::SessionPointer& session ) {
+ if( !session ) return 0;
+ return session.unsafe() ->safeUser();
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h (revision 1522570)
@@ -0,0 +1,60 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_USER_H
+#define KDEVTEAMWORK_USER_H
+
+#include <QObject>
+#include <QMetaType>
+#include <QString>
+#include <kiconloader.h>
+
+#include "lib/network/networkfwd.h"
+#include "teamworkfwd.h"
+#include "lib/network/user.h"
+
+using namespace Teamwork;
+class QIcon;
+
+namespace Teamwork {
+ class IdentificationMessage;
+}
+
+class KDevTeamworkUser : public QObject, public User {
+ Q_OBJECT
+ public:
+ KDevTeamworkUser( const User* user = 0 );
+
+ KDevTeamworkUser( IdentificationMessage* msg );
+
+ virtual void setSession( const SessionPointer& sess );
+
+ QIcon icon( KIconLoader::Group = KIconLoader::Small );
+
+ QString toolTip();
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & boost::serialization::base_object<User>( *this );
+ }
+
+ signals:
+ ///All signals in this class should be connected using queued connections, because they get called from other threads
+ void userStateChanged( KDevTeamworkUserPointer user );
+};
+
+typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h (revision 1522570)
@@ -0,0 +1,105 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_CLIENT_H
+#define KDEVTEAMWORK_CLIENT_H
+
+
+#include "teamworkfwd.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/teamworkclient.h"
+#include "kdevteamwork_messages.h"
+#include <list>
+
+
+#include <QTimer>
+
+///@TODO: Dispatch the messages in a more flexible way: Allow any client to register with an arbitrary message-type that he wants to get(including all sub-messages). DynamicMessageDispatcher can do this. Use that, and make the way messages are connected more flexible.
+
+Q_DECLARE_METATYPE( Teamwork::ServerInformation )
+Q_DECLARE_METATYPE( Teamwork::UserPointer )
+Q_DECLARE_METATYPE( ConnectionRequestPointer )
+Q_DECLARE_METATYPE( SafeSharedPtr<KDevTeamworkTextMessage> )
+Q_DECLARE_METATYPE( std::list<UserPointer> )
+Q_DECLARE_METATYPE( SafeSharedPtr<KDevSystemMessage> )
+Q_DECLARE_METATYPE( CollaborationMessagePointer )
+
+///most of the functions in this class are called from within another thread
+class KDevTeamworkClient : public QObject, public Teamwork::Client
+{
+ public:
+ KDevTeamworkClient( KDevTeamwork* teamwork );
+
+ void invalidateTeamwork() {
+ disconnectAllServers();
+ closeAllIncomingSessions();
+ stopRunning();
+ m_teamwork = 0;
+ }
+
+ int receiveMessage( CollaborationMessage* msg );
+
+ int receiveMessage( PatchesManagerMessage* msg );
+
+ int receiveMessage( KDevTeamworkTextMessage* msg );
+
+ int receiveMessage( KDevSystemMessage* msg );
+
+ int receiveMessage( ConnectionRequest* msg );
+
+ int receiveMessage( MessageInterface* /*msg*/ ) {
+ return 0;
+ }
+
+ signals:
+ ///All connections made to these signals must be queued, since these signals are emitted from within another thread
+ void guiUserConnected( Teamwork::UserPointer );
+ void guiUserDisconnected( Teamwork::UserPointer );
+ void guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
+ void guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
+ void guiUserList( std::list<UserPointer> );
+
+ void signalDispatchMessage( PatchesManagerMessagePointer );
+ void signalDispatchMessage( CollaborationMessagePointer );
+
+ protected:
+ virtual UserPointer createUser( IdentificationMessage* msg );
+ virtual UserPointer createUser( const User* user );
+
+ ///this is called whenever a new user successfully logged into the server
+ virtual void userConnected( const Teamwork::UserPointer& user );
+
+ ///called whenever a user leaves the server
+ virtual void userDisconnected( const Teamwork::UserPointer& user );
+
+ ///this is called whenever a connection is successfully established to a server
+ virtual void connectedToServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server );
+
+ ///this is called whenever a server the client disconnects from a connected server in any way
+ virtual void disconnectedFromServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server );
+
+ virtual void gotUserList( const std::list<UserPointer>& users );
+
+ void processMessage( MessageInterface* msg ) throw();
+
+ private:
+
+ //AllKDevTeamworkMessages, KDevTeamworkMessages
+ Q_OBJECT
+ KDevTeamwork* m_teamwork;
+
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h (revision 1522570)
@@ -0,0 +1,132 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGEHISTORYMANAGER_H
+#define MESSAGEHISTORYMANAGER_H
+
+
+#include <QList>
+#include <QMap>
+
+#include <klockfile.h>
+#include <kurl.h>
+
+#include "lib/network/user.h"
+#include "kdevteamwork_messages.h"
+#include "teamworkfwd.h"
+#include <nvp.h>
+
+
+class QTimer;
+class KDevTeamworkTextMessage;
+
+typedef SafeSharedPtr<KDevTeamworkTextMessage, MessageSerialization> HistoryMessagePointer;
+
+struct HistoryMessageDesc
+{
+ UserIdentity user;
+ bool isIncoming;
+ HistoryMessagePointer message;
+
+ HistoryMessageDesc();
+
+ HistoryMessageDesc( const HistoryMessagePointer& msg );
+
+ template<class Archive>
+ void load( Archive& arch, const uint /*version*/ ) {
+ arch & NVP( user );
+ arch & NVP( isIncoming );
+ arch & NVP( message );
+ HistoryMessagePointer::Locked l = message;
+ if( l ) {
+ l->info().setIsIncoming( isIncoming );
+ }
+ }
+
+ template<class Archive>
+ void save( Archive& arch, const uint /*version*/ ) const {
+ arch & NVP( user );
+ arch & NVP( isIncoming );
+ arch & NVP( message );
+ }
+
+ operator bool() {
+ return (bool) message;
+ }
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+};
+
+struct HistoryGroupLocation {
+ string fileName;
+ uint offset;
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & fileName;
+ arch & offset;
+ }
+};
+
+
+class MessageHistoryManager : public QObject {
+ Q_OBJECT
+ public:
+ typedef QMap<Teamwork::UserIdentity, bool > UserSet;
+
+
+ MessageHistoryManager( Teamwork::LoggerPointer logger );
+ ~MessageHistoryManager();
+
+ void addMessage( KDevTeamworkTextMessage* msg );
+
+ ///Returns all matching messages. If user is zero, returns messages from/to all users. This is slow(always reads the messages from disk)
+ QList<HistoryMessagePointer> getMessages( const KDevTeamworkClientPointer& client, const QDate& from = QDate(), const QDate& until = QDate(), UserSet users = UserSet() );
+
+ HistoryMessagePointer getMessageFromId( Teamwork::UniqueMessageId id, const KDevTeamworkClientPointer& client );
+
+ signals:
+ void newMessage( HistoryMessagePointer msg ); ///This is emitted whenever a new message should be added to the history
+
+ private slots:
+ void writePending();
+
+ private:
+ HistoryMessagePointer fillMessageUser( const HistoryMessageDesc& message, const KDevTeamworkClientPointer& client );
+
+ QString lockFileName();
+
+ QList<HistoryMessagePointer> fillMessageUsers( const QList<HistoryMessageDesc>& messages, const KDevTeamworkClientPointer& client );
+ ///Reads out the messages of just one chunk(the messages that follow a single header)
+ void readMessages( const QString& file, uint offset, QList<HistoryMessageDesc>& messages ) throw(QString);
+
+ void readIndex( std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString);
+
+ void writeIndex( const std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString);
+
+ ///May throw QString
+ KUrl directory() throw(QString);
+
+ QTimer* m_pendingTimer;
+ QList< HistoryMessageDesc > m_pending;
+ Teamwork::LoggerPointer m_logger;
+ KLockFile::Ptr m_lockFile;
+
+ Teamwork::LoggerPrinter out( Teamwork::Logger::Level = Teamwork::Logger::Info );
+
+ Teamwork::LoggerPrinter err();
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.cpp (revision 1522570)
@@ -0,0 +1,43 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "kdevutils.h"
+#include "teamworkfoldermanager.h"
+#include "kdevteamworkplugin.h"
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+#include <ktexteditor/cursor.h>
+
+using namespace KDevelop;
+
+QString currentDocumentPath() {
+ IDocumentController * docControl = KDevTeamworkPlugin::staticDocumentController();
+
+ IDocument* d = docControl->activeDocument();
+ if ( !d )
+ throw QString( "no active document" );
+
+ KTextEditor::Document* doc = d->textDocument();
+ if ( !doc )
+ throw QString( "active document is no text-document" );
+
+ KTextEditor::View* view = doc->activeView();
+ if ( !view )
+ throw QString( "no active document-view" );
+
+ return TeamworkFolderManager::workspaceRelative( d->url() );
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.h (revision 1522570)
@@ -0,0 +1,156 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef EDITPATCH_H
+#define EDITPATCH_H
+
+#include <QObject>
+#include "lib/network/sharedptr.h"
+#include "ui_kdevteamwork_editpatch.h"
+#include <QPointer>
+#include "safelogger.h"
+#include <memory>
+#include "patchmessage.h"
+
+
+namespace KParts{
+ class Part;
+}
+
+class QDialog;
+
+class PatchesManager;
+namespace Diff2 {
+class KompareModelList;
+class DiffModel;
+}
+namespace KTextEditor {
+ class SmartRange;
+}
+namespace Kompare {
+ class Info;
+}
+namespace KDevelop {
+class IDocument;
+}
+
+///Delete itself when the document(or textDocument), or Diff-Model is deleted.
+class DocumentHighlighter : public QObject {
+ Q_OBJECT
+ public:
+ DocumentHighlighter( const Diff2::DiffModel* model, KDevelop::IDocument* doc, bool isSource ) throw( QString );
+ ~DocumentHighlighter();
+ KDevelop::IDocument* doc();
+ private slots:
+ void documentDestroyed();
+ private:
+ QList<KTextEditor::SmartRange*> m_ranges;
+ KDevelop::IDocument* m_doc;
+};
+
+class DiffSettings;
+
+class EditPatch : public QObject, public Shared, public SafeLogger {
+ Q_OBJECT
+ public:
+ EditPatch( PatchesManager* parent, LocalPatchSourcePointer patch, bool local );
+ ~EditPatch();
+
+ void apply( bool reverse = false, const QString& fileName = "" );
+
+ LocalPatchSourcePointer patch() const;
+ signals:
+ void dialogClosed( EditPatch* );
+ void stateChanged( EditPatch* );
+ private slots:
+ void receivedTerminalData( const QString& s );
+ void slotEditOk();
+ void slotEditCancel();
+ void slotEditFileNameChanged( const QString& str );
+ void slotEditCommandChanged( const QString& str );
+ void slotFileNameEdited();
+ void slotCommandEdited();
+ void slotEditMimeType( const QString& str );
+ void slotEditDialogFinished( int result );
+ void slotChooseType();
+ void slotStateChanged();
+ void slotApplyEditPatch();
+ void slotUnapplyEditPatch();
+ void slotShowEditPatch();
+ void dialogDestroyed();
+ void slotDetermineState();
+ void slotToFile();
+ void slotUserButton();
+
+ void fileDoubleClicked( const QModelIndex& i );
+ void fileSelectionChanged();
+
+ void nextHunk();
+ void prevHunk();
+ void highlightFile();
+
+ void updateKompareModel();
+
+ void updateByType();
+ private:
+ void seekHunk( bool forwards, bool isSource, const QString& file = QString() );
+
+ virtual std::string logPrefix();
+
+ void showEditDialog();
+ void hideEditDialog();
+ void editPatchReadOnly();
+ LocalPatchSource::State editState();
+ void fillEditFromPatch();
+ LocalPatchSourcePointer patchFromEdit();
+
+ void removeHighlighting( const QString& file = QString() );
+
+ LocalPatchSource::State m_actionState;
+
+ ///Gets local patches via a fake-session
+ SafeSharedPtr<PatchMessage> getPatchMessage( PatchRequestData::RequestType type );
+ ///Tries to locally get the patch-message and then store it to a temporary file. If successful returns the filename.
+ KUrl getPatchFile(bool temp = false);
+
+ PatchesManager* m_parent;
+ LocalPatchSourcePointer m_editingPatch;
+ bool m_editPatchLocal;
+
+ Ui_EditPatch m_editPatch;
+ QDialog* m_editDlg;
+
+ QTime m_lastDataTime;
+ QString m_lastTerminalData;
+
+ QPointer<KParts::Part> m_konsolePart;
+
+ QTimer* m_updateKompareTimer;
+
+ bool m_reversed;
+ bool m_started;
+ QStandardItemModel* m_filesModel;
+ QPointer<DiffSettings> m_diffSettings;
+ auto_ptr<Kompare::Info> m_kompareInfo;
+ auto_ptr<Diff2::KompareModelList> m_modelList;
+ QString m_lastModelCommand, m_lastModelFile;
+ typedef QMap<QString, QPointer<DocumentHighlighter> > HighlightMap;
+ HighlightMap m_highlighters;
+ bool m_isSource;
+};
+
+typedef SharedPtr<EditPatch> EditPatchPointer;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/editpatch.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.h (revision 1522570)
@@ -0,0 +1,283 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef CONVERSATIONMANAGER_H
+#define CONVERSATIONMANAGER_H
+
+#include <QObject>
+#include <QtCore/QPointer>
+#include <QTime>
+#include <ktexteditor/document.h>
+#include <ktexteditor/smartcursor.h>
+#include <ktexteditor/smartinterface.h>
+#include "teamworkfwd.h"
+#include "indocumentreference.h"
+#include "messagehistorymanager.h"
+#include "lib/network/crossmap.h"
+#include "safelogger.h"
+#include "ui_kdevteamwork_internalmessage.h"
+#
+
+class QStandardItemModel;
+class TemporaryConversationConnector;
+class KDevTeamworkClient;
+class QTimer;
+class InDocumentMessage;
+
+namespace KDevelop {
+ class IDocument;
+}
+
+typedef SafeSharedPtr<InDocumentMessage, MessageSerialization> InDocumentMessagePointer;
+
+///This is a class that helps detecting when the document is deleted and then deleting the smartcursor, also it automatically creates the cursor. @todo replace with QOwnedPointer
+class SmartCursorContainer {
+ QPointer<KTextEditor::Document> m_document;
+ KTextEditor::SmartCursor* m_smartCursor;
+ public:
+ SmartCursorContainer( KTextEditor::Document* doc = 0 ) : m_document( doc ), m_smartCursor( 0 ) {
+ if ( m_document ) {
+ KTextEditor::SmartInterface * smart =
+ qobject_cast<KTextEditor::SmartInterface*>( doc );
+
+ if ( smart )
+ m_smartCursor = smart->newSmartCursor();
+ }
+ }
+ KTextEditor::SmartCursor* operator -> () {
+ return m_smartCursor;
+ }
+ ~SmartCursorContainer() {
+ if ( m_smartCursor )
+ delete m_smartCursor;
+ m_smartCursor = 0;
+ }
+ KTextEditor::SmartCursor& operator *() {
+ return * m_smartCursor;
+ }
+ SmartCursorContainer( const SmartCursorContainer& rhs ) {
+ if ( &rhs == this )
+ return ;
+ if ( m_smartCursor && m_document )
+ delete m_smartCursor;
+ m_document = rhs.m_document;
+ m_smartCursor = rhs.m_smartCursor;
+ const_cast<SmartCursorContainer&>( rhs ).m_smartCursor = 0;
+ }
+ SmartCursorContainer& operator = ( const SmartCursorContainer& rhs ) {
+ if ( &rhs == this )
+ return * this;
+ if ( m_smartCursor && m_document )
+ delete m_smartCursor;
+ m_document = rhs.m_document;
+ m_smartCursor = rhs.m_smartCursor;
+ const_cast<SmartCursorContainer&>( rhs ).m_smartCursor = 0;
+ return *this;
+ }
+
+ operator bool() {
+ return m_document && m_smartCursor && m_smartCursor->isValid();
+ }
+};
+
+namespace KTextEditor {
+class View;
+class Cursor;
+class SmartCursor;
+}
+class InDocumentMessage;
+enum LogLevel;
+class ConversationManager;
+class QWidget;
+class SmartCursor;
+
+CROSSMAP_DEFINE_CONTAINER( QList )
+
+struct OrderedDocumentMessage {
+ int position;
+ InDocumentMessagePointer message;
+ OrderedDocumentMessage( uint pos, const InDocumentMessagePointer& msg ) : position( pos ), message( msg ) {}
+ OrderedDocumentMessage() : position( 0 ), message( 0 ) {}
+
+ operator bool() const {
+ return ( bool ) message;
+ }
+ /*template<class Archive>
+ void serialize( Archive& arch, const uint version ) {
+ arch & position & message;
+ }*/
+};
+
+class InDocumentConversation : public QObject, public Shared, public SafeLogger {
+ Q_OBJECT
+ ///Order, message, file
+ BIND_LIST_3( Keys, InDocumentMessagePointer, int, QString )
+ typedef Utils::CrossMap< OrderedDocumentMessage, Keys > MessageSet;
+ public:
+ InDocumentConversation( InDocumentMessage* msg = 0 );
+ ~InDocumentConversation();
+
+ void addMessage( InDocumentMessage* msg );
+
+ template <class ArchType>
+ void load( ArchType& arch, unsigned int version );
+
+ template <class ArchType>
+ void save( ArchType& arch, unsigned int version ) const;
+
+ ConversationManager* manager() const;
+
+ void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork, MessagePointer msg );
+
+ ///Returns true if the message belongs to this conversation
+ bool match( InDocumentMessage* msg ) const;
+
+ void setActive( bool );
+
+ UserPointer primaryUser();
+
+ public slots:
+ void userStateChanged( KDevTeamworkUserPointer );
+ void documentActivated( KDevelop::IDocument* document );
+ void verticalScrollPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos );
+ void cursorPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos );
+ void horizontalScrollPositionChanged ( KTextEditor::View *view );
+ void jumpTo();
+ void hide();
+ void sendMessage();
+ void gotReply( MessagePointer msg );
+
+ void messageClicked( const QModelIndex& );
+ void messageContextMenu ( const QPoint & );
+ void selectMessage( InDocumentMessagePointer msg );
+
+ void userInfo();
+ void log( const QString& str, LogLevel level = Info ) const;
+ void selectNearestMessage();
+ private slots:
+ void textChanged ( KTextEditor::Document * document, const KTextEditor::Range & oldRange, const KTextEditor::Range & newRange );
+ void textRemoved ( KTextEditor::Document * document, const KTextEditor::Range & range );
+ void textInserted ( KTextEditor::Document * document, const KTextEditor::Range & range );
+
+ void rangeDeleted();
+ private:
+ virtual std::string logPrefix();
+
+ InDocumentMessagePointer selectedMessage();
+
+ void documentActivated( KDevelop::IDocument* document, const InDocumentMessagePointer& msg );
+
+ void messageSelected( const MessagePointer& msg );
+ template <class ArchType>
+ void serial( ArchType& arch, unsigned int /*version*/ ) {
+ arch & m_documentName;
+ arch & m_line;
+ arch & m_active;
+ }
+ void pushMessage( const InDocumentMessagePointer& msg );
+
+ KTextEditor::Cursor currentDocCursor() const;
+
+ QString context() const;
+ void messageSendReady( bool success );
+ void addListItem( const QString& txt, const QString& icon = "error" );
+ SessionPointer session();
+ void fillUserBox();
+ void fillMessageModel();
+ void fillMessageToModel( const LockedSharedPtr<InDocumentMessage>& );
+ void setupWidget( QWidget* parent );
+ void embedInView( KTextEditor::View* view, KDevelop::IDocument* document, KTextEditor::Cursor position );
+ KTextEditor::Cursor findPositionInDocument( InDocumentMessagePointer::Locked l, KTextEditor::Cursor* endTarget = 0 );
+ void placeWidget( KTextEditor::View* view, const KTextEditor::Cursor* awayFrom = 0, bool forceShow = false );
+
+ string m_documentName;
+ int m_line;
+ int m_conversationId;
+ bool m_active;
+ uint m_messageCount;
+
+ //list<InDocumentMessagePointer> m_messages;
+ MessageSet m_messages;
+
+ QPointer<QWidget> m_widget;
+ Ui_InternalMessage m_widgets;
+ SmartCursorContainer m_smartCursor;
+ QAction* m_jumpToAction;
+ QAction* m_hideAction;
+ QAction* m_userInfoAction;
+ QStandardItemModel* m_messagesModel;
+ InDocumentMessagePointer m_sendingMessage;
+ SharedPtr<TemporaryConversationConnector> m_userConnector;
+ bool m_block;
+
+ QTimer* m_selectNearestMessageTimer;
+
+ QPointer<KTextEditor::Document> m_currentConnectedDocument;
+
+ KTextEditor::SmartRange* m_currentRange;
+
+ InDocumentReference::TextSearchInstance m_currentSearchInstance;
+
+ QTime m_lastSendTime;
+ public:
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+};
+
+typedef SharedPtr<InDocumentConversation> InDocumentConversationPointer;
+
+class ConversationManager : public QObject {
+ Q_OBJECT
+ public:
+
+ ConversationManager( MessageManager* mng );
+ ~ConversationManager();
+
+ int processMessage( InDocumentMessage* msg );
+
+ static ConversationManager* instance() {
+ return m_instance;
+ }
+
+ void log( const QString& str, LogLevel level );
+
+ /* template <class ArchType>
+ void serialize( ArchType& arch, unsigned int ) {
+ arch & m_conversations;
+ }*/
+
+ MessageManager* manager() const {
+ return const_cast<MessageManager*>( m_manager );
+ }
+
+ ///Returns zero if the conversation does not exist.
+ InDocumentConversationPointer findConversation( const QString& context );
+
+ ///If the conversation does not exist, it is created.
+ InDocumentConversationPointer getConversation( InDocumentMessage* );
+
+ public slots:
+ void load();
+ void save();
+ void documentActivated( KDevelop::IDocument* document );
+
+ private:
+ static ConversationManager* m_instance;
+ typedef map<string, InDocumentConversationPointer> ConversationSet;
+ ConversationSet m_conversations; ///maps conversation-ids to conversations
+ MessageManager* m_manager;
+ static ConversationManager* globalManager;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp (revision 1522570)
@@ -0,0 +1,43 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "indocumentmessage.h"
+#include "lib/network/messagetypeset.h"
+#include "kdevteamwork_messageshower.h"
+
+///@todo move some stuff from conversationmanager.cpp here
+
+///Can be used to get and set the context-lines
+DocumentContextLines& InDocumentMessage::contextLines() {
+ return m_contextLines;
+}
+
+InDocumentReference& InDocumentMessage::start() {
+ return m_start;
+}
+
+InDocumentReference& InDocumentMessage::end() {
+ return m_end;
+}
+
+QString InDocumentMessage::shortName() const {
+ return "Document-Message";
+}
+
+void InDocumentMessage::showInWidget( QWidget* widget, KDevTeamwork* tw ) {
+ new InDocumentMessageShower( this, widget, tw );
+}
+
+REGISTER_MESSAGE( InDocumentMessage )
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp (revision 1522570)
@@ -0,0 +1,42 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "qdynamictext.h"
+#include "lib/network/serialization.h"
+#include <boost/serialization/export.hpp>
+
+QDynamicText::QDynamicText( const VectorTimestamp& initialState, const std::string& initialText ) : DynamicText( initialState, initialText ) {
+}
+
+void QDynamicText::notifyInserted( const ReplacementPointer& rep ) {
+ emit inserted( rep, *this );
+}
+
+void QDynamicText::notifyStateChanged() {
+ emit stateChanged( *this );
+}
+
+QDynamicText::QDynamicText( const QDynamicText& rhs ) : QObject(), DynamicText( rhs ) {
+}
+
+QDynamicText& QDynamicText::operator = ( const QDynamicText& rhs ) {
+ DynamicText::operator=( rhs );
+ return *this;
+}
+
+//BOOST_CLASS_EXPORT_GUID(QDynamicText, "QDynamicText")
+
+
+#include "qdynamictext.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp (revision 1522570)
@@ -0,0 +1,735 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "documentwrapper.h"
+#include "kdevteamwork_messages.h"
+#include "kdevteamworkplugin.h"
+#include <QStandardItemModel>
+#include <QModelIndex>
+#include <QMenu>
+#include <QVariant>
+#include <QFileInfo>
+#include <QFile>
+#include <kmessagebox.h>
+#include <klocalizedstring.h>
+#include <k3process.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/range.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+#include "lib/dynamictext/dynamictext.h"
+#include "kdevteamwork_helpers.h"
+#include "collaborationmanager.h"
+#include "filecollaborationmessages.h"
+#include "lib/network/basicsession.h"
+#include "utils.h"
+#include "lib/dynamictext/verify.h"
+#include "filesynchronizemessage.h"
+#include "qdynamictext.h"
+#include "vectortimestampeditor.h"
+#include "kdevteamwork.h"
+#include "patchesmanager.h"
+#include "teamworkfoldermanager.h"
+#include "filecollaborationsession.h"
+#include "patchmessage.h"
+#include "filecollaborationmanager.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/messagesendhelper.h"
+#include <interfaces/iuicontroller.h> /* defines [function] activeMainWindow */
+#include <interfaces/icore.h> /* defines [function] uiController */
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+using namespace KDevelop;
+
+#define IFDEBUG( x ) /**/
+//#define IFDEBUG( x ) x
+
+struct DocumentWrapperTreeAction : public StandardCollaborationTreeAction<DocumentWrapper> {
+ DocumentWrapperTreeAction( DocumentWrapper* w ) : StandardCollaborationTreeAction<DocumentWrapper>( w ) {}
+ virtual void doubleClicked() {
+ if ( target ) {
+ target->openDocument( true );
+ }
+ }
+ virtual void clicked() {}
+ virtual void fillContextMenu( QMenu* menu ) {
+ if ( target )
+ target->fillContextMenu( 0, menu );
+ }
+}
+;
+
+bool DocumentWrapper::hadError() const {
+ return m_hadError;
+}
+
+uint DocumentWrapper::id() const {
+ return m_id;
+}
+
+DocumentWrapper::DocumentWrapper( uint id, const LoggerPointer& logger, QString fileName, uint ownIndex, bool readFile_, FileCollaborationSession* session, bool fromBuffer ) :
+ SafeLogger( logger, ~( "document-wrapper \"" + fileName + "\": " ) ),
+ m_text( new QDynamicText() ),
+ m_block( false ),
+ m_realFile( readFile_ ),
+ m_fileName( fileName ),
+ m_document( 0 ),
+ m_session( session ),
+ m_ownIndex( ownIndex ),
+ m_id( id ),
+ m_hadError( false ),
+ m_disabled( false ),
+ m_dead( false ),
+ m_dispatcher( *this ){
+ //openDocument();
+ out( Logger::Debug ) << "DocumentWrapper for" << fileName << "created:" << ownIndex << "" << readFile_;
+ if ( m_realFile )
+ readFile( fromBuffer );
+
+ connect( m_text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( stateChanged() ) );
+}
+
+QIcon DocumentWrapper::icon() const {
+ if ( m_dead )
+ return IconCache::getIconStatic( "collaboration_file_dead" );
+ if ( !m_disabled )
+ return IconCache::getIconStatic( "collaboration_file" );
+ else
+ return IconCache::getIconStatic( "collaboration_file_disabled" );
+}
+
+void DocumentWrapper::updateTree( QModelIndex& i, QStandardItemModel* model ) {
+ model->setData( i, fileName(), Qt::DisplayRole );
+ model->setData( i, icon(), Qt::DecorationRole );
+ QVariant v;
+ v.setValue<CollaborationTreeActionPointer>( new DocumentWrapperTreeAction( this ) );
+ model->setData( i, v, Qt::UserRole );
+}
+
+void DocumentWrapper::fillContextMenu( int /*var*/, QMenu* menu ) {
+ QMenu * m = new QMenu( menu );
+ m->setTitle( "Save Visible State" );
+ m->addAction( "As Patch", this, SLOT( saveAsPatch() ) );
+ //m->addAction( "To New Buffer", this, SLOT( saveNewBuffer() ) );
+ //m->addSeparator();
+ m->addAction( QString( "As %1" ).arg( m_fileName ), this, SLOT( saveAsBufferFile() ) );
+ menu->addMenu( m );
+
+
+ if ( m_disabled )
+ menu->addAction( "Enable Editing", this, SLOT( toggleEnabled() ) );
+ else if ( m_session->isMasterSession() )
+ menu->addAction( "Disable Editing", this, SLOT( toggleEnabled() ) );
+
+ if ( m_session->isMasterSession() || m_dead ) {
+ menu->addSeparator();
+ menu->addAction( "Remove", this, SLOT( remove
+ () ) );
+ }
+
+ menu->addSeparator();
+ menu->addAction( "Manage Dynamic Text", this, SLOT( manageDynamicText() ) );
+}
+
+QString DocumentWrapper::text() const {
+ return ~m_text->text().text();
+}
+
+VectorTimestamp DocumentWrapper::state() const {
+ return m_text->state();
+}
+
+const QDynamicText& DocumentWrapper::dynamicText() const {
+ return * m_text;
+}
+
+bool DocumentWrapper::checkDocumentSync() const {
+ if ( m_document && m_document->textDocument() ) {
+ return m_document->textDocument() ->text() == ~m_text->text().text();
+ } else {
+ return true;
+ }
+}
+
+void DocumentWrapper::remove
+() {}
+
+
+void DocumentWrapper::toggleEnabled() {
+ m_disabled = !m_disabled;
+ out( Logger::Debug ) << "Editing is now" << ( m_disabled ? "disabled" : "enabled");
+}
+
+void DocumentWrapper::saveAsBufferFile() {
+ KUrl u = TeamworkFolderManager::workspaceAbsolute( m_fileName );
+
+ IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->openDocument( u, KTextEditor::Cursor() );
+
+ if ( doc && doc->textDocument() ) {
+ if ( doc->state() == IDocument::Modified || doc->state() == IDocument::DirtyAndModified ) {
+ int answer = KMessageBox::warningYesNo( KDevTeamworkPlugin::staticCore()->uiController()->activeMainWindow()->window(), i18n( "The buffer of %1 is modified, should the content be replaced?" , m_fileName ) );
+ if ( answer != KMessageBox::Yes )
+ return ;
+ }
+ doc->textDocument() ->setText( ~m_text->text().text() );
+
+ } else {
+ err() << "saveAsBufferFile(): could not open document for" << u.toLocalFile();
+ }
+}
+
+OutputFileWriter::OutputFileWriter( const QString& file ) : m_file( file ), m_failed( false ) {
+ if ( !m_file.open( QIODevice::WriteOnly ) )
+ throw QString( "could not open file %1" ).arg( file );
+}
+
+bool OutputFileWriter::failed() const {
+ return m_failed;
+}
+
+void OutputFileWriter::receivedStdout( K3Process */*proc*/, char *buffer, int buflen ) {
+ if ( m_file.write( buffer, buflen ) != buflen ) {
+ m_failed = true;
+ }
+}
+
+LocalPatchSourcePointer DocumentWrapper::saveAsPatch( bool addToList, bool edit ) {
+ try {
+ KDevTeamwork * tw = KDevTeamwork::self();
+
+ PatchesManager* pm = tw->patchesManager();
+
+ QString peer = m_session->firstPeerName();
+ if ( m_session->isMasterSession() )
+ peer = "local";
+
+ LocalPatchSourcePointer::Locked l = new LocalPatchSource();
+ l->name = ~( m_session->name() + "@" + peer + "_" + QDateTime::currentDateTime().toString( Qt::ISODate ) );
+ l->type = "text/x-diff";
+ l->applyCommand = "-p0";
+ l->unApplyCommand = "-p0 -R";
+ l->userIdentity = m_session->manager() ->teamwork() ->currentUserIdentity();
+
+ KUrl u = TeamworkFolderManager::createUniqueFile( "patches", "diff", ~l->name, "collab_", "" );
+
+ l->filename = ~TeamworkFolderManager::teamworkRelative( u, "patches" );
+
+ KUrl workingDir = TeamworkFolderManager::createUniqueDirectory( "temp", m_session->name(), "diff_" );
+ KUrl subFolder( TeamworkFolderManager::teamworkRelative( workingDir ) );
+ subFolder.addPath( QFileInfo( m_fileName ).path() );
+
+ KUrl tempCurrent = TeamworkFolderManager::createUniqueFile( subFolder.toLocalFile(), m_fileName );
+ KUrl tempBase = TeamworkFolderManager::createUniqueFile( subFolder.toLocalFile(), m_fileName, "base_" );
+
+ TeamworkFolderManager::self() ->registerTempItem( tempCurrent );
+ TeamworkFolderManager::self() ->registerTempItem( tempBase );
+
+ {
+ QByteArray path = tempCurrent.toLocalFile().toUtf8();
+ std::ofstream fCurrent( path.data(), ios_base::out );
+ if ( !fCurrent.is_open() )
+ throw "could not open file for writing: " + tempCurrent.toLocalFile();
+ fCurrent << m_text->text().text();
+ }
+ {
+ QByteArray path = tempBase.toLocalFile().toUtf8();
+ std::ofstream fBase( path.data(), ios_base::out );
+ if ( !fBase.is_open() )
+ throw "could not open file for writing: " + tempBase.toLocalFile();
+ fBase << m_text->initialText();
+ }
+ K3Process proc;
+ ///@todo make this work with remote files
+ OutputFileWriter ow( u.toLocalFile() );
+ proc.setWorkingDirectory( workingDir.toLocalFile() );
+ QString cmdLine = + + " " + tempCurrent.toLocalFile() + " > " + u.toLocalFile();
+ proc.setPriority( K3Process::PrioLowest );
+ proc << "diff";
+ proc << "--unified=4";
+ proc << tempBase.toLocalFile();
+ proc << tempCurrent.toLocalFile();
+
+ connect( &proc, SIGNAL( receivedStdout ( K3Process *, char *, int ) ), &ow, SLOT( receivedStdout( K3Process*, char*, int ) ) );
+
+ if ( ow.failed() )
+ throw QString( "writing to %1 failed" ).arg( u.prettyUrl() );
+
+ out( Logger::Debug ) << "saveAsPatch(..) executing \"diff --unified=4 " + tempBase.toLocalFile() + " " + tempCurrent.toLocalFile() + "\"";
+
+ proc.start( K3Process::Block, K3Process::Stdout );
+ if ( addToList )
+ pm->addPatch( l );
+ if ( edit )
+ pm->showPatchInfo( l, true );
+
+ return l;
+ } catch ( const QString & str ) {
+ err() << "saveAsPatch():" << str;
+ } catch ( const char * str ) {
+ err() << "saveAsPatch():" << str;
+ }
+ return 0;
+}
+
+void DocumentWrapper::saveNewBuffer() {
+ ///It would be nice to create a nameless buffer here and insert the text
+}
+
+void DocumentWrapper::manageDynamicText() {
+ new VectorTimestampEditor( logger(), this, false, m_text, true );
+}
+
+void DocumentWrapper::stateChanged() {
+ if ( m_block )
+ return ;
+ fillDocumentText();
+}
+
+bool DocumentWrapper::synchronize( const UserPointer& user ) {
+ if ( m_dead )
+ return false;
+
+ out( Logger::Debug ) << "synchronizing with" << user.unsafe()->safeName();
+
+ UserPointer::Locked l = user;
+ if ( l && l->online().session() ) {
+ return globalMessageSendHelper().send<FileSynchronize>( l->online().session().unsafe(), fileName(), *m_text, true, id(), m_session->id() );
+ } else {
+ err() << "cannot send synchronization-message because the user cannot be locked, or is not online";
+ return false;
+ }
+}
+
+int DocumentWrapper::receiveMessage( FileEditRejectMessage* msg ) {
+ if ( m_session->isMasterSession() ) {
+ out( Logger::Warning ) << "got a reject-message from a client, sending complete synchronization";
+ synchronize( msg->info().user() );
+ return 0;
+ }
+
+ ///A reject-message contains a new state that should be applied
+ VectorTimestamp v = msg->timeStamp();
+ try {
+ m_text->changeState( v );
+ m_text->cut();
+ } catch ( const DynamicTextError & err ) {
+ ///There is no other way than resynchronizing the whole file
+ out() << "error while handling a reject, resynchronizing. Error:" << err.what();
+ globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, VectorTimestamp(), id(), m_session->id() );
+ }
+ return 1;
+}
+
+int DocumentWrapper::receiveMessage( MessageInterface* msg ) {
+ out( Logger::Warning ) << "got unknown message of type" << msg->name();
+ return 0;
+}
+
+int DocumentWrapper::receiveMessage( FileEditMessage* msg ) {
+ try {
+ if ( ( m_disabled || m_dead ) && m_session->isMasterSession() ) {
+ globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, m_text->tailState(), id(), m_session->id() );
+ return 0;
+ }
+ FileEditMessage * emsg = dynamic_cast<FileEditMessage*>( msg );
+ {
+ Block b( m_block );
+ bool wasTail = m_text->state() == m_text->tailState();
+ m_text->insert( emsg->timeStamp(), emsg->replacement() );
+
+ if ( wasTail ) {
+ m_text->text().registerNotifier( this );
+ m_text->changeState();
+ m_text->text().unregisterNotifier();
+ }
+ }
+
+ } catch ( const DynamicTextError & error ) {
+ ///@todo error-handling
+ err() << "receiveMessage( FileEditMessage" << msg->timeStamp() << "" << msg->replacement() << "):" << error.what();
+ globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, m_text->tailState(), id(), m_session->id() );
+ m_text->text().unregisterNotifier(); //@todo use a little wrapper-class for this
+ }
+ return 1;
+}
+
+void DocumentWrapper::notifyFlexibleTextErase( int position, int length ) {
+ if ( m_document && m_document->textDocument() ) {
+ Block b( m_block );
+ int line, column;
+
+ m_text->text().linearToLineColumn( position, line, column );
+ if ( line == -1 || column == -1 )
+ throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
+
+ KTextEditor::Cursor start( line, column );
+
+
+ m_text->text().linearToLineColumn( position + length, line, column );
+
+ if ( line == -1 || column == -1 )
+ throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
+
+ KTextEditor::Cursor end( line, column );
+
+
+ m_document->textDocument() ->replaceText( KTextEditor::Range( start, end ), "" );
+ }
+}
+
+void DocumentWrapper::notifyFlexibleTextInsert( int position, const std::string& text ) {
+ if ( m_document && m_document->textDocument() ) {
+ Block b( m_block );
+ int line, column;
+
+ m_text->text().linearToLineColumn( position, line, column );
+ if ( line == -1 || column == -1 )
+ throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
+
+ KTextEditor::Cursor start( line, column );
+
+ m_document->textDocument() ->replaceText( KTextEditor::Range( start, start ), toQ( text.c_str() ) );
+ }
+}
+
+void DocumentWrapper::notifyFlexibleTextReplace( int position, int length, const std::string& replacement ) {
+ if ( m_document && m_document->textDocument() ) {
+ Block b( m_block );
+ int line, column;
+
+ m_text->text().linearToLineColumn( position, line, column );
+ if ( line == -1 || column == -1 )
+ throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
+
+ KTextEditor::Cursor start( line, column );
+
+
+ m_text->text().linearToLineColumn( position + length, line, column );
+
+ if ( line == -1 || column == -1 )
+ throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
+
+ KTextEditor::Cursor end( line, column );
+
+
+ m_document->textDocument() ->replaceText( KTextEditor::Range( start, end ), toQ( replacement.c_str() ) );
+ }
+}
+
+void DocumentWrapper::processMessage( DocumentWrapperMessage* msg ) {
+
+ /*if ( !checkDocumentSync() ) {
+ if ( m_document && m_document->textDocument() ) {
+ out( Logger::Warning ) << "processMessage(begin): document and dynamictext got out of sync! Resynchronizing";
+ fillDocumentText();
+ }
+ }*/
+
+ IFDEBUG( out( Logger::Debug ) << "processMessage(..) processing" << msg->name() );
+
+ m_dispatcher( msg );
+ /*
+ if ( !checkDocumentSync() ) {
+ if ( m_document && m_document->textDocument() ) {
+ out( Logger::Warning ) << "processMessage(end): document and dynamictext got out of sync! Resynchronizing";
+ fillDocumentText();
+ }
+ }*/
+}
+
+void DocumentWrapper::documentDestroyed() {
+ m_document = 0;
+}
+
+QString DocumentWrapper::fileName() const {
+ return m_fileName;
+}
+
+IDocument* DocumentWrapper::document() {
+ return m_document;
+}
+
+void DocumentWrapper::fillDocumentText() {
+ Block b( m_block );
+ if ( m_document && m_document->textDocument() ) {
+ m_document->textDocument() ->setText( ~m_text->text().text() );
+ } else {
+ err() << "cannot update document-text: no document available";
+ }
+}
+
+void DocumentWrapper::openDocument( bool toForeground ) {
+ try {
+ if ( m_document ) {
+ if( toForeground )
+ KDevTeamworkPlugin::staticDocumentController() ->activateDocument( m_document );
+ return ;
+ }
+
+ out( Logger::Debug ) << "openDocument()" << fileName() << "" << toForeground;
+
+ if ( m_tempFile.isEmpty() ) {
+ KUrl subfolder( QString( "filecollaboration" ) );
+ subfolder.addPath( m_session->name() + "_" + QString( "%1").arg(m_session->id() ) );
+
+ QString location;
+ if ( m_session->isMasterSession() ) {
+ location = "local";
+ } else {
+ location = m_session->firstPeerName();
+ }
+
+ ///@todo make this work work remote files
+ m_tempFile = TeamworkFolderManager::createUniqueFile( subfolder.toLocalFile(), m_fileName, "", "@" + m_session->name() ).toLocalFile();
+ }
+
+ out( Logger::Debug ) << "temporary file for" << fileName() << "is" << m_tempFile;
+
+ m_document = KDevTeamworkPlugin::staticDocumentController() ->openDocument( m_tempFile, KTextEditor::Cursor(), toForeground == true ? KDevelop::IDocumentController::DefaultMode : KDevelop::IDocumentController::DoNotActivate );
+
+ if ( m_document ) {
+ KTextEditor::Document * doc = m_document->textDocument();
+ if ( !doc ) {
+ m_document = 0;
+ throw "could not open as text-document";
+ }
+ fillDocumentText();
+
+ /*connect( m_document, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );*/
+ connect( m_document->textDocument(), SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
+ connect( doc, SIGNAL( textInserted ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ), this, SLOT( textInserted ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ) );
+ connect( doc, SIGNAL( textRemoved ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ), this, SLOT( textRemoved ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ) );
+ connect( doc, SIGNAL( textChanged ( KTextEditor::Document *,
+ const KTextEditor::Range &,
+ const KTextEditor::Range & ) ), this, SLOT( textChanged ( KTextEditor::Document *,
+ const KTextEditor::Range &,
+ const KTextEditor::Range & ) ) );
+ } else {
+ throw "could not open document";
+ }
+ } catch ( const QString & str ) {
+ err() << "openDocument():" << str;
+ } catch ( const char * str ) {
+ err() << "openDocument():" << str;
+ }
+}
+
+uint getPositionInDocument( KTextEditor::Document * doc, const KTextEditor::Cursor& cursor ) {
+ QString str = doc->text( KTextEditor::Range( KTextEditor::Cursor( 0, 0 ), cursor ) );
+ return str.length();
+}
+
+void DocumentWrapper::textChanged ( KTextEditor::Document * document, const KTextEditor::Range & oldRange, const KTextEditor::Range & newRange ) {
+ if ( m_block )
+ return ;
+ out( Logger::Debug ) << "textChanged";
+
+ VectorTimestamp v( m_text->state() );
+ v.setPrimaryIndex( m_ownIndex );
+ v.increase();
+
+ int start = m_text->text().lineColumnToLinear( oldRange.start().line(), oldRange.start().column() );
+ int end = m_text->text().lineColumnToLinear( oldRange.end().line(), oldRange.end().column() );
+
+ if ( start == -1 || end == -1 || start == end ) {
+ err() << "textRemoved(..): DynamicText and Document seem to be out of sync";
+
+ fillDocumentText();
+ return ;
+ }
+
+ std::string oldText = m_text->text().substr( start, end - start );
+ QString newText = document->text( newRange );
+
+ if ( oldRange.end().line() == oldRange.start().line() && newRange.end().line() == newRange.start().line() ) {
+ out( Logger::Debug ) << "textChanged at" << start << ":" << oldText << "->" << newText;
+ } else {
+ out( Logger::Debug ) << "textChanged at" << start;
+ }
+
+ ///It might be better to model the edit by one removal and one insertion, because that allows better resolution of conflicts.(Think about if it should be like that)
+ SimpleReplacement r( start, ~newText, oldText );
+
+ try {
+ DYN_VERIFY( !m_disabled );
+ DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
+ Block b( m_block );
+ m_text->insert( v, r );
+ } catch ( const DynamicTextError & error ) {
+ err() << "error in textRemoved(..):" << error.what();
+ fillDocumentText();
+ return ;
+ }
+
+ if ( !m_dead )
+ emit publishEdit( v, r, this );
+}
+
+///All the line/column to/from linear conversion is very slow and should be done different
+void DocumentWrapper::textRemoved ( KTextEditor::Document * /*document*/, const KTextEditor::Range & range ) {
+ if ( m_block )
+ return ;
+ int start = m_text->text().lineColumnToLinear( range.start().line(), range.start().column() );
+ int end = m_text->text().lineColumnToLinear( range.end().line(), range.end().column() );
+
+ if ( start == -1 || end == -1 ) {
+ err() << "textRemoved(..): DynamicText and Document seem to be out of sync";
+ fillDocumentText();
+ return ;
+ }
+
+ std::string oldText = m_text->text().substr( start, end - start );
+
+ if ( range.end().line() == range.start().line() ) {
+ IFDEBUG( out( Logger::Debug ) << "textRemoved at" << start << ":" << document->text( range ) );
+ } else {
+ IFDEBUG( out( Logger::Debug ) << "textRemoved at" << start );
+ }
+
+ SimpleReplacement r( start, "", oldText );
+
+ VectorTimestamp v;
+ try {
+ DYN_VERIFY( !m_disabled );
+ DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
+ Block b( m_block );
+ v = m_text->insert( m_ownIndex, r );
+ } catch ( const DynamicTextError & error ) {
+ err() << "error in textRemoved(..):" << error.what();
+ fillDocumentText();
+ return ;
+ }
+
+ if ( !m_dead )
+ emit publishEdit( v, r, this );
+}
+
+void DocumentWrapper::textInserted ( KTextEditor::Document * document, const KTextEditor::Range & range ) {
+ if ( m_block )
+ return ;
+ VectorTimestamp v;
+
+ QString newText = document->text( range );
+ uint pos = m_text->text().lineColumnToLinear( range.start().line(), range.start().column() );
+
+ if ( range.end().line() == range.start().line() ) {
+ IFDEBUG( out( Logger::Debug ) << "textInserted at" << pos << ":" << document->text( range ) );
+ } else {
+ IFDEBUG( out( Logger::Debug ) << "textInserted at" << pos );
+ }
+
+ SimpleReplacement r = SimpleReplacement( pos, ~newText, "" );
+
+ try {
+ DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
+ DYN_VERIFY( !m_disabled );
+ Block b( m_block );
+ v = m_text->insert( m_ownIndex, r );
+ } catch ( const DynamicTextError & error ) {
+ err() << "error in textInserted(..):" << error.what();
+ fillDocumentText();
+ return ;
+ }
+
+ if ( !m_dead )
+ emit publishEdit( v, r, this );
+}
+
+std::string DocumentWrapper::logPrefix() {
+ return "DocumentWrapper for " + ~fileName() + ": ";
+}
+
+int DocumentWrapper::receiveMessage( FileSynchronize* msg ) {
+ ///@todo merge synchronizations from different clients when self was crashed
+ /*if ( !m_text->state().isZero() ) {
+ err() << "got synchronization although timestamp already is" << m_text->state().print();
+ return ;
+ }*/
+ out( Logger::Debug ) << "got synchronization - current Timestamp:" << m_text->state().print() << "new:" << msg->state().print();
+
+ try {
+ m_text = msg->createDynamicText();
+ connect( m_text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( stateChanged() ) );
+ fillDocumentText();
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful );
+ } catch ( const DynamicTextError & error ) {
+ err() << "error while synchronization:" << error.what();
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
+ }
+
+ return 1;
+}
+
+bool DocumentWrapper::dead() const {
+ return m_dead;
+}
+
+bool DocumentWrapper::disabled() const {
+ return m_disabled;
+}
+
+void DocumentWrapper::setDisabled( bool disabled ) {
+ m_disabled = disabled;
+}
+
+void DocumentWrapper::setDead( bool dead ) {
+ m_dead = dead;
+}
+
+void DocumentWrapper::readFile( bool fromBuffer ) throw ( QString ) {
+ KUrl u = TeamworkFolderManager::workspaceAbsolute( m_fileName );
+
+ if ( !m_text->state().isZero() ) {
+ out( Logger::Warning ) << "readFile called although state already is" << m_text->state().print();
+ }
+
+ QString txt;
+
+ if ( fromBuffer ) {
+ IDocument * doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( u );
+ if ( doc && doc->textDocument() ) {
+ txt = doc->textDocument() ->text();
+ }
+ }
+
+ if ( txt.isEmpty() ) {
+ if ( !u.isLocalFile() )
+ throw QString( "file is not local" );
+ if ( !QFileInfo( u.toLocalFile() ).exists() )
+ throw QString( "file does not exist" );
+
+ QFile f( u.toLocalFile() );
+ if ( !f.open( QIODevice::ReadOnly ) )
+ throw QString( "could not open file" );
+
+ ///@todo What about encoding etc. ?
+ QByteArray b = f.readAll();
+ Block bl( m_block );
+ m_text = new QDynamicText( VectorTimestamp( m_ownIndex, VectorTimestamp() ), b.data() );
+ } else {
+ m_text = new QDynamicText( VectorTimestamp( m_ownIndex, VectorTimestamp() ), txt.toUtf8().data() );
+ }
+ /*m_text->changeState();
+ m_text->insert( m_ownIndex, SimpleReplacement( 0, b.data(), m_text->text() ) );*/
+}
+
+#include "documentwrapper.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp (revision 1522570)
@@ -0,0 +1,263 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "filecollaborationmessages.h"
+#include "filecollaborationmanager.h"
+#include "kdevteamwork.h"
+#include "collaborationmanager.h"
+#include <QMenu>
+#include <ktexteditor/document.h>
+#include "lib/network/messagesendhelper.h"
+#include "lib/network/messagetypeset.h"
+#include "kdevteamwork_helpers.h"
+#include "safesignaller.h"
+#include <boost/serialization/list.hpp>
+#include <boost/serialization/string.hpp>
+#include <boost/serialization/vector.hpp>
+#include "qtserialization.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+Q_DECLARE_METATYPE( MessagePointer )
+
+FileCollaborationRequestData::FileCollaborationRequestData( FileCollaboration* collab, uint index, uint senderIndex ) : m_state( Unknown ), m_index( index ), m_senderIndex( senderIndex ), m_isAutomatic( false ), m_collab( collab ), m_acceptAction( 0 ), m_denyAction( 0 ) {
+
+ if ( collab ) {
+ m_files = collab->session() ->fileNames();
+ if ( collab->session() ) {
+ m_session = collab->session();
+ m_name = collab->session() ->name();
+ connect( ( QObject* ) this, SIGNAL( stateChanged( const MessagePointer& ) ), ( QObject* ) collab->session() ->manager() ->teamwork() ->messageManager(), SLOT( updateMessage( const MessagePointer& ) ), Qt::QueuedConnection );
+ connect( ( QObject* ) this, SIGNAL( connectionResult( bool ) ), ( QObject* ) collab, SLOT( slotConnectionResult( bool ) ), Qt::QueuedConnection );
+ }
+
+ connect( this, SIGNAL( processReply( const MessagePointer& ) ), collab, SLOT( processMessage( const MessagePointer& ) ), Qt::QueuedConnection );
+
+ }
+}
+
+uint FileCollaborationRequestData::index( ) const {
+ return m_index;
+}
+
+uint FileCollaborationRequestData::senderIndex( ) const {
+ return m_senderIndex;
+}
+
+bool FileCollaborationRequestData::isAutomatic() const {
+ return m_isAutomatic;
+}
+
+void FileCollaborationRequestData::setAutomatic( bool automatic ) {
+ m_isAutomatic = automatic;
+}
+
+CollabFileList FileCollaborationRequestData::files() const {
+ return m_files;
+}
+
+void FileCollaborationRequestData::setFiles( const CollabFileList& theValue ) {
+ m_files = theValue;
+}
+
+QString FileCollaborationRequestData::name() const {
+ return m_name;
+}
+
+void FileCollaborationRequestData::setName( const QString& theValue ) {
+ m_name = theValue;
+}
+
+QString FileCollaborationRequest::messageText() const {
+ QString name = "unknown";
+ if ( info().user() )
+ name = ~info().user().unsafe() ->safeName();
+ QString files;
+ for( CollabFileList::const_iterator it = m_files.begin(); it != m_files.end(); ++it ) {
+ if( !files.isEmpty() ) files += "\n";
+ files += (*it).file;
+ }
+ if ( info().isIncoming() ) {
+ return QString( "File-collaboration-request from %1 on:\n%2" ).arg( name ).arg( files );
+ } else {
+ return QString( "File-collaboration-request to %1 on:\n%2" ).arg( name ).arg( files );
+ }
+}
+
+QIcon FileCollaborationRequest::messageIcon() const {
+ switch ( m_state ) {
+ case Unknown:
+ if ( info().isIncoming() )
+ return IconCache::getIconStatic( "filecollaborationrequest_in" );
+ else
+ return IconCache::getIconStatic( "filecollaborationrequest_out" );
+ case Accepted:
+ if ( info().isIncoming() )
+ return IconCache::getIconStatic( "filecollaborationrequest_in_accepted" );
+ else
+ return IconCache::getIconStatic( "filecollaborationrequest_out_accepted" );
+ case Denied:
+ if ( info().isIncoming() )
+ return IconCache::getIconStatic( "filecollaborationrequest_in_denied" );
+ else
+ return IconCache::getIconStatic( "filecollaborationrequest_out_denied" );
+ case Failed:
+ if ( info().isIncoming() )
+ return IconCache::getIconStatic( "filecollaborationrequest_in_failed" );
+ else
+ return IconCache::getIconStatic( "filecollaborationrequest_out_failed" );
+ }
+ return IconCache::getIconStatic( "unknown" );
+}
+
+FileCollaborationRequestData::State FileCollaborationRequestData::state() const {
+ return m_state;
+}
+
+void FileCollaborationRequestData::updateState() {
+ emit stateChanged( ( FileCollaborationRequest* ) this );
+}
+
+bool FileCollaborationRequest::needReply() const {
+ if ( m_collab )
+ return true;
+ else
+ return false;
+}
+
+
+MessageInterface::ReplyResult FileCollaborationRequest::gotReply( const MessagePointer& p ) {
+ if ( !m_collab )
+ return ReplyResult();
+ bool handled = false;
+ MessagePointer msg = p;
+ if ( m_state == Unknown ) {
+ if ( msg.cast<KDevSystemMessage>() ) {
+ LockedSharedPtr<KDevSystemMessage> lmsg = msg.cast<KDevSystemMessage>();
+ if ( lmsg ) {
+ if ( lmsg->message() == KDevSystemMessage::ActionSuccessful ) {
+ m_state = Accepted;
+ emit connectionResult( true );
+ } else if ( lmsg->message() == KDevSystemMessage::ActionDenied ) {
+ m_state = Denied;
+ emit connectionResult( false );
+ } else {
+ m_state = Failed;
+ emit connectionResult( false );
+ }
+ } else {
+ m_state = Failed;
+ emit connectionResult( false );
+ }
+ handled = true;
+ }
+
+ if ( m_state == Unknown && msg.cast<FileCollaborationRequest>() ) {
+ LockedSharedPtr<FileCollaborationRequest> lmsg = msg.cast<FileCollaborationRequest>();
+ if ( lmsg ) {
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( lmsg, KDevSystemMessage::ActionSuccessful );
+ m_state = Accepted;
+ emit connectionResult( true );
+ } else {
+ m_state = Failed;
+ emit connectionResult( false );
+ }
+ handled = true;
+ }
+
+ updateState();
+ }
+
+ emit processReply( p );
+
+ if ( m_state != Denied && m_state != Failed && m_collab && m_session )
+ return ReplyResult( true, true );
+ else
+ return ReplyResult( handled );
+}
+
+void FileCollaborationRequestData::dispatchSignal( const AcceptSignal& /*sig*/ ) {
+ acceptCollaboration();
+}
+
+void FileCollaborationRequestData::dispatchSignal( const DenySignal& /*sig*/ ) {
+ denyCollaboration();
+}
+
+
+void FileCollaborationRequestData::acceptCollaboration() {
+ cout << "acceptCollaboration" << endl;
+
+ MessagePointer::Locked l = ( FileCollaborationRequest* ) this;
+ if ( l && m_teamwork ) {
+ m_state = Accepted;
+ if ( !m_teamwork->collaborationManager() ->fileCollaborationManager().acceptCollaboration( ( FileCollaborationRequest* ) this ) )
+ m_state = Failed;
+ } else {
+ m_state = Failed;
+ }
+
+ updateState();
+}
+
+void FileCollaborationRequestData::denyCollaboration() {
+ cout << "denyCollaboration" << endl;
+ MessagePointer::Locked l = ( FileCollaborationRequest* ) this;
+ if ( l && m_teamwork ) {
+ globalMessageSendHelper().sendReply<KDevSystemMessage> ( l, KDevSystemMessage::ActionDenied );
+ m_state = Denied;
+ m_teamwork->collaborationManager() ->fileCollaborationManager().denyCollaboration( ( FileCollaborationRequest* ) this );
+ } else {
+ m_state = Failed;
+ }
+
+ updateState();
+}
+
+void FileCollaborationRequest::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
+ m_teamwork = teamwork;
+ if ( m_state == Unknown && info().isIncoming() ) {
+
+ /*QAction* a = menu->addAction( "Accept File-Collaboration", this, SLOT(acceptCollaboration()) );
+ QAction* d = menu->addAction( "Deny File-Collaboration", this, SLOT( denyCollaboration() ) );*/
+ QAction* a = menu->addAction( "Accept File-Collaboration", new QSafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::AcceptSignal(), menu ), SLOT( signal() ) );
+ QAction* d = menu->addAction( "Deny File-Collaboration", new QSafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::DenySignal(), menu ), SLOT( signal() ) );
+
+/*
+ connect( a, SIGNAL( triggered( bool ) ), new SafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::AcceptSignal(), menu ), SLOT( signal() ) );
+ connect( d, SIGNAL( triggered( bool ) ), new SafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::DenySignal(), menu ), SLOT( signal() ) );*/
+
+ connect( ( QObject* ) this, SIGNAL( stateChanged( const MessagePointer& ) ), ( QObject* ) teamwork->messageManager(), SLOT( updateMessage( const MessagePointer& ) ), Qt::QueuedConnection );
+
+ QVariant v;
+ v.setValue<MessagePointer>( this );
+ a->setData( v );
+ d->setData( v ); ///This makes sure that the message is not deleted in the wrong moment, and the slots can be called safely by the actions.
+ }
+}
+
+EASY_IMPLEMENT_MESSAGE( FileCollaborationMessage )
+EASY_IMPLEMENT_MESSAGE( DocumentWrapperMessage )
+EASY_IMPLEMENT_MESSAGE( FileCollaborationRequest )
+EASY_IMPLEMENT_MESSAGE( FileEditMessage )
+EASY_IMPLEMENT_MESSAGE( FileListMessage )
+EASY_IMPLEMENT_MESSAGE( FileEditRejectMessage )
+
+#include "filecollaborationmessages.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.h (revision 1522570)
@@ -0,0 +1,70 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SAFELOGGER_H
+#define SAFELOGGER_H
+
+#include <string>
+#include <vector>
+
+#include "lib/network/safesharedptr.h"
+#include "lib/network/logger.h"
+
+class LogSuffix;
+
+/** This class can be used for very comfortable and safe logging: Just derive your own class from it initialize
+ * it with the logger-pointer, and give a log-prefix or override logPrefix(..) for flexible prefixing.
+ *
+ * Then you can use 'out(...) << "your text"' or 'err() << "your text"' to log.
+ * */
+class SafeLogger {
+ public:
+ friend class LogSuffix;
+
+ explicit SafeLogger( Teamwork::LoggerPointer logger, std::string logPrefix = "" );
+
+ virtual ~SafeLogger();
+
+ ///Returns a temporary stream-object(see documentation of Teamwork::LoggerPrinter) for the given log-level.
+ Teamwork::LoggerPrinter out( Teamwork::Logger::Level level = Teamwork::Logger::Info );
+
+ ///Returns a temporary stream-object(see documentation of Teamwork::LoggerPrinter) for error-messages.
+ Teamwork::LoggerPrinter err();
+
+ ///Returns the used logger
+ Teamwork::LoggerPointer logger() const;
+
+ protected:
+ virtual std::string logPrefix();
+ private:
+ Teamwork::LoggerPointer m_logger;
+ std::string m_logPrefix;
+ std::vector<const char*> m_logSuffix;
+};
+
+/**This class can be used to temporarily extend the log-prefix(it can be created locally, and the prefix-suffix is removed as lifetime ends ends)
+ * Warning: For performance-reasons the given text is not copied, so it must live at least as long as this object.
+ * */
+class LogSuffix {
+ public:
+ LogSuffix( const char* txt, SafeLogger* logger );
+ ~LogSuffix();
+ private:
+ LogSuffix& operator = ( const LogSuffix& /*rhs */);
+ LogSuffix( const LogSuffix& /*rhs */);
+ SafeLogger* m_logger;
+};
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.h (revision 1522570)
@@ -0,0 +1,137 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef COLLABORATIONMANAGER_H
+#define COLLABORATIONMANAGER_H
+
+#include "lib/network/safesharedptr.h"
+#include "filecollaborationmessages.h"
+#include "kdevteamwork.h"
+#include "utils.h"
+#include <QObject>
+#include <set>
+#include "safelogger.h"
+#include <QPointer>
+#include <memory>
+
+
+class QPoint;
+class QModelIndex;
+class QMenu;
+class QStandardItemModel;
+
+///These helpers can be used to plug own actions into the tree-structure of the collaboration-manager. To get active, a CollaborationTreeActionPointer must be set as the UserData-entry in the model.
+struct CollaborationTreeAction : public Shared {
+ virtual void fillContextMenu( QMenu* menu ) = 0;
+ virtual void doubleClicked() {
+ }
+ virtual void clicked() {
+ }
+};
+
+///This class will call a fillContextMenu-function in the targetet-class
+template <class targetet, class ValueType = int>
+struct StandardCollaborationTreeAction : public CollaborationTreeAction {
+ QPointer<targetet> target;
+ ValueType var;
+
+ StandardCollaborationTreeAction( targetet* t, const ValueType& v ) : var( v ), target( t ) {}
+ StandardCollaborationTreeAction( targetet* t ) : target( t ) {}
+
+ virtual void fillContextMenu( QMenu* menu ) {
+ if ( target ) {
+ target->fillContextMenu( var, menu );
+ }
+ };
+};
+
+typedef SharedPtr< CollaborationTreeAction > CollaborationTreeActionPointer;
+
+Q_DECLARE_METATYPE( CollaborationTreeActionPointer )
+
+using namespace Teamwork;
+class KDevTeamwork;
+class FileCollaborationManager;
+class FileCollaborationSession;
+typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
+
+using namespace std;
+
+class CollaborationManager : public QObject, public SafeLogger {
+ Q_OBJECT
+ public:
+ CollaborationManager( KDevTeamwork* tw );
+ ~CollaborationManager();
+
+
+ void addCollaboratingUser( const UserPointer& u );
+
+ void removeCollaboratingUser( const UserPointer& user );
+
+ bool isCollaborating( const UserPointer& user );
+
+ void updateList();
+
+ void restorePartialProjectSession( const QDomElement* el );
+
+ void savePartialProjectSession( QDomElement* el );
+
+ void fillUserMenu( QMenu* menu, const UserPointer& user );
+
+ FileCollaborationManager& fileCollaborationManager() ;
+
+ QStandardItemModel* developersModel();
+
+ KDevTeamwork* teamwork();
+ signals:
+ void fillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
+ void updateModel( QStandardItemModel* model );
+
+ public slots:
+ void maybeContextMenu();
+ void init();
+ void collaboratingDeveloperClicked( const QModelIndex& i );
+ void collaboratingDeveloperDoubleClicked( const QModelIndex& i );
+ void collaboratingDeveloperContextMenu( const QPoint& );
+ void uiCloseCollaboration();
+ void updateConnection( const TeamworkClientPointer& );
+ void processMessage( const CollaborationMessagePointer& );
+ void sessionStateChanged( const FileCollaborationSessionPointer& session );
+
+ void uiAcceptCollaboration();
+ void uiDenyCollaboration();
+ void uiRequestCollaboration();
+
+ private:
+ void contextMenu( const QPoint& pos, const QModelIndex& index );
+ friend class ConnectionRequest;
+ KDevTeamwork* m_teamwork;
+ typedef set
+ <UserPointer> UserSet;
+ UserSet m_collaboratingUsers;
+ AutoConstructPointer<FileCollaborationManager> m_fileCollaboration;
+ QStandardItemModel* m_developersModel; ///Model for the collaborating-developers tree-view
+ auto_ptr<QPersistentModelIndex> m_contextMenuIndex; ///Only used for the timer
+
+ QAction* m_requestCollaborationAction;
+ QAction* m_closeCollaborationAction;
+ QAction* m_acceptConnectionAction;
+ QAction* m_denyConnectionAction;
+
+ QTimer* m_contextMenuTimer;
+ bool m_ignoreClick;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.h (revision 1522570)
@@ -0,0 +1,102 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef INDOCUMENTREFERENCE_H
+#define INDOCUMENTREFERENCE_H
+
+#include <QString>
+#include <string>
+#include "lib/network/sharedptr.h"
+#include "sumsearch.h"
+
+class InDocumentReference {
+ int m_line;
+ int m_col;
+ string m_document;
+ typedef SumReference<10> WeakReference;
+ WeakReference m_position;
+ public:
+
+ ///This can be used to speed up the search if multiple positions should be found within one text(then this object should be created outside and reached to findInText.
+ class TextSearchInstance {
+ public:
+ TextSearchInstance( const QString& txt );
+ TextSearchInstance( const TextSearchInstance& rhs );
+ TextSearchInstance();
+ ~TextSearchInstance();
+ operator bool() const;
+ QString text() const;
+ TextSearchInstance& operator = ( const TextSearchInstance& rhs );
+ private:
+ friend class InDocumentReference;
+ class Private;
+ SharedPtr<Private> m_data;
+ };
+
+ static QString createReference( const QString& file, int startLine, int startCol, int endLine, int endCol );
+ static void parseReference( const QString& ref, QString& file, int& startLine, int& startCol, int& endLine, int& endCol );
+
+ ///This creates a reference that refers to a position, but not intelligently.
+ explicit InDocumentReference( bool start = true, const QString& ref = "" );
+
+ InDocumentReference( const QString& document, int line, int col = 0, const QString& text = "" );
+
+ void useText( const QString& text );
+
+ template <class ArchType>
+ void serialize( ArchType& arch, uint /*version*/ ) {
+ arch & m_line & m_col & m_document & m_position;
+ }
+
+ QString document() const;
+
+ ///Finds the reference-position dynamically within the given text. If the search fails, puts -1 -1.
+ void findInText( const TextSearchInstance& text, int& line, int& col ) const;
+
+ bool isValid() const;
+
+ bool isDynamic() const;
+
+ operator bool() const;
+
+ ///findInText(..) should be preferred, because it can find the correct position even if the text changed.
+ int line() const;
+
+ QString asText() const;
+
+ int col() const;
+};
+
+class DocumentContextLines {
+ int m_lineOffset;
+ std::string m_lines;
+
+ public:
+ DocumentContextLines();
+
+ DocumentContextLines( const InDocumentReference& beginRef, const InDocumentReference& endRef, const QString& text, int /*contextSize*/ = 5 );
+
+ template <class Arch>
+ void serialize( Arch& arch, uint /*version*/ ) {
+ arch & m_lineOffset & m_lines;
+ }
+
+ operator bool() const ;
+
+ QString text() const;
+
+ int lineOffset() const;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.h (revision 1522570)
@@ -0,0 +1,131 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef FILECOLLABORATION_H
+#define FILECOLLABORATION_H
+
+#include <QStringList>
+#include <QList>
+#include <QIcon>
+
+#include "lib/network/messagetypeset.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/weaksafesharedptr.h"
+
+#include "filecollaborationmessages.h"
+#include "collaborationmanager.h"
+#include "lib/network/crossmap.h"
+#include "safelogger.h"
+#include "verify.h"
+
+namespace KTextEditor {
+class Document;
+}
+
+class FileCollaborationManager;
+class KDevTeamworkUser;
+class CollaborationManager;
+
+class FileCollaborationManager;
+class FileCollaborationSession;
+class QAction;
+class DocumentWrapper;
+class QModelIndex;
+class QStandardItemModel;
+
+typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
+typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
+typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
+
+// BIND_LIST_2( FileCollaborationDirectMessages, FileCollaborationRequest, FileCollaborationMessage )
+
+class FileCollaborationUserTreeAction;
+
+class FileCollaboration : public QObject, public Shared, public SafeLogger {
+ Q_OBJECT
+ public:
+
+ ///May throw QString
+ FileCollaboration( KDevTeamworkUserPointer user, FileCollaborationSession* session, const FileCollaborationRequestPointer& request = 0 );
+
+ KDevTeamworkUserPointer user() const;
+
+ FileCollaborationSessionPointer session() const;
+
+ ///This collaboration's index in the vector-timestamps
+ uint primaryIndex() const;
+
+ ///Returns whether the other side was invited to join the session by this side
+ bool invited() const;
+
+ ///@return whether the connection is active
+ bool connectionActive() const;
+
+ void close( const QString& reason );
+
+ QIcon icon() const;
+
+ signals:
+ void connectionResult( FileCollaboration*, bool ); ///If true, connection was successful. If false, connection failed.
+
+ public slots:
+ void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
+ void processMessage( const MessagePointer& msg );
+ void slotConnectionResult( bool );
+ void userStateChanged();
+
+ private:
+ void updateTree( QModelIndex& i, QStandardItemModel* model );
+
+ void invite( const FileCollaborationRequestPointer& request, bool automatic ) throw(QString);
+ void doubleClicked();
+ void fillContextMenu( int i, QMenu* menu );
+
+ friend class FileCollaborationUserTreeAction;
+ friend class FileCollaborationSession;
+
+// int receiveMessage( MessageInterface* msg );
+// int receiveMessage( FileSynchronize* msg );
+// int receiveMessage( FileCollaborationRequest* msg );
+// int receiveMessage( FileCollaborationMessage* msg );
+
+ KDevTeamworkUserPointer m_user;
+ FileCollaborationSessionPointer m_session;
+ FileCollaborationRequestPointer m_request;
+
+ QString m_userName;
+ uint m_index; ///The index of the other side this collaboration-object is a bridge to
+
+ bool m_connectionActive;
+ bool m_userConnected;
+ bool m_invited;
+
+ virtual std::string logPrefix();
+
+/* friend class MessageDispatcher< FileCollaboration, FileCollaborationDirectMessages >;
+ MessageDispatcher< FileCollaboration, FileCollaborationDirectMessages > m_dispatcher;*/
+};
+
+typedef SharedPtr<FileCollaboration> FileCollaborationPointer;
+
+struct FileCollaborationUserTreeAction : public StandardCollaborationTreeAction<FileCollaboration> {
+ FileCollaborationUserTreeAction( FileCollaboration* w ) : StandardCollaborationTreeAction<FileCollaboration>( w ) {}
+ virtual void doubleClicked();
+
+ virtual void fillContextMenu( QMenu* menu );
+}
+;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp (revision 1522570)
@@ -0,0 +1,68 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "kdevteamwork_user.h"
+#include "lib/network/teamworkmessages.h"
+#include "kdevteamwork.h"
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/export.hpp>
+#include "kdevteamwork_helpers.h"
+#include "lib/network/sessioninterface.h"
+
+
+KDevTeamworkUser::KDevTeamworkUser( const User* user ) {
+ qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
+ if( user ) {
+ (*(User*)this) = *user;
+ }
+}
+
+KDevTeamworkUser::KDevTeamworkUser( IdentificationMessage* msg ) : User((User)*msg) {
+ qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
+}
+
+void KDevTeamworkUser::setSession( const SessionPointer& sess ) {
+ User::setSession( sess );
+ emit userStateChanged( this );
+}
+
+QIcon KDevTeamworkUser::icon( KIconLoader::Group size ) {
+ SessionPointer s = online().session();
+
+ if( s && s.unsafe()->isOk() ) {
+ SessionPointer::Locked l = s;
+ if( l ) {
+ if( l->sessionType() == SessionInterface::Direct )
+ return IconCache::instance()->getIcon( "presence_online", size );
+ else
+ return IconCache::instance()->getIcon( "presence_away", size );
+ } else {
+ return IconCache::instance()->getIcon( "presence_offline", size );
+ }
+ } else {
+ return IconCache::instance()->getIcon( "presence_offline", size );
+ }
+ return IconCache::instance()->getIcon( "remove" );
+}
+
+QString KDevTeamworkUser::toolTip() {
+ return "";
+}
+
+Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
+BOOST_CLASS_EXPORT_GUID(KDevTeamworkUser, "KDevTeamworkUser")
+
+
+#include "kdevteamwork_user.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp (revision 1522570)
@@ -0,0 +1,152 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "kdevteamwork_client.h"
+#include <list>
+#include <kdebug.h>
+
+#include "kdevteamwork.h"
+#include "helpers.h"
+
+#include "patchmessage.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/teamworkmessages.h"
+#include "lib/network/defines.h"
+#include "kdevteamwork_user.h"
+#include "kdevteamwork_helpers.h"
+
+BIND_LIST_5( KDevTeamworkDispatchMessages, KDevTeamworkTextMessage, KDevSystemMessage, ConnectionRequest, PatchesManagerMessage, CollaborationMessage )
+
+std::string stringToAddr( const QString& txt ) {
+ if ( txt.indexOf( ':' ) != -1 )
+ return txt.left( txt.indexOf( ':' ) ).toUtf8().data();
+ return txt.toUtf8().data();
+}
+
+int stringToPort( const QString& txt ) {
+ if ( txt.indexOf( ':' ) == -1 )
+ return STANDARDPORT;
+ else
+ return txt.mid( txt.indexOf( ':' ) + 1 ).toLong();
+}
+
+
+KDevTeamworkClient::KDevTeamworkClient( KDevTeamwork* teamwork ) : Client( ServerInformation( "0.0.0.0", STANDARDPORT ), teamwork->m_logger.cast<Logger>() ), m_teamwork( teamwork ) {
+ qRegisterMetaType<Teamwork::UserPointer>( "Teamwork::UserPointer" );
+ qRegisterMetaType<Teamwork::ClientSessionDesc>( "Teamwork::ClientSessionDesc" );
+ qRegisterMetaType<Teamwork::ServerInformation>( "Teamwork::ServerInformation" );
+ qRegisterMetaType<SafeSharedPtr<KDevTeamworkTextMessage> >( "SafeSharedPtr<KDevTeamworkTextMessage>" );
+ qRegisterMetaType<ConnectionRequestPointer >( "ConnectionRequestPointer" );
+ qRegisterMetaType<std::list<UserPointer> >( "std::list<UserPointer>" );
+ qRegisterMetaType<SafeSharedPtr<KDevSystemMessage> >( "SafeSharedPtr<KDevSystemMessage>" );
+ qRegisterMetaType<PatchesManagerMessagePointer >( "PatchesManagerMessagePointer" );
+ qRegisterMetaType<CollaborationMessagePointer >( "CollaborationMessagePointer" );
+
+ connect( this, SIGNAL( guiUserConnected( Teamwork::UserPointer ) ), m_teamwork, SLOT( guiUserConnected( Teamwork::UserPointer ) ), Qt::QueuedConnection );
+ connect( this, SIGNAL( guiUserDisconnected( Teamwork::UserPointer ) ), m_teamwork, SLOT( guiUserDisconnected( Teamwork::UserPointer ) ), Qt::QueuedConnection );
+ connect( this, SIGNAL( guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), m_teamwork, SLOT( guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), Qt::QueuedConnection );
+ connect( this, SIGNAL( guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), m_teamwork, SLOT( guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), Qt::QueuedConnection );
+ connect( this, SIGNAL( guiUserList( std::list<UserPointer> ) ), m_teamwork, SLOT( guiUserList( std::list<UserPointer> ) ), Qt::QueuedConnection );
+
+ // messageTypes().registerMessageTypes<KDevTeamworkMessages>();
+ setIdentity( new User( "server&client" ) );
+}
+
+int KDevTeamworkClient::receiveMessage( KDevSystemMessage* msg ) {
+ if ( m_teamwork )
+ QMetaObject::invokeMethod( m_teamwork, "receiveMessage", Qt::QueuedConnection, Q_ARG( SafeSharedPtr<KDevSystemMessage>, msg ) );
+ return 1;
+}
+
+int KDevTeamworkClient::receiveMessage( CollaborationMessage* msg ) {
+ emit signalDispatchMessage( CollaborationMessagePointer( msg ) );
+ return 1;
+}
+
+int KDevTeamworkClient::receiveMessage( PatchesManagerMessage* msg ) {
+ emit signalDispatchMessage( PatchesManagerMessagePointer( msg ) );
+ return 1;
+}
+
+int KDevTeamworkClient::receiveMessage( KDevTeamworkTextMessage* msg ) {
+ if ( m_teamwork )
+ QMetaObject::invokeMethod( m_teamwork, "handleTextMessage", Qt::QueuedConnection, Q_ARG( SafeSharedPtr<KDevTeamworkTextMessage>, msg ) );
+ return 1;
+}
+
+int KDevTeamworkClient::receiveMessage( ConnectionRequest* msg ) {
+ out( Logger::Debug ) << "dispatching connection-request";
+ if ( m_teamwork )
+ QMetaObject::invokeMethod( m_teamwork, "connectionRequest", Qt::QueuedConnection, Q_ARG( ConnectionRequestPointer, msg ) );
+ return 1;
+}
+
+void KDevTeamworkClient::gotUserList( const std::list<UserPointer>& users ) {
+ emit guiUserList( users );
+}
+
+UserPointer KDevTeamworkClient::createUser( IdentificationMessage* msg ) {
+ return new KDevTeamworkUser( msg );
+}
+
+
+UserPointer KDevTeamworkClient::createUser( const User* user ) {
+ return new KDevTeamworkUser( user );
+}
+
+///this is called whenever a new user successfully logged into the server
+void KDevTeamworkClient::userConnected( const Teamwork::UserPointer& user ) {
+ kDebug(9500) << "userConnected";
+
+ emit guiUserConnected( user );
+
+ Client::userConnected( user );
+
+}
+
+///called whenever a user leaves the server
+void KDevTeamworkClient::userDisconnected( const Teamwork::UserPointer& user ) {
+ kDebug(9500) << "userDisconnected";
+
+ emit guiUserDisconnected( user );
+
+ Client::userDisconnected( user );
+}
+
+///this is called whenever a connection is successfully established to a server
+void KDevTeamworkClient::connectedToServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server ) {
+ kDebug(9500) << "connectedToServer";
+
+ emit guiServerConnected( session, server );
+
+ Client::connectedToServer( session, server );
+}
+
+///this is called whenever a server the client disconnects from a connected server in any way
+void KDevTeamworkClient::disconnectedFromServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server ) {
+ kDebug(9500) << "disconnectedFromServer";
+
+ emit guiServerDisconnected( session, server );
+
+ Client::disconnectedFromServer( session, server );
+}
+
+void KDevTeamworkClient::processMessage( MessageInterface* msg ) throw() {
+ Teamwork::MessageDispatcher< KDevTeamworkClient, KDevTeamworkDispatchMessages> dispatcher( *this );
+ if( !dispatcher( msg ) )
+ Teamwork::Client::processMessage( msg );
+}
+
+#include "kdevteamwork_client.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h (revision 1522570)
@@ -0,0 +1,189 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef FILECOLLABORATIONSESSION_H
+#define FILECOLLABORATIONSESSION_H
+
+#include <QStringList>
+#include <QList>
+
+#include "teamworkfwd.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/weaksafesharedptr.h"
+
+#include "filecollaborationmessages.h"
+#include "lib/network/crossmap.h"
+#include "safelogger.h"
+
+class VectorTimestamp;
+class FileCollaboration;
+typedef SharedPtr<FileCollaboration> FileCollaborationPointer;
+class FileCollaborationSession;
+typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
+class DocumentWrapper;
+class FileCollaborationManager;
+typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
+
+NAMED_TYPE( SessionName, QString );
+
+class FileCollaborationSession : public QObject, public WeakShared, public SafeLogger {
+ Q_OBJECT
+ public:
+
+ enum State {
+ Running,
+ Finished
+ };
+
+ ///Collaboration-class, the associated user
+ BIND_LIST_2( Keys, FileCollaborationPointer, UserPointer )
+ ///Document-Wrapper, its index, filename
+ BIND_LIST_3( FileKeys, DocumentWrapperPointer, uint, QString )
+ BIND_LIST_3( Messages, FileCollaborationMessage, DocumentWrapperMessage, FileListMessage )
+
+ typedef Utils::CrossMap<DocumentWrapperPointer, FileKeys> FileSet;
+
+ FileCollaborationSession( QString name, CollabFileList files, FileCollaborationManager* manager, uint primaryIndex, CollabSessionId id = 0 );
+
+ void inviteUser( const KDevTeamworkUserPointer& user );
+
+ void kickUser( const KDevTeamworkUserPointer& user );
+
+ FileCollaborationManager* manager();
+
+ bool acceptMessage( const FileCollaborationRequestPointer& msg );
+
+ const FileSet& files() const;
+
+ QString name() const;
+
+ QList<KDevTeamworkUserPointer> users() const;
+
+ //void processMessage( const FileCollaborationMessagePointer& msg );
+ int processMessage( FileCollaborationMessage* msg );
+
+ CollabFileList fileNames() const;
+
+ QStringList plainFileNames() const;
+
+ QList<uint> plainIds() const;
+
+ CollabSessionId id() const;
+
+ State state() const;
+
+ QIcon icon() const;
+
+ bool isMasterSession() const;
+
+ uint primaryIndex() const;
+
+ void updateTree( QModelIndex& i, QStandardItemModel* model );
+
+ void fillContextMenu( int i, QMenu* menu );
+
+ ///Allocates a new timestamp-index(for a new collaborator)
+ uint allocateIndex();
+
+ uint allocateWrapperIndex();
+
+ ///Returns the name of the first online peer-user, or empty string
+ QString firstPeerName();
+
+ ///This allows/disallows connected users to add own files to the collaboration
+ void setAllowSentDocuments( bool allow );
+ signals:
+ void userJoined( const KDevTeamworkUserPointer& );
+ void userLeft( const KDevTeamworkUserPointer& );
+ ///Emitted whenever an important information(file-set, user-set, etc.) changed
+ void stateChanged( const FileCollaborationSessionPointer& );
+ void documentSetChanged();
+
+ public slots:
+ void saveAsFiles();
+ void saveAsPatch();
+ void disableEditing();
+ void enableEditing();
+ void removeAllFiles();
+ void slotPublishFileList();
+ void publishStateChange();
+ void addFile();
+ void stopSession();
+ void closeSession();
+ void publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender );
+ void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
+ void slotConnectionResult( FileCollaboration*, bool ); ///If true, connection was successful. If false, connection failed.
+ private slots:
+ void removeUserAction();
+ private:
+ int receiveMessage( MessageInterface* msg );
+ int receiveMessage( FileListMessage* msg );
+ int receiveMessage( FileCollaborationMessage* msg );
+ int receiveMessage( DocumentWrapperMessage* msg );
+
+ void removeCollaboration( const FileCollaborationPointer& collab );
+
+ QAction* getRemoveUserAction( const UserPointer& user );
+
+ void publishFileRemove( uint id );
+ void publishFileList( const CollabFileList& files );
+
+ bool synchronizeFile( const FileCollaborationPointer& collab, const DocumentWrapperPointer& wrapper );
+
+ ///Does not necessarily remove the file, maybe it only disables collaboration on it.
+ bool killFile( uint id );
+ bool removeFile( uint id );
+ uint addFileInternal( const CollabFile& file, bool fromBuffer, bool readFile );
+
+ void aboutToClose();
+
+ virtual std::string logPrefix();
+
+ DocumentWrapperPointer getDocument( const QString& fileName );
+
+ friend class FileCollaboration;
+ friend class FileCollaborationManager;
+
+ ///May throw QString on error
+ FileCollaborationPointer newCollaboration( const KDevTeamworkUserPointer& u, const FileCollaborationRequestPointer& request = 0 );
+
+
+ FileSet m_files;
+ typedef Utils::CrossMap
+ <FileCollaborationPointer, Keys> CollaborationSet;
+ /*UserSet m_ivitedUsers; ///All users that are invited to join
+ UserSet m_users; ///All users that are actively collaborating*/
+ CollaborationSet m_collaborations;
+ FileCollaborationManager* m_manager;
+ CollabSessionId m_id;
+
+ bool m_allowSentDocuments;
+ bool m_isMasterSession;
+ uint m_primaryIndex;
+ uint m_indexCount;
+ uint m_wrapperIndexCount;
+ QString m_name;
+ QTimer* m_publishFileListTimer;
+ QTimer* m_stateChangeTimer;
+
+ QAction* m_removeUserAction;
+
+ friend class MessageDispatcher< FileCollaborationSession, Messages >;
+ MessageDispatcher< FileCollaborationSession, Messages > m_dispatcher;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp (revision 1522570)
@@ -0,0 +1,502 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#include "messagehistorymanager.h"
+#include <fstream>
+#include <QDate>
+#include <QMap>
+#include <QTimer>
+#include <kurl.h>
+#include <klockfile.h>
+#include <kio/netaccess.h>
+
+#include "lib/network/serialization.h"
+#include "lib/network/messageserialization.h"
+
+#include "kdevteamwork_messages.h"
+#include "kdevteamwork_user.h"
+#include "teamworkfoldermanager.h"
+
+
+#include <boost/serialization/vector.hpp>
+#include <boost/serialization/map.hpp>
+#include <boost/archive/xml_iarchive.hpp>
+#include <boost/archive/xml_oarchive.hpp>
+#include <boost/archive/binary_iarchive.hpp>
+#include <boost/archive/binary_oarchive.hpp>
+#include <boost/serialization/level.hpp>
+
+#include <QDir>
+#include "kdevteamwork_client.h"
+//#include <map>
+
+using namespace Teamwork;
+
+struct FileEntryHeader {
+ int version;
+ int messages;
+ FileEntryHeader( int _messages=0 ) : version(1), messages(_messages) {
+ }
+
+ void read( istream& str ) {
+ str >> version >> messages;
+ }
+ void write( ostream& str ) {
+ str << version << endl << messages << endl;
+ }
+};
+
+HistoryMessageDesc::HistoryMessageDesc() {
+}
+
+HistoryMessageDesc::HistoryMessageDesc( const HistoryMessagePointer& msg )
+{
+ message = msg;
+ HistoryMessagePointer::Locked l = msg;
+ if( l ) {
+ isIncoming = l->info().isIncoming();
+
+ UserPointer::Locked lu = userFromSession( l->info().session() );
+ if( lu ) {
+ user = lu->identity();
+ } else {
+ }
+ } else {
+ }
+}
+
+MessageHistoryManager::MessageHistoryManager( Teamwork::LoggerPointer logger ) : m_logger(logger) {
+ m_pendingTimer = new QTimer();
+ m_pendingTimer->start( 1000 );
+ m_lockFile = new KLockFile( lockFileName() );
+ connect( m_pendingTimer, SIGNAL( timeout() ), this, SLOT( writePending() ) );
+}
+
+MessageHistoryManager::~MessageHistoryManager() {
+}
+
+void MessageHistoryManager::addMessage( KDevTeamworkTextMessage* msg ) {
+ HistoryMessageDesc m( msg );
+ m_pending << m;
+ emit newMessage( msg );
+}
+
+QList< HistoryMessagePointer > MessageHistoryManager::getMessages( const KDevTeamworkClientPointer& client, const QDate& from, const QDate& until, UserSet users ) {
+ writePending();
+ QStringList interestingFiles;
+ QList< HistoryMessageDesc > ret;
+ try {
+ KUrl kdir = directory();
+
+ if( !kdir.isLocalFile() )
+ throw QString( "directory \"%1\" is not local" ).arg( kdir.prettyUrl() );
+
+ QDir dir( kdir.toLocalFile() );
+ if( !dir.isReadable() ) throw QString( "directory \"%1\" is not readable" ).arg( dir.path() );
+
+ QStringList files = dir.entryList( QDir::Files );
+
+ for( QStringList::iterator it = files.begin(); it != files.end(); ++it ) {
+ QDate date = QDate::fromString( *it, Qt::ISODate );
+ if( !date.isValid() ) continue;
+ if( from.isValid() ) {
+ if( until.isValid() ) {
+ ///from "from" until "until"
+ if( date >= from && date <= until )
+ interestingFiles << *it;
+ } else {
+ ///from "from" until now
+ if( date >= from )
+ interestingFiles << *it;
+ }
+ } else {
+ if( until.isValid() ) {
+ ///from begin until "until"
+ if( date <= until )
+ interestingFiles << *it;
+ } else {
+ ///All messages
+ interestingFiles << *it;
+ }
+ }
+ }
+
+ for( QStringList::iterator it = interestingFiles.begin(); it != interestingFiles.end(); ++it ) {
+ KUrl fileUrl = kdir;
+ fileUrl.addPath( *it );
+ std::ifstream f( fileUrl.toLocalFile().toLatin1(), ios_base::binary );
+ if( !f.good() ) {
+ err() << "could not open" << ~fileUrl.toLocalFile();
+ }
+ while( !f.eof() ) {
+ if( !f.good() ) {
+ err() << "error while reading" << ~fileUrl.toLocalFile();
+ break;
+ }
+
+ FileEntryHeader header;
+ header.read( f );
+
+ //f.read( (char*)&header, sizeof( FileEntryHeader ) );
+ if( f.eof() ) break;
+
+ if( !f.good() ) {
+ err() << "could not read a header from file \"" << ~*it << "\"";
+ break;
+ } else {
+ out( Logger::Debug ) << "successfully read a header";
+ }
+
+ try {
+ ///read the message from the archive
+ boost::archive::xml_iarchive arch( f );
+ QList<HistoryMessageDesc> messages;
+ for( int a = 0; a < header.messages; a++ ) {
+ HistoryMessageDesc msg;
+ arch >> boost::serialization::make_nvp( "message", msg );
+ if( users.empty() || users.contains( msg.user ) )
+ ret << msg;
+ }
+ }
+ catch( std::exception& exc ) {
+ err() << "error while deserializing from \"" << ~*it << "\":" << exc.what();
+ break;
+ }
+ }
+ }
+
+ }
+ catch( QString str ) {
+ err() << "error in MessageHistoryManager::getMessages:" << ~str;
+ }
+
+ return fillMessageUsers( ret, client );
+}
+
+struct WaitError {
+ QString str;
+ WaitError( const QString& stri ) : str( stri ) {
+ }
+};
+
+void MessageHistoryManager::writePending()
+{
+ try
+ {
+ KUrl dir = directory();
+ if( !dir.isLocalFile() ) throw QString( "the directory %1 is not local" ).arg( dir.prettyUrl() );
+
+ m_pendingTimer->start( 1000 );
+ QMap< QDate, QList<HistoryMessageDesc> > map;
+ std::map< Teamwork::UniqueMessageId, HistoryGroupLocation > insertions;
+
+ for( QList<HistoryMessageDesc>::iterator it = m_pending.begin(); it != m_pending.end(); ++it ) {
+ HistoryMessagePointer::Locked l = it->message;
+ if( l ) {
+ QDate key( l->creationTime().date() );
+ map[ key ] << *it;
+ } else {
+ err() << "could not lock a message for storing it into the history, the message will be lost";
+ }
+ }
+
+ for( QMap< QDate, QList<HistoryMessageDesc> >::iterator it = map.begin(); it != map.end(); ++it ) {
+ QDate date( it.key() );
+
+ if( !date.isValid() ) {
+ err() << "tried to store" << it->count() << "messages with invalid date";
+ continue;
+ }
+
+ if( !m_lockFile->isLocked() ) {
+ switch( m_lockFile->lock( KLockFile::NoBlockFlag | KLockFile::ForceFlag ) ) {
+ case KLockFile::LockOK:
+ break;
+ case KLockFile::LockFail:
+ throw WaitError( "locking the lockfile " + lockFileName() + " failed" );
+ break;
+ case KLockFile::LockError:
+ throw "an error occurred while locking the lockfile " + lockFileName();
+ break;
+ case KLockFile::LockStale:
+ throw WaitError( "the lockfile " + lockFileName() + " is stale" );
+ }
+ }
+
+ KUrl file = dir;
+ QString localFileName = date.toString( Qt::ISODate );
+ file.addPath( localFileName );
+ std::string fileName = ~file.toLocalFile();
+
+ if( fileName.empty() ) {
+ err() << "empty file-path for date" << ~date.toString( Qt::ISODate );
+ continue;
+ }
+
+ std::ofstream f( fileName.c_str(), ios_base::binary | ios_base::app );
+
+ if( !f.good() ) {
+ err() << "could not open file \"" << fileName << "\" for read/write";
+ continue;
+ }
+ f.seekp( 0, std::ios_base::end );
+
+ FileEntryHeader header( it->count() );
+
+ HistoryGroupLocation location;
+ location.fileName = ~localFileName;
+ location.offset = f.tellp();
+
+ header.write( f );
+ //f.write( (char*)&header, sizeof( FileEntryHeader ) );
+
+ if( !f.good() ) {
+ err() << "could not write header into file \"" << fileName << "\"";
+ continue;
+ }
+
+ try {
+ ///Store the messages into the archive
+ boost::archive::xml_oarchive arch( f );
+ for( QList<HistoryMessageDesc>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
+ arch << boost::serialization::make_nvp( "message", *it2 );
+
+ HistoryMessagePointer::Locked l = it2->message;
+ if( l ) {
+ insertions[ l->info().uniqueId() ] = location;
+ } else {
+ err() << "could not lock a message while storing it into the history";
+ }
+ }
+ }
+ catch( std::exception& exc ) {
+ err() << "error while serializing into \"" << fileName << "\":" << exc.what();
+ }
+ }
+
+ ///The index maps unique-message-ids to the files they can be found in(including offset to the FileEntryHeader)
+ std::map<Teamwork::UniqueMessageId, HistoryGroupLocation> index;
+
+ if( !insertions.empty() ) {
+ try {
+ readIndex( index );
+ }
+ catch( QString str ) {
+ out( Logger::Warning ) << "error in readIndex:" << str;
+ }
+
+ index.insert( insertions.begin(), insertions.end() );
+
+ writeIndex( index );
+ }
+
+
+ m_pending.clear();
+ }
+ catch( WaitError err ) {
+ out( Logger::Warning ) << "in MessageHistoryManager::writePending:" << err.str;
+ }
+ catch( QString str )
+ {
+ err() << "error in MessageHistoryManager::writePending:" << str;
+ m_pending.clear();
+ }
+
+ if( m_lockFile->isLocked() )
+ m_lockFile->unlock();
+}
+
+QString MessageHistoryManager::lockFileName() {
+ KUrl file = directory();
+ file.addPath( ".lock" );
+ return file.toLocalFile();
+}
+
+void MessageHistoryManager::readIndex( std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString) {
+ KUrl ind = directory();
+ ind.addPath( "index" );
+ if( !ind.isLocalFile() ) throw QString( "the index-file is not local" );
+
+ std::string indexFile = ~ind.toLocalFile();
+
+ {
+ std::ifstream f( indexFile.c_str(), ios_base::binary );
+ if( !f.good() ) throw QString( "could not open index-file for reading" );
+
+ try {
+ boost::archive::binary_iarchive arch( f );
+ arch & index;
+ }
+ catch( std::exception& exc ) {
+ err() << "error while deserializing the index \"" << indexFile << "\":" << exc.what();
+ throw QString( "error in readIndex" );
+ }
+ }
+}
+
+void MessageHistoryManager::writeIndex( const std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString) {
+ {
+ KUrl ind = directory();
+ ind.addPath( "index" );
+ if( !ind.isLocalFile() ) throw QString( "the index-file is not local" );
+
+ std::string indexFile = ~ind.toLocalFile();
+
+ std::ofstream f( indexFile.c_str(), ios_base::binary );
+ if( !f.good() ) throw QString( "could not open index-file for writing" );
+
+ try {
+ ///Store the messages into the archive
+ boost::archive::binary_oarchive arch( f );
+ arch & index;
+ }
+ catch( std::exception& exc ) {
+ err() << "error while serializing the index \"" << indexFile << "\":" << exc.what();
+ throw QString( "error in writeIndex" );
+ }
+ }
+}
+
+KUrl MessageHistoryManager::directory() throw(QString)
+{
+ KUrl ul = TeamworkFolderManager::teamworkAbsolute( "messages" );
+ TeamworkFolderManager::createTeamworkFolder();
+
+ if( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ KIO::NetAccess::mkdir( ul, 0 );
+
+ if( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ throw QString( "could not create messages-directory " ) + ul.toLocalFile();
+
+ return ul;
+}
+
+void MessageHistoryManager::readMessages( const QString& file, uint offset, QList<HistoryMessageDesc>& messages ) throw(QString)
+{
+ KUrl path = directory();
+ path.addPath( file );
+
+ if( !path.isLocalFile() ) throw QString( "message is not local" );
+ if( !KIO::NetAccess::exists( path, KIO::NetAccess::SourceSide, 0 ) ) throw QString( "index does not exist" );
+
+ std::ifstream f( path.toLocalFile().toLatin1(), ios_base::binary );
+ f.seekg( offset );
+ if( !f.good() || f.eof() ) throw QString( "could not open file and seek to offset %1 in file %2" ).arg( offset ).arg( path.toLocalFile() );
+
+ FileEntryHeader header;
+
+ header.read( f );
+ if( !f.eof() ) {
+ if( !f.good() || f.eof() )
+ throw QString( "could not read a header from file \"%1\"" ).arg( path.toLocalFile() );
+
+ try {
+ boost::archive::xml_iarchive arch( f );
+ for( int a = 0; a < header.messages; a++ ) {
+ HistoryMessageDesc msg;
+ arch >> boost::serialization::make_nvp( "message", msg );
+ messages << msg;
+ }
+ }
+ catch( std::exception& exc ) {
+ err() << "error while deserializing from \"" << ~path.toLocalFile() << "\":" << exc.what();
+ }
+ }
+}
+
+HistoryMessagePointer MessageHistoryManager::getMessageFromId( Teamwork::UniqueMessageId id, const KDevTeamworkClientPointer& client ) {
+ std::map<Teamwork::UniqueMessageId, HistoryGroupLocation> index;
+ try {
+ readIndex( index );
+ std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>::iterator it = index.find( id );
+ if( it != index.end() ) {
+ QList<HistoryMessageDesc> messages;
+ readMessages( ~it->second.fileName, it->second.offset, messages );
+
+ for( QList<HistoryMessageDesc>::iterator it = messages.begin(); it != messages.end(); ++it ) {
+ HistoryMessagePointer::Locked l = it->message;
+ if( l ){
+ if( l->info().uniqueId() == id ) {
+ return fillMessageUser( *it, client );
+ }
+ }
+ }
+
+ return HistoryMessagePointer();
+ } else {
+ return HistoryMessagePointer();
+ }
+ }
+ catch( QString str ) {
+ err() << "error in messageFromId:" << ~str;
+ return HistoryMessagePointer();
+ }
+}
+
+HistoryMessagePointer MessageHistoryManager::fillMessageUser( const HistoryMessageDesc& desc, const KDevTeamworkClientPointer& client ) {
+ HistoryMessagePointer::Locked lmsg = desc.message;
+ KDevTeamworkClientPointer::Locked l = client;
+ if( !l ) {
+ err() << "could not lock KDevTeamworkClient";
+ return HistoryMessagePointer();
+ }
+ if( lmsg ) {
+ lmsg->info().setUser( l->getUser( desc.user ) );
+ return lmsg;
+ } else {
+ err() << "could not lock a message in fillMessageUsers";
+ }
+
+ return HistoryMessagePointer();
+}
+
+QList<HistoryMessagePointer> MessageHistoryManager::fillMessageUsers( const QList<HistoryMessageDesc>& messages, const KDevTeamworkClientPointer& client ) {
+ QList<HistoryMessagePointer> ret;
+ KDevTeamworkClientPointer::Locked l = client;
+
+ if( l ) {
+ foreach( const HistoryMessageDesc& desc, messages ) {
+ HistoryMessagePointer::Locked lmsg = desc.message;
+ if( lmsg ) {
+ lmsg->info().setUser( l->getUser( desc.user ) );
+ ret << lmsg;
+ } else {
+ err() << "could not lock a message in fillMessageUsers";
+ }
+ }
+ } else {
+ err() << "could not lock teamwork-client";
+ }
+
+ return ret;
+}
+
+Teamwork::LoggerPrinter MessageHistoryManager::out( Teamwork::Logger::Level level ) {
+ Teamwork::LoggerPrinter ret( m_logger, level );
+ ret << "in MessageHistoryManager: ";
+ return ret;
+}
+
+
+Teamwork::LoggerPrinter MessageHistoryManager::err() {
+ Teamwork::LoggerPrinter ret( m_logger, Teamwork::Logger::Error );
+ ret << "Error in MessageHistoryManager: ";
+ return ret;
+}
+
+BOOST_CLASS_IMPLEMENTATION(HistoryMessageDesc, boost::serialization::object_serializable)
+
+#include "messagehistorymanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h (revision 1522570)
@@ -0,0 +1,116 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef VECTORTIMESTAMPEDITOR_H
+#define VECTORTIMESTAMPEDITOR_H
+
+#include "lib/network/sharedptr.h"
+#include <QObject>
+#include "ui_kdevteamwork_vectortimestampwidget.h"
+#include "ui_kdevteamwork_timestampwidget.h"
+#include "safelogger.h"
+#include <QList>
+#include <QDateTime>
+#include <QPointer>
+#include "loglevel.h"
+#include "lib/dynamictext/vectortimestamp.h"
+#include "lib/network/logger.h"
+
+class VectorTimestampEditor;
+class TimestampEditor;
+class QDynamicText;
+class QStandardItemModel;
+class Replacement;
+class BoostSerialization;
+class QVBoxLayout;
+
+typedef SharedPtr< QDynamicText, BoostSerializationNormal > QDynamicTextPointer;
+typedef SharedPtr<TimestampEditor> TimestampEditorPointer;
+typedef SharedPtr< Replacement, BoostSerializationNormal > ReplacementPointer;
+
+
+class TimestampEditor : public QObject, public Shared, public SafeLogger {
+ Q_OBJECT
+ public:
+ TimestampEditor( Teamwork::LoggerPointer logger, VectorTimestampEditor* parent, uint index );
+
+ void update();
+ private slots:
+ void tail();
+ void none();
+ void enableAll();
+ void stampChanged();
+ void dateChanged( const QDateTime& );
+ void enableChanged( bool );
+ private:
+ void fillWidgets();
+
+ bool trySeekTo( Timestamp s );
+
+ ///This returns the currently edited stamp. It the first one not currently applied to the tree.
+ Timestamp stamp();
+
+ ///This returns the currently edited replacement, or zero.
+ ReplacementPointer replacement();
+
+ VectorTimestampEditor* m_parent;
+ uint m_index;
+ Timestamp m_currentStamp;
+ Ui_TimestampWidget m_widgets;
+ bool m_block;
+};
+
+class VectorTimestampEditorLogger : public Teamwork::Logger {
+ public:
+ VectorTimestampEditorLogger( VectorTimestampEditor* ed );
+ virtual void log( const std::string& str , Level lv );
+ private:
+ VectorTimestampEditor* m_editor;
+};
+
+///If the parent is destroyed, VectorTimestampEditor is destroyed too. Also it destroys itself if "finish" is clicked, or the dynamic text is destroyed.
+class VectorTimestampEditor : public QObject, public SafeLogger {
+ Q_OBJECT
+ public:
+ ///If embed is false, a new dialog will be created
+ VectorTimestampEditor( Teamwork::LoggerPointer logger, QObject* parent, bool embed, QDynamicTextPointer text, bool editable );
+ ~VectorTimestampEditor();
+
+ QDynamicTextPointer text();
+
+ void log( const QString& str, LogLevel level = Info );
+
+ private slots:
+ void toTailTimestamp();
+ void clearLog();
+ void finish();
+ void textChanged();
+ void textDestroyed();
+
+ private:
+ void fillWidgets();
+
+ friend class TimestampEditor;
+
+ QDynamicText* m_text;
+ bool m_editable;
+ bool m_embed;
+ Ui_VectorTimestampWidget m_widgets;
+ QList< TimestampEditorPointer > m_timestamps;
+ QStandardItemModel* m_logModel;
+ QVBoxLayout* m_layout;
+ QPointer<KDialog> m_dialog; ///Can be zero
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h (revision 1522570)
@@ -0,0 +1,103 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGESHOWER_H
+#define MESSAGESHOWER_H
+
+class QWidget;
+class KDevTeamworkTextMessage;
+class KDevTeamwork;
+class KDevTeamworkUser;
+class InDocumentMessage;
+
+#include <QObject>
+#include "ui_kdevteamwork_textmessage.h"
+#include "ui_kdevteamwork_userinfo.h"
+#include <QPointer>
+#include "lib/network/safesharedptr.h"
+#include "kdevteamwork_helpers.h"
+#include "safelogger.h"
+#include "autoconstructpointer.h"
+
+
+class MessageSerialization;
+
+class InDocumentMessageShowerData;
+
+namespace Teamwork {
+class MessageInterface;
+typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
+}
+
+using namespace Teamwork;
+
+class KDevTeamworkMessageShower : public QObject {
+ Q_OBJECT
+ public:
+ KDevTeamworkMessageShower( KDevTeamworkTextMessage* msg, QWidget* widget, KDevTeamwork* teamwork );
+ public slots:
+ virtual void isReplyToButton();
+ virtual void menuButton();
+ virtual void historyButton();
+ virtual void userStateChanged();
+ virtual void messageUpdated( const MessagePointer& msg );
+ protected:
+ SafeSharedPtr<KDevTeamworkTextMessage> m_message;
+ QWidget* m_widget;
+ Ui_TextMessageShower m_widgetData;
+ QPointer<KDevTeamwork> m_teamwork;
+
+ virtual void fillData();
+
+ private:
+ void fill();
+};
+
+
+class KDevTeamworkUserInfoShower : public QObject {
+ Q_OBJECT
+ public:
+ KDevTeamworkUserInfoShower( KDevTeamworkUser* user, QWidget* widget, KDevTeamwork* teamwork );
+ public slots:
+ virtual void menuButton();
+ virtual void historyButton();
+ virtual void userStateChanged();
+ private:
+ void setIp();
+ void setStatus();
+ void setIcon();
+
+ SafeSharedPtr< KDevTeamworkUser > m_user;
+ QWidget* m_widget;
+ Ui_UserInfo m_widgetData;
+ QPointer<KDevTeamwork> m_teamwork;
+};
+
+class InDocumentMessageShower : public KDevTeamworkMessageShower, private SafeLogger {
+ Q_OBJECT
+ public:
+ InDocumentMessageShower( InDocumentMessage* msg, QWidget* widget, KDevTeamwork* teamwork );
+ public slots:
+ void fileClicked();
+ void contextClicked();
+ protected:
+
+ virtual void fillData();
+ private:
+ void fill();
+ AutoConstructPointer<InDocumentMessageShowerData> m_data;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp (revision 1522570)
@@ -0,0 +1,1280 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "conversationmanager.h"
+#include "lib/network/serialization.h"
+
+#include <boost/archive/polymorphic_xml_oarchive.hpp>
+#include <boost/archive/polymorphic_xml_iarchive.hpp>
+#include <boost/serialization/list.hpp>
+
+#include <QPalette>
+#include <QColor>
+#include <QPoint>
+#include <QMenu>
+#include <QTimer>
+#include <QStandardItemModel>
+#include <QHeaderView>
+#include <QBrush>
+#include <QMutexLocker>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+#include <ktexteditor/cursor.h>
+#include <ktexteditor/markinterface.h>
+#include <ktexteditor/attribute.h>
+
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+
+#include "lib/network/messageserialization.h"
+
+#include "messagemanager.h"
+#include "kdevteamwork_user.h"
+#include "kdevteamworkplugin.h"
+#include "kdevteamwork_messages.h"
+#include "kdevteamwork.h"
+#include "kdevteamwork_helpers.h"
+#include "teamworkfoldermanager.h"
+
+using namespace KDevelop;
+
+Q_DECLARE_METATYPE( Teamwork::UserPointer )
+
+Q_DECLARE_METATYPE( MessagePointer )
+Q_DECLARE_METATYPE( InDocumentMessagePointer )
+
+CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, int, 0, value.position )
+CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, InDocumentMessagePointer, 0, value.message )
+CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, QString, 0, value.message.lock()->start().document() )
+
+template <class ArchType>
+void InDocumentConversation::load( ArchType& arch, unsigned int version ) {
+ m_messageCount = 0;
+ serial( arch, version );
+ std::list<Teamwork::UniqueMessageId> ids;
+ arch & ids;
+ log( QString( "loading %1 ids" ).arg( ids.size() ), Debug );
+ m_messages.clear();
+ for ( std::list<Teamwork::UniqueMessageId>::iterator it = ids.begin(); it != ids.end(); ++it ) {
+ InDocumentMessagePointer msg = ConversationManager::instance() ->manager() ->historyManager().getMessageFromId( *it, ConversationManager::instance() ->manager() ->teamwork() ->client() );
+ if ( msg )
+ pushMessage( msg );
+ else
+ log( QString( "Could not get the message with id %1 from the history" ).arg( *it ), Warning );
+ }
+}
+
+KTextEditor::Cursor InDocumentConversation::currentDocCursor() const {
+ if( !m_currentConnectedDocument || !m_currentConnectedDocument->activeView() ) return KTextEditor::Cursor();
+ return m_currentConnectedDocument->activeView()->cursorPosition();
+}
+
+void InDocumentConversation::pushMessage( const InDocumentMessagePointer& msg ) {
+ m_messages.insert( OrderedDocumentMessage( m_messageCount++, msg ) );
+}
+
+template <class ArchType>
+void InDocumentConversation::save( ArchType& arch, unsigned int version ) const {
+ const_cast<InDocumentConversation*>( this ) ->serial( arch, version );
+
+ std::list<Teamwork::UniqueMessageId> ids;
+
+ ;
+ for ( MessageSet::Iterator it = m_messages.orderedValues<int>(); it; ++it ) {
+ InDocumentMessagePointer::Locked l = it->message;
+ if ( l ) {
+ ids.push_back( l->info().uniqueId() );
+ } else {
+ log( "could not lock InDocumentMessage for getting id", Error );
+ }
+ }
+
+ log( QString( "saving %1 ids" ).arg( ids.size() ), Debug );
+ arch & ids;
+}
+
+template void InDocumentConversation::load( InArchive& arch, unsigned int version )
+;
+template void InDocumentConversation::save( OutArchive& arch, unsigned int version )
+const;
+
+///This helper-class helps tracking connected user-signals and cleanly disconnecting them once they are not needed anymore
+struct TemporaryConversationConnector : public Shared {
+ KDevTeamworkUserPointer user;
+ InDocumentConversation* target;
+ TemporaryConversationConnector() : target( 0 ) {}
+ TemporaryConversationConnector( const KDevTeamworkUserPointer& u, InDocumentConversation* t ) : user( u ), target( t ) {
+ if ( user && target ) {
+ KDevTeamworkUserPointer::Locked l = user;
+ if ( l ) {
+ QObject::connect( l, SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), target, SLOT( userStateChanged( KDevTeamworkUserPointer ) ), Qt::QueuedConnection );
+ }
+ }
+ }
+ ~TemporaryConversationConnector() {
+ cleanup();
+ }
+ private:
+
+ void cleanup() {
+ if ( user && target ) {
+ KDevTeamworkUserPointer::Locked l = user;
+ if ( l ) {
+ QObject::disconnect( l, SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), target, SLOT( userStateChanged( KDevTeamworkUserPointer ) ) );
+ }
+ }
+ user = 0;
+ target = 0;
+ }
+
+ void invalidate() {
+ user = 0;
+ target = 0;
+ }
+
+ TemporaryConversationConnector ( const TemporaryConversationConnector& rhs ) : Shared(rhs) {}
+}
+;
+
+using namespace std;
+using namespace Teamwork;
+
+ConversationManager* ConversationManager::m_instance;
+
+ConversationManager::ConversationManager( MessageManager* mng ) {
+ m_manager = mng;
+ m_instance = this;
+ IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
+ if ( docControl ) {
+ connect( docControl, SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ connect( docControl, SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ }
+ connect( mng->teamwork(), SIGNAL( init() ), this, SLOT( load() ) );
+ connect( mng->teamwork(), SIGNAL( deInit() ), this, SLOT( save() ) );
+}
+
+ConversationManager::~ConversationManager() {
+}
+
+InDocumentConversationPointer ConversationManager::findConversation( const QString& context ) {
+ ConversationSet::iterator it = m_conversations.find( ~context );
+
+ if ( it != m_conversations.end() ) {
+ return ( *it ).second;
+ } else {
+ return 0;
+ }
+}
+
+InDocumentConversationPointer ConversationManager::getConversation( InDocumentMessage* msg ) {
+ SharedPtr<InDocumentConversation> ret = findConversation( msg->context() );
+ if ( ret ) {
+ return ret;
+ } else {
+ m_conversations[ ~msg->context() ] = new InDocumentConversation( msg );
+ return m_conversations[ ~msg->context() ];
+ }
+}
+
+int ConversationManager::processMessage( InDocumentMessage* msg ) {
+ getConversation( msg ) ->addMessage( msg );
+
+ return 0;
+}
+
+void ConversationManager::save() {
+ try {
+ KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "conversation.database" );
+ ///@todo make this work with remote Urls
+ if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
+
+ std::ofstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::out | ios_base::binary );
+ if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for writing";
+ boost::archive::polymorphic_xml_oarchive arch( file );
+ arch << NVP(m_conversations);
+ } catch ( std::exception & exc ) {
+ log( QString("save(): exception occurred while serialization: %1").arg( exc.what() ), Error );
+ } catch( const char* str ) {
+ log( QString("save(): %1").arg( str ), Error );
+ } catch( const QString& str ) {
+ log( QString( "save(): %1").arg( str ), Error );
+ }
+}
+
+void ConversationManager::load() {
+ try {
+ KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "conversation.database" );
+ ///@todo make this work with remote Urls
+ if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
+
+ std::ifstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::binary );
+ if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for reading";
+ boost::archive::polymorphic_xml_iarchive arch( file );
+ arch >> NVP(m_conversations);
+ } catch ( std::exception & exc ) {
+ log( QString("load(): exception occurred while serialization: %1").arg( exc.what() ), Error );
+ } catch( const char* str ) {
+ log( QString("load(): %1").arg( str ), Error );
+ } catch( const QString& str ) {
+ log( QString( "load(): %1").arg( str ), Error );
+ }
+}
+
+void ConversationManager::documentActivated( IDocument* /*document*/ ) {
+ //document->
+ /*for( ConversationSet::iterator it = m_conversations.begin(); it != m_conversations.end(); ++it ) {
+ (*it)->documentActivated( document );
+ }*/
+}
+
+void ConversationManager::log( const QString& str, LogLevel level ) {
+ m_manager->log( str, level );
+}
+
+ConversationManager* InDocumentConversation::manager() const {
+ return ConversationManager::instance();
+}
+
+std::string InDocumentConversation::logPrefix() {
+ return "InDocumentConversation(" + ~context() + "): ";
+}
+
+void InDocumentConversation::messageSelected( const MessagePointer& msg ) {
+ LogSuffix( "messageSelected: ", this );
+ try {
+ m_selectNearestMessageTimer->stop();
+
+ if( !m_currentConnectedDocument )
+ throw "no connected document";
+
+ KTextEditor::View* view = m_currentConnectedDocument->activeView();
+ if( !view )
+ throw "current document has no view";
+
+ MessagePointer::Locked l = msg;
+ if( !l )
+ throw "messageSelected: could not lock message";
+
+ KTextEditor::Cursor c, endC;
+ c = findPositionInDocument( l.cast<InDocumentMessage>(), &endC );
+
+ KTextEditor::SmartInterface* smart = dynamic_cast<KTextEditor::SmartInterface*>( (KTextEditor::Document*)m_currentConnectedDocument );
+ if ( smart ) {
+ if ( endC.isValid() && c.isValid() ) {
+ KTextEditor::Document* d = m_currentConnectedDocument;
+ disconnect( d, SIGNAL(destroyed( QObject* )), this, SLOT(rangeDeleted()) );
+ connect( d, SIGNAL(destroyed( QObject* )), this, SLOT(rangeDeleted()) );
+
+ QMutexLocker lock(smart->smartMutex());
+
+ if(m_currentRange)
+ delete m_currentRange;
+
+ m_currentRange = smart->newSmartRange(d->documentRange(), 0, KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight);
+ KTextEditor::SmartRange* highlightRange = smart->newSmartRange( c, endC, m_currentRange );
+ KSharedPtr<KTextEditor::Attribute> t( new KTextEditor::Attribute() );
+
+ t->setProperty( QTextFormat::BackgroundBrush, QBrush( Qt::yellow ) );
+ highlightRange->setAttribute( t );
+
+ smart->addHighlightToDocument( /*view, */m_currentRange );//, true );
+ }
+ } else {
+ throw "no smart-interface";
+ }
+
+ ///Select the message in the widget
+ if( m_widget && m_messagesModel ) {
+ for( int a = 0; a < m_messagesModel->rowCount(); a++ ) {
+ QModelIndex i = m_messagesModel->index( a, 0 );
+ if( i.isValid() ) {
+ QVariant v = m_messagesModel->data( i, Qt::UserRole );
+ if ( v.canConvert<MessagePointer>() ) {
+ InDocumentMessagePointer smsg = v.value<MessagePointer>().cast<InDocumentMessage>();
+ if( smsg.unsafe() == msg.unsafe() ) {
+ m_widgets.messages->selectionModel()->clear();
+ m_widgets.messages->selectionModel()->select( i, QItemSelectionModel::Select );
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ c = currentDocCursor();
+ placeWidget( view, &c, true );
+ } catch( const char* str ) {
+ err() << str;
+ } catch( const QString& str ) {
+ err() << str;
+ }
+}
+
+void InDocumentConversation::selectMessage( InDocumentMessagePointer msg ) {
+ LogSuffix( "selectMessage: ", this );
+ try {
+ setActive( true );
+
+ InDocumentMessagePointer::Locked l = msg;
+ if ( !l )
+ throw "could not lock message";
+
+ if( l->document().isEmpty() ) {
+ out( Logger::Warning ) << "the selected message has no text-reference";
+ return;
+ }
+
+ KUrl url = TeamworkFolderManager::workspaceAbsolute( l->document() );
+
+ out( Logger::Debug ) << "opening:" << url.toLocalFile();
+
+
+ IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
+
+ IDocument* doc = docControl->documentForUrl( url );
+ if(!doc) doc = docControl->openDocument( url );
+ if ( doc ) {
+ docControl->activateDocument( doc );
+ documentActivated( doc, msg );
+
+ KTextEditor::View* view = doc->textDocument() ->activeView();
+ if( !view ) {
+ out( Logger::Debug ) << "no view for the activated document available";
+ QList<KTextEditor::View*> views = doc->textDocument() ->views();
+ if( views.isEmpty() ) throw "no views available for document";
+ view = dynamic_cast<KTextEditor::View*>( views.front() );
+ }
+
+ if ( view ) {
+ KTextEditor::Cursor endC = KTextEditor::Cursor::invalid();
+ KTextEditor::Cursor c = findPositionInDocument( l, l->end().isValid() ? &endC : 0 );
+ view->setCursorPosition( c );
+ //view->setCursorPosition( KTextEditor::Cursor( c.line() > 10 ? c.line() - 10 : c.line(), c.column() ) );
+ if ( !c.isValid() )
+ throw "could not find current position, cursor is invalid";
+
+ {
+ Block b( m_block );
+ view->setCursorPosition( c );
+ }
+
+ messageSelected( msg );
+ } else {
+ throw "could not get view for " + url.toLocalFile();
+ }
+ } else {
+ throw "could not open document " + url.toLocalFile();
+ }
+ } catch ( const char * str ) {
+ err() << str;
+ } catch ( QString str ) {
+ err() << str;
+ }
+}
+void InDocumentConversation::userInfo() {
+ manager() ->manager() ->teamwork() ->showUserInfo( primaryUser() );
+}
+
+void InDocumentConversation::messageContextMenu ( const QPoint &p ) {
+ log( "messageContextMenu", Debug );
+ QMenu menu( m_widget );
+ QModelIndex i = m_widgets.messages->indexAt( p );
+ if( !i.isValid() ) {
+ log( "messageContextMenu: index is invalid", Error );
+ return;
+ }
+ QVariant v = m_messagesModel->data( i, Qt::UserRole );
+ if ( v.canConvert<MessagePointer>() ) {
+ InDocumentMessagePointer msg = v.value<MessagePointer>().cast<InDocumentMessage>();
+ manager() ->manager() ->fillMessageMenu( &menu, msg );
+ menu.exec( p );
+ }
+}
+
+InDocumentMessagePointer InDocumentConversation::selectedMessage() {
+ if( !m_widget ) return 0;
+ QModelIndexList il = m_widgets.messages->selectionModel()->selectedIndexes ();
+ if( il.isEmpty() ) return 0;
+ return m_messagesModel->data( il.front(), Qt::UserRole ).value<MessagePointer>().cast<InDocumentMessage>();
+}
+
+
+void InDocumentConversation::messageClicked( const QModelIndex& index ) {
+ log( "messageClicked", Debug );
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<MessagePointer>() ) {
+ InDocumentMessagePointer msg = v.value<MessagePointer>().cast<InDocumentMessage>();
+
+ QMetaObject::invokeMethod( this, "selectMessage", Qt::QueuedConnection, Q_ARG( InDocumentMessagePointer, msg ) );
+ } else {
+ manager() ->log( "cannot convert a list-item to a MessagePointer", Error );
+ }
+}
+
+void InDocumentConversation::gotReply( MessagePointer smsg ) {
+ MessagePointer::Locked msg = smsg;
+ if ( !msg ) {
+ addListItem( "failed to send, got no reply" );
+ } else {
+ if ( msg->info().replyToMessage().unsafe() == ( MessageInterface* ) m_sendingMessage.unsafe() ) {
+ SafeSharedPtr<KDevSystemMessage>::Locked sysMsg = msg.cast<KDevSystemMessage>();
+ if ( sysMsg ) {
+ if ( sysMsg->message() == KDevSystemMessage::ActionSuccessful ) {
+ messageSendReady( true );
+ SafeSharedPtr<InDocumentMessage>::Locked l = msg->info().replyToMessage().cast<InDocumentMessage>();
+ addMessage( l );
+ return ;
+ } else {
+ addListItem( "failed to send, reply: " + sysMsg->messageAsString() );
+ }
+ } else {
+ manager() ->log( "could not lock the received message as kdev-system-message", Error );
+ }
+ } else {
+ manager() ->log( "got unexpected reply-message", Error );
+ return ;
+ }
+ }
+
+ messageSendReady( false );
+}
+
+void InDocumentConversation::messageSendReady( bool success ) {
+ if ( m_widget ) {
+ if ( success ) {
+ m_widgets.message->clear();
+ }
+ m_widgets.message->setEnabled( true );
+ }
+
+ m_sendingMessage = 0;
+ if( !m_lastSendTime.isValid() || m_lastSendTime.msecsTo( QTime::currentTime() ) < 400 ) {
+ m_widgets.message->setFocus();
+ }
+}
+
+void InDocumentConversation::hide() {
+ setActive( false );
+ if ( m_widget )
+ m_widget->hide();
+}
+
+void InDocumentConversation::sendMessage() {
+ try {
+ LogSuffix( "sendMessage(): ", this );
+ if ( !m_widget )
+ throw QString( "no widget" );
+ QString text = m_widgets.message->text();
+ if ( text.isEmpty() )
+ throw "no text";
+
+ IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
+
+ IDocument* d = docControl->activeDocument();
+ if ( !d )
+ throw "no active document";
+
+ KTextEditor::Document* doc = d->textDocument();
+ if ( !doc )
+ throw "no active text-document";
+
+ KTextEditor::View* view = doc->activeView();
+ if ( !view )
+ throw "no active view";
+
+ InDocumentReference start( "" );
+ InDocumentReference end;
+ /*
+ KTextEditor::MarkInterface* mark = dynamic_cast<KTextEditor::MarkInterface*>( view );
+ if( !mark ) {
+ log( "no MarkInterface", Warning );
+ } else {
+ mark->
+ }*/
+ KTextEditor::Range r = view->selectionRange();
+ if ( r.isValid() ) {
+ KTextEditor::Cursor b = r.start();
+ KTextEditor::Cursor e = r.end();
+ QString txt = doc->text();
+ QString path = TeamworkFolderManager::workspaceRelative( doc->url() );
+ start = InDocumentReference( path, b.line(), b.column(), txt );
+ end = InDocumentReference( path, e.line(), e.column(), txt );
+ out( Logger::Debug ) << "sending references:" << start.asText() << "" << end.asText();
+ }
+
+ MessagePointer::Locked stdMsg = new InDocumentMessage( globalMessageTypeSet(), text, start, end, context() );
+
+ InDocumentMessagePointer::Locked msg = stdMsg.cast<InDocumentMessage>();
+
+ if ( !msg )
+ throw QString( "could not create InDocumentMessage" );
+
+ if ( r.isValid() )
+ msg->contextLines() = DocumentContextLines( start, end, doc->text(), 5 );
+
+
+ msg->setConversation( this );
+
+ SessionPointer s = session();
+
+ if ( !s )
+ throw QString( "no session to send the message" );
+
+ s.unsafe() ->send( msg );
+ m_widgets.message->setEnabled( false );
+ m_sendingMessage = msg;
+
+ manager()->manager()->teamwork()->addMessageToList( msg.data() );
+ } catch ( const char * str ) {
+ err() <<"error while sending message:" << str;
+ } catch ( QString str ) {
+ err() <<"error while sending message:" << str;
+ }
+}
+
+void InDocumentConversation::jumpTo() {
+ try {
+ if( m_messages.empty() )
+ throw "no messages";
+ //setActive( true );
+ QAction* action = qobject_cast<QAction*>( sender() );
+ if ( !action )
+ throw "no sender-action";
+
+ QVariant v = action->data();
+ if ( !v.canConvert<MessagePointer>() )
+ throw "cannot convert variant to message";
+
+ MessagePointer mp = v.value<MessagePointer>();
+ if ( !mp.cast<InDocumentMessage>( ) )
+ throw "wrong message-type";
+
+ selectMessage( mp.cast<InDocumentMessage>() );
+ } catch ( const char * str ) {
+ manager() ->log( QString( "error in jumpTo: " ) + str, Error );
+ }
+}
+
+void InDocumentConversation::fillContextMenu( QMenu* menu, KDevTeamwork* /*teamwork*/, MessagePointer msg ) {
+ if ( !m_jumpToAction ) {
+ m_jumpToAction = new QAction( i18n("Show in Document"), this );
+ connect( m_jumpToAction, SIGNAL( triggered() ), this, SLOT( jumpTo() ), Qt::QueuedConnection );
+ m_jumpToAction->setToolTip( i18n("Open the document and jump to the references position.") );
+
+ QVariant v;
+ v.setValue( msg );
+ m_jumpToAction->setData( v );
+ }
+
+ menu->addAction( m_jumpToAction );
+}
+
+void InDocumentConversation::cursorPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos ) {
+ if( !m_active ) return;
+ if ( m_smartCursor ) {
+ int diff = m_smartCursor->line() - newPos.line();
+ if ( diff > -10 && diff < 20 ) {
+ placeWidget( view, &newPos ); ///Move the widget away from the cursor
+ }
+ }
+
+ if( m_currentConnectedDocument ) ///Eventually select another message that is nearer
+ m_selectNearestMessageTimer->start( 400 );
+
+}
+
+void InDocumentConversation::verticalScrollPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& /*newPos*/ ) {
+ if( !m_active || m_block ) return;
+ KTextEditor::Cursor c = currentDocCursor();
+ placeWidget( view, &c );
+ //manager()->log( "verticalScrollPositionChanged", Debug );
+}
+
+void InDocumentConversation::log( const QString& str, LogLevel level ) const {
+ const_cast<ConversationManager*>( manager() ) ->log( "InDocumentConversation: " + str, level );
+}
+
+
+void InDocumentConversation::horizontalScrollPositionChanged ( KTextEditor::View */*view*/ ) {
+ //manager()->log( "horizontalScrollPositionChanged", Debug );
+}
+
+void InDocumentConversation::fillMessageModel() {
+ for ( MessageSet::Iterator it = m_messages.orderedValues<int>(); it; ++it ) {
+ fillMessageToModel( it->message );
+ }
+}
+
+void InDocumentConversation::selectNearestMessage() {
+ if( !m_currentConnectedDocument ) {
+ err() << "selectNearestMessage() called without active document";
+ return;
+ }
+ InDocumentMessagePointer msg;
+
+ KTextEditor::Cursor c = m_currentConnectedDocument->activeView()->cursorPosition();
+ int nearestDiff = 1000000;
+ KTextEditor::Cursor nearestCursor;
+
+ QString file = TeamworkFolderManager::workspaceRelative( m_currentConnectedDocument->url() );
+
+ MessageSet::Iterator it = m_messages.values( file );
+
+ while( it ) {
+ InDocumentMessagePointer::Locked l = it->message;
+ if( l ) {
+ KTextEditor::Cursor end;
+ KTextEditor::Cursor start = findPositionInDocument( l, &end );
+ int diff = c.line() - start.line();
+ if( diff < 0 ) diff = -diff;
+ if( diff < nearestDiff ) {
+ nearestDiff = diff;
+ nearestCursor = start;
+ msg = it->message;
+ }
+ }
+ ++it;
+ }
+ if( msg )
+ messageSelected( msg );
+}
+
+void InDocumentConversation::userStateChanged( KDevTeamworkUserPointer /*user*/ ) {
+ log( "userStateChanged" );
+ fillUserBox();
+}
+
+void InDocumentConversation::fillUserBox() {
+ try {
+ if ( !m_widget )
+ throw "no widget";
+ m_widgets.talkingUsers->clear();
+
+ UserPointer user = primaryUser();
+ if ( !user )
+ throw "could not figure out primary user";
+
+ UserPointer::Locked l = user;
+ if ( !l )
+ throw "could not lock user";
+ QVariant v;
+ v.setValue<UserPointer>( user );
+
+
+ KDevTeamworkUserPointer::Locked us = user.cast<KDevTeamworkUser>();
+ if ( !us )
+ throw "could not cast to KDevTeamworkUser, and lock.";
+
+ m_widgets.talkingUsers->addItem( us->icon(), ~l->name(), v );
+ m_userConnector = 0;
+ m_userConnector = new TemporaryConversationConnector( us, this );
+ } catch ( const char * str ) {
+ log( QString( "error in fillUserBox: " ) + str , Error );
+ }
+}
+
+void InDocumentConversation::rangeDeleted() {
+ m_currentRange = 0;
+}
+
+
+void InDocumentConversation::fillMessageToModel( const InDocumentMessagePointer::Locked& msg ) {
+ if ( !m_messagesModel )
+ return ;
+ if ( msg ) {
+ int row = 0; //m_messagesModel->rowCount();
+ m_messagesModel->insertRow( row );
+ QModelIndex i = m_messagesModel->index( row, 0 );
+ m_messagesModel->setData( i, msg->messageText(), Qt::DisplayRole );
+ m_messagesModel->setData( i, msg->messageIcon() , Qt::DecorationRole );
+ QVariant v;
+ MessagePointer m( ( MessageInterface* ) msg.data() );
+ v.setValue( m );
+ m_messagesModel->setData( i, v , Qt::UserRole );
+ } else {}
+}
+
+void InDocumentConversation::addListItem( const QString& txt , const QString& icon ) {
+ manager() ->log( txt, Debug );
+ if ( !m_messagesModel )
+ return ;
+ int row = 0; //m_messagesModel->rowCount();
+ m_messagesModel->insertRow( row );
+ QModelIndex i = m_messagesModel->index( row, 0 );
+ m_messagesModel->setData( i, txt, Qt::DisplayRole );
+ m_messagesModel->setData( i, IconCache::instance() ->getIcon( icon ) , Qt::DecorationRole );
+}
+
+void InDocumentConversation::setupWidget( QWidget* parent ) {
+ m_widget = new QWidget( parent );
+ m_widgets.setupUi( m_widget );
+
+ QPalette p = m_widgets.frame->palette();
+ p.setColor( QPalette::Background, QColor::fromRgb( 190, 190, 0, 150 ) );
+ m_widgets.frame->setPalette( p );
+ m_widgets.messages->header() ->hide();
+ //m_widgets.messages->setWrapping( true );
+
+ connect( m_widgets.message, SIGNAL( returnPressed() ), this, SLOT( sendMessage() ), Qt::QueuedConnection );
+ connect( m_widgets.messages, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( messageClicked( const QModelIndex& ) ) );
+ connect( m_widgets.messages, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT( messageContextMenu ( const QPoint & ) ) );
+
+ if ( !m_messagesModel ) {
+ m_messagesModel = new QStandardItemModel( 0, 1, 0 );
+ fillMessageModel();
+ }
+ m_widgets.messages->setModel( m_messagesModel );
+
+ if ( !m_userInfoAction ) {
+ m_userInfoAction = new QAction( i18n("User Info"), this );
+ connect( m_userInfoAction, SIGNAL( triggered() ), this, SLOT( userInfo() ) );
+ m_userInfoAction->setToolTip( i18n("Show information about the selected user.") );
+ }
+
+ if ( !m_hideAction ) {
+ m_hideAction = new QAction( i18n("Hide"), this );
+ connect( m_hideAction, SIGNAL( triggered() ), this, SLOT( hide() ) , Qt::QueuedConnection );
+ m_hideAction->setToolTip( i18n("Hide this conversation.") );
+ }
+
+ QMenu *actionMenu = new QMenu( "Actions", m_widgets.actionsButton );
+
+ actionMenu->addAction( m_hideAction );
+ actionMenu->addSeparator();
+ actionMenu->addAction( m_userInfoAction );
+
+ m_widgets.actionsButton->setMenu( actionMenu );
+ m_widgets.actionsButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
+ m_widgets.actionsButton->setArrowType( Qt::DownArrow );
+ m_widgets.actionsButton->setPopupMode( QToolButton::InstantPopup );
+
+ fillUserBox();
+}
+
+void InDocumentConversation::embedInView( KTextEditor::View* view, IDocument* document, KTextEditor::Cursor position ) {
+ LogSuffix( "embedInView: ", this );
+ try {
+ if ( !view )
+ throw "no view";
+ if ( m_messages.empty() )
+ throw "no messages";
+ if ( m_widget )
+ delete m_widget;
+
+ disconnect( view, 0, this, 0 );
+ // KTextEditor::Cursor cursor( line, 0 );
+ setupWidget( view );
+
+ if ( !m_widget )
+ throw "could not setup widget";
+
+ connect( view, SIGNAL( verticalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( verticalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
+
+ connect( view, SIGNAL( horizontalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( horizontalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
+
+ connect( view, SIGNAL( cursorPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( cursorPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
+
+ m_smartCursor = SmartCursorContainer( document->textDocument() );
+
+ if ( !m_smartCursor )
+ throw "smart-cursor could not be created, maybe the editor is missing the interface";
+
+ if( !document->textDocument() )
+ throw "no text-document";
+
+ if ( !position.isValid() )
+ throw "the cursor-position is not valid";
+
+ if( position > document->textDocument()->documentEnd() ) {
+ out( Logger::Debug ) << "found position behind end of document";
+ position = document->textDocument()->documentEnd();
+ }
+
+ m_smartCursor->setPosition( position );
+
+ KTextEditor::Cursor c = currentDocCursor();
+
+ placeWidget( view, &c, true );
+ } catch ( const char * str ) {
+ err() << str;
+ }
+}
+
+bool isCovered(int line1, int line2, int position, int length) {
+ if( line1 >= position-1 && line1 <= position+length+1 )
+ return true;
+ if( line2 >= position-1 && line2 <= position+length+1 )
+ return true;
+ return false;
+}
+
+void InDocumentConversation::placeWidget( KTextEditor::View* view, const KTextEditor::Cursor* awayFrom, bool forceShow ) {
+ try {
+ if ( !m_smartCursor )
+ throw "smartcursor is invalid";
+ if ( !m_widget )
+ throw "no widget";
+
+ QPoint p = view->cursorToCoordinate( *m_smartCursor );
+ if ( p == QPoint( -1, -1 ) ) {
+ if( !forceShow ) m_widget->hide();
+ } else {
+ if ( awayFrom ) {
+ int sline = m_smartCursor->line();
+ int widgetLines = 12; ///@todo Determine this better: How many lines does the widget cover?
+ int cline = awayFrom->line();
+ p = QPoint( -1, -1 );
+ //Find any line-position where neither cline nor sline are coverd
+
+ //Try 1; Above cline
+ int resultLine = -1;
+ if( !isCovered(cline, cline, sline+1, widgetLines) ) {
+ resultLine = sline+1;
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline - 5 - widgetLines, widgetLines) ) {
+ resultLine = cline - 5 - widgetLines; //Above cursor
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
+ view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
+ resultLine = -1; //Make sure the lower end of the widget is visible too
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline - 2 - widgetLines, widgetLines) ) {
+ resultLine = sline - 5 - widgetLines; //Above target-position
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
+ view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
+ resultLine = -1; //Make sure the lower end of the widget is visible too
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline + 5, widgetLines) ) {
+ resultLine = cline + 5; //Below cursor
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
+ view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
+ resultLine = -1; //Make sure the lower end of the widget is visible too
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline + 2, widgetLines) ) {
+ resultLine = sline + 5; //Below target-position
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+
+ ///Try exactly the same positions as above, using less distance
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline - 2 - widgetLines, widgetLines) ) {
+ resultLine = cline - 2 - widgetLines; //Above cursor
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
+ view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
+ resultLine = -1; //Make sure the lower end of the widget is visible too
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline + 2, widgetLines) ) {
+ resultLine = cline + 2; //Below cursor
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
+ view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
+ resultLine = -1; //Make sure the lower end of the widget is visible too
+
+ if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline + 2, widgetLines) ) {
+ resultLine = sline + 2; //Below target-position
+ if(resultLine >= 1 && resultLine < view->document()->lines())
+ p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
+ }
+
+ }
+
+ if( p == QPoint( -1, -1 ) ) {
+ if( !forceShow ) {
+ err() << "could not determine a good position to show the widget";
+ p.setX( 50 );
+ } else {
+ p.setX( 50 );
+ p.setY( 50 );
+ }
+ }
+
+ //manager()->log( QString("smartcursor coordinates: %1 %2").arg( p.x() ).arg( p.y() ), Debug );
+ m_widget->move( p );
+ m_widget->show();
+ }
+
+ } catch ( const char * str ) {
+ err() << "placeWidget:" << str;
+ }
+}
+
+KTextEditor::Cursor InDocumentConversation::findPositionInDocument( InDocumentMessagePointer::Locked l, KTextEditor::Cursor* endTarget ) {
+ LogSuffix s( "findPositionInDocument: ", this );
+ if( !m_currentConnectedDocument ) {
+ err() << "no connected document";
+ return KTextEditor::Cursor();
+ }
+ if( !m_currentSearchInstance )
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance( m_currentConnectedDocument->text() );
+
+ if ( l ) {
+ int line, col;
+ l->start().findInText( m_currentSearchInstance, line, col );
+ int endLine = -1, endCol = -1;
+ if ( l->end().isValid() && endTarget ) {
+ l->end().findInText( m_currentSearchInstance, endLine, endCol );
+ if ( endLine < line || ( endLine == line && endCol < col ) ) {
+ int l = line, c = col;
+ line = endLine;
+ col = endCol;
+ endLine = l;
+ endCol = c;
+ out( Logger::Warning ) << "Found end-marker before start-marker:" << line << ":" << col << "-" << endLine << ":" << endCol;
+ }
+ }
+
+ if ( line == -1 ) {
+ out( Logger::Warning ) << "Could not find reference-position for" << l->start().asText() << "in text of length "<< m_currentSearchInstance.text().length();
+ line = l->start().line();
+ col = l->start().col();
+ if ( l->end().isValid() && endTarget ) {
+ endLine = l->end().line();
+ endCol = l->end().col();
+ }
+ }
+
+ if ( endTarget && endLine != -1 ) {
+ *endTarget = KTextEditor::Cursor( endLine, endCol == -1 ? 0 : endCol );
+ }
+
+ if ( line == -1 ) {
+ err() << "cursor is invalid";
+ line = 0;
+ col = 0;
+ return KTextEditor::Cursor::invalid();
+ }
+ if ( line != -1 )
+ return KTextEditor::Cursor( line, col );
+ } else {
+ if ( !l )
+ err() << "could not lock first message";
+ else
+ err() << "kdev-document has no text-document";
+ }
+ return KTextEditor::Cursor::invalid();
+}
+
+InDocumentConversation::InDocumentConversation( InDocumentMessage* msg ) : SafeLogger( KDevTeamwork::self()->logger() ), m_messageCount( 0 ), m_jumpToAction( 0 ), m_hideAction( 0 ), m_userInfoAction( 0 ), m_messagesModel( 0 ), m_block( false ), m_currentRange(0) {
+ setActive( true );
+ LogSuffix s( "constructor: ", this );
+
+ m_selectNearestMessageTimer = new QTimer( this );
+ m_selectNearestMessageTimer->setSingleShot( true );
+ connect( m_selectNearestMessageTimer, SIGNAL( timeout() ), this, SLOT( selectNearestMessage() ) );
+
+ qRegisterMetaType<InDocumentMessagePointer>( "InDocumentMessagePointer" );
+
+ if ( msg ) {
+ m_line = msg->start().line();
+ m_documentName = ~msg->document();
+ manager() ->log( "document-name: " + ~m_documentName, Debug );
+ addMessage( msg );
+
+ try {
+ QString document = msg->document();
+ if ( document.isEmpty() )
+ throw "in-document-message has no document-information";
+
+ int line = msg->start().line();
+ if ( line == -1 )
+ throw "in-document-message has no line-information";
+
+ IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
+ if ( !docControl )
+ throw "no document-controller";
+
+ IDocument* kdevDoc = docControl->activeDocument();
+ if ( kdevDoc )
+ documentActivated( kdevDoc, msg );
+ }
+ catch ( const char * str ) {
+ manager() ->log( QString( "error while dispatching InDocumentMessage: " ) + str, Error );
+ }
+ }
+}
+
+InDocumentConversation::~InDocumentConversation() {
+ if ( m_messagesModel )
+ delete m_messagesModel;
+ if( m_currentRange )
+ delete m_currentRange;
+}
+
+SessionPointer InDocumentConversation::session() {
+ try {
+ if ( m_messages.empty() )
+ throw "no messages";
+ InDocumentMessagePointer::Locked lmsg = m_messages.value<int>( m_messageCount-1 ).message;
+ if ( !lmsg )
+ throw "could not lock message";
+ return lmsg->info().session();
+ } catch ( const char * str ) {
+ err() << "could not get session:" << str;
+ return 0;
+ }
+}
+
+UserPointer InDocumentConversation::primaryUser() {
+ if ( m_messages.empty() )
+ return 0;
+ InDocumentMessagePointer::Locked l = m_messages.value<int>(m_messageCount-1).message;
+ if ( !l )
+ return 0;
+ return l->info().user();
+}
+
+void InDocumentConversation::textChanged ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*oldRange*/, const KTextEditor::Range & /*newRange*/ ) {
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance();
+}
+
+void InDocumentConversation::textRemoved ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*range*/ ) {
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance();
+}
+
+void InDocumentConversation::textInserted ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*range*/ ) {
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance();
+}
+
+void InDocumentConversation::documentActivated( IDocument* document ) {
+ documentActivated( document, 0 );
+}
+
+void InDocumentConversation::documentActivated( IDocument* document, const InDocumentMessagePointer& msg_ ) {
+ LogSuffix s( "documentActivated: " , this );
+ if ( !m_active ) {
+ err() << "This conversation is not active";
+ return;
+ }
+ if( !document ) {
+ err() << "got document-pointer with value zero";
+ return;
+ }
+ if( !document->textDocument() || ! document->textDocument() ->activeView() ) {
+ err() << "Document is no text-document";
+ return ;
+ }
+ QString file = TeamworkFolderManager::workspaceRelative( document->url() );
+
+ MessageSet::Iterator it = m_messages.values( file );
+
+ if( !it /*&& !msg_*/ ) {
+ /* out( Logger::Debug ) << "comparing" << file << "failed: is not part of conversation";
+ MessageSet::Iterator it = m_messages.orderedValues<QString>();
+ QString current = "__/__";
+ while( it ) {
+ InDocumentMessagePointer::Locked l = it->message;
+ if( l ) {
+ if( current != l->document() ) {
+ out( Logger::Debug ) << "files are: \"" << l->document() << "\"";
+ current = l->document();
+ }
+ }
+
+ ++it;
+ }*/
+ return; ///Document contains none of our messages
+ }
+ out( Logger::Debug ) << "comparing" << file << "successful";
+
+ KTextEditor::Document* doc = document->textDocument();
+
+ InDocumentMessagePointer msg = msg_;
+
+ if( doc != m_currentConnectedDocument ) {
+
+ if( m_currentConnectedDocument )
+ disconnect( m_currentConnectedDocument, 0, this, 0 );
+
+ connect( doc, SIGNAL( textInserted ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ), this, SLOT( textInserted ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ) );
+ connect( doc, SIGNAL( textRemoved ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ), this, SLOT( textRemoved ( KTextEditor::Document *,
+ const KTextEditor::Range & ) ) );
+ connect( doc, SIGNAL( textChanged ( KTextEditor::Document *,
+ const KTextEditor::Range &,
+ const KTextEditor::Range & ) ), this, SLOT( textChanged ( KTextEditor::Document *,
+ const KTextEditor::Range &,
+ const KTextEditor::Range & ) ) );
+ }
+
+ if( m_currentConnectedDocument != doc )
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance();
+
+ m_currentConnectedDocument = doc;
+
+ ///Determine the nearest message to the cursor
+
+ if( msg ) {
+ ///Always re-embed, because it's possible that documentActivated was called earlier without a given message
+ embedInView( doc ->activeView(), document, findPositionInDocument( msg ) );
+
+ messageSelected( msg );
+ } else {
+ m_selectNearestMessageTimer->start( 300 );
+ }
+}
+
+void InDocumentConversation::setActive( bool active ) {
+ if ( m_active == active )
+ return ;
+
+ m_active = active;
+ IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
+
+ if ( active ) {
+ if( m_widget ) m_widget->show();
+ connect( docControl, SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ connect( docControl, SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ connect( manager() ->manager() ->teamwork(), SIGNAL( updateConnection( TeamworkClientPointer ) ), this, SLOT( updateAllUsers() ) );
+ if( docControl->activeDocument() )
+ documentActivated( docControl->activeDocument() );
+ } else {
+ if( m_currentConnectedDocument ) {
+ if( m_currentConnectedDocument->activeView() )
+ disconnect( m_currentConnectedDocument->activeView(), 0, this, 0 );
+ disconnect( m_currentConnectedDocument, 0, this, 0 );
+
+ }
+ m_currentConnectedDocument = 0;
+
+ m_currentSearchInstance = InDocumentReference::TextSearchInstance();
+
+ disconnect( docControl, 0, this, 0 );
+ disconnect( manager() ->manager() ->teamwork(), 0, this, 0 );
+
+ if(m_currentRange)
+ delete m_currentRange;
+ m_currentRange = 0;
+ }
+}
+
+QString InDocumentConversation::context() const {
+ if ( m_messages.empty() )
+ return "";
+ InDocumentMessagePointer::Locked l = const_cast<InDocumentMessagePointer&>( m_messages.value<int>(m_messageCount-1).message );
+ if ( l )
+ return l->context();
+ else
+ return "";
+}
+
+bool InDocumentConversation::match( InDocumentMessage* msg ) const {
+ return context() == msg->context();
+}
+
+void InDocumentConversation::addMessage( InDocumentMessage* msg ) {
+ msg->setConversation( this );
+ if( m_messages[(InDocumentMessagePointer)msg] ) return;
+ pushMessage( msg );
+ if ( m_messagesModel )
+ fillMessageToModel( msg );
+
+ if ( msg->info().isIncoming() && msg->info().session() ) {
+ ///Send a notification that the message arrived to the other side.
+ //globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful ); //this is also done for KDevTeamworkTextMessage now
+ }
+}
+
+
+struct DocumentMessageInternal {
+ QPointer<InDocumentConversation> m_conversation;
+};
+
+QIcon InDocumentMessage::messageIcon() const {
+ IconCache & cache( *IconCache::instance() );
+ if ( info().isIncoming() ) {
+ return cache( "document_message_in" ).pixmap( QSize( 16, 16 ), m_start ? QIcon::Normal : QIcon::Disabled );
+ } else {
+ return cache( "document_message_out" ).pixmap( QSize( 16, 16 ), m_start ? QIcon::Normal : QIcon::Disabled );
+ }
+}
+
+void InDocumentMessage::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
+ if ( m_internal.get() ) {
+ if ( m_internal->m_conversation ) {
+ m_internal->m_conversation->fillContextMenu( menu, teamwork, this );
+ }
+ }
+ KDevTeamworkTextMessage::fillContextMenu( menu, teamwork );
+}
+
+void InDocumentMessage::setConversation( InDocumentConversation* conv ) {
+ if ( !m_internal.get() )
+ m_internal = auto_ptr<DocumentMessageInternal>( new DocumentMessageInternal );
+ m_internal->m_conversation = conv;
+}
+
+QString InDocumentMessage::context() {
+ return ~m_context;
+}
+
+QString InDocumentMessage::document() {
+ return m_start.document();
+}
+
+InDocumentMessage::InDocumentMessage( const Teamwork::MessageConstructionInfo& info, const QString& text, const InDocumentReference& startRef, const InDocumentReference& endRef, const QString& context ) : KDevTeamworkTextMessage( info(this), text ), m_start( startRef ), m_end( endRef ), m_context( ~context ) {}
+
+InDocumentMessage::InDocumentMessage( InArchive& from, const Teamwork::MessageInfo& info ) : KDevTeamworkTextMessage( from, info ) {
+ serial( from );
+}
+
+void InDocumentMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+
+bool InDocumentMessage::needReply() const {
+ return m_internal.get() && m_internal->m_conversation;
+}
+
+void InDocumentMessage::result( bool success ) {
+ if ( !success ) {
+ QMetaObject::invokeMethod( ( InDocumentConversation* ) m_internal->m_conversation, "gotReply", Qt::QueuedConnection, Q_ARG( MessagePointer, ( MessagePointer ) 0 ) );
+ }
+}
+
+MessageInterface::ReplyResult InDocumentMessage::gotReply( const MessagePointer& p ) {
+ if ( m_internal.get() && m_internal->m_conversation ) {
+ QMetaObject::invokeMethod( ( InDocumentConversation* ) m_internal->m_conversation, "gotReply", Qt::QueuedConnection, Q_ARG( MessagePointer, ( MessagePointer ) p ) );
+ }
+
+ return KDevTeamworkTextMessage::gotReply( p );
+}
+
+#include "conversationmanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.h (revision 1522570)
@@ -0,0 +1,304 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_H
+#define KDEVTEAMWORK_H
+
+#include <QObject>
+#include <QMap>
+#include <QMenu>
+#include <QDomDocument>
+#include <memory>
+#include <kiconloader.h>
+#include <set>
+#include <list>
+
+#include "teamworkfwd.h"
+#include "loglevel.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/messageinterface.h"
+#include "autoconstructpointer.h"
+
+using namespace Teamwork;
+class KUrl;
+
+namespace Ui {
+class Teamwork;
+}
+
+class QModelIndex;
+
+class KDevTeamwork : public QObject {
+ static KDevTeamwork* m_self;
+ enum MessageTypes {
+ Message = 0,
+ SourceMessage = 1
+ };
+
+ Q_OBJECT
+ public:
+ typedef SafeSharedPtr<KDevTeamworkClient> TeamworkClientPointer;
+ KDevTeamwork( const KUrl& workspaceDirectory, KDevTeamworkPlugin *plugin, QWidget *parent );
+ virtual ~KDevTeamwork();
+
+ KDevTeamworkPlugin *plugin() const;
+
+ static KDevTeamwork* self() ;
+
+ /**Sets the whole teamwork-part(client plus server) active/inactive. When set inactive, all connetions are closed.
+ on success returns the given activity-state. */
+ bool setActive( bool active );
+ //
+ /**enables/disables the server. */
+ bool setServerActive( bool active );
+
+ void showUserInfo( const UserPointer& user );
+
+ ///@todo: make this a signal
+ void fillUserMenu( QMenu* menu, const UserPointer& user );
+
+ ///The main fillMessageMenu is the one in the MessageManager. That also invokes this one.
+ void fillMessageMenu( QMenu* menu, const MessagePointer& msg );
+
+ ///@todo remove
+ Ui::Teamwork& widgets();
+
+ QWidget* widget();
+
+ IconCache& icons();
+
+ void log( const QString& str, LogLevel level = Info );
+
+ void err( const QString& str );
+
+ QIcon iconFromUser( User* user, KIconLoader::Group size = KIconLoader::Small );
+
+ ///Starts the update-timer for the developer-lists
+ void startUpdateTimer();
+
+ TeamworkClientPointer& client();
+
+ PatchesManager* patchesManager();
+
+ CollaborationManager* collaborationManager();
+
+ MessageManager* messageManager();
+
+ void handlePatchesList( PatchesListMessage* msg );
+ void getPatchesList( const UserPointer& user );
+
+ LoggerPointer logger();
+
+ ///Inserts the given message into the various GUI-structures. It should be based on AbstractGUIMessage.
+ void addMessageToList( const MessagePointer& smsg );
+
+ virtual void restorePartialProjectSession( const QDomElement* el );
+
+ virtual void savePartialProjectSession( QDomElement* el );
+
+ UserPointer localUser();
+
+ UserIdentity currentUserIdentity();
+
+ public slots:
+
+ /**Prepares the GUI for sending a message to the given user. Second parameter may be zero
+ * @param target The user the message should be sent to
+ * @param answerTo which message this one is a reply to.
+ * */
+ void guiSendMessageTo( const UserPointer& target, const MessagePointer& answerTo = MessagePointer() );
+
+ ///This can be used by messages in other threads to send a request that their state(currently only icon) has changed
+ void updateMessageInfo( MessagePointer );
+
+ signals:
+ ///This is called whenever the local client was destroyed or created, the current client is given as parameter(may be null). Whenever this is emitted, all UserPointers become invalid.
+ void updateConnection( TeamworkClientPointer client );
+ ///Called once KDevTeamwork is completely constructed
+ void init();
+ void deInit();
+
+ private slots:
+ void documentActivated( KDevelop::IDocument* file );
+ void popupContextMenu( const QPoint &pos );
+ void allowIncomingChanged( int state );
+ void enableCollaborationChanged( int state );
+ void connectServer();
+
+ void uiShowPatches();
+ void uiUserInfo();
+
+ void uiFilterLog();
+
+ void connectionRequest( ConnectionRequestPointer request );
+
+ void developerClicked( const QModelIndex& index );
+ void developerDoubleClicked( const QModelIndex& index );
+ void developerContextMenu( const QPoint& );
+
+ void serverClicked( const QModelIndex& index );
+ void clientClicked( const QModelIndex& index );
+ void messageClicked( const QModelIndex& index );
+
+ void serverDoubleClicked( const QModelIndex& index );
+ void clientDoubleClicked( const QModelIndex& index );
+ void messageDoubleClicked( const QModelIndex& index );
+
+ void receiveMessage( SafeSharedPtr<KDevSystemMessage> msg );
+
+ void clearLogButton();
+ void saveLogButton();
+
+ void messageReplyTimeout();
+ void sendMessageButton();
+ void messageTypeIndexChanged( const int index );
+
+ void slotClearMessageText();
+
+ void slotClearMessages();
+ void slotMessageHistory();
+
+ void disconnectFromServer();
+ void disconnectAllServers();
+
+ void sendAnswerMessage();
+ void sendMessageToUser();
+ void kickClient();
+ void banClient();
+ void kickAllClients();
+
+ void messageTargetUserChanged();
+ void updateAnswerMenu();
+
+ void handleTextMessage( SafeSharedPtr<KDevTeamworkTextMessage> msg );
+
+ void guiUserConnected( Teamwork::UserPointer );
+ void guiUserDisconnected( Teamwork::UserPointer );
+ void guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
+ void guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
+ void guiUserList( std::list<UserPointer> );
+ void guiLog( QString str, int level ) {
+ log( str, ( LogLevel ) level );
+ }
+
+ ///Should be called time by time after the state of users changes. This updates all lists that contain users.
+ void updateTimeout();
+
+ void messageUpdated( const MessagePointer& msg );
+
+ void maybeDeveloperContextMenu();
+
+ void answerMenuToggled( bool state );
+ void answerMenuTriggered( bool );
+
+ private:
+ void contextMenu( const QPoint& p, const QModelIndex& index );
+
+ void lockMessageGui( const MessagePointer& msg );
+ void unlockMessageGui();
+
+ friend class KDevTeamworkLogger;
+ friend class KDevTeamworkClient;
+
+ void addSentMessageToList( const MessagePointer&, QStandardItemModel* model );
+
+ void addReceivedMessageToList( const MessagePointer&, QStandardItemModel* model );
+
+ QAction* sendAnswerAction;
+ QAction* sendMessageToUserAction;
+ QAction* disconnectFromServerAction;
+ QAction* disconnectAllServersAction;
+
+ QAction* kickClientAction;
+ QAction* banClientAction;
+ QAction* kickAllClientsAction;
+ QAction* m_userInfoAction;
+ QAction* showPatchesAction;
+
+ UserPointer sendingUser();
+
+ MessagePointer sendingMessage();
+
+ void addSentMessageToList( const MessagePointer& );
+
+ void addReceivedMessageToList( const MessagePointer& );
+
+ void addDeveloper( const Teamwork::UserPointer& u );
+
+ void enableActiveGUI( bool active );
+
+ void enableMessageGUI( bool active );
+
+ void filterLog( int max = 0 );
+
+ void registerPatches( PatchesListMessage* msg, QStandardItemModel* model );
+
+ UserPointer currentMessageTargetUser();
+
+ QMenu* m_messageFilterMenu;
+
+ AutoConstructPointer<TeamworkFolderManager> m_folderManager;
+
+ SafeSharedPtr<KDevTeamworkLogger> m_logger;
+
+ bool m_destroyed;
+ KDevTeamworkPlugin *m_plugin;
+ QWidget* m_widget;
+ AutoConstructPointer<Ui::Teamwork> m_widgets;
+ bool m_active, m_serverActive;
+ TeamworkClientPointer m_client;
+ QStandardItemModel* m_logModel;
+ QStandardItemModel* m_messagesModel;
+ QStandardItemModel* m_clientsModel;
+ QStandardItemModel* m_serversModel;
+ QStandardItemModel* m_developersModel;
+
+ ///The next message to send is answer to:
+ MessagePointer m_answerTo;
+ MessagePointer m_waitingForReply; ///This message is blocking the message-gui waiting for a reply
+ QTimer* m_replyWaitingTimeout;
+
+
+ friend class MessageUserTab;
+
+ KDevTeamworkUserPointer currentTabUser();
+
+ typedef QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> > UserTabMap;
+
+ UserTabMap m_userTabs;
+
+ MessagePointer m_actionMessage;
+
+ QTimer* m_updateTimer;
+ QTimer* m_updateAnswerTimer; ///Timer for updating the list of possible messages the user can reply to
+ AutoConstructPointer<PatchesManager> m_patchesManager;
+ AutoConstructPointer<CollaborationManager> m_collaborationManager;
+ AutoConstructPointer<MessageManager> m_messageManager;
+ AutoConstructPointer<MessageSendManager> m_messageSendManager;
+
+ std::set<UserPointer, UserPointer::ValueSmallerCompare> m_persistentUsers;
+
+ LogLevel m_currentLogFilter;
+
+ AutoConstructPointer<IconCache> m_icons;
+ std::auto_ptr<QPersistentModelIndex> m_contextMenuIndex;
+
+ enum MessageTypeIndex {
+ NormalMessage,
+ DocumentMessage
+ };
+};
+
+#endif // KDEVCODEVIEW_H
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.h (revision 1522570)
@@ -0,0 +1,49 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef QDYNAMICTEXT_H
+#define QDYNAMICTEXT_H
+
+#include <QObject>
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/base_object.hpp>
+#include "lib/dynamictext/dynamictext.h"
+
+class QDynamicText : public QObject, public DynamicText {
+ Q_OBJECT
+ public:
+ explicit QDynamicText( const VectorTimestamp& initialState = VectorTimestamp(), const std::string& initialText = std::string() );
+
+ QDynamicText( const QDynamicText& rhs );
+
+ QDynamicText& operator = ( const QDynamicText& rhs );
+
+ template<class Archive>
+ void serialize( Archive& arch, const unsigned int ) {
+ arch & boost::serialization::base_object<DynamicText>(*this);
+ }
+
+ signals:
+ void stateChanged( QDynamicText& text );
+ void inserted( const ReplacementPointer& replacement, QDynamicText& text );
+ private:
+ virtual void notifyInserted( const ReplacementPointer& rep );
+ virtual void notifyStateChanged();
+};
+
+typedef SharedPtr<QDynamicText, BoostSerializationNormal> QDynamicTextPointer;
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qdynamictext.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp (revision 1522570)
@@ -0,0 +1,1012 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "patchesmanager.h"
+#include <boost/archive/polymorphic_xml_oarchive.hpp>
+#include <boost/archive/polymorphic_xml_iarchive.hpp>
+
+#include <QPersistentModelIndex>
+#include <QMenu>
+#include <QFile>
+#include <QTimer>
+
+#include <kmimetype.h>
+#include <kmimetypetrader.h>
+#include <kopenwithdialog.h>
+#include <k3process.h>
+#include <kprocess.h>
+#include <kdialog.h>
+
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/iplugincontroller.h>
+
+#include "lib/network/sessioninterface.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/messagesendhelper.h"
+
+#include "kdevteamworkplugin.h"
+#include "kdevteamwork_user.h"
+#include "ui_kdevteamwork_interface.h"
+#include "collaborationmanager.h"
+#include "messagemanager.h"
+#include "kdevteamwork_client.h"
+#include "kdevteamwork_helpers.h"
+#include "teamworkfoldermanager.h"
+#include "editpatch.h"
+
+#include "serializationutils.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+QString userNameFromSession( const SessionPointer& session ) {
+ UserPointer::Locked lu = userFromSession( session );
+ if ( lu ) {
+ return ~lu->name();
+ } else {
+ return "unlockable-user";
+ }
+}
+
+///Tries to extract the default-extension from a pattern-list. The returned extension includes the dot.
+QString getDefaultExtension( const QStringList& patterns ) {
+ if ( patterns.isEmpty() )
+ return "";
+ for ( QStringList::const_iterator it = patterns.begin(); it != patterns.end(); ++it ) {
+ QString s = *it;
+ int i = s.lastIndexOf( "*." );
+ if ( i == -1 )
+ continue;
+ return s.mid( i + 1 );
+ }
+ return "";
+}
+
+
+///currently, KOpenWithDlg crashes.
+//#define USE_KOPENWITHDLG
+
+REGISTER_MESSAGE( PatchesManagerMessage )
+REGISTER_MESSAGE( PatchesListMessage )
+EASY_IMPLEMENT_MESSAGE( PatchRequestMessage )
+EASY_IMPLEMENT_MESSAGE( PatchMessage )
+
+Q_DECLARE_METATYPE( QPersistentModelIndex )
+Q_DECLARE_METATYPE( LocalPatchSourcePointer )
+Q_DECLARE_METATYPE( MessagePointer )
+
+PatchesManager::PatchesManager( KDevTeamwork* tw ) : QObject( tw ), m_teamwork( tw ), dispatcher_( *this ), m_manageDlg( 0 ) {
+
+ connect( m_teamwork, SIGNAL( init() ), this, SLOT( init() ) );
+
+ qRegisterMetaType<PatchesManagerMessagePointer>( "PatchesManagerMessagePointer" );
+ qRegisterMetaType<LocalPatchSourcePointer>( "LocalPatchSourcePointer" );
+
+ m_showPatchAction = new QAction( i18n("Show"), this );
+ connect( m_showPatchAction, SIGNAL( triggered() ), this, SLOT( slotShowPatch() ) );
+ m_showPatchAction->setToolTip( i18n("Request and show the selected file.") );
+
+ m_showPatchInfoAction = new QAction( i18n("Show Info"), this );
+ connect( m_showPatchInfoAction, SIGNAL( triggered() ), this, SLOT( slotShowPatchInfo() ) );
+ m_showPatchInfoAction->setToolTip( i18n("Show Information about the selected file.") );
+
+ m_downloadPatchAction = new QAction( i18n("Download Item"), this );
+ connect( m_downloadPatchAction, SIGNAL( triggered() ), this, SLOT( slotDownloadPatch() ) );
+ m_downloadPatchAction->setToolTip( i18n("Download the item and store it into the list of local items.") );
+
+ m_applyPatchAction = new QAction( i18n("Apply Locally"), this );
+ connect( m_applyPatchAction, SIGNAL( triggered() ), this, SLOT( slotApplyPatch() ) );
+ m_applyPatchAction->setToolTip( i18n("Apply the item/patch to the local workspace/project and store it into the list of local patches.") );
+
+ m_allowPatchAction = new QAction( i18n("Allow"), this );
+ connect( m_allowPatchAction, SIGNAL( triggered() ), this, SLOT( slotAllowPatch() ) );
+ m_allowPatchAction->setToolTip( i18n("Send the requested patch to the user.") );
+
+ m_denyPatchAction = new QAction( i18n("Deny"), this );
+ connect( m_denyPatchAction, SIGNAL( triggered() ), this, SLOT( slotDenyPatch() ) );
+ m_denyPatchAction->setToolTip( i18n("Do not send the requested patch to the user.") );
+
+ m_showRequestedPatchAction = new QAction( i18n("Show Patch-Info"), this );
+ connect( m_showRequestedPatchAction, SIGNAL( triggered() ), this, SLOT( slotShowRequestedPatch() ) );
+ m_showRequestedPatchAction->setToolTip( i18n("Show the requested patch.") );
+
+ m_updateTimer = new QTimer( this );
+ m_updateTimer->setSingleShot( true );
+ connect( m_updateTimer, SIGNAL(timeout()), this, SLOT(guiUpdatePatchesList() ) );
+ connect( m_teamwork, SIGNAL( deInit() ), this, SLOT( save() ) );
+}
+
+void PatchesManager::init() {
+ connect( m_teamwork->widgets().managePatches, SIGNAL( pressed() ), this, SLOT( slotManagePatches() ) );
+ connect( m_teamwork, SIGNAL( updateConnection( TeamworkClientPointer ) ), this, SLOT( slotUpdateConnection( TeamworkClientPointer ) ) );
+ load();
+}
+
+void PatchesManager::slotManagePatches() {
+ m_manageDlg = new KDialog( m_teamwork->widget() );
+ m_manageDlg->setButtons( KDialog::Close );
+ m_manageDlg->setCaption( i18n("Manage Patches") );
+ m_managePatches.setupUi( m_manageDlg->mainWidget() );
+ m_managePatches.patchesList->setEditTriggers( QAbstractItemView::NoEditTriggers );
+ connect( m_managePatches.edit, SIGNAL( pressed() ), this, SLOT( slotEditPatch() ) );
+ connect( m_managePatches.add, SIGNAL( pressed() ), this, SLOT( slotAddPatch() ) );
+ connect( m_managePatches.remove, SIGNAL( pressed() ), this, SLOT( slotRemovePatch() ) );
+ connect( m_manageDlg, SIGNAL( finished() ), this, SLOT( slotCloseManagement() ) );
+ m_manageDlg->show();
+ m_patchesModel = new QStandardItemModel( 0, 1, m_managePatches.patchesList );
+ m_managePatches.patchesList->setModel( m_patchesModel );
+ guiUpdatePatchesList();
+}
+
+void PatchesManager::slotUpdateConnection( TeamworkClientPointer newClient ) {
+ if ( newClient ) {
+ log( "slotUpdateConnection", Debug );
+ connect( newClient.unsafe(), SIGNAL( signalDispatchMessage( PatchesManagerMessagePointer ) ), this, SLOT( processMessage( PatchesManagerMessagePointer ) ), Qt::QueuedConnection );
+ }
+}
+
+void PatchesManager::log( const QString& str, LogLevel level ) {
+ m_teamwork->log( "patchesmanager: " + str, level );
+}
+
+void PatchesManager::addPatch( const LocalPatchSourcePointer& patch ) {
+ if( !hasPatch( patch ) ) {
+ m_config.addPatch( patch );
+ guiUpdatePatchesList();
+ }
+}
+
+void PatchesManager::editStateChanged( EditPatch* ) {
+ m_updateTimer->start( 100 );
+}
+
+void PatchesManager::editDialogClosed( EditPatch* dialog ) {
+ m_editing.removeAll( dialog );
+ m_updateTimer->start( 100 );
+}
+
+bool PatchesManager::hasPatch( const LocalPatchSourcePointer& patch ) {
+ return m_config.hasPatch( patch );
+}
+
+void PatchesManager::slotAddPatch() {
+ showEditDialog( new LocalPatchSource(), true );
+}
+
+void PatchesManager::showPatchInfo( const LocalPatchSourcePointer & patch, bool local ) {
+ showEditDialog( patch, local );
+}
+
+EditPatchPointer PatchesManager::showEditDialog( const LocalPatchSourcePointer & patch, bool local ) {
+ if( !patch ) return 0;
+ for( QList<EditPatchPointer>::iterator it = m_editing.begin(); it != m_editing.end(); ++it ) {
+ if( (*it)->patch() == patch ) return *it;
+ }
+ EditPatchPointer p = new EditPatch( this, patch, local );
+
+ connect( p.data(), SIGNAL(dialogClosed( EditPatch* )), this, SLOT( editDialogClosed( EditPatch* ) ) );
+ connect( p.data(), SIGNAL(stateChanged( EditPatch* )), this, SLOT( editStateChanged( EditPatch* ) ) );
+ m_editing << p;
+ return p;
+}
+
+void PatchesManager::slotEditPatch() {
+ showEditDialog( selectedPatch(), true );
+}
+
+void PatchesManager::slotRemovePatch() {
+ LocalPatchSourcePointer p = selectedPatch();
+
+ if ( p )
+ m_config.patchSources.remove( p );
+
+ guiUpdatePatchesList();
+}
+
+void PatchesManager::slotCloseManagement() {}
+
+void PatchesManager::slotManagementFinished( int /*result*/ ) {
+ m_manageDlg = 0;
+}
+
+LocalPatchSourcePointer PatchesManager::selectedPatch() {
+ if ( !m_manageDlg )
+ return LocalPatchSourcePointer();
+ QModelIndex i = m_managePatches.patchesList->currentIndex();
+ if ( i.isValid() )
+ i = m_patchesModel->index( i.row(), 0 );
+
+ if ( i.isValid() ) {
+ QVariant v = m_patchesModel->data( i, Qt::UserRole );
+ if ( v.canConvert<LocalPatchSourcePointer>() ) {
+ return v.value<LocalPatchSourcePointer>();
+ } else {
+ log( "bad data in patches-list" );
+ }
+ }
+
+ return LocalPatchSourcePointer();
+}
+
+///The following three functions are nearly the same, maybe they should be put together
+void PatchesManager::slotApplyPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<LocalPatchSourcePointer>() )
+ throw "cannot convert to patch-source";
+
+ LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
+ if ( !lpatch )
+ throw "could not lock patch-source";
+
+ UserPointer::Locked user = lpatch->user();
+ if ( !user )
+ throw "the patch has no associated user";
+ if ( !user->online() )
+ throw "the user is not online";
+
+ SessionPointer::Locked lsession = user->online().session();
+ if ( !lsession )
+ throw "the session could not be locked";
+
+ SafeSharedPtr<PatchRequestMessage>::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork, PatchRequestData::Apply );
+ lsession->send( mp );
+ m_teamwork->addMessageToList( ( PatchRequestMessage* ) mp );
+ } catch ( const char * str ) {
+ log( QString( "error in slotApplyPatch: " ) + str, Error );
+ }
+}
+
+void PatchesManager::slotDownloadPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<LocalPatchSourcePointer>() )
+ throw "cannot convert to patch-source";
+
+ LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
+ if ( !lpatch )
+ throw "could not lock patch-source";
+
+ UserPointer::Locked user = lpatch->user();
+ if ( !user )
+ throw "the patch has no associated user";
+ if ( !user->online() )
+ throw "the user is not online";
+
+ SessionPointer session = user->online().session();
+ if ( !session )
+ throw "the session could not be acquired";
+
+ MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork, PatchRequestData::Download );
+ session.unsafe() ->send( mp );
+ m_teamwork->addMessageToList( mp );
+ } catch ( const char * str ) {
+ log( QString( "error in slotDownloadPatch: " ) + str, Error );
+ }
+}
+
+void PatchesManager::slotShowPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<LocalPatchSourcePointer>() )
+ throw "cannot convert to patch-source";
+
+ LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
+ if ( !lpatch )
+ throw "could not lock patch-source";
+
+ UserPointer::Locked user = lpatch->user();
+ if ( !user )
+ throw "the patch has no associated user";
+ if ( !user->online() )
+ throw "the user is not online";
+
+ SessionPointer session = user->online().session();
+ if ( !session )
+ throw "the session could not be acquired";
+
+ MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork );
+ session.unsafe() ->send( mp );
+ m_teamwork->addMessageToList( mp );
+ } catch ( const char * str ) {
+ log( QString( "error in slotShowPatch: " ) + str, Error );
+ }
+}
+
+void PatchesManager::slotShowPatchInfo() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<LocalPatchSourcePointer>() )
+ throw "cannot convert to patch-source";
+
+ showPatchInfo( v.value<LocalPatchSourcePointer>(), false );
+ } catch ( const char * str ) {
+ log( QString( "error in slotShowPatchInfo: " ) + str, Error );
+ }
+}
+
+void PatchesManager::processMessage( PatchesManagerMessagePointer msg ) {
+ log( "dispatching message", Debug );
+ PatchesManagerMessagePointer::Locked l = msg;
+ if ( l ) {
+ dispatcher_( l );
+ } else {
+ log( "PatchesManager could not lock a message-pointer", Error );
+ }
+}
+
+int PatchesManager::receiveMessage( MessageInterface* msg ) {
+ m_teamwork->log( QString( "PatchesManager got unknown message of type " ) + msg->name() );
+ return 0;
+}
+
+int PatchesManager::receiveMessage( PatchMessage* msg ) {
+ try {
+ SafeSharedPtr<PatchRequestMessage>::Locked request = msg->info().replyToMessage().cast<PatchRequestMessage>();
+ if ( !request )
+ throw QString( "got unrequested patch-message, or could not lock patch-request" );
+
+ LocalPatchSourcePointer::Locked patchInfo = request->request(); ///For security, information like apply-command etc. are cached
+ if ( !patchInfo )
+ throw QString( "could not get or lock patch-information" );
+
+ LocalPatchSourcePointer::Locked patchInfoNew = msg->patch(); ///For security, information like apply-command etc. are cached
+ if ( !patchInfo )
+ throw QString( "could not get or lock patch-information" );
+
+ if ( !( patchInfoNew->identity() == request->patchIdentity() ) )
+ throw QString( "identity of received patch does not match the identity of the corresponding request" );
+
+ KMimeType::Ptr mime = KMimeType::mimeType( ~patchInfo->type );
+ if ( !mime )
+ throw QString( "Error in kdelibs: could not create mime-type" ); ///according to the documentation this should never happen, but it does
+
+ QString userName;
+ if( msg->info().session().cast<FakeSession>() )
+ userName = "local";
+ else
+ userName = userNameFromSession( msg->info().session() );
+ QString fileName = ~patchInfo->name;
+ if( !patchInfo->filename.empty() )
+ fileName += "_" + QFileInfo(~patchInfo->filename).fileName();
+ else
+ fileName += getDefaultExtension( mime->patterns() );
+
+ log( QString( "creating file for patch: %1" ).arg( fileName ), Debug );
+
+ KUrl filePath = TeamworkFolderManager::createUniqueFile( "patches/"+userName, fileName );
+
+ {
+ ///@todo make this work with remove files
+ QFile file( filePath.toLocalFile() );
+
+ file.open( QIODevice::WriteOnly );
+ if ( !file.isOpen() )
+ throw QString( "could not open %1" ).arg( filePath.prettyUrl() );
+
+ file.write( msg->data() );
+ log( QString( "writing patch of size %1 to %2" ).arg( msg->data().size() ).arg( filePath.prettyUrl() ), Debug );
+ }
+ if ( request->requestType() == PatchRequestData::View )
+ TeamworkFolderManager::registerTempItem( filePath );
+
+ switch ( request->requestType() ) {
+ case PatchRequestData::Apply: {
+ ///Apply the patch to the local tree
+ if ( patchFromIdentity( patchInfo->identity() ) )
+ throw QString( "there already is another local patch with identity \"%1\"" ).arg( ~patchInfo->identity().desc() );
+
+ //LocalPatchSourcePointer::Locked newPatchInfo( patchInfo );//new LocalPatchSource( *patchInfo ) );
+ if( !hasPatch( patchInfo ) ) {
+ ///@todo make work with remote files
+ patchInfo->setFileName( ~filePath.toLocalFile() );
+ addPatch( patchInfo);
+ }
+
+ EditPatch* p = showEditDialog( patchInfo, true );
+ if( !p ) throw QString( "cannot edit received patch" );
+ ///@todo ...
+ p->apply( false, filePath.toLocalFile() );
+
+ guiUpdatePatchesList();
+ };
+ break;
+ case PatchRequestData::Download: {
+ if ( patchFromIdentity( patchInfo->identity() ) )
+ throw QString( "there already is another local patch with identity \"%1\"" ).arg( ~patchInfo->identity().desc() );
+ ///Store the patch locally
+ LocalPatchSourcePointer::Locked newPatchInfo( new LocalPatchSource( *patchInfo ) );
+ ///@todo make work with remote files
+ newPatchInfo->setFileName( ~filePath.toLocalFile() );
+ m_config.patchSources.push_back( newPatchInfo );
+ guiUpdatePatchesList();
+ }
+ break;
+ case PatchRequestData::View: {
+ ///Show the patch
+
+ ///@todo where has KDevDiffFrontend gone? When will it be back?
+// if ( patchInfo->type == "text/x-diff" ) {
+// QString str = msg->data();
+//
+// KDevDiffFrontend *df = KDevTeamworkPlugin::staticCore()->pluginController()->pluginForExtension<KDevDiffFrontend>( "KDevelop/DiffFrontend" );
+// if ( df ) {
+// df->showDiff( str );
+// return 1;
+// } else {
+// log( "no diff-interface available!", Error );
+// }
+// }
+
+ if( !KDevTeamworkPlugin::staticDocumentController()->openDocument( filePath, KTextEditor::Cursor()) ) {
+ log( QString( "could not open %1 with the document-controller" ).arg( filePath.prettyUrl() ), Warning );
+
+ auto_ptr<KOpenWithDialog> d( new KOpenWithDialog( ~patchInfo->type, "" ) );
+
+ if ( d->exec() == QDialog::Accepted ) {
+ QString app = d->text();
+ if ( !app.isEmpty() ) {
+ ///@todo How to run this in a better way, so that .desktop-files are accepted etc.?
+ // Use KRun, of course!
+ KProcess proc;
+ proc << app;
+
+ proc << fileName;
+ proc.startDetached();
+ } else {
+ log( "no application was chosen for opening " + fileName, Warning );
+ }
+ } else {
+ throw QString( "open-with dialog was closed" );
+ }
+ d.reset(0);
+
+/* ///Open with KRun instead
+ if( KRun::runUrl( KUrl(filePath), ~patchInfo->type, KDevTeamworkPlugin::staticCore()->uiController()->activeMainWindow() ) == 0 ) {
+ log( QString( "Failed to open %1 with an application" ).arg( filePath ), Warning );
+ }*/
+ }
+ ///Find an application that is able to open the selected mime-type
+ /*
+ QString tempFileName;
+ KTempFile tempFile( QString(), getDefaultExtension( mime->patterns() ) );
+
+ if ( tempFile.status() != 0 ) {
+ throw QString( "could not create temporary file" );
+ } else {
+ tempFileName = tempFile.name();
+ log( "name of the temp-file: " + tempFileName, Debug );
+ QDataStream* stream = tempFile.dataStream();
+ if ( stream ) {
+ *stream << msg->data();
+ if ( tempFile.status() != 0 )
+ throw QString( "writing to the temporary file failed" );
+ } else {
+ throw QString( "could not get stream" );
+ }
+ }
+
+ if ( !mime->isValid() )
+ throw "service-type is not valid, file: " + tempFileName;
+
+ QString app;
+
+#ifdef USE_KOPENWITHDLG
+
+ auto_ptr<KOpenWithDlg> d = new KOpenWithDlg( ~patchInfo->type, "" );
+
+ if ( d->exec() == QDialog::Accepted ) {
+ app = d->text();
+ } else {
+ throw QString( "open-with dialog was closed" );
+ }
+ d = 0;
+#else
+
+ KService::Ptr service = KMimeTypeTrader::self() ->preferredService( ~patchInfo->type , "KPlugins/ReadOnlyPlugin" );
+ if ( !service )
+ throw QString( "could not get a service that can handle " + ~patchInfo->type );
+
+ app = service->exec();
+
+#endif
+
+ if ( !app.isEmpty() ) {
+ KProcess proc;
+ proc << app;
+
+ proc << tempFileName;
+ proc.startDetached();
+ } else {
+ log( "no application was chosen for opening " + tempFileName, Warning );
+ }*/
+ }
+ break;
+ }
+ } catch ( const QString & str ) {
+ log( QString( "dispatch of patch-message from %1 failed: " ).arg( userFromSession( msg->info().session() ) ) + str , Error );
+ }
+
+ return 0;
+}
+
+LocalPatchSourcePointer::Locked PatchesManager::patchFromIdentity( const LocalPatchSource::Identity& ident ) {
+ for ( list<LocalPatchSourcePointer>::iterator it = m_config.patchSources.begin(); it != m_config.patchSources.end(); ++it ) {
+ LocalPatchSourcePointer::Locked l = ( *it );
+ if ( l ) {
+ if ( ident == l->identity() ) {
+ return l;
+ }
+ } else {
+ log( "could not lock patch-source", Warning );
+ }
+ }
+ return 0;
+}
+
+LocalPatchSourcePointer PatchesManager::merge( const QString& name, const QList<LocalPatchSourcePointer>& patches ) {
+ try {
+ LocalPatchSourcePointer::Locked lp = new LocalPatchSource();
+
+ foreach( LocalPatchSourcePointer patch, patches ) {
+ LocalPatchSourcePointer::Locked l = patch;
+ if ( !l )
+ throw "could not lock patch-source";
+ if ( l->type != "text/x-diff" )
+ throw "a mime-type is not text/x-diff, only that types can be merged";
+ if(l->userIdentity) lp->userIdentity = l->userIdentity;
+ }
+
+
+ QString user = "local";
+ if( lp->userIdentity )
+ user = ~lp->userIdentity.name();
+
+ KUrl file = TeamworkFolderManager::createUniqueFile( "patches/"+user, name+".diff" );
+
+ ///@todo make this work with remove Urls
+ QFile target( file.toLocalFile() );
+ if ( !target.open( QIODevice::WriteOnly ) )
+ throw QString( "could not open file %1" ).arg( file.prettyUrl() );
+
+ foreach( LocalPatchSourcePointer patch, patches ) {
+ LocalPatchSourcePointer::Locked l = patch;
+ if ( !l )
+ throw "could not lock patch-source";
+
+
+
+ KUrl u = TeamworkFolderManager::teamworkAbsolute( ~l->filename, "patches" );
+ ///@todo make this work with remove Urls
+ QFile f( u.toLocalFile() );
+ if ( !f.open( QIODevice::ReadOnly ) )
+ throw QString( "could not open file %1" ).arg( u.prettyUrl() );
+
+ target.write( f.readAll() );
+ target.write( "\n", 1 );
+ }
+
+ lp->name = ~name;
+ lp->filename = ~TeamworkFolderManager::teamworkRelative( file, "patches" );
+ lp->type = "text/x-diff";
+
+ return lp;
+ } catch ( const char * str ) {
+ log( QString( "error while trying to merge patches: %1" ).arg( str ) , Error );
+ } catch ( const QString & str ) {
+ log( QString( "error while trying to merge patches: %1" ).arg( str ) , Error );
+ }
+ return 0;
+}
+
+
+int PatchesManager::receiveMessage( PatchRequestMessage* msg ) {
+ ///Send the patch to the target.
+ LocalPatchSourcePointer::Locked patch = patchFromIdentity( msg->patchIdentity() );
+
+ bool overrideAccess = false;
+ if( msg->info().session().cast<FakeSession>() ) overrideAccess = true;
+
+ LocalPatchSourcePointer::Locked lpatch = patch;
+ if ( patch && lpatch ) {
+ if( !overrideAccess ) {
+ switch ( lpatch->access ) {
+ case Public:
+ break;
+ case ConnectedOnly: {
+ if ( !m_teamwork->collaborationManager() ->isCollaborating( userFromSession( msg->info().session() ) ) ) {
+ log( "not sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) + " because the user is not collaborating" );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "access only for collaborating users" );
+ return 1;
+ }
+ }
+ break;
+ case Ask:
+ m_teamwork->addMessageToList( msg );
+ return 1;
+ break;
+ default: {
+ log( "not sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) + " because the patch is private" );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "the patch is private" );
+ return 1;
+ }
+ break;
+ }
+ }
+ log( "sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) );
+ globalMessageSendHelper().sendReply<PatchMessage>( msg, ( LocalPatchSourcePointer ) patch, m_teamwork->logger() );
+ } else {
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "no fitting patch available, or patch could not be locked" );
+ log( "got a patch-request, but the requested patch could not be found or could not be locked", Warning );
+ }
+
+ return 1;
+}
+
+int PatchesManager::receiveMessage( PatchesListMessage* msg ) {
+ ///Give the list to the GUI or whoever was waiting for it
+ m_teamwork->handlePatchesList( msg );
+ return 0;
+}
+
+int PatchesManager::receiveMessage( PatchesManagerMessage* msg ) {
+ if ( !msg->isDerived() ) {
+ switch ( msg->message() ) {
+ case PatchesManagerMessage::None:
+ break;
+ case PatchesManagerMessage::GetPatchesList: {
+ SessionPointer::Locked l = msg->info().session();
+ if ( l && l->isRunning() ) {
+ l->send( new PatchesListMessage( globalMessageTypeSet(), m_config.patchSources ) );
+
+ UserPointer::Locked pl = l->safeUser();
+ if ( pl ) {
+ log( QString( "sending patches-list to " ) + pl->name().c_str() );
+ } else {
+ log( "sent patches-list through anonymous session" );
+ }
+
+ } else {
+ log( QString( "could not answer a patches-list-request" ) );
+ }
+ }
+ break;
+ }
+ } else {
+ log( QString( "could not handle a PatchesManagerMessage of real type " ) + msg->name() );
+ }
+ return 0;
+}
+
+void PatchesManager::guiUpdatePatchesList() {
+ if ( !m_manageDlg )
+ return ;
+
+ m_patchesModel->clear();
+ m_patchesModel->insertColumns( 0, 5 );
+
+ m_patchesModel->setHeaderData( 0, Qt::Horizontal, QString( "Name" ) );
+ m_patchesModel->setHeaderData( 1, Qt::Horizontal, QString( "File/Command" ) );
+ m_patchesModel->setHeaderData( 2, Qt::Horizontal, QString( "Access" ) );
+ m_patchesModel->setHeaderData( 3, Qt::Horizontal, QString( "Type" ) );
+ m_patchesModel->setHeaderData( 4, Qt::Horizontal, QString( "State" ) );
+
+ for ( std::list<LocalPatchSourcePointer>::iterator it = m_config.patchSources.begin(); it != m_config.patchSources.end(); ++it ) {
+ LocalPatchSourcePointer::Locked l = *it;
+ m_patchesModel->insertRow( 0 );
+ if ( l ) {
+ m_patchesModel->setData( m_patchesModel->index( 0, 0 ), ~l->name, Qt::DisplayRole );
+ m_patchesModel->setData( m_patchesModel->index( 0, 1 ), ~( l->filename + l->command ), Qt::DisplayRole );
+ m_patchesModel->setData( m_patchesModel->index( 0, 2 ), ~l->accessAsString(), Qt::DisplayRole );
+ m_patchesModel->setData( m_patchesModel->index( 0, 3 ), ~l->type, Qt::DisplayRole );
+ m_patchesModel->setData( m_patchesModel->index( 0, 4 ), ~l->stateAsString(), Qt::DisplayRole );
+ } else {
+ m_patchesModel->setData( m_patchesModel->index( 0, 0 ), "lock failed", Qt::DisplayRole );
+ }
+ QVariant v;
+ v.setValue( *it );
+
+ m_patchesModel->setData( m_patchesModel->index( 0, 0 ), v, Qt::UserRole );
+ }
+
+ m_patchesModel->sort( 4 );
+}
+
+PatchesManager::~PatchesManager() {
+}
+
+QIcon LocalPatchSource::getIcon( IconCache& icons ) {
+ return icons( "patch" );
+}
+
+void PatchesManager::slotShowRequestedPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant userVar = act->data();
+ if ( !userVar.canConvert<MessagePointer>() )
+ throw "cannot convert to message-pointer";
+
+ SafeSharedPtr<PatchRequestMessage>::Locked msg = userVar.value<MessagePointer>().cast<PatchRequestMessage>();
+ if ( !msg )
+ throw "cannot lock/cast message";
+
+ LocalPatchSourcePointer::Locked lpatch = patchFromIdentity( msg->patchIdentity() );
+ if ( !lpatch )
+ throw "could not find the requested patch";
+
+ showEditDialog( lpatch, false );
+
+ } catch ( const char * str ) {
+ log( QString( "slotShowRequestedPatch failed: " ) + str );
+ }
+}
+
+void PatchesManager::slotAllowPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant userVar = act->data();
+
+ if ( !userVar.canConvert<MessagePointer>() )
+ throw "cannot convert to message-pointer";
+
+ SafeSharedPtr<PatchRequestMessage>::Locked msg = userVar.value<MessagePointer>().cast<PatchRequestMessage>();
+ if ( !msg )
+ throw "cannot lock/cast message";
+
+ LocalPatchSourcePointer::Locked lpatch = patchFromIdentity( msg->patchIdentity() );
+ if ( !lpatch )
+ throw "could not find the requested patch";
+
+ log( "sending patch " + ~lpatch->name + " to " + userNameFromSession( msg->info().session() ) );
+ globalMessageSendHelper().sendReply<PatchMessage>( msg, ( LocalPatchSourcePointer ) lpatch, m_teamwork->logger() );
+
+ msg->setStatus( PatchRequestData::Accepted );
+
+ m_teamwork->messageManager() ->updateMessage( msg.data() );
+ } catch ( const char * str ) {
+ log( QString( "slotAllowPatch failed: " ) + str );
+ }
+}
+
+
+void PatchesManager::slotDenyPatch() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+
+ if ( v.canConvert<MessagePointer>() )
+ throw "cannot convert to message-pointer";
+
+ SafeSharedPtr<PatchRequestMessage>::Locked msg = v.value<MessagePointer>().cast<PatchRequestMessage>();
+ if ( !msg )
+ throw "cannot lock/cast message";
+
+ log( "denying patch to " + userNameFromSession( msg->info().session() ) );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "access denied" );
+
+ msg->setStatus( PatchRequestData::Denied );
+
+ m_teamwork->messageManager() ->updateMessage( msg.data() );
+ } catch ( const char * str ) {
+ log( QString( "slotAllowPatch failed: " ) + str );
+ }
+}
+
+void PatchesManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {
+ /*try {
+ xmlDeserializeFromElementItem( el, "PatchesManager", NVP( m_config ) );
+ } catch ( const QString & str ) {
+ log( "could not restore the patch-information: " + str, Error );
+ }*/
+}
+
+void PatchesManager::savePartialProjectSession( QDomElement* /*el*/ ) {
+ /*try {
+ xmlSerializeToElementItem( el, "PatchesManager", NVP( m_config ) );
+ } catch ( const QString & str ) {
+ log( "could not save the patch-information: " + str, Error );
+ }*/
+}
+
+KDevTeamwork* PatchesManager::teamwork() {
+ return m_teamwork;
+}
+
+void PatchesManager::fillDeveloperActions( const QModelIndex& index, QMenu* menu ) {
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+
+ m_showPatchInfoAction->setData( v );
+ m_showPatchAction->setData( v );
+ m_downloadPatchAction->setData( v );
+ m_applyPatchAction->setData( v );
+
+ menu->addAction( m_showPatchInfoAction );
+ menu->addAction( m_showPatchAction );
+ menu->addAction( m_downloadPatchAction );
+ menu->addAction( m_applyPatchAction );
+}
+
+void PatchRequestData::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
+ QVariant v;
+
+ v.setValue( MessagePointer( selfMessage() ) );
+ teamwork->patchesManager() ->m_denyPatchAction->setData( v );
+ menu->addAction( teamwork->patchesManager() ->m_denyPatchAction );
+
+ teamwork->patchesManager() ->m_allowPatchAction->setData( v );
+ menu->addAction( teamwork->patchesManager() ->m_allowPatchAction );
+
+ teamwork->patchesManager() ->m_showRequestedPatchAction->setData( v );
+ menu->addAction( teamwork->patchesManager() ->m_showRequestedPatchAction );
+}
+
+QStringList splitArgs( const QString& str );
+
+LocalPatchSource::State PatchesManager::determineState( const LocalPatchSourcePointer& patch ) {
+ LocalPatchSourcePointer::Locked lpatch = patch;
+ if( !lpatch ) {
+ log( "determineState(..) could not lock patch", Error );
+ return LocalPatchSource::Unknown;
+ }
+ try {
+ if( lpatch->type != "text/x-diff" )
+ throw "state can only be determined for files of type \"text/x-diff\"";
+ if( lpatch->filename.empty() )
+ throw "state can only be determined for file-patches";
+
+/* KUrl fileUrl = projectDir();
+ if( (~lpatch->filename).startsWith( fileUrl.toLocalFile() ) )
+ fileUrl = KUrl( ~lpatch->filename );
+ else
+ fileUrl.addPath( ~lpatch->filename );*/
+ KUrl fileUrl = ~lpatch->filename;
+
+ if( lpatch->patchTool() != "patch" || lpatch->patchTool(true) != "patch" ) throw QString( "cannot determine state with other tool than patch: \"%1\" \"%2\"").arg(~lpatch->patchTool()).arg(~lpatch->patchTool(true)) ;
+
+ {
+ K3Process proc;
+ ///@todo does not work with remove directories
+ proc.setWorkingDirectory( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
+ // proc << ~lpatch->patchTool();
+ bool hadFile = false;
+ QString applyParams = ~lpatch->patchParams(false);
+ if( applyParams.contains( "$FILE" ) )
+ hadFile = true;
+ //applyParams.replace( "$FILE", fileUrl.toLocalFile() );
+ proc.setEnvironment( "FILE", fileUrl.toLocalFile() );
+ //proc << "--dry-run" << "-s" << "-f";
+ QString cmd = ~lpatch->patchTool() + " --dry-run " + applyParams + " -s -f";
+ if( !hadFile ) {
+ //proc << "-i" << fileUrl.toLocalFile();
+ cmd += " -i " + fileUrl.toLocalFile();
+ }
+ proc << splitArgs( cmd );
+
+ log( "determineState(...) calling " + cmd, Debug );
+
+ if( !proc.start( K3Process::Block ) ) throw "could not start process";
+ if( !proc.normalExit() ) throw "process did not exit normally";
+ log( QString( "exit-status: %1").arg( proc.exitStatus() ), Debug );
+ if( proc.exitStatus() == 0 ) {
+ lpatch->state = LocalPatchSource::NotApplied;
+ return LocalPatchSource::NotApplied;
+ }
+ }
+
+ {
+ K3Process proc;
+ ///@todo does not work with remove directories
+ proc.setWorkingDirectory( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
+ //proc << ~lpatch->patchTool(true);
+
+ bool hadFile = false;
+ QString applyParams = ~lpatch->patchParams(true);
+ if( applyParams.contains( "$FILE" ) ) {
+ hadFile = true;
+ }
+ proc.setEnvironment( "FILE", fileUrl.toLocalFile() );
+
+ //proc << "--dry-run" << "-s" << "-f" << applyParams;
+ QString cmd = ~lpatch->patchTool(true) + " --dry-run -s -f " + applyParams;
+ if( !hadFile ) {
+ //proc << "-i" << fileUrl.toLocalFile();
+ cmd += " -i " + fileUrl.toLocalFile();
+ }
+ proc << splitArgs( cmd );
+ log( "determineState(...) calling " + cmd, Debug );
+
+ if( !proc.start( K3Process::Block ) ) throw "could not start patch-process";
+ if( !proc.normalExit() ) throw "process did not exit normally";
+ log( QString( "exit-status: %1").arg( proc.exitStatus() ), Debug );
+ if( proc.exitStatus() == 0 ) {
+ lpatch->state = LocalPatchSource::Applied;
+ return LocalPatchSource::Applied;
+ }
+ }
+ } catch( const QString& str ) {
+ log( "Error in determineState: " + str, Error );
+ } catch( const char* str ) {
+ log( QString("Error in determineState: ") + str, Error );
+ }
+ lpatch->state = LocalPatchSource::Unknown;
+ return LocalPatchSource::Unknown;
+}
+
+void PatchesManager::save() {
+ try {
+ KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "patches.database" );
+ ///@todo does not work with remote files
+ if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
+
+ std::ofstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::out | ios_base::binary );
+ if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for writing";
+ boost::archive::polymorphic_xml_oarchive arch( file );
+ arch << NVP(m_config);
+ } catch ( std::exception & exc ) {
+ log( QString("save(): exception occurred while serialization: %1").arg( exc.what() ), Error );
+ } catch( const char* str ) {
+ log( QString("save(): %1").arg( str ), Error );
+ } catch( const QString& str ) {
+ log( QString( "save(): %1").arg( str ), Error );
+ }
+}
+
+void PatchesManager::load() {
+ try {
+ KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "patches.database" );
+ ///@todo does not work with remote files
+ if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
+
+ std::ifstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::binary );
+ if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for reading";
+ boost::archive::polymorphic_xml_iarchive arch( file );
+ arch >> NVP(m_config);
+ } catch ( std::exception & exc ) {
+ log( QString("load(): exception occurred while serialization: %1").arg( exc.what() ), Error );
+ } catch( const char* str ) {
+ log( QString("load(): %1").arg( str ), Error );
+ } catch( const QString& str ) {
+ log( QString( "load(): %1").arg( str ), Error );
+ }
+ guiUpdatePatchesList();
+}
+
+#include "patchesmanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp (revision 1522570)
@@ -0,0 +1,425 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "collaborationmanager.h"
+#include "lib/network/messagesendhelper.h"
+#include <QPersistentModelIndex>
+#include <QMenu>
+#include <QMetaType>
+#include "filecollaborationmanager.h"
+#include "messagemanager.h"
+#include "kdevteamwork_user.h"
+#include "kdevteamwork_client.h"
+#include <QModelIndex>
+#include <QPoint>
+#include <QTimer>
+#include "ui_kdevteamwork_interface.h"
+#include <QStandardItemModel>
+
+Q_DECLARE_METATYPE( MessagePointer )
+using namespace std;
+typedef QPointer<FileCollaborationSession> QFileCollaborationSessionPointer;
+Q_DECLARE_METATYPE( QPersistentModelIndex )
+Q_DECLARE_METATYPE( QFileCollaborationSessionPointer )
+
+CollaborationManager::CollaborationManager( KDevTeamwork* tw ) : SafeLogger( tw->logger() ), m_teamwork( tw ), m_fileCollaboration( this ), m_ignoreClick( false ) {
+
+ m_contextMenuTimer = new QTimer( this );
+ m_contextMenuTimer->setSingleShot( true );
+
+ connect( m_contextMenuTimer, SIGNAL( timeout() ), this, SLOT( maybeContextMenu() ) );
+
+ m_closeCollaborationAction = new QAction( i18n("Stop Collaboration"), this );
+ connect( m_closeCollaborationAction, SIGNAL( triggered() ), this, SLOT( uiCloseCollaboration() ) );
+
+ m_developersModel = new QStandardItemModel( 0, 1, this );
+
+ qRegisterMetaType<MessagePointer>( "MessagePointer" );
+ qRegisterMetaType<QFileCollaborationSessionPointer>( "QFileCollaborationSessionPointer" );
+
+ m_acceptConnectionAction = new QAction( i18n("Accept Collaboration"), this );
+ connect( m_acceptConnectionAction, SIGNAL( triggered() ), this, SLOT( uiAcceptCollaboration() ) );
+ m_acceptConnectionAction->setToolTip( i18n("Start a collaboration-session with the user.") );
+
+ m_denyConnectionAction = new QAction( i18n("Refuse Collaboration"), this );
+ connect( m_denyConnectionAction, SIGNAL( triggered() ), this, SLOT( uiDenyCollaboration() ) );
+ m_denyConnectionAction->setToolTip( i18n("Refuse collaborating with the user.") );
+
+ m_requestCollaborationAction = new QAction( i18n("Request Collaboration"), this );
+ connect( m_requestCollaborationAction, SIGNAL( triggered() ), this, SLOT( uiRequestCollaboration() ) );
+ m_requestCollaborationAction->setToolTip( i18n("Request a collaboration-session to the selected user.") );
+
+ connect( m_teamwork, SIGNAL(init()), this, SLOT(init() ) );
+}
+
+void CollaborationManager::init() {
+ connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( collaboratingDeveloperClicked( const QModelIndex& ) ) );
+ connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( collaboratingDeveloperDoubleClicked( const QModelIndex& ) ) );
+
+ connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT(collaboratingDeveloperContextMenu( const QPoint& ) ) );
+
+ connect( m_teamwork, SIGNAL( updateConnection(TeamworkClientPointer) ), this, SLOT( updateConnection(const TeamworkClientPointer&) ) );
+ m_closeCollaborationAction->setToolTip( i18n("Stop collaborating with the selected developer.") );
+}
+
+CollaborationManager::~CollaborationManager() {
+}
+
+void CollaborationManager::addCollaboratingUser( const UserPointer& u ) {
+ if ( u )
+ m_collaboratingUsers.insert( u );
+ m_teamwork->startUpdateTimer();
+}
+
+void CollaborationManager::removeCollaboratingUser( const UserPointer& user ) {
+ m_collaboratingUsers.erase( user );
+ m_teamwork->startUpdateTimer();
+}
+
+bool CollaborationManager::isCollaborating( const UserPointer& user ) {
+ return m_collaboratingUsers.find( user ) != m_collaboratingUsers.end();
+}
+
+void CollaborationManager::sessionStateChanged( const FileCollaborationSessionPointer& /*session*/ ) {
+ updateList();
+}
+
+void CollaborationManager::updateList() {
+ QStandardItemModel* model = m_developersModel;
+ /*model->clear();
+ model->insertColumn( 0 );*/
+
+ ///find all users and sessions, and where they are stored in the tree-view
+ QMap< UserPointer, QPersistentModelIndex > users;
+
+ for( int r = 0; r < model->rowCount(); ++r ) {
+ QModelIndex i = model->index( r, 0 );
+ if( !i.isValid() ) continue;
+ QVariant v = i.data( Qt::UserRole );
+
+ if( v.canConvert<UserPointer>() ) {
+ users[ v.value<UserPointer>() ] = QPersistentModelIndex( i );
+ } else {
+ for( int r2 = 0; r2 < model->rowCount( i ); ++r2 ) {
+ QModelIndex i2 = model->index( r2, 0, i );
+ if( !i2.isValid() ) continue;
+
+ QVariant v = i.data( Qt::UserRole );
+
+ if( v.canConvert<UserPointer>() )
+ users[ v.value<UserPointer>() ] = QPersistentModelIndex( i2 );
+ }
+ }
+ }
+
+ ///Now remove all users that are not collaborating anymore
+ for( QMap< UserPointer, QPersistentModelIndex >::iterator it = users.begin(); it != users.end(); ++it ) {
+ if( m_collaboratingUsers.find( it.key() ) == m_collaboratingUsers.end() )
+ model->removeRows( it->row(), 1, it->parent() );
+ }
+
+ ///Now add/update all users
+ for ( UserSet::reverse_iterator it = m_collaboratingUsers.rbegin(); it != m_collaboratingUsers.rend(); ++it ) {
+ //FileCollaborationSessionPointer session = m_fileCollaboration->sessions().value( (*it).cast<KDevTeamworkUser>() );
+
+ KDevTeamworkUserPointer::Locked l = (*it).cast<KDevTeamworkUser>();
+
+ QModelIndex iparent;//( sessions[session] );
+ ///Insert the user
+ QModelIndex i;
+ if( users.contains( l.data() ) ) {
+ i = users[l.data()];
+ } else {
+ model->insertRow( 0, iparent );
+ i = model->index( 0, 0, iparent );
+ }
+
+ ///Update user-data
+ if ( l ) {
+ QIcon icon = l->icon();
+ model->setData( i, ~l->User::name(), Qt::DisplayRole );
+ model->setData( i, icon, Qt::DecorationRole );
+ } else {
+ model->setData( i, QString( "not lockable" ), Qt::DisplayRole );
+ }
+ QVariant lv;
+ lv.setValue( *it );
+
+ model->setData( i, lv, Qt::UserRole );
+ }
+
+ emit updateModel( model );
+}
+
+void CollaborationManager::maybeContextMenu() {
+ if( !m_ignoreClick && m_contextMenuIndex.get() && m_contextMenuIndex->isValid() ) {
+ QModelIndex i = *m_contextMenuIndex;
+ QPoint p = QCursor::pos();
+ contextMenu( p, i );
+ }
+
+ m_ignoreClick = false;
+ m_contextMenuIndex.reset( 0 );
+}
+
+void CollaborationManager::collaboratingDeveloperDoubleClicked( const QModelIndex& index ) {
+ m_ignoreClick = true;
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ m_teamwork->guiSendMessageTo( v.value<UserPointer>() );
+ } else if( v.canConvert<CollaborationTreeActionPointer>() ) {
+ CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
+ if( p ) {
+ p->doubleClicked();
+ }
+ }
+}
+
+
+
+void CollaborationManager::collaboratingDeveloperClicked( const QModelIndex& index ) {
+ if ( !index.isValid() )
+ return ;
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ //if ( v.canConvert<UserPointer>() ) {
+ m_contextMenuIndex.reset( new QPersistentModelIndex( index ) );
+ m_contextMenuTimer->start( 250 );
+ /*} else if( v.canConvert<CollaborationTreeActionPointer>() ) {
+ CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
+ if( p ) {
+ p->clicked();
+ }
+ }*/
+
+}
+
+void CollaborationManager::contextMenu( const QPoint& p, const QModelIndex& index ) {
+
+ if(!index.isValid() )
+ return;
+ QMenu menu;
+
+ QVariant v = index.model() ->data( index, Qt::UserRole );
+ if ( v.canConvert<UserPointer>() ) {
+ m_teamwork->fillUserMenu( &menu, v.value<UserPointer>() );
+ m_teamwork->getPatchesList( v.value<UserPointer>() );
+
+ if( isCollaborating( v.value<UserPointer>() ) )
+ emit fillCollaboratingUserMenu( &menu, v.value<UserPointer>() );
+
+ m_closeCollaborationAction->setData( v );
+ menu.addAction( m_closeCollaborationAction );
+ } else if( v.canConvert<CollaborationTreeActionPointer>() ) {
+ CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
+ if( p ) {
+ p->fillContextMenu( &menu );
+ }
+ }
+
+ if( !menu.isEmpty() )
+ menu.exec( p );
+}
+
+void CollaborationManager::collaboratingDeveloperContextMenu( const QPoint& p ) {
+
+ QModelIndex index = m_teamwork->widgets().connectedDevelopers->indexAt( p );
+
+ contextMenu( p, index );
+}
+
+void CollaborationManager::uiCloseCollaboration() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<UserPointer>() )
+ throw "cannot convert model-index";
+
+ UserPointer::Locked lUser = v.value<UserPointer>();
+ if( !lUser ) throw "failed to lock user";
+
+ removeCollaboratingUser( lUser );
+
+ m_teamwork->startUpdateTimer();
+ if ( !m_teamwork->client() || !lUser->online().session() )
+ throw "no physical collaboration";
+
+ globalMessageSendHelper().send<KDevSystemMessage>( lUser->online().session().unsafe(), KDevSystemMessage::CollaborationClosed, "stopping collaboration" );
+ }
+ catch ( QString & str ) {
+ err() << "in uiCloseCollaboration:" << str;
+ } catch ( const char * str ) {
+ err() << "in uiCloseCollaboration:" << str;
+ }
+}
+
+void CollaborationManager::fillUserMenu( QMenu* menu, const UserPointer& user ) {
+ if ( !isCollaborating( user ) ) {
+ UserPointer::Locked l = user;
+ if ( l && l->online() ) {
+ QVariant v;
+ v.setValue( user );
+ m_requestCollaborationAction->setData( v );
+ menu->addAction( m_requestCollaborationAction );
+ }
+ }
+ //emit fillCollaboratingUserMenu( menu, user );
+}
+
+void CollaborationManager::updateConnection( const TeamworkClientPointer& cl ) {
+ if( cl ) {
+ connect( cl.unsafe(), SIGNAL(signalDispatchMessage(CollaborationMessagePointer)), this, SLOT(processMessage(const CollaborationMessagePointer&)) );
+ } else {
+ m_developersModel->clear();
+ m_developersModel->insertColumn( 0 );
+ }
+}
+
+void CollaborationManager::processMessage( const CollaborationMessagePointer& msg ) {
+ if( msg.cast< FileCollaborationMessage >() ) ///Here a dispatcher is not necessary yet
+ m_fileCollaboration->processMessage( msg.cast< FileCollaborationMessage >() );
+}
+
+void CollaborationManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {}
+
+void CollaborationManager::savePartialProjectSession( QDomElement* /*el*/ ) {}
+
+void setValueMessage( QVariant& v, const MessagePointer& msg );
+
+void ConnectionRequest::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
+ if ( m_state == Waiting ) {
+ QVariant v;
+ setValueMessage( v, MessagePointer( this ) );
+ teamwork->collaborationManager()->m_acceptConnectionAction->setData( v );
+ menu->addAction( teamwork->collaborationManager()->m_acceptConnectionAction );
+ teamwork->collaborationManager()->m_denyConnectionAction->setData( v );
+ menu->addAction( teamwork->collaborationManager()->m_denyConnectionAction );
+ menu->addSeparator();
+ }
+}
+
+KDevTeamwork * CollaborationManager::teamwork() {
+ return m_teamwork;
+}
+
+FileCollaborationManager& CollaborationManager::fileCollaborationManager() {
+ return *m_fileCollaboration;
+}
+
+QStandardItemModel * CollaborationManager::developersModel( )
+{
+ return m_developersModel;
+}
+
+void CollaborationManager::uiAcceptCollaboration() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "error";
+
+ QVariant v = act->data();
+
+ if ( !v.canConvert<MessagePointer>() )
+ throw "cannot convert data";
+
+ MessagePointer::Locked lMessage = v.value<MessagePointer>();
+
+ if ( lMessage && lMessage.cast<ConnectionRequest>() ) {
+ if ( lMessage->info().session() ) {
+ lMessage.cast<ConnectionRequest>() ->setState( ConnectionRequest::Accepted );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( lMessage, KDevSystemMessage::CollaborationAccepted, "collaboration accepted" );
+ if ( lMessage->info().user() )
+ addCollaboratingUser( lMessage->info().user() );
+ m_teamwork->messageManager()->updateMessage( lMessage );
+
+ m_teamwork->startUpdateTimer();
+ }
+ } else {
+ throw "could not lock message-info or client-class";
+ }
+ } catch ( const char * str ) {
+ err() << "in uiAcceptCollaboration:" << str;
+ }
+}
+
+void CollaborationManager::uiDenyCollaboration() {
+ try {
+ if ( !m_teamwork->client() )
+ throw "client not running";
+
+ QAction* act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "error";
+
+ QVariant v = act->data();
+
+ if ( !v.canConvert<MessagePointer>() )
+ throw "cannot convert data";
+
+ MessagePointer::Locked lMessage = v.value<MessagePointer>();
+
+ if ( lMessage && lMessage.cast<ConnectionRequest>() ) {
+ if ( lMessage->info().session() ) {
+ lMessage.cast<ConnectionRequest>() ->setState( ConnectionRequest::Accepted );
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( lMessage, KDevSystemMessage::CollaborationRefused, "collaboration denied" );
+ m_teamwork->messageManager()->updateMessage( lMessage );
+ }
+ } else {
+ throw "could not lock message-info or client-class";
+ }
+ } catch ( const char * str ) {
+ err() << "in uiDenyCollaboration: " << str;
+ }
+}
+
+void CollaborationManager::uiRequestCollaboration() {
+ TeamworkClientPointer::Locked l = m_teamwork->client();
+
+ try {
+ if ( !l )
+ throw "could not client while requesting connection" ;
+ QAction* act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "error in uiDenyCollaboration";
+
+ QVariant v = act->data();
+
+ if ( !v.canConvert<UserPointer>() )
+ throw "error in uiDenyCollaboration, cannot convert data";
+
+ UserPointer::Locked user = v.value<UserPointer>();
+ UserPointer::Locked ident = l->identity();
+ if ( user && ident ) {
+ if ( user->online().session() ) {
+ ConnectionRequest * msg = new ConnectionRequest( l->messageTypes(), ident, user, "please let me connect", m_teamwork );
+ user->online().session().unsafe() ->send( msg );
+ m_teamwork->addMessageToList( msg );
+ } else {
+ throw "no open session to the target-user";
+ }
+ } else {
+ throw "could not lock target-user or local user";
+ }
+ } catch ( const char * str ) {
+ err() << "uiRequestCollaboration:" << str;
+ }
+}
+
+
+#include "collaborationmanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.h (revision 1522570)
@@ -0,0 +1,113 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 header implements a very simple signalling-system that uses the SafeSharedPtr or WeakSafeSharedPtr-facilities to be thread-safe.
+*/
+
+#ifndef SAFESIGNALLER_H
+#define SAFESIGNALLER_H
+
+#include <QObject>
+#include <ext/hash_set>
+#include "lib/network/safesharedptr.h"
+#include "lib/network/weaksafesharedptr.h"
+
+struct SignalProxyBase {
+ virtual void signal() = 0;
+ virtual ~SignalProxyBase() {
+ };
+};
+
+template<class Type>
+struct hashCall {
+ size_t operator() ( const Type& rhs ) const {
+ return (size_t)rhs.unsafe();
+ }
+};
+
+///An object of this type represents a signal that multiple receiver-objects can be bound to. To get a function similar to qt's auto-disconnect, WeakSharedPtr<...> may be used as Target-type. If SafeSharedPtr is used, connected objects will be kept alive until the SafeSignal is destroyed or the object disconnected.
+template<class TargetType, class Signal>
+class SafeSignal {
+ SafeSignal& operator = ( const SafeSignal& rhs ) {
+ return *this;
+ }
+ SafeSignal( const SafeSignal& rhs ) {
+ }
+
+public:
+ SafeSignal() {
+ }
+
+ void connect( const TargetType& targ ) {
+ if( isConnected( targ ) ) return;
+ m_connected.insert( targ );
+ }
+
+ void disconnect( const TargetType& targ ) {
+ typename ConnectionMap::iterator it = m_connected.find( targ );
+ if( it != m_connected.end() )
+ m_connected.erase( it );
+ }
+
+ bool isConnected( const TargetType& targ ) {
+ return m_connected.find( targ ) != m_connected.end();
+ }
+
+ void operator() ( const Signal& signal = Signal() ) {
+ for( typename ConnectionMap::iterator it = m_connected.begin(); it != m_connected.end(); ++it ) {
+ typename TargetType::Locked l = *it;
+ if( l )
+ l->dispatchSignal( signal );
+ }
+ }
+
+private:
+ SignalProxyBase* m_proxy;
+ typedef __gnu_cxx::hash_set< TargetType, hashCall<TargetType> > ConnectionMap;
+ ConnectionMap m_connected;
+};
+
+template<class TargetType, class Signal>
+struct SignalProxy : public SignalProxyBase {
+ SafeSignal<TargetType, Signal> s;
+ Signal sign;
+ SignalProxy( const TargetType& target, const Signal& sig ) : sign( sig ) {
+ s.connect( target );
+ }
+ virtual void signal() {
+ s( sign );
+ }
+};
+
+///This is a very simple safe-signaller object that can be used to easily bind safe signals into QActions etc. The signal-type may be any copyable object. The given object will be copied, and sent once the signal is emitted.
+class QSafeSignaller : public QObject {
+ Q_OBJECT
+ QSafeSignaller& operator = ( const QSafeSignaller& rhs );
+ QSafeSignaller( const QSafeSignaller& rhs );
+public:
+ template<class Target, class Signal>
+ QSafeSignaller( const Target& target, const Signal& signal, QObject* parent ) : QObject( parent ) {
+ m_proxy = new SignalProxy<Target, Signal>( target, signal );
+ }
+ ~QSafeSignaller();
+public slots:
+ void signal();
+private:
+ SignalProxyBase* m_proxy;
+};
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h (revision 1522570)
@@ -0,0 +1,310 @@
+
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#ifndef FILECOLLABORATIONMESSAGES_H
+#define FILECOLLABORATIONMESSAGES_H
+
+#include <QPointer>
+#include <QObject>
+#include <QAction>
+
+//#include <boost/serialization/extended_type_info_typeid.hpp>
+#include "kdevteamwork_messages.h"
+#include "lib/network/easymessage.h"
+#include "utils.h"
+#include "lib/dynamictext/vectortimestamp.h"
+#include "lib/dynamictext/dynamictexthelpers.h"
+#include <list>
+//#include <boost/serialization/extended_type_info.hpp>
+
+namespace KTextEditor {
+class Document;
+}
+
+struct CollabFile {
+ uint id;
+ QString file;
+ CollabFile() : id(0) {
+ }
+ CollabFile( uint i, const QString& f ) : id(i), file(f) {
+ }
+ template <class Archive>
+ void serialize( Archive& arch, const uint ) {
+ arch & id;
+ arch & file;
+ }
+};
+
+typedef std::list<CollabFile> CollabFileList;
+
+typedef quint64 CollabSessionId;
+
+class FileCollaborationMessageData {
+ public:
+ enum Message {
+ NoMessage,
+ Synchronize, ///messageData contains a QString containing the name of the file to synchronize
+ CloseSession
+ };
+
+ explicit FileCollaborationMessageData( CollabSessionId sessionId = 0, Message message = NoMessage, const QVariant& messageData = QVariant() ) : m_sessionId( sessionId ), m_message( message ), m_messageData( messageData ) {}
+
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & m_sessionId;
+ arch & m_message;
+ arch & m_messageData;
+ }
+
+ ///Returns zero if the message is not associated to a session
+ CollabSessionId sessionId() {
+ return m_sessionId;
+ };
+
+ const QVariant& messageData() const {
+ return m_messageData;
+ }
+
+ void setMessageData( const QVariant& v ) {
+ m_messageData = v;
+ }
+
+ Message message() const {
+ return m_message;
+ }
+
+ QString messageAsString() const {
+ switch ( m_message ) {
+ case NoMessage:
+ return "NoMessage";
+ case Synchronize:
+ return "Synchronize";
+ case CloseSession:
+ return "CloseSession";
+ default:
+ return "unknown";
+ };
+ }
+
+ private:
+ CollabSessionId m_sessionId;
+ Message m_message;
+ QVariant m_messageData;
+};
+
+class FileCollaborationSession;
+class FileCollaboration;
+
+EASY_DECLARE_MESSAGE( FileCollaborationMessage, CollaborationMessage, 6, FileCollaborationMessageData, 3 );
+
+/**A file-collaboration-request is sent to request collaboration. The request stays alive
+ * in the session and keeps forwarding all replies to the FileCollaboration-object, until that
+ * object is deleted. When the request is accepted, a FileCollaborationRequest is sent back
+ * and stays alive in the other session, forwarding messages directly to the peer
+ * FileCollaboration-object. That way the connection is established without the messages having
+ * to go a very long way.
+*/
+
+
+
+class FileCollaborationRequestData : public QObject, public AbstractGUIMessage {
+ Q_OBJECT
+ public:
+ struct AcceptSignal {
+ };
+ struct DenySignal {
+ };
+ enum State {
+ Unknown,
+ Accepted,
+ Denied,
+ Failed
+ };
+
+ explicit FileCollaborationRequestData( FileCollaboration* collab = 0, uint index = 0, uint senderIndex = 0 );
+
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ arch & m_name;
+ arch & m_files;
+ arch & m_index;
+ arch & m_senderIndex;
+ arch & m_isAutomatic;
+ }
+
+ void setName( const QString& theValue );
+
+ QString name() const;
+
+ void setFiles( const CollabFileList& theValue );
+
+ CollabFileList files() const;
+
+ ///If the request is automatic that means that it was sent automatically by a session that discovered that a user came back online
+ bool isAutomatic() const;
+
+ void setAutomatic( bool automatic );
+
+ State state() const;
+
+ ///the index assigned to the side that is requested to collaborate
+ uint index() const;
+
+ void dispatchSignal( const AcceptSignal& sig );
+ void dispatchSignal( const DenySignal& sig );
+
+ ///The index of the sender of this message
+ uint senderIndex() const;
+ signals:
+ void processReply( const MessagePointer& msg );
+ void stateChanged( const MessagePointer& msg );
+ void connectionResult( bool );
+
+ public slots:
+ void acceptCollaboration();
+ void denyCollaboration();
+ private:
+ void updateState();
+ ///Data:
+ CollabFileList m_files;
+ QString m_name;
+ State m_state;
+ uint m_index;
+ uint m_senderIndex;
+ bool m_isAutomatic;
+
+ ///Internal:
+ QPointer<FileCollaborationSession> m_session;
+ QPointer<FileCollaboration> m_collab;
+ QPointer<KDevTeamwork> m_teamwork;
+ friend class FileCollaborationRequest;
+
+ QAction* m_acceptAction;
+ QAction* m_denyAction;
+};
+
+///A FileCollaborationRequest is an invitation to a local file-collaboration-session.
+EASY_DECLARE_MESSAGE_BEGIN( FileCollaborationRequest, FileCollaborationMessage, 2, FileCollaborationRequestData, 3 )
+
+virtual bool needReply() const;
+
+virtual void result( bool success ) {
+ if ( !success ) {
+ m_state = Failed;
+ updateState();
+ }
+}
+
+virtual QString messageText() const;
+
+virtual QIcon messageIcon() const;
+
+virtual ReplyResult gotReply( const MessagePointer& p );
+
+virtual void fillContextMenu( QMenu* /*menu*/, KDevTeamwork* /*teamwork*/ );
+
+END();
+
+typedef SafeSharedPtr<FileCollaborationMessage> FileCollaborationMessagePointer;
+typedef SafeSharedPtr<FileCollaborationRequest> FileCollaborationRequestPointer;
+
+
+class DocumentWrapperMessageData {
+ public:
+ DocumentWrapperMessageData( uint wrapperId = 0 ) : m_wrapperId( wrapperId ) {}
+
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ arch & m_wrapperId;
+ }
+ uint wrapperId() {
+ return m_wrapperId;
+ }
+ private:
+ uint m_wrapperId;
+};
+
+EASY_DECLARE_MESSAGE( DocumentWrapperMessage, FileCollaborationMessage, 4, DocumentWrapperMessageData, 1 );
+
+class FileEditMessageData {
+ public:
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ arch & m_replacement & m_state;
+ }
+
+ explicit FileEditMessageData( const VectorTimestamp& state = VectorTimestamp(), const SimpleReplacement& rep = SimpleReplacement() ) : m_replacement( rep ), m_state(state) {
+ }
+
+ const SimpleReplacement& replacement () const {
+ return m_replacement;
+ }
+
+ const VectorTimestamp& timeStamp() const {
+ return m_state;
+ }
+
+ private:
+ SimpleReplacement m_replacement;
+ VectorTimestamp m_state;
+};
+
+EASY_DECLARE_MESSAGE( FileEditMessage, DocumentWrapperMessage, 1, FileEditMessageData, 2 );
+
+struct FileEditRejectMessageData {
+ public:
+ FileEditRejectMessageData( const VectorTimestamp& vec = VectorTimestamp() ) : m_state( vec ) {
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ arch & m_state;
+ }
+
+ const VectorTimestamp& timeStamp() const {
+ return m_state;
+ }
+ private:
+ VectorTimestamp m_state;
+};
+
+EASY_DECLARE_MESSAGE( FileEditRejectMessage, DocumentWrapperMessage, 2, FileEditRejectMessageData, 1 );
+
+struct FileListMessageData {
+ FileListMessageData( const CollabFileList& files = CollabFileList() ) : m_files( files ) {
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ arch & m_files;
+ }
+
+ CollabFileList m_files;
+};
+
+
+EASY_DECLARE_MESSAGE( FileListMessage, FileCollaborationMessage, 5, FileListMessageData, 1 );
+
+BOOST_CLASS_IMPLEMENTATION( FileEditRejectMessageData, boost::serialization::object_serializable )
+BOOST_CLASS_IMPLEMENTATION( SimpleReplacement, boost::serialization::object_serializable )
+BOOST_CLASS_IMPLEMENTATION( FileCollaborationMessageData, boost::serialization::object_serializable )
+BOOST_CLASS_IMPLEMENTATION( FileCollaborationRequestData, boost::serialization::object_serializable )
+BOOST_CLASS_IMPLEMENTATION( FileEditMessageData, boost::serialization::object_serializable )
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h (revision 1522570)
@@ -0,0 +1,92 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include <QStringList>
+#include <QList>
+
+#ifndef FILECOLLABORATIONMANAGER_H
+#define FILECOLLABORATIONMANAGER_H
+
+#include "lib/network/messagetypeset.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/weaksafesharedptr.h"
+#include "lib/network/crossmap.h"
+
+#include "filecollaborationmessages.h"
+#include "safelogger.h"
+
+#include "filecollaboration.h"
+#include "filecollaborationsession.h"
+
+
+///There's not many messages that need to be dispatched right now
+BIND_LIST_2( FileCollaborationMessages, FileCollaborationMessage, FileCollaborationRequest )
+CROSSMAP_DEFINE_CONTAINER( QList )
+
+class FileCollaborationManager : public QObject, public SafeLogger {
+ Q_OBJECT
+ public:
+ ///FileCollaborationSession itself is used as key too, so sessions can always be found even if all Files und Users change.
+ BIND_LIST_5( SessionKeys, FileCollaborationSessionPointer, CollabSessionId, QList<QString>, QList<KDevTeamworkUserPointer>, SessionName )
+
+ typedef Utils::CrossMap< FileCollaborationSessionPointer, SessionKeys > SessionSet;
+
+ FileCollaborationManager( CollaborationManager* manager );
+
+ const SessionSet& sessions();
+
+ ///May return zero on failure
+ FileCollaborationSession* startSession( const QString& name, CollabFileList files , uint primaryIndex = 0, CollabSessionId id = 0 );
+
+ KDevTeamwork* teamwork();
+
+ bool acceptCollaboration( const FileCollaborationRequestPointer& msg );
+
+ void denyCollaboration( const FileCollaborationRequestPointer& msg );
+
+ void closeSession( const FileCollaborationSessionPointer& session );
+
+ public slots:
+ void updateCollaborationModel( QStandardItemModel* model );
+ void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
+ void slotStartCollaborationSession();
+ void slotSessionStateChanged( const FileCollaborationSessionPointer& );
+
+ signals:
+ void fillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
+
+ private:
+
+ void processMessage( FileCollaborationMessagePointer msg );
+
+ int receiveMessage( MessageInterface* msg );
+
+ int receiveMessage( FileCollaborationRequest* msg );
+
+ int receiveMessage( FileCollaborationMessage* msg );
+
+ CollaborationManager* m_manager;
+ SessionSet m_sessions;
+ QAction* m_startCollaborationSessionAction;
+
+ MessageDispatcher< FileCollaborationManager, FileCollaborationMessages > m_dispatcher;
+ friend class MessageDispatcher< FileCollaborationManager, FileCollaborationMessages >;
+ friend class CollaborationManager;
+
+ typedef std::multimap< CollabSessionId, FileCollaborationRequestPointer> RequestMap;
+ RequestMap m_requests; ///Here, requests are stored so all requests for the same session can be grouped together once that session is accepted
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp (revision 1522570)
@@ -0,0 +1,237 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "kdevteamwork_messages.h"
+#include "kdevteamwork.h"
+#include <QDateTime>
+#include "kdevteamwork_messageshower.h"
+#include "kdevteamwork_helpers.h"
+#include "indocumentreference.h"
+#include "lib/network/teamworkserver.h"
+#include "lib/network/teamworkclient.h"
+#include <boost/serialization/list.hpp>
+#include <boost/serialization/string.hpp>
+
+REGISTER_MESSAGE( KDevSystemMessage )
+REGISTER_MESSAGE( KDevTeamworkTextMessage )
+REGISTER_MESSAGE( ConnectionRequest )
+EASY_IMPLEMENT_MESSAGE( CollaborationMessage )
+
+
+KDevSystemMessage::KDevSystemMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : SystemMessage( arch, info ) {}
+KDevSystemMessage::KDevSystemMessage( const Teamwork::MessageConstructionInfo& info, Message msg , const string& str ) : SystemMessage( info(this), ( Teamwork::SystemMessage::Message ) msg, str ) {}
+
+KDevSystemMessage::Message KDevSystemMessage::message() {
+ return ( Message ) SystemMessage::message();
+}
+
+QString KDevSystemMessage::messageAsString() {
+ switch ( message() ) {
+ case CollaborationAccepted:
+ return "collaboration accepted";
+ case CollaborationRefused:
+ return "collaboration refused";
+ case CollaborationClosed:
+ return "collaboration stopped";
+ case ActionFailed:
+ return "action failed";
+ case ActionSuccessful:
+ return "action successful";
+ case ActionDenied:
+ return "action denied";
+ }
+ return "unknown kdev-system-message";
+}
+
+QString KDevSystemMessage::text() {
+ return SystemMessage::text().c_str();
+}
+
+typedef SafeSharedPtr<KDevSystemMessage> KDevSystemMessagePointer;
+
+KDevTeamworkTextMessage::KDevTeamworkTextMessage( const Teamwork::MessageConstructionInfo& info, const QString& text ) : TextMessage( info(this), text.toUtf8().data() ), creationTime_( QDateTime::currentDateTime() ), m_answered( false ) {}
+
+KDevTeamworkTextMessage::KDevTeamworkTextMessage( InArchive& from, const Teamwork::MessageInfo& info ) : TextMessage( from, info ), m_answered( false ) {
+ std::string date;
+ from & date;
+ creationTime_ = QDateTime::fromString( ~date, Qt::ISODate );
+}
+
+void KDevTeamworkTextMessage::setAnswered( bool a ) {
+ m_answered = a;
+}
+
+bool KDevTeamworkTextMessage::answered() const {
+ return m_answered;
+}
+
+QString KDevTeamworkTextMessage::messageText() const {
+ return ~Teamwork::TextMessage::text();
+}
+
+class DocumentMessageInternal;
+class InDocumentConversation;
+
+bool KDevTeamworkTextMessage::needReply() const {
+ return true;
+}
+
+ConnectionRequest::ConnectionRequest( InArchive& arch, const Teamwork::MessageInfo& info ) : KDevTeamworkTextMessage( arch, info ), m_state( Waiting ) {
+ arch & user_;
+ //user_.load( arch, 0 );
+}
+
+void ConnectionRequest::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ //user_.save( arch, version );
+ arch & user_;
+}
+
+const Teamwork::User& ConnectionRequest::user() {
+ return user_;
+}
+
+bool ConnectionRequest::needReply() const {
+ return true;
+}
+
+void ConnectionRequest::setState( State s ) {
+ m_state = s;
+}
+
+ConnectionRequest::State ConnectionRequest::state() {
+ return m_state;
+}
+
+bool KDevTeamworkTextMessage::canShowInWidget() {
+ return true;
+}
+
+
+void KDevTeamworkTextMessage::showInWidget( QWidget* widget, KDevTeamwork* tw ) {
+ new KDevTeamworkMessageShower( this, widget, tw );
+}
+
+QDateTime KDevTeamworkTextMessage::creationTime() {
+ return creationTime_;
+}
+
+void KDevTeamworkTextMessage::serialize( OutArchive& arch ) {
+ TextMessage::serialize( arch );
+ std::string date = ~creationTime_.toString( Qt::ISODate );
+ arch & date;
+}
+
+QIcon KDevTeamworkTextMessage::messageIcon() const {
+ IconCache & cache( *IconCache::instance() );
+
+ if ( info().isIncoming() )
+ return cache( "text_message_in" );
+ else
+ return cache( "text_message_out" );
+}
+
+ConnectionRequest::ConnectionRequest( const Teamwork::MessageConstructionInfo& info, const Teamwork::UserPointer& self, const Teamwork::UserPointer& target, const QString& text, KDevTeamwork* teamwork ) : KDevTeamworkTextMessage( info(this), text ), m_state( Waiting ), m_emitter( new SafeTeamworkEmitter( teamwork ) ) {
+ Teamwork::UserPointer::Locked l = self;
+ Teamwork::UserPointer::Locked tl = target;
+ if ( l ) {
+ user_ = *l;
+ user_.stripForTarget( *tl );
+ } else {
+ user_ = Teamwork::User( "unlockable" );
+ }
+}
+
+MessageInterface::ReplyResult ConnectionRequest::gotReply( const MessagePointer& p ) {
+ KDevSystemMessagePointer::Locked lmessage = ( ( MessagePointer ) p ).cast<KDevSystemMessage>();
+
+ if ( lmessage ) {
+ switch ( lmessage->message() ) {
+ case KDevSystemMessage::CollaborationRefused:
+ m_state = Denied;
+ break;
+ case KDevSystemMessage::CollaborationAccepted:
+ m_state = Accepted;
+ break;
+ case KDevSystemMessage::ActionFailed:
+ m_state = Unknown;
+ break;
+ default:
+ m_state = Unknown;
+ break;
+ }
+ } else {
+ return ReplyResult( false, true ); ///Messages other than KDevSystemMessage are not accepted
+ }
+
+ if ( m_emitter.data() )
+ m_emitter->updateMessageInfo( this );
+ return ReplyResult();
+}
+
+QIcon ConnectionRequest::messageIcon() const {
+ IconCache & cache( *IconCache::instance() );
+
+ if ( !info().isIncoming() ) {
+ if ( m_state == Denied ) {
+ return cache( "collaborationrequest_out_denied" );
+ } else if ( m_state == Accepted ) {
+ return cache( "collaborationrequest_out_accepted" );
+ } else if ( m_state == Unknown ) {
+ return cache( "unknown" );
+ } else {
+ return cache( "collaborationrequest_out" );
+ }
+ } else {
+ if ( m_state == Denied ) {
+ return cache( "collaborationrequest_in_denied" );
+ } else if ( m_state == Accepted ) {
+ return cache( "collaborationrequest_in_accepted" );
+ } else if ( m_state == Unknown ) {
+ return cache( "unknown" );
+ } else {
+ return cache( "collaborationrequest_in" );
+ }
+ }
+
+ if ( info().isIncoming() )
+ return cache( "collaborationrequest_in" );
+ else
+ return cache( "collaborationrequest_out" );
+}
+
+QIcon AbstractGUIMessage::messageTypeIcon() const {
+ IconCache & cache( *IconCache::instance() );
+ return cache( "message" );
+}
+
+QIcon AbstractGUIMessage::messageIcon() const {
+ IconCache & cache( *IconCache::instance() );
+ return cache( "message" );
+}
+
+FailureMessage::FailureMessage( const QString& text, const MessagePointer& msg ) : KDevTeamworkTextMessage( globalMessageTypeSet(), text ) {
+ info().setReplyMessage( msg );
+ MessagePointer::Locked l = msg;
+ if( l ) {
+ info().setReply( l->info().uniqueId() );
+ info().setUser( l->info().user() );
+ }
+}
+
+QIcon FailureMessage::messageIcon() const {
+ return IconCache::getIconStatic( "failed" );
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h (revision 1522570)
@@ -0,0 +1,96 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_HELPERS
+#define KDEVTEAMWORK_HELPERS
+
+#include"teamworkfwd.h"
+#include <QString>
+#include <QIcon>
+#include <QMap>
+#include <QPair>
+#include <QObject>
+#include <kicontheme.h>
+#include "lib/network/logger.h"
+
+///This file contains a few classes that I currently don't know where else to put
+
+using namespace Teamwork;
+
+///Since deleting the client by a reference-counter in some meta-object leads to crashes, this is used to keep the client alive longer and delete it as last.
+class LaterDeleter : public QObject {
+ Q_OBJECT
+ public:
+ LaterDeleter( const KDevTeamworkClientPointer& c );
+ ~LaterDeleter();
+ KDevTeamworkClientPointer m_c;
+};
+
+class SafeTeamworkEmitter : public QObject, public Shared {
+ Q_OBJECT
+ public:
+ SafeTeamworkEmitter( KDevTeamwork* tw );
+
+ void updateMessageInfo( const MessagePointer& msg );
+ signals:
+ void signalUpdateMessageInfo( MessagePointer );
+};
+
+typedef SharedPtr<SafeTeamworkEmitter> SafeTeamworkEmitterPointer;
+
+
+class IconCache {
+ typedef QMap<QPair<QString, KIconLoader::Group>, QIcon> IconMap;
+ QMap<QString, QString> maps_;
+ IconMap m_icons;
+ static IconCache* m_instance;
+ public:
+ IconCache();
+
+ QIcon operator () ( const QString& name, KIconLoader::Group grp = KIconLoader::Small );
+
+ static QIcon getIconStatic( QString name, KIconLoader::Group grp = KIconLoader::Small );
+
+ QIcon getIcon( QString name, KIconLoader::Group grp = KIconLoader::Small );
+
+ static IconCache* instance();
+};
+
+
+class KDevTeamworkLogger : public QObject, public Teamwork::Logger {
+ Q_OBJECT
+ KDevTeamwork* m_teamwork;
+ public:
+ ///This can be overridden for custom logging
+ KDevTeamworkLogger( KDevTeamwork* tw );
+
+ virtual void log( const std::string& str , Level lv );
+
+ void invalidate() {
+ m_teamwork = 0;
+ }
+
+ ///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
+ virtual void safeErrorLog( const std::string& str, Level lv );
+};
+
+/** This is a helper-class for easy logging
+ * Easiest way of using it: use it as a base-class in a class that should do logging,
+ * initialize it with the name of the class and the correct logger-object, and than start
+ * logging by streaming to out(..) or err(). ( Example: err() << "could not open file"; )
+ *
+ * */
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.cpp (revision 1522570)
@@ -0,0 +1,455 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "patchmessage.h"
+#include "lib/network/serialization.h"
+#include <boost/serialization/list.hpp>
+#include <boost/serialization/string.hpp>
+#include <boost/serialization/vector.hpp>
+#include <memory>
+
+#include <k3process.h>
+#include <kurl.h>
+#include <kmimetype.h>
+#include <memory.h>
+#include <kio/netaccess.h>
+#include <kio/job.h>
+#include <kio/jobclasses.h>
+#include "teamworkfoldermanager.h"
+
+#include "kdevteamwork.h"
+
+#include "kdevteamwork_helpers.h"
+
+PatchData::PatchData( const LocalPatchSourcePointer& p, LoggerPointer logg ) : m_patch( p ), logger( logg ), deserialized( false ), finished( false ), isBinary_( false ) {
+ projectDir = TeamworkFolderManager::workspaceDirectory();
+}
+
+LocalPatchSourcePointer PatchData::patch() {
+ return m_patch;
+}
+
+PatchesListMessage::PatchesListMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) {
+ serial( arch );
+}
+
+void PatchesListMessage::serialize( OutArchive& arch ) {
+ Precursor::serialize( arch );
+ serial( arch );
+}
+
+uint LocalPatchSource::patchDepth() const {
+ QString cmd = ~applyCommand;
+ int i = cmd.indexOf( "-p" );
+ if( i == -1 ) return 0;
+ if( i+1 >= cmd.length() ) return 0;
+ QString f = cmd.mid( i+2 ).trimmed();
+ if( f.isEmpty() ) return 0;
+ f.truncate( 1 );
+ bool b = false;
+ uint ret = f.toUInt( &b );
+ if( !b ) return 0;
+ else
+ return ret;
+}
+
+string LocalPatchSource::patchTool( bool reverse ) const {
+ QString cmd;
+ if( reverse )
+ cmd = (~unApplyCommand).trimmed();
+
+ if( cmd.isEmpty() )
+ cmd = (~applyCommand).trimmed();
+
+ if( cmd[0] == '-' ) return "patch";
+ int firstWhite = cmd.indexOf( " " );
+ QString ret;
+ if( firstWhite == -1 )
+ ret = cmd;
+ else
+ ret = cmd.mid( 0, firstWhite );
+
+ ret = ret.trimmed();
+ if( ret.isEmpty() )
+ return "patch";
+ else
+ return ~ret;
+}
+
+string LocalPatchSource::patchParams( bool reverse ) const {
+
+ QString cmd;
+ bool normalCommand = false;
+ if( reverse )
+ cmd = (~unApplyCommand).trimmed();
+ if( cmd.isEmpty() ) {
+ cmd = (~applyCommand).trimmed();
+ normalCommand = true;
+ }
+ if( cmd.isEmpty() )
+ return string("-p0 --backup") + (reverse ? " --reverse" : "");
+ else
+ if( reverse && normalCommand )
+ cmd += " --reverse";
+
+ if( cmd.startsWith( ~patchTool(reverse) ) )
+ return ~cmd.mid( patchTool(reverse).length() ).trimmed();
+ else
+ return ~cmd.trimmed();
+}
+
+/*
+void LocalPatchSource::setMimeType( KMimeType::Ptr mimeType ) {
+ QByteArray array;
+ {
+ QDataStream str( &array, QIODevice::WriteOnly );
+ mimeType->save( str );
+ }
+ mimetype.resize( array.count() );
+ memcpy( &( mimetype[ 0 ] ), array.data(), array.count() );
+}
+
+KMimeType::Ptr LocalPatchSource::getMimeType() {
+ QByteArray array( &( mimetype[ 0 ] ), mimetype.size() );
+ QDataStream str( &array, QIODevice::ReadOnly );
+ return KMimeType::Ptr( new KMimeType( str, 0 ) );
+}*/
+
+class AbstractPatchArchiver {
+ virtual void put( QByteArray& data );
+ virtual void put( int i );
+ virtual ~AbstractPatchArchiver() {
+ };
+ };
+ /*
+template<class Archive>
+class PatchArchiver {
+ Archive& arch;
+ PatchArchiver( Archive& a ) : arch(a) {
+ }
+
+ virtual void put( QByteArray& data ) {
+ arch & data;
+ }
+
+ virtual void put( int i ) {
+ arch & i;
+ }
+ };
+ */
+void PatchData::transferData( KIO::Job* /*job*/, const QByteArray& data ) {
+ std::vector<char> vec;
+ vec.resize( data.size() ); ///a serialization-function for QByteArray should be written instead of moving the data through std::vector
+ memcpy( &(vec[0]), data.data(), data.size() );
+ EntryType v = Vector;
+ *currentArchive << v;
+ *currentArchive & vec;
+}
+
+void PatchData::transferFinished() {
+ finished = true;
+}
+
+void PatchData::transferCanceled() {
+ errored = true;
+}
+
+//template<class Arch>
+void PatchData::saveInternal( OutArchive& arch, const uint /*version*/ ) {
+ auto_ptr<PatchDataReceiver> rec( new PatchDataReceiver( this ) );
+
+ if ( !m_patch || deserialized )
+ throw CannotReserialize(); ///This type of Message can only be serialized after being constructed with a local patch-source
+ try {
+ arch & m_patch;
+ currentArchive = &arch;
+ errored = false;
+ finished = false;
+ if ( !m_patch )
+ throw "invalid patch-source";
+ LocalPatchSourcePointer::Locked lpatch = m_patch;
+ if ( !lpatch )
+ throw "patch-source could not be locked";
+
+ if ( !lpatch->filename.empty() ) {
+ ///Load a file
+ isBinary_ = true;
+ EntryType v = BinaryHeader;
+ arch << v;
+ KUrl url = TeamworkFolderManager::teamworkAbsolute( ~lpatch->filename );
+ log( Logger::Debug ) << "opening file for sending:" << ~url.prettyUrl();
+
+ //(QWidget*)KDevApi::self()->mainWindow()->main()
+ if ( !KIO::NetAccess::exists( url, KIO::NetAccess::SourceSide, 0 ) )
+ throw ( "the file \"" + url.prettyUrl() + "\" seems not to exist, or is not accessible" );
+
+ auto_ptr<KIO::TransferJob> transfer( KIO::get
+ ( url, KIO::NoReload, KIO::HideProgressInfo ) );
+ if ( !transfer.get() )
+ throw ( "could not create transfer-job for reading " + url.prettyUrl() );
+ //transfer->setWindow( (QWidget*)KDevApi::self()->mainWindow()->main() );
+ QObject::connect( &( *transfer ), SIGNAL( data( KIO::Job *, const QByteArray & ) ), &( *rec ), SLOT( transferData( KIO::Job*, const QByteArray& ) ), Qt::DirectConnection );
+ QObject::connect( &( *transfer ), SIGNAL( result( KJob * ) ), &( *rec ), SLOT( transferFinished( KJob* ) ), Qt::DirectConnection );
+ if ( !transfer->exec() )
+ errored = true;
+
+ QString errorText;
+ int error = transfer->error();
+ if ( error )
+ errorText = transfer->errorString();
+
+ transfer->kill();
+
+ if ( error )
+ throw ( "failed reading the file \"" + url.prettyUrl() + "\" reason: \"" + errorText + "\"" );
+
+ EntryType t = End;
+ arch << t;
+
+ } else if ( !lpatch->command.empty() ) {
+ ///Execute a command and send it's output
+ isBinary_ = false;
+ EntryType v = TextHeader;
+ arch << v;
+ QStringList args = splitArgs( ~lpatch->command );
+ {
+ LoggerPrinter l = log() << "calling process: \"" << lpatch->command << "\" params: ";
+ for ( QStringList::iterator it = args.begin(); it != args.end(); ++it )
+ l << "\"" << ~( *it ) << "\"";
+ l << "in folder" << ~projectDir.toLocalFile();
+ }
+
+ auto_ptr<K3Process> proc( new K3Process() );
+ QObject::connect( &( *proc ), SIGNAL( receivedStdout( K3Process*, char*, int ) ), &( *rec ), SLOT( receivedStdout( K3Process*, char*, int ) ), Qt::DirectConnection );
+
+ proc->setPriority( K3Process::PrioLowest );
+ proc->setWorkingDirectory( projectDir.toLocalFile() );
+ *proc << args;
+ if ( !proc->start( K3Process::Block, K3Process::Stdout ) )
+ throw "the process could not be started";
+
+ if ( !proc->normalExit() )
+ throw "process did not exit normally";
+ if ( proc->exitStatus() != 0 )
+ throw QString( "process returned with exit-status " + QString::number( proc->exitStatus() ) );
+
+ log() << lpatch->command << ": successful";
+
+ EntryType t = End;
+ arch << t;
+ } else {
+ throw "the patch-data cannot be sent: missing command or url";
+ }
+ } catch ( const char * str ) {
+ currentArchive = 0;
+ throw NonFatalSerializationError( ( string( "PatchData::serialize: " ) + str ).c_str() );
+ } catch( QString str ) {
+ currentArchive = 0;
+ throw NonFatalSerializationError( ( string( "PatchData::serialize: " ) + str.toUtf8().data() ).c_str() );
+ }
+ currentArchive = 0;
+}
+
+//template<class Arch>
+void PatchData::load( InArchive& arch, const uint /*version*/ ) {
+ deserialized = true;
+ //cout << "got patch: ";
+
+ arch & m_patch;
+
+ EntryType t;
+ arch >> t;
+ if ( t == BinaryHeader ) {
+ isBinary_ = true;
+ while ( 1 ) {
+ arch >> t;
+ if ( t == Vector ) {
+ vector<char> vec;
+ arch & vec;
+ //cout << str;
+ m_data.append( QByteArray( &( vec[ 0 ] ), vec.size() ) );
+ } else {
+ if ( t != End )
+ throw NonFatalSerializationError( "stream-error in PatchData(Text)" );
+ else
+ break;
+ }
+ }
+ } else {
+ isBinary_ = false;
+ while ( 1 ) {
+ arch >> t;
+ if ( t == Text ) {
+ string str;
+ arch & str;
+ //cout << str;
+ m_data.append( str.c_str() );
+ } else {
+ if ( t != End )
+ throw NonFatalSerializationError( "stream-error in PatchData(Text)" );
+ else
+ break;
+ }
+ }
+ }
+}
+
+/*
+template void PatchData::load( boost::archive::polymorphic_iarchive& arch, const uint );
+
+template void PatchData::saveInternal( boost::archive::polymorphic_oarchive& arch, const uint );
+
+template void PatchData::load( boost::archive::text_iarchive& arch, const uint );
+
+template void PatchData::saveInternal( boost::archive::text_oarchive& arch, const uint );
+
+template void PatchData::load( boost::archive::binary_iarchive& arch, const uint );
+
+template void PatchData::saveInternal( boost::archive::binary_oarchive& arch, const uint );
+*/
+
+void PatchData::receivedStdout( K3Process */*proc*/, char *buffer, int /*buflen*/ ) {
+ if ( !currentArchive || errored ) {
+ if ( !errored ) {
+ log() << "received unexpected stdout-data";
+ errored = true;
+ }
+ return ;
+ }
+ EntryType t = Text;
+ *currentArchive << t;
+ string str( buffer );
+ *currentArchive << str;
+}
+
+bool PatchData::isBinary() {
+ return isBinary_;
+}
+
+const QByteArray& PatchData::data() {
+ return m_data;
+}
+
+QStringList splitArgs( const QString& str ) {
+ QStringList ret;
+ QString current = str;
+ int pos = 0;
+ while ( ( pos = current.indexOf( ' ', pos ) ) != -1 ) {
+ if ( current[ 0 ] == '"' ) {
+ int end = current.indexOf( '"' );
+ if ( end > pos )
+ pos = end;
+ }
+ QString s = current.left( pos );
+ if ( s.length() > 0 )
+ ret << s;
+ current = current.mid( pos + 1 );
+ pos = 0;
+ }
+ if ( current.length() )
+ ret << current;
+ return ret;
+}
+
+PatchRequestData::PatchRequestData( const LocalPatchSourcePointer& id, KDevTeamwork* tw, RequestType req ) : request_( id ), requestType_( req ), stat( Waiting ), emitter( new SafeTeamworkEmitter( tw ) ) {
+ LocalPatchSourcePointer::Locked l = id;
+ if( l ) {
+ ident_ = l->identity();
+ }
+}
+
+PatchDataReceiver::PatchDataReceiver( PatchData* d ) : data( d ) {}
+void PatchDataReceiver::receivedStdout( K3Process *proc, char *buffer, int buflen ) {
+ data->receivedStdout( proc, buffer, buflen );
+}
+
+void PatchDataReceiver::transferData( KIO::Job* job, const QByteArray& array ) {
+ data->transferData( job, array );
+}
+
+void PatchDataReceiver::transferFinished( KJob */*job*/ ) {
+ data->transferFinished();
+}
+
+QString PatchRequestData::messageText() const {
+ return "patch-request: " + ~patchDesc();
+}
+
+
+QIcon PatchRequestData::messageIcon() const {
+ IconCache & cache( *IconCache::instance() );
+
+ if ( !selfMessage() ->info().isIncoming() ) {
+ return cache( "generalrequest_out" );
+ if ( stat == Denied ) {
+ return cache( "generalrequest_out_denied" );
+ } else if ( stat == Accepted ) {
+ return cache( "generalrequest_out_accepted" );
+ } else if ( stat == Unknown ) {
+ return cache( "unknown" );
+ } else {
+ return cache( "generalrequest_out" );
+ }
+ } else {
+ if ( stat == Denied ) {
+ return cache( "generalrequest_in_denied" );
+ } else if ( stat == Accepted ) {
+ return cache( "generalrequest_in_accepted" );
+ } else if ( stat == Unknown ) {
+ return cache( "unknown" );
+ } else {
+ return cache( "generalrequest_in" );
+ }
+ }
+}
+
+PatchRequestMessage* PatchRequestData::selfMessage() {
+ return dynamic_cast<PatchRequestMessage*>( this );
+}
+
+const PatchRequestMessage* PatchRequestData::selfMessage() const {
+ return dynamic_cast<const PatchRequestMessage*>( this );
+}
+
+MessageInterface::ReplyResult PatchRequestMessage::gotReply( const MessagePointer& p ) {
+ KDevSystemMessagePointer::Locked lmessage = ( ( MessagePointer ) p ).cast<KDevSystemMessage>();
+
+ if ( lmessage ) {
+ switch ( lmessage->message() ) {
+ case KDevSystemMessage::ActionFailed:
+ stat = Failed;
+ break;
+ case KDevSystemMessage::ActionSuccessful:
+ stat = Accepted;
+ break;
+ case KDevSystemMessage::ActionDenied:
+ stat = Denied;
+ break;
+ default:
+ stat = Unknown;
+ break;
+ }
+ }
+
+ if ( emitter.data() )
+ emitter->updateMessageInfo( this );
+
+ return ReplyResult();
+}
+
+PatchRequestData::~PatchRequestData() {
+}
+
+#include "patchmessage.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.cpp (revision 1522570)
@@ -0,0 +1,173 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "messagemanager.h"
+#include "kdevteamwork.h"
+#include "serializationutils.h"
+#include "conversationmanager.h"
+#include "guimessagehistory.h"
+#include "messagehistorymanager.h"
+#include "lib/network/messagetypeset.h"
+#include <kdialog.h>
+#include <QMenu>
+#include "kdevteamwork_messageshower.h"
+
+#include <QList>
+#include <QAction>
+
+Q_DECLARE_METATYPE( MessagePointer )
+
+
+
+MessageManager::MessageManager( KDevTeamwork* tw ) : dispatcher_( *this ), m_teamwork( tw ), m_conversationManager( this ), m_historyManager( m_teamwork->logger() ) {
+ m_showMessageAction = new QAction( i18n("Show"), this );
+ connect( m_showMessageAction, SIGNAL( triggered() ), this, SLOT( slotShowMessage() ) );
+ connect( m_teamwork, SIGNAL( init() ), this, SLOT( init() ) );
+ m_showMessageAction->setToolTip( i18n("Show the message.") );
+}
+
+void MessageManager::init() {
+}
+
+MessageManager::~MessageManager() {}
+
+void MessageManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {
+ /*try {
+ xmlDeserializeFromElementItem( el, "ConversationManager", m_conversationManager );
+ } catch ( const QString & str ) {
+ log( "failed to restore the conversation-manager: " + str, Error );
+ }*/
+}
+
+void MessageManager::savePartialProjectSession( QDomElement* /*el*/ ) {
+ /*try {
+ xmlSerializeToElementItem( el, "ConversationManager", m_conversationManager );
+ } catch ( const QString & str ) {
+ log( "failed to store the conversation-manager: " + str, Error );
+ }*/
+}
+
+void MessageManager::showMessage( const MessagePointer& msg ) {
+ MessagePointer::Locked l = msg;
+ if ( !l )
+ throw "cannot lock message";
+ if ( !l.freeCast<AbstractGUIMessage>() )
+ throw "message is no GUI-message";
+
+ KDialog* d = new KDialog( m_teamwork->widget() );
+ d->setAttribute( Qt::WA_DeleteOnClose, true );
+
+ l.freeCast<AbstractGUIMessage>() ->showInWidget( d->mainWidget(), m_teamwork );
+
+ d->show();
+}
+
+void MessageManager::slotShowMessage() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<MessagePointer>() )
+ throw "cannot convert";
+
+ showMessage( v.value<MessagePointer>() );
+ } catch ( const char * str ) {
+ log( QString( "error in showMessage: " ) + str, Error );
+ }
+}
+
+
+int MessageManager::receiveMessage( MessageInterface* /*msg*/ ) {
+ return 0;
+}
+
+int MessageManager::receiveMessage( KDevTeamworkTextMessage* /*msg*/ ) {
+ return 0;
+}
+
+int MessageManager::receiveMessage( InDocumentMessage* msg ) {
+ return m_conversationManager->processMessage( msg );
+}
+
+int MessageManager::processMessage( KDevTeamworkTextMessage* msg ) {
+ if ( !msg )
+ return 0;
+ m_historyManager->addMessage( msg );
+ return dispatcher_( msg );
+}
+
+void MessageManager::log( const QString& str, LogLevel level ) {
+ m_teamwork->log( "MessageManager: " + str, level );
+}
+
+KDevTeamwork* MessageManager::teamwork() {
+ return m_teamwork;
+}
+
+MessageHistoryManager& MessageManager::historyManager() {
+ return * m_historyManager;
+}
+
+ConversationManager& MessageManager::conversationManager() {
+ return * m_conversationManager;
+}
+
+void MessageManager::showMessageHistory( const QList<KDevTeamworkUserPointer>& users, const QString& context ) {
+ new GuiMessageHistory( this, users, context );
+}
+
+void MessageManager::fillMessageMenu( QMenu* menu, MessagePointer msg ) {
+ QVariant v;
+ v.setValue( msg );
+ m_showMessageAction->setData( v );
+ menu->addAction( m_showMessageAction );
+
+ teamwork() ->fillMessageMenu( menu, msg );
+
+
+
+ MessagePointer::Locked l = msg;
+ if ( l ) {
+ UserPointer u = l->info().user();
+ if ( u ) {
+ if ( /*l->info().isIncoming() &&*/ l.freeCast<AbstractGUIMessage>() ) {
+ AbstractGUIMessage * request = l.freeCast<AbstractGUIMessage>();
+ request->fillContextMenu( menu, teamwork() );
+ }
+
+ if ( !menu->children().isEmpty() )
+ menu->addSeparator();
+
+ if ( l->info().session() && l->info().session().unsafe() ->isOk() ) {
+ QMenu * m = new QMenu( ~u.unsafe() ->safeName(), menu );
+ menu->addMenu( m );
+ m_teamwork->fillUserMenu( m, u );
+ }
+ } else
+ log( "could not get user from message", Error );
+
+ } else {
+ if ( !l )
+ log( "could not lock message", Error );
+ }
+}
+
+void MessageManager::updateMessage( const MessagePointer& msg ) {
+ emit messageUpdated( msg );
+}
+
+#include "messagemanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.cpp (revision 1522570)
@@ -0,0 +1,37 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "safesignaller.h"
+#include"kdevteamwork.h"
+#include "lib/network/weaksafesharedptr.h"
+
+QSafeSignaller::~QSafeSignaller() {
+ delete m_proxy;
+}
+
+void QSafeSignaller::signal() {
+ if(!KDevTeamwork::self())return;
+ KDevTeamwork::self()->log( "QSafeSignaller::signal()" );
+ m_proxy->signal();
+}
+
+QSafeSignaller& QSafeSignaller::operator = ( const QSafeSignaller& /*rhs*/ ) {
+ return *this;
+}
+
+QSafeSignaller::QSafeSignaller( const QSafeSignaller& /*rhs*/ ) : QObject() {
+}
+
+#include "safesignaller.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safesignaller.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/test.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/test.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/test.cpp (revision 1522570)
@@ -0,0 +1,274 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include "lib/network/crossmap.h"
+#include <assert.h>
+#include <iostream>
+#include <list>
+
+using namespace Utils;
+using namespace std;
+
+struct TestMappable {
+ NAMED_TYPE( Name, std::string );
+ int ints[ 2 ];
+
+ char* bla;
+ std::string string;
+ template <class Type, int number>
+ Type getKey() const {
+ return Type::Error;
+ }
+
+ std::list<int> intList;
+
+ Name name;
+
+ bool operator == ( const TestMappable& rhs ) const {
+ return ints[ 0 ] == rhs.ints[ 0 ] && ints[ 1 ] == rhs.ints[ 1 ] && bla == rhs.bla && string == rhs.string && name == rhs.name;
+ }
+};
+
+
+BIND_LIST_6( KeyList, TestMappable::Name, int, char*, std::string, int, std::list<int> )
+
+///A little test for GetListItem
+Assert< IfSame< GetListItem< 0, KeyList >::Result, TestMappable::Name, Success, Fail >::Result::value >::OK ok1;
+Assert<IfSame< GetListItem< 1, KeyList >::Result, int, Success, Fail >::Result::value >::OK ok2;
+Assert<IfSame< GetListItem< 2, KeyList >::Result, char*, Success, Fail >::Result::value >::OK ok3;
+Assert<IfSame< GetListItem< 3, KeyList >::Result, std::string, Success, Fail >::Result::value >::OK ok4;
+Assert<IfSame< GetListItem< 4, KeyList >::Result, int, Success, Fail >::Result::value >::OK ok42;
+
+Assert < FindInList< TestMappable::Name, KeyList >::value == 0 > ::OK ok5;
+Assert < FindInList< int, KeyList >::value == 1 > ::OK ok6;
+Assert < FindInList< char*, KeyList >::value == 2 > ::OK ok7;
+Assert < FindInList< std::string, KeyList >::value == 3 > ::OK ok8;
+Assert < FindInList< int, KeyList, 1 >::value == 4 > ::OK ok62;
+
+Assert < FindRelativeInList< TestMappable::Name, KeyList >::value == 0 > ::OK ok51;
+Assert < FindRelativeInList< int, KeyList, 1 >::value == 1 > ::OK ok61;
+Assert < FindRelativeInList< char*, KeyList, 2 >::value == 2 > ::OK ok71;
+Assert < FindRelativeInList< std::string, KeyList, 3 >::value == 3 > ::OK ok81;
+Assert < FindRelativeInList< int, KeyList, 4 >::value == 4 > ::OK ok621;
+
+AssertSame< FindRelativeInList< TestMappable::Name, KeyList >::relativeIndex, 0 >::OK ok52;
+AssertSame< FindRelativeInList< int, KeyList, 1 >::relativeIndex, 0 >::OK ok623;
+AssertSame< FindRelativeInList< char*, KeyList, 2 >::relativeIndex, 0 >::OK ok72;
+AssertSame< FindRelativeInList< std::string, KeyList, 3 >::relativeIndex, 0 >::OK ok82;
+AssertSame< FindRelativeInList< int, KeyList, 4 >::relativeIndex, 1 >::OK ok622;
+
+template<class Type>
+std::list<Type> make_list( const Type& t ) {
+ std::list<Type> ret;
+ ret.push_back( t );
+ return ret;
+}
+
+template<class Type>
+std::list<Type> make_list( const Type& i, const Type& i2 ) {
+ std::list<Type> ret;
+ ret.push_back( i );
+ ret.push_back( i2 );
+ return ret;
+}
+
+template<class Type>
+std::list<Type> make_list( const Type& i, const Type& i2, const Type& i3 ) {
+ std::list<Type> ret;
+ ret.push_back( i );
+ ret.push_back( i2 );
+ ret.push_back( i3 );
+ return ret;
+}
+
+template<class Type>
+std::list<Type> make_list( const Type& i, const Type& i2, const Type& i3, const Type& i4 ) {
+ std::list<Type> ret;
+ ret.push_back( i );
+ ret.push_back( i2 );
+ ret.push_back( i3 );
+ ret.push_back( i4 );
+ return ret;
+}
+
+template <>
+int TestMappable::getKey<int, 0>() const {
+ return ints[ 0 ];
+}
+
+template <>
+int TestMappable::getKey<int, 1>() const {
+ return ints[ 1 ];
+}
+
+template <>
+TestMappable::Name TestMappable::getKey<TestMappable::Name, 0>() const {
+ return name;
+}
+
+template <>
+std::string TestMappable::getKey<std::string, 0>() const {
+ return string;
+}
+
+template <>
+char* TestMappable::getKey<char*, 0>() const {
+ return bla;
+}
+
+template <>
+std::list<int> TestMappable::getKey<std::list<int>, 0>() const {
+ return intList;
+}
+
+typedef CrossMap< TestMappable, KeyList> TestSet;
+CrossMap< TestMappable, KeyList> testSet;
+
+
+TestMappable randomMappable() {
+ TestMappable t1;
+ int r = rand() % 5;
+ switch ( r ) {
+ case 0:
+ t1.name = "honk";
+ break;
+ case 1:
+ t1.name = "peter";
+ break;
+ case 2:
+ t1.name = "frank";
+ break;
+ case 3:
+ t1.name = "guildo";
+ break;
+ case 4:
+ t1.name = "joschi";
+ break;
+ }
+ t1.ints[ 0 ] = rand() % 100;
+ t1.ints[ 1 ] = rand() % 100;
+ r = rand() % 5;
+
+ switch ( r ) {
+ case 0:
+ t1.string = "urug";
+ break;
+ case 1:
+ t1.string = "welsch";
+ break;
+ case 2:
+ t1.string = "ick";
+ break;
+ case 3:
+ t1.string = "harr";
+ break;
+ case 4:
+ t1.string = "bloog";
+ break;
+ }
+ return t1;
+}
+
+
+int main() {
+
+ cout << "testing" << endl;
+ TestMappable t1;
+ t1.name = "honk";
+ t1.ints[ 0 ] = 15;
+ t1.ints[ 1 ] = 16;
+ t1.string = "someString";
+
+ TestMappable t2;
+ t2.name = "noHonk";
+ t2.ints[ 0 ] = 15;
+ t2.ints[ 1 ] = 27;
+ t2.string = "no string";
+
+ t1.intList = make_list<int>( 10, 11, 12, 13 );
+ t2.intList = make_list<int>( 11, 13, 17 );
+
+ testSet.insert( t1 );
+
+ assert( (testSet.value<2, int>( 10 ) == t1) );
+ assert( (testSet.value<2, int>( 11 ) == t1) );
+ assert( (testSet.value<2, int>( 12 ) == t1) );
+ assert( (testSet.value<2, int>( 13 ) == t1) );
+ assert( !(testSet.value<2, int>( 14 ) == t1) );
+
+ assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
+ assert( testSet.value<std::string> ( "someString" ) == t1 );
+ assert( testSet.value<int> ( 15 ) == t1 );
+ assert( ( testSet.value<1, int>( 16 ) == t1 ) );
+
+ testSet.update( testSet.find( t1 ) );
+
+ assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
+ assert( testSet.value<std::string> ( "someString" ) == t1 );
+ assert( testSet.value<int> ( 15 ) == t1 );
+ assert( ( testSet.value<1, int>( 16 ) == t1 ) );
+
+ assert( testSet.update( testSet.find( testSet[ 15 ] ) ) );
+
+ assert( testSet.hasContent() );
+
+ testSet.remove( testSet.value<1, int>( 16 ) );
+
+ assert( !testSet.hasContent() );
+
+ testSet.insert( t1 );
+ testSet.insert( t1 );
+ testSet.insert( t2 );
+
+ assert( (testSet.value<2, int>( 10 ) == t1) );
+ assert( (testSet.value<2, int>( 17 ) == t2) );
+ assert( (testSet.values<2, int>( 11 ).count() == 3) );
+
+ CrossMap< TestMappable, KeyList>::Iterator it = testSet.values<int>( 15 );
+ assert( it.count() == 3 );
+ while ( it ) {
+ cout << "Item:" << ( *it ).name.value << endl;
+ ++it;
+ }
+
+ assert( testSet.remove( t2 ) );
+
+ assert( testSet.count() == 2 );
+
+ assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
+ assert( testSet.value<std::string> ( "someString" ) == t1 );
+ assert( testSet.value<int> ( 15 ) == t1 );
+ assert( ( testSet.value<1, int>( 16 ) == t1 ) );
+
+ testSet.remove( t1 );
+
+ assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
+ assert( testSet.value<std::string> ( "someString" ) == t1 );
+ assert( testSet.value<int> ( 15 ) == t1 );
+ assert( ( testSet.value<1, int>( 16 ) == t1 ) );
+
+ testSet.remove( t1 );
+
+ assert( testSet.count() == 0 );
+ assert( !testSet.hasContent() );
+
+ cout << "success" << endl;
+
+ return 0;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/test.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp (revision 1522570)
@@ -0,0 +1,39 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "filesynchronizemessage.h"
+#include "lib/dynamictext/dynamictext.h"
+#include "utils.h"
+#include "qtserialization.h"
+#include <boost/serialization/vector.hpp>
+
+FileSynchronizeData::FileSynchronizeData( const QString& fileName, const QDynamicText& text, bool sendDynamic ) {
+ if( sendDynamic ) {
+ m_fileText = ~text.text().text();
+ } else {
+ m_text = new QDynamicText( text );
+ }
+ m_state = text.state();
+ m_fileName = fileName;
+}
+
+QDynamicTextPointer FileSynchronizeData::createDynamicText() {
+ if( m_text )
+ return m_text;
+ else
+ return new QDynamicText( m_state, ~m_fileText );
+}
+
+EASY_IMPLEMENT_MESSAGE( FileSynchronize )
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp (revision 1522570)
@@ -0,0 +1,369 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "filecollaborationmanager.h"
+#include <QAction>
+#include <QMenu>
+#include <QTimer>
+#include <QFileInfo>
+#include <QModelIndex>
+#include <QStandardItemModel>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/cursor.h>
+
+#include <interfaces/idocumentcontroller.h>
+
+#include "lib/network/messagesendhelper.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/sessioninterface.h"
+
+#include "lib/dynamictext/verify.h"
+
+#include "teamworkfwd.h"
+#include "patchesmanager.h"
+#include "kdevteamwork_user.h"
+#include "kdevutils.h"
+#include "documentwrapper.h"
+#include "kdevteamwork_helpers.h"
+#include "ui_kdevteamwork_filecollaborationsession.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+using namespace Teamwork;
+
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, QList<QString>, 0, value->plainFileNames() )
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, QList<KDevTeamworkUserPointer>, 0, value->users() )
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, SessionName, 0, value->name() )
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, FileCollaborationSessionPointer, 0, value )
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, CollabSessionId, 0, value->id() )
+
+/**How file-collaboration should work:
+ * Host:
+ * - Once developer starts a collaboration-session on an arbitrary set of files, he can invite an arbitrary count of collaborating developers to join it.
+ * - He can only host one collaboration-session at a time.
+ * - Once the session is closed, he is asked whether he'd like to store the changes of the session as a patch to the patches-list(that way he may also unapply the changes if he saved them).
+ * Client:
+ * - A client gets an invitation and can accept it.
+ * - The client can only be part of one collaboration-session at a time.
+ * - Once the session is closed, he is asked whether the result of the session should be stored as a diff-file to the patches-list.(that way it may be applied to the local tree)
+ *
+ * Implementation: See DynamicText
+ *
+ * */
+
+/**Algorithm for the FileCollaboration:
+ * - Each FileCollaboration-message that is sent gets a personal sequence-number(which is like a timestamp, the "count of locally happened events")
+ * that can be used to see which state of the communication it was sent in(and can be used to resolve causalities)
+ * - Each FileCollaboration-session has a vector containing all current sequence-numbers
+ * - Each FileCollaboration-message is sent together with that vector, so conflicts may be resolved.
+ * - Whenever the master-session sends a FileResynchronize-message, the local version of the slave-session is totally updated
+ * */
+
+
+Q_DECLARE_METATYPE( Teamwork::UserPointer )
+
+
+
+FileCollaborationManager::FileCollaborationManager( CollaborationManager* manager ) :
+ SafeLogger( manager->teamwork() ->logger(),
+ "FileCollaborationManager: " ),
+ m_manager( manager ),
+m_dispatcher( *this ) {
+ connect( m_manager, SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
+ m_startCollaborationSessionAction = new QAction( i18n("Start File-Collaboration"), this );
+ connect( m_startCollaborationSessionAction, SIGNAL( triggered() ), this, SLOT( slotStartCollaborationSession() ) );
+ connect( manager, SIGNAL( updateModel( QStandardItemModel* ) ), this, SLOT( updateCollaborationModel( QStandardItemModel* ) ) );
+
+}
+
+KDevTeamwork* FileCollaborationManager::teamwork() {
+ return m_manager->teamwork();
+}
+
+const FileCollaborationManager::SessionSet& FileCollaborationManager::sessions() {
+ return m_sessions;
+}
+
+FileCollaborationSession * FileCollaborationManager::startSession( const QString& name, CollabFileList files, uint primaryIndex, CollabSessionId id ) {
+ FileCollaborationSessionPointer s = new FileCollaborationSession( name, files, this, primaryIndex, id );
+ m_sessions.insert( s );
+
+ connect( s.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), this, SLOT( slotSessionStateChanged( const FileCollaborationSessionPointer& ) ) );
+
+ return s;
+}
+
+void FileCollaborationManager::updateCollaborationModel( QStandardItemModel* model ) {
+
+ ///Add/update sessions
+ QMap< FileCollaborationSessionPointer, QPersistentModelIndex > sessions;
+
+ for ( int r = model->rowCount() - 1; r >= 0 ; --r ) {
+ QModelIndex i = model->index( r, 0 );
+ if ( !i.isValid() )
+ continue;
+ QVariant v = i.data( Qt::UserRole );
+ if ( v.canConvert<CollaborationTreeActionPointer>() ) {
+ CollaborationTreeActionPointer action = v.value<CollaborationTreeActionPointer>();
+ StandardCollaborationTreeAction<FileCollaborationSession> *session = dynamic_cast< StandardCollaborationTreeAction<FileCollaborationSession>* >( action.data() );
+ if( session ) {
+ if ( !session->target ) {
+ model->removeRow( r );
+ } else {
+ sessions[ (FileCollaborationSession*)session->target ] = i;
+ }
+ }
+ }
+ }
+
+ SessionSet::ValueMap::const_iterator it = m_sessions.begin();
+ for ( ; it != m_sessions.end(); ++it ) {
+ FileCollaborationSessionPointer session = ( *it ).second.value;
+ QModelIndex i;
+ if ( sessions.contains( session ) ) {
+ i = sessions[ session ];
+ } else {
+ model->insertRow( 0 );
+ i = model->index( 0, 0 );
+ sessions[ session ] = QPersistentModelIndex( i );
+ disconnect( session.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), m_manager, SLOT( sessionStateChanged( const FileCollaborationSessionPointer& ) ) );
+ connect( session.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), m_manager, SLOT( sessionStateChanged( const FileCollaborationSessionPointer& ) ) );
+ }
+
+ QIcon icon = session->icon();
+ model->setData( i, session->name(), Qt::DisplayRole );
+ model->setData( i, icon, Qt::DecorationRole );
+
+ /*QVariant
+ model->setData( i, icon, Qt::DecorationRole );*/
+ QVariant v;
+ v.setValue<CollaborationTreeActionPointer>( new StandardCollaborationTreeAction<FileCollaborationSession>( session ) );
+ model->setData( i, v, Qt::UserRole );
+
+ session->updateTree( i, model );
+ }
+}
+
+void FileCollaborationManager::slotFillCollaboratingUserMenu( QMenu * menu, const UserPointer & user ) {
+ if ( m_sessions.empty() ) {
+ QVariant v;
+ v.setValue( user );
+ m_startCollaborationSessionAction->setData( v );
+
+ menu->addAction( m_startCollaborationSessionAction );
+ }
+
+ emit fillCollaboratingUserMenu( menu, user );
+}
+
+
+
+void FileCollaborationManager::slotStartCollaborationSession() {
+ try {
+ QAction * act = qobject_cast<QAction*>( sender() );
+ if ( !act )
+ throw "no action";
+
+ QVariant v = act->data();
+ if ( !v.canConvert<UserPointer>() )
+ throw "wrong data";
+
+ UserPointer::Locked lu = v.value<UserPointer>();
+ if ( !lu )
+ throw "could not lock user";
+
+ CollabFileList files;
+
+ files.push_back(CollabFile(0, currentDocumentPath() ) );
+
+ Ui_NewFileCollaborationSession s;
+ KDialog d;
+ d.setButtons( KDialog::Ok | KDialog::Cancel );
+ s.setupUi( d.mainWidget() );
+ s.sessionName->setText( "Collaborate_on_" + QFileInfo( files.front().file ).baseName() );
+ QString filesText = "Files:";
+ for( CollabFileList::iterator it = files.begin(); it != files.end(); ++it ) {
+ filesText += "\n" + it->file;
+ }
+ s.files->setText( filesText );
+
+ QString usersText = "Invite users:";
+ usersText += "\n" + ~lu->name();
+ s.users->setText( usersText );
+
+ if( d.exec() == QDialog::Accepted ) {
+ QString name = s.sessionName->text();
+ FileCollaborationSessionPointer p = startSession( name, files );
+
+ p->setAllowSentDocuments( s.allowSentDocuments->isChecked() );
+ p->inviteUser( lu.freeCast<KDevTeamworkUser>() );
+ }
+ } catch ( const char * str ) {
+ err() << QString( "Error in slotStartCollaborationSession(): " ) + str;
+ } catch ( QString str ) {
+ err() << QString( "Error in slotStartCollaborationSession(): " ) + str;
+ };
+}
+
+void FileCollaborationManager::processMessage( FileCollaborationMessagePointer msg ) {
+ FileCollaborationMessagePointer::Locked l = msg;
+ if ( l ) {
+ if ( l->sessionId() == 0 || msg.cast<FileCollaborationRequest>() ) {
+ m_dispatcher( l );
+ } else {
+ FileCollaborationSessionPointer s = m_sessions.value<CollabSessionId>( l->sessionId() );
+ if ( s ) {
+ s->processMessage( l.data() );
+ } else {
+ err() << "got message for unknown file-collaboration-session with id ~" << l->sessionId() <<", type:" << msg.unsafe()->name();
+ }
+ }
+ } else {
+ err() << "could not lock a FileCollaborationMessage";
+ }
+}
+
+int FileCollaborationManager::receiveMessage( MessageInterface* msg ) {
+ out( Logger::Warning ) << "got unknown message-type" << msg->name();
+ return 0;
+}
+
+int FileCollaborationManager::receiveMessage( FileCollaborationRequest* msg ) {
+ ///Since it is an AbstractGUIMessage, it can plug itself into the GUI and wait for an answer by the user.
+ m_manager->teamwork() ->addMessageToList( msg );
+ return 1;
+}
+
+int FileCollaborationManager::receiveMessage( FileCollaborationMessage* msg ) {
+ SessionSet::Iterator it = m_sessions.values<CollabSessionId>( msg->sessionId() );
+ if( it ) {
+ return const_cast<FileCollaborationSession*>((*it).data())->processMessage( msg );
+ } else {
+ out( Logger::Warning ) << "got a FileCollaborationMessage of type" << msg->name() << "for a non-existent session:" << (uint)msg->sessionId();
+ return 0;
+ }
+}
+
+void FileCollaborationManager::slotSessionStateChanged( const FileCollaborationSessionPointer & session ) {
+ m_sessions.update( session );
+}
+
+void FileCollaborationManager::denyCollaboration( const FileCollaborationRequestPointer& msg ) {
+ FileCollaborationRequestPointer::Locked l = msg;
+ if ( !l ) {
+ err() << "denyCollaboration(): could not lock message";
+ return;
+ }
+
+ std::pair< RequestMap::const_iterator, RequestMap::const_iterator > range = m_requests.equal_range( l->sessionId() );
+
+ ///Deny all other requests for the same session
+ bool ready = false;
+ while( !ready ) {
+ ready = true;
+ std::pair< RequestMap::iterator, RequestMap::iterator > range = m_requests.equal_range( l->sessionId() );
+
+ while( range.first != range.second ) {
+ if( (*range.first).second == msg ) {
+ m_requests.erase( range.first++ );
+ continue;
+ }
+ FileCollaborationRequestPointer::Locked lm = (*range.first).second;
+ if( lm ) {
+ int cnt = m_requests.size();
+ lm->denyCollaboration();
+ if( m_requests.size() != (uint)cnt ) {
+ ready = false;
+ break;
+ }
+ }
+ ++range.first;
+ }
+ }
+}
+
+bool FileCollaborationManager::acceptCollaboration( const FileCollaborationRequestPointer& msg ) {
+ try {
+ FileCollaborationRequestPointer::Locked l = msg;
+ if ( !l )
+ throw "could not lock message";
+
+ //Q_VERIFY( l->index() != 0 );
+
+ FileCollaborationSessionPointer session;
+ if( m_sessions.values( l->sessionId() ) ) {
+ session = m_sessions[ l->sessionId() ];
+ } else {
+ QString name = l->FileCollaborationRequestData::name();
+ if( name.isEmpty() ) {
+ name = "anonymous session";
+ if( l->info().user() )
+ name += "@" + ~l->info().user().unsafe()->safeName();
+ }
+ session = startSession( name, l->files(), l->index(), l->sessionId() );
+ if ( !session )
+ throw "could not create FileCollaborationSession";
+ }
+
+ session->acceptMessage( msg );
+
+ ///Now pull in all other requests waiting for this session
+ bool ready = false;
+ while( !ready ) {
+ ready = true;
+ std::pair< RequestMap::iterator, RequestMap::iterator > range = m_requests.equal_range( l->sessionId() );
+
+ while( range.first != range.second ) {
+ if( (*range.first).second == msg ) {
+ m_requests.erase( range.first++ );
+ continue;
+ }
+ FileCollaborationRequestPointer::Locked lm = (*range.first).second;
+ if( lm ) {
+ int cnt = m_requests.size();
+ lm->denyCollaboration();
+ if( m_requests.size() != (uint)cnt ) {
+ ready = false;
+ break;
+ }
+ }
+ ++range.first;
+ }
+ }
+
+ out( Logger::Debug ) << "collaboration accepted";
+ m_requests.erase( l->sessionId() );
+ return true;
+ } catch ( const QString & str ) {
+ err() << "error in acceptCollaboration:" << str;
+ return false;
+ } catch ( const char * str ) {
+ err() << "error in acceptCollaboration:" << str;
+ return false;
+ }
+}
+
+void FileCollaborationManager::closeSession( const FileCollaborationSessionPointer& session ) {
+ session->aboutToClose();
+ m_sessions.remove( session );
+}
+
+
+#include "filecollaborationmanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp (revision 1522570)
@@ -0,0 +1,112 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "kdevteamwork_helpers.h"
+#include <QIcon>
+#include <kiconloader.h>
+#include "lib/network/messagetypeset.h"
+
+IconCache* IconCache::m_instance = 0;
+
+
+IconCache::IconCache() {
+ ///Here, the appropriate icon-names can be chosen by mapping
+ m_instance = this;
+ maps_[ "unknown" ] = "unknown";
+ maps_[ "text_message_in" ] = "mail-receive";
+ maps_[ "text_message_out" ] = "mail-send";
+
+ maps_[ "document_message_in" ] = "folder_inbox";
+ maps_[ "document_message_out" ] = "folder_outbox";
+
+ maps_[ "generalrequest_in" ] = "bookmarks";
+ maps_[ "generalrequest_out" ] = "tools-wizard";
+ maps_[ "generalrequest_in_denied" ] = "fileclose";
+ maps_[ "generalrequest_in_accepted" ] = "dialog-ok";
+ maps_[ "generalrequest_out_denied" ] = "fileclose";
+ maps_[ "generalrequest_out_accepted" ] = "dialog-ok";
+ maps_[ "generalrequest_out_failed" ] = "remove";
+ maps_[ "generalrequest_in_failed" ] = "remove";
+
+ maps_[ "collaborationrequest_in" ] = "bookmarks";
+ maps_[ "collaborationrequest_out" ] = "tools-wizard";
+ maps_[ "collaborationrequest_accepted" ] = "dialog-ok";
+ maps_[ "collaborationrequest_denied" ] = "fileclose";
+ maps_[ "collaborationrequest_in_denied" ] = "fileclose";
+ maps_[ "collaborationrequest_in_accepted" ] = "dialog-ok";
+ maps_[ "collaborationrequest_out_denied" ] = "fileclose";
+ maps_[ "collaborationrequest_out_accepted" ] = "dialog-ok";
+ maps_[ "collaborationrequest_out_failed" ] = "remove";
+ maps_[ "collaborationrequest_in_failed" ] = "remove";
+
+ maps_[ "collaboration_file" ] = "completion";
+ maps_[ "collaboration_file_disabled" ] = "remove";
+ maps_[ "collaboration_file_dead" ] = "fileclose";
+ maps_[ "collaboration_session" ] = "system-switch-user";
+ maps_[ "collaboration_session_finished" ] = "remove";
+ maps_[ "collaboration_session_connectionlost" ] = "fileclose";
+
+ maps_[ "filecollaborationrequest_in" ] = "bookmarks";
+ maps_[ "filecollaborationrequest_out" ] = "tools-wizard";
+ maps_[ "filecollaborationrequest_accepted" ] = "dialog-ok";
+ maps_[ "filecollaborationrequest_denied" ] = "fileclose";
+ maps_[ "filecollaborationrequest_in_denied" ] = "fileclose";
+ maps_[ "filecollaborationrequest_in_accepted" ] = "dialog-ok";
+ maps_[ "filecollaborationrequest_out_denied" ] = "fileclose";
+ maps_[ "filecollaborationrequest_out_accepted" ] = "dialog-ok";
+ maps_[ "filecollaborationrequest_out_failed" ] = "remove";
+ maps_[ "filecollaborationrequest_in_failed" ] = "remove";
+ maps_[ "filecollaborationrequest_in_failed" ] = "remove";
+ maps_[ "fileusercollaboration_inactive" ] = "presence_unknown";
+
+ maps_[ "patch" ] = "text-x-generic";
+ maps_[ "failed" ] = "fileclose";
+
+ maps_[ "error" ] = "stop";
+}
+
+void SafeTeamworkEmitter::updateMessageInfo( const MessagePointer& msg ) {
+ emit signalUpdateMessageInfo( msg );
+}
+
+QIcon IconCache::operator () ( const QString& name, KIconLoader::Group grp ) {
+ return getIcon( name, grp );
+}
+
+QIcon IconCache::getIconStatic( QString name, KIconLoader::Group grp ) {
+ return IconCache::instance() ->getIcon( name, grp );
+}
+
+QIcon IconCache::getIcon( QString name, KIconLoader::Group grp ) {
+ {
+ QMap<QString, QString>::iterator it = maps_.find( name );
+
+ if ( it != maps_.end() )
+ name = *it;
+ }
+
+ QPair<QString, KIconLoader::Group> pos( name, grp );
+ IconMap::iterator it = m_icons.find( pos );
+ if ( it != m_icons.end() ) {
+ return * it;
+ } else {
+ m_icons[ pos ] = QIcon( KIconLoader::global() ->loadIcon( name, grp ) );
+ return m_icons[ pos ];
+ }
+}
+
+IconCache* IconCache::instance() {
+ return m_instance;
+}
+
+
+#include "kdevteamwork_helpers.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.h (revision 1522570)
@@ -0,0 +1,188 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef PATCHESMANAGER_H
+#define PATCHESMANAGER_H
+//#include <boost/serialization/list.hpp>
+#include <list>
+#include <string>
+#include <QObject>
+#include <QMetaType>
+#include <QStandardItemModel>
+#include <QPointer>
+
+#include "lib/network/serialization.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/easymessage.h"
+
+#include "ui_kdevteamwork_managepatches.h"
+#include "kdevteamwork_messages.h"
+#include "patchmessage.h"
+
+#include "utils.h"
+
+
+using namespace std;
+using namespace Teamwork;
+
+class EditPatch;
+class QDomElement;
+class IconCache;
+class KDevTeamwork;
+class KDevTeamworkClient;
+class PatchesManager;
+typedef SafeSharedPtr<KDevTeamworkClient> TeamworkClientPointer;
+typedef SharedPtr<EditPatch> EditPatchPointer;
+
+
+struct PatchesManagerConfig {
+ std::list<LocalPatchSourcePointer> patchSources;
+
+ template <class Archive>
+ void serializePatches( Archive& arch, const uint /*version*/ ) {
+ arch & NVP( patchSources );
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint version ) {
+ serializePatches( arch, version );
+ }
+
+ bool hasPatch( const LocalPatchSourcePointer& patch ) {
+ for ( std::list<LocalPatchSourcePointer>::iterator it = patchSources.begin(); it != patchSources.end(); ++it ) {
+ if ( *it == patch )
+ return true;
+ }
+ return false;
+ }
+
+ void addPatch( const LocalPatchSourcePointer& patch ) {
+ patchSources.push_back( patch );
+ }
+};
+
+BIND_LIST_4( PatchesManagerMessages, PatchesManagerMessage, PatchesListMessage, PatchRequestMessage, PatchMessage )
+
+class PatchesManager : public QObject {
+ Q_OBJECT
+ public:
+ PatchesManager( KDevTeamwork* tw );
+ ~PatchesManager();
+
+ void showPatchInfo( const LocalPatchSourcePointer& patch , bool local = true );
+
+ void restorePartialProjectSession( const QDomElement* el );
+
+ void savePartialProjectSession( QDomElement* el );
+
+ void fillDeveloperActions( const QModelIndex& index, QMenu* menu );
+
+ void addPatch( const LocalPatchSourcePointer& patch );
+ bool hasPatch( const LocalPatchSourcePointer& patch );
+
+ ///Tries to find out whether the patch is applied by using the patch-command in dry-run mode. Only works with patch-files(not commands). Fills the result into the given patch
+ LocalPatchSource::State determineState( const LocalPatchSourcePointer& patch );
+
+ ///Tries to merge the patches to one. If it fails, returns zero.
+ LocalPatchSourcePointer merge( const QString& name, const QList<LocalPatchSourcePointer>& patches );
+
+ KDevTeamwork* teamwork();
+
+ public slots:
+ void processMessage( PatchesManagerMessagePointer );
+ private slots:
+ void save();
+ void load();
+ void editDialogClosed( EditPatch* );
+ void editStateChanged( EditPatch* );
+
+ void guiUpdatePatchesList();
+
+ void init();
+ void slotManagePatches();
+ void slotUpdateConnection( TeamworkClientPointer newClient );
+
+ ///The patches-management-menu:
+ void slotEditPatch();
+ void slotAddPatch();
+ void slotRemovePatch();
+ void slotCloseManagement();
+ void slotManagementFinished( int result );
+
+ ///The developer/patch context-menu:
+ void slotShowPatch();
+ void slotShowPatchInfo();
+ void slotApplyPatch();
+ void slotDownloadPatch();
+
+ ///The patch-message context-menu
+ void slotShowRequestedPatch();
+ void slotDenyPatch();
+ void slotAllowPatch();
+
+ private:
+ EditPatchPointer showEditDialog( const LocalPatchSourcePointer& patch, bool local );
+ ///Actions for the developer/patch-menu:
+ QAction* m_showPatchAction;
+ QAction* m_showPatchInfoAction;
+ QAction* m_downloadPatchAction;
+ QAction* m_applyPatchAction;
+
+ LocalPatchSourcePointer::Locked patchFromIdentity( const LocalPatchSource::Identity& identity );
+
+ void log( const QString& str, LogLevel level = Info );
+
+ LocalPatchSourcePointer selectedPatch();
+
+ ///The edit-dialog:
+ LocalPatchSourcePointer patchFromEdit(); ///may return invalid pointer
+ void fillEditFromPatch( LocalPatchSourcePointer patch , bool local = true );
+
+ KDevTeamwork* m_teamwork;
+ PatchesManagerConfig m_config;
+
+ friend class MessageDispatcher< PatchesManager, PatchesManagerMessages >;
+ friend class EditPatch;
+
+ MessageDispatcher< PatchesManager, PatchesManagerMessages > dispatcher_;
+
+ Ui_ManagePatches m_managePatches;
+ QPointer<KDialog> m_manageDlg;
+
+ QStandardItemModel* m_patchesModel;
+
+ LocalPatchSourcePointer m_editingPatch;
+
+ void applyPatch( LocalPatchSourcePointer::Locked patch, bool reverse = false );
+
+ int receiveMessage( MessageInterface* msg );
+ int receiveMessage( PatchesManagerMessage* msg );
+ int receiveMessage( PatchesListMessage* msg );
+ int receiveMessage( PatchRequestMessage* msg );
+ int receiveMessage( PatchMessage* msg );
+
+ QList<EditPatchPointer> m_editing;
+
+ ///Actions for the PatchRequestMessage-menu:
+ QAction* m_denyPatchAction;
+ QAction* m_allowPatchAction;
+ QAction* m_showRequestedPatchAction;
+
+ QTimer* m_updateTimer;
+ friend class PatchRequestData;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchesmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qtserialization.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qtserialization.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qtserialization.h (revision 1522570)
@@ -0,0 +1,133 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef QTSERIALIZATION_H
+#define QTSERIALIZATION_H
+
+#include "lib/network/serialization.h"
+#include <boost/serialization/split_free.hpp>
+#include <boost/serialization/level.hpp>
+#include <boost/serialization/binary_object.hpp>
+#include <QDataStream>
+#include <QTextStream>
+#include <QByteArray>
+#include <QVariant>
+#include <vector>
+#include <QString>
+#include <string>
+#include <iostream>
+
+namespace boost {
+namespace serialization {
+template <class Archive>
+void load( Archive & arch, QByteArray& b, const unsigned int /*version*/ ) {
+ uint size;
+ arch & size;
+ b.resize( size );
+
+ binary_object o( b.data(), b.size() );
+ arch & o;
+}
+
+template <class Archive>
+void save( Archive & arch, const QByteArray& b, const unsigned int /*version*/ ) {
+ uint size = b.size();
+ arch & size;
+ binary_object o( const_cast<QByteArray&>( b ).data(), b.size() );
+ arch & o;
+}
+}
+}
+
+BOOST_SERIALIZATION_SPLIT_FREE( QByteArray )
+
+///Usually uses a QDataStream to convert to a binary object, and stores that.
+template <class Type>
+class QSerialize {
+ Type& m_t;
+ public:
+ QSerialize( const Type& t ) : m_t( const_cast<Type&>( t ) ) {}
+
+ template <class Archive>
+ void save( Archive& arch, unsigned int /*version*/ ) const {
+ QByteArray b;
+ QDataStream s( &b, QIODevice::WriteOnly );
+ s << m_t;
+ arch & b;
+ }
+
+ template <class Archive>
+ void load( Archive& arch, unsigned int /*version*/ ) {
+ QByteArray b;
+ arch & b;
+
+ QDataStream s( &b, QIODevice::ReadOnly );
+ s >> m_t;
+ }
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+};
+
+/**This function returns a temporary serialization-object that can be used to serialize Qt-Types using the boost-serialization-library. */
+template <class Type>
+QSerialize<Type> qStore( const Type& t ) {
+ return QSerialize<Type>( t );
+}
+
+namespace boost {
+namespace serialization {
+
+template <class Archive>
+void serialize( Archive & ar, QString& str, const unsigned int /*version*/ ) {
+ QSerialize<QString> s( str );
+ ar & s;
+}
+
+template <class Archive>
+void serialize( Archive & ar, QStringList& t, const unsigned int /*version*/ ) {
+ QSerialize<QStringList> s( t );
+ ar & s;
+}
+
+template <class Archive>
+void serialize( Archive & ar, QVariant& t, const unsigned int /*version*/ ) {
+ QSerialize<QVariant> s( t );
+ ar & s;
+}
+} // namespace serialization
+} // namespace
+
+///Tell boost not to store type-information for QSerialize<T>
+namespace boost {
+namespace serialization {
+template <class T>
+struct implementation_level< QSerialize<T> > {
+ typedef mpl::integral_c_tag tag;
+ typedef mpl::int_< object_serializable > type;
+ BOOST_STATIC_CONSTANT(
+ int,
+ value = implementation_level::type::value
+ );
+};
+}
+}
+
+BOOST_CLASS_IMPLEMENTATION(QString, object_serializable)
+BOOST_CLASS_IMPLEMENTATION(QStringList, object_serializable)
+BOOST_CLASS_IMPLEMENTATION(QVariant, object_serializable)
+BOOST_CLASS_IMPLEMENTATION(QByteArray, object_serializable)
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/qtserialization.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp (revision 1522570)
@@ -0,0 +1,105 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#include "messagesendmanager.h"
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+#include <interfaces/icore.h>
+#include <interfaces/idocument.h>
+#include <interfaces/idocumentcontroller.h>
+#include <indocumentreference.h>
+
+#include "kdevteamworkplugin.h"
+#include "teamworkfoldermanager.h"
+
+MessageSendManager::MessageSendManager( Ui::Teamwork& widgets ) : m_widgets( widgets ), m_lastDocument(0) {
+ connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
+ connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentClosed( KDevelop::IDocument* ) ), this, SLOT( documentClosed( KDevelop::IDocument* ) ) );
+ if( KDevTeamworkPlugin::staticDocumentController()->activeDocument() )
+ documentActivated( KDevTeamworkPlugin::staticDocumentController()->activeDocument() );
+}
+
+void MessageSendManager::documentActivated( KDevelop::IDocument* document ) {
+ if( document == m_lastDocument ) return;
+ disconnectDocument();
+ connectDocument( document );
+}
+
+void MessageSendManager::documentClosed( KDevelop::IDocument* document ) {
+ if( document == m_lastDocument )
+ disconnectDocument();
+}
+
+void MessageSendManager::connectDocument( KDevelop::IDocument* document ) {
+ m_lastDocument = document;
+ if( !document->textDocument() ) return;
+ connect( document->textDocument(), SIGNAL(destroyed( QObject* )), this, SLOT( documentDestroyed( QObject* ) ) );
+ connect( document->textDocument(), SIGNAL( viewCreated( KTextEditor::Document* , KTextEditor::View* ) ), this, SLOT( viewCreated( KTextEditor::Document*, KTextEditor::View* ) ) );
+
+ KTextEditor::View* v = view();
+ if( !v ) return;
+ connectView( v );
+}
+
+void MessageSendManager::connectView( KTextEditor::View* v ) {
+ disconnect( v, SIGNAL( selectionChanged( KTextEditor::View* ) ), this, SLOT( selectionChanged( KTextEditor::View* ) ) ); ///Just to make sure that multiple connections don't happen
+ connect( v, SIGNAL( selectionChanged( KTextEditor::View* ) ), this, SLOT( selectionChanged( KTextEditor::View* ) ) );
+}
+
+KTextEditor::View* MessageSendManager::view() {
+ if( !m_lastDocument ) return 0;
+ if( !m_lastDocument->textDocument() ) return 0;
+ return m_lastDocument->textDocument()->activeView();
+}
+
+void MessageSendManager::disconnectDocument() {
+ KDevelop::IDocument* document = m_lastDocument;
+ if( !document ) return;
+ if( !document->textDocument() ) return;
+ disconnect( document->textDocument(), SIGNAL(destroyed( QObject* )), this, SLOT( documentDestroyed( QObject* ) ) );
+ disconnect( document->textDocument(), SIGNAL( viewCreated( KTextEditor::Document* , KTextEditor::View* ) ), this, SLOT( viewCreated( KTextEditor::Document*, KTextEditor::View* ) ) );
+
+ m_lastDocument = 0;
+}
+
+void MessageSendManager::documentDestroyed( QObject* /*obj*/ ) {
+ m_lastDocument = 0;
+}
+
+void MessageSendManager::viewCreated( KTextEditor::Document* , KTextEditor::View* ) {
+}
+
+void MessageSendManager::selectionChanged( KTextEditor::View* view ) {
+
+ m_currentSelection = view->selectionRange();
+ KTextEditor::Document* doc = view->document();
+ m_currentFile = "";
+ if( doc )
+ m_currentFile = TeamworkFolderManager::workspaceRelative( doc->url() );
+
+ ///Now check if the message-send-widget is visible
+ if( m_widgets.toolBox->currentWidget() == m_widgets.messaging && !m_currentFile.isEmpty() ) {
+ if( m_currentSelection.isEmpty() ) {
+ ///Remove the selection
+ } else {
+ m_widgets.reference->setText( InDocumentReference::createReference( m_currentFile.pathOrUrl(), m_currentSelection.start().line(), m_currentSelection.start().column(), m_currentSelection.end().line(), m_currentSelection.end().column() ) );
+ }
+ }
+}
+
+#include "messagesendmanager.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h (revision 1522570)
@@ -0,0 +1,188 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+
+#ifndef KDEVTEAMWORK_MESSAGES_H
+#define KDEVTEAMWORK_MESSAGES_H
+
+//#include <boost/serialization/extended_type_info_typeid.hpp>
+
+#include "lib/network/serialization.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/teamworkmessages.h"
+#include "lib/network/forwardsession.h"
+
+#include <QString>
+#include <QDateTime>
+#include "utils.h"
+#include <QIcon>
+#include <QVariant>
+#include "lib/network/easymessage.h"
+#include <string>
+#include <boost/serialization/level.hpp>
+#include "loglevel.h"
+
+/*#define BOOST_SERIALIZATION_DEFAULT_TYPE_INFO(T) \
+ extended_type_info_typeid<const T>*/
+/**/
+
+using namespace Teamwork;
+
+class KDevTeamwork;
+class QMenu;
+class QModelIndex;
+class QWidget;
+
+class SafeTeamworkEmitter;
+typedef SharedPtr<SafeTeamworkEmitter> SafeTeamworkEmitterPointer;
+
+class IconCache;
+
+class KDevSystemMessage : public SystemMessage {
+ DECLARE_MESSAGE( KDevSystemMessage, SystemMessage, 5 );
+ public:
+ enum Message {
+ CollaborationAccepted,
+ CollaborationRefused,
+ CollaborationClosed,
+ ActionFailed, ///An Action failed
+ ActionSuccessful,
+ ActionDenied
+ };
+ KDevSystemMessage( InArchive& arch, const Teamwork::MessageInfo& info );
+
+ KDevSystemMessage( const Teamwork::MessageConstructionInfo& info, Message msg , const string& str = "" );
+
+ Message message();
+
+ QString messageAsString();
+
+ QString text();
+};
+
+typedef SafeSharedPtr<KDevSystemMessage> KDevSystemMessagePointer;
+
+struct AbstractGUIMessage {
+ QVariant data; ///@todo remove
+ virtual QString messageText() const = 0;
+ virtual QIcon messageIcon() const;
+ virtual void fillContextMenu( QMenu* /*menu*/, KDevTeamwork* /*teamwork*/ ) {}
+ ;
+ virtual ~AbstractGUIMessage() {}
+ ;
+ virtual bool show() {
+ return true;
+ }
+ virtual QString shortName() const {
+ return "Message";
+ }
+ ///This should return an icon that represents the message-type and has nothing to do with the message-instance
+ virtual QIcon messageTypeIcon() const;
+
+ virtual bool canShowInWidget() {
+ return false;
+ }
+
+ virtual void showInWidget( QWidget* /*widget*/, KDevTeamwork* /*tw*/ ) {}
+};
+
+class KDevTeamworkTextMessage : public TextMessage, public AbstractGUIMessage {
+ DECLARE_MESSAGE( KDevTeamworkTextMessage, TextMessage, 6 );
+ public:
+
+ KDevTeamworkTextMessage( const Teamwork::MessageConstructionInfo& info, const QString& text );
+
+ KDevTeamworkTextMessage( InArchive& from, const Teamwork::MessageInfo& info );
+
+ virtual QString messageText() const;
+
+ virtual QIcon messageIcon() const;
+
+ void setAnswered( bool );
+
+ bool answered() const;
+
+ virtual void serialize( OutArchive& arch );
+
+ virtual bool needReply() const;
+
+ QDateTime creationTime();
+
+ virtual bool canShowInWidget();
+
+ ///If this returns false, the widget is not shown.
+ virtual void showInWidget( QWidget* widget, KDevTeamwork* tw );
+
+ private:
+ QDateTime creationTime_;
+ bool m_answered;
+};
+
+///Just a dummy for compatible insertion of error-messages to the message-list
+class FailureMessage : public KDevTeamworkTextMessage {
+ public:
+ FailureMessage( const QString& text, const MessagePointer& msg );
+
+ virtual QIcon messageIcon() const;
+};
+
+class ConnectionRequest : public KDevTeamworkTextMessage {
+ public:
+ enum State {
+ Waiting,
+ Denied,
+ Accepted,
+ Unknown
+ };
+
+ ConnectionRequest( const Teamwork::MessageConstructionInfo& info, const Teamwork::UserPointer& self, const Teamwork::UserPointer& target, const QString& text, KDevTeamwork* teamwork );
+
+ ConnectionRequest( InArchive& arch, const Teamwork::MessageInfo& info );
+
+ virtual void serialize( OutArchive& arch );
+
+ const Teamwork::User& user();
+
+ virtual bool needReply() const;
+
+ virtual QIcon messageIcon() const;
+
+ virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
+
+ void setState( State s );
+
+ State state();
+
+ virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
+ private:
+ DECLARE_MESSAGE( ConnectionRequest, KDevTeamworkTextMessage, 1 );
+ Teamwork::User user_;
+ State m_state;
+ SafeTeamworkEmitterPointer m_emitter;
+};
+
+BOOST_CLASS_IMPLEMENTATION( NoData, boost::serialization::object_serializable )
+
+EASY_DECLARE_MESSAGE( CollaborationMessage, TextMessage, 9, NoData, 0 );
+
+typedef SafeSharedPtr<CollaborationMessage> CollaborationMessagePointer;
+
+UserPointer userFromSession( const SessionPointer& session );
+
+typedef KDevTeamworkTextMessage KDevTeamworkMessages;
+
+//typedef Teamwork::Binder<Teamwork::AllTeamworkClientMessages, KDevTeamworkMessages >::Append<ConnectionRequest>::Result::Append<KDevSystemMessage>::Result::Append<KDevSystemMessage>::Result AllKDevTeamworkMessages;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfwd.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfwd.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfwd.h (revision 1522570)
@@ -0,0 +1,65 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef TEAMWORKFWD_H
+#define TEAMWORKFWD_H
+
+#include "lib/network/networkfwd.h"
+
+class MessageManager;
+class CollaborationManager;
+class MessageSendManager;
+class PatchesManager;
+class KUrl;
+class KDevTeamworkPlugin;
+class KDevTeamwork;
+class QStandardItemModel;
+class QTimer;
+class QListView;
+class QWidget;
+class QModeIndex;
+class MessageSerialization;
+class BoostSerialization;
+class Ui_List;
+class KDevTeamworkLogger;
+class MessageUserTab;
+class QPersistentModelIndex;
+class TeamworkFolderManager;
+class IconCache;
+class PatchesListMessage;
+class KDevSystemMessage;
+class KDevTeamworkTextMessage;
+class PatchesManagerMessage;
+
+namespace KDevelop {
+ class ICore;
+ class IDocumentController;
+ class IDocument;
+}
+
+class KDevTeamworkUser;
+typedef SafeSharedPtr< KDevTeamworkUser, BoostSerialization > KDevTeamworkUserPointer;
+class KDevTeamworkClient;
+typedef SafeSharedPtr< KDevTeamworkClient > KDevTeamworkClientPointer;
+typedef SafeSharedPtr< KDevTeamworkClient > TeamworkClientPointer;
+
+class ConnectionRequest;
+typedef SafeSharedPtr<ConnectionRequest > ConnectionRequestPointer;
+
+typedef SafeSharedPtr< KDevTeamworkTextMessage > KDevTextMessagePointer;
+typedef SafeSharedPtr< ConnectionRequest > ConnectionRequestPointer;
+typedef SafeSharedPtr< PatchesManagerMessage > PatchesManagerMessagePointer;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfwd.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.h (revision 1522570)
@@ -0,0 +1,420 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef PATCHMESSAGE
+#define PATCHMESSAGE
+
+#include <list>
+#include <string>
+#include <vector>
+#include <QObject>
+#include <QDataStream>
+#include <QByteArray>
+#include <QMetaType>
+#include <QStandardItemModel>
+#include <kurl.h>
+#include <ksharedptr.h>
+
+#include "lib/network/serialization.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/messagetypeset.h"
+#include "lib/network/easymessage.h"
+
+#include "kdevteamwork_messages.h"
+#include "utils.h"
+#include "nvp.h"
+
+#include <boost/serialization/split_member.hpp>
+
+namespace KIO {
+ class Job;
+}
+class KMimeType;
+class KJob;
+
+QStringList splitArgs( const QString& str );
+
+enum PatchAccessRights {
+ None,
+ Public,
+ ConnectedOnly,
+ Private,
+ Ask ///This means that the patch is publically visible, but on request, the owner is asked whether it really should be sent.
+};
+
+class LocalPatchSource : public SafeShared {
+
+ ///This class should be used for identification instead of just the name, because the type of comparison might change in future
+ public:
+ class Identity {
+ private:
+ string name_;
+ public:
+ Identity( const LocalPatchSource& src ) : name_(src.name) {
+ }
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & name_;
+ }
+
+ Identity() {
+ }
+
+ bool operator == ( const Identity& rhs ) const {
+ return name_ == rhs.name_;
+ }
+
+ string desc() const {
+ return name_;
+ }
+ };
+
+ enum State {
+ Applied,
+ NotApplied,
+ Unknown
+ };
+
+ string stateAsString() {
+ switch( state ) {
+ case Applied:
+ return "Applied";
+ case NotApplied:
+ return "NotApplied";
+ default:
+ return "Unknown";
+ };
+ }
+
+ Identity identity() {
+ return Identity( *this );
+ }
+ string name;
+ string filename;
+ string command;
+ string type; ///This is the mime-type that was chosen for this item
+ string applyCommand;
+ string unApplyCommand;
+ string dependencies;
+ string description;
+ string author;
+ State state;
+
+ UserIdentity userIdentity;
+ PatchAccessRights access;
+
+ LocalPatchSource() : state( Unknown ), access( Private ) {
+ }
+
+ void setFileName( const string& str ) {
+ filename = str;
+ command = "";
+ }
+
+
+ ///Tries to determine the patch-depth(by searching for -pX parameters in the apply-command. Defaults to zero.
+ uint patchDepth() const;
+
+ ///Tries to determine the tool to be used for applying the patch. Defaults to "patch"
+ string patchTool( bool reverse = false ) const;
+
+ ///Tries to determine the params for applying the patch. If none are given, uses reasonable default-parameters. If reverse is true, the unapply-parameters are given.
+ string patchParams( bool reverse = false ) const;
+
+ template<class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ KUrl u( ~filename );
+ filename = ~u.prettyUrl(); ///If there is a password, leave it out
+
+ arch & NVP( filename );
+ arch & NVP( command );
+ arch & NVP( name );
+ arch & NVP( type );
+ arch & NVP( applyCommand );
+ arch & NVP( unApplyCommand );
+ arch & NVP( dependencies );
+ arch & NVP( description );
+// arch & NVP( mimetype );
+ arch & NVP( access );
+ arch & NVP( state );
+ arch & NVP( author );
+ arch & NVP( userIdentity );
+ }
+
+ static string accessToString( PatchAccessRights access ) {
+ switch( access ) {
+ case None:
+ return "none";
+ case Public:
+ return "public";
+ case ConnectedOnly:
+ return "connected only";
+ case Private:
+ return "private";
+ case Ask:
+ return "request";
+ };
+ return "unknown";
+ }
+
+ static PatchAccessRights accessFromString( const string& txt ) {
+ if( txt == "public")
+ return Public;
+
+ if( txt == "connected only" )
+ return ConnectedOnly;
+
+ if( txt == "request" )
+ return Ask;
+
+ if( txt == "private" )
+ return Private;
+
+ return None;
+ }
+
+ string accessAsString() {
+ return accessToString( access );
+ }
+
+ bool operator == ( const LocalPatchSource& rhs ) const {
+ return name == rhs.name;
+ }
+
+ QIcon getIcon( IconCache& icons );
+
+ void setUser( const UserPointer& u ) {
+ user_ = u;
+ }
+
+ const UserPointer& user() {
+ return user_;
+ }
+
+ /*void setMimeType( KSharedPtr<KMimeType> mimeType );
+
+ KSharedPtr<KMimeType> getMimeType();*/
+
+ private:
+ UserPointer user_;
+};
+
+//BOOST_CLASS_EXPORT( LocalPatchSource )
+
+typedef SafeSharedPtr<LocalPatchSource> LocalPatchSourcePointer;
+
+
+///This message is just a base-class for all messages that should be forwarded to the PatchesListManager
+class PatchesManagerMessage : public SystemMessage
+{
+ DECLARE_MESSAGE( PatchesManagerMessage, SystemMessage, 6 );
+
+ enum Message {
+ None = 50,
+ GetPatchesList
+ };
+
+ PatchesManagerMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) {
+ }
+
+ explicit PatchesManagerMessage( const Teamwork::MessageConstructionInfo& info, Message msg = None ) : Precursor( info(this), (SystemMessage::Message)msg, "" ) {
+ }
+
+ Message message() {
+ return (Message) SystemMessage::message();
+ }
+};
+
+typedef SafeSharedPtr<PatchesManagerMessage> PatchesManagerMessagePointer;
+
+
+class PatchesListMessage : public PatchesManagerMessage
+{
+ DECLARE_MESSAGE( PatchesListMessage, PatchesManagerMessage, 1 );
+ private:
+
+ template<class Arch>
+ void serial( Arch& arch ) {
+ arch & patches;
+ }
+
+ public:
+ list<LocalPatchSource> patches;
+
+ PatchesListMessage( InArchive& arch, const Teamwork::MessageInfo& info );
+
+ PatchesListMessage( const Teamwork::MessageConstructionInfo& info, list<LocalPatchSourcePointer>& _patches ) : Precursor( info(this), None ) {
+ for( list<LocalPatchSourcePointer>::iterator it = _patches.begin(); it != _patches.end(); ++it ) {
+ LocalPatchSourcePointer::Locked l = *it;
+ if( l ) {
+ patches.push_back( *l );
+ } else {
+ ///could not lock the patch-source
+ }
+ }
+ }
+
+ virtual void serialize( OutArchive& arch );
+};
+
+class PatchRequestMessage;
+
+class PatchRequestData : public AbstractGUIMessage {
+ public:
+ enum Status {
+ Waiting,
+ Denied,
+ Accepted,
+ Failed,
+ Unknown
+ };
+
+ enum RequestType {
+ View,
+ Download,
+ Apply
+ };
+
+ explicit PatchRequestData( const LocalPatchSourcePointer& id = LocalPatchSourcePointer(), KDevTeamwork* tw = 0, RequestType req = View );
+ virtual ~PatchRequestData();
+
+ template<class Arch>
+ void serialize( Arch& arch, const uint /*version*/ ) {
+ arch & ident_;
+ arch & requestType_;
+ }
+
+ LocalPatchSource::Identity patchIdentity() {
+ return ident_;
+ }
+
+ void setStatus( Status st ) {
+ stat = st;
+ }
+
+ string patchDesc() const {
+ return ident_.desc();
+ }
+
+ RequestType requestType() const {
+ return requestType_;
+ }
+
+ ///This returns the LocalPatchSourcePointer which was used to request the patch(only valid on sender-side, to cache the apply-commands etc. for security)
+ LocalPatchSourcePointer request() const {
+ return request_;
+ }
+
+ virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
+
+ virtual QIcon messageIcon() const;
+
+ virtual QString messageText() const;
+
+ PatchRequestMessage* selfMessage() ;
+ const PatchRequestMessage* selfMessage() const;
+
+ private:
+ LocalPatchSource::Identity ident_;
+ LocalPatchSourcePointer request_;
+ RequestType requestType_;
+ protected:
+ Status stat;
+ SafeTeamworkEmitterPointer emitter;
+};
+
+EASY_DECLARE_MESSAGE_BEGIN( PatchRequestMessage, PatchesManagerMessage, 11, PatchRequestData, 3 )
+ virtual bool needReply () const { return true; }
+ virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
+END();
+
+class PatchData;
+class K3Process;
+
+///This needs a helper, because the object must be created in the same thread.
+class PatchDataReceiver : public QObject {
+ Q_OBJECT
+ PatchData* data;
+ public:
+ PatchDataReceiver( PatchData* d );
+ public slots:
+ void receivedStdout(K3Process *proc, char *buffer, int buflen);
+ void transferData( KIO::Job*, const QByteArray& );
+ void transferFinished( KJob *job );
+// void transferSpeed( KIO::Job *job, unsigned long speed );
+};
+
+
+class PatchData {
+ public:
+ explicit PatchData( const LocalPatchSourcePointer& p = LocalPatchSourcePointer(), LoggerPointer logg = LoggerPointer() );
+
+ //template<class Arch>
+ void load( InArchive& arch, const uint /*version*/ );
+
+ //template<class Arch>
+ void save( OutArchive& arch, const uint version ) const {
+ const_cast<PatchData*>(this)->saveInternal( arch, version );
+ }
+
+ void receivedStdout(K3Process *proc, char *buffer, int buflen);
+
+ ///This is only valid if the message was not created locally.
+ const QByteArray& data();
+
+ bool isBinary();
+
+ ///Here the signals from TransferJob arrive.
+ void transferData( KIO::Job*, const QByteArray& );
+
+ void transferFinished();
+
+ void transferCanceled();
+
+ LocalPatchSourcePointer patch();
+
+ BOOST_SERIALIZATION_SPLIT_MEMBER()
+ private:
+
+ //template<class Arch>
+ void saveInternal( OutArchive& arch, const uint /*version*/ );
+
+ LocalPatchSourcePointer m_patch;
+ LoggerPointer logger;
+ OutArchive* currentArchive;
+ bool errored;
+ bool deserialized, finished, isBinary_;
+ QByteArray m_data; ///When this has no content, the patch should be computed from the information in LocalPatchSource while serializing.
+ KUrl projectDir;
+
+
+ enum EntryType {
+ End,
+ BinaryHeader,
+ TextHeader,
+ Text,
+ Vector,
+ None
+ };
+
+ LoggerPrinter log( Logger::Level level = Logger::Debug ) {
+ return LoggerPrinter( logger, level ) << "PatchMessage: ";
+ }
+};
+
+EASY_DECLARE_MESSAGE( PatchMessage, PatchesManagerMessage, 6, PatchData, 2 );
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/patchmessage.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.h (revision 1522570)
@@ -0,0 +1,74 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGEUSERTAB_H
+#define MESSAGEUSERTAB_H
+
+#include <QObject>
+#include <QPointer>
+#include "autoconstructpointer.h"
+
+#include "ui_kdevteamwork_list.h"
+#include "lib/network/safesharedptr.h"
+
+class QWidget;
+class QListView;
+class QStandardItemModel;
+class KDevTeamworkUser;
+class MessageSerialization;
+typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
+
+namespace Teamwork {
+ class MessageInterface;
+ typedef SafeSharedPtr< MessageInterface, MessageSerialization > MessagePointer;
+}
+
+class KDevTeamwork;
+
+class MessageUserTab : public QObject, public Shared {
+ Q_OBJECT
+ QPointer<QWidget> m_widget;
+ QStandardItemModel* m_model;
+ QListView* m_view;
+ KDevTeamworkUserPointer m_user;
+ KDevTeamwork* m_teamwork;
+
+ /*MessageUserTab( const MessageUserTab& rhs );*/
+
+ MessageUserTab& operator = ( const MessageUserTab& rhs );
+
+ AutoConstructPointer<Ui_List> m_list;
+
+ public:
+ MessageUserTab( KDevTeamwork* tw, KDevTeamworkUserPointer user );
+
+ ~MessageUserTab();
+
+ bool operator < ( const MessageUserTab& rhs );
+
+ QStandardItemModel* model();
+
+ QListView* view() ;
+
+ KDevTeamworkUserPointer user();
+
+ QWidget* widget();
+
+ void messageUpdated( const Teamwork::MessagePointer& msg );
+
+ public slots:
+ void userStateChanged( KDevTeamworkUserPointer );
+};
+
+#endif
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp (revision 1522570)
@@ -0,0 +1,258 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "teamworkfoldermanager.h"
+#include <interfaces/icore.h>
+#include "kdevteamworkplugin.h"
+#include <kio/netaccess.h>
+#include <krandom.h>
+#include <QStringList>
+#include <QFileInfo>
+#include <QFile>
+#include <QDateTime>
+#include <kdebug.h>
+#include <kurl.h>
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+TeamworkFolderManager* TeamworkFolderManager::m_self = 0;
+
+KUrl TeamworkFolderManager::workspaceDirectory() {
+ return m_self->m_workspaceDir;
+}
+
+TeamworkFolderManager::TeamworkFolderManager( const KUrl& directory ) {
+ m_self = this;
+
+ KUrl u = directory;
+ u.cleanPath();
+
+ m_workspaceDir = u;
+ u.addPath( ".teamwork" );
+ u.cleanPath();
+ m_teamworkDir = u;
+}
+
+TeamworkFolderManager* TeamworkFolderManager::self() {
+ return m_self;
+}
+
+KUrl TeamworkFolderManager::teamworkAbsolute( const QString& subDirectory, const QString& subFolder ) {
+ KUrl ret( self()->m_teamworkDir );
+ ret.addPath( subFolder );
+ if( subDirectory.startsWith( ret.toLocalFile() ) ) return subDirectory;
+ ret.addPath( subDirectory );
+ ret.cleanPath();
+ return ret;
+}
+
+KUrl TeamworkFolderManager::workspaceAbsolute( const QString& subDirectory, const QString& subFolder ) {
+ KUrl ret( self()->m_workspaceDir );
+ ret.addPath( subFolder );
+ if( subDirectory.startsWith( ret.toLocalFile() ) ) return subDirectory;
+ ret.addPath( subDirectory );
+ ret.cleanPath();
+ return ret;
+}
+
+void TeamworkFolderManager::createTeamworkFolder() throw(QString) {
+ KUrl ul = self()->m_workspaceDir;
+
+ ul.addPath( ".teamwork" );
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ if( !KIO::NetAccess::mkdir( ul, 0 ) )
+ throw QString( "could not create \"%1\"" ).arg( ul.prettyUrl() );
+}
+
+
+KUrl TeamworkFolderManager::createUniqueDirectory( const QString& subFolder, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
+ if( self()->m_workspaceDir.isEmpty() )
+ throw QString( "no teamwork-workspace-directory set" );
+ KUrl ul = self()->m_workspaceDir;
+
+ ul.addPath( ".teamwork" );
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ KIO::NetAccess::mkdir( ul, 0 );
+
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ throw QString( "could not create .teamwork-directory" );
+
+
+ QStringList sub = subFolder.split( "/" );
+ while( !sub.isEmpty() ) {
+ ul.addPath( sub.front() );
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ KIO::NetAccess::mkdir( ul, 0 );
+
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ throw QString( "could not create directory %1 directory" ).arg( ul.prettyUrl() );
+
+ sub.pop_front();
+ }
+
+
+ KUrl nu = ul;
+ nu.addPath( namePrefix + name + nameSuffix );
+ nu.cleanPath();
+
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
+ KIO::NetAccess::mkdir( nu, 0 );
+
+ if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
+ return nu;
+ }
+
+ ///If the file exists try it with additional date/time
+ nu = ul;
+ nu.addPath( namePrefix + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix );
+
+ nu.cleanPath();
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ) {
+ KIO::NetAccess::mkdir( nu, 0 );
+
+ if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
+ return nu;
+ }
+
+ ///If even this file exists, add a suffix behind the date
+ for( int a = 0; a < 100; a++ ) {
+ nu = ul;
+ nu.addPath( namePrefix + QString("_%1_").arg( a ) + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix );
+ nu.cleanPath();
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
+ KIO::NetAccess::mkdir( nu, 0 );
+
+ if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
+ return nu;
+ }
+ }
+
+ throw QString( "failed to allocate filename for %1" ).arg( name + "." + nameSuffix );
+}
+
+KUrl TeamworkFolderManager::createUniqueFile( const QString& subFolder, const QString& extension, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
+ if( self()->m_workspaceDir.isEmpty() )
+ throw QString( "no teamwork-workspace-directory set" );
+ KUrl ul = self()->m_workspaceDir;
+
+ ul.addPath( ".teamwork" );
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ KIO::NetAccess::mkdir( ul, 0 );
+
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ throw QString( "could not create .teamwork-directory" );
+
+
+ QStringList sub = subFolder.split( "/" );
+ while( !sub.isEmpty() ) {
+ ul.addPath( sub.front() );
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ KIO::NetAccess::mkdir( ul, 0 );
+
+ if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
+ throw QString( "could not create directory %1 directory" ).arg( ul.prettyUrl() );
+
+ sub.pop_front();
+ }
+
+
+ KUrl nu = ul;
+ nu.addPath( namePrefix + name + nameSuffix + "." + extension );
+
+ nu.cleanPath();
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
+ if( createFile( nu ) )
+ return nu;
+ }
+
+ ///If the file exists try it with additional date/time
+ nu = ul;
+ nu.addPath( namePrefix + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix + "." + extension );
+
+ nu.cleanPath();
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ) {
+ if( createFile( nu ) )
+ return nu;
+ }
+
+ ///If even this file exists, add a suffix behind the date
+ for( int a = 0; a < 100; a++ ) {
+ nu = ul;
+ nu.addPath( namePrefix + QString("_%1_").arg( a ) + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix + "." + extension );
+ nu.cleanPath();
+ if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
+ if( createFile( nu ) )
+ return nu;
+ }
+ }
+
+ throw QString( "failed to allocate filename for %1" ).arg( name + "." + nameSuffix );
+}
+
+KUrl TeamworkFolderManager::createUniqueFile( const QString& subFolder, const QString& fileName, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
+ QFileInfo i( fileName );
+ KUrl u( subFolder );
+ u.addPath( i.path() );
+ return createUniqueFile( u.toLocalFile(), i.completeSuffix(), i.baseName(), namePrefix, nameSuffix );
+}
+
+void TeamworkFolderManager::registerTempItem( const KUrl& u ) {
+ if( u.isRelative() )
+ self()->m_tempItems[teamworkAbsolute(u.toLocalFile()).pathOrUrl()] = true;
+ else
+ self()->m_tempItems[u.pathOrUrl()] = true;
+}
+
+QString TeamworkFolderManager::teamworkRelative( const KUrl& url, const QString& subfolder ) {
+ KUrl u = self()->m_teamworkDir;
+ u.addPath( subfolder );
+ u.adjustPath( KUrl::AddTrailingSlash );
+ return KUrl::relativeUrl( u, url );
+}
+
+QString TeamworkFolderManager::workspaceRelative( const KUrl& url, const QString& subfolder ) {
+ KUrl u = self()->m_workspaceDir;
+ u.addPath( subfolder );
+ u.adjustPath( KUrl::AddTrailingSlash );
+ //kDebug(9500) << "workspaceRelative(" << url << "," << subfolder << ") called. Worspace:" << self()->m_workspaceDir << "base:" << u << "result:" << KUrl::relativeUrl( u, url );
+ return KUrl::relativeUrl( u, url );
+}
+
+TeamworkFolderManager::~TeamworkFolderManager() {
+ for( QMap< QString, bool >::iterator it = m_tempItems.begin();it != m_tempItems.end(); ++it ) {
+ ///First, make sure that the file is really a subfolder of the .teamwork-directory
+ KUrl f( it.key() );
+ f.cleanPath();
+ if( (f.path()).startsWith( m_teamworkDir.path(KUrl::AddTrailingSlash) ) && (f.pathOrUrl()).startsWith( m_teamworkDir.pathOrUrl() ) ) {
+ if( ! KIO::NetAccess::del( f, 0 ) )
+ kDebug(9500) << "TeamworkFolderManager error: File" << f.prettyUrl() << "could not be deleted";
+ } else {
+ kDebug(9500) << "TeamworkFolderManager error: File" << f.prettyUrl() << "was registered as temporary file, but is not in folder" << m_teamworkDir;
+ }
+ }
+ m_tempItems.clear();
+}
+
+///@todo use netaccess!
+bool TeamworkFolderManager::createFile( const KUrl& url ) {
+ QFile f( url.path() );
+ if( f.open(QIODevice::WriteOnly) )
+ return true;
+ else
+ return false;
+}
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.h (revision 1522570)
@@ -0,0 +1,187 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef DOCUMENT_WRAPPER_H
+#define DOCUMENT_WRAPPER_H
+
+#include <QObject>
+#include <QFile>
+
+#include <KParts/MainWindow>
+#include <map>
+#include <string>
+
+#include "lib/dynamictext/vectortimestamp.h"
+#include "lib/dynamictext/flexibletextnotifier.h"
+#include "lib/network/safesharedptr.h"
+#include "lib/network/weaksafesharedptr.h"
+#include "safelogger.h"
+
+#include <autoconstructpointer.h>
+#include "filesynchronizemessage.h"
+
+namespace Teamwork {
+class Logger;
+typedef SafeSharedPtr<Logger> LoggerPointer;
+}
+
+namespace KTextEditor {
+class Document;
+class Range;
+}
+
+class FileSynchronize;
+class DynamicText;
+class QStandardItemModel;
+class QModelIndex;
+class QMenu;
+class QVariant;
+class DocumentWrapperTreeAction;
+namespace KDevelop {
+class IDocument;
+}
+class DocumentWrapperMessage;
+class QDynamicText;
+class FileCollaborationSession;
+class LocalPatchSource;
+class K3Process;
+
+using namespace Teamwork;
+
+typedef SafeSharedPtr<LocalPatchSource> LocalPatchSourcePointer;
+typedef SharedPtr<QDynamicText, BoostSerializationNormal> QDynamicTextPointer;
+
+class OutputFileWriter : public QObject {
+ Q_OBJECT
+ public:
+ OutputFileWriter( const QString& file );
+ bool failed() const;
+ public slots:
+ void receivedStdout(K3Process *proc, char *buffer, int buflen);
+ private:
+ QFile m_file;
+ bool m_failed;
+};
+
+///A class that cares about the state of a document and it's history
+class DocumentWrapper : public QObject, public SafeLogger, public Shared, public SumTree::FlexibleTextNotifier<std::string> {
+ Q_OBJECT
+ public:
+ ///If readFile is true, the file is read from disk. Else we wait for the file from the other side. May throw QString on error.
+ BIND_LIST_3( Messages, FileEditMessage, FileEditRejectMessage, FileSynchronize )
+
+ DocumentWrapper( uint id, const LoggerPointer& logger, QString fileName, uint ownIndex, bool readFile, FileCollaborationSession* session, bool fromBuffer );
+
+ QString fileName() const;
+
+ KDevelop::IDocument* document();
+
+ void updateTree( QModelIndex& i, QStandardItemModel* model );
+
+ void fillContextMenu( int var, QMenu* menu );
+
+ bool hadError() const;
+
+ QString text() const;
+
+ VectorTimestamp state() const;
+
+ const QDynamicText& dynamicText() const;
+
+ ///Returns an id that is unique within the wrapper's parent-session, and is equal on all collaborating peers.
+ uint id() const;
+
+ void processMessage( DocumentWrapperMessage* msg );
+
+ ///If the document-wrapper is dead, that means the it is not part of the session anymore
+ void setDead( bool dead );
+
+ bool dead() const;
+ ///This can be usedto completely disable the file(no editing is allowed anymore)
+ void setDisabled( bool disabled );
+
+ bool disabled() const;
+
+ QIcon icon() const;
+
+ bool synchronize( const UserPointer& user );
+
+ signals:
+ void publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender );
+
+ public slots:
+ void saveAsBufferFile();
+ LocalPatchSourcePointer saveAsPatch( bool addToList = true, bool edit = true );
+
+ private slots:
+ void remove();
+ void toggleEnabled();
+ void saveNewBuffer();
+ void manageDynamicText();
+
+ void stateChanged();
+ void documentDestroyed();
+ void textChanged ( KTextEditor::Document * document,
+ const KTextEditor::Range & oldRange,
+ const KTextEditor::Range & newRange );
+ void textRemoved ( KTextEditor::Document * document,
+ const KTextEditor::Range & range );
+ void textInserted ( KTextEditor::Document * document,
+ const KTextEditor::Range & range );
+ private:
+ ///Notifications from FlexibleText
+ virtual void notifyFlexibleTextErase( int position, int length );
+ virtual void notifyFlexibleTextInsert( int position, const std::string& text );
+ virtual void notifyFlexibleTextReplace( int position, int length, const std::string& replacement );
+
+
+ int receiveMessage( FileEditMessage* msg );
+ int receiveMessage( FileSynchronize* msg );
+ int receiveMessage( FileEditRejectMessage* msg );
+ int receiveMessage( MessageInterface* msg );
+
+ bool checkDocumentSync() const; ///Expensive, only for debugging
+
+ void fillDocumentText();
+ void openDocument( bool toForeground = false );
+
+ ///If fromBuffer is true, it is tried to get the content from an already open buffer (@todo)
+ void readFile( bool fromBuffer ) throw ( QString );
+
+ virtual std::string logPrefix();
+
+ QDynamicTextPointer m_text;
+
+ bool m_block;
+
+ bool m_realFile;
+ QString m_fileName; ///Relative path of the file(from project-dir)
+ KDevelop::IDocument* m_document;
+ WeakSharedPtr<FileCollaborationSession> m_session;
+ uint m_ownIndex;
+ uint m_id;
+ bool m_hadError, m_disabled, m_dead;
+
+ QString m_tempFile;
+
+ friend class DocumentWrapperTreeAction;
+
+ friend class MessageDispatcher< DocumentWrapper, Messages > ;
+ MessageDispatcher< DocumentWrapper, Messages > m_dispatcher;
+};
+
+typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/documentwrapper.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp (revision 1522570)
@@ -0,0 +1,283 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "filecollaboration.h"
+#include <QAction>
+#include <QMenu>
+#include <QFileInfo>
+#include <QStandardItemModel>
+#include <QModelIndex>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/cursor.h>
+
+#include "filecollaborationmanager.h"
+#include "kdevteamwork_user.h"
+#include "kdevutils.h"
+#include "documentwrapper.h"
+#include "kdevteamwork_helpers.h"
+
+#include "lib/dynamictext/verify.h"
+#include "lib/network/messagesendhelper.h"
+#include "lib/network/messagetypeset.h"
+
+
+
+FileCollaboration::FileCollaboration( KDevTeamworkUserPointer user, FileCollaborationSession* session, const FileCollaborationRequestPointer& request ) : SafeLogger( session->manager() ->teamwork() ->logger() ), m_user( user ), m_session( session ), /*m_dispatcher( *this ),*/ m_index( 0 ), m_connectionActive( false ), m_userConnected( false ), m_invited( false ) {
+ connect( session->manager(), SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
+
+ KDevTeamworkUserPointer::Locked l = user;
+ if ( !l )
+ throw QString( "in FileCollaboration(): could not lock user" );
+
+ connect( l.data(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
+
+ m_userName = ~l->User::name();
+
+ if ( !l->online().session() )
+ throw QString( "in FileCollaboration(): user is not online" );
+
+ if ( !request ) {
+ m_index = session->allocateIndex(); ///Create a new index
+ } else {
+ FileCollaborationRequestPointer::Locked lr = request;
+ if ( !lr )
+ throw QString( "could not lock request-message" );
+ m_index = lr->senderIndex(); ///The other side is the master, so the index is zero.
+ }
+
+ invite( request, false );
+}
+
+uint FileCollaboration::primaryIndex() const {
+ return m_index;
+}
+
+std::string FileCollaboration::logPrefix() {
+ return ~( "FileCollaboration(" + m_userName + ", " + m_session->name() + "): " );
+}
+
+void FileCollaboration::processMessage( const MessagePointer& msg ) {
+ MessagePointer::Locked l = msg;
+ if ( l ) {
+ //m_dispatcher( l );
+ } else {
+ err() << "could not lock a message";
+ }
+}
+/*
+int FileCollaboration::receiveMessage( MessageInterface* msg ) {
+ out( Logger::Warning ) << "got unknown message of type" << msg->name();
+ return 0;
+}
+
+int FileCollaboration::receiveMessage( FileCollaborationMessage* msg ) {
+ ///@todo clean/remove
+ out( Logger::Debug ) << "got FileCollaborationMessage";
+ if ( msg->isDerived() ) {
+ out( Logger::Warning ) << "dispatched a message of type" << msg->name() << "as FileCollaborationMessage";
+ return 0;
+ }
+ try {
+ switch ( msg->message() ) {
+ case FileCollaborationMessageData::Synchronize: {
+ if ( !msg->messageData().canConvert<QString>() )
+ throw "wrong messageData in Synchronize-request(cannot extract filename)";
+ QString fileName = msg->messageData().value<QString>();
+
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if ( !l )
+ throw "could not lock user";
+
+ if ( !l->online().session() )
+ throw "user is not online";
+
+ if ( !l->online().session().unsafe() ->isOk() )
+ throw "user is not online, session is dead";
+
+ }
+ break;
+ default:
+ out( Logger::Warning ) << "got unhandled FileCollaborationMessage with message" << msg->messageAsString();
+ break;
+ }
+ } catch ( const QString & str ) {
+ err() << "in receiveMessage( FileCollaborationMessage* ):" << str;
+ } catch ( const char * str ) {
+ err() << "in receiveMessage( FileCollaborationMessage* ):" << str;
+ }
+ return 0;
+}
+
+int FileCollaboration::receiveMessage( FileCollaborationRequest* msg ) {
+ out( Logger::Debug ) << "got FileCollaborationRequest";
+ return 0;
+}*/
+
+bool FileCollaboration::connectionActive() const {
+ return m_connectionActive;
+}
+
+void FileCollaboration::userStateChanged() {
+ try {
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if ( !l )
+ throw "could not lock user";
+
+ if ( l->online() && l->online().session().unsafe() ->isOk() ) {
+ if ( !m_userConnected ) {
+ ///Automatically re-invite the user to connect
+ invite( 0, true );
+ }
+ } else {
+ m_connectionActive = false;
+ m_userConnected = false;
+
+ emit connectionResult( this, false );
+ }
+ } catch ( const QString & str ) {
+ err() << "error in userStateChanged():" << str;
+ } catch ( const char * str ) {
+ err() << "error in userStateChanged():" << str;
+ }
+}
+
+void FileCollaboration::slotConnectionResult( bool result ) {
+ out( Logger::Debug ) << "slotConnectionResult" << result;
+ m_userConnected = result;
+ if ( result )
+ m_connectionActive = true;
+ else
+ m_connectionActive = false;
+ emit connectionResult( this, result );
+}
+
+KDevTeamworkUserPointer FileCollaboration::user() const {
+ return m_user;
+}
+
+FileCollaborationSessionPointer FileCollaboration::session() const {
+ return m_session;
+}
+
+void FileCollaboration::slotFillCollaboratingUserMenu( QMenu * /*menu*/, const UserPointer & /*user*/ ) {}
+
+bool FileCollaboration::invited() const {
+ return m_invited;
+}
+
+void FileCollaborationUserTreeAction::doubleClicked() {
+ if ( target )
+ target->doubleClicked();
+}
+
+void FileCollaborationUserTreeAction::fillContextMenu( QMenu* menu ) {
+ if ( target )
+ target->fillContextMenu( var, menu );
+}
+
+void FileCollaboration::fillContextMenu( int /*i*/, QMenu* menu ) {
+ KDevTeamwork::self()->fillUserMenu( menu, user().cast<User>() );
+ if( m_session->isMasterSession() ) {
+ menu->addAction( m_session->getRemoveUserAction( m_user.cast<User>() ) );
+ menu->addSeparator();
+ }
+}
+
+void FileCollaboration::doubleClicked() {
+ if ( m_user ) {
+ KDevTeamwork::self() ->guiSendMessageTo( m_user );
+ }
+}
+
+void FileCollaboration::invite( const FileCollaborationRequestPointer& request, bool automatic ) throw( QString ) {
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if ( !l )
+ throw QString( "in FileCollaboration(): could not lock user" );
+
+ LockedSharedPtr<FileCollaborationRequest> lmsg = new FileCollaborationRequest( globalMessageTypeSet(), this, m_index, m_session->primaryIndex(), m_session->id() );
+ if ( !lmsg )
+ throw QString( "in FileCollaboration(): could not create message" );
+
+ Q_VERIFY_SAME( lmsg->sessionId(), m_session->id() );
+ Q_VERIFY_SAME( lmsg->index(), m_index );
+
+ if ( automatic ) {
+ if ( m_index != 0 ) {
+ out( Logger::Info ) << "re-inviting user to join the session";
+ } else {
+ out( Logger::Info ) << "inviting session-host to continue the session";
+ }
+
+ lmsg->setAutomatic( true );
+ }
+
+ m_request = lmsg.freeCast<FileCollaborationRequest>();
+
+
+ if ( request ) {
+ ///When answering to a request, this will tell the other side that the request was accepted.
+ LockedSharedPtr<FileCollaborationRequest> lrequest = request;
+ if ( !lrequest )
+ throw QString( "in FileCollaboration(): could not lock request" );
+
+ lmsg->info().setReply( lrequest->info().uniqueId() );
+ lmsg->info().setReplyMessage( request );
+ } else {
+ m_invited = true;
+ }
+ l->online().session().unsafe() ->send( lmsg );
+
+ if ( !request && !automatic ) {
+ m_session->manager() ->teamwork() ->addMessageToList( lmsg.data() );
+ }
+
+}
+
+void FileCollaboration::close( const QString & /*reason*/ ) {
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if ( l && l->online().session() ) {
+ l->online().session().unsafe()->send( new FileCollaborationMessage( globalMessageTypeSet(), m_session->id(), FileCollaborationMessageData::CloseSession ) );
+ }
+}
+
+QIcon FileCollaboration::icon() const {
+ if( m_connectionActive ) {
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if( l )
+ return l->icon();
+ else
+ return QIcon();
+ } else
+ return IconCache::getIconStatic( "fileusercollaboration_inactive" );
+}
+
+void FileCollaboration::updateTree( QModelIndex& i, QStandardItemModel* model ) {
+ KDevTeamworkUserPointer::Locked l = user();
+ if ( !l ) {
+ model->setData( i, "lost user", Qt::DisplayRole );
+ model->setData( i, QIcon(), Qt::DecorationRole ); ///Maybe use some other icons indicating the state of the collaboration
+ } else {
+ model->setData( i, ~l->User::name(), Qt::DisplayRole );
+ model->setData( i, icon(), Qt::DecorationRole ); ///Maybe use some other icons indicating the state of the collaboration
+ QVariant v;
+ v.setValue<CollaborationTreeActionPointer>( new FileCollaborationUserTreeAction( this ) );
+ model->setData( i, v, Qt::UserRole );
+ }
+}
+
+
+#include "filecollaboration.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp (revision 1522570)
@@ -0,0 +1,789 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "filecollaborationsession.h"
+
+Q_DECLARE_METATYPE( Teamwork::UserPointer )
+
+#include <sstream>
+#include <QAction>
+#include <QMenu>
+#include <QTimer>
+#include <QStandardItemModel>
+#include <QModelIndex>
+
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+
+#include <krandom.h>
+#include <ktexteditor/document.h>
+#include <ktexteditor/cursor.h>
+
+#include "lib/network/messagesendhelper.h"
+#include "lib/network/messagetypeset.h"
+
+#include "filecollaborationmanager.h"
+#include "lib/dynamictext/vectortimestamp.h"
+#include "kdevteamwork_user.h"
+#include "kdevteamworkplugin.h"
+#include "documentwrapper.h"
+#include "patchesmanager.h"
+#include "kdevteamwork_helpers.h"
+
+
+#include "filesynchronizemessage.h"
+#include "teamworkfoldermanager.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+using namespace KDevelop;
+
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationPointer, FileCollaborationPointer, 0, value )
+CROSSMAP_KEY_EXTRACTOR( FileCollaborationPointer, UserPointer, 0, value->user() )
+
+CROSSMAP_KEY_EXTRACTOR( DocumentWrapperPointer, QString, 0, value->fileName() )
+CROSSMAP_KEY_EXTRACTOR( DocumentWrapperPointer, uint, 0, value->id() )
+
+FileCollaborationSession::FileCollaborationSession( QString name, CollabFileList files, FileCollaborationManager* manager, uint primaryIndex, CollabSessionId id ) :
+ SafeLogger( manager->teamwork() ->logger(), "in FileCollaborationSession:" ),
+ m_manager( manager ),
+ m_allowSentDocuments( false ),
+ m_isMasterSession( primaryIndex == 0 ),
+ m_primaryIndex( primaryIndex ),
+ m_indexCount( primaryIndex ? 0 : 1 ),
+ m_wrapperIndexCount( primaryIndex ? 0 : 1 ),
+ m_name( name ),
+ m_dispatcher( *this ) {
+ m_publishFileListTimer = new QTimer( this );
+ connect( m_publishFileListTimer, SIGNAL( timeout() ), this, SLOT( slotPublishFileList() ) );
+ m_publishFileListTimer->setSingleShot( true );
+ m_stateChangeTimer = new QTimer( this );
+ connect( m_stateChangeTimer, SIGNAL( timeout() ), this, SLOT( publishStateChange() ) );
+ m_publishFileListTimer->setSingleShot( true );
+
+ connect( m_manager, SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
+
+ m_removeUserAction = new QAction( IconCache::getIconStatic( "remove" ), "Remove User", this );
+ connect( m_removeUserAction, SIGNAL( triggered( bool ) ), this, SLOT( removeUserAction() ) );
+
+ if ( id != 0 )
+ m_id = id;
+ else {
+ QString str = KRandom::randomString( 8 ).toLatin1();
+ m_id = *( ( CollabSessionId* ) & ( str.toAscii().data() [ 0 ] ) ); ///Not a good way of generating a 64-bit random-number..
+ }
+
+ out( Logger::Debug ) << "starting session";
+
+ for ( CollabFileList::iterator it = files.begin(); it != files.end(); ++it ) {
+ addFileInternal( *it, true, m_isMasterSession );
+ }
+
+}
+
+void FileCollaborationSession::slotConnectionResult( FileCollaboration* collab, bool result ) {
+ if ( result && collab->invited() ) {
+ for ( FileSet::Iterator it = m_files.values(); it; ++it ) {
+ synchronizeFile( collab, *it );
+ }
+ }
+
+ emit stateChanged( this );
+}
+
+void FileCollaborationSession::setAllowSentDocuments( bool allow ) {
+ m_allowSentDocuments = allow;
+}
+
+
+bool FileCollaborationSession::synchronizeFile( const FileCollaborationPointer& collab, const DocumentWrapperPointer& wrapper ) {
+ return wrapper->synchronize( collab->user() );
+}
+
+QStringList FileCollaborationSession::plainFileNames() const {
+ QStringList ret;
+ for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it )
+ ret << ( *it ).second.value->fileName();
+ return ret;
+}
+
+QList<uint> FileCollaborationSession::plainIds() const {
+ QList<uint> ret;
+ for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it )
+ ret << ( *it ).second.value->id();
+ return ret;
+}
+
+void FileCollaborationSession::removeUserAction() {
+ try {
+ QAction* act = qobject_cast<QAction*>( sender() );
+ if( !act ) throw "no sender-action";
+
+ QVariant v = act->data();
+ UserPointer u = v.value<UserPointer>();
+ if( !u ) throw "could not get user";
+
+ FileCollaborationPointer collab = m_collaborations.value( u );
+ if( !collab ) throw "no file-collaboration for the specified user";
+
+ removeCollaboration( collab );
+ } catch( const char* str ) {
+ err() << "removeUserAction:" << str;
+ } catch( const QString& str ) {
+ err() << "removeUserAction:" << str;
+ }
+}
+
+void FileCollaborationSession::removeCollaboration( const FileCollaborationPointer& collab ) {
+ collab->close( "goodbye" );
+ m_collaborations.remove( collab );
+ emit stateChanged( this );
+}
+
+
+CollabFileList FileCollaborationSession::fileNames() const {
+ CollabFileList ret;
+ for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it ) {
+ ret.push_back( CollabFile( ( *it ).second.value->id(), ( *it ).second.value->fileName() ) );
+ }
+ return ret;
+}
+
+const FileCollaborationSession::FileSet& FileCollaborationSession::files() const {
+ return m_files;
+}
+
+
+void FileCollaborationSession::fillContextMenu( int /*i*/, QMenu* menu ) {
+ IDocument * d = KDevTeamworkPlugin::staticDocumentController() ->activeDocument();
+ if ( d && d->textDocument() ) {
+ KUrl u = TeamworkFolderManager::workspaceRelative( d->url() );
+
+ if ( !m_files.values( u.toLocalFile() ) )
+ menu->addAction( "Add Current File", this, SLOT( addFile() ) );
+ }
+ QMenu* m = new QMenu( menu );
+ m->setTitle( "Save Result" );
+ m->addAction( "As Files", this, SLOT( saveAsFiles() ) );
+ m->addAction( "As Patch", this, SLOT( saveAsPatch() ) );
+ menu->addSeparator();
+ FileSet::Iterator it = m_files.values();
+ if ( m_isMasterSession && it ) {
+ while ( it && ( *it ) ->dead() )
+ ++it;
+ if ( it ) {
+ if ( ( *it ) ->disabled() )
+ menu->addAction( "Enable Editing", this, SLOT( enableEditing() ) );
+ else
+ menu->addAction( "Disable Editing", this, SLOT( disableEditing() ) );
+ }
+ }
+ m = new QMenu( menu );
+ m->setTitle( "Remove" );
+ m->addAction( "All Users", this, SLOT( stopSession() ) );
+ m->addAction( "All Files", this, SLOT( removeAllFilesSession() ) );
+ menu->addSeparator();
+ menu->addAction( "Close", this, SLOT( closeSession() ) );
+}
+
+bool FileCollaborationSession::acceptMessage( const FileCollaborationRequestPointer& msg ) {
+ try {
+ FileCollaborationRequestPointer::Locked l = msg;
+ if ( !l )
+ throw "could not lock message";
+
+ KDevTeamworkUserPointer u = l->info().user().cast<KDevTeamworkUser>();
+ if ( !u )
+ throw "message has no user";
+
+ FileCollaborationPointer collab = newCollaboration( u, msg );
+ if ( !collab )
+ throw "could not create collaboration";
+
+ return true;
+ } catch ( const QString & str ) {
+ err() << "error in acceptMessage:" << str;
+ return false;
+ } catch ( const char * str ) {
+ err() << "error in acceptMessage:" << str;
+ return false;
+ }
+ return false;
+}
+
+DocumentWrapperPointer FileCollaborationSession::getDocument( const QString& fileName ) {
+ if ( ! m_files.values( fileName ) ) {
+ out( Logger::Warning ) << "getDocument: Document-wrapper for a file not being collaborated was requested:" << fileName;
+ return 0;
+ }
+
+ return m_files[ fileName ];
+}
+
+std::string FileCollaborationSession::logPrefix() {
+ ostringstream str;
+ str << "FileCollaborationSession(" << name() << "," << id() << "): ";
+ return str.str();
+}
+
+FileCollaborationPointer FileCollaborationSession::newCollaboration( const KDevTeamworkUserPointer & u, const FileCollaborationRequestPointer& request ) {
+ try {
+ FileCollaborationPointer ret = new FileCollaboration( u, this, request );
+ connect( ret, SIGNAL( connectionResult( FileCollaboration*, bool ) ), this, SLOT( slotConnectionResult( FileCollaboration*, bool ) ) );
+ m_collaborations.insert( ret );
+ return ret;
+ } catch ( const QString & str ) {
+ err() << "error while creating file-collaboration:" << str;
+ return 0;
+ }
+}
+
+void FileCollaborationSession::updateTree( QModelIndex& i, QStandardItemModel* model ) {
+ QMap<DocumentWrapperPointer, QPersistentModelIndex> positions;
+ QMap<FileCollaborationPointer, QPersistentModelIndex> userPositions;
+ try {
+ if ( model->columnCount( i ) == 0 )
+ model->insertColumn( 0, i );
+ ///Locate all files that are already there
+ for ( int a = model->rowCount( i ) - 1; a >= 0; a-- ) {
+ QModelIndex ind = model->index( a, 0, i );
+ QVariant v = model->data( ind, Qt::UserRole );
+ if ( v.canConvert<CollaborationTreeActionPointer>() ) {
+ StandardCollaborationTreeAction<DocumentWrapper>* d = dynamic_cast< StandardCollaborationTreeAction<DocumentWrapper>* >( v.value<CollaborationTreeActionPointer>().data() );
+ if ( d && d->target ) {
+ if ( m_files.values<DocumentWrapperPointer>( ( DocumentWrapper* ) d->target ) ) {
+ positions[ ( DocumentWrapper* ) d->target ] = ind;
+ } else {
+ ///Remove the old item
+ model->removeRow( a, i );
+ }
+ }
+ FileCollaborationUserTreeAction * userAction = dynamic_cast< FileCollaborationUserTreeAction* >( v.value<CollaborationTreeActionPointer>().data() );
+ if( userAction ) {
+ if( userAction->target && m_collaborations.value( (FileCollaborationPointer)userAction->target ) ) {
+ ///user is still collaborating
+ userPositions[(FileCollaborationPointer)userAction->target] = ind;
+ } else {
+ ///User must be removed
+ model->removeRow( a, i );
+ }
+ }
+ } else {
+ model->removeRow( a, i );
+ err() << "unexepected entry-type in tree, removing";
+ }
+ }
+ ///Add missing files
+ for ( FileSet::ValueMap::iterator it = m_files.begin(); it != m_files.end(); ++it ) {
+ if ( !positions.contains( ( *it ).second.value ) ) {
+ model->insertRow( 0, i ); ///Documents are inserted at the top, users at the bottom.
+ QModelIndex ind = model->index( 0, 0, i );
+ ;
+ if ( !ind.isValid() )
+ throw "index-error";
+ positions[ ( *it ).second.value ] = ind;
+ }
+ }
+
+ ///Add missing users
+ for( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
+ if ( !userPositions.contains( *it ) ) {
+ int num = model->rowCount( i );
+ model->insertRow( num, i );
+ QModelIndex ind = model->index( num, 0, i );
+
+ if ( !ind.isValid() )
+ throw "index-error";
+ userPositions[ *it ] = ind;
+ }
+ }
+
+ ///Update documents
+ for ( QMap<DocumentWrapperPointer, QPersistentModelIndex>::iterator it = positions.begin(); it != positions.end(); ++it ) {
+ QModelIndex i( *it );
+ const_cast<DocumentWrapperPointer&>( it.key() ) ->updateTree( i, model );
+ }
+
+ ///Update users
+ for ( QMap<FileCollaborationPointer, QPersistentModelIndex>::iterator it = userPositions.begin(); it != userPositions.end(); ++it ) {
+ QModelIndex i(*it);
+ it.key()->updateTree( i , model );
+
+ }
+
+ } catch ( const char * str ) {
+ err() << "in updateTree:" << str;
+ } catch ( const QString & str ) {
+ err() << "in updateTree:" << str;
+ }
+}
+
+QIcon FileCollaborationSession::icon() const {
+ if ( state() == Finished )
+ return IconCache::getIconStatic( "collaboration_session_finished" );
+ else {
+ if ( !m_isMasterSession ) {
+ CollaborationSet::Iterator it = m_collaborations.values();
+ if ( !( *it ) ->connectionActive() )
+ return IconCache::getIconStatic( "collaboration_session_connectionlost" );
+ }
+ return IconCache::getIconStatic( "collaboration_session" );
+ }
+}
+
+bool FileCollaborationSession::isMasterSession() const {
+ return m_isMasterSession;
+}
+
+uint FileCollaborationSession::primaryIndex() const {
+ return m_primaryIndex;
+}
+
+FileCollaborationSession::State FileCollaborationSession::state() const {
+ if ( !m_collaborations.empty() )
+ return Running;
+ return Finished;
+}
+
+bool FileCollaborationSession::removeFile( uint id ) {
+ DocumentWrapperPointer wrapper = m_files[ id ];
+ if ( !wrapper )
+ return false;
+ ///@todo ask if content should be saved or if the file should stay completely
+ m_files.remove( wrapper );
+
+ publishFileRemove( id );
+ m_stateChangeTimer->start( 100 );
+ return true;
+}
+
+bool FileCollaborationSession::killFile( uint id ) {
+ DocumentWrapperPointer wrapper = m_files[ id ];
+ if ( !wrapper )
+ return false;
+ ///@todo ask if content should be saved or if the file should stay completely
+ wrapper->setDisabled( true );
+ wrapper->setDead( true );
+
+ m_stateChangeTimer->start( 100 );
+ return true;
+}
+
+uint FileCollaborationSession::addFileInternal( const CollabFile& f, bool fromBuffer, bool readFile ) {
+ try {
+ if ( f.id > m_wrapperIndexCount )
+ m_wrapperIndexCount = f.id + 1;
+ QString file = f.file;
+ /*if ( KDevCore::projectController() ->activeProject() ) {
+ KUrl u( file );
+
+ if ( u.isParentOf( KDevCore::projectController() ->activeProject() ->projectDirectory() ) ) {
+ QString d = KDevCore::projectController() ->activeProject() ->projectDirectory().toLocalFile();
+ if( !d.endsWith( "/" ) ) d += "/";
+ file = KUrl::relativeUrl( d, u );
+ }
+ }*/
+
+ DocumentWrapperPointer p = new DocumentWrapper( f.id, m_manager->teamwork() ->logger(), file, m_primaryIndex, readFile, this, fromBuffer );
+ connect( p.data(), SIGNAL( publishEdit( const VectorTimestamp&, const SimpleReplacement&, DocumentWrapper* ) ), this, SLOT( publishEdit( const VectorTimestamp&, const SimpleReplacement&, DocumentWrapper* ) ) );
+ m_files.insert( p );
+ m_publishFileListTimer->start( 100 );
+ m_stateChangeTimer->start( 100 );
+ return f.id;
+ } catch ( const QString & str ) {
+ err() << "failed to create document-wrapper for" << f.file << ":" << str;
+ return 0;
+ }
+}
+
+void FileCollaborationSession::saveAsFiles() {
+ FileSet::Iterator it = m_files.values();
+ while ( it ) {
+ ( *it ) ->saveAsBufferFile();
+
+ ++it;
+ }
+}
+
+void FileCollaborationSession::saveAsPatch() {
+ FileSet::Iterator it = m_files.values();
+ QList<LocalPatchSourcePointer> patches;
+ while ( it ) {
+
+ LocalPatchSourcePointer p = ( *it ) ->saveAsPatch( false, false );
+
+ ++it;
+ }
+
+ QString patchName = name();
+
+ if ( !m_isMasterSession ) {
+ CollaborationSet::Iterator it = m_collaborations.values();
+ if ( ( *it ) ->user() )
+ patchName += "@" + ~( *it ) ->user().unsafe() ->safeName() + "_" + QDateTime::currentDateTime().toString( Qt::ISODate );
+ }
+
+ LocalPatchSourcePointer p = manager() ->teamwork() ->patchesManager() ->merge( patchName, patches );
+ if ( p ) {
+ manager() ->teamwork() ->patchesManager() ->addPatch( p );
+ } else {
+ err() << "could not merge the file-patches to one";
+ }
+}
+void FileCollaborationSession::addFile() {
+ try {
+ IDocument * document = KDevTeamworkPlugin::staticDocumentController() ->activeDocument();
+ Q_ASSERT( document != 0 );
+ Q_ASSERT( document->textDocument() != 0 );
+
+ KUrl u = TeamworkFolderManager::workspaceRelative( document->url() );
+
+ out( Logger::Debug ) << "adding" << u.toLocalFile() << "to the session";
+
+ uint index = allocateWrapperIndex();
+ QString fileName = TeamworkFolderManager::teamworkRelative( u );
+
+ if ( !addFileInternal( CollabFile( index, fileName ), true, true ) )
+ throw "could not add file " + u.toLocalFile();
+
+ DocumentWrapperPointer wrapper = m_files[ index ];
+ if ( !wrapper )
+ throw "could not get document-wrapper for " + fileName;
+
+ ///Synchronize the newly created file
+ for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it )
+ synchronizeFile( *it, wrapper );
+
+
+ } catch ( const QString & str ) {
+ err() << "addFile():" << str;
+ } catch ( const char * str ) {
+ err() << "addFile():" << str;
+ }
+}
+
+void FileCollaborationSession::stopSession() {
+ out() << "stopping session, disconnecting all users";
+ CollaborationSet::Iterator it = m_collaborations.values();
+ while ( it ) {
+ it.edit() ->data() ->close( "stop" );
+ ++it;
+ }
+ m_collaborations.clear();
+
+ emit stateChanged( this );
+}
+
+void FileCollaborationSession::disableEditing() {
+ FileSet::Iterator it = m_files.values();
+ while ( it ) {
+ if ( !( *it ) ->dead() ) {
+ ( *it ) ->setDisabled( true );
+ }
+ ++it;
+ }
+}
+
+void FileCollaborationSession::enableEditing() {
+ FileSet::Iterator it = m_files.values();
+ while ( it ) {
+ if ( !( *it ) ->dead() ) {
+ ( *it ) ->setDisabled( false );
+ }
+ ++it;
+ }
+}
+
+void FileCollaborationSession::removeAllFiles() {
+ FileSet::Iterator it = m_files.values();
+ while ( it ) {
+ removeFile( ( *it ) ->id() );
+ ++it;
+ }
+}
+
+void FileCollaborationSession::closeSession() {
+ manager() ->closeSession( this );
+}
+
+void FileCollaborationSession::publishStateChange() {
+ emit stateChanged( this );
+}
+
+QAction* FileCollaborationSession::getRemoveUserAction( const UserPointer& user ) {
+ QVariant v;
+ v.setValue( user );
+ m_removeUserAction->setData( v );
+ return m_removeUserAction;
+}
+
+void FileCollaborationSession::publishFileRemove( uint id ) {
+ CollabFileList files = fileNames();
+ files.push_back( CollabFile( id, "" ) );
+ publishFileList( files );
+}
+
+void FileCollaborationSession::slotPublishFileList() {
+ publishFileList( fileNames() );
+}
+
+void FileCollaborationSession::publishFileList( const CollabFileList& files ) {
+ for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
+ FileCollaborationPointer collab = *it;
+ KDevTeamworkUserPointer::Locked l = collab->user();
+ if ( l ) {
+ if ( l->online().session() ) {
+ globalMessageSendHelper().send<FileListMessage>( l->online().session().unsafe(), files, id() );
+ }
+ } else {
+ err() << "publishFileList(..): could not lock user";
+ }
+ }
+}
+
+void FileCollaborationSession::publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender ) {
+ for ( CollaborationSet::ValueMap::iterator it = m_collaborations.begin(); it != m_collaborations.end(); ++it ) {
+ FileCollaborationPointer collab = ( *it ).second.value;
+ if ( state.primaryIndex() != collab->primaryIndex() ) {
+ KDevTeamworkUserPointer::Locked l = collab->user();
+ if ( l ) {
+ if ( l->online().session() ) {
+ globalMessageSendHelper().send<FileEditMessage>( l->online().session().unsafe(), state, replacement, sender->id(), id() );
+ }
+ } else {
+ err() << "publishEdit(..): could not lock user";
+ }
+ }
+ }
+}
+
+void FileCollaborationSession::slotFillCollaboratingUserMenu( QMenu * /*menu*/, const UserPointer & /*user*/ ) {}
+
+CollabSessionId FileCollaborationSession::id() const {
+ return m_id;
+}
+
+QList< KDevTeamworkUserPointer > FileCollaborationSession::users() const {
+ QList<KDevTeamworkUserPointer> ret;
+ for ( CollaborationSet::ValueMap::const_iterator it = m_collaborations.begin(); it != m_collaborations.end(); ++it ) {
+ ret << ( *it ).second.value->user();
+ }
+ return ret;
+}
+
+void FileCollaborationSession::inviteUser( const KDevTeamworkUserPointer & user ) {
+ try {
+ if ( !m_isMasterSession )
+ throw "cannot invite user to a remote session";
+
+ KDevTeamworkUserPointer::Locked lu = user;
+ if ( !lu )
+ throw "could not lock user";
+
+ if ( !lu->online().session() )
+ throw "no session to user " + ~lu->User::name();
+
+ SessionPointer session = lu->online().session();
+
+ FileCollaborationPointer collab = newCollaboration( user );
+
+ } catch ( const char * str ) {
+ err() << "inviteUser:" << str;
+ } catch ( QString str ) {
+ err() << "inviteUser:" << str;
+ }
+}
+
+QString FileCollaborationSession::firstPeerName() {
+ CollaborationSet::ValueMap::iterator it = m_collaborations.begin();
+ if ( it != m_collaborations.end() ) {
+ KDevTeamworkUserPointer::Locked l = ( *it ).second.value->user();
+ if ( l ) {
+ return ~l->User::name();
+ } else {
+ err() << "firstPeerUserName() could not lock user";
+ return "";
+ }
+ }
+ return "";
+}
+
+uint FileCollaborationSession::allocateIndex() {
+ if ( m_primaryIndex != 0 ) {
+ err() << "allocateIndex() called although session is not master";
+ }
+ return m_indexCount++;
+}
+
+uint FileCollaborationSession::allocateWrapperIndex() {
+ /*if ( m_primaryIndex != 0 ) {
+ err() << "allocateWrapperIndex() called although session is not master";
+ }*/
+
+ uint ret = 0;
+ if ( m_isMasterSession )
+ ret = m_wrapperIndexCount++;
+ else
+ ret = m_wrapperIndexCount++ + KRandom::random() % 10 + 5; ///Return a higher number to avoid conflicts
+ if( m_files[ret] )
+ return allocateWrapperIndex();
+ else
+ return ret;
+
+}
+
+void FileCollaborationSession::kickUser( const KDevTeamworkUserPointer & /*user*/ ) {}
+
+QString FileCollaborationSession::name() const {
+ return m_name;
+}
+
+FileCollaborationManager * FileCollaborationSession::manager() {
+ return m_manager;
+}
+/*
+void FileCollaborationSession::processMessage( const FileCollaborationMessagePointer& msg ) {
+ try {
+ FileCollaborationMessagePointer::Locked lmsg = msg;
+ if ( !lmsg )
+ throw "could not lock message";
+
+ UserPointer u = lmsg->info().user();
+ if ( !u )
+ throw QString( "no user-information" );
+
+ FileCollaborationPointer collab = m_collaborations[ u ];
+ if ( !collab )
+ throw ~( "got message from not involved user \"" + u.unsafe() ->safeName() + "\"" );
+
+ collab->processMessage( msg );
+
+ } catch ( QString str ) {
+ err() << "could not process message:" << str;
+ }
+}*/
+int FileCollaborationSession::receiveMessage( MessageInterface* /*msg*/ ) {
+ err() << "got unknown message-type";
+ return 1;
+}
+
+int FileCollaborationSession::receiveMessage( FileListMessage* msg ) {
+ for ( CollabFileList::iterator it = msg->m_files.begin(); it != msg->m_files.end(); ++it ) {
+ FileSet::Iterator doc = m_files.values( it->id );
+ if ( doc ) {
+ if ( it->file.isEmpty() ) {
+ if( m_isMasterSession ) {
+ out( Logger::Debug ) << "file" << it->file << "was tried to be removed from the session";
+ } else {
+ out( Logger::Debug ) << "file" << it->file << "has been removed from the session";
+ killFile( it->id );
+ }
+ }
+ } else {
+ out( Logger::Warning ) << "unknown reference in file-list-message:" << it->id << "" << it->file;
+ /*if ( !it->file.isEmpty() ) {
+ ///Add the new file
+ addFileInternal( *it, false, false );
+ } else {
+ out( Logger::Warning ) << "unknown referenced in file-list-message:" << it->id;
+ }*/
+ }
+ }
+ return 1;
+}
+
+int FileCollaborationSession::receiveMessage( FileCollaborationMessage* msg ) {
+ switch ( msg->message() ) {
+ case FileCollaborationMessageData::CloseSession:
+ if ( !m_isMasterSession ) {
+ out() << "finishing session";
+ aboutToClose();
+ } else {
+ CollaborationSet::Iterator it = m_collaborations.values( msg->info().user() );
+ if ( it ) {
+ it.edit() ->data() ->close( "requested" );
+ m_collaborations.remove( it );
+ } else {
+ err() << "got message from a user that is not part of the collaboration-session";
+ }
+ }
+ default:
+ out() << "got unhandled file-collaboration-message:" << msg->messageAsString();
+ }
+ return 1;
+}
+
+int FileCollaborationSession::receiveMessage( DocumentWrapperMessage* msg ) {
+ CollaborationSet::Iterator sender = m_collaborations.values( msg->info().user() );
+ if ( !sender ) {
+ err() << "got FileSynchronize from a not collaborating user";
+ return 0;
+ }
+
+ FileSet::Iterator it = m_files.values<uint>( msg->wrapperId() );
+ if ( it ) {
+ it.edit() ->data() ->processMessage( msg );
+ } else {
+ FileSynchronize* smsg = dynamic_cast<FileSynchronize*>( msg );
+ if ( smsg ) {
+ ///This has to be unterstood as an invitation to add a new document.
+ if ( m_isMasterSession && !m_allowSentDocuments ) {
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionDenied );
+ QString userName = "anonymous user";
+ if ( msg->info().user() )
+ userName = ~msg->info().user().unsafe() ->safeName();
+ out( Logger::Warning ) << "got a file-synchronization from" << userName << "for \"" << smsg->fileName() << "\", but new files from collaborators are not allowed.";
+ return 1;
+ }
+ if ( addFileInternal( CollabFile( smsg->wrapperId(), smsg->fileName() ), false, false ) ) {
+ DocumentWrapperPointer wrapper = m_files[ smsg->wrapperId() ];
+ if ( !wrapper ) {
+ err() << "could not create wrapper";
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
+ return 1;
+ }
+ wrapper->processMessage( smsg );
+
+ if ( m_isMasterSession ) {
+ ///publish the new file to all other clients
+ for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
+ if ( sender == it )
+ continue;
+ synchronizeFile( *it, wrapper );
+ }
+ }
+ } else {
+ err() << "failed to add file on synchronization:" << smsg->fileName();
+ globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
+ }
+ } else {
+ out( Logger::Warning ) << "could not locate the correct document-wrapper for a message of type" << msg->name() << "wrapper-id:" << msg->wrapperId();
+ }
+ }
+ return 1;
+}
+
+int FileCollaborationSession::processMessage( FileCollaborationMessage* msg ) {
+ return m_dispatcher( msg );
+}
+
+void FileCollaborationSession::aboutToClose() {
+ stopSession();
+}
+
+#include "filecollaborationsession.moc"
+
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp (revision 1522570)
@@ -0,0 +1,323 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "vectortimestampeditor.h"
+#include <QStandardItemModel>
+#include <QModelIndex>
+#include <QVBoxLayout>
+#include <kdialog.h>
+#include "qdynamictext.h"
+#include "verify.h"
+#include "utils.h"
+
+std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs );
+
+VectorTimestampEditorLogger::VectorTimestampEditorLogger( VectorTimestampEditor* ed ) : m_editor(ed) {
+}
+
+void VectorTimestampEditorLogger::log( const std::string& str , Level lv ) {
+ m_editor->log( ~str, (LogLevel)lv );
+}
+
+TimestampEditor::TimestampEditor( Teamwork::LoggerPointer logger, VectorTimestampEditor* parent, uint index ) : SafeLogger( logger, ~QString("TimestampEditor %1: ").arg( index ) ), m_parent( parent ), m_index( index ), m_currentStamp( 0 ), m_block( false ) {
+ QWidget* w = new QWidget( parent->m_widgets.timestampsGroup );
+ m_widgets.setupUi( w );
+ connect( m_widgets.stamp, SIGNAL( valueChanged(int) ), this, SLOT( stampChanged() ) );
+ connect( m_widgets.date, SIGNAL( dateTimeChanged( const QDateTime& ) ), this, SLOT( dateChanged( const QDateTime& ) ) );
+ connect( m_widgets.tail, SIGNAL( clicked( bool ) ), this, SLOT( tail() ) );
+ connect( m_widgets.none, SIGNAL( clicked( bool ) ), this, SLOT( none() ) );
+ connect( m_widgets.enableAll, SIGNAL( clicked( bool ) ), this, SLOT( enableAll() ) );
+ connect( m_widgets.enableBox, SIGNAL( toggled( bool ) ), this, SLOT( enableChanged( bool ) ) );
+ fillWidgets();
+ m_parent->m_layout->addWidget( w );
+}
+
+ReplacementPointer TimestampEditor::replacement() {
+ return m_parent->text()->firstUnapplied( m_index );
+}
+
+Timestamp TimestampEditor::stamp() {
+ return m_parent->text()->state()[m_index] + 1;
+}
+
+bool TimestampEditor::trySeekTo( Timestamp s ) {
+ VectorTimestamp state = m_parent->text()->state();
+ state.setStamp( m_index, s ); state.setPrimaryIndex( m_index );
+ try {
+ return m_parent->text()->changeState( state );
+ } catch( const DynamicTextError& err ) {
+ m_parent->log( "TimestampEditor::trySeekTo( " + ~toText( s ) + " ) error: " + ~err.what(), Error );
+ return false;
+ }
+}
+
+void TimestampEditor::fillWidgets() {
+ QDynamicTextPointer t = m_parent->text();
+
+ ReplacementPointer p = replacement();
+
+ {
+ Block b( m_block );
+ m_widgets.stamp->setValue( stamp() );
+ }
+
+ if( p ) {
+ {
+ Block b( m_block );
+ m_widgets.enableBox->setChecked( p->enabled() );
+ }
+ m_widgets.replacementText->setText( ~toText( p->replacement() ) );
+ m_widgets.tail->setEnabled( true );
+ } else {
+ m_widgets.replacementText->setText( "" );
+ m_widgets.tail->setEnabled( false );
+ }
+
+ m_widgets.stampCount->setText( QString("(%1)").arg( t->highestStamp( m_index ) ) );
+ m_currentStamp = stamp();
+
+ if( m_currentStamp == 1 ) {
+ m_widgets.none->setEnabled( false );
+ } else {
+ m_widgets.none->setEnabled( true );
+ }
+
+ uint disabledCount = 0;
+ ///Now count all disabled replacements lower than the current together
+ ReplacementPointer p2 = t->first( m_index );
+ while( p2 != p && p2 != 0 ) {
+ if( !p2->enabled() ) disabledCount++;
+
+ p2 = p2->next();
+ }
+
+ m_widgets.enableAll->setText( i18n( "Enable Disabled (%1)" , disabledCount ) );
+ if( disabledCount == 0 )
+ m_widgets.enableAll->hide();
+ else
+ m_widgets.enableAll->show();
+}
+
+void TimestampEditor::update() {
+ if( m_currentStamp != stamp() ) fillWidgets();
+}
+
+void TimestampEditor::tail() {
+ QDynamicTextPointer t = m_parent->text();
+ ReplacementPointer p = t->last( m_index );
+ if( p ) {
+ if( !trySeekTo( p->primaryStamp() ) )
+ m_parent->log( "could not seek to current state", Error );
+ }
+
+ fillWidgets();
+}
+
+void TimestampEditor::none() {
+ QDynamicTextPointer t = m_parent->text();
+ if( !trySeekTo( t->initialState()[m_index] ) )
+ m_parent->log( "could not seek to initial state", Error );
+
+ fillWidgets();
+}
+
+void TimestampEditor::enableAll() {
+ QDynamicTextPointer t = m_parent->text();
+
+ VectorTimestamp cur = t->state();
+
+ ReplacementPointer p = replacement();
+
+ ReplacementPointer p2 = t->first( m_index );
+ if( !p2 ) {
+ m_parent->log( "enableAll: error", Error );
+ return;
+ }
+
+ ///Find the lowest disabled stamp
+ Timestamp lowest = stamp();
+
+ {
+ ReplacementPointer cur = t->lastApplied( m_index );
+ while( cur != 0 ) {
+ if( lowest > cur->primaryStamp() ) lowest = cur->primaryStamp();
+ cur = cur->prev();
+ }
+ }
+
+ if( lowest == stamp() ) return;
+
+ if( !trySeekTo( lowest - 1 ) ) {
+ m_parent->log( QString( "enableAll: could not seek to bottom-state %1").arg( lowest-1 ), Error );
+ fillWidgets();
+ return;
+ }
+
+ while( p2 != p && p2 != 0 ) {
+ if( !p2->enabled() ) p2->setEnabled( true );
+
+ p2 = p2->next();
+ }
+
+ if( !trySeekTo( cur[m_index] ) ) {
+ m_parent->log( "enableAll: seek back failed", Error );
+ }
+
+ fillWidgets();
+}
+
+void TimestampEditor::stampChanged() {
+ if( m_block ) return;
+ Timestamp t = m_widgets.stamp->value();
+ if( t != 0 ) t-=1;
+
+ Timestamp maxStamp = m_parent->text()->highestStamp( m_index );
+ if( t > maxStamp ) t = maxStamp;
+
+ if( !trySeekTo( t ) )
+ m_parent->log( "TimestampEditor::TimestampEditor::stampChanged(): trySeekTo failed", Error );
+
+ fillWidgets();
+}
+
+void TimestampEditor::dateChanged( const QDateTime& ) {
+}
+
+void TimestampEditor::enableChanged( bool enabled ) {
+ ReplacementPointer r = replacement();
+ try {
+ ReplacementPointer firstUnapplied = m_parent->text()->firstUnapplied( m_index );
+ if( r && firstUnapplied && (*firstUnapplied) <= (*r) ) {
+ r->setEnabled( enabled );
+ }
+ } catch( const DynamicTextError& err ) {
+ m_parent->log( "TimestampEditor::enableChanged(..): serious corruption-error: " + ~err.what(), Error );
+ }
+
+ fillWidgets();
+}
+
+
+VectorTimestampEditor::VectorTimestampEditor( Teamwork::LoggerPointer logger, QObject* parent, bool embed, QDynamicTextPointer text , bool editable ) : QObject( parent ), SafeLogger( logger, "VectorTimestampEditor: " ), m_text( text ), m_editable( editable ), m_embed( embed ), m_layout( 0 ), m_dialog( 0 ) {
+ QWidget* widget;
+ if( embed && qobject_cast<QWidget*>( parent ) )
+ {
+ widget = qobject_cast<QWidget*>( parent );
+ if( !widget ) {
+ err() << "parent is no QWidget";
+ deleteLater();
+ return;
+ }
+ } else {
+ m_dialog = new KDialog;
+ m_dialog->setButtons( KDialog::Close );
+ m_dialog->setAttribute( Qt::WA_DeleteOnClose, true );
+ widget = m_dialog->mainWidget();
+ connect( m_dialog, SIGNAL( closeClicked() ), this, SLOT( finish() ) );
+ }
+ m_widgets.setupUi( widget );
+ m_layout = new QVBoxLayout( m_widgets.timestampsGroup );
+ m_widgets.timestampsGroup->setLayout( m_layout );
+ widget->show();
+
+ m_logModel = new QStandardItemModel( m_widgets.log );
+ m_widgets.log->setModel( m_logModel );
+ m_logModel->insertColumn( 0 );
+ m_logModel->insertRow( 0 );
+ m_logModel->setData( m_logModel->index( 0, 0 ), "welcome", Qt::DisplayRole );
+
+ connect( m_widgets.toTailTimestamp, SIGNAL( clicked( bool ) ), this, SLOT( toTailTimestamp() ) );
+ connect( m_widgets.clearLog, SIGNAL( clicked( bool ) ), this, SLOT( clearLog() ) );
+ connect( text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( textChanged() ) );
+ connect( text.data(), SIGNAL( inserted( const ReplacementPointer&, QDynamicText& ) ), this, SLOT( textChanged() ) );
+ connect( m_text, SIGNAL( destroyed( QObject* ) ), this, SLOT( textDestroyed() ) );
+ connect( widget, SIGNAL( destroyed( QObject* ) ), this, SLOT( finish() ) );
+
+ fillWidgets();
+}
+
+VectorTimestampEditor::~VectorTimestampEditor() {
+}
+
+void VectorTimestampEditor::fillWidgets() {
+ uint cnt = m_timestamps.count();
+ uint sz = m_text->state().size();
+ if( cnt < sz ) { ///Add missing widgets
+ for( uint a = 0; a < sz - cnt; a++ ) {
+ m_timestamps << new TimestampEditor( new VectorTimestampEditorLogger( this ), this, a+cnt );
+ }
+ }
+
+ for( QList< TimestampEditorPointer >::iterator it = m_timestamps.begin(); it != m_timestamps.end(); ++it ) {
+ (*it)->update();
+ }
+
+ VectorTimestamp state = m_text->state();
+ VectorTimestamp tailState = m_text->tailState();
+
+ QString txt = QString( "Current State: %1 Tail-State: %2" ).arg( ~toText( state ) ).arg( ~toText( tailState ) );
+ m_widgets.stateInfo->setText( txt );
+
+ if( state == tailState ) {
+ m_widgets.toTailTimestamp->setEnabled( false );
+ } else {
+ m_widgets.toTailTimestamp->setEnabled( true );
+ }
+}
+
+void VectorTimestampEditor::log( const QString& str, LogLevel level ) {
+ m_logModel->insertRow( 0 );
+ QModelIndex i = m_logModel->index( 0, 0 );
+ if( i.isValid() ) {
+ m_logModel->setData( i, str, Qt::DisplayRole );
+ m_logModel->setData( i, iconFromLevel( level ), Qt::DecorationRole );
+ }
+}
+
+void VectorTimestampEditor::textDestroyed() {
+ m_text = 0;
+ finish();
+}
+
+void VectorTimestampEditor::textChanged() {
+ fillWidgets();
+}
+
+QDynamicTextPointer VectorTimestampEditor::text() {
+ return m_text;
+}
+
+void VectorTimestampEditor::toTailTimestamp() {
+ try {
+ m_text->changeState();
+ } catch( const DynamicTextError& error ) {
+ log( "error in toTailTimestamp: " + ~error.what(), Error );
+ }
+}
+
+void VectorTimestampEditor::clearLog() {
+ m_logModel->clear();
+ m_logModel->insertColumn( 0 );
+}
+
+void VectorTimestampEditor::finish() {
+ if( m_text ) m_text->changeState();
+ if( m_dialog ) m_dialog->deleteLater();
+ deleteLater();
+}
+
+
+
+#include "vectortimestampeditor.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui (revision 1522570)
@@ -0,0 +1,172 @@
+<ui version="4.0" >
+ <class>VectorTimestampWidget</class>
+ <widget class="QWidget" name="VectorTimestampWidget" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>760</width>
+ <height>172</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QGroupBox" name="timestampsGroup" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Expanding" hsizetype="Preferred" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="title" >
+ <string>Timestamps</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="groupBox_2" >
+ <property name="title" >
+ <string>Log</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QListView" name="log" >
+ <property name="selectionMode" >
+ <enum>QAbstractItemView::NoSelection</enum>
+ </property>
+ <property name="selectionBehavior" >
+ <enum>QAbstractItemView::SelectRows</enum>
+ </property>
+ <property name="resizeMode" >
+ <enum>QListView::Fixed</enum>
+ </property>
+ <property name="layoutMode" >
+ <enum>QListView::Batched</enum>
+ </property>
+ <property name="batchSize" >
+ <number>50</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="toTailTimestamp" >
+ <property name="text" >
+ <string>To Tail State</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="clearLog" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Fixed" hsizetype="Minimum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Clear Log</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="stateInfo" >
+ <property name="text" >
+ <string>Current State: Tail State: </string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>301</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui (revision 1522570)
@@ -0,0 +1,139 @@
+<ui version="4.0" >
+ <class>ManagePatches</class>
+ <widget class="QWidget" name="ManagePatches" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>537</width>
+ <height>432</height>
+ </rect>
+ </property>
+ <property name="windowTitle" >
+ <string>Manage Patches</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label" >
+ <property name="text" >
+ <string>Available patches:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QTreeView" name="patchesList" />
+ </item>
+ <item>
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="add" >
+ <property name="text" >
+ <string>Add</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="edit" >
+ <property name="text" >
+ <string>Edit</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="remove" >
+ <property name="text" >
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>20</width>
+ <height>231</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.h (revision 1522570)
@@ -0,0 +1,100 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef MESSAGEHISTORY_H
+#define MESSAGEHISTORY_H
+
+#include "ui_kdevteamwork_messagehistory.h"
+#include <QList>
+#include <QObject>
+#include <QWidget>
+#include "kdevteamwork_user.h"
+#include "safelogger.h"
+
+namespace Teamwork {
+ class Logger;
+ typedef SafeSharedPtr<Logger> LoggerPointer;
+}
+
+class KDialog;
+class MessageManager;
+class KDevTeamworkTextMessage;
+
+typedef SafeSharedPtr<KDevTeamworkTextMessage, MessageSerialization> HistoryMessagePointer;
+
+class QStandardItemModel;
+
+class GuiMessageHistory : public QObject, public SafeLogger {
+ Q_OBJECT
+ public:
+ typedef QList<KDevTeamworkUserPointer> UserList;
+ typedef QMap<KDevTeamworkUserPointer, bool> UserSet;
+ ///Empty list means All Users
+ explicit GuiMessageHistory( MessageManager* manager, UserList users = UserList(), const QString& context = "" );
+ ~GuiMessageHistory();
+
+ public slots:
+ void slotAllMessages();
+ void slotAllDevelopers();
+ void slotNewMessage( const HistoryMessagePointer& );
+ void slotUserStateChanged( const KDevTeamworkUserPointer& user );
+ void slotSelectionChanged();
+ void slotUpdateMessages();
+ void slotExit();
+ void messageItemClicked( const QModelIndex& index );
+ void updateMessageUserIcons();
+
+ ///Filters:
+ void typeFilterChanged( int index );
+ void contextFilterChanged( int index );
+
+ private:
+ bool fitMessageDate( const HistoryMessagePointer& msg );
+ void showMessage( const HistoryMessagePointer& msg );
+ void fillDeveloperList();
+ void updateUserIcon( const KDevTeamworkUserPointer& user );
+ UserSet selectedUsers();
+ void fillMessages();
+
+ void clearFilters();
+ void applyFilters( int firstN = 0 );
+
+ virtual std::string logPrefix() {
+ return "GuiMessageHistory: ";
+ }
+
+ void clearUsers();
+ void addUser( const KDevTeamworkUserPointer& user );
+
+ bool m_allUsers;
+ UserSet m_users;
+ MessageManager* m_manager;
+ Ui_MessageHistory m_widgetData;
+ QStandardItemModel* m_developersModel;
+ QStandardItemModel* m_messagesModel;
+ QTimer* m_updateTimer;
+ QTimer* m_userIconUpdateTimer;
+ KDialog* m_dialog;
+ QString m_defaultContext;
+
+ enum TableColumns {
+ TimeColumn = 0,
+ TypeColumn,
+ UserColumn,
+ TextColumn,
+ ColumnCount
+ };
+
+ QList<KDevTeamworkUserPointer> m_changedUsers;
+};
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/guimessagehistory.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui (revision 1522570)
@@ -0,0 +1,64 @@
+<ui version="4.0" >
+ <class>NewFileCollaborationSession</class>
+ <widget class="QWidget" name="NewFileCollaborationSession" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>386</width>
+ <height>214</height>
+ </rect>
+ </property>
+ <property name="windowTitle" >
+ <string>Dialog</string>
+ </property>
+ <layout class="QGridLayout" >
+ <item row="0" column="0" colspan="2" >
+ <widget class="QCheckBox" name="allowSentDocuments" >
+ <property name="text" >
+ <string>Allow collaborators to add own documents</string>
+ </property>
+ <property name="checked" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" colspan="2" >
+ <widget class="QLabel" name="files" >
+ <property name="text" >
+ <string>Files:
+File 1
+File 2</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" >
+ <widget class="QLabel" name="users" >
+ <property name="text" >
+ <string>Invite users:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0" >
+ <widget class="QLabel" name="label" >
+ <property name="text" >
+ <string>Session-Name:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1" >
+ <widget class="KLineEdit" name="sessionName" />
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KLineEdit</class>
+ <extends>QLineEdit</extends>
+ <header>klineedit.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections>
+ </connections>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui (revision 1522570)
@@ -0,0 +1,293 @@
+<ui version="4.0" >
+ <class>MessageHistory</class>
+ <widget class="QWidget" name="MessageHistory" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>712</width>
+ <height>616</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QGroupBox" name="groupBox_2" >
+ <property name="title" >
+ <string>Messages</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_3" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>From:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDateEdit" name="fromDate" />
+ </item>
+ <item>
+ <widget class="QLabel" name="label_2" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Until:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDateEdit" name="untilDate" >
+ <property name="currentSection" >
+ <enum>QDateTimeEdit::DaySection</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="allMessagesButton" >
+ <property name="text" >
+ <string>All</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QTreeView" name="messages" />
+ </item>
+ <item>
+ <widget class="QDockWidget" name="messageFrame" >
+ <property name="contextMenuPolicy" >
+ <enum>Qt::NoContextMenu</enum>
+ </property>
+ <property name="features" >
+ <set>QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable|QDockWidget::NoDockWidgetFeatures</set>
+ </property>
+ <widget class="QWidget" name="dockWidgetContents" />
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Type:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="typeFilter" />
+ </item>
+ <item>
+ <widget class="QLabel" name="label_4" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Context:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="contextFilter" />
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="1" >
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QGroupBox" name="groupBox" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>140</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title" >
+ <string>Developers</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QListView" name="developers" />
+ </item>
+ <item row="1" column="0" >
+ <widget class="QPushButton" name="allDevelopersButton" >
+ <property name="text" >
+ <string>All</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>allDevelopersButton</sender>
+ <signal>clicked()</signal>
+ <receiver>developers</receiver>
+ <slot>clearSelection()</slot>
+ <hints>
+ <hint type="sourcelabel" >
+ <x>54</x>
+ <y>517</y>
+ </hint>
+ <hint type="destinationlabel" >
+ <x>52</x>
+ <y>415</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui (revision 1522570)
@@ -0,0 +1,170 @@
+<ui version="4.0" >
+ <class>InDocumentState</class>
+ <widget class="QWidget" name="InDocumentState" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>609</width>
+ <height>80</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="1" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">File&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KUrlLabel" name="file" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration: underline;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" text-decoration:none;">file&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="label_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:Sans;">&lt;span style=" font-weight:600;">Position&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="position" >
+ <property name="text" >
+ <string>position</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_5" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:Sans;">&lt;span style=" font-weight:600;">Context&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KUrlLabel" name="context" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration: underline;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" text-decoration:none;">Context&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="label_3" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Reference-Type&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="referenceType" >
+ <property name="text" >
+ <string>referenceType</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0" >
+ <widget class="Line" name="line_2" >
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="Line" name="line" >
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KUrlLabel</class>
+ <extends>QLabel</extends>
+ <header>kurllabel.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui (revision 1522570)
@@ -0,0 +1,30 @@
+<ui version="4.0" >
+ <class>InDocumentButtons</class>
+ <widget class="QWidget" name="InDocumentButtons" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>333</width>
+ <height>51</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QPushButton" name="jumpToPosition" >
+ <property name="text" >
+ <string>Jump to Position</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui (revision 1522570)
@@ -0,0 +1,875 @@
+<ui version="4.0" >
+ <class>Teamwork</class>
+ <widget class="QWidget" name="Teamwork" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>321</width>
+ <height>748</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="1" column="0" >
+ <widget class="QToolBox" name="toolBox" >
+ <property name="currentIndex" >
+ <number>1</number>
+ </property>
+ <widget class="QWidget" name="connection" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>204</width>
+ <height>245</height>
+ </rect>
+ </property>
+ <attribute name="label" >
+ <string>Connection</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QTabWidget" name="connectionTab" >
+ <property name="enabled" >
+ <bool>true</bool>
+ </property>
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Expanding" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>16777215</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="currentIndex" >
+ <number>1</number>
+ </property>
+ <widget class="QWidget" name="localTab" >
+ <attribute name="title" >
+ <string>Local server</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="2" column="0" >
+ <widget class="QListView" name="connectedClients" />
+ </item>
+ <item row="1" column="0" >
+ <widget class="QLabel" name="connectedClientsLabel" >
+ <property name="text" >
+ <string>Connected clients:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="QCheckBox" name="allowIncoming" >
+ <property name="text" >
+ <string>Allow incoming</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="remoteTab" >
+ <attribute name="title" >
+ <string>Servers</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="3" column="0" colspan="3" >
+ <widget class="QListView" name="connectedServers" />
+ </item>
+ <item row="1" column="1" >
+ <widget class="KLineEdit" name="loginPassword" >
+ <property name="toolTip" >
+ <string>the password for logging into the server</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2" >
+ <widget class="QPushButton" name="connectServer" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="toolTip" >
+ <string>connect to the given server using the given login-information(if the name is blank the local name is used)</string>
+ </property>
+ <property name="text" >
+ <string>Connect</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" colspan="3" >
+ <widget class="QComboBox" name="serverBox" >
+ <property name="toolTip" >
+ <string>the server to connect</string>
+ </property>
+ <property name="editable" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" colspan="3" >
+ <widget class="QLabel" name="connectedServersLabel" >
+ <property name="text" >
+ <string>Connected servers:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <widget class="KLineEdit" name="loginName" >
+ <property name="toolTip" >
+ <string>the user-name for logging into the server</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="developers" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>303</width>
+ <height>335</height>
+ </rect>
+ </property>
+ <attribute name="label" >
+ <string>Developers</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QLabel" name="availableLabel" >
+ <property name="text" >
+ <string>Available:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <widget class="QTreeView" name="availableDevelopers" >
+ <property name="enabled" >
+ <bool>true</bool>
+ </property>
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>16777215</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="sizeIncrement" >
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="baseSize" >
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="lineWidth" >
+ <number>1</number>
+ </property>
+ <property name="editTriggers" >
+ <set>QAbstractItemView::NoEditTriggers</set>
+ </property>
+ <property name="alternatingRowColors" >
+ <bool>true</bool>
+ </property>
+ <property name="indentation" >
+ <number>15</number>
+ </property>
+ <property name="rootIsDecorated" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0" >
+ <widget class="QTreeView" name="connectedDevelopers" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>16777215</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="editTriggers" >
+ <set>QAbstractItemView::NoEditTriggers</set>
+ </property>
+ <property name="alternatingRowColors" >
+ <bool>true</bool>
+ </property>
+ <property name="indentation" >
+ <number>15</number>
+ </property>
+ <property name="rootIsDecorated" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" >
+ <widget class="QLabel" name="connectedLabel" >
+ <property name="text" >
+ <string>Collaborating:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="messaging" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>226</width>
+ <height>286</height>
+ </rect>
+ </property>
+ <attribute name="label" >
+ <string>Messaging</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="KComboBox" name="messageTargetUser" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Fixed" hsizetype="Preferred" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="toolTip" >
+ <string>target-user</string>
+ </property>
+ <property name="editable" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QToolButton" name="answeringToButton" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Maximum" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="contextMenuPolicy" >
+ <enum>Qt::NoContextMenu</enum>
+ </property>
+ <property name="autoFillBackground" >
+ <bool>true</bool>
+ </property>
+ <property name="text" >
+ <string>Answer To</string>
+ </property>
+ <property name="checkable" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="typeLabel" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>50</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="layoutDirection" >
+ <enum>Qt::LeftToRight</enum>
+ </property>
+ <property name="text" >
+ <string>Type:</string>
+ </property>
+ <property name="alignment" >
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="messageType" >
+ <item>
+ <property name="text" >
+ <string>Message</string>
+ </property>
+ </item>
+ <item>
+ <property name="text" >
+ <string>Comment</string>
+ </property>
+ </item>
+ <item>
+ <property name="text" >
+ <string>Source-discussion</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="contextLabel" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Thread:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="context" />
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>2</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="referenceLabel" >
+ <property name="sizePolicy" >
+ <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Reference:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="reference" />
+ </item>
+ </layout>
+ </item>
+ <item row="5" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="clearMessageButton" >
+ <property name="text" >
+ <string>Clear</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>71</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="sendMessage" >
+ <property name="text" >
+ <string>&amp;Send message</string>
+ </property>
+ <property name="shortcut" >
+ <string>S</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="4" column="0" >
+ <widget class="KTextEdit" name="messageText" >
+ <property name="toolTip" >
+ <string>the message you wish to send</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="localstate" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>179</width>
+ <height>49</height>
+ </rect>
+ </property>
+ <attribute name="label" >
+ <string>Local state</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QPushButton" name="managePatches" >
+ <property name="text" >
+ <string>Manage local patches</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ <item row="2" column="0" >
+ <widget class="QTabWidget" name="historyTab" >
+ <property name="currentIndex" >
+ <number>0</number>
+ </property>
+ <widget class="QWidget" name="messagesTab" >
+ <attribute name="title" >
+ <string>Messages</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QTabWidget" name="messageUsers" >
+ <property name="currentIndex" >
+ <number>0</number>
+ </property>
+ <widget class="QWidget" name="allUsersTab" >
+ <attribute name="title" >
+ <string>All Users</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QTreeView" name="messageList" >
+ <property name="isWrapping" stdset="0" >
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="clearMessages" >
+ <property name="text" >
+ <string>Clear</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="messageHistory" >
+ <property name="text" >
+ <string>History</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="logTab" >
+ <attribute name="title" >
+ <string>Log</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QVBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QListView" name="logList" />
+ </item>
+ <item>
+ <layout class="QHBoxLayout" >
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <property name="leftMargin" >
+ <number>0</number>
+ </property>
+ <property name="topMargin" >
+ <number>0</number>
+ </property>
+ <property name="rightMargin" >
+ <number>0</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="clearLog" >
+ <property name="text" >
+ <string>Clear</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="saveLog" >
+ <property name="text" >
+ <string>Save</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QToolButton" name="logFilter" >
+ <property name="text" >
+ <string>Filter</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="QCheckBox" name="enableCollaboration" >
+ <property name="text" >
+ <string>Enable Collaboration</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KComboBox</class>
+ <extends>QComboBox</extends>
+ <header>kcombobox.h</header>
+ </customwidget>
+ <customwidget>
+ <class>KTextEdit</class>
+ <extends>QTextEdit</extends>
+ <header>ktextedit.h</header>
+ </customwidget>
+ <customwidget>
+ <class>KLineEdit</class>
+ <extends>QLineEdit</extends>
+ <header>klineedit.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui (revision 1522570)
@@ -0,0 +1,417 @@
+<ui version="4.0" >
+ <class>TextMessageShower</class>
+ <widget class="QWidget" name="TextMessageShower" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>582</width>
+ <height>173</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="4" column="0" >
+ <widget class="QFrame" name="bottomSpace" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>4</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>16</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="0" >
+ <widget class="QFrame" name="frame_2" >
+ <property name="sizeIncrement" >
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ <property name="lineWidth" >
+ <number>1</number>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>2</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="menuButton" >
+ <property name="text" >
+ <string>Menu</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="historyButton" >
+ <property name="text" >
+ <string>History</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>331</width>
+ <height>27</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QFrame" name="buttonSpace" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="isReplyToButton" >
+ <property name="text" >
+ <string>Is Reply To</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="QFrame" name="topSpace" >
+ <property name="enabled" >
+ <bool>true</bool>
+ </property>
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>4</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>16</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <widget class="QGroupBox" name="textBox" >
+ <property name="font" >
+ <font>
+ <family>Sans Serif</family>
+ <pointsize>9</pointsize>
+ <weight>75</weight>
+ <italic>false</italic>
+ <bold>true</bold>
+ <underline>false</underline>
+ <strikeout>false</strikeout>
+ </font>
+ </property>
+ <property name="title" >
+ <string>Text</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>2</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QLabel" name="text" >
+ <property name="font" >
+ <font>
+ <family>Sans Serif</family>
+ <pointsize>9</pointsize>
+ <weight>50</weight>
+ <italic>false</italic>
+ <bold>false</bold>
+ <underline>false</underline>
+ <strikeout>false</strikeout>
+ </font>
+ </property>
+ <property name="text" >
+ <string>Text</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="2" column="0" >
+ <widget class="QFrame" name="middleSpace" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>4</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>16</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0" >
+ <widget class="QFrame" name="frame" >
+ <property name="frameShape" >
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>2</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="1" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="state_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">State&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="state" >
+ <property name="text" >
+ <string>State</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="time_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Time&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="time" >
+ <property name="text" >
+ <string>Time</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="user_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">User&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="userIcon" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="user" >
+ <property name="text" >
+ <string>User</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="direction_2" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
+p, li { white-space: pre-wrap; }
+&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
+&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Direction&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="direction" >
+ <property name="text" >
+ <string>Direction</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0" >
+ <widget class="QFrame" name="stateSpace" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>4</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize" >
+ <size>
+ <width>0</width>
+ <height>1</height>
+ </size>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Raised</enum>
+ </property>
+ <property name="lineWidth" >
+ <number>0</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui (revision 1522570)
@@ -0,0 +1,173 @@
+<ui version="4.0" >
+ <class>TimestampWidget</class>
+ <widget class="QWidget" name="TimestampWidget" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>950</width>
+ <height>29</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="tail" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Tail</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="none" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>None</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="enableAll" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Enable All(x)</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KIntNumInput" name="stamp" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize" >
+ <size>
+ <width>120</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="minimum" >
+ <number>0</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="stampCount" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>(last stamp)</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDateTimeEdit" name="date" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="lastDate" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>(last date)</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="enableBox" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Enable</string>
+ </property>
+ <property name="tristate" >
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="replacementText" >
+ <property name="text" >
+ <string>replacement-text</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KIntNumInput</class>
+ <extends>QWidget</extends>
+ <header>knuminput.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui (revision 1522570)
@@ -0,0 +1,26 @@
+<ui version="4.0" >
+ <class>List</class>
+ <widget class="QWidget" name="widget" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>300</width>
+ <height>319</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QListView" name="list" />
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui (revision 1522570)
@@ -0,0 +1,52 @@
+<ui version="4.0" >
+ <class>InDocumentContextLines</class>
+ <widget class="QWidget" name="InDocumentContextLines" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>611</width>
+ <height>137</height>
+ </rect>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QGroupBox" name="groupBox" >
+ <property name="font" >
+ <font>
+ <family>Sans Serif</family>
+ <pointsize>9</pointsize>
+ <weight>75</weight>
+ <italic>false</italic>
+ <bold>true</bold>
+ <underline>false</underline>
+ <strikeout>false</strikeout>
+ </font>
+ </property>
+ <property name="title" >
+ <string>Context-Lines:</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>2</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QTextEdit" name="contextLines" />
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.cpp (revision 1522570)
@@ -0,0 +1,29 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "verify.h"
+#include <sstream>
+
+ExpressionError::ExpressionError( const std::string& fun, int l, const std::string& f, const std::string& exp, const std::string& realExp ) : function( fun ), line( l ), file( f ), expression( exp ), realExpression( realExp ) {}
+
+std::string ExpressionError::what() const {
+ std::ostringstream os;
+ os << "DynamicTextError in" << function << "," << file << ":" << line;
+ if ( !expression.empty() )
+ os << ", expression \"" << expression << "\" failed";
+ if ( !realExpression.empty() )
+ os << ", values:" << realExpression;
+ return os.str();
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/sumsearch.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/sumsearch.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/sumsearch.h (revision 1522570)
@@ -0,0 +1,624 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SUMSEARCH_H
+#define SUMSEARCH_H
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+#include <vector>
+
+///For higher orders to work, the sum-type has to be signed
+#define DEFAULTSUMTYPE int
+#define DEFAULTORDER 2
+
+
+///State-based-build can only nearly complete with extreme compiler-parameters set, although it should theoretically be faster, if the compile would optimize it the right way.
+
+//#define STATEBASEDBUILD
+
+namespace FuzzySearch {
+
+/**
+ * How should all the differences be weighed together to a compound difference?
+ *
+ * The weighting still needs some work.
+ *
+ * */
+
+template < class Compare1, class Compare2, class Then, class Else >
+class IfEqual {
+public:
+ typedef Else Result;
+};
+
+template < class Compare, class Then, class Else >
+class IfEqual<Compare, Compare, Then, Else> {
+public:
+ typedef Then Result;
+};
+
+template <class Item>
+class PrimitiveVector {
+ Item* data_;
+ uint size_;
+ public:
+ PrimitiveVector() : data_( 0 ), size_( 0 ) {}
+ ;
+
+ ~PrimitiveVector() {
+ if ( data_ )
+ delete[] data_;
+ }
+
+ ///All data is lost when this is called
+ void rawResize( unsigned int i ) {
+ if ( size_ == i )
+ return ;
+ size_ = i;
+ if ( data_ )
+ delete[] data_;
+ if ( !i ) {
+ data_ = 0;
+ } else {
+ data_ = new Item[ i ];
+ }
+ };
+
+ Item& operator [] ( uint index ) {
+ return data_[ index ];
+ }
+
+ const Item& operator [] ( uint index ) const {
+ return data_[ index ];
+ }
+
+ uint size() const {
+ return size_;
+ }
+};
+
+///unsigned int is ok for document-sizes of up to about 16 Megabytes, 64-bit integers create problems here
+using namespace std;
+template <int maxDepth, class SumType = DEFAULTSUMTYPE>
+struct SumGroup {
+ SumType sums[ maxDepth ];
+
+ SumGroup( SumType* _sums = 0 ) {
+ if ( _sums ) {
+ for ( int a = 0; a < maxDepth; a++ ) {
+ sums[ a ] = _sums[ a ];
+ }
+ } else {
+ for ( int a = 0; a < maxDepth; a++ )
+ sums[ a ] = 0;
+ }
+ }
+
+ /*
+ SumType sumDifference( const SumGroup& rhs ) const {
+ SumType ret = 0;
+ for( int a = 0; a < maxDepth; a++ ) {
+ SumType dif;
+ if( sums[a] > rhs.sums[a] )
+ dif = sums[a] - rhs.sums[a];
+ else
+ dif = rhs.sums[a] - sums[a];
+
+ ret += ( dif * (maxDepth - a ) ) >> a;
+ }
+ return ret;
+ };*/
+
+ struct VecSumGetter {
+ SumType** sumVec;
+ VecSumGetter() : sumVec( 0 ) {}
+ VecSumGetter( SumType** vec ) : sumVec( vec ) {}
+
+ inline bool sumValid( const uint num ) const {
+ return ( bool ) sumVec[ num ];
+ }
+
+
+ inline SumType sum( const uint num ) const {
+ return * ( sumVec[ num ] );
+ }
+ };
+
+ struct ZeroGetter {
+ inline bool sumValid( const uint num ) const {
+ return false;
+ }
+ inline SumType sum( const uint num ) const {
+ return 0;
+ }
+ };
+
+ struct GroupSumGetter {
+ SumGroup& group;
+ GroupSumGetter( SumGroup& grp ) : group( grp ) {}
+
+ inline bool sumValid( const uint num ) const {
+ return true;
+ }
+
+
+ inline SumType sum( const uint num ) const {
+ return group.sums[ num ];
+ }
+ };
+
+ template <class SumGetter>
+ SumType sumDifference( const SumGetter& getter ) const {
+ SumType ret = 0;
+ for ( int a = 0; a < maxDepth; a++ ) {
+ SumType dif;
+ if ( getter.sumValid( a ) ) {
+ if ( sums[ a ] > getter.sum( a ) )
+ dif = sums[ a ] - getter.sum( a );
+ else
+ dif = getter.sum( a ) - sums[ a ];
+ } else {
+ dif = sums[ a ];
+ }
+
+ ///The weighting is a bit primitive at the moment
+ ret += ( dif * ( ( maxDepth - a ) + 1 ) ) /* >> a*/;
+ }
+ return ret;
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & sums;
+ }
+};
+
+template < int Condition, class Then, class Else >
+struct IfThen {
+ typedef Then Result;
+};
+
+template < class Then, class Else >
+struct IfThen <0, Then, Else> {
+ typedef Else Result;
+};
+
+
+template <int maxDepth, typename SumType, int order, bool dummy>
+class DifferenceSumReference {
+ public:
+ template <class Archive>
+ void serialize( Archive& /*arch*/, const uint /*version*/ ) {}
+}
+;
+
+template <int maxDepth, class SumType = DEFAULTSUMTYPE, int order = DEFAULTORDER>
+class SumReference {
+ bool valid_;
+ public:
+ SumGroup<maxDepth, SumType> leftMarker;
+ SumGroup<maxDepth, SumType> rightMarker;
+
+ DifferenceSumReference < maxDepth, SumType, order - 1, ( order - 1 ) == 0 > nextOrder_;
+
+ SumReference() : valid_( false ) {}
+
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & valid_ & leftMarker & rightMarker;
+ arch & nextOrder_;
+ }
+
+ void setValid( bool valid ) {
+ valid_ = valid;
+ }
+
+ bool isValid() const {
+ return valid_;
+ }
+};
+
+
+template <int maxDepth, typename SumType, int order>
+struct DifferenceSumReference<maxDepth, SumType, order, false> {
+ SumReference<maxDepth, SumType, order> reference_;
+public:
+ template <class Archive>
+ void serialize( Archive& arch, const uint /*version*/ ) {
+ arch & reference_;
+ }
+};
+
+/** The problem with a single sum-search: 123456| is detected as exactly same as 124356|.
+ * For that reason a parallel difference-sum-search can be used, which would look like 111111| in the first, and 112(-1)21| in the second case.
+ * SumType must be signed for that to work.
+ * */
+
+
+template <int maxDepth, typename SumType, int order, bool dummy>
+class DifferenceSumSearch {
+ public:
+ DifferenceSumSearch( const string& /*text*/ ) {}
+ template <class Type>
+ void fillReference( Type& /*t*/, int /*position*/ ) {}
+
+ template <class PrevType, class Evaluator>
+ struct FindRefProgress {
+ FindRefProgress( PrevType& /*t*/, const SumReference < maxDepth, SumType, order + 1 > & /*_ref*/, Evaluator& /*_eval*/ ) {}
+ SumType leftDiff() {
+ return 0;
+ }
+
+ SumType rightDiff() {
+ return 0;
+ }
+
+ void next() {}
+ }
+ ;
+};
+
+
+template <class SumType, int Depth, int EndDepth>
+struct SumBuildState : public SumBuildState < SumType, Depth + 1, EndDepth > {
+ typedef SumBuildState< SumType, Depth, EndDepth> Self;
+ typedef SumBuildState < SumType, Depth + 1, EndDepth > Next;
+ typedef SumBuildState< SumType, 0, EndDepth> Head;
+ SumType* v;
+
+ uint tempSumC;
+ SumType tempSum;
+ const char* text;
+ const char* ctext;
+ uint offset;
+
+ //uint maxCount = 1<<b;
+
+ SumBuildState( PrimitiveVector<SumType>* sumVecs_, const char* tx ) : Next( sumVecs_, tx ), tempSumC( 0 ), tempSum( 0 ), text( tx ), ctext( tx ), offset( 0 ) {
+ v = &( sumVecs_[ Depth ][ 0 ] );
+ }
+
+ inline void go1( register const char* ctex, register const uint offset ) {
+ Next::go1( ctex, offset );
+ {
+ if ( tempSumC == ( uint ) ( 1 << Depth ) ) {
+ ///remove the first summand
+ tempSum -= *( ctex - ( 1 << Depth ) );
+ } else {
+ tempSumC ++;
+ }
+
+ tempSum += *ctex;
+ ( * ( v + offset ) ) = tempSum;
+ }
+ }
+
+ /* inline void go2( register uint offset ) {
+ Next::go2( offset );
+ //++v;
+ }*/
+
+ inline void go() {
+ go1( ctext, offset );
+
+ //go2( offset );
+
+ ++ctext;
+ ++offset;
+ }
+};
+
+template <class SumType, int Depth>
+struct SumBuildState<SumType, Depth, Depth> {
+ SumBuildState( PrimitiveVector<SumType>*, const char* ) {}
+ ;
+
+ inline void go1( register const char* ctex, register const uint offset ) {}
+ // inline void go2() {
+ // }
+}
+;
+
+
+template <int maxDepth, typename SumType = DEFAULTSUMTYPE, int order = DEFAULTORDER>
+class SumSearch {
+ typedef SumSearch<maxDepth, SumType, order> SelfSumSearch;
+ typedef PrimitiveVector< SumType > SumVector;
+ string text_;
+ SumVector sumVecs_[ maxDepth ];
+ typedef DifferenceSumSearch < maxDepth, SumType, order - 1, ( order - 1 ) == 0 > NextOrderType;
+
+#ifdef STATEBASEDBUILD
+
+ void buildSumGroups() {
+ for ( int a = 0; a < maxDepth; a++ ) {
+ sumVecs_[ a ].rawResize( text_.size() );
+ }
+
+ SumBuildState< SumType, 0, maxDepth > state( sumVecs_, text_.c_str() );
+
+ uint textSize = text_.size();
+
+ for ( uint a = 0; a < textSize; a++ ) {
+ state.go();
+ }
+ }
+#else
+ void buildSumGroups() {
+ for ( int a = 0; a < maxDepth; a++ ) {
+ sumVecs_[ a ].rawResize( text_.size() );
+ }
+
+ const char* text = text_.c_str();
+ uint textSize = text_.size();
+
+ for ( uint b = 0; b < maxDepth; b++ ) {
+
+ SumType* v = &( sumVecs_[ b ][ 0 ] );
+ uint tempSumC = 0;
+ SumType tempSum = 0;
+ uint maxCount = 1 << b;
+
+ const char* ctext = text;
+
+ for ( uint a = 0; a < textSize; a++ ) {
+ if ( tempSumC == maxCount ) {
+ ///remove the first summand
+ tempSum -= *( ctext - maxCount );
+ } else {
+ tempSumC ++;
+ }
+
+ tempSum += ( *ctext );
+
+ ( *v ) = tempSum;
+ ++v;
+ ++ctext;
+ }
+ }
+ }
+#endif
+
+ public:
+ NextOrderType nextOrder_;
+
+ SumSearch( const string& text ) : nextOrder_( text ) {
+ text_ = text;
+ buildSumGroups();
+ }
+
+ ///position != 0
+ SumReference<maxDepth, SumType, order> getReference( int position ) {
+ SumReference<maxDepth, SumType, order> ret;
+ fillReference( ret, position );
+
+ nextOrder_.fillReference( ret, position );
+ return ret;
+ }
+
+
+ ///Should not be used from outside
+ void fillReference( SumReference<maxDepth, SumType, order>& ret, int position ) {
+ int leftPos = position - 1;
+ SumType leftSums[ maxDepth ];
+ SumType rightSums[ maxDepth ];
+
+ if ( leftPos >= 0 ) {
+ for ( int a = 0; a < maxDepth; a++ )
+ leftSums[ a ] = sumVecs_[ a ] [ leftPos ];
+ } else {
+ for ( int a = 0; a < maxDepth; a++ )
+ leftSums[ a ] = 0;
+ }
+
+ for ( int a = 0; a < maxDepth; a++ ) {
+ uint pos = leftPos + ( 1 << a );
+ if ( pos < sumVecs_[ 0 ].size() )
+ rightSums[ a ] = sumVecs_[ a ][ pos ];
+ else
+ rightSums[ a ] = 0;
+ }
+
+ ret.leftMarker = SumGroup<maxDepth, SumType>( leftSums );
+ ret.rightMarker = SumGroup<maxDepth, SumType>( rightSums );
+ ret.setValid( true );
+ }
+
+
+ struct SimpleEvaluator {
+ SumType minDif;
+ uint minDifPos;
+
+ SimpleEvaluator() : minDif( 100000 ), minDifPos( -1 ) {}
+ /**This should return a new compound difference-value. In the end, the position with the lowest difference will be returned,
+ *so this may be used to implement some weighting, maybe according to the position */
+ inline void operator () ( const SumType leftDifference, const SumType rightDifference, const uint position ) {
+ SumType dif = ( leftDifference + 1 ) * ( rightDifference + 1 );
+
+ if ( dif < minDif ) {
+ //cout << "best dif: " << dif << endl;
+ minDif = dif;
+ minDifPos = position;
+ }
+ }
+
+ uint result() {
+ return minDifPos;
+ }
+ };
+
+ SumVector* sumVecs() {
+ return sumVecs_;
+ }
+
+ template <class Evaluator>
+ struct FindReferenceProgress {
+ SumReference<maxDepth, SumType, order>& ref;
+ Evaluator& eval;
+
+ typename NextOrderType::template FindRefProgress<SelfSumSearch, Evaluator>
+ nextOrder_;
+
+ SumType* leftOffset[ maxDepth ];
+ SumType* rightOffset[ maxDepth ];
+
+ SumType* firstItem;
+ SumType* finalRight[ maxDepth ];
+
+ SumVector* sumVecs_;
+
+ typename SumGroup<maxDepth, SumType>::VecSumGetter leftGetter;
+ typename SumGroup<maxDepth, SumType>::VecSumGetter rightGetter;
+ typedef typename SumGroup<maxDepth, SumType>::ZeroGetter ZeroGetter;
+
+ FindReferenceProgress( SelfSumSearch& search, const SumReference<maxDepth, SumType, order>& _ref, Evaluator& _eval ) : ref( const_cast<SumReference<maxDepth, SumType, order>&>( _ref ) ), eval( _eval ), nextOrder_( search, ref, _eval ), sumVecs_( search.sumVecs() ) {
+ for ( uint a = 0; a < maxDepth; a++ ) {
+ leftOffset[ a ] = &( sumVecs_[ a ][ 0 - 1 ] );
+
+ if ( ( uint ) ( 1 << a ) < ( uint ) sumVecs_[ 0 ].size() ) {
+ rightOffset[ a ] = &( sumVecs_[ a ][ ( 1 << a ) - 1 ] );
+ } else {
+ rightOffset[ a ] = 0;
+ }
+ }
+
+ firstItem = &sumVecs_[ 0 ][ 0 ];
+
+ for ( int a = 0; a < maxDepth; a++ )
+ finalRight[ a ] = &( sumVecs_[ a ][ sumVecs_[ a ].size() - 1 ] );
+
+ leftGetter = typename SumGroup<maxDepth, SumType>::VecSumGetter( leftOffset );
+ rightGetter = typename SumGroup<maxDepth, SumType>::VecSumGetter( rightOffset );
+ }
+
+ operator bool() {
+ return ( bool ) rightOffset[ 0 ];
+ }
+
+ void next() {
+ for ( int a = 0; a < maxDepth; a++ ) {
+ ++leftOffset[ a ];
+ if ( !rightOffset[ a ] )
+ break;
+ ++rightOffset[ a ];
+ if ( rightOffset[ a ] > finalRight[ a ] )
+ rightOffset[ a ] = 0;
+ }
+ nextOrder_.next();
+ }
+
+ SumType leftDiff() {
+ if ( leftOffset[ 0 ] < firstItem ) {
+ return ref.leftMarker.sumDifference( ZeroGetter() ) + nextOrder_.leftDiff();
+ }
+ return ref.leftMarker.sumDifference( leftGetter ) + nextOrder_.leftDiff();
+ }
+
+ SumType rightDiff() {
+ return ref.rightMarker.sumDifference( rightGetter ) + nextOrder_.rightDiff();
+ }
+
+ uint difPos() {
+ return ( ((unsigned long)rightOffset[ 0 ] ) - (unsigned long)firstItem ) / sizeof( uint* );
+ }
+ };
+
+ template <class Evaluator>
+ int findReference( const SumReference<maxDepth, SumType, order>& ref, Evaluator& eval ) {
+ if ( !ref.isValid() )
+ return -1;
+ if ( sumVecs_[ 0 ].size() < 2 )
+ return -1;
+
+ FindReferenceProgress<Evaluator> prog( *this, ref, eval );
+
+ while ( prog ) {
+ SumType leftDif = 0; //prog.leftDiff();
+ SumType rightDif = prog.rightDiff();
+ uint difPos = prog.difPos();
+
+ eval( leftDif, rightDif, difPos );
+
+ prog.next();
+ }
+ return eval.result();
+ }
+
+ ///This uses the default-evaluator
+ inline int findReference( const SumReference<maxDepth, SumType, order>& ref ) {
+ SimpleEvaluator eval;
+ return findReference( ref, eval );
+ }
+};
+
+
+template <int maxDepth, typename SumType, int order>
+class DifferenceSumSearch<maxDepth, SumType, order, false> {
+ typedef SumSearch<maxDepth, SumType, order> MySearch;
+ typedef SumSearch < maxDepth, SumType, order + 1 > MyPrevSearch;
+ MySearch search_;
+
+ static string makeDifference( const string& str ) {
+ string ret = str;
+ uint len = ret.length();
+ char last = 0;
+ if ( !ret.empty() )
+ last = ret[ 0 ];
+
+ for ( uint n = 0; n < len; n++ ) {
+ char r = ret[ n ];
+ ret[ n ] = r - last;
+ last = r;
+ }
+ return ret;
+ }
+
+ public:
+ DifferenceSumSearch( const string& text ) : search_( makeDifference( text ) ) {}
+
+ template <class Type>
+ void fillReference( Type& t, int position ) {
+ search_.fillReference( t.nextOrder_.reference_, position );
+ }
+
+ template <class PrevSearch, class Evaluator>
+ struct FindRefProgress {
+ typename MySearch:: template FindReferenceProgress<Evaluator>
+ find;
+
+ FindRefProgress( PrevSearch& search, const SumReference < maxDepth, SumType, order + 1 > & _ref, Evaluator& _eval ) : find( search.nextOrder_.search_, _ref.nextOrder_.reference_, _eval )
+ {}
+
+ SumType leftDiff() {
+ return find.leftDiff();
+ }
+ SumType rightDiff() {
+ return find.rightDiff();
+ }
+
+ void next() {
+ find.next();
+ }
+ };
+};
+
+
+} //FuzzySearch
+
+using namespace FuzzySearch;
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/sumsearch.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/nvp.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/nvp.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/nvp.h (revision 1522570)
@@ -0,0 +1,26 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef NVP_H
+#define NVP_H
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/nvp.hpp>
+
+///NVP means Name-Value-Pair, and is used for serialization into Xml-Archives
+#undef NVP
+#define NVP(x) BOOST_SERIALIZATION_NVP(x)
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/nvp.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp (revision 1522570)
@@ -0,0 +1,223 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "indocumentreference.h"
+#include "utils.h"
+
+/* Exclude this file from doublequote_chars check as krazy doesn't understand
+std::string*/
+//krazy:excludeall=doublequote_chars
+
+QString InDocumentReference::createReference( const QString& file, int startLine, int startCol, int endLine, int endCol ) {
+ QString ret = file;
+ if( startLine != -1 ) ret.append( QString( ":%1" ).arg( startLine ) );
+ if( startCol != -1 ) ret.append( QString( ":%1" ).arg( startCol ) );
+ if( endLine != -1 ) ret.append( QString( ":%1" ).arg( endLine ) );
+ if( endCol != -1 ) ret.append( QString( ":%1" ).arg( endCol ) );
+ return ret;
+}
+
+void InDocumentReference::parseReference( const QString& ref, QString& file, int& startLine, int& startCol, int& endLine, int& endCol ) {
+ file = "";
+ startLine = endLine = startCol = endCol = -1;
+ if ( ref.indexOf( ':' ) != -1 ) {
+ file = ref.left( ref.indexOf( ':' ) );
+
+ QString tail = ref.mid( file.length()+1 );
+
+ int refs[4] = {-1, -1, -1, -1};
+ for( int a = 0; a < 4; a++ ) {
+ if( tail.isEmpty() ) break;
+ int nextPos = tail.indexOf( ':' );
+ if( nextPos == -1 ) nextPos = tail.length();
+ refs[a] = tail.left( nextPos ).toInt();
+ tail = tail.mid( nextPos+1 );
+ if( tail.isEmpty() ) break;
+ }
+
+ startLine = refs[0];
+ startCol = refs[1];
+ endLine = refs[2];
+ endCol = refs[3];
+ }
+}
+
+///This creates a reference that refers to a position, but not intelligently.
+InDocumentReference::InDocumentReference( bool start, const QString& ref ) : m_line( -1 ), m_col( -1 ) {
+ int d1, d2;
+ QString doc;
+ if( start )
+ parseReference( ref, doc, m_line, m_col, d1, d2 );
+ else
+ parseReference( ref, doc, d1, d2, m_line, m_col );
+ m_document = ~doc;
+}
+
+InDocumentReference::InDocumentReference( const QString& document, int line, int col, const QString& text ) {
+ m_line = line;
+ m_document = ~document;
+ m_col = col;
+ if ( !text.isEmpty() )
+ useText( text );
+}
+
+void InDocumentReference::useText( const QString& text ) {
+ if ( m_line == -1 )
+ return ;
+ int index = lineColToIndex( text, m_line, m_col == -1 ? 0 : m_col );
+ if ( index != -1 ) {
+ SumSearch<10> search( ~text );
+ m_position = search.getReference( index );
+ }
+}
+
+QString InDocumentReference::document() const {
+ return ~m_document;
+}
+
+struct InDocumentReference::TextSearchInstance::Private : public Shared {
+ SumSearch<10> search;
+ QString text;
+
+ Private( const QString& txt ) : search( ~txt ), text( txt ) {
+
+ }
+};
+
+
+InDocumentReference::TextSearchInstance::TextSearchInstance( const TextSearchInstance& rhs ) {
+ *this = rhs;
+}
+
+InDocumentReference::TextSearchInstance::TextSearchInstance( const QString& txt ) {
+ m_data = new Private( txt );
+}
+
+InDocumentReference::TextSearchInstance::TextSearchInstance() {
+}
+
+QString InDocumentReference::TextSearchInstance::text() const {
+ if( !m_data ) return "";
+ else
+ return m_data->text;
+}
+
+InDocumentReference::TextSearchInstance::~TextSearchInstance() {
+}
+
+InDocumentReference::TextSearchInstance& InDocumentReference::TextSearchInstance::operator = ( const TextSearchInstance& rhs ) {
+ m_data = rhs.m_data;
+ return *this;
+}
+
+InDocumentReference::TextSearchInstance::operator bool() const {
+ return (bool)m_data;
+}
+
+///Finds the reference-position dynamically within the given text. If the search fails, puts -1 -1.
+void InDocumentReference::findInText( const TextSearchInstance& text, int& line, int& col ) const {
+ if ( !isValid() || !text ) {
+ line = -1;
+ col = -1;
+ return ;
+ }
+ int pos = text.m_data->search.findReference( m_position );
+
+ if ( pos == -1 ) {
+ line = -1;
+ col = -1;
+ return ;
+ /*
+ ///Fall bock to returning the fixed line- and column-numbers
+ line = m_line;
+ if( m_col != -1 )
+ col = m_col;
+ else
+ col = 0; */
+ } else {
+ indexToLineCol( pos, text.m_data->text, line, col );
+ }
+}
+
+bool InDocumentReference::isValid() const {
+ return ( m_line != -1 ) && !m_document.empty();
+}
+
+bool InDocumentReference::isDynamic() const {
+ return m_position.isValid();
+}
+
+InDocumentReference::operator bool() const {
+ return isValid();
+}
+
+///findInText(..) should be preferred, because it can find the correct position even if the text changed.
+int InDocumentReference::line() const {
+ return m_line;
+}
+
+QString InDocumentReference::asText() const {
+ QString ret = QString( "%1" ).arg( m_line );
+ if ( m_col != 0 && m_col != -1 )
+ ret += QString( ":%1" ).arg( m_col );
+ if ( m_position.isValid() )
+ ret = "~" + ret;
+ return ret;
+}
+
+int InDocumentReference::col() const {
+ if ( m_col != -1 )
+ return m_col;
+ else
+ return 0;
+}
+
+DocumentContextLines::DocumentContextLines() : m_lineOffset( 0 ) {}
+
+DocumentContextLines::DocumentContextLines( const InDocumentReference& beginRef, const InDocumentReference& endRef, const QString& text, int /*contextSize*/ ) : m_lineOffset( 0 ) {
+ int startLine = beginRef.line();
+ int endLine = endRef.line();
+ if ( startLine == -1 )
+ return ;
+ m_lineOffset = startLine - 5;
+ if ( endLine == -1 )
+ endLine = startLine;
+ int end = endLine + 5;
+ if ( m_lineOffset < 0 )
+ m_lineOffset = 0;
+ if ( end < m_lineOffset )
+ end = m_lineOffset + 1;
+
+ int i = lineColToIndex( text, m_lineOffset, 0 );
+ if ( i == -1 ) {
+ m_lineOffset = 0;
+ return ;
+ }
+ int endI = lineColToIndex( text, end, 0 );
+ if ( endI == -1 )
+ endI = text.size();
+
+ m_lines = ~text.mid( i, endI - i );
+}
+
+DocumentContextLines::operator bool() const {
+ return !m_lines.empty();
+}
+
+QString DocumentContextLines::text() const {
+ return ~m_lines;
+}
+
+int DocumentContextLines::lineOffset() const {
+ return m_lineOffset;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.h (revision 1522570)
@@ -0,0 +1,54 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVTEAMWORK_UTILS
+#define KDEVTEAMWORK_UTILS
+
+#include <QString>
+#include <string>
+#include <ostream>
+
+QString toQ( const std::string& rhs );
+std::string fromQ( const QString& str );
+
+///This operator converts between Q- and std-classes
+std::string operator ~ ( const QString& rhs );
+
+QString operator ~ ( const std::string& rhs );
+
+std::ostream& operator << ( std::ostream& stream, const QString& str );
+
+void indexToLineCol( int index, const QString& text, int& line, int& col );
+
+///Returns -1 if the index does not exist
+int lineColToIndex( const QString& text, int line, int col );
+
+void indexToLineCol( int index, const std::string& text, int& line, int& col );
+
+///Returns -1 if the index does not exist
+int lineColToIndex( const std::string& text, int line, int col );
+
+struct Block {
+ bool& b;
+ bool old;
+ Block( bool& bl ) : b( bl ), old(bl) {
+ b = true;
+ }
+ ~Block() {
+ b = old;
+ }
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h (revision 1522570)
@@ -0,0 +1,99 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef TEAMWORKFOLDERMANAGER_H
+#define TEAMWORKFOLDERMANAGER_H
+
+#include <kurl.h>
+#include <QString>
+#include <QMap>
+
+/**Since KDevelop now is no single-project application any more,
+ * a notion of a workspace is necessary so teamwork is possible across multiple projects.
+ * The workspace-directory is the directory where the .teamwork-subfolder with all the teamwork-data
+ * will be created, and file-collaboration is possible on subfolders of that workspace.
+ * Of course the workspace-directory could be a simple project-directory.
+ * This class manages the .teamwork-subfolder of the workspace.
+ * */
+class TeamworkFolderManager {
+ public:
+ TeamworkFolderManager( const KUrl& directory );
+ ~TeamworkFolderManager();
+ /**
+ * This function creates an empty file.
+ * This function throws QString on errors.
+ * @param subFolder can be a whole sub-tree which will be created if it doesn't exist.
+ * @param extension the extension of the file to create, without dot(example "cpp")
+ * @param name name of the file. If a file with that name already exists, it will be prefixed to be unique.
+ * @return the absolute URL of the file
+ * */
+ static KUrl createUniqueFile( const QString& subFolder, const QString& extension, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString);
+
+ static KUrl createUniqueDirectory( const QString& subFolder, const QString& name, const QString& namePrefix = "", const QString& nameSuffix = "" ) throw(QString);
+
+ /** This takes a complete reference-filename which may include folders(those will be created), and from which extension and name will be extracted.(see function above)
+ * */
+ static KUrl createUniqueFile( const QString& subFolder, const QString& fileName, const QString& namePrefix = "", const QString& nameSuffix = "" ) throw(QString);
+
+ /**
+ * This may be called with a file/folder. On destruction of the class(close of the workspace), that folder will automatically be deleted.
+ * @param url Complete url of the file/folder to be deleted on destruction. It must be a subfolder of the .teamwork-folder.
+ * */
+ static void registerTempItem( const KUrl& file );
+
+ /**
+ * @param subfolder a subfolder of .teamwork that the url will be relative to
+ * @return the URL relative to the .teamwork-directory
+ * */
+ static QString teamworkRelative( const KUrl& url, const QString& subfolder = QString() );
+
+ /**
+ * @param subfolder a subfolder of workspace-dir that the url will be relative to
+ * @return the URL relative to the workspace-directory
+ * */
+ static QString workspaceRelative( const KUrl& url, const QString& subfolder = QString() );
+
+ /**
+ * @param subFolder an additional subFolder of workspace-dir that the sub-url is in
+ * @return the absolute directory of the given sub-directory
+ * */
+ static KUrl workspaceAbsolute( const QString& subPath, const QString& subFolder = QString() );
+
+ /**
+ * @param subFolder an additional subFolder of .teamwork that the sub-url is in
+ * @return the absolute directory of the given sub-directory of the .teamwork-folder
+ * */
+ static KUrl teamworkAbsolute( const QString& subPath, const QString& subFolder = QString() );
+
+ static KUrl workspaceDirectory();
+
+ static TeamworkFolderManager* self();
+
+ /**
+ * Creates the .teamwork folder if it does not exist yet.
+ **/
+ static void createTeamworkFolder() throw(QString);
+
+ private:
+ static bool createFile( const KUrl& url );
+ static TeamworkFolderManager* m_self;
+
+ KUrl m_teamworkDir;
+ KUrl m_workspaceDir;
+
+ QMap<QString, bool> m_tempItems;
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.h (revision 1522570)
@@ -0,0 +1,27 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef HELPERS_H
+#define HELPERS_H
+
+#include "teamworkfwd.h"
+
+///This header contains little helper-functions that have no other dependencies than teamworkfwd.h
+
+/**Returns the user the session is pointing to, and returns zero if the session is zero.
+ * */
+Teamwork::UserPointer userFromSession( const Teamwork::SessionPointer& session );
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/helpers.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.h (revision 1522570)
@@ -0,0 +1,64 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef VERIFY_H
+#define VERIFY_H
+
+#include <string>
+#include <sstream>
+
+struct ExpressionError {
+ std::string function;
+ int line;
+ std::string file;
+ std::string expression;
+ std::string realExpression;
+ ExpressionError( const std::string& fun, int l, const std::string& f, const std::string& exp, const std::string& realExp = "" );
+ std::string what() const;
+};
+
+#ifndef HAVE_TOTEXT
+#define HAVE_TOTEXT
+
+template <class Item>
+std::string toText( const Item& it ) {
+ std::ostringstream os;
+ os << it;
+ return os.str();
+}
+#endif
+
+#define VERIFY( x ) if( x ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ); }
+#define VERIFY_SAME( a, b ) if( a == b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ); }
+#define VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ); }
+#define VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ); }
+#define VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ); }
+
+
+///These throw a std::string
+#define S_VERIFY( x ) if( x ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ).what(); }
+#define S_VERIFY_SAME( a, b ) if( a == b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ).what(); }
+#define S_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ).what(); }
+#define S_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ).what(); }
+#define S_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ).what(); }
+
+///These throw a QString
+#define Q_VERIFY( x ) if( x ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ).what().c_str() ); }
+#define Q_VERIFY_SAME( a, b ) if( a == b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ).what().c_str() ); }
+#define Q_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ).what().c_str() ); }
+#define Q_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ).what().c_str() ); }
+#define Q_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ).what().c_str() ); }
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/verify.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.h (revision 1522570)
@@ -0,0 +1,26 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef KDEVUTILS_H
+#define KDEVUTILS_H
+#include <QString>
+
+/** Returns the path of the current document,
+ * relative to the workspace-directory.
+ *
+ * Throws a QString on error */
+QString currentDocumentPath();
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevutils.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.h (revision 1522570)
@@ -0,0 +1,85 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef INDOCUMENTMESSAGE_H
+#define INDOCUMENTMESSAGE_H
+
+#include "kdevteamwork_messages.h"
+#include "indocumentreference.h"
+
+class DocumentMessageInternal;
+class InDocumentConversation;
+
+class InDocumentMessage : public KDevTeamworkTextMessage {
+ DECLARE_MESSAGE( InDocumentMessage, KDevTeamworkTextMessage, 3 );
+ InDocumentReference m_start, m_end;
+ string m_context;
+ auto_ptr<DocumentMessageInternal> m_internal;
+
+ DocumentContextLines m_contextLines;
+
+ enum {
+ MessageVersion = 1
+ };
+
+ template <class Arch>
+ void serial( Arch& arch ) {
+ int v = MessageVersion;
+ arch & v;
+
+ arch & m_start & m_end & m_context;
+
+ if ( v >= 1 )
+ arch & m_contextLines;
+ }
+
+ public:
+
+ InDocumentMessage( const Teamwork::MessageConstructionInfo& info, const QString& text, const InDocumentReference& startRef, const InDocumentReference& endRef, const QString& context );
+
+ InDocumentMessage( InArchive& from, const Teamwork::MessageInfo& info );
+
+ virtual void serialize( OutArchive& arch );
+
+ ///Context means the name of a conversation-thread
+ QString context();
+
+ ///Can be used to get and set the context-lines
+ DocumentContextLines& contextLines() ;
+
+ QString document();
+
+ InDocumentReference& start();
+
+ InDocumentReference& end() ;
+
+ virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
+
+ virtual QIcon messageIcon() const;
+
+ void setConversation( InDocumentConversation* conv );
+
+ virtual bool needReply() const;
+
+ virtual void result( bool success );
+
+ virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
+
+ virtual QString shortName() const;
+
+ virtual void showInWidget( QWidget* widget, KDevTeamwork* tw );
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/indocumentmessage.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.h (revision 1522570)
@@ -0,0 +1,95 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGEMANAGER_H
+#define MESSAGEMANAGER_H
+#include <list>
+#include "kdevteamwork_messages.h"
+#include "utils.h"
+#include "indocumentmessage.h"
+#include "autoconstructpointer.h"
+
+class QDomElement;
+class KDevTeamwork;
+class LocalPatchSource;
+class KDevTeamworkTextMessage;
+class MessageHistory;
+class MessageHistoryManager;
+class QAction;
+//class LocalPatchSource::Identity;
+
+class KDevTeamworkUser;
+
+typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
+
+class ConversationManager;
+
+
+BIND_LIST_2( MessageManagerMessages, KDevTeamworkTextMessage, InDocumentMessage )
+
+/** This class manages the KDevTeamworkTextMessage-based messages
+ */
+
+class MessageManager : public QObject {
+ Q_OBJECT
+ public:
+ MessageManager( KDevTeamwork* tw );
+ ~MessageManager();
+
+ void restorePartialProjectSession( const QDomElement* el );
+
+ void savePartialProjectSession( QDomElement* el );
+
+ int receiveMessage( MessageInterface* msg );
+ int receiveMessage( KDevTeamworkTextMessage* msg );
+ int receiveMessage( InDocumentMessage* msg );
+
+ int processMessage( KDevTeamworkTextMessage* msg );
+
+ KDevTeamwork* teamwork();
+
+ void log( const QString& str, LogLevel level = Info );
+
+ MessageHistoryManager& historyManager();
+ ConversationManager& conversationManager();
+
+ void showMessageHistory( const QList<KDevTeamworkUserPointer>& users = QList<KDevTeamworkUserPointer>(), const QString& context = "" );
+
+ void fillMessageMenu( QMenu* menu, MessagePointer msg );
+
+ void showMessage( const MessagePointer& msg );
+
+ public slots:
+ ///This can be used to indicate that information about the message(like icon, text, etc.) has been changed.
+ void updateMessage( const MessagePointer& msg );
+ void slotShowMessage();
+ void init();
+
+ signals:
+ ///Is emitted whenver a message is reported to have changed.(through updateMessage(..))
+ void messageUpdated( const MessagePointer& msg );
+
+ private:
+ MessageDispatcher<MessageManager, MessageManagerMessages> dispatcher_;
+ KDevTeamwork* m_teamwork;
+
+ AutoConstructPointer<ConversationManager> m_conversationManager;
+ AutoConstructPointer<MessageHistoryManager> m_historyManager;
+
+ QAction* m_showMessageAction;
+};
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagemanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.h (revision 1522570)
@@ -0,0 +1,60 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef MESSAGESENDMANAGER_H
+#define MESSAGESENDMANAGER_H
+
+#include <QObject>
+#include <QPointer>
+#include "ui_kdevteamwork_interface.h"
+#include <ktexteditor/range.h>
+
+namespace KDevelop {
+class IDocument;
+}
+
+namespace KTextEditor {
+ class View;
+ class Document;
+}
+
+/**This cares about the "send message"-tab in the kdevteamwork user-interface by updating it, according to the current selection in the current document.
+ * */
+class MessageSendManager : public QObject {
+ Q_OBJECT
+ public:
+ MessageSendManager( Ui::Teamwork& widgets );
+
+ private slots:
+ void documentActivated( KDevelop::IDocument* document );
+ void documentClosed( KDevelop::IDocument* document );
+ void documentDestroyed( QObject* obj );
+ void selectionChanged( KTextEditor::View* );
+ void viewCreated( KTextEditor::Document* , KTextEditor::View* );
+ private:
+ void connectView( KTextEditor::View* view );
+ void connectDocument( KDevelop::IDocument* );
+ void disconnectDocument();
+ Ui::Teamwork& m_widgets;
+ KDevelop::IDocument* m_lastDocument;
+
+ KTextEditor::View* view();
+
+ KUrl m_currentFile; ///Currently edited file
+ KTextEditor::Range m_currentSelection; ///Current selection within that file
+};
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messagesendmanager.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.cpp (revision 1522570)
@@ -0,0 +1,51 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "serializationutils.h"
+#include <sstream>
+
+#ifdef XML_USE_TEXT_ARCHIVE
+#include <boost/archive/polymorphic_text_iarchive.hpp>
+#include <boost/archive/polymorphic_text_oarchive.hpp>
+typedef boost::archive::polymorphic_text_iarchive XmlIArchive;
+typedef boost::archive::polymorphic_text_oarchive XmlOArchive;
+#else
+#include <boost/archive/polymorphic_xml_iarchive.hpp>
+#include <boost/archive/polymorphic_xml_oarchive.hpp>
+typedef boost::archive::polymorphic_xml_iarchive XmlIArchive;
+typedef boost::archive::polymorphic_xml_oarchive XmlOArchive;
+#endif
+
+struct IArchiveContainer::Private {
+ XmlIArchive arch;
+ Private( istream& str ) : arch( str ) {
+ }
+};
+
+struct OArchiveContainer::Private {
+ XmlOArchive arch;
+ Private( ostream& str ) : arch( str ) {
+ }
+};
+IArchiveContainer::IArchiveContainer( istream& str ) : priv( new Private( str ) ), arch( priv->arch ) {
+}
+
+IArchiveContainer::~IArchiveContainer() {
+ delete priv;
+}
+
+OArchiveContainer::OArchiveContainer( ostream& str ) : priv( new Private( str ) ), arch( priv->arch ) {
+}
+
+OArchiveContainer::~OArchiveContainer() {
+ delete priv;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.cpp (revision 1522570)
@@ -0,0 +1,109 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#include "messageusertab.h"
+
+#include <QWidget>
+#include<QListView>
+#include<QStandardItemModel>
+
+#include "kdevteamwork.h"
+#include "kdevteamwork_user.h"
+#include <QMetaType>
+#include "ui_kdevteamwork_interface.h"
+#include "utils.h"
+#include "kdevteamwork_messages.h"
+
+Q_DECLARE_METATYPE( MessagePointer )
+
+
+MessageUserTab& MessageUserTab::operator = ( const MessageUserTab& /*rhs*/ ) {
+ return * this;
+}
+
+MessageUserTab::~MessageUserTab() {
+ delete m_widget;
+}
+
+bool MessageUserTab::operator < ( const MessageUserTab& rhs ) {
+ return m_user < rhs.m_user;
+}
+
+MessageUserTab::MessageUserTab( KDevTeamwork* tw, KDevTeamworkUserPointer user ) : m_user( user ), m_teamwork( tw ) {
+ m_widget = new QWidget;
+ m_list->setupUi( m_widget );
+ qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
+ m_view = m_list->list;
+ m_model = new QStandardItemModel( 0, 1, m_widget );
+ m_view->setModel( m_model );
+ KDevTeamworkUserPointer::Locked l = user;
+ if ( l ) {
+ tw->m_widgets->messageUsers->addTab( m_widget, l->icon(), ~l->safeName() );
+ connect( l.data(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged( KDevTeamworkUserPointer ) ), Qt::QueuedConnection );
+ }
+ connect( m_view, SIGNAL( clicked( const QModelIndex& ) ), tw, SLOT( messageClicked( const QModelIndex& ) ) );
+
+ userStateChanged( m_user );
+}
+
+void MessageUserTab::userStateChanged( KDevTeamworkUserPointer ) {
+ if ( !m_teamwork->m_widget )
+ return ;
+ int i = m_teamwork->m_widgets->messageUsers->indexOf( m_widget );
+ if ( i != -1 ) {
+ KDevTeamworkUserPointer::Locked l = m_user;
+ if ( l ) {
+ m_teamwork->m_widgets->messageUsers->setTabIcon( i, l->icon() );
+ }
+ }
+}
+
+void MessageUserTab::messageUpdated( const Teamwork::MessagePointer& msg ) {
+ for ( int a = 0; a < m_model->rowCount(); ++a ) {
+ QModelIndex i = m_model->index( a, 0 );
+ if ( i.isValid() ) {
+ QVariant v = m_model->data( i, Qt::UserRole );
+ if ( v.canConvert<MessagePointer>() ) {
+ if ( v.value<MessagePointer>() == msg ) {
+ MessagePointer::Locked l = msg;
+ if ( l ) {
+ AbstractGUIMessage * guiMsg = l.freeCast<AbstractGUIMessage>();
+ if ( guiMsg ) {
+ m_model->setData( i, guiMsg->messageIcon(), Qt::DecorationRole );
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+QStandardItemModel* MessageUserTab::model() {
+ return m_model;
+}
+
+QListView* MessageUserTab::view() {
+ return m_view;
+}
+
+KDevTeamworkUserPointer MessageUserTab::user() {
+ return m_user;
+}
+
+QWidget* MessageUserTab::widget() {
+ return m_widget;
+}
+
+#include "messageusertab.moc"
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/messageusertab.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/loglevel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/loglevel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/loglevel.h (revision 1522570)
@@ -0,0 +1,26 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef LOGLEVEL_H
+#define LOGLEVEL_H
+
+#include <QIcon>
+enum LogLevel {
+ Info = 1,
+ Warning = 2,
+ Error = 4,
+ Debug = 8
+};
+
+QIcon iconFromLevel( LogLevel lv );
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/loglevel.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h (revision 1522570)
@@ -0,0 +1,105 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef AUTO_CONSTRUCT_POINTER_H
+#define AUTO_CONSTRUCT_POINTER_H
+
+/**This is a pointer-class that can be used as a simple wrapper to have the same safety
+*as using normal element-classes, but allows the classes to be forward-declared. Also
+*it features serialization.
+*It cannot be zero! */
+
+class NormalSerialization;
+
+template <class T, class Serialization = NormalSerialization>
+class AutoConstructPointer {
+ T* m_data;
+
+ public:
+
+ AutoConstructPointer() {
+ m_data = new T();
+ }
+
+ AutoConstructPointer( const AutoConstructPointer& rhs ) {
+ m_data = new T( *rhs );
+ }
+
+ AutoConstructPointer& operator = ( const AutoConstructPointer& rhs ) {
+ return * this;
+ }
+
+ template <class Param>
+ AutoConstructPointer( Param& param ) {
+ m_data = new T( param );
+ }
+
+ template <class Param>
+ AutoConstructPointer( const Param& param ) {
+ m_data = new T( param );
+ }
+ template <class Param, class Param2>
+ AutoConstructPointer( Param& param, Param2& param2 ) {
+ m_data = new T( param, param2 );
+ }
+
+ ~AutoConstructPointer() {
+ delete m_data;
+ }
+
+ void reset( T* t ) {
+ m_data = t;
+ }
+
+ T& operator *() {
+ return * m_data;
+ }
+
+ const T& operator *() const {
+ return * m_data;
+ }
+
+ T* data() {
+ return m_data;
+ }
+
+ operator const T* () const {
+ return m_data;
+ }
+
+ operator T* () {
+ return m_data;
+ }
+
+ const T* data() const {
+ return m_data;
+ }
+
+ T* operator -> () {
+ return m_data;
+ }
+
+ const T* operator -> () const {
+ return m_data;
+ }
+
+ template <class Archive>
+ void serialize( Archive& arch, uint /*version*/ ) {
+ arch & ( *data() );
+ }
+};
+
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.cpp (revision 1522570)
@@ -0,0 +1,123 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "utils.h"
+#include <QDomDocument>
+#include <QDomNode>
+#include <QTextStream>
+#include <sstream>
+#include <iostream>
+//#include <ostringstream>
+#include <QList>
+#include <QByteArray>
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/split_free.hpp>
+#include <boost/serialization/level.hpp>
+#include <boost/serialization/traits.hpp>
+#include <boost/serialization/level_enum.hpp>
+
+
+QString toQ( const std::string& str ) {
+ return QString::fromUtf8( str.c_str() );
+ //return QString::fromStdString( str );
+}
+
+std::string fromQ( const QString& str ) {
+ return str.toUtf8().data();
+ //return QString::toStdString( str );
+}
+
+std::string operator ~ ( const QString& rhs ) {
+ return fromQ( rhs );
+}
+
+QString operator ~ ( const std::string& rhs ) {
+ return toQ(rhs );
+}
+
+std::ostream& operator << ( std::ostream& stream, const QString& str ) {
+ stream << str.toUtf8().data();
+ return stream;
+}
+
+void indexToLineCol( int position, const QString& text, int& line, int& col ) {
+ line = 0;
+ col = 0;
+ int tlen = (int)text.length();
+ for( int a = 0; a < tlen; a++ )
+ {
+ if( a == position ) return;
+ if( text[a] == '\n' ) {
+ line++;
+ col = 0;
+ } else {
+ col++;
+ }
+ }
+ return;
+}
+
+int lineColToIndex( const QString& text, int sline, int scol ) {
+ int line = 0;
+ int col = 0;
+ int tlen = (int)text.length();
+ for( int a = 0; a < tlen; a++ )
+ {
+ if( line == sline && col == scol ) return a;
+ if( text[a] == '\n' ) {
+ line++;
+ col = 0;
+ } else {
+ col++;
+ }
+ }
+ if( line == sline && col == scol ) return tlen; ///Include the last bounding index
+ return -1;
+}
+
+void indexToLineCol( int position, const std::string& text, int& line, int& col ) {
+ line = 0;
+ col = 0;
+ int tlen = (int)text.length();
+ for( int a = 0; a < tlen; a++ )
+ {
+ if( a == position ) return;
+ if( text[a] == '\n' ) {
+ line++;
+ col = 0;
+ } else {
+ col++;
+ }
+ }
+ return;
+}
+
+int lineColToIndex( const std::string& text, int sline, int scol ) {
+ int line = 0;
+ int col = 0;
+ int tlen = (int)text.length();
+ for( int a = 0; a < tlen; a++ )
+ {
+ if( line == sline && col == scol ) return a;
+ if( text[a] == '\n' ) {
+ line++;
+ col = 0;
+ } else {
+ col++;
+ }
+ }
+ if( line == sline && col == scol ) return tlen; ///Include the last bounding index
+ return -1;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/utils.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.h (revision 1522570)
@@ -0,0 +1,226 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#ifndef SERIALIZATION_UTILS_H
+#define SERIALIZATION_UTILS_H
+
+///Unfortunately it seems that boost doesn't like the things that Qt syntactically does to the xml-syntax.
+///It fails to load logically same documents when they come from QDom, so we embed the data as simple text into the xml-document.
+
+#define XML_USE_TEXT_ARCHIVE
+
+#ifdef XML_USE_TEXT_ARCHIVE
+#include <boost/archive/polymorphic_text_iarchive.hpp>
+#include <boost/archive/polymorphic_text_oarchive.hpp>
+typedef boost::archive::polymorphic_text_iarchive XmlIArchive;
+typedef boost::archive::polymorphic_text_oarchive XmlOArchive;
+#else
+#include <boost/archive/polymorphic_xml_iarchive.hpp>
+#include <boost/archive/polymorphic_xml_oarchive.hpp>
+typedef boost::archive::polymorphic_xml_iarchive XmlIArchive;
+typedef boost::archive::polymorphic_xml_oarchive XmlOArchive;
+#endif
+
+#include <boost/serialization/extended_type_info_typeid.hpp>
+#include <boost/serialization/base_object.hpp>
+//#include <boost/serialization/extended_type_info.hpp>
+#include <boost/serialization/utility.hpp>
+#include <boost/serialization/list.hpp>
+#include <boost/serialization/vector.hpp>
+#include <boost/serialization/level.hpp>
+#include "nvp.h"
+
+#include <QString>
+#include <QDomDocument>
+#include <QDomNode>
+#include <QTextStream>
+
+///All these functions throw QString's as error-descriptions on error
+
+template <class Type>
+void xmlTextDeserialize( QString& buffer, Type& object ) throw( QString ) {
+ QByteArray bufLocal = buffer.toUtf8().data();
+ std::istringstream str;
+ str.str( bufLocal.data() );
+ try {
+ XmlIArchive arch( str );
+ arch & object;
+ } catch ( std::exception & exc ) {
+ throw QString( "exception occurred while deserialization: " ) + exc.what();
+ }
+}
+
+template <class Type>
+void xmlTextSerialize( QString& buffer, Type& object ) throw( QString ) {
+ buffer.clear();
+
+ std::ostringstream str;
+
+ try {
+ XmlOArchive arch( str );
+
+ arch & object;
+ } catch ( std::exception & exc ) {
+ throw QString( "exception occurred while serialization: " ) + exc.what();
+ }
+
+ buffer = str.str().c_str();
+}
+
+template <class Type>
+void xmlDeserialize( QDomNode& node, Type& object ) throw( QString ) {
+ QDomNode header = node.namedItem( "header" );
+ ///QDomNode type = node.namedItem( "doctype" );
+ QDomNode serializationNode = node.namedItem( "boost_serialization" );
+ if ( header.isNull() )
+ throw QString( "document does not contain header" );
+ /* if( type.isNull() )
+ throw QString( "document does not contain type" );*/
+ if ( serializationNode.isNull() )
+ throw QString( "document does not contain serialization-node" );
+ if ( !header.isElement() && !header.isText() )
+ throw QString( "header is no element" );
+ /*if( type.isElement() && !type.isText() )
+ throw QString( "type is no element" );*/
+ /* if( serializationNode.isElement() )
+ throw QString( "serialization-node is no element" );*/
+
+ QDomNode headerText = header;
+ if ( !header.isText() )
+ headerText = header.firstChild();
+ /*QDomNode typeText = type;
+ if( !type.isText() )
+ typeText = header.firstChild();*/
+
+ if ( headerText.isNull() /*|| typeText.isNull()*/ || !headerText.isText() /*|| !typeText.isText()*/ )
+ throw QString( "header- or type-elements have wrong type" );
+
+ QString text;
+ {
+ QTextStream stream( &text );
+ serializationNode.save( stream, 1 );
+ }
+
+ //text = headerText.data() +"\n" + typeText.data() + "\n" + text;
+ if ( text.isEmpty() )
+ throw QString( "text is empty" );
+ text = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n <!DOCTYPE boost_serialization>\n" + text;
+ cout << "deserializing: " << endl << text.toUtf8().data();
+ xmlTextDeserialize( text, object );
+}
+
+template <class Type>
+void xmlSerialize( QDomNode& container, Type& object, const QString& nodeName = "" ) throw( QString ) {
+ QString buf;
+ xmlTextSerialize( buf, object );
+ if ( buf.isEmpty() )
+ throw QString( "serialized buffer is empty" );
+
+ QDomDocument doc( nodeName );
+ doc.setContent( buf );
+
+ QDomNode header = doc.firstChild();
+ QDomDocumentType type = doc.doctype();
+ QString headerText, typeText;
+
+ cout << "full serialized data: \n" << buf.toUtf8().data() << endl;
+
+ {
+ QTextStream stream( &headerText );
+ header.save( stream, 1 );
+ }
+ {
+ QTextStream stream( &typeText );
+ type.save( stream, 1 );
+ }
+
+ QDomDocument domDoc = container.ownerDocument();
+ QDomElement storedHeaderNode = domDoc.createElement( "header" );
+ QDomElement storedTypeNode = domDoc.createElement( "doctype" );
+ storedHeaderNode.appendChild( domDoc.createTextNode( headerText + "\n" + typeText ) );
+ storedTypeNode.appendChild( domDoc.createTextNode( typeText ) );
+
+ container.appendChild( storedHeaderNode );
+ // container.appendChild( storedTypeNode );
+ container.appendChild( doc.firstChildElement().cloneNode() ); ///While serialization, there is one "boost_serialization"-child created. Only that should be exported.
+}
+
+/**This deletes the previous element of the given name, and replaces it with a new one containing the data.
+ *the given object-type must already be a name-value-pair(see NVP(...) )
+ * Errors are thrown as QString
+*/
+
+template <class Type>
+void xmlSerializeToElementItem( QDomElement* el, const QString& item, Type& object ) throw( QString ) {
+ QDomDocument domDoc = el->ownerDocument();
+ {
+ QDomNode containerNode = el->namedItem( item );
+
+ if ( !containerNode.isNull() )
+ el->removeChild( containerNode );
+ }
+
+ QDomElement containerNode = domDoc.createElement( item );
+ el->appendChild( containerNode );
+
+#ifdef XML_USE_TEXT_ARCHIVE
+
+ QString buffer;
+ xmlTextSerialize( buffer, object );
+ if ( buffer.isEmpty() )
+ throw QString( "deserialized buffer is empty" );
+ containerNode.appendChild( domDoc.createTextNode( buffer ) );
+#else
+
+ xmlSerialize( containerNode, object, item );
+
+#endif
+}
+
+/**is invoked the same way as xmlSerializeToElementItem(...)
+ * Errors are thrown as QString
+ */
+
+template <class Type>
+void xmlDeserializeFromElementItem( const QDomElement* el, const QString& item, Type& object ) throw( QString ) {
+ QDomNode containerNode = el->namedItem( item );
+ if ( containerNode.isNull() )
+ throw "container-node of name \"" + item + "\" is missing";
+
+#ifdef XML_USE_TEXT_ARCHIVE
+
+ QDomNode node = containerNode.firstChild();
+ if ( node.isNull() )
+ throw "the container-node of name \"" + item + "\" does not contain the correct data";
+
+ QString data;
+
+ QDomText textNode = node.toText();
+ if ( textNode.isNull() )
+ throw "the container-node of name \"" + item + "\" does not contain the correct data";
+
+ data = textNode.data();
+ if ( data.isEmpty() )
+ throw QString( "stored data is empty" );
+ xmlTextDeserialize( data, object );
+#else
+
+ xmlDeserialize( containerNode, object );
+
+#endif
+
+}
+
+#endif
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/serializationutils.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.cpp (revision 1522570)
@@ -0,0 +1,62 @@
+/***************************************************************************
+Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+
+#include "safelogger.h"
+
+LogSuffix& LogSuffix::operator = ( const LogSuffix& /*rhs */ ) {
+ return * this;
+}
+LogSuffix::LogSuffix( const LogSuffix& /*rhs */ ) {}
+
+LogSuffix::LogSuffix( const char* txt, SafeLogger* logger ) : m_logger( logger ) {
+ m_logger->m_logSuffix.push_back( txt );
+}
+
+LogSuffix::~LogSuffix() {
+ if ( !m_logger->m_logSuffix.empty() )
+ m_logger->m_logSuffix.pop_back();
+ else
+ m_logger->err() << "error in SafeLogger::LogSuffix: tried to pop more than pushed";
+}
+
+SafeLogger::SafeLogger( Teamwork::LoggerPointer logger, std::string logPrefix ) : m_logger( logger ), m_logPrefix( logPrefix ) {}
+
+SafeLogger::~SafeLogger() {}
+
+Teamwork::LoggerPrinter SafeLogger::out( Teamwork::Logger::Level level ) {
+ Teamwork::LoggerPrinter ret( m_logger, level );
+ ret << logPrefix();
+ uint sz = m_logSuffix.size();
+ for ( uint a = 0; a < sz; a++ )
+ ret << m_logSuffix[ a ];
+ return ret;
+}
+
+Teamwork::LoggerPointer SafeLogger::logger() const {
+ return m_logger;
+}
+
+Teamwork::LoggerPrinter SafeLogger::err() {
+ Teamwork::LoggerPrinter ret( m_logger, Teamwork::Logger::Error );
+ ret << logPrefix();
+ uint sz = m_logSuffix.size();
+ for ( uint a = 0; a < sz; a++ )
+ ret << m_logSuffix[ a ];
+ return ret;
+}
+
+std::string SafeLogger::logPrefix() {
+ return m_logPrefix;
+}
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/safelogger.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h (revision 1522570)
@@ -0,0 +1,62 @@
+/***************************************************************************
+ Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
+***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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. *
+ * *
+ ***************************************************************************/
+#ifndef FILESYNCHRONIZEMESSAGE_H
+#define FILESYNCHRONIZEMESSAGE_H
+
+#include "filecollaborationmessages.h"
+#include "qdynamictext.h"
+
+class DynamicText;
+
+class FileSynchronizeData {
+
+ public:
+ explicit FileSynchronizeData( const QString& fileName = "", const QDynamicText& text = QDynamicText(), bool sendDynamic = true );
+
+ template <class Archive>
+ void serialize( Archive& arch, unsigned int /*version*/ ) {
+ try {
+ arch & m_text;
+ }
+ catch( const DynamicTextError& err ) {
+ throw Teamwork::NonFatalSerializationError( "FileSynchronizeData::serialize(): " + err.what() );
+ }
+ arch & m_fileName;
+ arch & m_fileText;
+ arch & m_state;
+ }
+
+ QString fileName() {
+ return m_fileName;
+ }
+
+ VectorTimestamp state() {
+ return m_state;
+ }
+
+ QDynamicTextPointer createDynamicText();
+ private:
+ QString m_fileText;
+ QString m_fileName;
+ VectorTimestamp m_state;
+ SharedPtr<QDynamicText, BoostSerializationNormal> m_text;
+};
+
+EASY_DECLARE_MESSAGE( FileSynchronize, DocumentWrapperMessage, 3, FileSynchronizeData, 3 );
+
+BOOST_CLASS_IMPLEMENTATION( FileSynchronizeData, boost::serialization::object_serializable )
+
+// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
+///Eventually think about sending a whole history with a FileSynchronize
+
+#endif
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc (revision 1522570)
@@ -0,0 +1,3 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KDevTeamwork" version="8">
+</kpartgui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/dotest
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/dotest (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/dotest (revision 1522570)
@@ -0,0 +1,2 @@
+#!/bin/sh
+colorgcc test.cpp test -lstdc++ -I../../ -ftemplate-depth-30 && ./test
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/dotest
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui (revision 1522570)
@@ -0,0 +1,441 @@
+<ui version="4.0" >
+ <class>EditPatch</class>
+ <widget class="QDialog" name="EditPatch" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>502</width>
+ <height>688</height>
+ </rect>
+ </property>
+ <property name="windowTitle" >
+ <string>Edit Patch</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QTabWidget" name="tabWidget" >
+ <property name="currentIndex" >
+ <number>1</number>
+ </property>
+ <widget class="QWidget" name="fileTab" >
+ <attribute name="title" >
+ <string>File</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="1" column="0" colspan="2" >
+ <widget class="QLabel" name="mimetype" >
+ <property name="text" >
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <widget class="QLabel" name="label_2" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">File:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1" >
+ <widget class="KUrlRequester" name="filename" />
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="commandTab" >
+ <attribute name="title" >
+ <string>command-output</string>
+ </attribute>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>9</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_9" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Command:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="command" />
+ </item>
+ <item>
+ <widget class="QPushButton" name="commandToFile" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>To File</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ <item row="12" column="0" >
+ <widget class="QGroupBox" name="filesGroup" >
+ <property name="title" >
+ <string>Files</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="margin" >
+ <number>2</number>
+ </property>
+ <property name="spacing" >
+ <number>4</number>
+ </property>
+ <item row="0" column="1" >
+ <widget class="QListView" name="filesList" >
+ <property name="editTriggers" >
+ <set>QAbstractItemView::NoEditTriggers</set>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" >
+ <layout class="QVBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="highlightFiles" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Highlight</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="previousHunk" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Previous Hunk</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="nextHunk" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Next Hunk</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="10" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_11" >
+ <property name="text" >
+ <string>Author:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="author" />
+ </item>
+ <item>
+ <widget class="QPushButton" name="userButton" >
+ <property name="text" >
+ <string>User</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="11" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="determineState" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Determine</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="label_10" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>State:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="state" />
+ </item>
+ <item>
+ <widget class="QLabel" name="label" >
+ <property name="sizePolicy" >
+ <sizepolicy>
+ <hsizetype>4</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text" >
+ <string>Access:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="KComboBox" name="accessRights" />
+ </item>
+ </layout>
+ </item>
+ <item row="9" column="0" >
+ <widget class="QTextEdit" name="description" />
+ </item>
+ <item row="4" column="0" >
+ <widget class="QLabel" name="label_6" >
+ <property name="text" >
+ <string>recommended unapply-command:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="0" >
+ <widget class="QLineEdit" name="unapplyCommand" />
+ </item>
+ <item row="6" column="0" >
+ <widget class="QLabel" name="label_7" >
+ <property name="text" >
+ <string>Dependencies:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0" >
+ <widget class="QLineEdit" name="applyCommand" />
+ </item>
+ <item row="2" column="0" >
+ <widget class="QLabel" name="label_5" >
+ <property name="text" >
+ <string>recommended apply-command:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label_8" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">N&lt;span style=" font-weight:600;">ame:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="name" />
+ </item>
+ <item>
+ <widget class="QLabel" name="label_3" >
+ <property name="text" >
+ <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Type:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="type" />
+ </item>
+ <item>
+ <widget class="QPushButton" name="chooseType" >
+ <property name="text" >
+ <string>Choose</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="8" column="0" >
+ <widget class="QLabel" name="label_4" >
+ <property name="text" >
+ <string>Description:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="0" >
+ <widget class="QLineEdit" name="dependencies" />
+ </item>
+ <item row="13" column="0" >
+ <widget class="QDockWidget" name="konsoleDock" >
+ <property name="features" >
+ <set>QDockWidget::AllDockWidgetFeatures</set>
+ </property>
+ <widget class="QWidget" name="dockWidgetContents" />
+ </widget>
+ </item>
+ <item row="14" column="0" >
+ <layout class="QHBoxLayout" >
+ <property name="margin" >
+ <number>0</number>
+ </property>
+ <property name="spacing" >
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="applyButton" >
+ <property name="text" >
+ <string>Apply</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="unApplyButton" >
+ <property name="text" >
+ <string>Unapply</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="showButton" >
+ <property name="text" >
+ <string>Show</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <property name="orientation" >
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" >
+ <size>
+ <width>40</width>
+ <height>31</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="okButton" >
+ <property name="text" >
+ <string>Close</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>KUrlRequester</class>
+ <extends>QFrame</extends>
+ <header>kurlrequester.h</header>
+ </customwidget>
+ <customwidget>
+ <class>KComboBox</class>
+ <extends>QComboBox</extends>
+ <header>kcombobox.h</header>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>okButton</sender>
+ <signal>clicked()</signal>
+ <receiver>EditPatch</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel" >
+ <x>278</x>
+ <y>253</y>
+ </hint>
+ <hint type="destinationlabel" >
+ <x>96</x>
+ <y>254</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui (revision 1522570)
@@ -0,0 +1,100 @@
+<ui version="4.0" >
+ <class>InternalMessage</class>
+ <widget class="QWidget" name="InternalMessage" >
+ <property name="geometry" >
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>463</width>
+ <height>193</height>
+ </rect>
+ </property>
+ <property name="windowTitle" >
+ <string>Internal Message</string>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QFrame" name="frame" >
+ <property name="autoFillBackground" >
+ <bool>true</bool>
+ </property>
+ <property name="frameShape" >
+ <enum>QFrame::Panel</enum>
+ </property>
+ <property name="frameShadow" >
+ <enum>QFrame::Plain</enum>
+ </property>
+ <layout class="QGridLayout" >
+ <property name="leftMargin" >
+ <number>9</number>
+ </property>
+ <property name="topMargin" >
+ <number>9</number>
+ </property>
+ <property name="rightMargin" >
+ <number>9</number>
+ </property>
+ <property name="bottomMargin" >
+ <number>9</number>
+ </property>
+ <property name="horizontalSpacing" >
+ <number>6</number>
+ </property>
+ <property name="verticalSpacing" >
+ <number>6</number>
+ </property>
+ <item row="0" column="0" >
+ <widget class="QToolButton" name="actionsButton" >
+ <property name="text" >
+ <string>actions</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1" >
+ <widget class="QComboBox" name="talkingUsers" />
+ </item>
+ <item row="1" column="0" colspan="2" >
+ <widget class="QTreeView" name="messages" >
+ <property name="editTriggers" >
+ <set>QAbstractItemView::NoEditTriggers</set>
+ </property>
+ <property name="alternatingRowColors" >
+ <bool>true</bool>
+ </property>
+ <property name="indentation" >
+ <number>2</number>
+ </property>
+ <property name="animationsEnabled" stdset="0" >
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" colspan="2" >
+ <widget class="QLineEdit" name="message" />
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/README
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/README (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/README (revision 1522570)
@@ -0,0 +1,51 @@
+Some notes about this plugin from commit-digest/2006-09-10:
+When I first heard about Summer Of Code I thought about proposing a project called "Advanced Code Completion for KDevelop 3"(with full support for templates, comments, etc.), but when that didn't go down well with most of the KDevelop developers (since they were already focused on KDevelop 4), I just started implementing it. I spent a lot of time working on that until SOC started (and even quite some time since then), and you can see the result in the current KDevelop 3.4 SVN tree. I finished everything I planned and more.
+
+Some of the features:
+Intelligent resolution of types.
+Support for templates like for example shared pointers.
+Support for implicit template-instatiation
+Nicer and more useful completion-list with items ordered in a useful way and indented by inheritance-depth, with popups that include comments and any other interesting information
+Many improvements in the parser, for example all comments are extracted and used in any possible way, macros are dealt with correctly, Enums are handled in a more useful way, and much more
+A powerful navigation-menu: Click any item within a function and see it's real type, a trace of all typedefs on the way to that type, information on all involved typedefs, classes, variables, functions, etc., and the same as a submenu for all involved template-parameters, argument-types, base-classes, etc.
+Improved jump-to-menus and navigation-bar.
+Highlighting of function-names in the navigation-bar and class-tree.
+And countless other major improvements in code-completion and navigation.. see the feature list of the beta releases or the commit log to see all of them.
+
+KDevelop 3 is doing well feature-wise, but currently lacks developers since the focus already is on KDevelop 4, but it'll take a long time until that is really usable, so I hereby encourage anyone interested to start using the SVN version of KDevelop 3.4 and hunt down a few bugs, to make sure that a stable version can be released soon.
+
+Collaboration through the internet is fundamental to most open-source-software. Almost any open- and even closed-source-software might profit from better collaboration-possibilities. If you work for a project that has a collaboration-server, you can directly ask other developers working on the same project for very specific help, patches can be reviewed very quickly, and discussion can instantly take place within the documents themselves. File Collaboration may also be useful for discussion of new ideas, teaching, for friends less experienced in programming requesting help (Or am I the only one who is asked how to program something through ICQ again and again?), and simply because it's cool ;)
+
+So I took the basic Idea for the Summer Of Code project "KDevelop Teamwork" from the Wiki where someone proposed it, and developed it using my own Ideas, trying to add some of the teamwork features I always missed in any IDE I ever used. :)
+
+Generally it consists of four parts:
+Client/Server Architecture
+I created a multi-threaded library for networking, including client/server- and user-management, and a standalone server not dependent on Qt which can be run on any webserver and administrated using the console.
+
+File Collaboration
+An arbitrary count of developers can collaboratively edit a dynamic set of files, and the edited documents can be dynamically transformed (for example chosen changes made by exactly one user could be undone, which will allow single-user undo, redo, etc.)
+
+Conversation
+All users connected to any of the connected servers, as well as the servers themselves (in the case they are not standalone) can be contacted by using instant messages, collaboration-requests, patch-requests, in-document messages, etc.
+
+The most interesting message for conversation is the in-document message: It can reference a position or piece of text within any document, and the receiver of the message automatically jumps to that document and highlights the referenced piece of text as the message is selected, and pops up a chat-window within the document itself at the found position, where other messages of the same thread may be selected and discussion can take place.
+
+Any answers written into the chat will automatically reference the currently selected text. Referencing is simply done by marking a piece of text before sending a message, and the reference-position is being found by a fuzzy algorithm I developed which tries to find the correct place even within totally different documents (and is pretty successful at doing so).
+
+Patch Management
+Every user can manage a set of patches (or other file types) for each project. They can either be files or dynamic patches which are automatically retrieved from commands on request (for example "svn diff"). Patches can be easily shared directly through the developer-list, using different access-levels.
+
+A modified version of Kompare's diff3-library is used to get information from patches. Using that the patch-manager can automatically highlight all changes made by an applied patch within all documents, and allows you to easily browse through those positions so you can review the patch within the correct context and directly discuss about it using in-document messages.
+
+They can be applied/reverted to the local tree using single buttons, and for diff-files it is possible to automatically determine whether the patch is already applied or not. If problems arise within the patching process they can be dealt with using an embedded console in the patch-management-window.
+It is important that all those features are well integrated: For example you can store the results of a file-collaboration-session as a patch into your local patches-list, and thereby share it with other developers and easily revert it at any time, and you can use in-document messages directly within the temporary file-collaboration files.
+
+To store all the project-specific data (like patches), a ".teamwork" subfolder is created within the project directory.
+
+I encountered many problems during development. Apart from one harddisk crash, the most annoying problem was the very unstable and (in the begginning) difficult to compile kdelibs/qt-copy/qdbus/kdesupport etc. combination, which again and again cost me days and hours just to get it working.
+
+The most challenging part was the file-collaboration. Getting a simple form of collaborative editing to work was quite fast, but making the document-transformation work correctly in all test-cases really took some time, and I had to finish it after the deadline without stress (luckily I didn't mention anything like it in my application ;)). The trick was writing everything down and trying to solve it mathematically as I learnt at university, unfortunately I got that idea after days of unsuccessful hacking and trying - well... you live and learn :)
+
+I was able to finish nearly everything I planned until the deadline, but unfortunately I missed the week I planned in my application for "debug, make it perfect", so that work is missing, and it shows :) Most of the work I did after the Summer Of Code ended was in other, more important parts (finishing the text-transformation algorithm, or fixing file-collaboration which stopped working after a kdelibs-update), but it is work I'll surely do. Then there's one other big problem, the executable-size when the executable is built with debug-information. During my work on this project I fell in love with templates and meta-programming, but I think the main reason is my use of boost serialization, I'll still have to work on that. Then of course i'll need some nice icons. :)
+
+ Now that the Summer Of Code has concluded, the first thing I will do is working intensively for the institute of my university that paid me the whole year, and that I neglected since March because of my work for KDevelop 3 Code Completion and then the Summer Of Code. Of course, I won't forget KDevelop and KDE in general, since I like the Open-Source Idea a lot. I started working on Open-Source Software before I started the Summer Of Code, and I won't stop it now that it's over :) I'll keep maintaining the teamwork-module (and of course finish it), I'll keep caring about KDevelop, and maybe I'll start a project to make KDE more Tablet PC friendly if I can find the time for it.
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/teamwork/README
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop (revision 1522570)
@@ -0,0 +1,70 @@
+[Desktop Entry]
+Type=Service
+
+Name=UI Strings tool
+Name[bs]=Opcije UI stringa(niz znakova)
+Name[ca]=Eina de cadenes d'IU
+Name[ca@valencia]=Eina de cadenes d'IU
+Name[de]=Textwerkzeug für grafische Oberflächen
+Name[en_GB]=UI Strings tool
+Name[es]=Herramienta de cadenas de la interfaz de usuario
+Name[et]=Kasutajaliidese stringide tööriist
+Name[fr]=Outil de chaînes de caractères d'interfaces graphiques
+Name[gl]=Ferramenta de cadeas de interface gráfica
+Name[it]=Strumento Stringhe interfaccia
+Name[nl]=UI Strings hulpmiddel
+Name[pl]=Narzędzie ciągów znaków interfejsu użytkownika
+Name[pt]=Ferramenta de textos da GUI
+Name[pt_BR]=Ferramenta de textos da GUI
+Name[sv]=Verktyg för strängar i grafiskt gränssnitt
+Name[uk]=Інструмент рядків графічного інтерфейсу
+Name[x-test]=xxUI Strings toolxx
+GenericName=UI Strings tool
+GenericName[bs]=Opcije UI stringa(niz znakova)
+GenericName[ca]=Eina de cadenes d'IU
+GenericName[ca@valencia]=Eina de cadenes d'IU
+GenericName[de]=Textwerkzeug für grafische Oberflächen
+GenericName[en_GB]=UI Strings tool
+GenericName[es]=Herramienta de cadenas de la interfaz de usuario
+GenericName[et]=Kasutajaliidese stringide tööriist
+GenericName[fr]=Outil de chaînes de caractères d'interfaces graphiques
+GenericName[gl]=Ferramenta de cadeas de interface gráfica
+GenericName[it]=Strumento Stringhe interfaccia
+GenericName[nl]=UI Strings hulpmiddel
+GenericName[pl]=Narzędzie ciągów znaków interfejsu użytkownika
+GenericName[pt]=Ferramenta de textos da GUI
+GenericName[pt_BR]=Ferramenta de textos da GUI
+GenericName[sv]=Verktyg för strängar i grafiskt gränssnitt
+GenericName[uk]=Інструмент рядків графічного інтерфейсу
+GenericName[x-test]=xxUI Strings toolxx
+Comment=Enables central handling of strings in the UI
+Comment[bs]=Omogućava centralno rukovanje strigovima u UI-u
+Comment[ca]=Habilita la gestió central de cadenes a la IU
+Comment[ca@valencia]=Habilita la gestió central de cadenes a la IU
+Comment[de]=Ermöglicht die zentrale Bearbeitung von Texten in der grafischen Benutzeroberfläche
+Comment[en_GB]=Enables central handling of strings in the UI
+Comment[es]=Habilita el manejo central de cadenas en la interfaz de usuario
+Comment[et]=Kasutajaliidese stringide keskne haldamine
+Comment[fr]=Active la gestion centralisée de chaînes de caractères dans l'interface graphique
+Comment[gl]=Permite xestionar de maneira centralizada as cadeas das interfaces gráficas.
+Comment[it]=Abilita la gestione centralizzata delle stringhe nell'interfaccia utente
+Comment[nl]=Maakt centraal beheer van tekst in de UI mogelijk
+Comment[pl]=Włącza centralną obsługę ciągów znaków w interfejsie użytkownika
+Comment[pt]=Permite o tratamento centralizado de textos na interface gráfica
+Comment[pt_BR]=Permite o tratamento centralizado de textos na interface gráfica
+Comment[sv]=Aktiverar central hantering av strängar i det grafiska gränssnittet
+Comment[uk]=Уможливлює загальну обробку рядків у графічному інтерфейсі
+Comment[x-test]=xxEnables central handling of strings in the UIxx
+Icon=text-plain
+ServiceTypes=KDevelop/Plugin
+
+X-KDE-Library=kdevuistrings
+X-KDE-PluginInfo-Name=kdevuistrings
+X-KDE-PluginInfo-Author=Friedrich W. H. Kossebau
+X-KDE-PluginInfo-Email=kossebau@kde.org
+X-KDE-PluginInfo-Version=0.1
+X-KDE-PluginInfo-License=GPL
+X-KDevelop-Version=9
+X-KDevelop-Category=Global
+# X-KDevelop-SupportedMimeTypes=audio/x-wav;
+X-KDevelop-Mode=GUI
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp (revision 1522570)
@@ -0,0 +1,60 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringsplugin.h"
+
+// plugin
+#include "uistringscompletionmodel.h"
+#include "uistringstoolviewfactory.h"
+// KDev
+#include <interfaces/icore.h>
+#include <interfaces/iuicontroller.h>
+#include <interfaces/ipartcontroller.h>
+#include <language/codecompletion/codecompletion.h>
+// KDE
+#include <KAboutData>
+#include <KPluginFactory>
+
+
+K_PLUGIN_FACTORY(UiStringsPluginFactory, registerPlugin<KDevelop::UiStringsPlugin>(); )
+K_EXPORT_PLUGIN( UiStringsPluginFactory( KAboutData( "kdevuistrings","kdevuistrings", ki18n("UI Strings"), "0.1", ki18n("Lists UI Strings"), KAboutData::License_GPL)))
+
+namespace KDevelop
+{
+
+UiStringsPlugin::UiStringsPlugin( QObject* parent, const QVariantList& args )
+ : IPlugin( UiStringsPluginFactory::componentData(), parent ),
+ mUiStringsCompletionModel( new UiStringsCompletionModel(this) )
+{
+ Q_UNUSED(args)
+
+ UiStringsToolViewFactory* toolViewFactory = new UiStringsToolViewFactory();
+ core()->uiController()->addToolView( i18n("UI Strings"), toolViewFactory );
+
+ new KDevelop::CodeCompletion( this, mUiStringsCompletionModel, QString() );
+}
+
+UiStringsPlugin::~UiStringsPlugin()
+{
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsplugin.h (revision 1522570)
@@ -0,0 +1,60 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSPLUGIN_H
+#define UISTRINGSPLUGIN_H
+
+// KDev
+#include <interfaces/iplugin.h>
+// Qt
+#include <QtCore/QVariantList>
+
+namespace KTextEditor {
+class View;
+class Document;
+}
+namespace KParts {
+class Part;
+}
+
+
+namespace KDevelop
+{
+class UiStringsCompletionModel;
+
+
+class UiStringsPlugin: public IPlugin
+{
+ Q_OBJECT
+
+ public:
+ UiStringsPlugin( QObject* parent, const QVariantList& args = QVariantList() );
+
+ virtual ~UiStringsPlugin();
+
+ protected:
+ UiStringsCompletionModel* mUiStringsCompletionModel;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp (revision 1522570)
@@ -0,0 +1,69 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringscompletionmodel.h"
+
+// plugin
+#include "uistringstool.h"
+
+
+namespace KDevelop
+{
+
+UiStringsCompletionModel::UiStringsCompletionModel( QObject* parent )
+ : KTextEditor::CodeCompletionModel( parent )
+{
+ setHasGroups( false );
+}
+
+QVariant UiStringsCompletionModel::data( const QModelIndex& index, int role ) const
+{
+ const int row = index.row();
+
+ if( !index.isValid() || row < 0 || row >= rowCount() )
+ return QVariant();
+
+ return QVariant();//m_snippets.at( index.row() )->data( index, role, 0);
+}
+
+void UiStringsCompletionModel::executeCompletionItem( KTextEditor::Document* document, const KTextEditor::Range& w, int row ) const
+{
+// m_snippets.at( row )->execute( document, w );
+}
+
+void UiStringsCompletionModel::completionInvoked( KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType)
+{
+ Q_UNUSED( range );
+ Q_UNUSED( invocationType );
+ initData( view );
+}
+
+void UiStringsCompletionModel::initData( KTextEditor::View* view )
+{
+ // find out if we are cpp, if we are in UI string
+ reset();
+ setRowCount( 0 );
+}
+
+UiStringsCompletionModel::~UiStringsCompletionModel() {}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h (revision 1522570)
@@ -0,0 +1,55 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSCOMPLETIONMODEL
+#define UISTRINGSCOMPLETIONMODEL
+
+// KDE
+#include <ktexteditor/codecompletionmodel.h>
+
+
+namespace KDevelop
+{
+
+class UiStringsCompletionModel : public KTextEditor::CodeCompletionModel
+{
+ Q_OBJECT
+
+ public:
+ explicit UiStringsCompletionModel( QObject* parent );
+
+ virtual ~UiStringsCompletionModel();
+
+ public: // QAbstractItemModel API
+ virtual QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
+
+ public: // KTextEditor::CodeCompletionModel API
+ virtual void completionInvoked( KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType);
+ virtual void executeCompletionItem( KTextEditor::Document* document, const KTextEditor::Range& w, int row ) const;
+
+ protected:
+ void initData( KTextEditor::View* view );
+};
+
+}
+
+#endif
\ No newline at end of file
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,37 @@
+project( uistrings )
+
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${uistrings_SOURCE_DIR}/cmake/modules )
+
+find_package(KDE4 4.3.0 REQUIRED)
+find_package(KDevPlatform 0.9.98 REQUIRED)
+
+include_directories( ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR} )
+include_directories( ${uistrings_SOURCE_DIR} ${uistrings_BINARY_DIR} )
+
+# add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9038 )
+
+SET( kdevuistrings_PART_SRCS
+ uistringscompletionmodel.cpp
+ i18nusescollector.cpp
+ uistringsmodel.cpp
+ uistringstool.cpp
+ uistringstoolviewfactory.cpp
+ uistringstoolviewwidget.cpp
+ uistringsplugin.cpp
+)
+
+kde4_add_plugin( kdevuistrings ${kdevuistrings_PART_SRCS} )
+
+TARGET_LINK_LIBRARIES( kdevuistrings
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+# ${KDEVPLATFORM_SUBLIME_LIBRARIES}
+# ${KDEVPLATFORM_SHELL_LIBRARIES}
+ ${KDE4_KDEUI_LIBS}
+)
+
+install(TARGETS kdevuistrings DESTINATION ${PLUGIN_INSTALL_DIR})
+
+
+install(FILES kdevuistrings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+install(FILES kdevuistrings.rc DESTINATION ${DATA_INSTALL_DIR}/kdevuistrings )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp (revision 1522570)
@@ -0,0 +1,93 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "i18nusescollector.h"
+
+// plugin
+#include "uistringstool.h"
+// KDev
+#include <language/duchain/declaration.h>
+#include <language/codegen/coderepresentation.h>
+#include <interfaces/icore.h>
+#include <interfaces/iprojectcontroller.h>
+#include <interfaces/iproject.h>
+
+
+namespace KDevelop
+{
+
+I18nUsesCollector::I18nUsesCollector( UiStringsTool* tool, IndexedDeclaration declaration )
+ : UsesCollector( declaration ),
+ mTool( tool )
+{
+}
+
+void I18nUsesCollector::processUses( ReferencedTopDUContext topContext )
+{
+// kDebug()<<topContext->
+// mTool->append( topContext->url().str() );
+}
+
+void I18nUsesCollector::progress( uint processed, uint total )
+{
+ const bool isDone = ( processed == total );
+ if( isDone )
+ {
+ const QList<IProject*> projects = ICore::self()->projectController()->projects();
+
+ QMap<IndexedString, QList<SimpleRange> > uses = declaration().data()->uses();
+ QMap<IndexedString, QList<SimpleRange> >::ConstIterator it = uses.constBegin();
+ QMap<IndexedString, QList<SimpleRange> >::ConstIterator end = uses.constEnd();
+ for( ; it != end; ++it )
+ {
+ const IndexedString& string = it.key();
+ bool isInProject = false;
+ foreach( IProject* project, projects )
+ {
+ const QSet<IndexedString> fileSet = project->fileSet();
+ if( fileSet.contains(string) )
+ {
+ isInProject = true;
+ break;
+ }
+ }
+ if( ! isInProject )
+ continue;
+
+ const QString fileName = string.toUrl().fileName();
+ CodeRepresentation::Ptr codeRepresentation = createCodeRepresentation( string );
+ const QList<SimpleRange>& ranges = it.value();
+ foreach( const SimpleRange& range, ranges )
+ {
+ KTextEditor::Range textRange = range.textRange();
+ const int endColumn = textRange.end().column();
+ textRange.end().setColumn( endColumn+10 );
+ textRange.start().setColumn( endColumn+1 );
+ mTool->append( fileName + ':'+ codeRepresentation->rangeText(textRange) );
+ }
+ }
+ }
+}
+
+I18nUsesCollector::~I18nUsesCollector() {}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.cpp (revision 1522570)
@@ -0,0 +1,74 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringstool.h"
+
+// plugin
+#include "i18nusescollector.h"
+// KDev
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/persistentsymboltable.h>
+
+
+namespace KDevelop
+{
+
+UiStringsTool::UiStringsTool( QObject* parent )
+ : QObject( parent )
+{
+}
+
+void UiStringsTool::update()
+{
+ mStrings.clear();
+
+ DUChainReadLocker lock( DUChain::lock() );
+
+ QualifiedIdentifier qualifiedIdentifier( QString::fromLatin1("i18n") );
+ PersistentSymbolTable::Declarations declarations =
+ PersistentSymbolTable::self().getDeclarations( qualifiedIdentifier );
+
+ for( PersistentSymbolTable::Declarations::Iterator it = declarations.iterator(); it; ++it )
+ {
+ Declaration* declaration = it->declaration();
+
+ UsesCollector* usesCollector = new I18nUsesCollector( this, declaration );
+ usesCollector->setCollectDefinitions( false );
+// connect( usesCollector, SIGNAL(processUsesSignal(KDevelop::ReferencedTopDUContext)),
+// SLOT(onProcessUsesSignal(KDevelop::ReferencedTopDUContext)) );
+ usesCollector->startCollecting();
+ }
+}
+
+void UiStringsTool::append( const QString& string )
+{
+kDebug()<<string;
+ mStrings.append( string );
+ emit stringsUpdated();
+}
+
+UiStringsTool::~UiStringsTool()
+{
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstool.h (revision 1522570)
@@ -0,0 +1,65 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSTOOL_H
+#define UISTRINGSTOOL_H
+
+// KDev
+#include <language/duchain/topducontext.h>
+// Qt
+#include <QtCore/QObject>
+#include <QtCore/QStringList>
+
+
+namespace KDevelop
+{
+
+class UiStringsTool: public QObject
+{
+ Q_OBJECT
+
+ public:
+ explicit UiStringsTool( QObject* parent = 0 );
+
+ virtual ~UiStringsTool();
+
+ public:
+ int stringCount() const;
+ const QString& string( int index ) const;
+ void append( const QString& string );
+
+ public Q_SLOTS:
+ void update();
+
+ Q_SIGNALS:
+ void stringsUpdated();
+
+ protected:
+ QStringList mStrings;
+};
+
+inline int UiStringsTool::stringCount() const { return mStrings.count(); }
+inline const QString& UiStringsTool::string( int index ) const { return mStrings.at(index); }
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/i18nusescollector.h (revision 1522570)
@@ -0,0 +1,54 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef I18NUSESCOLLECTOR_H
+#define I18NUSESCOLLECTOR_H
+
+// KDev
+#include <language/duchain/navigation/usescollector.h>
+
+
+namespace KDevelop
+{
+class UiStringsTool;
+
+
+class I18nUsesCollector : public UsesCollector
+{
+ Q_OBJECT
+
+ public:
+ explicit I18nUsesCollector( UiStringsTool* tool, IndexedDeclaration declaration );
+
+ virtual ~I18nUsesCollector();
+
+ private: // UsesCollector API
+ virtual void processUses( ReferencedTopDUContext topContext );
+ virtual void progress( uint processed, uint total );
+
+ protected:
+ UiStringsTool* mTool;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp (revision 1522570)
@@ -0,0 +1,57 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringstoolviewfactory.h"
+
+// plugin
+#include "uistringstoolviewwidget.h"
+#include "uistringstool.h"
+// KDE
+#include <KIcon>
+
+
+namespace KDevelop
+{
+
+UiStringsToolViewFactory::UiStringsToolViewFactory()
+ : IToolViewFactory(),
+ mTool( new UiStringsTool() )
+{
+}
+
+QString UiStringsToolViewFactory::id() const { return QString::fromLatin1("org.kde.okteta."); }
+Qt::DockWidgetArea UiStringsToolViewFactory::defaultPosition() { return Qt::LeftDockWidgetArea; }
+
+QWidget* UiStringsToolViewFactory::create( QWidget* parent )
+{
+ QWidget* widget = new UiStringsToolViewWidget( mTool, parent );
+ widget->setWindowIcon( KIcon("text-plain") );
+ return widget;
+}
+
+
+UiStringsToolViewFactory::~UiStringsToolViewFactory()
+{
+ delete mTool;
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp (revision 1522570)
@@ -0,0 +1,107 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringsmodel.h"
+
+// plugin
+#include "uistringstool.h"
+// KDE
+#include <KLocale>
+
+
+namespace KDevelop
+{
+
+UiStringsModel::UiStringsModel( UiStringsTool* tool, QObject* parent )
+ : QAbstractTableModel( parent ),
+ mTool( tool )
+{
+ connect( mTool, SIGNAL(stringsUpdated()), SLOT(update()) );
+}
+
+void UiStringsModel::update()
+{
+ reset();
+}
+
+
+int UiStringsModel::rowCount( const QModelIndex& parent ) const
+{
+Q_UNUSED( parent )
+ return mTool->stringCount();
+}
+
+int UiStringsModel::columnCount( const QModelIndex& parent ) const
+{
+Q_UNUSED( parent )
+ return NoOfColumnIds;
+}
+
+QVariant UiStringsModel::data( const QModelIndex& index, int role ) const
+{
+ QVariant result;
+ if( role == Qt::DisplayRole
+ || role == Qt::ToolTipRole )
+ {
+ const int stringIndex = index.row();
+
+ if( 0 <= stringIndex && stringIndex < mTool->stringCount() )
+ {
+ const QString &string = mTool->string( stringIndex );
+
+ const int column = index.column();
+ switch( column )
+ {
+ case StringColumnId:
+ {
+ result = string;
+ break;
+ }
+ default:
+ ;
+ }
+ }
+ }
+
+ return result;
+}
+
+QVariant UiStringsModel::headerData( int section, Qt::Orientation orientation, int role ) const
+{
+ QVariant result;
+
+ if( role == Qt::DisplayRole )
+ {
+ const QString titel =
+ section == StringColumnId ? i18nc("@title:column string extracted from the byte array", "String") :
+ QString();
+ result = titel;
+ }
+ else
+ result = QAbstractTableModel::headerData( section, orientation, role );
+
+ return result;
+}
+
+UiStringsModel::~UiStringsModel() {}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h (revision 1522570)
@@ -0,0 +1,54 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSTOOLVIEWFACTORY_H
+#define UISTRINGSTOOLVIEWFACTORY_H
+
+// KDev
+#include <interfaces/iuicontroller.h>
+
+
+namespace KDevelop
+{
+class UiStringsTool;
+
+
+class UiStringsToolViewFactory : public IToolViewFactory
+{
+ public:
+ UiStringsToolViewFactory();
+
+ virtual ~UiStringsToolViewFactory();
+
+ public: // KDevelop::IToolViewFactory API
+ virtual QWidget* create( QWidget* parent );
+ virtual Qt::DockWidgetArea defaultPosition();
+
+ virtual QString id() const;
+
+ protected:
+ UiStringsTool* mTool;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringsmodel.h (revision 1522570)
@@ -0,0 +1,66 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSMODEL_H
+#define UISTRINGSMODEL_H
+
+// Qt
+#include <QtCore/QAbstractTableModel>
+
+
+namespace KDevelop
+{
+class UiStringsTool;
+
+
+class UiStringsModel: public QAbstractTableModel
+{
+ Q_OBJECT
+
+ public:
+ enum ColumnIds
+ {
+ StringColumnId = 0,
+ NoOfColumnIds = 1 // TODO: what pattern is usually used to mark number of ids?
+ };
+
+ public:
+ explicit UiStringsModel( UiStringsTool* tool, QObject* parent = 0 );
+
+ virtual ~UiStringsModel();
+
+ public: // QAbstractTableModel API
+ virtual int rowCount( const QModelIndex& parent ) const;
+ virtual int columnCount( const QModelIndex& parent ) const;
+ virtual QVariant data( const QModelIndex& index, int role ) const;
+ virtual QVariant headerData( int section, Qt::Orientation orientation, int role ) const;
+
+ public Q_SLOTS:
+ void update();
+
+ protected:
+ UiStringsTool* mTool;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc (revision 1522570)
@@ -0,0 +1,27 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<gui name="uistrings" version="1">
+<MenuBar>
+ <Menu name="edit">
+ <Action name="edit_undo" group="edit_undo_merge" />
+ <Action name="edit_redo" group="edit_undo_merge" />
+ <Separator group="edit_undo_merge" />
+ <Action name="edit_cut" group="edit_paste_merge" />
+ <Action name="edit_copy" group="edit_paste_merge" />
+ <Action name="edit_paste" group="edit_paste_merge" />
+ <Action name="copy_as" group="edit_paste_merge" />
+ <Action name="insert" group="edit_paste_merge" />
+ <Separator group="edit_paste_merge" />
+ <Action name="edit_select_all" group="edit_select_merge" />
+ <Action name="edit_deselect" group="edit_select_merge" />
+ <Action name="edit_select" group="edit_select_merge" />
+ <Separator group="edit_select_merge" />
+ <Action name="edit_find" group="edit_find_merge" />
+ <Action name="edit_find_next" group="edit_find_merge" />
+ <Action name="edit_find_prev" group="edit_find_merge" />
+ <Action name="edit_replace" group="edit_find_merge" />
+ <Separator group="edit_find_merge" />
+ <Action name="set_overwrite" group="edit_select_merge" />
+ <Separator group="edit_find_merge" />
+ <Action name="goto_offset" group="edit_find_merge" />
+ </Menu>
+</gui>
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp (revision 1522570)
@@ -0,0 +1,96 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "uistringstoolviewwidget.h"
+
+// plugin
+#include "uistringstool.h"
+#include "uistringsmodel.h"
+// KDE
+#include <KPushButton>
+#include <KGuiItem>
+#include <KLocale>
+// Qt
+#include <QtGui/QVBoxLayout>
+#include <QtGui/QHBoxLayout>
+#include <QtGui/QTreeView>
+#include <QtGui/QHeaderView>
+
+
+namespace KDevelop
+{
+
+UiStringsToolViewWidget::UiStringsToolViewWidget( UiStringsTool* tool, QWidget* parent )
+ : QWidget( parent ),
+ mTool( tool )
+{
+ QVBoxLayout* layout = new QVBoxLayout( this );
+ layout->setMargin( 0 );
+
+ // update
+ QHBoxLayout* updateLayout = new QHBoxLayout();
+ updateLayout->setMargin( 0 );
+
+ updateLayout->addStretch();
+ const KGuiItem updateGuiItem( i18nc("@action:button","&Extract"), "document-export",
+ i18nc("@info:tooltip","Finds the UI strings contained in the project and lists them in the view below."),
+ i18nc("@info:whatsthis",
+ "If you press the <interface>Extract</interface> button, "
+ "the project is searched for all strings used in the UI. "
+ "This strings found will be listed in the view below.") );
+ KPushButton* mUpdateButton = new KPushButton( updateGuiItem, this );
+// mUpdateButton->setEnabled( mTool->isApplyable() );
+ connect( mUpdateButton, SIGNAL(clicked(bool)), mTool, SLOT(update()) );
+ updateLayout->addWidget( mUpdateButton );
+
+ layout->addLayout( updateLayout );
+
+ // table
+ UiStringsModel* mUiStringsModel = new UiStringsModel( mTool, this );
+
+ QTreeView* mStringView = new QTreeView( this );
+
+ mStringView->setObjectName( "StringTable" );
+ mStringView->setRootIsDecorated( false );
+ mStringView->setItemsExpandable( false );
+ mStringView->setUniformRowHeights( true );
+ mStringView->setAllColumnsShowFocus( true );
+ mStringView->setSelectionMode( QAbstractItemView::ExtendedSelection );
+ mStringView->setSortingEnabled( true );
+ mStringView->installEventFilter( this );
+ QHeaderView* header = mStringView->header();
+ header->setResizeMode( QHeaderView::ResizeToContents );
+ mStringView->setModel( mUiStringsModel );
+ mStringView->sortByColumn( UiStringsModel::StringColumnId, Qt::AscendingOrder );
+// connect( mStringView, SIGNAL(doubleClicked( const QModelIndex& )),
+// SLOT(onStringDoubleClicked( const QModelIndex& )) );
+// connect( mStringView->selectionModel(),
+// SIGNAL(selectionChanged( const QItemSelection &, const QItemSelection & )),
+// SLOT(onStringSelectionChanged()) );
+ layout->addWidget( mStringView );
+}
+
+UiStringsToolViewWidget::~UiStringsToolViewWidget()
+{
+}
+
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h (revision 1522570)
@@ -0,0 +1,50 @@
+/*
+ This file is part of the KDevelop UIStrings module, part of the KDE project.
+
+ Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) version 3, or any
+ later version accepted by the membership of KDE e.V. (or its
+ successor approved by the membership of KDE e.V.), which shall
+ act as a proxy defined in Section 6 of version 3 of the license.
+
+ 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef UISTRINGSTOOLVIEWWIDGET_H
+#define UISTRINGSTOOLVIEWWIDGET_H
+
+// Qt
+#include <QtGui/QWidget>
+
+
+namespace KDevelop
+{
+class UiStringsTool;
+
+
+class UiStringsToolViewWidget : public QWidget
+{
+ Q_OBJECT
+
+ public:
+ explicit UiStringsToolViewWidget( UiStringsTool* tool, QWidget* parent = 0 );
+
+ virtual ~UiStringsToolViewWidget();
+
+ protected:
+ UiStringsTool* mTool;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,28 @@
+find_package(KDE4 REQUIRED)
+include(MacroOptionalAddSubdirectory)
+
+macro_optional_depend_package(KDevelop "kdevelop")
+if(DEPEND_PACKAGE_KDevelop)
+ macro_optional_find_package(KDevelop)
+else(DEPEND_PACKAGE_KDevelop)
+ set(KDEVELOP_FOUND FALSE)
+endif(DEPEND_PACKAGE_KDevelop)
+
+if(KDEVELOP_FOUND)
+macro_optional_add_subdirectory( automake )
+endif(KDEVELOP_FOUND)
+macro_optional_add_subdirectory( bazaar )
+macro_optional_add_subdirectory( csharp )
+macro_optional_add_subdirectory( ctest )
+macro_optional_add_subdirectory( duchainviewer )
+
+#commented out pending being brought up to speed with the current kdevelop api
+#macro_optional_add_subdirectory( check )
+
+macro_optional_add_subdirectory( java )
+macro_optional_add_subdirectory( metrics )
+macro_optional_add_subdirectory( preprocessor)
+macro_optional_add_subdirectory( sloc )
+macro_optional_add_subdirectory( teamwork )
+macro_optional_add_subdirectory( cppunit )
+macro_optional_add_subdirectory( qtdesigner )
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h (revision 1522570)
@@ -0,0 +1,174 @@
+/*
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef STREAM_H
+#define STREAM_H
+
+#include <cppparserexport.h>
+
+#include <QtCore/QIODevice>
+
+#include <language/editor/simplecursor.h>
+#include <language/duchain/indexedstring.h>
+#include "anchor.h"
+#include "chartools.h"
+
+typedef QVector<unsigned int> PreprocessedContents;
+
+namespace KDevelop {
+ class IndexedString;
+}
+
+namespace rpp {
+
+class LocationTable;
+
+/**
+ * Stream designed for character-at-a-time processing
+ *
+ * @author Hamish Rodda <rodda@kde.org>
+ */
+class KDEVCPPRPP_EXPORT Stream
+{
+ static const uint newline;
+
+ public:
+ Stream();
+ //If the given offset anchor has the member "collapsed" set to true, the position will be locked.
+ explicit Stream( const uint * string, uint stringSize, const Anchor& offset = Anchor(0,0), LocationTable* table = 0 );
+ explicit Stream( PreprocessedContents * string, const Anchor& offset = Anchor(0,0), LocationTable* table = 0 );
+ explicit Stream( PreprocessedContents * string, LocationTable* table );
+ virtual ~Stream();
+
+ bool isNull() const;
+
+ bool atEnd() const;
+
+ void toEnd();
+
+ /// Returns true if toEnd was called on this stream.
+ bool skippedToEnd() const;
+
+ int offset() const;
+
+ const uint& peek(uint offset = 1) const;
+
+ char peekNextCharacter() const {
+ const unsigned int* next = c+1;
+ if (next >= end || !isCharacter(*next))
+ return (char)0;
+
+ return characterFromIndex(*next);
+ }
+
+ //Slow, just for debugging
+ QByteArray stringFrom(int offset) const;
+
+ /// \warning the input and output lines are not updated when calling this function.
+ /// if you're seek()ing over a line boundary, you'll need to fix the line and column
+ /// numbers.
+ void seek(int offset);
+
+ /// Start from the beginning again
+ void reset();
+
+ /// Lock/unlock the input position. If the input position is locked, it will not be moved forwards.
+ void lockInputPosition(bool lock);
+
+ /// If a macro-expansion is set, all anchors given to mark() will get that macro-expansion set.
+ /// It marks the position from where the macro-expansion was started that leads to the current output @see rpp::Anchor
+ void setMacroExpansion(const KDevelop::SimpleCursor&);
+ KDevelop::SimpleCursor macroExpansion() const;
+
+ //Checks whether the current index represents a character, and eventually compares it
+ bool operator==(const char otherc) const {
+ return isCharacter(*c) && *c == indexFromCharacter(otherc);
+ }
+
+ //Checks whether the current index represents a character, and eventually compares it
+ bool operator!=(const char otherc) const {
+ return !isCharacter(*c) || *c != indexFromCharacter(otherc);
+ }
+
+ inline const uint& current() const { return *c; } //krazy:exclude=inline
+ inline operator const uint&() const { return *c; } //krazy:exclude=inline
+ inline Stream& operator++() //krazy:exclude=inline
+ {
+ if (c == end)
+ return *this;
+
+ if(m_inputPositionLocked)
+ ++m_inputLineStartedAt;
+ else if (*c == newline) {
+ ++m_inputLine;
+ m_inputLineStartedAt = m_pos + 1;
+ }else if(!isCharacter(*c)) {
+ //We have to do some special hacking here to keep the column-number correct.
+ m_inputLineStartedAt += 1-KDevelop::IndexedString(QChar(*c)).length();
+ }
+
+ ++c;
+ ++m_pos;
+
+ return *this;
+ }
+
+ ///@warning Doesn't handle newlines correctly!
+ Stream& operator--();
+
+ ///Returns the cursor that points to the current input position.
+ Anchor inputPosition() const;
+ ///If the input position is collapsed, the input position will be locked from now on. It will stay the same until a new one is set.
+ void setInputPosition(const Anchor& position);
+
+ ///Input-position that marks the start of the topmost currently expanding macro in the original document
+ KDevelop::SimpleCursor originalInputPosition() const;
+ void setOriginalInputPosition(const KDevelop::SimpleCursor& position);
+
+ ///Used for output streams to mark stream positions with input position
+ ///The macroExpansion member may have no effect if macroExpansion is set for this stream.
+ void mark(const Anchor& position);
+
+ Stream & operator<< ( const char& c ) {
+ return operator<<(indexFromCharacter(c));
+ }
+ Stream & operator<< ( const unsigned int& c );
+ Stream & operator<< ( const Stream& input );
+ Stream& appendString( const Anchor& inputPosition, const PreprocessedContents & string );
+ Stream& appendString( const Anchor& inputPosition, KDevelop::IndexedString index );
+
+ private:
+ Q_DISABLE_COPY(Stream)
+
+ PreprocessedContents* m_string;
+ const unsigned int* c;
+ const unsigned int* end;
+ bool m_isNull, m_skippedToEnd, m_inputPositionLocked, m_onwsString;
+ KDevelop::SimpleCursor m_macroExpansion;
+ int m_pos;
+ int m_inputLine;
+ int m_inputLineStartedAt;
+ LocationTable* m_locationTable;
+ KDevelop::SimpleCursor m_originalInputPosition;
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h (revision 1522570)
@@ -0,0 +1,266 @@
+/*
+ Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_ENGINE_H
+#define PP_ENGINE_H
+
+//krazy:excludeall=inline
+
+#include <QtCore/QHash>
+
+#include <QtCore/QStack>
+#include <cppparserexport.h>
+
+#include <language/interfaces/iproblem.h>
+
+#include "pp-macro.h"
+#include "pp-macro-expander.h"
+#include "pp-scanner.h"
+
+typedef QVector<unsigned int> PreprocessedContents;
+
+namespace rpp {
+
+class Preprocessor;
+class Environment;
+
+struct Value
+{
+ Value() : kind(Kind_Long), l(0) {}
+
+ enum Kind {
+ Kind_Long,
+ Kind_ULong
+ };
+
+ Kind kind;
+
+ union {
+ long l;
+ unsigned long ul;
+ };
+
+ inline bool is_ulong () const { return kind == Kind_ULong; }
+
+ inline void set_ulong (unsigned long v)
+ {
+ ul = v;
+ kind = Kind_ULong;
+ }
+
+ inline void set_long (long v)
+ {
+ l = v;
+ kind = Kind_Long;
+ }
+
+ inline bool is_zero () const { return l == 0; }
+
+#define PP_DEFINE_BIN_OP2(op) \
+ inline Value operator op(const Value &other) \
+ { \
+ Value ret; \
+ if (is_ulong () || other.is_ulong ()) \
+ ret.set_ulong (ul op other.ul); \
+ else \
+ ret.set_long (l op other.l); \
+ return ret; \
+ }
+
+#define PP_DEFINE_BIN_OP(op, op2) \
+ inline Value &operator op2(const Value &other) \
+ { \
+ if (is_ulong () || other.is_ulong ()) \
+ set_ulong (ul op other.ul); \
+ else \
+ set_long (l op other.l); \
+ return *this; \
+ }
+
+ PP_DEFINE_BIN_OP(+, +=)
+ PP_DEFINE_BIN_OP(-, -=)
+ PP_DEFINE_BIN_OP(*, *=)
+ PP_DEFINE_BIN_OP(/, /=)
+ PP_DEFINE_BIN_OP(%, %=)
+ PP_DEFINE_BIN_OP(<<, <<=)
+ PP_DEFINE_BIN_OP(>>, >>=)
+ PP_DEFINE_BIN_OP(&, &=)
+ PP_DEFINE_BIN_OP(|, |=)
+ PP_DEFINE_BIN_OP(^, ^=)
+ PP_DEFINE_BIN_OP2(<)
+ PP_DEFINE_BIN_OP2(>)
+ PP_DEFINE_BIN_OP2(!=)
+ PP_DEFINE_BIN_OP2(==)
+ PP_DEFINE_BIN_OP2(<=)
+ PP_DEFINE_BIN_OP2(>=)
+ PP_DEFINE_BIN_OP2(&&)
+ PP_DEFINE_BIN_OP2(||)
+
+#undef PP_DEFINE_BIN_OP
+};
+
+
+class KDEVCPPRPP_EXPORT pp
+{
+ Environment* m_environment;
+ pp_macro_expander expand;
+ pp_skip_identifier skip_identifier;
+ pp_skip_comment_or_divop skip_comment_or_divop;
+ pp_skip_blanks skip_blanks;
+ pp_skip_number skip_number;
+ QStack<KDevelop::IndexedString> m_files;
+ Preprocessor* m_preprocessor;
+ QList<KDevelop::ProblemPointer> m_problems;
+
+ enum { MAX_LEVEL = 512 };
+ int _M_skipping[MAX_LEVEL];
+ int _M_true_test[MAX_LEVEL];
+ int iflevel;
+ int nextToken;
+ bool haveNextToken;
+ bool hideNext;
+
+ union {
+ long token_value;
+ unsigned long token_uvalue;
+ };
+ KDevelop::IndexedString token_text;
+
+ enum TOKEN_TYPE
+ {
+ TOKENS_START = 1000,
+ TOKEN_NUMBER,
+ TOKEN_UNUMBER,
+ TOKEN_IDENTIFIER,
+ TOKEN_DEFINED,
+ TOKEN_LT_LT,
+ TOKEN_LT_EQ,
+ TOKEN_GT_GT,
+ TOKEN_GT_EQ,
+ TOKEN_EQ_EQ,
+ TOKEN_NOT_EQ,
+ TOKEN_OR_OR,
+ TOKEN_AND_AND,
+ TOKENS_END
+ };
+
+public:
+ pp(Preprocessor* preprocessor);
+ ~pp();
+
+ Preprocessor* preprocessor();
+
+ enum StringType { File, Data };
+
+ ///@todo Remove
+ inline QString currentFileNameString () const { return m_files.top().str(); }
+
+ inline KDevelop::IndexedString currentFileName () const { return m_files.top(); }
+
+ Value eval_expression (Stream& input);
+
+ /** Read file @p fileName and preprocess
+ * Currently the file is expected to be utf8-encoded. */
+ PreprocessedContents processFile(const QString& fileName);
+
+ /** Preprocess @p fileName with content @p data. Do not actually open file @p fileName
+ * Currently the file is expected to be utf8-encoded. */
+ PreprocessedContents processFile(const QString& fileName, const QByteArray& data);
+
+ void operator () (Stream& input, Stream& output);
+
+ void checkMarkNeeded(Stream& input, Stream& output);
+
+ bool hideNextMacro() const;
+ void setHideNextMacro(bool hideNext);
+
+ Environment* environment() const;
+ // once set, belongs to the engine
+ void setEnvironment(Environment* env);
+
+ const QList<KDevelop::ProblemPointer>& problems() const;
+ void problemEncountered(const KDevelop::Problem& problem);
+ void problemEncountered(const KDevelop::ProblemPointer& problem);
+
+ //Returns a hash-value computed from all until currently open branching-conditions and their decisions(like #ifdef's)
+ uint branchingHash() const;
+
+private:
+ void processFileInternal(const QString& fileName, const QByteArray& fileContent, PreprocessedContents& result);
+
+ int skipping() const;
+ bool test_if_level();
+
+ void createProblem(Stream& input, const QString& description);
+
+ void skip(Stream& input, Stream& output, bool outputText = true);
+
+ Value eval_primary(Stream& input);
+
+ Value eval_multiplicative(Stream& input);
+
+ Value eval_additive(Stream& input);
+
+ Value eval_shift(Stream& input);
+
+ Value eval_relational(Stream& input);
+
+ Value eval_equality(Stream& input);
+
+ Value eval_and(Stream& input);
+
+ Value eval_xor(Stream& input);
+
+ Value eval_or(Stream& input);
+
+ Value eval_logical_and(Stream& input);
+
+ Value eval_logical_or(Stream& input);
+
+ Value eval_constant_expression(Stream& input);
+
+ void handle_directive(uint directive, Stream& input, Stream& output);
+
+ void handle_include(bool skip_current_path, Stream& input, Stream& output);
+
+ void handle_define(Stream& input);
+
+ void handle_if(Stream& input);
+
+ void handle_else(int sourceLine);
+
+ void handle_elif(Stream& input);
+
+ void handle_endif(Stream& input, Stream& output);
+
+ void handle_ifdef(bool check_undefined, Stream& input);
+
+ void handle_undef(Stream& input);
+
+ int next_token (Stream& input);
+ int next_token_accept (Stream& input);
+ void accept_token();
+};
+
+}
+
+#endif // PP_ENGINE_H
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h (revision 1522570)
@@ -0,0 +1,37 @@
+/*
+ Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_INTERNAL_H
+#define PP_INTERNAL_H
+
+#include "pp-stream.h"
+
+namespace rpp
+{
+
+bool isComment(Stream& input);
+
+Stream& devnull();
+
+}
+// _PP_internal
+
+#endif // PP_INTERNAL_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h (revision 1522570)
@@ -0,0 +1,50 @@
+/*
+ Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef ANCHOR_H
+#define ANCHOR_H
+
+#include <language/editor/simplecursor.h>
+
+#include <cppparserexport.h>
+
+namespace rpp {
+/**
+ * A KDevelop::SimpleCursor with additional boolean value whether the range opened by this anchor is collapsed.
+ * If that value is true, it means that Everything behind the anchor until the next one is collapsed to the exact position of this anchor.
+ * */
+class KDEVCPPRPP_EXPORT Anchor : public KDevelop::SimpleCursor {
+public:
+ Anchor() : collapsed(false) {
+ }
+
+ explicit Anchor(const SimpleCursor& cursor, bool _collapsed=false, KDevelop::SimpleCursor _macroExpansion=KDevelop::SimpleCursor::invalid()) : SimpleCursor(cursor), collapsed(_collapsed), macroExpansion(_macroExpansion) {
+ }
+ explicit Anchor(int line, int column, bool _collapsed=false, KDevelop::SimpleCursor _macroExpansion=KDevelop::SimpleCursor::invalid()) : SimpleCursor(line, column), collapsed(_collapsed), macroExpansion(_macroExpansion) {
+ }
+
+ bool collapsed;
+
+ ///@todo create a sub-class that contains macroExpansion. It is only needed in the location-table and everything using not, not actually in the anchors.
+ KDevelop::SimpleCursor macroExpansion; //Zero if this position was not transformed through a macro-expansion, else a number that identifies the expansion
+};
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h (revision 1522570)
@@ -0,0 +1,185 @@
+/*
+ Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_MACRO_H
+#define PP_MACRO_H
+
+//krazy:excludeall=inline
+
+#include <QtCore/QStringList>
+#include <QVector>
+#include <cppparserexport.h>
+#include <language/duchain/indexedstring.h>
+#include <language/editor/hashedstring.h>
+
+//Foreach macro that also works with KDevVarLengthArray
+#define FOREACH_CUSTOM(item, container, size) for(int a = 0, mustDo = 1; a < (int)size; ++a) if((mustDo = 1)) for(item(container[a]); mustDo; mustDo = 0)
+
+
+namespace rpp {
+
+ //This contains the data of a macro that can be marshalled by directly copying the memory
+struct KDEVCPPRPP_EXPORT pp_macro_direct_data
+{
+ pp_macro_direct_data(const KDevelop::IndexedString& nm = KDevelop::IndexedString());
+ typedef uint HashType;
+
+ KDevelop::IndexedString name;
+ KDevelop::IndexedString file;
+
+ int sourceLine; //line
+
+ bool defined: 1; // !isUndefMacro
+ bool hidden: 1;
+ bool function_like: 1; // hasArguments
+ bool variadics: 1;
+
+ //The valueHash is not necessarily valid
+ mutable HashType m_valueHash; //Hash that represents the values of all macros
+
+ bool operator==(const pp_macro_direct_data& rhs) const {
+ return name == rhs.name && file == rhs.file && sourceLine == rhs.sourceLine && defined == rhs.defined && hidden == rhs.hidden && function_like == rhs.function_like && variadics == rhs.variadics;
+ }
+
+ bool isUndef() const {
+ return !defined;
+ }
+
+ HashType completeHash() const {
+ return m_valueHash + name.hash() * 3777;
+ }
+
+ HashType idHash() const {
+ return name.hash();
+ }
+}; ///@todo enable structure packing
+
+///Never construct his directly. It represents a macro that is stored in a repository,
+///and that is stored in a memory-unit together with its definition- and formal-list
+///@see macrorepository.h and macrorepository.cpp
+struct KDEVCPPRPP_EXPORT pp_macro : public pp_macro_direct_data {
+ //Count of items in the tokenized definition vector
+ uint definitionSize() const;
+ const uint* definition() const;
+
+ //Count of items in the list of formals
+ uint formalsSize() const;
+ const uint* formals() const;
+
+ QString toString() const;
+
+ //Does a complete comparison
+ bool operator==(const pp_macro& rhs) const;
+
+ ///Hash that identifies all of this macro, the value and the identity
+ HashType completeHash() const {
+ return m_valueHash + name.hash() * 3777;
+ }
+
+ unsigned int hash() const {
+ return completeHash();
+ }
+
+ short unsigned int itemSize() const;
+
+ private:
+ Q_DISABLE_COPY(pp_macro)
+};
+
+class KDEVCPPRPP_EXPORT pp_dynamic_macro : public pp_macro_direct_data
+{
+public:
+ pp_dynamic_macro();
+ pp_dynamic_macro(const KDevelop::IndexedString& name);
+ pp_dynamic_macro(const char* name);
+
+ QVector<uint> definition; //Indices in the string index(essentially the same thing as IndexedString)
+ QVector<uint> formals; // argumentList, also indices in the string repository(IndexedString)
+
+ QString toString() const;
+
+ HashType valueHash() const {
+ if( !m_valueHashValid ) computeHash();
+ return m_valueHash;
+ }
+
+ ///Hash that identifies all of this macro, the value and the identity
+ HashType completeHash() const {
+ return valueHash() + idHash() * 3777;
+ }
+
+ void invalidateHash();
+
+ struct NameCompare {
+ bool operator () ( const pp_dynamic_macro& lhs, const pp_dynamic_macro& rhs ) const {
+ return lhs.name.index() < rhs.name.index();
+ }
+ #ifdef Q_CC_MSVC
+
+ HashType operator () ( const pp_dynamic_macro& macro ) const
+ {
+ return macro.idHash();
+ }
+
+ enum
+ { // parameters for hash table
+ bucket_size = 4, // 0 < bucket_size
+ min_buckets = 8}; // min_buckets = 2 ^^ N, 0 < N
+ #endif
+ };
+
+ //Hash over id and value
+ struct CompleteHash {
+ HashType operator () ( const pp_dynamic_macro& lhs ) const {
+ return lhs.completeHash();
+ }
+
+ #ifdef Q_CC_MSVC
+
+ bool operator () ( const pp_dynamic_macro& lhs, const pp_dynamic_macro& rhs ) const {
+ HashType lhash = lhs.valueHash()+lhs.idHash();
+ HashType rhash = rhs.valueHash()+rhs.idHash();
+ if( lhash < rhash ) return true;
+ else if( lhash > rhash ) return false;
+
+ int df = lhs.name.str().compare( rhs.name.str() );
+ return df < 0;
+ }
+
+ enum
+ { // parameters for hash table
+ bucket_size = 4, // 0 < bucket_size
+ min_buckets = 8}; // min_buckets = 2 ^^ N, 0 < N
+ #endif
+ };
+
+ private:
+ void computeHash() const;
+ mutable bool m_valueHashValid;
+};
+
+}
+
+inline uint qHash( const rpp::pp_dynamic_macro& m ) {
+ return (uint)m.idHash();
+}
+
+#endif // PP_MACRO_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration (revision 1522570)
@@ -0,0 +1,86 @@
+#define __DBL_MIN_EXP__ (-1021)
+#define __FLT_MIN__ 1.17549435e-38F
+#define __CHAR_BIT__ 8
+#define __WCHAR_MAX__ 2147483647
+#define __DBL_DENORM_MIN__ 4.9406564584124654e-324
+#define __FLT_EVAL_METHOD__ 2
+#define __DBL_MIN_10_EXP__ (-307)
+#define __FINITE_MATH_ONLY__ 0
+#define __GNUC_PATCHLEVEL__ 2
+#define __SHRT_MAX__ 32767
+#define __LDBL_MAX__ 1.18973149535723176502e+4932L
+#define __UINTMAX_TYPE__ long long unsigned int
+#define __linux 1
+#define __unix 1
+#define __LDBL_MAX_EXP__ 16384
+#define __linux__ 1
+#define __SCHAR_MAX__ 127
+#define __USER_LABEL_PREFIX__
+#define __STDC_HOSTED__ 1
+#define __LDBL_HAS_INFINITY__ 1
+#define __DBL_DIG__ 15
+#define __FLT_EPSILON__ 1.19209290e-7F
+#define __GXX_WEAK__ 1
+#define __LDBL_MIN__ 3.36210314311209350626e-4932L
+#define __unix__ 1
+#define __DECIMAL_DIG__ 21
+#define __gnu_linux__ 1
+#define __LDBL_HAS_QUIET_NAN__ 1
+#define __GNUC__ 4
+#define __DBL_MAX__ 1.7976931348623157e+308
+#define __DBL_HAS_INFINITY__ 1
+#define __cplusplus 1
+#define __DEPRECATED 1
+#define __DBL_MAX_EXP__ 1024
+#define __GNUG__ 4
+#define __LONG_LONG_MAX__ 9223372036854775807LL
+#define __GXX_ABI_VERSION 1002
+#define __FLT_MIN_EXP__ (-125)
+#define __DBL_MIN__ 2.2250738585072014e-308
+#define __FLT_MIN_10_EXP__ (-37)
+#define __DBL_HAS_QUIET_NAN__ 1
+#define __REGISTER_PREFIX__
+#define __NO_INLINE__ 1
+#define __i386 1
+#define __FLT_MANT_DIG__ 24
+#define __VERSION__ "4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)"
+#define i386 1
+#define __i486__ 1
+#define unix 1
+#define __i386__ 1
+#define __SIZE_TYPE__ unsigned int
+#define __ELF__ 1
+#define __FLT_RADIX__ 2
+#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
+#define __FLT_HAS_QUIET_NAN__ 1
+#define __FLT_MAX_10_EXP__ 38
+#define __LONG_MAX__ 2147483647L
+#define __FLT_HAS_INFINITY__ 1
+#define linux 1
+#define __EXCEPTIONS 1
+#define __LDBL_MANT_DIG__ 64
+#define __WCHAR_TYPE__ int
+#define __FLT_DIG__ 6
+#define __INT_MAX__ 2147483647
+#define __i486 1
+#define __FLT_MAX_EXP__ 128
+#define __DBL_MANT_DIG__ 53
+#define __WINT_TYPE__ unsigned int
+#define __LDBL_MIN_EXP__ (-16381)
+#define __LDBL_MAX_10_EXP__ 4932
+#define __DBL_EPSILON__ 2.2204460492503131e-16
+#define __tune_i486__ 1
+#define __INTMAX_MAX__ 9223372036854775807LL
+#define __FLT_DENORM_MIN__ 1.40129846e-45F
+#define __FLT_MAX__ 3.40282347e+38F
+#define __INTMAX_TYPE__ long long int
+#define __GNUC_MINOR__ 0
+#define __DBL_MAX_10_EXP__ 308
+#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
+#define __PTRDIFF_TYPE__ int
+#define __LDBL_MIN_10_EXP__ (-4931)
+#define __LDBL_DIG__ 18
+#define _GNU_SOURCE 1
+
+
+#define __STDC__
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h (revision 1522570)
@@ -0,0 +1,89 @@
+/*
+ Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef CHARTOOLS
+#define CHARTOOLS
+#include <QChar>
+#include "cppparserexport.h"
+
+template<class T>
+class QVector;
+class QString;
+class QByteArray;
+typedef QVector<unsigned int> PreprocessedContents;
+
+inline bool isSpace(char c) {
+ return QChar(c).isSpace();
+}
+
+inline bool isLetter(char c) {
+ return QChar(c).isLetter();
+}
+
+inline bool isLetterOrNumber(char c) {
+ return QChar(c).isLetterOrNumber();
+}
+
+inline bool isNumber(char c) {
+ return QChar(c).isNumber();
+}
+
+//Takes an index as delt with during preprocessing, and determines whether it is a fake-index that represents
+//a character. If the 0xffff0000 bits are set, it is a custom character.
+#define isCharacter(index) ((index & 0xffff0000) == 0xffff0000)
+
+//Creates an index that represents the given character
+#define indexFromCharacter(character) ((unsigned int)character | 0xffff0000)
+
+//Extracts the character that is represented by the index
+#define characterFromIndex(index) ((char)(index & 0xffff))
+
+inline bool isSpace(unsigned int c) {
+ return isCharacter(c) && QChar(characterFromIndex(c)).isSpace();
+}
+
+inline bool isLetter(unsigned int c) {
+ return isCharacter(c) && QChar(characterFromIndex(c)).isLetter();
+}
+
+inline bool isLetterOrNumber(unsigned int c) {
+ return isCharacter(c) && QChar(characterFromIndex(c)).isLetterOrNumber();
+}
+
+inline bool isNumber(unsigned int c) {
+ return isCharacter(c) && QChar(characterFromIndex(c)).isNumber();
+}
+
+///Opposite of convertFromByteArray
+KDEVCPPRPP_EXPORT QByteArray stringFromContents(const PreprocessedContents& contents, int offset = 0, int count = 0);
+
+///Opposite of convertFromByteArray
+KDEVCPPRPP_EXPORT QByteArray stringFromContents(const uint* contents, int count);
+
+///Returns a string that has a gap inserted between the tokens(for debugging)
+KDEVCPPRPP_EXPORT QByteArray stringFromContentsWithGaps(const PreprocessedContents& contents, int offset = 0, int count = 0);
+
+///Converts the byte array to a vector of fake-indices containing the text
+KDEVCPPRPP_EXPORT PreprocessedContents convertFromByteArray(const QByteArray& array);
+
+///Converts the byte array to a vector of fake-indices containing the text
+///This also tokenizes the given array when possible
+KDEVCPPRPP_EXPORT PreprocessedContents tokenizeFromByteArray(const QByteArray& array);
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h (revision 1522570)
@@ -0,0 +1,61 @@
+/*
+ Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef MACROREPOSITORY_H
+#define MACROREPOSITORY_H
+
+#include <language/duchain/repositories/itemrepository.h>
+#include <cppparserexport.h>
+#include "pp-macro.h"
+
+struct KDEVCPPRPP_EXPORT MacroRepositoryItemRequest {
+
+ //The text is supposed to be utf8 encoded
+ MacroRepositoryItemRequest(const rpp::pp_macro& _macro);
+
+ enum {
+ AverageSize = 20 //This should be the approximate average size of an Item
+ };
+
+ typedef unsigned int HashType;
+
+ HashType hash() const {
+ return macro.completeHash();
+ }
+
+ size_t itemSize() const;
+
+ void createItem(rpp::pp_macro* item) const;
+
+ //Should return whether the here requested item equals the given item
+ bool equals(const rpp::pp_macro* item) const;
+
+ const rpp::pp_macro& macro;
+};
+
+typedef KDevelop::ItemRepository<rpp::pp_macro, MacroRepositoryItemRequest> MacroDataRepository;
+
+//Returns the size of the object
+KDEVCPPRPP_EXPORT size_t constantSize(const rpp::pp_macro* macro);
+//Size of the pp_macro object for the given macro
+KDEVCPPRPP_EXPORT size_t constantSize(const rpp::pp_dynamic_macro* macro);
+//Constructs a constant macro object
+KDEVCPPRPP_EXPORT rpp::pp_macro* makeConstant(const rpp::pp_dynamic_macro* macro);
+//Creates an exact copy
+KDEVCPPRPP_EXPORT rpp::pp_macro* copyConstantMacro(const rpp::pp_macro* macro);
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h (revision 1522570)
@@ -0,0 +1,119 @@
+/*
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_ENVIRONMENT_H
+#define PP_ENVIRONMENT_H
+
+#include <QHash>
+#include <QMap>
+
+#include <QStack>
+#include <cppparserexport.h>
+
+namespace KDevelop {
+ class IndexedString;
+}
+
+namespace rpp {
+
+class pp_macro;
+class pp;
+class LocationTable;
+
+class KDEVCPPRPP_EXPORT MacroBlock
+{
+public:
+ MacroBlock(int _sourceLine);
+ virtual ~MacroBlock();
+
+ void setMacro(pp_macro* macro);
+
+ QList<MacroBlock*> childBlocks;
+
+ // The condition that opened this block(list of string indices)
+ QVector<uint> condition;
+ // The block to use if this block's condition was not met
+ MacroBlock* elseBlock;
+
+ // The source line where the block occurred
+ int sourceLine;
+
+ // This block is the owner of these macros
+ QList<pp_macro*> macros;
+};
+
+class KDEVCPPRPP_EXPORT Environment
+{
+public:
+ typedef QHash<KDevelop::IndexedString, pp_macro*> EnvironmentMap;
+
+ Environment(pp* preprocessor);
+ virtual ~Environment();
+
+ MacroBlock* firstBlock() const;
+ MacroBlock* currentBlock() const;
+
+ void enterBlock(MacroBlock* block);
+ MacroBlock* enterBlock(int sourceLine, const QVector<uint>& condition = QVector<uint>());
+ MacroBlock* elseBlock(int sourceLine, const QVector<uint>& condition = QVector<uint>());
+ void leaveBlock();
+
+ // Replay previously saved blocks on this environment
+ void visitBlock(MacroBlock* block, int depth = 0);
+
+ void clear();
+
+ // For those not interested in the result, just in getting memory released etc.
+ void cleanup();
+
+ void clearMacro(const KDevelop::IndexedString& name);
+
+ //Note: Undef-macros are allowed too
+ virtual void setMacro(pp_macro* macro);
+ virtual pp_macro* retrieveMacro(const KDevelop::IndexedString& name) const;
+
+ //Returns macros that are really stored locally(retrieveMacro may be overridden to perform more complex actions)
+ pp_macro* retrieveStoredMacro(const KDevelop::IndexedString& name) const;
+
+ QList<pp_macro*> allMacros() const;
+
+ //Take the set of environment-macros from the given environment
+ void swapMacros( Environment* parentEnvironment );
+
+ //Faster access then allMacros(..), because nothing is copied
+ const EnvironmentMap& environment() const; //krazy:exclude=constref
+
+ LocationTable* locationTable() const;
+ LocationTable* takeLocationTable();
+
+private:
+ EnvironmentMap m_environment;
+
+ QStack<MacroBlock*> m_blocks;
+ bool m_replaying;
+ pp* m_preprocessor;
+ LocationTable* m_locationTable;
+};
+
+}
+
+#endif // PP_ENVIRONMENT_H
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h (revision 1522570)
@@ -0,0 +1,111 @@
+/*
+ Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_MACRO_EXPANDER_H
+#define PP_MACRO_EXPANDER_H
+
+#include <QtCore/QList>
+#include <QtCore/QHash>
+
+
+#include "pp-macro.h"
+#include "pp-stream.h"
+#include "pp-scanner.h"
+#include "anchor.h"
+#include <language/editor/simplecursor.h>
+
+namespace KDevelop {
+ class IndexedString;
+}
+
+namespace rpp {
+
+class pp;
+
+//The value of a preprocessor function-like macro parameter
+class pp_actual {
+public:
+ QList<PreprocessedContents> text;
+ QList<Anchor> inputPosition; //Each inputPosition marks the beginning of one item in the text list
+
+ bool isValid() const {
+ return !text.isEmpty();
+ }
+ void clear() {
+ text.clear();
+ inputPosition.clear();
+ }
+
+ PreprocessedContents mergeText() const {
+ if(text.count() == 1)
+ return text.at(0);
+
+ PreprocessedContents ret;
+
+ foreach(const PreprocessedContents& t, text)
+ ret += t;
+ return ret;
+ }
+};
+
+class pp_frame
+{
+public:
+ pp_frame (pp_macro* __expandingMacro, const QList<pp_actual>& __actuals);
+
+ pp_macro* expandingMacro;
+ QList<pp_actual> actuals;
+};
+
+class pp_macro_expander
+{
+public:
+ explicit pp_macro_expander(pp* engine, pp_frame* frame = 0, bool inHeaderSection = false);
+
+ pp_actual resolve_formal(KDevelop::IndexedString name, Stream& input);
+
+ /// Expands text with the known macros. Continues until it finds a new text line
+ /// beginning with #, at which point control is returned.
+ void operator()(Stream& input, Stream& output);
+
+ void skip_argument_variadics (const QList<pp_actual>& __actuals, pp_macro *__macro,
+ Stream& input, Stream& output);
+
+private:
+ pp* m_engine;
+ pp_frame* m_frame;
+
+ pp_skip_number skip_number;
+ pp_skip_identifier skip_identifier;
+ pp_skip_string_literal skip_string_literal;
+ pp_skip_char_literal skip_char_literal;
+ pp_skip_argument skip_argument;
+ pp_skip_comment_or_divop skip_comment_or_divop;
+ pp_skip_blanks skip_blanks;
+ pp_skip_whitespaces skip_whitespaces;
+
+ bool m_in_header_section;
+};
+
+}
+
+#endif // PP_MACRO_EXPANDER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h (revision 1522570)
@@ -0,0 +1,86 @@
+/*
+ Copyright 2007 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_LOCATION_H
+#define PP_LOCATION_H
+
+#include <QMap>
+
+#include <language/editor/simplecursor.h>
+
+#include <cppparserexport.h>
+#include "anchor.h"
+
+typedef QVector<unsigned int> PreprocessedContents;
+
+namespace rpp {
+
+class KDEVCPPRPP_EXPORT LocationTable
+{
+ public:
+ LocationTable();
+
+ /// Generates the location table from the contents
+ LocationTable(const PreprocessedContents& contents);
+
+ ///@param contents is allowed to be zero only if offset is zero, or if anchor.column is zero.
+ void anchor(std::size_t offset, Anchor anchor, const PreprocessedContents* contents);
+
+ /**
+ * Return the position of the preprocessed source \a offset in the original source
+ * If the "collapsed" member of the returned anchor is true, the position is within a collapsed range.
+ @param collapseIfMacroExpansion @see LocationTable::positionForOffset
+ * \note the return line starts from 0, not 1.
+ * Returns the found position stored in the anchor, and the possible maximum length until the next anchored position, or zero.
+ */
+ QPair<rpp::Anchor, uint> positionAt(std::size_t offset, const PreprocessedContents& contents, bool collapseIfMacroExpansion = false) const;
+
+ struct AnchorInTable {
+ uint position; //Position of this anchor
+ Anchor anchor; //This anchor
+ uint nextPosition;//Position of the next following anchor, or zero
+ Anchor nextAnchor;//The next following anchor
+ };
+
+ /**
+ * Returns the nearest anchor before @param position, and the position of the anchor.
+ * If the character is in a collapsed range, the collapsed member is true.
+ @param collapseIfMacroExpansion When this is true, all ranges that come from macro-expansion will be
+ considered collapsed.(The returned anchor will also have the collapsed member set)
+ * */
+ AnchorInTable anchorForOffset(std::size_t position, bool collapseIfMacroExpansion = false) const;
+
+ void dump() const;
+
+ /**
+ * Splits the given @param text using this location-table into sub-strings each assigned to a cursor where it starts.
+ * @param textStartPosition must be given as the start-position, because the location-table might not contain an anchor
+ * for the first character.
+ * */
+ void splitByAnchors(const PreprocessedContents& text, const Anchor& textStartPosition, QList<PreprocessedContents>& strings, QList<Anchor>& anchors) const;
+
+ private:
+ QMap<std::size_t, Anchor> m_offsetTable;
+ mutable QMap<std::size_t, Anchor>::ConstIterator m_currentOffset;
+};
+
+}
+
+#endif // PP_LOCATION_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h (revision 1522570)
@@ -0,0 +1,97 @@
+/*
+ Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PP_SCANNER_H
+#define PP_SCANNER_H
+
+
+
+#include "pp-stream.h"
+
+namespace rpp {
+
+class pp_skip_blanks
+{
+public:
+ void operator()(Stream& input, Stream& output);
+};
+
+class pp_skip_whitespaces
+{
+public:
+ void operator()(Stream& input, Stream& output);
+};
+
+class pp_skip_comment_or_divop
+{
+public:
+ /**
+ * This scanner can either output equivalent blank space,
+ * or the actual text (the default).
+ */
+ void operator()(Stream& input, Stream& output, bool outputText = false);
+
+private:
+ bool m_outputText;
+};
+
+class pp_skip_identifier
+{
+public:
+ uint operator()(Stream& input);
+};
+
+class pp_skip_number
+{
+public:
+ void operator()(Stream& input, Stream& output);
+};
+
+class pp_skip_string_literal
+{
+public:
+ void operator()(Stream& input, Stream& output);
+};
+
+class pp_skip_char_literal
+{
+public:
+ void operator()(Stream& input, Stream& output);
+};
+
+//Does also skip any whitespace behind the argument
+class pp_skip_argument
+{
+public:
+ void operator()(Stream& input, Stream& output);
+
+private:
+ pp_skip_number skip_number;
+ pp_skip_identifier skip_identifier;
+ pp_skip_string_literal skip_string_literal;
+ pp_skip_char_literal skip_char_literal;
+ pp_skip_comment_or_divop skip_comment_or_divop;
+};
+
+}
+
+#endif // PP_SCANNER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h (revision 1522570)
@@ -0,0 +1,73 @@
+/*
+ Copyright 2005 Harald Fernengel <harry@kdevelop.org>
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation.
+
+ 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
+ KDEVELOP TEAM 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.
+*/
+
+#ifndef PREPROCESSOR_H
+#define PREPROCESSOR_H
+
+#include <QtCore/QString>
+#include <cppparserexport.h>
+namespace rpp {
+
+class Stream;
+
+class KDEVCPPRPP_EXPORT Preprocessor
+{
+public:
+ enum IncludeType {
+ /// An include specified as being local (eg. "file.h")
+ IncludeLocal,
+ /// An include specified as being global (eg. &lt;file.h&gt;)
+ IncludeGlobal
+ };
+
+ virtual ~Preprocessor();
+
+// QString processString(const QString& string);
+
+
+ /**
+ * This function is called by the preprocessor whenever
+ * it encounters an include directive.
+ *
+ * This class is permitted to modify \a fileName%; this
+ * value will be used when marking the file in the preprocessed
+ * output.
+ *
+ * \param fileName name of the source file to include
+ * \param type the way that the file was requested
+ * \param skipCurrentPath whether the path fileName was found in should be skipped(gcc extension include_next)
+ *
+ * \return a Stream with the appropriate contents to allow
+ * the file to be #included. Ownership of the Stream is yielded to
+ * class pp at this point.
+ */
+ virtual Stream* sourceNeeded(QString& fileName, IncludeType type, int sourceLine, bool skipCurrentPath);
+
+ /**
+ * Is called when the header-section ended. The header-section is the top of the file, that consists only if #include, #define, and #ifdef statements, or comments.
+ * It ends as soon as anything else is found. You can use stream.toEnd() to stop the preprocessing.
+ * */
+ virtual void headerSectionEnded(rpp::Stream& stream);
+};
+
+}
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h (revision 1522570)
@@ -0,0 +1,77 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef CODEMODEL_FWD_H
+#define CODEMODEL_FWD_H
+
+#include "kdevsharedptr.h"
+
+#include <QtCore/QList>
+
+// forward declarations
+class CodeModel;
+class _ArgumentModelItem;
+class _ClassModelItem;
+class _CodeModelItem;
+class _EnumModelItem;
+class _EnumeratorModelItem;
+class _FileModelItem;
+class _FunctionDefinitionModelItem;
+class _FunctionModelItem;
+class _NamespaceModelItem;
+class _ScopeModelItem;
+class _TemplateModelItem;
+class _TemplateParameterModelItem;
+class _TypeAliasModelItem;
+class _VariableModelItem;
+class _MemberModelItem;
+
+typedef KDevelop::SharedPtr<_ArgumentModelItem> ArgumentModelItem;
+typedef KDevelop::SharedPtr<_ClassModelItem> ClassModelItem;
+typedef KDevelop::SharedPtr<_CodeModelItem> CodeModelItem;
+typedef KDevelop::SharedPtr<_EnumModelItem> EnumModelItem;
+typedef KDevelop::SharedPtr<_EnumeratorModelItem> EnumeratorModelItem;
+typedef KDevelop::SharedPtr<_FileModelItem> FileModelItem;
+typedef KDevelop::SharedPtr<_FunctionDefinitionModelItem> FunctionDefinitionModelItem;
+typedef KDevelop::SharedPtr<_FunctionModelItem> FunctionModelItem;
+typedef KDevelop::SharedPtr<_NamespaceModelItem> NamespaceModelItem;
+typedef KDevelop::SharedPtr<_ScopeModelItem> ScopeModelItem;
+typedef KDevelop::SharedPtr<_TemplateModelItem> TemplateModelItem;
+typedef KDevelop::SharedPtr<_TemplateParameterModelItem> TemplateParameterModelItem;
+typedef KDevelop::SharedPtr<_TypeAliasModelItem> TypeAliasModelItem;
+typedef KDevelop::SharedPtr<_VariableModelItem> VariableModelItem;
+typedef KDevelop::SharedPtr<_MemberModelItem> MemberModelItem;
+
+typedef QList<ArgumentModelItem> ArgumentList;
+typedef QList<ClassModelItem> ClassList;
+typedef QList<CodeModelItem> CodeList;
+typedef QList<CodeModelItem> ItemList;
+typedef QList<EnumModelItem> EnumList;
+typedef QList<EnumeratorModelItem> EnumeratorList;
+typedef QList<FileModelItem> FileList;
+typedef QList<FunctionDefinitionModelItem> FunctionDefinitionList;
+typedef QList<FunctionModelItem> FunctionList;
+typedef QList<NamespaceModelItem> NamespaceList;
+typedef QList<ScopeModelItem> ScopeList;
+typedef QList<TemplateModelItem> TemplateList;
+typedef QList<TemplateParameterModelItem> TemplateParameterList;
+typedef QList<TypeAliasModelItem> TypeAliasList;
+typedef QList<VariableModelItem> VariableList;
+typedef QList<MemberModelItem> MemberList;
+
+#endif // CODEMODEL_FWD_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parser.h (revision 1522570)
@@ -0,0 +1,262 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef PARSER_H
+#define PARSER_H
+
+#include "ast.h"
+#include "lexer.h"
+#include "commentparser.h"
+
+#include <QtCore/QQueue>
+#include <QtCore/QSet>
+#include <QtCore/QString>
+#include <cppparserexport.h>
+
+class TokenStream;
+class Control;
+
+/**
+The Parser.
+LL(k) parser for c++ code.
+*/
+class KDEVCPPPARSER_EXPORT Parser
+{
+public:
+ Parser(Control *control);
+ ~Parser();
+
+ /**Parses the @p contents of the buffer of given @p size using the
+ memory pool @p p to store tokens found.
+
+ Calls lexer to tokenize all contents buffer, skips the first token
+ (because the lexer provides Token_EOF as the first token,
+ creates and fills the AST and returns translation unit or 0
+ if nothing was parsed.
+
+ @sa pool for more information about the memory pool used.*/
+ TranslationUnitAST *parse(ParseSession* session);
+
+ /**
+ * Same as parse, except that it parses the content as a compound statement.
+ * This is useful for parsing independent expression-strings that appear for
+ * example within a function.
+ *
+ * parse(..) expects the content to be a valid translation-unit,
+ * while parseStatement can parse strings like "{a.b = 5;}" as if they
+ * appeared within a function.
+ *
+ * Note: The input must be a valid compound-statement, which means it must
+ * start at least with "{", and end with ";}"
+ **/
+ StatementAST *parseStatement(ParseSession* session);
+
+ /**
+ * Nearly the same as parseStatement, except that it parses the content as a type-id if possible,
+ * if that fails, as an expression. This is perfect for parsing template-arguements.
+ * The input can be as simple as "A" or "A::a+2"
+ * @param forceExpression If this is true, the text will not be considered to be a type-id, only an expression.
+ * */
+ AST *parseTypeOrExpression(ParseSession* session, bool forceExpression = false);
+ /**@return the problem count.*/
+ int problemCount() const { return _M_problem_count; }
+
+private:
+ /**Convenience method to report problems. Constructs the problem
+ using the information about the current line and column in the buffer
+ that is being parsed. Then stores the problem in the control object.*/
+ void reportError(const QString& msg);
+ /**Reports a syntax error about unexpected token. The token
+ reported is LA (look-ahead) from the stream.*/
+ void syntaxError();
+ /**Reports a syntax error about required token when LA is wrong.*/
+ void tokenRequiredError(int expected);
+
+public:
+ bool parseAbstractDeclarator(DeclaratorAST *&node);
+ bool parseAccessSpecifier(DeclarationAST *&node);
+ bool parseAdditiveExpression(ExpressionAST *&node);
+ bool parseAndExpression(ExpressionAST *&node, bool templArgs = false);
+ bool parseAsmDefinition(DeclarationAST *&node);
+ bool parseAssignmentExpression(ExpressionAST *&node);
+ bool parseBaseClause(BaseClauseAST *&node);
+ bool parseBaseSpecifier(BaseSpecifierAST *&node);
+ bool parseBlockDeclaration(DeclarationAST *&node);
+ bool parseCastExpression(ExpressionAST *&node);
+ bool parseClassSpecifier(TypeSpecifierAST *&node);
+ bool parseCommaExpression(ExpressionAST *&node);
+ bool parseCompoundStatement(StatementAST *&node);
+ bool parseCondition(ConditionAST *&node, bool initRequired = true);
+ bool parseConditionalExpression(ExpressionAST *&node);
+ bool parseConstantExpression(ExpressionAST *&node);
+ bool parseCtorInitializer(CtorInitializerAST *&node);
+ bool parseCvQualify(const ListNode<std::size_t> *&node);
+ bool parseDeclaration(DeclarationAST *&node);
+ bool parseDeclarationInternal(DeclarationAST *&node);
+ bool parseDeclarationStatement(StatementAST *&node);
+ bool parseDeclarator(DeclaratorAST *&node);
+ bool parseDeleteExpression(ExpressionAST *&node);
+ bool parseDoStatement(StatementAST *&node);
+ bool parseElaboratedTypeSpecifier(TypeSpecifierAST *&node);
+ bool parseEnumSpecifier(TypeSpecifierAST *&node);
+ bool parseEnumerator(EnumeratorAST *&node);
+ bool parseEqualityExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseExceptionSpecification(ExceptionSpecificationAST *&node);
+ bool parseExclusiveOrExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseExpression(ExpressionAST *&node);
+ bool parseExpressionOrDeclarationStatement(StatementAST *&node);
+ bool parseExpressionStatement(StatementAST *&node);
+ bool parseForInitStatement(StatementAST *&node);
+ bool parseForStatement(StatementAST *&node);
+ bool parseFunctionBody(StatementAST *&node);
+ bool parseFunctionSpecifier(const ListNode<std::size_t> *&node);
+ bool parseIfStatement(StatementAST *&node);
+ bool parseInclusiveOrExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseInitDeclarator(InitDeclaratorAST *&node);
+ bool parseInitDeclaratorList(const ListNode<InitDeclaratorAST*> *&node);
+ bool parseInitializer(InitializerAST *&node);
+ bool parseInitializerClause(InitializerClauseAST *&node);
+ bool parseInitializerList(const ListNode<InitializerClauseAST*> *&node);
+ bool parseJumpStatement(StatementAST *&node);
+ bool parseLabeledStatement(StatementAST *&node);
+ bool parseLinkageBody(LinkageBodyAST *&node);
+ bool parseLinkageSpecification(DeclarationAST *&node);
+ bool parseLogicalAndExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseLogicalOrExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseMemInitializer(MemInitializerAST *&node);
+ bool parseMemInitializerList(const ListNode<MemInitializerAST*> *&node);
+ bool parseMemberSpecification(DeclarationAST *&node);
+ bool parseMultiplicativeExpression(ExpressionAST *&node);
+ bool parseName(NameAST *&node, bool acceptTemplateId = false);
+ bool parseNamespace(DeclarationAST *&node);
+ bool parseNamespaceAliasDefinition(DeclarationAST *&node);
+ bool parseNewDeclarator(NewDeclaratorAST *&node);
+ bool parseNewExpression(ExpressionAST *&node);
+ bool parseNewInitializer(NewInitializerAST *&node);
+ bool parseNewTypeId(NewTypeIdAST *&node);
+ bool parseOperator(OperatorAST *&node);
+ bool parseOperatorFunctionId(OperatorFunctionIdAST *&node);
+ bool parseParameterDeclaration(ParameterDeclarationAST *&node);
+ bool parseParameterDeclarationClause(ParameterDeclarationClauseAST *&node);
+ bool parseParameterDeclarationList(const ListNode<ParameterDeclarationAST*> *&node);
+ bool parsePmExpression(ExpressionAST *&node);
+ bool parsePostfixExpression(ExpressionAST *&node);
+ bool parsePostfixExpressionInternal(ExpressionAST *&node);
+ bool parsePrimaryExpression(ExpressionAST *&node);
+ bool parsePtrOperator(PtrOperatorAST *&node);
+ bool parsePtrToMember(PtrToMemberAST *&node);
+ bool parseRelationalExpression(ExpressionAST *&node,
+ bool templArgs = false);
+ bool parseShiftExpression(ExpressionAST *&node);
+ bool parseSimpleTypeSpecifier(TypeSpecifierAST *&node,
+ bool onlyIntegral = false);
+ bool parseStatement(StatementAST *&node);
+ bool parseStorageClassSpecifier(const ListNode<std::size_t> *&node);
+ bool parseStringLiteral(StringLiteralAST *&node);
+ bool parseSwitchStatement(StatementAST *&node);
+ bool parseTemplateArgument(TemplateArgumentAST *&node);
+ bool parseTemplateArgumentList(const ListNode<TemplateArgumentAST*> *&node,
+ bool reportError = true);
+ bool parseTemplateDeclaration(DeclarationAST *&node);
+ bool parseTemplateParameter(TemplateParameterAST *&node);
+ bool parseTemplateParameterList(const ListNode<TemplateParameterAST*> *&node);
+ bool parseThrowExpression(ExpressionAST *&node);
+ bool parseTranslationUnit(TranslationUnitAST *&node);
+ bool parseTryBlockStatement(StatementAST *&node);
+ bool parseTypeId(TypeIdAST *&node);
+ bool parseTypeIdList(const ListNode<TypeIdAST*> *&node);
+ bool parseTypeParameter(TypeParameterAST *&node);
+ bool parseTypeSpecifier(TypeSpecifierAST *&node);
+ bool parseTypeSpecifierOrClassSpec(TypeSpecifierAST *&node);
+ bool parseTypedef(DeclarationAST *&node);
+ bool parseUnaryExpression(ExpressionAST *&node);
+ bool parseUnqualifiedName(UnqualifiedNameAST *&node,
+ bool parseTemplateId = true);
+ bool parseUsing(DeclarationAST *&node);
+ bool parseUsingDirective(DeclarationAST *&node);
+ bool parseWhileStatement(StatementAST *&node);
+ bool parseWinDeclSpec(WinDeclSpecAST *&node);
+
+ bool skipUntil(int token);
+ bool skipUntilDeclaration();
+ bool skipUntilStatement();
+ bool skip(int l, int r);
+
+ void addComment( CommentAST* ast, const Comment& comment );
+ //Moves all currently available comments to the given AST, removing them from the comment-store
+ void moveComments( CommentAST* ast );
+
+ void advance(bool skipComment = true);
+ void rewind(size_t position);
+ // private:
+ TokenStream* token_stream;
+
+// private:
+ Control *control;
+ Lexer lexer;
+private:
+
+ int lineFromTokenNumber( size_t tokenNumber ) const;
+
+ ///parses all comments until the end of the line
+ Comment comment();
+ ///Preparses comments in the same line as given token-number
+ void preparseLineComments( int tokenNumber );
+ void processComment( int offset = 0, int line = -1 );
+ void clearComment( );
+
+ bool holdErrors(bool hold);
+ void reportPendingErrors();
+
+ Comment m_currentComment;
+ CommentStore m_commentStore;
+
+ int _M_problem_count;
+ int _M_max_problem_count;
+ ParseSession* session;
+ bool _M_hold_errors;
+ size_t _M_last_valid_token; //Last encountered token that was not a comment
+ size_t _M_last_parsed_comment;
+
+ // keeps track of tokens where a syntax error has been found
+ // so that the same error is not reported twice for a token
+ QSet<std::size_t> m_syntaxErrorTokens;
+
+ // when _M_hold_errors is true, reported errors are held in m_pendingErrors
+ // rather than being reported to the Control immediately.
+ //
+ // this is used, for example, when parsing ambiguous statements.
+ struct PendingError
+ {
+ QString message;
+ std::size_t cursor;
+ };
+ QQueue<PendingError> m_pendingErrors;
+
+private:
+ Parser(const Parser& source);
+ void operator = (const Parser& source);
+};
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/visitor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/visitor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/visitor.h (revision 1522570)
@@ -0,0 +1,134 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef VISITOR_H
+#define VISITOR_H
+
+#include "ast.h"
+#include <cppparserexport.h>
+
+class KDEVCPPPARSER_EXPORT Visitor
+{
+public:
+ Visitor();
+ virtual ~Visitor();
+
+ virtual void visit(AST *node);
+
+protected:
+ virtual void visitAccessSpecifier(AccessSpecifierAST *) {}
+ virtual void visitAsmDefinition(AsmDefinitionAST *) {}
+ virtual void visitBaseClause(BaseClauseAST *) {}
+ virtual void visitBaseSpecifier(BaseSpecifierAST *) {}
+ virtual void visitBinaryExpression(BinaryExpressionAST *) {}
+ virtual void visitCastExpression(CastExpressionAST *) {}
+ virtual void visitClassMemberAccess(ClassMemberAccessAST *) {}
+ virtual void visitClassSpecifier(ClassSpecifierAST *) {}
+ virtual void visitCompoundStatement(CompoundStatementAST *) {}
+ virtual void visitCondition(ConditionAST *) {}
+ virtual void visitConditionalExpression(ConditionalExpressionAST *) {}
+ virtual void visitCppCastExpression(CppCastExpressionAST *) {}
+ virtual void visitCtorInitializer(CtorInitializerAST *) {}
+ virtual void visitDeclarationStatement(DeclarationStatementAST *) {}
+ virtual void visitDeclarator(DeclaratorAST *) {}
+ virtual void visitDeleteExpression(DeleteExpressionAST *) {}
+ virtual void visitDoStatement(DoStatementAST *) {}
+ virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *) {}
+ virtual void visitEnumSpecifier(EnumSpecifierAST *) {}
+ virtual void visitEnumerator(EnumeratorAST *) {}
+ virtual void visitExceptionSpecification(ExceptionSpecificationAST *) {}
+ virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *) {}
+ virtual void visitExpressionStatement(ExpressionStatementAST *) {}
+ virtual void visitForStatement(ForStatementAST *) {}
+ virtual void visitFunctionCall(FunctionCallAST *) {}
+ virtual void visitFunctionDefinition(FunctionDefinitionAST *) {}
+ virtual void visitIfStatement(IfStatementAST *) {}
+ virtual void visitIncrDecrExpression(IncrDecrExpressionAST *) {}
+ virtual void visitInitDeclarator(InitDeclaratorAST *) {}
+ virtual void visitInitializer(InitializerAST *) {}
+ virtual void visitInitializerClause(InitializerClauseAST *) {}
+ virtual void visitJumpStatement(JumpStatementAST *) {}
+ virtual void visitLabeledStatement(LabeledStatementAST *) {}
+ virtual void visitLinkageBody(LinkageBodyAST *) {}
+ virtual void visitLinkageSpecification(LinkageSpecificationAST *) {}
+ virtual void visitMemInitializer(MemInitializerAST *) {}
+ virtual void visitName(NameAST *) {}
+ virtual void visitNamespace(NamespaceAST *) {}
+ virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *) {}
+ virtual void visitNewDeclarator(NewDeclaratorAST *) {}
+ virtual void visitNewExpression(NewExpressionAST *) {}
+ virtual void visitNewInitializer(NewInitializerAST *) {}
+ virtual void visitNewTypeId(NewTypeIdAST *) {}
+ virtual void visitOperator(OperatorAST *) {}
+ virtual void visitOperatorFunctionId(OperatorFunctionIdAST *) {}
+ virtual void visitParameterDeclaration(ParameterDeclarationAST *) {}
+ virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *) {}
+ virtual void visitPostfixExpression(PostfixExpressionAST *) {}
+ virtual void visitPrimaryExpression(PrimaryExpressionAST *) {}
+ virtual void visitPtrOperator(PtrOperatorAST *) {}
+ virtual void visitPtrToMember(PtrToMemberAST *) {}
+ virtual void visitReturnStatement(ReturnStatementAST *) {}
+ virtual void visitSimpleDeclaration(SimpleDeclarationAST *) {}
+ virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *) {}
+ virtual void visitSizeofExpression(SizeofExpressionAST *) {}
+ virtual void visitStringLiteral(StringLiteralAST *) {}
+ virtual void visitSubscriptExpression(SubscriptExpressionAST *) {}
+ virtual void visitSwitchStatement(SwitchStatementAST *) {}
+ virtual void visitTemplateArgument(TemplateArgumentAST *) {}
+ virtual void visitTemplateDeclaration(TemplateDeclarationAST *) {}
+ virtual void visitTemplateParameter(TemplateParameterAST *) {}
+ virtual void visitThrowExpression(ThrowExpressionAST *) {}
+ virtual void visitTranslationUnit(TranslationUnitAST *) {}
+ virtual void visitTryBlockStatement(TryBlockStatementAST *) {}
+ virtual void visitCatchStatement(CatchStatementAST *) {}
+ virtual void visitTypeId(TypeIdAST *) {}
+ virtual void visitTypeIdentification(TypeIdentificationAST *) {}
+ virtual void visitTypeParameter(TypeParameterAST *) {}
+ virtual void visitTypedef(TypedefAST *) {}
+ virtual void visitUnaryExpression(UnaryExpressionAST *) {}
+ virtual void visitUnqualifiedName(UnqualifiedNameAST *) {}
+ virtual void visitUsing(UsingAST *) {}
+ virtual void visitUsingDirective(UsingDirectiveAST *) {}
+ virtual void visitWhileStatement(WhileStatementAST *) {}
+ virtual void visitWinDeclSpec(WinDeclSpecAST *) {}
+
+private:
+ typedef void (Visitor::*visitor_fun_ptr)(AST *);
+ static visitor_fun_ptr _S_table[];
+};
+
+template <class _Tp>
+ void visitNodes(Visitor *v, const ListNode<_Tp> *nodes)
+ {
+ if (!nodes)
+ return;
+
+ const ListNode<_Tp>
+ *it = nodes->toFront(),
+ *end = it;
+
+ do
+ {
+ v->visit(it->element);
+ it = it->next;
+ }
+ while (it != end);
+ }
+
+#endif // VISITOR_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/cppparserexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/cppparserexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/cppparserexport.h (revision 1522570)
@@ -0,0 +1,42 @@
+/*
+ This file is part of the KDevelop platform
+ Copyright 2004 Jaroslaw Staniek <js@iidea.pl>
+ Copyright 2006 Matt Rogers <mattr@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+#ifndef CPPPARSEREXPORT_H
+#define CPPPARSEREXPORT_H
+
+/* needed for KDE_EXPORT macros */
+#include <kdemacros.h>
+
+#ifndef KDEVCPPPARSER_EXPORT
+# ifdef MAKE_KDEV4CPPPARSER_LIB
+# define KDEVCPPPARSER_EXPORT KDE_EXPORT
+# else
+# define KDEVCPPPARSER_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#ifndef KDEVCPPRPP_EXPORT
+# ifdef MAKE_KDEV4CPPRPP_LIB
+# define KDEVCPPRPP_EXPORT KDE_EXPORT
+# else
+# define KDEVCPPRPP_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif /* CPPPARSEREXPORT_H*/
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/memorypool.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/memorypool.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/memorypool.h (revision 1522570)
@@ -0,0 +1,41 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef MEMORYPOOL_H
+#define MEMORYPOOL_H
+
+#include "rxx_allocator.h"
+#include <cstring>
+
+/**Memory pool for chars.*/
+class pool
+{
+ rxx_allocator<char> __alloc;
+
+public:
+ /**Allocates the @p size bytes in the pool.*/
+ inline void *allocate(std::size_t __size);
+};
+
+inline void *pool::allocate(std::size_t __size)
+{
+ return __alloc.allocate(__size);
+}
+
+#endif // MEMORYPOOL_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/default_visitor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/default_visitor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/default_visitor.h (revision 1522570)
@@ -0,0 +1,113 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef DEFAULT_VISITOR_H
+#define DEFAULT_VISITOR_H
+
+#include "visitor.h"
+#include <cppparserexport.h>
+
+class KDEVCPPPARSER_EXPORT DefaultVisitor: public Visitor
+{
+public:
+ DefaultVisitor() {}
+
+protected:
+ virtual void visitAccessSpecifier(AccessSpecifierAST *);
+ virtual void visitAsmDefinition(AsmDefinitionAST *);
+ virtual void visitBaseClause(BaseClauseAST *);
+ virtual void visitBaseSpecifier(BaseSpecifierAST *);
+ virtual void visitBinaryExpression(BinaryExpressionAST *);
+ virtual void visitCastExpression(CastExpressionAST *);
+ virtual void visitClassMemberAccess(ClassMemberAccessAST *);
+ virtual void visitClassSpecifier(ClassSpecifierAST *);
+ virtual void visitCompoundStatement(CompoundStatementAST *);
+ virtual void visitCondition(ConditionAST *);
+ virtual void visitConditionalExpression(ConditionalExpressionAST *);
+ virtual void visitCppCastExpression(CppCastExpressionAST *);
+ virtual void visitCtorInitializer(CtorInitializerAST *);
+ virtual void visitDeclarationStatement(DeclarationStatementAST *);
+ virtual void visitDeclarator(DeclaratorAST *);
+ virtual void visitDeleteExpression(DeleteExpressionAST *);
+ virtual void visitDoStatement(DoStatementAST *);
+ virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *);
+ virtual void visitEnumSpecifier(EnumSpecifierAST *);
+ virtual void visitEnumerator(EnumeratorAST *);
+ virtual void visitExceptionSpecification(ExceptionSpecificationAST *);
+ virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *);
+ virtual void visitExpressionStatement(ExpressionStatementAST *);
+ virtual void visitForStatement(ForStatementAST *);
+ virtual void visitFunctionCall(FunctionCallAST *);
+ virtual void visitFunctionDefinition(FunctionDefinitionAST *);
+ virtual void visitIfStatement(IfStatementAST *);
+ virtual void visitIncrDecrExpression(IncrDecrExpressionAST *);
+ virtual void visitInitDeclarator(InitDeclaratorAST *);
+ virtual void visitInitializer(InitializerAST *);
+ virtual void visitInitializerClause(InitializerClauseAST *);
+ virtual void visitJumpStatement(JumpStatementAST *);
+ virtual void visitLabeledStatement(LabeledStatementAST *);
+ virtual void visitLinkageBody(LinkageBodyAST *);
+ virtual void visitLinkageSpecification(LinkageSpecificationAST *);
+ virtual void visitMemInitializer(MemInitializerAST *);
+ virtual void visitName(NameAST *);
+ virtual void visitNamespace(NamespaceAST *);
+ virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *);
+ virtual void visitNewDeclarator(NewDeclaratorAST *);
+ virtual void visitNewExpression(NewExpressionAST *);
+ virtual void visitNewInitializer(NewInitializerAST *);
+ virtual void visitNewTypeId(NewTypeIdAST *);
+ virtual void visitOperator(OperatorAST *);
+ virtual void visitOperatorFunctionId(OperatorFunctionIdAST *);
+ virtual void visitParameterDeclaration(ParameterDeclarationAST *);
+ virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *);
+ virtual void visitPostfixExpression(PostfixExpressionAST *);
+ virtual void visitPrimaryExpression(PrimaryExpressionAST *);
+ virtual void visitPtrOperator(PtrOperatorAST *);
+ virtual void visitPtrToMember(PtrToMemberAST *);
+ virtual void visitReturnStatement(ReturnStatementAST *);
+ virtual void visitSimpleDeclaration(SimpleDeclarationAST *);
+ virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *);
+ virtual void visitSizeofExpression(SizeofExpressionAST *);
+ virtual void visitStringLiteral(StringLiteralAST *);
+ virtual void visitSubscriptExpression(SubscriptExpressionAST *);
+ virtual void visitSwitchStatement(SwitchStatementAST *);
+ virtual void visitTemplateArgument(TemplateArgumentAST *);
+ virtual void visitTemplateDeclaration(TemplateDeclarationAST *);
+ virtual void visitTemplateParameter(TemplateParameterAST *);
+ virtual void visitThrowExpression(ThrowExpressionAST *);
+ virtual void visitTranslationUnit(TranslationUnitAST *);
+ virtual void visitTryBlockStatement(TryBlockStatementAST *);
+ virtual void visitCatchStatement(CatchStatementAST *);
+ virtual void visitTypeId(TypeIdAST *);
+ virtual void visitTypeIdentification(TypeIdentificationAST *);
+ virtual void visitTypeParameter(TypeParameterAST *);
+ virtual void visitTypedef(TypedefAST *);
+ virtual void visitUnaryExpression(UnaryExpressionAST *);
+ virtual void visitUnqualifiedName(UnqualifiedNameAST *);
+ virtual void visitUsing(UsingAST *);
+ virtual void visitUsingDirective(UsingDirectiveAST *);
+ virtual void visitWhileStatement(WhileStatementAST *);
+ virtual void visitWinDeclSpec(WinDeclSpecAST *);
+
+private:
+ typedef void (Visitor::*visitor_fun_ptr)(AST *);
+ static visitor_fun_ptr _S_table[];
+};
+
+#endif // VISITOR_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/tokens.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/tokens.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/tokens.h (revision 1522570)
@@ -0,0 +1,141 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef TOKENS_H
+#define TOKENS_H
+
+#include <cppparserexport.h>
+
+/**@file Token kinds.*/
+
+/**Token kinds.*/
+enum TOKEN_KIND
+{
+ Token_EOF = 0,
+
+ Token_K_DCOP = 1000,
+ Token_Q_OBJECT,
+ Token___attribute__,
+ Token___typeof,
+ Token_and,
+ Token_and_eq,
+ Token_arrow,
+ Token_asm,
+ Token_assign,
+ Token_auto,
+ Token_bitand,
+ Token_bitor,
+ Token_bool,
+ Token_break,
+ Token_case,
+ Token_catch,
+ Token_char,
+ Token_char_literal,
+ Token_class,
+ Token_comment,
+ Token_compl,
+ Token_concat,
+ Token_const,
+ Token_const_cast,
+ Token_continue,
+ Token_decr,
+ Token_default,
+ Token_delete,
+ Token_do,
+ Token_double,
+ Token_dynamic_cast,
+ Token_ellipsis,
+ Token_else,
+ Token_emit,
+ Token_enum,
+ Token_eq,
+ Token_explicit,
+ Token_export,
+ Token_extern,
+ Token_false,
+ Token_float,
+ Token_for,
+ Token_friend,
+ Token_geq,
+ Token_goto,
+ Token_identifier,
+ Token_if,
+ Token_incr,
+ Token_inline,
+ Token_int,
+ Token_k_dcop,
+ Token_k_dcop_signals,
+ Token_leq,
+ Token_long,
+ Token_mutable,
+ Token_namespace,
+ Token_new,
+ Token_not,
+ Token_not_eq,
+ Token_number_literal,
+ Token_operator,
+ Token_or,
+ Token_or_eq,
+ Token_preproc,
+ Token_private,
+ Token_protected,
+ Token_ptrmem,
+ Token_public,
+ Token_register,
+ Token_reinterpret_cast,
+ Token_return,
+ Token_scope,
+ Token_shift,
+ Token_short,
+ Token_signals,
+ Token_signed,
+ Token_sizeof,
+ Token_slots,
+ Token_static,
+ Token_static_cast,
+ Token_string_literal,
+ Token_struct,
+ Token_switch,
+ Token_template,
+ Token_this,
+ Token_throw,
+ Token_true,
+ Token_try,
+ Token_typedef,
+ Token_typeid,
+ Token_typename,
+ Token_union,
+ Token_unsigned,
+ Token_using,
+ Token_virtual,
+ Token_void,
+ Token_volatile,
+ Token_wchar_t,
+ Token_while,
+ Token_whitespaces,
+ Token_xor,
+ Token_xor_eq,
+
+ TOKEN_KIND_COUNT
+};
+
+/**@return human-readable name of the token.*/
+KDEVCPPPARSER_EXPORT char const *token_name(int token);
+
+#endif
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/symbol.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/symbol.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/symbol.h (revision 1522570)
@@ -0,0 +1,140 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef SYMBOL_H
+#define SYMBOL_H
+
+#include <QtCore/QString>
+#include <cstring>
+
+#include <QtCore/QHash>
+#include <QtCore/QPair>
+
+/**@file symbol.h Symbol table for the parser.*/
+
+/**
+Symbol in the parser symbol table.
+*/
+struct NameSymbol
+{
+ const char *data;
+ std::size_t count;
+
+ inline QString as_string() const
+ {
+ return QString::fromUtf8(data, count);
+ }
+
+ /**Required to put NameSymbol's into a QHash.*/
+ inline bool operator == (const NameSymbol &other) const
+ {
+ return count == other.count
+ && std::strncmp(data, other.data, count) == 0;
+ }
+
+protected:
+ inline NameSymbol() {}
+ inline NameSymbol(const char *d, std::size_t c)
+ : data(d), count(c) {}
+
+private:
+ void operator = (const NameSymbol &);
+
+ friend class NameTable;
+};
+
+
+/**
+@brief Required to put NameSymbol's into a QHash.
+@see qHash(const QPair<const char*, std::size_t> &r) method for the reference.*/
+inline uint qHash(const NameSymbol &r)
+{
+ uint hash_value = 0;
+
+ for (std::size_t i=0; i<r.count; ++i)
+ hash_value = (hash_value << 5) - hash_value + r.data[i];
+
+ return hash_value;
+}
+
+
+/**
+Required to put pairs of char* and std::size_t into a QHash.
+
+Hash function is: hash = hash*31 + key[i].@n
+It looks like a Bernstein's hash function with a different factor.
+@n Original Bernstein's function is: hash = hash*33 + key[i].
+@n Factor of 31 makes this function return reliably unique values
+for english words with 6 symbols length.
+
+@n More information can be found at @a http://burtleburtle.net/bob/hash/doobs.html.
+*/
+inline uint qHash(const QPair<const char*, std::size_t> &r)
+{
+ uint hash_value = 0;
+
+ for (std::size_t i=0; i<r.second; ++i)
+ hash_value = (hash_value << 5) - hash_value + r.first[i];
+
+ return hash_value;
+}
+
+/**Symbol table for the parser.*/
+class NameTable
+{
+public:
+ typedef QPair<const char *, std::size_t> KeyType;
+ typedef QHash<KeyType, NameSymbol*> ContainerType;
+
+public:
+ NameTable() {}
+
+ ~NameTable()
+ {
+ qDeleteAll(_M_storage);
+ }
+
+ inline const NameSymbol *findOrInsert(const char *str, std::size_t len)
+ {
+ KeyType key(str, len);
+
+ NameSymbol *name = _M_storage.value(key);
+ if (!name)
+ {
+ name = new NameSymbol(str, len);
+ _M_storage.insert(key, name);
+ }
+
+ return name;
+ }
+
+ inline std::size_t count() const
+ {
+ return _M_storage.size();
+ }
+
+private:
+ ContainerType _M_storage;
+
+private:
+ NameTable(const NameTable &other);
+ void operator = (const NameTable &other);
+};
+
+#endif // SYMBOL_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/name_compiler.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/name_compiler.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/name_compiler.h (revision 1522570)
@@ -0,0 +1,68 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef NAME_COMPILER_H
+#define NAME_COMPILER_H
+
+#include "default_visitor.h"
+#include <language/duchain/identifier.h>
+#include <cppparserexport.h>
+#include <language/duchain/declaration.h>
+
+class ParseSession;
+class OperatorAST;
+
+class KDEVCPPPARSER_EXPORT NameCompiler: protected DefaultVisitor
+{
+public:
+ NameCompiler(ParseSession* session);
+
+ void run(NameAST *node);
+ void run(UnqualifiedNameAST *node) { m_typeSpecifier = 0; internal_run(node); }
+
+ QString name() const { return _M_name.toString(); }
+ QStringList qualifiedName() const { return _M_name.toStringList(); }
+
+ const KDevelop::QualifiedIdentifier& identifier() const;
+
+ /**
+ * When the name contains one type-specifier, this should contain that specifier after the run.
+ * Especially this is the type-specifier of a conversion-operator like "operator int()"
+ * */
+ TypeSpecifierAST* lastTypeSpecifier() const;
+
+protected:
+ virtual void visitUnqualifiedName(UnqualifiedNameAST *node);
+ virtual void visitTemplateArgument(TemplateArgumentAST *node);
+
+ void internal_run(AST *node);
+
+private:
+ ParseSession* m_session;
+ TypeSpecifierAST* m_typeSpecifier;
+ KDevelop::QualifiedIdentifier m_base;
+ KDevelop::Identifier m_currentIdentifier;
+ KDevelop::QualifiedIdentifier _M_name;
+};
+
+//Extracts a type-identifier from a template argument
+KDevelop::TypeIdentifier KDEVCPPPARSER_EXPORT typeIdentifierFromTemplateArgument(ParseSession* session, TemplateArgumentAST *node);
+uint KDEVCPPPARSER_EXPORT parseConstVolatile(ParseSession* session, const ListNode<std::size_t> *cv);
+
+#endif // NAME_COMPILER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parsesession.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parsesession.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/parsesession.h (revision 1522570)
@@ -0,0 +1,91 @@
+/* This file is part of KDevelop
+ Copyright 2006 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef PARSESESSION_H
+#define PARSESESSION_H
+
+#include <cstdlib>
+
+#include <QtCore/QString>
+#include <QtCore/QByteArray>
+
+#include <language/editor/simplecursor.h>
+
+#include <cppparserexport.h>
+#include <ksharedptr.h>
+#include <kurl.h>
+#include "rpp/anchor.h"
+
+#include <language/duchain/indexedstring.h>
+
+namespace Cpp {
+ class EnvironmentFile;
+}
+
+class pool;
+class TokenStream;
+class Token;
+
+typedef QVector<unsigned int> PreprocessedContents;
+
+namespace rpp { class MacroBlock; class LocationTable; }
+
+/// Contains everything needed to keep an AST useful once the rest of the parser
+/// has gone away.
+class KDEVCPPPARSER_EXPORT ParseSession
+{
+public:
+ ///@todo Make stringUnifier unnecessary by moving the string-repository into the parser
+ ParseSession();
+ ~ParseSession();
+
+ /**
+ * Return the position of the preprocessed source \a offset in the original source
+ * If the "collapsed" member of the returned anchor is true, the position is within a collapsed range.
+ @param collapseIfMacroExpansion @see LocationTable::positionForOffset
+ * \note the return line starts from 0, not 1.
+ */
+ rpp::Anchor positionAt(std::size_t offset, bool collapseIfMacroExpansion = false) const;
+
+ QPair<rpp::Anchor, uint> positionAndSpaceAt(std::size_t offset, bool collapseIfMacroExpansion = false) const;
+
+ ///The contents must already be tokenized. Either by the preprocessor, or by tokenizeFromByteArray(..)
+ void setContents(const PreprocessedContents& contents, rpp::LocationTable* locationTable);
+
+ /// Unweildy name, but we want to be clear here, if there is already a location table, this would be the wrong setup function to call
+ void setContentsAndGenerateLocationTable(const PreprocessedContents& contents);
+
+ void setUrl(const KDevelop::IndexedString& url); ///@todo change to IndexedString
+ const KDevelop::IndexedString& url() const;
+
+ uint *contents();
+ const uint *contents() const;
+ const PreprocessedContents& contentsVector() const;
+ std::size_t size() const;
+ pool* mempool;
+ TokenStream* token_stream;
+
+ rpp::MacroBlock* macros;
+ KDevelop::IndexedString m_url; //Should contain the url from which the content was extracted, can also be empty.
+
+private:
+ PreprocessedContents m_contents;
+ rpp::LocationTable* m_locationTable;
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/lexer.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/lexer.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/lexer.h (revision 1522570)
@@ -0,0 +1,307 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef LEXER_H
+#define LEXER_H
+
+#include "symbol.h"
+#include <cppparserexport.h>
+#include <QtCore/QString>
+#include <cstdlib>
+#include <language/duchain/indexedstring.h>
+
+#include <language/interfaces/iproblem.h>
+
+struct NameSymbol;
+class Lexer;
+class Control;
+class ParseSession;
+
+typedef void (Lexer::*scan_fun_ptr)();
+
+/**Token.*/
+class KDEVCPPPARSER_EXPORT Token
+{
+public:
+ ///kind of the token @see TOKEN_KIND enum reference.
+ int kind;
+ ///position in the preprocessed buffer
+ std::size_t position;
+ ///size of the token in the preprocessed buffer. Do not confuse this with symbolLength.
+ std::size_t size;
+ ///pointer to the parse session.
+ const ParseSession* session;
+
+ //Symbol associated to the token. This only works if this is a simple symbol
+ //only consisting of one identifier(not comments), does not work for operators like "->" or numbers like "50"
+ KDevelop::IndexedString symbol() const;
+
+ //This always works, but is expensive
+ QString symbolString() const;
+
+ uint symbolLength() const;
+
+ ///@todo adymo: find out what @p right_brace is
+ union
+ {
+ //const NameSymbol *symbol;
+ std::size_t right_brace;
+ } extra;
+};
+
+/**Stream of tokens found by lexer.
+Internally works like an array of @ref Token continuosly allocated.
+All tokens are destructed when this stream is deleted.
+
+The stream has a "cursor" which is simply an integer which defines
+the offset (index) of the token currently "observed" from the beginning of
+the stream.*/
+class TokenStream
+{
+private:
+ TokenStream(const TokenStream &);
+ void operator = (const TokenStream &);
+
+public:
+ /**Creates a token stream with the default size of 1024 tokens.*/
+ inline TokenStream(std::size_t size = 1024)
+ : tokens(0),
+ index(0),
+ token_count(0)
+ {
+ resize(size);
+ }
+
+ inline ~TokenStream()
+ { ::free(tokens); }
+
+ /**@return the size of the token stream.*/
+ inline std::size_t size() const
+ { return token_count; }
+
+ /**@return the "cursor" - the offset (index) of the token
+ currently "observed" from the beginning of the stream.*/
+ inline std::size_t cursor() const
+ { return index; }
+
+ /**Sets the cursor to the position @p i.*/
+ inline void rewind(int i)
+ { index = i; }
+
+ /**Resizes the token stream.*/
+ void resize(std::size_t size)
+ {
+ Q_ASSERT(size > 0);
+ tokens = (Token*) ::realloc(tokens, sizeof(Token) * size);
+ token_count = size;
+ }
+
+ /**Updates the cursor position to point to the next token and returns
+ the cursor.*/
+ inline std::size_t nextToken()
+ { return index++; }
+
+ /**@return the kind of the next (LA) token in the stream.*/
+ inline int lookAhead(std::size_t i = 0) const
+ { return tokens[index + i].kind; }
+
+ /**@return the kind of the current token in the stream.*/
+ inline int kind(std::size_t i) const
+ { return tokens[i].kind; }
+
+ /**@return the position of the current token in the c++ source buffer.*/
+ inline std::size_t position(std::size_t i) const
+ { return tokens[i].position; }
+
+ /**@return the name symbol of the current token.*/
+ //inline const NameSymbol *symbol(std::size_t i) const
+ //{ return tokens[i].extra.symbol; }
+
+ /**@return the position of the matching right brace in the
+ c++ source buffer.
+ @todo this doesn't seem to work as the lexer does not provide this
+ information at the moment.*/
+ inline std::size_t matchingBrace(std::size_t i) const
+ { return tokens[i].extra.right_brace; }
+
+ /**@return the token at position @p index.*/
+ inline Token &operator[](int index)
+ { Q_ASSERT(index >= 0 && index < (int)token_count); return tokens[index]; }
+
+ /**@return the token at position @p index.*/
+ inline const Token &token(int index) const
+ { return tokens[index]; }
+
+private:
+ Token *tokens;
+ std::size_t index;
+ std::size_t token_count;
+
+private:
+ friend class Lexer;
+};
+
+/**C++ Lexer.*/
+class Lexer
+{
+public:
+ /**
+ * Constructor.
+ *
+ * \param token_stream Provides a stream of tokens to the lexer.
+ * \param location_table a table which will be filled with non-preprocessed line -> offset values
+ * \param line_table a table which will be filled with (non-preproccessed line which contains a preprocessor line) -> offset values
+ */
+ Lexer(Control *control);
+
+ /**Finds tokens in the @p contents buffer and fills the @ref token_stream.*/
+ void tokenize(ParseSession* session);
+
+ ParseSession* session;
+
+private:
+ void skipComment();
+ /**Fills the scan table with method pointers.*/
+ void initialize_scan_table();
+ void scan_newline();
+ void scan_white_spaces();
+ void scan_identifier_or_keyword();
+ void scan_identifier_or_literal();
+ void scan_int_constant();
+ void scan_char_constant();
+ void scan_string_constant();
+ void scan_invalid_input();
+ void scan_preprocessor();
+
+ // keywords
+ void scanKeyword0();
+ void scanKeyword2();
+ void scanKeyword3();
+ void scanKeyword4();
+ void scanKeyword5();
+ void scanKeyword6();
+ void scanKeyword7();
+ void scanKeyword8();
+ void scanKeyword9();
+ void scanKeyword10();
+ void scanKeyword11();
+ void scanKeyword12();
+ void scanKeyword13();
+ void scanKeyword14();
+ void scanKeyword16();
+
+ // operators
+ void scan_not();
+ void scan_remainder();
+ void scan_and();
+ void scan_left_paren();
+ void scan_right_paren();
+ void scan_star();
+ void scan_plus();
+ void scan_comma();
+ void scan_minus();
+ void scan_dot();
+ void scan_divide();
+ void scan_colon();
+ void scan_semicolon();
+ void scan_less();
+ void scan_equal();
+ void scan_greater();
+ void scan_question();
+ void scan_left_bracket();
+ void scan_right_bracket();
+ void scan_xor();
+ void scan_left_brace();
+ void scan_or();
+ void scan_right_brace();
+ void scan_tilde();
+ void scan_EOF();
+
+ KDevelop::Problem createProblem() const;
+
+private:
+ Control *control;
+
+ struct SpecialCursor {
+ bool operator==(uint index) const {
+ return *current == index;
+ }
+ bool operator==(char character) const {
+ return *current == (character | 0xffff0000);
+ }
+ bool isChar() const {
+ return ((*current) & 0xffff0000) == 0xffff0000;
+ }
+ inline char operator*() const {
+ if(isChar())
+ return (char)*current;
+ else
+ return '_'; //Return a valid character, because the identifiers created by the preprocessor are alpha-numerical
+ }
+ void operator++() {
+ ++current;
+ }
+ void operator+=(int offset) {
+ current += offset;
+ }
+ bool operator !=(const SpecialCursor& rhs) const {
+ return current != rhs.current;
+ }
+ bool operator !=(const uint* rhs) const {
+ return current != rhs;
+ }
+ void operator--() {
+ --current;
+ }
+ bool operator<(const uint* end) const {
+ return current < end;
+ }
+
+ int operator -(const SpecialCursor& rhs) const {
+ return (((char*)current) - ((char*)rhs.current)) / sizeof(uint);
+ }
+
+ uint offsetIn(const uint* base) const {
+ return ((char*)current - (char*)base) / sizeof(uint);
+ }
+
+ SpecialCursor operator +(int offset) {
+ SpecialCursor ret(*this);
+ ret.current += offset;
+ return ret;
+ }
+
+ uint* current;
+ };
+
+ SpecialCursor cursor;
+ const uint* endCursor;
+ std::size_t index;
+
+ bool m_leaveSize; //Marks the current token that its size should not be automatically set
+ bool m_canMergeComment; //Whether we may append new comments to the last encountered one
+ bool m_firstInLine; //Whether the next token is the first one in a line
+
+ ///scan table contains pointers to the methods to scan for various token types
+ static scan_fun_ptr s_scan_table[];
+ static scan_fun_ptr s_scan_keyword_table[];
+ static bool s_initialized;
+};
+
+#endif // LEXER_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentparser.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentparser.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentparser.h (revision 1522570)
@@ -0,0 +1,84 @@
+/*
+ Copyright (C) 2007 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef COMMENTPARSER_H
+#define COMMENTPARSER_H
+
+#include <QString>
+#include <set>
+
+class ParseSession;
+
+class Comment {
+ public:
+ explicit Comment( size_t token = 0, int line = -1 );
+
+ operator bool() const;
+
+ inline int line() const {
+ return m_line;
+ }
+
+ bool operator==( const Comment& comment ) const;
+
+ bool operator < ( const Comment& rhs ) const;
+
+ bool isSame ( const Comment& rhs ) const;
+
+ size_t token() const {
+ return m_token;
+ }
+ private:
+ int m_line;
+ size_t m_token;
+};
+
+
+class CommentStore {
+ private:
+ typedef std::set< Comment > CommentSet;
+ CommentSet m_comments;
+
+ public:
+
+ /**
+ * Returns & removes the first comment currently in the comment-store
+ * */
+ Comment takeFirstComment();
+
+ /**
+ * Returns the comment nearest to the line of "end"(inclusive), and returns & removes it
+ * */
+ Comment takeCommentInRange( int endLine, int startLine = 0 );
+
+ ///Returns and removes the comment in the given line
+ Comment takeComment( int line );
+
+ void addComment( Comment comment );
+
+ ///Does not delete the comment
+ Comment latestComment() const;
+
+ bool hasComment() const {
+ return !m_comments.empty();
+ }
+
+ void clear();
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/control.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/control.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/control.h (revision 1522570)
@@ -0,0 +1,52 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef CONTROL_H
+#define CONTROL_H
+
+#include "symbol.h"
+#include "memorypool.h"
+#include <language/interfaces/iproblem.h>
+#include <cppparserexport.h>
+
+#include <QtCore/QHash>
+
+struct Declarator;
+struct Type;
+
+/**Parser control information.
+Provides problem tracking, context(visibility)-aware symbol name tables,
+typedef table and other information about the parsing process.*/
+class KDEVCPPPARSER_EXPORT Control
+{
+public:
+ Control();
+ ~Control();
+
+ const QList<KDevelop::ProblemPointer>& problems() const;
+
+ /**Adds a problem to the list of problems.*/
+ void reportProblem(const KDevelop::ProblemPointer &problem);
+ void reportProblem(const KDevelop::Problem &problem);
+
+private:
+ QList<KDevelop::ProblemPointer> _M_problems;
+};
+
+#endif // CONTROL_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/listnode.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/listnode.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/listnode.h (revision 1522570)
@@ -0,0 +1,94 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef LISTNODE_H
+#define LISTNODE_H
+
+#include "memorypool.h"
+#include <kdebug.h>
+
+template <typename Tp>
+struct ListNode
+{
+ Tp element;
+ int index;
+ mutable const ListNode<Tp> *next;
+
+ static ListNode *create(const Tp &element, pool *p)
+ {
+ ListNode<Tp> *node = new (p->allocate(sizeof(ListNode))) ListNode();
+ node->element = element;
+ node->index = 0;
+ node->next = node;
+
+ return node;
+ }
+
+ static ListNode *create(const ListNode *n1, const Tp &element, pool *p)
+ {
+ ListNode<Tp> *n2 = ListNode::create(element, p);
+
+ n2->index = n1->index + 1;
+ n2->next = n1->next;
+ n1->next = n2;
+
+ return n2;
+ }
+
+ inline const ListNode<Tp> *at(int index) const
+ {
+ const ListNode<Tp> *node = this;
+ while (index != node->index)
+ node = node->next;
+
+ return node;
+ }
+
+ inline bool hasNext() const
+ { return ( next && index < next->index ); }
+
+ inline int count() const
+ { return 1 + toBack()->index; }
+
+ inline const ListNode<Tp> *toFront() const
+ { return toBack()->next; }
+
+ inline const ListNode<Tp> *toBack() const
+ {
+ const ListNode<Tp> *node = this;
+ while (node->hasNext())
+ node = node->next;
+
+ return node;
+ }
+};
+
+template <class Tp>
+inline const ListNode<Tp> *snoc(const ListNode<Tp> *list,
+ const Tp &element, pool *p)
+{
+
+ if (!list)
+ return ListNode<Tp>::create(element, p);
+
+ return ListNode<Tp>::create(list->toBack(), element, p);
+}
+
+#endif // FASTLIST_H
+
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h (revision 1522570)
@@ -0,0 +1,128 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef RXX_ALLOCATOR_H
+#define RXX_ALLOCATOR_H
+
+#include <cstddef>
+#include <cstdlib>
+#include <string.h>
+#include <memory>
+
+/**The allocator which uses fixed size blocks for allocation of its elements.
+Block size is currently 64k, allocated space is not reclaimed,
+if the size of the element being allocated extends the amount of free
+memory in the block then a new block is allocated.
+
+The allocator supports standard c++ library interface but does not
+make use of allocation hints.
+*/
+template <class _Tp> class rxx_allocator {
+public:
+ typedef _Tp value_type;
+ typedef _Tp* pointer;
+ typedef const _Tp* const_pointer;
+ typedef _Tp& reference;
+ typedef const _Tp& const_reference;
+ typedef std::size_t size_type;
+ typedef std::ptrdiff_t difference_type;
+
+ static const size_type max_block_count = size_type(-1);
+ static const size_type _S_block_size = 1 << 16; // 64K
+
+ rxx_allocator() {
+ init();
+ }
+
+ rxx_allocator(const rxx_allocator &/*__o*/) {
+ init();
+ }
+
+ ~rxx_allocator() {
+ for (size_type index = 0; index < _M_block_index + 1; ++index)
+ delete[] _M_storage[index];
+
+ ::free(_M_storage);
+ }
+
+ pointer address(reference __val) { return &__val; }
+ const_pointer address(const_reference __val) const { return &__val; }
+
+ /**Allocates @p __n elements continuosly in the pool. Warning! no
+ check is done to check if the size of those @p __n elements
+ fit into the block. You should assure you do not allocate more
+ than the size of a block.*/
+ pointer allocate(size_type __n, const void* = 0) {
+ const size_type bytes = __n * sizeof(_Tp);
+
+ if (_M_current_block == 0
+ || _S_block_size < _M_current_index + bytes)
+ {
+ ++_M_block_index;
+
+ _M_storage = reinterpret_cast<char**>
+ (::realloc(_M_storage, sizeof(char*) * (1 + _M_block_index)));
+
+ _M_current_block = _M_storage[_M_block_index] = reinterpret_cast<char*>
+ (new char[_S_block_size]);
+
+ ::memset(_M_current_block, 0, _S_block_size);
+ _M_current_index = 0;
+ }
+
+ pointer p = reinterpret_cast<pointer>
+ (_M_current_block + _M_current_index);
+
+ _M_current_index += bytes;
+
+ return p;
+ }
+
+ /**Deallocate does nothing in this implementation.*/
+ void deallocate(pointer /*__p*/, size_type /*__n*/) {}
+
+ size_type max_size() const { return size_type(-1) / sizeof(_Tp); }
+
+ void construct(pointer __p, const_reference __val) { new (__p) _Tp(__val); }
+ void destroy(pointer __p) { __p->~_Tp(); }
+
+ template <class _Tp1> struct rebind {
+ typedef rxx_allocator<_Tp1> other;
+ };
+
+private:
+
+ void init()
+ {
+ _M_block_index = max_block_count;
+ _M_current_index = 0;
+ _M_storage = 0;
+ _M_current_block = 0;
+ }
+
+ template <class _Tp1> rxx_allocator(const rxx_allocator<_Tp1> &__o) {}
+
+private:
+ size_type _M_block_index;
+ size_type _M_current_index;
+ char *_M_current_block;
+ char **_M_storage;
+};
+
+#endif // RXX_ALLOCATOR_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentformatter.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentformatter.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/commentformatter.h (revision 1522570)
@@ -0,0 +1,51 @@
+/*
+ Copyright (C) 2007 David Nolden <david.nolden.kdevelop@art-master.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef COMMENTFORMATTER_H
+#define COMMENTFORMATTER_H
+
+#include <QString>
+#include <cppparserexport.h>
+
+template<class Tp>
+class ListNode;
+
+/**
+ * This class cares about extracting the interesting information out of a comment.
+ * For example it removes all the stars at the beginning, and re-indents the text.
+ * */
+
+class ParseSession;
+
+class KDEVCPPPARSER_EXPORT CommentFormatter {
+ public:
+ static QString formatComment( const QString& comment );
+ ///Processes the comment represented by the given token-number within the parse-session's token-stream
+ static QString formatComment( size_t token, const ParseSession* session );
+
+ ///Processes the list of comments represented by the given token-number within the parse-session's token-stream
+ static QString formatComment( const ListNode<size_t>* node, const ParseSession* session );
+ private:
+ static inline bool isWhite( QChar c ) {
+ return c.isSpace();
+ }
+ static void rStrip( const QString& str, QString& from );
+ static void strip( const QString& str, QString& from );
+};
+
+#endif
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/ast.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/ast.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/include/ast.h (revision 1522570)
@@ -0,0 +1,917 @@
+/* This file is part of KDevelop
+ Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ 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.
+*/
+
+#ifndef AST_H
+#define AST_H
+
+#include "memorypool.h"
+#include "listnode.h"
+
+#define DECLARE_AST_NODE(k) \
+ enum { __node_kind = Kind_##k };
+
+class ParseSession;
+namespace KDevelop
+{
+class DUContext;
+}
+struct AccessSpecifierAST;
+struct AsmDefinitionAST;
+struct BaseClauseAST;
+struct BaseSpecifierAST;
+struct BinaryExpressionAST;
+struct CastExpressionAST;
+struct ClassMemberAccessAST;
+struct ClassSpecifierAST;
+struct CompoundStatementAST;
+struct ConditionAST;
+struct ConditionalExpressionAST;
+struct CppCastExpressionAST;
+struct CtorInitializerAST;
+struct DeclarationAST;
+struct DeclarationStatementAST;
+struct DeclaratorAST;
+struct DeleteExpressionAST;
+struct DoStatementAST;
+struct Elaborated;
+struct EnumSpecifierAST;
+struct EnumeratorAST;
+struct ExceptionSpecificationAST;
+struct ExpressionAST;
+struct ExpressionOrDeclarationStatementAST;
+struct ExpressionStatementAST;
+struct ForStatementAST;
+struct FunctionCallAST;
+struct FunctionDefinitionAST;
+struct IfStatementAST;
+struct IncrDecrExpressionAST;
+struct InitDeclaratorAST;
+struct InitializerAST;
+struct InitializerClauseAST;
+struct LabeledStatementAST;
+struct LinkageBodyAST;
+struct LinkageSpecificationAST;
+struct MemInitializerAST;
+struct NameAST;
+struct NamespaceAST;
+struct NamespaceAliasDefinitionAST;
+struct NewDeclaratorAST;
+struct NewExpressionAST;
+struct NewInitializerAST;
+struct NewTypeIdAST;
+struct OperatorAST;
+struct OperatorFunctionIdAST;
+struct ParameterDeclarationAST;
+struct ParameterDeclarationClauseAST;
+struct PostfixExpressionAST;
+struct PrimaryExpressionAST;
+struct PtrOperatorAST;
+struct PtrToMemberAST;
+struct ReturnStatementAST;
+struct SimpleDeclarationAST;
+struct SimpleTypeSpecifierAST;
+struct SizeofExpressionAST;
+struct StatementAST;
+struct StringLiteralAST;
+struct SubscriptExpressionAST;
+struct SwitchStatementAST;
+struct TemplateArgumentAST;
+struct TemplateDeclarationAST;
+struct TemplateParameterAST;
+struct ThrowExpressionAST;
+struct TranslationUnitAST;
+struct TryBlockStatementAST;
+struct CatchStatementAST;
+struct TypeIdAST;
+struct TypeIdentificationAST;
+struct TypeParameterAST;
+struct TypeSpecifierAST;
+struct TypedefAST;
+struct UnaryExpressionAST;
+struct UnqualifiedNameAST;
+struct UsingAST;
+struct UsingDirectiveAST;
+struct WhileStatementAST;
+struct WinDeclSpecAST;
+
+struct AST
+{///@warning When adding new nodes here, also modify the names[] array in dumptree.cpp
+ enum NODE_KIND
+ {
+ Kind_UNKNOWN = 0,
+
+ Kind_AccessSpecifier, // 1
+ Kind_AsmDefinition, // 2
+ Kind_BaseClause, // 3
+ Kind_BaseSpecifier, // 4
+ Kind_BinaryExpression, // 5
+ Kind_CastExpression, // 6
+ Kind_ClassMemberAccess, // 7
+ Kind_ClassSpecifier, // 8
+ Kind_CompoundStatement, // 9
+ Kind_Condition, // 10
+ Kind_ConditionalExpression, // 11
+ Kind_CppCastExpression, // 12
+ Kind_CtorInitializer, // 13
+ Kind_DeclarationStatement, // 14
+ Kind_Declarator, // 15
+ Kind_DeleteExpression, // 16
+ Kind_DoStatement, // 17
+ Kind_ElaboratedTypeSpecifier, // 18
+ Kind_EnumSpecifier, // 19
+ Kind_Enumerator, // 20
+ Kind_ExceptionSpecification, // 21
+ Kind_ExpressionOrDeclarationStatement, // 22
+ Kind_ExpressionStatement, // 23
+ Kind_ForStatement, // 24
+ Kind_FunctionCall, // 25
+ Kind_FunctionDefinition, // 26
+ Kind_IfStatement, // 27
+ Kind_IncrDecrExpression, // 28
+ Kind_InitDeclarator, // 29
+ Kind_Initializer, // 30
+ Kind_InitializerClause, // 31
+ Kind_LabeledStatement, // 32
+ Kind_LinkageBody, // 33
+ Kind_LinkageSpecification, // 34
+ Kind_MemInitializer, // 35
+ Kind_Name, // 36
+ Kind_Namespace, // 37
+ Kind_NamespaceAliasDefinition, // 38
+ Kind_NewDeclarator, // 39
+ Kind_NewExpression, // 40
+ Kind_NewInitializer, // 41
+ Kind_NewTypeId, // 42
+ Kind_Operator, // 43
+ Kind_OperatorFunctionId, // 44
+ Kind_ParameterDeclaration, // 45
+ Kind_ParameterDeclarationClause, // 46
+ Kind_PostfixExpression, // 47
+ Kind_PrimaryExpression, // 48
+ Kind_PtrOperator, // 49
+ Kind_PtrToMember, // 50
+ Kind_ReturnStatement, // 51
+ Kind_SimpleDeclaration, // 52
+ Kind_SimpleTypeSpecifier, // 53
+ Kind_SizeofExpression, // 54
+ Kind_StringLiteral, // 55
+ Kind_SubscriptExpression, // 56
+ Kind_SwitchStatement, // 57
+ Kind_TemplateArgument, // 58
+ Kind_TemplateDeclaration, // 59
+ Kind_TemplateParameter, // 60
+ Kind_ThrowExpression, // 61
+ Kind_TranslationUnit, // 62
+ Kind_TryBlockStatement, // 63
+ Kind_CatchStatement, // 64
+ Kind_TypeId, // 65
+ Kind_TypeIdentification, // 66
+ Kind_TypeParameter, // 67
+ Kind_Typedef, // 68
+ Kind_UnaryExpression, // 69
+ Kind_UnqualifiedName, // 70
+ Kind_Using, // 71
+ Kind_UsingDirective, // 72
+ Kind_WhileStatement, // 73
+ Kind_WinDeclSpec, // 74
+ Kind_Comment, // 75
+ Kind_JumpStatement, // 76
+ NODE_KIND_COUNT
+ };
+
+ int kind;
+
+ std::size_t start_token;
+ std::size_t end_token;
+
+ /** Context opened by this AST
+ *This is usually not filled for all AST's, only for those that open a new context
+ */
+ KDevelop::DUContext* ducontext;
+};
+
+struct CommentAST {
+ const ListNode<std::size_t> *comments; //A list of comment-tokens
+};
+
+struct TypeSpecifierAST: public AST
+{
+ const ListNode<std::size_t> *cv; // const or volatile tokens
+};
+
+struct StatementAST: public AST
+{
+};
+
+struct ExpressionAST: public AST
+{
+};
+
+struct DeclarationAST: public AST, public CommentAST
+{
+};
+
+struct AccessSpecifierAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(AccessSpecifier)
+
+ const ListNode<std::size_t> *specs;
+};
+
+struct AsmDefinitionAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(AsmDefinition)
+
+ const ListNode<std::size_t> *cv;
+};
+
+struct BaseClauseAST: public AST // ### kill me
+{
+ DECLARE_AST_NODE(BaseClause)
+
+ const ListNode<BaseSpecifierAST*> *base_specifiers;
+};
+
+struct BaseSpecifierAST: public AST
+{
+ DECLARE_AST_NODE(BaseSpecifier)
+
+ std::size_t virt;
+ std::size_t access_specifier;
+ NameAST *name;
+};
+
+struct BinaryExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(BinaryExpression)
+
+ std::size_t op; //Index of the token that describes the operator
+ ExpressionAST *left_expression;
+ ExpressionAST *right_expression;
+};
+
+struct CastExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(CastExpression)
+
+ TypeIdAST *type_id;
+ ExpressionAST *expression;
+};
+
+struct ClassMemberAccessAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(ClassMemberAccess)
+
+ std::size_t op; //Index of the token that describes the operator
+ NameAST *name;
+};
+
+struct ClassSpecifierAST: public TypeSpecifierAST
+{
+ DECLARE_AST_NODE(ClassSpecifier)
+
+ WinDeclSpecAST *win_decl_specifiers;
+ std::size_t class_key;
+ NameAST *name;
+ BaseClauseAST *base_clause;
+ const ListNode<DeclarationAST*> *member_specs;
+};
+
+struct CompoundStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(CompoundStatement)
+
+ const ListNode<StatementAST*> *statements;
+};
+
+struct ConditionAST: public AST
+{
+ DECLARE_AST_NODE(Condition)
+
+ TypeSpecifierAST *type_specifier;
+ DeclaratorAST *declarator;
+ ExpressionAST *expression;
+};
+
+struct ConditionalExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(ConditionalExpression)
+
+ ExpressionAST *condition;
+ ExpressionAST *left_expression;
+ ExpressionAST *right_expression;
+};
+
+/**
+ * type_id is the type that should be casted to
+ * expression is the expression casted from
+ * sub_expressions is a list of post-fix expressions, see PostfixExpressionAST
+ */
+struct CppCastExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(CppCastExpression)
+
+ std::size_t op; //Index of the token that describes the operator
+ TypeIdAST *type_id;
+ ExpressionAST *expression;
+ const ListNode<ExpressionAST*> *sub_expressions;
+};
+
+struct CtorInitializerAST: public AST
+{
+ DECLARE_AST_NODE(CtorInitializer)
+
+ std::size_t colon;
+ const ListNode<MemInitializerAST*> *member_initializers;
+};
+
+struct DeclarationStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(DeclarationStatement)
+
+ DeclarationAST *declaration;
+};
+
+struct DeclaratorAST: public AST
+{
+ DECLARE_AST_NODE(Declarator)
+
+ const ListNode<PtrOperatorAST*> *ptr_ops;
+ DeclaratorAST *sub_declarator;
+ NameAST *id;
+ ExpressionAST *bit_expression;
+ const ListNode<ExpressionAST*> *array_dimensions;
+ ParameterDeclarationClauseAST *parameter_declaration_clause;
+ const ListNode<std::size_t> *fun_cv;
+ ExceptionSpecificationAST *exception_spec;
+};
+
+struct DeleteExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(DeleteExpression)
+
+ std::size_t scope_token;
+ std::size_t delete_token;
+ std::size_t lbracket_token;
+ std::size_t rbracket_token;
+ ExpressionAST *expression;
+};
+
+struct DoStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(DoStatement)
+
+ StatementAST *statement;
+ ExpressionAST *expression;
+};
+
+struct ElaboratedTypeSpecifierAST: public TypeSpecifierAST
+{
+ DECLARE_AST_NODE(ElaboratedTypeSpecifier)
+
+ std::size_t type;
+ NameAST *name;
+};
+
+struct EnumSpecifierAST: public TypeSpecifierAST
+{
+ DECLARE_AST_NODE(EnumSpecifier)
+
+ NameAST *name;
+ const ListNode<EnumeratorAST*> *enumerators;
+};
+
+struct EnumeratorAST: public AST, public CommentAST
+{
+ DECLARE_AST_NODE(Enumerator)
+
+ std::size_t id;
+ ExpressionAST *expression;
+};
+
+struct ExceptionSpecificationAST: public AST
+{
+ DECLARE_AST_NODE(ExceptionSpecification)
+
+ std::size_t ellipsis;
+ const ListNode<TypeIdAST*> *type_ids;
+};
+
+struct ExpressionOrDeclarationStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(ExpressionOrDeclarationStatement)
+
+ StatementAST *expression;
+ StatementAST *declaration;
+
+ // This was not originally part of the AST - added by the context visitor
+ bool expressionChosen;
+};
+
+///An expression terminated by a semicolon or similar
+struct ExpressionStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(ExpressionStatement)
+
+ ExpressionAST *expression;
+};
+
+struct FunctionCallAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(FunctionCall)
+
+ ExpressionAST *arguments;
+};
+
+struct FunctionDefinitionAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(FunctionDefinition)
+
+ const ListNode<std::size_t> *storage_specifiers;
+ const ListNode<std::size_t> *function_specifiers;
+ TypeSpecifierAST *type_specifier;
+ InitDeclaratorAST *init_declarator;
+ StatementAST *function_body;
+ WinDeclSpecAST *win_decl_specifiers;
+ CtorInitializerAST *constructor_initializers;
+};
+
+struct ForStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(ForStatement)
+
+ StatementAST *init_statement;
+ ConditionAST *condition;
+ ExpressionAST *expression;
+ StatementAST *statement;
+};
+
+struct IfStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(IfStatement)
+
+ ConditionAST *condition;
+ StatementAST *statement;
+ StatementAST *else_statement;
+};
+
+struct IncrDecrExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(IncrDecrExpression)
+
+ std::size_t op; //Index of the token that describes the operator
+};
+
+struct InitDeclaratorAST: public AST
+{
+ DECLARE_AST_NODE(InitDeclarator)
+
+ DeclaratorAST *declarator;
+ InitializerAST *initializer;
+};
+
+struct InitializerAST: public AST
+{
+ DECLARE_AST_NODE(Initializer)
+
+ InitializerClauseAST *initializer_clause;
+ ExpressionAST *expression;
+};
+
+struct InitializerClauseAST: public AST
+{
+ DECLARE_AST_NODE(InitializerClause)
+
+ // either 'expression' or 'initializer_list' or neither are used.
+ // neither are used when the clause represents the empty initializer "{}"
+
+ // assignment expression
+ ExpressionAST *expression;
+ const ListNode<InitializerClauseAST*> *initializer_list;
+};
+
+struct LabeledStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(LabeledStatement)
+
+ //The constant label expression
+ ExpressionAST *expression;
+ StatementAST* statement;
+};
+
+struct LinkageBodyAST: public AST
+{
+ DECLARE_AST_NODE(LinkageBody)
+
+ const ListNode<DeclarationAST*> *declarations;
+};
+
+struct LinkageSpecificationAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(LinkageSpecification)
+
+ std::size_t extern_type;
+ LinkageBodyAST *linkage_body;
+ DeclarationAST *declaration;
+};
+
+struct MemInitializerAST: public AST
+{
+ DECLARE_AST_NODE(MemInitializer)
+
+ NameAST *initializer_id;
+ ExpressionAST *expression;
+};
+
+struct NameAST: public AST
+{
+ DECLARE_AST_NODE(Name)
+
+ bool global;
+ const ListNode<UnqualifiedNameAST*> *qualified_names;
+ UnqualifiedNameAST *unqualified_name;
+};
+
+struct NamespaceAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(Namespace)
+
+ std::size_t namespace_name;
+ LinkageBodyAST *linkage_body;
+};
+
+struct NamespaceAliasDefinitionAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(NamespaceAliasDefinition)
+
+ std::size_t namespace_name;
+ NameAST *alias_name;
+};
+
+struct NewDeclaratorAST: public AST
+{
+ DECLARE_AST_NODE(NewDeclarator)
+
+ PtrOperatorAST *ptr_op;
+ NewDeclaratorAST *sub_declarator;
+ const ListNode<ExpressionAST*> *expressions;
+};
+
+struct NewExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(NewExpression)
+
+ std::size_t scope_token;
+ std::size_t new_token;
+ ExpressionAST *expression;
+ TypeIdAST *type_id;
+ NewTypeIdAST *new_type_id;
+ NewInitializerAST *new_initializer;
+};
+
+struct NewInitializerAST: public AST
+{
+ DECLARE_AST_NODE(NewInitializer)
+
+ ExpressionAST *expression;
+};
+
+struct NewTypeIdAST: public AST
+{
+ DECLARE_AST_NODE(NewTypeId)
+
+ TypeSpecifierAST *type_specifier;
+ NewInitializerAST *new_initializer;
+ NewDeclaratorAST *new_declarator;
+};
+
+struct OperatorAST: public AST
+{
+ DECLARE_AST_NODE(Operator)
+
+ std::size_t op; //Index of the token that describes the operator
+ std::size_t open;
+ std::size_t close;
+};
+
+struct OperatorFunctionIdAST: public AST
+{
+ DECLARE_AST_NODE(OperatorFunctionId)
+
+ OperatorAST *op;
+ TypeSpecifierAST *type_specifier;
+ const ListNode<PtrOperatorAST*> *ptr_ops;
+};
+
+struct ParameterDeclarationAST: public AST
+{
+ DECLARE_AST_NODE(ParameterDeclaration)
+
+ TypeSpecifierAST *type_specifier;
+ DeclaratorAST *declarator;
+ ExpressionAST *expression;
+};
+
+struct ParameterDeclarationClauseAST: public AST
+{
+ DECLARE_AST_NODE(ParameterDeclarationClause)
+
+ const ListNode<ParameterDeclarationAST*> *parameter_declarations;
+ std::size_t ellipsis;
+};
+
+/**
+ * A post-fix expression is an expression that consists of one primary expression and multiple sub-expressions that are evaluated from
+ * left to right, each sub-expression based on the previous expression.
+ *
+ *
+ * Examples:
+ * "a->b" : "a" is the primary expression, "->b" is a sub-expression
+ * "a->b(5,3)" : "a" is the primary expression, "->b" is a sub-expression, and "(5,3)" is a sub-expression
+ **/
+struct PostfixExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(PostfixExpression)
+
+ TypeSpecifierAST *type_specifier;
+ ExpressionAST *expression;
+ const ListNode<ExpressionAST*> *sub_expressions;
+};
+
+struct PrimaryExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(PrimaryExpression)
+
+ StringLiteralAST *literal;
+ std::size_t token;
+ StatementAST *expression_statement;
+ ExpressionAST *sub_expression;
+ NameAST *name;
+};
+
+struct PtrOperatorAST: public AST
+{
+ DECLARE_AST_NODE(PtrOperator)
+
+ const ListNode<std::size_t> *cv;
+ std::size_t op; //Index of the token that describes the operator. Is zero when mem_ptr is non-zero.
+ PtrToMemberAST *mem_ptr;
+};
+
+struct PtrToMemberAST: public AST
+{
+ DECLARE_AST_NODE(PtrToMember)
+};
+
+struct JumpStatementAST : public StatementAST
+{
+ DECLARE_AST_NODE(JumpStatement)
+
+ // index of operator token which describes the jump, one of
+ // 'break', 'continue' or 'goto. Return statements are handled by
+ // ReturnStatementAST
+ std::size_t op;
+ // identifier for 'goto' statements
+ std::size_t identifier;
+};
+
+struct ReturnStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(ReturnStatement)
+
+ ExpressionAST *expression;
+};
+
+struct SimpleDeclarationAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(SimpleDeclaration)
+
+ const ListNode<std::size_t> *storage_specifiers;
+ const ListNode<std::size_t> *function_specifiers;
+ TypeSpecifierAST *type_specifier;
+ const ListNode<InitDeclaratorAST*> *init_declarators;
+ WinDeclSpecAST *win_decl_specifiers;
+};
+
+struct SimpleTypeSpecifierAST: public TypeSpecifierAST
+{
+ DECLARE_AST_NODE(SimpleTypeSpecifier)
+
+ const ListNode<std::size_t> *integrals;
+ std::size_t type_of;
+ TypeIdAST *type_id;
+ ExpressionAST *expression;
+ NameAST *name;
+};
+
+struct SizeofExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(SizeofExpression)
+
+ std::size_t sizeof_token;
+ TypeIdAST *type_id;
+ ExpressionAST *expression;
+};
+
+struct StringLiteralAST: public AST
+{
+ DECLARE_AST_NODE(StringLiteral)
+
+ const ListNode<std::size_t> *literals;
+};
+
+/// operator []
+struct SubscriptExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(SubscriptExpression)
+
+ ExpressionAST *subscript;
+};
+
+struct SwitchStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(SwitchStatement)
+
+ ConditionAST *condition;
+ StatementAST *statement;
+};
+
+struct TemplateArgumentAST: public AST
+{
+ DECLARE_AST_NODE(TemplateArgument)
+
+ TypeIdAST *type_id;
+ ExpressionAST *expression;
+};
+
+struct TemplateDeclarationAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(TemplateDeclaration)
+
+ std::size_t exported;
+ const ListNode<TemplateParameterAST*> *template_parameters;
+ DeclarationAST* declaration;
+};
+
+struct TemplateParameterAST: public AST
+{
+ DECLARE_AST_NODE(TemplateParameter)
+
+ TypeParameterAST *type_parameter;
+ ParameterDeclarationAST *parameter_declaration; //Default-parameter
+};
+
+struct ThrowExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(ThrowExpression)
+
+ std::size_t throw_token;
+ ExpressionAST *expression;
+};
+
+struct TranslationUnitAST: public AST, public CommentAST
+{
+ DECLARE_AST_NODE(TranslationUnit)
+
+ const ListNode<DeclarationAST*> *declarations;
+
+ // Note: non AST related, saves parsing session...
+ ParseSession* session;
+};
+
+struct TryBlockStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(TryBlockStatement)
+
+ StatementAST* try_block;
+ const ListNode<CatchStatementAST*> *catch_blocks;
+};
+
+struct CatchStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(CatchStatement)
+
+ ConditionAST* condition;
+ StatementAST* statement;
+};
+
+struct TypeIdAST: public AST
+{
+ DECLARE_AST_NODE(TypeId)
+
+ TypeSpecifierAST *type_specifier;
+ DeclaratorAST *declarator;
+};
+
+///"typename"
+struct TypeIdentificationAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(TypeIdentification)
+
+ std::size_t typename_token;
+ NameAST *name;
+ ExpressionAST *expression;
+};
+
+struct TypeParameterAST: public AST
+{
+ DECLARE_AST_NODE(TypeParameter)
+
+ std::size_t type;
+ NameAST *name;
+ TypeIdAST *type_id;
+ const ListNode<TemplateParameterAST*> *template_parameters;
+ NameAST *template_name;
+};
+
+struct TypedefAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(Typedef)
+
+ TypeSpecifierAST *type_specifier;
+ const ListNode<InitDeclaratorAST*> *init_declarators;
+};
+
+struct UnaryExpressionAST: public ExpressionAST
+{
+ DECLARE_AST_NODE(UnaryExpression)
+
+ std::size_t op; //Index of the token that describes the operator
+ ExpressionAST *expression;
+};
+
+struct UnqualifiedNameAST: public AST
+{
+ DECLARE_AST_NODE(UnqualifiedName)
+
+ std::size_t tilde;
+ std::size_t id;
+ OperatorFunctionIdAST *operator_id;
+ const ListNode<TemplateArgumentAST*> *template_arguments;
+};
+
+struct UsingAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(Using)
+
+ std::size_t type_name;
+ NameAST *name;
+};
+
+struct UsingDirectiveAST: public DeclarationAST
+{
+ DECLARE_AST_NODE(UsingDirective)
+
+ NameAST *name;
+};
+
+struct WhileStatementAST: public StatementAST
+{
+ DECLARE_AST_NODE(WhileStatement)
+
+ ConditionAST *condition;
+ StatementAST *statement;
+};
+
+struct WinDeclSpecAST: public AST
+{
+ DECLARE_AST_NODE(WinDeclSpec)
+
+ std::size_t specifier;
+ std::size_t modifier;
+};
+
+template <class _Tp>
+_Tp *CreateNode(pool *memory_pool)
+{
+ _Tp *node = reinterpret_cast<_Tp*>(memory_pool->allocate(sizeof(_Tp)));
+ node->kind = _Tp::__node_kind;
+ return node;
+}
+
+template <class _Tp>
+_Tp ast_cast(AST *item)
+{
+ if (item && static_cast<_Tp>(0)->__node_kind == item->kind)
+ return static_cast<_Tp>(item);
+
+ return 0;
+}
+
+#endif // AST_H
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,9 @@
+project(McCabe)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${McCabe_SOURCE_DIR}/cmake/)
+cmake_minimum_required(VERSION 2.6)
+find_package(Qt4 REQUIRED)
+find_package(KDE4 REQUIRED)
+find_package(KDevPlatform REQUIRED)
+
+add_subdirectory(src)
+add_subdirectory(tests)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,27 @@
+
+set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
+include_directories(
+ ${McCabe_SOURCE_DIR}/include
+ ${McCabe_SOURCE_DIR}/src
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${KDE4_INCLUDE_DIR}
+ ${QT_INCLUDES}
+ ${KDEVPLATFORM_INCLUDE_DIR})
+
+macro(mccabe_add_test test_EXEC)
+ set(test_SRCS ${ARGN})
+ qt4_automoc( ${test_SRCS} )
+ kde4_add_unit_test(mccabe-${test_EXEC} ${test_SRCS})
+ target_link_libraries(mccabe-${test_EXEC}
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTXML_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDEVPLATFORM_INTERFACES}
+ ${KDEVPLATFORM_LANGUAGE}
+ ${KDE4_LIB_DIR}/libkdev4cppparser.so
+ ${KDE4_LIB_DIR}/libkdev4cpprpp.so)
+endmacro(mccabe_add_test)
+
+mccabe_add_test(metricengine metricenginetest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
+mccabe_add_test(functionname functionnametest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
+mccabe_add_test(sourcelocation sourcelocationtest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h (revision 1522570)
@@ -0,0 +1,54 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef QTEST_SOURCELOCATIONTEST_H_INCLUDED
+#define QTEST_SOURCELOCATIONTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include "metrics.h"
+
+class MetricEngineFake;
+
+class SourceLocationTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void function_startOfDocument();
+ void function_middle();
+ void function_endOfDocument();
+ void function_multiple();
+ void function_whitespace();
+
+ void tdd_class_middle();
+ void tdd_function_class_mixed();
+
+private:
+ void assertMetricLineNumberEquals(int expectedLineNr, const McCabeMetric& metric);
+ QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
+
+ MetricEngineFake* m_engine;
+ McCabeMetric m_metric;
+};
+
+#endif // QTEST_SOURCELOCATIONTEST_H_INCLUDED
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp (revision 1522570)
@@ -0,0 +1,144 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "sourcelocationtest.h"
+#include <QtTest/QTest>
+
+#include "metricengine.h"
+#include <kurl.h>
+#include <kdebug.h>
+
+class MetricEngineFake : public MetricEngine
+{
+public:
+ QByteArray content;
+protected:
+ virtual QByteArray readAll(const KUrl& filename) {
+ Q_UNUSED(filename);
+ return content;
+ }
+};
+
+void SourceLocationTest::init()
+{
+ m_engine = new MetricEngineFake;
+ m_metric = McCabeMetric();
+}
+
+void SourceLocationTest::cleanup()
+{
+}
+
+// SUT stimulation helper
+QList<McCabeMetric> SourceLocationTest::computeMcCabeMetricFor(const QByteArray& source)
+{
+ m_engine->content = source;
+ MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
+ return mtr.mcCabeComplexity();
+}
+
+// custom assertion
+void SourceLocationTest::assertMetricLineNumberEquals(int expectedLineNr, const McCabeMetric& metric)
+{
+ QCOMPARE(metric.line(), expectedLineNr);
+}
+
+
+void SourceLocationTest::function_startOfDocument()
+{
+ QList<McCabeMetric> mtr = computeMcCabeMetricFor(
+ "void fun() {}\n"
+ "\n");
+ QCOMPARE(1, mtr.count());
+ assertMetricLineNumberEquals(1, mtr[0]);
+}
+
+void SourceLocationTest::function_middle()
+{
+ QList<McCabeMetric> mtr = computeMcCabeMetricFor(
+ "\n"
+ "void fun() {}\n"
+ "\n");
+ QCOMPARE(1, mtr.count());
+ assertMetricLineNumberEquals(2, mtr[0]);
+}
+
+void SourceLocationTest::function_endOfDocument()
+{
+ QList<McCabeMetric> mtr = computeMcCabeMetricFor(
+ "\n"
+ "void fun() {}");
+ QCOMPARE(1, mtr.count());
+ assertMetricLineNumberEquals(2, mtr[0]);
+}
+
+namespace
+{
+
+McCabeMetric retrieveMetricForFunction(const QString& functionName, QList<McCabeMetric>& metrics)
+{
+ foreach(const McCabeMetric& mtr, metrics) {
+ if (mtr.function() == functionName) {
+ kDebug() << mtr.function();
+ return mtr;
+ }
+ }
+ return McCabeMetric();
+}
+
+}
+
+void SourceLocationTest::function_multiple()
+{
+ QList<McCabeMetric> mtr = computeMcCabeMetricFor(
+ "void foo() {}\n"
+ "void bar() {}\n"
+ "void baz() {}\n");
+ QCOMPARE(3, mtr.count());
+ McCabeMetric fooMtr = retrieveMetricForFunction("foo()", mtr);
+ assertMetricLineNumberEquals(1, fooMtr);
+ McCabeMetric barMtr = retrieveMetricForFunction("bar()", mtr);
+ assertMetricLineNumberEquals(2, barMtr);
+ McCabeMetric bazMtr = retrieveMetricForFunction("baz()", mtr);
+ assertMetricLineNumberEquals(3, bazMtr);
+}
+
+void SourceLocationTest::function_whitespace()
+{
+ QList<McCabeMetric> mtr = computeMcCabeMetricFor(
+ "\n\n\n"
+ " void bar() {\n}\n");
+ QCOMPARE(1, mtr.count());
+ assertMetricLineNumberEquals(4, mtr[0]);
+}
+
+void SourceLocationTest::tdd_class_middle()
+{
+ QFAIL("No class metrics yet, can not test.");
+}
+
+void SourceLocationTest::tdd_function_class_mixed()
+{
+ QFAIL("No class metrics yet, can not test.");
+}
+
+QTEST_MAIN( SourceLocationTest )
+#include "sourcelocationtest.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp (revision 1522570)
@@ -0,0 +1,286 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "functionnametest.h"
+#include <QtTest/QTest>
+#include "metricengine.h"
+#include <kurl.h>
+
+class MetricEngineFake : public MetricEngine
+{
+public:
+ QByteArray content;
+protected:
+ virtual QByteArray readAll(const KUrl& filename) {
+ Q_UNUSED(filename);
+ return content;
+ }
+};
+
+void FunctionNameTest::init()
+{
+ m_engine = new MetricEngineFake;
+ m_metric = McCabeMetric();
+}
+
+void FunctionNameTest::cleanup()
+{
+ if (m_engine) delete m_engine;
+}
+
+// SUT stimulation helper
+QList<McCabeMetric> FunctionNameTest::computeMcCabeMetricFor(const QByteArray& source)
+{
+ m_engine->content = source;
+ MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
+ return mtr.mcCabeComplexity();
+}
+
+// custom assertion
+void FunctionNameTest::assertMetricFunctionEquals(const QString& function, const McCabeMetric& metric)
+{
+ QCOMPARE(metric.function(), function);
+}
+
+
+// command
+void FunctionNameTest::multipleFunctions_singlePath()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "void foo() {}\n"
+ "void bar() {}\n");
+
+ QCOMPARE(2, cm.count());
+ assertMetricFunctionEquals("foo()", cm[0]);
+ assertMetricFunctionEquals("bar()", cm[1]);
+}
+
+// command
+void FunctionNameTest::classMemberFunction_singlePath()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor("void Foo::foo() {}");
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("Foo::foo()", cm[0]);
+}
+
+// command
+void FunctionNameTest::nestedClassMemberFunction_singlePath()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor("void Foo::Bar::baz() {}");
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("Foo::Bar::baz()", cm[0]);
+}
+
+// command
+void FunctionNameTest::namespaceFunction_singlePath()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "namespace Foo {"
+ " void foo() {} "
+ " namespace Bar { "
+ " void bar() {} "
+ " }"
+ " void foo2() {} "
+ "}"
+ "void baz() {}");
+
+ QCOMPARE(4, cm.count());
+ assertMetricFunctionEquals("Foo::foo()", cm[0]);
+ assertMetricFunctionEquals("Foo::Bar::bar()", cm[1]);
+ assertMetricFunctionEquals("Foo::foo2()", cm[2]);
+ assertMetricFunctionEquals("baz()", cm[3]);
+}
+
+// command
+void FunctionNameTest::usingMemberFunction()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "using Foo::Bar; void Bar::baz() {}"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("Foo::Bar::baz()", cm[0]);
+}
+
+// command
+void FunctionNameTest::usingFreeStandingFunction()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "using Foo::bar; void bar() {}"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("Foo::bar()", cm[0]);
+}
+
+// command
+void FunctionNameTest::operatorFunction()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class A{}; int operator+(A a, A b) { return 0; }"
+ );
+
+ // just make sure it doesnt crash, the C++ parser seems to fail when
+ // trying to retrieve the function name for operator functions.
+
+ QCOMPARE(0, cm.count()); // should be fixed some day, for now be happy
+}
+
+// command
+void FunctionNameTest::anonymousNamespace()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "namespace { void bar() {} }"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("<anonymous>::bar()", cm[0]);
+}
+
+// command
+void FunctionNameTest::inlineClassMemberFunction()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class Foo { public: void foo() {} }; "
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("Foo::foo()", cm[0]);
+}
+
+// command
+void FunctionNameTest::nestedInlineClassMemberFunction()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class Foo { "
+ "public: "
+ " void foo() {} "
+ " class Bar { "
+ " public: void bar() {} "
+ " }; "
+ " void foo2() {} "
+ "}; "
+ "void baz() {}\n"
+ );
+
+ QCOMPARE(4, cm.count());
+ assertMetricFunctionEquals("Foo::foo()", cm[0]);
+ assertMetricFunctionEquals("Foo::Bar::bar()", cm[1]);
+ assertMetricFunctionEquals("Foo::foo2()", cm[2]);
+ assertMetricFunctionEquals("baz()", cm[3]);
+}
+
+// command
+void FunctionNameTest::function_singleArgument()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "void foo(int i) {}\n"
+ "class Bar {};\n"
+ "void bar(Bar b) {}\n"
+ );
+
+ QCOMPARE(2, cm.count());
+ assertMetricFunctionEquals("foo(int)", cm[0]);
+ assertMetricFunctionEquals("bar(Bar)", cm[1]);
+}
+
+// command
+void FunctionNameTest::function_multipleArguments()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class Bar {};\n"
+ "void bar(int i, Bar b) {}\n"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("bar(int,Bar)", cm[0]);
+}
+
+// command
+void FunctionNameTest::function_templateArgument()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "template <typename T> class Foo {};\n"
+ "void foo(Foo<int> bar) {}\n"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("foo(Foo<int>)", cm[0]);
+}
+
+// command
+void FunctionNameTest::function_qualifiedArgument()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "namespace Foo { class Bar {}; }\n"
+ "void foo(Foo::Bar b) {} \n"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("foo(Foo::Bar)", cm[0]);
+}
+
+void FunctionNameTest::tdd_constRefArgument()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class A {};\n"
+ "void foo(const A& a) {} \n"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("foo(const A&)", cm[0]);
+}
+
+void FunctionNameTest::tdd_pointerArgument()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class A {};\n"
+ "void foo(A* a) {} \n"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertMetricFunctionEquals("foo(A*)", cm[0]);
+}
+
+
+// command
+void FunctionNameTest::anonymousType()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "class { void foo() {} } bar;\n"
+ "struct { void zoo() {} } baz;\n");
+
+ QCOMPARE(2, cm.count());
+ assertMetricFunctionEquals("<anonymous-type>::foo()", cm[0]);
+ assertMetricFunctionEquals("<anonymous-type>::zoo()", cm[1]);
+}
+
+// command
+void FunctionNameTest::garbage()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "invalid c++ , () {}");
+}
+
+QTEST_MAIN( FunctionNameTest )
+#include "functionnametest.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/functionnametest.h (revision 1522570)
@@ -0,0 +1,66 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef QTEST_FUNCTIONNAMETEST_H_INCLUDED
+#define QTEST_FUNCTIONNAMETEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include "metrics.h"
+
+class MetricEngineFake;
+
+class FunctionNameTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void multipleFunctions_singlePath();
+ void classMemberFunction_singlePath();
+ void nestedClassMemberFunction_singlePath();
+ void namespaceFunction_singlePath();
+ void usingMemberFunction();
+ void usingFreeStandingFunction();
+ void inlineClassMemberFunction();
+ void nestedInlineClassMemberFunction();
+
+ void operatorFunction();
+ void anonymousNamespace();
+ void function_singleArgument();
+ void function_multipleArguments();
+ void function_templateArgument();
+ void function_qualifiedArgument();
+ void anonymousType();
+ void tdd_constRefArgument();
+ void tdd_pointerArgument();
+
+ void garbage();
+
+private:
+ void assertMetricFunctionEquals(const QString& name, const McCabeMetric& metric);
+
+ QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
+ MetricEngineFake* m_engine;
+ McCabeMetric m_metric;
+};
+
+#endif // QTEST_FUNCTIONNAMETEST_H_INCLUDED
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h (revision 1522570)
@@ -0,0 +1,63 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef QTEST_METRICENGINETEST_H_INCLUDED
+#define QTEST_METRICENGINETEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include "metrics.h"
+
+class MetricEngineFake;
+
+/*! @unitundertest MetricEngine */
+class McCabeMetricTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void simpleFunction_singlePath();
+ void simpleFunction_if();
+ void simpleFunction_multipleIf();
+ void simpleFunction_while();
+ void simpleFunction_for();
+ void function_singleAnd();
+ void function_multipleAnd();
+ void function_singleOr();
+ void function_plusInIf();
+ void function_switch();
+ void function_ternary();
+ void function_elseif();
+ void function_macro();
+ void function_catch();
+
+private:
+ QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
+ void computeMcCabeMetricFor(const QByteArray& source, McCabeMetric& result);
+ void assertCycloComplexityEquals(int value, const McCabeMetric& metric);
+
+private:
+ MetricEngineFake* m_engine;
+ McCabeMetric m_metric;
+};
+
+#endif // QTEST_METRICENGINETEST_H_INCLUDED
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp (revision 1522570)
@@ -0,0 +1,184 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#include "metricenginetest.h"
+#include "metricengine.h"
+#include "metrics.h"
+#include <QtTest/QTest>
+#include <kurl.h>
+
+class MetricEngineFake : public MetricEngine
+{
+public:
+ QByteArray content;
+protected:
+ virtual QByteArray readAll(const KUrl& filename) {
+ Q_UNUSED(filename);
+ return content;
+ }
+};
+
+void McCabeMetricTest::init()
+{
+ m_engine = new MetricEngineFake;
+ m_metric = McCabeMetric();
+}
+
+void McCabeMetricTest::cleanup()
+{
+ if (m_engine) delete m_engine;
+}
+
+// SUT stimulation helper
+QList<McCabeMetric> McCabeMetricTest::computeMcCabeMetricFor(const QByteArray& source)
+{
+ m_engine->content = source;
+ MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
+ return mtr.mcCabeComplexity();
+}
+
+void McCabeMetricTest::computeMcCabeMetricFor(const QByteArray& source, McCabeMetric& result)
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(source);
+ QCOMPARE(1, cm.count());
+ result = cm[0];
+}
+
+// command
+void McCabeMetricTest::simpleFunction_singlePath()
+{
+ computeMcCabeMetricFor("void foo() { int i; }", m_metric);
+ assertCycloComplexityEquals(1, m_metric);
+}
+
+// custom assertion
+void McCabeMetricTest::assertCycloComplexityEquals(int value, const McCabeMetric& metric)
+{
+ QCOMPARE(metric.value(), value);
+}
+
+// command
+void McCabeMetricTest::simpleFunction_if()
+{
+ computeMcCabeMetricFor("void bar() { bool b; if (b) { int a; } }", m_metric);
+ assertCycloComplexityEquals(2, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_elseif()
+{
+ QList<McCabeMetric> cm = computeMcCabeMetricFor(
+ "void bar() { int i; if (i<0) {} else if (i<10) {} }"
+ );
+
+ QCOMPARE(1, cm.count());
+ assertCycloComplexityEquals(3, cm[0]);
+}
+
+// command
+void McCabeMetricTest::simpleFunction_multipleIf()
+{
+ computeMcCabeMetricFor("void bar() { bool b; if (b) { int a; } if (!b) { int c; } }", m_metric);
+ assertCycloComplexityEquals(3, m_metric);
+}
+
+void McCabeMetricTest::function_switch()
+{
+ computeMcCabeMetricFor("void bar() { int i; switch (i) { case 1: i+1; case 2: i+2; } }", m_metric);
+ assertCycloComplexityEquals(3, m_metric); // +1 for each case
+}
+
+void McCabeMetricTest::function_ternary()
+{
+ computeMcCabeMetricFor("void bar() { bool b; int i; b ? i+1 : i+2; }", m_metric);
+ assertCycloComplexityEquals(2, m_metric);
+}
+
+// command
+void McCabeMetricTest::simpleFunction_while()
+{
+ computeMcCabeMetricFor("void bar() { while (1) {} }", m_metric);
+ assertCycloComplexityEquals(2, m_metric);
+}
+
+// command
+void McCabeMetricTest::simpleFunction_for()
+{
+ computeMcCabeMetricFor("void bar() { for (;;) {} }", m_metric);
+ assertCycloComplexityEquals(2, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_singleAnd()
+{
+ computeMcCabeMetricFor("void bar() { bool a,b; if ( a && b) {} }", m_metric);
+ assertCycloComplexityEquals(3, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_multipleAnd()
+{
+ computeMcCabeMetricFor("void bar() { bool a,b; if ( (a && b) && c) {} }", m_metric);
+ assertCycloComplexityEquals(4, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_singleOr()
+{
+ computeMcCabeMetricFor("void bar() { bool a,b; if ( a || b) {} }", m_metric);
+ assertCycloComplexityEquals(3, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_plusInIf()
+{
+ computeMcCabeMetricFor("void bar() { int a,b; if( a+b) {} }", m_metric);
+ assertCycloComplexityEquals(2, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_macro()
+{
+ computeMcCabeMetricFor(
+ "#define IF if (a>0) {}\n"
+ "void bar() { int a; IF IF }", m_metric);
+ assertCycloComplexityEquals(3, m_metric);
+}
+
+// command
+void McCabeMetricTest::function_catch()
+{
+ computeMcCabeMetricFor(
+ "class Exception1 {};\n"
+ "class Exception2 {};\n"
+ "void bar() { \n"
+ " try { \n"
+ " int i=1+1; \n"
+ " } catch (Exception1& e) { \n"
+ " } catch (Exception2& e) {}\n"
+ "}\n",
+ m_metric);
+ assertCycloComplexityEquals(3, m_metric);
+}
+
+
+QTEST_MAIN( McCabeMetricTest )
+#include "metricenginetest.moc"
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,17 @@
+include_directories(
+ ../include
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${QT_INCLUDES}
+ ${KDE4_INCLUDE_DIR}
+ ${KDEVPLATFORM_INCLUDE_DIR})
+
+
+set(McCabe_SRCS main.cpp metricengine.cpp metrics.cpp)
+add_executable(McCabe ${McCabe_SRCS})
+target_link_libraries(McCabe
+ ${QT_QTCORE_LIBRARY}
+ ${KDEVPLATFORM_INTERFACES}
+ ${KDEVPLATFORM_LANGUAGE}
+ ${KDE4_LIB_DIR}/libkdev4cppparser.so
+ ${KDE4_LIB_DIR}/libkdev4cpprpp.so
+)
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.cpp (revision 1522570)
@@ -0,0 +1,327 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "metricengine.h"
+#include <kurl.h>
+#include <QtCore/QFile>
+
+#include <ast.h>
+#include <tokens.h>
+#include <lexer.h>
+#include <parser.h>
+#include <control.h>
+#include <parsesession.h>
+#include <default_visitor.h>
+#include <rpp/preprocessor.h>
+#include <rpp/chartools.h>
+#include <rpp/pp-engine.h>
+#include <QFile>
+#include <kdebug.h>
+
+namespace {
+
+
+class McCabeASTVisitor : public DefaultVisitor
+{
+public:
+ McCabeASTVisitor(ParseSession& session) : m_session(session), m_switchDepth(0) {}
+ virtual ~McCabeASTVisitor() {}
+
+ ////////////////////////// data members //////////////////////////////////
+
+ ParseSession& m_session;
+ McCabeMetric m_currentMcCabe;
+ MetricStore m_metrics;
+ int m_switchDepth;
+ QStringList m_currentNamePrefix;
+ QHash<QString,QString> m_using;
+ QString m_parameterClause;
+
+ ////////////////////////// helpers ///////////////////////////////////////
+
+ QString symbolForTokenId(std::size_t id) {
+ return m_session.token_stream->token(id).symbolString();
+ }
+
+ int sourceLineForTokenId(std::size_t id) {
+ std::size_t tokenPosition = m_session.token_stream->token(id).position;
+ const rpp::Anchor& a = m_session.positionAt(tokenPosition);
+ return a.line + 1; // +1 since editor-lines start from 1 while FooIndex starts from 0
+ }
+
+ void concatenateTokensBetween(int startToken, int endToken, QString& result) {
+ if (startToken == 0) return;
+ for (int i=startToken; i<=endToken; i++) {
+ result += symbolForTokenId(i);
+ }
+ }
+
+ void appendQualifiedNames(const ListNode<UnqualifiedNameAST*>* qualifiedNames, QString& name) {
+ if (!qualifiedNames) return;
+
+ const ListNode<UnqualifiedNameAST*> *it = qualifiedNames->toFront(), *end = it;
+ do {
+ if (!name.isEmpty()) name += "::";
+ name += symbolForTokenId(it->element->id);
+ it = it->next;
+ } while (it!=end);
+ }
+
+ ////////////////////////// visit overrides ///////////////////////////////
+
+ virtual void visitConditionalExpression(ConditionalExpressionAST *node) {
+ m_currentMcCabe.increment();
+ DefaultVisitor::visitConditionalExpression(node);
+ }
+
+ virtual void visitBinaryExpression(BinaryExpressionAST *node) {
+ QString op = symbolForTokenId(node->op);
+ if (op == "||" || op == "&&") {
+ m_currentMcCabe.increment();
+ }
+ DefaultVisitor::visitBinaryExpression(node);
+ }
+
+ virtual void visitWhileStatement(WhileStatementAST *node) {
+ DefaultVisitor::visitWhileStatement(node);
+ m_currentMcCabe.increment();
+ }
+
+ virtual void visitForStatement(ForStatementAST *node) {
+ DefaultVisitor::visitForStatement(node);
+ m_currentMcCabe.increment();
+ }
+
+ virtual void visitIfStatement(IfStatementAST *node) {
+ DefaultVisitor::visitIfStatement(node);
+ m_currentMcCabe.increment();
+ }
+
+ virtual void visitFunctionDefinition(FunctionDefinitionAST *node) {
+ QString functionName;
+ m_parameterClause.clear();
+
+ if (!m_currentNamePrefix.isEmpty()) {
+ functionName = m_currentNamePrefix.join("::");
+ }
+ if (!node->init_declarator->declarator->id) return;
+
+ const ListNode<UnqualifiedNameAST*>* nodes = node->init_declarator->declarator->id->qualified_names;
+ appendQualifiedNames(nodes, functionName);
+
+ if (m_using.contains(functionName)) {
+ functionName = m_using[functionName] + "::" + functionName;
+ }
+
+ int nameTokenId = node->init_declarator->declarator->id->unqualified_name->id;
+ if (nameTokenId == 0) {
+ kWarning() << "Ignoring function definition since tokenID is zero. This might indicate an operator() function.";
+ return;
+ }
+
+ if (!functionName.isEmpty()) functionName += "::";
+ functionName += symbolForTokenId(nameTokenId);
+ if (m_using.contains(functionName)) {
+ functionName = m_using[functionName] + "::" + functionName;
+ }
+
+ m_currentMcCabe = McCabeMetric();
+ m_currentMcCabe.increment();
+ m_currentMcCabe.setLine(sourceLineForTokenId(node->start_token));
+ visitParameterDeclarationClause(node->init_declarator->declarator->parameter_declaration_clause);
+ visit(node->function_body);
+ m_currentMcCabe.setFunction(functionName + "(" + m_parameterClause + ")");
+ m_metrics.addMcCabeMetric(m_currentMcCabe);
+ }
+
+ virtual void visitLabeledStatement(LabeledStatementAST *node) {
+ DefaultVisitor::visitLabeledStatement(node);
+ if (m_switchDepth>0) {
+ m_currentMcCabe.increment();
+ }
+ }
+
+ virtual void visitNamespace(NamespaceAST *node) {
+ int nameTokenId = node->namespace_name;
+ if (nameTokenId != 0) {
+ m_currentNamePrefix << symbolForTokenId(nameTokenId);
+ } else {
+ m_currentNamePrefix << "<anonymous>";
+ }
+ DefaultVisitor::visitNamespace(node);
+ m_currentNamePrefix.takeLast();
+ }
+
+ virtual void visitSwitchStatement(SwitchStatementAST *node) {
+ m_switchDepth++;
+ DefaultVisitor::visitSwitchStatement(node);
+ m_switchDepth--;
+ }
+
+ virtual void visitUsing(UsingAST *node) {
+ NameAST* name = node->name;
+ if (!name) return;
+
+ QString prefix;
+ const ListNode<UnqualifiedNameAST*>* nodes = name->qualified_names;
+ appendQualifiedNames(nodes, prefix);
+
+ QString suffix = symbolForTokenId(name->unqualified_name->id);
+ // eg for 'using Foo::Bar;' Foo is the prefix, Bar the suffix.
+ m_using[suffix] = prefix;
+ }
+
+ virtual void visitClassSpecifier(ClassSpecifierAST *node) {
+ int nameTokenId = 0;
+ if (!node->name) {
+ m_currentNamePrefix << "<anonymous-type>";
+ } else {
+ nameTokenId = node->name->unqualified_name->id; // TODO also insert qualified prefixes
+ if (nameTokenId != 0) {
+ m_currentNamePrefix << symbolForTokenId(nameTokenId);
+ }
+ }
+ DefaultVisitor::visitClassSpecifier(node);
+ if (!node->name || nameTokenId != 0) m_currentNamePrefix.takeLast();
+ }
+
+ virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *node) {
+ DefaultVisitor::visitSimpleTypeSpecifier(node);
+ }
+
+ virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *node) {
+ if (!node) return;
+
+ if (!node->parameter_declarations) return;
+ const ListNode<ParameterDeclarationAST*> *it = node->parameter_declarations->toFront(), *end = it;
+ do {
+ TypeSpecifierAST* typeAst = it->element->type_specifier;
+ if (!m_parameterClause.isEmpty()) m_parameterClause += ",";
+ concatenateTokensBetween(typeAst->start_token, typeAst->end_token-1, m_parameterClause);
+ it = it->next;
+ } while (it!=end);
+ // TODO ellipsis
+ }
+
+ virtual void visitCatchStatement(CatchStatementAST *node) {
+ m_currentMcCabe.increment();
+ DefaultVisitor::visitCatchStatement(node);
+ }
+
+// virtual void visitBaseClause(BaseClauseAST *node) { DefaultVisitor::visitBaseClause(node); }
+// virtual void visitBaseSpecifier(BaseSpecifierAST *node) { DefaultVisitor::visitBaseSpecifier(node); }
+// virtual void visitClassMemberAccess(ClassMemberAccessAST *node) { DefaultVisitor::visitClassMemberAccess(node); }
+// virtual void visitCompoundStatement(CompoundStatementAST *node) { DefaultVisitor::visitCompoundStatement(node); }
+// virtual void visitCondition(ConditionAST *node) { DefaultVisitor::visitCondition(node); }
+// virtual void visitDeclarationStatement(DeclarationStatementAST *node) { DefaultVisitor::visitDeclarationStatement(node); }
+// virtual void visitDeclarator(DeclaratorAST *node) { DefaultVisitor::visitDeclarator(node); }
+// virtual void visitDoStatement(DoStatementAST *node) { DefaultVisitor::visitDoStatement(node); }
+// virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *node) { DefaultVisitor::visitElaboratedTypeSpecifier(node); }
+// virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *node) { DefaultVisitor::visitExpressionOrDeclarationStatement(node); }
+// virtual void visitExpressionStatement(ExpressionStatementAST *node) { DefaultVisitor::visitExpressionStatement(node); }
+// virtual void visitInitDeclarator(InitDeclaratorAST *node) { DefaultVisitor::visitInitDeclarator(node); }
+// virtual void visitJumpStatement(JumpStatementAST *node) { DefaultVisitor::visitJumpStatement(node); }
+// virtual void visitName(NameAST *node) { DefaultVisitor::visitName(node); }
+// virtual void visitLinkageBody(LinkageBodyAST *node) { DefaultVisitor::visitLinkageBody(node); }
+// virtual void visitOperator(OperatorAST *node) { DefaultVisitor::visitOperator(node); }
+// virtual void visitOperatorFunctionId(OperatorFunctionIdAST *node) { DefaultVisitor::visitOperatorFunctionId(node); }
+// virtual void visitPrimaryExpression(PrimaryExpressionAST *node) { DefaultVisitor::visitPrimaryExpression(node); }
+// virtual void visitReturnStatement(ReturnStatementAST *node) { DefaultVisitor::visitReturnStatement(node); }
+// virtual void visitSimpleDeclaration(SimpleDeclarationAST *node) { DefaultVisitor::visitSimpleDeclaration(node); }
+
+// virtual void visitThrowExpression(ThrowExpressionAST *node) { DefaultVisitor::visitThrowExpression(node); }
+// virtual void visitTranslationUnit(TranslationUnitAST *node) { DefaultVisitor::visitTranslationUnit(node); }
+// virtual void visitTryBlockStatement(TryBlockStatementAST *node) { DefaultVisitor::visitTryBlockStatement(node); }
+// virtual void visitUnaryExpression(UnaryExpressionAST *node) { DefaultVisitor::visitUnaryExpression(node); }
+// virtual void visitUnqualifiedName(UnqualifiedNameAST *node) { DefaultVisitor::visitUnqualifiedName(node); }
+
+// virtual void visitAccessSpecifier(AccessSpecifierAST *) {}
+// virtual void visitAsmDefinition(AsmDefinitionAST *) {}
+// virtual void visitParameterDeclaration(ParameterDeclarationAST*) {}
+// virtual void visitPostfixExpression(PostfixExpressionAST *) {}
+// virtual void visitCastExpression(CastExpressionAST *) {}
+// virtual void visitCppCastExpression(CppCastExpressionAST *) {}
+// virtual void visitCtorInitializer(CtorInitializerAST *) {}
+// virtual void visitDeleteExpression(DeleteExpressionAST *) {}
+// virtual void visitEnumSpecifier(EnumSpecifierAST *) {}
+// virtual void visitEnumerator(EnumeratorAST *) {}
+// virtual void visitExceptionSpecification(ExceptionSpecificationAST *) {}
+// virtual void visitInitializerClause(InitializerClauseAST *) {}
+// virtual void visitInitializer(InitializerAST *) {}
+// virtual void visitFunctionCall(FunctionCallAST *) {}
+// virtual void visitIncrDecrExpression(IncrDecrExpressionAST *) {}
+// virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *) {}
+// virtual void visitNewDeclarator(NewDeclaratorAST *) {}
+// virtual void visitNewExpression(NewExpressionAST *) {}
+// virtual void visitNewInitializer(NewInitializerAST *) {}
+// virtual void visitNewTypeId(NewTypeIdAST *) {}
+// virtual void visitLinkageSpecification(LinkageSpecificationAST *) {}
+// virtual void visitMemInitializer(MemInitializerAST *) {}
+// virtual void visitPtrOperator(PtrOperatorAST *) {}
+// virtual void visitPtrToMember(PtrToMemberAST *) {}
+// virtual void visitSizeofExpression(SizeofExpressionAST *) {}
+// virtual void visitStringLiteral(StringLiteralAST *) {}
+// virtual void visitSubscriptExpression(SubscriptExpressionAST *) {}
+// virtual void visitTemplateArgument(TemplateArgumentAST *) {}
+// virtual void visitTemplateDeclaration(TemplateDeclarationAST *) {}
+// virtual void visitTemplateParameter(TemplateParameterAST *) {}
+// virtual void visitTypeId(TypeIdAST *) {}
+// virtual void visitTypeIdentification(TypeIdentificationAST *) {}
+// virtual void visitTypeParameter(TypeParameterAST *) {}
+// virtual void visitTypedef(TypedefAST *) {}
+// virtual void visitUsingDirective(UsingDirectiveAST *) {}
+// virtual void visitWinDeclSpec(WinDeclSpecAST *) {}
+};
+
+} // end anonymous namespace
+
+MetricEngine::MetricEngine()
+{}
+
+MetricEngine::~MetricEngine()
+{}
+
+MetricStore MetricEngine::process(const KUrl& file)
+{
+ QByteArray contents = readAll(file);
+
+ ParseSession session;
+ rpp::Preprocessor preprocessor;
+ rpp::pp pp(&preprocessor);
+ PreprocessedContents ppContents;
+ ppContents= pp.processFile(file.path(), contents);
+ session.setContentsAndGenerateLocationTable(ppContents);
+
+ Control control;
+ Parser parzer(&control);
+ TranslationUnitAST *ast = parzer.parse(&session);
+ McCabeASTVisitor vtor(session);
+ vtor.visit(ast);
+
+ return vtor.m_metrics;
+}
+
+QByteArray MetricEngine::readAll(const KUrl& filename)
+{
+ QFile f(filename.path());
+ f.open(QIODevice::ReadOnly);
+ return f.readAll();
+}
+
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metricengine.h (revision 1522570)
@@ -0,0 +1,40 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#ifndef MCCABE_METRICENGINE_H
+#define MCCABE_METRICENGINE_H
+
+#include "metrics.h"
+class KUrl;
+
+/*! @short Metric computation workhorse
+ * @unittest MetricEngineTest */
+class MetricEngine
+{
+public:
+ MetricEngine();
+ virtual ~MetricEngine();
+ MetricStore process(const KUrl& file);
+
+protected:
+ virtual QByteArray readAll(const KUrl& filename);
+};
+
+#endif // MCCABE_METRICENGINE_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.cpp (revision 1522570)
@@ -0,0 +1,64 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "metrics.h"
+
+McCabeMetric::McCabeMetric() : m_line(-1), m_complexity(0)
+{}
+
+QString McCabeMetric::function() const
+{
+ return m_function;
+}
+
+void McCabeMetric::setFunction(const QString& signature)
+{
+ m_function = signature;
+}
+
+int McCabeMetric::line() const
+{
+ return m_line;
+}
+
+void McCabeMetric::setLine(int line)
+{
+ m_line = line;
+}
+
+int McCabeMetric::value() const
+{
+ return m_complexity;
+}
+
+void McCabeMetric::increment()
+{
+ m_complexity += 1;
+}
+
+void MetricStore::addMcCabeMetric(const McCabeMetric& mc)
+{
+ m_mcCabeComplexity << mc;
+}
+
+QList<McCabeMetric> MetricStore::mcCabeComplexity()
+{
+ return m_mcCabeComplexity;
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/metrics.h (revision 1522570)
@@ -0,0 +1,58 @@
+/*
+ * This file is part of KDevelop
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+
+#ifndef MCCABE_METRICS_H
+#define MCCABE_METRICS_H
+
+#include <QtCore/QString>
+#include <QtCore/QList>
+
+/*! Single Cyclomatic Complexity entity */
+class McCabeMetric
+{
+public:
+ McCabeMetric();
+ QString function() const;
+ void setFunction(const QString&);
+
+ int line() const;
+ void setLine(int);
+
+ int value() const;
+ void increment();
+
+private:
+ QString m_function;
+ int m_line;
+ int m_complexity;
+};
+
+class MetricStore
+{
+public:
+ void addMcCabeMetric(const McCabeMetric&);
+ QList<McCabeMetric> mcCabeComplexity();
+
+private:
+ QList<McCabeMetric> m_mcCabeComplexity;
+};
+
+#endif // MCCABE_METRICS_H
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/main.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/main.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/src/main.cpp (revision 1522570)
@@ -0,0 +1,27 @@
+#include "metricengine.h"
+#include "metrics.h"
+#include <iostream>
+#include <kurl.h>
+
+using std::cerr;
+using std::cout;
+using std::endl;
+
+int main(int argc, char** argv)
+{
+ cout << "McCabe cyclomatic complexity engine" << endl;
+ if (argc == 1) {
+ cerr << "No source files provided\nusage: "
+ << argv[0] << " file1 [file2 [file3 [...]]]" << endl;
+ return -1;
+ }
+ MetricEngine me;
+ for (int i=1; i<argc; i++) {
+ cout << "Processing " << argv[i] << endl;
+ MetricStore ms = me.process(KUrl(argv[i]));
+ foreach(const McCabeMetric& mc, ms.mcCabeComplexity()) {
+ cout << mc.value() << " " << mc.function().toLatin1().data() << endl;
+ }
+ }
+ return 0;
+}
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/mccabe.kdev4
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/mccabe.kdev4 (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/mccabe.kdev4 (revision 1522570)
@@ -0,0 +1,4 @@
+[Project]
+Name=McCabe
+Manager=KDevCMakeManager
+VersionControl=
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf (revision 1522570)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
___________________________________________________________________
Added: svn:mime-type
## -0,0 +1 ##
+application/octet-stream
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake (revision 1522570)
@@ -0,0 +1,46 @@
+#
+# Find the KDevelop Platform modules and sets various variables accordingly
+#
+# Example usage of this module:
+# find_package(KDevPlatform 1.0.0 REQUIRED)
+#
+# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
+# variable to help it find the required files and directories
+
+# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
+#
+# KDEVPLATFORM_VERSION - The version number of kdevplatform
+# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
+# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
+# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
+# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
+# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
+# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
+# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
+# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
+# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
+# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
+# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
+# contains some useful tools and a way to replace parts of Core
+# classes with custom implementations
+# KDEVPLATFORM_UTIL_LIBRARIES - util module library
+# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
+# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
+# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
+#
+# The following macros are added (from KDevPlatformMacros.cmake):
+#
+# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
+# Use this to get packaged template archives for the given templates.
+# Parameters should be the directories containing the templates.
+#
+# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
+# Redistribution and use is allowed according to the terms of the BSD license.
+
+set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
+find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
+set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,24 @@
+set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR})
+
+include_directories(${KDEVPlATFORM_INCLUDES})
+
+macro(kdev_add_test test_EXEC test_SRCS)
+ qt4_automoc( ${test_SRCS} )
+ kde4_add_unit_test(veritas-${test_EXEC} ${test_SRCS})
+ target_link_libraries(veritas-${test_EXEC}
+ veritascpp
+ ${QT_QTTEST_LIBRARY}
+ ${QT_QTXML_LIBRARY}
+ ${KDE4_KDECORE_LIBS}
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+ ${KDE4_KTEXTEDITOR_LIBRARY})
+endmacro(kdev_add_test)
+
+kdev_add_test(unit-classskeleton classskeletontest.cpp)
+kdev_add_test(unit-stubcreation stubcreationtest.cpp)
+kdev_add_test(unit-constructorskeleton constructorskeletontest.cpp)
+kdev_add_test(unit-methodskeleton methodskeletontest.cpp)
+kdev_add_test(unit-classwriter classwritertest.cpp)
+kdev_add_test(unit-uutcreation uutcreationtest.cpp)
+kdev_add_test(unit-ktextdocumentstub ktextdocumentstubtest.cpp)
+kdev_add_test(unit-includewriter includewritertest.cpp)
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h (revision 1522570)
@@ -0,0 +1,28 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KDEVELOP_KDEVTEST_H_INCLUDED
+#define KDEVELOP_KDEVTEST_H_INCLUDED
+
+#include <qtest_kde.h>
+#include <QtTest/QTest>
+#include "xtest/kasserts.h"
+
+#endif // KDEVELOP_KDEVTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h (revision 1522570)
@@ -0,0 +1,41 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
+#define QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas { namespace Test {
+
+/*! Might want to remove it, testing basic value classes is not so useful */
+class ConstructorSkeletonTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void instantiate();
+};
+
+}}
+
+#endif // QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h (revision 1522570)
@@ -0,0 +1,52 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#ifndef QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
+#define QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include <KUrl>
+
+namespace Veritas { namespace Test {
+
+class DocumentAccessStubTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void text();
+ void textRange();
+ void textRange_data();
+// void textRangeLines();
+// void character();
+// void character_data();
+// void line();
+// void line_data();
+
+private:
+ KUrl m_someUrl;
+};
+
+}}
+
+#endif // QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp (revision 1522570)
@@ -0,0 +1,151 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include "classwritertest.h"
+#include "../classwriter.h"
+#include "../classskeleton.h"
+#include "kdevtest.h"
+#include <KDebug>
+#include <QRegExp>
+
+using Veritas::Test::ClassWriterTest;
+using Veritas::ClassSerializer;
+using Veritas::ClassSkeleton;
+
+/////////////////////////// test commands ////////////////////////////////////
+
+void ClassWriterTest::noMethods()
+{
+ ClassSkeleton cs;
+ cs.setName("Foo");
+
+ QString actual = serialize(cs);
+ QString expected("class Foo { };");
+
+ assertAlike(expected, actual);
+}
+
+void ClassWriterTest::method()
+{
+ ClassSkeleton cs;
+ cs.setName("Foo");
+ MethodSkeleton ms;
+ ms.setName("foo");
+ ms.setVirtual();
+ cs.addMethod(ms);
+
+ QString expected("class Foo { public: virtual void foo() { } };");
+ QString actual = serialize(cs);
+
+ assertAlike(expected, actual);
+}
+
+void ClassWriterTest::constructor()
+{
+ ClassSkeleton cs;
+ cs.setName("Foo");
+ ConstructorSkeleton ctr;
+ ctr.setName("Foo");
+ ctr.addInitializer("m_foo(0)");
+ ctr.setAccess(Veritas::Public);
+ cs.setConstructor(ctr);
+
+ QString actual = serialize(cs);
+ QString expected =
+ "class Foo { public: Foo() : m_foo(0) { } }; ";
+
+ assertAlike(expected, actual);
+}
+
+void ClassWriterTest::constMethod()
+{
+ ClassSkeleton cs;
+ cs.setName("Foo");
+ MethodSkeleton ms;
+ ms.setName( "foo" );
+ ms.setConst( true );
+ ms.setReturnType( "void" );
+ cs.addMethod( ms );
+
+ QString actual = serialize(cs);
+ QVERIFY(actual.contains( " const" ));
+}
+
+void ClassWriterTest::singleNamespace()
+{
+ ClassSkeleton cs;
+ cs.setName("FooSpace::Foo");
+
+ QString actual = serialize(cs);
+ QString expected =
+ "namespace FooSpace { "
+ "class Foo { }; } ";
+
+ assertAlike(expected, actual);
+}
+
+void ClassWriterTest::nestedNamespace()
+{
+ ClassSkeleton cs;
+ cs.setName("FooSpace::BarSpace::Foo");
+
+ QString actual = serialize(cs);
+ QString expected =
+ "namespace FooSpace { namespace BarSpace { "
+ "class Foo { }; }} ";
+
+ assertAlike(expected, actual);
+}
+
+
+////////////////////////// helpers ///////////////////////////////////////////
+
+/*! Construct a regular expression that is tolerant on
+spaces, newlines tabs etc */
+QRegExp ClassWriterTest::whiteSpaceRegex(const QString& text)
+{
+ QString ws("[\\s\\n\\r\\t]*");
+ QString escaped = QRegExp::escape(text);
+ QStringList r = escaped.split(" ");
+ r.push_front(ws);
+ r.push_back(ws);
+ return QRegExp(r.join(ws));
+}
+
+// helper
+QString ClassWriterTest::serialize(const ClassSkeleton& cs)
+{
+ QBuffer buff;
+ ClassSerializer cw;
+ cw.write(cs, &buff);
+ return QString(buff.data());
+}
+
+// custom assertion
+void ClassWriterTest::assertAlike(const QString& expected, const QString& actual)
+{
+ QRegExp pattern = whiteSpaceRegex(expected);
+ KVERIFY_MSG(pattern.isValid(), pattern.errorString() + " " +pattern.pattern());
+ QString failMsg = QString("\nExpected:\n%1\nActual:\n%2").arg(expected).arg(actual);
+ KVERIFY_MSG(pattern.exactMatch(actual), failMsg);
+}
+
+QTEST_MAIN( ClassWriterTest )
+#include "classwritertest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp (revision 1522570)
@@ -0,0 +1,335 @@
+/*
+ * KDevelop xUnit test support
+ * Copyright 2008 Manuel Breugelmans
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stubcreationtest.h"
+
+#include "kdevtest.h"
+
+#include "../stubconstructor.h"
+#include "../classskeleton.h"
+#include "../constructorskeleton.h"
+#include "../methodskeleton.h"
+
+#include "classdeclarationfactory.h"
+
+#include <language/duchain/classdeclaration.h>
+#include <language/editor/simplecursor.h>
+
+
+using Veritas::StubConstructor;
+using Veritas::ClassSkeleton;
+using Veritas::ConstructorSkeleton;
+using Veritas::MethodSkeleton;
+using Veritas::Test::StubCreationTest;
+using Veritas::Test::DeclarationFactory;
+
+using namespace KDevelop;
+
+/////////////////////////// fixture //////////////////////////////////////////
+
+void StubCreationTest::init()
+{
+ m_factory = new DeclarationFactory;
+ m_constructor = new StubConstructor;
+}
+
+void StubCreationTest::cleanup()
+{
+ if (m_factory) {
+ //m_factory->release();
+ delete m_factory;
+ }
+ if (m_constructor) delete m_constructor;
+}
+
+/////////////////////////// commands /////////////////////////////////////////
+
+void StubCreationTest::appendStubToClassName()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ClassSkeleton expected;
+ expected.setName("IFooStub");
+ KOMPARE("IFoo", actual.super());
+ KOMPARE(expected.name(), actual.name());
+}
+
+void StubCreationTest::basicConstructor()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{ public: IFoo(); virtual ~IFoo(); };\n");
+
+ ConstructorSkeleton cs = actual.constructor();
+ KVERIFY(!cs.isEmpty());
+ KOMPARE("IFooStub", cs.name());
+}
+
+void StubCreationTest::basicDestructor()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{ public: IFoo(); virtual ~IFoo(); };\n");
+
+ MethodSkeleton d = actual.destructor();
+ KOMPARE("~IFooStub", d.name());
+}
+
+void StubCreationTest::basicInterface()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual void foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ MethodSkeleton ms;
+ ms.setName("foo");
+ ms.setReturnType("void");
+ ms.setBody("");
+ KOMPARE("IFooStub", actual.name());
+ KOMPARE("IFoo", actual.super());
+ KOMPARE(1, actual.methods().count());
+ kompareMethods(ms, actual.methods()[0]);
+
+ KVERIFY(!actual.hasMembers());
+ KOMPARE(0, actual.memberCount());
+}
+
+void StubCreationTest::nonVoidReturnType()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual int foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ MethodSkeleton ms;
+ ms.setName("foo");
+ ms.setReturnType("int");
+ ms.setBody("return m_foo;");
+ KOMPARE("IFooStub", actual.name());
+ KOMPARE(1, actual.methods().count());
+ kompareMethods(ms, actual.methods()[0]);
+ KOMPARE(1, actual.memberCount());
+ KOMPARE("int m_foo", actual.member(0));
+}
+
+void StubCreationTest::nonVirtualMethod()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " int foo();\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ KVERIFY(actual.methods().isEmpty());
+}
+
+void StubCreationTest::privateMethod()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "private: virtual bool bar();\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ KVERIFY(actual.methods().isEmpty());
+}
+
+void StubCreationTest::signal()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "signals: void foo();\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ KVERIFY(actual.methods().isEmpty());
+}
+
+void StubCreationTest::signalWithEmptyPublic()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ "signals: void foo();\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ KVERIFY(actual.methods().isEmpty());
+}
+
+void StubCreationTest::prependNamespace()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "namespace Zoo { class IFoo {}; }\n");
+
+ KVERIFY(!actual.isEmpty());
+ KOMPARE("Zoo::IFooStub", actual.name());
+}
+
+void StubCreationTest::prependNestedNamespace()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "namespace Zoo { namespace Loo { class IFoo {}; } }\n");
+
+ KVERIFY(!actual.isEmpty());
+ KOMPARE("Zoo::Loo::IFooStub", actual.name());
+}
+
+void StubCreationTest::constMethod()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual void foo() const = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ MethodSkeleton expectedMtd;
+ expectedMtd.setName("foo");
+ expectedMtd.setReturnType("void");
+ expectedMtd.setBody("");
+ expectedMtd.setConst(true);
+ KOMPARE(1, actual.methods().count());
+ kompareMethods(expectedMtd, actual.methods()[0]);
+}
+
+void StubCreationTest::dropMemberConstness()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual const int foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ KOMPARE(1, actual.memberCount());
+ KOMPARE("int m_foo", actual.member(0));
+}
+
+void StubCreationTest::pointerConstructorInitializer()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual IFoo* foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ConstructorSkeleton cs = actual.constructor();
+ KOMPARE(1, cs.initializerList().size());
+ KOMPARE("m_foo(0)", cs.initializerList()[0]);
+}
+
+void StubCreationTest::boolConstructorInitializer()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual bool foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ConstructorSkeleton cs = actual.constructor();
+ KOMPARE(1, cs.initializerList().size());
+ KOMPARE("m_foo(false)", cs.initializerList()[0]);
+}
+
+void StubCreationTest::intConstructorInitializer()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual int foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ConstructorSkeleton cs = actual.constructor();
+ KOMPARE(1, cs.initializerList().size());
+ KOMPARE("m_foo(0)", cs.initializerList()[0]);
+}
+
+void StubCreationTest::noInitializerRegularClass()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual IFoo foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ConstructorSkeleton cs = actual.constructor();
+ KOMPARE(0, cs.initializerList().size());
+}
+
+void StubCreationTest::noInitializerVoidReturn()
+{
+ ClassSkeleton actual = createStubClassFrom(
+ "class IFoo\n"
+ "{\n"
+ "public:\n"
+ " virtual void foo() = 0;\n"
+ "};\n");
+
+ KVERIFY(!actual.isEmpty());
+ ConstructorSkeleton cs = actual.constructor();
+ KOMPARE(0, cs.initializerList().size());
+}
+
+/////////////////////////// helpers //////////////////////////////////////////
+
+void StubCreationTest::kompareMethods(const MethodSkeleton& expected, const MethodSkeleton& actual)
+{
+ KOMPARE(expected.name(), actual.name());
+ KOMPARE(expected.returnType(), actual.returnType());
+ KOMPARE(expected.arguments(), actual.arguments());
+ KOMPARE(expected.body(), actual.body());
+ KOMPARE(expected.isConst(), actual.isConst());
+}
+
+ClassSkeleton StubCreationTest::createStubClassFrom(const QByteArray& text)
+{
+ ClassDeclaration* clazz = m_factory->classFromText(text);
+ kDebug() << clazz;
+ return m_constructor->morph(clazz);
+}
+
+QTEST_KDEMAIN( StubCreationTest, NoGUI )
+#include "stubcreationtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp (revision 1522570)
@@ -0,0 +1,325 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "uutcreationtest.h"
+#include "kdevtest.h"
+#include "classdeclarationfactory.h"
+#include "../uutconstructor.h"
+#include "../classskeleton.h"
+#include "documentaccessstub.h"
+#include <language/duchain/use.h>
+
+using Veritas::Test::UUTCreationTest;
+using Veritas::Test::DeclarationFactory;
+using Veritas::Test::DocumentAccessStub;
+using Veritas::UUTConstructor;
+using Veritas::ClassSkeleton;
+using Veritas::MethodSkeleton;
+
+using namespace KDevelop;
+
+void UUTCreationTest::init()
+{
+ m_factory = new DeclarationFactory;
+ m_document = new DocumentAccessStub;
+ m_constructor = new UUTConstructor;
+ m_constructor->setDocumentAccess(m_document);
+}
+
+void UUTCreationTest::cleanup()
+{
+ if (m_factory) delete m_factory;
+ if (m_document) delete m_document;
+ if (m_constructor) delete m_constructor;
+}
+
+void UUTCreationTest::unresolvedVariable()
+{
+ QList<Declaration*> variables = m_factory->unresolvedVariablesFromText("Foo f;");
+ Q_ASSERT(variables.count() == 1);
+ ClassSkeleton cs = m_constructor->morph(variables[0]);
+
+ KVERIFY(!cs.isEmpty());
+ KOMPARE("Foo", cs.name());
+ KVERIFY(cs.methods().isEmpty());
+ KOMPARE(0, cs.memberCount());
+}
+
+void UUTCreationTest::resolvedVariables()
+{
+ QList<Declaration*> variables = m_factory->variablesFromText(
+ "class Foo {}; int i; Foo f;");
+ Q_ASSERT(variables.count() == 2);
+
+ KVERIFY(m_constructor->morph(variables[0]).isEmpty());
+ KVERIFY(m_constructor->morph(variables[1]).isEmpty());
+}
+
+// helper to construct a class from it's implementation
+ClassSkeleton UUTCreationTest::classFromImplementation(const QByteArray& text)
+{
+ QList<Declaration*> variables =
+ m_factory->unresolvedVariablesFromText(text);
+ m_document->m_text = QString(text);
+ if (!variables.count()) return ClassSkeleton();
+ return m_constructor->morph(variables[0]);
+}
+
+void UUTCreationTest::singleUse()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo moo; moo.foo(); } ");
+
+ assertNamed("Foo", cs);
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::tdd_nonVoidReturn()
+{
+ TDD_TODO;
+
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; int i = f.foo(); } ");
+
+ assertNamed("Foo", cs);
+ KOMPARE(1, cs.methods().count());
+
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("int", ms.returnType());
+ assertNoArguments(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::singleArgument()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; int i; f.foo(i); } ");
+
+ assertNamed("Foo", cs);
+ KOMPARE(1, cs.methods().count());
+
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("(int)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::tdd_pointerUse()
+{
+ TDD_TODO;
+
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo *f; f->foo(); } ");
+ assertNamed("Foo", cs);
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::multipleUses()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f.foo(); f.foo1(); } ");
+
+ assertNamed("Foo", cs);
+ KOMPARE(2, cs.methods().count());
+
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ assertNoArguments(ms);
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+
+ MethodSkeleton ms2 = cs.methods()[1];
+ assertNamed("foo1", ms2);
+ assertNoArguments(ms2);
+ assertReturnsVoid(ms2);
+ assertDefaultBody(ms2);
+}
+
+void UUTCreationTest::useInIfConstruct()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; if (true) { f.foo(); } } ");
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::assertSimpleFooMethod(const ClassSkeleton& cs)
+{
+ KOMPARE(1, cs.methods().count());
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ assertNoArguments(ms);
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::spacesBeforeDot()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f .foo(); } ");
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::spacesAfterDot()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f. foo(); } ");
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::methodOnNextLine()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f.\nfoo(); } ");
+ assertSimpleFooMethod(cs);
+}
+
+void UUTCreationTest::dataMemberUse()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f.m_foo; } ");
+ KOMPARE(0, cs.methods().count());
+}
+
+void UUTCreationTest::multipleParameters()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; int i; char c; f.foo(i,c); } ");
+
+ KOMPARE(1, cs.methods().count());
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("(int, char)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::classParameter()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "class Bar; void fun() { Foo f; Bar b; f.foo(b); } ");
+
+ KOMPARE(1, cs.methods().count());
+ MethodSkeleton ms = cs.methods()[0];
+ KOMPARE("(Bar)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::threeParameters()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; int i; char c; bool b; f.foo(i,c,b); } ");
+
+ KOMPARE(1, cs.methods().count());
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("(int, char, bool)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::functionUseWithIdenticalName()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void f() {} void fun() { Foo f; f.foo(); f(); } ");
+ assertSimpleFooMethod(cs);
+}
+
+
+void UUTCreationTest::multipleParametersSmearedOverMultipleLines()
+{
+ kDebug() << 4;
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() {\n"
+ " Foo f; int i; char c;\n"
+ " f.foo(\n"
+ " i,\n"
+ " c);\n"
+ "}\n");
+
+ KOMPARE(1, cs.methods().count());
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("(int, char)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::nestedBraces()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "int fn() {\n"
+ " return 0;\n"
+ "}\n"
+ "void fun() {\n"
+ " Foo f;\n"
+ " int i;\n"
+ " f.foo(fn());\n"
+ "}\n");
+ MethodSkeleton ms = cs.methods()[0];
+ assertNamed("foo", ms);
+ KOMPARE("(int)", ms.arguments());
+ assertReturnsVoid(ms);
+ assertDefaultBody(ms);
+}
+
+void UUTCreationTest::noSemicolon()
+{
+ ClassSkeleton cs = classFromImplementation(
+ "void fun() { Foo f; f.foo() } ");
+ assertNamed("Foo", cs);
+ KOMPARE(0, cs.methods().count());
+}
+
+//////////////////// Custom assertions ///////////////////////////////////////
+
+void UUTCreationTest::assertReturnsVoid(const MethodSkeleton& ms)
+{
+ QString failMsg = QString("Was expecting void return type but got: %1").arg(ms.returnType());
+ KOMPARE_MSG("void", ms.returnType(), failMsg);
+}
+
+void UUTCreationTest::assertNoArguments(const MethodSkeleton& ms)
+{
+ QString failMsg = QString("Was expecting no arguments but got: %1").arg(ms.returnType());
+ KOMPARE_MSG("()", ms.arguments(), failMsg);
+}
+
+void UUTCreationTest::assertNamed(const QString& name, const ClassSkeleton& t)
+{
+ QString failMsg = QString("Wrong name. Expected : ``%1'' but got ``%2''").arg(name).arg(t.name());
+ KOMPARE_MSG(name, t.name(), failMsg);
+}
+
+void UUTCreationTest::assertNamed(const QString& name, const MethodSkeleton& t)
+{
+ QString failMsg = QString("Wrong name. Expected : ``%1'' but got ``%2''").arg(name).arg(t.name());
+ KOMPARE_MSG(name, t.name(), failMsg);
+}
+
+void UUTCreationTest::assertDefaultBody(const MethodSkeleton& ms)
+{
+ KOMPARE("// GENERATED", ms.body());
+}
+
+QTEST_MAIN( UUTCreationTest )
+#include "uutcreationtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h (revision 1522570)
@@ -0,0 +1,61 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#ifndef VERITAS_DOCUMENTACCESSSTUB_H
+#define VERITAS_DOCUMENTACCESSSTUB_H
+
+#include "../documentaccess.h"
+#include <QList>
+
+namespace Veritas { namespace Test {
+
+class DocumentAccessStub : public Veritas::DocumentAccess
+{
+public:
+ DocumentAccessStub() { m_count = 0; }
+ virtual ~DocumentAccessStub() {}
+ virtual QString text(const KUrl&, const KDevelop::SimpleRange& range) const {
+ m_ranges << range;
+ QStringList lines;
+ foreach(QString line, m_text.split("\n")) lines.append(line+"\n");
+ if (lines.isEmpty()) return "";
+ for (int i=lines.count(); i>range.end.line+1 && !lines.isEmpty(); i--)
+ lines.removeLast();
+ for (int i=0; i<range.start.line && !lines.isEmpty(); i++)
+ lines.removeFirst();
+ if (lines.isEmpty()) return "";
+ lines[0] = lines[0].mid(range.start.column);
+ if (range.start.line == range.end.line) {
+ lines[0] = lines[0].left(range.end.column - range.start.column);
+ } else if (m_text.split("\n").count() > range.end.line) {
+ lines[lines.count()-1] = lines[lines.count()-1].left(range.end.column);
+ }
+ return lines.join("");
+ }
+ QString text(const KUrl& ) const { return m_text; }
+ QString m_text;
+ int m_count;
+ mutable QList<KDevelop::SimpleRange> m_ranges;
+};
+
+}}
+
+#endif // VERITAS_DOCUMENTACCESSTUB_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp (revision 1522570)
@@ -0,0 +1,183 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include "classdeclarationfactory.h"
+
+// kdevplatform
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/duchainlock.h>
+
+// kdevelop
+#include <language/duchain/classdeclaration.h>
+#include "../cppduchain/declarationbuilder.h"
+#include "../cppduchain/environmentmanager.h"
+#include "../cppduchain/usebuilder.h"
+#include "../parser/parser.h"
+#include "../parser/parsesession.h"
+#include "../parser/rpp/preprocessor.h"
+#include "../parser/rpp/pp-engine.h"
+
+using Veritas::Test::DeclarationFactory;
+using namespace KDevelop;
+using namespace Cpp;
+
+int DeclarationFactory::m_count = 0;
+
+DeclarationFactory::DeclarationFactory()
+{
+ m_lock = new DUChainWriteLocker(DUChain::lock());
+ m_lock->unlock();
+}
+
+DeclarationFactory::~DeclarationFactory()
+{
+ if (m_lock && m_lock->locked()) {
+ m_lock->unlock();
+ delete m_lock;
+ }
+}
+
+namespace
+{
+ClassDeclaration* classDeclarationIn(DUContext* ctx)
+{
+ Q_ASSERT(ctx->localDeclarations().count() !=0 );
+ Declaration* dcl = ctx->localDeclarations().first();
+ Q_ASSERT(dcl);
+ ClassDeclaration* clazz = dynamic_cast<ClassDeclaration*>(dcl);
+ Q_ASSERT(clazz);
+ return clazz;
+}
+}
+
+ClassDeclaration* DeclarationFactory::classFromText(const QByteArray& text)
+{
+ if (m_lock->locked()) m_lock->unlock();
+ TopDUContext* top = parseText(text);
+ Q_ASSERT(top);
+ m_tops << top;
+ if (!m_lock->locked()) m_lock->lock();
+ DUContext* context = top;
+
+ if (context->localDeclarations().count() == 0) {
+ // see if we'r in a namespace. if so extract the class from there
+ QVector<DUContext*> children = context->childContexts();
+ Q_ASSERT(!children.isEmpty());
+ Q_ASSERT(children[0]->type() == DUContext::Namespace);
+ context = children[0];
+ if (context->localDeclarations().count() == 0) {
+ // still no classdeclaration, try one more
+ QVector<DUContext*> children = context->childContexts();
+ Q_ASSERT(!children.isEmpty());
+ Q_ASSERT(children[0]->type() == DUContext::Namespace);
+ context = children[0];
+ }
+ }
+
+ ClassDeclaration* clazz = classDeclarationIn(context);
+ if (m_lock->locked()) m_lock->unlock();
+ return clazz;
+}
+
+QList<Declaration*> DeclarationFactory::variablesFromText(const QByteArray& text)
+{
+ if (m_lock->locked()) m_lock->unlock();
+ TopDUContext* top = parseText(text);
+ Q_ASSERT(top);
+ m_tops << top;
+ if (!m_lock->locked()) m_lock->lock();
+ Q_ASSERT(top->localDeclarations().count() !=0 );
+ QList<Declaration*> ret;
+ foreach(Declaration* dcl, top->localDeclarations()) {
+ if (dcl && (dcl->kind() == Declaration::Instance) && (dcl->isDefinition())) {
+ ret << dcl;
+ }
+ }
+ if (m_lock->locked()) m_lock->unlock();
+ return ret;
+}
+
+QList<Declaration*> dcls(DUContext* ctx)
+{
+ QList<Declaration*> ret;
+ foreach(Declaration* dcl, ctx->localDeclarations()) {
+ if ((dcl->kind() == Declaration::Instance) && (dcl->isDefinition())) {
+ DelayedType::Ptr type = dcl->type<DelayedType>();
+ if (!type || type->kind() != DelayedType::Unresolved) {
+ kDebug() << "Is a resolved type, or delayed.";
+ } else {
+ ret << dcl;
+ }
+ }
+ }
+ foreach(DUContext* cctx, ctx->childContexts()) {
+ ret += dcls(cctx);
+ }
+ return ret;
+}
+
+QList<Declaration*> DeclarationFactory::unresolvedVariablesFromText(const QByteArray& text)
+{
+ if (m_lock->locked()) m_lock->unlock();
+ TopDUContext* top = parseText(text);
+ Q_ASSERT(top);
+ m_tops << top;
+ if (!m_lock->locked()) m_lock->lock();
+ Q_ASSERT(top->localDeclarations().count() !=0 );
+ QList<Declaration*> ret = dcls(top);
+ if (m_lock->locked()) m_lock->unlock();
+ return ret;
+}
+
+void DeclarationFactory::release()
+{
+ foreach(TopDUContext* top, m_tops) {
+ if (top) {
+ TopDUContextPointer tp(top);
+ DUChain::self()->removeDocumentChain(static_cast<TopDUContext*>(top));
+ Q_ASSERT(!tp);
+ }
+ }
+ m_lock->unlock();
+}
+
+TopDUContext* DeclarationFactory::parseText(const QByteArray& text)
+{
+ ParseSession* session = new ParseSession();
+ rpp::Preprocessor preprocessor;
+ rpp::pp pp(&preprocessor);
+ session->setContentsAndGenerateLocationTable(
+ pp.processFile("anonymous", text));
+
+ Parser parser(&m_control);
+ TranslationUnitAST* ast = parser.parse(session);
+ ast->session = session;
+
+ IndexedString url(QString("/internal/%1").arg(m_count));
+ DeclarationBuilder definitionBuilder(session);
+ Cpp::EnvironmentFilePointer file(new Cpp::EnvironmentFile(url,0));
+ TopDUContext* top = definitionBuilder.buildDeclarations(file, ast);
+
+ UseBuilder useBuilder(session);
+ useBuilder.buildUses(ast);
+
+ delete session;
+ return top;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h (revision 1522570)
@@ -0,0 +1,55 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef QTEST_CLASSWRITERTEST_H_INCLUDED
+#define QTEST_CLASSWRITERTEST_H_INCLUDED
+
+#include <QObject>
+#include <QString>
+#include <QRegExp>
+
+namespace Veritas
+{
+class ClassSkeleton;
+
+namespace Test
+{
+
+/*! @unitundertest Veritas::ClassSerializer */
+class ClassWriterTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void noMethods();
+ void method();
+ void constructor();
+ void constMethod();
+ void singleNamespace();
+ void nestedNamespace();
+
+private:
+ QRegExp whiteSpaceRegex(const QString& text);
+ QString serialize(const ClassSkeleton& cs);
+ void assertAlike(const QString& expected, const QString& actual);
+};
+
+}}
+
+#endif // QTEST_CLASSWRITERTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h (revision 1522570)
@@ -0,0 +1,72 @@
+/*
+ * KDevelop xUnit test support
+ * Copyright 2008 Manuel Breugelmans
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef QTEST_STUBCREATIONTEST_H_INCLUDED
+#define QTEST_STUBCREATIONTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include "../classskeleton.h"
+
+
+namespace Veritas
+{
+class StubConstructor;
+namespace Test
+{
+
+class DeclarationFactory;
+class StubCreationTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void appendStubToClassName();
+ void basicConstructor();
+ void basicDestructor();
+ void basicInterface();
+ void nonVoidReturnType();
+ void nonVirtualMethod();
+ void privateMethod();
+ void signal();
+ void signalWithEmptyPublic();
+ void prependNamespace();
+ void prependNestedNamespace();
+ void constMethod();
+ void dropMemberConstness();
+ void pointerConstructorInitializer();
+ void intConstructorInitializer();
+ void boolConstructorInitializer();
+ void noInitializerRegularClass();
+ void noInitializerVoidReturn();
+
+private:
+ ClassSkeleton createStubClassFrom(const QByteArray&);
+ void kompareMethods(const MethodSkeleton& expected, const MethodSkeleton& actual);
+
+private:
+ DeclarationFactory* m_factory;
+ StubConstructor* m_constructor;
+};
+
+}}
+
+#endif // QTEST_STUBCREATIONTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h (revision 1522570)
@@ -0,0 +1,84 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef QTEST_UUTCREATIONTEST_H_INCLUDED
+#define QTEST_UUTCREATIONTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas
+{
+class UUTConstructor;
+class MethodSkeleton;
+class ClassSkeleton;
+
+namespace Test
+{
+
+class DocumentAccessStub;
+class DeclarationFactory;
+
+/*! @unitundertest Veritas::UUTConstructor */
+class UUTCreationTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void unresolvedVariable();
+ void resolvedVariables();
+ void singleUse();
+ void tdd_nonVoidReturn();
+ void singleArgument();
+ void tdd_pointerUse();
+ void multipleUses();
+ void useInIfConstruct();
+ void spacesBeforeDot();
+ void spacesAfterDot();
+ void methodOnNextLine();
+ void dataMemberUse();
+ void multipleParameters();
+ void classParameter();
+ void threeParameters();
+ void functionUseWithIdenticalName();
+ void multipleParametersSmearedOverMultipleLines();
+ void nestedBraces();
+ void noSemicolon();
+
+private:
+ void assertReturnsVoid(const MethodSkeleton& ms);
+ void assertNoArguments(const MethodSkeleton& ms);
+ void assertNamed(const QString& name, const MethodSkeleton&);
+ void assertNamed(const QString& name, const ClassSkeleton&);
+ void assertDefaultBody(const MethodSkeleton&);
+ ClassSkeleton classFromImplementation(const QByteArray& text);
+ void assertSimpleFooMethod(const ClassSkeleton& cs);
+
+private:
+ DeclarationFactory* m_factory;
+ DocumentAccessStub* m_document;
+ UUTConstructor* m_constructor;
+};
+
+}}
+
+
+#endif // QTEST_UUTCREATIONTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h (revision 1522570)
@@ -0,0 +1,62 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#ifndef VERITAS_CPP_CLASSDECLARATIONFACTORY
+#define VERITAS_CPP_CLASSDECLARATIONFACTORY
+
+#include <QList>
+#include "../veritascppexport.h"
+#include "../parser/control.h"
+
+namespace KDevelop { class ClassDeclaration; class TopDUContext; class DUChainWriteLocker; class Declaration;}
+
+namespace Veritas { namespace Test {
+
+class VERITASCPP_EXPORT DeclarationFactory
+{
+public:
+ DeclarationFactory();
+ virtual ~DeclarationFactory();
+
+ /*! Extract a classdeclaration from a piece of code in @p text.
+ * Try the first declaration, and the first declaration in namespaces.
+ * This method is rather conservative, ie loads of Q_ASSERT's */
+ KDevelop::ClassDeclaration* classFromText(const QByteArray& text);
+
+ QList<KDevelop::Declaration*> variablesFromText(const QByteArray& text);
+ QList<KDevelop::Declaration*> unresolvedVariablesFromText(const QByteArray& text);
+
+ /*! Call this after you are done with a declaration.
+ Cleanup of created topducontexts. */
+ void release();
+
+ KDevelop::DUChainWriteLocker* m_lock;
+
+private:
+ KDevelop::TopDUContext* parseText(const QByteArray& text);
+ static int m_count;
+ Control m_control;
+ QList<KDevelop::TopDUContext*> m_tops;
+};
+
+}}
+
+#endif // VERITAS_CPP_CLASSDECLARATIONFACTORY
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp (revision 1522570)
@@ -0,0 +1,48 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include "classskeletontest.h"
+#include "kdevtest.h"
+#include "../classskeleton.h"
+
+using Veritas::ClassSkeleton;
+using Veritas::Test::ClassSkeletonTest;
+
+void ClassSkeletonTest::init()
+{
+}
+
+void ClassSkeletonTest::cleanup()
+{
+}
+
+void ClassSkeletonTest::construct()
+{
+ ClassSkeleton sc;
+ KVERIFY(sc.isEmpty());
+ KVERIFY(sc.name().isEmpty());
+ KVERIFY(sc.methods().isEmpty());
+ sc.setName("Foo");
+ KOMPARE("Foo", sc.name());
+ KVERIFY(!sc.isEmpty());
+}
+
+QTEST_MAIN( ClassSkeletonTest )
+#include "classskeletontest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h (revision 1522570)
@@ -0,0 +1,41 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef QTEST_STUBCLASSTEST_H_INCLUDED
+#define QTEST_STUBCLASSTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas { namespace Test {
+
+/*! Does not deserve it's own testcase */
+class ClassSkeletonTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void construct();
+};
+
+}}
+
+#endif // QTEST_STUBCLASSTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp (revision 1522570)
@@ -0,0 +1,112 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#include "includewritertest.h"
+#include "kdevtest.h"
+#include "../includewriter.h"
+
+using Veritas::Test::IncludeWriterTest;
+using Veritas::IncludeSerializer;
+using Veritas::IncludeGuardSerializer;
+
+QString IncludeWriterTest::construct(const QString included, const QString includer)
+{
+ QBuffer buff;
+ IncludeSerializer is;
+ is.write(included, includer, &buff);
+ return QString(buff.data());
+}
+
+void IncludeWriterTest::sameDir()
+{
+ QString included("/path/to/foo.h");
+ QString includer("/path/to/bar.h");
+
+ QString actual = construct(included, includer);
+ QString expected = "#include \"foo.h\"";
+
+ assertAlike(expected, actual);
+}
+
+void IncludeWriterTest::oneDirUp()
+{
+ QString included("/path/to/foo.h");
+ QString includer("/path/to/more/bar.h");
+
+ QString actual = construct(included, includer);
+ QString expected = "#include \"../foo.h\"";
+
+ assertAlike(expected, actual);
+}
+
+void IncludeWriterTest::oneDirDown()
+{
+ QString included("/path/to/more/foo.h");
+ QString includer("/path/to/bar.h");
+
+ QString actual = construct(included, includer);
+ QString expected = "#include \"more/foo.h\"";
+
+ assertAlike(expected, actual);
+}
+
+void IncludeWriterTest::guards()
+{
+ QBuffer buff;
+ IncludeGuardSerializer igs;
+ QString filename("/path/to/foo.h");
+
+ igs.writeOpen(filename, &buff);
+ QString actual = QString(buff.data());
+ QString expected("#ifndef PATH_TO_FOO_H_INCLUDED\n#define PATH_TO_FOO_H_INCLUDED");
+
+ assertAlike(expected, actual);
+
+ QBuffer buff2;
+ igs.writeClose(filename, &buff2);
+ actual = QString(buff2.data());
+ expected = QString("#endif // PATH_TO_FOO_H_INCLUDED");
+
+ assertAlike(expected, actual);
+}
+
+////////////////////// Helpers ///////////////////////////////////////////////
+
+/*! Construct a regular expression that is tolerant on
+spaces, newlines tabs etc */
+QRegExp IncludeWriterTest::whiteSpaceRegex(const QString& text)
+{
+ QString ws("[\\s\\n\\r\\t]*");
+ QString escaped = QRegExp::escape(text);
+ return QRegExp(ws + escaped + ws);
+}
+
+// custom assertion
+void IncludeWriterTest::assertAlike(const QString& expected, const QString& actual)
+{
+ QRegExp pattern = whiteSpaceRegex(expected);
+ KVERIFY_MSG(pattern.isValid(), pattern.errorString() + " " +pattern.pattern());
+ QString failMsg = QString("\nExpected:\n%1\nActual:\n%2").arg(expected).arg(actual);
+ KVERIFY_MSG(pattern.exactMatch(actual), failMsg);
+}
+
+QTEST_MAIN( IncludeWriterTest )
+#include "includewritertest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp (revision 1522570)
@@ -0,0 +1,52 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include "methodskeletontest.h"
+#include "kdevtest.h"
+#include "../methodskeleton.h"
+
+using Veritas::Test::MethodSkeletonTest;
+using Veritas::MethodSkeleton;
+
+void MethodSkeletonTest::init()
+{
+}
+
+void MethodSkeletonTest::cleanup()
+{
+}
+
+void MethodSkeletonTest::construct()
+{
+ MethodSkeleton ms;
+ KVERIFY(ms.isEmpty());
+ ms.setName("foo");
+ ms.setBody("int i=0;");
+ ms.setArguments("(int j)");
+ ms.setReturnType("int");
+ KVERIFY(!ms.isEmpty());
+ KOMPARE("foo", ms.name());
+ KOMPARE("int i=0;", ms.body());
+ KOMPARE("(int j)", ms.arguments());
+ KOMPARE("int", ms.returnType());
+}
+
+QTEST_MAIN( MethodSkeletonTest )
+#include "methodskeletontest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h (revision 1522570)
@@ -0,0 +1,48 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef QTEST_INCLUDEWRITERTEST_H_INCLUDED
+#define QTEST_INCLUDEWRITERTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+#include <QString>
+#include <QRegExp>
+
+namespace Veritas { namespace Test {
+
+/*! @unitundertest Veritas::IncludeSerializer */
+class IncludeWriterTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void sameDir();
+ void oneDirUp();
+ void oneDirDown();
+ void guards();
+
+private:
+ QRegExp whiteSpaceRegex(const QString& text);
+ void assertAlike(const QString& expected, const QString& actual);
+ QString construct(const QString included, const QString includer);
+};
+
+}}
+
+#endif // QTEST_INCLUDEWRITERTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp (revision 1522570)
@@ -0,0 +1,50 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include "constructorskeletontest.h"
+#include "kdevtest.h"
+#include "../constructorskeleton.h"
+
+using Veritas::Test::ConstructorSkeletonTest;
+using Veritas::ConstructorSkeleton;
+
+void ConstructorSkeletonTest::init()
+{
+}
+
+void ConstructorSkeletonTest::cleanup()
+{
+}
+
+void ConstructorSkeletonTest::instantiate()
+{
+ ConstructorSkeleton cs;
+ KVERIFY(cs.isEmpty());
+ cs.setName("Foo");
+ cs.setBody("int i=0;");
+ cs.addInitializer("m_i(0)");
+ cs.addInitializer("m_j(1)");
+ KOMPARE("Foo", cs.name());
+ KOMPARE("int i=0;", cs.body());
+ KOMPARE(QStringList() << "m_i(0)" << "m_j(1)", cs.initializerList());
+}
+
+QTEST_MAIN( ConstructorSkeletonTest )
+#include "constructorskeletontest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h (revision 1522570)
@@ -0,0 +1,41 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef QTEST_METHODSKELETONTEST_H_INCLUDED
+#define QTEST_METHODSKELETONTEST_H_INCLUDED
+
+#include <QtCore/QObject>
+
+namespace Veritas { namespace Test {
+
+/*! A bit redundant */
+class MethodSkeletonTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void init();
+ void cleanup();
+
+ void construct();
+};
+
+}}
+
+#endif // QTEST_METHODSKELETONTEST_H_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp (revision 1522570)
@@ -0,0 +1,157 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#include "ktextdocumentstubtest.h"
+
+#include "kdevtest.h"
+
+#include "documentaccessstub.h"
+#include <language/editor/simplerange.h>
+#include <ktexteditor/range.h>
+#include <ktexteditor/cursor.h>
+
+using Veritas::Test::DocumentAccessStubTest;
+using Veritas::Test::DocumentAccessStub;
+using KTextEditor::Range;
+using KTextEditor::Cursor;
+using KDevelop::SimpleRange;
+
+Q_DECLARE_METATYPE(KTextEditor::Range)
+Q_DECLARE_METATYPE(KTextEditor::Cursor)
+
+void DocumentAccessStubTest::init()
+{
+ qRegisterMetaType<Range>();
+ qRegisterMetaType<Cursor>();
+}
+
+void DocumentAccessStubTest::cleanup()
+{
+}
+
+void DocumentAccessStubTest::text()
+{
+ KUrl f;
+ DocumentAccessStub* stub = new DocumentAccessStub;
+ stub->m_text = QString("boo");
+ KOMPARE("boo", stub->text(f));
+
+ stub = new DocumentAccessStub();
+ stub->m_text = "boo\nhoo";
+ KOMPARE("boo\nhoo", stub->text(f));
+}
+
+void DocumentAccessStubTest::textRange_data()
+{
+ QTest::addColumn<QString>("input");
+ QTest::addColumn<Range>("range");
+ QTest::addColumn<QString>("expected");
+
+ QString in("boo\nho\nzoop");
+ QTest::newRow("01") << in << Range(0,0,0,1) << "b";
+ QTest::newRow("02") << in << Range(0,1,0,2) << "o";
+ QTest::newRow("03") << in << Range(0,0,0,3) << "boo";
+ QTest::newRow("04") << in << Range(0,0,1,0) << "boo\n";
+ QTest::newRow("05") << in << Range(1,0,1,2) << "ho";
+ QTest::newRow("06") << in << Range(2,0,2,3) << "zoo";
+ QTest::newRow("07") << in << Range(0,0,1,2) << "boo\nho";
+ QTest::newRow("08") << in << Range(1,1,2,1) << "o\nz";
+ QTest::newRow("09") << in << Range(0,0,2,4) << "boo\nho\nzoop";
+ QTest::newRow("10") << in << Range(2,3,2,4) << "p";
+ QTest::newRow("11") << in << Range(1,2,2,0) << "\n";
+ QTest::newRow("12") << in << Range(0,0,4,0) << in + "\n"; // dont care about trailing newlines
+}
+
+void DocumentAccessStubTest::textRange()
+{
+ QFETCH(QString, expected);
+ DocumentAccessStub* stub = new DocumentAccessStub;
+ QFETCH(QString, input);
+ stub->m_text = input;
+ QFETCH(Range, range);
+ KUrl url;
+ SimpleRange sr(range);
+ QString actual = stub->text(url,sr);
+ KOMPARE(expected, actual);
+}
+
+// void DocumentAccessStubTest::textRangeLines()
+// {
+// DocumentAccessStub* stub = new DocumentAccessStub;
+// stub->m_text = "foo\nbar\nbaz\n";
+// Range range(1,0,1,3);
+// QStringList actual = stub->textLines(range);
+// KOMPARE(QStringList() << "bar", actual);
+// }
+//
+// void DocumentAccessStubTest::character_data()
+// {
+// QTest::addColumn<QString>("input");
+// QTest::addColumn<Cursor>("cursor");
+// QTest::addColumn<QChar>("expected");
+//
+// QString in("boo\nho\nzoap");
+// QTest::newRow("01") << in << Cursor(0,0) << QChar('b');
+// QTest::newRow("02") << in << Cursor(0,1) << QChar('o');
+// QTest::newRow("03") << in << Cursor(0,3) << QChar('\n');
+// QTest::newRow("04") << in << Cursor(1,0) << QChar('h');
+// QTest::newRow("05") << in << Cursor(2,2) << QChar('a');
+// QTest::newRow("06") << in << Cursor(2,3) << QChar('p');
+// }
+//
+// void DocumentAccessStubTest::character()
+// {
+// DocumentAccessStub* stub = new DocumentAccessStub;
+// QFETCH(QString, input);
+// stub->m_text = input;
+// QFETCH(Cursor, cursor);
+// QChar actual = stub->character(cursor);
+// QFETCH(QChar, expected);
+// KOMPARE(expected, actual);
+// }
+//
+// void DocumentAccessStubTest::line_data()
+// {
+// QTest::addColumn<QString>("input");
+// QTest::addColumn<int>("line");
+// QTest::addColumn<QString>("expected");
+//
+// QString in("boo\nho\nzoap\n\n");
+// QTest::newRow("01") << in << 0 << "boo\n";
+// QTest::newRow("02") << in << 1 << "ho\n";
+// QTest::newRow("03") << in << 2 << "zoap\n";
+// QTest::newRow("04") << in << 3 << "\n";
+// }
+//
+// void DocumentAccessStubTest::line()
+// {
+// DocumentAccessStub* stub = new DocumentAccessStub;
+// QFETCH(QString, input);
+// stub->m_text = input;
+// QFETCH(int, line);
+// QString actual = stub->line(line);
+// QFETCH(QString, expected);
+// KOMPARE(expected, actual);
+// }
+
+
+QTEST_MAIN( DocumentAccessStubTest )
+#include "ktextdocumentstubtest.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt (revision 1522570)
@@ -0,0 +1,39 @@
+remove_definitions( -DKDE_DEFAULT_DEBUG_AREA=9007 )
+add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
+
+include_directories(
+ ${cpp_SOURCE_DIR}
+ ${cpp_BINARY_DIR})
+
+#add_subdirectory(tests)
+
+########### next target ###############
+
+set(veritascppsupport_LIB_SRCS
+ testswitch.cpp
+ classskeleton.cpp
+ constructorskeleton.cpp
+ methodskeleton.cpp
+ stubconstructor.cpp
+ classwriter.cpp
+ stubcontextaction.cpp
+ uutconstructor.cpp
+ documentaccess.cpp
+ uutcontextaction.cpp
+ tests/classdeclarationfactory.cpp
+)
+
+# Note: This library doesn't follow API/ABI/BC rules and shouldn't have a SOVERSION
+# Its only purpose is to support the plugin without needing to add all source files
+# to the plugin target
+
+kde4_add_library(veritascpp SHARED ${veritascppsupport_LIB_SRCS})
+target_link_libraries(veritascpp
+ kdev4cppduchain
+ kdev4cppparser
+ kdev4cpprpp
+ ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
+ ${KDEVPLATFORM_INTERFACES_LIBRARIES}
+ ${KDE4_KTEXTEDITOR_LIBS})
+install(TARGETS veritascpp ${INSTALL_TARGETS_DEFAULT_ARGS})
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h (revision 1522570)
@@ -0,0 +1,48 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef VERITASCPP_CONSTRUCTORSKELETON_INCLUDED
+#define VERITASCPP_CONSTRUCTORSKELETON_INCLUDED
+
+#include "veritascppexport.h"
+#include <QStringList>
+#include "methodskeleton.h"
+
+namespace Veritas
+{
+
+/*! Value class which stores a simplified AST for constructors methods */
+class VERITASCPP_EXPORT ConstructorSkeleton : public MethodSkeleton
+{
+public:
+ ConstructorSkeleton();
+ virtual ~ConstructorSkeleton();
+
+ void addInitializer(const QString&);
+ QStringList initializerList() const;
+
+private:
+ QStringList m_initializerList;
+};
+
+}
+
+#endif // VERITASCPP_METHODSKELETON_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp (revision 1522570)
@@ -0,0 +1,62 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "documentaccess.h"
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/idocument.h>
+#include <ktexteditor/document.h>
+
+using Veritas::DocumentAccess;
+using namespace KDevelop;
+
+DocumentAccess::DocumentAccess(QObject* parent)
+ : QObject(parent)
+{}
+
+DocumentAccess::~DocumentAccess()
+{}
+
+KTextEditor::Document* documentForUrl(const KUrl& url)
+{
+ ICore* c = ICore::self();
+ IDocumentController* dc = c->documentController();
+ IDocument* doc = dc->documentForUrl(url);
+ if (!doc || !doc->isTextDocument() ) return 0;
+ KTextEditor::Document* tdoc = doc->textDocument();
+ return tdoc;
+}
+
+QString DocumentAccess::text(const KUrl& url, const KDevelop::SimpleRange& range) const
+{
+ KTextEditor::Document* tdoc = documentForUrl(url);
+ if (!tdoc) return QString();
+ return tdoc->text(range.textRange());
+}
+
+QString DocumentAccess::text(const KUrl& url) const
+{
+ KTextEditor::Document* tdoc = documentForUrl(url);
+ if (!tdoc) return QString();
+ return tdoc->text();
+}
+
+#include "documentaccess.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.cpp (revision 1522570)
@@ -0,0 +1,374 @@
+/*
+ * KDevelop xUnit test support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "testswitch.h"
+
+#include <KAction>
+#include <KActionCollection>
+#include <KLocale>
+#include <QFileInfo>
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+// kdevplatform includes
+#include <interfaces/icore.h>
+#include <interfaces/idocument.h>
+#include <interfaces/idocumentcontroller.h>
+#include <language/backgroundparser/backgroundparser.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/ducontext.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/indexedstring.h>
+#include <language/duchain/use.h>
+#include <language/duchain/duchain.h>
+#include <language/editor/simplecursor.h>
+#include <language/duchain/parsingenvironment.h>
+#include <language/duchain/persistentsymboltable.h>
+
+// kdevelop includes
+#include "../cpputils.h"
+#include "../cppduchain/cppduchain.h"
+#include "../cppduchain/environmentmanager.h"
+#include "../cppduchain/cpppreprocessenvironment.h"
+
+using Veritas::TestSwitch;
+using namespace KDevelop;
+
+namespace
+{
+
+IDocument* activeDocument()
+{
+ ICore* core = ICore::self();
+ IDocumentController* dc = core->documentController();
+ IDocument* doc = dc->activeDocument();
+ if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
+ return 0;
+ } else {
+ return doc;
+ }
+}
+
+QStringList headerExtensions(QString("h,H,hh,hxx,hpp,tlh,h++").split(','));
+bool isHeader(const KUrl& url)
+{
+ QFileInfo fi(url.toLocalFile());
+ return headerExtensions.contains(fi.suffix());
+}
+
+/*! check if ctx contains a qExec() call */
+bool hasQExecInvocation(DUContext* ctx, TopDUContext* top)
+{
+ const Use* u = ctx->uses();
+ Declaration* d;
+ Identifier qExec("qExec");
+ for(int i=0; i<ctx->usesCount(); i++, u++) {
+ d = top->usedDeclarationForIndex(u->m_declarationIndex);
+ if (!d || !d->isFunctionDeclaration()) continue;
+ if (d->identifier() == qExec) return true;
+ }
+ return false;
+}
+
+/*! find a main() declaration */
+DUContext* findMainContext(TopDUContext* ctx)
+{
+ Identifier main("main");
+ QList<Declaration*> dcls = ctx->findDeclarations(main);
+ Declaration* d = 0;
+ foreach(Declaration* d2, dcls) {
+ if (d2->isFunctionDeclaration() && d2->isDefinition()) {
+ d = d2;
+ break;
+ } else {
+ }
+ }
+ if(d)
+ return d->internalContext();
+ else
+ return 0;
+}
+
+/*! return true if ctx contains a QTest main function (expanded QTEST_MAIN macro) */
+bool hasQTestMainFunction(TopDUContext* ctx)
+{
+ DUContext* mainCtx = findMainContext(ctx);
+ if (!mainCtx) return false; // no main() present
+ return hasQExecInvocation(mainCtx, ctx);
+}
+
+Declaration* mostFrequentClass(const QMap<Declaration*, int>& classes)
+{
+ int maxCount = -1;
+ Declaration* max = 0;
+ QMapIterator<Declaration*, int> it(classes);
+ while (it.hasNext()) {
+ it.next();
+ if (it.value() > maxCount) {
+ maxCount = it.value();
+ max = it.key();
+ }
+ }
+ return max;
+}
+
+/*! Try to fetch the owner class declaration for a member function */
+Declaration* isMemberFunctionDefinition(Declaration* decl)
+{
+ if (!decl->isFunctionDeclaration() || !decl->isDefinition()) {
+ return 0; // not a member defintion
+ }
+ return Cpp::localClassFromCodeContext(decl->internalContext());
+}
+
+/*! Increment the class count for @param clazz */
+void updateClassCount(Declaration* clazz, QMap<Declaration*,int>& classes)
+{
+ if (!classes.contains(clazz)) {
+ classes[clazz] = 0;
+ }
+ classes[clazz] += 1;
+ kDebug() << "Incremented member definition count for " << clazz->toString();
+}
+
+/*! Calculates the class with the highest number of member function
+ implementations in context ctx */
+Declaration* dominantClassInCpp(TopDUContext* ctx)
+{
+ kDebug() << "";
+ QMap<Declaration*, int> classes;
+ foreach(Declaration* d, ctx->localDeclarations()) {
+ if (Declaration* const clazz = isMemberFunctionDefinition(d)) {
+ updateClassCount(clazz, classes);
+ }
+ }
+ return mostFrequentClass(classes);
+}
+
+/*! Increment the class count for the owner class of context @param ctx */
+void updateClassMemberCountFor(DUContext* ctx, QMap<Declaration*,int>& classes)
+{
+ Declaration* clazz = ctx->owner();
+ if (!classes.contains(clazz)) classes[clazz] = 0;
+ int& count = classes[clazz];
+ foreach(Declaration* d, ctx->localDeclarations()) {
+ if (d->isFunctionDeclaration()) {
+ count += 1;
+ }
+ }
+}
+
+/*! recursive functions which traverses ctx for classes and updates the
+ member counts in the classes map */
+void computeClassMemberCount(DUContext* parent, QMap<Declaration*,int>& classes)
+{
+ foreach(DUContext* child, parent->childContexts()){
+ switch(child->type()) {
+ case DUContext::Class: {
+ updateClassMemberCountFor(child, classes); break;
+ } case DUContext::Namespace: {
+ computeClassMemberCount(child, classes); break;
+ } default: {}
+ }
+ }
+}
+
+/*! Calculates the class with the highest number of member function
+ declarations in context ctx */
+Declaration* dominantClassInHeader(TopDUContext* ctx)
+{
+ kDebug() << "";
+ QMap<Declaration*, int> classes;
+ computeClassMemberCount(ctx, classes);
+ kDebug() << "classes_" << classes;
+ return mostFrequentClass(classes);
+}
+
+bool isTest(Declaration* clazz)
+{
+ QualifiedIdentifier qid = clazz->qualifiedIdentifier();
+ return qid.toString().endsWith("Test"); //|| hasQTestMainFunction(docCtx);
+}
+
+QualifiedIdentifier getUnitUnderTestIdFor(Declaration* testClass)
+{
+ QString qidStr(testClass->qualifiedIdentifier().toString());
+ qidStr.chop(4); // truncate 'Test'
+ QualifiedIdentifier uutQid(qidStr);
+ return uutQid;
+}
+
+QualifiedIdentifier getTestIdFor(Declaration* uutClass)
+{
+ QString qidStr(uutClass->qualifiedIdentifier().toString());
+ QualifiedIdentifier testQid(qidStr + "Test");
+ return testQid;
+}
+
+KUrl findTargetLocation(QualifiedIdentifier target)
+{
+ kDebug() << "Querying persistent symbol table for " << target.toString();
+ PersistentSymbolTable& pst = PersistentSymbolTable::self();
+ const IndexedDeclaration* matches;
+ uint count;
+ pst.declarations(target, count, matches);
+ KUrl url;
+/* if (count > 0) {
+ url = KUrl(matches->declaration()->url().str());
+ }*/
+ for(uint i=0; i<count; ++i, ++matches) {
+ Declaration* matched = matches->declaration();
+ if (!matched || matched->url().isEmpty()) continue;
+ kDebug() << "matched " << matched->toString() << " " << matched->url().str();
+ if (!matched->isForwardDeclaration()) {
+ url = KUrl(matches->declaration()->url().str());
+ }
+ }
+ return url;
+}
+
+/*! Parse doc string @p comment for @p key and extract it's argument.
+ Return default string if not found. */
+QString extractArgumentFromDocs(const QString& key, const QString& comment)
+{
+ kDebug() << key;
+ int i = comment.indexOf(key);
+ if (i==-1) return QString();
+ QString rest = comment.mid(i + 1 + QString(key).count()); // +1 is for space
+ QStringList spl = rest.split(' ', QString::SkipEmptyParts);
+ rest = spl[0];
+ if (rest.contains("\n") || rest.contains("*")) {
+ return QString();
+ } else {
+ return rest;
+ }
+}
+
+KUrl resolveTargetUrl(QualifiedIdentifier& target)
+{
+ KUrl targetUrl = findTargetLocation(target);
+ if (targetUrl.isEmpty() && target.count() > 1) {
+ // try without namespaces
+ QualifiedIdentifier qid(target.last().toString());
+ targetUrl = findTargetLocation(qid);
+ }
+ if (targetUrl.isEmpty() && target.count() > 2) {
+ // given foo::baz::Bar try foo::Bar
+ QualifiedIdentifier qid(target.first().toString());
+ qid += QualifiedIdentifier(target.last().toString());
+ targetUrl = findTargetLocation(qid);
+ }
+ return targetUrl;
+}
+
+} // end anonymous namespace
+
+TestSwitch::TestSwitch(QObject* parent)
+ : QObject(parent), m_actionConnected(false), m_standardMacros(0), m_buzzySwitching(false)
+{}
+
+TestSwitch::~TestSwitch()
+{}
+
+void TestSwitch::connectAction(KActionCollection* col)
+{
+ if (m_actionConnected) return;
+ KAction* a = col->addAction("switch_test_unitundertest");
+ a->setText( i18n("&Switch Test/Unit Under Test") );
+ a->setShortcut( Qt::CTRL | Qt::SHIFT | Qt::Key_R );
+ connect(a, SIGNAL(triggered()),
+ this, SLOT(swapTest_UnitUnderTest()));
+ m_actionConnected = true;
+}
+
+
+void TestSwitch::setStandardMacros(Cpp::ReferenceCountedMacroSet* macros)
+{
+ m_standardMacros = macros;
+}
+
+TopDUContext* TestSwitch::documentContextFor(const KUrl& url)
+{
+ CppPreprocessEnvironment* env = new CppPreprocessEnvironment(0, Cpp::EnvironmentFilePointer());
+ if (m_standardMacros) env->merge(*m_standardMacros);
+ DUChain* chainStore = DUChain::self();
+ TopDUContext* docCtx = chainStore->chainForDocument(url, env);
+ delete env;
+ if(docCtx && docCtx->parsingEnvironmentFile() && docCtx->parsingEnvironmentFile()->isProxyContext()) {
+ if(!docCtx->importedParentContexts().isEmpty()) {
+ docCtx = dynamic_cast<TopDUContext*>(docCtx->importedParentContexts().first().context(0));
+ }
+ }
+ return docCtx;
+}
+
+#define STOP_IF(X, MSG) \
+ if (X) { kDebug() << MSG; m_buzzySwitching = false; return; }
+
+void TestSwitch::swapTest_UnitUnderTest()
+{
+ if (m_buzzySwitching) return;
+ m_buzzySwitching = true;
+ kDebug() << "Switching between test and unit under test";
+ IDocument* doc = activeDocument();
+ STOP_IF(!doc, "Can't switch, no active document.")
+
+ DUChainReadLocker lock(DUChain::lock());
+ TopDUContext* docCtx = documentContextFor(doc->url());
+ STOP_IF(!docCtx, QString("Failed to get chain for %1").arg(doc->url().toLocalFile()))
+
+ Declaration* clazz = (isHeader(doc->url())) ?
+ dominantClassInHeader(docCtx) :
+ dominantClassInCpp(docCtx);
+ STOP_IF(!clazz, "No dominant class found.")
+ kDebug() << "Dominant Class >> " << clazz->toString();
+
+ QString dox = clazz->comment(), docTarget;
+ kDebug() << "DOX\n" << dox;
+ if (dox.contains("@unitundertest")) {
+ docTarget = extractArgumentFromDocs("@unitundertest", dox);
+ } else if (dox.contains("@unittest")) {
+ docTarget = extractArgumentFromDocs("@unittest", dox);
+ }
+
+ QualifiedIdentifier target; // the class to load
+ if (!docTarget.isEmpty()) {
+ target = QualifiedIdentifier(docTarget);
+ } else { // resort to naming conventions
+ target = (isTest(clazz)) ?
+ getUnitUnderTestIdFor(clazz) :
+ getTestIdFor(clazz);
+ }
+ KUrl targetUrl = resolveTargetUrl(target);
+ lock.unlock();
+
+ if (!targetUrl.isEmpty()) {
+ kDebug() << "Found test/uut in " << targetUrl;
+ IDocumentController* dc = ICore::self()->documentController();
+ dc->openDocument(targetUrl);
+ } else {
+ kDebug() << "Failed to find switch candidate for " << doc->url();
+ }
+ m_buzzySwitching = false;
+}
+
+#include "testswitch.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.cpp (revision 1522570)
@@ -0,0 +1,110 @@
+/*
+ * KDevelop xUnit testing support
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "classwriter.h"
+#include "classskeleton.h"
+#include "constructorskeleton.h"
+#include "methodskeleton.h"
+#include <QIODevice>
+#include <QTextStream>
+
+using Veritas::ClassSerializer;
+using Veritas::ClassSkeleton;
+using Veritas::ConstructorSkeleton;
+using Veritas::MethodSkeleton;
+
+namespace
+{
+
+const QString INDENT = " ";
+QString indent() { return INDENT; }
+
+void intro(const ClassSkeleton& source, QTextStream& str)
+{
+ QStringList qualifiedName = source.name().split("::");
+ Q_ASSERT(qualifiedName.size()>=1);
+ for (int i=0; i<qualifiedName.size()-1;i++) {
+ str << "\nnamespace " << qualifiedName[i] << " {";
+ }
+ str << "\nclass " << qualifiedName.last();
+ if (!source.super().isEmpty()) {
+ str << " : public " << source.super();
+ }
+ str << "\n" << "{\n";
+}
+
+void writeConstructor(const ConstructorSkeleton& ctr, QTextStream& str)
+{
+ if(ctr.isEmpty()) return;
+ str << indent() << ctr.name() << "() ";
+ QStringList inits = ctr.initializerList();
+ if (inits.count()!=0) str << ": ";
+ for(int i=0; i<inits.count(); i++) {
+ str << inits[i];
+ if (i!=inits.count()-1) str << ", ";
+ }
+ str << " {}\n";
+}
+
+void writeDestructor(const MethodSkeleton& destr, QTextStream& str)
+{
+ if (!destr.isEmpty()) {
+ str << indent() << "virtual " << destr.name() << "() {}\n";
+ }
+}
+
+void writeMethod(const MethodSkeleton& mtd, QTextStream& str)
+{
+ QString const_ = mtd.isConst() ? " const " : "";
+ str << indent() << "virtual " << mtd.returnType()
+ << " " << mtd.name() << mtd.arguments() << const_ << " {\n";
+ foreach(const QString& line, mtd.body().split('\n', QString::SkipEmptyParts)) {
+ str << indent() << indent() << line << "\n";
+ }
+ str << indent() << "}\n";
+}
+
+} // end anonymous namespace
+
+void ClassSerializer::write(const ClassSkeleton& source, QIODevice* target)
+{
+ target->open(QIODevice::Append);
+ QTextStream str(target);
+ intro(source, str);
+ if (source.hasSomething()) {
+ str << "public:\n";
+ writeConstructor(source.constructor(), str);
+ writeDestructor(source.destructor(), str);
+ foreach(const MethodSkeleton &ms, source.methods()) {
+ writeMethod(ms, str);
+ }
+ for(int i=0; i<source.memberCount(); i++) {
+ str << INDENT << source.member(i) << ";\n";
+ }
+ }
+ str << "};\n";
+ int nrofNamespaces = source.name().split("::").size()-1;
+ for (int i=0; i<nrofNamespaces; i++) {
+ str << "}";
+ }
+ if (nrofNamespaces!=0) str << "\n";
+ target->close();
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.h (revision 1522570)
@@ -0,0 +1,47 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITASCPP_DOCUMENT_ACCESS
+#define VERITASCPP_DOCUMENT_ACCESS
+
+#include <KUrl>
+#include <QtCore/QObject>
+#include <language/editor/simplerange.h>
+#include "veritascppexport.h"
+
+namespace Veritas
+{
+
+/*! Extra layer of indirection to get around ICore, IDocumentController, IDocument and KT::Document
+ dependencies in tests. (and put the shiny new stub generator to good use :> ) */
+class VERITASCPP_EXPORT DocumentAccess : public QObject
+{
+Q_OBJECT
+public:
+ DocumentAccess(QObject* parent=0);
+ virtual ~DocumentAccess();
+ /*! Fetch the text contained in a @param range for a @param url */
+ virtual QString text(const KUrl& url, const KDevelop::SimpleRange& range) const;
+ virtual QString text(const KUrl&) const;
+};
+
+}
+
+#endif // VERITASCPP_DOCUMENT_ACCESS
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/documentaccess.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.h (revision 1522570)
@@ -0,0 +1,62 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef VERITAS_TESTSWITCH_H
+#define VERITAS_TESTSWITCH_H
+
+#include "veritascppexport.h"
+#include "../cppduchain/environmentmanager.h"
+#include <QtCore/QObject>
+
+class KActionCollection;
+class KUrl;
+namespace KDevelop { class TopDUContext; }
+
+namespace Veritas
+{
+
+/*! Adds an action which allows for swapping between a test and its unit
+ under test. */
+class VERITASCPP_EXPORT TestSwitch : public QObject
+{
+Q_OBJECT
+public:
+ TestSwitch(QObject* parent);
+ virtual ~TestSwitch();
+
+ /*! Creates and connects the QAction. Invoke this once. */
+ void connectAction(KActionCollection*);
+ void setStandardMacros(Cpp::ReferenceCountedMacroSet*);
+
+private slots:
+ /*! Connected to the action's triggered() signal */
+ void swapTest_UnitUnderTest();
+
+private:
+ KDevelop::TopDUContext* documentContextFor(const KUrl& url);
+ bool m_actionConnected;
+ Cpp::ReferenceCountedMacroSet* m_standardMacros;
+ bool m_buzzySwitching;
+};
+
+}
+
+#endif // VERITAS_TESTSWITCH_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/testswitch.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:mergeinfo
## -0,0 +0,0 ##
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.h (revision 1522570)
@@ -0,0 +1,42 @@
+/*
+* KDevelop xUnit testing support
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+
+#ifndef VERITAS_CPP_CLASSWRITER_INCLUDED
+#define VERITAS_CPP_CLASSWRITER_INCLUDED
+
+class QIODevice;
+#include "veritascppexport.h"
+
+namespace Veritas
+{
+class ClassSkeleton;
+
+/*! @unittest Veritas::Test::ClassWriterTest */
+class VERITASCPP_EXPORT ClassSerializer
+{
+public:
+ void write(const ClassSkeleton& source, QIODevice* target);
+
+};
+
+}
+
+#endif // VERITAS_CPP_CLASSWRITER_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classwriter.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp (revision 1522570)
@@ -0,0 +1,129 @@
+/*
+ * KDevelop xUnit test support
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "classskeleton.h"
+
+using Veritas::ClassSkeleton;
+using Veritas::ConstructorSkeleton;
+using Veritas::MethodSkeleton;
+
+ClassSkeleton::ClassSkeleton()
+ : m_empty(true)
+{}
+
+ClassSkeleton::~ClassSkeleton()
+{}
+
+bool ClassSkeleton::isEmpty() const
+{
+ return m_empty;
+}
+
+QString ClassSkeleton::name() const
+{
+ return m_name;
+}
+
+void ClassSkeleton::setName(const QString& name)
+{
+ m_empty = false;
+ m_name = name;
+}
+
+void ClassSkeleton::addMethod(const MethodSkeleton& mtd)
+{
+ m_methods << mtd;
+}
+
+ConstructorSkeleton ClassSkeleton::constructor() const
+{
+ return m_constructor;
+}
+
+MethodSkeleton ClassSkeleton::destructor() const
+{
+ return m_destructor;
+}
+
+QList<MethodSkeleton> ClassSkeleton::methods() const
+{
+ return m_methods;
+}
+
+void ClassSkeleton::setConstructor(const ConstructorSkeleton& ctr)
+{
+ m_constructor = ctr;
+}
+
+void ClassSkeleton::setDestructor(const MethodSkeleton& dtr)
+{
+ m_destructor = dtr;
+}
+
+int ClassSkeleton::memberCount() const
+{
+ return m_members.count();
+}
+
+QString ClassSkeleton::member(int i) const
+{
+ return m_members.value(i);
+}
+
+void ClassSkeleton::addMember(const QString& member)
+{
+ m_members << member;
+}
+
+bool ClassSkeleton::hasMethods() const
+{
+ return m_methods.count()!=0;
+}
+
+bool ClassSkeleton::hasMembers() const
+{
+ return memberCount()!=0;
+}
+
+bool ClassSkeleton::hasConstructor() const
+{
+ return !constructor().isEmpty();
+}
+
+bool ClassSkeleton::hasDestructor() const
+{
+ return !destructor().isEmpty();
+}
+
+bool ClassSkeleton::hasSomething() const
+{
+ return hasMembers() || hasMethods() || hasConstructor() || hasDestructor();
+}
+
+void ClassSkeleton::addSuper(const QString& super)
+{
+ m_super = super;
+}
+
+QString ClassSkeleton::super() const
+{
+ return m_super;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.h (revision 1522570)
@@ -0,0 +1,76 @@
+/*
+ * KDevelop xUnit test support
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef VERITAS_CLASSSKELETON_INCLUDED_H
+#define VERITAS_CLASSSKELETON_INCLUDED_H
+
+#include <QtCore/QString>
+#include "veritascppexport.h"
+#include "constructorskeleton.h"
+#include "methodskeleton.h"
+
+namespace Veritas
+{
+
+/*! Lightweight struct which stores C++ Class information (simple AST)
+ * It is intended to be used for code generation. */
+class VERITASCPP_EXPORT ClassSkeleton
+{
+public:
+ ClassSkeleton();
+ virtual ~ClassSkeleton();
+
+ bool isEmpty() const;
+
+ QString name() const;
+ QString super() const;
+ ConstructorSkeleton constructor() const;
+ MethodSkeleton destructor() const;
+ QList<MethodSkeleton> methods() const;
+
+ void addSuper(const QString&);
+ void setName(const QString&);
+ void setConstructor(const ConstructorSkeleton&);
+ void setDestructor(const MethodSkeleton&);
+ void addMethod(const MethodSkeleton&);
+
+ int memberCount() const;
+ QString member(int i) const;
+ void addMember(const QString&);
+
+ bool hasMethods() const;
+ bool hasMembers() const;
+ bool hasConstructor() const;
+ bool hasDestructor() const;
+ bool hasSomething() const;
+
+private:
+ QString m_name;
+ QList<MethodSkeleton> m_methods;
+ bool m_empty;
+ ConstructorSkeleton m_constructor;
+ MethodSkeleton m_destructor;
+ QList<QString> m_members;
+ QString m_super;
+};
+
+}
+
+#endif // VERITAS_CLASSSKELETON_INCLUDED_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/classskeleton.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp (revision 1522570)
@@ -0,0 +1,159 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stubcontextaction.h"
+#include "stubconstructor.h"
+#include "classwriter.h"
+#include "includewriter.h"
+#include "classskeleton.h"
+
+#include <KAction>
+#include <KDebug>
+#include <KLocale>
+#include <QFile>
+#include <QDir>
+#include <QInputDialog>
+#include <QFileInfo>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+// kdevplatform
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/context.h>
+#include <interfaces/contextmenuextension.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainutils.h>
+#include <language/editor/simplecursor.h>
+#include <language/interfaces/editorcontext.h>
+#include <language/duchain/duchainlock.h>
+
+// kdevelop
+#include <language/duchain/classdeclaration.h>
+
+using Veritas::ClassSkeleton;
+using Veritas::ClassSerializer;
+using Veritas::StubConstructor;
+using Veritas::IncludeSerializer;
+using Veritas::IncludeGuardSerializer;
+using Veritas::StubContextAction;
+using namespace KDevelop;
+
+namespace
+{
+QString activeUrl()
+{
+ ICore* core = ICore::self();
+ IDocumentController* dc = core->documentController();
+ IDocument* doc = dc->activeDocument();
+ if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
+ return "";
+ } else {
+ return doc->url().toLocalFile();
+ }
+}
+
+QString stubUrl()
+{
+ ICore* core = ICore::self();
+ IDocumentController* dc = core->documentController();
+ IDocument* doc = dc->activeDocument();
+ if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
+ return "";
+ } else {
+ QFileInfo fi(doc->url().toLocalFile());
+ return fi.absolutePath() + QDir::separator() + fi.baseName() + "stub." + fi.completeSuffix();
+ }
+}
+
+} // end anonymous namespace
+
+StubContextAction::StubContextAction(QObject* parent)
+ : QObject(parent), m_clazz(0), m_constructStub(0)
+{
+}
+
+/*! initialization */
+void StubContextAction::setup()
+{
+ Q_ASSERT(m_clazz == 0); Q_ASSERT(m_constructStub == 0);
+ m_constructStub = new KAction(this);
+ m_constructStub->setText(i18n("Generate Stub Class"));
+ connect(m_constructStub, SIGNAL(triggered()), this, SLOT(constructStub()));
+ Q_ASSERT(m_constructStub);
+}
+
+void StubContextAction::constructStub()
+{
+ Q_ASSERT(m_constructStub);
+ if (!m_clazz) return;
+
+ bool owk;
+ QString url;
+ QString current = activeUrl();
+ url = QInputDialog::getText(
+ 0, i18n("Generate Stub"),
+ i18n("Save to "), QLineEdit::Normal,
+ stubUrl(), &owk);
+ if (!owk || url.isEmpty() || QFile::exists(url)) return;
+
+ QFile target(url);
+ IncludeGuardSerializer().writeOpen(url, &target);
+ IncludeSerializer().write(current, url, &target);
+ ClassSkeleton cs = StubConstructor().morph(m_clazz);
+ ClassSerializer().write(cs, &target);
+ IncludeGuardSerializer().writeClose(url, &target);
+
+ ICore::self()->documentController()->openDocument(KUrl(url));
+}
+
+StubContextAction::~StubContextAction()
+{}
+
+#define STOP_IF(X) \
+ if (X) { m_clazz = 0; return; }\
+ else (void)0
+
+void StubContextAction::appendTo(ContextMenuExtension& menu, Context* context)
+{
+ KDevelop::ContextMenuExtension cm;
+ STOP_IF(context->type() != Context::EditorContext);
+
+ EditorContext* ec = dynamic_cast<EditorContext*>(context);
+ STOP_IF(!ec);
+
+ DUChainWriteLocker lock(DUChain::lock());
+ ///@todo this isn't neede any more, the context contains the information
+ SimpleCursor sc(ec->position());
+ Declaration* dcl = DUChainUtils::itemUnderCursor(ec->url(), sc);
+ STOP_IF(!dcl);
+ STOP_IF(dcl->kind() != Declaration::Type);
+
+ ClassDeclaration* clazz = dynamic_cast<ClassDeclaration*>(dcl);
+ STOP_IF(!clazz);
+
+ m_clazz = clazz;
+ menu.addAction(ContextMenuExtension::ExtensionGroup, m_constructStub);
+ Q_ASSERT(m_clazz);
+}
+
+#include "stubcontextaction.moc"
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp (revision 1522570)
@@ -0,0 +1,160 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "uutcontextaction.h"
+#include "uutconstructor.h"
+#include "classwriter.h"
+#include "includewriter.h"
+#include "classskeleton.h"
+#include "documentaccess.h"
+
+#include <KAction>
+#include <KDebug>
+#include <KLocale>
+#include <QFile>
+#include <QDir>
+#include <QInputDialog>
+#include <QFileInfo>
+
+#include <ktexteditor/document.h>
+#include <ktexteditor/view.h>
+
+// kdevplatform
+#include <interfaces/icore.h>
+#include <interfaces/idocumentcontroller.h>
+#include <interfaces/context.h>
+#include <interfaces/contextmenuextension.h>
+#include <language/duchain/declaration.h>
+#include <language/duchain/duchainutils.h>
+#include <language/editor/simplecursor.h>
+#include <language/duchain/duchainlock.h>
+#include <language/interfaces/editorcontext.h>
+
+// kdevelop
+#include <language/duchain/classdeclaration.h>
+
+using Veritas::ClassSkeleton;
+using Veritas::ClassSerializer;
+using Veritas::IncludeGuardSerializer;
+using Veritas::UUTConstructor;
+using Veritas::UUTContextAction;
+using Veritas::DocumentAccess;
+using namespace KDevelop;
+
+namespace
+{
+QString activeUrl()
+{
+ ICore* core = ICore::self();
+ IDocumentController* dc = core->documentController();
+ IDocument* doc = dc->activeDocument();
+ if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
+ return "";
+ } else {
+ QFileInfo fi(doc->url().toLocalFile());
+ return fi.absolutePath() + QDir::separator() + fi.baseName() + "gen." + fi.completeSuffix();
+ }
+}
+} // end anonymous namespace
+
+UUTContextAction::UUTContextAction(QObject* parent)
+ : QObject(parent), m_clazz(0), m_createImplementation(0), m_constructor(0)
+{}
+
+void UUTContextAction::setup()
+{
+ Q_ASSERT(m_clazz == 0); Q_ASSERT(m_createImplementation == 0); Q_ASSERT(m_constructor == 0);
+ m_createImplementation = new KAction(this);
+ m_createImplementation->setText(i18n("Generate Unit Under Test"));
+ connect(m_createImplementation, SIGNAL(triggered()),
+ this, SLOT(createImplementation()));
+ DocumentAccess* docAccess = new DocumentAccess(this);
+ m_constructor = new UUTConstructor;
+ m_constructor->setDocumentAccess(docAccess);
+ Q_ASSERT(m_createImplementation && m_constructor);
+}
+
+void UUTContextAction::createImplementation()
+{
+ Q_ASSERT(m_createImplementation); Q_ASSERT(m_constructor);
+ if (!m_clazz) return;
+
+ bool owk;
+ QString url;
+ url = QInputDialog::getText(
+ 0, i18n("Generate Unit Under Test"),
+ i18n("Save to "), QLineEdit::Normal,
+ activeUrl(), &owk);
+ if (!owk || url.isEmpty() || QFile::exists(url)) return;
+
+ QFile target(url);
+ IncludeGuardSerializer().writeOpen(url, &target);
+ ClassSkeleton cs = m_constructor->morph(m_clazz);
+ ClassSerializer().write(cs, &target);
+ IncludeGuardSerializer().writeClose(url, &target);
+
+ ICore::self()->documentController()->openDocument(KUrl(url));
+}
+
+UUTContextAction::~UUTContextAction()
+{
+ if (m_createImplementation) delete m_createImplementation;
+ if (m_constructor) delete m_constructor;
+}
+
+#define STOP_IF(X) \
+if (X) { m_clazz = 0; return; } \
+else (void)(0)
+
+#define STOP_IF_(X, MSG) \
+if (X) {\
+ m_clazz = 0;\
+ kDebug() << "Not appending UUT action because " << MSG;\
+ return;\
+} else (void)(0)
+
+
+void UUTContextAction::appendTo(ContextMenuExtension& menu, Context* context)
+{
+ Q_ASSERT(m_createImplementation); Q_ASSERT(m_constructor);
+ STOP_IF(context->type() != Context::EditorContext);
+ EditorContext* ec = dynamic_cast<EditorContext*>(context);
+ STOP_IF(!ec);
+
+ DUChainWriteLocker lock(DUChain::lock());
+ SimpleCursor sc(ec->position());
+ ///@todo not needed any more, just take the data out of the context(DeclarationContext)
+ Declaration* decl = DUChainUtils::itemUnderCursor(ec->url(), sc);
+ STOP_IF_(!decl, "no declaration under cursor.");
+ STOP_IF_(decl->kind() != Declaration::Instance, "Not an instance declaration.");
+ STOP_IF_(!decl->isDefinition(), "Not a definition");
+
+ DelayedType::Ptr type = decl->type<DelayedType>();
+ STOP_IF_(!type, "Not a delayed/unresolved type (null)");
+ STOP_IF_(type->kind() != DelayedType::Unresolved, "Not an unresolved type [but delayed]");
+
+ m_clazz = decl;
+ menu.addAction(ContextMenuExtension::ExtensionGroup, m_createImplementation);
+ Q_ASSERT(m_clazz);
+}
+
+#include "uutcontextaction.moc"
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp (revision 1522570)
@@ -0,0 +1,132 @@
+/*
+ * KDevelop xUnit test support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#include "stubconstructor.h"
+
+// kdevplatform
+#include <interfaces/idocument.h>
+#include <language/duchain/duchainutils.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/ducontext.h>
+#include <language/duchain/classfunctiondeclaration.h>
+
+// kdevelop
+#include <language/duchain/classdeclaration.h>
+
+using Veritas::ClassSkeleton;
+using Veritas::MethodSkeleton;
+using Veritas::ConstructorSkeleton;
+using Veritas::StubConstructor;
+using namespace KDevelop;
+
+namespace
+{
+
+/*! Returns true if @param decl is a member function with the following properties:
+ - no constructor nor destructor
+ - virtual
+ - not private
+ - not a Qt meta function */
+QStringList blackList(QString("metaObject,qt_metacast,qt_metacall").split(','));
+ClassFunctionDeclaration* filterMemberFunction(Declaration* decl)
+{
+ ClassFunctionDeclaration* fdcl = dynamic_cast<ClassFunctionDeclaration*>(decl);
+ if (fdcl) {
+ if (fdcl->isDestructor() || fdcl->isConstructor() ||
+ !fdcl->isVirtual() || fdcl->accessPolicy() == Declaration::Private ||
+ blackList.contains(fdcl->identifier().toString())) {
+ return 0;
+ }
+ }
+ return fdcl;
+}
+
+MethodSkeleton fillMethod(ClassFunctionDeclaration* function)
+{
+ MethodSkeleton ms;
+ FunctionType::Ptr type = function->type<FunctionType>();
+ if (!type) { kDebug() << "Erm type == 0"; return ms; }
+ ms.setName(function->identifier().toString());
+ ms.setFunctionType(type);
+ ms.setConst(type->modifiers() & AbstractType::ConstModifier);
+ return ms;
+}
+
+QString stubNameFor(ClassDeclaration* clazz)
+{
+ return clazz->qualifiedIdentifier().toString() + "Stub";
+}
+
+/*! add a data member to the class and return this in method ms.
+ eg: class FooStub { int m_foo; int foo() { return m_foo; } }; */
+void insertFakeMember(const QString& member, MethodSkeleton& ms, ClassSkeleton& cs, ConstructorSkeleton& constr)
+{
+ ms.setBody("return " + member + ';');
+ QString type = ms.returnType();
+ if (type.startsWith("const ")) {
+ type = type.mid(6, -1);
+ }
+ cs.addMember(type + ' ' + member);
+ if (type == "bool") {
+ constr.addInitializer(member + "(false)");
+ } else if (type == "int" || type.contains("*")) {
+ constr.addInitializer(member + "(0)");
+ }
+}
+
+} // end anonymous namespace
+
+StubConstructor::StubConstructor()
+{}
+
+StubConstructor::~StubConstructor()
+{}
+
+ClassSkeleton StubConstructor::morph(ClassDeclaration* clazz)
+{
+ Q_ASSERT(clazz);
+ DUChainReadLocker lock(DUChain::lock());
+
+ QString stubName = stubNameFor(clazz);
+ ClassSkeleton cs; cs.setName(stubName);
+ cs.addSuper(clazz->identifier().toString());
+ ConstructorSkeleton constr; constr.setName(stubName);
+ MethodSkeleton destr; destr.setName('~' + stubName);
+
+ ClassFunctionDeclaration* function;
+ foreach(Declaration* dcl, clazz->internalContext()->localDeclarations()) {
+ function = filterMemberFunction(dcl);
+ if (function) { // construct and add method to the stub
+ MethodSkeleton ms = fillMethod(function);
+ if (ms.returnType() != "void") {
+ QString member = "m_" + ms.name();
+ insertFakeMember(member, ms, cs, constr);
+ }
+ cs.addMethod(ms);
+ }
+ }
+
+ cs.setConstructor(constr);
+ cs.setDestructor(destr);
+ return cs;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp (revision 1522570)
@@ -0,0 +1,291 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#include "uutconstructor.h"
+#include "documentaccess.h"
+
+// kdevplatform
+#include <language/duchain/declaration.h>
+#include <language/editor/simplecursor.h>
+#include <language/duchain/duchain.h>
+#include <language/duchain/use.h>
+#include <language/duchain/topducontext.h>
+#include <language/duchain/duchainlock.h>
+#include <language/duchain/types/delayedtype.h>
+
+#include "../cppduchain/expressionparser.h"
+#include "../cppduchain/expressionevaluationresult.h"
+
+#include <ktexteditor/smartrange.h>
+
+using Veritas::UUTConstructor;
+using Veritas::ClassSkeleton;
+using Veritas::MethodSkeleton;
+using KTextEditor::SmartRange;
+using namespace KDevelop;
+using Cpp::ExpressionParser;
+using Cpp::ExpressionEvaluationResult;
+
+namespace
+{
+
+/*! Debugger helper for types */
+void printTypeInfoFor(Declaration* decl)
+{
+ AbstractType::Ptr atype = decl->type<AbstractType>();
+ if (atype) {
+ kDebug() << "Not an Unresolved type [" << atype->toString()
+ << " " << decl->toString() << "]";
+ } else {
+ kDebug() << "Failed to fetch type for " << decl->toString();
+ }
+}
+
+/*! Serialize @param type to string. Remove any prefixes. */
+QString cleanTypeNameFor(DelayedType::Ptr type)
+{
+ QString strType = type->toString();
+ if (strType.startsWith("<unresolved> ")) {
+ strType = strType.split(' ').last();
+ }
+ return strType;
+}
+
+/*! Fetch the declaration associated with @param use */
+Declaration* declarationForUse(const Use* use, DUContext* ctx)
+{
+ TopDUContext* top = ctx->topContext();
+ int declarationId = use->m_declarationIndex;
+ return top->usedDeclarationForIndex(declarationId);
+}
+
+DelayedType::Ptr isUnresolvedType(Declaration* variable)
+{
+ DelayedType::Ptr type = variable->type<DelayedType>();
+ if (!type || type->kind() != DelayedType::Unresolved) {
+ printTypeInfoFor(variable);
+ type = 0;
+ }
+ return type;
+}
+
+void printAllDeclarations(DUContext* ctx)
+{
+ kDebug() << "";
+ foreach(Declaration* dcl, ctx->localDeclarations()) {
+ kDebug() << dcl->toString();
+ }
+ kDebug() << "";
+}
+
+} // end anonymous namespace
+
+void UUTConstructor::printUseInfo(int useId, const Use* use, DUContext* ctx)
+{
+ Q_UNUSED(useId);
+ Declaration* decl = declarationForUse(use,ctx);
+ if (!decl) return;
+ kDebug() << "decl " << decl->toString();
+ KUrl url(decl->url().str());
+ kDebug() << "useTxt " << m_docAccess->text(url, use->m_range);
+}
+
+ClassSkeleton UUTConstructor::morph(Declaration* variable)
+{
+ Q_ASSERT(variable); Q_ASSERT(m_docAccess);
+ DUChainReadLocker lock(DUChain::lock());
+
+ ClassSkeleton cs;
+ DelayedType::Ptr varType = isUnresolvedType(variable);
+ if (!varType) return cs;
+ cs.setName(cleanTypeNameFor(varType));
+
+ DUContext* ctx = variable->context();
+ printAllDeclarations(ctx);
+ constructMethodsFor(ctx, variable, cs);
+ return cs;
+}
+
+void UUTConstructor::constructMethodsFor(DUContext* ctx, Declaration* classToMorph, ClassSkeleton& cs)
+{
+ const Use* uses = ctx->uses();
+ for(int i=0; i<ctx->usesCount(); i++, uses++) {
+ Declaration* decl = declarationForUse(uses, ctx);
+ printUseInfo(i, uses, ctx);
+ if (decl == classToMorph) {
+ MethodSkeleton ms = createMethod(decl, uses, ctx);
+ if (!ms.isEmpty()) {
+ cs.addMethod(ms);
+ }
+ }
+ }
+ foreach(DUContext* child, ctx->childContexts()) {
+ constructMethodsFor(child, classToMorph, cs);
+ }
+}
+
+
+UUTConstructor::UUTConstructor()
+ : m_docAccess(0)
+{}
+
+UUTConstructor::~UUTConstructor()
+{}
+
+void UUTConstructor::setDocumentAccess(Veritas::DocumentAccess* docAccess)
+{
+ Q_ASSERT(!m_docAccess);
+ m_docAccess = docAccess;
+ Q_ASSERT(m_docAccess);
+}
+
+
+QString UUTConstructor::enoughText(const KUrl& url, const KDevelop::SimpleCursor& cursor) const
+{
+ SimpleCursor ahead(cursor.line+4, 0); // though luck if you smear a use over more than 3 lines.
+ //SimpleCursor ahead(cursor.line, cursor.column+10);
+ SimpleRange farEnough(cursor, ahead);
+ QString txt = m_docAccess->text(url, farEnough);
+ kDebug() << txt;
+ return txt;
+}
+
+namespace
+{
+/*! remove spaces, newlines and stuff after the first semicolon.
+ Also get rid of first '.' or '->' */
+void normalize(QString& text)
+{
+ kDebug() << QString("before ``%1''").arg(text);
+ text.remove(QRegExp("[ \r\n\t]"));
+ int pos = text.indexOf(";");
+ if (pos == -1) {
+ text.clear();
+ kDebug() << QString("after ``%1''").arg(text);
+ return;
+ }
+ text = text.left(pos);
+ if (text.startsWith('.')) {
+ text = text.mid(1, -1);
+ } else if (text.startsWith("->")) {
+ text = text.mid(2, -1);
+ } else {
+ text.clear();
+ }
+ kDebug() << QString("after ``%1''").arg(text);
+}
+
+QString extractMethodName(QString& text)
+{
+ kDebug() << text;
+ int firstBrace = text.indexOf("(");
+ QString methodName = text.left(firstBrace);
+ text = text.mid(firstBrace);
+ return methodName;
+}
+
+QList<int> topLevelCommaPositions(const QString& text)
+{
+ QStack<bool> braces;
+ QList<int> result;
+ if (!text.contains(',')) return result;
+ QString text_ = text.mid(1, text.count()-1);
+ for (int i=0; i<text_.count(); i++) {
+ QChar c = text_[i];
+ if (c == ',') {
+ if (braces.isEmpty()) result << i;
+ } else if (c == '(') {
+ braces.push(true);
+ } else if (c == ')' && !braces.isEmpty()) {
+ braces.pop();
+ }
+ }
+ return result;
+}
+
+QString serializeTypeFromExpression(const QString& expr, DUContext* ctx)
+{
+ ExpressionParser* ep = new ExpressionParser;
+ DUContextPointer p(ctx);
+ TopDUContext* top = ctx->topContext();
+ ExpressionEvaluationResult er = ep->evaluateType(expr.toLatin1(), p, top);
+ delete ep;
+ if (!er.type) {
+ kDebug() << "failed to grab arguments";
+ return QString();
+ }
+ if (er.type.abstractType()->whichType() == AbstractType::TypeFunction) {
+ TypePtr<FunctionType> f = er.type.type<FunctionType>();
+ Q_ASSERT(f); Q_ASSERT(f->returnType());
+ return f->returnType()->toString();
+ } else {
+ return er.type.abstractType()->toString();
+ }
+}
+
+QString extractArguments(QString& text, DUContext* ctx)
+{
+ kDebug() << text;
+ QList<int> commas = topLevelCommaPositions(text);
+ kDebug() << "COMMAS " << commas;
+ if (commas.isEmpty()) {
+ int lastBrace = text.indexOf(')');
+ QString type = serializeTypeFromExpression(text.mid(1, lastBrace), ctx);
+ if (type.isEmpty()) return QString();
+ return QString("(%1)").arg(type);
+ } else {
+ QString args("(");
+ int prev = 1;
+ foreach(int i, commas) {
+ i = i+1;
+ QString expr = text.mid(prev, i);
+ args += serializeTypeFromExpression(expr, ctx) + ", ";
+ prev = i+1;
+ }
+ int lastBrace = text.indexOf(')');
+ args += serializeTypeFromExpression(text.mid(prev, lastBrace), ctx);
+ args += ')';
+ return args;
+ }
+}
+
+} // end anonymous namespace
+
+MethodSkeleton UUTConstructor::createMethod(Declaration* clazz, const Use* use, DUContext* ctx)
+{
+ KUrl doc(clazz->url().str());
+ MethodSkeleton ms;
+ QString text = enoughText(doc, use->m_range.end);
+ normalize(text);
+ if (text.isEmpty()) {
+ kDebug() << "Failed to parser\n" << enoughText(doc, use->m_range.end);
+ return ms;
+ }
+ if (text.contains("(") && text.contains(")")) { // function member use
+ ms.setName(extractMethodName(text));
+ if (!text.startsWith("()")) {
+ ms.setArguments(extractArguments(text, ctx));
+ }
+ ms.setBody("// GENERATED");
+ } else { // data member use. do nothing for now.
+ }
+ return ms;
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp (revision 1522570)
@@ -0,0 +1,100 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include "methodskeleton.h"
+#include <language/duchain/types/functiontype.h>
+
+using Veritas::MethodSkeleton;
+using KDevelop::FunctionType;
+
+MethodSkeleton::MethodSkeleton()
+ : m_empty(true), m_arguments("()"), m_isConst(false)
+{}
+
+MethodSkeleton::~MethodSkeleton()
+{}
+
+void MethodSkeleton::setFunctionType(FunctionType::Ptr fn)
+{
+ m_arguments = fn->partToString(FunctionType::SignatureArguments);
+ m_returnType = fn->partToString(FunctionType::SignatureReturn);
+}
+
+bool MethodSkeleton::isEmpty() const
+{
+ return m_empty;
+}
+
+void MethodSkeleton::setName(const QString& name)
+{
+ m_empty = false;
+ m_name = name;
+}
+
+void MethodSkeleton::setBody(const QString& body)
+{
+ m_body = body;
+}
+
+void MethodSkeleton::setReturnType(const QString& rt)
+{
+ m_returnType = rt;
+}
+
+#include <KDebug>
+
+void MethodSkeleton::setArguments(const QString& sig)
+{
+ m_arguments = sig;
+}
+
+QString MethodSkeleton::name() const
+{
+ return m_name;
+}
+
+QString MethodSkeleton::body() const
+{
+ return m_body;
+}
+
+QString MethodSkeleton::returnType() const
+{
+ if (!isEmpty() && m_returnType.isEmpty()) return "void";
+ return m_returnType;
+}
+
+QString MethodSkeleton::arguments() const
+{
+ if (m_arguments.isEmpty()) {
+ return "()";
+ }
+ return m_arguments;
+}
+
+void MethodSkeleton::setConst(bool isConst)
+{
+ m_isConst = isConst;
+}
+
+bool MethodSkeleton::isConst() const
+{
+ return m_isConst;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/includewriter.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/includewriter.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/includewriter.h (revision 1522570)
@@ -0,0 +1,92 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITAS_CPP_INCLUDEWRITER_H
+#define VERITAS_CPP_INCLUDEWRITER_H
+
+#include <KUrl>
+#include <QTextStream>
+#include <QDir>
+
+namespace Veritas
+{
+
+/*! @unittest Veritas::Test::IncludeWriterTest */
+class IncludeSerializer
+{
+public:
+ void write(const QString& included, const QString& includer, QIODevice* target) {
+ KUrl includedUrl(included);
+ KUrl includerUrl(includer);
+ target->open(QIODevice::Append);
+ QTextStream str(target);
+ if (includedUrl.upUrl() == includerUrl.upUrl()) {
+ str << "#include \"" << includedUrl.fileName() << "\"\n";
+ } else if (includedUrl.upUrl() == includerUrl.upUrl().upUrl()) {
+ str << "#include \"../" << includedUrl.fileName() << "\"\n";
+ } else if (includedUrl.upUrl().upUrl() == includerUrl.upUrl()) {
+ str << "#include \"" << includedUrl.upUrl().fileName() << QDir::separator() << includedUrl.fileName() << "\"\n";
+ } else {
+ int common = 0;
+ while ( common < included.count() && common < includer.count() ) {
+ if (included[common] != includer[common]) {
+ break;
+ }
+ common++;
+ }
+ str << "#include \"" << included.mid(common) << "\"\n";
+ }
+ target->close();
+ }
+};
+
+/*! @unittest Veritas::Test::IncludeWriterTest */
+class IncludeGuardSerializer
+{
+public:
+ void writeOpen(const QString& headerFile, QIODevice* target) {
+ target->open(QIODevice::Append);
+ QTextStream str(target);
+ str << "\n#ifndef " << guard(headerFile)
+ << "\n#define " << guard(headerFile) << "\n\n";
+ target->close();
+ }
+
+ void writeClose(const QString& headerFile, QIODevice* target) {
+ target->open(QIODevice::Append);
+ QTextStream str(target);
+ str << "\n#endif // " << guard(headerFile) << "\n";
+ target->close();
+ }
+
+private:
+ QString guard(const QString& headerFile) {
+ KUrl url(headerFile);
+ QString upUp = url.upUrl().upUrl().fileName().toUpper();
+ QString up = url.upUrl().fileName().toUpper();
+ QString fn = url.fileName().toUpper();
+ fn = fn.replace(".", "_");
+ return upUp + "_" + up + "_" + fn + "_INCLUDED";
+ }
+};
+
+}
+
+#endif // VERITAS_CPP_INCLUDEWRITER_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/includewriter.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h (revision 1522570)
@@ -0,0 +1,63 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
+#define VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
+
+#include "veritascppexport.h"
+#include <QObject>
+
+class KAction;
+namespace KDevelop { class Context; class ContextMenuExtension; }
+namespace KDevelop { class ClassDeclaration; }
+
+namespace Veritas
+{
+
+/*! Provides a context menu action on class declarations which
+ allows for stub code generation.
+ @see Veritas::StubConstructor */
+class VERITASCPP_EXPORT StubContextAction : public QObject
+{
+Q_OBJECT
+public:
+ StubContextAction(QObject* parent=0);
+ ~StubContextAction();
+
+ /*! initialization */
+ void setup();
+
+ /*! Checks if @param context should get an uut action and adds it to
+ @param menu if so. Otherwise nothing happens. */
+ void appendTo(KDevelop::ContextMenuExtension& menu, KDevelop::Context* context);
+
+private slots:
+ void constructStub();
+
+private:
+ KDevelop::ClassDeclaration* m_clazz;
+ KAction* m_constructStub;
+};
+
+}
+
+#endif // VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h (revision 1522570)
@@ -0,0 +1,64 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef VERITASCPP_UUTCONTEXTACTION_INCLUDED
+#define VERITASCPP_UUTCONTEXTACTION_INCLUDED
+
+#include "veritascppexport.h"
+#include <QObject>
+
+class KAction;
+namespace KDevelop { class Context; class ContextMenuExtension; class Declaration; }
+
+namespace Veritas
+{
+class UUTConstructor;
+
+/*! Context menu action to create a unit under test skeleton based
+ on it's implementation.
+ @see Veritas::UUTConstructor */
+class VERITASCPP_EXPORT UUTContextAction : public QObject
+{
+Q_OBJECT
+public:
+ UUTContextAction(QObject* parent=0);
+ ~UUTContextAction();
+
+ /*! initialization */
+ void setup();
+
+ /*! Checks if @param context should get an uut action and adds it to
+ @param menu if so. Otherwise nothing happens. */
+ void appendTo(KDevelop::ContextMenuExtension& menu, KDevelop::Context* context);
+
+private slots:
+ void createImplementation();
+
+private:
+ KDevelop::Declaration* m_clazz;
+ KAction* m_createImplementation;
+ UUTConstructor* m_constructor;
+};
+
+}
+
+#endif // VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/veritascppexport.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/veritascppexport.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/veritascppexport.h (revision 1522570)
@@ -0,0 +1,37 @@
+/***************************************************************************
+ * This file is part of KDevelop *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
+ * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
+ * Copyright 2006 Matt Rogers <mattr@kde.org> *
+ * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
+ * *
+ * This program 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 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 Library General Public *
+ * License along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+#ifndef LANGUAGES_CPP_VERITASCPP_EXPORT_H
+#define LANGUAGES_CPP_VERITASCPP_EXPORT_H
+
+#include <kdemacros.h>
+
+#ifndef VERITASCPP_EXPORT
+# ifdef MAKE_VERITASCPP_LIB
+# define VERITASCPP_EXPORT KDE_EXPORT
+# else
+# define VERITASCPP_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#endif // LANGUAGES_CPP_VERITASCPP_EXPORT_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/veritascppexport.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.h (revision 1522570)
@@ -0,0 +1,62 @@
+/*
+ * KDevelop xUnit test support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef VERITAS_STUBCONSTRUCTOR_INCLUDED_H
+#define VERITAS_STUBCONSTRUCTOR_INCLUDED_H
+
+#include "veritascppexport.h"
+#include "classskeleton.h"
+
+namespace KDevelop { class ClassDeclaration; }
+
+namespace Veritas
+{
+
+/*!
+Constructs a test fake sub class implementation for a given class.
+
+input:
+@code
+class Foo {
+public:
+ virtual int foo();
+};
+@endcode
+
+=> output:
+@code
+class FooStub {
+public:
+ int m_foo;
+ virtual int foo() { return m_foo; };
+};
+@endcode */
+class VERITASCPP_EXPORT StubConstructor
+{
+public:
+ StubConstructor();
+ virtual ~StubConstructor();
+ ClassSkeleton morph(KDevelop::ClassDeclaration*);
+};
+
+}
+
+#endif // VERITAS_STUBCONSTRUCTOR_INCLUDED_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/stubconstructor.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.h (revision 1522570)
@@ -0,0 +1,81 @@
+/*
+* KDevelop xUnit integration
+* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
+* 02110-1301, USA.
+*/
+
+#ifndef VERITASCPP_UUTCONSTRUCTOR_H
+#define VERITASCPP_UUTCONSTRUCTOR_H
+
+#include "veritascppexport.h"
+#include "classskeleton.h"
+#include "methodskeleton.h"
+#include <language/editor/simplecursor.h>
+
+namespace KDevelop { class Declaration; class Use; class DUContext; class SimpleCursor; }
+
+namespace Veritas
+{
+
+class DocumentAccess;
+/*!
+Generate a skeleton for unit under test from its implementation
+in a test. Fetches all method uses and construct method skeletons
+for those.
+
+input:
+@code
+void MyTest::test() {
+ MyUnitUnderTest uut;
+ uut.rockOn();
+}
+@endcode
+=>
+output:
+@code
+class MyUnitUnderTest {
+public:
+ void rockOn();
+};
+@endcode
+@unittest Veritas::Test::UUTCreationTest
+*/
+class VERITASCPP_EXPORT UUTConstructor
+{
+public:
+ /*! Generate a class for an unresolved variable and all it's Use's */
+ virtual ClassSkeleton morph(KDevelop::Declaration* variable);
+
+ UUTConstructor();
+ virtual ~UUTConstructor();
+ virtual void setDocumentAccess(DocumentAccess*);
+
+private:
+ /*! Create a method skeleton from a @param use of @param clazz
+ eg: Foo f; f.bar(); => method Foo::bar() */
+ MethodSkeleton createMethod(KDevelop::Declaration* clazz, const KDevelop::Use* use, KDevelop::DUContext*);
+ QString enoughText(const KUrl& url, const KDevelop::SimpleCursor&) const;
+ void printUseInfo(int useId, const KDevelop::Use* use, KDevelop::DUContext* ctx);
+ void constructMethodsFor(KDevelop::DUContext* ctx, KDevelop::Declaration* variable, ClassSkeleton& cs);
+
+private:
+ DocumentAccess* m_docAccess;
+};
+
+}
+
+#endif // VERITASCPP_UUTCONSTRUCTOR_H
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/uutconstructor.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.h (revision 1522570)
@@ -0,0 +1,67 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+#ifndef VERITASCPP_METHODSKELETON_INCLUDED
+#define VERITASCPP_METHODSKELETON_INCLUDED
+
+#include "veritascppexport.h"
+#include <QtCore/QString>
+#include <language/duchain/types/functiontype.h>
+
+namespace Veritas
+{
+enum Access { Public, Protected, Private };
+
+/*! Value class which stores a simplified AST for member functions */
+class VERITASCPP_EXPORT MethodSkeleton
+{
+public:
+ MethodSkeleton();
+ virtual ~MethodSkeleton();
+ bool isEmpty() const;
+
+ void setFunctionType(KDevelop::FunctionType::Ptr);
+ void setName(const QString&);
+ void setArguments(const QString&);
+ void setReturnType(const QString&);
+ void setBody(const QString&);
+ void setAccess(Access) {}
+ void setVirtual() {}
+ void setConst(bool);
+
+ QString name() const;
+ QString arguments() const;
+ QString body() const;
+ QString returnType() const;
+ bool isConst() const;
+
+private:
+ bool m_empty;
+ QString m_name;
+ QString m_body;
+ QString m_returnType;
+ QString m_arguments;
+ bool m_isConst;
+};
+
+}
+
+#endif // VERITASCPP_METHODSKELETON_INCLUDED
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/methodskeleton.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp (revision 1522570)
@@ -0,0 +1,40 @@
+/*
+ * KDevelop xUnit testing support
+ *
+ * Copyright 2008 Manuel Breugelmans
+ *
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+#include "constructorskeleton.h"
+
+using Veritas::ConstructorSkeleton;
+
+ConstructorSkeleton::ConstructorSkeleton()
+{}
+
+
+ConstructorSkeleton::~ConstructorSkeleton()
+{}
+
+void ConstructorSkeleton::addInitializer(const QString& initializer)
+{
+ m_initializerList << initializer;
+}
+
+QStringList ConstructorSkeleton::initializerList() const
+{
+ return m_initializerList;
+}
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h (revision 1522570)
@@ -0,0 +1,64 @@
+/*
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+/*! Examples and howto for stub code generation */
+
+/*!
+This is your everyday interface. Now we want to construct
+a stub class skeleton for the virtual methods.
+
+Steps:
+ 1/ Point your mouse cursor to the first 'Foo'
+ 2/ Notice the neat code highlighting
+ 3/ Right click to spawn a context menu
+ 4/ Choose ``Generate Stub Class''
+ 5/ A dialog box will appear. Provide a filename
+ This file will contain the generated code
+ 6/ Hit ok.
+ 7/ Stub is generated and focused.
+*/
+class Foo
+{
+public:
+ Foo();
+ virtual ~Foo();
+ virtual int foo(char);
+};
+
+/*! Only virtual methods are stubbed. No code is generated
+ * for non-virtual, signals nor for private methods. */
+class Bar
+{
+public:
+ void bar();
+signals:
+ void barr();
+private:
+ void barrr();
+};
+
+namespace Zoo
+{
+class Loo
+{
+public:
+ virtual void moo();
+ virtual void boo() const;
+};
+}
+
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h (revision 1522570)
@@ -0,0 +1,45 @@
+/*
+ * This program 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 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+/*! Examples and howto for unit under test generation from a test-driven
+ implementation. */
+
+/*!
+This is your everyday test first test command. You have
+coded the Baz class by intention and now want to generate
+a skeleton implementation.
+
+Steps:
+ 1/ Move your cursor to baz
+ 2/ Notice the neat code highlighting
+ 3/ Right click to spawn a context menu
+ 4/ Choose ``Generate Unit Under Test''
+ 5/ A dialog box will appear. Provide a filename
+ This file will contain the generated code
+ 6/ Hit ok.
+ 7/ Unit Under Test skeleton is generated
+
+*/
+class Foo;
+class Bar;
+void FooTest::foo()
+{
+ Baz baz;
+ baz.moo();
+ baz.zoo(Foo(), Bar());
+}
+
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switch.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switch.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switch.h (revision 1522570)
@@ -0,0 +1,38 @@
+/*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+/*! Test - Unit Under Test code navigation example
+
+Purpose is to navigate quickly from a test to it's unit.
+
+KDevelop4 will read the switch target from the class'
+documentation string. If this is not present a heuristic
+based on naming conventions will try to resolve a switch
+candidate.
+
+First open both switch.h and switchtest.h in KDevelop4 to make
+sure the symbols are parsed. Next configure the switch shortcut
+in Settings -> Configure Shortcuts -> Switch Test/Unit Under Test.
+Hit this key combination to jump between switch.h and switchtest.h
+*/
+
+/*! @unittest SwitchExampleTest */
+class SwitchExample
+{
+public:
+ void foo();
+};
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switch.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h (revision 1522570)
@@ -0,0 +1,39 @@
+/*
+* This program 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 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.,
+* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+/*! Test - Unit Under Test code navigation example
+
+Purpose is to navigate quickly from a test to it's unit.
+
+KDevelop4 will read the switch target from the class'
+documentation string. If this is not present a heuristic
+based on naming conventions will try to resolve a switch
+candidate.
+
+First open both switch.h and switchtest.h in KDevelop4 to make
+sure the symbols are parsed. Next configure the switch shortcut
+in Settings -> Configure Shortcuts -> Switch Test/Unit Under Test.
+Hit this key combination to jump between switch.h and switchtest.h
+*/
+
+/*! @unitundertest SwitchExample */
+class SwitchExampleTest : public QObject
+{
+Q_OBJECT
+private slots:
+ void testFoo();
+};
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Index: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/clean.sh
===================================================================
--- tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/clean.sh (nonexistent)
+++ tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/clean.sh (revision 1522570)
@@ -0,0 +1,6 @@
+#!/bin/bash
+
+KEEPERS="(^stubgeneration.h$|^uutgeneration.h$|^switch.h$|^switchtest.h$|^clean.sh$)"
+GARBAGE=$(ls | grep -Ev $KEEPERS)
+echo "Removing $GARBAGE"
+rm -i $GARBAGE
Property changes on: tags/unmaintained/4/kdevelop4-extra-plugins/veritascpp/examples/clean.sh
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-libraries/veritas/README
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-libraries/veritas/README (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-libraries/veritas/README (nonexistent)
@@ -1,11 +0,0 @@
-Veritas has moved to Git.
-
-Put the following in your ~/.gitconfig:
-
- [url "git://anongit.kde.org/"]
- insteadOf = kde:
- [url "ssh://git@git.kde.org/"]
- pushInsteadOf = kde:
-
-Then to clone Veritas:
- $ git clone kde:veritas
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/CMakeLists.txt (nonexistent)
@@ -1,31 +0,0 @@
-set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
-include_directories(
- ${XtestPlugin_SOURCE_DIR}/check
- ${XtestPlugin_SOURCE_DIR} # for kasserts.h
-)
-
-add_definitions(${KDE4_ENABLE_EXCEPTIONS})
-
-macro(kdev_add_test test_EXEC)
- set(test_SRCS ${ARGN})
- qt4_automoc( ${test_SRCS} )
- kde4_add_unit_test(check-${test_EXEC} ${test_SRCS})
- target_link_libraries(check-${test_EXEC}
- ${QT_QTTEST_LIBRARY}
- ${QT_QTXML_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- kdevcheck)
-endmacro(kdev_add_test)
-
-kdev_add_test(sys-checkrunnertest checkrunnertest.cpp)
-
-add_executable(emptysuite fake_emptysuite.cpp)
-target_link_libraries(emptysuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
-
-add_executable(sunnysuite fake_sunnysuite.cpp)
-target_link_libraries(sunnysuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
-
-add_executable(multisuite fake_multisuite.cpp)
-target_link_libraries(multisuite ${QT_QTCORE_LIBRARY} ${CHECK_LIBRARY})
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.cpp (nonexistent)
@@ -1,146 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "checkrunnertest.h"
-
-#include <kasserts.h>
-#include <qtest_kde.h>
-#include "plugins/xtest/cppunit/register.h"
-#include <veritas/runnertesthelper.h>
-#include "testsuite.h"
-#include "testroot.h"
-
-
-using Veritas::RunnerTestHelper;
-using Check::TestSuite;
-using Check::TestRoot;
-using Check::Test::CheckRunnerTest;
-
-void CheckRunnerTest::init()
-{
- m_runner = new RunnerTestHelper;
- m_runner->initializeGUI();
-}
-
-void CheckRunnerTest::cleanup()
-{
- m_runner->cleanupGUI();
- delete m_runner;
-}
-
-// helper
-Veritas::Test* CheckRunnerTest::fetchRoot(const char* exe)
-{
- Register<TestRoot, TestSuite> reg;
- QFileInfo executable(exe);
- reg.addFromExe(executable);
- reg.rootItem()->setExecutable(executable);
- return reg.rootItem();
-}
-
-// command
-void CheckRunnerTest::empty()
-{
- Veritas::Test* root = fetchRoot("./emptysuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- QStringList runnerItems;
- runnerItems << "0 my_suite"
- << "0 0 x"
- << "1 x";
- m_runner->verifyTestTree(runnerItems);
-
- QList<QStringList> results;
- m_runner->verifyResultItems(results);
-}
-
-QStringList sunnyDayTests()
-{
- QStringList runnerItems;
- runnerItems
- << "0 root_suite"
- << "0 0 foo_test"
- << "0 0 0 foo_cmd1"
- << "0 0 1 foo_cmd2"
- << "0 0 2 x"
- << "0 1 bar_test"
- << "0 1 0 bar_cmd1"
- << "0 1 1 bar_cmd2"
- << "0 1 2 x"
- << "0 2 baz_test"
- << "0 2 0 baz_cmd1"
- << "0 2 1 x"
- << "0 3 x"
- << "1 x";
- return runnerItems;
-}
-
-QMap<QString, Veritas::TestState> sunnyDayTestStates()
-{
- QMap<QString, Veritas::TestState> states;
- states["root_suite/foo_test/foo_cmd1"] = Veritas::RunSuccess;
- states["root_suite/foo_test/foo_cmd2"] = Veritas::RunSuccess;
- states["root_suite/bar_test/bar_cmd1"] = Veritas::RunSuccess;
- states["root_suite/bar_test/bar_cmd2"] = Veritas::RunError;
- states["root_suite/baz_test/baz_cmd1"] = Veritas::RunSuccess;
- return states;
-}
-
-// command
-void CheckRunnerTest::sunnyDay()
-{
- Veritas::Test* root = fetchRoot("./sunnysuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- m_runner->verifyTestTree(sunnyDayTests());
- m_runner->verifyTestStates(sunnyDayTestStates(), root);
- QStringList result;
- result << "bar_cmd2" << "Assertion '0' failed" << "fake_sunnysuite.cpp" << "53";
- m_runner->verifyResultItems(QList<QStringList>() << result);
-}
-
-// command
-void CheckRunnerTest::multiSuite()
-{
- Veritas::Test* root = fetchRoot("./multisuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- QStringList topo;
- topo << "0 foo"
- << "0 0 foo_test"
- << "0 0 0 foo_cmd"
- << "0 0 1 x"
- << "1 bar"
- << "1 0 bar_test"
- << "1 0 0 bar_cmd"
- << "1 0 1 x"
- << "1 1 x"
- << "2 x";
- m_runner->verifyTestTree(topo);
-
- QList<QStringList> results;
- m_runner->verifyResultItems(results);
-}
-
-#include "checkrunnertest.moc"
-QTEST_KDEMAIN(CheckRunnerTest, GUI)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/checkrunnertest.h (nonexistent)
@@ -1,51 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_CHECK_CHECKRUNNERTEST_H
-#define VERITAS_CHECK_CHECKRUNNERTEST_H
-
-#include <QtTest/QTest>
-
-namespace Veritas { class RunnerTestHelper; class Test; }
-
-namespace Check { namespace Test {
-
-class CheckRunnerTest : public QObject
-{
-Q_OBJECT
-
-private slots:
- void init();
- void cleanup();
-
- void empty();
- void sunnyDay();
- void multiSuite();
-
-private:
- Veritas::Test* fetchRoot(const char* exe);
-
-private:
- Veritas::RunnerTestHelper* m_runner;
-};
-
-}}
-
-#endif // VERITAS_CHECK_CHECKRUNNERTEST
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_sunnysuite.cpp (nonexistent)
@@ -1,87 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <checkwrapper.h>
-#include <unistd.h>
-
-// "0 root_suite"
-// "0 0 foo_test"
-// "0 0 0 foo_cmd1"
-// "0 0 1 foo_cmd2"
-// "0 0 2 x"
-// "0 1 bar_test"
-// "0 1 0 bar_cmd1"
-// "0 1 1 bar_cmd2"
-// "0 1 2 x"
-// "0 2 baz_test"
-// "0 2 0 baz_cmd1"
-// "0 2 1 x"
-// "0 3 x"
-// "1 x"
-
-START_TEST( foo_cmd1 )
-{}
-END_TEST
-
-START_TEST( foo_cmd2 )
-{}
-END_TEST
-
-START_TEST( bar_cmd1 )
-{}
-END_TEST
-
-START_TEST( bar_cmd2 )
-{
- fail_unless(0);
-}
-END_TEST
-
-START_TEST( baz_cmd1 )
-{
- usleep(50000);
-}
-END_TEST
-
-Suite* suite(void)
-{
- Suite *s = suite_create("root_suite");
-
- /* foo test case */
- TCase *tc_foo = tcase_create("foo_test");
- tcase_add_test(tc_foo, foo_cmd1);
- tcase_add_test(tc_foo, foo_cmd2);
- suite_add_tcase(s, tc_foo);
-
- /* bar test case */
- TCase *tc_bar = tcase_create("bar_test");
- tcase_add_test(tc_bar, bar_cmd1);
- tcase_add_test(tc_bar, bar_cmd2);
- suite_add_tcase(s, tc_bar);
-
- /* baz test case */
- TCase *tc_baz = tcase_create("baz_test");
- tcase_add_test(tc_baz, baz_cmd1);
- suite_add_tcase(s, tc_baz);
-
- return s;
-}
-
-CHECK_VERITAS_MAIN_( suite() )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_emptysuite.cpp (nonexistent)
@@ -1,23 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <checkwrapper.h>
-
-CHECK_VERITAS_MAIN_( suite_create("my_suite") )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/tests/fake_multisuite.cpp (nonexistent)
@@ -1,62 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <checkwrapper.h>
-#include <unistd.h>
-
-// "0 foo"
-// "0 0 foo_test"
-// "0 0 0 foo_cmd"
-// "0 0 1 x"
-// "0 bar"
-// "1 0 bar_test"
-// "1 0 0 bar_cmd"
-// "1 1 1 x"
-// "1 1 x"
-// "2 x"
-
-START_TEST( foo_cmd )
-{}
-END_TEST
-
-START_TEST( bar_cmd )
-{}
-END_TEST
-
-Suite* ss[2];
-
-Suite** suites(void)
-{
- Suite *fs = suite_create("foo");
- TCase *tc_foo = tcase_create("foo_test");
- tcase_add_test(tc_foo, foo_cmd);
- suite_add_tcase(fs, tc_foo);
-
- Suite *bs = suite_create("bar");
- TCase *tc_bar = tcase_create("bar_test");
- tcase_add_test(tc_bar, bar_cmd);
- suite_add_tcase(bs, tc_bar);
-
- ss[0] = fs;
- ss[1] = bs;
- return ss;
-}
-
-CHECK_VERITAS_MAIN( suites(), 2 )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/check_list.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/check_list.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/check_list.h (nonexistent)
@@ -1,71 +0,0 @@
-/*
- * Check: a unit test framework for C
- * Copyright (C) 2001, 2002 Arien Malec
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
- */
-
-#ifndef CHECK_LIST_H
-#define CHECK_LIST_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct List {
- int n_elts;
- int max_elts;
- int current; /* pointer to the current node */
- int last; /* pointer to the node before END */
- const void **data;
-};
-
-typedef struct List List;
-
-/* Create an empty list */
-List * check_list_create (void);
-
-/* Is list at end? */
-int list_at_end (List * lp);
-
-/* Position list at front */
-void list_front(List *lp);
-
-/* Add a value to the front of the list,
- positioning newly added value as current value.
- More expensive than list_add_end, as it uses memmove. */
-void list_add_front (List *lp, const void *val);
-
-/* Add a value to the end of the list,
- positioning newly added value as current value */
-void list_add_end (List *lp, const void *val);
-
-/* Give the value of the current node */
-void *list_val (List * lp);
-
-/* Position the list at the next node */
-void list_advance (List * lp);
-
-/* Free a list, but don't free values */
-void list_free (List * lp);
-
-void list_apply (List *lp, void (*fp) (void *));
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CHECK_LIST_H */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.cpp (nonexistent)
@@ -1,227 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "outputparser.h"
-#include "testsuite.h"
-#include "testroot.h"
-#include "plugins/xtest/cppunit/testcase.h"
-#include <KUrl>
-#include <KDebug>
-
-using Check::TestRoot;
-using Check::OutputParser;
-using Veritas::TestResult;
-
-/*example xml:
-<?xml version="1.0"?>
-<testsuites xmlns="http://check.sourceforge.net/ns">
- <datetime>2008-06-20 13:59:25</datetime>
- <suite>
- <title>Money</title>
- <test result="success">
- <path>.</path>
- <fn>check_money.c:28</fn>
- <id>test_money_create</id>
- <iteration>0</iteration>
- <description>Core</description>
- <message>Passed</message>
- </test>
- <test result="error">
- <path>.</path>
- <fn>check_money.c:37</fn>
- <id>test_money_create_neg</id>
- <iteration>0</iteration>
- <description>Limits</description>
- <message>Test timeout expired</message>
- </test>
- <test result="success">
- <path>.</path>
- <fn>check_money.c:46</fn>
- <id>test_money_create_zero</id>
- <iteration>0</iteration>
- <description>Limits</description>
- <message>Passed</message>
- </test>
- </suite>
- <duration>0.000000</duration>
-</testsuites>
-*/
-
-const QString OutputParser::c_suite("suite");
-const QString OutputParser::c_test("test");
-const QString OutputParser::c_title("title");
-const QString OutputParser::c_path("path");
-const QString OutputParser::c_file("fn");
-const QString OutputParser::c_id("id");
-const QString OutputParser::c_description("description");
-const QString OutputParser::c_message("message");
-const QString OutputParser::c_result("result");
-const QString OutputParser::c_error("error");
-const QString OutputParser::c_failure("failure");
-const QString OutputParser::c_success("success");
-
-#define ENSURE_FOUND(c,p,n) Q_ASSERT_X(c, "hm",\
- qstrdup((QString("Failed to find ") + n + QString(" as child of ")\
- + p->name()).toAscii().data()));
-
-
-OutputParser::OutputParser(QIODevice* device)
- : QXmlStreamReader(device),
- m_result(0)
-{}
-
-OutputParser::~OutputParser()
-{}
-
-bool OutputParser::isStartElement_(const QString& elementName)
-{
- return isStartElement() && (name() == elementName);
-}
-
-bool OutputParser::isEndElement_(const QString& elementName)
-{
- return isEndElement() && (name() == elementName);
-}
-
-void OutputParser::go(TestRoot* root)
-{
- m_root = root;
- if (!device()->isOpen()) {
- device()->open(QIODevice::ReadOnly);
- }
- if (!device()->isReadable()) {
- // do something
- }
- while (!atEnd()) {
- readNext();
- if (isStartElement_(c_suite)) {
- processSuite();
- }
- }
- kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
-}
-
-void OutputParser::processSuite()
-{
- QString name = fetchName();
- m_suite = m_root->childNamed(name);
- ENSURE_FOUND(m_suite, m_root, name);
- while (!atEnd() && !isEndElement_(c_suite)) {
- readNext();
- if (isStartElement_(c_test)) {
- processTest();
- }
- }
-}
-
-void OutputParser::processTest()
-{
- QString caze, cmd, result, file, msg;
- bool ok = readTestElement(caze, cmd, result, file, msg);
- if (ok) postResult(caze, cmd, result, file, msg);
-}
-
-void OutputParser::postResult(const QString& caze, const QString& cmd, const QString& result,
- const QString& file, const QString& msg)
-{
- if (result == c_success) {
- setSuccess();
- } else if (result == c_error || result == c_failure) {
- setFailure(file, msg);
- } else {
- kDebug() << "unkwown result: " << result << " for " << caze << ":" << cmd;
- }
- m_case = m_suite->childNamed(caze);
- ENSURE_FOUND(m_case, m_suite, caze);
- m_cmd = m_case->childNamed(cmd);
- ENSURE_FOUND(m_cmd, m_case, cmd);
-
- m_cmd->setResult(m_result);
- m_cmd->signalStarted();
- m_cmd->signalFinished();
-}
-
-/*
-<test result="success">
- <path>.</path>
- <fn>check_money.c:28</fn>
- <id>test_money_create</id>
- <iteration>0</iteration>
- <description>Core</description>
- <message>Passed</message>
-</test>
-*/
-bool OutputParser::readTestElement(QString& caze, QString& cmd, QString& result,
- QString& file, QString& msg)
-{
- int count = 0;
- QString path;
- result = attributes().value("result").toString();
- m_result = new TestResult;
- while (!atEnd() && !isEndElement_(c_test)) {
- readNext();
- if (!isStartElement()) {
- continue;
- } else if (name() == c_path) {
- path = readElementText();
- } else if(name() == c_file) {
- file = readElementText();
- } else if (name() == c_description) {
- caze = readElementText();
- } else if (name() == c_message) {
- msg = readElementText();
- } else if (name() == c_id) {
- cmd = readElementText();
- }
- count++;
- }
- if (isEndElement_(c_test)) {
- Q_ASSERT_X(count == 6, "readTestElement", QString("Execpted 5 elements, got " + QString::number(count)).toAscii());
- return true;
- } else {
- return false;
- }
-}
-
-QString OutputParser::fetchName()
-{
- while (!atEnd()) {
- readNext();
- if (isStartElement_(c_title)) {
- return readElementText();
- }
- }
- Q_ASSERT(0);
- return "??????";
-}
-
-void OutputParser::setSuccess()
-{
- m_result->setState(Veritas::RunSuccess);
-}
-
-void OutputParser::setFailure(const QString& location, const QString& msg)
-{
- m_result->setState(Veritas::RunError);
- QStringList spl = location.split(':');
- m_result->setFile(KUrl(spl.value(0)));
- m_result->setLine(spl.value(1).toInt());
- m_result->setMessage(msg);
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcheck.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/CMakeLists.txt (nonexistent)
@@ -1,58 +0,0 @@
-project(check)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${check_SOURCE_DIR}/cmake)
-
-add_subdirectory(tests)
-#
-# TODO install kdevcheck headers
-#
-
-add_definitions(${KDE4_ENABLE_EXCEPTIONS})
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-
-set(TestBuild on)
-if(TestBuild)
-# expose all symbols
- add_definitions( -fvisibility=default )
-endif(TestBuild)
-
-include_directories(
- ${XtestPlugin_SOURCE_DIR}
-)
-
-set(kdevcheck_SRCS
- ../cppunit/testcase.cpp
- ../cppunit/testcommand.cpp
- outputparser.cpp
- testsuite.cpp
- checkviewdata.cpp
- testroot.cpp)
-
-qt4_automoc( ${kdevcheck_SRCS} )
-kde4_add_library(kdevcheck SHARED ${kdevcheck_SRCS})
-target_link_libraries(kdevcheck
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${CHECK_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${QT_QTCORE_LIBRARY})
-install(TARGETS kdevcheck ${INSTALL_TARGETS_DEFAULT_ARGS} )
-
-#########################################
-
-set(kdevcheckview_SRCS checkplugin.cpp)
-qt4_automoc(${kdevcheckview_SRCS})
-kde4_add_plugin(kdevcheckview ${kdevcheckview_SRCS})
-target_link_libraries(kdevcheckview
- kdevcheck
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDE4_KDEUI_LIBS}
- ${QT_QTCORE_LIBRARY})
-install(TARGETS kdevcheckview DESTINATION ${PLUGIN_INSTALL_DIR})
-
-########### install files ###############
-
-install( FILES kdevcheck.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevcheck.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcheck )
-install( FILES checkwrapper.h check_impl.h check_list.h
- DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/veritas/ )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/check.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/check.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/check.kdev4 (nonexistent)
@@ -1,3 +0,0 @@
-[Project]
-Name=check
-Manager=KDevCustomMakeManager
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.h (nonexistent)
@@ -1,51 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_CHECK_TESTROOT_H
-#define VERITAS_CHECK_TESTROOT_H
-
-#include <QString>
-#include <QFileInfo>
-
-#include <veritas/test.h>
-#include "testsuite.h"
-
-namespace Check
-{
-
-/*! Prime item in the Check Test Tree. Holds the executable */
-class TestRoot : public Veritas::Test
-{
-Q_OBJECT
-public:
- TestRoot(const QList<QVariant>& data);
- virtual ~TestRoot();
- TestSuite* child(int i) const;
- void setExecutable(const QFileInfo& e) { m_exe = e; }
- int run();
- bool shouldRun() const;
-
-private:
- QFileInfo m_exe;
-};
-
-} // end namespace Check
-
-#endif // VERITAS_CHECK_TESTROOT_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.desktop (nonexistent)
@@ -1,87 +0,0 @@
-[Desktop Entry]
-Type=Service
-Icon=kdevelop
-Exec=blubb
-Comment=Check test runner
-Comment[bs]=Provjeri test runner(pokreće neku akciju)
-Comment[ca]=Comprovador de l'executor de proves
-Comment[ca@valencia]=Comprovador de l'executor de proves
-Comment[de]=Check-Test ausführen
-Comment[el]=Εκτελεστής εκτελεστή ελέγχου
-Comment[en_GB]=Check test runner
-Comment[es]=Comprobar lanzador de pruebas
-Comment[et]=Kontrolltesti käivitaja
-Comment[fr]=Lanceur de tests de vérification
-Comment[ga]=Seiceáil an feidhmitheoir tástála
-Comment[gl]=Executor de probas de comprobación
-Comment[it]=Controlla l'esecutore test
-Comment[ms]=Periksa pelari ujian
-Comment[nds]=Prööv-Testdreger
-Comment[nl]=Test controles uitvoeren
-Comment[pa]=ਟੈਸਟ ਰਨਰ ਚੈੱਕ ਕਰੋ
-Comment[pl]=Uruchamianie testu sprawdzającego
-Comment[pt]=Verificar a execução dos testes
-Comment[pt_BR]=Verificar a execução dos testes
-Comment[sv]=Kör kontrolltest
-Comment[tr]=Denetim sınaması çalıştırıcı
-Comment[uk]=Засіб запуску перевірки Check
-Comment[x-test]=xxCheck test runnerxx
-Name=Check runner
-Name[bs]=Provjeri runner(pokreće neku akciju)
-Name[ca]=Comprova executor
-Name[ca@valencia]=Comprova executor
-Name[de]=Check ausführen
-Name[el]=Έλεγχος εκτελεστή
-Name[en_GB]=Check runner
-Name[es]=Comprobar lanzador
-Name[et]=Kontrolli käivitaja
-Name[fr]=Lanceur de vérification
-Name[ga]=Seiceáil an feidhmitheoir
-Name[gl]=Executor de probas de comprobación
-Name[it]=Esecutore controlli
-Name[ms]=Periksa pelari
-Name[nds]=Pröövdreger
-Name[nl]=Controles uitvoeren
-Name[pa]=ਰਨਰ ਚੈੱਕ
-Name[pl]=Uruchamianie sprawdzania
-Name[pt]=Verificar a execução
-Name[pt_BR]=Verificar a execução
-Name[sv]=Kör kontroll
-Name[tr]=Denetim çalıştırıcı
-Name[uk]=Засіб запуску Check
-Name[x-test]=xxCheck runnerxx
-GenericName=Unit test runner
-GenericName[bs]=Jednični test runner(pokreće neku akciju)
-GenericName[ca]=Executor de prova Unit
-GenericName[ca@valencia]=Executor de prova Unit
-GenericName[de]=Unittest ausführen
-GenericName[el]=Εκτελεστής ελέγχου unit
-GenericName[en_GB]=Unit test runner
-GenericName[es]=Lanzador de pruebas unitarias
-GenericName[et]=Unit-testi käivitaja
-GenericName[fr]=Lanceur de test unitaire
-GenericName[ga]=Feidhmitheoir tástála aonad
-GenericName[gl]=Executor de probas unitarias
-GenericName[it]=Esecutore di unit test
-GenericName[ms]=Pelari unit uji
-GenericName[nds]=Unit-Testdreger
-GenericName[nl]=Test-startprogramma voor eenheid
-GenericName[pa]=ਯੂਨਿਟ ਟੈਸਟ ਰਨਰ
-GenericName[pl]=Uruchamianie jednostki testu
-GenericName[pt]=Execução de testes unitários
-GenericName[pt_BR]=Execução de testes unitários
-GenericName[sk]=Spúštač unit testov
-GenericName[sv]=Kör enhetstest
-GenericName[tr]=Birim sınaması çalıştırıcı
-GenericName[uk]=Засіб запуску перевірки модулів
-GenericName[x-test]=xxUnit test runnerxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevcheckview
-X-KDE-PluginInfo-Name=checkview
-X-KDE-PluginInfo-Author=Manuel Breugelmans
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=LGPL
-X-KDevelop-Version=7
-X-KDevelop-Interfaces=org.kdevelop.ITestFramework
-X-KDevelop-Category=Global
-X-KDevelop-Properties=GlobalFileManagement
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkexport.h (nonexistent)
@@ -1,37 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef VERITAS_CHECKEXPORT_H
-#define VERITAS_CHECKEXPORT_H
-
-#include <kdemacros.h>
-
-#ifndef VERITAS_CHECK_EXPORT
-# ifdef MAKE_KDEVCHECK_LIB
-# define VERITAS_CHECK_EXPORT KDE_EXPORT
-# else
-# define VERITAS_CHECK_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif // VERITAS_CHECK_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.h (nonexistent)
@@ -1,53 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_CHECK_TESTSUITE_H
-#define VERITAS_CHECK_TESTSUITE_H
-
-#include <QString>
-#include <QFileInfo>
-#include <KProcess>
-
-#include <veritas/test.h>
-
-#include "plugins/xtest/cppunit/testcase.h"
-
-namespace Check
-{
-
-/*! Test aggregate item in the test tree. Contains TestCases */
-class TestSuite : public Veritas::Test
-{
-Q_OBJECT
-public:
- /*!
- * Provide name, executable location and Test parent.
- */
- TestSuite(const QString&, const QFileInfo&, Veritas::Test*);
- virtual ~TestSuite();
- TestCase* child(int i) const;
-
-private:
- QFileInfo m_exe;
-};
-
-} // end namespace Check
-
-#endif // VERITAS_CHECK_TESTSUITE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/outputparser.h (nonexistent)
@@ -1,84 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_CHECK_CHECKOUTPUTPARSER
-#define VERITAS_CHECK_CHECKOUTPUTPARSER
-
-#include <QXmlStreamReader>
-#include <veritas/testresult.h>
-
-class QIODevice;
-namespace Veritas { class Test; }
-
-namespace Check
-{
-class TestRoot;
-
-/*! Translates Check XML Output into TestResults */
-class OutputParser : public QXmlStreamReader
-{
-public:
- OutputParser(QIODevice* device);
- virtual ~OutputParser();
-
- /**
- * Start parsing and emit results
- **/
- void go(TestRoot*);
-
-private: // helpers
- void processSuite();
- void processTest();
- bool readTestElement(QString&, QString&, QString&, QString&, QString&);
- void postResult(const QString&, const QString&, const QString&,
- const QString&, const QString&);
- QString fetchName();
- void setFailure(const QString&, const QString&);
- void setSuccess();
-
- inline bool isStartElement_(const QString& elem);
- inline bool isEndElement_(const QString& elem);
-
-private: // state
- Veritas::TestResult* m_result;
- QString m_currentSuite;
- TestRoot* m_root;
- Veritas::Test* m_suite;
- Veritas::Test* m_case;
- Veritas::Test* m_cmd;
-
-private: // some xml constants
- static const QString c_suite;
- static const QString c_test;
- static const QString c_title;
- static const QString c_path;
- static const QString c_file;
- static const QString c_id;
- static const QString c_description;
- static const QString c_message;
- static const QString c_result;
- static const QString c_error;
- static const QString c_failure;
- static const QString c_success;
-};
-
-} // namespace Check
-
-#endif // VERITAS_CHECK_CHECKOUTPUTPARSER
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkwrapper.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkwrapper.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkwrapper.h (nonexistent)
@@ -1,107 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-/*!
-Constructs a compatible check executable for check Suite(s)
-through main macro's. See CHECK_VERITAS_MAIN.
-This header is intended for users of the runner, not a part of the
-check plugin.
-*/
-
-#ifndef CHECK_WRAPPER_H
-#define CHECK_WRAPPER_H
-
-#include <stdio.h>
-#include <check.h>
-#include "check_list.h"
-#include "check_impl.h"
-
-void qxcheck_print_suite(Suite* suite)
-{
- printf("<suite name=\"%s\">\n", suite->name);
- List *cases = suite->tclst;
- list_front(cases);
- while (!list_at_end(cases)) {
- TCase* caze = (struct TCase*)list_val(cases);
- printf(" <case name=\"%s\">\n", caze->name);
- List *cmds = caze->tflst;
- list_front(cmds);
- while (!list_at_end(cmds)) {
- TF* cmd = (struct TF*)list_val(cmds);
- printf(" <command name=\"%s\"/>\n", cmd->name);
- list_advance(cmds);
- }
- printf(" </case>\n");
- list_advance(cases);
- }
- printf("</suite>\n");
-}
-
-int qxcheck_print_tests(Suite** suites, int num)
-{
- int i;
- printf("<?xml version=\"1.0\"?>\n"
- "<testsuites>\n");
- for (i=0; i<num; i++) {
- Suite* s = suites[i];
- qxcheck_print_suite(s);
- }
- printf("</testsuites>\n");
- return 0;
-}
-
-int qxcheck_run_tests(Suite** suites, int num)
-{
- int number_failed, i;
-
- SRunner *sr = srunner_create(suites[0]);
- for (i=1; i<num; i++) {
- srunner_add_suite(sr, suites[i]);
- }
- srunner_set_xml(sr, "checklog.xml");
- srunner_run_all(sr, CK_SILENT);
- number_failed = srunner_ntests_failed(sr);
- srunner_free(sr);
- return (number_failed == 0) ? 0 : 1;
-}
-
-#define CHECK_VERITAS_MAIN_( root ) \
-int main(int argc, char** argv)\
-{\
- Suite* s = root; \
- Suite* suites[1] = {s}; \
- if (argc == 1 || argv[1][0] != '-') { \
- return qxcheck_run_tests(suites,1); \
- } else { \
- return qxcheck_print_tests(suites,1); \
- }\
-}
-
-#define CHECK_VERITAS_MAIN( multi, num ) \
-int main(int argc, char** argv)\
-{\
- if (argc == 1 || argv[1][0] != '-') {\
- return qxcheck_run_tests(multi, num); \
- } else { \
- return qxcheck_print_tests(multi, num); \
- }\
-}
-
-#endif // CHECK_WRAPPER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.h (nonexistent)
@@ -1,39 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CHECK_CHECKVIEWDATA_H
-#define CHECK_CHECKVIEWDATA_H
-
-#include <veritas/itestrunner.h>
-
-namespace Veritas { class Test; class ITestFramework; }
-
-/*! Assorted check toolview data and operation */
-class CheckViewData : public Veritas::ITestRunner
-{
-Q_OBJECT
-public:
- CheckViewData(Veritas::ITestFramework* framework);
- virtual ~CheckViewData();
- void registerTests();
- QString fetchExe();
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/kdevcheck.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevXtest" version="1">
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.cpp (nonexistent)
@@ -1,78 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "checkplugin.h"
-#include <veritas/testtoolviewfactory.h>
-
-#include <kpluginfactory.h>
-#include <kaboutdata.h>
-#include <kpluginloader.h>
-#include <ksharedconfig.h>
-
-#include <interfaces/iuicontroller.h>
-#include <interfaces/iproject.h>
-#include <interfaces/iprojectcontroller.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <project/projectmodel.h>
-#include <interfaces/icore.h>
-#include <veritas/test.h>
-#include "plugins/xtest/cppunit/register.h"
-#include <QFile>
-#include <KDebug>
-#include <KConfigGroup>
-
-#include "testroot.h"
-#include "testsuite.h"
-#include "checkviewdata.h"
-
-using KDevelop::IProject;
-using KDevelop::IProjectController;
-using Veritas::TestToolViewFactory;
-using Check::TestRoot;
-using Check::TestSuite;
-
-K_PLUGIN_FACTORY(CheckPluginFactory, registerPlugin<CheckPlugin>();)
-K_EXPORT_PLUGIN(CheckPluginFactory(KAboutData("kdevcheck","kdevcheck", ki18n("Check Test"), "0.1", ki18n("Support for running check unit tests"), KAboutData::License_GPL)))
-
-CheckPlugin::CheckPlugin(QObject* parent, const QVariantList &)
- : IPlugin(CheckPluginFactory::componentData(), parent)
-{
- KDEV_USE_EXTENSION_INTERFACE( Veritas::ITestFramework );
- TestToolViewFactory* factory = new TestToolViewFactory(this);
- core()->uiController()->addToolView(name() + " Runner", factory);
- setXMLFile("kdevcheck.rc");
-}
-
-CheckPlugin::~CheckPlugin()
-{
-}
-
-QString CheckPlugin::name() const
-{
- static QString s_name("Check");
- return s_name;
-}
-
-Veritas::ITestRunner* CheckPlugin::createRunner()
-{
- return new CheckViewData(this);
-}
-
-#include "checkplugin.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.cpp
___________________________________________________________________
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/check/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/testsuite.cpp (nonexistent)
@@ -1,46 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testsuite.h"
-#include "outputparser.h"
-#include <KDebug>
-#include <QDir>
-
-using Check::TestSuite;
-using Check::OutputParser;
-using Veritas::Test;
-
-TestSuite::TestSuite(const QString& name, const QFileInfo& exe, Test* parent)
- : Test(name, parent), m_exe(exe)
-{}
-
-TestSuite::~TestSuite()
-{}
-
-TestCase* TestSuite::child(int i) const
-{
- Test* child = Test::child(i);
- TestCase* caze = qobject_cast<TestCase*>(child);
- kWarning(caze==0) << "cast failed? " << name() << " "
- << i << " " << ((child!=0) ? child->name() : "null");
- return caze;
-}
-
-#include "testsuite.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/check_impl.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/check_impl.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/check_impl.h (nonexistent)
@@ -1,128 +0,0 @@
-/*
- * Check: a unit test framework for C
- * Copyright (C) 2001,2002 Arien Malec
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
- */
-
-#ifndef CHECK_IMPL_H
-#define CHECK_IMPL_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* This header should be included by any module that needs
- to know the implementation details of the check structures
- Include stdio.h & list.h before this header
-*/
-
-/* magic values */
-
-/* Unspecified fork status, used only internally */
-#define CK_FORK_UNSPECIFIED -1
-
-
-typedef struct TF {
- TFun fn;
- int loop_start;
- int loop_end;
- const char *name;
- int signal;
-} TF;
-
-struct Suite {
- const char *name;
- List *tclst; /* List of test cases */
-};
-
-typedef struct Fixture
-{
- int ischecked;
- SFun fun;
-} Fixture;
-
-struct TCase {
- const char *name;
- int timeout;
- List *tflst; /* list of test functions */
- List *unch_sflst;
- List *unch_tflst;
- List *ch_sflst;
- List *ch_tflst;
-};
-
-typedef struct TestStats {
- int n_checked;
- int n_failed;
- int n_errors;
-} TestStats;
-
-struct TestResult {
- enum test_result rtype; /* Type of result */
- enum ck_result_ctx ctx; /* When the result occurred */
- char *file; /* File where the test occurred */
- int line; /* Line number where the test occurred */
- int iter; /* The iteration value for looping tests */
- const char *tcname; /* Test case that generated the result */
- const char *tname; /* Test that generated the result */
- char *msg; /* Failure message */
-};
-
-TestResult *tr_create(void);
-void tr_reset(TestResult *tr);
-
-enum cl_event {
- CLINITLOG_SR,
- CLENDLOG_SR,
- CLSTART_SR,
- CLSTART_S,
- CLEND_SR,
- CLEND_S,
- CLEND_T
-};
-
-typedef void (*LFun) (SRunner *, FILE*, enum print_output,
- void *, enum cl_event);
-
-typedef struct Log {
- FILE *lfile;
- LFun lfun;
- int close;
- enum print_output mode;
-} Log;
-
-struct SRunner {
- List *slst; /* List of Suite objects */
- TestStats *stats; /* Run statistics */
- List *resultlst; /* List of unit test results */
- const char *log_fname; /* name of log file */
- const char *xml_fname; /* name of xml output file */
- List *loglst; /* list of Log objects */
- enum fork_status fstat; /* controls if suites are forked or not
- NOTE: Don't use this value directly,
- instead use srunner_fork_status */
-};
-
-
-void set_fork_status(enum fork_status fstat);
-enum fork_status cur_fork_status (void);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CHECK_IMPL_H */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.h (nonexistent)
@@ -1,44 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CHECK_CHECKPLUGIN
-#define CHECK_CHECKPLUGIN
-
-#include <QVariantList>
-#include <interfaces/iplugin.h>
-#include <veritas/itestframework.h>
-
-namespace Veritas { class TestToolViewFactory; }
-
-/*! Test runner plugin for the Check C unit testing framework */
-class CheckPlugin : public KDevelop::IPlugin, public Veritas::ITestFramework
-{
-Q_OBJECT
-Q_INTERFACES(Veritas::ITestFramework)
-
-public:
- explicit CheckPlugin(QObject* parent, const QVariantList & = QVariantList());
- virtual ~CheckPlugin();
- virtual Veritas::ITestRunner* createRunner();
- virtual QString name() const;
- virtual QWidget* createConfigWidget() { return 0; }
-};
-
-#endif // CHECK_CHECKPLUGIN
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkplugin.h
___________________________________________________________________
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/testroot.cpp (nonexistent)
@@ -1,73 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testroot.h"
-#include "outputparser.h"
-#include <QDir>
-#include <KDebug>
-#include <KProcess>
-
-
-using Veritas::Test;
-
-using Check::TestRoot;
-using Check::TestSuite;
-using Check::OutputParser;
-
-TestRoot::TestRoot(const QList<QVariant>& data)
- : Test(data, 0)
-{}
-
-TestRoot::~TestRoot()
-{}
-
-bool TestRoot::shouldRun() const
-{
- return true;
-}
-
-TestSuite* TestRoot::child(int i) const
-{
- Test* child = Test::child(i);
- TestSuite* suite = qobject_cast<TestSuite*>(child);
- kWarning(suite==0) << "cast failed? " << name() << " "
- << i << " " << ((child!=0) ? child->name() : "null");
- return suite;
-}
-
-int TestRoot::run()
-{
- KProcess proc;
- QStringList argv;
- proc.setProgram(m_exe.filePath(), argv);
- kDebug() << "executing " << proc.program();
- proc.setOutputChannelMode(KProcess::SeparateChannels);
- proc.start();
- proc.waitForFinished(-1);
- QStringList spl = m_exe.filePath().split('/');
- QFile f(QFileInfo(QDir::currentPath(), "checklog.xml").filePath());
- kWarning(!f.exists()) << "Failure: testresult dump does not exist [" << f.fileName();
- OutputParser parser(&f);
- parser.go(this);
- emit executionFinished();
- return 0;
-}
-
-#include "testroot.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/check/checkviewdata.cpp (nonexistent)
@@ -1,63 +0,0 @@
- /* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "checkviewdata.h"
-#include <KSharedConfig>
-#include <KConfigGroup>
-#include <interfaces/iproject.h>
-#include "../cppunit/register.h"
-#include "testroot.h"
-#include "testsuite.h"
-
-using namespace KDevelop;
-using namespace Veritas;
-using namespace Check;
-
-CheckViewData::CheckViewData(Veritas::ITestFramework* framework) : Veritas::ITestRunner(framework)
-{}
-
-CheckViewData::~CheckViewData() {}
-
-void CheckViewData::registerTests()
-{
- Register<TestRoot, TestSuite> reg;
- QString testExe = fetchExe();
- if (testExe.isEmpty()) {
- return; // TODO failure message
- }
- reg.addFromExe(KUrl(testExe));
- reg.rootItem()->setExecutable(testExe);
- emit registerFinished(reg.rootItem());
-}
-
-QString CheckViewData::fetchExe()
-{
- if (project() == 0) return QString();
- KSharedConfig::Ptr cfg = project()->projectConfiguration();
- KConfigGroup group(cfg.data(), "Veritas");
- QStringList executables;
- executables = group.readEntry("executables", executables);
- if (executables.isEmpty()) {
- return QString();
- }
- return executables[0];
-}
-
-#include "checkviewdata.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevqtdesigner.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt (nonexistent)
@@ -1,32 +0,0 @@
-project(qtdesigner)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${qtdesigner_SOURCE_DIR}/cmake/)
-
-find_package(KDE4 4.2.0 REQUIRED)
-find_package(KDevPlatform 0.9.93 REQUIRED)
-
-include_directories( ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR})
-include_directories( ${qtdesigner_SOURCE_DIR} ${qtdesigner_BINARY_DIR})
-
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9038 )
-
-########### next target ###############
-
-SET(kdevqtdesigner_PART_SRCS
-qtdesignerplugin.cpp
-qtdesignerdocument.cpp
-qtdesignerview.cpp
-qtdesignerwidget.cpp
-)
-
-
-
-kde4_add_plugin(kdevqtdesigner ${kdevqtdesigner_PART_SRCS})
-
-TARGET_LINK_LIBRARIES(kdevqtdesigner ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${QT_QTDESIGNER_LIBRARY} ${QT_QTDESIGNERCOMPONENTS_LIBRARY} ${KDEVPLATFORM_SUBLIME_LIBRARIES})
-install(TARGETS kdevqtdesigner DESTINATION ${PLUGIN_INSTALL_DIR})
-
-
-########### install files ###############
-
-install(FILES kdevqtdesigner.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install(FILES kdevqtdesigner.rc DESTINATION ${DATA_INSTALL_DIR}/kdevqtdesigner )
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc (nonexistent)
@@ -1,58 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<gui name="guibuilder" version="7">
-<MenuBar>
- <Menu name="file">
- <text context="@title:menu">File</text>
- <Action name="file_save" group="save_merge"/>
- </Menu>
-
- <Menu name="edit">
- <text context="@title:menu">Edit</text>
- <Action name="designer_undo" group="edit_undo_merge"/>
- <Action name="designer_redo" group="edit_undo_merge"/>
- <Action name="designer_cut" group="edit_paste_merge"/>
- <Action name="designer_copy" group="edit_paste_merge"/>
- <Action name="designer_paste" group="edit_paste_merge"/>
- </Menu>
-
- <Menu name="layout">
- <text context="@title:menu">Form</text>
- <Action name="layout_horiz"/>
- <Action name="layout_vertical"/>
- <Action name="layout_split_horiz"/>
- <Action name="layout_split_vert"/>
- <Action name="layout_grid"/>
- <Action name="break_layout"/>
- <Separator/>
- <Action name="adjust_size"/>
- <Separator/>
- <Action name="widgeteditor"/>
- <Action name="signaleditor"/>
- <Action name="buddyeditor"/>
- <Action name="tabordereditor"/>
- </Menu>
-</MenuBar>
-
-<ToolBar name="mainToolBar"><text>Main Toolbar</text>
- <Action name="file_save" group="file_operations"/>
- <Action name="designer_undo" group="edit_operations"/>
- <Action name="designer_redo" group="edit_operations"/>
- <Action name="designer_cut" group="edit_operations"/>
- <Action name="designer_copy" group="edit_operations"/>
- <Action name="designer_paste" group="edit_operations"/>
-</ToolBar>
-
-<ToolBar name="designerToolbar" noMerge="1"><text>Designer Layout Toolbar</text>
- <Action name="layout_horiz"/>
- <Action name="layout_vertical"/>
- <Action name="layout_split_horiz"/>
- <Action name="layout_split_vert"/>
- <Action name="layout_grid"/>
- <Action name="break_layout"/>
- <Separator/>
- <Action name="adjust_size"/>
-</ToolBar>
-
-</gui>
-
-<!-- kate: space-indent on; indent-width 4; replace-tabs on; -->
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.rc
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp (nonexistent)
@@ -1,277 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Roberto Raggi <roberto@kdevelop.org> *
- * Copyright 2005 Harald Fernengel <harry@kdevelop.org> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include "qtdesignerplugin.h"
-
-#include <QObject>
-#include <QAction>
-#include <QFile>
-#include <QTextStream>
-#include <QtDesigner/QtDesigner>
-#include <QtDesigner/QDesignerComponents>
-#include <QPluginLoader>
-#include <QWorkspace>
-
-#include <kaboutdata.h>
-#include <kaction.h>
-#include <kmimetype.h>
-#include <kxmlguiwindow.h>
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-#include <kparts/mainwindow.h>
-#include <kparts/partmanager.h>
-#include <ksavefile.h>
-#include <kstandardaction.h>
-#include <kicon.h>
-#include <kactioncollection.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/iuicontroller.h>
-#include "qtdesignerdocument.h"
-#include "internals/qdesigner_integration_p.h"
-
-K_PLUGIN_FACTORY(QtDesignerPluginFactory, registerPlugin<QtDesignerPlugin>(); )
-K_EXPORT_PLUGIN(QtDesignerPluginFactory(KAboutData("kdevqtdesigner","kdevqtdesigner", ki18n("Qt Designer"), "0.1", ki18n("A GUI form designer for the Qt toolkit"), KAboutData::License_GPL)))
-
-class QtDesignerDocumentFactory : public KDevelop::IDocumentFactory
-{
-public:
- QtDesignerDocumentFactory(QtDesignerPlugin* plugin)
- : KDevelop::IDocumentFactory(), m_plugin(plugin)
- {
- }
-
- KDevelop::IDocument* create( const KUrl& url, KDevelop::ICore* core)
- {
- kDebug(9038) << "creating doc for designer?";
- KMimeType::Ptr mimetype = KMimeType::findByUrl(url);
- kDebug(9038) << "mimetype for" << url << "is" << mimetype->name();
- if( mimetype->name() == "application/x-designer" )
- {
- QtDesignerDocument* d = new QtDesignerDocument(url, core);
- d->setDesignerPlugin(m_plugin);
-// m_plugin->activateDocument(d);
- return d;
- }
- return 0;
- }
- private:
- QtDesignerPlugin* m_plugin;
-};
-
-class QtDesignerToolViewFactory : public KDevelop::IToolViewFactory
-{
-public:
- enum Type
- {
- WidgetBox,
- PropertyEditor,
- ActionEditor,
- ObjectInspector,
- SignalSlotEditor,
- ResourceEditor
- };
- QtDesignerToolViewFactory( QtDesignerPlugin* plugin, Type typ )
- : IToolViewFactory(), m_plugin(plugin), m_type(typ)
- {
- }
-
- virtual QWidget* create(QWidget *parent = 0)
- {
- if( m_type == WidgetBox )
- return m_plugin->designer()->widgetBox();
- else if( m_type == PropertyEditor )
- return m_plugin->designer()->propertyEditor();
- else if( m_type == ActionEditor )
- return m_plugin->designer()->actionEditor();
- else if( m_type == ObjectInspector )
- return m_plugin->designer()->objectInspector();
- else if( m_type == SignalSlotEditor )
- return QDesignerComponents::createSignalSlotEditor(m_plugin->designer(), 0);
- else if( m_type == ResourceEditor )
- return QDesignerComponents::createResourceEditor(m_plugin->designer(), 0);
- kDebug(9038) << "Type not found:" << m_type;
- return 0;
- }
- virtual Qt::DockWidgetArea defaultPosition()
- {
- if( m_type == WidgetBox )
- return Qt::LeftDockWidgetArea;
- else if( m_type == PropertyEditor )
- return Qt::RightDockWidgetArea;
- else if( m_type == ActionEditor )
- return Qt::RightDockWidgetArea;
- else if( m_type == ObjectInspector )
- return Qt::RightDockWidgetArea;
- else if( m_type == SignalSlotEditor )
- return Qt::BottomDockWidgetArea;
- else if( m_type == ResourceEditor )
- return Qt::BottomDockWidgetArea;
- kDebug(9038) << "Type not found:" << m_type;
- return Qt::TopDockWidgetArea;
- }
-
- virtual QString id() const
- {
- if( m_type == WidgetBox )
- return "org.kevelop.qtdesigner.WidgetBox";
- else if( m_type == PropertyEditor )
- return "org.kevelop.qtdesigner.PropertyEditor";
- else if( m_type == ActionEditor )
- return "org.kevelop.qtdesigner.ActionEditor";
- else if( m_type == ObjectInspector )
- return "org.kevelop.qtdesigner.ObjectInspector";
- else if( m_type == SignalSlotEditor )
- return "org.kevelop.qtdesigner.SignalSlotEditor";
- else if( m_type == ResourceEditor )
- return "org.kevelop.qtdesigner.ResourceEditor";
- return QString();
- }
-
-private:
- QtDesignerPlugin* m_plugin;
- Type m_type;
-};
-
-QtDesignerPlugin::QtDesignerPlugin(QObject *parent, const QVariantList &args)
- : KDevelop::IPlugin(QtDesignerPluginFactory::componentData(),parent),
- m_docFactory(new QtDesignerDocumentFactory(this)),
- m_widgetBoxFactory(0), m_propertyEditorFactory(0),
- m_objectInspectorFactory(0), m_actionEditorFactory(0)
-{
- Q_UNUSED(args)
- QDesignerComponents::initializeResources();
-// connect( idc, SIGNAL( documentActivated( KDevelop::IDocument* ) ),
-// this, SLOT( activateDocument( KDevelop::IDocument* ) ) );
-
- QDesignerFormEditorInterface* formeditor = QDesignerComponents::createFormEditor(this);
- QDesignerComponents::initializePlugins( formeditor );
-
- kDebug(9038) << "integration:" << formeditor->integration();
-
- //TODO apaku: if multiple mainwindows exist, this needs to be changed on mainwindow-change
- formeditor->setTopLevel(core()->uiController()->activeMainWindow());
-
- formeditor->setWidgetBox(QDesignerComponents::createWidgetBox(formeditor, 0));
-
-// load the standard widgets
- formeditor->widgetBox()->setFileName(QLatin1String(":/trolltech/widgetbox/widgetbox.xml"));
- formeditor->widgetBox()->load();
-
- formeditor->setPropertyEditor(QDesignerComponents::createPropertyEditor(formeditor, 0));
- formeditor->setActionEditor(QDesignerComponents::createActionEditor(formeditor, 0));
- formeditor->setObjectInspector(QDesignerComponents::createObjectInspector(formeditor, 0));
-
- m_designer = new qdesigner_internal::QDesignerIntegration(formeditor, this);
- qdesigner_internal::QDesignerIntegration::initializePlugins( formeditor );
-
- kDebug() << "integration now:" << formeditor->integration();
-
- m_designer->core()->widgetBox()->setObjectName( i18n("Widget Box") );
- m_designer->core()->propertyEditor()->setObjectName( i18n("Property Editor") );
- m_designer->core()->actionEditor()->setObjectName( i18n("Action Editor") );
- m_designer->core()->objectInspector()->setObjectName( i18n("Object Inspector") );
-
-
- foreach (QObject *plugin, QPluginLoader::staticInstances())
- {
- QDesignerFormEditorPluginInterface *fep;
-
- if ( (fep = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) )
- {
- fep->initialize(designer());
- }
- }
- m_widgetBoxFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::WidgetBox );
- m_propertyEditorFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::PropertyEditor);
- m_actionEditorFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::ActionEditor);
- m_objectInspectorFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::ObjectInspector);
- m_signalSlotEditorFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::SignalSlotEditor);
- m_resourceEditorFactory = new QtDesignerToolViewFactory( this,
- QtDesignerToolViewFactory::ResourceEditor);
-
- core()->uiController()->addToolView("Widget Box", m_widgetBoxFactory );
- core()->uiController()->addToolView("Property Editor", m_propertyEditorFactory );
- core()->uiController()->addToolView("Action Editor", m_actionEditorFactory );
- core()->uiController()->addToolView("Object Inspector", m_objectInspectorFactory );
- core()->uiController()->addToolView("Signal/Slot Editor", m_signalSlotEditorFactory );
- core()->uiController()->addToolView("Resource Editor", m_resourceEditorFactory );
-
- KDevelop::IDocumentController* idc = core()->documentController();
- idc->registerDocumentForMimetype("application/x-designer", m_docFactory);
-}
-
-QtDesignerPlugin::~QtDesignerPlugin()
-{
- delete m_designer;
- delete m_docFactory;
-}
-
-QDesignerFormEditorInterface *QtDesignerPlugin::designer() const
-{
- return m_designer->core();
-}
-
-// bool QtDesignerPlugin::saveFile()
-// {
-// KSaveFile uiFile( localFilePath() );
-// //FIXME: find a way to return an error. KSaveFile
-// //doesn't use the KIO error codes
-// if ( !uiFile.open() )
-// return false;
-//
-// QTextStream stream ( &uiFile );
-// QByteArray windowXml = m_window->contents().toUtf8();
-// stream << windowXml;
-//
-// if ( !uiFile.finalize() )
-// return false;
-//
-// m_window->setDirty(false);
-// setModified(false);
-// return true;
-// }
-/*
-void QtDesignerPlugin::saveActiveDocument()
-{
- kDebug(9038) << "going to save:" << m_activeDoc;
- if( m_activeDoc )
- {
- m_activeDoc->save( KDevelop::IDocument::Default );
- }
-}
-
-void QtDesignerPlugin::activateDocument( KDevelop::IDocument* doc )
-{
- if( doc->mimeType()->is( "application/x-designer" ) )
- {
- kDebug(9038) << "Doc activated:" << doc;
- m_activeDoc = doc;
- }
-}*/
-
-#include "qtdesignerplugin.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h (nonexistent)
@@ -1,87 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Roberto Raggi <roberto@kdevelop.org> *
- * Copyright 2005 Harald Fernengel <harry@kdevelop.org> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef QTDESIGNER_PLUGIN_H
-#define QTDESIGNER_PLUGIN_H
-
-#include <QHash>
-#include <QtCore/QPointer>
-#include <interfaces/iplugin.h>
-#include <QtCore/QVariant>
-
-class QAction;
-class QDesignerIntegrationInterface;
-class QDesignerFormEditorInterface;
-class QtDesignerDocumentFactory;
-class QtDesignerToolViewFactory;
-
-namespace KDevelop
-{
- class IDocument;
-}
-
-template<class T> class QList;
-
-typedef QHash<QAction*, QAction*> DesignerActionHash;
-
-
-/**
- * This is a plugin that embeds Qt designer into a kdevplatform application
- *
- * TODO: - fix moving of form contents via mouse
- * TODO: - properly enable/disable save button
- * TODO: - detect external changes by using QFileSystemWatcher (more reliable implementation than KDirWatch)
- * TODO: - fix other ui bugs, like having to double-click in a menubar to edit it
- */
-class QtDesignerPlugin: public KDevelop::IPlugin
-{
- Q_OBJECT
-public:
- QtDesignerPlugin(QObject *parent, const QVariantList &args = QVariantList() );
- virtual ~QtDesignerPlugin();
-
-// virtual bool openFile();
-// virtual bool saveFile();
-
- QDesignerFormEditorInterface *designer() const;
-public Q_SLOTS:
-// void activateDocument( KDevelop::IDocument* );
-protected:
-
-private:
-
-private Q_SLOTS:
-// void saveActiveDocument();
-private:
- QDesignerIntegrationInterface* m_designer;
-
-// KDevelop::IDocument* m_activeDoc;
- QtDesignerDocumentFactory* m_docFactory;
- QtDesignerToolViewFactory* m_widgetBoxFactory;
- QtDesignerToolViewFactory* m_propertyEditorFactory;
- QtDesignerToolViewFactory* m_objectInspectorFactory;
- QtDesignerToolViewFactory* m_actionEditorFactory;
- QtDesignerToolViewFactory* m_signalSlotEditorFactory;
- QtDesignerToolViewFactory* m_resourceEditorFactory;
-};
-
-#endif // QTDESIGNER_PART_H
-//kate: space-indent on; indent-width 2; replace-tabs on; indent-mode cstyle;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerplugin.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.cpp (nonexistent)
@@ -1,43 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "qtdesignerview.h"
-
-#include <QtDesigner/QDesignerFormWindowInterface>
-
-#include "qtdesignerdocument.h"
-#include "qtdesignerwidget.h"
-
-QtDesignerView::QtDesignerView( QtDesignerDocument* doc )
- : Sublime::View( doc ), m_widget( 0 )
-{
-}
-
-QtDesignerView::~QtDesignerView()
-{
-}
-
-QWidget* QtDesignerView::createWidget( QWidget* parent )
-{
- return new QtDesignerWidget( parent, qobject_cast<QtDesignerDocument*>( document() ) );
-}
-
-#include "qtdesignerview.moc"
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerview.h (nonexistent)
@@ -1,43 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef QTDESIGNERVIEW_H
-#define QTDESIGNERVIEW_H
-
-#include <sublime/view.h>
-
-class QtDesignerDocument;
-class QtDesignerWidget;
-class QDesignerFormWindowInterface;
-
-class QtDesignerView : public Sublime::View
-{
- Q_OBJECT
-public:
- QtDesignerView( QtDesignerDocument* );
- ~QtDesignerView();
- QWidget* createWidget( QWidget* parent = 0 );
-private:
- QDesignerFormWindowInterface* m_form;
- QtDesignerWidget* m_widget;
-};
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.cpp (nonexistent)
@@ -1,164 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "qtdesignerwidget.h"
-
-#include <QtDesigner/QDesignerFormWindowInterface>
-#include <QtDesigner/QDesignerFormWindowManagerInterface>
-#include <QtDesigner/QDesignerFormEditorInterface>
-#include <QtDesigner/QDesignerFormEditorPluginInterface>
-#include <QtCore/QPluginLoader>
-#include <QtGui/QMdiSubWindow>
-
-#include <kdebug.h>
-#include <klocale.h>
-#include <kaction.h>
-#include <kstandardaction.h>
-#include <kactioncollection.h>
-
-#include <sublime/view.h>
-
-#include "qtdesignerdocument.h"
-#include "qtdesignerplugin.h"
-
-QtDesignerWidget::QtDesignerWidget( QWidget* parent, QtDesignerDocument* document )
- : QMdiArea( parent ), KXMLGUIClient(), m_document( document )
-{
- // area->setScrollBarsEnabled( true ); //FIXME commented just to make it compile with the new qt-copy
- // area->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
- // area->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
-
- QDesignerFormWindowInterface* form = m_document->form();
-
- setComponentData( m_document->designerPlugin()->componentData() );
- setXMLFile( "kdevqtdesigner.rc" );
-
- QMdiSubWindow* window = addSubWindow(form, Qt::Window | Qt::WindowShadeButtonHint | Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
- const QSize containerSize = form->mainContainer()->size();
- const QSize containerMinimumSize = form->mainContainer()->minimumSize();
- const QSize containerMaximumSize = form->mainContainer()->maximumSize();
- const QSize decorationSize = window->geometry().size() - window->contentsRect().size();
- window->resize(containerSize+decorationSize);
- window->setMinimumSize(containerMinimumSize+decorationSize);
- if( containerMaximumSize == QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX) )
- window->setMaximumSize(containerMaximumSize);
- else
- window->setMaximumSize(containerMaximumSize+decorationSize);
- window->setWindowTitle( form->mainContainer()->windowTitle() );
-
- setupActions();
-}
-
-void QtDesignerWidget::setupActions()
-{
-
- QDesignerFormWindowManagerInterface* manager = m_document->form()->core()->formWindowManager();
- KActionCollection* ac = actionCollection();
-
- KStandardAction::save( this, SLOT( save() ), ac);
- ac->addAction( "adjust_size", manager->actionAdjustSize() );
- ac->addAction( "break_layout", manager->actionBreakLayout() );
- ac->addAction( "designer_cut", manager->actionCut() );
- ac->addAction( "designer_copy", manager->actionCopy() );
- ac->addAction( "designer_paste", manager->actionPaste() );
- ac->addAction( "designer_delete", manager->actionDelete() );
- ac->addAction( "layout_grid", manager->actionGridLayout() );
- ac->addAction( "layout_horiz", manager->actionHorizontalLayout() );
- ac->addAction( "layout_vertical", manager->actionVerticalLayout() );
- ac->addAction( "layout_split_horiz", manager->actionSplitHorizontal() );
- ac->addAction( "layout_split_vert", manager->actionSplitVertical() );
- ac->addAction( "designer_undo", manager->actionUndo() );
- ac->addAction( "designer_redo", manager->actionRedo() );
- ac->addAction( "designer_select_all", manager->actionSelectAll() );
- KAction* action = ac->addAction( "widgeteditor" );
- action->setCheckable( true );
- action->setChecked( true );
- action->setText( i18n("Edit Widgets") );
- connect( action, SIGNAL(triggered()), SLOT(editWidgets()));
- foreach (QObject *plugin, QPluginLoader::staticInstances())
- {
- if ( !plugin )
- continue;
-
- kDebug() << "checking plugin:" << plugin;
- QDesignerFormEditorPluginInterface *fep;
-
- if ( (fep = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) )
- {
- // action name may have '&', remove them
- QString actionText = fep->action()->text();
- actionText = actionText.remove('&');
-
- fep->action()->setCheckable(true);
- if( actionText == "Edit Signals/Slots" ) {
- connect(fep->action(), SIGNAL(triggered()), SLOT(editSignals()));
- actionCollection()->addAction("signaleditor", fep->action());
- }
- if( actionText == "Edit Buddies" ) {
- connect(fep->action(), SIGNAL(triggered()), SLOT(editBuddys()));
- actionCollection()->addAction("buddyeditor", fep->action());
- }
- if( actionText == "Edit Tab Order" ) {
- connect(fep->action(), SIGNAL(triggered()), SLOT(editTabOrder()));
- actionCollection()->addAction("tabordereditor", fep->action());
- }
-
- kDebug(9038) << "Added action:" << fep->action()->objectName() << "|" << fep->action()->text();
- }
- }
-}
-
-void QtDesignerWidget::editWidgets()
-{
- QDesignerFormWindowInterface* form = m_document->form();
- form->editWidgets();
- actionCollection()->action("signaleditor")->setChecked(false);
- actionCollection()->action("buddyeditor")->setChecked(false);
- actionCollection()->action("tabordereditor")->setChecked(false);
-}
-
-void QtDesignerWidget::editBuddys()
-{
- actionCollection()->action("widgeteditor")->setChecked(false);
- actionCollection()->action("signaleditor")->setChecked(false);
- actionCollection()->action("tabordereditor")->setChecked(false);
-}
-
-void QtDesignerWidget::editSignals()
-{
- actionCollection()->action("widgeteditor")->setChecked(false);
- actionCollection()->action("buddyeditor")->setChecked(false);
- actionCollection()->action("tabordereditor")->setChecked(false);
-}
-
-void QtDesignerWidget::editTabOrder()
-{
- actionCollection()->action("widgeteditor")->setChecked(false);
- actionCollection()->action("buddyeditor")->setChecked(false);
- actionCollection()->action("signaleditor")->setChecked(false);
-}
-
-void QtDesignerWidget::save()
-{
- m_document->save();
-}
-
-#include "qtdesignerwidget.moc"
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerwidget.h (nonexistent)
@@ -1,45 +0,0 @@
-/***************************************************************************
-* This file is part of KDevelop *
-* Copyright 2008 Andreas Pakulat <apaku@gmx.de> *
-* *
-* This program 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 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 Library General Public *
-* License along with this program; if not, write to the *
-* Free Software Foundation, Inc., *
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
-***************************************************************************/
-
-#ifndef QTDESIGNERWIDGET_H
-#define QTDESIGNERWIDGET_H
-
-#include <QtGui/QMdiArea>
-#include <kxmlguiclient.h>
-
-class QtDesignerDocument;
-
-class QtDesignerWidget : public QMdiArea, public KXMLGUIClient
-{
- Q_OBJECT
- public:
- QtDesignerWidget( QWidget* parent, QtDesignerDocument* document );
- private slots:
- void save();
- void editWidgets();
- void editBuddys();
- void editSignals();
- void editTabOrder();
- private:
- void setupActions();
- QtDesignerDocument* m_document;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h (nonexistent)
@@ -1,58 +0,0 @@
-/****************************************************************************
-**
-** Copyright 1992-2006 Trolltech AS. All rights reserved.
-**
-** This file is part of the Qt Designer of the Qt Toolkit.
-**
-** This file may be used under the terms of the GNU General Public
-** License version 2.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of
-** this file. Please review the following information to ensure GNU
-** General Public Licensing requirements will be met:
-** http://www.trolltech.com/products/qt/opensource.html
-**
-** If you are unsure which license is appropriate for your use, please
-** review the following information:
-** http://www.trolltech.com/products/qt/licensing.html or contact the
-** sales department at sales@trolltech.com.
-**
-** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
-** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of Qt Designer. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef SHARED_GLOBAL_H
-#define SHARED_GLOBAL_H
-
-#include <QtCore/qglobal.h>
-
-#ifdef QT_DESIGNER_STATIC
-#define QDESIGNER_SHARED_EXTERN
-#define QDESIGNER_SHARED_IMPORT
-#else
-#define QDESIGNER_SHARED_EXTERN Q_DECL_EXPORT
-#define QDESIGNER_SHARED_IMPORT Q_DECL_IMPORT
-#endif
-
-#ifndef QT_NO_SHARED_EXPORT
-# ifdef QDESIGNER_SHARED_LIBRARY
-# define QDESIGNER_SHARED_EXPORT QDESIGNER_SHARED_EXTERN
-# else
-# define QDESIGNER_SHARED_EXPORT QDESIGNER_SHARED_IMPORT
-# endif
-#else
-# define QDESIGNER_SHARED_EXPORT
-#endif
-
-#endif // SHARED_GLOBAL_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/shared_global_p.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h (nonexistent)
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright 1992-2007 Trolltech ASA. All rights reserved.
-**
-** This file is part of the Qt Designer of the Qt Toolkit.
-**
-** This file may be used under the terms of the GNU General Public
-** License version 2.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of
-** this file. Please review the following information to ensure GNU
-** General Public Licensing requirements will be met:
-** http://www.trolltech.com/products/qt/opensource.html
-**
-** If you are unsure which license is appropriate for your use, please
-** review the following information:
-** http://www.trolltech.com/products/qt/licensing.html or contact the
-** sales department at sales@trolltech.com.
-**
-** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
-** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-**
-****************************************************************************/
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists for the convenience
-// of Qt Designer. This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QDESIGNER_INTEGRATION_H
-#define QDESIGNER_INTEGRATION_H
-
-#include "shared_global_p.h"
-#include <QtDesigner/QDesignerIntegrationInterface>
-
-#include <QtCore/QObject>
-
-class QDesignerFormEditorInterface;
-class QDesignerFormWindowInterface;
-class QDesignerFormWindowManagerInterface;
-
-class QVariant;
-class QWidget;
-
-namespace qdesigner_internal {
-
-struct Selection;
-
-class QDESIGNER_SHARED_EXPORT QDesignerIntegration: public QDesignerIntegrationInterface
-{
- Q_OBJECT
-public:
- QDesignerIntegration(QDesignerFormEditorInterface *core, QObject *parent = 0);
- virtual ~QDesignerIntegration();
-
- virtual QWidget *containerWindow(QWidget *widget) const;
-
- // Load plugins into widget database and factory.
- static void initializePlugins(QDesignerFormEditorInterface *formEditor);
-
-signals:
- void propertyChanged(QDesignerFormWindowInterface *formWindow, const QString &name, const QVariant &value);
-
-public slots:
- //virtual void updateProperty(const QString &name, const QVariant &value);
- // Additional signals of designer property editor
- virtual void updatePropertyComment(const QString &name, const QString &value);
- virtual void resetProperty(const QString &name);
- virtual void addDynamicProperty(const QString &name, const QVariant &value);
- virtual void removeDynamicProperty(const QString &name);
-
-
- virtual void updateActiveFormWindow(QDesignerFormWindowInterface *formWindow);
- virtual void setupFormWindow(QDesignerFormWindowInterface *formWindow);
- virtual void updateSelection();
- virtual void updateGeometry();
- virtual void activateWidget(QWidget *widget);
-
- void updateCustomWidgetPlugins();
-
-private:
- void initialize();
- void getSelection(Selection &s);
- QObject *propertyEditorObject();
-
- QDesignerFormWindowManagerInterface *m_formWindowManager;
-};
-
-} // namespace qdesigner_internal
-
-#endif // QDESIGNER_INTEGRATION_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/internals/qdesigner_integration_p.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop (nonexistent)
@@ -1,75 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=GUI Builder based on Qt Designer
-Comment[bs]=GUI Builder baziran na Qt Designer-u.
-Comment[ca]=Constructor d'IGU basat en Qt Designer
-Comment[ca@valencia]=Constructor d'IGU basat en Qt Designer
-Comment[de]=GUI-Designer auf der Basis vom Qt-Designer
-Comment[en_GB]=GUI Builder based on Qt Designer
-Comment[es]=Constructor de interfaces gráficas basado en QtDesigner
-Comment[et]=GUI ehitaja Qt Disaineri põhjal
-Comment[fr]=Constructeur d'interfaces graphiques fondé sur Qt Designer
-Comment[gl]=Construtor de interfaces gráficas baseado en Qt Designer.
-Comment[it]=Creatore di interfacce basato su Qt Designer
-Comment[nl]=GUI Builder gebaseerd op Qt Designer
-Comment[pl]=Program budujący GUI oparty o projektanta Qt
-Comment[pt]=Construtor de GUI, baseado no Qt Designer
-Comment[pt_BR]=Construtor de GUI baseado no Qt Designer
-Comment[sv]=Grafisk gränssnittskonstruktion baserad på Qt Designer
-Comment[uk]=Створення графічного інтерфейсу з Дизайнера Qt
-Comment[x-test]=xxGUI Builder based on Qt Designerxx
-Name=Qt Designer Integration
-Name[bs]=Qt Dizajnerska integracija
-Name[ca]=Integració del Qt Designer
-Name[ca@valencia]=Integració del Qt Designer
-Name[de]=Qt-Designer-Integration
-Name[en_GB]=Qt Designer Integration
-Name[es]=Integración del Diseñador Qt
-Name[et]=Qt Disaineri lõimimine
-Name[fr]=Intégration de Qt Designer
-Name[ga]=Comhtháthú Qt Designer
-Name[gl]=Integración con Qt Designer
-Name[it]=integrazione di Qt Designer
-Name[nds]=QtDesigner-Inbinnen
-Name[nl]=Qt Designer Integratie
-Name[pl]=Integracja projektanta Qt
-Name[pt]=Integração com o Qt Designer
-Name[pt_BR]=Integração com o Qt Designer
-Name[sv]=Integrering med Qt Designer
-Name[tr]=Qt tasarımcı Bütünleşmesi
-Name[ug]=Qt لايىھىلىگۈچ يۈرۈشلەشتۈرۈلۈشى
-Name[uk]=Інтеграція Дизайнера Qt
-Name[x-test]=xxQt Designer Integrationxx
-GenericName=GUI Designer Integration
-GenericName[bs]=Qt Dizajnerska integracija
-GenericName[ca]=Integració del dissenyador d'IGU
-GenericName[ca@valencia]=Integració del dissenyador d'IGU
-GenericName[de]=GUI-Designer-Integration
-GenericName[en_GB]=GUI Designer Integration
-GenericName[es]=Integración del diseñador de interfaces gráficas
-GenericName[et]=Graafilise Disaineri lõimine
-GenericName[fr]=Intégration du concepteur d'interfaces graphiques
-GenericName[gl]=Funcionalidade de deseño de interfaces gráficas
-GenericName[it]=Integrazione di GUI Designer
-GenericName[nds]=Böversietmaker-Inbinnen
-GenericName[nl]=GUI Designer Integratie
-GenericName[pl]=Integracja projektanta GUI
-GenericName[pt]=Integração com o Desenhador de GUI's
-GenericName[pt_BR]=Integração com o Desenhador de GUI's
-GenericName[sv]=Integrering med grafisk gränssnittskonstruktion
-GenericName[tr]=Arayüz Tasarlayıcı Bütünleşmesi
-GenericName[ug]=GUI لايىھىلىگۈچ يۈرۈشلەشتۈرۈلۈشى
-GenericName[uk]=Інтеграція дизайнера графічного інтерфейсу
-GenericName[x-test]=xxGUI Designer Integrationxx
-icon=kdevelop
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevqtdesigner
-X-KDE-PluginInfo-Name=kdevqtdesigner
-X-KDE-PluginInfo-Author=Matt Rogers
-X-KDE-PluginInfo-Email=mattr@kde.org
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=9
-X-KDevelop-SupportedMimeTypes=application/x-designer
-X-KDevelop-Mode=GUI
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/kdevqtdesigner.desktop
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp (nonexistent)
@@ -1,258 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-/****************************************************************************
-**
-** Copyright 1992-2006 Trolltech AS. All rights reserved.
-**
-** This file is part of the Qt Designer of the Qt Toolkit.
-**
-** This file may be used under the terms of the GNU General Public
-** License version 2.0 as published by the Free Software Foundation
-** and appearing in the file LICENSE.GPL included in the packaging of
-** this file. Please review the following information to ensure GNU
-** General Public Licensing requirements will be met:
-** http://www.trolltech.com/products/qt/opensource.html
-**
-** If you are unsure which license is appropriate for your use, please
-** review the following information:
-** http://www.trolltech.com/products/qt/licensing.html or contact the
-** sales department at sales@trolltech.com.
-**
-** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
-** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-**
-****************************************************************************/
-
-#include "qtdesignerdocument.h"
-
-#include <QtDesigner/QDesignerFormWindowManagerInterface>
-#include <QtDesigner/QDesignerFormWindowInterface>
-#include <QtDesigner/QDesignerFormEditorInterface>
-#include <QtGui/QMdiArea>
-#include <QtGui/QMdiSubWindow>
-#include <QtCore/QFile>
-#include <QApplication>
-#include <KMessageBox>
-#include <KLocale>
-
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-#include <interfaces/idocumentcontroller.h>
-#include <sublime/view.h>
-#include <sublime/area.h>
-#include <sublime/controller.h>
-
-#include "qtdesignerview.h"
-#include "qtdesignerplugin.h"
-
-QtDesignerDocument::QtDesignerDocument( const KUrl& url , KDevelop::ICore* core )
- : Sublime::UrlDocument(core->uiController()->controller(), url),
- KDevelop::IDocument(core), m_state(KDevelop::IDocument::Clean)
-{
-
-}
-
-KSharedPtr<KMimeType> QtDesignerDocument::mimeType() const
-{
- return KMimeType::mimeType("application/x-designer");
-}
-
-KParts::Part* QtDesignerDocument::partForView(QWidget*) const
-{
- return 0;
-}
-
-KTextEditor::Document* QtDesignerDocument::textDocument() const
-{
- return 0;
-}
-
-bool QtDesignerDocument::save(KDevelop::IDocument::DocumentSaveMode mode)
-{
- if (mode & Discard)
- return true;
-
- kDebug(9038) << "Going to Save";
- if( m_state == KDevelop::IDocument::Clean )
- return false;
- if( !m_form )
- return false;
- QFile f(url().toLocalFile());
- if( !f.open( QIODevice::WriteOnly ) )
- {
- kDebug(9038) << "Couldn't open file:" << f.error();
- return false;
- }
- QTextStream s(&f);
- s << m_form->contents();
- s.flush();
- f.close();
- m_state = KDevelop::IDocument::Clean;
- notifySaved();
- return true;
-}
-
-void QtDesignerDocument::reload()
-{
- QFile uiFile(url().toLocalFile());
- m_form->setContents(&uiFile);
- m_state = KDevelop::IDocument::Clean;
- notifyStateChanged();
-}
-
-bool QtDesignerDocument::close(KDevelop::IDocument::DocumentSaveMode mode)
-{
- kDebug() << "form:" << m_form;
- if (!(mode & Discard)) {
- if (mode & Silent) {
- if (!save(mode))
- return false;
-
- } else {
- if (state() == IDocument::Modified) {
- int code = KMessageBox::warningYesNoCancel(
- qApp->activeWindow(),
- i18n("The document \"%1\" has unsaved changes. Would you like to save them?", url().toLocalFile()),
- i18n("Close Document"));
-
- if (code == KMessageBox::Yes) {
- if (!save(mode))
- return false;
-
- } else if (code == KMessageBox::Cancel) {
- return false;
- }
-
- } else if (state() == IDocument::DirtyAndModified) {
- if (!save(mode))
- return false;
- }
- }
- }
-
- //close all views and then delete ourself
- ///@todo test this
- foreach (Sublime::Area *area,
- KDevelop::ICore::self()->uiController()->controller()->allAreas())
- {
- QList<Sublime::View*> areaViews = area->views();
- foreach (Sublime::View *view, areaViews) {
- if (views().contains(view)) {
- kDebug() << "form before:" << m_form;
- kDebug() << "closing view" << view;
- kDebug() << "form after:" << m_form;
- area->removeView(view);
- delete view;
- }
- }
- }
-
-// kDebug() << "removing" << m_form << "from window manager";
- // m_designerPlugin->designer()->formWindowManager()->removeFormWindow(m_form);
-
- KDevelop::ICore::self()->documentController()->notifyDocumentClosed(this);
-
- // Here we go...
- deleteLater();
-
- return true;
-}
-
-bool QtDesignerDocument::isActive() const
-{
- QDesignerFormWindowInterface* activeWin =
- m_designerPlugin->designer()->formWindowManager()->activeFormWindow();
- if( activeWin == m_form )
- return true;
- return false;
-}
-
-KDevelop::IDocument::DocumentState QtDesignerDocument::state() const
-{
- return m_state;
-}
-
-void QtDesignerDocument::setCursorPosition(const KTextEditor::Cursor&)
-{
- return;
-}
-
-void QtDesignerDocument::setTextSelection(const KTextEditor::Range &)
-{
-}
-
-void QtDesignerDocument::activate(Sublime::View* view, KParts::MainWindow*)
-{
- m_designerPlugin->designer()->formWindowManager()->setActiveFormWindow( m_form );
- notifyActivated();
-}
-
-void QtDesignerDocument::setDesignerPlugin(QtDesignerPlugin* plugin)
-{
- m_designerPlugin = plugin;
-}
-
-Sublime::View *QtDesignerDocument::newView(Sublime::Document* doc)
-{
- if( qobject_cast<QtDesignerDocument*>( doc ) ) {
- QFile uiFile(url().toLocalFile());
- uiFile.open(QIODevice::ReadOnly | QIODevice::Text);
-
- m_form = designerPlugin()->designer()->formWindowManager()->createFormWindow();
- kDebug(9038) << "now we have" << m_form->core()->formWindowManager()->formWindowCount() << "formwindows";
- m_form->setFileName(url().toLocalFile());
- m_form->setContents(&uiFile);
- connect( m_form, SIGNAL(changed()), this, SLOT(formChanged()));
- designerPlugin()->designer()->formWindowManager()->setActiveFormWindow(m_form);
- return new QtDesignerView( this );
- }
- return 0;
-}
-
-QDesignerFormWindowInterface* QtDesignerDocument::form()
-{
- return m_form;
-}
-
-void QtDesignerDocument::formChanged()
-{
- m_state = KDevelop::IDocument::Modified;
- notifyStateChanged();
-}
-
-KTextEditor::Cursor QtDesignerDocument::cursorPosition( ) const
-{
- return KTextEditor::Cursor();
-}
-
-QtDesignerPlugin* QtDesignerDocument::designerPlugin()
-{
- return m_designerPlugin;
-}
-
-
-bool QtDesignerDocument::closeDocument()
-{
- return close();
-}
-
-
-#include "qtdesignerdocument.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h (nonexistent)
@@ -1,72 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef QTDESIGNERDOCUMENT_H
-#define QTDESIGNERDOCUMENT_H
-
-#include <QtCore/QList>
-
-#include <sublime/urldocument.h>
-#include <interfaces/idocument.h>
-
-namespace KDevelop
-{
- class ICore;
-}
-
-class QtDesignerPlugin;
-class QDesignerFormWindowInterface;
-class QMdiArea;
-
-class QtDesignerDocument : public Sublime::UrlDocument, public KDevelop::IDocument
-{
- Q_OBJECT
-public:
- QtDesignerDocument( const KUrl&, KDevelop::ICore* );
-
- KUrl url() const { return Sublime::UrlDocument::url(); }
-
- virtual KSharedPtr<KMimeType> mimeType() const;
- virtual KParts::Part* partForView(QWidget*) const;
- virtual KTextEditor::Document* textDocument() const;
- virtual bool save(KDevelop::IDocument::DocumentSaveMode = KDevelop::IDocument::Default);
- virtual void reload();
- virtual bool close(KDevelop::IDocument::DocumentSaveMode = KDevelop::IDocument::Default);
- virtual bool isActive() const;
- virtual DocumentState state() const;
- virtual void setCursorPosition(const KTextEditor::Cursor&);
- virtual void setTextSelection(const KTextEditor::Range &range);
- virtual void activate(Sublime::View*, KParts::MainWindow*);
- virtual KTextEditor::Cursor cursorPosition() const;
- void setDesignerPlugin(QtDesignerPlugin*);
- QtDesignerPlugin* designerPlugin();
- QDesignerFormWindowInterface* form();
- virtual bool closeDocument();
-private slots:
- void formChanged();
- Sublime::View* newView( Sublime::Document* d );
-private:
- QtDesignerPlugin* m_designerPlugin;
- KDevelop::IDocument::DocumentState m_state;
- QDesignerFormWindowInterface* m_form;
-};
-
-#endif
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner/qtdesignerdocument.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/qtdesigner
___________________________________________________________________
Deleted: svn:ignore
## -1,4 +0,0 ##
-.libs
-Makefile
-Makefile.in
-*.moc
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/CMakeLists.txt (nonexistent)
@@ -1,28 +0,0 @@
-find_package(KDE4 REQUIRED)
-include(MacroOptionalAddSubdirectory)
-
-macro_optional_depend_package(KDevelop "kdevelop")
-if(DEPEND_PACKAGE_KDevelop)
- macro_optional_find_package(KDevelop)
-else(DEPEND_PACKAGE_KDevelop)
- set(KDEVELOP_FOUND FALSE)
-endif(DEPEND_PACKAGE_KDevelop)
-
-if(KDEVELOP_FOUND)
-macro_optional_add_subdirectory( automake )
-endif(KDEVELOP_FOUND)
-macro_optional_add_subdirectory( bazaar )
-macro_optional_add_subdirectory( csharp )
-macro_optional_add_subdirectory( ctest )
-macro_optional_add_subdirectory( duchainviewer )
-
-#commented out pending being brought up to speed with the current kdevelop api
-#macro_optional_add_subdirectory( check )
-
-macro_optional_add_subdirectory( java )
-macro_optional_add_subdirectory( metrics )
-macro_optional_add_subdirectory( preprocessor)
-macro_optional_add_subdirectory( sloc )
-macro_optional_add_subdirectory( teamwork )
-macro_optional_add_subdirectory( cppunit )
-macro_optional_add_subdirectory( qtdesigner )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.cpp (nonexistent)
@@ -1,84 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "coveredfile.h"
-
-using Veritas::CoveredFile;
-
-CoveredFile::CoveredFile()
- : m_nrofLines(0), m_nrofCoveredLines(0)
-{}
-
-CoveredFile::~CoveredFile()
-{
-}
-
-KUrl CoveredFile::url() const
-{
- return m_sourceLoc;
-}
-
-void CoveredFile::setUrl(const KUrl& url)
-{
- m_sourceLoc = url;
-}
-
-void CoveredFile::setCallCount(int line, int count)
-{
- m_nrofCalls[line] = count;
- m_reachableLines << line;
- m_nrofLines = m_reachableLines.count();
- if (count != 0) {
- m_coveredLines << line;
- m_nrofCoveredLines = m_coveredLines.count();
- }
-}
-
-QSet<int> CoveredFile::coveredLines() const
-{
- return m_coveredLines;
-}
-
-QSet<int> CoveredFile::reachableLines() const
-{
- return m_reachableLines;
-}
-
-double CoveredFile::coverageRatio() const
-{
- if (m_nrofLines == 0) return 0;
- return 100*(double)m_nrofCoveredLines/(double)m_nrofLines;
-}
-
-int CoveredFile::sloc() const
-{
- return m_nrofLines;
-}
-
-int CoveredFile::nrofCoveredLines() const
-{
- return m_nrofCoveredLines;
-}
-
-QMap<int, int> CoveredFile::callCountMap() const
-{
- return m_nrofCalls;
-}
-
-#include "coveredfile.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h (nonexistent)
@@ -1,52 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBTEST_H
-#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBTEST_H
-
-#include <QtCore/QObject>
-
-namespace Veritas {
-
-class RemoveGcdaFilesJobTest: public QObject {
-Q_OBJECT
-private slots:
-
- void initTestCase();
- void init();
- void cleanup();
- void cleanupTestCase();
-
- void testRemoveFilesInSingleDirectory();
- void testRemoveFilesInComplexDirectory();
-
- void testStopJob();
-
-private:
-
- QString m_testPath;
-
- void createFile(const QString& filename);
- void deleteDirectory(const QString& filename);
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp (nonexistent)
@@ -1,75 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "lcovjobtest.h"
-#include "../lcovjob.h"
-#include "../covoutputdelegate.h"
-#include "plugincontrollerstub.h"
-#include "corestub.h"
-#include "pluginstub.h"
-#include <KProcess>
-#include <QtTest/QTest>
-#include <qtest_kde.h>
-
-using Veritas::CovOutputDelegate;
-using Veritas::LcovJob;
-using Veritas::LcovJobTest;
-
-namespace
-{
-class MyKProcess : public KProcess
-{
-public:
- MyKProcess() : m_startCalled(false) {}
- virtual ~MyKProcess() {}
- virtual void start() { m_startCalled = true; }
- bool m_startCalled;
-};
-}
-
-void LcovJobTest::initTestCase()
-{
- m_core = new TestStubs::Core;
- Q_ASSERT(m_core);
- m_plugCtrl = new TestStubs::PluginController;
- m_plugCtrl->m_pluginForExtension = new TestStubs::Plugin(KGlobal::mainComponent(), 0);
- m_core->m_pluginController = m_plugCtrl;
-}
-
-void LcovJobTest::init()
-{
-}
-
-void LcovJobTest::cleanup()
-{
-}
-
-void LcovJobTest::basicRun()
-{
- MyKProcess* proc = new MyKProcess;
- CovOutputDelegate* del = new CovOutputDelegate;
- LcovJob* m_job = new LcovJob(KUrl("/my/root/dir"));
- m_job->setProcess(proc);
- m_job->setDelegate(del);
- m_job->start();
-}
-
-QTEST_KDEMAIN( LcovJobTest, NoGUI)
-#include "lcovjobtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp (nonexistent)
@@ -1,440 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "reportwidgettest.h"
-
-#define protected public
-#define private public
-#include "../reportwidget.h"
-#undef private
-#undef protected
-
-#include "../coveredfile.h"
-#include "../drilldownview.h"
-#include "../reportmodel.h"
-#include "../reportproxymodel.h"
-#include "../ui_reportwidget.h"
-
-#include <QtTest/QTest>
-#include <QtTest/QTestKeyClicksEvent>
-#include <qtest_kde.h>
-#include <QDir>
-#include <QLabel>
-
-using Veritas::CoveredFile;
-using Veritas::DrillDownView;
-using Veritas::ReportDirData;
-using Veritas::ReportModel;
-using Veritas::ReportProxyModel;
-using Veritas::ReportWidget;
-using Veritas::ReportWidgetTest;
-
-void ReportWidgetTest::init()
-{
- m_reportWidget = new ReportWidget(0);
- m_reportWidget->init();
-}
-
-void ReportWidgetTest::cleanup()
-{
- delete m_reportWidget;
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithRawDataFloorRoundedCoverage()
-{
-
- ReportDirData data;
- data.setSloc(10000);
- data.setNrofCoveredLines(4223);
- m_reportWidget->setCoverageStatistics(data);
-
- assertStatistics(m_reportWidget, 10000, 4223, 42.2);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithRawDataCeilRoundedCoverage()
-{
- ReportDirData data;
- data.setSloc(100000);
- data.setNrofCoveredLines(42160);
- m_reportWidget->setCoverageStatistics(data);
-
- assertStatistics(m_reportWidget, 100000, 42160, 42.2);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithNewSelection()
-{
- setModelFor(m_reportWidget);
-
- QItemSelection selection;
- QModelIndex topLeft = table(m_reportWidget)->model()->index(0, 0);
- QModelIndex bottomRight = table(m_reportWidget)->model()->index(3, 1);
- selection.select(topLeft, bottomRight);
-
- m_reportWidget->setCoverageStatistics(selection, QItemSelection());
-
- assertStatistics(m_reportWidget, 8, 4, 50.0);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithAddedSelection()
-{
- setModelFor(m_reportWidget);
-
- setStatistics(m_reportWidget, 12, 12);
-
- QItemSelection selection;
- QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
- QModelIndex second = table(m_reportWidget)->model()->index(1, 0);
- selection.select(first, second);
-
- m_reportWidget->setCoverageStatistics(selection, QItemSelection());
-
- assertStatistics(m_reportWidget, 16, 15, 93.8);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithRemovedSelection()
-{
- setModelFor(m_reportWidget);
-
- setStatistics(m_reportWidget, 8, 6);
-
- QItemSelection deselection;
- QModelIndex second = table(m_reportWidget)->model()->index(1, 0);
- QModelIndex third = table(m_reportWidget)->model()->index(2, 0);
- deselection.select(second, third);
-
- m_reportWidget->setCoverageStatistics(QItemSelection(), deselection);
-
- assertStatistics(m_reportWidget, 4, 4, 100.0);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithChangedSelection()
-{
- setModelFor(m_reportWidget);
-
- setStatistics(m_reportWidget, 16, 15);
-
- QItemSelection selection;
- QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
- selection.select(first, first);
-
- QItemSelection deselection;
- QModelIndex fourth = table(m_reportWidget)->model()->index(3, 0);
- deselection.select(fourth, fourth);
-
- m_reportWidget->setCoverageStatistics(selection, deselection);
-
- assertStatistics(m_reportWidget, 18, 17, 94.4);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithEmptySelection()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->setCoverageStatistics(QItemSelection(), QItemSelection());
-
- assertEmptyStatistics(m_reportWidget);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithInvalidSelection()
-{
- setModelFor(m_reportWidget);
-
- QItemSelection selection;
- QModelIndex index;
- selection.select(index, index);
-
- m_reportWidget->setCoverageStatistics(selection, QItemSelection());
-
- assertEmptyStatistics(m_reportWidget);
-}
-
-//Shouldn't happen, but just in case... it should ignore file items and only
-//take into account directory items
-void ReportWidgetTest::setCoverageStatisticsWithDirectoriesAndFileSelection()
-{
- setModelFor(m_reportWidget);
-
- QItemSelection selection;
- QModelIndex first = table(m_reportWidget)->model()->index(0, 0);
- selection.select(first, first);
-
- QModelIndex third = table(m_reportWidget)->model()->index(2, 1);
- QModelIndex thirdFile1 = table(m_reportWidget)->model()->index(0, 0, third);
- selection.select(thirdFile1, thirdFile1);
-
- QModelIndex fourth = table(m_reportWidget)->model()->index(3, 0);
- selection.select(fourth, fourth);
-
- m_reportWidget->setCoverageStatistics(selection, QItemSelection());
-
- assertStatistics(m_reportWidget, 4, 2, 50.0);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithIndex()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->setCoverageStatistics(table(m_reportWidget)->model()->index(0, 0));
-
- assertStatistics(m_reportWidget, 3, 2, 66.7);
-}
-
-void ReportWidgetTest::setCoverageStatisticsWithInvalidIndex()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->setCoverageStatistics(QModelIndex());
-
- assertEmptyStatistics(m_reportWidget);
-}
-
-//Shouldn't modify the statistics
-void ReportWidgetTest::setCoverageStatisticsWithFileIndex()
-{
- setModelFor(m_reportWidget);
-
- QModelIndex dirIndex = table(m_reportWidget)->model()->index(0, 0);
- m_reportWidget->setCoverageStatistics(table(m_reportWidget)->model()->index(0, 0, dirIndex));
-
- assertEmptyStatistics(m_reportWidget);
-}
-
-//Selects first directory
-void ReportWidgetTest::statisticsSelectingSingleDirectory()
-{
- setModelFor(m_reportWidget);
-
- //TODO I can't get it to work without showing the widget and waiting some
- //time before triggering the click. Is there a way for this to work without
- //showing the widget and waiting?
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
-
- assertStatistics(m_reportWidget, 3, 2, 66.7);
-}
-
-//Selects all directories
-void ReportWidgetTest::statisticsSelectingSeveralDirectories()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
-
- assertStatistics(m_reportWidget, 8, 4, 50.0);
-}
-
-//Selects second and fourth directories
-void ReportWidgetTest::statisticsSelectingSeveralDirectoriesNotContiguous()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ControlModifier);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ControlModifier);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::ControlModifier);
-
- assertStatistics(m_reportWidget, 2, 1, 50.0);
-}
-
-//Selects second and fourth directories
-void ReportWidgetTest::statisticsSelectingSeveralDirectoriesNotContiguousUsingMouse()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
-
- QModelIndex dirIndex = table(m_reportWidget)->model()->index(1, 0);
- QPoint point = table(m_reportWidget)->visualRect(dirIndex).center();
- //The widget used must be the viewport, as simulating the mouse press on
- //the table doesn't even deliver a mousePressEvent to it (I don't know
- //why)
- QTest::mousePress(table(m_reportWidget)->viewport(), Qt::LeftButton,
- Qt::NoModifier, point, 500);
-
- dirIndex = table(m_reportWidget)->model()->index(3, 1);
- point = table(m_reportWidget)->visualRect(dirIndex).center();
- QTest::mouseClick(table(m_reportWidget)->viewport(), Qt::LeftButton,
- Qt::ControlModifier, point);
-
- assertStatistics(m_reportWidget, 2, 1, 50.0);
-}
-
-//Selects first directory, and clicks on an empty space
-void ReportWidgetTest::statisticsAfterClearingSelection()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
-
- QModelIndex dirIndex = table(m_reportWidget)->model()->index(3, 0);
- QPoint point = table(m_reportWidget)->visualRect(dirIndex).bottomLeft();
- point.setX(point.x() + 10);
- point.setY(point.y() + 10);
- QTest::mousePress(table(m_reportWidget)->viewport(), Qt::LeftButton,
- Qt::NoModifier, point);
-
- assertStatistics(m_reportWidget, 0, 0, 0.0);
-}
-
-//Selects first and second directory, and slides in second directory
-void ReportWidgetTest::statisticsAfterSlidingRight()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Space, Qt::NoModifier, 500);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::ShiftModifier);
-
- QTest::keyClick(table(m_reportWidget), Qt::Key_Right);
-
- assertStatistics(m_reportWidget, 1, 1, 100.0);
-}
-
-//Selects fourth, third and second directory, slides in second directory,
-//selects first file, slides left, and selects third directory
-
-void ReportWidgetTest::statisticsAfterSlidingLeft()
-{
- setModelFor(m_reportWidget);
-
- m_reportWidget->show();
- table(m_reportWidget)->setFocus();
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Up, Qt::ShiftModifier);
- QTest::keyClick(table(m_reportWidget), Qt::Key_Up, Qt::ShiftModifier);
-
- QTest::keyClick(table(m_reportWidget), Qt::Key_Right);
-
- //Wait to avoid the slide to eat the event
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
-
- assertStatistics(m_reportWidget, 1, 1, 100.0);
-
- QTest::keyClick(table(m_reportWidget), Qt::Key_Left);
-
- assertStatistics(m_reportWidget, 5, 2, 40.0);
-
- //Wait to avoid the slide to eat the event
- QTest::keyClick(table(m_reportWidget), Qt::Key_Down, Qt::NoModifier, 500);
-
- assertStatistics(m_reportWidget, 3, 1, 33.3);
-}
-
-////////////////////////////// Asserts ////////////////////////////////////////
-
-void ReportWidgetTest::assertStatistics(ReportWidget* rw, int sloc,
- int instrumented, double coverage)
-{
- QCOMPARE(rw->m_ui->sloc->text(), QString::number(sloc));
- QCOMPARE(rw->m_ui->nrofCoveredLines->text(), QString::number(instrumented));
- QCOMPARE(rw->m_ui->coverageRatio->text(), QLocale().toString(coverage, 'f', 1) + " %");
-}
-
-void ReportWidgetTest::assertEmptyStatistics(ReportWidget* rw)
-{
- QCOMPARE(rw->m_ui->sloc->text(), QString("-"));
- QCOMPARE(rw->m_ui->nrofCoveredLines->text(), QString("-"));
- QCOMPARE(rw->m_ui->coverageRatio->text(), QString("-"));
-}
-
-////////////////////////////// Helpers ////////////////////////////////////////
-
-DrillDownView* ReportWidgetTest::table(ReportWidget* rw)
-{
- return rw->table();
-}
-
-void ReportWidgetTest::setStatistics(ReportWidget* rw, int sloc, int instrumented)
-{
- rw->m_ui->sloc->setText(QString::number(sloc));
- rw->m_ui->nrofCoveredLines->setText(QString::number(instrumented));
-}
-
-void ReportWidgetTest::setModelFor(ReportWidget* rw)
-{
- ReportModel* model = createReportModel();
- ReportProxyModel* proxyModel = new ReportProxyModel(this);
- proxyModel->setSourceModel(model);
-
- rw->table()->setModel(proxyModel);
- rw->m_proxy = proxyModel;
- rw->m_model = model;
-
- connect(rw->table()->selectionModel(),
- SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- rw,
- SLOT(dispatchSelectionSignal(QItemSelection,QItemSelection)));
-}
-
-// dir1: sloc 3, instrumented 2, coverage 66.6 %
-// dir1File1: sloc 3, instrumented 2, coverage 66.6 %
-// dir2: sloc 1, instrumented 1, coverage 100.0 %
-// dir2File1: sloc 1, instrumented 1, coverage 100.0 %
-// dir3: sloc 3, instrumented 1, coverage 33.3 %
-// dir3File1: sloc 3, instrumented 1, coverage 33.3 %
-// dir4: sloc 1, instrumented 0, coverage 0.0 %
-// dir4File1: sloc 1, instrumented 0, coverage 0.0 %
-ReportModel* ReportWidgetTest::createReportModel()
-{
- ReportModel* model = new ReportModel(this);
-
- CoveredFile dir1File1;
- dir1File1.setUrl(KUrl("/dir1/file1"));
- dir1File1.setCallCount(4, 1);
- dir1File1.setCallCount(8, 0);
- dir1File1.setCallCount(15, 1);
- model->addCoverageData(&dir1File1);
-
- CoveredFile dir2File1;
- dir2File1.setUrl(KUrl("/dir2/file1"));
- dir2File1.setCallCount(16, 1);
- model->addCoverageData(&dir2File1);
-
- CoveredFile dir3File1;
- dir3File1.setUrl(KUrl("/dir2/dir3/file1"));
- dir3File1.setCallCount(23, 0);
- dir3File1.setCallCount(42, 0);
- dir3File1.setCallCount(108, 1);
- model->addCoverageData(&dir3File1);
-
- CoveredFile dir4File1;
- dir4File1.setUrl(KUrl("/dir2/dir4/file1"));
- dir4File1.setCallCount(815, 0);
- model->addCoverageData(&dir4File1);
-
- return model;
-}
-
-QTEST_KDEMAIN( ReportWidgetTest, GUI )
-#include "reportwidgettest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h (nonexistent)
@@ -1,84 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_COVEREDFILEFACTORY_H
-#define VERITAS_COVERAGE_COVEREDFILEFACTORY_H
-
-#include "../coveredfile.h"
-
-namespace Veritas
-{
-namespace Test
-{
-
-class CoveredFileFactory
-{
-public:
- typedef QList<int> Lines;
-
- /*! Construct a covered file with @param sloc number of reachable lines and
- @param instrumented covered lines */
- static CoveredFile* create(const KUrl& name, int sloc, int instrumented)
- {
- CoveredFile* f = new CoveredFile;
- f->setUrl(name);
- for (int i=0; i<sloc; i++) {
- f->setCallCount(i,0);
- }
- for (int i=0; i<instrumented; i++) {
- f->setCallCount(i,1);
- }
- return f;
- }
-
- /*! Construct a covered file with the line numbers in @param notCoveredLines
- as lines of code with call count zero and those in @param coveredLines with a call
- count greater than zero. */
- static CoveredFile* create(const KUrl& name, const Lines& coveredLines, const Lines& notCoveredLines)
- {
- CoveredFile* f = new CoveredFile;
- f->setUrl(name);
- foreach(int line, notCoveredLines) {
- f->setCallCount(line,0);
- }
- foreach(int line, coveredLines) {
- f->setCallCount(line, 1);
- }
- return f;
- }
-
- /*! Construct a covered file with given @param callCountMap Keys are line numbers, values the
- associated call count */
- static CoveredFile* create(const KUrl& name, const QMap<int, int>& callCountMap)
- {
- CoveredFile* f = new CoveredFile;
- f->setUrl(name);
- QMapIterator<int,int> it(callCountMap);
- while(it.hasNext()) {
- it.next();
- f->setCallCount(it.key(), it.value());
- }
- return f;
- }
-};
-
-}} // namespace Veritas
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfilefactory.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py (nonexistent)
@@ -1,198 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-# run valgrind's memory error checker on all tests.
-# filter uninteresting errors and known false positives
-# eg staticly initialized memory from libraries like libfontconfig
-#
-
-from os import system, remove
-from sys import exit, stdout
-from subprocess import Popen, PIPE
-from xml.dom.minidom import parse, parseString
-
-def garbage(line):
- ''' filter for valgridn output'''
- return not line.startswith('<unknown program name>') and \
- not line.startswith('profiling:') and \
- line.find('</valgrindoutput>') # problem is that valgrind erroneously puts multiple of these end-document entries if processes are spawned _inside_ the exe under investigation
-
-def isValgrind3_5OrHigher():
- process = Popen("valgrind --version", stdout=PIPE, shell=True)
- process.wait()
- valgrindOutput = process.stdout.read().strip()
-
- import re, string
- version = re.search("[0-9]+(.[0-9]+)*", valgrindOutput).group(0)
- version = string.split(version, ".")
-
- if map(int, version) < [3, 5]:
- return False
- else:
- return True
-
-def memcheck(test):
- ''' run valgrind-memcheck on test in testdir. return xml output as string '''
- #proc = Popen("valgrind --tool=memcheck --leak-check=full --xml=yes " + test, stdout=PIPE, stderr=PIPE, shell=True, executable="/bin/bash")
- #proc.wait()
- #out = proc.stderr.readlines()
- if isValgrind3_5OrHigher():
- system("valgrind --tool=memcheck --leak-check=full --xml=yes --xml-file=.memcheck.tmp --num-callers=50 " + test + " 1>/dev/null")
- else:
- system("valgrind --tool=memcheck --leak-check=full --xml=yes --num-callers=75 " + test + " 1>/dev/null 2>.memcheck.tmp")
- out = open(".memcheck.tmp").readlines()
- remove(".memcheck.tmp")
- out = filter(garbage, out)
- return ''.join(out) + "\n</valgrindoutput>\n"
-
-def xml_child_data(dom,tag):
- ''' extract child data for tag. return None if not found'''
- elem = dom.getElementsByTagName(tag)
- val = None
- if len(elem) != 0:
- val = elem[0].firstChild.data
- return val
-
-class Frame:
- ''' single entry in a memory error backtrace '''
- def __init__(self, dom_frame):
- '''<frame>
- <ip>0x62ACDBF</ip>
- <obj>/home/nix/KdeDev/kde4/lib/libkdevplatformlanguage.so.1.0.0</obj>
- <fn>KDevelop::ParamIterator::ParamIterator(QString, QString, int)</fn>
- <dir>/home/nix/KdeDev/kdevplatform/language/duchain</dir>
- <file>stringhelpers.cpp</file>
- <line>292</line>
- </frame>'''
- self.obj = xml_child_data(dom_frame, 'obj')
- self.func = xml_child_data(dom_frame, 'fn')
- self.sfile = xml_child_data(dom_frame, 'file')
- self.sline = xml_child_data(dom_frame, 'line')
-
- def __str__(self):
- out = ""
- if self.func:
- out += "\t" + self.func
- if self.sfile and self.sline:
- out += " (" + self.sfile + ":" + self.sline + ")"
- #if self.obj:
- #out += "\t" + self.obj + "\n"
- out += "\n"
- return out
-
-class BackTrace:
- ''' valgrind memcheck stack trace '''
- def __init__(self, errordom):
- self.dom = errordom
- self.kind = self.dom.getElementsByTagName('kind')[0].firstChild.data
- stack = self.dom.getElementsByTagName('frame')
- self.stack = []
- for frame in stack:
- if xml_child_data(frame, 'fn'): # filter anonymous frames out
- self.stack.append(Frame(frame))
- self.what = xml_child_data(self.dom, 'what')
- if self.dom.getElementsByTagName('xwhat').length > 0:
- self.what = xml_child_data(self.dom.getElementsByTagName('xwhat')[0], 'text')
-
- def is_definitely_lost(self):
- return self.kind == u'Leak_DefinitelyLost'
-
- def is_qtest(self):
- is_interesting = False
- for frame in self.stack:
- if frame.func:
- if frame.func.find("QTest") != -1 or frame.func.find("Veritas") != -1:
- is_interesting = True
- if frame.func.find('XRegisterIMInstantiateCallback') != -1:
- return False # X-related static memory allocation, no leak
- if frame.func.find('FcDefaultSubstitute') != -1:
- return False # something Qt-Font related, not interested in this
- if frame.func.find('__nss_database_lookup') != -1:
- return False # more crap
- if frame.func.find('HB_OpenTypePosition') != -1 and frame.sfile.find("harfbuzz-shaper.cpp") != -1:
- return False
- if frame.sfile:
- if frame.sfile.find("xtest") != -1 or frame.sfile.find("veritas") != -1:
- is_interesting = True
- return is_interesting
-
- def __str__(self):
- out = self.what + "\n"
- for frame in self.stack:
- out += str(frame)
- return out
-
-def parse_errors(out):
- ''' extract the interesting memcheck errors from the xml-string input 'out'.
- return these as a list '''
- xmldoc = parseString(out)
- errors = xmldoc.getElementsByTagName('error')
- errors_ = []
- for error in errors:
- bt = BackTrace(error)
- if bt.is_definitely_lost() and bt.is_qtest():
- errors_.append(bt)
- return errors_
-
-def run_all_tests():
- tests=['qtest-unit-casebuilder', \
- 'qtest-unit-qtestcase', 'qtest-ut-qtestcommand', \
- 'qtest-unit-qtestoutputmorpher', 'qtest-unit-qtestoutputparser', \
- 'qtest-unit-qtestregister', 'qtest-unit-qtestsuite', \
- 'qtest-unit-suitebuilder', 'qtest-sys-qtestrunnertest']
- tests=['qtest-it-qtestrunnertest']
-
- root='/home/nix/KdeDev/kdevelop/build/'
- testdir=root + 'plugins/xtest/qtest/tests/'
- system("export LD_LIBRARY_PATH="+root+"lib/:$LD_LIBRARY_PATH")
-
- print ">> running valgrind memcheck"
- all = len(tests)
- curr = 1
- found_error = False
- for test in tests:
- print str(curr) + "/" + str(all) + " " + test + "\t",
- if len(test) < 20: print "\t",
- stdout.flush()
- curr+=1
- out = memcheck(testdir + test)
- errors = parse_errors(out)
- if len(errors) == 0:
- print "OK"
- else:
- found_error = True
- log = open(test+".memcheck", 'w')
- for trace in errors:
- log.write(str(trace))
- log.write("---------------------------------------------------\n")
- log.close()
- print "NOK (see " + test + ".memcheck)"
- if found_error: exit(-1)
-
-def run_single_test(exe_name):
- print ">> running valgrind memcheck on " + exe_name
- system("export LD_LIBRARY_PATH="+sys.argv[2]+"/lib/:$LD_LIBRARY_PATH")
- count = 0
- import xml
- while count < 5:
- try:
- out = memcheck(exe_name)
- errors = parse_errors(out)
- if len(errors) == 0:
- print "PASS"
- exit(0)
- else:
- for trace in errors:
- print trace,
- print "---------------------------------------------------"
- exit(-1)
- except xml.parsers.expat.ExpatError:
- print "Valgrind fooked up, retry"
- count += 1
- pass
-
-################### ENTRY ####################################################
-
-if __name__ == '__main__':
- import sys
- if len(sys.argv) == 1: run_all_tests()
- else: run_single_test(sys.argv[1])
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/runMemcheck.py
___________________________________________________________________
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt (nonexistent)
@@ -1,65 +0,0 @@
-set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
-include_directories(..)
-
-# QtTest needs this in order to include the gui stuff.
-# The alternative (which requires Qt>=4.6) is #include <QTestGui>
-add_definitions(-DQT_GUI_LIB)
-
-macro(kdev_add_test test_EXEC test_SRCS)
- qt4_automoc( ${test_SRCS} )
- kde4_add_unit_test(gcov-${test_EXEC} ${test_SRCS} )
- target_link_libraries(gcov-${test_EXEC}
- kdevveritascoverage
- ${KDEVPLATFORM_SUBLIME_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_SHELL_LIBRARIES}
- ${KDEVPLATFORM_TESTS_LIBRARIES}
- ${KDE4_KTEXTEDITOR_LIBRARY}
- ${KDE4_KPARTS_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${QT_QTTEST_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDE4_KDEUI_LIBS}
- ${KDE4_KFILE_LIBS})
-endmacro(kdev_add_test)
-
-
-kdev_add_test(unit-annotationmanager annotationmanagertest.cpp)
-kdev_add_test(unit-lcovinfoparser lcovinfoparsertest.cpp)
-kdev_add_test(unit-coveredfile coveredfiletest.cpp)
-#kdev_add_test(ut-lcovjob lcovjobtest.cpp)
-kdev_add_test(unit-lcovjobprogress lcovjobprogresstest.cpp)
-kdev_add_test(unit-buildpathselection buildpathselectiontest.cpp)
-kdev_add_test(unit-colorrange colorrangetest.cpp)
-kdev_add_test(unit-discretecolorrange discretecolorrangetest.cpp)
-kdev_add_test(unit-gradientcolorrange gradientcolorrangetest.cpp)
-kdev_add_test(unit-removegcdafilesjob removegcdafilesjobtest.cpp)
-kdev_add_test(unit-removegcdafilesjobprogress removegcdafilesjobprogresstest.cpp)
-kdev_add_test(unit-reportmodel reportmodeltest.cpp)
-kdev_add_test(unit-reportitems reportitemstest.cpp)
-kdev_add_test(unit-reportfileitem reportfileitemtest.cpp)
-if(NOT MSVC)
-kdev_add_test(unit-reportwidget reportwidgettest.cpp)
-endif(NOT MSVC)
-
-macro(coverage_add_mem_test test_EXEC prefix)
- add_test(gcov-mem-${test_EXEC}
- ${CMAKE_CURRENT_SOURCE_DIR}/runMemcheck.py ${CMAKE_CURRENT_BINARY_DIR}/gcov-${prefix}-${test_EXEC} ${CMAKE_BINARY_DIR})
-endmacro(coverage_add_mem_test)
-
-coverage_add_mem_test(annotationmanager unit)
-coverage_add_mem_test(lcovinfoparser unit)
-coverage_add_mem_test(coveredfile unit)
-coverage_add_mem_test(lcovjobprogress unit)
-# Disabled as it is too slow and uses too much memory (as it uses a KDevelop::Core)
-# coverage_add_mem_test(buildpathselection unit)
-coverage_add_mem_test(colorrange unit)
-coverage_add_mem_test(discretecolorrange unit)
-coverage_add_mem_test(gradientcolorrange unit)
-coverage_add_mem_test(removegcdafilesjob unit)
-coverage_add_mem_test(removegcdafilesjobprogress unit)
-coverage_add_mem_test(reportmodel unit)
-coverage_add_mem_test(reportitems unit)
-coverage_add_mem_test(reportfileitem unit)
-coverage_add_mem_test(reportwidget unit)
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp (nonexistent)
@@ -1,381 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "colorrangetest.h"
-#include "../colorrange.h"
-
-#include "testutils.h"
-
-#include <QFile>
-
-#include <KConfig>
-#include <KConfigGroup>
-#include <KStandardDirs>
-
-using Veritas::ColorRangeTest;
-
-static const char* filename = "coverageConfigurationTest";
-
-void ColorRangeTest::cleanup() {
- QFile file(KStandardDirs().findResource("config", filename));
- if (file.exists()) {
- file.remove();
- }
-}
-
-void ColorRangeTest::testConstructor()
-{
- ColorRange cr;
-
- QCOMPARE(cr.mode(), ColorRange::Discrete);
- QCOMPARE(cr.stopPoints().size(), 1);
- QCOMPARE(cr.colorAt(1), QColor(Qt::white));
-
- cr.setMode(ColorRange::Gradient);
- QCOMPARE(cr.stopPoints().size(), 2);
- QCOMPARE(cr.colorAt(0), QColor(Qt::black));
- QCOMPARE(cr.colorAt(1), QColor(Qt::white));
-}
-
-void ColorRangeTest::testSetMode()
-{
- ColorRange cr;
- cr.setMode(ColorRange::Gradient);
-
- QCOMPARE(cr.mode(), ColorRange::Gradient);
-
- cr.setMode(ColorRange::Discrete);
-
- QCOMPARE(cr.mode(), ColorRange::Discrete);
-}
-
-void ColorRangeTest::testSetStopPoints()
-{
- ColorRange cr;
-
- cr.setMode(ColorRange::Discrete);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Gradient);
- stopPoints.clear();
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- QCOMPARE(cr.stopPoints().size(), 1);
- QCOMPARE(cr.stopPoints()[0].first, 1.0);
- QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::cyan));
-
- cr.setMode(ColorRange::Gradient);
- QCOMPARE(cr.stopPoints().size(), 2);
- QCOMPARE(cr.stopPoints()[0].first, 0.0);
- QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::red));
- QCOMPARE(cr.stopPoints()[1].first, 1.0);
- QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::green));
-}
-
-void ColorRangeTest::testColorAtDiscreteMode()
-{
- ColorRange cr;
-
- cr.setMode(ColorRange::Discrete);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(1, QColor(Qt::yellow)));
- cr.setStopPoints(stopPoints);
-
- QCOMPARE(cr.colorAt(0.42), QColor(Qt::yellow));
-}
-
-void ColorRangeTest::testColorAtGradientMode()
-{
- ColorRange cr;
-
- cr.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
-
- assertFuzzyColor(cr.colorAt(0.5), QColor(127, 127, 0));
-}
-
-void ColorRangeTest::testLoad()
-{
- KConfig config(filename);
- KConfigGroup group(&config, "Color range test");
-
- group.writeEntry("Mode", "Gradient");
- KConfigGroup discreteGroup(&group, "Discrete");
- discreteGroup.writeEntry("NumberOfStopPoints", 2);
- discreteGroup.writeEntry("StopPoint0Position", 0.42);
- discreteGroup.writeEntry("StopPoint0Color", QColor(Qt::black));
- discreteGroup.writeEntry("StopPoint1Position", 1.0);
- discreteGroup.writeEntry("StopPoint1Color", QColor(Qt::cyan));
-
- KConfigGroup gradientGroup(&group, "Gradient");
- gradientGroup.writeEntry("NumberOfStopPoints", 3);
- gradientGroup.writeEntry("StopPoint0Position", 0.0);
- gradientGroup.writeEntry("StopPoint0Color", QColor(Qt::red));
- gradientGroup.writeEntry("StopPoint1Position", 0.5);
- gradientGroup.writeEntry("StopPoint1Color", QColor(Qt::yellow));
- gradientGroup.writeEntry("StopPoint2Position", 1.0);
- gradientGroup.writeEntry("StopPoint2Color", QColor(Qt::green));
-
- ColorRange cr;
- cr.load(group);
-
- QCOMPARE(cr.mode(), ColorRange::Gradient);
-
- cr.setMode(ColorRange::Discrete);
- QCOMPARE(cr.stopPoints().size(), 2);
- QCOMPARE(cr.stopPoints()[0].first, 0.42);
- QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::black));
- QCOMPARE(cr.stopPoints()[1].first, 1.0);
- QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::cyan));
-
- cr.setMode(ColorRange::Gradient);
- QCOMPARE(cr.stopPoints().size(), 3);
- QCOMPARE(cr.stopPoints()[0].first, 0.0);
- QCOMPARE(cr.stopPoints()[0].second, QColor(Qt::red));
- QCOMPARE(cr.stopPoints()[1].first, 0.5);
- QCOMPARE(cr.stopPoints()[1].second, QColor(Qt::yellow));
- QCOMPARE(cr.stopPoints()[2].first, 1.0);
- QCOMPARE(cr.stopPoints()[2].second, QColor(Qt::green));
-}
-
-void ColorRangeTest::testSave()
-{
- ColorRange cr;
-
- cr.setMode(ColorRange::Discrete);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Gradient);
- stopPoints.clear();
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
-
- KConfig config(filename);
- KConfigGroup group(&config, "Color range test");
- cr.save(group);
-
- QCOMPARE(group.readEntry("Mode"), QString("Gradient"));
-
- KConfigGroup discreteGroup = group.group("Discrete");
- QCOMPARE(discreteGroup.readEntry("NumberOfStopPoints", 0), 2);
- QCOMPARE(discreteGroup.readEntry("StopPoint0Position", 0.0), 0.42);
- QCOMPARE(discreteGroup.readEntry("StopPoint0Color", QColor()),
- QColor(Qt::black));
- QCOMPARE(discreteGroup.readEntry("StopPoint1Position", 0.0), 1.0);
- QCOMPARE(discreteGroup.readEntry("StopPoint1Color", QColor()),
- QColor(Qt::cyan));
-
- KConfigGroup gradientGroup = group.group("Gradient");
- QCOMPARE(gradientGroup.readEntry("NumberOfStopPoints", 0), 3);
- QCOMPARE(gradientGroup.readEntry("StopPoint0Position", 1.0), 0.0);
- QCOMPARE(gradientGroup.readEntry("StopPoint0Color", QColor()),
- QColor(Qt::red));
- QCOMPARE(gradientGroup.readEntry("StopPoint1Position", 0.0), 0.5);
- QCOMPARE(gradientGroup.readEntry("StopPoint1Color", QColor()),
- QColor(Qt::yellow));
- QCOMPARE(gradientGroup.readEntry("StopPoint2Position", 0.0), 1.0);
- QCOMPARE(gradientGroup.readEntry("StopPoint2Color", QColor()),
- QColor(Qt::green));
-}
-
-void ColorRangeTest::testLoadAfterSave()
-{
- ColorRange cr;
-
- cr.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
-
- KConfig config(filename);
- KConfigGroup group(&config, "Color range test");
- cr.save(group);
-
- ColorRange newCr;
- newCr.load(group);
-
- QCOMPARE(newCr.mode(), ColorRange::Discrete);
-
- newCr.setMode(ColorRange::Discrete);
- QCOMPARE(newCr.stopPoints().size(), 2);
- QCOMPARE(newCr.stopPoints()[0].first, 0.42);
- QCOMPARE(newCr.stopPoints()[0].second, QColor(Qt::black));
- QCOMPARE(newCr.stopPoints()[1].first, 1.0);
- QCOMPARE(newCr.stopPoints()[1].second, QColor(Qt::cyan));
-
- newCr.setMode(ColorRange::Gradient);
- QCOMPARE(newCr.stopPoints().size(), 3);
- QCOMPARE(newCr.stopPoints()[0].first, 0.0);
- QCOMPARE(newCr.stopPoints()[0].second, QColor(Qt::red));
- QCOMPARE(newCr.stopPoints()[1].first, 0.5);
- QCOMPARE(newCr.stopPoints()[1].second, QColor(Qt::yellow));
- QCOMPARE(newCr.stopPoints()[2].first, 1.0);
- QCOMPARE(newCr.stopPoints()[2].second, QColor(Qt::green));
-}
-
-void ColorRangeTest::testOperatorEqual()
-{
- ColorRange cr;
- ColorRange cr2;
-
- cr.setMode(ColorRange::Gradient);
- cr2.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- cr2.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- QVERIFY(cr == cr2);
- QVERIFY(!(cr != cr2));
-}
-
-void ColorRangeTest::testOperatorEqualDifferentMode()
-{
- ColorRange cr;
- ColorRange cr2;
-
- cr.setMode(ColorRange::Gradient);
- cr2.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- cr2.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- cr2.setMode(ColorRange::Gradient);
-
- QVERIFY(!(cr == cr2));
- QVERIFY(cr != cr2);
-}
-
-void ColorRangeTest::testOperatorEqualDifferentDiscreteColorRange()
-{
- ColorRange cr;
- ColorRange cr2;
-
- cr.setMode(ColorRange::Gradient);
- cr2.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- cr2.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
-
- stopPoints.clear();
- stopPoints.append(StopPoint(0.23, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr2.setStopPoints(stopPoints);
-
- QVERIFY(!(cr == cr2));
- QVERIFY(cr != cr2);
-}
-
-void ColorRangeTest::testOperatorEqualDifferentGradientColorRange()
-{
- ColorRange cr;
- ColorRange cr2;
-
- cr.setMode(ColorRange::Gradient);
- cr2.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr.setStopPoints(stopPoints);
- stopPoints.clear();
- stopPoints.append(StopPoint(0, QColor(Qt::blue)));
- stopPoints.append(StopPoint(0.5, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- cr2.setStopPoints(stopPoints);
-
- cr.setMode(ColorRange::Discrete);
- cr2.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.42, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- cr.setStopPoints(stopPoints);
- cr2.setStopPoints(stopPoints);
-
- QVERIFY(!(cr == cr2));
- QVERIFY(cr != cr2);
-}
-
-////////////////////////////// Asserts ////////////////////////////////////////
-
-void ColorRangeTest::assertFuzzyColor(const QColor& actual, const QColor& expected)
-{
- QVERIFY(actual.red() >= expected.red() -1);
- QVERIFY(actual.red() <= expected.red() + 1);
- QVERIFY(actual.green() >= expected.green() -1);
- QVERIFY(actual.green() <= expected.green() + 1);
- QVERIFY(actual.blue() >= expected.blue() -1);
- QVERIFY(actual.blue() <= expected.blue() + 1);
-}
-
-QTEST_KDEMAIN(ColorRangeTest, NoGUI)
-
-#include "colorrangetest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h (nonexistent)
@@ -1,66 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_LCOVJOBPROGRESSTEST_H
-#define VERITAS_COVERAGE_LCOVJOBPROGRESSTEST_H
-
-#include <QtCore/QObject>
-
-class QSignalSpy;
-
-namespace Veritas {
-
-class LcovJobProgressTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void init();
- void cleanup();
-
- void testStatusName();
-
- void testStart();
-
- void testParseLinesBeforeScanning();
- void testParseLinesScanning();
-
- void testParseLinesFilesFound();
- void testParseLinesNoFilesFound();
-
- void testParseLinesProcessing();
- void testParseLinesProcessingWithGarbage();
-
- void testFinish();
-
-private:
-
- class LcovJobProgress* m_lcovJobProgress;
-
- QSignalSpy* m_clearMessageSpy;
- QSignalSpy* m_showMessageSpy;
- QSignalSpy* m_showErrorMessageSpy;
- QSignalSpy* m_hideProgressSpy;
- QSignalSpy* m_showProgressSpy;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h (nonexistent)
@@ -1,76 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTSTUBS_PLUGINCONTROLLER_STUB_H
-#define TESTSTUBS_PLUGINCONTROLLER_STUB_H
-
-
-
-#include "interfaces/iplugincontroller.h"
-#include "interfaces/contextmenuextension.h"
-#include "shell/profileengine.h" // yaikes, needed because no interface + plugincontroller returns references.
-
-namespace TestStubs
-{
-
-class PluginController : public KDevelop::IPluginController
-{
-public:
-// enum PluginType {
-// Global = 0,
-// Project
-// };
-
- PluginController( QObject* parent = 0 ) : KDevelop::IPluginController(parent), m_pluginForExtension(0) {} ;
- virtual ~PluginController() {}
-
- KDevelop::IPlugin* m_pluginForExtension;
-
- virtual KPluginInfo pluginInfo( KDevelop::IPlugin* ) const { Q_ASSERT(0); return KPluginInfo(); }
- virtual QList<KDevelop::IPlugin*> loadedPlugins() const { Q_ASSERT(0); return QList<KDevelop::IPlugin*>(); }
- virtual void unloadPlugin( const QString & plugin ) {Q_ASSERT(0); }
- virtual KDevelop::IPlugin* loadPlugin( const QString & pluginName ) { Q_ASSERT(0); return 0; }
-
- virtual KDevelop::IPlugin *pluginForExtension(const QString &extension, const QString& pluginname = "" ) { return m_pluginForExtension; }
- virtual QList<KDevelop::IPlugin*> allPluginsForExtension(const QString &extension, const QStringList &constraints) { Q_ASSERT(0); return QList<KDevelop::IPlugin*>(); }
-
-// static KPluginInfo::List query( const QString &serviceType, const QString &constraint );
-// static KPluginInfo::List queryPlugins( const QString &constraint );
-// static QStringList argumentsFromService( const KService::Ptr &service );
-
- virtual QString currentProfile() const { Q_ASSERT(0); return ""; }
- virtual void loadPlugins( PluginType offer ) { Q_ASSERT(0); return; }
- virtual void unloadPlugins( PluginType offer ) { Q_ASSERT(0); return; }
- KDevelop::ProfileEngine* m_engine;
- virtual KDevelop::ProfileEngine &engine() const { Q_ASSERT(0); return *m_engine; }
- virtual QString changeProfile( const QString &newProfile ) { Q_ASSERT(0); return ""; }
- virtual QExtensionManager* extensionManager() { Q_ASSERT(0); return 0; }
- virtual QList<KDevelop::ContextMenuExtension> queryPluginsForContextMenuExtensions( KDevelop::Context* context ) const { Q_ASSERT(0); return QList<KDevelop::ContextMenuExtension>(); }
-
-// Q_SIGNALS:
-// void loadingPlugin( const QString& );
-// void pluginLoaded( KDevelop::KDevelop::IPlugin* );
-// void pluginUnloaded( KDevelop::KDevelop::IPlugin* );
-// void profileChanged();
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/plugincontrollerstub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp (nonexistent)
@@ -1,104 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "discretecolorrangetest.h"
-#include "../discretecolorrange.h"
-
-#include "testutils.h"
-
-using Veritas::DiscreteColorRangeTest;
-
-void DiscreteColorRangeTest::testConstructor()
-{
- DiscreteColorRange dcr;
-
- QCOMPARE(dcr.stopPoints().size(), 1);
- QCOMPARE(dcr.colorAt(1), QColor(Qt::white));
-}
-
-void DiscreteColorRangeTest::testSetStopPoints()
-{
- DiscreteColorRange dcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0.23, QColor(Qt::blue)));
- stopPoints.append(StopPoint(0.42, QColor(Qt::darkGreen)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- dcr.setStopPoints(stopPoints);
-
- QCOMPARE(dcr.stopPoints().size(), 3);
- QCOMPARE(dcr.stopPoints()[0].first, 0.23);
- QCOMPARE(dcr.stopPoints()[0].second, QColor(Qt::blue));
- QCOMPARE(dcr.stopPoints()[1].first, 0.42);
- QCOMPARE(dcr.stopPoints()[1].second, QColor(Qt::darkGreen));
- QCOMPARE(dcr.stopPoints()[2].first, 1.0);
- QCOMPARE(dcr.stopPoints()[2].second, QColor(Qt::cyan));
-}
-
-void DiscreteColorRangeTest::testColorAtWithNoMiddleStopPoints()
-{
- DiscreteColorRange dcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(1, QColor(QColor(Qt::green))));
- dcr.setStopPoints(stopPoints);
-
- QCOMPARE(dcr.colorAt(0), QColor(Qt::green));
- QCOMPARE(dcr.colorAt(0.5), QColor(Qt::green));
- QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
-}
-
-void DiscreteColorRangeTest::testColorAtWithSeveralStopPoints()
-{
- DiscreteColorRange dcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0.333, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.667, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- dcr.setStopPoints(stopPoints);
-
- QCOMPARE(dcr.colorAt(0), QColor(Qt::red));
- QCOMPARE(dcr.colorAt(0.23), QColor(Qt::red));
- QCOMPARE(dcr.colorAt(0.333), QColor(Qt::red));
- QCOMPARE(dcr.colorAt(0.334), QColor(Qt::yellow));
- QCOMPARE(dcr.colorAt(0.42), QColor(Qt::yellow));
- QCOMPARE(dcr.colorAt(0.667), QColor(Qt::yellow));
- QCOMPARE(dcr.colorAt(0.668), QColor(Qt::green));
- QCOMPARE(dcr.colorAt(0.8), QColor(Qt::green));
- QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
-}
-
-void DiscreteColorRangeTest::testColorAtWithStopPointAtBegin()
-{
- DiscreteColorRange dcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::black)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- dcr.setStopPoints(stopPoints);
-
- QCOMPARE(dcr.colorAt(0), QColor(Qt::black));
- QCOMPARE(dcr.colorAt(0.001), QColor(Qt::green));
- QCOMPARE(dcr.colorAt(1), QColor(Qt::green));
-}
-
-QTEST_KDEMAIN(DiscreteColorRangeTest, NoGUI)
-
-#include "discretecolorrangetest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h (nonexistent)
@@ -1,51 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QTEST_LCOVINFOPARSERTEST_H_INCLUDED
-#define QTEST_LCOVINFOPARSERTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas
-{
-
-class CoveredFile;
-class LcovInfoParser;
-class LcovInfoParserTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
- void cleanupTestCase();
-
- void singleCoveredFile();
- void multipleFiles();
-
-private:
- void assertCoveredFilesEqual(CoveredFile*, CoveredFile*);
-
-private:
- LcovInfoParser* m_parser;
-};
-
-}
-
-#endif // QTEST_LCOVINFOPARSERTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h (nonexistent)
@@ -1,62 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESSTEST_H
-#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESSTEST_H
-
-#include <QtCore/QObject>
-
-class QSignalSpy;
-
-namespace Veritas
-{
-
-class RemoveGcdaFilesJobProgressTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void init();
- void cleanup();
-
- void testStatusName();
-
- void testStart();
-
- void testSetNumberOfFilesFound();
-
- void testProgressUpdateWhenFilesAreRemoved();
-
- void testFinish();
-
-private:
-
- class RemoveGcdaFilesJobProgress* m_removeGcdaFilesJobProgress;
-
- QSignalSpy* m_clearMessageSpy;
- QSignalSpy* m_showMessageSpy;
- QSignalSpy* m_showErrorMessageSpy;
- QSignalSpy* m_hideProgressSpy;
- QSignalSpy* m_showProgressSpy;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h (nonexistent)
@@ -1,62 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REPORTMODELTEST_H
-#define VERITAS_COVERAGE_REPORTMODELTEST_H
-
-#include <QtCore/QObject>
-#include <QtCore/QVariant>
-#include <KUrl>
-class QModelIndex;
-
-namespace Veritas
-{
-
-class CoveredFile;
-class ReportModel;
-class ReportModelTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void sortRole();
- void addSingleCoverageData();
- void multiCoverageOneFile();
- void differentSlocSetOneFile();
-
-private:
- QVariant fetchSortData(int row);
- void assertDirAtEquals(const QModelIndex& i, QString path, int sloc, int instrumented);
- void assertFileAtEquals(const QModelIndex& i, QString name, int sloc, int instrumented, double cov);
-
-private:
- ReportModel* m_model;
- KUrl m_fileUrl;
- QString m_fileDir;
- QString m_fileName;
-
- QList<CoveredFile*> m_garbage;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_REPORTMODELTEST_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h (nonexistent)
@@ -1,63 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef QTEST_REPORTITEMSTEST_H_INCLUDED
-#define QTEST_REPORTITEMSTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-class QStandardItem;
-
-namespace Veritas
-{
-
-class CoveredFile;
-class ReportDirItem;
-
-class ReportItemsTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void constructDoubleValueItem();
- void constructIntValueItem();
-
- void constructDirItem();
- void addFileToDirItem();
- void addMultipleFilesToDir();
-
- void constructDirData();
- void dirDataSetSloc();
- void dirDataSetInstrumented();
- void dirDataCoverage();
-
-private:
- void addCoverageDataTo(ReportDirItem& dir, const QString& path, int sloc, int instrumented);
-
-private:
- QList<QStandardItem*> m_garbage;
- QList<CoveredFile*> m_garbageFiles;
-
-};
-
-}
-
-#endif // QTEST_REPORTITEMSTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h (nonexistent)
@@ -1,81 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_BUILDPATHSELECTIONTEST_H
-#define VERITAS_COVERAGE_BUILDPATHSELECTIONTEST_H
-
-#include <QObject>
-
-#include <KUrl>
-
-class KComboBox;
-class KUrlNavigator;
-
-namespace KDevelop
-{
-class IProject;
-}
-
-namespace Veritas
-{
-
-class BuildPathSelection;
-
-class BuildPathSelectionTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void initTestCase();
- void init();
- void cleanup();
- void cleanupTestCase();
-
- void testRequestProjectSelectionWidget();
-
- void testProjectFilter();
-
- void testSelectProject();
-
- void testChangeBuildPath();
- void testChangeBuildPathToUnknownPath();
-
-private:
-
- KUrl writeProjectConfiguration(const QString& name, const QString& buildPath) const;
- void openProject(const KUrl& url) const;
- void closeProject(KDevelop::IProject* project) const;
-
- QString m_testPath;
-
- KUrl m_project1Url;
- KUrl m_project2Url;
- KUrl m_project3FilteredUrl;
-
- KUrlNavigator* m_urlNavigator;;
- BuildPathSelection* m_buildPathSelection;
-
- QWidget* m_parent;
- KComboBox* m_comboBox;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.h (nonexistent)
@@ -1,50 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTSTUBS_PLUGINSTUB_H
-#define TESTSTUBS_PLUGINSTUB_H
-
-#include "interfaces/iplugin.h"
-#include "interfaces/contextmenuextension.h"
-#include "../coverageexport.h"
-
-namespace TestStubs
-{
-class VERITAS_COVERAGE_EXPORT Plugin : public KDevelop::IPlugin
-{
-Q_OBJECT
-public:
- Plugin(const KComponentData &instance, QObject *parent) : KDevelop::IPlugin(instance, parent) {}
- virtual ~Plugin() {}
- virtual void unload() { Q_ASSERT(0); }
- KIconLoader* iconLoader() const { Q_ASSERT(0); return 0; }
- KDevelop::ICore *core() const { Q_ASSERT(0); return 0; }
- virtual KDevelop::ContextMenuExtension contextMenuExtension( KDevelop::Context* context ) { Q_UNUSED(context); return KDevelop::ContextMenuExtension(); }
-
-/*public Q_SLOTS:
- void newIconLoader() const;
-
-protected:
- void addExtension( const QString& );
- virtual void initializeGuiState();*/
-};
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h (nonexistent)
@@ -1,58 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QTEST_REPORTFILEITEMTEST_H_INCLUDED
-#define QTEST_REPORTFILEITEMTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include <KUrl>
-#include <QString>
-
-namespace Veritas
-{
-
-class ReportFileItem;
-class CoveredFile;
-class ReportFileItemTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void construct();
- void addCoverage();
- void addMultipleCoverage();
-
-private:
- void assertInstrumentedItem(int);
- void assertCoverageItem(double);
- void assertSlocItem(int);
-
-private:
- ReportFileItem* m_file;
- KUrl m_url;
- QString m_fileName;
- QList<CoveredFile*> m_garbage;
-};
-
-}
-
-#endif // QTEST_REPORTFILEITEMTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/kasserts.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/kasserts.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/kasserts.h (nonexistent)
@@ -1,90 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-/*! Various QTestLib convenience macros and toString printers */
-
-#ifndef QXQTEST_KASSERTS_H
-#define QXQTEST_KASSERTS_H
-
-#include <QtTest/QtTest>
-#include <KUrl>
-
-namespace QTest
-{
-
-template<> inline char* toString(const QFileInfo& fi)
-{
- return qstrdup(fi.filePath().toLatin1().constData());
-}
-#if QT_VERSION < QT_VERSION_CHECK(4,6,0)
-template<> inline char* toString(const QVariant& va)
-{
- return qstrdup(va.toString().toLatin1().constData());
-}
-#endif
-template<> inline char* toString(const KUrl& url)
-{
- return qstrdup(url.toLocalFile().toLatin1().constData());
-}
-
-} // namespace QTest
-
-#define KVERIFY(condition) QVERIFY(condition)
-
-#define KVERIFY_MSG(condition,message) \
-{\
- char* __failMsg__ = QTest::toString(message); \
- bool __assertion_failed__ = \
- !QTest::qVerify(condition, #condition, __failMsg__, __FILE__, __LINE__);\
- delete [] __failMsg__; \
- if (__assertion_failed__) return; \
-} (void)(0)
-
-#define KOMPARE(expected, actual) \
-{ \
- char* __expected__ = QTest::toString(expected); \
- char* __actual__ = QTest::toString(actual); \
- QByteArray __failMsg__ = \
- QByteArray("\nexpected: \'").append(__expected__).append("\' actual \'").\
- append(__actual__).append("\'"); \
- delete [] __expected__; \
- delete [] __actual__; \
- if (!QTest::qVerify(expected == actual, "KOMPARE", __failMsg__.constData(), __FILE__, __LINE__))\
- return;\
-} (void)(0)
-
-#define KOMPARE_MSG(expected, actual, msg) \
-{ \
- char* __expected__ = QTest::toString(expected); \
- char* __actual__ = QTest::toString(actual); \
- char* __fail_msg__ = QTest::toString(msg); \
- QByteArray __failMsg__ = \
- QByteArray("\nexpected: \'").append(__expected__).append("\' actual \'").\
- append(__actual__).append("\'\n").append(__fail_msg__); \
- delete [] __expected__; \
- delete [] __actual__; \
- delete [] __fail_msg__; \
- if (!QTest::qVerify(expected == actual, "KOMPARE_MSG", __failMsg__.constData(), __FILE__, __LINE__))\
- return;\
-} (void)(0)
-
-#define TDD_TODO QSKIP("Test command not implemented yet", SkipSingle)
-
-#endif // QXQTEST_KASSERTS_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/kasserts.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h (nonexistent)
@@ -1,50 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_GRADIENTCOLORRANGETEST_H
-#define VERITAS_COVERAGE_GRADIENTCOLORRANGETEST_H
-
-#include <QtCore/QObject>
-#include <QColor>
-
-namespace Veritas {
-
-class GradientColorRangeTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void testConstructor();
- void testSetStopPoints();
- void testColorAtWithNoMiddleStopPoints();
- void testColorAtWithSeveralStopPoints();
-
-private:
-
- /**
- * Checks that actual has the three RGB components equal to the RGB
- * components +-1 of expected.
- */
- void assertFuzzyColor(const QColor& actual, const QColor& expected);
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/testutils.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/testutils.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/testutils.h (nonexistent)
@@ -1,27 +0,0 @@
-/*
- * This file is part of KDevelop.
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef COVERAGE_TESTUTILS_H
-#define COVERAGE_TESTUTILS_H
-
-#include "kasserts.h"
-#include <qtest_kde.h>
-
-#endif // COVERAGE_TESTUTILS_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/testutils.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/corestub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/corestub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/corestub.h (nonexistent)
@@ -1,281 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTFAKES_CORESTUB_H
-#define TESTFAKES_CORESTUB_H
-
-#include "interfaces/icore.h"
-#include <KComponentData>
-
-namespace KDevelop
-{
-class IDocumentController;
-class IDocumentationController;
-class ILanguageController;
-class IPluginController;
-class IProjectController;
-class IRunController;
-class IUiController;
-class ISessionController;
-class IPartController;
-}
-
-namespace TestStubs
-{
-
-/*! Allows for proper unit testing of components with an ICore dependency */
-class Core : public KDevelop::ICore
-{
-public:
- Core() :
- m_documentController(0),
- m_languageController(0),
- m_pluginController(0),
- m_projectController(0),
- m_uiController(0),
- m_runController(0),
- m_selectionController(0),
- m_session(0),
- m_partController(0),
- m_documentationController(0),
- m_debugController(0),
- m_testController(0),
- m_shuttingDown(0) {}
-
- virtual ~Core() {}
- virtual KDevelop::IDocumentController *documentController() {
- return m_documentController;
- }
- virtual KDevelop::ISelectionController *selectionController() {
- return m_selectionController;
- }
- virtual KDevelop::ILanguageController *languageController() {
- return m_languageController;
- }
- virtual KDevelop::IPluginController *pluginController() {
- return m_pluginController;
- }
- virtual KDevelop::IProjectController *projectController() {
- return m_projectController;
- }
- virtual KDevelop::IRunController *runController() {
- return m_runController;
- }
- virtual KDevelop::IUiController *uiController() {
- return m_uiController;
- }
- virtual KDevelop::IPartController *partController() {
- return m_partController;
- }
- virtual KDevelop::IDocumentationController* documentationController() {
- return m_documentationController;
- }
- virtual KDevelop::IDebugController* debugController() {
- return m_debugController;
- }
- virtual KDevelop::ITestController* testController() {
- return m_testController;
- }
- virtual KDevelop::ISession* activeSession() {
- return m_session;
- }
- virtual KDevelop::ISourceFormatterController *sourceFormatterController() {
- return 0;
- }
- virtual KComponentData componentData() const {
- return KGlobal::mainComponent();
- }
- virtual bool shuttingDown() const {
- return m_shuttingDown;
- }
-
- // inject whatever it is you want.
- KDevelop::IDocumentController* m_documentController;
- KDevelop::ILanguageController* m_languageController;
- KDevelop::IPluginController* m_pluginController;
- KDevelop::IProjectController* m_projectController;
- KDevelop::IUiController* m_uiController;
- KDevelop::IRunController* m_runController;
- KDevelop::ISelectionController* m_selectionController;
- KDevelop::ISession* m_session;
- KDevelop::IPartController* m_partController;
- KDevelop::IDocumentationController* m_documentationController;
- KDevelop::IDebugController* m_debugController;
- KDevelop::ITestController* m_testController;
- bool m_shuttingDown;
-};
-
-}
-
-#include "interfaces/iuicontroller.h"
-
-namespace TestStubs
-{
-
-class UiController : public KDevelop::IUiController {
-public:
- UiController() : m_activeMainWindow(0) {}
- virtual ~UiController() {}
-
- //enum SwitchMode {
- // ThisWindow /**< indicates that the area switch should be in the this window */,
- // NewWindow /**< indicates that the area switch should be using a new window */
- //};
-
- virtual void switchToArea(const QString &areaName, SwitchMode switchMode) {}
- virtual void addToolView(const QString &name, KDevelop::IToolViewFactory *factory) {}
- virtual void removeToolView(KDevelop::IToolViewFactory *factory) {}
- virtual QWidget* findToolView(const QString& name, KDevelop::IToolViewFactory *factory, KDevelop::IUiController::FindFlags flags = CreateAndRaise) { return m_activeMainWindow;}
- virtual void raiseToolView(QWidget* toolViewWidget) {}
- virtual KParts::MainWindow *activeMainWindow() { return m_activeMainWindow; }
- virtual Sublime::Controller* controller() { return m_controller; }
- virtual void registerStatus(QObject*) {}
- virtual void popUpAssistant(const KSharedPtr<KDevelop::IAssistant>& ) {}
- virtual void hideAssistant(const KSharedPtr<KDevelop::IAssistant>& ) {}
- virtual void showErrorMessage(const QString &message, int timeout) {}
- virtual Sublime::Area* activeArea() { return m_area; }
-
- KParts::MainWindow* m_activeMainWindow;
- Sublime::Area* m_area;
- Sublime::Controller* m_controller;
-};
-
-}
-
-#include <interfaces/idocumentcontroller.h>
-
-namespace TestStubs
-{
-
-class DocumentController : public KDevelop::IDocumentController
-{
-// Q_OBJECT
-public:
-#if 0
- enum DocumentActivation
- {
- DefaultMode = 0, /**Activate document and create a view if no other flags passed.*/
- DoNotActivate = 1, /**Don't activate the Document.*/
- DoNotCreateView = 2 /**Don't create and show the view for the Document.*/
- };
- Q_DECLARE_FLAGS(DocumentActivationParams, DocumentActivation)
-#endif
- DocumentController(QObject *parent) : IDocumentController(parent) {}
- virtual ~DocumentController() {}
-
- virtual void setEncoding( const QString &encoding ) {}
- virtual QString encoding() const { return ""; }
-
- virtual KDevelop::IDocument* documentForUrl( const KUrl & url ) const { return 0; }
- virtual QList<KDevelop::IDocument*> openDocuments() const { return QList<KDevelop::IDocument*>(); }
- virtual KDevelop::IDocument* activeDocument() const { return 0; }
- virtual void activateDocument( KDevelop::IDocument * document, const KTextEditor::Range& range = KTextEditor::Range::invalid() ) {}
- virtual void registerDocumentForMimetype( const QString&, KDevelop::IDocumentFactory* ) {}
- virtual bool saveAllDocuments(KDevelop::IDocument::DocumentSaveMode mode = KDevelop::IDocument::Default) { return true; }
- virtual bool saveSomeDocuments(const QList<KDevelop::IDocument*>& list, KDevelop::IDocument::DocumentSaveMode mode = KDevelop::IDocument::Default) { return true; }
- virtual bool saveAllDocumentsForWindow(KParts::MainWindow* mw, KDevelop::IDocument::DocumentSaveMode mode, bool currentAreaOnly = false) { return true; }
- virtual KDevelop::IDocument* openDocumentFromText( const QString& data ) { return 0; }
- virtual void notifyDocumentClosed(KDevelop::IDocument* doc) {}
- virtual KTextEditor::Document* globalTextEditorInstance() { return 0; }
-
- virtual KDevelop::IDocument* openDocument( const KUrl&, const QString& ) { return 0; }
-
- // actually these are virtual slots, but so long as Qt does not cry we'r good.
- virtual KDevelop::IDocument* openDocument( const KUrl &url,
- const KTextEditor::Range& range = KTextEditor::Range::invalid(),
- DocumentActivationParams activationParams = 0,
- const QString& encoding = "") { return 0; }
-
- virtual KDevelop::IDocument* openDocument( const KUrl &url,
- const KTextEditor::Range& range = KTextEditor::Range::invalid(),
- DocumentActivationParams activationParams = 0,
- const QString& encoding = "",
- KDevelop::IDocument* buddy = 0) { return 0; }
-
- virtual bool openDocument(KDevelop::IDocument* doc,
- const KTextEditor::Range& range = KTextEditor::Range::invalid(),
- DocumentActivationParams activationParams = 0,
- KDevelop::IDocument* buddy = 0) { return true; }
-
- virtual KDevelop::IDocumentFactory* factory(const QString& mime) const { return 0; }
- virtual void closeAllDocuments() {}
-
- void emitDocumentActivated(KDevelop::IDocument* doc) {
- emit documentActivated(doc);
- }
- void emitTextDocumentCreated(KDevelop::IDocument* doc) {
- emit textDocumentCreated(doc);
- }
-
-#if 0
-public Q_SLOTS:
- /**Opens a new or existing document.
- @param url The full Url of the document to open.
- @param range The location information, if applicable.
- @param activate Indicates whether to fully activate the document.*/
- KDevelop::IDocument* openDocument( const KUrl &url,
- const KTextEditor::Cursor& cursor,
- DocumentActivationParams activationParams = 0 );
-
- /**Opens a new or existing document.
- @param url The full Url of the document to open.
- @param range The range of text to select, if applicable.
- @param activate Indicates whether to fully activate the document.*/
- virtual KDevelop::IDocument* openDocument( const KUrl &url,
- const KTextEditor::Range& range = KTextEditor::Range::invalid(),
- DocumentActivationParams activationParams = 0 ) = 0;
-
- virtual void closeAllDocuments() = 0;
-
-Q_SIGNALS:
- /**Emitted when the document has been activated.*/
- void documentActivated( KDevelop::IDocument* document );
-
- /**Emitted when a document has been saved.*/
- void documentSaved( KDevelop::IDocument* document );
-
- /**Emitted when a document has been loaded.
- Note, no views exist for the document at the time this signal is emitted.*/
- void documentLoaded( KDevelop::IDocument* document );
-
- /**Emitted when a text document has been loaded, and the text document created.
- Note, no views exist for the document at the time this signal is emitted.*/
- void textDocumentCreated( KDevelop::IDocument* document );
-
- /**Emitted when a document has been closed.*/
- void documentClosed( KDevelop::IDocument* document );
-
- /**This is emitted when the document state(the relationship
- * between the file in the editor and the file stored on disk) changes.*/
- void documentStateChanged( KDevelop::IDocument* document );
-
- /**This is emitted when the document content changed.*/
- void documentContentChanged( KDevelop::IDocument* document );
-
- /**Emitted when a document has been loaded, but before documentLoaded(..) is emitted.
- * this allows parts of kdevplatform to prepare data-structures that can be used by other parts
- * during documentLoaded(..).*/
- void documentLoadedPrepare( KDevelop::IDocument* document );
-
-#endif
-};
-
-} // end namespace TestStubs
-
-#endif // TESTFAKES_CORESTUB_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/corestub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp (nonexistent)
@@ -1,251 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "removegcdafilesjobtest.h"
-#define protected public
-#define private public
-#include "../removegcdafilesjob.h"
-#undef private
-#undef protected
-#include "../removegcdafilesjobprogress.h"
-#include "testutils.h"
-
-#include <KStandardDirs>
-
-#include <tests/autotestshell.h>
-#include <tests/testcore.h>
-
-using KDevelop::AutoTestShell;
-using KDevelop::Core;
-using KDevelop::TestCore;
-
-using Veritas::RemoveGcdaFilesJob;
-using Veritas::RemoveGcdaFilesJobProgress;
-using Veritas::RemoveGcdaFilesJobTest;
-
-void RemoveGcdaFilesJobTest::initTestCase() {
- AutoTestShell::init();
- TestCore::initialize(Core::NoUi);
-}
-
-void RemoveGcdaFilesJobTest::init() {
- m_testPath = KStandardDirs().saveLocation("tmp", "removeGcdaFilesJobTest/");
-
- QString currentDir = m_testPath;
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
-
- currentDir = m_testPath + "/parentDir/";
- QDir().mkpath(currentDir);
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
- createFile(currentDir + "file2");
- createFile(currentDir + "file2.gcda");
- createFile(currentDir + "file2.gcda.bak");
-
- currentDir = m_testPath + "/parentDir/dir1/";
- QDir().mkpath(currentDir);
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
- createFile(currentDir + "file2");
- createFile(currentDir + "file2.gcda");
- createFile(currentDir + "file2.gcda.bak");
-
- currentDir = m_testPath + "/parentDir/dir2/";
- QDir().mkpath(currentDir);
-
- currentDir = m_testPath + "/parentDir/dir3/";
- QDir().mkpath(currentDir);
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
-
- currentDir = m_testPath + "/parentDir/dir2/childDir/";
- QDir().mkpath(currentDir);
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
-
- currentDir = m_testPath + "/parentDir/dir3/childDir/";
- QDir().mkpath(currentDir);
- createFile(currentDir + "file");
- createFile(currentDir + "file.gcda");
- createFile(currentDir + "file.gcda.bak");
-}
-
-void RemoveGcdaFilesJobTest::cleanup() {
- deleteDirectory(m_testPath);
-}
-
-void RemoveGcdaFilesJobTest::cleanupTestCase() {
- TestCore::shutdown();
-}
-
-void RemoveGcdaFilesJobTest::testRemoveFilesInSingleDirectory() {
- RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/dir1");
-
- RemoveGcdaFilesJobProgress* progress = job->findChild<RemoveGcdaFilesJobProgress*>();
-
- QVERIFY(progress);
-
- //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
- qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
- QSignalSpy showProgressSpy(progress, SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
-
- job->start();
-
- QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file.gcda.bak"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file.gcda"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda.bak"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file2"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda.bak"));
-
- QCOMPARE(showProgressSpy.count(), 5);
- QCOMPARE(showProgressSpy.at(0).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(0).at(2).toInt(), 1);
- QCOMPARE(showProgressSpy.at(0).at(3).toInt(), 0);
- QCOMPARE(showProgressSpy.at(1).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(1).at(2).toInt(), 2);
- QCOMPARE(showProgressSpy.at(1).at(3).toInt(), 1);
- QCOMPARE(showProgressSpy.at(2).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(2).at(2).toInt(), 100);
- QCOMPARE(showProgressSpy.at(2).at(3).toInt(), 50);
- QCOMPARE(showProgressSpy.at(3).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(3).at(2).toInt(), 100);
- QCOMPARE(showProgressSpy.at(3).at(3).toInt(), 75);
- QCOMPARE(showProgressSpy.at(4).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(4).at(2).toInt(), 1);
- QCOMPARE(showProgressSpy.at(4).at(3).toInt(), 1);
-}
-
-void RemoveGcdaFilesJobTest::testRemoveFilesInComplexDirectory() {
- RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/");
- job->start();
-
- QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda.bak"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file2"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file2.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/file.gcda"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/file2.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file.gcda.bak"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file.gcda"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir2/childDir/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/file.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir3/file.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/childDir/file"));
- QVERIFY(QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda.bak"));
- QVERIFY(!QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda"));
-
- QVERIFY(QFile::exists(m_testPath + "/file"));
- QVERIFY(QFile::exists(m_testPath + "/file.gcda.bak"));
- QVERIFY(QFile::exists(m_testPath + "/file.gcda"));
-}
-
-void RemoveGcdaFilesJobTest::testStopJob() {
- QPointer<RemoveGcdaFilesJob> job = new RemoveGcdaFilesJob(m_testPath + "/parentDir/");
-
- RemoveGcdaFilesJobProgress* progress = job->findChild<RemoveGcdaFilesJobProgress*>();
-
- QVERIFY(progress);
-
- //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
- qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
- QSignalSpy showProgressSpy(progress, SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
-
- job->start();
-
- job->kill();
-
- //Ask the QFuture itself instead of the QFutureWatcher as the QFutureWatcher
- //may return false for every isX() method if some events were not processed
- //yet
- QVERIFY(job->mDoWorkWatcher->future().isFinished());
-
- QTest::kWaitForSignal(job, SIGNAL(destroyed(QObject*)));
-
- //This assertion may fail if the job was not killed quickly enough
- QVERIFY(QFile::exists(m_testPath + "/parentDir/file.gcda") ||
- QFile::exists(m_testPath + "/parentDir/file2.gcda") ||
- QFile::exists(m_testPath + "/parentDir/dir1/file.gcda") ||
- QFile::exists(m_testPath + "/parentDir/dir1/file2.gcda") ||
- QFile::exists(m_testPath + "/parentDir/dir2/childDir/file.gcda") ||
- QFile::exists(m_testPath + "/parentDir/dir3/file.gcda") ||
- QFile::exists(m_testPath + "/parentDir/dir3/childDir/file.gcda"));
-
- QVERIFY(showProgressSpy.count() >= 2);
- QCOMPARE(showProgressSpy.at(0).at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.at(0).at(2).toInt(), 1);
- QCOMPARE(showProgressSpy.at(0).at(3).toInt(), 0);
- QCOMPARE(showProgressSpy.last().at(1).toInt(), 0);
- QCOMPARE(showProgressSpy.last().at(2).toInt(), 1);
- QCOMPARE(showProgressSpy.last().at(3).toInt(), 1);
-}
-
-/////////////////////////////////// Helpers ////////////////////////////////////
-
-void RemoveGcdaFilesJobTest::createFile(const QString& filename) {
- QFile file(filename);
- file.open(QIODevice::WriteOnly);
- file.close();
-}
-
-void RemoveGcdaFilesJobTest::deleteDirectory(const QString& filename) {
- QDir directory(filename);
-
- foreach (QFileInfo fileInfo, directory.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files)) {
- if (fileInfo.isDir()) {
- deleteDirectory(fileInfo.absoluteFilePath());
- } else {
- QFile::remove(fileInfo.absoluteFilePath());
- }
- }
-
- directory.rmdir(filename);
-}
-
-QTEST_KDEMAIN(RemoveGcdaFilesJobTest, NoGUI)
-
-#include "removegcdafilesjobtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp (nonexistent)
@@ -1,273 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "lcovjobprogresstest.h"
-#include "../lcovjobprogress.h"
-
-#include "testutils.h"
-
-using Veritas::LcovJobProgress;
-using Veritas::LcovJobProgressTest;
-
-//KDevelop::IStatus* must be declared as a metatype to be used in qvariant_cast
-Q_DECLARE_METATYPE(KDevelop::IStatus*);
-
-void LcovJobProgressTest::init()
-{
- m_lcovJobProgress = new LcovJobProgress();
-
- //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
- qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
-
- m_clearMessageSpy = new QSignalSpy(m_lcovJobProgress,
- SIGNAL(clearMessage(KDevelop::IStatus*)));
- m_showMessageSpy = new QSignalSpy(m_lcovJobProgress,
- SIGNAL(showMessage(KDevelop::IStatus*,QString,int)));
- m_showErrorMessageSpy = new QSignalSpy(m_lcovJobProgress,
- SIGNAL(showErrorMessage(QString,int)));
- m_hideProgressSpy = new QSignalSpy(m_lcovJobProgress,
- SIGNAL(hideProgress(KDevelop::IStatus*)));
- m_showProgressSpy = new QSignalSpy(m_lcovJobProgress,
- SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
-}
-
-void LcovJobProgressTest::cleanup()
-{
- delete m_clearMessageSpy;
- delete m_showMessageSpy;
- delete m_showErrorMessageSpy;
- delete m_hideProgressSpy;
- delete m_showProgressSpy;
-
- delete m_lcovJobProgress;
-}
-
-void LcovJobProgressTest::testStatusName()
-{
- QCOMPARE(m_lcovJobProgress->statusName(),
- i18nc("@info:progress", "Running <command>geninfo</command>"));
-}
-
-void LcovJobProgressTest::testStart()
-{
- m_lcovJobProgress->start();
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- QVariant argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
-}
-
-void LcovJobProgressTest::testParseLinesBeforeScanning()
-{
- m_lcovJobProgress->parseLines(QStringList() << "Found gcov version: 4.4.1");
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
- QCOMPARE(m_showProgressSpy->count(), 0);
-}
-
-void LcovJobProgressTest::testParseLinesScanning()
-{
- m_lcovJobProgress->parseLines(QStringList() << "Scanning /home/vader for .gcda files ...");
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
- QVariant argument = m_showMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Scanning for .gcda files"));
- QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
-}
-
-void LcovJobProgressTest::testParseLinesFilesFound()
-{
- m_lcovJobProgress->parseLines(QStringList() << "Found 42 data files in /home/indiana");
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
- QVariant argument = m_showMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Processing .gcda files"));
- QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 2);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
-}
-
-void LcovJobProgressTest::testParseLinesNoFilesFound()
-{
- m_lcovJobProgress->parseLines(QStringList() << "ERROR: no .gcda files found in /home/threepwood!");
-
- QCOMPARE(m_showMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_clearMessageSpy->count(), 1);
- QVariant argument = m_clearMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
-}
-
-void LcovJobProgressTest::testParseLinesProcessing()
-{
- QStringList lines;
- lines << "Found 5 data files in /home/hammond";
- lines << "Processing /home/hammond/brachiosaurus.cpp";
- lines << "Processing /home/hammond/velociraptor.cpp";
- lines << "Processing /home/hammond/dilophosaurus.cpp";
- lines << "Processing /home/hammond/triceratops.cpp";
- lines << "Processing /home/hammond/tyrannosaurus.cpp";
- lines << "Finished .info-file creation";
-
- m_lcovJobProgress->parseLines(lines);
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
-
- QCOMPARE(m_showProgressSpy->count(), 7);
- QVariant argument = m_showProgressSpy->at(1).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
-
- argument = m_showProgressSpy->at(2).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
-
- argument = m_showProgressSpy->at(3).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(3).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(3).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(3).at(3).toInt(), 70);
-
- argument = m_showProgressSpy->at(4).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(4).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(4).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(4).at(3).toInt(), 80);
-
- argument = m_showProgressSpy->at(5).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(5).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(5).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(5).at(3).toInt(), 90);
-
- argument = m_showProgressSpy->at(6).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(6).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(6).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(6).at(3).toInt(), 1);
-}
-
-void LcovJobProgressTest::testParseLinesProcessingWithGarbage()
-{
- QStringList lines;
- lines << "Found 5 data files in /home/doc";
- lines << "Processing /home/doc/copernicus.cpp.gcda";
- lines << "/home/doc/copernicus.cpp.gcno:version '402*', prefer '404*'";
- lines << "/home/doc/copernicus.cpp.gcda:version '402*', prefer '404*'";
- lines << "Processing /home/doc/einstein.cpp.gcda";
- lines << "/home/doc/verne.h:cannot open source file";
-
- m_lcovJobProgress->parseLines(lines);
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
-
- QCOMPARE(m_showProgressSpy->count(), 3);
- QVariant argument = m_showProgressSpy->at(1).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
-
- argument = m_showProgressSpy->at(2).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
-}
-
-void LcovJobProgressTest::testFinish()
-{
- m_lcovJobProgress->finish();
-
- QCOMPARE(m_showMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
-
- QCOMPARE(m_clearMessageSpy->count(), 1);
- QVariant argument = m_clearMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
-
- QCOMPARE(m_hideProgressSpy->count(), 1);
- argument = m_hideProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_lcovJobProgress);
-}
-
-QTEST_KDEMAIN(LcovJobProgressTest, NoGUI)
-
-#include "lcovjobprogresstest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobprogresstest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h (nonexistent)
@@ -1,50 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVEREDFILETEST_H_INCLUDED
-#define VERITAS_COVEREDFILETEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas
-{
-
-class CoveredFile;
-class CoveredFileTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void construct();
- void sunny();
- void zeroSloc();
- void callCount();
- void linesSet();
- void isReachable();
-
-private:
- CoveredFile* m_file;
-};
-
-}
-
-#endif // VERITAS_COVEREDFILETEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp (nonexistent)
@@ -1,372 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "annotationmanagertest.h"
-#include "../annotationmanager.h"
-#include "../coveredfile.h"
-#include <interfaces/icore.h>
-#include <interfaces/idocument.h>
-#include <sublime/controller.h>
-
-#include <kparts/mainwindow.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-#include <ktexteditor/annotationinterface.h>
-
-#include "corestub.h"
-#include "documentstub.h"
-#include "viewstub.h"
-
-#include "testutils.h"
-#include <QTextStream>
-
-using KDevelop::ICore;
-using KDevelop::IDocument;
-using KDevelop::ILanguageController;
-using KDevelop::IProjectController;
-using KDevelop::IUiController;
-using KDevelop::IRunController;
-
-using Veritas::AnnotationManager;
-using Veritas::AnnotationManagerTest;
-using Veritas::CoveredFile;
-
-using KTextEditor::AnnotationModel;
-using KTextEditor::Cursor;
-using KTextEditor::Range;
-using KTextEditor::View;
-
-using TestStubs::KDevDocument;
-using TestStubs::Core;
-using TestStubs::TextDocument;
-using TestStubs::UiController;
-
-///////////////// fixture ////////////////////////////////////////////////////
-
-void AnnotationManagerTest::initTestCase()
-{
- m_core = new TestStubs::Core;
- Q_ASSERT(m_core);
- UiController* uic = new TestStubs::UiController;
- m_core->m_uiController = uic;
- uic->m_activeMainWindow = new KParts::MainWindow;
- uic->m_controller = new Sublime::Controller;
- m_docCtrl = new TestStubs::DocumentController(0);
- m_core->m_documentController = m_docCtrl;
-}
-
-void AnnotationManagerTest::init()
-{
- m_annotationManager = new AnnotationManager;
- m_someUrl = KUrl("foo.cpp");
- m_widget = new QWidget;
- m_lineNr = 10;
- m_nrofCalls = 5;
-}
-
-void AnnotationManagerTest::cleanup()
-{
- if (m_annotationManager) delete m_annotationManager;
- if (m_widget) delete m_widget;
- qDeleteAll(m_garbageFiles);
- m_garbageFiles.clear();
- qDeleteAll(m_garbageDocs);
- m_garbageDocs.clear();
- qDeleteAll(m_garbage);
- m_garbage.clear();
-}
-
-///////////////// commands ///////////////////////////////////////////////////
-
-void AnnotationManagerTest::instantiate()
-{
- QMap<KUrl, CoveredFile*> files;
- m_annotationManager->setCoveredFiles(files);
- KDevDocument* doc = createKDevDocument(m_someUrl);
- m_annotationManager->watch(doc);
- m_annotationManager->stopWatching(doc);
-}
-
-void AnnotationManagerTest::singleLine()
-{
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
- m_annotationManager->watch(doc);
-
- View* v = triggerAnnotationsOnView(doc); // exercise
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v); // verify
-}
-
-void AnnotationManagerTest::multipleLines()
-{
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- int line2 = 20, callCount2 = 10;
- f->setCallCount(line2, callCount2);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
- m_annotationManager->watch(doc);
-
- View* v = triggerAnnotationsOnView(doc); // exercise
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v); // verify
- assertAnnoCallCountEquals(line2, callCount2, v);
-}
-
-void AnnotationManagerTest::multipleViews()
-{
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
- m_annotationManager->watch(doc);
-
- // exercise
- View* v1 = triggerAnnotationsOnView(doc);
- // inject another view in the stub
- TextDocument* tdoc = (TextDocument*)doc->textDocument();
- tdoc->m_createView = new TestStubs::TextView(0);
- m_garbage << tdoc->m_createView;
- View* v2 = triggerAnnotationsOnView(doc);
- Q_ASSERT(v1 != v2);
-
- // verify
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v1);
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v2);
-}
-
-void AnnotationManagerTest::multipleFiles()
-{
- // setup
- CoveredFile* f1 = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f1);
- int line2 = 20, nrofCalls2 = 5;
- CoveredFile* f2 = createCoveredFile(line2, nrofCalls2, KUrl("bar.cpp"));
- m_annotationManager->addCoverageData(f2);
-
- KDevDocument* doc1 = createKDevDocument(f1->url());
- m_annotationManager->watch(doc1);
- KDevDocument* doc2 = createKDevDocument(f2->url());
- m_annotationManager->watch(doc2);
-
- // exercise
- View* v1 = triggerAnnotationsOnView(doc1);
- View* v2 = triggerAnnotationsOnView(doc2);
-
- // verify
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v1);
- assertAnnoCallCountEquals(line2, nrofCalls2, v2);
-}
-
-void AnnotationManagerTest::notCovered()
-{
- // setup
- m_lineNr = 5;
- CoveredFile* f = createCoveredFile(5, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
- m_annotationManager->watch(doc);
-
- // exercise
- View* v = triggerAnnotationsOnView(doc);
-
- // verify
- assertNoAnnotationsOnLine(4, v);
- assertNoAnnotationsOnLine(6, v);
- assertNoAnnotationsOnLine(10, v);
-}
-
-void AnnotationManagerTest::multiCoverageOneFile()
-{
- CoveredFile* f1 = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- CoveredFile* f2 = createCoveredFile(m_lineNr+1, m_nrofCalls+1, m_someUrl);
- m_annotationManager->addCoverageData(f1);
- m_annotationManager->addCoverageData(f2);
- KDevDocument* doc = createKDevDocument(m_someUrl);
- m_annotationManager->watch(doc);
-
- View* v = triggerAnnotationsOnView(doc);
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
- assertAnnoCallCountEquals(m_lineNr+1, m_nrofCalls+1, v);
-}
-
-
-void AnnotationManagerTest::stopWatching()
-{
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
- m_annotationManager->watch(doc);
-
- // exercise
- View* v = triggerAnnotationsOnView(doc);
- m_annotationManager->stopWatching(doc);
-
- // verify
- KTextEditor::AnnotationViewInterface *anno =
- qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
- Q_ASSERT_X(anno, "assertAnnoCallCountEquals()", "Err?");
- KVERIFY(! anno->isAnnotationBorderVisible());
- AnnotationModel* model = anno->annotationModel();
- KVERIFY(! model);
-}
-
-void AnnotationManagerTest::annotationsOnExistingView()
-{
- // create and activate a text view _before_ activating coverage
- // annotations on the document
-
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
-
- // create a view
- m_docCtrl->emitTextDocumentCreated(doc);
- QTest::qWait(50);
- KTextEditor::Document* tdoc = doc->textDocument();
- KTextEditor::View* v = tdoc->createView(m_widget);
- QTest::qWait(50);
-
- // exercise
- m_annotationManager->watch(doc);
-
- // verify
- KTextEditor::AnnotationViewInterface *anno =
- qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
- Q_ASSERT_X(anno, "annotationsOnExistingView", "Err?");
- KVERIFY(anno->isAnnotationBorderVisible());
- AnnotationModel* model = anno->annotationModel();
- KVERIFY(model);
-
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
-}
-
-void AnnotationManagerTest::addRemoveAndReAddAnnotations()
-{
- // setup
- CoveredFile* f = createCoveredFile(m_lineNr, m_nrofCalls, m_someUrl);
- m_annotationManager->addCoverageData(f);
- KDevDocument* doc = createKDevDocument(f->url());
-
- // exercise
- m_annotationManager->watch(doc);
- View* v = triggerAnnotationsOnView(doc);
- m_annotationManager->stopWatching(doc);
- m_annotationManager->watch(doc);
-
- // verify
- assertAnnoCallCountEquals(m_lineNr, m_nrofCalls, v);
-}
-
-////////////////// setup helpers /////////////////////////////////////////////
-
-void AnnotationManagerTest::initManager(CoveredFile* f)
-{
- //QMap<KUrl, CoveredFile*> files;
- //files[f->url()] = f;
- //m_manager->setCoveredFiles(files);
-}
-
-KDevDocument* AnnotationManagerTest::createKDevDocument(const KUrl& u)
-{
- TestStubs::KDevDocument* kdoc = new TestStubs::KDevDocument(m_core);
- m_garbageDocs << kdoc;
- kdoc->m_url = u;
- TestStubs::TextDocument* doc = new TestStubs::TextDocument;
- m_garbage << doc;
- kdoc->m_textDocument = doc;
- doc->m_createView = new TestStubs::TextView(0);
- m_garbage << doc->m_createView;
- return kdoc;
-}
-
-CoveredFile* AnnotationManagerTest::createCoveredFile(int line, int callCount, KUrl url)
-{
- CoveredFile* f = new CoveredFile();
- f->setUrl(url);
- f->setCallCount(line, callCount);
- m_garbageFiles << f;
- return f;
-}
-
-/////////////////// exercise helpers /////////////////////////////////////////
-
-KTextEditor::View* AnnotationManagerTest::triggerAnnotationsOnView(KDevelop::IDocument* doc)
-{
- m_docCtrl->emitTextDocumentCreated(doc); // fake activate the doc.
- QTest::qWait(50);
- KTextEditor::Document* tdoc = doc->textDocument();
- // now spawn a view which should trigger annotations being set.
- KTextEditor::View* v = tdoc->createView(m_widget);
- QTest::qWait(50);
- return v;
-}
-
-////////////////// custom assertions /////////////////////////////////////////
-
-AnnotationModel* annotationModelForView(View* v)
-{
- KTextEditor::AnnotationViewInterface *anno =
- qobject_cast<KTextEditor::AnnotationViewInterface*>(v);
- Q_ASSERT_X(anno, "assertAnnoCallCountEquals()", "Err?");
- Q_ASSERT(anno->isAnnotationBorderVisible());
- KTextEditor::AnnotationModel* model = anno->annotationModel();
- return model;
-}
-
-void AnnotationManagerTest::assertAnnoCallCountEquals(int line, int count, KTextEditor::View* v)
-{
- AnnotationModel* model = annotationModelForView(v);
- KVERIFY_MSG(model != 0, "Annotation model not set");
- QString expected = QString::number(count);
- // annotationmodel starts counting from zero
- QString actual = model->data(line-1, Qt::DisplayRole).toString();
- QString failureMsg;
- QTextStream str(&failureMsg);
- str << "Wrong call count for line " << line
- << " was expecting " << expected << " but got " << actual;
- KOMPARE_MSG(expected, actual, failureMsg);
-}
-
-void AnnotationManagerTest::assertNoAnnotationsOnLine(int line, KTextEditor::View* v)
-{
- AnnotationModel* model = annotationModelForView(v);
- KVERIFY_MSG(model != 0, "Annotation model not set");
- QVariant expected; // should return default qvariant.
- QVariant actual = model->data(line-1, Qt::DisplayRole);
- QString failureMsg;
- QTextStream str(&failureMsg);
- str << "Was not expecting annotation on line "
- << line << " but got " << actual.toString();
- KOMPARE_MSG(expected, actual, failureMsg);
-}
-
-void AnnotationManagerTest::assertAnnotationsGone(View* v)
-{
- AnnotationModel* model = annotationModelForView(v);
- KVERIFY_MSG(! model, "Annotation model should have be reset.");
-}
-
-
-#include "annotationmanagertest.moc"
-QTEST_KDEMAIN(AnnotationManagerTest, GUI)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h (nonexistent)
@@ -1,49 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QTEST_LCOVJOBTEST_H_INCLUDED
-#define QTEST_LCOVJOBTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace TestStubs { class Core; class PluginController; }
-
-namespace Veritas
-{
-
-class LcovJobTest : public QObject
-{
-Q_OBJECT
-private slots:
- void initTestCase();
- void init();
- void cleanup();
-
- void basicRun();
-
-private:
- TestStubs::Core* m_core;
- TestStubs::PluginController* m_plugCtrl;
-
-};
-
-}
-
-#endif // QTEST_LCOVJOBTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovjobtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h (nonexistent)
@@ -1,58 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_COLORRANGETEST_H
-#define VERITAS_COVERAGE_COLORRANGETEST_H
-
-#include <QtCore/QObject>
-#include <QColor>
-
-namespace Veritas {
-
-class ColorRangeTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void cleanup();
-
- void testConstructor();
- void testSetMode();
- void testSetStopPoints();
- void testColorAtDiscreteMode();
- void testColorAtGradientMode();
-
- void testLoad();
- void testSave();
- void testLoadAfterSave();
-
- void testOperatorEqual();
- void testOperatorEqualDifferentMode();
- void testOperatorEqualDifferentDiscreteColorRange();
- void testOperatorEqualDifferentGradientColorRange();
-
-private:
-
- void assertFuzzyColor(const QColor& actual, const QColor& expected);
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/colorrangetest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.h (nonexistent)
@@ -1,124 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTSTUBS_VIEWSTUB_H
-#define TESTSTUBS_VIEWSTUB_H
-
-#include <ktexteditor/view.h>
-#include <ktexteditor/annotationinterface.h>
-#include "../coverageexport.h"
-
-namespace TestStubs
-{
-
-class VERITAS_COVERAGE_EXPORT TextView :
- public KTextEditor::View,
- public KTextEditor::AnnotationViewInterface
-{
-Q_OBJECT
-Q_INTERFACES(KTextEditor::AnnotationViewInterface)
-
-public:
- void setAnnotationModel(KTextEditor::AnnotationModel* model) {
- m_annotationModel = model;
- }
- KTextEditor::AnnotationModel* annotationModel() const {
- return m_annotationModel;
- }
- void setAnnotationBorderVisible(bool visible) {
- m_borderVisible = visible;
- }
- bool isAnnotationBorderVisible() const {
- return m_borderVisible;
- }
- KTextEditor::AnnotationModel* m_annotationModel;
- bool m_borderVisible;
-
-Q_SIGNALS:
- void annotationContextMenuAboutToShow(KTextEditor::View* view, QMenu* menu, int line);
- void annotationActivated(KTextEditor::View* view, int line);
- void annotationBorderVisibilityChanged(View* view, bool visible);
-
-public:
- TextView(QWidget *parent) :
- KTextEditor::View(parent),
- m_annotationModel(0) {}
- virtual ~TextView() {}
-
- virtual KTextEditor::Document *document() const { return 0; }
- virtual QString viewMode() const { return ""; }
-// enum EditMode {
-// EditInsert = 0, /**< Insert mode. Characters will be added. */
-// EditOverwrite = 1 /**< Overwrite mode. Characters will be replaced. */
-// };
- virtual enum EditMode viewEditMode() const { return EditOverwrite; }
- virtual void setContextMenu(QMenu *menu) { Q_UNUSED(menu); }
- virtual QMenu *contextMenu() const { return 0; }
- virtual QMenu* defaultContextMenu(QMenu* menu = 0L) const { Q_UNUSED(menu); return 0; }
- virtual bool setCursorPosition(KTextEditor::Cursor position) { Q_UNUSED(position); return false; }
- virtual KTextEditor::Cursor cursorPosition() const { return KTextEditor::Cursor(); }
- virtual KTextEditor::Cursor cursorPositionVirtual() const { return KTextEditor::Cursor(); }
- virtual QPoint cursorToCoordinate(const KTextEditor::Cursor& cursor) const { Q_UNUSED(cursor); return QPoint(); }
- virtual QPoint cursorPositionCoordinates() const { return QPoint(); }
- virtual bool setSelection(const KTextEditor::Range &range) { Q_UNUSED(range); return true; }
- /* virtual bool setSelection(const Cursor &position,
- int length,
- bool wrap = true);*/
- virtual bool selection() const { return true; }
-
- KTextEditor::Range m_selectionRange;
-
- virtual const KTextEditor::Range &selectionRange() const { return m_selectionRange; }
- virtual QString selectionText() const { return ""; }
- virtual bool removeSelection() { return true; }
- virtual bool removeSelectionText() { return true; }
- virtual bool setBlockSelection(bool on) { Q_UNUSED(on); return true; }
- virtual bool blockSelection() const { return true; }
-
- virtual bool mouseTrackingEnabled() const { return true; }
- virtual bool setMouseTrackingEnabled(bool b) { Q_UNUSED(b); return true; }
-
-#if 0
- Q_SIGNALS:
- void contextMenuAboutToShow(KTextEditor::View* view, QMenu* menu);
- void focusIn(KTextEditor::View *view);
- void focusOut(KTextEditor::View *view);
- void viewModeChanged(KTextEditor::View *view);
- void viewEditModeChanged(KTextEditor::View *view,
- enum KTextEditor::View::EditMode mode);
- void informationMessage(KTextEditor::View *view, const QString &message);
- void textInserted(KTextEditor::View *view,
- const KTextEditor::Cursor &position,
- const QString &text);
-
- void cursorPositionChanged(KTextEditor::View *view,
- const KTextEditor::Cursor& newPosition);
- void verticalScrollPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor& newPos);
- void horizontalScrollPositionChanged(KTextEditor::View *view);
- void mousePositionChanged(KTextEditor::View *view,
- const KTextEditor::Cursor& newPosition);
- void selectionChanged(KTextEditor::View *view);
-#endif
-
-};
-
-}
-
-#endif // TESTFAKES_VIEWSTUB
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp (nonexistent)
@@ -1,191 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "reportmodeltest.h"
-#include "../reportmodel.h"
-#include "../coveredfile.h"
-#include "coveredfilefactory.h"
-
-#include "testutils.h"
-
-using Veritas::CoveredFile;
-using Veritas::ReportModelTest;
-using Veritas::ReportModel;
-using Veritas::ReportFileItem;
-using Veritas::ReportDirItem;
-using Veritas::ReportValueItem;
-using Veritas::Test::CoveredFileFactory;
-
-////////////////////////// fixture ///////////////////////////////////////////
-
-void ReportModelTest::init()
-{
- m_model = new ReportModel;
- KUrl m_fileUrl = KUrl("/path/to/foo.cpp");
- QString m_fileDir = "/path/to/";
- QString m_fileName = "foo.cpp";
-}
-
-void ReportModelTest::cleanup()
-{
- if (m_model) delete m_model;
- qDeleteAll(m_garbage);
- m_garbage.clear();
-}
-
-////////////////////////// commands ///////////////////////////////////////////
-
-void ReportModelTest::sortRole()
-{
- ReportDirItem* dir = new ReportDirItem(m_fileDir);
- ReportFileItem* file = new ReportFileItem(m_fileUrl);
- ReportValueItem* val = new ReportValueItem(10);
- m_model->appendRow(dir);
- m_model->appendRow(file);
- m_model->appendRow(val);
-
- KOMPARE(m_fileDir, fetchSortData(0));
- KOMPARE(m_fileName, fetchSortData(1));
- KOMPARE(10.0, fetchSortData(2));
-}
-
-void ReportModelTest::addSingleCoverageData()
-{
- CoveredFile* f = CoveredFileFactory::create(m_fileUrl, 10, 5);
- m_model->addCoverageData(f);
-
- QModelIndex dirIndex = m_model->index(0,0);
- int expSloc = 10;
- int expInstrumented = 5;
- assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
-
- QModelIndex fileIndex = m_model->index(0,0, dirIndex);
- double expCoverage = 50.0;
- assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
-
- KVERIFY(!m_model->index(1,0).isValid());
- KVERIFY(!m_model->index(1,0, dirIndex).isValid());
-
- m_garbage << f;
-}
-
-void ReportModelTest::multiCoverageOneFile()
-{
- // The parser can emit multiple CoveredFile instances
- // for a single URL [covered by multiple 'tests']
- // The model aggregates this data.
- QList<int> covered; covered << 1 << 2;
- QList<int> notCovered; notCovered << 3 << 4;
- CoveredFile* f1 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
-
- covered.clear(); covered << 4;
- notCovered.clear(); notCovered << 1 << 2 << 3;
- CoveredFile* f2 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
-
- m_model->addCoverageData(f1);
- m_model->addCoverageData(f2);
-
- QModelIndex dirIndex = m_model->index(0,0);
- int expSloc = 4;
- int expInstrumented = 2 + 1;
- assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
-
- QModelIndex fileIndex = m_model->index(0,0,dirIndex);
- double expCoverage = 100*((double)expInstrumented/expSloc);
- assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
-
- KVERIFY(!m_model->index(1,0).isValid());
- KVERIFY(!m_model->index(1,0, dirIndex).isValid());
-
- m_garbage << f1 << f2;
-}
-
-void ReportModelTest::differentSlocSetOneFile()
-{
- // It can happen that a file has different sets of reachable
- // lines of code associated with it over multiple coverage
- // data parses. For example on inline'd functions of header
- // files. For such a case the SLOC should be adjust accordingly.
- QList<int> covered; covered << 1;
- QList<int> notCovered; notCovered << 2;
- CoveredFile* f1 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
-
- covered.clear(); covered << 2;
- notCovered.clear(); notCovered << 3;
- CoveredFile* f2 = CoveredFileFactory::create(m_fileUrl, covered, notCovered);
-
- m_model->addCoverageData(f1);
- m_model->addCoverageData(f2);
-
- QModelIndex dirIndex = m_model->index(0,0);
- int expSloc = 3; // lines 1,2,3
- int expInstrumented = 2; // lines 1 and 2
- assertDirAtEquals(dirIndex, m_fileDir, expSloc, expInstrumented);
-
- QModelIndex fileIndex = m_model->index(0,0,dirIndex);
- double expCoverage = 100*((double)expInstrumented/expSloc);
- assertFileAtEquals(fileIndex, m_fileName, expSloc, expInstrumented, expCoverage);
-
- m_garbage << f1 << f2;
-}
-
-///////////////////////// helpers ////////////////////////////////////////////
-
-QVariant ReportModelTest::fetchSortData(int row)
-{
- return m_model->index(row, 0).data(ReportModel::SortRole);
-}
-
-//////////////////////// custom assertions ///////////////////////////////////
-
-void ReportModelTest::assertDirAtEquals(const QModelIndex& i, QString path, int sloc, int instrumented)
-{
- KVERIFY(i.isValid());
- QStandardItem* sdir = m_model->itemFromIndex(i);
- KVERIFY(ReportModel::Dir == sdir->type());
- ReportDirItem* dir = dynamic_cast<ReportDirItem*>(sdir);
- KVERIFY(dir);
- QString actualPath = dir->data(Qt::DisplayRole).toString();
- KOMPARE_MSG(path, actualPath,
- QString("Wrong display data for diritem: expected: %1 but got %2.").
- arg(path).arg(actualPath));
- KOMPARE(sloc, dir->sloc());
- KOMPARE(instrumented, dir->nrofCoveredLines());
-
-}
-
-void ReportModelTest::assertFileAtEquals(const QModelIndex& i, QString name, int sloc, int instrumented, double cov)
-{
- KVERIFY(i.isValid());
- QStandardItem* sfile = m_model->itemFromIndex(i);
- KVERIFY(ReportModel::File == sfile->type());
- ReportFileItem* file = dynamic_cast<ReportFileItem*>(sfile);
- KVERIFY(file);
- KOMPARE(QVariant(name), file->data(Qt::DisplayRole));
- ReportValueItem* slocItem = file->slocItem();
- KOMPARE((double)sloc, slocItem->value());
- ReportValueItem* instrumentedItem = file->nrofCoveredLinesItem();
- KOMPARE((double)instrumented, instrumentedItem->value());
- ReportValueItem* coverageItem = file->coverageRatioItem();
- KVERIFY(qAbs(cov - coverageItem->value()) < 0.1);
-}
-
-QTEST_KDEMAIN( ReportModelTest, NoGUI)
-#include "reportmodeltest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportmodeltest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h (nonexistent)
@@ -1,42 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_DISCRETECOLORRANGETEST_H
-#define VERITAS_COVERAGE_DISCRETECOLORRANGETEST_H
-
-#include <QtCore/QObject>
-
-namespace Veritas {
-
-class DiscreteColorRangeTest: public QObject
-{
-Q_OBJECT
-private slots:
-
- void testConstructor();
- void testSetStopPoints();
- void testColorAtWithNoMiddleStopPoints();
- void testColorAtWithSeveralStopPoints();
- void testColorAtWithStopPointAtBegin();
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/discretecolorrangetest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h (nonexistent)
@@ -1,76 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef QTEST_REPORTWIDGETTEST_H_INCLUDED
-#define QTEST_REPORTWIDGETTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas
-{
-
-class DrillDownView;
-class ReportModel;
-class ReportWidget;
-
-/*! @unitundertest Veritas::ReportWidget */
-class ReportWidgetTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void setCoverageStatisticsWithRawDataFloorRoundedCoverage();
- void setCoverageStatisticsWithRawDataCeilRoundedCoverage();
- void setCoverageStatisticsWithNewSelection();
- void setCoverageStatisticsWithAddedSelection();
- void setCoverageStatisticsWithRemovedSelection();
- void setCoverageStatisticsWithChangedSelection();
- void setCoverageStatisticsWithEmptySelection();
- void setCoverageStatisticsWithInvalidSelection();
- void setCoverageStatisticsWithDirectoriesAndFileSelection();
- void setCoverageStatisticsWithIndex();
- void setCoverageStatisticsWithInvalidIndex();
- void setCoverageStatisticsWithFileIndex();
-
- void statisticsSelectingSingleDirectory();
- void statisticsSelectingSeveralDirectories();
- void statisticsSelectingSeveralDirectoriesNotContiguous();
- void statisticsSelectingSeveralDirectoriesNotContiguousUsingMouse();
- void statisticsAfterClearingSelection();
- void statisticsAfterSlidingRight();
- void statisticsAfterSlidingLeft();
-
-private:
-
- void assertStatistics(ReportWidget* rw, int sloc, int instrumented, double coverage);
- void assertEmptyStatistics(ReportWidget* rw);
-
- DrillDownView* table(ReportWidget* rw);
- void setStatistics(ReportWidget* rw, int sloc, int instrumented);
- void setModelFor(ReportWidget* rw);
- ReportModel* createReportModel();
- ReportWidget* m_reportWidget;
-};
-
-}
-
-#endif // QTEST_REPORTWIDGETTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportwidgettest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp (nonexistent)
@@ -1,153 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "reportitemstest.h"
-#include "coveredfilefactory.h"
-#include "../coveredfile.h"
-#include "../reportmodel.h"
-
-#include "testutils.h"
-
-using Veritas::CoveredFile;
-using Veritas::ReportItemsTest;
-using Veritas::ReportValueItem;
-using Veritas::ReportDirData;
-using Veritas::ReportDirItem;
-using Veritas::ReportFileItem;
-using Veritas::ReportModel;
-using Veritas::Test::CoveredFileFactory;
-
-///////////////////////////// fixture ////////////////////////////////////////
-
-void ReportItemsTest::init()
-{}
-
-void ReportItemsTest::cleanup()
-{
- qDeleteAll(m_garbage);
- m_garbage.clear();
- qDeleteAll(m_garbageFiles);
- m_garbageFiles.clear();
-}
-
-///////////////////////////// commands ////////////////////////////////////////
-
-void ReportItemsTest::constructDoubleValueItem()
-{
- ReportValueItem doubleItem(5.0);
- KVERIFY(ReportModel::Value == doubleItem.type());
- KOMPARE(5.0, doubleItem.value());
- KOMPARE(QString("5.0"), doubleItem.data(Qt::DisplayRole));
- KVERIFY(! doubleItem.isEditable());
- KVERIFY(! doubleItem.isSelectable());
- KVERIFY(! doubleItem.isCheckable());
-}
-
-void ReportItemsTest::constructIntValueItem()
-{
- ReportValueItem intItem(5);
- KVERIFY(ReportModel::Value == intItem.type());
- KOMPARE(5, intItem.value());
- KOMPARE(QString("5"), intItem.data(Qt::DisplayRole));
- KVERIFY(! intItem.isEditable());
- KVERIFY(! intItem.isSelectable());
- KVERIFY(! intItem.isCheckable());
-}
-
-void ReportItemsTest::constructDirItem()
-{
- ReportDirItem dir("/my/dir");
- KVERIFY(ReportModel::Dir == dir.type());
- KOMPARE(0, dir.sloc());
- KOMPARE(0, dir.nrofCoveredLines());
- KOMPARE(0, dir.coverageRatio());
- KVERIFY(! dir.isEditable());
- KVERIFY(dir.isSelectable());
- KVERIFY(! dir.isCheckable());
-}
-
-void ReportItemsTest::addCoverageDataTo(ReportDirItem& dir, const QString& path, int sloc, int instrumented)
-{
- CoveredFile* f = CoveredFileFactory::create(KUrl(path), sloc, instrumented);
- ReportFileItem* fItem = new ReportFileItem(KUrl(path));
- fItem->addCoverageData(f);
- dir.appendRow(fItem);
- dir.updateStats();
- m_garbage << fItem->coverageRatioItem() << fItem->slocItem() << fItem->nrofCoveredLinesItem();
- m_garbageFiles << f;
-}
-
-void ReportItemsTest::addFileToDirItem()
-{
- ReportDirItem* dir = new ReportDirItem("/my/dir");
- addCoverageDataTo(*dir, "/my/dir/foo.cpp", 10, 5);
- KOMPARE(10, dir->sloc());
- KOMPARE(5, dir->nrofCoveredLines());
- KVERIFY(qAbs(100*5/10 - dir->coverageRatio()) < 0.1);
- delete dir;
-}
-
-void ReportItemsTest::addMultipleFilesToDir()
-{
- ReportDirItem* dir = new ReportDirItem("/my/dir");
- addCoverageDataTo(*dir, "/my/dir/foo.cpp", 10, 5);
- addCoverageDataTo(*dir, "/my/dir/bar.cpp", 20, 5);
- KOMPARE(10+20, dir->sloc());
- KOMPARE(5+5, dir->nrofCoveredLines());
- KVERIFY(qAbs(100*((double)dir->nrofCoveredLines()/dir->sloc()) - dir->coverageRatio()) < 0.1);
- delete dir;
-}
-
-void ReportItemsTest::constructDirData()
-{
- ReportDirData dirData;
- KOMPARE(0, dirData.sloc());
- KOMPARE(0, dirData.nrofCoveredLines());
-}
-
-void ReportItemsTest::dirDataSetSloc()
-{
- ReportDirData dirData;
- dirData.setSloc(16);
- KOMPARE(16, dirData.sloc());
-}
-
-void ReportItemsTest::dirDataSetInstrumented()
-{
- ReportDirData dirData;
- dirData.setNrofCoveredLines(23);
- KOMPARE(23, dirData.nrofCoveredLines());
-}
-
-void ReportItemsTest::dirDataCoverage()
-{
- ReportDirData dirData;
- KOMPARE(0, dirData.coverageRatio());
-
- dirData.setNrofCoveredLines(21);
- dirData.setSloc(42);
- KOMPARE(50, dirData.coverageRatio());
-
- dirData.setNrofCoveredLines(4);
- dirData.setSloc(2500);
- QCOMPARE(0.16, dirData.coverageRatio());
-}
-
-QTEST_KDEMAIN( ReportItemsTest, NoGUI)
-#include "reportitemstest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportitemstest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp (nonexistent)
@@ -1,139 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "lcovinfoparsertest.h"
-#include "../lcovinfoparser.h"
-#include "../coveredfile.h"
-#include "coveredfilefactory.h"
-#include <KDebug>
-#include "testutils.h"
-
-using Veritas::CoveredFile;
-using Veritas::LcovInfoParser;
-using Veritas::LcovInfoParserTest;
-using Veritas::Test::CoveredFileFactory;
-
-void LcovInfoParserTest::init()
-{
- m_parser = new LcovInfoParser;
-}
-
-void LcovInfoParserTest::cleanup()
-{
-// delete m_parser;
- m_parser->deleteLater();
-}
-
-void LcovInfoParserTest::cleanupTestCase()
-{
- QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit()));
- QCoreApplication::exec();
-}
-
-void LcovInfoParserTest::assertCoveredFilesEqual(CoveredFile* f1, CoveredFile* f2)
-{
- KOMPARE(f1->url(), f2->url());
- KOMPARE(f1->sloc(), f2->sloc());
- KOMPARE(f1->nrofCoveredLines(), f2->nrofCoveredLines());
- KVERIFY(qAbs(f1->coverageRatio() - f2->coverageRatio()) < 0.01);
- KOMPARE(f1->callCountMap(), f2->callCountMap());
- KOMPARE(f1->coveredLines(), f2->coveredLines());
-}
-
-void LcovInfoParserTest::singleCoveredFile()
-{
- // just a quick test, needs to be extended and cleaned.
-
- QString input =
- "SF:/path/to/foo.h\n"
- "FN:10,_ZN11QStringListD1Ev\n"
- "DA:10,5\n"
- "DA:11,0\n"
- "LF:2\n"
- "LH:1\n"
- "end_of_record\n";
-
- m_parser->parseLines( input.split( '\n' ) );
- QList<CoveredFile*> files = m_parser->fto_coveredFiles();
- KOMPARE(1, files.count());
- CoveredFile* f = files[0];
- KVERIFY(f != 0);
-
- KOMPARE(KUrl("/path/to/foo.h"), f->url());
- KOMPARE(2, f->sloc());
- KOMPARE(1, f->nrofCoveredLines());
- KOMPARE(50, f->coverageRatio());
- KOMPARE(2, f->callCountMap().count());
- KVERIFY(f->callCountMap().contains(10));
- KVERIFY(f->callCountMap().contains(11));
- KOMPARE(5, f->callCountMap()[10]);
- KOMPARE(0, f->callCountMap()[11]);
- }
-
-void LcovInfoParserTest::multipleFiles()
-{
- QString input =
- "SF:/path/to/foo.h\n"
- "FN:10,functionFoo()\n"
- "DA:10,5\n"
- "DA:11,0\n"
- "LF:2\n"
- "LH:1\n"
- "end_of_record\n"
- "SF:/path/to/bar.h\n"
- "FN:15,functionBar()\n"
- "DA:15,5\n"
- "DA:16,0\n"
- "DA:17,10\n"
- "LF:3\n"
- "LH:2\n"
- "end_of_record\n";
-
- m_parser->parseLines( input.split( '\n' ) );
- QList<CoveredFile*> files = m_parser->fto_coveredFiles();
- KOMPARE(2, files.count());
-
- CoveredFile* actualFile1 = files[0];
- KVERIFY(actualFile1 != 0);
- QMap<int, int> expCallCount; // expected number of calls on a source line.
- // { source line x call count }
- expCallCount[10] = 5;
- expCallCount[11] = 0;
- KUrl url("/path/to/foo.h");
- CoveredFile* expFile1 = CoveredFileFactory::create(url, expCallCount);
- assertCoveredFilesEqual(expFile1, actualFile1);
-
- CoveredFile* actualFile2 = files[1];
- KVERIFY(actualFile2 != 0);
- url = KUrl("/path/to/bar.h");
- expCallCount.clear();
- expCallCount[15] = 5;
- expCallCount[16] = 0;
- expCallCount[17] = 10;
- CoveredFile* expFile2 = CoveredFileFactory::create(url, expCallCount);
- assertCoveredFilesEqual(expFile2, actualFile2);
-
- delete expFile1;
- delete expFile2;
-}
-
-
-QTEST_MAIN( LcovInfoParserTest )
-#include "lcovinfoparsertest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/lcovinfoparsertest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp (nonexistent)
@@ -1,189 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "removegcdafilesjobprogresstest.h"
-#include "../removegcdafilesjobprogress.h"
-
-#include "testutils.h"
-
-using Veritas::RemoveGcdaFilesJobProgress;
-using Veritas::RemoveGcdaFilesJobProgressTest;
-
-//KDevelop::IStatus* must be declared as a metatype to be used in qvariant_cast
-Q_DECLARE_METATYPE(KDevelop::IStatus*);
-
-void RemoveGcdaFilesJobProgressTest::init()
-{
- m_removeGcdaFilesJobProgress = new RemoveGcdaFilesJobProgress();
-
- //KDevelop::IStatus* must be registered in order to be used with QSignalSpy
- qRegisterMetaType<KDevelop::IStatus*>("KDevelop::IStatus*");
-
- m_clearMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
- SIGNAL(clearMessage(KDevelop::IStatus*)));
- m_showMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
- SIGNAL(showMessage(KDevelop::IStatus*,QString,int)));
- m_showErrorMessageSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
- SIGNAL(showErrorMessage(QString,int)));
- m_hideProgressSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
- SIGNAL(hideProgress(KDevelop::IStatus*)));
- m_showProgressSpy = new QSignalSpy(m_removeGcdaFilesJobProgress,
- SIGNAL(showProgress(KDevelop::IStatus*,int,int,int)));
-}
-
-void RemoveGcdaFilesJobProgressTest::cleanup()
-{
- delete m_clearMessageSpy;
- delete m_showMessageSpy;
- delete m_showErrorMessageSpy;
- delete m_hideProgressSpy;
- delete m_showProgressSpy;
-
- delete m_removeGcdaFilesJobProgress;
-}
-
-void RemoveGcdaFilesJobProgressTest::testStatusName()
-{
- QCOMPARE(m_removeGcdaFilesJobProgress->statusName(), i18nc("@info:progress", "Removing coverage data"));
-}
-
-void RemoveGcdaFilesJobProgressTest::testStart()
-{
- m_removeGcdaFilesJobProgress->start();
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
- QVariant argument = m_showMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Scanning for .gcda files"));
- QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 0);
-}
-
-void RemoveGcdaFilesJobProgressTest::testSetNumberOfFilesFound()
-{
- m_removeGcdaFilesJobProgress->setNumberOfFilesFound(42);
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
- QVariant argument = m_showMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showMessageSpy->at(0).at(1).toString(), i18nc("@info:progress", "Removing .gcda files"));
- QCOMPARE(m_showMessageSpy->at(0).at(2).toInt(), 0);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 2);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
-}
-
-void RemoveGcdaFilesJobProgressTest::testProgressUpdateWhenFilesAreRemoved()
-{
- m_removeGcdaFilesJobProgress->setNumberOfFilesFound(5);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
-
- m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
-
- QCOMPARE(m_showProgressSpy->count(), 2);
- QVariant argument = m_showProgressSpy->at(1).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(1).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(1).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(1).at(3).toInt(), 50);
-
- m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
-
- QCOMPARE(m_showProgressSpy->count(), 3);
- argument = m_showProgressSpy->at(2).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(2).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(2).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(2).at(3).toInt(), 60);
-
- m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
- m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
- m_removeGcdaFilesJobProgress->fileAboutToBeRemoved();
-
- QCOMPARE(m_showProgressSpy->count(), 6);
- argument = m_showProgressSpy->at(3).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(3).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(3).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(3).at(3).toInt(), 70);
-
- argument = m_showProgressSpy->at(4).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(4).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(4).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(4).at(3).toInt(), 80);
-
- argument = m_showProgressSpy->at(5).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(5).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(5).at(2).toInt(), 100);
- QCOMPARE(m_showProgressSpy->at(5).at(3).toInt(), 90);
-
- QCOMPARE(m_clearMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
- QCOMPARE(m_hideProgressSpy->count(), 0);
-
- QCOMPARE(m_showMessageSpy->count(), 1);
-}
-
-void RemoveGcdaFilesJobProgressTest::testFinish()
-{
- m_removeGcdaFilesJobProgress->finish();
-
- QCOMPARE(m_showMessageSpy->count(), 0);
- QCOMPARE(m_showErrorMessageSpy->count(), 0);
-
- QCOMPARE(m_clearMessageSpy->count(), 1);
- QVariant argument = m_clearMessageSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
-
- QCOMPARE(m_showProgressSpy->count(), 1);
- argument = m_showProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
- QCOMPARE(m_showProgressSpy->at(0).at(1).toInt(), 0);
- QCOMPARE(m_showProgressSpy->at(0).at(2).toInt(), 1);
- QCOMPARE(m_showProgressSpy->at(0).at(3).toInt(), 1);
-
- QCOMPARE(m_hideProgressSpy->count(), 1);
- argument = m_hideProgressSpy->at(0).at(0);
- QCOMPARE(qvariant_cast<KDevelop::IStatus*>(argument), m_removeGcdaFilesJobProgress);
-}
-
-QTEST_KDEMAIN(RemoveGcdaFilesJobProgressTest, NoGUI)
-
-#include "removegcdafilesjobprogresstest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/removegcdafilesjobprogresstest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp (nonexistent)
@@ -1,278 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "buildpathselectiontest.h"
-#include "../buildpathselection.h"
-#include "testutils.h"
-
-#include <KComboBox>
-#include <KStandardDirs>
-#include <KUrlNavigator>
-
-#include <interfaces/iproject.h>
-#include <interfaces/iprojectcontroller.h>
-#include <project/projectmodel.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <shell/core.h>
-#include <tests/autotestshell.h>
-
-using KDevelop::AutoTestShell;
-using KDevelop::Core;
-using KDevelop::IProject;
-
-using Veritas::BuildPathSelection;
-using Veritas::BuildPathSelectionTest;
-
-Q_DECLARE_METATYPE(KDevelop::IProject*)
-
-//Start of code adapted from veritas/tests/projectselectiontest.h
-
-/**
- * Modified version of private KSignalSpy found in
- * kdelibs/kdecore/util/qtest_kde.cpp.
- * Original KDESignalSpy, accessed through
- * QTest::kWaitForSignal(QObject*, const char*, int), can miss a signal if it is
- * emitted too quickly (that is, before the connect is reached). This modified
- * version, instead of starting the wait in the constructor, has a specific
- * method for it. So the object can be created before executing the call that
- * emits the signal, enabling it to register the signal before starting to wait
- * and thus ensuring that no signal will be missed.
- *
- * Moreover, this modified version allows to wait for up to n emitted signals
- * instead of only the first one. Note that the count isn't reseted after
- * receiving all the expected signals, so if you wait for more signals use an
- * absolute value (that is, the already received signals plus those you want to
- * wait for now).
- */
-class SignalSpy: public QObject
-{
-Q_OBJECT
-public:
- SignalSpy(QObject* object, const char* signal):
- QObject(0), m_signalSpy(object, signal), m_expectedCount(0)
- {
- connect(object, signal, this, SLOT(signalEmitted()));
- }
-
- bool waitForCount(int expectedCount, int timeout)
- {
- if (m_signalSpy.count() < expectedCount) {
- m_expectedCount = expectedCount;
-
- if (timeout > 0) {
- QObject::connect(&m_timer, SIGNAL(timeout()), &m_loop, SLOT(quit()));
- m_timer.setSingleShot(true);
- m_timer.start(timeout);
- }
- m_loop.exec();
- }
-
- if (m_signalSpy.count() >= expectedCount) {
- return true;
- }
- return false;
- }
-
-private Q_SLOTS:
- void signalEmitted()
- {
- if (m_signalSpy.count() >= m_expectedCount) {
- m_timer.stop();
- m_loop.quit();
- }
- }
-private:
- QSignalSpy m_signalSpy;
- int m_expectedCount;
- QEventLoop m_loop;
- QTimer m_timer;
-};
-
-void BuildPathSelectionTest::initTestCase()
-{
- AutoTestShell::init();
- Core::initialize();
- qRegisterMetaType<KDevelop::IProject*>();
-
- m_testPath = KStandardDirs().saveLocation("tmp", "buildPathSelectionTest/");
-
- m_project1Url = writeProjectConfiguration("Project1", "/project1/build");
- m_project2Url = writeProjectConfiguration("Project2", "/project2/build");
- m_project3FilteredUrl = writeProjectConfiguration("Project3Filtered", "");
-}
-
-void BuildPathSelectionTest::init()
-{
- m_urlNavigator = new KUrlNavigator(0, KUrl(QDir::homePath()), 0);
- m_buildPathSelection = new BuildPathSelection(m_urlNavigator);
-
- m_parent = new QWidget();
- QWidget* widget = m_buildPathSelection->requestProjectSelectionWidget(m_parent);
- m_comboBox = qobject_cast<KComboBox*>(widget);
-}
-
-void BuildPathSelectionTest::cleanup()
-{
- SignalSpy projectClosedSignal(Core::self()->projectController(), SIGNAL(projectClosed(KDevelop::IProject*)));
- int count = Core::self()->projectController()->projects().count();
-
- foreach(IProject* project, Core::self()->projectController()->projects()) {
- Core::self()->projectController()->closeProject(project);
- }
-
- projectClosedSignal.waitForCount(count, 30000);
-
- //Project configuration file isn't the kdev4 project file used to load the
- //project, so if the configuration was modified in a test it would be
- //modified in the other tests if these files aren't removed
- QFile(m_testPath + ".kdev4/Project1.kdev4").remove();
- QFile(m_testPath + ".kdev4/Project2.kdev4").remove();
- QFile(m_testPath + ".kdev4/Project3Filtered.kdev4").remove();
-
- delete m_parent;
- delete m_buildPathSelection;
- delete m_urlNavigator;
-}
-
-void BuildPathSelectionTest::cleanupTestCase()
-{
- QDir().rmdir(m_testPath + ".kdev4/");
- QFile(m_project1Url.path()).remove();
- QFile(m_project2Url.path()).remove();
- QFile(m_project3FilteredUrl.path()).remove();
- QDir().rmdir(m_testPath);
-}
-
-//End of code adapted from veritas/tests/projectselectiontest.h
-
-void BuildPathSelectionTest::testRequestProjectSelectionWidget()
-{
- QVERIFY(m_comboBox);
- QCOMPARE(m_comboBox->parentWidget(), m_parent);
-}
-
-void BuildPathSelectionTest::testProjectFilter()
-{
- openProject(m_project1Url);
- openProject(m_project2Url);
- openProject(m_project3FilteredUrl);
-
- QAbstractItemModel* model = m_comboBox->model();
-
- QVERIFY(model->flags(model->index(0, 0)) & Qt::ItemIsEnabled);
- QVERIFY(model->flags(model->index(1, 0)) & Qt::ItemIsEnabled);
- QVERIFY(model->flags(model->index(2, 0)) & ~Qt::ItemIsEnabled);
-}
-
-void BuildPathSelectionTest::testSelectProject()
-{
- openProject(m_project1Url);
- openProject(m_project2Url);
-
- QCOMPARE(m_comboBox->currentIndex(), -1);
- QCOMPARE(m_urlNavigator->url(), KUrl(QDir::homePath()));
-
- m_comboBox->setCurrentIndex(0);
-
- QCOMPARE(m_urlNavigator->url().toLocalFile(KUrl::AddTrailingSlash), QString("/project1/build/"));
-
- m_comboBox->setCurrentIndex(1);
-
- QCOMPARE(m_urlNavigator->url().toLocalFile(KUrl::AddTrailingSlash), QString("/project2/build/"));
-}
-
-void BuildPathSelectionTest::testChangeBuildPath()
-{
- openProject(m_project1Url);
- openProject(m_project2Url);
-
- m_urlNavigator->setUrl(QString("file:///project2/build/"));
-
- QCOMPARE(m_comboBox->currentIndex(), 1);
-
- m_urlNavigator->setUrl(QString("file:///project1/build"));
-
- QCOMPARE(m_comboBox->currentIndex(), 0);
-}
-
-void BuildPathSelectionTest::testChangeBuildPathToUnknownPath()
-{
- openProject(m_project1Url);
- openProject(m_project2Url);
-
- m_urlNavigator->setUrl(QString("file:///project1/build"));
-
- QCOMPARE(m_comboBox->currentIndex(), 0);
-
- m_urlNavigator->setUrl(QString("file:///project2"));
-
- QCOMPARE(m_comboBox->currentIndex(), -1);
-}
-
-/////////////////////////////////// Helpers ////////////////////////////////////
-
-//Start of code adapted from veritas/tests/projectselectiontest.h
-
-KUrl BuildPathSelectionTest::writeProjectConfiguration(const QString& name,
- const QString& buildPath) const
-{
- KUrl configurationUrl = KUrl(m_testPath + name + ".kdev4");
-
- QFile file(configurationUrl.pathOrUrl());
- file.open(QIODevice::WriteOnly);
- QTextStream out(&file);
- out << "[Project]\n"
- << "Name=" << name << "\n";
- if (!buildPath.isEmpty()) {
- out << "Manager=KDevCMakeManager\n"
- << "[CMake]\n"
- << "BuildDirs=" << buildPath << "\n"
- << "CurrentBuildDir=file://" << buildPath << "\n";
- }
- file.close();
-
- return configurationUrl;
-}
-
-void BuildPathSelectionTest::openProject(const KUrl& url) const
-{
- SignalSpy projectOpenedSignal(Core::self()->projectController(),
- SIGNAL(projectOpened(KDevelop::IProject*)));
- Core::self()->projectController()->openProject(url);
- if (!projectOpenedSignal.waitForCount(1, 30000)) {
- QWARN("Timeout waiting for projectOpened");
- }
-}
-
-void BuildPathSelectionTest::closeProject(IProject* project) const
-{
- SignalSpy projectClosedSignal(Core::self()->projectController(),
- SIGNAL(projectClosed(KDevelop::IProject*)));
- Core::self()->projectController()->closeProject(project);
- if (!projectClosedSignal.waitForCount(1, 30000)) {
- QWARN("Timeout waiting for projectClosed");
- }
-}
-
-//End of code adapted from veritas/tests/projectselectiontest.h
-
-QTEST_KDEMAIN(BuildPathSelectionTest, GUI)
-
-#include "moc_buildpathselectiontest.cpp"
-#include "buildpathselectiontest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/buildpathselectiontest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp (nonexistent)
@@ -1,123 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "reportfileitemtest.h"
-#include "coveredfilefactory.h"
-#include "../reportmodel.h"
-#include "../coveredfile.h"
-
-#include "testutils.h"
-
-using Veritas::ReportFileItemTest;
-using Veritas::ReportFileItem;
-using Veritas::CoveredFile;
-using Veritas::Test::CoveredFileFactory;
-
-void ReportFileItemTest::init()
-{
- m_url = KUrl("/path/to/foo.cpp");
- m_fileName = m_url.fileName();
- m_file = new ReportFileItem(m_url);
-}
-
-void ReportFileItemTest::cleanup()
-{
- if (m_file) {
- delete m_file->coverageRatioItem();
- delete m_file->nrofCoveredLinesItem();
- delete m_file->slocItem();
- delete m_file;
- }
- qDeleteAll(m_garbage);
- m_garbage.clear();
-}
-
-void ReportFileItemTest::construct()
-{
- KVERIFY(ReportModel::File == m_file->type());
- KOMPARE(m_url, m_file->url());
-
- // QStandardItem properties
- KVERIFY(! m_file->isEditable());
- KVERIFY(m_file->isSelectable());
- KVERIFY(! m_file->isCheckable());
-
- // Neighbour items should be initialized on 0
- KOMPARE(0, m_file->slocItem());
- KOMPARE(0, m_file->coverageRatioItem());
- KOMPARE(0, m_file->nrofCoveredLinesItem());
-}
-
-void ReportFileItemTest::addCoverage()
-{
- int sloc = 2, nrofCovered = 1;
- CoveredFile* f = CoveredFileFactory::create(m_url, sloc, nrofCovered);
- m_file->addCoverageData(f);
-
- assertSlocItem(2);
- assertInstrumentedItem(1);
- assertCoverageItem(100*(double)1/2);
-
- m_garbage << f;
-}
-
-void ReportFileItemTest::assertInstrumentedItem(int instrumented)
-{
- ReportValueItem* instrumentedItem = m_file->nrofCoveredLinesItem();
- KOMPARE(instrumented, instrumentedItem->value());
-}
-
-void ReportFileItemTest::assertSlocItem(int sloc)
-{
- ReportValueItem* slocItem = m_file->slocItem();
- KOMPARE(sloc, slocItem->value());
-}
-
-void ReportFileItemTest::assertCoverageItem(double coverage)
-{
- ReportValueItem* coverageItem = m_file->coverageRatioItem();
- double actual = coverageItem->value();
- KVERIFY_MSG(qAbs(coverage - actual) < 0.1,
- QString("\nWrong coverage percentage for coverage item.\n"
- "expected %1 but got %2").arg(coverage).arg(actual));
-}
-
-void ReportFileItemTest::addMultipleCoverage()
-{
- QList<int> covered; covered << 1 << 2 << 3;
- QList<int> notCovered; notCovered << 4;
- CoveredFile* f = CoveredFileFactory::create(m_url, covered, notCovered);
- m_file->addCoverageData(f);
-
- covered.clear(); covered << 3 << 4;
- notCovered.clear(); notCovered << 1 << 2;
- CoveredFile* f2 = CoveredFileFactory::create(m_url, covered, notCovered);
- m_file->addCoverageData(f2);
-
- assertInstrumentedItem(4);
- assertSlocItem(4);
- assertCoverageItem(100.0);
-
- m_garbage << f << f2;
-}
-
-
-QTEST_KDEMAIN( ReportFileItemTest, NoGUI)
-#include "reportfileitemtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/reportfileitemtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp (nonexistent)
@@ -1,21 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "pluginstub.h"
-#include "pluginstub.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/pluginstub.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h (nonexistent)
@@ -1,80 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef COVERAGE_ANNOTATIONMANAGER_TEST_H
-#define COVERAGE_ANNOTATIONMANAGER_TEST_H
-
-#include <QtCore/QObject>
-#include <KUrl>
-
-namespace KDevelop { class ICore; class IDocument; }
-namespace KTextEditor { class View; }
-namespace TestStubs { class Core; class KDevDocument; class DocumentController; }
-namespace Veritas { class CoveredFile; }
-
-namespace Veritas
-{
-
-class AnnotationManager;
-class AnnotationManagerTest : public QObject
-{
-Q_OBJECT
-private slots:
- void initTestCase();
- void init();
- void cleanup();
-
- void instantiate();
- void singleLine();
- void multipleLines();
- void multipleViews();
- void multipleFiles();
- void notCovered();
- void stopWatching();
- void multiCoverageOneFile();
- void annotationsOnExistingView();
- void addRemoveAndReAddAnnotations();
-
-private: // helpers
- void initManager(Veritas::CoveredFile* f);
- KTextEditor::View* triggerAnnotationsOnView(KDevelop::IDocument*);
- TestStubs::KDevDocument* createKDevDocument(const KUrl& u);
- Veritas::CoveredFile* createCoveredFile(int line, int callCount, KUrl);
- void assertAnnoCallCountEquals(int line, int count, KTextEditor::View*);
- void assertNoAnnotationsOnLine(int line, KTextEditor::View* v);
- void assertAnnotationsGone(KTextEditor::View* v);
-
-private: // fixture
- AnnotationManager* m_annotationManager;
- TestStubs::Core* m_core;
- TestStubs::DocumentController* m_docCtrl;
- KUrl m_someUrl;
- QWidget* m_widget;
- int m_lineNr; // source line number
- int m_nrofCalls; // number of calls on this line
-
- QList<CoveredFile*> m_garbageFiles;
- QList<TestStubs::KDevDocument*> m_garbageDocs;
- QList<QObject*> m_garbage;
-};
-
-}
-
-#endif // COVERAGE_ANNOTATIONMANAGER_TEST_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/annotationmanagertest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp (nonexistent)
@@ -1,22 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "viewstub.h"
-#include "viewstub.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/viewstub.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/documentstub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/documentstub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/documentstub.h (nonexistent)
@@ -1,198 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTFAKES_DOCUMENTSTUB_H
-#define TESTFAKES_DOCUMENTSTUB_H
-
-#include "interfaces/idocument.h"
-
-namespace KDevelop
-{
-class ICore;
-}
-
-namespace TestStubs
-{
-
-class KDevDocument : public KDevelop::IDocument
-{
-public:
- KDevDocument(KDevelop::ICore* c) : IDocument(c) {
- m_isTextDocument = true;
- m_isActive = true;
- m_save = true;
- m_partForView = 0;
- m_state = IDocument::Clean;
- m_textDocument = 0;
- }
- virtual ~KDevDocument() {}
-
- virtual KUrl url() const {
- return m_url;
- }
- virtual KMimeType::Ptr mimeType() const {
- return KSharedPtr<KMimeType>();
- }
- virtual KParts::Part* partForView(QWidget *view) const {
- return m_partForView;
- }
- virtual bool isTextDocument() const {
- return m_isTextDocument;
- }
- virtual KTextEditor::Document* textDocument() const {
- return m_textDocument;
- }
- virtual bool save(DocumentSaveMode mode = Default) {
- return m_save;
- }
- virtual void reload() {}
- virtual bool close(DocumentSaveMode mode = Default) {
- return true;
- }
- virtual bool isActive() const {
- return m_isActive;
- }
- virtual DocumentState state() const {
- return m_state;
- }
- virtual KTextEditor::Cursor cursorPosition() const {
- return KTextEditor::Cursor();
- }
- virtual void setCursorPosition(const KTextEditor::Cursor &cursor) {
- }
- virtual KTextEditor::Range textSelection() const {
- return KTextEditor::Range();
- }
- virtual void setTextSelection(const KTextEditor::Range &/*range*/) {
- }
- virtual void activate(Sublime::View *activeView, KParts::MainWindow *mainWindow) {
- }
-
- // inject whatever it is you need
- KUrl m_url;
- bool m_isTextDocument;
- bool m_isActive;
- bool m_save;
- KParts::Part* m_partForView;
- DocumentState m_state;
- KTextEditor::Document* m_textDocument;
- KTextEditor::Cursor m_cursorPosition;
- KTextEditor::Range m_textSelection;
-};
-
-}
-
-#include <ktexteditor/document.h>
-
-namespace TestStubs
-{
-
-class TextDocument : public KTextEditor::Document
-{
-// Q_OBJECT
-
-public:
- TextDocument(QObject *parent = 0) :
- KTextEditor::Document(parent),
- m_createView(0) {}
- virtual ~TextDocument() {}
-
- QList<KTextEditor::View*> m_views;
- KTextEditor::Editor* m_editor;
- KTextEditor::View* m_createView;
- KTextEditor::View* m_activeView;
- QString m_encoding;
- QString m_documentName;
-
-public:
- virtual KTextEditor::Editor *editor() { return m_editor; }
- virtual KTextEditor::View *createView(QWidget *parent) {
- emit viewCreated(this, m_createView);
- //m_views.clear();
- m_views << m_createView;
- return m_createView;
- }
-
- virtual KTextEditor::View* activeView() const { return m_activeView; }
- virtual const QList<KTextEditor::View*> &views() const { return m_views; }
- virtual const QString &documentName() const { return m_documentName; }
- virtual QString mimeType() { return ""; }
- virtual bool setEncoding(const QString &encoding) { return true; }
- virtual const QString &encoding() const { return m_encoding; }
- virtual bool documentReload() { return true; }
- virtual bool documentSave() { return true; }
- virtual bool documentSaveAs() { return true; }
- virtual bool startEditing() { return true; }
- virtual bool endEditing() { return true; }
- virtual QString text() const { return ""; }
- virtual QString text(const KTextEditor::Range& /*range*/, bool block = false) const { return ""; }
- virtual QChar character(const KTextEditor::Cursor& position) const { return ' '; }
- virtual QStringList textLines(const KTextEditor::Range& /*range*/, bool block = false) const { return QStringList(); }
- virtual QString line(int /*line*/) const { return QString(); }
- virtual int /*line*/s() const { return 0; }
- virtual KTextEditor::Cursor documentEnd() const { return KTextEditor::Cursor(); }
- virtual int totalCharacters() const { return 0; }
- virtual bool isEmpty() const { return true; }
- virtual int /*line*/Length(int /*line*/) const { return 0; }
- virtual bool setText(const QString &/*text*/) { return true; }
- virtual bool setText(const QStringList &text) { return true; }
- virtual bool clear() { return true; }
- virtual bool insertText(const KTextEditor::Cursor &/*position*/, const QString &/*text*/, bool block = false) { return true; }
- virtual bool insertText(const KTextEditor::Cursor &/*position*/, const QStringList &text, bool block = false) { return true; }
- virtual bool replaceText(const KTextEditor::Range &/*range*/, const QString &/*text*/, bool block = false) { return true; }
- virtual bool replaceText(const KTextEditor::Range &/*range*/, const QStringList &/*text*/, bool block = false) { return true; }
- virtual bool removeText(const KTextEditor::Range &/*range*/, bool block = false) { return true; }
- virtual bool insertLine(int /*line*/, const QString &/*text*/) { return true; }
- virtual bool insertLines(int /*line*/, const QStringList &/*text*/) { return true; }
- virtual bool removeLine(int /*line*/) { return true; }
- virtual QString mode() const { return ""; }
- virtual QString highlightingMode() const { return ""; }
- virtual QStringList modes() const { return QStringList(); }
- virtual QStringList highlightingModes() const { return QStringList(); }
- virtual bool setMode(const QString &/*name*/) { return true; }
- virtual bool setHighlightingMode(const QString &/*name*/) { return true; }
- virtual QString highlightingModeSection(int /*index*/) const { return ""; }
- virtual QString modeSection(int /*index*/) const { return ""; }
-
- virtual bool openFile() { return true; }
- virtual bool saveFile() { return true; }
- virtual int lines() const { return 0; }
- virtual int lineLength(int) const { return 0; }
-
-
-#if 0
-Q_SIGNALS:
- void viewCreated(KTextEditor::Document *document, KTextEditor::View *view);
- void documentNameChanged(KTextEditor::Document *document);
- void documentUrlChanged(KTextEditor::Document *document);
- void modifiedChanged(KTextEditor::Document *document);
- void textChanged(KTextEditor::Document *document);
- void textInserted(KTextEditor::Document *document, const KTextEditor::Range& /*range*/);
- void textRemoved(KTextEditor::Document *document, const KTextEditor::Range& /*range*/);
- void textChanged(KTextEditor::Document *document, const KTextEditor::Range& oldRange,
- const KTextEditor::Range& newRange);
- void aboutToClose(KTextEditor::Document *document);
- void aboutToReload(KTextEditor::Document *document);
-#endif
-};
-
-}
-
-
-#endif // TESTFAKES_DOCUMENTSTUB_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/documentstub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp (nonexistent)
@@ -1,106 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "gradientcolorrangetest.h"
-#include "../gradientcolorrange.h"
-
-#include "testutils.h"
-
-using Veritas::GradientColorRangeTest;
-
-void GradientColorRangeTest::testConstructor()
-{
- GradientColorRange gcr;
-
- QCOMPARE(gcr.stopPoints().size(), 2);
- QCOMPARE(gcr.colorAt(0), QColor(Qt::black));
- QCOMPARE(gcr.colorAt(1), QColor(Qt::white));
-}
-
-void GradientColorRangeTest::testSetStopPoints()
-{
- GradientColorRange gcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.23, QColor(Qt::blue)));
- stopPoints.append(StopPoint(0.42, QColor(Qt::darkGreen)));
- stopPoints.append(StopPoint(1, QColor(Qt::cyan)));
- gcr.setStopPoints(stopPoints);
-
- QCOMPARE(gcr.stopPoints().size(), 4);
- QCOMPARE(gcr.stopPoints()[0].first, 0.0);
- QCOMPARE(gcr.stopPoints()[0].second, QColor(Qt::red));
- QCOMPARE(gcr.stopPoints()[1].first, 0.23);
- QCOMPARE(gcr.stopPoints()[1].second, QColor(Qt::blue));
- QCOMPARE(gcr.stopPoints()[2].first, 0.42);
- QCOMPARE(gcr.stopPoints()[2].second, QColor(Qt::darkGreen));
- QCOMPARE(gcr.stopPoints()[3].first, 1.0);
- QCOMPARE(gcr.stopPoints()[3].second, QColor(Qt::cyan));
-}
-
-void GradientColorRangeTest::testColorAtWithNoMiddleStopPoints()
-{
- GradientColorRange gcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::red)));
- stopPoints.append(StopPoint(1, QColor(Qt::yellow)));
- gcr.setStopPoints(stopPoints);
-
- QCOMPARE(gcr.colorAt(0), QColor(Qt::red));
- assertFuzzyColor(gcr.colorAt(0.5), QColor(255, 127, 0));
- QCOMPARE(gcr.colorAt(1), QColor(Qt::yellow));
-}
-
-void GradientColorRangeTest::testColorAtWithSeveralStopPoints()
-{
- GradientColorRange gcr;
-
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor(Qt::black)));
- stopPoints.append(StopPoint(0.333, QColor(Qt::red)));
- stopPoints.append(StopPoint(0.667, QColor(Qt::yellow)));
- stopPoints.append(StopPoint(1, QColor(Qt::green)));
- gcr.setStopPoints(stopPoints);
-
- QCOMPARE(gcr.colorAt(0), QColor(Qt::black));
- assertFuzzyColor(gcr.colorAt(0.167), QColor(127, 0, 0));
- assertFuzzyColor(gcr.colorAt(0.333), QColor(Qt::red));
- assertFuzzyColor(gcr.colorAt(0.5), QColor(255, 127, 0));
- assertFuzzyColor(gcr.colorAt(0.667), QColor(Qt::yellow));
- assertFuzzyColor(gcr.colorAt(0.834), QColor(127, 255, 0));
- QCOMPARE(gcr.colorAt(1), QColor(Qt::green));
-}
-
-////////////////////////////// Asserts ////////////////////////////////////////
-
-void GradientColorRangeTest::assertFuzzyColor(const QColor& actual, const QColor& expected)
-{
- QVERIFY(actual.red() >= expected.red() -1);
- QVERIFY(actual.red() <= expected.red() + 1);
- QVERIFY(actual.green() >= expected.green() -1);
- QVERIFY(actual.green() <= expected.green() + 1);
- QVERIFY(actual.blue() >= expected.blue() -1);
- QVERIFY(actual.blue() <= expected.blue() + 1);
-}
-
-QTEST_KDEMAIN(GradientColorRangeTest, NoGUI)
-
-#include "gradientcolorrangetest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/gradientcolorrangetest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp (nonexistent)
@@ -1,101 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "coveredfiletest.h"
-#include "../coveredfile.h"
-
-#include "testutils.h"
-
-using Veritas::CoveredFile;
-using Veritas::CoveredFileTest;
-
-void CoveredFileTest::init()
-{
- m_file = new CoveredFile;
-}
-
-void CoveredFileTest::cleanup()
-{
- if (m_file) delete m_file;
-}
-
-void CoveredFileTest::construct()
-{
- KOMPARE(KUrl(), m_file->url());
- KOMPARE(0, m_file->coverageRatio());
- KOMPARE(0, m_file->sloc());
- KOMPARE(0, m_file->nrofCoveredLines());
- KOMPARE(0, m_file->callCountMap().count());
-}
-
-void CoveredFileTest::sunny()
-{
- m_file->setCallCount(1,0);
- m_file->setCallCount(2,0);
- m_file->setCallCount(3,1);
- m_file->setCallCount(4,1);
- KOMPARE(50.0, m_file->coverageRatio());
-}
-
-void CoveredFileTest::zeroSloc()
-{
- KOMPARE(0, m_file->coverageRatio());
-}
-
-void CoveredFileTest::callCount()
-{
- m_file->setCallCount(10, 5);
- m_file->setCallCount(11, 4);
-
- QMap<int, int> callMap = m_file->callCountMap();
- KOMPARE(2, callMap.count());
- KVERIFY(callMap.contains(10));
- KOMPARE(5, callMap[10]);
- KVERIFY(callMap.contains(11));
- KOMPARE(4, callMap[11]);
-}
-
-void CoveredFileTest::linesSet()
-{
- m_file->setCallCount(9, 0);
- m_file->setCallCount(10, 5);
- m_file->setCallCount(11, 0);
- m_file->setCallCount(12, 3);
-
-
- QSet<int> lines;
- lines << 10 << 12;
- KOMPARE(lines, m_file->coveredLines());
-}
-
-void CoveredFileTest::isReachable()
-{
- m_file->setCallCount(2,1);
- KVERIFY(m_file->isReachable(2));
- KVERIFY(!m_file->isReachable(1));
-
- m_file->setCallCount(1,0);
- KVERIFY(m_file->isReachable(1));
- KVERIFY(m_file->isReachable(2));
- KVERIFY(!m_file->isReachable(3));
-}
-
-QTEST_KDEMAIN( CoveredFileTest, NoGUI)
-#include "coveredfiletest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/tests/coveredfiletest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.h (nonexistent)
@@ -1,50 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
-#define VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
-
-#include <QtGui/QItemDelegate>
-#include <kcolorscheme.h>
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-/*! Colorizes the lcovjob somewhat */
-class VERITAS_COVERAGE_EXPORT CovOutputDelegate : public QItemDelegate
-{
-public:
- explicit CovOutputDelegate(QObject* parent = 0);
- virtual ~CovOutputDelegate();
-
- void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
-private:
- KStatefulBrush textBrush;
- KStatefulBrush processBrush;
- KStatefulBrush warningBrush;
- KStatefulBrush errorBrush;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_COVOUTPUTDELEGATE_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.cpp (nonexistent)
@@ -1,213 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "lcovjob.h"
-#include "covoutputmodel.h"
-#include "covoutputdelegate.h"
-
-#include "lcovinfoparser.h"
-#include "lcovjobprogress.h"
-#include "coveredfile.h"
-#include "annotationmodel.h"
-#include "annotationmanager.h"
-#include "reportwidget.h"
-
-#include <QDir>
-#include <QTableWidget>
-
-#include <KProcess>
-#include <KLocale>
-#include <KConfigGroup>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <util/processlinemaker.h>
-#include <shell/core.h>
-
-#include <ktexteditor/annotationinterface.h>
-#include <ktexteditor/cursor.h>
-#include <ktexteditor/document.h>
-
-using KDevelop::ICore;
-using KDevelop::Core;
-using KDevelop::IDocument;
-using KDevelop::IDocumentController;
-using KDevelop::IOutputView;
-using KDevelop::IToolViewFactory;
-using KDevelop::ProcessLineMaker;
-
-using KTextEditor::AnnotationModel;
-using KTextEditor::AnnotationInterface;
-using KTextEditor::AnnotationViewInterface;
-using KTextEditor::Document;
-
-using Veritas::CoveredFile;
-using Veritas::LcovJob;
-using Veritas::LcovJobProgress;
-using Veritas::CovOutputModel;
-using Veritas::CovOutputDelegate;
-using Veritas::LcovInfoParser;
-using Veritas::AnnotationManager;
-using Veritas::ReportViewFactory;
-
-LcovJob::LcovJob(const KUrl& root, QObject* parent)
- : OutputJob(parent), m_lcov(0), m_root(root), m_parser(0)
-{
- setCapabilities(Killable);
- setObjectName(i18nc("@action:inmenu", "Run <command>geninfo</command> on <filename>%1</filename> directory", root.toLocalFile()));
-
- m_lcovJobProgress = new LcovJobProgress(this);
- ICore::self()->uiController()->registerStatus(m_lcovJobProgress);
- connect(this, SIGNAL(result(KJob*)), m_lcovJobProgress, SLOT(finish()));
-}
-
-LcovJob::~LcovJob()
-{}
-
-void LcovJob::setDelegate(CovOutputDelegate* delegate)
-{
- OutputJob::setDelegate(delegate);
-}
-
-void LcovJob::setParser(LcovInfoParser* parser)
-{
- Q_ASSERT(parser); Q_ASSERT(m_parser == 0);
- m_parser = parser;
-}
-
-void LcovJob::setProcess(KProcess *proc)
-{
- Q_ASSERT(proc);
- m_lcov = proc;
- m_lcov->setParent(this);
-}
-
-void LcovJob::initProcess()
-{
- Q_ASSERT_X(m_lcov, "LcovJob::initProcess()", "illegal usage, set process first.");
- QStringList args;
- //m_tmpPath = QDir::tempPath() + QDir::separator() + "kdevcoverage.tmp";
- QString root = m_root.pathOrUrl();
- if (root.endsWith(QLatin1String("./"))) root.chop(3);
- args << "-o"
- //<< m_tmpPath
- << "-"
- << m_root.pathOrUrl();
- KConfigGroup grp = KGlobal::config()->group("Code Coverage");
- KUrl geninfo = grp.readEntry("geninfoPath", KUrl("/usr/bin/geninfo") );
- m_lcov->setProgram( geninfo.toLocalFile(), args);
- m_lcov->setWorkingDirectory(m_root.pathOrUrl());
- m_lcov->setOutputChannelMode(KProcess::SeparateChannels);
- m_lineMaker = new ProcessLineMaker(m_lcov);
-
- //Ensure that the process output will be untranslated
- m_lcov->unsetEnv("LC_ALL");
- m_lcov->setEnv("LC_MESSAGES", "C");
-
- //connect(m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
- // model(), SLOT(appendOutputs(QStringList)));
- connect(m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
- model(), SLOT(appendErrors(QStringList)));
- connect(m_lineMaker, SIGNAL(receivedStderrLines(QStringList)),
- m_lcovJobProgress, SLOT(parseLines(QStringList)));
- connect(m_lcov, SIGNAL(finished(int,QProcess::ExitStatus)),
- this, SLOT(slotFinished()));
- connect(m_lcov, SIGNAL(error(QProcess::ProcessError)),
- this, SLOT(slotError(QProcess::ProcessError)));
-}
-
-void LcovJob::initOutputView()
-{
- setToolTitle(i18n("Cov verbose output"));
- setViewType(KDevelop::IOutputView::HistoryView);
- setStandardToolView(KDevelop::IOutputView::TestView);
- setBehaviours(IOutputView::AutoScroll | IOutputView::AllowUserClose);
- setModel(new CovOutputModel(0));
-}
-
-void LcovJob::initParser()
-{
- Q_ASSERT(m_parser);
- connect(m_lineMaker, SIGNAL(receivedStdoutLines(QStringList)),
- m_parser, SLOT(parseLines(QStringList)));
-}
-
-
-void LcovJob::start()
-{
- initOutputView();
- startOutput();
- initProcess();
- initParser();
- m_lcovJobProgress->start();
- m_lcov->start();
-}
-
-void LcovJob::slotFinished()
-{
- m_lineMaker->flushBuffers();
- model()->slotCompleted();
- emitResult();
-}
-
-void LcovJob::slotError(QProcess::ProcessError error)
-{
- QStringList errorList;
- if (error == QProcess::FailedToStart) {
- //i18nc can't be used. It seems that at this moment (2009-09-04) only
- //plain text can be used in the outputview
- //errorList << i18nc("@info", "Failed to start <filename>%1</filename>. Make sure that the path to <command>geninfo</command> is specified correctly in <interface>Settings->Configure KDevelop...->Lcov Preferences->geninfo Executable</interface>.", m_lcov->program().first());
- errorList << i18n("Failed to start '%1'. Make sure that the path to geninfo is specified correctly in Settings->Configure KDevelop...->Lcov Preferences->geninfo Executable.", m_lcov->program().first());
- } else if (error == QProcess::Crashed) {
- errorList << i18n("geninfo process crashed.");
- } else if (error == QProcess::Timedout) {
- errorList << i18n("geninfo process timed out.");
- } else if (error == QProcess::WriteError) {
- errorList << i18n("Failed to write to geninfo process.");
- } else if (error == QProcess::ReadError) {
- errorList << i18n("Failed to read from geninfo process.");
- } else if (error == QProcess::UnknownError) {
- errorList << i18n("Unknown geninfo process error.");
- }
- model()->appendErrors(errorList);
-
- m_lineMaker->flushBuffers();
- model()->slotCompleted();
- m_lcov->kill();
- setError(UserDefinedError);
- emitResult();
-}
-
-CovOutputModel* LcovJob::model() const
-{
- return static_cast<CovOutputModel*>(OutputJob::model());
-}
-
-bool LcovJob::doKill()
-{
- m_lcov->kill();
-
- model()->appendErrors(QStringList() << i18n("geninfo process was killed"));
-
- return true;
-}
-
-#include "lcovjob.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.h (nonexistent)
@@ -1,102 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_DISCRETECOLORRANGE_H
-#define VERITAS_COVERAGE_DISCRETECOLORRANGE_H
-
-#include <QColor>
-#include <QPair>
-#include <QVector>
-
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-typedef QPair<double, QColor> StopPoint;
-typedef QVector<StopPoint> StopPoints;
-
-/**
- * A collection of colors associated with discrete, non-overlapping ranges from
- * 0 to 1 (both included).
- * A stop point associate the range from the previous stop point (or
- * the beginning) to that point with a color. There is always at least one stop
- * point, the one at position 1.
- *
- * Method colorAt(double) can be used to know the color at some position (no
- * matter if there is a stop point or not at that position).
- *
- * Setting a red stop point at 0.333, a yellow stop point at 0.667 and a green
- * stop point at 1, the following values would be returned by colorAt:
- * - [0, 0.333] -> Red
- * - (0.333, 0.667] -> Yellow
- * - (0.667, 1] -> Green
- */
-class VERITAS_COVERAGE_EXPORT DiscreteColorRange
-{
-public:
-
- /**
- * Creates a new DiscreteColorRange.
- * The color at 1 is set to white, and there are no other stop points.
- */
- DiscreteColorRange();
-
- /**
- * Destroys this DiscreteColorRange.
- */
- virtual ~DiscreteColorRange();
-
- /**
- * Returns the color at the given position.
- *
- * @param position The position, in the range 0 to 1 (both included).
- * @return The color.
- */
- QColor colorAt(double position) const;
-
- /**
- * Returns the stop points.
- *
- * @return The stop points.
- */
- StopPoints stopPoints() const;
-
- /**
- * Sets the stop points.
- * The StopPoints must be in the range [0, 1], in ascending order, and they
- * must contain only valid colors. The list must contain at least the stop
- * point located at position 1.
- *
- * @param stopPoints The StopPoints to set.
- */
- void setStopPoints(const StopPoints& stopPoints);
-
-private:
-
- /**
- * The stop points.
- */
- StopPoints mStopPoints;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kcm_kdev_lcovsettings.desktop (nonexistent)
@@ -1,55 +0,0 @@
-[Desktop Entry]
-Icon=kdevelop
-Type=Service
-ServiceTypes=KCModule
-
-X-KDE-ModuleType=Library
-X-KDE-Library=kcm_kdev_lcovsettings
-X-KDE-FactoryName=kcm_kdev_lcovsettings
-X-KDE-ParentApp=kdevplatform
-X-KDE-ParentComponents=kdevplatform
-
-Name=lcov settings
-Name[bs]=icov postavke
-Name[ca]=Arranjament de lcov
-Name[ca@valencia]=Arranjament de lcov
-Name[de]=LCov-Einstellungen
-Name[en_GB]=lcov settings
-Name[es]=Preferencias de lcov
-Name[et]=LCovi seadistused
-Name[fr]=Paramètres de lcov
-Name[ga]=Socruithe lcov
-Name[gl]=Configuración de Icov
-Name[hu]=lcov beállítások
-Name[it]=Impostazioni di lcov
-Name[nl]=lcov instellingen
-Name[pl]=Ustawienia lcov
-Name[pt]=Configuração do Lcov
-Name[pt_BR]=Configuração do lcov
-Name[sv]=Inställningar av Lcov
-Name[tr]=Lcov ayarları
-Name[uk]=Параметри lcov
-Name[x-test]=xxlcov settingsxx
-Comment=Configure lcov settings
-Comment[bs]=Konfiguracija Icov postavki
-Comment[ca]=Configura l'arranjament de lcov
-Comment[ca@valencia]=Configura l'arranjament de lcov
-Comment[de]=lcov-Einstellungen festlegen
-Comment[en_GB]=Configure lcov settings
-Comment[es]=Configurar las preferencias de lcov
-Comment[et]=LCovi seadistamine
-Comment[fr]=Configurer les paramètres de Icov
-Comment[ga]=Cumraigh socruithe lcov
-Comment[gl]=Configurar as opcións de Icov
-Comment[hu]=Icov beállítások módosítása
-Comment[it]=Configura le impostazioni di lcov
-Comment[nds]=lcov instellen
-Comment[nl]=Configureert lcov instellingen
-Comment[pl]=Ustawienia lcov
-Comment[pt]=Configurar as opções do 'lcov'
-Comment[pt_BR]=Configurar as opções do 'lcov'
-Comment[sv]=Anpassa inställningar av Lcov
-Comment[tr]=lcov ayarlarını yapılandır
-Comment[uk]=Налаштувати параметри lcov
-Comment[x-test]=xxConfigure lcov settingsxx
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/CMakeLists.txt (nonexistent)
@@ -1,103 +0,0 @@
-project(coverage)
-
-set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${coverage_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-find_package(KDevVeritas REQUIRED)
-
-include(KDE4Defaults)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDEVVERITAS_INCLUDE_DIR}
- ${KDE4_INCLUDES}
-)
-
-kde4_no_enable_final(coverage)
-add_subdirectory(tests)
-
-add_definitions( ${KDE4_ENABLE_EXCEPTIONS} )
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-
-########### next target ###############
-
-set(veritascoverage_SRCS
- coveredfile.cpp
- annotationmodel.cpp
- lcovinfoparser.cpp
- annotationmanager.cpp
- lcovjob.cpp
- lcovjobprogress.cpp
- covoutputmodel.cpp
- covoutputdelegate.cpp
- reportwidget.cpp
- reportmodel.cpp
- reportproxymodel.cpp
- drilldownview.cpp
- colorrange.cpp
- discretecolorrange.cpp
- gradientcolorrange.cpp
- buildpathselection.cpp
- removegcdafilesjob.cpp
- removegcdafilesjobprogress.cpp
- tests/viewstub.cpp
- tests/pluginstub.cpp)
-
-kde4_add_ui_files(veritascoverage_SRCS reportwidget.ui)
-
-kde4_add_library(kdevveritascoverage SHARED ${veritascoverage_SRCS})
-target_link_libraries(kdevveritascoverage
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_SHELL_LIBRARIES}
- ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
- ${KDEVPLATFORM_UTIL_LIBRARIES}
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDE4_KDEUI_LIBS}
- ${KDE4_KTEXTEDITOR_LIBS}
- ${KDE4_KFILE_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVVERITAS_LIBRARY})
-install(TARGETS kdevveritascoverage ${INSTALL_TARGETS_DEFAULT_ARGS})
-
-qt4_automoc(coverageplugin.cpp)
-kde4_add_plugin(kdevcoverage coverageplugin.cpp)
-target_link_libraries(kdevcoverage
- kdevveritascoverage
- ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_UTIL_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KTEXTEDITOR_LIBS}
- ${KDE4_KDEUI_LIBS})
-install(TARGETS kdevcoverage DESTINATION ${PLUGIN_INSTALL_DIR})
-
-if( NOT KDE_VERSION VERSION_LESS "4.2.2" )
-
- set(lcovsettings_cfg_SRCS
- lcovprefs.cpp
- lcovprefswidget.cpp
- lcovsettingsbase.cpp
- stoppointwidget.cpp
- colorrangebar.cpp
- colorrange.cpp
- discretecolorrange.cpp
- gradientcolorrange.cpp)
-
- kde4_add_ui_files( lcovsettings_cfg_SRCS lcovprefswidget.ui stoppointwidget.ui)
- kde4_add_kcfg_files( lcovsettings_cfg_SRCS lcovconfig.kcfgc )
- kde4_add_plugin( kcm_kdev_lcovsettings ${lcovsettings_cfg_SRCS} )
- target_link_libraries( kcm_kdev_lcovsettings ${KDE4_KUTILS_LIBS} ${KDE4_KDEUI_LIBS} ${KDE4_KIO_LIBS} )
- install( TARGETS kcm_kdev_lcovsettings DESTINATION ${PLUGIN_INSTALL_DIR})
- install( FILES kcm_kdev_lcovsettings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-
-endif( NOT KDE_VERSION VERSION_LESS "4.2.2" )
-
-########### install files ###############
-
-install( FILES kdevcoverage.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevcoverage.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcoverage )
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.h (nonexistent)
@@ -1,208 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REPORTWIDGET_H
-#define VERITAS_COVERAGE_REPORTWIDGET_H
-
-#include <QPointer>
-#include <QtGui/QWidget>
-#include <KUrl>
-#include <interfaces/iuicontroller.h>
-#include "coverageexport.h"
-
-class QAbstractItemView;
-class QItemSelection;
-class QLineEdit;
-class QModelIndex;
-class QStandardItem;
-class QTableView;
-class KJob;
-class KUrlNavigator;
-
-namespace Ui
-{
-class ReportWidget;
-}
-
-namespace Veritas
-{
-
-class AnnotationManager;
-class CoveredFile;
-class DrillDownView;
-class LcovInfoParser;
-class ReportDirData;
-class ReportModel;
-class ReportProxyModel;
-class ReportViewFactory;
-class CovOutputDelegate;
-
-/*! Coverage report main widget, as shown in the toolview
- * @unittest Veritas::ReportWidgetTest */
-class VERITAS_COVERAGE_EXPORT ReportWidget : public QWidget
-{
-Q_OBJECT
-public:
- explicit ReportWidget(QWidget* parent = 0);
- virtual ~ReportWidget();
-
- /*! initialize child widgets and connects signals.
- called by ReportViewFactory after construction */
- void init();
-
-private Q_SLOTS:
- void dispatchSelectionSignal(const QItemSelection&, const QItemSelection&);
- void dispatchDoubleClickedSignal(const QModelIndex&);
-
- void setDirViewState();
- void setFileViewState();
- void updateTableView();
- void updateColumns();
-
- /*!
- * Starts or stops the lcov job depending on whether there is a job already
- * running or not.
- */
- void startOrStopLcovJob();
-
- /*!
- * Restores the widgets changed when the lcov job was started.
- */
- void updateStateWhenLcovJobFinishes();
-
- /*!
- * Starts or stops the remove gcda files job depending on whether there is a
- * job already running or not.
- */
- void startOrStopRemoveGcdaFilesJob();
-
- /*!
- * Restores the widgets changed when the remove gcda files job was started.
- */
- void updateStateWhenRemoveGcdaFilesJobFinishes();
-
-private:
-
- /*!
- * Starts the lcov job.
- */
- void startLcovJob();
-
- /*!
- * Starts the remove gcda files job.
- */
- void startRemoveGcdaFilesJob();
-
- /*!
- * Sets the icon and texts of lcov job button to start the job.
- */
- void setStartLcovJobButton();
-
- /*!
- * Sets the icon and texts of lcov job button to stop the job.
- */
- void setStopLcovJobButton();
-
- /*!
- * Sets the icon and texts of remove gcda files job button to start the job.
- */
- void setStartRemoveGcdaFilesJobButton();
-
- /*!
- * Sets the icon and texts of remove gcda files job button to stop the job.
- */
- void setStopRemoveGcdaFilesJobButton();
-
- /*!
- * Returns the ReportDirData used in the item identified by the index.
- * If no ReportDirData exists for that index (that is, if the index does
- * not identify a ReportDirItem), a null pointer is returned.
- *
- * @param index The index in the model of the table.
- * @return The data if it exists, a null pointer otherwise.
- */
- const ReportDirData* getReportDirDataFromProxyIndex(const QModelIndex&) const;
-
- /*!
- * Updates the coverage statistics labels with the specified data.
- * Coverage percentage is shown with 1 decimal. SLOC and instrumented lines
- * are plain integers.
- *
- * @param data The data to set.
- */
- void setCoverageStatistics(const ReportDirData&);
-
- /*!
- * Updates the coverage statistics labels for the selection change.
- * The newly selected directories data is added to the statistics, and the
- * deselected directories data is removed from them. File items are
- * ignored. If there is no directory, the statistics aren't modified.
- *
- * @param selected The newly selected items.
- * @param deselected The deselected items.
- * @see setCoverageStatistics(const ReportDirData&)
- */
- void setCoverageStatistics(const QItemSelection&, const QItemSelection&);
-
- /*!
- * Updates the coverage statistics labels for the specified index.
- * The statistics are set to the data of the directory identified by the
- * index. If it is not a directory, the statistics aren't modified.
- *
- * @param index The index of the item.
- * @see setCoverageStatistics(const ReportDirData&)
- */
- void setCoverageStatistics(const QModelIndex&);
-
- /*! open source file in editor */
- void jumpToSource(const QItemSelection&, const QItemSelection&);
- void jumpToSource(const QModelIndex&);
-
- /*! fetch the item corresponding to a view index. returns 0 on failure */
- QStandardItem* getItemFromProxyIndex(const QModelIndex&) const;
- DrillDownView* table() const;
- QLineEdit* filterBox() const; //krazy:exclude=qclasses
-
- /*! totally reset the widget */
- void reset_();
-
-protected:
- void resizeEvent(QResizeEvent* event);
- bool eventFilter(QObject* obj, QEvent* event);
-
-private:
- friend class ReportViewFactory;
- enum State { DirView, FileView } m_state;
- AnnotationManager* m_manager;
- ReportProxyModel* m_proxy;
- ReportModel* m_model;
- QTimer* m_timer;
- int m_timerTicks;
- QString m_oldDirFilter;
- KUrlNavigator* m_targetDirectory; // lets the user select a directory to run coverage on
- CovOutputDelegate* m_delegate;
- Ui::ReportWidget* m_ui;
- QPointer<KJob> m_lcovJob;
- QPointer<KJob> m_removeGcdaFilesJob;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_REPORTWIDGET_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp (nonexistent)
@@ -1,135 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "lcovinfoparser.h"
-#include <QFile>
-#include <QTextStream>
-#include <QStringList>
-#include <KDebug>
-#include "coveredfile.h"
-
-
-using Veritas::LcovInfoParser;
-using Veritas::CoveredFile;
-
-LcovInfoParser::LcovInfoParser(QObject* parent) : QObject(parent), m_current(0)
-{}
-
-LcovInfoParser::~LcovInfoParser()
-{
- if (m_current) m_current->deleteLater();
- foreach(CoveredFile* f, m_files) {
- f->deleteLater();
- }
-}
-
-namespace
-{
-
-inline bool firstTwoCharsEqual(const char* one, char* two)
-{
- return !qstrncmp(one, two, 2);
-}
-
-}
-
-void LcovInfoParser::parseLines(const QStringList& lines)
-{
- foreach(const QString& l, lines) parseLine(l);
-}
-
-void LcovInfoParser::parseLine(const QString& line)
-{
- // # SF:<absolute path to the source file>
-// # FN:<line number of function start>,<function name> for each function
-// # DA:<line number>,<execution count> for each instrumented line
-// # LH:<number of lines with an execution count> greater than 0
-// # LF:<number of instrumented lines>
-
-// SF:/usr/include/QtCore/qstringlist.h
-// FN:69,_ZN11QStringListD1Ev
-// FN:73,_ZN11QStringListC1ERKS_
-// FN:69,_ZN11QStringListaSERKS_
-// FN:85,_ZNK11QStringListplERKS_
-// FN:72,_ZN11QStringListC1ERK7QString
-// DA:69,36
-// DA:71,113
-// DA:72,88
-// DA:73,90
-// DA:74,0
-// DA:85,0
-// DA:86,0
-// DA:88,24
-// DA:90,0
-// LF:9
-// LH:5
-// end_of_record
-
- if (line.count() < 3) return;
- tmp_firstChar = line[0].toAscii();
- tmp_secondChar = line[1].toAscii();
- switch(tmp_firstChar) {
- case 'D': {
- if (tmp_secondChar != 'A') break;
- // DA:<line number>,<execution count> for each instrumented line
- Q_ASSERT(m_current);
- //l = line.split(":");
- tmp_f = line.mid(3, -1);
- tmp_s = tmp_f.split(',');
- int lineNumber = tmp_s.value(0).toInt();
- int callCount = tmp_s.value(1).toInt();
- m_current->setCallCount(lineNumber, callCount);
- break;
- } case 'F': { break;
- } case 'S': {
- if (tmp_secondChar != 'F') break;
- // SF:<absolute path to the source file>
- Q_ASSERT(m_current == 0);
- m_current = new CoveredFile;
- m_current->setUrl(KUrl(line.split(':').value(1)));
- break;
- } case 'L': {
- /*if (tmp_secondChar == 'F') {
- // # LF:<number of instrumented lines>
- Q_ASSERT(m_current);
- m_current->setSloc(line.split(":").value(1).toInt());
- } else if (tmp_secondChar == 'H') {
- // # LH:<number of lines with an execution count> greater than 0
- Q_ASSERT(m_current);
- m_current->setInstrumented(line.split(":").value(1).toInt());
- }*/
- break;
- } case 'e': {
- if (line.startsWith(QLatin1String("end_of_record"))) {
- Q_ASSERT(m_current);
- m_files << m_current;
- emit parsedCoverageData(m_files.last());
- m_current = 0;
- }
- break;
- } default: {}}
-}
-
-QList<CoveredFile*> LcovInfoParser::fto_coveredFiles()
-{
- return m_files;
-}
-
-#include "lcovinfoparser.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp (nonexistent)
@@ -1,71 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "removegcdafilesjobprogress.h"
-
-#include <KLocalizedString>
-
-using Veritas::RemoveGcdaFilesJobProgress;
-
-RemoveGcdaFilesJobProgress::RemoveGcdaFilesJobProgress(QObject* parent /*= 0*/):
- QObject(parent),
- m_numberOfFilesFound(0), m_numberOfFilesRemoved(0)
-{
-}
-
-QString RemoveGcdaFilesJobProgress::statusName() const
-{
- return i18nc("@info:progress", "Removing coverage data");
-}
-
-void RemoveGcdaFilesJobProgress::start()
-{
- emit showMessage(this, i18nc("@info:progress", "Scanning for .gcda files"));
- emit showProgress(this, 0, 1, 0);
-}
-
-void RemoveGcdaFilesJobProgress::setNumberOfFilesFound(int numberOfFilesFound)
-{
- Q_ASSERT(numberOfFilesFound >= 0);
-
- m_numberOfFilesFound = numberOfFilesFound;
-
- emit showMessage(this, i18nc("@info:progress", "Removing .gcda files"));
- emit showProgress(this, 0, 2, 1);
-}
-
-void RemoveGcdaFilesJobProgress::fileAboutToBeRemoved()
-{
- Q_ASSERT(m_numberOfFilesFound >= m_numberOfFilesRemoved + 1);
-
- //Half total progress was scanning for .gcda files
- int progress = 50;
- progress += 50 * m_numberOfFilesRemoved / (float)m_numberOfFilesFound;
-
- emit showProgress(this, 0, 100, progress);
-
- m_numberOfFilesRemoved++;
-}
-
-void RemoveGcdaFilesJobProgress::finish()
-{
- emit clearMessage(this);
- emit showProgress(this, 0, 1, 1);
- emit hideProgress(this);
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp (nonexistent)
@@ -1,63 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "reportproxymodel.h"
-#include "reportmodel.h"
-
-using Veritas::ReportModel;
-using Veritas::ReportProxyModel;
-
-ReportProxyModel::ReportProxyModel(QObject* parent)
- : QSortFilterProxyModel(parent), m_state(DirView)
-{
- setDynamicSortFilter(true);
- setSortRole(ReportModel::SortRole);
-}
-
-ReportProxyModel::~ReportProxyModel()
-{}
-
-
-bool ReportProxyModel::filterAcceptsColumn(int source_column, const QModelIndex & source_parent) const
-{
- Q_UNUSED(source_parent);
- switch(m_state) {
- case DirView: {
- return source_column == 0 || source_column == 1;
- }case FileView: {
- return true;
- } default: {
- Q_ASSERT_X(0, "filterAcceptsColumn", "Serious corruption, impossible m_state value.");
- return false;
- }}
-}
-
-void ReportProxyModel::setFileViewState()
-{
- m_state = ReportProxyModel::FileView;
-}
-
-void ReportProxyModel::setDirViewState()
-{
- m_state = ReportProxyModel::DirView;
-}
-
-
-#include "reportproxymodel.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.cpp (nonexistent)
@@ -1,104 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "buildpathselection.h"
-
-#include <KLocalizedString>
-#include <KUrlNavigator>
-
-#include <interfaces/iproject.h>
-#include <project/projectmodel.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-
-#include <veritas/projectselection.h>
-
-using Veritas::BuildPathSelection;
-using Veritas::ProjectSelection;
-
-class BuildPathProjectFilter: public ProjectSelection::IProjectFilter
-{
-public:
-
- BuildPathProjectFilter():
- IProjectFilter(i18nc("@info:whatsthis Appended to the end of another WhatsThis help",
- "<para>In this case, only projects with a build path set can be selected.</para>"))
- {
- }
-
- virtual bool canBeSelected(KDevelop::IProject* project)
- {
- if (!project->buildSystemManager() ||
- project->buildSystemManager()->buildDirectory(project->projectItem()).isEmpty()) {
- return false;
- }
-
- return true;
- }
-
-};
-
-BuildPathSelection::BuildPathSelection(KUrlNavigator* targetDirectory, QObject* parent /*= 0*/):
- QObject(parent)
-{
- m_projectSelection = new ProjectSelection(this, new BuildPathProjectFilter());
- m_projectSelection->setToolBarMode(KSelectAction::ComboBoxMode);
- connect(m_projectSelection, SIGNAL(projectSelected(KDevelop::IProject*)),
- this, SLOT(setBuildPathFromProject(KDevelop::IProject*)));
- connect(targetDirectory, SIGNAL(urlChanged(KUrl)),
- this, SLOT(setProjectFromBuildPath(KUrl)));
- connect(this, SIGNAL(buildPathToSet(KUrl)),
- targetDirectory, SLOT(setUrl(KUrl)));
-}
-
-QWidget* BuildPathSelection::requestProjectSelectionWidget(QWidget* parent)
-{
- return m_projectSelection->requestWidget(parent);
-}
-
-void BuildPathSelection::setBuildPathFromProject(KDevelop::IProject* project)
-{
- if (!project) {
- return;
- }
-
- Q_ASSERT(project->buildSystemManager());
- Q_ASSERT(!project->buildSystemManager()->buildDirectory(project->projectItem()).isEmpty());
-
- //KUrlNavigator::setUrl emits KUrlNavigator::urlChanged signal, which is connected to
- //setProjectFromBuildPath, so the project is set with itself. It does no
- //harm, but that superfluous call to setProjectFromBuildPath should be
- //avoided
- emit buildPathToSet(project->buildSystemManager()->buildDirectory(project->projectItem()));
-}
-
-void BuildPathSelection::setProjectFromBuildPath(const KUrl& url)
-{
- foreach (KDevelop::IProject* project, m_projectSelection->projects()) {
- if (project->buildSystemManager()) {
- KUrl buildDirectory = project->buildSystemManager()->buildDirectory(project->projectItem());
- if (buildDirectory.equals(url, KUrl::CompareWithoutTrailingSlash)) {
- m_projectSelection->selectProject(project);
- return;
- }
- }
- }
-
- m_projectSelection->selectProject(0);
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.h (nonexistent)
@@ -1,122 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_LCOVJOBPROGRESS_H
-#define VERITAS_COVERAGE_LCOVJOBPROGRESS_H
-
-#include <interfaces/istatus.h>
-
-#include "coverageexport.h"
-
-namespace KDevelop
-{
-class IStatus;
-}
-
-namespace Veritas
-{
-
-/**
- * Shows progress information about geninfo execution.
- * geninfo first scans the given directory looking for gcda files and then
- * generates a report for each gcda file found.
- * While geninfo is looking for gcda files no progress updates are given. Once
- * it finishes looking for them, it tells how many files were found and then
- * process them one for one.
- *
- * The progress is reported by this class in this way:
- * - 0: when geninfo starts and while it is scanning the directory.
- * - 50: when geninfo finishes scanning the directory.
- * - (50-100]: when geninfo is processing the files. The progress will be
- * updated proportionally to how many files are going to be processed and how
- * many files have already been processed.
- * - 100: when geninfo finishes, no matter why.
- *
- * Also, the status message will specify whether geninfo is scanning for files
- * or processing them already.
- */
-class VERITAS_COVERAGE_EXPORT LcovJobProgress: public QObject, public KDevelop::IStatus
-{
-Q_OBJECT
-Q_INTERFACES(KDevelop::IStatus)
-
-public:
-
- /**
- * Creates a new LcovJobProgress.
- *
- * @param parent The parent QObject.
- */
- explicit LcovJobProgress(QObject* parent = 0);
-
- /**
- * Destroys this LcovJobProgress.
- */
- virtual ~LcovJobProgress();
-
- //<KDevelop::IStatus>
-
- /**
- * The name of this status update.
- *
- * @return "Running geninfo"
- */
- virtual QString statusName() const;
-
-Q_SIGNALS:
-
- void clearMessage(KDevelop::IStatus* status);
- void showMessage(KDevelop::IStatus* status, const QString & message, int timeout = 0);
- void showErrorMessage(const QString & message, int timeout = 0);
- void hideProgress(KDevelop::IStatus* status);
- void showProgress(KDevelop::IStatus* status, int minimum, int maximum, int value);
-
- //</KDevelop::IStatus>
-
-public slots:
-
- /**
- * Reports that geninfo has been started.
- * No message will be given.
- */
- void start();
-
- /**
- * Parses the informative output of geninfo and updates the progress.
- *
- * @param lines The informative output received.
- */
- void parseLines(const QStringList &lines);
-
- /**
- * Reports that geninfo has finished, no matter why.
- * Clears the message and shows a 100% progress before hidding it.
- */
- void finish();
-
-private:
-
- int m_numberOfFilesFound;
- int m_numberOfFilesProcessed;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.h (nonexistent)
@@ -1,94 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Benjamin Meyer <ben@meyerhome.net> *
- * Copyright 2006 Alexander Dymo <adymo@kdevelop.org> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef VERITAS_COVERAGE_DRILLDOWNVIEW_H
-#define VERITAS_COVERAGE_DRILLDOWNVIEW_H
-
-#include <QtGui/QtGui>
-
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-/*! Coverage report table */
-class VERITAS_COVERAGE_EXPORT DrillDownView: public QTableView
-{
-Q_OBJECT
-
-public:
- explicit DrillDownView(QWidget *parent = 0);
- virtual ~DrillDownView();
- void resizeFileStateColumns();
-
- /*!
- * Shows the coverage data for directories.
- * The selection is cleared, and then set again to the directories selected
- * before sliding to the left (including the current index).
- */
- void slideLeft();
-
- /*!
- * Shows the coverage data for the files in the currently selected
- * directory.
- * The selection is cleared.
- */
- void slideRight(const QModelIndex&);
-
-Q_SIGNALS:
- void returnPressed(const QModelIndex &index);
- void rootIndexChanged(const QModelIndex &index);
- void completedSlideLeft();
- void completedSlideRight();
-
-public Q_SLOTS:
- void resizeDirStateColumns();
- void setRootIndex(const QModelIndex &index);
-
-protected:
- virtual void paintEvent(QPaintEvent * event);
- virtual void keyPressEvent(QKeyEvent *event);
- virtual void mousePressEvent(QMouseEvent* event);
-
-private Q_SLOTS:
- void slide(int x);
-
-private:
- bool isBusy();
- void animateSlide(int moveDirection);
- int maxWidth() const;
-
-private:
- QTimeLine animation;
- QPixmap oldView;
- QPixmap newView;
- int lastPosition;
-
- /*!
- * Stores the selection of directories to restore it when sliding left
- * again.
- */
- QItemSelection leftSelection;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_DRILLDOWNVIEW_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.ui (nonexistent)
@@ -1,170 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>LCovPrefsWidget</class>
- <widget class="QWidget" name="LCovPrefsWidget">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>427</width>
- <height>346</height>
- </rect>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_3">
- <item>
- <widget class="QGroupBox" name="pathsGroupBox">
- <property name="title">
- <string comment="@title:group">Paths</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QLabel" name="geninfoPathLabel">
- <property name="text">
- <string comment="@label:textbox">geninfo Executable:</string>
- </property>
- <property name="buddy">
- <cstring>kcfg_geninfoPath</cstring>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KUrlRequester" name="kcfg_geninfoPath">
- <property name="toolTip">
- <string comment="@info:tooltip">Select the geninfo executable to use for extracting visualization from coverage data</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="colorsGroupBox">
- <property name="whatsThis">
- <string comment="@info:whatsthis">&lt;para&gt;Configuration for coverage report colors.&lt;/para&gt;
-
-&lt;para&gt;In the directory view of the coverage report, each directory coverage percentage is represented using a color.&lt;/para&gt;
-
-&lt;para&gt;The color associated to each percentage is taken from a color range, made up of several stop points. Stop points represent a color at a specific percentage.&lt;/para&gt;
-
-&lt;para&gt;A color range has two different and independent modes: discrete and gradient. In discrete type, all percentage values between the previous stop point and the current one have the color of the current one. In gradient type, the values are interpolated between the previous stop point's color and the current stop point's color.&lt;/para&gt;</string>
- </property>
- <property name="title">
- <string comment="@title:group">Report colors</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_2" stretch="1,0,10">
- <item>
- <widget class="QFrame" name="colorRangeBarFrame">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>30</height>
- </size>
- </property>
- <property name="toolTip">
- <string comment="@info:tooltip">Current color range</string>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">Representation of the color range to be used in the coverage report colors.</string>
- </property>
- <property name="frameShape">
- <enum>QFrame::Box</enum>
- </property>
- <property name="frameShadow">
- <enum>QFrame::Plain</enum>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="typeLabel">
- <property name="text">
- <string comment="@label:listbox">Type:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KComboBox" name="modeComboBox">
- <property name="toolTip">
- <string comment="@info:tooltip">Color range type</string>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">Choose the type of color range to be used in the coverage report colors.</string>
- </property>
- <item>
- <property name="text">
- <string comment="@item:inlistbox Discrete color range type">Discrete</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string comment="@item:inlistbox Gradient color range type">Gradient</string>
- </property>
- </item>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QScrollArea" name="stopPointsScrollArea">
- <property name="frameShape">
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow">
- <enum>QFrame::Plain</enum>
- </property>
- <property name="widgetResizable">
- <bool>true</bool>
- </property>
- <widget class="QWidget" name="scrollAreaWidgetContents">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>387</width>
- <height>154</height>
- </rect>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout"/>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KUrlRequester</class>
- <extends>QFrame</extends>
- <header>kurlrequester.h</header>
- </customwidget>
- <customwidget>
- <class>KComboBox</class>
- <extends>QComboBox</extends>
- <header>kcombobox.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp (nonexistent)
@@ -1,58 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "covoutputdelegate.h"
-#include "covoutputmodel.h"
-#include <QtGui/QPainter>
-#include <QtCore/QModelIndex>
-
-using Veritas::CovOutputDelegate;
-
-CovOutputDelegate::CovOutputDelegate(QObject* parent)
- : QItemDelegate(parent),
- textBrush(KColorScheme::View, KColorScheme::NormalText),
- processBrush(KColorScheme::View, KColorScheme::PositiveText),
- warningBrush(KColorScheme::View, KColorScheme::NeutralText),
- errorBrush(KColorScheme::View, KColorScheme::NegativeText)
-{}
-
-CovOutputDelegate::~CovOutputDelegate()
-{}
-
-void CovOutputDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
- const QModelIndex& index) const
-{
- QStyleOptionViewItem opt = option;
- opt.palette.setBrush(QPalette::Text, textBrush.brush(option.palette));
- QString text = index.data().toString();
- if (text.startsWith(QLatin1String("Processing"))) {
- opt.palette.setBrush(QPalette::Text, processBrush.brush(option.palette));
- } else if (text.contains("source file is newer than graph file")) {
- opt.palette.setBrush(QPalette::Text, warningBrush.brush(option.palette));
- } else if (text.contains("WARNING:")) {
- opt.palette.setBrush(QPalette::Text, warningBrush.brush(option.palette));
- } else if (text.contains("ERROR:")) {
- opt.palette.setBrush(QPalette::Text, errorBrush.brush(option.palette));
- }
- QItemDelegate::paint(painter, opt, index);
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputdelegate.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfg (nonexistent)
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
- http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">
- <kcfgfile name="kdeveloprc"/>
- <group name="Code Coverage">
- <entry name="geninfoPath" key="geninfoPath" type="Url">
- <default>file:///usr/bin/geninfo</default>
- <label>Specifies which geninfo executable to use to generate coverage information</label>
- <whatsthis>The geninfo executable from the lcov toolset is needed to create a visualizable format from gcov code coverage data.
- </whatsthis>
- </entry>
- </group>
-</kcfg>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.cpp (nonexistent)
@@ -1,93 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "coverageplugin.h"
-#include "reportwidget.h"
-
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-
-#include <QAbstractItemView>
-#include <QDir>
-#include <KAction>
-#include <KAboutData>
-#include <KActionCollection>
-#include <KActionMenu>
-#include <KLocale>
-#include <KPluginFactory>
-#include <KPluginLoader>
-
-using KDevelop::ICore;
-using KDevelop::IUiController;
-
-using Veritas::CoveragePlugin;
-using Veritas::ReportViewFactory;
-using Veritas::ReportWidget;
-
-K_PLUGIN_FACTORY(CoveragePluginFactory, registerPlugin<CoveragePlugin>();)
-K_EXPORT_PLUGIN(CoveragePluginFactory(KAboutData("kdevcoverage","kdevcoverage", ki18n("Coverage Support"), "0.1", ki18n("Support for running coverage tools"), KAboutData::License_GPL)))
-
-//////////////////////////// CoveragePlugin ///////////////////////////////
-
-CoveragePlugin::CoveragePlugin(QObject* parent, const QVariantList&)
- : KDevelop::IPlugin( CoveragePluginFactory::componentData(), parent ),
- m_factory(new ReportViewFactory())
-{
- setXMLFile("kdevcoverage.rc");
- core()->uiController()->addToolView(i18n("Coverage"), m_factory);
-}
-
-CoveragePlugin::~CoveragePlugin()
-{
-}
-
-void CoveragePlugin::unload()
-{
- core()->uiController()->removeToolView( m_factory );
-}
-
-//////////////////////////// ReportViewFactory ///////////////////////////////
-
-ReportViewFactory::ReportViewFactory()
-{
-}
-
-ReportViewFactory::~ReportViewFactory()
-{
-}
-
-QWidget* ReportViewFactory::create(QWidget *parent)
-{
- ReportWidget* w = new ReportWidget(parent);
- w->init();
- return w;
-}
-
-Qt::DockWidgetArea ReportViewFactory::defaultPosition()
-{
- return Qt::RightDockWidgetArea;
-}
-
-QString ReportViewFactory::id() const
-{
- return "org.kdevelop.CoverageReport";
-}
-
-#include "coverageplugin.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.h (nonexistent)
@@ -1,51 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVANNOTATIONMODEL_H
-#define VERITAS_COVANNOTATIONMODEL_H
-
-#include <ktexteditor/annotationinterface.h>
-#include <QBrush>
-
-namespace Veritas {
-
-class CoveredFile;
-
-/*! Places annotations on text-views, which show the covered lines
- * and their callcount */
-class AnnotationModel : public KTextEditor::AnnotationModel
-{
- Q_OBJECT
- public:
- explicit AnnotationModel(Veritas::CoveredFile* file, QObject* parent=0);
- virtual ~AnnotationModel();
- virtual QVariant data(int line, Qt::ItemDataRole role) const;
- void update();
-
-private:
- Veritas::CoveredFile* m_file;
- QBrush m_notInstrumented;
- QBrush m_noCoverage;
- QBrush m_covered;
-
-};
-
-}
-
-#endif // VERITAS_COVANNOTATIONMODEL_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp (nonexistent)
@@ -1,88 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "gradientcolorrange.h"
-
-using Veritas::GradientColorRange;
-using Veritas::StopPoints;
-using Veritas::StopPoint;
-
-GradientColorRange::GradientColorRange()
-{
- mStopPoints.append(StopPoint(0, QColor(Qt::black)));
- mStopPoints.append(StopPoint(1, QColor(Qt::white)));
-}
-
-GradientColorRange::~GradientColorRange()
-{
-}
-
-QColor GradientColorRange::colorAt(double position) const
-{
- Q_ASSERT(position >= 0 && position <= 1);
-
- for (int i=0; i<stopPoints().size(); i++) {
- if (position == stopPoints()[i].first) {
- return stopPoints()[i].second;
- } else if (position < stopPoints()[i+1].first) {
- return interpolateColor(stopPoints()[i], stopPoints()[i+1],
- position);
- }
- }
-
- return mStopPoints.last().second;
-}
-
-StopPoints GradientColorRange::stopPoints() const
-{
- return mStopPoints;
-}
-
-void GradientColorRange::setStopPoints(const StopPoints& stopPoints)
-{
- Q_ASSERT(stopPoints.size() >= 2);
- Q_ASSERT(stopPoints.first().first == 0);
- Q_ASSERT(stopPoints.last().first == 1);
-
- mStopPoints = stopPoints;
-}
-
-QColor GradientColorRange::interpolateColor(const StopPoint& begin,
- const StopPoint& end,
- double position) const
-{
- double beginPosition = begin.first;
- double endPosition = end.first;
- double width = endPosition - beginPosition;
-
- double relativePosition = (position - beginPosition) / width;
-
- QColor beginColor = begin.second;
- QColor endColor = end.second;
-
- QColor interpolatedColor;
- interpolatedColor.setRed(qRound(beginColor.red() +
- (endColor.red() - beginColor.red()) * relativePosition));
- interpolatedColor.setGreen(qRound(beginColor.green() +
- (endColor.green() - beginColor.green()) * relativePosition));
- interpolatedColor.setBlue(qRound(beginColor.blue() +
- (endColor.blue() - beginColor.blue()) * relativePosition));
-
- return interpolatedColor;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp (nonexistent)
@@ -1,87 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "covoutputmodel.h"
-
-#include <QModelIndex>
-#include <KGlobalSettings>
-#include <interfaces/icore.h>
-
-using Veritas::CovOutputModel;
-
-CovOutputModel::CovOutputModel(QObject *parent)
- : QStandardItemModel(parent)
-{}
-
-CovOutputModel::~CovOutputModel()
-{}
-
-QModelIndex CovOutputModel::nextHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-QModelIndex CovOutputModel::previousHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-
-QVariant CovOutputModel::data(const QModelIndex& index, int role) const
-{
- if (role != Qt::FontRole) {
- return QStandardItemModel::data(index, role);
- } else {
- return KGlobalSettings::fixedFont();
- }
-}
-
-void CovOutputModel::activate(const QModelIndex &idx)
-{
- Q_UNUSED(idx);
-}
-
-void CovOutputModel::appendOutputs(const QStringList &lines)
-{
- Q_UNUSED(lines);
- // stdout gets the lcov output, which contains the useful stuff
- // so do nothing here. stderr gets status messages
-}
-
-void CovOutputModel::appendErrors(const QStringList &lines)
-{
- foreach(const QString& line, lines) {
- appendRow(new QStandardItem(line));
- }
-}
-
-void CovOutputModel::slotCompleted()
-{
-}
-
-void CovOutputModel::slotFailed()
-{
- appendRow(new QStandardItem("Failed"));
-}
-
-#include "covoutputmodel.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.cpp (nonexistent)
@@ -1,484 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "reportwidget.h"
-#include "annotationmanager.h"
-#include "buildpathselection.h"
-#include "coveredfile.h"
-#include "drilldownview.h"
-#include "reportmodel.h"
-#include "reportproxymodel.h"
-#include "lcovinfoparser.h"
-#include "lcovjob.h"
-#include "covoutputdelegate.h"
-#include "removegcdafilesjob.h"
-#include "ui_reportwidget.h"
-
-#include <QTimer>
-#include <KLocale>
-#include <KComboBox>
-#include <KIcon>
-#include <KMessageBox>
-#include <KProcess>
-#include <KUrlNavigator>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocument.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/iuicontroller.h>
-#include <interfaces/iprojectcontroller.h>
-#include <interfaces/iproject.h>
-#include <interfaces/iruncontroller.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-
-using KDevelop::ICore;
-using KDevelop::IDocument;
-using KDevelop::IDocumentController;
-using KDevelop::IProject;
-using KDevelop::IProjectController;
-using KDevelop::IBuildSystemManager;
-
-using Veritas::AnnotationManager;
-using Veritas::BuildPathSelection;
-using Veritas::CoveredFile;
-using Veritas::CovOutputDelegate;
-using Veritas::DrillDownView;
-using Veritas::LcovInfoParser;
-using Veritas::LcovJob;
-using Veritas::RemoveGcdaFilesJob;
-using Veritas::ReportWidget;
-using Veritas::ReportDirData;
-using Veritas::ReportModel;
-using Veritas::ReportViewFactory;
-
-//////////////////////////////// ReportWidget ///////////////////////////////
-
-void ReportWidget::resizeEvent(QResizeEvent* event)
-{
- Q_UNUSED(event);
- installEventFilter(this);
- switch(m_state) {
- case DirView: { table()->resizeDirStateColumns(); break; }
- case FileView: { table()->resizeFileStateColumns(); break; }
- default: { Q_ASSERT(0); }
- }
- removeEventFilter(this);
-}
-
-bool ReportWidget::eventFilter(QObject* obj, QEvent* event)
-{
- if (event->type()==QEvent::Resize) {
- return true;
- }
- return QWidget::eventFilter(obj, event);
-}
-
-DrillDownView* ReportWidget::table() const
-{
- return m_ui->table;
-}
-
-void ReportWidget::init()
-{
- m_ui = new Ui::ReportWidget();
- m_ui->setupUi(this);
-
- //KUrlNavigator can't be set using a placeholder in Qt Designer as there is
- //no KUrlNavigator(QWidget*) constructor
- int startButtonIndex = m_ui->buildPathSelectionLayout->indexOf(m_ui->lcovJobButton);
- m_targetDirectory = new KUrlNavigator(0, KUrl(QDir::homePath()), this);
- m_ui->buildPathSelectionLayout->insertWidget(startButtonIndex, m_targetDirectory);
-
- BuildPathSelection* buildPathSelection = new BuildPathSelection(m_targetDirectory, this);
-
- //ProjectSelection widget can't be set using Qt Designer, as it is got from
- //a method of a non widget class
- int getFromProjectTextLabelIndex = m_ui->projectSelectionLayout->indexOf(m_ui->getFromProjectTextLabel);
- QWidget* projectSelectionWidget = buildPathSelection->requestProjectSelectionWidget(m_ui->buildPathFrame);
- m_ui->projectSelectionLayout->insertWidget(getFromProjectTextLabelIndex + 1, projectSelectionWidget);
-
- if (qobject_cast<KComboBox*>(projectSelectionWidget) != 0) {
- static_cast<KComboBox*>(projectSelectionWidget)->setSizeAdjustPolicy(QComboBox::AdjustToContents);
- }
-
- setStartLcovJobButton();
- connect(m_ui->lcovJobButton, SIGNAL(clicked(bool)), SLOT(startOrStopLcovJob()));
-
- setStartRemoveGcdaFilesJobButton();
- connect(m_ui->removeGcdaFilesJobButton, SIGNAL(clicked(bool)), SLOT(startOrStopRemoveGcdaFilesJob()));
-
- connect(table(), SIGNAL(doubleClicked(QModelIndex)),
- SLOT(dispatchDoubleClickedSignal(QModelIndex)));
-
- connect(table(), SIGNAL(completedSlideLeft()), SLOT(setDirViewState()));
- connect(table(), SIGNAL(completedSlideRight()), SLOT(setFileViewState()));
-
- m_timer->setInterval(50);
- m_timer->setSingleShot(true);
- connect(m_timer, SIGNAL(timeout()), this, SLOT(updateTableView()));
-}
-
-void ReportWidget::updateTableView()
-{
- if (m_timerTicks < 10) {
- table()->viewport()->update();
- m_timerTicks += 1;
- m_timer->start();
- }
-}
-
-ReportWidget::ReportWidget(QWidget* parent) :
- QWidget(parent),
- m_state(ReportWidget::DirView),
- m_manager(0),
- m_proxy(0),
- m_model(0),
- m_timer(new QTimer(this)),
- m_targetDirectory(0),
- m_delegate(new CovOutputDelegate(this)),
- m_ui(0)
-{
- setObjectName("Coverage Report");
- setWindowIcon(SmallIcon("system-file-manager"));
-}
-
-#define ILLEGAL_STATE \
- Q_ASSERT_X(0, "ReportWidget::signalDispatch", \
- "Serious corruption, impossible m_state value.")
-
-void ReportWidget::dispatchSelectionSignal(const QItemSelection& selected, const QItemSelection& deselected)
-{
- switch(m_state) {
- case DirView: {
- setCoverageStatistics(selected, deselected); break;
- } case FileView: {
- /*jumpToSource(selected, deselected); */break;
- } default: {
- ILLEGAL_STATE;
- }}
-}
-
-void ReportWidget::dispatchDoubleClickedSignal(const QModelIndex& index)
-{
- switch(m_state) {
- case DirView: {
- table()->slideRight(index); break;
- } case FileView: {
- jumpToSource(index); break;
- } default: {
- ILLEGAL_STATE;
- }}
-}
-
-void ReportWidget::jumpToSource(const QItemSelection& selected, const QItemSelection& deselected)
-{
- Q_UNUSED(selected);
- Q_UNUSED(deselected);
- // TODO
-}
-
-void ReportWidget::jumpToSource(const QModelIndex& index)
-{
- QStandardItem* item = getItemFromProxyIndex(index);
- if (!item || item->type() != ReportModel::File ) return;
- ReportFileItem* file = static_cast<ReportFileItem*>(item);
- Q_ASSERT(file);
-
- IDocumentController* dc = ICore::self()->documentController();
- kDebug() << "Open doc with coverage annotations " << file->url();
- KTextEditor::Cursor cursor;
- IDocument* doc;
- doc = dc->openDocument(file->url(), cursor);
- if (!doc || !doc->isTextDocument()) return;
- Q_ASSERT(m_manager);
- m_manager->watch(doc);
- dc->activateDocument(doc);
-}
-
-void ReportWidget::reset_()
-{
- m_proxy->invalidate();
- filterBox()->clear();
- table()->viewport()->update();
- m_timerTicks = 0;
- m_timer->start(); // TODO figure out the correct signal instead of this kludge
-}
-
-void ReportWidget::setDirViewState()
-{
- m_state = ReportWidget::DirView;
- m_proxy->setDirViewState();
- reset_();
- table()->resizeDirStateColumns();
- filterBox()->setReadOnly(false);
- filterBox()->setText(m_oldDirFilter);
-
- //When the view slides to the left, the previously selected directories are
- //selected again. However, until the slide is completed we are in File
- //state, so the statistics aren't updated.
- m_ui->sloc->setText("0");
- m_ui->nrofCoveredLines->setText("0");
- setCoverageStatistics(table()->selectionModel()->selection(), QItemSelection());
-}
-
-QLineEdit* ReportWidget::filterBox() const //krazy:exclude=qclasses
-{
- return m_ui->filterBox;
-}
-
-void ReportWidget::setFileViewState()
-{
- m_state = ReportWidget::FileView;
- m_proxy->setFileViewState();
- m_oldDirFilter = filterBox()->text();
- reset_();
- table()->resizeFileStateColumns();
- filterBox()->setReadOnly(true);
-
- //Set the statistics for the current directory
- setCoverageStatistics(table()->rootIndex());
-}
-
-ReportWidget::~ReportWidget()
-{
- delete m_ui;
-}
-
-QStandardItem* ReportWidget::getItemFromProxyIndex(const QModelIndex& index) const
-{
- if (!index.isValid()) {
- kDebug() << "Invalid index";
- return 0;
- }
- QModelIndex sourceIndex = m_proxy->mapToSource(index);
- QStandardItem* item = m_model->itemFromIndex(sourceIndex);
- Q_ASSERT(item);
- return item;
-}
-
-const ReportDirData* ReportWidget::getReportDirDataFromProxyIndex(const QModelIndex& index) const
-{
- QStandardItem* item = getItemFromProxyIndex(index);
- if (!item || item->type() != ReportModel::Dir) return 0;
-
- return &static_cast<ReportDirItem*>(item)->reportDirData();
-}
-
-void ReportWidget::setCoverageStatistics(const ReportDirData& data)
-{
- //QLocale used as QString::number does not honor the user's locale setting
- m_ui->coverageRatio->setText(QLocale().toString(data.coverageRatio(), 'f', 1) + " %");
- m_ui->coverageRatio->update();
- m_ui->sloc->setText(QString::number(data.sloc()));
- m_ui->sloc->update();
- m_ui->nrofCoveredLines->setText(QString::number(data.nrofCoveredLines()));
- m_ui->nrofCoveredLines->update();
-}
-
-void ReportWidget::setCoverageStatistics(const QModelIndex& index)
-{
- const ReportDirData* data = getReportDirDataFromProxyIndex(index);
- if (!data) {
- return;
- }
-
- setCoverageStatistics(*data);
-}
-
-void ReportWidget::setCoverageStatistics(const QItemSelection& selected, const QItemSelection& deselected)
-{
- ReportDirData fullData;
- if (m_ui->sloc->text() != "-" && m_ui->nrofCoveredLines->text() != "-") {
- fullData.setSloc(m_ui->sloc->text().toInt());
- fullData.setNrofCoveredLines(m_ui->nrofCoveredLines->text().toInt());
- }
-
- bool statisticsChanged = false;
-
- foreach (const QModelIndex& index, selected.indexes()) {
- const ReportDirData* data = getReportDirDataFromProxyIndex(index);
- if (data) {
- statisticsChanged = true;
- fullData.setSloc(fullData.sloc() + data->sloc());
- fullData.setNrofCoveredLines(fullData.nrofCoveredLines() + data->nrofCoveredLines());
- }
- }
-
- foreach (const QModelIndex& index, deselected.indexes()) {
- const ReportDirData* data = getReportDirDataFromProxyIndex(index);
- if (data) {
- statisticsChanged = true;
- fullData.setSloc(fullData.sloc() - data->sloc());
- fullData.setNrofCoveredLines(fullData.nrofCoveredLines() - data->nrofCoveredLines());
- }
- }
-
- if (statisticsChanged) {
- setCoverageStatistics(fullData);
- }
-}
-
-void ReportWidget::startOrStopLcovJob()
-{
- if (!m_lcovJob) {
- startLcovJob();
- } else {
- m_lcovJob->kill(KJob::EmitResult);
- }
-}
-
-void ReportWidget::startLcovJob()
-{
- Q_ASSERT(m_delegate); Q_ASSERT(m_targetDirectory);
-
- if (m_state == FileView) {
- filterBox()->setReadOnly(false);
- filterBox()->setText(m_oldDirFilter);
- } else {
- m_oldDirFilter = filterBox()->text();
- }
-
- m_ui->coverageRatio->setText("-");
- m_ui->nrofCoveredLines->setText("-");
- m_ui->sloc->setText("-");
-
- m_state = DirView;
-
- if (m_model) delete m_model;
- if (m_manager) delete m_manager;
- if (m_proxy) delete m_proxy;
-
- m_model = new ReportModel(this);
- m_model->setRootDirectory( m_targetDirectory->url() );
- m_manager = new AnnotationManager(this);
- m_proxy = new ReportProxyModel(this);
- table()->setModel(m_proxy);
- m_proxy->setSourceModel(m_model);
- m_proxy->setFilterWildcard(m_oldDirFilter);
-
- //Since Qt 4.1 (or maybe 4.0, but not documented), setting the model
- //replaces the previous selection model, so it must be connected again
- //http://doc.trolltech.com/4.1/qabstractitemview.html#setModel
- connect(table()->selectionModel(),
- SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- SLOT(dispatchSelectionSignal(QItemSelection,QItemSelection)));
-
- setStopLcovJobButton();
- m_ui->removeGcdaFilesJobButton->setEnabled(false);
-
- LcovJob* job = new LcovJob(m_targetDirectory->url(), m_delegate);
- LcovInfoParser* parser = new LcovInfoParser(job);
-
- connect(parser, SIGNAL(parsedCoverageData(CoveredFile*)), m_model, SLOT(addCoverageData(CoveredFile*)));
- connect(parser, SIGNAL(parsedCoverageData(CoveredFile*)), m_manager, SLOT(addCoverageData(CoveredFile*)));
- connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(updateColumns()));
- connect(filterBox(), SIGNAL(textChanged(QString)), m_proxy, SLOT(setFilterWildcard(QString)));
-
- job->setDelegate(m_delegate);
- job->setProcess(new KProcess);
- job->setParser(parser);
-
- connect(job, SIGNAL(finished(KJob*)), SLOT(updateStateWhenLcovJobFinishes()));
-
- m_lcovJob = job;
-
- ICore::self()->runController()->registerJob(job);
-}
-
-void ReportWidget::updateStateWhenLcovJobFinishes()
-{
- setStartLcovJobButton();
- m_ui->removeGcdaFilesJobButton->setEnabled(true);
-}
-
-void ReportWidget::setStartLcovJobButton()
-{
- m_ui->lcovJobButton->setToolTip(i18nc("@info:tooltip", "Start coverage analysis"));
- m_ui->lcovJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Start coverage analysis in the specified path.</para>\n"
-"<para>The directory and, recursively, its subdirectories are scanned for .gcda files.</para>"));
- m_ui->lcovJobButton->setIcon(KIcon("arrow-right"));
-}
-
-void ReportWidget::setStopLcovJobButton()
-{
- m_ui->lcovJobButton->setToolTip(i18nc("@info:tooltip", "Stop coverage analysis"));
- m_ui->lcovJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Stop coverage analysis killing <command>geninfo</command> process.</para>"));
- m_ui->lcovJobButton->setIcon(KIcon("process-stop"));
-}
-
-void ReportWidget::startOrStopRemoveGcdaFilesJob()
-{
- if (!m_removeGcdaFilesJob) {
- if (KMessageBox::warningContinueCancel(this, i18nc("@info", "Remove all the .gcda files in <filename>%1</filename> directory and, recursively, in its subdirectories?", m_targetDirectory->url().toLocalFile()),
- i18nc("@title:window", "Remove .gcda files")) == KMessageBox::Continue) {
- startRemoveGcdaFilesJob();
- }
- } else {
- m_removeGcdaFilesJob->kill(KJob::EmitResult);
- }
-}
-
-void ReportWidget::startRemoveGcdaFilesJob()
-{
- Q_ASSERT(m_targetDirectory);
-
- setStopRemoveGcdaFilesJobButton();
- m_ui->lcovJobButton->setEnabled(false);
-
- RemoveGcdaFilesJob* job = new RemoveGcdaFilesJob(m_targetDirectory->url(), this);
- connect(job, SIGNAL(finished(KJob*)), SLOT(updateStateWhenRemoveGcdaFilesJobFinishes()));
-
- m_removeGcdaFilesJob = job;
-
- ICore::self()->runController()->registerJob(job);
-}
-
-void ReportWidget::updateStateWhenRemoveGcdaFilesJobFinishes()
-{
- setStartRemoveGcdaFilesJobButton();
- m_ui->lcovJobButton->setEnabled(true);
-}
-
-void ReportWidget::setStartRemoveGcdaFilesJobButton()
-{
- m_ui->removeGcdaFilesJobButton->setToolTip(i18nc("@info:tooltip", "Remove coverage data"));
- m_ui->removeGcdaFilesJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Remove coverage data from the specified path.</para>\n"
-"<para>The .gcda files are removed in the given directory and, recursively, its subdirectories.</para>"));
- m_ui->removeGcdaFilesJobButton->setIcon(KIcon("edit-delete"));
-}
-
-void ReportWidget::setStopRemoveGcdaFilesJobButton()
-{
- m_ui->removeGcdaFilesJobButton->setToolTip(i18nc("@info:tooltip", "Stop removing coverage data"));
- m_ui->removeGcdaFilesJobButton->setWhatsThis(i18nc("@info:whatsthis", "<para>Stop removing coverage data from the specified path.</para>"));
- m_ui->removeGcdaFilesJobButton->setIcon(KIcon("process-stop"));
-}
-
-void ReportWidget::updateColumns()
-{
- switch(m_state) {
- case DirView: { table()->resizeDirStateColumns(); break; }
- case FileView: { table()->resizeFileStateColumns(); break; }
- default: { Q_ASSERT(0); }
- }
-}
-
-#include "reportwidget.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h (nonexistent)
@@ -1,121 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOB_H
-#define VERITAS_COVERAGE_REMOVEGCDAFILESJOB_H
-
-#include <QFileInfo>
-#include <QFutureWatcher>
-
-#include <KJob>
-#include <KUrl>
-
-#include "coverageexport.h"
-
-class QDir;
-
-namespace Veritas {
-class RemoveGcdaFilesJobProgress;
-}
-
-namespace Veritas {
-
-/**
- * Job to remove the .gcda files from the given directory and, recursively, its
- * subdirectories.
- * The job is a killable job, and it removes the files in an auxiliar thread.
- */
-class VERITAS_COVERAGE_EXPORT RemoveGcdaFilesJob: public KJob {
-Q_OBJECT
-
-public:
-
- /**
- * Creates a new RemoveGcdaFilesJob for the given path.
- *
- * @param rootPath The root path to remove the .gcda files from.
- * @param parent The parent object.
- */
- explicit RemoveGcdaFilesJob(const KUrl& rootPath, QObject* parent = 0);
-
- /**
- * Starts the job.
- * It runs a new thread that does all the work.
- */
- virtual void start();
-
-protected:
-
- /**
- * Kills the job.
- * The job waits until the auxiliar thread has finished.
- *
- * @return True.
- */
- virtual bool doKill();
-
-private Q_SLOTS:
-
- /**
- * Emits the result for this job.
- */
- void jobDone();
-
-private:
-
- /**
- * The root path to remove the .gcda files from it and its subdirectories.
- */
- KUrl mRootPath;
-
- /**
- * True if kill() was called.
- */
- bool mKillRequested;
-
- /**
- * Watches the execution of the auxiliar thread to know if it has finished.
- */
- QFutureWatcher<void>* mDoWorkWatcher;
-
- /**
- * The status updater for this job.
- */
- RemoveGcdaFilesJobProgress* mRemoveGcdaFilesJobProgress;
-
- /**
- * Finds and removes the .gcda files in the root path and its
- * subdirectories.
- */
- void doWork() const;
-
- /**
- * Returns a list with the .gcda files in the given directory and its
- * subdirectories.
- *
- * @param directory The directory to find its .gcda files.
- * @return A list with the .gcda files.
- */
- QFileInfoList findGcdaFilesIn(const QDir& directory) const;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovconfig.kcfgc (nonexistent)
@@ -1,8 +0,0 @@
-File=lcovconfig.kcfg
-ClassName=LCovSettings
-Inherits=LCovSettingsBase
-Singleton=true
-IncludeFiles=\"lcovsettingsbase.h\"
-UseEnumTypes=true
-SetUserTexts=true
-ItemAccessors=true
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.h (nonexistent)
@@ -1,171 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REPORTMODEL_H
-#define VERITAS_COVERAGE_REPORTMODEL_H
-
-#include <QtCore/QList>
-#include <QtGui/QStandardItem>
-#include <QtGui/QStandardItemModel>
-#include <QSet>
-#include <QHash>
-#include <KUrl>
-
-#include "coverageexport.h"
-#include "colorrange.h"
-
-namespace Veritas
-{
-
-class CoveredFile;
-class ReportDirData;
-class ReportDirItem;
-class ReportFileItem;
-class ReportValueItem;
-
-/*! Main model for the coverage report */
-class VERITAS_COVERAGE_EXPORT ReportModel : public QStandardItemModel
-{
-Q_OBJECT
-public:
- explicit ReportModel(QObject* parent=0);
- virtual ~ReportModel();
- void setRootDirectory(const KUrl& root);
-
- QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const;
- enum
- {
- File = QStandardItem::UserType + 1,
- Dir = QStandardItem::UserType + 2,
- Value = QStandardItem::UserType + 3
- };
- enum { SortRole = Qt::UserRole + 1 };
-
-public Q_SLOTS:
- void addCoverageData(CoveredFile*);
-
-private:
- QList<QStandardItem*> createFileRow(CoveredFile*);
- void appendDir(const QString& dir);
- void updateColoredCoverageColumn(ReportDirItem* dir);
-
- /**
- * Returns the brush with the color for the given coverage percent.
- *
- * @param percent The coverage percent.
- * @return The brush.
- */
- QBrush brushForCoverage(double percent);
-
-private:
- KUrl m_root;
- QHash<KUrl, ReportFileItem*> m_files;
- QMap<QString, ReportDirItem*> m_dirs;
-
- /**
- * The color range used to associate colors with coverage percent values.
- */
- ColorRange m_colorRange;
-};
-
-// TODO merge this with the CoveredFile class, it is totally redundant to have both waste resources
-class VERITAS_COVERAGE_EXPORT ReportFileItem : public QStandardItem
-{
-public:
- explicit ReportFileItem(const KUrl& url);
- virtual ~ReportFileItem();
- virtual int type() const;
- KUrl url();
-
- void addCoverageData(CoveredFile* f);
-
- ReportValueItem* coverageRatioItem() const;
- ReportValueItem* slocItem() const;
- ReportValueItem* nrofCoveredLinesItem() const;
-
-private:
- KUrl m_fullUrl;
- ReportValueItem* m_coverageRatioItem;
- ReportValueItem* m_slocItem;
- ReportValueItem* m_nrofCoveredLinesItem;
- QSet<int> m_coveredLines;
- QSet<int> m_reachableLines;
-};
-
-/*!
- * Stores the data for the report of a directory.
- * The data stored are the SLOC and the number of covered lines.
- * Coverage percentage is calculated based on those values.
- */
-class VERITAS_COVERAGE_EXPORT ReportDirData
-{
-public:
-
- /*!
- * Creates a new ReportDirData.
- * All the values are initialized to 0.
- */
- ReportDirData();
-
- int sloc() const;
- int nrofCoveredLines() const;
- double coverageRatio() const;
- void setSloc(int sloc);
- void setNrofCoveredLines(int nrof);
-
-private:
- int m_sloc;
- int m_nrofCoveredLines;
-};
-
-class VERITAS_COVERAGE_EXPORT ReportDirItem : public QStandardItem
-{
-public:
- explicit ReportDirItem(const QString& dir);
- virtual ~ReportDirItem();
- virtual int type() const;
- void updateStats();
- int sloc();
- int nrofCoveredLines();
- double coverageRatio();
- const ReportDirData& reportDirData() const;
-
-private:
- ReportDirData m_reportDirData;
- };
-
-class VERITAS_COVERAGE_EXPORT ReportValueItem: public QStandardItem
-{
-public:
- explicit ReportValueItem(double value);
- explicit ReportValueItem(int value);
- virtual ~ReportValueItem();
- virtual int type() const;
- double value() const;
- void setValue(double value);
- void setValue(int value);
-
-private:
- void initProperties();
- double m_value;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_REPORTMODEL_h
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.h (nonexistent)
@@ -1,66 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_ANNOTATIONMANAGER_H
-#define VERITAS_COVERAGE_ANNOTATIONMANAGER_H
-
-#include "coverageexport.h"
-
-#include <KUrl>
-#include <QMap>
-
-namespace KDevelop { class IDocument; }
-namespace KTextEditor { class Document; class View; }
-
-namespace Veritas
-{
-
-class CoveredFile;
-/*!
- * Makes sure document views are annotated with coverage info
- * @unittest AnnotationManagerTest
- */
-class VERITAS_COVERAGE_EXPORT AnnotationManager : public QObject
-{
-Q_OBJECT
-public:
- explicit AnnotationManager(QObject* parent=0);
- virtual ~AnnotationManager();
-
- void setCoveredFiles(const QMap<KUrl, CoveredFile*>& files);
- void watch(KDevelop::IDocument*);
- void stopWatching(KDevelop::IDocument*);
-
-public Q_SLOTS:
- void addCoverageData(CoveredFile* f);
-
-private Q_SLOTS:
- void connectKDocWithTextDoc(KDevelop::IDocument*);
- void fixAnnotation(KTextEditor::Document*, KTextEditor::View*);
-
-private:
- QMap<KUrl, CoveredFile*> m_files;
- QList<KDevelop::IDocument*> m_docs;
- QMap<KTextEditor::Document*, KUrl> m_textDocUrls;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_ANNOTATIONMANAGER_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.ui (nonexistent)
@@ -1,92 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>StopPointWidget</class>
- <widget class="QWidget" name="StopPointWidget">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>425</width>
- <height>43</height>
- </rect>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">A stop point in the current color range type.</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,1,0,0,0,0">
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QLabel" name="colorLabel">
- <property name="text">
- <string comment="@label:chooser The color to be used">Color:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KColorButton" name="colorChooser">
- <property name="toolTip">
- <string comment="@info:tooltip">Color for this stop point</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="percentageLabel">
- <property name="text">
- <string comment="@label:spinbox">For percentage:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDoubleSpinBox" name="percentageSpinBox">
- <property name="toolTip">
- <string comment="@info:tooltip">Percentage for this stop point</string>
- </property>
- <property name="maximum">
- <double>100.000000000000000</double>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="addButton">
- <property name="toolTip">
- <string comment="@info:tooltip">Add new stop point</string>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">Adds a new stop point after this one to the current color range type.</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="removeButton">
- <property name="toolTip">
- <string comment="@info:tooltip">Remove this stop point</string>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">Removes this stop point from the current color range type.</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KColorButton</class>
- <extends>QPushButton</extends>
- <header>kcolorbutton.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.h (nonexistent)
@@ -1,206 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITAS_COVERAGE_LCOVPREFSWIDGET_H
-#define VERITAS_COVERAGE_LCOVPREFSWIDGET_H
-
-#include <QtGui/QWidget>
-
-#include "ui_lcovprefswidget.h"
-
-#include "colorrange.h"
-
-class LCovSettingsBase;
-class StopPointWidget;
-
-/**
- * Preferences widget for coverage plugin.
- * This widget manages the ColorRange configuration used in coverage report
- * colors, as it can be managed by the KDE Configuration Compiler itself.
- * However, those widgets managed by the KDE Configuration Compiler aren't
- * managed in any way by LCovPrefsWidget.
- *
- * This LCovPrefsWidget is meant to be used with LCovSettingsBase and LCovPrefs
- * objects.
- *
- * LCovPrefs manages the dialog, and calls the appropriate methods in
- * LCovSettingsBase when it is loaded, saved, or default values are set. When
- * the ColorRange is modified by the user, LCovPrefsWidget emits changed(bool)
- * signal. The parameter tells whether the ColorRange is different to the saved
- * one (true), or equal to it (false), so "Apply" button can be enabled or
- * disabled as needed by LCovPrefs.
- *
- * LCovSettingsBase manages the configuration: load, save and set default
- * values. Using that class it can be checked whether the actual ColorRange is
- * equal to the saved one. In order to show changes to the ColorRange made
- * outside LCovPrefsWidget (for example, when setting the default ColorRange in
- * LCovSettingsBase), reloadColorRange() slot is called.
- */
-class LCovPrefsWidget: public QWidget
-{
-Q_OBJECT
-public:
-
- /**
- * Creates a new LCovPrefsWidget.
- *
- * @param settings The base settings that contain the ColorRange to show.
- * @param parent The parent widget.
- */
- explicit LCovPrefsWidget(LCovSettingsBase* settings, QWidget* parent = 0);
-
- /**
- * Destroys this LCovPrefsWidget.
- */
- virtual ~LCovPrefsWidget();
-
-public slots:
-
- /**
- * Changes the mode of the ColorRange.
- * Emits changed(bool).
- *
- * @param mode "Discrete" or "Gradient", depending on the mode to set.
- */
- void changeMode(const QString& mode);
-
- /**
- * Changes the color of the stop point at the given index.
- * Emits changed(bool).
- *
- * @param index The index of the stop point.
- * @param color The color to set.
- */
- void changeColor(int index, const QColor& color);
-
- /**
- * Changes the position of the stop point at the given index.
- * The range for the previous and next StopPointWidget are updated.
- * Emits changed(bool).
- *
- * @param index The index of the stop point.
- * @param position The position to set.
- */
- void changePosition(int index, double position);
-
- /**
- * Adds a new stop point after the one at the given index.
- * The value of the stop points that follow the added one are updated, so
- * they don't overlap.
- * The stop points are reloaded.
- * Emits changed(bool).
- *
- * @param index The index to add the stop point after.
- */
- void addStopPointAfter(int index);
-
- /**
- * Removes the stop point at the given index.
- * The stop points are reloaded.
- * Emits changed(bool).
- *
- * @param index The index of the stop point to remove.
- */
- void removeStopPoint(int index);
-
- /**
- * Sets the type combobox to the current type of the ColorRange, and reloads
- * the list of stop points.
- * Emits changed(bool).
- */
- void reloadColorRange();
-
-signals:
-
- /**
- * Emitted when the ColorRange changes.
- *
- * @param changed True if it changed and it is different to the saved one,
- * false otherwise.
- */
- void changed(bool changed);
-
-private:
-
- /**
- * The Qt Designer widget file.
- */
- Ui::LCovPrefsWidget mUi;
-
- /**
- * The base settings that contain the color range to show.
- */
- LCovSettingsBase* mSettings;
-
- /**
- * Reloads the list of StopPointWidgets.
- * The previous StopPointWidgets are removed and deleted, and a new
- * StopPointWidget is added for each StopPoint in the current mode of the
- * ColorRange.
- * If there is only one stop point, a dummy StopPointWidget is added first.
- */
- void reloadStopPoints();
-
- /**
- * Creates a new StopPointWidget.
- *
- * @param stopPoints The list of StopPoints.
- * @param index The index of the StopPoint to create the widget for.
- * @param mode The mode of the StopPoint.
- * @return The new StopPointWidget.
- */
- StopPointWidget* newStopPointWidgetFor(
- const Veritas::StopPoints& stopPoints, int index,
- Veritas::ColorRange::Mode mode);
-
- /**
- * Creates a new dummy StopPointWidget.
- *
- * @return The new dummy StopPointWidget.
- */
- StopPointWidget* newDummyStopPointWidget();
-
- /**
- * Returns the StopPointWidget at the given index.
- *
- * @param index The index of the StopPointWidget.
- * @return The StopPointWidget.
- */
- StopPointWidget* getStopPointWidget(int index);
-
- /**
- * Updates the range of the StopPointWidget at the given index.
- * The range is set to the previous and next stop point positions, or 0 or 1
- * if there are no previous or next stop points.
- *
- * @param index The index of the StopPointWidget.
- */
- void updateRange(int index);
-
- /**
- * Emits changed(bool).
- * The boolean value is set to true if the actual color range in the
- * settings is different to the saved one, false otherwise.
- */
- void checkIfChanged();
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.cpp (nonexistent)
@@ -1,213 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Benjamin Meyer <ben@meyerhome.net> *
- * Copyright 2006 Alexander Dymo <adymo@kdevelop.org> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include "drilldownview.h"
-
-#include <QSortFilterProxyModel>
-#include <QHeaderView>
-#include <QAbstractScrollArea>
-
-using Veritas::DrillDownView;
-
-DrillDownView::DrillDownView(QWidget *parent)
- : QTableView(parent)
-{
- setFrameShape((QFrame::Shape)(QFrame::StyledPanel | QFrame::Raised));
- setGridStyle(Qt::SolidLine);
- setShowGrid(true);
-
- connect(&animation, SIGNAL(frameChanged(int)), this, SLOT(slide(int)));
- connect(&animation, SIGNAL(finished()), this, SLOT(update()));
- animation.setDuration(125);
- setAlternatingRowColors(true); // hmz
- verticalHeader()->hide();
- setSortingEnabled(true);
- horizontalHeader()->resizeSection(0, width());
-
- setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
-
- resizeDirStateColumns();
-
- setSelectionBehavior(QAbstractItemView::SelectRows);
-}
-
-DrillDownView::~DrillDownView()
-{}
-
-void DrillDownView::paintEvent(QPaintEvent *event)
-{
- if (animation.state() != QTimeLine::Running) {
- QTableView::paintEvent(event);
- return;
- }
-
- QPainter painter(viewport());
- if (animation.direction() == QTimeLine::Backward) {
- painter.drawPixmap(-animation.currentFrame(), 0, newView);
- painter.drawPixmap(-animation.currentFrame() + animation.endFrame(), 0, oldView);
- } else {
- painter.drawPixmap(-animation.currentFrame(), 0, oldView);
- painter.drawPixmap(-animation.currentFrame() + animation.endFrame(), 0, newView);
- }
-}
-
-void DrillDownView::slide(int x)
-{
- viewport()->scroll(lastPosition - x, 0);
- lastPosition = x;
-}
-
-void DrillDownView::keyPressEvent(QKeyEvent *event)
-{
- QModelIndex current = currentIndex();
- if (isBusy()) {
- return; //eat event if animation is running
- }
- if (!(current.isValid() || event->key() == Qt::Key_Left)) {
- QTableView::keyPressEvent(event);
- return;
- }
- QSortFilterProxyModel* p = static_cast<QSortFilterProxyModel*>(model());
- QAbstractItemModel* m = p->sourceModel();
- QModelIndex srcIndex;
- switch(event->key()) {
- case Qt::Key_Right:
- current = current.sibling(current.row(), 0);
- srcIndex = p->mapToSource(current);
- if (m->hasChildren(srcIndex)) slideRight(current);
- return;
- break;
- case Qt::Key_Left:
- slideLeft();
- return;
- break;
- case Qt::Key_Return:
- emit returnPressed(current);
- break;
- default: break;
- }
- QTableView::keyPressEvent(event);
-}
-
-void DrillDownView::resizeFileStateColumns()
-{
- QHeaderView* header = horizontalHeader();
- header->resizeSection(1, 75);
- header->resizeSection(2, 75);
- header->resizeSection(3, 75);
- header->resizeSection(0, (maxWidth()-225 > 75) ? maxWidth()-225 : 75);
-}
-
-int DrillDownView::maxWidth() const
-{
- QScrollBar* vertbar = verticalScrollBar();
- Q_ASSERT(vertbar);
- int width = maximumViewportSize().width();
- if (vertbar->isVisible()) {
- width = width - vertbar->width();
- }
- return width - 5;
-}
-
-void DrillDownView::resizeDirStateColumns()
-{
- horizontalHeader()->resizeSection(1, 20);
- horizontalHeader()->resizeSection(0, maxWidth() - 20);
-}
-
-void DrillDownView::slideRight(const QModelIndex& current)
-{
- if (current == rootIndex()) return;
- if (model()->canFetchMore(current)) {
- model()->fetchMore(current);
- return;
- }
- setUpdatesEnabled(false);
-
- leftSelection = selectionModel()->selection();
- selectionModel()->clear();
-
- setRootIndex(current);
-
- animateSlide(Qt::Key_Right);
- resizeFileStateColumns();
- setUpdatesEnabled(true);
- emit completedSlideRight();
- }
-
-void DrillDownView::slideLeft()
-{
- QModelIndex current = currentIndex();
- QModelIndex root = rootIndex();
- if (!root.isValid()) return;
- setUpdatesEnabled(false);
-
- setRootIndex(root.parent());
-
- selectionModel()->clear();
- selectionModel()->select(leftSelection, QItemSelectionModel::Select);
- selectionModel()->setCurrentIndex(root, QItemSelectionModel::NoUpdate);
-
- animateSlide(Qt::Key_Left);
- resizeDirStateColumns();
- setUpdatesEnabled(true);
- emit completedSlideLeft();
-}
-
-void DrillDownView::animateSlide(int moveDirection)
-{
- executeDelayedItemsLayout();
- // Force the hiding/showing of scrollbars
- setVerticalScrollBarPolicy(verticalScrollBarPolicy());
- newView = QPixmap::grabWidget(viewport());
- setUpdatesEnabled(true);
- int length = qMax(oldView.width(), newView.width());
- lastPosition = moveDirection == Qt::Key_Left ? length : 0;
- animation.setFrameRange(0, length);
- animation.stop();
- animation.setDirection(moveDirection == Qt::Key_Right ?
- QTimeLine::Forward : QTimeLine::Backward);
- animation.start();
-}
-
-//TODO Since Qt 4.4.2, clicking on an empty space of the QTableView clears
-//the selection. Remove this whole method when required Qt version for
-//KDevelop is >= 4.4.2
-void DrillDownView::mousePressEvent(QMouseEvent* event)
-{
- if (selectionModel() && !indexAt(event->pos()).isValid()) {
- selectionModel()->clearSelection();
- }
- QTableView::mousePressEvent(event);
-}
-
-bool DrillDownView::isBusy()
-{
- return animation.state() == QTimeLine::Running;
-}
-
-void DrillDownView::setRootIndex(const QModelIndex &index)
-{
- QTableView::setRootIndex(index);
- emit rootIndexChanged(index);
-}
-
-#include "drilldownview.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/drilldownview.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/cmake/FindKDevVeritas.cmake (nonexistent)
@@ -1,30 +0,0 @@
-#
-# Find the KDevelop Veritas library
-#
-# Example usage of this module:
-# find_package(KDevVeritas)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVVERITAS_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVVERITAS_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVVERITAS_LIBRARY - veritas module library
-#
-# Copyright 2009 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-find_path( KDEVVERITAS_INCLUDE_DIR veritas/test.h
- PATH_SUFFIXES kdevplatform
- )
-find_library( KDEVVERITAS_LIBRARY kdevplatformveritas
- )
-
-# handle the QUIETLY and REQUIRED arguments and set JPEG_FOUND to TRUE if
-# all listed variables are TRUE
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevVeritas DEFAULT_MSG KDEVVERITAS_LIBRARY KDEVVERITAS_INCLUDE_DIR)
-
-mark_as_advanced(KDEVVERITAS_INCLUDE_DIR KDEVVERITAS_LIBRARY)
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.cpp (nonexistent)
@@ -1,152 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "colorrange.h"
-
-#include <KConfigGroup>
-
-using Veritas::ColorRange;
-using Veritas::StopPoints;
-
-ColorRange::ColorRange()
-{
- mMode = Discrete;
-}
-
-ColorRange::~ColorRange()
-{
-}
-
-ColorRange::Mode ColorRange::mode() const
-{
- return mMode;
-}
-
-void ColorRange::setMode(Mode mode)
-{
- mMode = mode;
-}
-
-QColor ColorRange::colorAt(double position) const
-{
- if (mMode == Discrete) {
- return mDiscreteColorRange.colorAt(position);
- }
-
- return mGradientColorRange.colorAt(position);
-}
-
-StopPoints ColorRange::stopPoints() const
-{
- if (mMode == Discrete) {
- return mDiscreteColorRange.stopPoints();
- }
-
- return mGradientColorRange.stopPoints();
-}
-
-void ColorRange::setStopPoints(const StopPoints& stopPoints)
-{
- if (mMode == Discrete) {
- mDiscreteColorRange.setStopPoints(stopPoints);
- } else {
- mGradientColorRange.setStopPoints(stopPoints);
- }
-}
-
-void ColorRange::load(const KConfigGroup& group)
-{
- if (group.readEntry("Mode") == "Gradient") {
- mMode = Gradient;
- } else {
- mMode = Discrete;
- }
-
- mDiscreteColorRange.setStopPoints(loadStopPoints(group.group("Discrete")));
- mGradientColorRange.setStopPoints(loadStopPoints(group.group("Gradient")));
-}
-
-void ColorRange::save(KConfigGroup& group)
-{
- if (mMode == Gradient) {
- group.writeEntry("Mode", "Gradient");
- } else {
- group.writeEntry("Mode", "Discrete");
- }
-
- KConfigGroup discreteGroup(&group, "Discrete");
- saveStopPoints(discreteGroup, mDiscreteColorRange.stopPoints());
-
- KConfigGroup gradientGroup(&group, "Gradient");
- saveStopPoints(gradientGroup, mGradientColorRange.stopPoints());
-}
-
-bool ColorRange::operator==(const ColorRange& colorRange) const
-{
- if (mMode != colorRange.mMode) {
- return false;
- }
-
- if (mDiscreteColorRange.stopPoints() !=
- colorRange.mDiscreteColorRange.stopPoints()) {
- return false;
- }
-
- if (mGradientColorRange.stopPoints() !=
- colorRange.mGradientColorRange.stopPoints()) {
- return false;
- }
-
- return true;
-}
-
-bool ColorRange::operator!=(const ColorRange& colorRange) const
-{
- return !(*this == colorRange);
-}
-
-StopPoints ColorRange::loadStopPoints(const KConfigGroup& group) const
-{
- StopPoints stopPoints;
-
- int numberOfStopPoints = group.readEntry("NumberOfStopPoints", 0);
- for (int i=0; i<numberOfStopPoints; ++i) {
- QString baseName = QString("StopPoint") + QString::number(i);
-
- StopPoint stopPoint;
- stopPoint.first = group.readEntry(baseName + "Position", 0.0);
- stopPoint.second = group.readEntry(baseName + "Color", QColor());
-
- stopPoints.append(stopPoint);
- }
-
- return stopPoints;
-}
-
-void ColorRange::saveStopPoints(KConfigGroup& group,
- const StopPoints& stopPoints) const
-{
- group.writeEntry("NumberOfStopPoints", stopPoints.size());
- for (int i=0; i<stopPoints.size(); ++i) {
- QString baseName = QString("StopPoint") + QString::number(i);
-
- group.writeEntry(baseName + "Position", stopPoints[i].first);
- group.writeEntry(baseName + "Color", stopPoints[i].second);
- }
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h (nonexistent)
@@ -1,145 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITAS_COVERAGE_LCOVSETTINGSBASE_H
-#define VERITAS_COVERAGE_LCOVSETTINGSBASE_H
-
-#include <KConfigSkeleton>
-
-#include "colorrange.h"
-
-/**
- * Base class for LCovSettings.
- * This class manages the configuration of coverage report colors, as it can't
- * be managed using the KDE Configuration Compiler.
- *
- * It is done implementing the usrReadConfig(), usrWriteConfig(),
- * usrSetDefaults() and usrUseDefaults() protected methods. KConfigSkeleton
- * takes care of calling them when needed.
- *
- * In order to allow the modification of the coverage report colors, the actual
- * ColorRange is exposed in colorRange() method. It can be checked whether the
- * actual ColorRange is equal to the default one or to the last saved one using
- * isDefaultColorRange() and isSavedColorRange().
- *
- * When the ColorRange changes (due to being read or set to the default value),
- * colorRangeChanged() is emitted.
- */
-class LCovSettingsBase: public KConfigSkeleton
-{
-Q_OBJECT
-public:
-
- /**
- * Destroys this LCovSettingsBase.
- */
- virtual ~LCovSettingsBase();
-
- /**
- * Returns the actual ColorRange.
- *
- * @return The actual ColorRange.
- */
- Veritas::ColorRange* colorRange();
-
- /**
- * Whether the actual ColorRange is equal to the default one or not.
- *
- * @return True if the actual ColorRange is equal to the default one, false
- * otherwise.
- */
- bool isDefaultColorRange() const;
-
- /**
- * Whether the actual ColorRange is equal to the saved one or not.
- *
- * @return True if the actual ColorRange is equal to the saved one, false
- * otherwise.
- */
- bool isSavedColorRange() const;
-
-signals:
-
- /**
- * Emitted when the actual ColorRange changes (due to the configuration
- * being read or the default values set).
- * Note that it won't be emitted if the configuration is read but the actual
- * ColorRange is equal to the newly read one, or if the default values are
- * set and the actual ColorRange is equal to the default one.
- */
- void colorRangeChanged();
-
-protected:
-
- /**
- * Creates a new LCovSettingsBase.
- * Actual and saved ColorRange are set to the default one.
- *
- * @param configurationFileName The name of the configuration file.
- */
- LCovSettingsBase(const QString &configurationFileName);
-
- /**
- * Loads the saved ColorRange from the configuration.
- * If there is no entry for it, the saved ColorRange is the default one.
- * The actual ColorRange is set to the saved one.
- */
- virtual void usrReadConfig();
-
- /**
- * Sets the actual ColorRange to the default one.
- */
- virtual void usrSetDefaults();
-
- /**
- * Swaps default and actual ColorRange values.
- *
- * @param useDefaults Ignored.
- * @return False (ignored in KConfigSkeleton::useDefaults(bool)).
- */
- virtual bool usrUseDefaults(bool useDefaults);
-
- /**
- * Saves the ColorRange to the configuration.
- * If the actual ColorRange is equal to the default ColorRange, it is
- * removed from the configuration.
- */
- virtual void usrWriteConfig();
-
-private:
-
- /**
- * The actual ColorRange.
- */
- Veritas::ColorRange mColorRange;
-
- /**
- * The saved ColorRange.
- */
- Veritas::ColorRange mSavedColorRange;
-
- /**
- * The default ColorRange.
- */
- Veritas::ColorRange mDefaultColorRange;
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.h (nonexistent)
@@ -1,189 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITAS_COVERAGE_STOPPOINTWIDGET_H
-#define VERITAS_COVERAGE_STOPPOINTWIDGET_H
-
-#include <QtGui/QWidget>
-
-#include "colorrange.h"
-
-namespace Ui
-{
-class StopPointWidget;
-}
-
-/**
- * Widget to display and edit a StopPoint.
- * StopPoints are used to define ColorRanges: each StopPoint contains a Color
- * and its position (in [0, 1] range), and a ColorRange contains several
- * StopPoints for each mode (discrete and gradient).
- *
- * This widget is used with LCovPrefsWidget to modify a ColorRange.
- * LCovPrefsWidget contains as many StopPointWidgets as StopPoint are in the
- * current mode of the ColorRange.
- *
- * Each StopPointWidget displays the values for a StopPoint, identified by
- * its index. When the values are modified, LCovPrefsWidget modifies the
- * ColorRange to reflect the changes.
- *
- * As the position of a StopPoint must be greater than the position of the
- * previous one, and lower than the position of the next one, the valid range of
- * values for the StopPoint can be set using setRange(double, double).
- *
- * Although the methods expect positions in range [0, 1], the position of the
- * StopPoint is shown to the user as a percentage.
- *
- * There is a special case in StopPointWidgets: dummy StopPointWidget. A dummy
- * StopPointWidget only has its add button visible. It is used in discrete mode
- * when there is only one stop point. A dummy StopPointWidget is added before
- * its StopPointWidget to allow the user insert a new StopPoint (as the widget
- * for the last and unique StopPoint would have its add button disabled).
- */
-class StopPointWidget: public QWidget
-{
-Q_OBJECT
-public:
-
- /**
- * Creates a new StopPointWidget.
- *
- * @param parent The parent widget.
- */
- explicit StopPointWidget(QWidget* parent = 0);
-
- /**
- * Destroys this StopPointWidget.
- */
- virtual ~StopPointWidget();
-
- /**
- * Sets the StopPoint.
- * A StopPoint at position 1 has its position, add and remove buttons
- * disabled. Also, in Gradient mode, a StopPoint at 0 has its position and
- * add button disabled.
- *
- * @param stopPoint The StopPoint.
- */
- void setStopPoint(const Veritas::StopPoint& stopPoint,
- Veritas::ColorRange::Mode mode);
-
- /**
- * Sets the index of the StopPoint.
- *
- * @param index The index of the StopPoint.
- */
- void setStopPointIndex(int index);
-
- /**
- * Sets the range of valid position values.
- * The range must be between 0 and 1, both inclusive. The range shown to the
- * user is set to [minimum * 100 + 0,01, maximum * 100 - 0,01].
- *
- * When the StopPoint position is 1, or the StopPoint position is 0 and it
- * is in GradientMode, the ranges are ignored.
- *
- * @param minimum The position of the previous stop point.
- * @param maximum The position of the next stop point.
- */
- void setRange(double minimum, double maximum);
-
- /**
- * Sets this StopPointWidget in dummy mode.
- *
- * @param dummy True to hide everything but the add button, false to show
- * everything.
- */
- void setDummy(bool dummy);
-
-signals:
-
- /**
- * Emitted when the color for the StopPoint at the given index changes.
- *
- * @param index The index of the StopPoint.
- * @param color The new color.
- */
- void colorChanged(int index, const QColor& color);
-
- /**
- * Emitted when the position for the StopPoint at the given index changes.
- *
- * @param index The index of the StopPoint.
- * @param position The new position.
- */
- void positionChanged(int index, double position);
-
- /**
- * Emitted when a new StopPoint has to be added after the given index.
- *
- * @param index The index of the StopPoint.
- */
- void stopPointToAddAfter(int index);
-
- /**
- * Emitted when the StopPoint at the given index has to be removed.
- *
- * @param index The index of the StopPoint.
- */
- void stopPointToRemove(int index);
-
-private:
-
- /**
- * The Qt Designer widget file.
- */
- Ui::StopPointWidget* mUi;
-
- /**
- * The index of the StopPoint.
- */
- int mIndex;
-
- /**
- * The mode of the StopPoint.
- */
- Veritas::ColorRange::Mode mMode;
-
-private slots:
-
- /**
- * Emits colorChanged(int, const QColor&).
- */
- void changeColor(const QColor& color);
-
- /**
- * Emits positionChanged(int, double).
- */
- void changePosition(double percentage);
-
- /**
- * Emits stopPointToAddAfter(int).
- */
- void addStopPointAfter();
-
- /**
- * Emits stopPointToRemove(int).
- */
- void removeStopPoint();
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.desktop (nonexistent)
@@ -1,53 +0,0 @@
-[Desktop Entry]
-Type=Service
-Icon=kdevelop
-Exec=blubb
-Comment=Gcov C(++) coverage
-Comment[bs]=Gcov C(++) pokrivenost
-Comment[ca]=Cobertura Gcov C(++)
-Comment[ca@valencia]=Cobertura Gcov C(++)
-Comment[de]=Gcov-C(++)-Testabdeckung
-Comment[en_GB]=Gcov C(++) coverage
-Comment[es]=Cobertura Gcov C(++)
-Comment[et]=Gcov C(++) kaetus
-Comment[fr]=Couverture de Gcov C(++)
-Comment[gl]=Cobertura de C(++) de Gcov
-Comment[it]=Copertura di C(++) Gcov
-Comment[nds]=GCov-C(++)-Afdecken
-Comment[nl]=Gcov C(++) coverage
-Comment[pl]=Pokrycie Gcov C(++)
-Comment[pt]=Cobertura de C(++) Gcov
-Comment[pt_BR]=Cobertura de C(++) Gcov
-Comment[sv]=Gcov C(++)-täckningsverktyg
-Comment[uk]=Покриття Gcov C(++)
-Comment[x-test]=xxGcov C(++) coveragexx
-
-Name=Code Coverage Report
-Name[bs]=Izvještaj pokrivenosti koda
-Name[ca]=Informe de cobertura del codi
-Name[ca@valencia]=Informe de cobertura del codi
-Name[de]=Bericht zur Testabdeckung
-Name[en_GB]=Code Coverage Report
-Name[es]=Informe de cobertura del código
-Name[et]=Koodi kaetuse aruanne
-Name[fr]=Rapport de couverture de code
-Name[gl]=Informe de cobertura de código
-Name[it]=Resoconto copertura del codice
-Name[nds]=Kodeafdeck-Bericht
-Name[nl]=Code Coverage Rapportage
-Name[pl]=Sprawozdanie pokrycia kodu
-Name[pt]=Relatório de Cobertura do Código
-Name[pt_BR]=Relatório de cobertura do código
-Name[sv]=Kodtäckningsrapport
-Name[uk]=Звіт щодо покриття коду
-Name[x-test]=xxCode Coverage Reportxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevcoverage
-X-KDE-PluginInfo-Name=coverageplugin
-X-KDE-PluginInfo-Author=Manuel Breugelmans
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=LGPL
-X-KDevelop-Version=15
-X-KDevelop-Category=Global
-X-KDevelop-IRequired=org.kdevelop.IOutputView
-X-KDevelop-Mode=GUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp (nonexistent)
@@ -1,63 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "discretecolorrange.h"
-
-using Veritas::DiscreteColorRange;
-using Veritas::StopPoints;
-
-DiscreteColorRange::DiscreteColorRange()
-{
- mStopPoints.append(StopPoint(1, QColor(Qt::white)));
-}
-
-DiscreteColorRange::~DiscreteColorRange()
-{
-}
-
-QColor DiscreteColorRange::colorAt(double position) const
-{
- Q_ASSERT(position >= 0 && position <= 1);
-
- if (position >= 0 && position <= mStopPoints[0].first) {
- return mStopPoints[0].second;
- }
-
- for (int i=1; i<mStopPoints.size()-1; ++i) {
- if (position > mStopPoints[i-1].first &&
- position <= mStopPoints[i].first) {
- return mStopPoints[i].second;
- }
- }
-
- return mStopPoints.last().second;
-}
-
-StopPoints DiscreteColorRange::stopPoints() const
-{
- return mStopPoints;
-}
-
-void DiscreteColorRange::setStopPoints(const StopPoints& stopPoints)
-{
- Q_ASSERT(stopPoints.size() >= 1);
- Q_ASSERT(stopPoints.last().first == 1);
-
- mStopPoints = stopPoints;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/discretecolorrange.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` `find . -name \*.kcfg` >>rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h | grep -v '/tests/'` -o $podir/kdevcoverage.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/kdevcoverage.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="kdevcoverage" version="1">
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.h (nonexistent)
@@ -1,72 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_LCOVINFOPARSER_H
-#define VERITAS_LCOVINFOPARSER_H
-
-#include <QIODevice>
-#include <QList>
-#include <QStringList>
-#include <KUrl>
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-class CoveredFile;
-
-/*! Parses lcov output into CoveredFile* and emits those as soon
- * as they are read
- * @note instantiate a fresh parser for every lcov.info file */
-class VERITAS_COVERAGE_EXPORT LcovInfoParser : public QObject
-{
-Q_OBJECT
-public:
- explicit LcovInfoParser(QObject* parent=0);
- ~LcovInfoParser();
-
- /*! Parse a single line of lcov output. The results are
- * emitted through `parsedCoverageData(CoveredFile*)' */
- void parseLine(const QString& line);
-
- QList<CoveredFile*> fto_coveredFiles();
-
-Q_SIGNALS:
- /*! Emitted whenever a full coverage record was parsed.
- * @p file contains the parsed coverage information */
- void parsedCoverageData(CoveredFile* file);
-
-public Q_SLOTS:
- void parseLines(const QStringList& lines);
-
-private:
- CoveredFile* m_current;
- QList<CoveredFile*> m_files;
-
- // scratch variables
- char tmp_firstChar;
- char tmp_secondChar;
- QStringList tmp_s;
- QStringList tmp_l;
- QString tmp_f;
-};
-
-}
-
-#endif // VERITAS_LCOVINFOPARSER_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovinfoparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp (nonexistent)
@@ -1,82 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "lcovjobprogress.h"
-
-#include <QTimer>
-
-#include <KLocalizedString>
-
-using Veritas::LcovJobProgress;
-
-LcovJobProgress::LcovJobProgress(QObject* parent /*= 0*/): QObject(parent),
- m_numberOfFilesFound(0), m_numberOfFilesProcessed(0)
-{
-}
-
-LcovJobProgress::~LcovJobProgress()
-{
-}
-
-QString LcovJobProgress::statusName() const
-{
- return i18nc("@info:progress", "Running <command>geninfo</command>");
-}
-
-void LcovJobProgress::start()
-{
- emit showProgress(this, 0, 1, 0);
-}
-
-void LcovJobProgress::parseLines(const QStringList &lines)
-{
- foreach (const QString& line, lines) {
- if (line.contains(QRegExp("^Scanning .* for \\.gcda files"))) {
- emit showMessage(this, i18nc("@info:progress", "Scanning for .gcda files"));
- emit showProgress(this, 0, 1, 0);
- } else if (line.contains(QRegExp("^Found \\d+ data files in .*"))) {
- m_numberOfFilesFound = line.split(' ')[1].toInt();
-
- emit showMessage(this, i18nc("@info:progress", "Processing .gcda files"));
- emit showProgress(this, 0, 2, 1);
- } else if (line.contains(QRegExp("^ERROR: no .gcda files found in .*"))) {
- emit clearMessage(this);
- emit showProgress(this, 0, 1, 1);
- } else if (line.contains(QRegExp("^Processing .*"))) {
- //Half total progress was scanning for .gcda files
- int progress = 50;
- progress += 50 * m_numberOfFilesProcessed / (float)m_numberOfFilesFound;
-
- emit showProgress(this, 0, 100, progress);
-
- m_numberOfFilesProcessed++;
- } else if (line.contains("Finished .info-file creation")) {
- emit showProgress(this, 0, 1, 1);
- }
- }
-}
-
-void LcovJobProgress::finish()
-{
- emit clearMessage(this);
- emit showProgress(this, 0, 1, 1);
- emit hideProgress(this);
-}
-
-#include "lcovjobprogress.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjobprogress.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.h (nonexistent)
@@ -1,71 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVEREDFILE_H
-#define VERITAS_COVEREDFILE_H
-
-#include "coverageexport.h"
-
-#include <QList>
-#include <KUrl>
-#include <QMap>
-#include <QSet>
-
-namespace Veritas
-{
-
-/*! Prime value class, holds coverage data for a file. This
- * includes the covered lines, uncovered ones and callcounts */
-class VERITAS_COVERAGE_EXPORT CoveredFile : public QObject
-{
-Q_OBJECT
-public:
- CoveredFile();
- virtual ~CoveredFile();
-
- KUrl url() const;
- void setUrl(const KUrl& url);
- void setCallCount(int line, int count);
- /*! line coverage percentage */
- double coverageRatio() const;
- /*! number of source lines of code */
- int sloc() const;
-
- /*! number of visited lines of code */
- int nrofCoveredLines() const;
-
- QMap<int, int> callCountMap() const;
- QSet<int> coveredLines() const;
- QSet<int> reachableLines() const;
- inline bool isReachable(int line) const {
- return m_reachableLines.contains(line);
- }
-
-private:
- QMap<int, int> m_nrofCalls; // { line x nrofcalls }
- int m_nrofLines;
- int m_nrofCoveredLines;
- KUrl m_sourceLoc;
- QSet<int> m_coveredLines;
- QSet<int> m_reachableLines;
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coveredfile.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.cpp (nonexistent)
@@ -1,74 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "colorrangebar.h"
-#include "colorrange.h"
-
-#include <QPainter>
-
-using Veritas::ColorRange;
-using Veritas::StopPoints;
-
-ColorRangeBar::ColorRangeBar(ColorRange* colorRange, QWidget* parent):
- QWidget(parent) {
- mColorRange = colorRange;
-}
-
-void ColorRangeBar::paintEvent(QPaintEvent*) {
- QPainter painter(this);
- if (mColorRange->mode() == ColorRange::Discrete) {
- paintDiscreteColorRange(this->contentsRect(), &painter);
- } else {
- paintGradientColorRange(this->contentsRect(), &painter);
- }
-}
-
-void ColorRangeBar::paintDiscreteColorRange(const QRect& rectangle,
- QPainter* painter) {
- QBrush brush(Qt::SolidPattern);
- QRectF rectangleRange(rectangle);
-
- StopPoints stopPoints = mColorRange->stopPoints();
-
- for (int i=0; i<stopPoints.size(); ++i) {
- double width = rectangle.width();
- if (i == 0) {
- width = width * stopPoints[i].first;
- } else {
- width = width * (stopPoints[i].first - stopPoints[i-1].first);
- }
- rectangleRange.setWidth(width);
-
- brush.setColor(stopPoints[i].second);
- painter->fillRect(rectangleRange, brush);
- rectangleRange.translate(width, 0);
- }
-}
-
-void ColorRangeBar::paintGradientColorRange(const QRect& rectangle,
- QPainter* painter) {
- QLinearGradient linearGradient(0, 0.5, 1, 0.5);
- linearGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
- linearGradient.setStops(mColorRange->stopPoints());
-
- painter->fillRect(rectangle, QBrush(linearGradient));
-}
-
-#include "colorrangebar.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.h (nonexistent)
@@ -1,93 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_LCOVJOB_H
-#define VERITAS_COVERAGE_LCOVJOB_H
-
-#include <interfaces/iplugin.h>
-#include <outputview/outputjob.h>
-#include "coverageexport.h"
-
-#include <QProcess>
-#include <QString>
-#include <KUrl>
-
-namespace KDevelop
-{
-class IOutputView;
-class IProject;
-class ProcessLineMaker;
-}
-
-class KProcess;
-
-namespace Veritas
-{
-
-class CovOutputModel;
-class CovOutputDelegate;
-class LcovInfoParser;
-class LcovJobProgress;
-
-/*! Executes the lcov coverage script in an outputview */
-class VERITAS_COVERAGE_EXPORT LcovJob : public KDevelop::OutputJob
-{
- Q_OBJECT
-
-public:
- explicit LcovJob(const KUrl& root, QObject* parent=0);
- virtual ~LcovJob();
- void setProcess(KProcess *proc); // takes ownership.
- void setParser(LcovInfoParser* parser);
- void setDelegate(CovOutputDelegate* delegate);
- virtual void start();
-
-protected:
- CovOutputModel* model() const;
-
- /**
- * Kill underlying geninfo/lcov process.
- * An error message is also added to the model.
- *
- * @return true.
- */
- virtual bool doKill();
-
-private Q_SLOTS:
- void slotFinished();
- void slotError(QProcess::ProcessError error);
-
-private:
- void initProcess();
- void initOutputView();
- void initParser();
-
-private:
- KDevelop::ProcessLineMaker* m_lineMaker;
- KProcess* m_lcov;
- KUrl m_root;
- QString m_tmpPath;
- LcovInfoParser* m_parser;
- LcovJobProgress* m_lcovJobProgress;
-};
-
-}
-
-#endif // VERITAS_COVERAGE_LCOVJOB_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovjob.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h (nonexistent)
@@ -1,126 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESS_H
-#define VERITAS_COVERAGE_REMOVEGCDAFILESJOBPROGRESS_H
-
-#include <interfaces/istatus.h>
-
-#include "coverageexport.h"
-
-namespace KDevelop
-{
-class IStatus;
-}
-
-namespace Veritas
-{
-
-/**
- * Shows progress information for remove gcda files job.
- * The job first scans the given directory looking for gcda files and then
- * removes each gcda file found.
- * While the job is looking for gcda files no progress updates are given. Once
- * it finishes looking for them, it tells how many files were found and then
- * notifies the files removed one by one.
- *
- * The progress is reported by this class in this way:
- * - 0: when the job starts and while it is scanning the directory.
- * - 50: when the job finishes scanning the directory.
- * - (50-100]: when the job is removing the files. The progress will be updated
- * proportionally to how many files are going to be removed and how many files
- * have already been removed.
- * - 100: when the job finishes, no matter why.
- *
- * Also, the status message will specify whether the job is scanning for files
- * or removing them already.
- */
-class VERITAS_COVERAGE_EXPORT RemoveGcdaFilesJobProgress: public QObject, public KDevelop::IStatus
-{
-Q_OBJECT
-Q_INTERFACES(KDevelop::IStatus)
-
-public:
-
- /**
- * Creates a new RemoveGcdaFilesJobProgress.
- *
- * @param parent The parent QObject.
- */
- explicit RemoveGcdaFilesJobProgress(QObject* parent = 0);
-
- //<KDevelop::IStatus>
-
- /**
- * The name of this status update.
- *
- * @return "Removing coverage data"
- */
- virtual QString statusName() const;
-
-Q_SIGNALS:
-
- void clearMessage(KDevelop::IStatus* status);
- void showMessage(KDevelop::IStatus* status, const QString & message, int timeout = 0);
- void showErrorMessage(const QString & message, int timeout = 0);
- void hideProgress(KDevelop::IStatus* status);
- void showProgress(KDevelop::IStatus* status, int minimum, int maximum, int value);
-
- //</KDevelop::IStatus>
-
-public:
-
- /**
- * Reports that the job has been started.
- * The message will be set to "Scanning for .gcda files".
- */
- void start();
-
- /**
- * Sets the number of files found.
- * It is assumed that the job has finished scanning the directory, so the
- * message will be set to "Removing .gcda files" and the progress set to
- * 50%.
- *
- * @param numberOfFilesFound The number of gcda files found.
- */
- void setNumberOfFilesFound(int numberOfFilesFound);
-
- /**
- * Updates the progress based on the number of files that were removed
- * already.
- */
- void fileAboutToBeRemoved();
-
- /**
- * Reports that the job has finished, no matter why.
- * Clears the message and shows a 100% progress before hidding it.
- */
- void finish();
-
-private:
-
- int m_numberOfFilesFound;
- int m_numberOfFilesRemoved;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjobprogress.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.cpp (nonexistent)
@@ -1,101 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "annotationmodel.h"
-#include "coveredfile.h"
-#include <KLocale>
-
-using Veritas::AnnotationModel;
-using Veritas::CoveredFile;
-
-
-AnnotationModel::AnnotationModel(CoveredFile* file, QObject* parent)
- : m_notInstrumented(QBrush(Qt::BDiagPattern)),
- m_noCoverage(QBrush(Qt::red)),
- m_covered(QBrush(Qt::green))
-{
- setParent(parent);
- m_file = new CoveredFile;
- m_file->setUrl(file->url());
- QMap<int, int> cc = file->callCountMap();
- QMapIterator<int, int> it(cc);
- while(it.hasNext()) {
- it.next();
- m_file->setCallCount(it.key(), it.value());
- }
-}
-
-AnnotationModel::~AnnotationModel()
-{
- delete m_file;
-}
-
-/**
- * data() is used to retrieve the information needed to present the
- * annotation information from the annotation model. The provider
- * should return useful information for the line and the data role.
- *
- * \param line the line for which the data is to be retrieved
- * \param role the role to identify which kind of annotation is to be retrieved
- *
- * \returns a \ref QVariant that contains the data for the given role. The
- * following roles are supported:
- *
- * \ref Qt::DisplayRole - a short display text to be placed in the border
- * \ref Qt::TooltipRole - a tooltip information, longer text possible
- * \ref Qt::BackgroundRole - a brush to be used to paint the background on the border
- * \ref Qt::ForegroundRole - a brush to be used to paint the text on the border
- */
-QVariant AnnotationModel::data(int line, Qt::ItemDataRole role) const
-{
- Q_ASSERT(m_file);
- line += 1; // annotationmodel counts from zero
- int count;
- switch(role) {
- case Qt::DisplayRole: {
- if (m_file->isReachable(line)) {
- return QString::number(m_file->callCountMap()[line]);
- }
- break;
- } case Qt::BackgroundRole: {
- if (!m_file->isReachable(line)) {
- return m_notInstrumented;
- }
- count = m_file->callCountMap()[line];
- if (count == 0) return m_noCoverage;
- else return m_covered;
- break;
- } case Qt::ToolTipRole : {
- if (m_file->isReachable(line)) {
- return QVariant(i18n("Number of times visited."));
- } else {
- return QVariant(i18n("Line not reachable."));
- }
- break;
- } default: break;
- }
- return QVariant();
-}
-
-void AnnotationModel::update()
-{
- emit reset();
-}
-
-#include "annotationmodel.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.h (nonexistent)
@@ -1,120 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2010 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_BUILDPATHSELECTION_H
-#define VERITAS_COVERAGE_BUILDPATHSELECTION_H
-
-#include <QObject>
-
-#include "coverageexport.h"
-
-class QWidget;
-class KUrl;
-class KUrlNavigator;
-
-namespace KDevelop
-{
-class IProject;
-}
-
-namespace Veritas
-{
-
-class ProjectSelection;
-
-/**
- * Manages the build path selection.
- * The build path is scanned for .gcda files when the coverage analysis starts.
- * It can be set directly in a KUrlNavigator, or got from the current build path
- * used in an opened project.
- *
- * If a project is selected, the URL shown by the KUrlNavigator is set to the
- * build path of that project. If the URL shown by the KUrlNavigator is changed,
- * the selected project will change to the one that uses that build path. If
- * there is none, the selected project will be cleared.
- *
- * Only projects that have a build manager with a build path set can be
- * selected.
- */
-class VERITAS_COVERAGE_EXPORT BuildPathSelection: public QObject
-{
-Q_OBJECT
-public:
-
- /**
- * Creates a new BuildPathSelection.
- *
- * @param targetDirectory The KUrlNavigator to update when a project is
- * selected.
- * @param parent The parent object.
- */
- explicit BuildPathSelection(KUrlNavigator* targetDirectory, QObject* parent = 0);
-
- /**
- * Returns a widget that represents the ProjectSelection action.
- *
- * @param parent The parent widget.
- * @return The widget that represents the action.
- */
- QWidget* requestProjectSelectionWidget(QWidget* parent);
-
-public Q_SLOTS:
-
- /**
- * Sets the build path from the given project.
- * If a project was selected, it must have a build system manager with a
- * configured build directory. A null pointer can be received when the
- * current project is cleared (because its configuration changed or because
- * it is closed), and nothing is done in that case.
- *
- * @param project The project to get the build path from.
- */
- void setBuildPathFromProject(KDevelop::IProject* project);
-
- /**
- * Sets the selected project as the first one that has the given URL as
- * build path.
- * If no project has that URL as build path, the current project is
- * deselected.
- *
- * @param url The URL of the build path.
- */
- void setProjectFromBuildPath(const KUrl& url);
-
-Q_SIGNALS:
-
- /**
- * Emitted when the build path from the selected project has to be set.
- *
- * @param url The build path.
- */
- void buildPathToSet(const KUrl& url);
-
-private:
-
- /**
- * Manages the selection of projects.
- */
- ProjectSelection* m_projectSelection;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/buildpathselection.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageexport.h (nonexistent)
@@ -1,42 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2004 Jarosław Staniek <staniek@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef VERITAS_COVERAGE_EXPORT_H
-#define VERITAS_COVERAGE_EXPORT_H
-
-#include <kdemacros.h>
-
-#ifndef VERITAS_COVERAGE_EXPORT
-# ifdef MAKE_KDEVVERITASCOVERAGE_LIB
-# define VERITAS_COVERAGE_EXPORT KDE_EXPORT
-# else
-# define VERITAS_COVERAGE_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#ifdef MAKE_KCM_KDEV_LCOVSETTINGS_LIB
-# undef VERITAS_COVERAGE_EXPORT
-# define VERITAS_COVERAGE_EXPORT
-#endif
-
-#endif // VERITAS_COVERAGE_EXPORT_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageexport.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.h (nonexistent)
@@ -1,64 +0,0 @@
-/* KDevelop coverage plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGEPLUGIN_H
-#define VERITAS_COVERAGEPLUGIN_H
-
-#include <KUrl>
-#include <QVariantList>
-#include <QFileInfo>
-#include <interfaces/iplugin.h>
-#include <interfaces/iuicontroller.h>
-
-class QDir;
-
-namespace Veritas
-{
-class ReportViewFactory;
-
-/*! GCC GCOV coverage plugin. Code coverage report with source annotations (line call count). */
-class CoveragePlugin : public KDevelop::IPlugin
-{
-Q_OBJECT
-
-public:
- explicit CoveragePlugin(QObject* parent, const QVariantList& = QVariantList());
- virtual ~CoveragePlugin();
- virtual void unload();
-
-private:
- ReportViewFactory* m_factory;
-};
-
-/*! Report toolview factory */
-class ReportViewFactory : public KDevelop::IToolViewFactory
-{
-public:
- ReportViewFactory();
- virtual ~ReportViewFactory();
-
- virtual QWidget* create(QWidget *parent = 0);
- virtual Qt::DockWidgetArea defaultPosition();
- virtual QString id() const;
-};
-
-} // namespace Veritas
-
-#endif // VERITAS_COVERAGEPLUGIN_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/coverageplugin.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp (nonexistent)
@@ -1,120 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "lcovsettingsbase.h"
-
-using Veritas::ColorRange;
-using Veritas::StopPoint;
-using Veritas::StopPoints;
-
-LCovSettingsBase::~LCovSettingsBase()
-{
-}
-
-Veritas::ColorRange* LCovSettingsBase::colorRange()
-{
- return &mColorRange;
-}
-
-bool LCovSettingsBase::isDefaultColorRange() const
-{
- return mColorRange == mDefaultColorRange;
-}
-
-bool LCovSettingsBase::isSavedColorRange() const
-{
- return mColorRange == mSavedColorRange;
-}
-
-LCovSettingsBase::LCovSettingsBase(const QString &configurationFileName):
- KConfigSkeleton(configurationFileName)
-{
- mDefaultColorRange.setMode(ColorRange::Gradient);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0, QColor("black")));
- stopPoints.append(StopPoint(0.3333, QColor("red")));
- stopPoints.append(StopPoint(0.6667, QColor("orange")));
- stopPoints.append(StopPoint(1, QColor("green")));
- mDefaultColorRange.setStopPoints(stopPoints);
-
- mDefaultColorRange.setMode(ColorRange::Discrete);
- stopPoints.clear();
- stopPoints.append(StopPoint(0.25, QColor("black")));
- stopPoints.append(StopPoint(0.50, QColor("red")));
- stopPoints.append(StopPoint(0.75, QColor("orange")));
- stopPoints.append(StopPoint(1, QColor("green")));
- mDefaultColorRange.setStopPoints(stopPoints);
-
- mColorRange = mDefaultColorRange;
- mSavedColorRange = mDefaultColorRange;
-}
-
-void LCovSettingsBase::usrReadConfig()
-{
- KConfigGroup coverageGroup = config()->group("Code Coverage");
- if (coverageGroup.hasGroup("Color Range")) {
- mSavedColorRange.load(coverageGroup.group("Color Range"));
- } else {
- mSavedColorRange = mDefaultColorRange;
- }
-
- if (!isSavedColorRange()) {
- mColorRange = mSavedColorRange;
- emit colorRangeChanged();
- }
-}
-
-void LCovSettingsBase::usrSetDefaults()
-{
- if (!isDefaultColorRange()) {
- mColorRange = mDefaultColorRange;
- emit colorRangeChanged();
- }
-}
-
-bool LCovSettingsBase::usrUseDefaults(bool)
-{
- //Implemented following the implementation of
- //KConfigSkeletonGenericItem::swapDefaults(), which is called in
- //KCoreConfigSkeleton::useDefaults(bool)
- ColorRange temporal = mColorRange;
- mColorRange = mDefaultColorRange;
- mDefaultColorRange = temporal;
-
- emit colorRangeChanged();
-
- return false;
-}
-
-void LCovSettingsBase::usrWriteConfig()
-{
- KConfigGroup coverageGroup = config()->group("Code Coverage");
- coverageGroup.deleteGroup("Color Range");
-
- if (!isDefaultColorRange()) {
- KConfigGroup colorRangeGroup(&coverageGroup, "Color Range");
- mColorRange.save(colorRangeGroup);
- }
-
- //After writing the configuration, it is read again in KConfigSkeleton, so
- //there is no need to set mSavedColorRange here.
-}
-
-#include "lcovsettingsbase.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovsettingsbase.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.h (nonexistent)
@@ -1,44 +0,0 @@
-/* KDevelop Project Settings
- *
- * Copyright 2006 Matt Rogers <mattr@kde.org>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef LCOVPREFS_H
-#define LCOVPREFS_H
-
-#include <kcmodule.h>
-
-#include <kurl.h>
-
-class LCovPrefs : public KCModule
-{
- Q_OBJECT
-public:
- LCovPrefs( QWidget *parent, const QVariantList &args );
-
- virtual void save();
- virtual void load();
- virtual void defaults();
-
-public slots:
-
- void changeState(bool changed);
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.cpp (nonexistent)
@@ -1,327 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008-2009 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "reportmodel.h"
-#include "coveredfile.h"
-#include <KConfigGroup>
-#include <KGlobal>
-#include <KLocale>
-
-using Veritas::CoveredFile;
-using Veritas::ReportModel;
-using Veritas::ReportDirData;
-using Veritas::ReportDirItem;
-using Veritas::ReportFileItem;
-using Veritas::ReportValueItem;
-
-///////////////// ReportItems ////////////////////////////////////////////////
-
-ReportValueItem* ReportFileItem::coverageRatioItem() const
-{
- return m_coverageRatioItem;
-}
-
-ReportValueItem* ReportFileItem::slocItem() const
-{
- return m_slocItem;
-}
-
-ReportValueItem* ReportFileItem::nrofCoveredLinesItem() const
-{
- return m_nrofCoveredLinesItem;
-}
-
-ReportFileItem::ReportFileItem(const KUrl& url)
- : QStandardItem(url.fileName()),
- m_fullUrl(url),
- m_coverageRatioItem(0),
- m_slocItem(0),
- m_nrofCoveredLinesItem(0)
-{
- setEditable(false);
- setSelectable(true);
- setCheckable(false);
-}
-
-void ReportFileItem::addCoverageData(CoveredFile* f)
-{
- Q_ASSERT(f->url() == url());
- if (!m_coverageRatioItem) {
- m_coverageRatioItem = new ReportValueItem(f->coverageRatio());
- m_slocItem = new ReportValueItem(f->sloc());
- m_nrofCoveredLinesItem = new ReportValueItem(f->nrofCoveredLines());
- m_coveredLines = f->coveredLines();
- m_reachableLines = f->reachableLines();
- } else {
- m_coveredLines += f->coveredLines(); // set union
- m_reachableLines += f->reachableLines();
- int covered = m_coveredLines.count();
- int reachable = m_reachableLines.count();
- m_nrofCoveredLinesItem->setValue(covered);
- m_slocItem->setValue(reachable);
- m_coverageRatioItem->setValue(100*(double)covered/reachable);
- }
-}
-
-KUrl ReportFileItem::url()
-{
- return m_fullUrl;
-}
-
-ReportFileItem::~ReportFileItem()
-{}
-
-int ReportFileItem::type() const
-{
- return ReportModel::File;
-}
-
-ReportDirData::ReportDirData()
-{
- m_sloc = 0;
- m_nrofCoveredLines = 0;
-}
-
-int ReportDirData::sloc() const
-{
- return m_sloc;
-}
-
-int ReportDirData::nrofCoveredLines() const
-{
- return m_nrofCoveredLines;
-}
-
-double ReportDirData::coverageRatio() const
-{
- return (m_sloc == 0) ? 0 : 100*double(m_nrofCoveredLines)/double(m_sloc);
-}
-
-void ReportDirData::setSloc(int sloc)
-{
- m_sloc = sloc;
-}
-
-void ReportDirData::setNrofCoveredLines(int nrof)
-{
- m_nrofCoveredLines = nrof;
-}
-
-ReportDirItem::ReportDirItem(const QString& dir)
- : QStandardItem(dir) {
- setEditable(false);
- setSelectable(true);
- setCheckable(false);
-}
-
-void ReportDirItem::updateStats()
-{
- int sloc = 0;
- int nrofCoveredLines = 0;
- QStandardItem* si;
- ReportFileItem* rfi;
- for (int row=0; row<rowCount(); row++) {
- si = child(row, 0);
- if (si->type() == ReportModel::File) {
- rfi = static_cast<ReportFileItem*>(si);
- nrofCoveredLines += rfi->nrofCoveredLinesItem()->value();
- sloc += rfi->slocItem()->value();
- }
- }
-
- m_reportDirData.setSloc(sloc);
- m_reportDirData.setNrofCoveredLines(nrofCoveredLines);
-}
-
-ReportDirItem::~ReportDirItem()
-{}
-
-int ReportDirItem::type() const
-{
- return ReportModel::Dir;
-}
-
-int ReportDirItem::sloc()
-{
- return m_reportDirData.sloc();
-}
-
-int ReportDirItem::nrofCoveredLines()
-{
- return m_reportDirData.nrofCoveredLines();
-}
-
-double ReportDirItem::coverageRatio()
-{
- return m_reportDirData.coverageRatio();
-}
-
-const ReportDirData& ReportDirItem::reportDirData() const
-{
- return m_reportDirData;
-}
-
-ReportValueItem::ReportValueItem(double value)
-{
- setValue(value);
- initProperties();
-}
-
-ReportValueItem::ReportValueItem(int value)
-{
- setValue(value);
- initProperties();
-}
-
-double ReportValueItem::value() const
-{
- return m_value;
-}
-
-void ReportValueItem::setValue(double value)
-{
- m_value = value;
- setData(QString::number(value, 'f', 1), Qt::DisplayRole);
-}
-
-void ReportValueItem::setValue(int value)
-{
- m_value = value;
- setData(QString::number(value), Qt::DisplayRole);
-}
-
-void ReportValueItem::initProperties()
-{
- setEditable(false);
- setSelectable(false);
- setCheckable(false);
-}
-
-ReportValueItem::~ReportValueItem()
-{}
-
-int ReportValueItem::type() const
-{
- return ReportModel::Value;
-}
-
-///////////////// ReportModel ////////////////////////////////////////////////
-
-ReportModel::ReportModel(QObject* parent)
- : QStandardItemModel(parent)
-{
- QStringList headers;
- headers << i18nc("@title:column Coverage report column", "source")
- << i18nc("@title:column Coverage report column", "coverage")
- << i18nc("@title:column Coverage report column", "visited")
- << i18nc("@title:column Coverage report column", "SLOC");
- setHorizontalHeaderLabels(headers);
-
- KConfigGroup group = KGlobal::config()->group("Code Coverage");
- if (group.hasGroup("Color Range")) {
- m_colorRange.load(group.group("Color Range"));
- } else {
- m_colorRange.setMode(ColorRange::Discrete);
- StopPoints stopPoints;
- stopPoints.append(StopPoint(0.25, QColor("black")));
- stopPoints.append(StopPoint(0.50, QColor("red")));
- stopPoints.append(StopPoint(0.75, QColor("orange")));
- stopPoints.append(StopPoint(1, QColor("green")));
- m_colorRange.setStopPoints(stopPoints);
- }
-}
-
-void ReportModel::setRootDirectory(const KUrl& root)
-{
- m_root = root;
-}
-
-ReportModel::~ReportModel()
-{}
-
-QVariant ReportModel::data(const QModelIndex& i, int role) const
-{
- if (role != ReportModel::SortRole) {
- return QStandardItemModel::data(i, role);
- }
- // SortRole
- QStandardItem* item = itemFromIndex(i);
- if (item->type() == ReportModel::Value) {
- ReportValueItem* rvi = static_cast<ReportValueItem*>(item);
- return QVariant(rvi->value());
- } else { // sort on display value
- return QStandardItemModel::data(i, Qt::DisplayRole);
- }
-}
-
-QList<QStandardItem*> ReportModel::createFileRow(CoveredFile* f)
-{
- ReportFileItem* file = new ReportFileItem(f->url()); // do these get cleaned?
- m_files.insert(f->url(), file);
- file->addCoverageData(f);
- QList<QStandardItem*> row;
- row << file << file->coverageRatioItem() << file->nrofCoveredLinesItem() << file->slocItem();
- return row;
-}
-
-// slot called when new CoveredFile has been parsed
-void ReportModel::addCoverageData(CoveredFile* f)
-{
- QString dir = f->url().directory();
- if (!m_dirs.contains(dir)) appendDir(dir);
- ReportDirItem* dirItem = m_dirs[dir];
- if (!m_files.contains(f->url())) {
- dirItem->appendRow(createFileRow(f));
- } else {
- m_files[f->url()]->addCoverageData(f);
- }
- dirItem->updateStats();
- updateColoredCoverageColumn(dirItem);
- }
-
-// helper for addCoverageData
-void ReportModel::appendDir(const QString& dir)
-{
- ReportDirItem* dirItem = new ReportDirItem(dir);
- m_dirs[dir] = dirItem;
- QStandardItem *root = invisibleRootItem();
- QList<QStandardItem*> row;
- row << dirItem;
- root->appendRow(row);
-}
-
-// helper for addCoverageData
-void ReportModel::updateColoredCoverageColumn(ReportDirItem* dir)
-{
- QModelIndex i = dir->index();
- i = i.sibling(i.row(), i.column()+1);
- QStandardItem* it = itemFromIndex(i);
- QBrush b = brushForCoverage(dir->coverageRatio());
- it->setBackground(b);
- it->setForeground(b);
- it->setData(dir->coverageRatio(), Qt::DisplayRole);
-}
-
-QBrush ReportModel::brushForCoverage(double percent)
-{
- return QBrush(m_colorRange.colorAt(percent / 100));
-}
-
-#include "reportmodel.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.h (nonexistent)
@@ -1,120 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_GRADIENTCOLORRANGE_H
-#define VERITAS_COVERAGE_GRADIENTCOLORRANGE_H
-
-#include <QColor>
-#include <QPair>
-#include <QVector>
-
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-typedef QPair<double, QColor> StopPoint;
-typedef QVector<StopPoint> StopPoints;
-
-/**
- * A gradient of colors, each of them associated with a point in range 0 to 1
- * (both included).
- * A stop point associate a point with a color. There are always at least two
- * stop points, associated with positions 0 and 1. Any other position has a
- * color calculated as a gradient between the set stop points.
- *
- * Method colorAt(double) can be used to know the color at some position (no
- * matter if there is a stop point or not at that position). A color between two
- * stop points is the linear interpolated color between them.
- *
- * Setting a red stop point at 0, a yellow stop point at 0.5 and a green stop
- * point at 1, the following values would be returned by colorAt:
- * - 0 -> Red
- * - 0.25 -> Orange
- * - 0.5 -> Yellow
- * - 0.75 -> Yellowish green
- * - 1 -> Green
- */
-class VERITAS_COVERAGE_EXPORT GradientColorRange
-{
-public:
-
- /**
- * Creates a new GradientColorRange.
- * The color at 0 is set to black, the color at 1 is set to white, and there
- * are no middle stop points.
- */
- GradientColorRange();
-
- /**
- * Destroys this GradientColorRange.
- */
- virtual ~GradientColorRange();
-
- /**
- * Returns the color at the given position.
- *
- * @param position The position, in the range 0 to 1 (both included).
- * @return The color.
- */
- QColor colorAt(double position) const;
-
- /**
- * Returns the stop points.
- *
- * @return The stop points.
- */
- StopPoints stopPoints() const;
-
- /**
- * Sets the stop points.
- * The StopPoints must be in the range [0, 1], in ascending order, and they
- * must contain only valid colors. The list must contain at least the stop
- * points located at position 0 and 1.
- *
- * @param stopPoints The StopPoints to set.
- */
- void setStopPoints(const StopPoints& stopPoints);
-
-private:
-
- /**
- * The stop points.
- */
- StopPoints mStopPoints;
-
- /**
- * Interpolates a color between two stop points.
- * Each component (red, green and blue) of the returned color is the result
- * of applying linear interpolation between the components of the begin and
- * end colors at the given position.
- *
- * @param begin The first stop point.
- * @param end The second stop point.
- * @param position The position of the color to interpolate.
- * @return The interpolated color.
- */
- QColor interpolateColor(const StopPoint& begin, const StopPoint& end,
- double position) const;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/gradientcolorrange.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp (nonexistent)
@@ -1,232 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "lcovprefswidget.h"
-#include "lcovsettingsbase.h"
-#include "colorrangebar.h"
-#include "stoppointwidget.h"
-
-using Veritas::ColorRange;
-using Veritas::StopPoint;
-using Veritas::StopPoints;
-
-LCovPrefsWidget::LCovPrefsWidget(LCovSettingsBase* settings, QWidget* parent):
- QWidget(parent)
-{
- mUi.setupUi(this);
- mSettings = settings;
-
- reloadColorRange();
-
- QHBoxLayout* layout = new QHBoxLayout(mUi.colorRangeBarFrame);
- ColorRangeBar* colorRangeBar = new ColorRangeBar(mSettings->colorRange(),
- this);
- layout->addWidget(colorRangeBar);
- layout->setContentsMargins(0, 0, 0, 0);
-
- connect(this, SIGNAL(changed(bool)), colorRangeBar, SLOT(update()));
-
- connect(mUi.modeComboBox, SIGNAL(currentIndexChanged(QString)),
- this, SLOT(changeMode(QString)));
-}
-
-LCovPrefsWidget::~LCovPrefsWidget()
-{
-}
-
-void LCovPrefsWidget::changeMode(const QString& mode)
-{
- if (mode ==
- i18nc("@item:inlistbox Discrete color range type", "Discrete")) {
- mSettings->colorRange()->setMode(ColorRange::Discrete);
- } else {
- mSettings->colorRange()->setMode(ColorRange::Gradient);
- }
-
- reloadStopPoints();
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::changeColor(int index, const QColor& color)
-{
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- stopPoints[index].second = color;
- mSettings->colorRange()->setStopPoints(stopPoints);
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::changePosition(int index, double position)
-{
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- stopPoints[index].first = position;
- mSettings->colorRange()->setStopPoints(stopPoints);
-
- if (index > 0) {
- updateRange(index - 1);
- }
- updateRange(index + 1);
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::addStopPointAfter(int index)
-{
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- StopPoint newStopPoint;
- if (index == -1) {
- newStopPoint.first = 0.0001;
- newStopPoint.second = stopPoints[0].second;
- } else {
- newStopPoint = stopPoints[index];
- newStopPoint.first += 0.0001;
- }
- stopPoints.insert(index + 1, newStopPoint);
-
- //Ensure that next values don't overlap
- for (int i=index+2; i<stopPoints.size(); ++i) {
- double minimum = stopPoints[i-1].first + 0.0001;
- if (stopPoints[i].first < minimum) {
- stopPoints[i].first = minimum;
- }
- }
-
- mSettings->colorRange()->setStopPoints(stopPoints);
-
- reloadStopPoints();
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::removeStopPoint(int index)
-{
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- stopPoints.remove(index);
- mSettings->colorRange()->setStopPoints(stopPoints);
-
- reloadStopPoints();
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::reloadColorRange()
-{
- if (mSettings->colorRange()->mode() == ColorRange::Discrete) {
- mUi.modeComboBox->setCurrentIndex(mUi.modeComboBox->findText(
- i18nc("@item:inlistbox Discrete color range type", "Discrete")));
- } else {
- mUi.modeComboBox->setCurrentIndex(mUi.modeComboBox->findText(
- i18nc("@item:inlistbox Gradient color range type", "Gradient")));
- }
-
- reloadStopPoints();
-
- checkIfChanged();
-}
-
-void LCovPrefsWidget::reloadStopPoints()
-{
- QLayout* layout = mUi.stopPointsScrollArea->widget()->layout();
- QLayoutItem *child;
- while ((child = layout->takeAt(0)) != 0) {
- if (child->widget()) {
- child->widget()->deleteLater();
- }
- delete child;
- }
-
- QVBoxLayout* boxLayout = qobject_cast<QVBoxLayout*>(layout);
-
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- if (stopPoints.size() == 1) {
- boxLayout->addWidget(newDummyStopPointWidget());
- }
- for (int i=0; i<stopPoints.size(); ++i) {
- ColorRange::Mode mode = mSettings->colorRange()->mode();
- boxLayout->addWidget(newStopPointWidgetFor(stopPoints, i, mode));
- }
-
- boxLayout->addStretch();
-}
-
-StopPointWidget* LCovPrefsWidget::newStopPointWidgetFor(
- const StopPoints& stopPoints, int index, ColorRange::Mode mode)
-{
- StopPointWidget* stopPointWidget = new StopPointWidget(this);
-
- stopPointWidget->setStopPoint(stopPoints[index], mode);
- stopPointWidget->setStopPointIndex(index);
-
- double minimum = index>0 ? stopPoints[index-1].first : 0;
- double maximum = index<stopPoints.size()-1 ? stopPoints[index+1].first : 1;
- stopPointWidget->setRange(minimum, maximum);
-
- connect(stopPointWidget, SIGNAL(colorChanged(int,QColor)),
- this, SLOT(changeColor(int,QColor)));
- connect(stopPointWidget, SIGNAL(positionChanged(int,double)),
- this, SLOT(changePosition(int,double)));
- connect(stopPointWidget, SIGNAL(stopPointToAddAfter(int)),
- this, SLOT(addStopPointAfter(int)));
- connect(stopPointWidget, SIGNAL(stopPointToRemove(int)),
- this, SLOT(removeStopPoint(int)));
-
- return stopPointWidget;
-}
-
-StopPointWidget* LCovPrefsWidget::newDummyStopPointWidget()
-{
- StopPointWidget* stopPointWidget = new StopPointWidget(this);
- stopPointWidget->setDummy(true);
- stopPointWidget->setStopPointIndex(-1);
-
- connect(stopPointWidget, SIGNAL(stopPointToAddAfter(int)),
- this, SLOT(addStopPointAfter(int)));
-
- return stopPointWidget;
-}
-
-StopPointWidget* LCovPrefsWidget::getStopPointWidget(int index)
-{
- QLayout* layout = mUi.stopPointsScrollArea->widget()->layout();
- QLayoutItem* item = layout->itemAt(index);
- return qobject_cast<StopPointWidget*>(item->widget());
-}
-
-void LCovPrefsWidget::updateRange(int index)
-{
- StopPointWidget* stopPointWidget = getStopPointWidget(index);
-
- StopPoints stopPoints = mSettings->colorRange()->stopPoints();
- double minimum = index>0 ? stopPoints[index-1].first : 0;
- double maximum = index<stopPoints.size()-1 ? stopPoints[index+1].first : 1;
- stopPointWidget->setRange(minimum, maximum);
-}
-
-void LCovPrefsWidget::checkIfChanged()
-{
- if (mSettings->isSavedColorRange()) {
- emit changed(false);
- } else {
- emit changed(true);
- }
-}
-
-#include "lcovprefswidget.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefswidget.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.h (nonexistent)
@@ -1,56 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_COVOUTPUTMODEL_H
-#define VERITAS_COVERAGE_COVOUTPUTMODEL_H
-
-#include <QStandardItemModel>
-#include <outputview/ioutputviewmodel.h>
-
-class QModelIndex;
-
-namespace Veritas
-{
-
-/*! Used by the lcovjob */
-class CovOutputModel : public QStandardItemModel, public KDevelop::IOutputViewModel
-{
- Q_OBJECT
-
-public:
- explicit CovOutputModel(QObject *parent);
- ~CovOutputModel();
-
- void activate(const QModelIndex &idx);
- QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
- QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
- QVariant data(const QModelIndex& index, int role) const;
-
-public Q_SLOTS:
- void appendOutputs(const QStringList &lines);
- void appendErrors(const QStringList &lines);
- void slotCompleted();
- void slotFailed();
-};
-
-}
-
-#endif // VERITAS_COVERAGE_COVOUTPUTMODEL_h
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/covoutputmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp (nonexistent)
@@ -1,103 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2011 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "removegcdafilesjob.h"
-
-#include "removegcdafilesjobprogress.h"
-
-#include <QDir>
-#include <QtConcurrentRun>
-#include <QFuture>
-
-#include <KLocale>
-
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-
-using KDevelop::ICore;
-
-using Veritas::RemoveGcdaFilesJob;
-using Veritas::RemoveGcdaFilesJobProgress;
-
-RemoveGcdaFilesJob::RemoveGcdaFilesJob(const KUrl& rootPath, QObject* parent):
- KJob(parent),
- mRootPath(rootPath),
- mKillRequested(false) {
-
- setCapabilities(Killable);
- setObjectName(i18nc("@action:inmenu", "Remove coverage data from <filename>%1</filename> directory", rootPath.toLocalFile()));
-
- mRemoveGcdaFilesJobProgress = new RemoveGcdaFilesJobProgress(this);
- ICore::self()->uiController()->registerStatus(mRemoveGcdaFilesJobProgress);
-}
-
-void RemoveGcdaFilesJob::start() {
- mRemoveGcdaFilesJobProgress->start();
-
- mDoWorkWatcher = new QFutureWatcher<void>(this);
- connect(mDoWorkWatcher, SIGNAL(finished()), this, SLOT(jobDone()));
-
- QFuture<void> doWorkFuture = QtConcurrent::run(this, &RemoveGcdaFilesJob::doWork);
- mDoWorkWatcher->setFuture(doWorkFuture);
-}
-
-bool RemoveGcdaFilesJob::doKill() {
- mKillRequested = true;
-
- mDoWorkWatcher->waitForFinished();
-
- return true;
-}
-
-void RemoveGcdaFilesJob::jobDone() {
- mRemoveGcdaFilesJobProgress->finish();
-
- emitResult();
-}
-
-void RemoveGcdaFilesJob::doWork() const {
- QFileInfoList gcdaFileInfos = findGcdaFilesIn(QDir(mRootPath.toLocalFile()));
-
- mRemoveGcdaFilesJobProgress->setNumberOfFilesFound(gcdaFileInfos.count());
-
- QListIterator<QFileInfo> it(gcdaFileInfos);
- while (it.hasNext() && !mKillRequested) {
- mRemoveGcdaFilesJobProgress->fileAboutToBeRemoved();
-
- QFile(it.next().absoluteFilePath()).remove();
- }
-}
-
-QFileInfoList RemoveGcdaFilesJob::findGcdaFilesIn(const QDir& directory) const {
- QFileInfoList gcdaFileInfos;
-
- QFileInfoList directories;
- directories << directory.absolutePath();
-
- while (!directories.isEmpty() && !mKillRequested) {
- //Note that absolutePath() would return the path to the parent
- //directory, not the one we are interested in
- QDir currentDirectory = directories.takeFirst().absoluteFilePath();
- directories << currentDirectory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
-
- gcdaFileInfos << currentDirectory.entryInfoList(QStringList() << "*.gcda", QDir::Files | QDir::NoSymLinks);
- }
-
- return gcdaFileInfos;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/removegcdafilesjob.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.h (nonexistent)
@@ -1,50 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_REPORTPROXYMODEL_H
-#define VERITAS_COVERAGE_REPORTPROXYMODEL_H
-
-#include <QSortFilterProxyModel>
-
-#include "coverageexport.h"
-
-namespace Veritas
-{
-
-/*! Used to filter coverage directories from the model */
-class VERITAS_COVERAGE_EXPORT ReportProxyModel : public QSortFilterProxyModel
-{
-Q_OBJECT
-public:
- explicit ReportProxyModel(QObject* parent);
- virtual ~ReportProxyModel();
-
- void setFileViewState();
- void setDirViewState();
-
-protected:
- bool filterAcceptsColumn(int, const QModelIndex&) const;
-
-private:
- enum State { DirView, FileView } m_state;
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportproxymodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp (nonexistent)
@@ -1,64 +0,0 @@
-/*
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-/*! KDevelop4 gcov coverage tool example.
-usage:
-1/ Boot up KDevelop4
-2/ Project -> Open -> prime.kdev4
-3/ Build. Notice the gcov data file `main.gcno'
- in the project's directory
-4/ Run `is_prime'. Notice `main.gcda'
-5/ Add the coverage toolview. View -> Add Tool View -> Coverage
-6/ Enter the prime-projects root directory under 'Build Path:'
-7/ Hit the run coverage button, next to the breadcrumb widget
-8/ Use left and right arrow to navigate the report
-9/ Close this file
-10/ Double click 'main.cpp' to view coverage annotations
-*/
-
-#include <stdio.h>
-bool is_prime(long number);
-
-int main(int,char**)
-{
- if (is_prime(2111*4111)) {
- printf("not covered, not prime.\n");
- }
- if (is_prime(29)) {
- printf("covered, 29 is prime.\n");
- }
- return 0;
-}
-
-const bool g_primes[10] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0};
-bool is_prime(long number)
-{
- if (number < 10) {
- return g_primes[number];
- }
- if (number % 2 == 0) {
- return false;
- }
- for(long m = 3; m*m <= number; m += 2) {
- if (number % m == 0) {
- return false;
- }
- }
- return true;
-}
-
-//krazy:skip
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/main.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/.kdev4/prime.kdev4 (nonexistent)
@@ -1,2 +0,0 @@
-[Buildset]
-Number of Builditems=0
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/prime.kdev4 (nonexistent)
@@ -1,3 +0,0 @@
-[Project]
-Name=prime
-Manager=KDevCustomMakeManager
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/Makefile
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/Makefile (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/examples/prime/Makefile (nonexistent)
@@ -1,8 +0,0 @@
-is_prime: main.o
- g++ -fprofile-arcs -ftest-coverage -o $@ $^
-
-main.o: main.cpp
- g++ -fprofile-arcs -ftest-coverage -O0 -c $^
-
-clean:
- @rm -v is_prime *.o *.gcno *.gcda *~
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.h (nonexistent)
@@ -1,191 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_COVERAGE_COLORRANGE_H
-#define VERITAS_COVERAGE_COLORRANGE_H
-
-#include <QColor>
-#include <QPair>
-#include <QVector>
-
-#include "coverageexport.h"
-
-#include "discretecolorrange.h"
-#include "gradientcolorrange.h"
-
-class KConfigGroup;
-
-namespace Veritas
-{
-
-typedef QPair<double, QColor> StopPoint;
-typedef QVector<StopPoint> StopPoints;
-
-/**
- * Colors associated with subranges or points in range 0 to 1 (both included).
- * ColorRange has two independent modes: discrete and gradient. In discrete
- * mode, each color is associated with a subrange of the full range. In gradient
- * mode, each color is associated with a point, and the other points are
- * calculated as a gradient between the set points. For further information
- * about each mode, see the documentation of DiscreteColorRange and
- * GradientColorRange.
- *
- * The changes made in each mode doesn't affect those made in the other mode.
- * Also note that depending on the current mode, the semantics of the stop
- * points change a bit, as discrete mode uses 1 stop point less than gradient
- * mode, and in discrete mode they represent subranges and in gradient mode just
- * points.
- *
- * A ColorRange can be loaded from and saved to a KConfigurationGroup.
- *
- * @see DiscreteColorRange
- * @see GradientColorRange
- */
-class VERITAS_COVERAGE_EXPORT ColorRange
-{
-public:
-
- enum Mode {
- Gradient = 0,
- Discrete
- };
-
- /**
- * Creates a new ColorRange.
- * Default mode is Discrete.
- */
- ColorRange();
-
- /**
- * Destroys this ColorRange.
- */
- virtual ~ColorRange();
-
- /**
- * Returns the current mode of this ColorRange.
- *
- * @return The current mode of this ColorRange.
- */
- Mode mode() const;
-
- /**
- * Sets the current mode of this ColorRange.
- *
- * @param mode The current mode of this ColorRange.
- */
- void setMode(Mode mode);
-
- /**
- * Returns the color for the current mode at the given position.
- *
- * @param position The position, in the range 0 to 1 (both included).
- * @return The color.
- */
- QColor colorAt(double position) const;
-
- /**
- * Returns the stop points for the current mode.
- *
- * @return The stop points.
- */
- StopPoints stopPoints() const;
-
- /**
- * Sets the stop points for the current mode.
- *
- * @param stopPoints The StopPoints to set.
- * @see DiscreteColorRange::setStopPoints(const StopPoints&)
- * @see GradientColorRange::setStopPoints(const StopPoints&)
- */
- void setStopPoints(const StopPoints& stopPoints);
-
- /**
- * Loads this ColorRange from the given configuration group.
- *
- * @param group The configuration group to load this ColorRange from.
- * @see save(KConfigGroup&)
- */
- void load(const KConfigGroup& group);
-
- /**
- * Saves this ColorRange to the given configuration group.
- * The configuration group is expected to be empty. Also note that no sync
- * is made, only the needed groups and entries are added.
- *
- * The current mode of this ColorRange is saved, as a QString, in "Mode"
- * entry (with values "Discrete" and "Gradient"). The StopPoints of discrete
- * mode are saved in a group called "Discrete", and the StopPoints of
- * gradient mode are saved in a group called "Gradient". Note that both
- * modes are saved, no matter which is the current mode.
- *
- * @param group The empty configuration group to save this ColorRange to.
- * @see saveStopPoints(const KConfigGroup&, const StopPoints&)
- */
- void save(KConfigGroup& group);
-
- /**
- * Check whether this ColorRange is equal to the given one or not.
- *
- * @param colorRange The ColorRange to compare to.
- * @return True if both ColorRange are equal, false otherwise.
- */
- bool operator==(const ColorRange& colorRange) const;
-
- /**
- * Check whether this ColorRange is different to the given one or not.
- *
- * @param colorRange The ColorRange to compare to.
- * @return True if both ColorRange are different, false otherwise.
- */
- bool operator!=(const ColorRange& colorRange) const;
-
-private:
-
- Mode mMode;
- DiscreteColorRange mDiscreteColorRange;
- GradientColorRange mGradientColorRange;
-
- /**
- * Loads the StopPoints stored in the given configuration group.
- *
- * @param group The configuration group to load the StopPoints from.
- * @return The loaded StopPoints.
- * @see saveStopPoints(const KConfigGroup&, const StopPoints&)
- */
- StopPoints loadStopPoints(const KConfigGroup& group) const;
-
- /**
- * Saves the StopPoints in the given configuration group.
- * The number of StopPoints are saved, as an integer, in
- * "NumberOfStopPoints" entry. For each StopPoint, to entries are saved:
- * "StopPointXPosition", a real, with the position of the StopPoint, and
- * "StopPointXColor", a QColor, with the color of the StopPoint.
- * In both names, the X refer to the index of the StopPoint, indexed at 0.
- *
- * @param group The configuration group to save the StopPoints to.
- * @param stopPoints The StopPoints to save.
- */
- void saveStopPoints(KConfigGroup& group,
- const StopPoints& stopPoints) const;
-
-};
-
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrange.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.cpp (nonexistent)
@@ -1,72 +0,0 @@
-/* KDevelop Covergage lcov settings
-*
-* Copyright 2009 Andreas Pakulat <apaku@gmx.de>
-*
-* 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-#include "lcovprefs.h"
-
-#include <kgenericfactory.h>
-#include <kaboutdata.h>
-
-#include "lcovconfig.h"
-#include "lcovprefswidget.h"
-
-K_PLUGIN_FACTORY(LCovPrefsFactory, registerPlugin<LCovPrefs>();)
-K_EXPORT_PLUGIN(LCovPrefsFactory(KAboutData("kcm_kdev_lcovsettings", "kdevelop", ki18n("LCov Settings"), "0.1")))
-
-LCovPrefs::LCovPrefs( QWidget *parent, const QVariantList &args )
- : KCModule( LCovPrefsFactory::componentData(), parent, args )
-{
-
- QVBoxLayout * l = new QVBoxLayout( this );
- QWidget* w = new LCovPrefsWidget(LCovSettings::self(), parent);
- l->addWidget( w );
-
- connect(w, SIGNAL(changed(bool)), this, SLOT(changeState(bool)));
- connect(LCovSettings::self(), SIGNAL(colorRangeChanged()),
- w, SLOT(reloadColorRange()));
-
- addConfig( LCovSettings::self(), w );
-
- load();
-}
-
-void LCovPrefs::save()
-{
- LCovSettings::self()->writeConfig();
- KCModule::save();
-}
-
-void LCovPrefs::load()
-{
- LCovSettings::self()->readConfig();
- KCModule::load();
-}
-
-void LCovPrefs::defaults()
-{
- LCovSettings::self()->setDefaults();
- KCModule::defaults();
-}
-
-void LCovPrefs::changeState(bool changed)
-{
- unmanagedWidgetChangeState(changed);
-}
-
-#include "lcovprefs.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/lcovprefs.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/reportwidget.ui (nonexistent)
@@ -1,288 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>ReportWidget</class>
- <widget class="QWidget" name="ReportWidget">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>357</width>
- <height>498</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Coverage Report</string>
- </property>
- <property name="whatsThis">
- <string>GCOV code coverage statistics.
-
-Set the directory to generate the report for and start the scan.
-
-Once finished, you can select the directories in the coverage report to see their statistics. A more detailed report can be seen for each directory, showing all the covered files in it. Each file can also be shown in the editor, annotated with line by line coverage information.</string>
- </property>
- <layout class="QVBoxLayout" name="reportWidgetLayout">
- <item>
- <widget class="QFrame" name="buildPathFrame">
- <property name="frameShape">
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow">
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QVBoxLayout" name="buildPathFrameLayout">
- <item>
- <layout class="QHBoxLayout" name="buildPathSelectionLayout">
- <item>
- <widget class="QLabel" name="buildPathTextLabel">
- <property name="whatsThis">
- <string>The directory to scan for .gcda files.</string>
- </property>
- <property name="text">
- <string>Build Path: </string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="lcovJobButton">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="removeGcdaFilesJobButton">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="projectSelectionLayout">
- <item>
- <widget class="QLabel" name="getFromProjectTextLabel">
- <property name="toolTip">
- <string comment="@info:tooltip">Use the build path from the selected project</string>
- </property>
- <property name="whatsThis">
- <string comment="@info:whatsthis">When one of the opened projects is selected, the directory to scan for &lt;filename&gt;.gcda&lt;/filename&gt; files will be set to the build path of that project.</string>
- </property>
- <property name="text">
- <string comment="@label:listbox">Get from project:</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="projectSelectionSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QFrame" name="statisticsFrame">
- <property name="frameShape">
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow">
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QHBoxLayout" name="statisticsFrameLayout">
- <item>
- <spacer name="horizontalSpacer_3">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>71</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="KLineEdit" name="filterBox">
- <property name="toolTip">
- <string>Filter directories by name</string>
- </property>
- <property name="whatsThis">
- <string>When the report is in directory mode, only those containing the specified text in their path are shown.
-
-In file mode, the filter has no effect.</string>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>30</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="coverageRatioTextLabel">
- <property name="whatsThis">
- <string>Percentage of covered lines in the selected directories.</string>
- </property>
- <property name="text">
- <string>Line Coverage:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QLabel" name="coverageRatio">
- <property name="whatsThis">
- <string>Percentage of covered lines in the selected directories.</string>
- </property>
- <property name="text">
- <string>-</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="nrofCoveredLinesTextLabel">
- <property name="whatsThis">
- <string>Number of covered lines in the selected directories.
-
-Covered lines are those that were executed at least once.</string>
- </property>
- <property name="text">
- <string>Covered Lines:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QLabel" name="nrofCoveredLines">
- <property name="whatsThis">
- <string>Number of covered lines in the selected directories.
-
-Covered lines are those that were executed at least once.</string>
- </property>
- <property name="text">
- <string>-</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="slocTextLabel">
- <property name="whatsThis">
- <string>Total number of lines of code in the selected directories.
-
-Note that it only includes executable lines. That is, things like comments, macros, forward declarations, etc. are not taken into account.</string>
- </property>
- <property name="text">
- <string>Total SLOC:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLabel" name="sloc">
- <property name="whatsThis">
- <string>Total number of lines of code in the selected directories.
-
-Note that it only includes executable lines. That is, things like comments, macros, forward declarations, etc. are not taken into account.</string>
- </property>
- <property name="text">
- <string>-</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <spacer name="horizontalSpacer_2">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>30</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- <item>
- <spacer name="horizontalSpacer_4">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>71</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="Veritas::DrillDownView" name="table">
- <property name="whatsThis">
- <string>Coverage report.
-
-In directory mode, the report summarizes the coverage with a list of all the directories that contain at least one covered file. It could include directories out of the specified path, depending on the files included in the source code.
-
-In file mode, all the files of the selected directory are shown. If several directories are selected, only the files of the last selected directory are shown. Double clicking on any of the items shows the associated file in the editor, annotated with the coverage information.
-
-You can change between directory and file mode using left and right keys.</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KLineEdit</class>
- <extends>QLineEdit</extends>
- <header>klineedit.h</header>
- </customwidget>
- <customwidget>
- <class>Veritas::DrillDownView</class>
- <extends>QTableView</extends>
- <header>drilldownview.h</header>
- <slots>
- <signal>completedSlideLeft()</signal>
- <signal>completedSlideRight()</signal>
- </slots>
- </customwidget>
- </customwidgets>
- <tabstops>
- <tabstop>lcovJobButton</tabstop>
- <tabstop>filterBox</tabstop>
- <tabstop>table</tabstop>
- </tabstops>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp (nonexistent)
@@ -1,133 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "stoppointwidget.h"
-#include "ui_stoppointwidget.h"
-
-#include <KIcon>
-
-using Veritas::ColorRange;
-using Veritas::StopPoint;
-
-StopPointWidget::StopPointWidget(QWidget* parent): QWidget(parent)
-{
- mIndex = -1;
- mMode = ColorRange::Discrete;
-
- mUi = new Ui::StopPointWidget();
- mUi->setupUi(this);
-
- mUi->addButton->setIcon(KIcon("list-add"));
- mUi->removeButton->setIcon(KIcon("list-remove"));
-
- connect(mUi->colorChooser, SIGNAL(changed(QColor)),
- this, SLOT(changeColor(QColor)));
- connect(mUi->percentageSpinBox, SIGNAL(valueChanged(double)),
- this, SLOT(changePosition(double)));
- connect(mUi->addButton, SIGNAL(clicked(bool)),
- this, SLOT(addStopPointAfter()));
- connect(mUi->removeButton, SIGNAL(clicked(bool)),
- this, SLOT(removeStopPoint()));
-}
-
-StopPointWidget::~StopPointWidget()
-{
- delete mUi;
-}
-
-void StopPointWidget::setStopPoint(const StopPoint& stopPoint,
- ColorRange::Mode mode)
-{
- mUi->percentageSpinBox->setValue(stopPoint.first * 100);
- mUi->colorChooser->setColor(stopPoint.second);
-
- if (stopPoint.first == 1) {
- mUi->addButton->setEnabled(false);
- mUi->removeButton->setEnabled(false);
- mUi->percentageSpinBox->setEnabled(false);
- } else if (stopPoint.first == 0 && mode == ColorRange::Gradient) {
- mUi->addButton->setEnabled(true);
- mUi->removeButton->setEnabled(false);
- mUi->percentageSpinBox->setEnabled(false);
- } else {
- mUi->addButton->setEnabled(true);
- mUi->removeButton->setEnabled(true);
- mUi->percentageSpinBox->setEnabled(true);
- }
-
- mMode = mode;
-}
-
-void StopPointWidget::setStopPointIndex(int index)
-{
- mIndex = index;
-}
-
-void StopPointWidget::setRange(double minimum, double maximum)
-{
- if (mUi->percentageSpinBox->value() == 100 ||
- (mUi->percentageSpinBox->value() == 0 &&
- mMode == ColorRange::Gradient)) {
- return;
- }
-
- mUi->percentageSpinBox->setMinimum(minimum * 100 + 0.01);
- mUi->percentageSpinBox->setMaximum(maximum * 100 - 0.01);
-}
-
-void StopPointWidget::setDummy(bool dummy) {
- if (dummy) {
- mUi->horizontalSpacer->changeSize(5, 5, QSizePolicy::Expanding);
- mUi->colorLabel->hide();
- mUi->colorChooser->hide();
- mUi->percentageLabel->hide();
- mUi->percentageSpinBox->hide();
- mUi->removeButton->hide();
- } else {
- mUi->horizontalSpacer->changeSize(0, 0);
- mUi->colorLabel->show();
- mUi->colorChooser->show();
- mUi->percentageLabel->show();
- mUi->percentageSpinBox->show();
- mUi->removeButton->show();
- }
-}
-
-void StopPointWidget::changeColor(const QColor& color)
-{
- emit colorChanged(mIndex, color);
-}
-
-void StopPointWidget::changePosition(double percentage)
-{
- emit positionChanged(mIndex, percentage/100);
-}
-
-void StopPointWidget::addStopPointAfter()
-{
- emit stopPointToAddAfter(mIndex);
-}
-
-void StopPointWidget::removeStopPoint()
-{
- emit stopPointToRemove(mIndex);
-}
-
-#include "stoppointwidget.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/stoppointwidget.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.h (nonexistent)
@@ -1,80 +0,0 @@
-/* KDevelop Coverage lcov settings
-*
-* Copyright 2009 Daniel Calviño Sánchez <danxuliu@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITAS_COVERAGE_COLORRANGEBAR_H
-#define VERITAS_COVERAGE_COLORRANGEBAR_H
-
-#include <QtGui/QWidget>
-
-#include "colorrange.h"
-
-namespace Veritas
-{
-class ColorRange;
-}
-
-/**
- * Graphical representation of a ColorRange.
- * The ColorRangeBar should be updated when the ColorRange is modified. It can
- * be done calling update() slot.
- */
-class ColorRangeBar: public QWidget {
-Q_OBJECT
-public:
-
- /**
- * Creates a new ColorRangeBar for the given ColorRange.
- *
- * @param colorRange The ColorRange to show.
- * @parent The parent widget.
- */
- ColorRangeBar(Veritas::ColorRange* colorRange, QWidget* parent);
-
- /**
- * Paints the ColorRange in this ColorRangeBar.
- */
- virtual void paintEvent(QPaintEvent*);
-
-private:
-
- /**
- * The ColorRange to show.
- */
- Veritas::ColorRange* mColorRange;
-
- /**
- * Paints the ColorRange when it is in discrete mode.
- *
- * @param rectangle The rectanble to paint the ColorRange to.
- * @param painter The painter to use.
- */
- void paintDiscreteColorRange(const QRect& rectangle, QPainter* painter);
-
- /**
- * Paints the ColorRange when it is in gradient mode.
- *
- * @param rectangle The rectanble to paint the ColorRange to.
- * @param painter The painter to use.
- */
- void paintGradientColorRange(const QRect& rectangle, QPainter* painter);
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/colorrangebar.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.cpp (nonexistent)
@@ -1,152 +0,0 @@
-/* KDevelop coverage plugin
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "annotationmanager.h"
-#include "annotationmodel.h"
-#include "coveredfile.h"
-
-#include <interfaces/icore.h>
-#include <interfaces/idocument.h>
-#include <interfaces/idocumentcontroller.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-#include <ktexteditor/annotationinterface.h>
-#include <KDebug>
-
-using KDevelop::ICore;
-using KDevelop::IDocument;
-using KDevelop::IDocumentController;
-using KTextEditor::AnnotationViewInterface;
-
-using Veritas::AnnotationManager;
-using Veritas::AnnotationModel;
-
-namespace Veritas
-{
-
-AnnotationManager::AnnotationManager(QObject* parent)
- : QObject(parent)
-{
- IDocumentController* dc = ICore::self()->documentController();
- connect(dc, SIGNAL(textDocumentCreated(KDevelop::IDocument*)),
- this, SLOT(connectKDocWithTextDoc(KDevelop::IDocument*)));
-}
-
-AnnotationManager::~AnnotationManager()
-{
- foreach(CoveredFile* f, m_files) {
- delete f;
- }
-}
-
-void AnnotationManager::connectKDocWithTextDoc(KDevelop::IDocument* doc)
-{
- if (!m_docs.contains(doc)) return;
- Q_ASSERT(doc->isTextDocument());
- KTextEditor::Document* tdoc = doc->textDocument();
- Q_ASSERT_X(tdoc, "AnnotationManager::watch()", "doc->textDoc() null.");
- m_textDocUrls[tdoc] = doc->url();
- tdoc->disconnect(this);
- connect(tdoc, SIGNAL(viewCreated(KTextEditor::Document*,KTextEditor::View*)),
- this, SLOT(fixAnnotation(KTextEditor::Document*,KTextEditor::View*)));
-}
-
-void AnnotationManager::setCoveredFiles(const QMap<KUrl, CoveredFile*>& files)
-{
- m_files = files;
-}
-
-void AnnotationManager::watch(IDocument* doc)
-{
- Q_ASSERT_X(doc, "AnotationManager::watch()", "got null document.");
- Q_ASSERT(doc->isTextDocument());
- m_docs << doc;
- if (!doc->textDocument()) return;
- m_textDocUrls[doc->textDocument()] = doc->url();
- foreach(KTextEditor::View* view, doc->textDocument()->views()) {
- fixAnnotation(doc->textDocument(), view);
- }
-}
-
-void AnnotationManager::fixAnnotation(KTextEditor::Document* doc, KTextEditor::View* view)
-{
- if (!m_textDocUrls.contains(doc)) {
- kDebug() << "Shouldn't happen, got a doc for which no url was registered.";
- return;
- }
- KUrl url = m_textDocUrls[doc];
- if (!m_files.contains(url)) {
- kDebug() << "No CoveredFile data available for " << url;
- return;
- }
- CoveredFile* f = m_files[url];
- Q_ASSERT(f);
- AnnotationModel* model = new AnnotationModel(f, view);
- AnnotationViewInterface *anno = qobject_cast<AnnotationViewInterface*>(view);
- Q_ASSERT(anno);
- anno->setAnnotationModel(model);
- anno->setAnnotationBorderVisible(true);
-}
-
-void AnnotationManager::stopWatching(IDocument* doc)
-{
- if (!m_docs.contains(doc)) return;
- m_docs.removeOne(doc);
- KTextEditor::Document* tdoc = doc->textDocument();
- Q_ASSERT(tdoc);
- tdoc->disconnect(this);
- foreach(KTextEditor::View* view, tdoc->views()) {
- AnnotationViewInterface* anno = qobject_cast<AnnotationViewInterface*>(view);
- if (!anno) continue;
- anno->setAnnotationBorderVisible(0);
- anno->setAnnotationModel(0);
- }
-}
-
-void AnnotationManager::addCoverageData(CoveredFile* f)
-{
- QMap<int, int> cc = f->callCountMap();
- QMapIterator<int, int> it(cc);
- if (!m_files.contains(f->url())) {
- CoveredFile* cf = new CoveredFile;
- cf->setUrl(f->url());
- while(it.hasNext()) {
- it.next();
- cf->setCallCount(it.key(), it.value());
- }
- m_files[f->url()] = cf;
- } else {
- CoveredFile* cf = m_files[f->url()];
- QSet<int> newLines = f->reachableLines() - cf->reachableLines();
- foreach(int line, newLines) {
- cf->setCallCount(line, 0);
- }
- QMap<int, int> curcc = cf->callCountMap();
- while(it.hasNext()) {
- it.next();
- const int& line = it.key();
- const int& count = it.value();
- cf->setCallCount(line, count + curcc[line]);
- }
- }
-}
-
-}
-
-#include "annotationmanager.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage/annotationmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/coverage
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/coverage (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/coverage (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/coverage
___________________________________________________________________
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevduchainviewer.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt (nonexistent)
@@ -1,35 +0,0 @@
-project(duchainviewer)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${duchainviewer_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9514 )
-
-
-########### next target ###############
-
-set(kdevduchainview_PART_SRCS
- duchainmodel.cpp
- duchainviewplugin.cpp
- duchaintree.cpp
-)
-
-kde4_add_plugin(kdevduchainview ${kdevduchainview_PART_SRCS})
-target_link_libraries(kdevduchainview ${KDEVPLATFORM_LANGUAGE_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS})
-
-install(TARGETS kdevduchainview DESTINATION ${PLUGIN_INSTALL_DIR})
-
-
-########### install files ###############
-
-install(FILES kdevduchainview.desktop DESTINATION ${SERVICES_INSTALL_DIR})
-install(FILES kdevduchainview.rc DESTINATION ${DATA_INSTALL_DIR}/kdevduchainview)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevDUChainView" version="8">
-</kpartgui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.rc
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp (nonexistent)
@@ -1,574 +0,0 @@
-/*
- * KDevelop DUChain viewer
- *
- * Copyright 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "duchainmodel.h"
-
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <ktemporaryfile.h>
-#include <kprocess.h>
-
-#include <interfaces/idocument.h>
-#include <interfaces/icore.h>
-#include <interfaces/ilanguagecontroller.h>
-#include <language/backgroundparser/backgroundparser.h>
-#include <language/backgroundparser/parsejob.h>
-
-#include <language/editor/hashedstring.h>
-
-#include <language/duchain/dumpdotgraph.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/use.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/duchainpointer.h>
-
-#include "duchainviewplugin.h"
-#include <language/duchain/functiondefinition.h>
-
-//#include "modeltest.h"
-
-using namespace KTextEditor;
-using namespace KDevelop;
-
-///When the context is a proxy-context, returns the assigned content-context.
-TopDUContext* getRealContext(TopDUContext* ctx) {
- if(ctx && ctx->parsingEnvironmentFile() && ctx->parsingEnvironmentFile()->isProxyContext() && !ctx->importedParentContexts().isEmpty())
- return dynamic_cast<TopDUContext*>(ctx->importedParentContexts()[0].context(0));
- else
- return ctx;
-}
-
-ProxyObject::ProxyObject(DUChainBase* _parent, DUChainBase* _object)
-: DUChainBase(_object->range())
- , parent(_parent)
- , object(_object)
-{
- setSmartRange(_object->smartRange(), DUChainBase::DontOwn);
-}
-
-DUChainModel::DUChainModel(DUChainViewPlugin* parent)
- : QAbstractItemModel(parent)
- , m_chain(0)
-{
- //new ModelTest(this);
- connect( plugin()->core()->languageController()->backgroundParser(), SIGNAL(parseJobFinished(KDevelop::ParseJob*)), this, SLOT(parseJobFinished(KDevelop::ParseJob*)));
-
- bool success = connect(DUChain::self()->notifier(), SIGNAL(branchAdded(KDevelop::DUContextPointer)), SLOT(branchAdded(KDevelop::DUContextPointer)), Qt::QueuedConnection);
- Q_ASSERT(success);
- #ifdef QT_NO_DEBUG
- Q_UNUSED(success);
- #endif
-}
-
-DUChainViewPlugin* DUChainModel::plugin() const {
- return qobject_cast<DUChainViewPlugin*>(QObject::parent());
-}
-
-DUChainModel::~DUChainModel()
-{
- qDeleteAll(m_knownObjects);
-}
-
-void DUChainModel::parseJobFinished(KDevelop::ParseJob* job)
-{
- if( KUrl(job->document().str()) == m_document && job->duChain() ) {
- setTopContext(TopDUContextPointer(job->duChain()->weakPointer()));
- }
-
-}
-
-void DUChainModel::documentActivated(KDevelop::IDocument* document)
-{
- if (document) {
- DUChainReadLocker readLock(DUChain::lock());
- TopDUContext* ptr = DUChain::self()->chainForDocument(document->url());
- TopDUContextPointer chain(ptr);
- if (chain && chain != m_chain)
- setTopContext(chain);
- else {
- m_document = document->url();
- }
- }
-}
-
-void DUChainModel::setTopContext(TopDUContextPointer context)
-{
- DUChainReadLocker readLock(DUChain::lock());
-
- if( context )
- m_document = KUrl(context->url().str());
- else
- m_document = KUrl();
-
- context = TopDUContextPointer(getRealContext(context.data()));
-
- if (m_chain != context)
- m_chain = context;
-
- qDeleteAll(m_proxyObjects);
- m_proxyObjects.clear();
-
- m_objectLists.clear();
- m_modelRow.clear();
-
- reset();
-}
-
-int DUChainModel::columnCount(const QModelIndex & parent) const
-{
- Q_UNUSED(parent);
-
- return 1;
-}
-
-DUChainBasePointer* DUChainModel::objectForIndex(const QModelIndex& index) const
-{
- return static_cast<DUChainBasePointer*>(index.internalPointer());
-}
-
-QModelIndex DUChainModel::index(int row, int column, const QModelIndex & parent) const
-{
- if (row < 0 || column < 0 || column > 0 || !m_chain)
- return QModelIndex();
-
- if (!parent.isValid()) {
- if (parent.row() > 0 || parent.column() > 0)
- return QModelIndex();
-
- return createIndex(row,column,createPointerForObject(m_chain.data()));
- }
-
- DUChainReadLocker readLock(DUChain::lock());
-
- DUChainBasePointer* base = objectForIndex(parent);
- if (!base || !base->data())
- return QModelIndex();
-
- QList<DUChainBasePointer*>* items = childItems(base);
-
- if (!items)
- return QModelIndex();
-
- if (row >= items->count())
- return QModelIndex();
-
- return createIndex(row, column, items->at(row));
-}
-
-QModelIndex DUChainModel::parent(const QModelIndex & index) const
-{
- if (!index.isValid())
- return QModelIndex();
-
- DUChainReadLocker readLock(DUChain::lock());
-
- DUChainBasePointer* basep = objectForIndex(index);
- if (!basep || !basep->data())
- return QModelIndex();
-
- DUChainBase* base = basep->data();
-
- if (ProxyObject* proxy = dynamic_cast<ProxyObject*>(base))
- return createParentIndex(createPointerForObject(proxy->parent));
-
- if (DUContext* context = dynamic_cast<DUContext*>(base))
- {
- if (context && context->parentContext())
- return createParentIndex(createPointerForObject(context->parentContext()));
- else
- return QModelIndex();
- }
-
- if (Declaration* dec = dynamic_cast<Declaration*>(base))
- return createParentIndex(createPointerForObject(dec->context()));
-
-// if (Use* use = dynamic_cast<Use*>(base))
-// return createParentIndex(createPointerForObject(use->declaration()));
-
- // Shouldn't really hit this
- //Q_ASSERT(false);
- return QModelIndex();
-}
-
-QVariant DUChainModel::data(const QModelIndex& index, int role) const
-{
- if (!index.isValid())
- return QVariant();
-
- DUChainReadLocker readLock(DUChain::lock());
-
- DUChainBasePointer* basep = objectForIndex(index);
- if (!basep || !basep->data())
- return QVariant();
-
- DUChainBase* base = basep->data();
-
- ProxyObject* proxy = dynamic_cast<ProxyObject*>(base);
- if (proxy)
- base = proxy->object;
-
- if(role == Qt::ToolTipRole)
- return i18n("Range: %1:%2 -> %3 %4", base->range().start.line, base->range().start.column, base->range().end.line, base->range().start.column);
-
- if (DUContext* context = dynamic_cast<DUContext*>(base)) {
- switch (role) {
- case Qt::DisplayRole:
- if (proxy)
- return i18n("Imported Context: %1", context->localScopeIdentifier().toString());
- else if (context == m_chain.data())
- return i18n("Top level context");
- else
- return i18n("Context: %1", context->localScopeIdentifier().toString());
- }
-
- } else if (Declaration* dec = dynamic_cast<Declaration*>(base)) {
- switch (role) {
- case Qt::DisplayRole: {
- if(dynamic_cast<FunctionDefinition*>(dec) && static_cast<FunctionDefinition*>(dec)->declaration(m_chain.data()))
- return i18n("Definition: %1", static_cast<FunctionDefinition*>(dec)->declaration(m_chain.data())->identifier().toString());
- else
- return i18n("Declaration: %1", dec->identifier().toString());
- }
- }
-
- }/* else if (Use* use = dynamic_cast<Use*>(base)) {
- switch (role) {
- case Qt::DisplayRole:
- return i18n("Use: %1", use->declaration() ? use->declaration()->identifier().toString() : i18n("[No definition found]"));
- }
-
- }*/ else {
- switch (role) {
- case Qt::DisplayRole:
- return i18n("Unknown object.");
- }
- }
-
- return QVariant();
-}
-
-int DUChainModel::rowCount(const QModelIndex & parent) const
-{
- if (!m_chain)
- return 0;
-
- if (!parent.isValid())
- return 1;
-
- DUChainReadLocker readLock(DUChain::lock());
-
- DUChainBasePointer* base = objectForIndex(parent);
- if (!base || !base->data())
- return 0;
-
- QList<DUChainBasePointer*>* items = childItems(base);
- if (!items)
- return 0;
-
- return items->count();
-}
-
-#define TEST_NEXT(iterator, index) \
- if (!first.isValid()) { \
- current = nextItem(iterator, firstInit); \
- if (current.isValid() && (current < first || !first.isValid())) { \
- first = current; \
- found = index; \
- } \
- }
-
-QList<DUChainBasePointer*>* DUChainModel::childItems(DUChainBasePointer* parentp) const
-{
- Q_ASSERT(parentp->data());
-
- if (m_objectLists.contains(parentp))
- return m_objectLists[parentp];
-
- DUChainBase* parent = parentp->data();
-
- ProxyObject* proxy = dynamic_cast<ProxyObject*>(parent);
- if (proxy)
- parent = proxy->object;
-
- QList<DUChainBasePointer*>* list = 0;
-
- if (DUContext* context = dynamic_cast<DUContext*>(parent)) {
-
- QVector<DUContext*> importedParentContextsData;
- ///@todo Think whether this can be called for top-contexts, and if it can, care about endless recursion because of loops.
- foreach( const DUContext::Import &p, context->importedParentContexts() )
- if( p.context(0) )
- importedParentContextsData << p.context(0);
-
- QVectorIterator<DUContext*> contexts = context->childContexts();
- QVectorIterator<DUContext*> importedParentContexts = importedParentContextsData;
- QVectorIterator<Declaration*> declarations = context->localDeclarations();
-// QListIterator<Use*> uses = context->uses();
-
-
- bool firstInit = true;
- forever {
- DUChainBase* currentItem = 0;
- Cursor first = Cursor::invalid(), current;
- int found = 0;
-
- TEST_NEXT(contexts, 1)
- TEST_NEXT(importedParentContexts, 2)
- TEST_NEXT(declarations, 3)
-
- if (first.isValid()) {
- switch (found) {
- case 1:
- currentItem = item(contexts);
- break;
- case 2:
- currentItem = proxyItem(context, importedParentContexts);
- break;
- case 3:
- currentItem = item(declarations);
- break;
- default:
- Q_ASSERT(false);
- break;
- }
-
- if (!list)
- list = new QList<DUChainBasePointer*>();
-
- DUChainBasePointer* currentPointer = createPointerForObject(currentItem);
- m_modelRow[currentPointer] = list->count();
- list->append(currentPointer);
-
- first = Cursor::invalid();
- } else {
- break;
- }
-
- firstInit = false;
- }
-
- } else if (Declaration* dec = dynamic_cast<Declaration*>(parent)) {
- if (!dec->isDefinition() && FunctionDefinition::definition(dec)) {
- list = new QList<DUChainBasePointer*>();
- list->append(createPointerForObject(FunctionDefinition::definition(dec)));
- }
-
-// foreach (Use* use, dec->uses()) {
-// if (!list)
-// list = new QList<DUChainBasePointer*>();
-//
-// list->append(createPointerForObject(use));
-// }
-
- } else {
- // No child items for definitions or uses
- //kDebug(9500) << "No child items for definitions or uses";
- }
-
- m_objectLists.insert(parentp, list);
-
- return list;
-}
-
-/*bool DUChainModel::hasChildren(const QModelIndex & parent) const
-{
- if (!parent.isValid())
- return true;
-
- DUChainReadLocker readLock(DUChain::lock());
-
- DUChainBase* base = objectForIndex(parent);
- if (!base)
- return false;
-
- if (m_objectLists.contains(base))
- return !m_objectLists[base]->isEmpty();
-
- ProxyObject* proxy = dynamic_cast<ProxyObject*>(base);
- if (proxy)
- base = proxy->object;
-
- if (DUContext* context = dynamic_cast<DUContext*>(base))
- return !context->childContexts().isEmpty() || !context->importedParentContexts().isEmpty() || !context->localDeclarations().isEmpty() || !context->localDefinitions().isEmpty() || !context->uses().isEmpty();
-
- else if (Declaration* dec = dynamic_cast<Declaration*>(base))
- return dec->definition() || !dec->uses().isEmpty();
-
- return false;
-}*/
-
-void DUChainModel::branchAdded(DUContextPointer context)
-{
- DUChainReadLocker readLock(DUChain::lock());
-
- if (!context)
- return;
-
- if (!m_chain || !m_chain->parentContextOf(context.data()))
- return;
-
- DUChainBasePointer* parent = pointerForObject(context->parentContext());
-
- if (!parent || !m_objectLists.contains(parent) || !m_modelRow.contains(parent))
- // No entry for parent, ok - it will be created if the view interrogates for it
- return;
-
- QList<DUChainBasePointer*>* list = childItems(parent);
-
- DUChainBasePointer* contextPointer = createPointerForObject(context.data());
-
- int index = findInsertIndex(*list, context.data());
-
- if (list->at(index) == contextPointer)
- // Already added...
- return;
-
- beginInsertRows(createIndex(m_modelRow[parent], 0, parent), index, index);
- list->insert(index, contextPointer);
- endInsertRows();
-
- // Don't worry about children, they will be queried for if the view needs it
-}
-
-/*switch (relationship) {
- case DUChainObserver::ChildContexts:
- switch (change) {
- case DUChainObserver::Deletion:
- case DUChainObserver::Removal: {
- if (m_objectLists.contains(context)) {
- m_objectLists.remove(context);
- m_knownObjects.remove(ro->data());
- delete ro;
- }
- // fallthrough
- }
- if( *context == m_chain ) {
- //Top-context was deleted
- setTopContext(TopDUContextPointer());
- return;
- }
-
-
- case DUChainObserver::Change: {
- int index = list->indexOf(ro);
- Q_ASSERT(index != -1);
- beginRemoveRows(createIndex(m_modelRow[context], 0, context), index, index);
- list->removeAt(index);
- endRemoveRows();
- if (change == DUChainObserver::Removal || change == DUChainObserver::Deletion)
- break;
- // else fallthrough
- }
-*/
-
-KDevelop::DUChainBasePointer* DUChainModel::pointerForObject(KDevelop::DUChainBase* object) const
-{
- if (m_knownObjects.contains(object))
- return m_knownObjects[object];
-
- return 0L;
-}
-
-KDevelop::DUChainBasePointer* DUChainModel::createPointerForObject(KDevelop::DUChainBase* object) const
-{
- KDevelop::DUChainBasePointer* ret = 0L;
-
- if (!m_knownObjects.contains(object)) {
- ret = new KDevelop::DUChainBasePointer(object->weakPointer());
- m_knownObjects.insert(object, ret);
-
- } else {
- ret = m_knownObjects[object];
- }
-
- return ret;
-}
-
-QModelIndex DUChainModel::createParentIndex(DUChainBasePointer* type) const
-{
- return createIndex(m_modelRow[type], 0, type);
-}
-
-int DUChainModel::findInsertIndex(QList<DUChainBasePointer*>& list, DUChainBase* object) const
-{
- for (int i = 0; i < list.count(); ++i)
- if (DUChainBase* at = list.at(i)->data())
- if (at->range().textRange().start() > object->range().textRange().start())
- return i;
-
- return list.count();
-}
-
-void DUChainModel::doubleClicked ( const QModelIndex & index ) {
- DUChainReadLocker readLock(DUChain::lock());
- if( index.isValid() ) {
- DUChainBase* base = objectForIndex(index)->data();
- DUContext* ctx = dynamic_cast<DUContext*>(base);
- if( base && !ctx && dynamic_cast<Declaration*>(base) )
- ctx = static_cast<Declaration*>(base)->internalContext();
-
- if(ctx) {
- KTemporaryFile tempFile;
-
- {
- QString suffix = (dynamic_cast<TopDUContext*>(ctx) ?
- static_cast<TopDUContext*>(ctx)->url().str()
- : ctx->localScopeIdentifier().toString());
- suffix = suffix.replace('/', '_');
- suffix = suffix.replace(':', '.');
- suffix = suffix.replace(' ', '_');
- suffix += ".temp.dot";
- tempFile.setSuffix( suffix );
-
- if( !tempFile.open() ) {
- readLock.unlock();
- KMessageBox::error(0, i18n("Cannot create temporary file \"%1\" with suffix \"%2\"", tempFile.fileName(), suffix));
- return;
- }
- DumpDotGraph dump;
- tempFile.write( dump.dotGraph( ctx ).toLocal8Bit() ); //Shorten if it is a top-context, because it would become too much output
- }
-
- tempFile.setAutoRemove(false);
- QString fileName = tempFile.fileName();
- tempFile.close();
- kDebug(9500) << "Wrote dot-graph of context " << ctx << " into " << fileName;
- KProcess proc; ///@todo this is a simple hack. Maybe do it with mime-types etc.
- proc << "kgraphviewer" << fileName;
- if( !proc.startDetached() ) {
- KProcess proc2;
- proc2 << "dotty" << fileName;
- if( !proc2.startDetached() ) {
- readLock.unlock();
- KMessageBox::error(0, i18n("Could not open %1 with kgraphviewer or dotty.", fileName));
- }
- }
-
- }
- }
-}
-
-#include "duchainmodel.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h (nonexistent)
@@ -1,140 +0,0 @@
-/*
- * KDevelop DUChain viewer
- *
- * Copyright 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef DUCHAINMODEL_H
-#define DUCHAINMODEL_H
-
-#include <QtCore/QAbstractItemModel>
-#include <QtCore/QHash>
-
-#include <ktexteditor/cursor.h>
-#include <kurl.h>
-
-#include <language/duchain/duchainbase.h>
-#include <language/duchain/duchainobserver.h>
-
-class DUChainViewPlugin;
-
-namespace KDevelop {
- class TopDUContext;
- class IDocument;
- class ParseJob;
-}
-
-class ProxyObject : public KDevelop::DUChainBase
-{
-public:
- ProxyObject(KDevelop::DUChainBase* _parent, KDevelop::DUChainBase* _object);
-
- virtual void preDelete() {};
-
- KDevelop::DUChainBase* parent;
- KDevelop::DUChainBase* object;
-};
-
-class DUChainModel : public QAbstractItemModel
-{
- Q_OBJECT
-
-public:
- DUChainModel(DUChainViewPlugin* parent);
- virtual ~DUChainModel();
-
- void setTopContext(KDevelop::TopDUContextPointer context);
-
- KDevelop::DUChainBasePointer* objectForIndex(const QModelIndex& index) const;
-
-public Q_SLOTS:
- void documentActivated(KDevelop::IDocument* document);
- void parseJobFinished(KDevelop::ParseJob* job);
-
-public:
- virtual int columnCount(const QModelIndex & parent = QModelIndex()) const;
- virtual QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const;
- virtual QModelIndex parent(const QModelIndex & index) const;
- virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
- virtual int rowCount(const QModelIndex & parent = QModelIndex()) const;
- //virtual bool hasChildren(const QModelIndex & parent = QModelIndex()) const;
-
-private slots:
- void doubleClicked ( const QModelIndex & index );
-
- // Watch definition use chain changes
- void branchAdded(KDevelop::DUContextPointer context);
-
-private:
- DUChainViewPlugin* plugin() const;
-
- int findInsertIndex(QList<KDevelop::DUChainBasePointer*>& list, KDevelop::DUChainBase* object) const;
-
- QModelIndex createParentIndex(KDevelop::DUChainBasePointer* type) const;
-
- template <typename T>
- KTextEditor::Cursor nextItem(QVectorIterator<T*>& it, bool initialise) const
- {
- if (initialise)
- if (it.hasNext())
- it.next();
-
- if (it.hasPrevious())
- return it.peekPrevious()->range().textRange().start();
-
- return KTextEditor::Cursor::invalid();
- }
-
- template <typename T>
- KDevelop::DUChainBase* item(QVectorIterator<T*>& it) const
- {
- Q_ASSERT(it.hasPrevious());
- KDevelop::DUChainBase* item = it.peekPrevious();
- if (it.hasNext())
- it.next();
- else
- // Make hasPrevious return false
- it.toFront();
-
- return item;
- }
-
- template <typename T>
- KDevelop::DUChainBase* proxyItem(KDevelop::DUChainBase* parent, QVectorIterator<T*>& it) const
- {
- KDevelop::DUChainBase* target = item(it);
- KDevelop::DUChainBase* proxy = new ProxyObject(parent, target);
- m_proxyObjects.insert(target, createPointerForObject(proxy));
- return proxy;
- }
-
- QList<KDevelop::DUChainBasePointer*>* childItems(KDevelop::DUChainBasePointer* parent) const;
- KDevelop::DUChainBasePointer* pointerForObject(KDevelop::DUChainBase* object) const;
- KDevelop::DUChainBasePointer* createPointerForObject(KDevelop::DUChainBase* object) const;
-
- KDevelop::TopDUContextPointer m_chain;
- KUrl m_document;
- mutable QHash<KDevelop::DUChainBase*, KDevelop::DUChainBasePointer*> m_knownObjects;
- mutable QHash<KDevelop::DUChainBasePointer*, QList<KDevelop::DUChainBasePointer*>* > m_objectLists;
- mutable QHash<KDevelop::DUChainBasePointer*, int > m_modelRow;
- mutable QHash<KDevelop::DUChainBase*, KDevelop::DUChainBasePointer*> m_proxyObjects;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.cpp (nonexistent)
@@ -1,73 +0,0 @@
-/*
- * KDevelop DUChain viewer
- *
- * Copyright (c) 2007 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "duchaintree.h"
-
-#include <QHeaderView>
-
-#include <klocale.h>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-#include <language/duchain/duchainbase.h>
-
-#include "duchainmodel.h"
-#include "duchainviewplugin.h"
-
-using namespace KDevelop;
-
-DUChainTree::DUChainTree(QWidget* parent, DUChainViewPlugin* plugin)
- : QTreeView(parent)
- , mplugin(plugin)
-{
- setObjectName("DUChain Viewer Tree");
- setWindowTitle(i18n("Definition-Use Chain"));
- setModel(mplugin->model());
- header()->hide();
-
- connect(this, SIGNAL(activated(const QModelIndex&)), SLOT(contextActivated(const QModelIndex&)));
-}
-
-DUChainTree::~DUChainTree()
-{
-}
-
-DUChainModel* DUChainTree::model()
-{
- return mplugin->model();
-}
-
-void DUChainTree::contextActivated(const QModelIndex& index)
-{
- DUChainBasePointer* base = model()->objectForIndex(index);
- if (base && base->data()) {
- IDocument* doc = mplugin->core()->documentController()->activeDocument();
- doc->textDocument()->activeView()->setSelection((*base)->range().textRange());
- }
-}
-
-// kate: space-indent on; indent-width 2; tab-width: 4; replace-tabs on; auto-insert-doxygen on
-
-#include "duchaintree.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h (nonexistent)
@@ -1,51 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright 2006 Adam Treat <treat@kde.org>
- * Copyright 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef DUCHAINVIEW_PART_H
-#define DUCHAINVIEW_PART_H
-
-#include <interfaces/iplugin.h>
-#include <QtCore/QVariant>
-
-class DUChainModel;
-
-class DUChainViewPlugin : public KDevelop::IPlugin
-{
- Q_OBJECT
-
-public:
- DUChainViewPlugin(QObject *parent, const QVariantList & = QVariantList() );
- virtual ~DUChainViewPlugin();
-
- // KDevelop::Plugin methods
- virtual void unload();
-
- DUChainModel* model() const;
-
-private:
- DUChainModel* m_model;
- class DUChainViewFactory* m_factory;
-};
-
-#endif // DUCHAINVIEW_PART_H
-
-// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchaintree.h (nonexistent)
@@ -1,56 +0,0 @@
-/*
- * KDevelop DUChain viewer
- *
- * Copyright (c) 2007 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef DUCHAINTREE_H
-#define DUCHAINTREE_H
-
-#include <QtGui/QTreeView>
-
-#include <language/duchain/duchainbase.h>
-#include <language/duchain/duchainobserver.h>
-
-class DUChainViewPlugin;
-
-namespace KDevelop {
- class TopDUContext;
- class IDocument;
-}
-
-class DUChainTree : public QTreeView
-{
- Q_OBJECT
-
-public:
- DUChainTree(QWidget* parent, DUChainViewPlugin* plugin);
- virtual ~DUChainTree();
-
- class DUChainModel* model();
-
-private Q_SLOTS:
- void contextActivated(const QModelIndex& index);
-
-private:
- DUChainViewPlugin* mplugin;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width: 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop (nonexistent)
@@ -1,72 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=This plugin displays a graphical view of the definition-use chain produced by the C++ support
-Comment[bs]=Ovaj dodatak prikazuje grafički prikaz definicije lanca upotrebe, izrađenog od strane C++ podrške
-Comment[ca]=Aquest connector mostra una vista gràfica de la cadena de definició-ús produïda per la implementació del llenguatge C++
-Comment[ca@valencia]=Aquest connector mostra una vista gràfica de la cadena de definició-ús produïda per la implementació del llenguatge C++
-Comment[de]=Dieses Modul zeigt eine grafische Ansicht der Definition-Use-Chain, die durch die Unterstützung für C++ erzeugt wurde.
-Comment[en_GB]=This plugin displays a graphical view of the definition-use chain produced by the C++ support
-Comment[es]=Este complemento muestra una vista gráfica de la cadena definición-uso producida por la implementación de C++
-Comment[et]=See plugin näitab graafiliselt C++ toetusel loodud definitsiooni-kasutuse ahelat.
-Comment[fr]=Ce module externe affiche une vue graphique de la chaîne définition-utilisation produite par la prise en charge du C++
-Comment[gl]=Este complemento mostra unha vista gráfica da cadea de definicións e usos producida pola compatibilidade con C++.
-Comment[it]=Questa estensione mostra graficamente la definition-use chain (DUChain) prodotta dal supporto per il linguaggio C++.
-Comment[nl]=Deze plugin geeft een grafische weergave van door C++ ondersteuning geproduceerde definition-use Chain
-Comment[pl]=Wtyczka ta wyświetla widok graficzny łańcucha definicji-użycia wyprodukowany przez obsługę C++
-Comment[pt]=Este 'plugin' apresenta uma vista gráfica sobre a sequência de definições-usos que é produzida pelo componente da linguagem C++
-Comment[pt_BR]=Este plugin apresenta uma vista gráfica sobre a sequência de definições-usos que é produzida pelo suporte ao C++
-Comment[sv]=Insticksprogrammet visar en grafisk vy av definition-användningskedjan skapad av C++ stödet.
-Comment[uk]=За допомогою цього додатка можна переглянути у графічному вигляді ланцюжок «Визначення-Використання», створений частиною, що відповідає за мову програмування C++.
-Comment[x-test]=xxThis plugin displays a graphical view of the definition-use chain produced by the C++ supportxx
-Name=DUChain View
-Name[bs]=DUChain pregled
-Name[ca]=Visualització de cadena DU
-Name[ca@valencia]=Visualització de cadena DU
-Name[de]=DUChain-Ansicht
-Name[en_GB]=DUChain View
-Name[es]=Vista DUChain
-Name[et]=DU-ahela vaade
-Name[fr]=Affichage DUChain
-Name[ga]=Amharc DUChain
-Name[gl]=Vista de DUChain
-Name[it]=Vista DUChain
-Name[nl]=DUChain weergave
-Name[pl]=Widok DUChain
-Name[pt]=Área de Definições-Usos
-Name[pt_BR]=Área de Definições-Usos
-Name[sk]=Prehliadať DUChain
-Name[sv]=Visning av definition-användningskedja
-Name[uk]=Перегляд ВВ-ланцюжка
-Name[x-test]=xxDUChain Viewxx
-GenericName=DUChain View
-GenericName[bs]=DUChain pregled
-GenericName[ca]=Visualització de cadena DU
-GenericName[ca@valencia]=Visualització de cadena DU
-GenericName[de]=DUChain-Ansicht
-GenericName[en_GB]=DUChain View
-GenericName[es]=Vista DUChain
-GenericName[et]=DU-ahela vaade
-GenericName[fr]=Afficheur DUChain
-GenericName[ga]=Amharc DUChain
-GenericName[gl]=Vista de DUChain
-GenericName[it]=Vista DUChain
-GenericName[ja]=DUChain ビュー
-GenericName[nds]=Dbkeed-Ansicht
-GenericName[nl]=DUChain weergave
-GenericName[pl]=Widok DUChain
-GenericName[pt]=Área de Definições-Usos
-GenericName[pt_BR]=Área de Definições-Usos
-GenericName[sk]=Prehliadať DUChain
-GenericName[sv]=Visning av definition-användningskedja
-GenericName[tr]=DUChain Görünümü
-GenericName[uk]=Перегляд ВВ-ланцюжка
-GenericName[x-test]=xxDUChain Viewxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevduchainview
-X-KDevelop-Version=7
-X-KDevelop-Category=Project
-X-KDE-PluginInfo-Name=kdevduchainview
-X-KDE-PluginInfo-Author=Hamish Rodda
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Mode=GUI
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/kdevduchainview.desktop
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp (nonexistent)
@@ -1,93 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright 2006 Adam Treat <treat@kde.org>
- * Copyright 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "duchainviewplugin.h"
-#include "duchainmodel.h"
-#include "duchaintree.h"
-
-#include <klocale.h>
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-#include <kaboutdata.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-#include <interfaces/idocumentcontroller.h>
-
-K_PLUGIN_FACTORY(KDevDUChainViewFactory, registerPlugin<DUChainViewPlugin>(); )
-K_EXPORT_PLUGIN(KDevDUChainViewFactory(KAboutData("kdevduchainview","kdevduchainviewer",ki18n("DUChain View"), "0.1", ki18n("A simple tool to view the raw DUChain"), KAboutData::License_GPL)))
-
-class DUChainViewFactory: public KDevelop::IToolViewFactory
-{
-public:
- DUChainViewFactory(DUChainViewPlugin *plugin): mplugin(plugin) {}
-
- virtual QWidget* create(QWidget *parent = 0)
- {
- QTreeView* view = new DUChainTree(parent, mplugin);
- QObject::connect(view, SIGNAL(doubleClicked(const QModelIndex &)), mplugin->model(), SLOT(doubleClicked(const QModelIndex &)));
- return view;
- }
-
- virtual Qt::DockWidgetArea defaultPosition()
- {
- return Qt::RightDockWidgetArea;
- }
-
- virtual QString id() const
- {
- return "org.kdevelop.DUChainView";
- }
-
-private:
- DUChainViewPlugin *mplugin;
-};
-
-DUChainViewPlugin::DUChainViewPlugin(QObject *parent,
- const QVariantList&)
- : KDevelop::IPlugin(KDevDUChainViewFactory::componentData(), parent)
- , m_model(new DUChainModel(this))
- , m_factory(new DUChainViewFactory(this))
-{
- core()->uiController()->addToolView(i18n("DUChain Viewer"), m_factory);
- setXMLFile( "kdevduchainview.rc" );
-
- connect(core()->documentController(), SIGNAL(documentActivated(KDevelop::IDocument*)), m_model, SLOT(documentActivated(KDevelop::IDocument*)));
-}
-
-DUChainViewPlugin::~DUChainViewPlugin()
-{
-}
-
-void DUChainViewPlugin::unload()
-{
- core()->uiController()->removeToolView(m_factory);
-}
-
-DUChainModel* DUChainViewPlugin::model() const
-{
- return m_model;
-}
-
-#include "duchainviewplugin.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 4; replace-tabs on; auto-insert-doxygen on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/duchainviewer/duchainviewplugin.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevgettersetter.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/CMakeLists.txt (nonexistent)
@@ -1,45 +0,0 @@
-PROJECT(kdevgettersetter)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${kdevgettersetter_SOURCE_DIR}/cmake)
-
-add_definitions(-DKDE_DEFAULT_DEBUG_AREA=9525)
-
-set(KDE_MIN_VERSION "4.2.0")
-
-
-find_package(KDE4 4.2.0 REQUIRED)
-find_package(KDevPlatform 0.9.95 REQUIRED)
-
-include (KDE4Defaults)
-
-add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS} -DHAVE_CONFIG_H=1)
-
-include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR} )
-
-set(kdevgettersetter_PART_SRCS
- gettersetterplugin.cpp
- propertynode.cpp
- propertymodel.cpp
- propertiesdialog.cpp
- propertydelegate.cpp
- cpppropertycreator.cpp
- javapropertycreator.cpp
- csharppropertycreator.cpp
-)
-kde4_add_ui_files( kdevgettersetter_PART_SRCS propertiesform.ui )
-
-kde4_add_plugin(kdevgettersetter ${kdevgettersetter_PART_SRCS})
-
-
-target_link_libraries(kdevgettersetter
- ${KDE4_KDEUI_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
-)
-
-install(TARGETS kdevgettersetter DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-
-########### install files ###############
-install( FILES kdevgettersetter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevgettersetter.rc DESTINATION ${DATA_INSTALL_DIR}/kdevgettersetter )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.desktop (nonexistent)
@@ -1,74 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=Generate reader-writer / getter-setter properties
-Comment[bs]=Generiši čitač-pisač/"dostavljač"-postavljač svojstava
-Comment[ca]=Genera propietats reader-writer / getter-setter
-Comment[ca@valencia]=Genera propietats reader-writer / getter-setter
-Comment[de]=Reader-Writer/Getter-Setter-Eigenschaften erzeugen
-Comment[en_GB]=Generate reader-writer / getter-setter properties
-Comment[es]=Generar propiedades de lectura-escritura / obtener-fijar
-Comment[et]=Lugeja-kirjutaja / tagastaja-seadja omaduste genereerimine
-Comment[fr]=Génère les propriétés des méthodes lecteur-scripteur / accesseur-mutateur
-Comment[gl]=Xerar propiedades de lectura e escritura
-Comment[hu]=Olvasó-író / lekérő-beállító tulajdonságok előállítása
-Comment[it]=Genera proprietà reader-writer / getter-setter
-Comment[nl]=Genereert lees-schrijf / getter-setter eigenschappen
-Comment[pl]=Generuj właściwości programu czytająco-zapisującego / pobierająco-ustawiającego
-Comment[pt]=Gerar propriedades de leitura-escrita / 'get'-'set'
-Comment[pt_BR]=Gerar propriedades de leitura-escrita / 'get'-'set'
-Comment[sk]=Vygenerovať vlastnosti čítača-zapisovača / gettera-settera
-Comment[sv]=Skapa läs-skriv och hämta-tilldela egenskaper
-Comment[uk]=Створення записів властивостей читання-запису / отримання-встановлення
-Comment[x-test]=xxGenerate reader-writer / getter-setter propertiesxx
-Name=Getter & Setter
-Name[bs]="čitač"-postavljač
-Name[ca]=Getter i Setter
-Name[ca@valencia]=Getter i Setter
-Name[de]=Getter & Setter
-Name[en_GB]=Getter & Setter
-Name[es]=«Getter» y «setter»
-Name[et]=Getter ja Setter
-Name[fr]=Accesseur et mutateur
-Name[gl]=Lector e escritor
-Name[hu]=Lekérő és beállító
-Name[it]=Getter e Setter
-Name[nl]=Getter & Setter
-Name[pl]=Pobieranie & Ustawianie
-Name[pt]='Get' & 'Set'
-Name[pt_BR]='Get' & 'Set'
-Name[sv]=&Hämta-tilldela
-Name[uk]=Отримання і встановлення
-Name[x-test]=xxGetter & Setterxx
-GenericName=Generate reader-writer / getter-setter properties
-GenericName[bs]=Generiši čitač-pisač/"preuzimač-postavljač svojstava
-GenericName[ca]=Genera propietats reader-writer / getter-setter
-GenericName[ca@valencia]=Genera propietats reader-writer / getter-setter
-GenericName[de]=Reader-Writer/Getter-Setter-Eigenschaften erzeugen
-GenericName[en_GB]=Generate reader-writer / getter-setter properties
-GenericName[es]=Generar propiedades de lectura-escritura / obtener-fijar
-GenericName[et]=Lugeja-kirjutaja / tagastaja-seadja omaduste genereerimine
-GenericName[fr]=Génère les propriétés des méthodes lecteur-scripteur / accesseur-mutateur
-GenericName[gl]=Xerar propiedades de lectura e escritura
-GenericName[hu]=Olvasó-író / lekérő-beállító tulajdonságok előállítása
-GenericName[it]=Genera proprietà reader-writer / getter-setter
-GenericName[nl]=Genereert lees-schrijf / getter-setter eigenschappen
-GenericName[pl]=Generuj właściwości programu czytająco-zapisującego / pobierająco-ustawiającego
-GenericName[pt]=Gerar propriedades de leitura-escrita / 'get'-'set'
-GenericName[pt_BR]=Gerar propriedades de leitura-escrita / 'get'-'set'
-GenericName[sk]=Vygenerovať vlastnosti čítača-zapisovača / gettera-settera
-GenericName[sv]=Skapa läs-skriv och hämta-tilldela egenskaper
-GenericName[uk]=Створення записів властивостей читання-запису / отримання-встановлення
-GenericName[x-test]=xxGenerate reader-writer / getter-setter propertiesxx
-Icon=kdevelop
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevgettersetter
-X-KDE-PluginInfo-Name=kdevgettersetter
-X-KDE-PluginInfo-Author=Ruan Strydom
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=8
-X-KDevelop-Category=Global
-X-KDevelop-Mode=GUI
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/kdevgettersetter.rc (nonexistent)
@@ -1,9 +0,0 @@
-<!DOCTYPE kpartgui>
-<kpartgui name="kdevgettersetter" version="1">
-<MenuBar>
- <Menu name="edit" >
- <text context="@title:menu">Edit</text>
- <Action name="generate_gettersetter" group="edit_formatting"/>
- </Menu>
-</MenuBar>
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.h (nonexistent)
@@ -1,141 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#ifndef PROPERTYMODEL_H
-#define PROPERTYMODEL_H
-
-#include <QtCore/QAbstractTableModel>
-#include <QtCore/QModelIndex>
-#include <QtCore/QVariant>
-#include <QtCore/QString>
-
-
-#include "propertynode.h"
-
-using namespace KDevelop;
-
-namespace KDevelop
-{
-class ClassDeclaration ;
-class ClassMemberDeclaration ;
-}
-
-class PropertiesDialog;
-
-/** Stores property selection/display info and a handle to the class in question.
- * Use PropertyCreator to populate and ProperiesDialog to display.
- */
-class PropertyModel : public QAbstractTableModel
-{
- Q_OBJECT
-
- friend class PropertiesDialog;
-public:
-
- PropertyModel (QObject *parent = 0);
- ~PropertyModel();
-
- enum Modifier {FINAL, VIRTUAL, PURE_VIRTUAL, INLINE};
-
- virtual int columnCount (const QModelIndex& parent = QModelIndex()) const
- {
- Q_UNUSED (parent);
- return 7;
- }
-
- virtual QVariant data (const QModelIndex& index, int role = Qt::DisplayRole) const;
-
- virtual bool setData (const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
-
- virtual int rowCount (const QModelIndex& parent = QModelIndex()) const
- {
- Q_UNUSED (parent);
- return m_nodes.size();
- }
-
- virtual QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
-
-
- virtual Qt::ItemFlags flags (const QModelIndex& index) const;
-
- virtual bool createQtProperties() const
- {
- return m_createQtProperties;
- }
-
- virtual bool hasQObject() const
- {
- return m_hasQObject;
- }
-
- const QList< PropertyNode >& nodes() const
- {
- return m_nodes;
- }
-
- void setNodes (const QList< PropertyNode > &n)
- {
- m_nodes = n;
- }
-
- void setHasQObject (bool hq)
- {
- m_hasQObject = hq;
- }
-
- void setCreateQtProperties (bool cqp)
- {
- m_createQtProperties = cqp;
- }
-
- Modifier modifier() const
- {
- return m_modifier;
- }
-
- void setModifier (Modifier m)
- {
- m_modifier = m;
- }
-
- bool createDocumentation() const
- {
- return m_createDocumentation;
- }
-
- void setCreateDocumentation (bool cd)
- {
- m_createDocumentation = cd;
- }
-
-
- virtual KDevelop::ClassDeclaration* klass() const { return m_klass; }
-
- virtual void setKlass ( KDevelop::ClassDeclaration* k ) { m_klass = k; }
-protected:
- QList<PropertyNode> m_nodes;
- bool m_hasQObject;
- bool m_createQtProperties;
- bool m_createDocumentation;
- Modifier m_modifier;
- ClassDeclaration * m_klass;
-};
-
-#endif // PROPERTYMODEL_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.cpp (nonexistent)
@@ -1,90 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#include "propertydelegate.h"
-
-AccessListDelegate::AccessListDelegate (QObject *parent) : QItemDelegate (parent)
-{
-}
-
-QWidget * AccessListDelegate::createEditor (QWidget *parent, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
-{
- Q_UNUSED (index);
- Q_UNUSED (option);
- QComboBox * box = new QComboBox (parent);
- populateList (box);
- box->setAutoFillBackground (true);
- return box;
-}
-
-void AccessListDelegate::setEditorData (QWidget *editor, const QModelIndex &index) const
-{
- QComboBox * box = dynamic_cast<QComboBox *> (editor);
- if (!box)
- {
- kDebug() << "Null editor";
- return;
- }
-
- //Selected
- QVariant sel = index.model()->data (index, Qt::EditRole);
- box->setCurrentIndex (box->findData (sel, Qt::DisplayRole));
-
-}
-void AccessListDelegate::setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
-{
- QComboBox * box = dynamic_cast<QComboBox *> (editor);
- if (!box)
- {
- kDebug() << "Null editor";
- return;
- }
-
- QVariant var = box->itemData (box->currentIndex(), Qt::DisplayRole);
- if (!var.isValid())
- return;
-
- model->setData (index, var, Qt::EditRole);
-}
-
-void AccessListDelegate::updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
- Q_UNUSED (index);
- QComboBox * box = dynamic_cast<QComboBox *> (editor);
- if (!box)
- {
- kDebug() << "Null editor";
- return;
- }
- QRect r = option.rect;
- r.setWidth (box->contentsRect().width());
- box->setGeometry (r);
-}
-
-void AccessListDelegate::populateList (QComboBox * box) const
-{
- box->insertItem (0,"public");
- box->setItemData (0, "public", Qt::DisplayRole);
- box->insertItem (1,"protected");
- box->setItemData (1, "protected", Qt::DisplayRole);
- box->insertItem (2,"private");
- box->setItemData (2, "private", Qt::DisplayRole);
-}
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.h (nonexistent)
@@ -1,55 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#ifndef PROPERTIESDIALOG_H
-#define PROPERTIESDIALOG_H
-
-#include <KDialog>
-
-class PropertyModel;
-namespace Ui
-{
-class propertiesForm;
-}
-class PropertiesDialog : public KDialog
-{
- Q_OBJECT
-
-public:
- explicit PropertiesDialog (QWidget* parent = 0, Qt::WFlags flags = 0);
- virtual ~PropertiesDialog();
- void show (PropertyModel * model);
- void setModel (PropertyModel * model);
- PropertyModel * model()
- {
- return m_model;
- }
-public slots:
- void selectAll();
- void deselectAll();
- void createQtProperties (bool create);
- void createDocumentation (bool create);
- void changeModifier (int index);
-protected:
- Ui::propertiesForm * m_form;
- PropertyModel *m_model;
-};
-
-#endif // PROPERTIESDIALOG_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.cpp (nonexistent)
@@ -1,49 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#include "propertynode.h"
-#include "propertymodel.h"
-
-#include <QtCore/QRegExp>
-
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainutils.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/classdeclaration.h>
-#include <language/duchain/classmemberdeclaration.h>
-#include <KMessageBox>
-
-PropertyNode::PropertyNode ()
-{
- m_createGetter = false;
- m_createSetter = false;
- m_canCreateGetter = true;
- m_canCreateSetter = true;
- m_getterAccess = "public";
- m_setterAccess = "public";
-}
-
-PropertyNode::~PropertyNode()
-{
-
-}
-
-
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.h (nonexistent)
@@ -1,30 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef CSHARPPROPERTYCREATOR_H
-#define CSHARPPROPERTYCREATOR_H
-
-#include <propertcreator.h>
-
-
-class CSharpPropertyCreator : public PropertyCreator
-{
- virtual void create(PropertyModel* m);
- virtual bool parse(PropertyModel* m, QList< KDevelop::Declaration* > selection);
-};
-
-#endif // CSHARPPROPERTYCREATOR_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertcreator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertcreator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertcreator.h (nonexistent)
@@ -1,43 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef PROPERTYCREATOR_H
-#define PROPERTYCREATOR_H
-
-#include <QtCore/QList>
-
-class PropertyModel;
-
-namespace KDevelop
-{
-class DUContext;
-class Declaration;
-}
-
-using namespace KDevelop;
-
-class PropertyCreator
-{
-public:
- virtual ~PropertyCreator() {};
- virtual bool parse (PropertyModel * m, QList<Declaration*> selection) = 0;
- virtual void create (PropertyModel * m) = 0;
-};
-
-#endif //PROPERTYCREATOR_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.cpp (nonexistent)
@@ -1,231 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#include "gettersetterplugin.h"
-
-#include <interfaces/icore.h>
-#include <interfaces/contextmenuextension.h>
-#include <interfaces/context.h>
-#include <interfaces/idocument.h>
-#include <interfaces/iuicontroller.h>
-#include <interfaces/idocumentcontroller.h>
-
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainutils.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/classdeclaration.h>
-#include <language/duchain/classmemberdeclaration.h>
-#include <shell/sourceformattercontroller.h>
-#include <interfaces/isourceformatter.h>
-
-#include <KPluginFactory>
-#include <KPluginLoader>
-#include <KLocalizedString>
-#include <KAboutData>
-#include <KTextEditor/Document>
-#include <KDebug>
-#include <KMessageBox>
-#include <KActionCollection>
-#include <KAction>
-#include <KTextEditor/SmartCursor>
-
-#include <QtCore/QPair>
-#include <QtCore/QList>
-
-#include "propertiesdialog.h"
-#include "propertymodel.h"
-#include "cpppropertycreator.h"
-#include "javapropertycreator.h"
-#include "csharppropertycreator.h"
-
-
-#define ERROR_MESSAGE ({KMessageBox::error(NULL, i18n(QString("An error occured while parsing the class. Please log a report. File: %1 Line: %2").arg(__FILE__).arg(__LINE__).toAscii().constData()));});
-
-K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<GetterSetterPlugin>();)
-K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("GetterSetter","GetterSetter", ki18n ("Generate reader-writer / getter-setter properties"), "0.1", ki18n ("Generate reader-writer / getter-setter properties"), KAboutData::License_GPL)))
-
-GetterSetterPlugin::GetterSetterPlugin (QObject *parent, const QVariantList &)
- :IPlugin (KdevPlugFactory::componentData(), parent)
-{
- setXMLFile ("gettersetter.rc");
-
- m_action = actionCollection()->addAction ("generate_gettersetter");
- //m_action->setIcon (KIcon ("kdevelop"));
- m_action->setText (i18n ("Generate properties.."));
- m_action->setShortcut (KShortcut ("Ctrl+Alt+p"));
- connect (m_action, SIGNAL (triggered (bool)), this, SLOT (slotCreateProperties()));
- m_action->setToolTip (i18n ("Generate reader-writer/getter-setter properties"));
- m_action->setWhatsThis (i18n ("<b>GetterSetter</b><p> Generate reader-writer/getter-setter properties"));
- m_action->setEnabled (false);
-}
-
-GetterSetterPlugin::~GetterSetterPlugin()
-{
-}
-
-void GetterSetterPlugin::slotCreateProperties()
-{
- DUChainReadLocker lock (DUChain::lock());
-
- QList<Declaration*> decls = cursorItemDeclarations();
- if (decls.size() < 1)
- {
- KMessageBox::information (0, i18n ("No valid declaration in selection.\nIt is possible that the parser is still busy."));
- return;
- }
-
- createProperties (decls);
-}
-
-void GetterSetterPlugin::createProperties (QList<Declaration*> decls)
-{
- DUChainReadLocker lock (DUChain::lock());
- static PropertiesDialog *d = ({
- PropertiesDialog *d = new PropertiesDialog ( (QWidget *) ICore::self()->uiController()->activeMainWindow());
- connect (d, SIGNAL (okClicked()), this, SLOT (slotWriteProperties()));
- d;
- });
- static PropertyModel *m = new PropertyModel;
-
- if (d->isVisible())
- return;
-
- if(decls.size() == 0)
- return;
-
- IDocument* doc = ICore::self()->documentController()->documentForUrl ( decls[0]->url().toUrl() );
- if ( !doc )
- {
- ERROR_MESSAGE
- return;
- }
-
- PropertyCreator * pc = creatorForMime(doc->mimeType());
- if(!pc)
- return;
-
- if(!pc->parse (m, decls))
- return;
-
- d->setCaption (i18n ("Class: ") + m->klass()->identifier().toString());
- d->setModal (false);
- d->show (m);
-}
-
-void GetterSetterPlugin::slotWriteProperties()
-{
- PropertiesDialog *d = dynamic_cast<PropertiesDialog *> (this->sender());
- if (!d)
- {
- ERROR_MESSAGE
- kDebug() << "sender() not instance of PropertiesDialog";
- return;
- }
- IDocument* doc = ICore::self()->documentController()->documentForUrl ( d->model()->klass()->url().toUrl() );
- if ( !doc )
- {
- ERROR_MESSAGE
- return;
- }
-
- PropertyCreator * pc = creatorForMime(doc->mimeType());
- if(!pc)
- return;
- pc->create (d->model());
-}
-
-ContextMenuExtension GetterSetterPlugin::contextMenuExtension (Context* context)
-{
- Q_UNUSED (context);
-
- DUChainReadLocker lock (DUChain::lock());
- ContextMenuExtension ext;
- m_action->setEnabled (false);
- QList<Declaration *> decls = cursorItemDeclarations();
- if (decls.size() > 0) {
- m_action->setEnabled (true);
- ext.addAction (ContextMenuExtension::EditGroup, m_action);
- }
- return ext;
-}
-
-QList<Declaration*> GetterSetterPlugin::cursorItemDeclarations()
-{
- QList<Declaration*> list;
- IDocument* doc = ICore::self()->documentController()->activeDocument();
- if (!doc)
- return list;
-
- if(!creatorForMime(doc->mimeType())) {
- return list;
- }
-
- KTextEditor::Document* textDoc = doc->textDocument();
- if (!textDoc)
- return list;
-
- KTextEditor::View* view = textDoc->activeView();
- if (!view)
- return list;
-
- if(view->selection()) {
- KTextEditor::Range r = view->selectionRange();
- TopDUContext * tc = DUChainUtils::standardContextForUrl(doc->url());
- for(int i = r.start().line(); i <= r.end().line(); i++) {
- Declaration *d = DUChainUtils::declarationInLine(SimpleCursor(i,0),tc);
- if (d && d->kind() == Declaration::Instance && !d->isFunctionDeclaration() &&
- d->context() && d->context()->type() == DUContext::Class)
- {
- list.append(d);
- }
- }
- } else {
- SimpleCursor c (view->cursorPosition());
- Declaration* d = DUChainUtils::itemUnderCursor (doc->url(), c);
- if (d && d->kind() == Declaration::Instance && !d->isFunctionDeclaration() &&
- d->context() && d->context()->type() == DUContext::Class)
- list.append(d);
- else if (d && d->internalContext() && d->internalContext()->type() == DUContext::Class)
- list.append(d);
- }
- return list;
-}
-
-
-PropertyCreator* GetterSetterPlugin::creatorForMime(const KMimeType::Ptr& mime)
-{
- static CppPropertyCreator cpp;
- static JavaPropertyCreator java;
- static CSharpPropertyCreator csharp;
- if(mime->is("text/x-c++src") || mime->is("text/x-c++hdr") || mime->is("text/x-chdr")) {
- return &cpp;
- }
- if(mime->is("text/x-java")) {
- return &java;
- }
- if(mime->is("text/x-csharp")) {
- return &csharp;
- }
- return NULL;
-}
-
-
-#include "gettersetterplugin.moc"
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/gettersetterplugin.h (nonexistent)
@@ -1,61 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef KDEVGETTERSETTERPLUGIN_H_
-#define KDEVGETTERSETTERPLUGIN_H_
-
-#include <interfaces/iplugin.h>
-
-#include <QVariantList>
-#include <KMimeType>
-
-class PropertyCreator;
-class KAction;
-
-using namespace KDevelop;
-
-namespace KDevelop
-{
-class Declaration;
-class DUContext;
-class ClassDeclaration ;
-class ClassMemberDeclaration ;
-}
-
-//kind = Type
-class GetterSetterPlugin: public KDevelop::IPlugin
-{
- Q_OBJECT
-public:
- GetterSetterPlugin (QObject *parent, const QVariantList & = QVariantList());
- ~GetterSetterPlugin();
- KDevelop::ContextMenuExtension contextMenuExtension (Context* context);
- void createProperties (QList<Declaration*> decls);
-private slots:
- void slotCreateProperties();
- void slotWriteProperties();
-
-private:
- static PropertyCreator * creatorForMime(const KMimeType::Ptr &mime);
- static QList<Declaration*> cursorItemDeclarations();
- //kind = Instance
- KAction *m_action;
-};
-
-#endif //KDEVGETTERSETTERPLUGIN_H_
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesform.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesform.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesform.ui (nonexistent)
@@ -1,128 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>propertiesForm</class>
- <widget class="QWidget" name="propertiesForm">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>600</width>
- <height>350</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>500</width>
- <height>200</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>Properties</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QComboBox" name="comboBoxModifier">
- <property name="insertPolicy">
- <enum>QComboBox::InsertAtBottom</enum>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QCheckBox" name="checkBoxDocumentation">
- <property name="text">
- <string>Documentation</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QCheckBox" name="checkBoxQtProp">
- <property name="text">
- <string notr="true">QT_PROPERTY's</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="buttonSelectAll">
- <property name="text">
- <string>Select All</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonDeselectAll">
- <property name="text">
- <string>Deselect All</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QTableView" name="tableView">
- <property name="editTriggers">
- <set>QAbstractItemView::AllEditTriggers</set>
- </property>
- <property name="alternatingRowColors">
- <bool>true</bool>
- </property>
- <property name="selectionMode">
- <enum>QAbstractItemView::NoSelection</enum>
- </property>
- <property name="selectionBehavior">
- <enum>QAbstractItemView::SelectRows</enum>
- </property>
- <property name="showGrid">
- <bool>false</bool>
- </property>
- <property name="sortingEnabled">
- <bool>false</bool>
- </property>
- <property name="wordWrap">
- <bool>false</bool>
- </property>
- <attribute name="horizontalHeaderVisible">
- <bool>true</bool>
- </attribute>
- <attribute name="horizontalHeaderCascadingSectionResizes">
- <bool>false</bool>
- </attribute>
- <attribute name="horizontalHeaderDefaultSectionSize">
- <number>25</number>
- </attribute>
- <attribute name="horizontalHeaderMinimumSectionSize">
- <number>25</number>
- </attribute>
- <attribute name="horizontalHeaderShowSortIndicator" stdset="0">
- <bool>false</bool>
- </attribute>
- <attribute name="horizontalHeaderStretchLastSection">
- <bool>false</bool>
- </attribute>
- <attribute name="verticalHeaderVisible">
- <bool>false</bool>
- </attribute>
- <attribute name="verticalHeaderHighlightSections">
- <bool>false</bool>
- </attribute>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.cpp (nonexistent)
@@ -1,31 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "javapropertycreator.h"
-
-void JavaPropertyCreator::create(PropertyModel* m)
-{
- Q_UNUSED(m)
-}
-
-bool JavaPropertyCreator::parse(PropertyModel* m, QList< KDevelop::Declaration* > selection)
-{
- Q_UNUSED(m)
- Q_UNUSED(selection)
- return false;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertymodel.cpp (nonexistent)
@@ -1,228 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#include "propertymodel.h"
-
-#include <QtGui/QColor>
-#include <KMessageBox>
-#include <KLocalizedString>
-
-PropertyModel::PropertyModel (QObject* parent) : QAbstractTableModel (parent)
-{
- Q_UNUSED (parent);
- m_hasQObject = false;
- m_createQtProperties = false;
- m_modifier = FINAL;
-}
-
-
-PropertyModel::~PropertyModel()
-{
-
-}
-
-
-Qt::ItemFlags PropertyModel::flags (const QModelIndex& index) const
-{
- if (!index.isValid())
- return Qt::ItemIsEnabled;
-
- const PropertyNode &n = m_nodes[index.row() ];
- switch (index.column())
- {
- case 1:
- if (n.canCreateGetter())
- return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
- else
- return Qt::ItemIsUserCheckable;
- case 2:
- if (n.canCreateGetter())
- return QAbstractTableModel::flags (index) | Qt::ItemIsEditable;
- else
- return Qt::NoItemFlags;
- case 3:
- if (n.canCreateGetter())
- QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
- else
- return Qt::NoItemFlags;
- case 4:
- if (n.canCreateSetter())
- return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
- else
- return Qt::ItemIsUserCheckable;
- case 5:
- if (n.canCreateSetter())
- return QAbstractTableModel::flags (index) | Qt::ItemIsEditable;
- else
- return Qt::NoItemFlags;
- case 6:
- if (n.canCreateSetter())
- QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
- else
- return Qt::NoItemFlags;
- }
-
- return QAbstractTableModel::flags (index) | Qt::ItemIsEnabled;
-}
-
-
-QVariant PropertyModel::headerData (int section, Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
- {
- switch (section)
- {
- case 0:
- return i18n("Member");
- //case 1:
- // return QString();
- case 2:
- return i18n("Getter Access");
- case 3:
- return i18n("Getter Name");
- //case 4:
- // return QString();
- case 5:
- return i18n("Setter Access");
- case 6:
- return i18n("Setter Name");
- default:
- return QVariant();
- }
- }
-
- return QAbstractTableModel::headerData (section, orientation, role);
-}
-
-
-bool PropertyModel::setData (const QModelIndex& index, const QVariant& value, int role)
-{
- if (index.row() > m_nodes.size()-1 || index.column() > columnCount())
- return false;
-
- PropertyNode &n = m_nodes[index.row() ];
-
- if (role == Qt::CheckStateRole)
- {
- switch (index.column())
- {
- case 1:
- n.setCreateGetter (value.toInt() == Qt::Checked ? true : false);
- break;
- case 4:
- n.setCreateSetter (value.toInt() == Qt::Checked ? true : false);
- break;
- }
- return true;
- }
-
- if (role == Qt::EditRole)
- {
- switch (index.column())
- {
- case 2:
- n.setGetterAccess (value.toString());
- break;
- case 5:
- n.setSetterAccess (value.toString());
- break;
- }
- return true;
- }
-
- return false;
-}
-
-QVariant PropertyModel::data (const QModelIndex& index, int role) const
-{
- if (index.row() > m_nodes.size() -1 || index.column() > columnCount())
- return QVariant();
-
- const PropertyNode &n = m_nodes[index.row() ];
-
- if (role == Qt::CheckStateRole)
- {
- switch (index.column())
- {
- case 1:
- return n.createGetter() ? Qt::Checked : Qt::Unchecked;
- case 4:
- return n.createSetter() ? Qt::Checked : Qt::Unchecked;
- }
- return QVariant();
- }
-
- if (role == Qt::EditRole)
- {
- switch (index.column())
- {
- case 1:
- return n.createGetter() ? Qt::Checked : Qt::Unchecked;
- case 2:
- return n.getterAccess();
- case 4:
- return n.createSetter() ? Qt::Checked : Qt::Unchecked;
- case 5:
- return n.setterAccess();
- }
- return QVariant();
- }
-
- if (role == Qt::DecorationRole)
- {
- switch (index.column())
- {
- case 0:
- return n.icon();
- }
- return QVariant();
- }
-
- if (role == Qt::ForegroundRole)
- {
- if (index.column() < 1)
- return QColor (128,128,128);
- }
-
- if (role == Qt::DisplayRole)
- {
- switch (index.column())
- {
- case 0:
- return n.name() + ":" + n.type();
- case 1:
- return QString();
- case 2:
- return n.getterAccess();
- case 3:
- return n.getterName();
- case 4:
- return QString();
- case 5:
- return n.setterAccess();
- case 6:
- return n.setterName();
- }
- }
-
- return QVariant();
-}
-
-#include "propertymodel.moc"
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/javapropertycreator.h (nonexistent)
@@ -1,31 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef JAVAPROPERTYCREATOR_H
-#define JAVAPROPERTYCREATOR_H
-
-#include <propertcreator.h>
-
-#include <QString>
-
-class JavaPropertyCreator : public PropertyCreator
-{
- virtual void create(PropertyModel* m);
- virtual bool parse(PropertyModel* m, QList< KDevelop::Declaration* > selection);
-};
-
-#endif // JAVAPROPERTYCREATOR_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertydelegate.h (nonexistent)
@@ -1,48 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef ACCESSITEMDELEGATE_H
-#define ACCESSITEMDELEGATE_H
-
-#include <QtGui/QItemDelegate>
-#include <QtCore/QModelIndex>
-#include <QtGui/QStyleOptionViewItem>
-#include <QtGui/QComboBox>
-#include <QtCore/QAbstractItemModel>
-#include <KDebug>
-
-class AccessListDelegate : public QItemDelegate
-{
-public:
- AccessListDelegate (QObject *parent = 0);
-
- QWidget *createEditor (QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
- void setEditorData (QWidget *editor, const QModelIndex &index) const;
-
- void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
-
- void updateEditorGeometry (QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-private:
-
- void populateList (QComboBox * box) const;
-};
-
-#endif // ACCESSITEMDELEGATE_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/csharppropertycreator.cpp (nonexistent)
@@ -1,31 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "csharppropertycreator.h"
-
-void CSharpPropertyCreator::create(PropertyModel* m)
-{
- Q_UNUSED(m)
-}
-
-bool CSharpPropertyCreator::parse(PropertyModel* m, QList< KDevelop::Declaration* > selection)
-{
- Q_UNUSED(m)
- Q_UNUSED(selection)
- return false;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertiesdialog.cpp (nonexistent)
@@ -1,141 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "propertiesdialog.h"
-
-#include "propertymodel.h"
-#include "ui_propertiesform.h"
-#include "propertydelegate.h"
-
-PropertiesDialog::PropertiesDialog (QWidget* parent, Qt::WFlags flags) :
- KDialog (parent, flags),
- m_form (0),
- m_model (0)
-{
- QWidget * w = new QWidget (this);
- m_form = new Ui::propertiesForm;
- m_form->setupUi (w);
-
- m_form->comboBoxModifier->addItem ("default", PropertyModel::FINAL);
- m_form->comboBoxModifier->addItem ("virtual", PropertyModel::VIRTUAL);
- m_form->comboBoxModifier->addItem ("pure virtual", PropertyModel::PURE_VIRTUAL);
- m_form->comboBoxModifier->addItem ("inline", PropertyModel::INLINE);
-
- m_form->tableView->setItemDelegateForColumn (2, new AccessListDelegate (m_form->tableView));
- m_form->tableView->setItemDelegateForColumn (5, new AccessListDelegate (m_form->tableView));
- m_form->tableView->horizontalHeader()->setResizeMode (QHeaderView::Interactive);
-
- connect (m_form->buttonSelectAll, SIGNAL (clicked()), this, SLOT (selectAll()));
- connect (m_form->buttonDeselectAll, SIGNAL (clicked()), this, SLOT (deselectAll()));
- connect (m_form->checkBoxQtProp, SIGNAL (clicked (bool)), this, SLOT (createQtProperties (bool)));
- connect (m_form->checkBoxDocumentation, SIGNAL (clicked (bool)), this, SLOT (createDocumentation (bool)));
- connect (m_form->comboBoxModifier, SIGNAL (currentIndexChanged (int)), this, SLOT (changeModifier (int)));
-
- setMainWidget (w);
- resize (600,350);
-}
-
-PropertiesDialog::~PropertiesDialog()
-{
- delete m_form;
-}
-
-
-void PropertiesDialog::setModel (PropertyModel* model)
-{
- m_form->tableView->setModel (0);
- m_form->tableView->reset();
-
- m_model = model;
-
- if (!m_model->m_hasQObject)
- {
- m_form->checkBoxQtProp->setEnabled (false);
- m_form->checkBoxQtProp->setVisible (false);
- m_model->m_createQtProperties = false;
- }
- else
- {
- m_form->checkBoxQtProp->setEnabled (true);
- m_form->checkBoxQtProp->setVisible (true);
- m_model->m_createQtProperties = m_form->checkBoxQtProp->checkState() == Qt::Checked;
- }
-
- m_model->m_createDocumentation = m_form->checkBoxDocumentation->checkState() == Qt::Checked;
-
- m_model->setModifier ( (PropertyModel::Modifier) m_form->comboBoxModifier->itemData (m_form->comboBoxModifier->currentIndex()).toInt());
-
- m_form->tableView->setModel (m_model);
- m_form->tableView->reset();
- m_form->tableView->resizeColumnsToContents();
-}
-
-void PropertiesDialog::show (PropertyModel * model)
-{
- setModel (model);
- KDialog::show();
-}
-
-
-void PropertiesDialog::deselectAll()
-{
- for (int i = 0; i < m_model->m_nodes.size(); i++)
- {
- PropertyNode &node = m_model->m_nodes[i];
- if (node.canCreateGetter())
- node.setCreateGetter (false);
- if (node.canCreateSetter())
- node.setCreateSetter (false);
- }
- m_form->tableView->reset();
-}
-
-
-void PropertiesDialog::selectAll()
-{
- for (int i = 0; i < m_model->m_nodes.size(); i++)
- {
- PropertyNode &node = m_model->m_nodes[i];
- if (node.canCreateGetter())
- node.setCreateGetter (true);
- if (node.canCreateSetter())
- node.setCreateSetter (true);
- }
- m_form->tableView->reset();
-}
-
-void PropertiesDialog::createQtProperties (bool create)
-{
- m_model->m_createQtProperties = create;
-}
-
-
-void PropertiesDialog::createDocumentation (bool create)
-{
- m_model->m_createDocumentation = create;
-}
-
-void PropertiesDialog::changeModifier (int index)
-{
- m_model->setModifier ( (PropertyModel::Modifier) m_form->comboBoxModifier->itemData (index).toInt());
-}
-
-
-#include "propertiesdialog.moc"
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.h (nonexistent)
@@ -1,109 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef CPPPROPERTYCREATOR_H
-#define CPPPROPERTYCREATOR_H
-
-#include "propertcreator.h"
-#include <QString>
-#include <QList>
-#include <KMessageBox>
-#include <language/duchain/types/abstracttype.h>
-
-namespace KDevelop
-{
- class IDocument;
- class DUContext;
- class Declaration;
-}
-
-class PropertyNode;
-
-class CppPropertyCreator : public PropertyCreator
-{
-public:
- bool parse (PropertyModel * m, QList<Declaration*> selection);
- void create (PropertyModel * m);
-
-private:
- /** Used to block head, public, protected, private int the text.<br/>
- * @todo This works only on lines and not columns, the same for the regular expressions to find these blocks.
- */
- class CodeRange
- {
- public:
- CodeRange() : lineStart (0), lineEnd (0) {}
- CodeRange(const CodeRange& o) : name(o.name), lineStart (o.lineStart), lineEnd (o.lineEnd) {}
- CodeRange (const QString & n) : name (n), lineStart (0), lineEnd (0) {}
- CodeRange (const QString & n, int s, int e) : name (n), lineStart (s), lineEnd (e) {}
- virtual ~CodeRange() {}
- QString name;
- int lineStart;
- int lineEnd;
- };
-
- /** Used to block head, public, protected, private in the text.<br/>
- * @todo This works only on lines and not columns, the same for the regular expressions to find these blocks.
- */
- QList<CodeRange> m_ranges;
-
- /** Return a range identified by a QString.
- * @see CppPropertyCreator::CodeRange
- */
- CodeRange *getRange (const QString &name);
-
- /** Return a range index into m_ranges identified by a QString.
- * @see CppPropertyCreator::CodeRange
- */
- int getRangeIndex (const QString &name);
-
- /** Append text at the end of a range.
- */
- void appendText(IDocument *doc, CodeRange *range, const QStringList &text, const QString &indent = "", int *lineCount = NULL);
-
- /** Returns a name like getSomeValue for someValue.
- */
- QString getterName (const QString &property);
-
- /** Returns a name like setSomeValue for someValue.
- */
- QString setterName (const QString &property);
-
- /** Returns a name like someValue for m_someValue.
- */
- QString propertyName (const QString &property);
-
- /** Returns a name like sv for m_someValue.
- */
- QString propertyAlias (const QString &property);
-
- /** Try's to return the correct type for QT_PROPERTY's.
- */
- QString qPropertyType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
-
- /** Try's to return the correct type for the reader ie const QString & when the type is QString.
- */
- QString getterType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
-
- /** Try's to return the correct type for the writer ie const QString & when the type is QString.
- */
- QString setterType (const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type);
-};
-
-#endif //CPPPROPERTYCREATOR_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/cpppropertycreator.cpp (nonexistent)
@@ -1,647 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#include "cpppropertycreator.h"
-#include "propertynode.h"
-#include "propertymodel.h"
-
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/classdeclaration.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainutils.h>
-#include <language/duchain/classfunctiondeclaration.h>
-#include <language/duchain/types/functiontype.h>
-#include <interfaces/idocument.h>
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-
-#include <KTextEditor/View>
-#include <KTextEditor/Document>
-#include <interfaces/isourceformattercontroller.h>
-#include <interfaces/isourceformatter.h>
-#include <interfaces/ilanguagecontroller.h>
-#include <interfaces/ilanguage.h>
-#include <language/interfaces/ilanguagesupport.h>
-#include <language/duchain/types/typeutils.h>
-#include <KLocalizedString>
-
-#define ERROR_MESSAGE ({KMessageBox::error(NULL, i18n(QString("An error occured while parsing the class. Please log a report. File: %1 Line: %2").arg(__FILE__).arg(__LINE__).toAscii().constData()));});
-#include <KDE/KMessageBox>
-
-CppPropertyCreator::CodeRange* CppPropertyCreator::getRange ( const QString& name )
-{
- //There is only a small number so a loop should be fine
- for ( int i = 0; i < m_ranges.size(); i++ )
- {
- if ( m_ranges.at ( i ).name == name )
- return & ( m_ranges[i] );
- }
- return NULL;
-}
-
-
-int CppPropertyCreator::getRangeIndex ( const QString& name )
-{
- //There is only a small number so a loop should be fine
- for ( int i = 0; i < m_ranges.size(); i++ )
- {
- if ( m_ranges.at ( i ).name == name )
- return i;
- }
- return -1;
-}
-
-
-
-void CppPropertyCreator::create ( PropertyModel* m )
-{
- DUChainReadLocker lock ( DUChain::lock() );
-
- ClassDeclaration * cd = m->klass();
-
- IDocument* doc = ICore::self()->documentController()->documentForUrl ( cd->topContext()->url().toUrl() );
- if ( !doc )
- {
- ERROR_MESSAGE
- return;
- }
-
- KTextEditor::Document* textDoc = doc->textDocument();
- if ( !textDoc )
- {
- ERROR_MESSAGE
- return;
- }
-
- KTextEditor::View* view = textDoc->activeView();
- if ( !view )
- {
- ERROR_MESSAGE
- return;
- }
-
- //Turn on clumsy code TODO needs refactoring
-
- QString text = textDoc->text ( m->klass()->internalContext()->range().textRange() );
-
- //Used to see where we at in the file
- int lineCount = m->klass()->internalContext()->range().start.line;
- int *end = &lineCount;
-
- //Find indentation etc in the text
- static QRegExp publicExp ( "^(\\s*)public\\s*:.*" );
- static QRegExp protectedExp ( "^(\\s*)protected\\s*:.*" );
- static QRegExp privateExp ( "^(\\s*)private\\s*:.*" );
- //A list of qt_properites to make sure we dont create them twice
- QStringList qtProperties;
- static QRegExp propertyExp ( "^.*Q_PROPERTY.*([\\w\\d_]+)\\s+(READ|WRITE).*" );
- //Used for indentation when adding/inserting text
- QString indent = "";
- QString accessIndent = "";
- static QRegExp indentExp ( "^(\\s+)\\w+.*" );
-
- m_ranges.clear();
- m_ranges.append ( CodeRange ( "head", lineCount, lineCount ) );
- end = & ( getRange ( "head" )->lineEnd );
-
- QStringList lines = text.split ( '\n' );
- foreach ( const QString &line, lines )
- {
- //Single tab or space or \r or something
- if(line.size() < 2) {
- lineCount++;
- continue;
- }
-
- //Skip inline classes
- DUContext *duc = m->klass()->internalContext()->findContextAt ( SimpleCursor ( lineCount, 0 ) );
- if ( duc && duc != m->klass()->internalContext() )
- {
- lineCount++;
- continue;
- }
-
- if ( publicExp.exactMatch ( line ) )
- {
- if ( !getRange ( "public" ) )
- m_ranges.append ( CodeRange ( "public" ) );
- getRange ( "public" )->lineStart = lineCount;
- *end = lineCount;
- end = & ( getRange ( "public" )->lineEnd );
- accessIndent = publicExp.cap ( 1 );
- }
- else if ( protectedExp.exactMatch ( line ) )
- {
- if ( !getRange ( "protected" ) )
- m_ranges.append ( CodeRange ( "protected" ) );
- getRange ( "protected" )->lineStart = lineCount;
- *end = lineCount;
- end = & ( getRange ( "protected" )->lineEnd );
- accessIndent = protectedExp.cap ( 1 );
- } else if ( privateExp.exactMatch ( line ) )
- {
- if ( !getRange ( "private" ) )
- m_ranges.append ( CodeRange ( "private" ) );
- getRange ( "private" )->lineStart = lineCount;
- *end = lineCount;
- end = & ( getRange ( "private" )->lineEnd );
- accessIndent = privateExp.cap ( 1 );
- } else if (propertyExp.exactMatch(line))
- {
- qtProperties.append(propertyExp.cap(1));
- } else if ( indentExp.exactMatch ( line ) )
- {
- indent = indentExp.cap ( 1 );
- }
-
- lineCount++;
- }
- lineCount--;
- *end = m->klass()->internalContext()->range().end.line;
-
- foreach ( const PropertyNode &n, m->nodes() )
- {
- //GETTER
- if ( n.createGetter() && n.canCreateGetter() )
- {
- QStringList itext ( "" );
- QString text = QString ( "%1 %2() const { return %3; }" ).arg ( getterType ( n.type(), n.resolvedType(), n.whichType() ), n.getterName(), n.name() );
-
- switch ( m->modifier() )
- {
- case PropertyModel::VIRTUAL:
- text = QString ( "virtual " ) + text;
- break;
- case PropertyModel::PURE_VIRTUAL:
- text = QString ( "virtual %1 %2() const = 0;" ).arg ( getterType ( n.type(), n.resolvedType(), n.whichType() ), n.getterName() );
- break;
- case PropertyModel::INLINE:
- text = QString ( "inline " ) + text;
- break;
- }
-
- CodeRange *range = getRange ( n.getterAccess() );
- if ( !range )
- {
- m_ranges.append ( CodeRange ( n.getterAccess(), lineCount, lineCount ) );
- range = getRange ( n.getterAccess() );
- appendText ( doc, range, QStringList ( QString ( "%1:" ).arg ( n.getterAccess() ) ), accessIndent, &lineCount );
- }
-
- if ( m->createDocumentation() )
- {
- itext.append ( QString ( "/** Get method for %1." ).arg ( n.name() ) );
- itext.append ( QString ( " * @see %1" ).arg ( n.name() ) );
- itext.append ( QString ( " * @return %1" ).arg ( n.name() ) );
- itext.append ( " */" );
- }
- itext.append ( text );
- appendText ( doc, range, itext, indent, &lineCount );
- }
-
- //SETTER
- if ( n.createSetter() && n.canCreateSetter() )
- {
- QStringList itext ( "" );
- QString text = QString ( "void %1( %2 %4 ) { %3 = %4; }" ).arg ( n.setterName(), setterType ( n.type(), n.resolvedType(), n.whichType() ), n.name(), propertyAlias ( n.name() ) );
-
- //We cant asign arrays, it needs a memcpy or something
- if ( n.whichType() == AbstractType::TypeArray )
- {
- static QRegExp e ( "(.*)(\\[(\\d*)\\])" ); //ie int [255]
- e.exactMatch ( n.type() );
- text = QString ( "void %1( const %2 %3%4 ) { /*TODO*/ for(int i; i<%5; i++) %6[i] = %3[i]; }" ).arg ( n.setterName(), e.cap ( 1 ), propertyAlias ( n.name() ), e.cap ( 2 ), e.cap ( 3 ), n.name() );
- }
-
- switch ( m->modifier() )
- {
- case PropertyModel::VIRTUAL:
- text = QString ( "virtual " ) + text;
- break;
- case PropertyModel::PURE_VIRTUAL:
- text = QString ( "virtual void %1( %2 %3 ) = 0;" ).arg ( n.setterName(), setterType ( n.type(), n.resolvedType(), n.whichType() ), propertyAlias ( n.name() ) );
- //We cant asign arrays, it needs a memcpy or something
- if ( n.whichType() == AbstractType::TypeArray )
- {
- static QRegExp e ( "(.*)(\\[\\d*\\])" ); //ie int [255]
- e.exactMatch ( n.type() );
- text = QString ( "void %1( const %2 %3%4 ) = 0;" ).arg ( n.setterName(), e.cap ( 1 ), propertyAlias ( n.name() ), e.cap ( 2 ) );
- }
- break;
- case PropertyModel::INLINE:
- text = QString ( "inline " ) + text;
- break;
- }
-
- CodeRange *range = getRange ( n.setterAccess() );
- if ( !range )
- {
- m_ranges.append ( CodeRange ( n.setterAccess(), lineCount, lineCount ) );
- range = getRange ( n.setterAccess() );
- appendText ( doc, range, QStringList ( QString ( "%1:" ).arg ( n.setterAccess() ) ), accessIndent, &lineCount );
- }
-
- if ( m->createDocumentation() )
- {
- itext.append ( QString ( "/** Set method for %1." ).arg ( n.name() ) );
- itext.append ( QString ( " * @see %1" ).arg ( n.name() ) );
- itext.append ( QString ( " * @param %1 Value for %2." ).arg ( propertyAlias ( n.name() ), n.name() ) );
- itext.append ( " */" );
- }
-
- itext.append ( text );
- appendText ( doc, range, itext, indent, &lineCount );
- }
-
- //Q_PROPERTY
- if ( m->hasQObject() &&
- m->createQtProperties() &&
- ( n.createGetter() || n.createSetter() ) &&
- !qtProperties.contains(propertyName(n.name())))
- {
- QStringList itext;
- QString type = qPropertyType ( n.type(), n.resolvedType(), n.whichType() );
- if ( !type.isNull() )
- {
- QString text = QString ( "Q_PROPERTY(%1 %2%3%4)" ).arg ( type,
- propertyName ( n.name() ),
- n.createGetter() && n.createGetter() ? QString ( " READ %1" ).arg ( getterName ( n.name() ) ) : "",
- n.createSetter() && n.createSetter() ? QString ( " WRITE %1" ).arg ( setterName ( n.name() ) ) : "" );
- CodeRange *range = getRange ( "head" );
- itext.append ( text );
- appendText ( doc, range, itext, indent, &lineCount );
- }
- }
- }
-
- //TODO while(true) { Turn off clumsy code!! }
-}
-
-
-void CppPropertyCreator::appendText ( IDocument *doc, CodeRange *range, const QStringList &text, const QString &indent, int *lineCount )
-{
- if ( !doc || !range )
- {
- ERROR_MESSAGE
- return;
- }
- KTextEditor::Document* textDoc = doc->textDocument();
- if ( !textDoc )
- {
- ERROR_MESSAGE
- return;
- }
-
- QStringList itext;
-
- if ( ICore::self() )
- {
- QString t = ICore::self()->sourceFormatterController()->formatterForUrl ( doc->url() )->formatSource ( text.join ( "\n" ) ,doc->mimeType() );
- itext = t.split ( "\n" );
- }
- while ( itext.last().size() == 0 || itext.last() == "\n" )
- itext.removeLast();
-
- for ( int i= 0; i < itext.size(); i++ )
- {
- textDoc->insertLine ( range->lineEnd, indent + itext[i] );
- range->lineEnd+=1;
- if ( lineCount )
- *lineCount = *lineCount + 1;
- }
- for ( int i = getRangeIndex ( range->name ) + 1; i < m_ranges.size(); i++ )
- {
- m_ranges[i].lineStart += itext.size();
- m_ranges[i].lineEnd += itext.size();
- }
-}
-
-bool CppPropertyCreator::parse ( PropertyModel* m, QList<Declaration*> selection )
-{
- DUChainReadLocker lock ( DUChain::lock() );
- QList<PropertyNode> nodes;
-
- //Damn - just making sure we get a class.
- ClassDeclaration *klass = NULL;
- foreach ( Declaration* decl, selection )
- {
- if ( decl && decl->context() && decl->context()->type() == DUContext::Class )
- {
- klass = dynamic_cast<ClassDeclaration *> ( decl->context()->owner() );
- if ( klass ) break;
- }
- else if ( decl && decl->internalContext() && decl->internalContext()->type() == DUContext::Class )
- {
- klass = dynamic_cast<ClassDeclaration *> ( decl->internalContext()->owner() );
- if ( klass ) break;
- }
- klass = dynamic_cast<ClassDeclaration *> ( decl );
- if ( klass ) break;
- }
-
- //We did not?
- if ( !klass )
- {
- ERROR_MESSAGE
- return false;
- }
-
- m->setKlass ( klass );
-
- foreach ( Declaration* decl, klass->internalContext()->localDeclarations() )
- {
- ClassMemberDeclaration* memDecl = dynamic_cast<ClassMemberDeclaration*> ( decl );
- if ( !memDecl )
- continue;
-
- if ( ! ( !memDecl->isFunctionDeclaration() && memDecl->kind() == Declaration::Instance ) )
- continue;
-
- //TODO This depends on staticMetaObject being at the begining of the loop
- if ( memDecl->identifier().toString() == "staticMetaObject" )
- {
- m->setHasQObject ( true );
- continue;
- }
-
- PropertyNode n;
- n.setName ( memDecl->identifier().toString() );
- n.setType ( memDecl->abstractType()->toString() );
- AbstractType::Ptr aptr = TypeUtils::unAliasedType ( memDecl->abstractType() );
- n.setResolvedType ( aptr->toString() );
- n.setWhichType ( aptr->whichType() );
- n.setGetterName ( getterName ( n.name() ) );
- n.setSetterName ( setterName ( n.name() ) );
-
- /*(The users selection) NOTE I dont know if comparing the pointers is valid?
- But the duchain was locked before calling this routine so its should be.
- */
- foreach ( Declaration* decl, selection )
- {
- if ( memDecl == decl )
- {
- n.setCreateGetter ( true );
- n.setCreateSetter ( true );
- }
- }
-
- //ie: const int& TODO get modifier from duchain rather
- if ( ( n.whichType() == AbstractType::TypeReference || n.whichType() == AbstractType::TypeArray ) &&
- ( n.type().contains ( "const" ) || n.resolvedType().contains ( "const" ) ) )
- {
- n.setCanCreateSetter ( false );
- n.setCreateSetter ( false );
- }
-
- foreach ( Declaration * d, klass->internalContext()->localDeclarations() )
- {
- ClassFunctionDeclaration * dm = dynamic_cast<ClassFunctionDeclaration*> ( d );
- if ( !dm )
- continue;
-
- FunctionType::Ptr ft = dm->abstractType().cast<FunctionType>();
- if ( !ft )
- continue;
- if ( !ft->returnType() )
- continue;
-
- QString access = "default";
- switch ( dm->accessPolicy() )
- {
- case Declaration::Public:
- access = "public";
- break;
- case Declaration::Protected:
- access = "protected";
- break;
- case Declaration::Private:
- access = "private";
- break;
- }
-
- if ( dm->identifier().toString() == n.getterName() &&
- ft->arguments().size() == 0 &&
- ft->modifiers() & AbstractType::ConstModifier )
- {
- n.setCanCreateGetter ( false );
- n.setCreateGetter ( true );
- n.setGetterAccess ( access );
- continue;
- }
-
- if ( dm->identifier().toString() == n.setterName() &&
- ft->returnType()->toString() == "void" &&
- ft->arguments().size() == 1 &&
- ft->arguments() [0]->toString() == setterType ( n.type(), n.resolvedType(), n.whichType() ) )
- {
- n.setCanCreateSetter ( false );
- n.setCreateSetter ( true );
- n.setSetterAccess ( access );
- continue;
- }
- }
- nodes.append ( n );
- }
-
- m->setNodes ( nodes );
-
- return true;
-}
-
-
-QString CppPropertyCreator::propertyAlias ( const QString& property )
-{
- if ( property.isNull() )
- {
- ERROR_MESSAGE
- return "null";
- }
-
- QString p = propertyName ( property );
- QString r = "";
- r += p[0];
- bool kase = false;
- for ( int i = 1; i < p.size(); i++ )
- {
- if ( p[i].isUpper() && kase == false )
- {
- r += p[i].toLower();
- kase = true;
- }
- if ( p[i].isLower() && kase == true )
- kase = false;
- if ( p[i] == '_' && i < p.size() - 1 )
- r += p[i+1];
- }
-
- if ( r == property )
- r = QString ( "_%1" ).arg ( r );
- return r;
-}
-
-
-QString CppPropertyCreator::propertyName ( const QString& property )
-{
- if ( property.isNull() )
- {
- ERROR_MESSAGE
- return "null";
- }
-
- QString n = QString ( "%1" ).arg ( property );
- if ( property.size() > 1 && property[0] == 'm' && property[1].isUpper() )
- n = n.remove ( ( {static QRegExp e ( "(^m_)|(^m)|(^_+)" ); e;} ) );
- else
- n = n.remove ( ( {static QRegExp e ( "(^m_)|(^_+)" ); e;} ) );
- n[0] = n[0].toLower();
- return n;
-}
-
-QString CppPropertyCreator::getterName ( const QString& property )
-{
- if ( property.isNull() )
- {
- ERROR_MESSAGE
- return "null";
- }
-
- QString n = propertyName ( property );
- if ( n == property )
- {
- n[0] = n[0].toUpper();
- n = QString ( "get%1" ).arg ( n );
- }
- return n;
-}
-
-QString CppPropertyCreator::setterName ( const QString& property )
-{
- if ( property.isNull() )
- {
- ERROR_MESSAGE
- return QString();
- }
-
- QString n = propertyName ( property );
- n[0] = n[0].toUpper();
- return QString ( "set%1" ).arg ( n );
-}
-
-QString CppPropertyCreator::qPropertyType ( const QString& abstractType, const QString& resolvedType, AbstractType::WhichType type )
-{
- if ( abstractType.isNull() || resolvedType.isNull() )
- {
- ERROR_MESSAGE
- return QString();
- }
-
- bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
-
- /*
- 1 cant create property for pointer has to be const * ie:
- - int * t must be const int * t; -> Q_PROPERTY ( const int * t3 READ getT3 WRITE setT3 )
- 2 array must have const int *
- - int t4[100]; Q_PROPERTY ( const int* t4 READ getT4 WRITE setT4 )
- */
-
- //Arrays
- if ( type == AbstractType::TypeArray )
- {
- if ( hasConst )
- return QString ( "%1*" ).arg ( QString ( resolvedType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
- return QString ( "const %1*" ).arg ( QString ( resolvedType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
- }
-
- if ( type == AbstractType::TypePointer )
- {
- if ( !hasConst )
- return QString();
- return resolvedType;
- }
-
- return QString ( resolvedType ).remove ( ( {static QRegExp e ( "(const)|([&]*)" ); e; }) );
-}
-
-QString CppPropertyCreator::getterType ( const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type )
-{
- if ( abstractType.isNull() || resolvedType.isNull() )
- {
- ERROR_MESSAGE
- return QString();
- }
-
- //TODO This could and probably should come from the DUChain 'modifier'
- bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
-
- //Primitives
- if ( type == AbstractType::TypeIntegral || type == AbstractType::TypeEnumeration )
- return QString ( abstractType ).remove ( "const" );
-
- //Array's see writerType() //ie int [255]
- if ( type == AbstractType::TypeArray )
- {
- if ( hasConst )
- return QString ( "%1*" ).arg ( QString ( abstractType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
- return QString ( "const %1*" ).arg ( QString ( abstractType ).remove ( ( {static QRegExp e ( "(\\[\\d*\\])" ); e;} ) ) );
- }
-
- //References and pointer
- if ( type == AbstractType::TypePointer || type == AbstractType::TypeReference )
- {
- if ( hasConst )
- return QString ( abstractType );
- return QString ( "const %1" ).arg ( abstractType );
- }
-
- //Whats left
- if ( hasConst )
- return QString ( "%1&" ).arg ( abstractType );
- return QString ( "const %1&" ).arg ( abstractType );
-}
-
-QString CppPropertyCreator::setterType ( const QString & abstractType, const QString & resolvedType, AbstractType::WhichType type )
-{
- if ( abstractType.isNull() || resolvedType.isNull() )
- {
- ERROR_MESSAGE
- return QString();
- }
-
- //TODO This could and probably should come from the DUChain 'modifier'
- bool hasConst = abstractType.contains ( "const" ) || resolvedType.contains ( "const" );
-
- //Arrays need a special implementation, this is only used to compare parameters //ie const int [255]
- if ( type == AbstractType::TypeArray )
- return QString ( "const %1" ).arg ( abstractType );
-
- //Primitives
- if ( type == AbstractType::TypeIntegral || type == AbstractType::TypeEnumeration )
- return QString ( abstractType ).remove ( "const" );
-
- //References and pointer
- if ( type == AbstractType::TypePointer || type == AbstractType::TypeReference )
- return QString ( "%1" ).arg ( abstractType );
-
- //Whats left
- if ( hasConst )
- return QString ( "%1&" ).arg ( abstractType );
- return QString ( "const %1&" ).arg ( abstractType );
-}
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on; replace-tabs on; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/gettersetter/propertynode.h (nonexistent)
@@ -1,113 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2009 Ruan Strydom <rm3dom@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 3 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-
-#ifndef PROPERTYNODE_H
-#define PROPERTYNODE_H
-
-#include <QtGui/QIcon>
-#include <language/duchain/declaration.h>
-
-
-using namespace KDevelop;
-
-
-/** Stores info about an property.
- * @todo This should keep a handle to the Declaration. Rather than a bunch of members.
- * This represents a row in the table of PropertiesDialog and PropertyModel.
- */
-class PropertyNode
-{
-public:
- PropertyNode ();
- virtual ~PropertyNode();
-
-
- virtual const QString& getterName() const { return m_getterName; }
-
- virtual void setGetterName ( const QString& rn ) { m_getterName = rn; }
-
- virtual bool createGetter() const { return m_createGetter; }
-
- virtual void setCreateGetter ( bool cr ) { m_createGetter = cr; }
-
- virtual bool canCreateGetter() const { return m_canCreateGetter; }
-
- virtual void setCanCreateGetter ( bool ccr ) { m_canCreateGetter = ccr; }
-
- virtual const QString& getterAccess() const { return m_getterAccess; }
-
- virtual void setGetterAccess ( const QString& ra ) { m_getterAccess = ra; }
-
- virtual const QString& setterName() const { return m_setterName; }
-
- virtual void setSetterName ( const QString& wn ) { m_setterName = wn; }
-
- virtual bool createSetter() const { return m_createSetter; }
-
- virtual void setCreateSetter ( bool cw ) { m_createSetter = cw; }
-
- virtual bool canCreateSetter() const { return m_canCreateSetter; }
-
- virtual void setCanCreateSetter ( bool ccw ) { m_canCreateSetter = ccw; }
-
- virtual const QString& setterAccess() const { return m_setterAccess; }
-
- virtual void setSetterAccess ( const QString& wa ) { m_setterAccess = wa; }
-
- virtual const QString& name() const { return m_name; }
-
- virtual void setName ( const QString& n ) { m_name = n; }
-
- virtual const QIcon& icon() const { return m_icon; }
-
- virtual void setIcon ( const QIcon& i ) { m_icon = i; }
-
- virtual const QString& type() const { return m_type; }
-
- virtual void setType ( const QString& t ) { m_type = t; }
-
- virtual const QString& resolvedType() const { return m_resolvedType; }
-
- virtual void setResolvedType ( const QString& rt ) { m_resolvedType = rt; }
-
- virtual KDevelop::AbstractType::WhichType whichType() const { return m_whichType; }
-
- virtual void setWhichType ( KDevelop::AbstractType::WhichType wt ) { m_whichType = wt; }
-
-protected:
- QString m_getterName;
- bool m_createGetter;
- bool m_canCreateGetter;
- QString m_getterAccess;
-
- QString m_setterName;
- bool m_createSetter;
- bool m_canCreateSetter;
- QString m_setterAccess;
-
- QString m_name;
- QIcon m_icon;
-
- QString m_type;
- QString m_resolvedType;
- AbstractType::WhichType m_whichType;
-};
-
-#endif // PROPERTYNODE_H
-
-// kate: indent-mode cstyle; space-indent on; indent-width 4; replace-tabs on;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/CMakeLists.txt (nonexistent)
@@ -1,30 +0,0 @@
-set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
-include_directories(
- ${XtestPlugin_SOURCE_DIR}/cppunit
- ${XtestPlugin_SOURCE_DIR} # for kasserts.h
-)
-
-add_definitions(${KDE4_ENABLE_EXCEPTIONS})
-
-macro(kdev_qx_add_test test_EXEC)
- set(test_SRCS ${ARGN})
- qt4_automoc( ${test_SRCS} )
- kde4_add_unit_test(cppunit-${test_EXEC} ${test_SRCS})
- target_link_libraries(cppunit-${test_EXEC}
- ${QT_QTTEST_LIBRARY}
- ${QT_QTXML_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- kdevcppunit)
-endmacro(kdev_qx_add_test)
-
-kdev_qx_add_test(sys-cppunitrunnertest cppunitrunnertest.cpp)
-
-add_executable(emptysuite fake_emptysuite.cpp)
-target_link_libraries(emptysuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
-
-add_executable(sunnysuite fake_sunnysuite.cpp)
-target_link_libraries(sunnysuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
-
-add_executable(multisuite fake_multisuite.cpp)
-target_link_libraries(multisuite ${QT_QTCORE_LIBRARY} ${CPPUNIT_LIBRARY})
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.cpp (nonexistent)
@@ -1,144 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "cppunitrunnertest.h"
-
-#include <kasserts.h>
-#include <qtest_kde.h>
-#include <veritas/testresult.h>
-#include <veritas/runnertesthelper.h>
-#include "register.h"
-
-#include "testroot.h"
-#include "testsuite.h"
-
-using Veritas::RunnerTestHelper;
-using CppUnit::Test::CppUnitRunnerTest;
-
-Q_DECLARE_METATYPE(QList<QStringList>)
-
-void CppUnitRunnerTest::init()
-{
- m_runner = new RunnerTestHelper;
- m_runner->initializeGUI();
-}
-
-void CppUnitRunnerTest::cleanup()
-{
- delete m_runner;
-}
-
-// command
-void CppUnitRunnerTest::empty()
-{
- Veritas::Test* root = fetchRoot("./emptysuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- QStringList runnerItems;
- runnerItems << "0 x"; // an empty test-tree
- m_runner->verifyTestTree(runnerItems);
-
- QList<QStringList> results; // no test failures
- m_runner->verifyResultItems(results);
-}
-
-QStringList sunnyDayTests()
-{
- QStringList runnerItems;
- runnerItems << "0 RootSuite"
- << "0 0 FooTest"
- << "0 0 0 testCmd1"
- << "0 0 1 testCmd2"
- << "0 0 2 x"
- << "0 1 BarTest"
- << "0 1 0 testCmd1"
- << "0 1 1 testCmd2"
- << "0 1 2 x"
- << "0 2 BazTest"
- << "0 2 0 testCmd1"
- << "0 2 1 x"
- << "0 3 x"
- << "1 x";
- return runnerItems;
-}
-
-QMap<QString, Veritas::TestState> sunnyDayTestStates()
-{
- QMap<QString, Veritas::TestState> states;
- states["RootSuite/FooTest/testCmd1"] = Veritas::RunSuccess;
- states["RootSuite/FooTest/testCmd2"] = Veritas::RunSuccess;
- states["RootSuite/BarTest/testCmd1"] = Veritas::RunSuccess;
- states["RootSuite/BarTest/testCmd2"] = Veritas::RunError;
- states["RootSuite/BazTest/testCmd1"] = Veritas::RunSuccess;
- return states;
-}
-
-// command
-void CppUnitRunnerTest::sunnyDay()
-{
- Veritas::Test* root = fetchRoot("./sunnysuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- m_runner->verifyTestTree(sunnyDayTests());
- m_runner->verifyTestStates(sunnyDayTestStates(), root);
- QStringList result0;
- result0 << "testCmd2" << "" << KUrl(__FILE__).upUrl().path() + "fake_sunnysuite.cpp" << "63";
- QList<QStringList> results;
- results << result0;
- m_runner->verifyResultItems(results);
-}
-
-// command
-void CppUnitRunnerTest::multiSuite()
-{
- Veritas::Test* root = fetchRoot("./multisuite");
- m_runner->setRoot(root);
- m_runner->runTests();
-
- QStringList topo;
- topo << "0 FooSuite"
- << "0 0 FooTest"
- << "0 0 0 FooTest::fooCmd"
- << "0 0 1 x"
- << "0 1 x"
- << "1 BarSuite"
- << "1 0 BarTest"
- << "1 0 0 BarTest::barCmd"
- << "1 0 1 x"
- << "1 1 x"
- << "2 x";
- m_runner->verifyTestTree(topo);
-
- QList<QStringList> results;
- m_runner->verifyResultItems(results);
-}
-
-Veritas::Test* CppUnitRunnerTest::fetchRoot(const char* exe)
-{
- Register<TestRoot, TestSuite> reg;
- reg.addFromExe(QFileInfo(exe));
- reg.rootItem()->setExecutable(QFileInfo(exe));
- return reg.rootItem();
-}
-
-#include "cppunitrunnertest.moc"
-QTEST_KDEMAIN(CppUnitRunnerTest, GUI)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_sunnysuite.cpp (nonexistent)
@@ -1,108 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <cppunit/TestSuite.h>
-#include <cppunit/TestFixture.h>
-#include <cppunit/TestCaller.h>
-#include <cppunitwrapper.h>
-
-// "0 RootSuite"
-// "0 0 FooTest"
-// "0 0 0 testCmd1"
-// "0 0 1 testCmd2"
-// "0 0 2 x"
-// "0 1 BarTest"
-// "0 1 0 testCmd1"
-// "0 1 1 testCmd2"
-// "0 1 2 x"
-// "0 2 BazTest"
-// "0 2 0 testCmd1"
-// "0 2 1 x"
-// "0 3 x"
-// "1 x"
-
-using namespace CppUnit;
-
-class FooTest : public TestFixture
-{
-public:
- void testCmd1() {}
- void testCmd2() {}
-
- static Test* suite() {
- TestSuite* suite = new CppUnit::TestSuite("FooTest");
- typedef TestCaller<FooTest> fooCaller;
- suite->addTest(new fooCaller("testCmd1", &FooTest::testCmd1));
- suite->addTest(new fooCaller("testCmd2", &FooTest::testCmd2));
- return suite;
- }
-};
-
-class BarTest : public TestFixture
-{
-public:
- void testCmd1() {}
- void testCmd2() {
- CPPUNIT_ASSERT(false);
- }
-
- static Test* suite() {
- TestSuite* suite = new CppUnit::TestSuite("BarTest");
- typedef TestCaller<BarTest> barCaller;
- suite->addTest(new barCaller("testCmd1", &BarTest::testCmd1));
- suite->addTest(new barCaller("testCmd2", &BarTest::testCmd2));
- return suite;
- }
-};
-
-#include <QThread>
-
-class Sleep : public QThread
-{
-public:
- void run() {}
- static void waitAbit() {
- QThread::usleep(50000); // 0.05 sec
- }
-};
-
-class BazTest : public TestFixture
-{
-public:
- void testCmd1() { Sleep::waitAbit(); }
-
- static Test* suite() {
- TestSuite* suite = new CppUnit::TestSuite("BazTest");
- typedef TestCaller<BazTest> bazCaller;
- suite->addTest(new bazCaller("testCmd1", &BazTest::testCmd1));
- return suite;
- }
-};
-
-Test* suite()
-{
- TestSuite* suite = new TestSuite("RootSuite");
- suite->addTest(FooTest::suite());
- suite->addTest(BarTest::suite());
- suite->addTest(BazTest::suite());
- return suite;
-}
-
-CPPUNIT_VERITAS_MAIN(suite())
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_emptysuite.cpp (nonexistent)
@@ -1,24 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <cppunit/TestSuite.h>
-#include <cppunitwrapper.h>
-
-CPPUNIT_VERITAS_MAIN( new CppUnit::TestSuite() )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/cppunitrunnertest.h (nonexistent)
@@ -1,52 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CPPUNIT_CPPUNITRUNNERTEST_H
-#define CPPUNIT_CPPUNITRUNNERTEST_H
-
-#include <QtTest/QTest>
-
-namespace Veritas { class RunnerTestHelper; class Test; }
-
-namespace CppUnit {
-namespace Test {
-
-class CppUnitRunnerTest : public QObject
-{
-Q_OBJECT
-
-private slots:
- void init();
- void cleanup();
-
- void empty();
- void sunnyDay();
- void multiSuite();
-
-private:
- Veritas::Test* fetchRoot(const char*);
-
-private:
- Veritas::RunnerTestHelper* m_runner;
-};
-
-}}
-
-#endif // CPPUNIT_CPPUNITRUNNERTEST_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/tests/fake_multisuite.cpp (nonexistent)
@@ -1,75 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <cppunit/TestSuite.h>
-#include <cppunit/TestFixture.h>
-#include <cppunit/TestCaller.h>
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunitwrapper.h>
-#include <vector>
-
-// "0 FooSuite"
-// "0 0 FooTest"
-// "0 0 0 fooCmd"
-// "0 0 1 x"
-// "0 1 x"
-// "1 BarSuite"
-// "1 0 BarTest"
-// "1 0 0 barCmd"
-// "1 0 1 x"
-// "1 1 x"
-// "2 x"
-
-using namespace CppUnit;
-
-class FooTest : public TestFixture
-{
-CPPUNIT_TEST_SUITE( FooTest );
- CPPUNIT_TEST( fooCmd );
-CPPUNIT_TEST_SUITE_END();
-
-public:
- void fooCmd() {}
-};
-
-class BarTest : public TestFixture
-{
-CPPUNIT_TEST_SUITE( BarTest );
- CPPUNIT_TEST( barCmd );
-CPPUNIT_TEST_SUITE_END();
-
-public:
- void barCmd() {}
-};
-
-std::vector<TestSuite*> suite()
-{
- TestSuite* fs = new TestSuite("FooSuite");
- fs->addTest(FooTest::suite());
- TestSuite* bs = new TestSuite("BarSuite");
- bs->addTest(BarTest::suite());
-
- std::vector<TestSuite*> suites;
- suites.push_back(fs);
- suites.push_back(bs);
- return suites;
-}
-
-CPPUNIT_VERITAS_MAIN_(suite())
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/register.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/register.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/register.h (nonexistent)
@@ -1,215 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CPPUNIT_TESTREGISTER_H
-#define CPPUNIT_TESTREGISTER_H
-
-#include <QtCore/QString>
-#include <QtCore/QFileInfo>
-#include <QtXml/QXmlStreamReader>
-
-#include <veritas/test.h>
-#include "testcase.h"
-#include "qxcppunitexport.h"
-
-class KProcess;
-class QIODevice;
-
-/*!
- * Retrieves and builds a Test Tree from an external executable's
- * xml output.
- *
- * This class removes bad duplication between the Check
- * & CppUnit plugins. It might be completely irrelevant for
- * other frameworks.
- */
-template<typename R, typename S>
-class QXCPPUNIT_EXPORT Register : public QXmlStreamReader
-{
-public:
- typedef R TestRoot;
- typedef S TestSuite;
-
- Register();
- virtual ~Register();
-
- void addFromXml(QIODevice*);
- void addFromExe(const QFileInfo& exe);
- void addFromExe(const KUrl& exe);
- TestRoot* rootItem();
- void setRootDir(const QString& root);
- void setExecutable(const QFileInfo& exe);
-
-private: // helpers
- void execute(KProcess*);
- bool isStartElement_(const QString& elem);
- bool isEndElement_(const QString& elem);
- void processSuite();
- void processCase(TestSuite* suite);
- void processCmd(TestCase* caze);
- QString fetchName();
- QFileInfo fetchDir();
- QFileInfo fetchExe();
-
-private: // state
- TestRoot* m_rootItem;
- QString m_root;
- QFileInfo m_exe;
-
-private: // some xml constants
- const QString c_suite;
- const QString c_case;
- const QString c_cmd;
- const QString c_name;
-};
-
-///// template implementation
-
-#include <KDebug>
-#include <KProcess>
-#include <KLocalizedString>
-
-template<typename R, typename S>
-Register<R,S>::Register()
- : m_root(""),
- c_suite("suite"),
- c_case("case"),
- c_cmd("command"),
- c_name("name")
-{}
-
-template<typename R, typename S>
-Register<R,S>::~Register()
-{}
-
-template<typename R, typename S>
-R* Register<R,S>::rootItem()
-{
- return m_rootItem;
-}
-
-template<typename R, typename S>
-bool Register<R,S>::isStartElement_(const QString& elem)
-{
- return isStartElement() && (name() == elem);
-}
-
-template<typename R, typename S>
-bool Register<R,S>::isEndElement_(const QString& elem)
-{
- return isEndElement() && (name() == elem);
-}
-
-template<typename R, typename S>
-void Register<R,S>::addFromExe(const QFileInfo& exe)
-{
- KProcess* proc = new KProcess;
- setExecutable(exe);
- execute(proc);
- addFromXml(proc);
-}
-
-template<typename R, typename S>
-void Register<R,S>::addFromExe(const KUrl& exe)
-{
- KProcess* proc = new KProcess;
- setExecutable(QFileInfo(exe.path()));
- execute(proc);
- addFromXml(proc);
-}
-
-template<typename R, typename S>
-void Register<R,S>::execute(KProcess* proc)
-{
- QStringList argv;
- argv << "-proto";
- proc->setProgram(m_exe.filePath(), argv);
- kDebug() << "executing " << proc->program();
- proc->setOutputChannelMode(KProcess::SeparateChannels);
- proc->start();
- proc->waitForFinished(-1);
-}
-
-template<typename R, typename S>
-void Register<R,S>::addFromXml(QIODevice* dev)
-{
- m_rootItem = new TestRoot(QList<QVariant>() << "" << "" << "" << "");
-
- Q_ASSERT(dev != 0);
- setDevice(dev);
- if (!device()->isOpen())
- device()->open(QIODevice::ReadOnly);
-
- while (!atEnd()) {
- readNext();
- if (isStartElement_(c_suite))
- processSuite();
- }
- kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
-}
-
-template<typename R, typename S>
-void Register<R,S>::processSuite()
-{
- TestSuite* suite = new TestSuite(fetchName(), m_exe, m_rootItem);
- m_rootItem->addChild(suite);
- kDebug() << suite->name();
-
- while (!atEnd() && !isEndElement_(c_suite)) {
- readNext();
- if (isStartElement_(c_case))
- processCase(suite);
- }
-}
-
-template<typename R, typename S>
-void Register<R,S>::processCase(TestSuite* suite)
-{
- TestCase* caze = new TestCase(fetchName(), suite);
- suite->addChild(caze);
- kDebug() << caze->name();
- while (!atEnd() && !isEndElement_(c_case)) {
- readNext();
- if (isStartElement_(c_cmd))
- processCmd(caze);
- }
-}
-
-template<typename R, typename S>
-void Register<R,S>::setExecutable(const QFileInfo& exe)
-{
- m_exe = exe;
-}
-
-template<typename R, typename S>
-void Register<R,S>::processCmd(TestCase* caze)
-{
- TestCommand* cmd = new TestCommand(fetchName(), caze);
- caze->addChild(cmd);
- kDebug() << cmd->name();
-}
-
-template<typename R, typename S>
-QString Register<R,S>::fetchName()
-{
- return attributes().value(c_name).toString();
-}
-
-#endif // CPPUNIT_REGISTER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.h (nonexistent)
@@ -1,39 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CPPUNIT_CPPUNITVIEWDATA_H
-#define CPPUNIT_CPPUNITVIEWDATA_H
-
-#include <veritas/testrunner.h>
-#include "qxcppunitexport.h"
-
-namespace Veritas { class Test; class ITestFramework; class ITestTreeBuilder; }
-
-/*! Assorted test runner operations and data */
-class QXCPPUNIT_EXPORT CppUnitViewData : public Veritas::TestRunner
-{
-Q_OBJECT
-public:
- CppUnitViewData(Veritas::ITestFramework* framework, Veritas::ITestTreeBuilder* builder);
- virtual ~CppUnitViewData();
-};
-
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.cpp (nonexistent)
@@ -1,191 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "outputparser.h"
-#include "testroot.h"
-#include <veritas/test.h>
-#include "testcase.h"
-#include <KUrl>
-#include <KDebug>
-
-using Veritas::Test;
-using Veritas::TestResult;
-using CppUnit::TestRoot;
-using CppUnit::OutputParser;
-
-/*example xml:
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<root>
-<suite name="RootSuite">
- <case name="FooTest">
- <command name="testCmd1"></command>
- <command name="testCmd2"></command>
- </case>
- <case name="BarTest">
- <command name="testCmd1"></command>
- <command name="testCmd2">
- <status type="assertion" file="/home/nix/KdeDev/kdevelop/plugins/xtest/qxcppunit/tests/fake_sunnysuite.cpp" line="63"/>
- </command>
- </case>
- <case name="BazTest">
- <command name="testCmd1"></command>
- </case>
-</suite>
-</root>
-*/
-
-const QString OutputParser::c_suite("suite");
-const QString OutputParser::c_case("case");
-const QString OutputParser::c_command("command");
-const QString OutputParser::c_name("name");
-const QString OutputParser::c_status("status");
-const QString OutputParser::c_type("type");
-const QString OutputParser::c_assertion("assertion");
-const QString OutputParser::c_file("file");
-const QString OutputParser::c_line("line");
-
-#define ENSURE_FOUND(c,p,n) Q_ASSERT_X(c, "hm",\
- qstrdup((QString("Failed to find ") + n + QString(" as child of ")\
- + p->name()).toAscii().data()));
-
-
-OutputParser::OutputParser(QIODevice* device)
- : QXmlStreamReader(device),
- m_result(0),
- m_processingSuite(false),
- m_processingCase(false),
- m_processingCmd(false)
-{}
-
-OutputParser::~OutputParser()
-{}
-
-bool OutputParser::isStartElement_(const QString& elementName)
-{
- return isStartElement() && (name() == elementName);
-}
-
-bool OutputParser::isEndElement_(const QString& elementName)
-{
- return isEndElement() && (name() == elementName);
-}
-
-void OutputParser::go(TestRoot* root)
-{
- m_root = root;
- if (!device()->isOpen())
- device()->open(QIODevice::ReadOnly);
- if (!device()->isReadable()) {
- // do something
- }
-
- if (m_processingCmd)
- processCmd();
- if (m_processingCase)
- processCase();
- if (m_processingSuite)
- processSuite();
-
- while (!atEnd()) {
- readNext();
- if (isStartElement_(c_suite)) {
- processSuite();
- }
- }
-
- kError(hasError()) << errorString() << " @ " << lineNumber() << ":" << columnNumber();
-}
-
-void OutputParser::processSuite()
-{
- m_processingSuite = true;
- QString name = fetchName();
- m_suite = m_root->childNamed(name);
- ENSURE_FOUND(m_suite, m_root, name);
- while (!atEnd() && !isEndElement_(c_suite)) {
- readNext();
- if (isStartElement_(c_case))
- processCase();
- }
- if (isEndElement_(c_suite))
- m_processingSuite = false;
-}
-
-void OutputParser::processCase()
-{
- if (!m_processingCase) {
- m_currentCase = fetchName();
- m_case = m_suite->childNamed(m_currentCase);
- }
- ENSURE_FOUND(m_case, m_suite, m_currentCase);
- m_processingCase = true;
- while (!atEnd() && !isEndElement_(c_case)) {
- readNext();
- if (isStartElement_(c_command))
- processCmd();
- }
- if (isEndElement_(c_case))
- m_processingCase = false;
-}
-
-QString OutputParser::fetchName()
-{
- return attributes().value(c_name).toString();
-}
-
-void OutputParser::processCmd()
-{
- if (!m_processingCmd) {
- m_currentCmd = fetchName();
- m_cmd = m_case->childNamed(m_currentCmd);
- ENSURE_FOUND(m_cmd, m_case, m_currentCmd);
- m_cmd->signalStarted();
- m_result = new TestResult;
- }
- Q_ASSERT(m_cmd);
- m_processingCmd = true;
- bool gotFailureMsg = false;
- while (!atEnd() && !isEndElement_(c_command)) {
- readNext();
- if (isStartElement_(c_status)) {
- gotFailureMsg = true;
- setFailure();
- }
- }
- if (isEndElement_(c_command)) {
- m_processingCmd = false;
- if (!gotFailureMsg)
- setSuccess();
- m_cmd->setResult(m_result);
- m_cmd->signalFinished();
- }
-}
-
-void OutputParser::setSuccess()
-{
- m_result->setState(Veritas::RunSuccess);
-}
-
-void OutputParser::setFailure()
-{
- m_result->setState(Veritas::RunError);
- m_result->setFile(KUrl(attributes().value(c_file).toString()));
- m_result->setLine(attributes().value(c_line).toString().toInt());
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.h (nonexistent)
@@ -1,43 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTCOMMAND_H
-#define TESTCOMMAND_H
-
-#include <veritas/test.h>
-#include <QtCore/QString>
-#include "qxcppunitexport.h"
-
-/*!
- * Leaf item in the test tree.
- *
- * This class removes bad duplication between the Check
- * & CppUnit plugins. It might be completely irrelevant for
- * other frameworks.
- */
-class VERITAS_EXPORT TestCommand : public Veritas::Test
-{
-Q_OBJECT
-public:
- TestCommand(const QString& name, Veritas::Test* parent);
- virtual ~TestCommand();
-};
-
-#endif // TESTCOMMAND_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcppunit.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/CMakeLists.txt (nonexistent)
@@ -1,75 +0,0 @@
-project(cppunit)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${cppunit_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-find_package(CppUnit)
-macro_log_feature(CPPUNIT_FOUND "CppUnit" "KDevelop4 extra plugin cppunit" "http://TODO" FALSE "" "")
-
-if (CPPUNIT_FOUND)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-add_subdirectory(tests)
-
-#
-# TODO install qxcppunit headers
-#
-
-add_definitions(${KDE4_ENABLE_EXCEPTIONS})
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-
-include_directories(
- ${XtestPlugin_SOURCE_DIR}
- )
-
-set(kdevcppunit_SRCS
- testcommand.cpp
- testcase.cpp
- testsuite.cpp
- testroot.cpp
- cppunitviewdata.cpp
- cppunittesttreebuilder.cpp
- outputparser.cpp)
-
-qt4_add_resources(kdevcppunit_SRCS
- resources/qxcppunit.qrc)
-
-qt4_automoc( ${kdevcppunit_SRCS} )
-kde4_add_library(kdevcppunit SHARED ${kdevcppunit_SRCS})
-target_link_libraries(kdevcppunit
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${CPPUNIT_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${QT_QTCORE_LIBRARY})
-install(TARGETS kdevcppunit ${INSTALL_TARGETS_DEFAULT_ARGS} )
-
-#########################################
-
-set(kdevcppunitview_SRCS cppunitplugin.cpp cppunittesttreebuilder.cpp)
-qt4_automoc(${kdevcppunitview_SRCS})
-kde4_add_plugin(kdevcppunitview ${kdevcppunitview_SRCS})
-target_link_libraries(kdevcppunitview
- kdevcppunit
- ${KDEVPLATFORM_VERITAS_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${KDE4_KDEUI_LIBS}
- ${QT_QTCORE_LIBRARY})
-install(TARGETS kdevcppunitview DESTINATION ${PLUGIN_INSTALL_DIR})
-
-########### install files ###############
-
-install( FILES kdevcppunit.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevcppunit.rc DESTINATION ${DATA_INSTALL_DIR}/kdevcppunit )
-install( FILES cppunitwrapper.h DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/veritas/ )
-
-endif()
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/mainpage_
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/mainpage_ (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/mainpage_ (nonexistent)
@@ -1,144 +0,0 @@
-/*!
- * \file mainpage.h
- *
- * \brief Contains documentation.
- *
- * This file contains text and doxygen formatting commands for the
- * \ref main "Main Page" and other parts of the API documentation.
- */
-
-/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
-
-/*!
-\page license License
-\verbatim
-
-QxCppUnit Library
-Copyright (C) 2006 systest.ch
-
-This library is free software; you can redistribute it and/or modify it under
-the terms of the GNU Lesser General Public License as published by the Free
-Software Foundation; either version 2.1 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 Lesser General Public License for more
-details.
-
-You should have received a copy of the GNU Lesser General Public License
-along with this library; if not, write to the Free Software Foundation, Inc.,
-59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-\endverbatim
-*/
-
-
-namespace QxCppUnit { // Enables doxygen to create links to documented items
-
-
-/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
-
-/*!
-\mainpage
-
-\image html qxcppunit_64x64.png
-
-<!------------------------------------------------------------------->
-
-\section intro Introduction
-
-The QxCppUnit library provides a GUI frontend for CppUnit test execution.
-It is based on the QxRunner and Qt libraries. It can be used to unit test
-any kind of C++ software, it's not limited to Qt applications.
-
-This library is just a thin wrapper around the QxRunner library.
-Actually the idea to write a Qt test runner with a user-friendly GUI
-led to the development of the QxRunner library.
-
-The QxCppUnit library mainly consists of the CppUnitItem class, which
-subclasses QxRunner::RunnerItem, and the CppUnitModel class derived from
-QxRunner::RunnerModel. The TestRunner class populates a CppUnitModel
-instance with CppUnitItem objects and uses a QxRunner::Runner instance
-to show the GUI on the screen.
-
-To write a GUI test runner for CppUnit just the TestRunner class
-is needed as described in the \ref examples page.
-*/
-
-/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
-
-/*!
-\page implementation_ascpects Implementation Aspects
-
-<!------------------------------------------------------------------->
-
-\section symbols Exported Symbols
-
-This applies for the Win32 world only. By default symbols of the library
-are 'hidden' when created as a DLL. Therefore symbols, in particular
-classes, that must be accessible from the outside of the library are
-exported with the QXCPPUNIT_EXPORT macro:
-
-\code
-class QXCPPUNIT_EXPORT TestRunner
-{
-public: // Operations
- ...
-\endcode
-
-Only the TestRunner class is exported right now, the other classes are
-for internal use only. This might be reconsidered in the future and more
-classes could become exported to be used somewhere outside the library.
-
-<!------------------------------------------------------------------->
-
-\section result_types Result Types
-
-See the CppUnitModel class for the result types handled by the library.
-*/
-
-/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
-
-/*!
-\namespace QxCppUnit
-
-\brief Namespace for the QxCppUnit library entities.
-
-\namespace QxRunner
-
-\brief Namespace of the
-<a target="_blank" href="http://qxrunner.systest.ch">QxRunner Library</a>.
-
-\namespace CPPUNIT_NS
-
-\brief The CppUnit library exposes its classes in the CPPUNIT_NS namespace.
-*/
-
-/*!<!--xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-->*/
-
-/*!
-\page examples Examples
-
-The demo program shipped with the QxCppUnit library can be used as the
-starting point for writing a GUI test runner for CppUnit. It has some
-CppUnit test fixtures with simple test cases which succeed or fail and
-uses a TestRunner instance in the main program to launch the GUI.
-
-\section demo_test_example A CppUnit Test Example
-
-This is one of the test fixtures of the demo program. Of course this is a
-very simple test and only used for demonstration purposes. It isn't
-intended to show how to write CppUnit tests.
-
-\includelineno testexamples2.cpp
-
-\section demo_main The Demo Main Program
-
-The main program is straightforward:
-
-\includelineno main.cpp
-*/
-
-} // namespace
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc (nonexistent)
@@ -1,5 +0,0 @@
-<RCC>
- <qresource prefix="/icons" >
- <file>qxcppunit_16x16.png</file>
- </qresource>
-</RCC>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit.qrc
___________________________________________________________________
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_16x16.png
___________________________________________________________________
Deleted: svn:mime-type
## -1 +0,0 ##
-application/octet-stream
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/resources/qxcppunit_64x64.png
___________________________________________________________________
Deleted: svn:mime-type
## -1 +0,0 ##
-application/octet-stream
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.h (nonexistent)
@@ -1,41 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CPPUNIT_CPPUNITPLUGIN_H
-#define CPPUNIT_CPPUNITPLUGIN_H
-
-#include <interfaces/iplugin.h>
-#include <veritas/itestframework.h>
-#include <QVariantList>
-
-class CppUnitPlugin : public KDevelop::IPlugin, public Veritas::ITestFramework
-{
-Q_OBJECT
-Q_INTERFACES(Veritas::ITestFramework)
-
-public:
- explicit CppUnitPlugin(QObject* parent, const QVariantList & = QVariantList());
- virtual ~CppUnitPlugin();
- virtual Veritas::TestRunner* createRunner();
- virtual QString name() const;
- virtual QWidget* createConfigWidget() { return 0; }
-};
-
-#endif // CPPUNIT_CPPUNITPLUGIN_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.h
___________________________________________________________________
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitwrapper.h (nonexistent)
@@ -1,231 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-/*!
-Constructs a compatible CppUnit executable from CppUnit::TestSuite(s)
-through main macro's. See CPPUNIT_VERITAS_MAIN.
-This header is intended for users of the runner, not a part of the
-cppunit plugin.
-*/
-
-#ifndef CPPUNIT_WRAPPER_H
-#define CPPUNIT_WRAPPER_H
-
-#include <exception>
-#include <vector>
-#include <cppunit/TestCase.h>
-#include <cppunit/TestPath.h>
-#include <cppunit/TestSuite.h>
-#include <cppunit/TestRunner.h>
-#include <cppunit/TestResult.h>
-#include <cppunit/TestFailure.h>
-#include <cppunit/TestListener.h>
-
-//
-// CppUnit's terminology is a tad different from
-// the standard way of naming things.
-//
-// The following mapping is used:
-// CppUnit --> xTest
-// TestCase --> TestCommand
-// TestSuite (with case children) --> TestCase
-// TestSuite (without case children) --> TestSuite
-//
-
-namespace CppUnit
-{
-
-static inline bool isSuite(CppUnit::Test* test)
-{
- CppUnit::TestSuite* suite = dynamic_cast<CppUnit::TestSuite*>(test);
- if (!suite || suite->getChildTestCount() == 0)
- return false;
- CppUnit::Test* child = suite->getChildTestAt(0);
- CppUnit::TestCase* caze = dynamic_cast<CppUnit::TestCase*>(child);
- return (caze == 0); // no testcase children, ie a pure suite
-}
-
-static inline bool isCase(CppUnit::Test* test)
-{
- CppUnit::TestSuite* suite = dynamic_cast<CppUnit::TestSuite*>(test);
- if (!suite) {
- return false;
- }
- if (suite->getChildTestCount() == 0) {
- return true;
- }
- CppUnit::Test* child = suite->getChildTestAt(0);
- CppUnit::TestCase* caze = dynamic_cast<CppUnit::TestCase*>(child);
- return (caze != 0);
-}
-
-static inline bool isCommand(CppUnit::Test* test)
-{
- CppUnit::TestCase* cmd = dynamic_cast<CppUnit::TestCase*>(test);
- return (cmd != 0);
-}
-
-static inline const char* tagFor(CppUnit::Test* test)
-{
- static const char* suite = "suite";
- static const char* caze = "case";
- static const char* cmd = "command";
- static const char* unkw = "unknown";
- const char* tag;
- if (isSuite(test)) {
- tag = suite;
- } else if (isCase(test)) {
- tag = caze;
- } else if (isCommand(test)) {
- tag = cmd;
- } else {
- tag = unkw;
- }
- return tag;
-}
-
-// recursivly print the test structure as XML
-static inline void printTestTree(CppUnit::Test* test)
-{
- const char* tag = tagFor(test);
- int nrofChilds = test->getChildTestCount();
- if (nrofChilds == 0) {
- printf("<%s name=\"%s\" />\n", tag, test->getName().c_str());
- } else {
- printf("<%s name=\"%s\" >\n", tag, test->getName().c_str());
- for (int i = 0; i < nrofChilds; i++) {
- printTestTree(test->getChildTestAt(i));
- }
- printf("</%s>\n", tag);
- }
-}
-
-class XMLProgressListener : public CppUnit::TestListener
-{
-public:
- XMLProgressListener() {};
- virtual ~XMLProgressListener() {};
-
- virtual void startTest(CppUnit::Test *test) {
- printf("<command name=\"%s\">\n", test->getName().c_str());
- }
-
- virtual void addFailure(const CppUnit::TestFailure &failure) {
- CppUnit::SourceLine loc = failure.sourceLine();
- printf("<status type=\"%s\" file=\"%s\" line=\"%d\"/>\n",
- (failure.isError() ? "error" : "assertion"),
- loc.fileName().c_str(),
- loc.lineNumber());
- }
-
- virtual void endTest(CppUnit::Test*) {
- printf("</command>\n");
- }
-
- virtual void startSuite(CppUnit::Test* test) {
- printf("<%s name=\"%s\">\n", tagFor(test), test->getName().c_str());
- }
-
- virtual void endSuite(CppUnit::Test *test) {
- printf("</%s>\n", tagFor(test));
- }
-
-private:
- XMLProgressListener(const XMLProgressListener &copy);
- void operator=(const XMLProgressListener &copy);
-
-};
-
-static inline void runTest(CppUnit::Test* root)
-{
- CppUnit::TestResult testresult;
- CppUnit::XMLProgressListener progress;
- testresult.addListener(&progress);
- CppUnit::TestRunner testrunner;
- testrunner.addTest(root);
- testrunner.run(testresult);
-}
-
-template<typename T>
-static inline void runAllTests(T suites, int argc, char **)
-{
- printf("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
- "<root>\n");
- if (argc == 1) {
- // run evrything
- typename T::const_iterator it;
- for (it=suites.begin(); it!=suites.end(); it++) {
- runTest(*it);
- }
- } else {
-// try {
-// for (int i = 1; i < argc; i++) {
-// CppUnit::TestPath path;
-// path = root->resolveTestPath(argv[i]);
-// runTest(path.getChildTest());
-// }
-// } catch (std::exception& exc) {
-// printf("<error message=\"%s\" />\n", exc.what());
-// } catch (...) {
-// printf("<error message=\"unknown exception occurred in client test code\"/>\n");
-// }
- }
- printf("</root>\n");
-}
-
-template<typename T>
-static inline void printAllTests(T suites)
-{
- printf("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
- "<root>\n");
- typename T::const_iterator it;
- for (it=suites.begin(); it!= suites.end(); it++) {
- printTestTree(*it);
- }
- printf("</root>\n");
-}
-
-#define CPPUNIT_VERITAS_MAIN( root ) \
-int main(int argc, char** argv)\
-{\
- std::vector<CppUnit::Test*> suites;\
- suites.push_back(root);\
- if (argc == 1 || argv[1][0] != '-') { \
- CppUnit::runAllTests(suites, argc, argv); \
- } else { \
- CppUnit::printAllTests(suites); \
- }\
- return 0;\
-}
-
-#define CPPUNIT_VERITAS_MAIN_( suites ) \
-int main(int argc, char** argv)\
-{\
- if (argc == 1 || argv[1][0] != '-') { \
- CppUnit::runAllTests(suites, argc, argv); \
- } else { \
- CppUnit::printAllTests(suites); \
- }\
- return 0;\
-}
-
-} // namespace CppUnit
-
-#endif // CPPUNIT_WRAPPER
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/qxcppunitexport.h (nonexistent)
@@ -1,37 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef QXCPPUNITEXPORT_H
-#define QXCPPUNITEXPORT_H
-
-#include <kdemacros.h>
-
-#ifndef QXCPPUNIT_EXPORT
-# ifdef MAKE_KDEVCPPUNIT_LIB
-# define QXCPPUNIT_EXPORT KDE_EXPORT
-# else
-# define QXCPPUNIT_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif // QXCPPUNIT_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.h (nonexistent)
@@ -1,53 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef VERITAS_CPPUNIT_TESTROOT_H
-#define VERITAS_CPPUNIT_TESTROOT_H
-
-#include <QString>
-#include <QFileInfo>
-
-#include <veritas/test.h>
-#include "testsuite.h"
-#include "qxcppunitexport.h"
-
-namespace CppUnit
-{
-
-/*! Prime item in the test tree responsible for calling
-the executable */
-class QXCPPUNIT_EXPORT TestRoot : public Veritas::Test
-{
-Q_OBJECT
-public:
- TestRoot(const QList<QVariant>& data);
- virtual ~TestRoot();
- TestSuite* child(int i) const;
- void setExecutable(const QFileInfo& e) { m_exe = e; }
- int run();
- bool shouldRun() const;
-
-private:
- QFileInfo m_exe;
-};
-
-} // end namespace Check
-
-#endif // VERITAS_CPPUNIT_TESTROOT_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp (nonexistent)
@@ -1,75 +0,0 @@
-/*
-* KDevelop CPPUnit integration
-* Copyright 2009 Andrew Coles <andrew_coles@yahoo.co.uk
-*
-* 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "cppunittesttreebuilder.h"
-#include <interfaces/iproject.h>
-#include <KSharedConfig>
-#include <KConfigGroup>
-#include <QtCore/QString>
-
-using namespace KDevelop;
-using namespace Veritas;
-using namespace CppUnit;
-
-CppUnitTestTreeBuilder::CppUnitTestTreeBuilder() : reg(0), m_root(0) {};
-
-CppUnitTestTreeBuilder::~CppUnitTestTreeBuilder() {
- delete reg;
-}
-
-void CppUnitTestTreeBuilder::reload(KDevelop::IProject* project) {
- delete reg;
- reg = new Register<TestRoot, TestSuite>;
- KUrl testExe = KUrl(fetchExe(project));
- if (testExe.isEmpty()) {
-// emit reloadFailed();
- return;
- }
- reg->addFromExe(testExe);
- reg->rootItem()->setExecutable(testExe.path());
- m_root = reg->rootItem();
-/* if (m_root) {
- emit reloadFinished(m_root);
- } else {
- emit reloadFailed();
- }*/
-};
-
-QString CppUnitTestTreeBuilder::fetchExe(KDevelop::IProject* project)
-{
- if (project == 0) return QString();
- KSharedConfig::Ptr cfg = project->projectConfiguration();
- KConfigGroup group(cfg.data(), "Veritas");
- QStringList executables;
- executables = group.readEntry<QStringList>("executables", executables);
- if (executables.isEmpty()) return QString();
- return executables[0];
-}
-
-
-
-Test* CppUnitTestTreeBuilder::root() const
-{
- Q_ASSERT(m_root);
- return m_root;
-}
-
-
-#include "cppunittesttreebuilder.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h (nonexistent)
@@ -1,57 +0,0 @@
-/*
-* KDevelop CPPUnit integration
-* Copyright 2009 Andrew Coles <andrew_coles@yahoo.co.uk
-*
-* 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef CPPUNIT_CPPUNITTESTTREEBUILDER_H
-#define CPPUNIT_CPPUNITTESTTREEBUILDER_H
-
-#include <QObject>
-#include <veritas/testexecutableinfo.h>
-#include <veritas/itesttreebuilder.h>
-#include "qxcppunitexport.h"
-#include "register.h"
-#include "testroot.h"
-#include "testsuite.h"
-
-namespace KDevelop { class IProject; }
-namespace Veritas { class Test; }
-
-/*! Collects the test tree structure for a project. */
-class CppUnitTestTreeBuilder : public Veritas::ITestTreeBuilder
-{
-Q_OBJECT
-
-public:
- CppUnitTestTreeBuilder();
- virtual ~CppUnitTestTreeBuilder();
-
- virtual Veritas::Test* root() const;
- virtual void reload(KDevelop::IProject* project);
-
- QString fetchExe(KDevelop::IProject* project);
-
-private:
-
- Register<CppUnit::TestRoot, CppUnit::TestSuite> * reg;
- CppUnit::TestRoot * m_root;
-
-
-};
-
-#endif // CPPUNIT_CPPUNITTESTTREEBUILDER_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunittesttreebuilder.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.cpp (nonexistent)
@@ -1,37 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testcase.h"
-
-using Veritas::Test;
-
-TestCase::TestCase(const QString& name, Test* parent)
- : Test(name, parent)
-{}
-
-TestCase::~TestCase()
-{}
-
-TestCommand* TestCase::child(int i) const
-{
- return static_cast<TestCommand*>(Test::child(i));
-}
-
-#include "testcase.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.h (nonexistent)
@@ -1,51 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QXCPPUNIT_TESTSUITE_H
-#define QXCPPUNIT_TESTSUITE_H
-
-#include <QString>
-#include <QFileInfo>
-#include <KProcess>
-#include <veritas/test.h>
-#include "qxcppunitexport.h"
-
-#include "testcase.h"
-
-namespace CppUnit
-{
-
-/*! Aggregate item in the test tree */
-class QXCPPUNIT_EXPORT TestSuite : public Veritas::Test
-{
-Q_OBJECT
-public:
- TestSuite();
- TestSuite(const QString&, const QFileInfo& executable, Veritas::Test* parent);
- virtual ~TestSuite();
- TestCase* child(int i) const;
-
-private:
- QFileInfo m_exe;
-};
-
-} // CppUnit
-
-#endif // QXCPPUNIT_TESTSUITE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/outputparser.h (nonexistent)
@@ -1,91 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QXCPPUNIT_CPPUNITOUTPUTPARSER
-#define QXCPPUNIT_CPPUNITOUTPUTPARSER
-
-#include <QXmlStreamReader>
-#include <veritas/testresult.h>
-
-class QIODevice;
-
-namespace Veritas { class Test; }
-
-namespace CppUnit
-{
-
-class TestRoot;
-
-/*! Parses CppUnit XML output into TestResults */
-class OutputParser : public QXmlStreamReader
-{
-public:
- OutputParser(QIODevice* device);
- virtual ~OutputParser();
-
- /**
- * Start parsing and emit results
- **/
- void go(TestRoot*);
-
-private: // helpers
- void processSuite();
- void processCase();
- void processCmd();
- void setFailure();
- void setSuccess();
- QString fetchName();
-
- inline bool isStartElement_(const QString& elem);
- inline bool isEndElement_(const QString& elem);
-
-private: // state
- Veritas::TestResult* m_result;
-
- // remember state to continue when parsing
- // incrementally
- bool m_processingSuite;
- bool m_processingCase;
- bool m_processingCmd;
-
- QString m_currentSuite;
- QString m_currentCase;
- QString m_currentCmd;
-
- TestRoot* m_root;
- Veritas::Test* m_suite;
- Veritas::Test* m_case;
- Veritas::Test* m_cmd;
-
-private: // some xml constants
- static const QString c_suite;
- static const QString c_case;
- static const QString c_command;
- static const QString c_name;
- static const QString c_status;
- static const QString c_type;
- static const QString c_assertion;
- static const QString c_file;
- static const QString c_line;
-};
-
-} // namespace CppUnit
-
-#endif // QXCPPUNIT_CPPUNITOUTPUTPARSER
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.desktop (nonexistent)
@@ -1,85 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Icon=kdevelop
-Comment=CppUnit test runner
-Comment[bs]=CppUnit izvršitelj testova
-Comment[ca]=Llançador de proves Cppunit
-Comment[ca@valencia]=Llançador de proves Cppunit
-Comment[de]=CppUnit-Test ausführen
-Comment[el]=Εκτελεστής ελέγχου μονάδας Cpp
-Comment[en_GB]=CppUnit test runner
-Comment[es]=Lanzador de pruebas unitarias de Cpp
-Comment[et]=CppUniti testi käivitaja
-Comment[fr]=Lanceur de tests CppUnit
-Comment[ga]=Feidhmitheoir tástála CppUnit
-Comment[gl]=Executor de probas de CppUnit
-Comment[it]=Esecutore di test CppUnit
-Comment[ms]=Pelari unit CppUnit
-Comment[nds]=CppUnit-Testdreger
-Comment[nl]=Voert CppUnit tests uit
-Comment[pl]=Uruchomienie testu CppUnit
-Comment[pt]=Execução de testes do CppUnit
-Comment[pt_BR]=Execução de testes do CppUnit
-Comment[sv]=Kör Cpp-enhetstest
-Comment[tr]=CppUnit sınaması çalıştırıcı
-Comment[uk]=Засіб запуску перевірки CppUnit
-Comment[x-test]=xxCppUnit test runnerxx
-Name=CppUnit runner
-Name[bs]=CppUnit runner(pokreće neku akciju)
-Name[ca]=Executor CppUnit
-Name[ca@valencia]=Executor CppUnit
-Name[de]=CppUnit ausführen
-Name[el]=Εκτελεστής μονάδας Cpp
-Name[en_GB]=CppUnit runner
-Name[es]=Lanzador CppUnit
-Name[et]=CppUniti käivitaja
-Name[fr]=Lanceur CppUnit
-Name[ga]=Feidhmitheoir CppUnit
-Name[gl]=Executor de CppUnit
-Name[it]=Esecutore CppUnit
-Name[ms]=Pelari CppUnit
-Name[nds]=CppUnit-Dreger
-Name[nl]=Voert CppUnit uit
-Name[pl]=Uruchomienie CppUnit
-Name[pt]=Execução do CppUnit
-Name[pt_BR]=Execução do CppUnit
-Name[sv]=Kör Cpp-enhet
-Name[tr]=CppUnit çalıştırıcı
-Name[uk]=Засіб запуску CppUnit
-Name[x-test]=xxCppUnit runnerxx
-GenericName=Unit test runner
-GenericName[bs]=Jednični test runner(pokreće neku akciju)
-GenericName[ca]=Executor de prova Unit
-GenericName[ca@valencia]=Executor de prova Unit
-GenericName[de]=Unittest ausführen
-GenericName[el]=Εκτελεστής ελέγχου unit
-GenericName[en_GB]=Unit test runner
-GenericName[es]=Lanzador de pruebas unitarias
-GenericName[et]=Unit-testi käivitaja
-GenericName[fr]=Lanceur de test unitaire
-GenericName[ga]=Feidhmitheoir tástála aonad
-GenericName[gl]=Executor de probas unitarias
-GenericName[it]=Esecutore di unit test
-GenericName[ms]=Pelari unit uji
-GenericName[nds]=Unit-Testdreger
-GenericName[nl]=Test-startprogramma voor eenheid
-GenericName[pa]=ਯੂਨਿਟ ਟੈਸਟ ਰਨਰ
-GenericName[pl]=Uruchamianie jednostki testu
-GenericName[pt]=Execução de testes unitários
-GenericName[pt_BR]=Execução de testes unitários
-GenericName[sk]=Spúštač unit testov
-GenericName[sv]=Kör enhetstest
-GenericName[tr]=Birim sınaması çalıştırıcı
-GenericName[uk]=Засіб запуску перевірки модулів
-GenericName[x-test]=xxUnit test runnerxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevcppunitview
-X-KDE-PluginInfo-Name=cppunitview
-X-KDE-PluginInfo-Author=Manuel Breugelmans
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=LGPL
-X-KDevelop-Interfaces=org.kdevelop.ITestFramework
-X-KDevelop-Version=7
-X-KDevelop-Category=Global
-X-KDevelop-Properties=GlobalFileManagement
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp (nonexistent)
@@ -1,83 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "cppunitplugin.h"
-
-#include <kpluginfactory.h>
-#include <kaboutdata.h>
-#include <kpluginloader.h>
-#include <ksharedconfig.h>
-
-#include <interfaces/iuicontroller.h>
-#include <interfaces/iproject.h>
-#include <interfaces/iprojectcontroller.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <project/projectmodel.h>
-#include <interfaces/icore.h>
-#include <veritas/test.h>
-#include <veritas/testtoolviewfactory.h>
-#include "register.h"
-
-#include <QFile>
-#include <KConfigGroup>
-#include <KDebug>
-#include <KProcess>
-
-#include "testroot.h"
-#include "cppunitviewdata.h"
-#include "cppunittesttreebuilder.h"
-
-using KDevelop::IPlugin;
-using KDevelop::IProject;
-using KDevelop::IProjectController;
-
-using Veritas::Test;
-
-using CppUnit::TestRoot;
-using CppUnit::TestSuite;
-
-K_PLUGIN_FACTORY(CppUnitPluginFactory, registerPlugin<CppUnitPlugin>();)
-K_EXPORT_PLUGIN(CppUnitPluginFactory(KAboutData("kdevcppunit","kdevcppunit", ki18n("CppUnit test"), "0.1", ki18n("Support running CppUnit tests"), KAboutData::License_GPL)))
-
-CppUnitPlugin::CppUnitPlugin(QObject* parent, const QVariantList &)
- : IPlugin(CppUnitPluginFactory::componentData(), parent)
-{
- KDEV_USE_EXTENSION_INTERFACE( Veritas::ITestFramework );
- Veritas::TestToolViewFactory* factory = new Veritas::TestToolViewFactory(this);
- core()->uiController()->addToolView("CppUnit Runner", factory);
- setXMLFile("kdevcppunit.rc");
-}
-
-CppUnitPlugin::~CppUnitPlugin()
-{
-}
-
-QString CppUnitPlugin::name() const
-{
- static QString s_name("CppUnit");
- return s_name;
-}
-
-Veritas::TestRunner* CppUnitPlugin::createRunner()
-{
- return new CppUnitViewData(this, new CppUnitTestTreeBuilder);
-}
-
-#include "cppunitplugin.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitplugin.cpp
___________________________________________________________________
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/kdevcppunit.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevCppUnit" version="1">
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake (nonexistent)
@@ -1,34 +0,0 @@
-# - Find CppUnit
-# This module finds an installed CppUnit package.
-#
-# Obtained from:
-# http://root.cern.ch/viewvc/trunk/cint/reflex/cmake/modules/FindCppUnit.cmake?view=log&pathrev=24750
-#
-# It sets the following variables:
-# CPPUNIT_FOUND - Set to false, or undefined, if CppUnit isn't found.
-# CPPUNIT_INCLUDE_DIR - The CppUnit include directory.
-# CPPUNIT_LIBRARY - The CppUnit library to link against.
-
-FIND_PATH(CPPUNIT_INCLUDE_DIR cppunit/Test.h)
-FIND_LIBRARY(CPPUNIT_LIBRARY NAMES cppunit)
-
-IF (CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARY)
- SET(CPPUNIT_FOUND TRUE)
-ENDIF (CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARY)
-
-IF (CPPUNIT_FOUND)
-
- # show which CppUnit was found only if not quiet
- IF (NOT CppUnit_FIND_QUIETLY)
- MESSAGE(STATUS "Found CppUnit: ${CPPUNIT_LIBRARY}")
- ENDIF (NOT CppUnit_FIND_QUIETLY)
-
-ELSE (CPPUNIT_FOUND)
-
- # fatal error if CppUnit is required but not found
- IF (CppUnit_FIND_REQUIRED)
- MESSAGE(FATAL_ERROR "Could not find CppUnit")
- ENDIF (CppUnit_FIND_REQUIRED)
-
-ENDIF (CPPUNIT_FOUND)
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindCppUnit.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testsuite.cpp (nonexistent)
@@ -1,45 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testsuite.h"
-#include "outputparser.h"
-#include <KDebug>
-
-using CppUnit::TestSuite;
-using CppUnit::OutputParser;
-using Veritas::Test;
-
-TestSuite::TestSuite()
- : Test("", 0)
-{}
-
-TestSuite::TestSuite(const QString& name, const QFileInfo& exe, Test* parent)
- : Test(name, parent), m_exe(exe)
-{}
-
-TestSuite::~TestSuite()
-{}
-
-TestCase* TestSuite::child(int i) const
-{
- return static_cast<TestCase*>(Test::child(i));
-}
-
-#include "testsuite.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/cppunitviewdata.cpp (nonexistent)
@@ -1,37 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "cppunitviewdata.h"
-#include <interfaces/iproject.h>
-#include "register.h"
-#include "testroot.h"
-#include "testsuite.h"
-
-using namespace KDevelop;
-using namespace Veritas;
-using namespace CppUnit;
-
-CppUnitViewData::CppUnitViewData(ITestFramework* framework, ITestTreeBuilder * builder) : TestRunner(framework, builder)
-{
-}
-
-CppUnitViewData::~CppUnitViewData() {}
-
-#include "cppunitviewdata.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcommand.cpp (nonexistent)
@@ -1,32 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testcommand.h"
-
-using Veritas::Test;
-
-TestCommand::TestCommand(const QString& name, Test* parent)
- : Test(name, parent)
-{}
-
-TestCommand::~TestCommand()
-{}
-
-#include "testcommand.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testroot.cpp (nonexistent)
@@ -1,70 +0,0 @@
-/* KDevelop xUnit plugin
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "testroot.h"
-#include "outputparser.h"
-#include <QDir>
-#include <KDebug>
-#include <KProcess>
-
-
-using Veritas::Test;
-
-using CppUnit::TestRoot;
-using CppUnit::TestSuite;
-using CppUnit::OutputParser;
-
-TestRoot::TestRoot(const QList<QVariant>& data)
- : Test(data, 0)
-{}
-
-TestRoot::~TestRoot()
-{}
-
-bool TestRoot::shouldRun() const
-{
- return true;
-}
-
-TestSuite* TestRoot::child(int i) const
-{
- Test* child = Test::child(i);
- TestSuite* suite = qobject_cast<TestSuite*>(child);
- kWarning(suite==0) << "cast failed? " << name() << " "
- << i << " " << ((child!=0) ? child->name() : "null");
- return suite;
-}
-
-int TestRoot::run()
-{
- KProcess proc;
- QStringList argv;
- proc.setProgram(m_exe.filePath(), argv);
- kDebug() << "executing " << proc.program();
- proc.setOutputChannelMode(KProcess::SeparateChannels);
- proc.start();
- proc.waitForFinished(-1);
- OutputParser parser(&proc);
- parser.go(this);
- emit executionFinished();
- return 0;
-}
-
-#include "testroot.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/cppunit/testcase.h (nonexistent)
@@ -1,46 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef TESTCASE_H
-#define TESTCASE_H
-
-#include <veritas/test.h>
-#include "testcommand.h"
-#include <QtCore/QString>
-#include "qxcppunitexport.h"
-
-/*!
- * Item in the test tree that contains TestCommands
- *
- * This class removes bad duplication between the Check
- * & CppUnit plugins. It might be completely irrelevant for
- * other frameworks.
- */
-class QXCPPUNIT_EXPORT TestCase : public Veritas::Test
-{
-Q_OBJECT
-public:
- TestCase(const QString& name, Veritas::Test* parent);
- virtual ~TestCase();
- TestCommand* child(int i) const;
-};
-
-
-#endif // TESTCASE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/CMakeLists.txt (nonexistent)
@@ -1,27 +0,0 @@
-
-set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
-include_directories(
- ${McCabe_SOURCE_DIR}/include
- ${McCabe_SOURCE_DIR}/src
- ${CMAKE_CURRENT_BINARY_DIR}
- ${KDE4_INCLUDE_DIR}
- ${QT_INCLUDES}
- ${KDEVPLATFORM_INCLUDE_DIR})
-
-macro(mccabe_add_test test_EXEC)
- set(test_SRCS ${ARGN})
- qt4_automoc( ${test_SRCS} )
- kde4_add_unit_test(mccabe-${test_EXEC} ${test_SRCS})
- target_link_libraries(mccabe-${test_EXEC}
- ${QT_QTTEST_LIBRARY}
- ${QT_QTXML_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDEVPLATFORM_INTERFACES}
- ${KDEVPLATFORM_LANGUAGE}
- ${KDE4_LIB_DIR}/libkdev4cppparser.so
- ${KDE4_LIB_DIR}/libkdev4cpprpp.so)
-endmacro(mccabe_add_test)
-
-mccabe_add_test(metricengine metricenginetest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
-mccabe_add_test(functionname functionnametest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
-mccabe_add_test(sourcelocation sourcelocationtest.cpp ../src/metrics.cpp ../src/metricengine.cpp)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.cpp (nonexistent)
@@ -1,184 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "metricenginetest.h"
-#include "metricengine.h"
-#include "metrics.h"
-#include <QtTest/QTest>
-#include <kurl.h>
-
-class MetricEngineFake : public MetricEngine
-{
-public:
- QByteArray content;
-protected:
- virtual QByteArray readAll(const KUrl& filename) {
- Q_UNUSED(filename);
- return content;
- }
-};
-
-void McCabeMetricTest::init()
-{
- m_engine = new MetricEngineFake;
- m_metric = McCabeMetric();
-}
-
-void McCabeMetricTest::cleanup()
-{
- if (m_engine) delete m_engine;
-}
-
-// SUT stimulation helper
-QList<McCabeMetric> McCabeMetricTest::computeMcCabeMetricFor(const QByteArray& source)
-{
- m_engine->content = source;
- MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
- return mtr.mcCabeComplexity();
-}
-
-void McCabeMetricTest::computeMcCabeMetricFor(const QByteArray& source, McCabeMetric& result)
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(source);
- QCOMPARE(1, cm.count());
- result = cm[0];
-}
-
-// command
-void McCabeMetricTest::simpleFunction_singlePath()
-{
- computeMcCabeMetricFor("void foo() { int i; }", m_metric);
- assertCycloComplexityEquals(1, m_metric);
-}
-
-// custom assertion
-void McCabeMetricTest::assertCycloComplexityEquals(int value, const McCabeMetric& metric)
-{
- QCOMPARE(metric.value(), value);
-}
-
-// command
-void McCabeMetricTest::simpleFunction_if()
-{
- computeMcCabeMetricFor("void bar() { bool b; if (b) { int a; } }", m_metric);
- assertCycloComplexityEquals(2, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_elseif()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "void bar() { int i; if (i<0) {} else if (i<10) {} }"
- );
-
- QCOMPARE(1, cm.count());
- assertCycloComplexityEquals(3, cm[0]);
-}
-
-// command
-void McCabeMetricTest::simpleFunction_multipleIf()
-{
- computeMcCabeMetricFor("void bar() { bool b; if (b) { int a; } if (!b) { int c; } }", m_metric);
- assertCycloComplexityEquals(3, m_metric);
-}
-
-void McCabeMetricTest::function_switch()
-{
- computeMcCabeMetricFor("void bar() { int i; switch (i) { case 1: i+1; case 2: i+2; } }", m_metric);
- assertCycloComplexityEquals(3, m_metric); // +1 for each case
-}
-
-void McCabeMetricTest::function_ternary()
-{
- computeMcCabeMetricFor("void bar() { bool b; int i; b ? i+1 : i+2; }", m_metric);
- assertCycloComplexityEquals(2, m_metric);
-}
-
-// command
-void McCabeMetricTest::simpleFunction_while()
-{
- computeMcCabeMetricFor("void bar() { while (1) {} }", m_metric);
- assertCycloComplexityEquals(2, m_metric);
-}
-
-// command
-void McCabeMetricTest::simpleFunction_for()
-{
- computeMcCabeMetricFor("void bar() { for (;;) {} }", m_metric);
- assertCycloComplexityEquals(2, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_singleAnd()
-{
- computeMcCabeMetricFor("void bar() { bool a,b; if ( a && b) {} }", m_metric);
- assertCycloComplexityEquals(3, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_multipleAnd()
-{
- computeMcCabeMetricFor("void bar() { bool a,b; if ( (a && b) && c) {} }", m_metric);
- assertCycloComplexityEquals(4, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_singleOr()
-{
- computeMcCabeMetricFor("void bar() { bool a,b; if ( a || b) {} }", m_metric);
- assertCycloComplexityEquals(3, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_plusInIf()
-{
- computeMcCabeMetricFor("void bar() { int a,b; if( a+b) {} }", m_metric);
- assertCycloComplexityEquals(2, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_macro()
-{
- computeMcCabeMetricFor(
- "#define IF if (a>0) {}\n"
- "void bar() { int a; IF IF }", m_metric);
- assertCycloComplexityEquals(3, m_metric);
-}
-
-// command
-void McCabeMetricTest::function_catch()
-{
- computeMcCabeMetricFor(
- "class Exception1 {};\n"
- "class Exception2 {};\n"
- "void bar() { \n"
- " try { \n"
- " int i=1+1; \n"
- " } catch (Exception1& e) { \n"
- " } catch (Exception2& e) {}\n"
- "}\n",
- m_metric);
- assertCycloComplexityEquals(3, m_metric);
-}
-
-
-QTEST_MAIN( McCabeMetricTest )
-#include "metricenginetest.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/metricenginetest.h (nonexistent)
@@ -1,63 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef QTEST_METRICENGINETEST_H_INCLUDED
-#define QTEST_METRICENGINETEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include "metrics.h"
-
-class MetricEngineFake;
-
-/*! @unitundertest MetricEngine */
-class McCabeMetricTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void simpleFunction_singlePath();
- void simpleFunction_if();
- void simpleFunction_multipleIf();
- void simpleFunction_while();
- void simpleFunction_for();
- void function_singleAnd();
- void function_multipleAnd();
- void function_singleOr();
- void function_plusInIf();
- void function_switch();
- void function_ternary();
- void function_elseif();
- void function_macro();
- void function_catch();
-
-private:
- QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
- void computeMcCabeMetricFor(const QByteArray& source, McCabeMetric& result);
- void assertCycloComplexityEquals(int value, const McCabeMetric& metric);
-
-private:
- MetricEngineFake* m_engine;
- McCabeMetric m_metric;
-};
-
-#endif // QTEST_METRICENGINETEST_H_INCLUDED
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.cpp (nonexistent)
@@ -1,144 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "sourcelocationtest.h"
-#include <QtTest/QTest>
-
-#include "metricengine.h"
-#include <kurl.h>
-#include <kdebug.h>
-
-class MetricEngineFake : public MetricEngine
-{
-public:
- QByteArray content;
-protected:
- virtual QByteArray readAll(const KUrl& filename) {
- Q_UNUSED(filename);
- return content;
- }
-};
-
-void SourceLocationTest::init()
-{
- m_engine = new MetricEngineFake;
- m_metric = McCabeMetric();
-}
-
-void SourceLocationTest::cleanup()
-{
-}
-
-// SUT stimulation helper
-QList<McCabeMetric> SourceLocationTest::computeMcCabeMetricFor(const QByteArray& source)
-{
- m_engine->content = source;
- MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
- return mtr.mcCabeComplexity();
-}
-
-// custom assertion
-void SourceLocationTest::assertMetricLineNumberEquals(int expectedLineNr, const McCabeMetric& metric)
-{
- QCOMPARE(metric.line(), expectedLineNr);
-}
-
-
-void SourceLocationTest::function_startOfDocument()
-{
- QList<McCabeMetric> mtr = computeMcCabeMetricFor(
- "void fun() {}\n"
- "\n");
- QCOMPARE(1, mtr.count());
- assertMetricLineNumberEquals(1, mtr[0]);
-}
-
-void SourceLocationTest::function_middle()
-{
- QList<McCabeMetric> mtr = computeMcCabeMetricFor(
- "\n"
- "void fun() {}\n"
- "\n");
- QCOMPARE(1, mtr.count());
- assertMetricLineNumberEquals(2, mtr[0]);
-}
-
-void SourceLocationTest::function_endOfDocument()
-{
- QList<McCabeMetric> mtr = computeMcCabeMetricFor(
- "\n"
- "void fun() {}");
- QCOMPARE(1, mtr.count());
- assertMetricLineNumberEquals(2, mtr[0]);
-}
-
-namespace
-{
-
-McCabeMetric retrieveMetricForFunction(const QString& functionName, QList<McCabeMetric>& metrics)
-{
- foreach(const McCabeMetric& mtr, metrics) {
- if (mtr.function() == functionName) {
- kDebug() << mtr.function();
- return mtr;
- }
- }
- return McCabeMetric();
-}
-
-}
-
-void SourceLocationTest::function_multiple()
-{
- QList<McCabeMetric> mtr = computeMcCabeMetricFor(
- "void foo() {}\n"
- "void bar() {}\n"
- "void baz() {}\n");
- QCOMPARE(3, mtr.count());
- McCabeMetric fooMtr = retrieveMetricForFunction("foo()", mtr);
- assertMetricLineNumberEquals(1, fooMtr);
- McCabeMetric barMtr = retrieveMetricForFunction("bar()", mtr);
- assertMetricLineNumberEquals(2, barMtr);
- McCabeMetric bazMtr = retrieveMetricForFunction("baz()", mtr);
- assertMetricLineNumberEquals(3, bazMtr);
-}
-
-void SourceLocationTest::function_whitespace()
-{
- QList<McCabeMetric> mtr = computeMcCabeMetricFor(
- "\n\n\n"
- " void bar() {\n}\n");
- QCOMPARE(1, mtr.count());
- assertMetricLineNumberEquals(4, mtr[0]);
-}
-
-void SourceLocationTest::tdd_class_middle()
-{
- QFAIL("No class metrics yet, can not test.");
-}
-
-void SourceLocationTest::tdd_function_class_mixed()
-{
- QFAIL("No class metrics yet, can not test.");
-}
-
-QTEST_MAIN( SourceLocationTest )
-#include "sourcelocationtest.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/sourcelocationtest.h (nonexistent)
@@ -1,54 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef QTEST_SOURCELOCATIONTEST_H_INCLUDED
-#define QTEST_SOURCELOCATIONTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include "metrics.h"
-
-class MetricEngineFake;
-
-class SourceLocationTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void function_startOfDocument();
- void function_middle();
- void function_endOfDocument();
- void function_multiple();
- void function_whitespace();
-
- void tdd_class_middle();
- void tdd_function_class_mixed();
-
-private:
- void assertMetricLineNumberEquals(int expectedLineNr, const McCabeMetric& metric);
- QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
-
- MetricEngineFake* m_engine;
- McCabeMetric m_metric;
-};
-
-#endif // QTEST_SOURCELOCATIONTEST_H_INCLUDED
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.cpp (nonexistent)
@@ -1,286 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#include "functionnametest.h"
-#include <QtTest/QTest>
-#include "metricengine.h"
-#include <kurl.h>
-
-class MetricEngineFake : public MetricEngine
-{
-public:
- QByteArray content;
-protected:
- virtual QByteArray readAll(const KUrl& filename) {
- Q_UNUSED(filename);
- return content;
- }
-};
-
-void FunctionNameTest::init()
-{
- m_engine = new MetricEngineFake;
- m_metric = McCabeMetric();
-}
-
-void FunctionNameTest::cleanup()
-{
- if (m_engine) delete m_engine;
-}
-
-// SUT stimulation helper
-QList<McCabeMetric> FunctionNameTest::computeMcCabeMetricFor(const QByteArray& source)
-{
- m_engine->content = source;
- MetricStore mtr = m_engine->process(KUrl("dummy.cpp"));
- return mtr.mcCabeComplexity();
-}
-
-// custom assertion
-void FunctionNameTest::assertMetricFunctionEquals(const QString& function, const McCabeMetric& metric)
-{
- QCOMPARE(metric.function(), function);
-}
-
-
-// command
-void FunctionNameTest::multipleFunctions_singlePath()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "void foo() {}\n"
- "void bar() {}\n");
-
- QCOMPARE(2, cm.count());
- assertMetricFunctionEquals("foo()", cm[0]);
- assertMetricFunctionEquals("bar()", cm[1]);
-}
-
-// command
-void FunctionNameTest::classMemberFunction_singlePath()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor("void Foo::foo() {}");
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("Foo::foo()", cm[0]);
-}
-
-// command
-void FunctionNameTest::nestedClassMemberFunction_singlePath()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor("void Foo::Bar::baz() {}");
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("Foo::Bar::baz()", cm[0]);
-}
-
-// command
-void FunctionNameTest::namespaceFunction_singlePath()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "namespace Foo {"
- " void foo() {} "
- " namespace Bar { "
- " void bar() {} "
- " }"
- " void foo2() {} "
- "}"
- "void baz() {}");
-
- QCOMPARE(4, cm.count());
- assertMetricFunctionEquals("Foo::foo()", cm[0]);
- assertMetricFunctionEquals("Foo::Bar::bar()", cm[1]);
- assertMetricFunctionEquals("Foo::foo2()", cm[2]);
- assertMetricFunctionEquals("baz()", cm[3]);
-}
-
-// command
-void FunctionNameTest::usingMemberFunction()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "using Foo::Bar; void Bar::baz() {}"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("Foo::Bar::baz()", cm[0]);
-}
-
-// command
-void FunctionNameTest::usingFreeStandingFunction()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "using Foo::bar; void bar() {}"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("Foo::bar()", cm[0]);
-}
-
-// command
-void FunctionNameTest::operatorFunction()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class A{}; int operator+(A a, A b) { return 0; }"
- );
-
- // just make sure it doesnt crash, the C++ parser seems to fail when
- // trying to retrieve the function name for operator functions.
-
- QCOMPARE(0, cm.count()); // should be fixed some day, for now be happy
-}
-
-// command
-void FunctionNameTest::anonymousNamespace()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "namespace { void bar() {} }"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("<anonymous>::bar()", cm[0]);
-}
-
-// command
-void FunctionNameTest::inlineClassMemberFunction()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class Foo { public: void foo() {} }; "
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("Foo::foo()", cm[0]);
-}
-
-// command
-void FunctionNameTest::nestedInlineClassMemberFunction()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class Foo { "
- "public: "
- " void foo() {} "
- " class Bar { "
- " public: void bar() {} "
- " }; "
- " void foo2() {} "
- "}; "
- "void baz() {}\n"
- );
-
- QCOMPARE(4, cm.count());
- assertMetricFunctionEquals("Foo::foo()", cm[0]);
- assertMetricFunctionEquals("Foo::Bar::bar()", cm[1]);
- assertMetricFunctionEquals("Foo::foo2()", cm[2]);
- assertMetricFunctionEquals("baz()", cm[3]);
-}
-
-// command
-void FunctionNameTest::function_singleArgument()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "void foo(int i) {}\n"
- "class Bar {};\n"
- "void bar(Bar b) {}\n"
- );
-
- QCOMPARE(2, cm.count());
- assertMetricFunctionEquals("foo(int)", cm[0]);
- assertMetricFunctionEquals("bar(Bar)", cm[1]);
-}
-
-// command
-void FunctionNameTest::function_multipleArguments()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class Bar {};\n"
- "void bar(int i, Bar b) {}\n"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("bar(int,Bar)", cm[0]);
-}
-
-// command
-void FunctionNameTest::function_templateArgument()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "template <typename T> class Foo {};\n"
- "void foo(Foo<int> bar) {}\n"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("foo(Foo<int>)", cm[0]);
-}
-
-// command
-void FunctionNameTest::function_qualifiedArgument()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "namespace Foo { class Bar {}; }\n"
- "void foo(Foo::Bar b) {} \n"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("foo(Foo::Bar)", cm[0]);
-}
-
-void FunctionNameTest::tdd_constRefArgument()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class A {};\n"
- "void foo(const A& a) {} \n"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("foo(const A&)", cm[0]);
-}
-
-void FunctionNameTest::tdd_pointerArgument()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class A {};\n"
- "void foo(A* a) {} \n"
- );
-
- QCOMPARE(1, cm.count());
- assertMetricFunctionEquals("foo(A*)", cm[0]);
-}
-
-
-// command
-void FunctionNameTest::anonymousType()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "class { void foo() {} } bar;\n"
- "struct { void zoo() {} } baz;\n");
-
- QCOMPARE(2, cm.count());
- assertMetricFunctionEquals("<anonymous-type>::foo()", cm[0]);
- assertMetricFunctionEquals("<anonymous-type>::zoo()", cm[1]);
-}
-
-// command
-void FunctionNameTest::garbage()
-{
- QList<McCabeMetric> cm = computeMcCabeMetricFor(
- "invalid c++ , () {}");
-}
-
-QTEST_MAIN( FunctionNameTest )
-#include "functionnametest.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/tests/functionnametest.h (nonexistent)
@@ -1,66 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef QTEST_FUNCTIONNAMETEST_H_INCLUDED
-#define QTEST_FUNCTIONNAMETEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include "metrics.h"
-
-class MetricEngineFake;
-
-class FunctionNameTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void multipleFunctions_singlePath();
- void classMemberFunction_singlePath();
- void nestedClassMemberFunction_singlePath();
- void namespaceFunction_singlePath();
- void usingMemberFunction();
- void usingFreeStandingFunction();
- void inlineClassMemberFunction();
- void nestedInlineClassMemberFunction();
-
- void operatorFunction();
- void anonymousNamespace();
- void function_singleArgument();
- void function_multipleArguments();
- void function_templateArgument();
- void function_qualifiedArgument();
- void anonymousType();
- void tdd_constRefArgument();
- void tdd_pointerArgument();
-
- void garbage();
-
-private:
- void assertMetricFunctionEquals(const QString& name, const McCabeMetric& metric);
-
- QList<McCabeMetric> computeMcCabeMetricFor(const QByteArray& source);
- MetricEngineFake* m_engine;
- McCabeMetric m_metric;
-};
-
-#endif // QTEST_FUNCTIONNAMETEST_H_INCLUDED
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/CMakeLists.txt (nonexistent)
@@ -1,9 +0,0 @@
-project(McCabe)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${McCabe_SOURCE_DIR}/cmake/)
-cmake_minimum_required(VERSION 2.6)
-find_package(Qt4 REQUIRED)
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-add_subdirectory(src)
-add_subdirectory(tests)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/mccabe.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/mccabe.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/mccabe.kdev4 (nonexistent)
@@ -1,4 +0,0 @@
-[Project]
-Name=McCabe
-Manager=KDevCMakeManager
-VersionControl=
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cyclocomplexity_whitepaper.pdf
___________________________________________________________________
Deleted: svn:mime-type
## -1 +0,0 ##
-application/octet-stream
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parsesession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parsesession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parsesession.h (nonexistent)
@@ -1,91 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef PARSESESSION_H
-#define PARSESESSION_H
-
-#include <cstdlib>
-
-#include <QtCore/QString>
-#include <QtCore/QByteArray>
-
-#include <language/editor/simplecursor.h>
-
-#include <cppparserexport.h>
-#include <ksharedptr.h>
-#include <kurl.h>
-#include "rpp/anchor.h"
-
-#include <language/duchain/indexedstring.h>
-
-namespace Cpp {
- class EnvironmentFile;
-}
-
-class pool;
-class TokenStream;
-class Token;
-
-typedef QVector<unsigned int> PreprocessedContents;
-
-namespace rpp { class MacroBlock; class LocationTable; }
-
-/// Contains everything needed to keep an AST useful once the rest of the parser
-/// has gone away.
-class KDEVCPPPARSER_EXPORT ParseSession
-{
-public:
- ///@todo Make stringUnifier unnecessary by moving the string-repository into the parser
- ParseSession();
- ~ParseSession();
-
- /**
- * Return the position of the preprocessed source \a offset in the original source
- * If the "collapsed" member of the returned anchor is true, the position is within a collapsed range.
- @param collapseIfMacroExpansion @see LocationTable::positionForOffset
- * \note the return line starts from 0, not 1.
- */
- rpp::Anchor positionAt(std::size_t offset, bool collapseIfMacroExpansion = false) const;
-
- QPair<rpp::Anchor, uint> positionAndSpaceAt(std::size_t offset, bool collapseIfMacroExpansion = false) const;
-
- ///The contents must already be tokenized. Either by the preprocessor, or by tokenizeFromByteArray(..)
- void setContents(const PreprocessedContents& contents, rpp::LocationTable* locationTable);
-
- /// Unweildy name, but we want to be clear here, if there is already a location table, this would be the wrong setup function to call
- void setContentsAndGenerateLocationTable(const PreprocessedContents& contents);
-
- void setUrl(const KDevelop::IndexedString& url); ///@todo change to IndexedString
- const KDevelop::IndexedString& url() const;
-
- uint *contents();
- const uint *contents() const;
- const PreprocessedContents& contentsVector() const;
- std::size_t size() const;
- pool* mempool;
- TokenStream* token_stream;
-
- rpp::MacroBlock* macros;
- KDevelop::IndexedString m_url; //Should contain the url from which the content was extracted, can also be empty.
-
-private:
- PreprocessedContents m_contents;
- rpp::LocationTable* m_locationTable;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/ast.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/ast.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/ast.h (nonexistent)
@@ -1,917 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef AST_H
-#define AST_H
-
-#include "memorypool.h"
-#include "listnode.h"
-
-#define DECLARE_AST_NODE(k) \
- enum { __node_kind = Kind_##k };
-
-class ParseSession;
-namespace KDevelop
-{
-class DUContext;
-}
-struct AccessSpecifierAST;
-struct AsmDefinitionAST;
-struct BaseClauseAST;
-struct BaseSpecifierAST;
-struct BinaryExpressionAST;
-struct CastExpressionAST;
-struct ClassMemberAccessAST;
-struct ClassSpecifierAST;
-struct CompoundStatementAST;
-struct ConditionAST;
-struct ConditionalExpressionAST;
-struct CppCastExpressionAST;
-struct CtorInitializerAST;
-struct DeclarationAST;
-struct DeclarationStatementAST;
-struct DeclaratorAST;
-struct DeleteExpressionAST;
-struct DoStatementAST;
-struct Elaborated;
-struct EnumSpecifierAST;
-struct EnumeratorAST;
-struct ExceptionSpecificationAST;
-struct ExpressionAST;
-struct ExpressionOrDeclarationStatementAST;
-struct ExpressionStatementAST;
-struct ForStatementAST;
-struct FunctionCallAST;
-struct FunctionDefinitionAST;
-struct IfStatementAST;
-struct IncrDecrExpressionAST;
-struct InitDeclaratorAST;
-struct InitializerAST;
-struct InitializerClauseAST;
-struct LabeledStatementAST;
-struct LinkageBodyAST;
-struct LinkageSpecificationAST;
-struct MemInitializerAST;
-struct NameAST;
-struct NamespaceAST;
-struct NamespaceAliasDefinitionAST;
-struct NewDeclaratorAST;
-struct NewExpressionAST;
-struct NewInitializerAST;
-struct NewTypeIdAST;
-struct OperatorAST;
-struct OperatorFunctionIdAST;
-struct ParameterDeclarationAST;
-struct ParameterDeclarationClauseAST;
-struct PostfixExpressionAST;
-struct PrimaryExpressionAST;
-struct PtrOperatorAST;
-struct PtrToMemberAST;
-struct ReturnStatementAST;
-struct SimpleDeclarationAST;
-struct SimpleTypeSpecifierAST;
-struct SizeofExpressionAST;
-struct StatementAST;
-struct StringLiteralAST;
-struct SubscriptExpressionAST;
-struct SwitchStatementAST;
-struct TemplateArgumentAST;
-struct TemplateDeclarationAST;
-struct TemplateParameterAST;
-struct ThrowExpressionAST;
-struct TranslationUnitAST;
-struct TryBlockStatementAST;
-struct CatchStatementAST;
-struct TypeIdAST;
-struct TypeIdentificationAST;
-struct TypeParameterAST;
-struct TypeSpecifierAST;
-struct TypedefAST;
-struct UnaryExpressionAST;
-struct UnqualifiedNameAST;
-struct UsingAST;
-struct UsingDirectiveAST;
-struct WhileStatementAST;
-struct WinDeclSpecAST;
-
-struct AST
-{///@warning When adding new nodes here, also modify the names[] array in dumptree.cpp
- enum NODE_KIND
- {
- Kind_UNKNOWN = 0,
-
- Kind_AccessSpecifier, // 1
- Kind_AsmDefinition, // 2
- Kind_BaseClause, // 3
- Kind_BaseSpecifier, // 4
- Kind_BinaryExpression, // 5
- Kind_CastExpression, // 6
- Kind_ClassMemberAccess, // 7
- Kind_ClassSpecifier, // 8
- Kind_CompoundStatement, // 9
- Kind_Condition, // 10
- Kind_ConditionalExpression, // 11
- Kind_CppCastExpression, // 12
- Kind_CtorInitializer, // 13
- Kind_DeclarationStatement, // 14
- Kind_Declarator, // 15
- Kind_DeleteExpression, // 16
- Kind_DoStatement, // 17
- Kind_ElaboratedTypeSpecifier, // 18
- Kind_EnumSpecifier, // 19
- Kind_Enumerator, // 20
- Kind_ExceptionSpecification, // 21
- Kind_ExpressionOrDeclarationStatement, // 22
- Kind_ExpressionStatement, // 23
- Kind_ForStatement, // 24
- Kind_FunctionCall, // 25
- Kind_FunctionDefinition, // 26
- Kind_IfStatement, // 27
- Kind_IncrDecrExpression, // 28
- Kind_InitDeclarator, // 29
- Kind_Initializer, // 30
- Kind_InitializerClause, // 31
- Kind_LabeledStatement, // 32
- Kind_LinkageBody, // 33
- Kind_LinkageSpecification, // 34
- Kind_MemInitializer, // 35
- Kind_Name, // 36
- Kind_Namespace, // 37
- Kind_NamespaceAliasDefinition, // 38
- Kind_NewDeclarator, // 39
- Kind_NewExpression, // 40
- Kind_NewInitializer, // 41
- Kind_NewTypeId, // 42
- Kind_Operator, // 43
- Kind_OperatorFunctionId, // 44
- Kind_ParameterDeclaration, // 45
- Kind_ParameterDeclarationClause, // 46
- Kind_PostfixExpression, // 47
- Kind_PrimaryExpression, // 48
- Kind_PtrOperator, // 49
- Kind_PtrToMember, // 50
- Kind_ReturnStatement, // 51
- Kind_SimpleDeclaration, // 52
- Kind_SimpleTypeSpecifier, // 53
- Kind_SizeofExpression, // 54
- Kind_StringLiteral, // 55
- Kind_SubscriptExpression, // 56
- Kind_SwitchStatement, // 57
- Kind_TemplateArgument, // 58
- Kind_TemplateDeclaration, // 59
- Kind_TemplateParameter, // 60
- Kind_ThrowExpression, // 61
- Kind_TranslationUnit, // 62
- Kind_TryBlockStatement, // 63
- Kind_CatchStatement, // 64
- Kind_TypeId, // 65
- Kind_TypeIdentification, // 66
- Kind_TypeParameter, // 67
- Kind_Typedef, // 68
- Kind_UnaryExpression, // 69
- Kind_UnqualifiedName, // 70
- Kind_Using, // 71
- Kind_UsingDirective, // 72
- Kind_WhileStatement, // 73
- Kind_WinDeclSpec, // 74
- Kind_Comment, // 75
- Kind_JumpStatement, // 76
- NODE_KIND_COUNT
- };
-
- int kind;
-
- std::size_t start_token;
- std::size_t end_token;
-
- /** Context opened by this AST
- *This is usually not filled for all AST's, only for those that open a new context
- */
- KDevelop::DUContext* ducontext;
-};
-
-struct CommentAST {
- const ListNode<std::size_t> *comments; //A list of comment-tokens
-};
-
-struct TypeSpecifierAST: public AST
-{
- const ListNode<std::size_t> *cv; // const or volatile tokens
-};
-
-struct StatementAST: public AST
-{
-};
-
-struct ExpressionAST: public AST
-{
-};
-
-struct DeclarationAST: public AST, public CommentAST
-{
-};
-
-struct AccessSpecifierAST: public DeclarationAST
-{
- DECLARE_AST_NODE(AccessSpecifier)
-
- const ListNode<std::size_t> *specs;
-};
-
-struct AsmDefinitionAST: public DeclarationAST
-{
- DECLARE_AST_NODE(AsmDefinition)
-
- const ListNode<std::size_t> *cv;
-};
-
-struct BaseClauseAST: public AST // ### kill me
-{
- DECLARE_AST_NODE(BaseClause)
-
- const ListNode<BaseSpecifierAST*> *base_specifiers;
-};
-
-struct BaseSpecifierAST: public AST
-{
- DECLARE_AST_NODE(BaseSpecifier)
-
- std::size_t virt;
- std::size_t access_specifier;
- NameAST *name;
-};
-
-struct BinaryExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(BinaryExpression)
-
- std::size_t op; //Index of the token that describes the operator
- ExpressionAST *left_expression;
- ExpressionAST *right_expression;
-};
-
-struct CastExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(CastExpression)
-
- TypeIdAST *type_id;
- ExpressionAST *expression;
-};
-
-struct ClassMemberAccessAST: public ExpressionAST
-{
- DECLARE_AST_NODE(ClassMemberAccess)
-
- std::size_t op; //Index of the token that describes the operator
- NameAST *name;
-};
-
-struct ClassSpecifierAST: public TypeSpecifierAST
-{
- DECLARE_AST_NODE(ClassSpecifier)
-
- WinDeclSpecAST *win_decl_specifiers;
- std::size_t class_key;
- NameAST *name;
- BaseClauseAST *base_clause;
- const ListNode<DeclarationAST*> *member_specs;
-};
-
-struct CompoundStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(CompoundStatement)
-
- const ListNode<StatementAST*> *statements;
-};
-
-struct ConditionAST: public AST
-{
- DECLARE_AST_NODE(Condition)
-
- TypeSpecifierAST *type_specifier;
- DeclaratorAST *declarator;
- ExpressionAST *expression;
-};
-
-struct ConditionalExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(ConditionalExpression)
-
- ExpressionAST *condition;
- ExpressionAST *left_expression;
- ExpressionAST *right_expression;
-};
-
-/**
- * type_id is the type that should be casted to
- * expression is the expression casted from
- * sub_expressions is a list of post-fix expressions, see PostfixExpressionAST
- */
-struct CppCastExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(CppCastExpression)
-
- std::size_t op; //Index of the token that describes the operator
- TypeIdAST *type_id;
- ExpressionAST *expression;
- const ListNode<ExpressionAST*> *sub_expressions;
-};
-
-struct CtorInitializerAST: public AST
-{
- DECLARE_AST_NODE(CtorInitializer)
-
- std::size_t colon;
- const ListNode<MemInitializerAST*> *member_initializers;
-};
-
-struct DeclarationStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(DeclarationStatement)
-
- DeclarationAST *declaration;
-};
-
-struct DeclaratorAST: public AST
-{
- DECLARE_AST_NODE(Declarator)
-
- const ListNode<PtrOperatorAST*> *ptr_ops;
- DeclaratorAST *sub_declarator;
- NameAST *id;
- ExpressionAST *bit_expression;
- const ListNode<ExpressionAST*> *array_dimensions;
- ParameterDeclarationClauseAST *parameter_declaration_clause;
- const ListNode<std::size_t> *fun_cv;
- ExceptionSpecificationAST *exception_spec;
-};
-
-struct DeleteExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(DeleteExpression)
-
- std::size_t scope_token;
- std::size_t delete_token;
- std::size_t lbracket_token;
- std::size_t rbracket_token;
- ExpressionAST *expression;
-};
-
-struct DoStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(DoStatement)
-
- StatementAST *statement;
- ExpressionAST *expression;
-};
-
-struct ElaboratedTypeSpecifierAST: public TypeSpecifierAST
-{
- DECLARE_AST_NODE(ElaboratedTypeSpecifier)
-
- std::size_t type;
- NameAST *name;
-};
-
-struct EnumSpecifierAST: public TypeSpecifierAST
-{
- DECLARE_AST_NODE(EnumSpecifier)
-
- NameAST *name;
- const ListNode<EnumeratorAST*> *enumerators;
-};
-
-struct EnumeratorAST: public AST, public CommentAST
-{
- DECLARE_AST_NODE(Enumerator)
-
- std::size_t id;
- ExpressionAST *expression;
-};
-
-struct ExceptionSpecificationAST: public AST
-{
- DECLARE_AST_NODE(ExceptionSpecification)
-
- std::size_t ellipsis;
- const ListNode<TypeIdAST*> *type_ids;
-};
-
-struct ExpressionOrDeclarationStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(ExpressionOrDeclarationStatement)
-
- StatementAST *expression;
- StatementAST *declaration;
-
- // This was not originally part of the AST - added by the context visitor
- bool expressionChosen;
-};
-
-///An expression terminated by a semicolon or similar
-struct ExpressionStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(ExpressionStatement)
-
- ExpressionAST *expression;
-};
-
-struct FunctionCallAST: public ExpressionAST
-{
- DECLARE_AST_NODE(FunctionCall)
-
- ExpressionAST *arguments;
-};
-
-struct FunctionDefinitionAST: public DeclarationAST
-{
- DECLARE_AST_NODE(FunctionDefinition)
-
- const ListNode<std::size_t> *storage_specifiers;
- const ListNode<std::size_t> *function_specifiers;
- TypeSpecifierAST *type_specifier;
- InitDeclaratorAST *init_declarator;
- StatementAST *function_body;
- WinDeclSpecAST *win_decl_specifiers;
- CtorInitializerAST *constructor_initializers;
-};
-
-struct ForStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(ForStatement)
-
- StatementAST *init_statement;
- ConditionAST *condition;
- ExpressionAST *expression;
- StatementAST *statement;
-};
-
-struct IfStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(IfStatement)
-
- ConditionAST *condition;
- StatementAST *statement;
- StatementAST *else_statement;
-};
-
-struct IncrDecrExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(IncrDecrExpression)
-
- std::size_t op; //Index of the token that describes the operator
-};
-
-struct InitDeclaratorAST: public AST
-{
- DECLARE_AST_NODE(InitDeclarator)
-
- DeclaratorAST *declarator;
- InitializerAST *initializer;
-};
-
-struct InitializerAST: public AST
-{
- DECLARE_AST_NODE(Initializer)
-
- InitializerClauseAST *initializer_clause;
- ExpressionAST *expression;
-};
-
-struct InitializerClauseAST: public AST
-{
- DECLARE_AST_NODE(InitializerClause)
-
- // either 'expression' or 'initializer_list' or neither are used.
- // neither are used when the clause represents the empty initializer "{}"
-
- // assignment expression
- ExpressionAST *expression;
- const ListNode<InitializerClauseAST*> *initializer_list;
-};
-
-struct LabeledStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(LabeledStatement)
-
- //The constant label expression
- ExpressionAST *expression;
- StatementAST* statement;
-};
-
-struct LinkageBodyAST: public AST
-{
- DECLARE_AST_NODE(LinkageBody)
-
- const ListNode<DeclarationAST*> *declarations;
-};
-
-struct LinkageSpecificationAST: public DeclarationAST
-{
- DECLARE_AST_NODE(LinkageSpecification)
-
- std::size_t extern_type;
- LinkageBodyAST *linkage_body;
- DeclarationAST *declaration;
-};
-
-struct MemInitializerAST: public AST
-{
- DECLARE_AST_NODE(MemInitializer)
-
- NameAST *initializer_id;
- ExpressionAST *expression;
-};
-
-struct NameAST: public AST
-{
- DECLARE_AST_NODE(Name)
-
- bool global;
- const ListNode<UnqualifiedNameAST*> *qualified_names;
- UnqualifiedNameAST *unqualified_name;
-};
-
-struct NamespaceAST: public DeclarationAST
-{
- DECLARE_AST_NODE(Namespace)
-
- std::size_t namespace_name;
- LinkageBodyAST *linkage_body;
-};
-
-struct NamespaceAliasDefinitionAST: public DeclarationAST
-{
- DECLARE_AST_NODE(NamespaceAliasDefinition)
-
- std::size_t namespace_name;
- NameAST *alias_name;
-};
-
-struct NewDeclaratorAST: public AST
-{
- DECLARE_AST_NODE(NewDeclarator)
-
- PtrOperatorAST *ptr_op;
- NewDeclaratorAST *sub_declarator;
- const ListNode<ExpressionAST*> *expressions;
-};
-
-struct NewExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(NewExpression)
-
- std::size_t scope_token;
- std::size_t new_token;
- ExpressionAST *expression;
- TypeIdAST *type_id;
- NewTypeIdAST *new_type_id;
- NewInitializerAST *new_initializer;
-};
-
-struct NewInitializerAST: public AST
-{
- DECLARE_AST_NODE(NewInitializer)
-
- ExpressionAST *expression;
-};
-
-struct NewTypeIdAST: public AST
-{
- DECLARE_AST_NODE(NewTypeId)
-
- TypeSpecifierAST *type_specifier;
- NewInitializerAST *new_initializer;
- NewDeclaratorAST *new_declarator;
-};
-
-struct OperatorAST: public AST
-{
- DECLARE_AST_NODE(Operator)
-
- std::size_t op; //Index of the token that describes the operator
- std::size_t open;
- std::size_t close;
-};
-
-struct OperatorFunctionIdAST: public AST
-{
- DECLARE_AST_NODE(OperatorFunctionId)
-
- OperatorAST *op;
- TypeSpecifierAST *type_specifier;
- const ListNode<PtrOperatorAST*> *ptr_ops;
-};
-
-struct ParameterDeclarationAST: public AST
-{
- DECLARE_AST_NODE(ParameterDeclaration)
-
- TypeSpecifierAST *type_specifier;
- DeclaratorAST *declarator;
- ExpressionAST *expression;
-};
-
-struct ParameterDeclarationClauseAST: public AST
-{
- DECLARE_AST_NODE(ParameterDeclarationClause)
-
- const ListNode<ParameterDeclarationAST*> *parameter_declarations;
- std::size_t ellipsis;
-};
-
-/**
- * A post-fix expression is an expression that consists of one primary expression and multiple sub-expressions that are evaluated from
- * left to right, each sub-expression based on the previous expression.
- *
- *
- * Examples:
- * "a->b" : "a" is the primary expression, "->b" is a sub-expression
- * "a->b(5,3)" : "a" is the primary expression, "->b" is a sub-expression, and "(5,3)" is a sub-expression
- **/
-struct PostfixExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(PostfixExpression)
-
- TypeSpecifierAST *type_specifier;
- ExpressionAST *expression;
- const ListNode<ExpressionAST*> *sub_expressions;
-};
-
-struct PrimaryExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(PrimaryExpression)
-
- StringLiteralAST *literal;
- std::size_t token;
- StatementAST *expression_statement;
- ExpressionAST *sub_expression;
- NameAST *name;
-};
-
-struct PtrOperatorAST: public AST
-{
- DECLARE_AST_NODE(PtrOperator)
-
- const ListNode<std::size_t> *cv;
- std::size_t op; //Index of the token that describes the operator. Is zero when mem_ptr is non-zero.
- PtrToMemberAST *mem_ptr;
-};
-
-struct PtrToMemberAST: public AST
-{
- DECLARE_AST_NODE(PtrToMember)
-};
-
-struct JumpStatementAST : public StatementAST
-{
- DECLARE_AST_NODE(JumpStatement)
-
- // index of operator token which describes the jump, one of
- // 'break', 'continue' or 'goto. Return statements are handled by
- // ReturnStatementAST
- std::size_t op;
- // identifier for 'goto' statements
- std::size_t identifier;
-};
-
-struct ReturnStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(ReturnStatement)
-
- ExpressionAST *expression;
-};
-
-struct SimpleDeclarationAST: public DeclarationAST
-{
- DECLARE_AST_NODE(SimpleDeclaration)
-
- const ListNode<std::size_t> *storage_specifiers;
- const ListNode<std::size_t> *function_specifiers;
- TypeSpecifierAST *type_specifier;
- const ListNode<InitDeclaratorAST*> *init_declarators;
- WinDeclSpecAST *win_decl_specifiers;
-};
-
-struct SimpleTypeSpecifierAST: public TypeSpecifierAST
-{
- DECLARE_AST_NODE(SimpleTypeSpecifier)
-
- const ListNode<std::size_t> *integrals;
- std::size_t type_of;
- TypeIdAST *type_id;
- ExpressionAST *expression;
- NameAST *name;
-};
-
-struct SizeofExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(SizeofExpression)
-
- std::size_t sizeof_token;
- TypeIdAST *type_id;
- ExpressionAST *expression;
-};
-
-struct StringLiteralAST: public AST
-{
- DECLARE_AST_NODE(StringLiteral)
-
- const ListNode<std::size_t> *literals;
-};
-
-/// operator []
-struct SubscriptExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(SubscriptExpression)
-
- ExpressionAST *subscript;
-};
-
-struct SwitchStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(SwitchStatement)
-
- ConditionAST *condition;
- StatementAST *statement;
-};
-
-struct TemplateArgumentAST: public AST
-{
- DECLARE_AST_NODE(TemplateArgument)
-
- TypeIdAST *type_id;
- ExpressionAST *expression;
-};
-
-struct TemplateDeclarationAST: public DeclarationAST
-{
- DECLARE_AST_NODE(TemplateDeclaration)
-
- std::size_t exported;
- const ListNode<TemplateParameterAST*> *template_parameters;
- DeclarationAST* declaration;
-};
-
-struct TemplateParameterAST: public AST
-{
- DECLARE_AST_NODE(TemplateParameter)
-
- TypeParameterAST *type_parameter;
- ParameterDeclarationAST *parameter_declaration; //Default-parameter
-};
-
-struct ThrowExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(ThrowExpression)
-
- std::size_t throw_token;
- ExpressionAST *expression;
-};
-
-struct TranslationUnitAST: public AST, public CommentAST
-{
- DECLARE_AST_NODE(TranslationUnit)
-
- const ListNode<DeclarationAST*> *declarations;
-
- // Note: non AST related, saves parsing session...
- ParseSession* session;
-};
-
-struct TryBlockStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(TryBlockStatement)
-
- StatementAST* try_block;
- const ListNode<CatchStatementAST*> *catch_blocks;
-};
-
-struct CatchStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(CatchStatement)
-
- ConditionAST* condition;
- StatementAST* statement;
-};
-
-struct TypeIdAST: public AST
-{
- DECLARE_AST_NODE(TypeId)
-
- TypeSpecifierAST *type_specifier;
- DeclaratorAST *declarator;
-};
-
-///"typename"
-struct TypeIdentificationAST: public ExpressionAST
-{
- DECLARE_AST_NODE(TypeIdentification)
-
- std::size_t typename_token;
- NameAST *name;
- ExpressionAST *expression;
-};
-
-struct TypeParameterAST: public AST
-{
- DECLARE_AST_NODE(TypeParameter)
-
- std::size_t type;
- NameAST *name;
- TypeIdAST *type_id;
- const ListNode<TemplateParameterAST*> *template_parameters;
- NameAST *template_name;
-};
-
-struct TypedefAST: public DeclarationAST
-{
- DECLARE_AST_NODE(Typedef)
-
- TypeSpecifierAST *type_specifier;
- const ListNode<InitDeclaratorAST*> *init_declarators;
-};
-
-struct UnaryExpressionAST: public ExpressionAST
-{
- DECLARE_AST_NODE(UnaryExpression)
-
- std::size_t op; //Index of the token that describes the operator
- ExpressionAST *expression;
-};
-
-struct UnqualifiedNameAST: public AST
-{
- DECLARE_AST_NODE(UnqualifiedName)
-
- std::size_t tilde;
- std::size_t id;
- OperatorFunctionIdAST *operator_id;
- const ListNode<TemplateArgumentAST*> *template_arguments;
-};
-
-struct UsingAST: public DeclarationAST
-{
- DECLARE_AST_NODE(Using)
-
- std::size_t type_name;
- NameAST *name;
-};
-
-struct UsingDirectiveAST: public DeclarationAST
-{
- DECLARE_AST_NODE(UsingDirective)
-
- NameAST *name;
-};
-
-struct WhileStatementAST: public StatementAST
-{
- DECLARE_AST_NODE(WhileStatement)
-
- ConditionAST *condition;
- StatementAST *statement;
-};
-
-struct WinDeclSpecAST: public AST
-{
- DECLARE_AST_NODE(WinDeclSpec)
-
- std::size_t specifier;
- std::size_t modifier;
-};
-
-template <class _Tp>
-_Tp *CreateNode(pool *memory_pool)
-{
- _Tp *node = reinterpret_cast<_Tp*>(memory_pool->allocate(sizeof(_Tp)));
- node->kind = _Tp::__node_kind;
- return node;
-}
-
-template <class _Tp>
-_Tp ast_cast(AST *item)
-{
- if (item && static_cast<_Tp>(0)->__node_kind == item->kind)
- return static_cast<_Tp>(item);
-
- return 0;
-}
-
-#endif // AST_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/visitor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/visitor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/visitor.h (nonexistent)
@@ -1,134 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef VISITOR_H
-#define VISITOR_H
-
-#include "ast.h"
-#include <cppparserexport.h>
-
-class KDEVCPPPARSER_EXPORT Visitor
-{
-public:
- Visitor();
- virtual ~Visitor();
-
- virtual void visit(AST *node);
-
-protected:
- virtual void visitAccessSpecifier(AccessSpecifierAST *) {}
- virtual void visitAsmDefinition(AsmDefinitionAST *) {}
- virtual void visitBaseClause(BaseClauseAST *) {}
- virtual void visitBaseSpecifier(BaseSpecifierAST *) {}
- virtual void visitBinaryExpression(BinaryExpressionAST *) {}
- virtual void visitCastExpression(CastExpressionAST *) {}
- virtual void visitClassMemberAccess(ClassMemberAccessAST *) {}
- virtual void visitClassSpecifier(ClassSpecifierAST *) {}
- virtual void visitCompoundStatement(CompoundStatementAST *) {}
- virtual void visitCondition(ConditionAST *) {}
- virtual void visitConditionalExpression(ConditionalExpressionAST *) {}
- virtual void visitCppCastExpression(CppCastExpressionAST *) {}
- virtual void visitCtorInitializer(CtorInitializerAST *) {}
- virtual void visitDeclarationStatement(DeclarationStatementAST *) {}
- virtual void visitDeclarator(DeclaratorAST *) {}
- virtual void visitDeleteExpression(DeleteExpressionAST *) {}
- virtual void visitDoStatement(DoStatementAST *) {}
- virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *) {}
- virtual void visitEnumSpecifier(EnumSpecifierAST *) {}
- virtual void visitEnumerator(EnumeratorAST *) {}
- virtual void visitExceptionSpecification(ExceptionSpecificationAST *) {}
- virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *) {}
- virtual void visitExpressionStatement(ExpressionStatementAST *) {}
- virtual void visitForStatement(ForStatementAST *) {}
- virtual void visitFunctionCall(FunctionCallAST *) {}
- virtual void visitFunctionDefinition(FunctionDefinitionAST *) {}
- virtual void visitIfStatement(IfStatementAST *) {}
- virtual void visitIncrDecrExpression(IncrDecrExpressionAST *) {}
- virtual void visitInitDeclarator(InitDeclaratorAST *) {}
- virtual void visitInitializer(InitializerAST *) {}
- virtual void visitInitializerClause(InitializerClauseAST *) {}
- virtual void visitJumpStatement(JumpStatementAST *) {}
- virtual void visitLabeledStatement(LabeledStatementAST *) {}
- virtual void visitLinkageBody(LinkageBodyAST *) {}
- virtual void visitLinkageSpecification(LinkageSpecificationAST *) {}
- virtual void visitMemInitializer(MemInitializerAST *) {}
- virtual void visitName(NameAST *) {}
- virtual void visitNamespace(NamespaceAST *) {}
- virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *) {}
- virtual void visitNewDeclarator(NewDeclaratorAST *) {}
- virtual void visitNewExpression(NewExpressionAST *) {}
- virtual void visitNewInitializer(NewInitializerAST *) {}
- virtual void visitNewTypeId(NewTypeIdAST *) {}
- virtual void visitOperator(OperatorAST *) {}
- virtual void visitOperatorFunctionId(OperatorFunctionIdAST *) {}
- virtual void visitParameterDeclaration(ParameterDeclarationAST *) {}
- virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *) {}
- virtual void visitPostfixExpression(PostfixExpressionAST *) {}
- virtual void visitPrimaryExpression(PrimaryExpressionAST *) {}
- virtual void visitPtrOperator(PtrOperatorAST *) {}
- virtual void visitPtrToMember(PtrToMemberAST *) {}
- virtual void visitReturnStatement(ReturnStatementAST *) {}
- virtual void visitSimpleDeclaration(SimpleDeclarationAST *) {}
- virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *) {}
- virtual void visitSizeofExpression(SizeofExpressionAST *) {}
- virtual void visitStringLiteral(StringLiteralAST *) {}
- virtual void visitSubscriptExpression(SubscriptExpressionAST *) {}
- virtual void visitSwitchStatement(SwitchStatementAST *) {}
- virtual void visitTemplateArgument(TemplateArgumentAST *) {}
- virtual void visitTemplateDeclaration(TemplateDeclarationAST *) {}
- virtual void visitTemplateParameter(TemplateParameterAST *) {}
- virtual void visitThrowExpression(ThrowExpressionAST *) {}
- virtual void visitTranslationUnit(TranslationUnitAST *) {}
- virtual void visitTryBlockStatement(TryBlockStatementAST *) {}
- virtual void visitCatchStatement(CatchStatementAST *) {}
- virtual void visitTypeId(TypeIdAST *) {}
- virtual void visitTypeIdentification(TypeIdentificationAST *) {}
- virtual void visitTypeParameter(TypeParameterAST *) {}
- virtual void visitTypedef(TypedefAST *) {}
- virtual void visitUnaryExpression(UnaryExpressionAST *) {}
- virtual void visitUnqualifiedName(UnqualifiedNameAST *) {}
- virtual void visitUsing(UsingAST *) {}
- virtual void visitUsingDirective(UsingDirectiveAST *) {}
- virtual void visitWhileStatement(WhileStatementAST *) {}
- virtual void visitWinDeclSpec(WinDeclSpecAST *) {}
-
-private:
- typedef void (Visitor::*visitor_fun_ptr)(AST *);
- static visitor_fun_ptr _S_table[];
-};
-
-template <class _Tp>
- void visitNodes(Visitor *v, const ListNode<_Tp> *nodes)
- {
- if (!nodes)
- return;
-
- const ListNode<_Tp>
- *it = nodes->toFront(),
- *end = it;
-
- do
- {
- v->visit(it->element);
- it = it->next;
- }
- while (it != end);
- }
-
-#endif // VISITOR_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/parser.h (nonexistent)
@@ -1,262 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef PARSER_H
-#define PARSER_H
-
-#include "ast.h"
-#include "lexer.h"
-#include "commentparser.h"
-
-#include <QtCore/QQueue>
-#include <QtCore/QSet>
-#include <QtCore/QString>
-#include <cppparserexport.h>
-
-class TokenStream;
-class Control;
-
-/**
-The Parser.
-LL(k) parser for c++ code.
-*/
-class KDEVCPPPARSER_EXPORT Parser
-{
-public:
- Parser(Control *control);
- ~Parser();
-
- /**Parses the @p contents of the buffer of given @p size using the
- memory pool @p p to store tokens found.
-
- Calls lexer to tokenize all contents buffer, skips the first token
- (because the lexer provides Token_EOF as the first token,
- creates and fills the AST and returns translation unit or 0
- if nothing was parsed.
-
- @sa pool for more information about the memory pool used.*/
- TranslationUnitAST *parse(ParseSession* session);
-
- /**
- * Same as parse, except that it parses the content as a compound statement.
- * This is useful for parsing independent expression-strings that appear for
- * example within a function.
- *
- * parse(..) expects the content to be a valid translation-unit,
- * while parseStatement can parse strings like "{a.b = 5;}" as if they
- * appeared within a function.
- *
- * Note: The input must be a valid compound-statement, which means it must
- * start at least with "{", and end with ";}"
- **/
- StatementAST *parseStatement(ParseSession* session);
-
- /**
- * Nearly the same as parseStatement, except that it parses the content as a type-id if possible,
- * if that fails, as an expression. This is perfect for parsing template-arguements.
- * The input can be as simple as "A" or "A::a+2"
- * @param forceExpression If this is true, the text will not be considered to be a type-id, only an expression.
- * */
- AST *parseTypeOrExpression(ParseSession* session, bool forceExpression = false);
- /**@return the problem count.*/
- int problemCount() const { return _M_problem_count; }
-
-private:
- /**Convenience method to report problems. Constructs the problem
- using the information about the current line and column in the buffer
- that is being parsed. Then stores the problem in the control object.*/
- void reportError(const QString& msg);
- /**Reports a syntax error about unexpected token. The token
- reported is LA (look-ahead) from the stream.*/
- void syntaxError();
- /**Reports a syntax error about required token when LA is wrong.*/
- void tokenRequiredError(int expected);
-
-public:
- bool parseAbstractDeclarator(DeclaratorAST *&node);
- bool parseAccessSpecifier(DeclarationAST *&node);
- bool parseAdditiveExpression(ExpressionAST *&node);
- bool parseAndExpression(ExpressionAST *&node, bool templArgs = false);
- bool parseAsmDefinition(DeclarationAST *&node);
- bool parseAssignmentExpression(ExpressionAST *&node);
- bool parseBaseClause(BaseClauseAST *&node);
- bool parseBaseSpecifier(BaseSpecifierAST *&node);
- bool parseBlockDeclaration(DeclarationAST *&node);
- bool parseCastExpression(ExpressionAST *&node);
- bool parseClassSpecifier(TypeSpecifierAST *&node);
- bool parseCommaExpression(ExpressionAST *&node);
- bool parseCompoundStatement(StatementAST *&node);
- bool parseCondition(ConditionAST *&node, bool initRequired = true);
- bool parseConditionalExpression(ExpressionAST *&node);
- bool parseConstantExpression(ExpressionAST *&node);
- bool parseCtorInitializer(CtorInitializerAST *&node);
- bool parseCvQualify(const ListNode<std::size_t> *&node);
- bool parseDeclaration(DeclarationAST *&node);
- bool parseDeclarationInternal(DeclarationAST *&node);
- bool parseDeclarationStatement(StatementAST *&node);
- bool parseDeclarator(DeclaratorAST *&node);
- bool parseDeleteExpression(ExpressionAST *&node);
- bool parseDoStatement(StatementAST *&node);
- bool parseElaboratedTypeSpecifier(TypeSpecifierAST *&node);
- bool parseEnumSpecifier(TypeSpecifierAST *&node);
- bool parseEnumerator(EnumeratorAST *&node);
- bool parseEqualityExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseExceptionSpecification(ExceptionSpecificationAST *&node);
- bool parseExclusiveOrExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseExpression(ExpressionAST *&node);
- bool parseExpressionOrDeclarationStatement(StatementAST *&node);
- bool parseExpressionStatement(StatementAST *&node);
- bool parseForInitStatement(StatementAST *&node);
- bool parseForStatement(StatementAST *&node);
- bool parseFunctionBody(StatementAST *&node);
- bool parseFunctionSpecifier(const ListNode<std::size_t> *&node);
- bool parseIfStatement(StatementAST *&node);
- bool parseInclusiveOrExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseInitDeclarator(InitDeclaratorAST *&node);
- bool parseInitDeclaratorList(const ListNode<InitDeclaratorAST*> *&node);
- bool parseInitializer(InitializerAST *&node);
- bool parseInitializerClause(InitializerClauseAST *&node);
- bool parseInitializerList(const ListNode<InitializerClauseAST*> *&node);
- bool parseJumpStatement(StatementAST *&node);
- bool parseLabeledStatement(StatementAST *&node);
- bool parseLinkageBody(LinkageBodyAST *&node);
- bool parseLinkageSpecification(DeclarationAST *&node);
- bool parseLogicalAndExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseLogicalOrExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseMemInitializer(MemInitializerAST *&node);
- bool parseMemInitializerList(const ListNode<MemInitializerAST*> *&node);
- bool parseMemberSpecification(DeclarationAST *&node);
- bool parseMultiplicativeExpression(ExpressionAST *&node);
- bool parseName(NameAST *&node, bool acceptTemplateId = false);
- bool parseNamespace(DeclarationAST *&node);
- bool parseNamespaceAliasDefinition(DeclarationAST *&node);
- bool parseNewDeclarator(NewDeclaratorAST *&node);
- bool parseNewExpression(ExpressionAST *&node);
- bool parseNewInitializer(NewInitializerAST *&node);
- bool parseNewTypeId(NewTypeIdAST *&node);
- bool parseOperator(OperatorAST *&node);
- bool parseOperatorFunctionId(OperatorFunctionIdAST *&node);
- bool parseParameterDeclaration(ParameterDeclarationAST *&node);
- bool parseParameterDeclarationClause(ParameterDeclarationClauseAST *&node);
- bool parseParameterDeclarationList(const ListNode<ParameterDeclarationAST*> *&node);
- bool parsePmExpression(ExpressionAST *&node);
- bool parsePostfixExpression(ExpressionAST *&node);
- bool parsePostfixExpressionInternal(ExpressionAST *&node);
- bool parsePrimaryExpression(ExpressionAST *&node);
- bool parsePtrOperator(PtrOperatorAST *&node);
- bool parsePtrToMember(PtrToMemberAST *&node);
- bool parseRelationalExpression(ExpressionAST *&node,
- bool templArgs = false);
- bool parseShiftExpression(ExpressionAST *&node);
- bool parseSimpleTypeSpecifier(TypeSpecifierAST *&node,
- bool onlyIntegral = false);
- bool parseStatement(StatementAST *&node);
- bool parseStorageClassSpecifier(const ListNode<std::size_t> *&node);
- bool parseStringLiteral(StringLiteralAST *&node);
- bool parseSwitchStatement(StatementAST *&node);
- bool parseTemplateArgument(TemplateArgumentAST *&node);
- bool parseTemplateArgumentList(const ListNode<TemplateArgumentAST*> *&node,
- bool reportError = true);
- bool parseTemplateDeclaration(DeclarationAST *&node);
- bool parseTemplateParameter(TemplateParameterAST *&node);
- bool parseTemplateParameterList(const ListNode<TemplateParameterAST*> *&node);
- bool parseThrowExpression(ExpressionAST *&node);
- bool parseTranslationUnit(TranslationUnitAST *&node);
- bool parseTryBlockStatement(StatementAST *&node);
- bool parseTypeId(TypeIdAST *&node);
- bool parseTypeIdList(const ListNode<TypeIdAST*> *&node);
- bool parseTypeParameter(TypeParameterAST *&node);
- bool parseTypeSpecifier(TypeSpecifierAST *&node);
- bool parseTypeSpecifierOrClassSpec(TypeSpecifierAST *&node);
- bool parseTypedef(DeclarationAST *&node);
- bool parseUnaryExpression(ExpressionAST *&node);
- bool parseUnqualifiedName(UnqualifiedNameAST *&node,
- bool parseTemplateId = true);
- bool parseUsing(DeclarationAST *&node);
- bool parseUsingDirective(DeclarationAST *&node);
- bool parseWhileStatement(StatementAST *&node);
- bool parseWinDeclSpec(WinDeclSpecAST *&node);
-
- bool skipUntil(int token);
- bool skipUntilDeclaration();
- bool skipUntilStatement();
- bool skip(int l, int r);
-
- void addComment( CommentAST* ast, const Comment& comment );
- //Moves all currently available comments to the given AST, removing them from the comment-store
- void moveComments( CommentAST* ast );
-
- void advance(bool skipComment = true);
- void rewind(size_t position);
- // private:
- TokenStream* token_stream;
-
-// private:
- Control *control;
- Lexer lexer;
-private:
-
- int lineFromTokenNumber( size_t tokenNumber ) const;
-
- ///parses all comments until the end of the line
- Comment comment();
- ///Preparses comments in the same line as given token-number
- void preparseLineComments( int tokenNumber );
- void processComment( int offset = 0, int line = -1 );
- void clearComment( );
-
- bool holdErrors(bool hold);
- void reportPendingErrors();
-
- Comment m_currentComment;
- CommentStore m_commentStore;
-
- int _M_problem_count;
- int _M_max_problem_count;
- ParseSession* session;
- bool _M_hold_errors;
- size_t _M_last_valid_token; //Last encountered token that was not a comment
- size_t _M_last_parsed_comment;
-
- // keeps track of tokens where a syntax error has been found
- // so that the same error is not reported twice for a token
- QSet<std::size_t> m_syntaxErrorTokens;
-
- // when _M_hold_errors is true, reported errors are held in m_pendingErrors
- // rather than being reported to the Control immediately.
- //
- // this is used, for example, when parsing ambiguous statements.
- struct PendingError
- {
- QString message;
- std::size_t cursor;
- };
- QQueue<PendingError> m_pendingErrors;
-
-private:
- Parser(const Parser& source);
- void operator = (const Parser& source);
-};
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/name_compiler.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/name_compiler.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/name_compiler.h (nonexistent)
@@ -1,68 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef NAME_COMPILER_H
-#define NAME_COMPILER_H
-
-#include "default_visitor.h"
-#include <language/duchain/identifier.h>
-#include <cppparserexport.h>
-#include <language/duchain/declaration.h>
-
-class ParseSession;
-class OperatorAST;
-
-class KDEVCPPPARSER_EXPORT NameCompiler: protected DefaultVisitor
-{
-public:
- NameCompiler(ParseSession* session);
-
- void run(NameAST *node);
- void run(UnqualifiedNameAST *node) { m_typeSpecifier = 0; internal_run(node); }
-
- QString name() const { return _M_name.toString(); }
- QStringList qualifiedName() const { return _M_name.toStringList(); }
-
- const KDevelop::QualifiedIdentifier& identifier() const;
-
- /**
- * When the name contains one type-specifier, this should contain that specifier after the run.
- * Especially this is the type-specifier of a conversion-operator like "operator int()"
- * */
- TypeSpecifierAST* lastTypeSpecifier() const;
-
-protected:
- virtual void visitUnqualifiedName(UnqualifiedNameAST *node);
- virtual void visitTemplateArgument(TemplateArgumentAST *node);
-
- void internal_run(AST *node);
-
-private:
- ParseSession* m_session;
- TypeSpecifierAST* m_typeSpecifier;
- KDevelop::QualifiedIdentifier m_base;
- KDevelop::Identifier m_currentIdentifier;
- KDevelop::QualifiedIdentifier _M_name;
-};
-
-//Extracts a type-identifier from a template argument
-KDevelop::TypeIdentifier KDEVCPPPARSER_EXPORT typeIdentifierFromTemplateArgument(ParseSession* session, TemplateArgumentAST *node);
-uint KDEVCPPPARSER_EXPORT parseConstVolatile(ParseSession* session, const ListNode<std::size_t> *cv);
-
-#endif // NAME_COMPILER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/control.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/control.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/control.h (nonexistent)
@@ -1,52 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef CONTROL_H
-#define CONTROL_H
-
-#include "symbol.h"
-#include "memorypool.h"
-#include <language/interfaces/iproblem.h>
-#include <cppparserexport.h>
-
-#include <QtCore/QHash>
-
-struct Declarator;
-struct Type;
-
-/**Parser control information.
-Provides problem tracking, context(visibility)-aware symbol name tables,
-typedef table and other information about the parsing process.*/
-class KDEVCPPPARSER_EXPORT Control
-{
-public:
- Control();
- ~Control();
-
- const QList<KDevelop::ProblemPointer>& problems() const;
-
- /**Adds a problem to the list of problems.*/
- void reportProblem(const KDevelop::ProblemPointer &problem);
- void reportProblem(const KDevelop::Problem &problem);
-
-private:
- QList<KDevelop::ProblemPointer> _M_problems;
-};
-
-#endif // CONTROL_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/default_visitor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/default_visitor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/default_visitor.h (nonexistent)
@@ -1,113 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef DEFAULT_VISITOR_H
-#define DEFAULT_VISITOR_H
-
-#include "visitor.h"
-#include <cppparserexport.h>
-
-class KDEVCPPPARSER_EXPORT DefaultVisitor: public Visitor
-{
-public:
- DefaultVisitor() {}
-
-protected:
- virtual void visitAccessSpecifier(AccessSpecifierAST *);
- virtual void visitAsmDefinition(AsmDefinitionAST *);
- virtual void visitBaseClause(BaseClauseAST *);
- virtual void visitBaseSpecifier(BaseSpecifierAST *);
- virtual void visitBinaryExpression(BinaryExpressionAST *);
- virtual void visitCastExpression(CastExpressionAST *);
- virtual void visitClassMemberAccess(ClassMemberAccessAST *);
- virtual void visitClassSpecifier(ClassSpecifierAST *);
- virtual void visitCompoundStatement(CompoundStatementAST *);
- virtual void visitCondition(ConditionAST *);
- virtual void visitConditionalExpression(ConditionalExpressionAST *);
- virtual void visitCppCastExpression(CppCastExpressionAST *);
- virtual void visitCtorInitializer(CtorInitializerAST *);
- virtual void visitDeclarationStatement(DeclarationStatementAST *);
- virtual void visitDeclarator(DeclaratorAST *);
- virtual void visitDeleteExpression(DeleteExpressionAST *);
- virtual void visitDoStatement(DoStatementAST *);
- virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *);
- virtual void visitEnumSpecifier(EnumSpecifierAST *);
- virtual void visitEnumerator(EnumeratorAST *);
- virtual void visitExceptionSpecification(ExceptionSpecificationAST *);
- virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *);
- virtual void visitExpressionStatement(ExpressionStatementAST *);
- virtual void visitForStatement(ForStatementAST *);
- virtual void visitFunctionCall(FunctionCallAST *);
- virtual void visitFunctionDefinition(FunctionDefinitionAST *);
- virtual void visitIfStatement(IfStatementAST *);
- virtual void visitIncrDecrExpression(IncrDecrExpressionAST *);
- virtual void visitInitDeclarator(InitDeclaratorAST *);
- virtual void visitInitializer(InitializerAST *);
- virtual void visitInitializerClause(InitializerClauseAST *);
- virtual void visitJumpStatement(JumpStatementAST *);
- virtual void visitLabeledStatement(LabeledStatementAST *);
- virtual void visitLinkageBody(LinkageBodyAST *);
- virtual void visitLinkageSpecification(LinkageSpecificationAST *);
- virtual void visitMemInitializer(MemInitializerAST *);
- virtual void visitName(NameAST *);
- virtual void visitNamespace(NamespaceAST *);
- virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *);
- virtual void visitNewDeclarator(NewDeclaratorAST *);
- virtual void visitNewExpression(NewExpressionAST *);
- virtual void visitNewInitializer(NewInitializerAST *);
- virtual void visitNewTypeId(NewTypeIdAST *);
- virtual void visitOperator(OperatorAST *);
- virtual void visitOperatorFunctionId(OperatorFunctionIdAST *);
- virtual void visitParameterDeclaration(ParameterDeclarationAST *);
- virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *);
- virtual void visitPostfixExpression(PostfixExpressionAST *);
- virtual void visitPrimaryExpression(PrimaryExpressionAST *);
- virtual void visitPtrOperator(PtrOperatorAST *);
- virtual void visitPtrToMember(PtrToMemberAST *);
- virtual void visitReturnStatement(ReturnStatementAST *);
- virtual void visitSimpleDeclaration(SimpleDeclarationAST *);
- virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *);
- virtual void visitSizeofExpression(SizeofExpressionAST *);
- virtual void visitStringLiteral(StringLiteralAST *);
- virtual void visitSubscriptExpression(SubscriptExpressionAST *);
- virtual void visitSwitchStatement(SwitchStatementAST *);
- virtual void visitTemplateArgument(TemplateArgumentAST *);
- virtual void visitTemplateDeclaration(TemplateDeclarationAST *);
- virtual void visitTemplateParameter(TemplateParameterAST *);
- virtual void visitThrowExpression(ThrowExpressionAST *);
- virtual void visitTranslationUnit(TranslationUnitAST *);
- virtual void visitTryBlockStatement(TryBlockStatementAST *);
- virtual void visitCatchStatement(CatchStatementAST *);
- virtual void visitTypeId(TypeIdAST *);
- virtual void visitTypeIdentification(TypeIdentificationAST *);
- virtual void visitTypeParameter(TypeParameterAST *);
- virtual void visitTypedef(TypedefAST *);
- virtual void visitUnaryExpression(UnaryExpressionAST *);
- virtual void visitUnqualifiedName(UnqualifiedNameAST *);
- virtual void visitUsing(UsingAST *);
- virtual void visitUsingDirective(UsingDirectiveAST *);
- virtual void visitWhileStatement(WhileStatementAST *);
- virtual void visitWinDeclSpec(WinDeclSpecAST *);
-
-private:
- typedef void (Visitor::*visitor_fun_ptr)(AST *);
- static visitor_fun_ptr _S_table[];
-};
-
-#endif // VISITOR_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rxx_allocator.h (nonexistent)
@@ -1,128 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef RXX_ALLOCATOR_H
-#define RXX_ALLOCATOR_H
-
-#include <cstddef>
-#include <cstdlib>
-#include <string.h>
-#include <memory>
-
-/**The allocator which uses fixed size blocks for allocation of its elements.
-Block size is currently 64k, allocated space is not reclaimed,
-if the size of the element being allocated extends the amount of free
-memory in the block then a new block is allocated.
-
-The allocator supports standard c++ library interface but does not
-make use of allocation hints.
-*/
-template <class _Tp> class rxx_allocator {
-public:
- typedef _Tp value_type;
- typedef _Tp* pointer;
- typedef const _Tp* const_pointer;
- typedef _Tp& reference;
- typedef const _Tp& const_reference;
- typedef std::size_t size_type;
- typedef std::ptrdiff_t difference_type;
-
- static const size_type max_block_count = size_type(-1);
- static const size_type _S_block_size = 1 << 16; // 64K
-
- rxx_allocator() {
- init();
- }
-
- rxx_allocator(const rxx_allocator &/*__o*/) {
- init();
- }
-
- ~rxx_allocator() {
- for (size_type index = 0; index < _M_block_index + 1; ++index)
- delete[] _M_storage[index];
-
- ::free(_M_storage);
- }
-
- pointer address(reference __val) { return &__val; }
- const_pointer address(const_reference __val) const { return &__val; }
-
- /**Allocates @p __n elements continuosly in the pool. Warning! no
- check is done to check if the size of those @p __n elements
- fit into the block. You should assure you do not allocate more
- than the size of a block.*/
- pointer allocate(size_type __n, const void* = 0) {
- const size_type bytes = __n * sizeof(_Tp);
-
- if (_M_current_block == 0
- || _S_block_size < _M_current_index + bytes)
- {
- ++_M_block_index;
-
- _M_storage = reinterpret_cast<char**>
- (::realloc(_M_storage, sizeof(char*) * (1 + _M_block_index)));
-
- _M_current_block = _M_storage[_M_block_index] = reinterpret_cast<char*>
- (new char[_S_block_size]);
-
- ::memset(_M_current_block, 0, _S_block_size);
- _M_current_index = 0;
- }
-
- pointer p = reinterpret_cast<pointer>
- (_M_current_block + _M_current_index);
-
- _M_current_index += bytes;
-
- return p;
- }
-
- /**Deallocate does nothing in this implementation.*/
- void deallocate(pointer /*__p*/, size_type /*__n*/) {}
-
- size_type max_size() const { return size_type(-1) / sizeof(_Tp); }
-
- void construct(pointer __p, const_reference __val) { new (__p) _Tp(__val); }
- void destroy(pointer __p) { __p->~_Tp(); }
-
- template <class _Tp1> struct rebind {
- typedef rxx_allocator<_Tp1> other;
- };
-
-private:
-
- void init()
- {
- _M_block_index = max_block_count;
- _M_current_index = 0;
- _M_storage = 0;
- _M_current_block = 0;
- }
-
- template <class _Tp1> rxx_allocator(const rxx_allocator<_Tp1> &__o) {}
-
-private:
- size_type _M_block_index;
- size_type _M_current_index;
- char *_M_current_block;
- char **_M_storage;
-};
-
-#endif // RXX_ALLOCATOR_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/codemodel_fwd.h (nonexistent)
@@ -1,77 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef CODEMODEL_FWD_H
-#define CODEMODEL_FWD_H
-
-#include "kdevsharedptr.h"
-
-#include <QtCore/QList>
-
-// forward declarations
-class CodeModel;
-class _ArgumentModelItem;
-class _ClassModelItem;
-class _CodeModelItem;
-class _EnumModelItem;
-class _EnumeratorModelItem;
-class _FileModelItem;
-class _FunctionDefinitionModelItem;
-class _FunctionModelItem;
-class _NamespaceModelItem;
-class _ScopeModelItem;
-class _TemplateModelItem;
-class _TemplateParameterModelItem;
-class _TypeAliasModelItem;
-class _VariableModelItem;
-class _MemberModelItem;
-
-typedef KDevelop::SharedPtr<_ArgumentModelItem> ArgumentModelItem;
-typedef KDevelop::SharedPtr<_ClassModelItem> ClassModelItem;
-typedef KDevelop::SharedPtr<_CodeModelItem> CodeModelItem;
-typedef KDevelop::SharedPtr<_EnumModelItem> EnumModelItem;
-typedef KDevelop::SharedPtr<_EnumeratorModelItem> EnumeratorModelItem;
-typedef KDevelop::SharedPtr<_FileModelItem> FileModelItem;
-typedef KDevelop::SharedPtr<_FunctionDefinitionModelItem> FunctionDefinitionModelItem;
-typedef KDevelop::SharedPtr<_FunctionModelItem> FunctionModelItem;
-typedef KDevelop::SharedPtr<_NamespaceModelItem> NamespaceModelItem;
-typedef KDevelop::SharedPtr<_ScopeModelItem> ScopeModelItem;
-typedef KDevelop::SharedPtr<_TemplateModelItem> TemplateModelItem;
-typedef KDevelop::SharedPtr<_TemplateParameterModelItem> TemplateParameterModelItem;
-typedef KDevelop::SharedPtr<_TypeAliasModelItem> TypeAliasModelItem;
-typedef KDevelop::SharedPtr<_VariableModelItem> VariableModelItem;
-typedef KDevelop::SharedPtr<_MemberModelItem> MemberModelItem;
-
-typedef QList<ArgumentModelItem> ArgumentList;
-typedef QList<ClassModelItem> ClassList;
-typedef QList<CodeModelItem> CodeList;
-typedef QList<CodeModelItem> ItemList;
-typedef QList<EnumModelItem> EnumList;
-typedef QList<EnumeratorModelItem> EnumeratorList;
-typedef QList<FileModelItem> FileList;
-typedef QList<FunctionDefinitionModelItem> FunctionDefinitionList;
-typedef QList<FunctionModelItem> FunctionList;
-typedef QList<NamespaceModelItem> NamespaceList;
-typedef QList<ScopeModelItem> ScopeList;
-typedef QList<TemplateModelItem> TemplateList;
-typedef QList<TemplateParameterModelItem> TemplateParameterList;
-typedef QList<TypeAliasModelItem> TypeAliasList;
-typedef QList<VariableModelItem> VariableList;
-typedef QList<MemberModelItem> MemberList;
-
-#endif // CODEMODEL_FWD_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/tokens.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/tokens.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/tokens.h (nonexistent)
@@ -1,141 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef TOKENS_H
-#define TOKENS_H
-
-#include <cppparserexport.h>
-
-/**@file Token kinds.*/
-
-/**Token kinds.*/
-enum TOKEN_KIND
-{
- Token_EOF = 0,
-
- Token_K_DCOP = 1000,
- Token_Q_OBJECT,
- Token___attribute__,
- Token___typeof,
- Token_and,
- Token_and_eq,
- Token_arrow,
- Token_asm,
- Token_assign,
- Token_auto,
- Token_bitand,
- Token_bitor,
- Token_bool,
- Token_break,
- Token_case,
- Token_catch,
- Token_char,
- Token_char_literal,
- Token_class,
- Token_comment,
- Token_compl,
- Token_concat,
- Token_const,
- Token_const_cast,
- Token_continue,
- Token_decr,
- Token_default,
- Token_delete,
- Token_do,
- Token_double,
- Token_dynamic_cast,
- Token_ellipsis,
- Token_else,
- Token_emit,
- Token_enum,
- Token_eq,
- Token_explicit,
- Token_export,
- Token_extern,
- Token_false,
- Token_float,
- Token_for,
- Token_friend,
- Token_geq,
- Token_goto,
- Token_identifier,
- Token_if,
- Token_incr,
- Token_inline,
- Token_int,
- Token_k_dcop,
- Token_k_dcop_signals,
- Token_leq,
- Token_long,
- Token_mutable,
- Token_namespace,
- Token_new,
- Token_not,
- Token_not_eq,
- Token_number_literal,
- Token_operator,
- Token_or,
- Token_or_eq,
- Token_preproc,
- Token_private,
- Token_protected,
- Token_ptrmem,
- Token_public,
- Token_register,
- Token_reinterpret_cast,
- Token_return,
- Token_scope,
- Token_shift,
- Token_short,
- Token_signals,
- Token_signed,
- Token_sizeof,
- Token_slots,
- Token_static,
- Token_static_cast,
- Token_string_literal,
- Token_struct,
- Token_switch,
- Token_template,
- Token_this,
- Token_throw,
- Token_true,
- Token_try,
- Token_typedef,
- Token_typeid,
- Token_typename,
- Token_union,
- Token_unsigned,
- Token_using,
- Token_virtual,
- Token_void,
- Token_volatile,
- Token_wchar_t,
- Token_while,
- Token_whitespaces,
- Token_xor,
- Token_xor_eq,
-
- TOKEN_KIND_COUNT
-};
-
-/**@return human-readable name of the token.*/
-KDEVCPPPARSER_EXPORT char const *token_name(int token);
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/symbol.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/symbol.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/symbol.h (nonexistent)
@@ -1,140 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef SYMBOL_H
-#define SYMBOL_H
-
-#include <QtCore/QString>
-#include <cstring>
-
-#include <QtCore/QHash>
-#include <QtCore/QPair>
-
-/**@file symbol.h Symbol table for the parser.*/
-
-/**
-Symbol in the parser symbol table.
-*/
-struct NameSymbol
-{
- const char *data;
- std::size_t count;
-
- inline QString as_string() const
- {
- return QString::fromUtf8(data, count);
- }
-
- /**Required to put NameSymbol's into a QHash.*/
- inline bool operator == (const NameSymbol &other) const
- {
- return count == other.count
- && std::strncmp(data, other.data, count) == 0;
- }
-
-protected:
- inline NameSymbol() {}
- inline NameSymbol(const char *d, std::size_t c)
- : data(d), count(c) {}
-
-private:
- void operator = (const NameSymbol &);
-
- friend class NameTable;
-};
-
-
-/**
-@brief Required to put NameSymbol's into a QHash.
-@see qHash(const QPair<const char*, std::size_t> &r) method for the reference.*/
-inline uint qHash(const NameSymbol &r)
-{
- uint hash_value = 0;
-
- for (std::size_t i=0; i<r.count; ++i)
- hash_value = (hash_value << 5) - hash_value + r.data[i];
-
- return hash_value;
-}
-
-
-/**
-Required to put pairs of char* and std::size_t into a QHash.
-
-Hash function is: hash = hash*31 + key[i].@n
-It looks like a Bernstein's hash function with a different factor.
-@n Original Bernstein's function is: hash = hash*33 + key[i].
-@n Factor of 31 makes this function return reliably unique values
-for english words with 6 symbols length.
-
-@n More information can be found at @a http://burtleburtle.net/bob/hash/doobs.html.
-*/
-inline uint qHash(const QPair<const char*, std::size_t> &r)
-{
- uint hash_value = 0;
-
- for (std::size_t i=0; i<r.second; ++i)
- hash_value = (hash_value << 5) - hash_value + r.first[i];
-
- return hash_value;
-}
-
-/**Symbol table for the parser.*/
-class NameTable
-{
-public:
- typedef QPair<const char *, std::size_t> KeyType;
- typedef QHash<KeyType, NameSymbol*> ContainerType;
-
-public:
- NameTable() {}
-
- ~NameTable()
- {
- qDeleteAll(_M_storage);
- }
-
- inline const NameSymbol *findOrInsert(const char *str, std::size_t len)
- {
- KeyType key(str, len);
-
- NameSymbol *name = _M_storage.value(key);
- if (!name)
- {
- name = new NameSymbol(str, len);
- _M_storage.insert(key, name);
- }
-
- return name;
- }
-
- inline std::size_t count() const
- {
- return _M_storage.size();
- }
-
-private:
- ContainerType _M_storage;
-
-private:
- NameTable(const NameTable &other);
- void operator = (const NameTable &other);
-};
-
-#endif // SYMBOL_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/lexer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/lexer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/lexer.h (nonexistent)
@@ -1,307 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef LEXER_H
-#define LEXER_H
-
-#include "symbol.h"
-#include <cppparserexport.h>
-#include <QtCore/QString>
-#include <cstdlib>
-#include <language/duchain/indexedstring.h>
-
-#include <language/interfaces/iproblem.h>
-
-struct NameSymbol;
-class Lexer;
-class Control;
-class ParseSession;
-
-typedef void (Lexer::*scan_fun_ptr)();
-
-/**Token.*/
-class KDEVCPPPARSER_EXPORT Token
-{
-public:
- ///kind of the token @see TOKEN_KIND enum reference.
- int kind;
- ///position in the preprocessed buffer
- std::size_t position;
- ///size of the token in the preprocessed buffer. Do not confuse this with symbolLength.
- std::size_t size;
- ///pointer to the parse session.
- const ParseSession* session;
-
- //Symbol associated to the token. This only works if this is a simple symbol
- //only consisting of one identifier(not comments), does not work for operators like "->" or numbers like "50"
- KDevelop::IndexedString symbol() const;
-
- //This always works, but is expensive
- QString symbolString() const;
-
- uint symbolLength() const;
-
- ///@todo adymo: find out what @p right_brace is
- union
- {
- //const NameSymbol *symbol;
- std::size_t right_brace;
- } extra;
-};
-
-/**Stream of tokens found by lexer.
-Internally works like an array of @ref Token continuosly allocated.
-All tokens are destructed when this stream is deleted.
-
-The stream has a "cursor" which is simply an integer which defines
-the offset (index) of the token currently "observed" from the beginning of
-the stream.*/
-class TokenStream
-{
-private:
- TokenStream(const TokenStream &);
- void operator = (const TokenStream &);
-
-public:
- /**Creates a token stream with the default size of 1024 tokens.*/
- inline TokenStream(std::size_t size = 1024)
- : tokens(0),
- index(0),
- token_count(0)
- {
- resize(size);
- }
-
- inline ~TokenStream()
- { ::free(tokens); }
-
- /**@return the size of the token stream.*/
- inline std::size_t size() const
- { return token_count; }
-
- /**@return the "cursor" - the offset (index) of the token
- currently "observed" from the beginning of the stream.*/
- inline std::size_t cursor() const
- { return index; }
-
- /**Sets the cursor to the position @p i.*/
- inline void rewind(int i)
- { index = i; }
-
- /**Resizes the token stream.*/
- void resize(std::size_t size)
- {
- Q_ASSERT(size > 0);
- tokens = (Token*) ::realloc(tokens, sizeof(Token) * size);
- token_count = size;
- }
-
- /**Updates the cursor position to point to the next token and returns
- the cursor.*/
- inline std::size_t nextToken()
- { return index++; }
-
- /**@return the kind of the next (LA) token in the stream.*/
- inline int lookAhead(std::size_t i = 0) const
- { return tokens[index + i].kind; }
-
- /**@return the kind of the current token in the stream.*/
- inline int kind(std::size_t i) const
- { return tokens[i].kind; }
-
- /**@return the position of the current token in the c++ source buffer.*/
- inline std::size_t position(std::size_t i) const
- { return tokens[i].position; }
-
- /**@return the name symbol of the current token.*/
- //inline const NameSymbol *symbol(std::size_t i) const
- //{ return tokens[i].extra.symbol; }
-
- /**@return the position of the matching right brace in the
- c++ source buffer.
- @todo this doesn't seem to work as the lexer does not provide this
- information at the moment.*/
- inline std::size_t matchingBrace(std::size_t i) const
- { return tokens[i].extra.right_brace; }
-
- /**@return the token at position @p index.*/
- inline Token &operator[](int index)
- { Q_ASSERT(index >= 0 && index < (int)token_count); return tokens[index]; }
-
- /**@return the token at position @p index.*/
- inline const Token &token(int index) const
- { return tokens[index]; }
-
-private:
- Token *tokens;
- std::size_t index;
- std::size_t token_count;
-
-private:
- friend class Lexer;
-};
-
-/**C++ Lexer.*/
-class Lexer
-{
-public:
- /**
- * Constructor.
- *
- * \param token_stream Provides a stream of tokens to the lexer.
- * \param location_table a table which will be filled with non-preprocessed line -> offset values
- * \param line_table a table which will be filled with (non-preproccessed line which contains a preprocessor line) -> offset values
- */
- Lexer(Control *control);
-
- /**Finds tokens in the @p contents buffer and fills the @ref token_stream.*/
- void tokenize(ParseSession* session);
-
- ParseSession* session;
-
-private:
- void skipComment();
- /**Fills the scan table with method pointers.*/
- void initialize_scan_table();
- void scan_newline();
- void scan_white_spaces();
- void scan_identifier_or_keyword();
- void scan_identifier_or_literal();
- void scan_int_constant();
- void scan_char_constant();
- void scan_string_constant();
- void scan_invalid_input();
- void scan_preprocessor();
-
- // keywords
- void scanKeyword0();
- void scanKeyword2();
- void scanKeyword3();
- void scanKeyword4();
- void scanKeyword5();
- void scanKeyword6();
- void scanKeyword7();
- void scanKeyword8();
- void scanKeyword9();
- void scanKeyword10();
- void scanKeyword11();
- void scanKeyword12();
- void scanKeyword13();
- void scanKeyword14();
- void scanKeyword16();
-
- // operators
- void scan_not();
- void scan_remainder();
- void scan_and();
- void scan_left_paren();
- void scan_right_paren();
- void scan_star();
- void scan_plus();
- void scan_comma();
- void scan_minus();
- void scan_dot();
- void scan_divide();
- void scan_colon();
- void scan_semicolon();
- void scan_less();
- void scan_equal();
- void scan_greater();
- void scan_question();
- void scan_left_bracket();
- void scan_right_bracket();
- void scan_xor();
- void scan_left_brace();
- void scan_or();
- void scan_right_brace();
- void scan_tilde();
- void scan_EOF();
-
- KDevelop::Problem createProblem() const;
-
-private:
- Control *control;
-
- struct SpecialCursor {
- bool operator==(uint index) const {
- return *current == index;
- }
- bool operator==(char character) const {
- return *current == (character | 0xffff0000);
- }
- bool isChar() const {
- return ((*current) & 0xffff0000) == 0xffff0000;
- }
- inline char operator*() const {
- if(isChar())
- return (char)*current;
- else
- return '_'; //Return a valid character, because the identifiers created by the preprocessor are alpha-numerical
- }
- void operator++() {
- ++current;
- }
- void operator+=(int offset) {
- current += offset;
- }
- bool operator !=(const SpecialCursor& rhs) const {
- return current != rhs.current;
- }
- bool operator !=(const uint* rhs) const {
- return current != rhs;
- }
- void operator--() {
- --current;
- }
- bool operator<(const uint* end) const {
- return current < end;
- }
-
- int operator -(const SpecialCursor& rhs) const {
- return (((char*)current) - ((char*)rhs.current)) / sizeof(uint);
- }
-
- uint offsetIn(const uint* base) const {
- return ((char*)current - (char*)base) / sizeof(uint);
- }
-
- SpecialCursor operator +(int offset) {
- SpecialCursor ret(*this);
- ret.current += offset;
- return ret;
- }
-
- uint* current;
- };
-
- SpecialCursor cursor;
- const uint* endCursor;
- std::size_t index;
-
- bool m_leaveSize; //Marks the current token that its size should not be automatically set
- bool m_canMergeComment; //Whether we may append new comments to the last encountered one
- bool m_firstInLine; //Whether the next token is the first one in a line
-
- ///scan table contains pointers to the methods to scan for various token types
- static scan_fun_ptr s_scan_table[];
- static scan_fun_ptr s_scan_keyword_table[];
- static bool s_initialized;
-};
-
-#endif // LEXER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-environment.h (nonexistent)
@@ -1,119 +0,0 @@
-/*
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_ENVIRONMENT_H
-#define PP_ENVIRONMENT_H
-
-#include <QHash>
-#include <QMap>
-
-#include <QStack>
-#include <cppparserexport.h>
-
-namespace KDevelop {
- class IndexedString;
-}
-
-namespace rpp {
-
-class pp_macro;
-class pp;
-class LocationTable;
-
-class KDEVCPPRPP_EXPORT MacroBlock
-{
-public:
- MacroBlock(int _sourceLine);
- virtual ~MacroBlock();
-
- void setMacro(pp_macro* macro);
-
- QList<MacroBlock*> childBlocks;
-
- // The condition that opened this block(list of string indices)
- QVector<uint> condition;
- // The block to use if this block's condition was not met
- MacroBlock* elseBlock;
-
- // The source line where the block occurred
- int sourceLine;
-
- // This block is the owner of these macros
- QList<pp_macro*> macros;
-};
-
-class KDEVCPPRPP_EXPORT Environment
-{
-public:
- typedef QHash<KDevelop::IndexedString, pp_macro*> EnvironmentMap;
-
- Environment(pp* preprocessor);
- virtual ~Environment();
-
- MacroBlock* firstBlock() const;
- MacroBlock* currentBlock() const;
-
- void enterBlock(MacroBlock* block);
- MacroBlock* enterBlock(int sourceLine, const QVector<uint>& condition = QVector<uint>());
- MacroBlock* elseBlock(int sourceLine, const QVector<uint>& condition = QVector<uint>());
- void leaveBlock();
-
- // Replay previously saved blocks on this environment
- void visitBlock(MacroBlock* block, int depth = 0);
-
- void clear();
-
- // For those not interested in the result, just in getting memory released etc.
- void cleanup();
-
- void clearMacro(const KDevelop::IndexedString& name);
-
- //Note: Undef-macros are allowed too
- virtual void setMacro(pp_macro* macro);
- virtual pp_macro* retrieveMacro(const KDevelop::IndexedString& name) const;
-
- //Returns macros that are really stored locally(retrieveMacro may be overridden to perform more complex actions)
- pp_macro* retrieveStoredMacro(const KDevelop::IndexedString& name) const;
-
- QList<pp_macro*> allMacros() const;
-
- //Take the set of environment-macros from the given environment
- void swapMacros( Environment* parentEnvironment );
-
- //Faster access then allMacros(..), because nothing is copied
- const EnvironmentMap& environment() const; //krazy:exclude=constref
-
- LocationTable* locationTable() const;
- LocationTable* takeLocationTable();
-
-private:
- EnvironmentMap m_environment;
-
- QStack<MacroBlock*> m_blocks;
- bool m_replaying;
- pp* m_preprocessor;
- LocationTable* m_locationTable;
-};
-
-}
-
-#endif // PP_ENVIRONMENT_H
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-internal.h (nonexistent)
@@ -1,37 +0,0 @@
-/*
- Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_INTERNAL_H
-#define PP_INTERNAL_H
-
-#include "pp-stream.h"
-
-namespace rpp
-{
-
-bool isComment(Stream& input);
-
-Stream& devnull();
-
-}
-// _PP_internal
-
-#endif // PP_INTERNAL_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-configuration (nonexistent)
@@ -1,86 +0,0 @@
-#define __DBL_MIN_EXP__ (-1021)
-#define __FLT_MIN__ 1.17549435e-38F
-#define __CHAR_BIT__ 8
-#define __WCHAR_MAX__ 2147483647
-#define __DBL_DENORM_MIN__ 4.9406564584124654e-324
-#define __FLT_EVAL_METHOD__ 2
-#define __DBL_MIN_10_EXP__ (-307)
-#define __FINITE_MATH_ONLY__ 0
-#define __GNUC_PATCHLEVEL__ 2
-#define __SHRT_MAX__ 32767
-#define __LDBL_MAX__ 1.18973149535723176502e+4932L
-#define __UINTMAX_TYPE__ long long unsigned int
-#define __linux 1
-#define __unix 1
-#define __LDBL_MAX_EXP__ 16384
-#define __linux__ 1
-#define __SCHAR_MAX__ 127
-#define __USER_LABEL_PREFIX__
-#define __STDC_HOSTED__ 1
-#define __LDBL_HAS_INFINITY__ 1
-#define __DBL_DIG__ 15
-#define __FLT_EPSILON__ 1.19209290e-7F
-#define __GXX_WEAK__ 1
-#define __LDBL_MIN__ 3.36210314311209350626e-4932L
-#define __unix__ 1
-#define __DECIMAL_DIG__ 21
-#define __gnu_linux__ 1
-#define __LDBL_HAS_QUIET_NAN__ 1
-#define __GNUC__ 4
-#define __DBL_MAX__ 1.7976931348623157e+308
-#define __DBL_HAS_INFINITY__ 1
-#define __cplusplus 1
-#define __DEPRECATED 1
-#define __DBL_MAX_EXP__ 1024
-#define __GNUG__ 4
-#define __LONG_LONG_MAX__ 9223372036854775807LL
-#define __GXX_ABI_VERSION 1002
-#define __FLT_MIN_EXP__ (-125)
-#define __DBL_MIN__ 2.2250738585072014e-308
-#define __FLT_MIN_10_EXP__ (-37)
-#define __DBL_HAS_QUIET_NAN__ 1
-#define __REGISTER_PREFIX__
-#define __NO_INLINE__ 1
-#define __i386 1
-#define __FLT_MANT_DIG__ 24
-#define __VERSION__ "4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)"
-#define i386 1
-#define __i486__ 1
-#define unix 1
-#define __i386__ 1
-#define __SIZE_TYPE__ unsigned int
-#define __ELF__ 1
-#define __FLT_RADIX__ 2
-#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
-#define __FLT_HAS_QUIET_NAN__ 1
-#define __FLT_MAX_10_EXP__ 38
-#define __LONG_MAX__ 2147483647L
-#define __FLT_HAS_INFINITY__ 1
-#define linux 1
-#define __EXCEPTIONS 1
-#define __LDBL_MANT_DIG__ 64
-#define __WCHAR_TYPE__ int
-#define __FLT_DIG__ 6
-#define __INT_MAX__ 2147483647
-#define __i486 1
-#define __FLT_MAX_EXP__ 128
-#define __DBL_MANT_DIG__ 53
-#define __WINT_TYPE__ unsigned int
-#define __LDBL_MIN_EXP__ (-16381)
-#define __LDBL_MAX_10_EXP__ 4932
-#define __DBL_EPSILON__ 2.2204460492503131e-16
-#define __tune_i486__ 1
-#define __INTMAX_MAX__ 9223372036854775807LL
-#define __FLT_DENORM_MIN__ 1.40129846e-45F
-#define __FLT_MAX__ 3.40282347e+38F
-#define __INTMAX_TYPE__ long long int
-#define __GNUC_MINOR__ 0
-#define __DBL_MAX_10_EXP__ 308
-#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
-#define __PTRDIFF_TYPE__ int
-#define __LDBL_MIN_10_EXP__ (-4931)
-#define __LDBL_DIG__ 18
-#define _GNU_SOURCE 1
-
-
-#define __STDC__
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-engine.h (nonexistent)
@@ -1,266 +0,0 @@
-/*
- Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_ENGINE_H
-#define PP_ENGINE_H
-
-//krazy:excludeall=inline
-
-#include <QtCore/QHash>
-
-#include <QtCore/QStack>
-#include <cppparserexport.h>
-
-#include <language/interfaces/iproblem.h>
-
-#include "pp-macro.h"
-#include "pp-macro-expander.h"
-#include "pp-scanner.h"
-
-typedef QVector<unsigned int> PreprocessedContents;
-
-namespace rpp {
-
-class Preprocessor;
-class Environment;
-
-struct Value
-{
- Value() : kind(Kind_Long), l(0) {}
-
- enum Kind {
- Kind_Long,
- Kind_ULong
- };
-
- Kind kind;
-
- union {
- long l;
- unsigned long ul;
- };
-
- inline bool is_ulong () const { return kind == Kind_ULong; }
-
- inline void set_ulong (unsigned long v)
- {
- ul = v;
- kind = Kind_ULong;
- }
-
- inline void set_long (long v)
- {
- l = v;
- kind = Kind_Long;
- }
-
- inline bool is_zero () const { return l == 0; }
-
-#define PP_DEFINE_BIN_OP2(op) \
- inline Value operator op(const Value &other) \
- { \
- Value ret; \
- if (is_ulong () || other.is_ulong ()) \
- ret.set_ulong (ul op other.ul); \
- else \
- ret.set_long (l op other.l); \
- return ret; \
- }
-
-#define PP_DEFINE_BIN_OP(op, op2) \
- inline Value &operator op2(const Value &other) \
- { \
- if (is_ulong () || other.is_ulong ()) \
- set_ulong (ul op other.ul); \
- else \
- set_long (l op other.l); \
- return *this; \
- }
-
- PP_DEFINE_BIN_OP(+, +=)
- PP_DEFINE_BIN_OP(-, -=)
- PP_DEFINE_BIN_OP(*, *=)
- PP_DEFINE_BIN_OP(/, /=)
- PP_DEFINE_BIN_OP(%, %=)
- PP_DEFINE_BIN_OP(<<, <<=)
- PP_DEFINE_BIN_OP(>>, >>=)
- PP_DEFINE_BIN_OP(&, &=)
- PP_DEFINE_BIN_OP(|, |=)
- PP_DEFINE_BIN_OP(^, ^=)
- PP_DEFINE_BIN_OP2(<)
- PP_DEFINE_BIN_OP2(>)
- PP_DEFINE_BIN_OP2(!=)
- PP_DEFINE_BIN_OP2(==)
- PP_DEFINE_BIN_OP2(<=)
- PP_DEFINE_BIN_OP2(>=)
- PP_DEFINE_BIN_OP2(&&)
- PP_DEFINE_BIN_OP2(||)
-
-#undef PP_DEFINE_BIN_OP
-};
-
-
-class KDEVCPPRPP_EXPORT pp
-{
- Environment* m_environment;
- pp_macro_expander expand;
- pp_skip_identifier skip_identifier;
- pp_skip_comment_or_divop skip_comment_or_divop;
- pp_skip_blanks skip_blanks;
- pp_skip_number skip_number;
- QStack<KDevelop::IndexedString> m_files;
- Preprocessor* m_preprocessor;
- QList<KDevelop::ProblemPointer> m_problems;
-
- enum { MAX_LEVEL = 512 };
- int _M_skipping[MAX_LEVEL];
- int _M_true_test[MAX_LEVEL];
- int iflevel;
- int nextToken;
- bool haveNextToken;
- bool hideNext;
-
- union {
- long token_value;
- unsigned long token_uvalue;
- };
- KDevelop::IndexedString token_text;
-
- enum TOKEN_TYPE
- {
- TOKENS_START = 1000,
- TOKEN_NUMBER,
- TOKEN_UNUMBER,
- TOKEN_IDENTIFIER,
- TOKEN_DEFINED,
- TOKEN_LT_LT,
- TOKEN_LT_EQ,
- TOKEN_GT_GT,
- TOKEN_GT_EQ,
- TOKEN_EQ_EQ,
- TOKEN_NOT_EQ,
- TOKEN_OR_OR,
- TOKEN_AND_AND,
- TOKENS_END
- };
-
-public:
- pp(Preprocessor* preprocessor);
- ~pp();
-
- Preprocessor* preprocessor();
-
- enum StringType { File, Data };
-
- ///@todo Remove
- inline QString currentFileNameString () const { return m_files.top().str(); }
-
- inline KDevelop::IndexedString currentFileName () const { return m_files.top(); }
-
- Value eval_expression (Stream& input);
-
- /** Read file @p fileName and preprocess
- * Currently the file is expected to be utf8-encoded. */
- PreprocessedContents processFile(const QString& fileName);
-
- /** Preprocess @p fileName with content @p data. Do not actually open file @p fileName
- * Currently the file is expected to be utf8-encoded. */
- PreprocessedContents processFile(const QString& fileName, const QByteArray& data);
-
- void operator () (Stream& input, Stream& output);
-
- void checkMarkNeeded(Stream& input, Stream& output);
-
- bool hideNextMacro() const;
- void setHideNextMacro(bool hideNext);
-
- Environment* environment() const;
- // once set, belongs to the engine
- void setEnvironment(Environment* env);
-
- const QList<KDevelop::ProblemPointer>& problems() const;
- void problemEncountered(const KDevelop::Problem& problem);
- void problemEncountered(const KDevelop::ProblemPointer& problem);
-
- //Returns a hash-value computed from all until currently open branching-conditions and their decisions(like #ifdef's)
- uint branchingHash() const;
-
-private:
- void processFileInternal(const QString& fileName, const QByteArray& fileContent, PreprocessedContents& result);
-
- int skipping() const;
- bool test_if_level();
-
- void createProblem(Stream& input, const QString& description);
-
- void skip(Stream& input, Stream& output, bool outputText = true);
-
- Value eval_primary(Stream& input);
-
- Value eval_multiplicative(Stream& input);
-
- Value eval_additive(Stream& input);
-
- Value eval_shift(Stream& input);
-
- Value eval_relational(Stream& input);
-
- Value eval_equality(Stream& input);
-
- Value eval_and(Stream& input);
-
- Value eval_xor(Stream& input);
-
- Value eval_or(Stream& input);
-
- Value eval_logical_and(Stream& input);
-
- Value eval_logical_or(Stream& input);
-
- Value eval_constant_expression(Stream& input);
-
- void handle_directive(uint directive, Stream& input, Stream& output);
-
- void handle_include(bool skip_current_path, Stream& input, Stream& output);
-
- void handle_define(Stream& input);
-
- void handle_if(Stream& input);
-
- void handle_else(int sourceLine);
-
- void handle_elif(Stream& input);
-
- void handle_endif(Stream& input, Stream& output);
-
- void handle_ifdef(bool check_undefined, Stream& input);
-
- void handle_undef(Stream& input);
-
- int next_token (Stream& input);
- int next_token_accept (Stream& input);
- void accept_token();
-};
-
-}
-
-#endif // PP_ENGINE_H
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro-expander.h (nonexistent)
@@ -1,111 +0,0 @@
-/*
- Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_MACRO_EXPANDER_H
-#define PP_MACRO_EXPANDER_H
-
-#include <QtCore/QList>
-#include <QtCore/QHash>
-
-
-#include "pp-macro.h"
-#include "pp-stream.h"
-#include "pp-scanner.h"
-#include "anchor.h"
-#include <language/editor/simplecursor.h>
-
-namespace KDevelop {
- class IndexedString;
-}
-
-namespace rpp {
-
-class pp;
-
-//The value of a preprocessor function-like macro parameter
-class pp_actual {
-public:
- QList<PreprocessedContents> text;
- QList<Anchor> inputPosition; //Each inputPosition marks the beginning of one item in the text list
-
- bool isValid() const {
- return !text.isEmpty();
- }
- void clear() {
- text.clear();
- inputPosition.clear();
- }
-
- PreprocessedContents mergeText() const {
- if(text.count() == 1)
- return text.at(0);
-
- PreprocessedContents ret;
-
- foreach(const PreprocessedContents& t, text)
- ret += t;
- return ret;
- }
-};
-
-class pp_frame
-{
-public:
- pp_frame (pp_macro* __expandingMacro, const QList<pp_actual>& __actuals);
-
- pp_macro* expandingMacro;
- QList<pp_actual> actuals;
-};
-
-class pp_macro_expander
-{
-public:
- explicit pp_macro_expander(pp* engine, pp_frame* frame = 0, bool inHeaderSection = false);
-
- pp_actual resolve_formal(KDevelop::IndexedString name, Stream& input);
-
- /// Expands text with the known macros. Continues until it finds a new text line
- /// beginning with #, at which point control is returned.
- void operator()(Stream& input, Stream& output);
-
- void skip_argument_variadics (const QList<pp_actual>& __actuals, pp_macro *__macro,
- Stream& input, Stream& output);
-
-private:
- pp* m_engine;
- pp_frame* m_frame;
-
- pp_skip_number skip_number;
- pp_skip_identifier skip_identifier;
- pp_skip_string_literal skip_string_literal;
- pp_skip_char_literal skip_char_literal;
- pp_skip_argument skip_argument;
- pp_skip_comment_or_divop skip_comment_or_divop;
- pp_skip_blanks skip_blanks;
- pp_skip_whitespaces skip_whitespaces;
-
- bool m_in_header_section;
-};
-
-}
-
-#endif // PP_MACRO_EXPANDER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/macrorepository.h (nonexistent)
@@ -1,61 +0,0 @@
-/*
- Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef MACROREPOSITORY_H
-#define MACROREPOSITORY_H
-
-#include <language/duchain/repositories/itemrepository.h>
-#include <cppparserexport.h>
-#include "pp-macro.h"
-
-struct KDEVCPPRPP_EXPORT MacroRepositoryItemRequest {
-
- //The text is supposed to be utf8 encoded
- MacroRepositoryItemRequest(const rpp::pp_macro& _macro);
-
- enum {
- AverageSize = 20 //This should be the approximate average size of an Item
- };
-
- typedef unsigned int HashType;
-
- HashType hash() const {
- return macro.completeHash();
- }
-
- size_t itemSize() const;
-
- void createItem(rpp::pp_macro* item) const;
-
- //Should return whether the here requested item equals the given item
- bool equals(const rpp::pp_macro* item) const;
-
- const rpp::pp_macro& macro;
-};
-
-typedef KDevelop::ItemRepository<rpp::pp_macro, MacroRepositoryItemRequest> MacroDataRepository;
-
-//Returns the size of the object
-KDEVCPPRPP_EXPORT size_t constantSize(const rpp::pp_macro* macro);
-//Size of the pp_macro object for the given macro
-KDEVCPPRPP_EXPORT size_t constantSize(const rpp::pp_dynamic_macro* macro);
-//Constructs a constant macro object
-KDEVCPPRPP_EXPORT rpp::pp_macro* makeConstant(const rpp::pp_dynamic_macro* macro);
-//Creates an exact copy
-KDEVCPPRPP_EXPORT rpp::pp_macro* copyConstantMacro(const rpp::pp_macro* macro);
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/preprocessor.h (nonexistent)
@@ -1,73 +0,0 @@
-/*
- Copyright 2005 Harald Fernengel <harry@kdevelop.org>
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PREPROCESSOR_H
-#define PREPROCESSOR_H
-
-#include <QtCore/QString>
-#include <cppparserexport.h>
-namespace rpp {
-
-class Stream;
-
-class KDEVCPPRPP_EXPORT Preprocessor
-{
-public:
- enum IncludeType {
- /// An include specified as being local (eg. "file.h")
- IncludeLocal,
- /// An include specified as being global (eg. &lt;file.h&gt;)
- IncludeGlobal
- };
-
- virtual ~Preprocessor();
-
-// QString processString(const QString& string);
-
-
- /**
- * This function is called by the preprocessor whenever
- * it encounters an include directive.
- *
- * This class is permitted to modify \a fileName%; this
- * value will be used when marking the file in the preprocessed
- * output.
- *
- * \param fileName name of the source file to include
- * \param type the way that the file was requested
- * \param skipCurrentPath whether the path fileName was found in should be skipped(gcc extension include_next)
- *
- * \return a Stream with the appropriate contents to allow
- * the file to be #included. Ownership of the Stream is yielded to
- * class pp at this point.
- */
- virtual Stream* sourceNeeded(QString& fileName, IncludeType type, int sourceLine, bool skipCurrentPath);
-
- /**
- * Is called when the header-section ended. The header-section is the top of the file, that consists only if #include, #define, and #ifdef statements, or comments.
- * It ends as soon as anything else is found. You can use stream.toEnd() to stop the preprocessing.
- * */
- virtual void headerSectionEnded(rpp::Stream& stream);
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-macro.h (nonexistent)
@@ -1,185 +0,0 @@
-/*
- Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_MACRO_H
-#define PP_MACRO_H
-
-//krazy:excludeall=inline
-
-#include <QtCore/QStringList>
-#include <QVector>
-#include <cppparserexport.h>
-#include <language/duchain/indexedstring.h>
-#include <language/editor/hashedstring.h>
-
-//Foreach macro that also works with KDevVarLengthArray
-#define FOREACH_CUSTOM(item, container, size) for(int a = 0, mustDo = 1; a < (int)size; ++a) if((mustDo = 1)) for(item(container[a]); mustDo; mustDo = 0)
-
-
-namespace rpp {
-
- //This contains the data of a macro that can be marshalled by directly copying the memory
-struct KDEVCPPRPP_EXPORT pp_macro_direct_data
-{
- pp_macro_direct_data(const KDevelop::IndexedString& nm = KDevelop::IndexedString());
- typedef uint HashType;
-
- KDevelop::IndexedString name;
- KDevelop::IndexedString file;
-
- int sourceLine; //line
-
- bool defined: 1; // !isUndefMacro
- bool hidden: 1;
- bool function_like: 1; // hasArguments
- bool variadics: 1;
-
- //The valueHash is not necessarily valid
- mutable HashType m_valueHash; //Hash that represents the values of all macros
-
- bool operator==(const pp_macro_direct_data& rhs) const {
- return name == rhs.name && file == rhs.file && sourceLine == rhs.sourceLine && defined == rhs.defined && hidden == rhs.hidden && function_like == rhs.function_like && variadics == rhs.variadics;
- }
-
- bool isUndef() const {
- return !defined;
- }
-
- HashType completeHash() const {
- return m_valueHash + name.hash() * 3777;
- }
-
- HashType idHash() const {
- return name.hash();
- }
-}; ///@todo enable structure packing
-
-///Never construct his directly. It represents a macro that is stored in a repository,
-///and that is stored in a memory-unit together with its definition- and formal-list
-///@see macrorepository.h and macrorepository.cpp
-struct KDEVCPPRPP_EXPORT pp_macro : public pp_macro_direct_data {
- //Count of items in the tokenized definition vector
- uint definitionSize() const;
- const uint* definition() const;
-
- //Count of items in the list of formals
- uint formalsSize() const;
- const uint* formals() const;
-
- QString toString() const;
-
- //Does a complete comparison
- bool operator==(const pp_macro& rhs) const;
-
- ///Hash that identifies all of this macro, the value and the identity
- HashType completeHash() const {
- return m_valueHash + name.hash() * 3777;
- }
-
- unsigned int hash() const {
- return completeHash();
- }
-
- short unsigned int itemSize() const;
-
- private:
- Q_DISABLE_COPY(pp_macro)
-};
-
-class KDEVCPPRPP_EXPORT pp_dynamic_macro : public pp_macro_direct_data
-{
-public:
- pp_dynamic_macro();
- pp_dynamic_macro(const KDevelop::IndexedString& name);
- pp_dynamic_macro(const char* name);
-
- QVector<uint> definition; //Indices in the string index(essentially the same thing as IndexedString)
- QVector<uint> formals; // argumentList, also indices in the string repository(IndexedString)
-
- QString toString() const;
-
- HashType valueHash() const {
- if( !m_valueHashValid ) computeHash();
- return m_valueHash;
- }
-
- ///Hash that identifies all of this macro, the value and the identity
- HashType completeHash() const {
- return valueHash() + idHash() * 3777;
- }
-
- void invalidateHash();
-
- struct NameCompare {
- bool operator () ( const pp_dynamic_macro& lhs, const pp_dynamic_macro& rhs ) const {
- return lhs.name.index() < rhs.name.index();
- }
- #ifdef Q_CC_MSVC
-
- HashType operator () ( const pp_dynamic_macro& macro ) const
- {
- return macro.idHash();
- }
-
- enum
- { // parameters for hash table
- bucket_size = 4, // 0 < bucket_size
- min_buckets = 8}; // min_buckets = 2 ^^ N, 0 < N
- #endif
- };
-
- //Hash over id and value
- struct CompleteHash {
- HashType operator () ( const pp_dynamic_macro& lhs ) const {
- return lhs.completeHash();
- }
-
- #ifdef Q_CC_MSVC
-
- bool operator () ( const pp_dynamic_macro& lhs, const pp_dynamic_macro& rhs ) const {
- HashType lhash = lhs.valueHash()+lhs.idHash();
- HashType rhash = rhs.valueHash()+rhs.idHash();
- if( lhash < rhash ) return true;
- else if( lhash > rhash ) return false;
-
- int df = lhs.name.str().compare( rhs.name.str() );
- return df < 0;
- }
-
- enum
- { // parameters for hash table
- bucket_size = 4, // 0 < bucket_size
- min_buckets = 8}; // min_buckets = 2 ^^ N, 0 < N
- #endif
- };
-
- private:
- void computeHash() const;
- mutable bool m_valueHashValid;
-};
-
-}
-
-inline uint qHash( const rpp::pp_dynamic_macro& m ) {
- return (uint)m.idHash();
-}
-
-#endif // PP_MACRO_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/chartools.h (nonexistent)
@@ -1,89 +0,0 @@
-/*
- Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef CHARTOOLS
-#define CHARTOOLS
-#include <QChar>
-#include "cppparserexport.h"
-
-template<class T>
-class QVector;
-class QString;
-class QByteArray;
-typedef QVector<unsigned int> PreprocessedContents;
-
-inline bool isSpace(char c) {
- return QChar(c).isSpace();
-}
-
-inline bool isLetter(char c) {
- return QChar(c).isLetter();
-}
-
-inline bool isLetterOrNumber(char c) {
- return QChar(c).isLetterOrNumber();
-}
-
-inline bool isNumber(char c) {
- return QChar(c).isNumber();
-}
-
-//Takes an index as delt with during preprocessing, and determines whether it is a fake-index that represents
-//a character. If the 0xffff0000 bits are set, it is a custom character.
-#define isCharacter(index) ((index & 0xffff0000) == 0xffff0000)
-
-//Creates an index that represents the given character
-#define indexFromCharacter(character) ((unsigned int)character | 0xffff0000)
-
-//Extracts the character that is represented by the index
-#define characterFromIndex(index) ((char)(index & 0xffff))
-
-inline bool isSpace(unsigned int c) {
- return isCharacter(c) && QChar(characterFromIndex(c)).isSpace();
-}
-
-inline bool isLetter(unsigned int c) {
- return isCharacter(c) && QChar(characterFromIndex(c)).isLetter();
-}
-
-inline bool isLetterOrNumber(unsigned int c) {
- return isCharacter(c) && QChar(characterFromIndex(c)).isLetterOrNumber();
-}
-
-inline bool isNumber(unsigned int c) {
- return isCharacter(c) && QChar(characterFromIndex(c)).isNumber();
-}
-
-///Opposite of convertFromByteArray
-KDEVCPPRPP_EXPORT QByteArray stringFromContents(const PreprocessedContents& contents, int offset = 0, int count = 0);
-
-///Opposite of convertFromByteArray
-KDEVCPPRPP_EXPORT QByteArray stringFromContents(const uint* contents, int count);
-
-///Returns a string that has a gap inserted between the tokens(for debugging)
-KDEVCPPRPP_EXPORT QByteArray stringFromContentsWithGaps(const PreprocessedContents& contents, int offset = 0, int count = 0);
-
-///Converts the byte array to a vector of fake-indices containing the text
-KDEVCPPRPP_EXPORT PreprocessedContents convertFromByteArray(const QByteArray& array);
-
-///Converts the byte array to a vector of fake-indices containing the text
-///This also tokenizes the given array when possible
-KDEVCPPRPP_EXPORT PreprocessedContents tokenizeFromByteArray(const QByteArray& array);
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/anchor.h (nonexistent)
@@ -1,50 +0,0 @@
-/*
- Copyright 2008 David Nolden <david.nolden.kdevelop@art-master.de>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef ANCHOR_H
-#define ANCHOR_H
-
-#include <language/editor/simplecursor.h>
-
-#include <cppparserexport.h>
-
-namespace rpp {
-/**
- * A KDevelop::SimpleCursor with additional boolean value whether the range opened by this anchor is collapsed.
- * If that value is true, it means that Everything behind the anchor until the next one is collapsed to the exact position of this anchor.
- * */
-class KDEVCPPRPP_EXPORT Anchor : public KDevelop::SimpleCursor {
-public:
- Anchor() : collapsed(false) {
- }
-
- explicit Anchor(const SimpleCursor& cursor, bool _collapsed=false, KDevelop::SimpleCursor _macroExpansion=KDevelop::SimpleCursor::invalid()) : SimpleCursor(cursor), collapsed(_collapsed), macroExpansion(_macroExpansion) {
- }
- explicit Anchor(int line, int column, bool _collapsed=false, KDevelop::SimpleCursor _macroExpansion=KDevelop::SimpleCursor::invalid()) : SimpleCursor(line, column), collapsed(_collapsed), macroExpansion(_macroExpansion) {
- }
-
- bool collapsed;
-
- ///@todo create a sub-class that contains macroExpansion. It is only needed in the location-table and everything using not, not actually in the anchors.
- KDevelop::SimpleCursor macroExpansion; //Zero if this position was not transformed through a macro-expansion, else a number that identifies the expansion
-};
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-scanner.h (nonexistent)
@@ -1,97 +0,0 @@
-/*
- Copyright 2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_SCANNER_H
-#define PP_SCANNER_H
-
-
-
-#include "pp-stream.h"
-
-namespace rpp {
-
-class pp_skip_blanks
-{
-public:
- void operator()(Stream& input, Stream& output);
-};
-
-class pp_skip_whitespaces
-{
-public:
- void operator()(Stream& input, Stream& output);
-};
-
-class pp_skip_comment_or_divop
-{
-public:
- /**
- * This scanner can either output equivalent blank space,
- * or the actual text (the default).
- */
- void operator()(Stream& input, Stream& output, bool outputText = false);
-
-private:
- bool m_outputText;
-};
-
-class pp_skip_identifier
-{
-public:
- uint operator()(Stream& input);
-};
-
-class pp_skip_number
-{
-public:
- void operator()(Stream& input, Stream& output);
-};
-
-class pp_skip_string_literal
-{
-public:
- void operator()(Stream& input, Stream& output);
-};
-
-class pp_skip_char_literal
-{
-public:
- void operator()(Stream& input, Stream& output);
-};
-
-//Does also skip any whitespace behind the argument
-class pp_skip_argument
-{
-public:
- void operator()(Stream& input, Stream& output);
-
-private:
- pp_skip_number skip_number;
- pp_skip_identifier skip_identifier;
- pp_skip_string_literal skip_string_literal;
- pp_skip_char_literal skip_char_literal;
- pp_skip_comment_or_divop skip_comment_or_divop;
-};
-
-}
-
-#endif // PP_SCANNER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-location.h (nonexistent)
@@ -1,86 +0,0 @@
-/*
- Copyright 2007 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef PP_LOCATION_H
-#define PP_LOCATION_H
-
-#include <QMap>
-
-#include <language/editor/simplecursor.h>
-
-#include <cppparserexport.h>
-#include "anchor.h"
-
-typedef QVector<unsigned int> PreprocessedContents;
-
-namespace rpp {
-
-class KDEVCPPRPP_EXPORT LocationTable
-{
- public:
- LocationTable();
-
- /// Generates the location table from the contents
- LocationTable(const PreprocessedContents& contents);
-
- ///@param contents is allowed to be zero only if offset is zero, or if anchor.column is zero.
- void anchor(std::size_t offset, Anchor anchor, const PreprocessedContents* contents);
-
- /**
- * Return the position of the preprocessed source \a offset in the original source
- * If the "collapsed" member of the returned anchor is true, the position is within a collapsed range.
- @param collapseIfMacroExpansion @see LocationTable::positionForOffset
- * \note the return line starts from 0, not 1.
- * Returns the found position stored in the anchor, and the possible maximum length until the next anchored position, or zero.
- */
- QPair<rpp::Anchor, uint> positionAt(std::size_t offset, const PreprocessedContents& contents, bool collapseIfMacroExpansion = false) const;
-
- struct AnchorInTable {
- uint position; //Position of this anchor
- Anchor anchor; //This anchor
- uint nextPosition;//Position of the next following anchor, or zero
- Anchor nextAnchor;//The next following anchor
- };
-
- /**
- * Returns the nearest anchor before @param position, and the position of the anchor.
- * If the character is in a collapsed range, the collapsed member is true.
- @param collapseIfMacroExpansion When this is true, all ranges that come from macro-expansion will be
- considered collapsed.(The returned anchor will also have the collapsed member set)
- * */
- AnchorInTable anchorForOffset(std::size_t position, bool collapseIfMacroExpansion = false) const;
-
- void dump() const;
-
- /**
- * Splits the given @param text using this location-table into sub-strings each assigned to a cursor where it starts.
- * @param textStartPosition must be given as the start-position, because the location-table might not contain an anchor
- * for the first character.
- * */
- void splitByAnchors(const PreprocessedContents& text, const Anchor& textStartPosition, QList<PreprocessedContents>& strings, QList<Anchor>& anchors) const;
-
- private:
- QMap<std::size_t, Anchor> m_offsetTable;
- mutable QMap<std::size_t, Anchor>::ConstIterator m_currentOffset;
-};
-
-}
-
-#endif // PP_LOCATION_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/rpp/pp-stream.h (nonexistent)
@@ -1,174 +0,0 @@
-/*
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- Permission to use, copy, modify, distribute, and sell this software and its
- documentation for any purpose is hereby granted without fee, provided that
- the above copyright notice appear in all copies and that both that
- copyright notice and this permission notice appear in supporting
- documentation.
-
- 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
- KDEVELOP TEAM 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.
-*/
-
-#ifndef STREAM_H
-#define STREAM_H
-
-#include <cppparserexport.h>
-
-#include <QtCore/QIODevice>
-
-#include <language/editor/simplecursor.h>
-#include <language/duchain/indexedstring.h>
-#include "anchor.h"
-#include "chartools.h"
-
-typedef QVector<unsigned int> PreprocessedContents;
-
-namespace KDevelop {
- class IndexedString;
-}
-
-namespace rpp {
-
-class LocationTable;
-
-/**
- * Stream designed for character-at-a-time processing
- *
- * @author Hamish Rodda <rodda@kde.org>
- */
-class KDEVCPPRPP_EXPORT Stream
-{
- static const uint newline;
-
- public:
- Stream();
- //If the given offset anchor has the member "collapsed" set to true, the position will be locked.
- explicit Stream( const uint * string, uint stringSize, const Anchor& offset = Anchor(0,0), LocationTable* table = 0 );
- explicit Stream( PreprocessedContents * string, const Anchor& offset = Anchor(0,0), LocationTable* table = 0 );
- explicit Stream( PreprocessedContents * string, LocationTable* table );
- virtual ~Stream();
-
- bool isNull() const;
-
- bool atEnd() const;
-
- void toEnd();
-
- /// Returns true if toEnd was called on this stream.
- bool skippedToEnd() const;
-
- int offset() const;
-
- const uint& peek(uint offset = 1) const;
-
- char peekNextCharacter() const {
- const unsigned int* next = c+1;
- if (next >= end || !isCharacter(*next))
- return (char)0;
-
- return characterFromIndex(*next);
- }
-
- //Slow, just for debugging
- QByteArray stringFrom(int offset) const;
-
- /// \warning the input and output lines are not updated when calling this function.
- /// if you're seek()ing over a line boundary, you'll need to fix the line and column
- /// numbers.
- void seek(int offset);
-
- /// Start from the beginning again
- void reset();
-
- /// Lock/unlock the input position. If the input position is locked, it will not be moved forwards.
- void lockInputPosition(bool lock);
-
- /// If a macro-expansion is set, all anchors given to mark() will get that macro-expansion set.
- /// It marks the position from where the macro-expansion was started that leads to the current output @see rpp::Anchor
- void setMacroExpansion(const KDevelop::SimpleCursor&);
- KDevelop::SimpleCursor macroExpansion() const;
-
- //Checks whether the current index represents a character, and eventually compares it
- bool operator==(const char otherc) const {
- return isCharacter(*c) && *c == indexFromCharacter(otherc);
- }
-
- //Checks whether the current index represents a character, and eventually compares it
- bool operator!=(const char otherc) const {
- return !isCharacter(*c) || *c != indexFromCharacter(otherc);
- }
-
- inline const uint& current() const { return *c; } //krazy:exclude=inline
- inline operator const uint&() const { return *c; } //krazy:exclude=inline
- inline Stream& operator++() //krazy:exclude=inline
- {
- if (c == end)
- return *this;
-
- if(m_inputPositionLocked)
- ++m_inputLineStartedAt;
- else if (*c == newline) {
- ++m_inputLine;
- m_inputLineStartedAt = m_pos + 1;
- }else if(!isCharacter(*c)) {
- //We have to do some special hacking here to keep the column-number correct.
- m_inputLineStartedAt += 1-KDevelop::IndexedString(QChar(*c)).length();
- }
-
- ++c;
- ++m_pos;
-
- return *this;
- }
-
- ///@warning Doesn't handle newlines correctly!
- Stream& operator--();
-
- ///Returns the cursor that points to the current input position.
- Anchor inputPosition() const;
- ///If the input position is collapsed, the input position will be locked from now on. It will stay the same until a new one is set.
- void setInputPosition(const Anchor& position);
-
- ///Input-position that marks the start of the topmost currently expanding macro in the original document
- KDevelop::SimpleCursor originalInputPosition() const;
- void setOriginalInputPosition(const KDevelop::SimpleCursor& position);
-
- ///Used for output streams to mark stream positions with input position
- ///The macroExpansion member may have no effect if macroExpansion is set for this stream.
- void mark(const Anchor& position);
-
- Stream & operator<< ( const char& c ) {
- return operator<<(indexFromCharacter(c));
- }
- Stream & operator<< ( const unsigned int& c );
- Stream & operator<< ( const Stream& input );
- Stream& appendString( const Anchor& inputPosition, const PreprocessedContents & string );
- Stream& appendString( const Anchor& inputPosition, KDevelop::IndexedString index );
-
- private:
- Q_DISABLE_COPY(Stream)
-
- PreprocessedContents* m_string;
- const unsigned int* c;
- const unsigned int* end;
- bool m_isNull, m_skippedToEnd, m_inputPositionLocked, m_onwsString;
- KDevelop::SimpleCursor m_macroExpansion;
- int m_pos;
- int m_inputLine;
- int m_inputLineStartedAt;
- LocationTable* m_locationTable;
- KDevelop::SimpleCursor m_originalInputPosition;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/memorypool.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/memorypool.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/memorypool.h (nonexistent)
@@ -1,41 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef MEMORYPOOL_H
-#define MEMORYPOOL_H
-
-#include "rxx_allocator.h"
-#include <cstring>
-
-/**Memory pool for chars.*/
-class pool
-{
- rxx_allocator<char> __alloc;
-
-public:
- /**Allocates the @p size bytes in the pool.*/
- inline void *allocate(std::size_t __size);
-};
-
-inline void *pool::allocate(std::size_t __size)
-{
- return __alloc.allocate(__size);
-}
-
-#endif // MEMORYPOOL_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/cppparserexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/cppparserexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/cppparserexport.h (nonexistent)
@@ -1,42 +0,0 @@
-/*
- This file is part of the KDevelop platform
- Copyright 2004 Jaroslaw Staniek <js@iidea.pl>
- Copyright 2006 Matt Rogers <mattr@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-#ifndef CPPPARSEREXPORT_H
-#define CPPPARSEREXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-#ifndef KDEVCPPPARSER_EXPORT
-# ifdef MAKE_KDEV4CPPPARSER_LIB
-# define KDEVCPPPARSER_EXPORT KDE_EXPORT
-# else
-# define KDEVCPPPARSER_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#ifndef KDEVCPPRPP_EXPORT
-# ifdef MAKE_KDEV4CPPRPP_LIB
-# define KDEVCPPRPP_EXPORT KDE_EXPORT
-# else
-# define KDEVCPPRPP_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif /* CPPPARSEREXPORT_H*/
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentformatter.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentformatter.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentformatter.h (nonexistent)
@@ -1,51 +0,0 @@
-/*
- Copyright (C) 2007 David Nolden <david.nolden.kdevelop@art-master.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef COMMENTFORMATTER_H
-#define COMMENTFORMATTER_H
-
-#include <QString>
-#include <cppparserexport.h>
-
-template<class Tp>
-class ListNode;
-
-/**
- * This class cares about extracting the interesting information out of a comment.
- * For example it removes all the stars at the beginning, and re-indents the text.
- * */
-
-class ParseSession;
-
-class KDEVCPPPARSER_EXPORT CommentFormatter {
- public:
- static QString formatComment( const QString& comment );
- ///Processes the comment represented by the given token-number within the parse-session's token-stream
- static QString formatComment( size_t token, const ParseSession* session );
-
- ///Processes the list of comments represented by the given token-number within the parse-session's token-stream
- static QString formatComment( const ListNode<size_t>* node, const ParseSession* session );
- private:
- static inline bool isWhite( QChar c ) {
- return c.isSpace();
- }
- static void rStrip( const QString& str, QString& from );
- static void strip( const QString& str, QString& from );
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/commentparser.h (nonexistent)
@@ -1,84 +0,0 @@
-/*
- Copyright (C) 2007 David Nolden <david.nolden.kdevelop@art-master.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef COMMENTPARSER_H
-#define COMMENTPARSER_H
-
-#include <QString>
-#include <set>
-
-class ParseSession;
-
-class Comment {
- public:
- explicit Comment( size_t token = 0, int line = -1 );
-
- operator bool() const;
-
- inline int line() const {
- return m_line;
- }
-
- bool operator==( const Comment& comment ) const;
-
- bool operator < ( const Comment& rhs ) const;
-
- bool isSame ( const Comment& rhs ) const;
-
- size_t token() const {
- return m_token;
- }
- private:
- int m_line;
- size_t m_token;
-};
-
-
-class CommentStore {
- private:
- typedef std::set< Comment > CommentSet;
- CommentSet m_comments;
-
- public:
-
- /**
- * Returns & removes the first comment currently in the comment-store
- * */
- Comment takeFirstComment();
-
- /**
- * Returns the comment nearest to the line of "end"(inclusive), and returns & removes it
- * */
- Comment takeCommentInRange( int endLine, int startLine = 0 );
-
- ///Returns and removes the comment in the given line
- Comment takeComment( int line );
-
- void addComment( Comment comment );
-
- ///Does not delete the comment
- Comment latestComment() const;
-
- bool hasComment() const {
- return !m_comments.empty();
- }
-
- void clear();
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/listnode.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/listnode.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/include/listnode.h (nonexistent)
@@ -1,94 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef LISTNODE_H
-#define LISTNODE_H
-
-#include "memorypool.h"
-#include <kdebug.h>
-
-template <typename Tp>
-struct ListNode
-{
- Tp element;
- int index;
- mutable const ListNode<Tp> *next;
-
- static ListNode *create(const Tp &element, pool *p)
- {
- ListNode<Tp> *node = new (p->allocate(sizeof(ListNode))) ListNode();
- node->element = element;
- node->index = 0;
- node->next = node;
-
- return node;
- }
-
- static ListNode *create(const ListNode *n1, const Tp &element, pool *p)
- {
- ListNode<Tp> *n2 = ListNode::create(element, p);
-
- n2->index = n1->index + 1;
- n2->next = n1->next;
- n1->next = n2;
-
- return n2;
- }
-
- inline const ListNode<Tp> *at(int index) const
- {
- const ListNode<Tp> *node = this;
- while (index != node->index)
- node = node->next;
-
- return node;
- }
-
- inline bool hasNext() const
- { return ( next && index < next->index ); }
-
- inline int count() const
- { return 1 + toBack()->index; }
-
- inline const ListNode<Tp> *toFront() const
- { return toBack()->next; }
-
- inline const ListNode<Tp> *toBack() const
- {
- const ListNode<Tp> *node = this;
- while (node->hasNext())
- node = node->next;
-
- return node;
- }
-};
-
-template <class Tp>
-inline const ListNode<Tp> *snoc(const ListNode<Tp> *list,
- const Tp &element, pool *p)
-{
-
- if (!list)
- return ListNode<Tp>::create(element, p);
-
- return ListNode<Tp>::create(list->toBack(), element, p);
-}
-
-#endif // FASTLIST_H
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.h (nonexistent)
@@ -1,58 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-
-#ifndef MCCABE_METRICS_H
-#define MCCABE_METRICS_H
-
-#include <QtCore/QString>
-#include <QtCore/QList>
-
-/*! Single Cyclomatic Complexity entity */
-class McCabeMetric
-{
-public:
- McCabeMetric();
- QString function() const;
- void setFunction(const QString&);
-
- int line() const;
- void setLine(int);
-
- int value() const;
- void increment();
-
-private:
- QString m_function;
- int m_line;
- int m_complexity;
-};
-
-class MetricStore
-{
-public:
- void addMcCabeMetric(const McCabeMetric&);
- QList<McCabeMetric> mcCabeComplexity();
-
-private:
- QList<McCabeMetric> m_mcCabeComplexity;
-};
-
-#endif // MCCABE_METRICS_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/CMakeLists.txt (nonexistent)
@@ -1,17 +0,0 @@
-include_directories(
- ../include
- ${CMAKE_CURRENT_BINARY_DIR}
- ${QT_INCLUDES}
- ${KDE4_INCLUDE_DIR}
- ${KDEVPLATFORM_INCLUDE_DIR})
-
-
-set(McCabe_SRCS main.cpp metricengine.cpp metrics.cpp)
-add_executable(McCabe ${McCabe_SRCS})
-target_link_libraries(McCabe
- ${QT_QTCORE_LIBRARY}
- ${KDEVPLATFORM_INTERFACES}
- ${KDEVPLATFORM_LANGUAGE}
- ${KDE4_LIB_DIR}/libkdev4cppparser.so
- ${KDE4_LIB_DIR}/libkdev4cpprpp.so
-)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.cpp (nonexistent)
@@ -1,327 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "metricengine.h"
-#include <kurl.h>
-#include <QtCore/QFile>
-
-#include <ast.h>
-#include <tokens.h>
-#include <lexer.h>
-#include <parser.h>
-#include <control.h>
-#include <parsesession.h>
-#include <default_visitor.h>
-#include <rpp/preprocessor.h>
-#include <rpp/chartools.h>
-#include <rpp/pp-engine.h>
-#include <QFile>
-#include <kdebug.h>
-
-namespace {
-
-
-class McCabeASTVisitor : public DefaultVisitor
-{
-public:
- McCabeASTVisitor(ParseSession& session) : m_session(session), m_switchDepth(0) {}
- virtual ~McCabeASTVisitor() {}
-
- ////////////////////////// data members //////////////////////////////////
-
- ParseSession& m_session;
- McCabeMetric m_currentMcCabe;
- MetricStore m_metrics;
- int m_switchDepth;
- QStringList m_currentNamePrefix;
- QHash<QString,QString> m_using;
- QString m_parameterClause;
-
- ////////////////////////// helpers ///////////////////////////////////////
-
- QString symbolForTokenId(std::size_t id) {
- return m_session.token_stream->token(id).symbolString();
- }
-
- int sourceLineForTokenId(std::size_t id) {
- std::size_t tokenPosition = m_session.token_stream->token(id).position;
- const rpp::Anchor& a = m_session.positionAt(tokenPosition);
- return a.line + 1; // +1 since editor-lines start from 1 while FooIndex starts from 0
- }
-
- void concatenateTokensBetween(int startToken, int endToken, QString& result) {
- if (startToken == 0) return;
- for (int i=startToken; i<=endToken; i++) {
- result += symbolForTokenId(i);
- }
- }
-
- void appendQualifiedNames(const ListNode<UnqualifiedNameAST*>* qualifiedNames, QString& name) {
- if (!qualifiedNames) return;
-
- const ListNode<UnqualifiedNameAST*> *it = qualifiedNames->toFront(), *end = it;
- do {
- if (!name.isEmpty()) name += "::";
- name += symbolForTokenId(it->element->id);
- it = it->next;
- } while (it!=end);
- }
-
- ////////////////////////// visit overrides ///////////////////////////////
-
- virtual void visitConditionalExpression(ConditionalExpressionAST *node) {
- m_currentMcCabe.increment();
- DefaultVisitor::visitConditionalExpression(node);
- }
-
- virtual void visitBinaryExpression(BinaryExpressionAST *node) {
- QString op = symbolForTokenId(node->op);
- if (op == "||" || op == "&&") {
- m_currentMcCabe.increment();
- }
- DefaultVisitor::visitBinaryExpression(node);
- }
-
- virtual void visitWhileStatement(WhileStatementAST *node) {
- DefaultVisitor::visitWhileStatement(node);
- m_currentMcCabe.increment();
- }
-
- virtual void visitForStatement(ForStatementAST *node) {
- DefaultVisitor::visitForStatement(node);
- m_currentMcCabe.increment();
- }
-
- virtual void visitIfStatement(IfStatementAST *node) {
- DefaultVisitor::visitIfStatement(node);
- m_currentMcCabe.increment();
- }
-
- virtual void visitFunctionDefinition(FunctionDefinitionAST *node) {
- QString functionName;
- m_parameterClause.clear();
-
- if (!m_currentNamePrefix.isEmpty()) {
- functionName = m_currentNamePrefix.join("::");
- }
- if (!node->init_declarator->declarator->id) return;
-
- const ListNode<UnqualifiedNameAST*>* nodes = node->init_declarator->declarator->id->qualified_names;
- appendQualifiedNames(nodes, functionName);
-
- if (m_using.contains(functionName)) {
- functionName = m_using[functionName] + "::" + functionName;
- }
-
- int nameTokenId = node->init_declarator->declarator->id->unqualified_name->id;
- if (nameTokenId == 0) {
- kWarning() << "Ignoring function definition since tokenID is zero. This might indicate an operator() function.";
- return;
- }
-
- if (!functionName.isEmpty()) functionName += "::";
- functionName += symbolForTokenId(nameTokenId);
- if (m_using.contains(functionName)) {
- functionName = m_using[functionName] + "::" + functionName;
- }
-
- m_currentMcCabe = McCabeMetric();
- m_currentMcCabe.increment();
- m_currentMcCabe.setLine(sourceLineForTokenId(node->start_token));
- visitParameterDeclarationClause(node->init_declarator->declarator->parameter_declaration_clause);
- visit(node->function_body);
- m_currentMcCabe.setFunction(functionName + "(" + m_parameterClause + ")");
- m_metrics.addMcCabeMetric(m_currentMcCabe);
- }
-
- virtual void visitLabeledStatement(LabeledStatementAST *node) {
- DefaultVisitor::visitLabeledStatement(node);
- if (m_switchDepth>0) {
- m_currentMcCabe.increment();
- }
- }
-
- virtual void visitNamespace(NamespaceAST *node) {
- int nameTokenId = node->namespace_name;
- if (nameTokenId != 0) {
- m_currentNamePrefix << symbolForTokenId(nameTokenId);
- } else {
- m_currentNamePrefix << "<anonymous>";
- }
- DefaultVisitor::visitNamespace(node);
- m_currentNamePrefix.takeLast();
- }
-
- virtual void visitSwitchStatement(SwitchStatementAST *node) {
- m_switchDepth++;
- DefaultVisitor::visitSwitchStatement(node);
- m_switchDepth--;
- }
-
- virtual void visitUsing(UsingAST *node) {
- NameAST* name = node->name;
- if (!name) return;
-
- QString prefix;
- const ListNode<UnqualifiedNameAST*>* nodes = name->qualified_names;
- appendQualifiedNames(nodes, prefix);
-
- QString suffix = symbolForTokenId(name->unqualified_name->id);
- // eg for 'using Foo::Bar;' Foo is the prefix, Bar the suffix.
- m_using[suffix] = prefix;
- }
-
- virtual void visitClassSpecifier(ClassSpecifierAST *node) {
- int nameTokenId = 0;
- if (!node->name) {
- m_currentNamePrefix << "<anonymous-type>";
- } else {
- nameTokenId = node->name->unqualified_name->id; // TODO also insert qualified prefixes
- if (nameTokenId != 0) {
- m_currentNamePrefix << symbolForTokenId(nameTokenId);
- }
- }
- DefaultVisitor::visitClassSpecifier(node);
- if (!node->name || nameTokenId != 0) m_currentNamePrefix.takeLast();
- }
-
- virtual void visitSimpleTypeSpecifier(SimpleTypeSpecifierAST *node) {
- DefaultVisitor::visitSimpleTypeSpecifier(node);
- }
-
- virtual void visitParameterDeclarationClause(ParameterDeclarationClauseAST *node) {
- if (!node) return;
-
- if (!node->parameter_declarations) return;
- const ListNode<ParameterDeclarationAST*> *it = node->parameter_declarations->toFront(), *end = it;
- do {
- TypeSpecifierAST* typeAst = it->element->type_specifier;
- if (!m_parameterClause.isEmpty()) m_parameterClause += ",";
- concatenateTokensBetween(typeAst->start_token, typeAst->end_token-1, m_parameterClause);
- it = it->next;
- } while (it!=end);
- // TODO ellipsis
- }
-
- virtual void visitCatchStatement(CatchStatementAST *node) {
- m_currentMcCabe.increment();
- DefaultVisitor::visitCatchStatement(node);
- }
-
-// virtual void visitBaseClause(BaseClauseAST *node) { DefaultVisitor::visitBaseClause(node); }
-// virtual void visitBaseSpecifier(BaseSpecifierAST *node) { DefaultVisitor::visitBaseSpecifier(node); }
-// virtual void visitClassMemberAccess(ClassMemberAccessAST *node) { DefaultVisitor::visitClassMemberAccess(node); }
-// virtual void visitCompoundStatement(CompoundStatementAST *node) { DefaultVisitor::visitCompoundStatement(node); }
-// virtual void visitCondition(ConditionAST *node) { DefaultVisitor::visitCondition(node); }
-// virtual void visitDeclarationStatement(DeclarationStatementAST *node) { DefaultVisitor::visitDeclarationStatement(node); }
-// virtual void visitDeclarator(DeclaratorAST *node) { DefaultVisitor::visitDeclarator(node); }
-// virtual void visitDoStatement(DoStatementAST *node) { DefaultVisitor::visitDoStatement(node); }
-// virtual void visitElaboratedTypeSpecifier(ElaboratedTypeSpecifierAST *node) { DefaultVisitor::visitElaboratedTypeSpecifier(node); }
-// virtual void visitExpressionOrDeclarationStatement(ExpressionOrDeclarationStatementAST *node) { DefaultVisitor::visitExpressionOrDeclarationStatement(node); }
-// virtual void visitExpressionStatement(ExpressionStatementAST *node) { DefaultVisitor::visitExpressionStatement(node); }
-// virtual void visitInitDeclarator(InitDeclaratorAST *node) { DefaultVisitor::visitInitDeclarator(node); }
-// virtual void visitJumpStatement(JumpStatementAST *node) { DefaultVisitor::visitJumpStatement(node); }
-// virtual void visitName(NameAST *node) { DefaultVisitor::visitName(node); }
-// virtual void visitLinkageBody(LinkageBodyAST *node) { DefaultVisitor::visitLinkageBody(node); }
-// virtual void visitOperator(OperatorAST *node) { DefaultVisitor::visitOperator(node); }
-// virtual void visitOperatorFunctionId(OperatorFunctionIdAST *node) { DefaultVisitor::visitOperatorFunctionId(node); }
-// virtual void visitPrimaryExpression(PrimaryExpressionAST *node) { DefaultVisitor::visitPrimaryExpression(node); }
-// virtual void visitReturnStatement(ReturnStatementAST *node) { DefaultVisitor::visitReturnStatement(node); }
-// virtual void visitSimpleDeclaration(SimpleDeclarationAST *node) { DefaultVisitor::visitSimpleDeclaration(node); }
-
-// virtual void visitThrowExpression(ThrowExpressionAST *node) { DefaultVisitor::visitThrowExpression(node); }
-// virtual void visitTranslationUnit(TranslationUnitAST *node) { DefaultVisitor::visitTranslationUnit(node); }
-// virtual void visitTryBlockStatement(TryBlockStatementAST *node) { DefaultVisitor::visitTryBlockStatement(node); }
-// virtual void visitUnaryExpression(UnaryExpressionAST *node) { DefaultVisitor::visitUnaryExpression(node); }
-// virtual void visitUnqualifiedName(UnqualifiedNameAST *node) { DefaultVisitor::visitUnqualifiedName(node); }
-
-// virtual void visitAccessSpecifier(AccessSpecifierAST *) {}
-// virtual void visitAsmDefinition(AsmDefinitionAST *) {}
-// virtual void visitParameterDeclaration(ParameterDeclarationAST*) {}
-// virtual void visitPostfixExpression(PostfixExpressionAST *) {}
-// virtual void visitCastExpression(CastExpressionAST *) {}
-// virtual void visitCppCastExpression(CppCastExpressionAST *) {}
-// virtual void visitCtorInitializer(CtorInitializerAST *) {}
-// virtual void visitDeleteExpression(DeleteExpressionAST *) {}
-// virtual void visitEnumSpecifier(EnumSpecifierAST *) {}
-// virtual void visitEnumerator(EnumeratorAST *) {}
-// virtual void visitExceptionSpecification(ExceptionSpecificationAST *) {}
-// virtual void visitInitializerClause(InitializerClauseAST *) {}
-// virtual void visitInitializer(InitializerAST *) {}
-// virtual void visitFunctionCall(FunctionCallAST *) {}
-// virtual void visitIncrDecrExpression(IncrDecrExpressionAST *) {}
-// virtual void visitNamespaceAliasDefinition(NamespaceAliasDefinitionAST *) {}
-// virtual void visitNewDeclarator(NewDeclaratorAST *) {}
-// virtual void visitNewExpression(NewExpressionAST *) {}
-// virtual void visitNewInitializer(NewInitializerAST *) {}
-// virtual void visitNewTypeId(NewTypeIdAST *) {}
-// virtual void visitLinkageSpecification(LinkageSpecificationAST *) {}
-// virtual void visitMemInitializer(MemInitializerAST *) {}
-// virtual void visitPtrOperator(PtrOperatorAST *) {}
-// virtual void visitPtrToMember(PtrToMemberAST *) {}
-// virtual void visitSizeofExpression(SizeofExpressionAST *) {}
-// virtual void visitStringLiteral(StringLiteralAST *) {}
-// virtual void visitSubscriptExpression(SubscriptExpressionAST *) {}
-// virtual void visitTemplateArgument(TemplateArgumentAST *) {}
-// virtual void visitTemplateDeclaration(TemplateDeclarationAST *) {}
-// virtual void visitTemplateParameter(TemplateParameterAST *) {}
-// virtual void visitTypeId(TypeIdAST *) {}
-// virtual void visitTypeIdentification(TypeIdentificationAST *) {}
-// virtual void visitTypeParameter(TypeParameterAST *) {}
-// virtual void visitTypedef(TypedefAST *) {}
-// virtual void visitUsingDirective(UsingDirectiveAST *) {}
-// virtual void visitWinDeclSpec(WinDeclSpecAST *) {}
-};
-
-} // end anonymous namespace
-
-MetricEngine::MetricEngine()
-{}
-
-MetricEngine::~MetricEngine()
-{}
-
-MetricStore MetricEngine::process(const KUrl& file)
-{
- QByteArray contents = readAll(file);
-
- ParseSession session;
- rpp::Preprocessor preprocessor;
- rpp::pp pp(&preprocessor);
- PreprocessedContents ppContents;
- ppContents= pp.processFile(file.path(), contents);
- session.setContentsAndGenerateLocationTable(ppContents);
-
- Control control;
- Parser parzer(&control);
- TranslationUnitAST *ast = parzer.parse(&session);
- McCabeASTVisitor vtor(session);
- vtor.visit(ast);
-
- return vtor.m_metrics;
-}
-
-QByteArray MetricEngine::readAll(const KUrl& filename)
-{
- QFile f(filename.path());
- f.open(QIODevice::ReadOnly);
- return f.readAll();
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metricengine.h (nonexistent)
@@ -1,40 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef MCCABE_METRICENGINE_H
-#define MCCABE_METRICENGINE_H
-
-#include "metrics.h"
-class KUrl;
-
-/*! @short Metric computation workhorse
- * @unittest MetricEngineTest */
-class MetricEngine
-{
-public:
- MetricEngine();
- virtual ~MetricEngine();
- MetricStore process(const KUrl& file);
-
-protected:
- virtual QByteArray readAll(const KUrl& filename);
-};
-
-#endif // MCCABE_METRICENGINE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/main.cpp (nonexistent)
@@ -1,27 +0,0 @@
-#include "metricengine.h"
-#include "metrics.h"
-#include <iostream>
-#include <kurl.h>
-
-using std::cerr;
-using std::cout;
-using std::endl;
-
-int main(int argc, char** argv)
-{
- cout << "McCabe cyclomatic complexity engine" << endl;
- if (argc == 1) {
- cerr << "No source files provided\nusage: "
- << argv[0] << " file1 [file2 [file3 [...]]]" << endl;
- return -1;
- }
- MetricEngine me;
- for (int i=1; i<argc; i++) {
- cout << "Processing " << argv[i] << endl;
- MetricStore ms = me.process(KUrl(argv[i]));
- foreach(const McCabeMetric& mc, ms.mcCabeComplexity()) {
- cout << mc.value() << " " << mc.function().toLatin1().data() << endl;
- }
- }
- return 0;
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/metrics/src/metrics.cpp (nonexistent)
@@ -1,64 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "metrics.h"
-
-McCabeMetric::McCabeMetric() : m_line(-1), m_complexity(0)
-{}
-
-QString McCabeMetric::function() const
-{
- return m_function;
-}
-
-void McCabeMetric::setFunction(const QString& signature)
-{
- m_function = signature;
-}
-
-int McCabeMetric::line() const
-{
- return m_line;
-}
-
-void McCabeMetric::setLine(int line)
-{
- m_line = line;
-}
-
-int McCabeMetric::value() const
-{
- return m_complexity;
-}
-
-void McCabeMetric::increment()
-{
- m_complexity += 1;
-}
-
-void MetricStore::addMcCabeMetric(const McCabeMetric& mc)
-{
- m_mcCabeComplexity << mc;
-}
-
-QList<McCabeMetric> MetricStore::mcCabeComplexity()
-{
- return m_mcCabeComplexity;
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.h (nonexistent)
@@ -1,41 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef QTEST_LOCATIONREGEXTEST_H_INCLUDED
-#define QTEST_LOCATIONREGEXTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-class LocationRegExTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void simpleLocation();
- void noMatch();
-
-private:
- void assertLocationEquals(const QString& inputLine, const QString& expFile, int expLine);
- void assertNoLocationLine(const QString& inputLine);
-
-};
-
-#endif // QTEST_LOCATIONREGEXTEST_H_INCLUDED
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/CMakeLists.txt (nonexistent)
@@ -1,34 +0,0 @@
-
-include_directories(${CMAKE_CURRENT_BINARY_DIR})
-
-kde4_add_library(kdevctestlib
- ../ctestoutmodel.cpp
- ../ctestlogjob.cpp
- ../ctestlogdelegate.cpp
- ../ctestlogmodel.cpp)
-target_link_libraries(kdevctestlib
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDE4_KDEUI_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
- ${KDEVPLATFORM_UTIL_LIBRARIES})
-
-kde4_add_unit_test(statusregextest statusregextest.cpp )
-target_link_libraries(statusregextest
- kdevctestlib
- ${QT_QTTEST_LIBRARY}
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS})
-
-kde4_add_unit_test(locationregextest locationregextest.cpp )
-target_link_libraries(locationregextest
- kdevctestlib
- ${QT_QTTEST_LIBRARY}
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS})
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.cpp (nonexistent)
@@ -1,94 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "statusregextest.h"
-#include "../ctestoutmodel.h"
-#include <QtTest/QTest>
-
-void StatusRegExTest::assertMatch(const QString& line)
-{
- QVERIFY2(ctestStatusLineRegExp().exactMatch(line), line.toLatin1());
-}
-
-void StatusRegExTest::assertNoMatch(const QString& line)
-{
- QVERIFY2(!ctestStatusLineRegExp().exactMatch(line), line.toLatin1());
-}
-
-void StatusRegExTest::assertCaptured(const QString& text, const QString& testId, const QString& testName)
-{
- QRegExp re = ctestStatusLineRegExp();
- int id = re.indexIn(text);
- QVERIFY(id!=-1);
- QStringList capt = re.capturedTexts();
- QVERIFY(capt.size() >= 3); // The whole match, testId & testName
- QString actualId = capt[1].trimmed();
- QString actualName = capt[2].trimmed();
- QCOMPARE(testName, actualName);
- QCOMPARE(testId, actualId);
-}
-
-void StatusRegExTest::isValid()
-{
- QVERIFY(ctestStatusLineRegExp().isValid());
-}
-
-void StatusRegExTest::passed()
-{
- assertMatch(" 3/ 10 Testing FooBar Passed");
- assertMatch(" 3/ 10 Testing FooBar Passed ");
- assertMatch(" 3/ 10 Testing FooBar Passed");
- assertMatch(" 3/ 10 Testing FooBar Passed");
- assertMatch(" 1/ 300 Testing FooBar Passed");
-}
-
-void StatusRegExTest::noMatch()
-{
- assertNoMatch("FooBar");
- assertNoMatch("abc/ 10 Testing FooBar Passed");
- assertNoMatch(" 3/ edf Testing FooBar ***Failed");
- assertNoMatch(" 3/ 10 AlloAllo FooBar Passed");
- assertNoMatch(" 3 / 10 Testing FooBar Passed");
-}
-
-void StatusRegExTest::failed()
-{
- assertMatch("10/ 30 Testing FooBar ***Failed");
- assertMatch("10/ 30 Testing FooBar ***Failed ");
-}
-
-void StatusRegExTest::timeout()
-{
- assertMatch("10/ 30 Testing FooBar ***Timeout");
- assertMatch("10/ 30 Testing FooBar ***Timeout ");
-}
-
-void StatusRegExTest::capture()
-{
- assertCaptured(" 3/ 10 Testing FooBar Passed", "3/ 10", "FooBar");
-}
-
-void StatusRegExTest::oneOne()
-{
- assertMatch(" 1/ 1 Testing statusregextest Passed");
- assertMatch(" 1/ 1 Testing statusregextest Passed"); // double space
-}
-
-#include "statusregextest.moc"
-QTEST_MAIN(StatusRegExTest)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/statusregextest.h (nonexistent)
@@ -1,45 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTWRAPPER_TEST_STATUSREGEXTEST_H
-#define CTESTWRAPPER_TEST_STATUSREGEXTEST_H
-
-#include <QtCore/QObject>
-
-/*! Tests regular expression that should match lines like:
- * ' 4 / 50 Testing FooTest Passed' */
-class StatusRegExTest : public QObject
-{
-Q_OBJECT
-private slots:
- void isValid();
- void passed();
- void failed();
- void timeout();
- void noMatch();
- void capture();
- void oneOne();
-
-private:
- void assertMatch(const QString& line);
- void assertNoMatch(const QString& line);
- void assertCaptured(const QString& text, const QString& testId, const QString& testName);
-};
-
-#endif // CTESTWRAPPER_TEST_STATUSREGEXTEST_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/tests/locationregextest.cpp (nonexistent)
@@ -1,81 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "locationregextest.h"
-#include <QtTest/QTest>
-#include <qtest_kde.h>
-#include "../ctestlogmodel.h"
-#include <KDebug>
-
-void LocationRegExTest::init()
-{
-}
-
-void LocationRegExTest::cleanup()
-{
-}
-
-void LocationRegExTest::assertLocationEquals(const QString& inputLine, const QString& expFile, int expLine)
-{
- KUrl expFile_(expFile);
- KUrl actualFile;
- int actualLine;
- bool isSrcLine = CTestLogModel::isSourceLocationLine(inputLine, actualFile, actualLine);
- kDebug() << inputLine;
- QVERIFY(isSrcLine);
- QCOMPARE(expFile_, actualFile);
- QCOMPARE(expLine, actualLine);
-}
-
-void LocationRegExTest::assertNoLocationLine(const QString& inputLine)
-{
- KUrl foo; int line;
- bool isSrcLine = CTestLogModel::isSourceLocationLine(inputLine, foo, line);
- QVERIFY(!isSrcLine);
-}
-
-void LocationRegExTest::simpleLocation()
-{
- // run-off-the-mill line
- assertLocationEquals("[/path/to/file(5)]", "/path/to/file", 5);
- assertLocationEquals("[/path/to/file(20)]", "/path/to/file", 20);
- assertLocationEquals("[/path/file(10)]", "/path/file", 10);
-
- // extra stuff in front should be ignored
- assertLocationEquals(" Loc: [/foo/bar(5)]", "/foo/bar", 5);
- // extension
- assertLocationEquals("[/path/to/file.cpp(10)]", "/path/to/file.cpp", 10);
- // top level file
- assertLocationEquals("[/file(15)]", "/file", 15);
-
- assertLocationEquals("[/path/to/file(0)]", "/path/to/file", 0);
- assertLocationEquals("[/path/to/file(9)]", "/path/to/file", 9);
-}
-
-void LocationRegExTest::noMatch()
-{
- assertNoLocationLine("foo bar");
- // no '[ ]'
- assertNoLocationLine("/path/to/file(20)");
- // no number in '()'
- assertNoLocationLine("[/path/to/file(foo)");
-}
-
-QTEST_MAIN( LocationRegExTest )
-#include "locationregextest.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.cpp (nonexistent)
@@ -1,223 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "ctestplugin.h"
-
-#include <KAction>
-#include <KActionCollection>
-#include <KDebug>
-#include <KLocale>
-#include <KPluginFactory>
-#include <KPluginLoader>
-#include <KSelectAction>
-#include <KDialog>
-#include <KLineEdit>
-#include <KHistoryComboBox>
-#include <QComboBox>
-#include <QFrame>
-#include <QGridLayout>
-#include <QLabel>
-#include <KConfig>
-
-#include <interfaces/icore.h>
-#include <interfaces/iproject.h>
-#include <interfaces/idocument.h>
-#include <interfaces/iruncontroller.h>
-#include <project/projectmodel.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <project/interfaces/iprojectfilemanager.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/iprojectcontroller.h>
-#include <ktexteditor/document.h>
-
-#include "ctestoutdelegate.h"
-#include "ctestjob.h"
-
-using namespace KDevelop;
-
-K_PLUGIN_FACTORY(CTestPluginFactory, registerPlugin<CTestPlugin>();)
-K_EXPORT_PLUGIN(CTestPluginFactory("kdevctest"))
-
-CTestPlugin::CTestPlugin(QObject* parent, const QVariantList&)
- : KDevelop::IPlugin( CTestPluginFactory::componentData(), parent )
-{
- setXMLFile("kdevctest.rc");
- m_runDelegate = new CTestOutDelegate(this);
- KAction* run = actionCollection()->addAction("run_ctest");
- run->setText(i18n("Run CTest"));
- run->setShortcut( Qt::ALT| Qt::META | Qt::Key_R );
- connect(run, SIGNAL(triggered()), this, SLOT(showDialog()));
-}
-
-CTestPlugin::~CTestPlugin()
-{
-}
-
-namespace
-{
-QString activeProject()
-{
- ICore* core = ICore::self();
- IDocumentController* dc = core->documentController();
- IDocument* doc = dc->activeDocument();
- if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
- return QString();
- }
-
- // found an active document
- IProjectController* pc = core->projectController();
- IProject* proj = pc->findProjectForUrl( doc->url() );
- if (!proj) {
- return QString();
- }
- return proj->name();
-}
-}
-
-void CTestPlugin::showDialog()
-{
- KDialog* dialog = new KDialog(0);
- dialog->setButtonText(KDialog::Ok, i18n("&Run"));
- dialog->setModal(true);
- dialog->setSizeGripEnabled(false);
-
- QFrame* main = new QFrame(dialog);
- dialog->setMainWidget(main);
- QGridLayout* lay = new QGridLayout();
-
- QLabel* projLabel = new QLabel(dialog);
- projLabel->setText(i18n("Project: "));
- lay->addWidget(projLabel, 0, 0);
-
- QComboBox* projSelection = new QComboBox(dialog);
- projSelection->setObjectName("ProjectSelection");
- projSelection->setDuplicatesEnabled(true);
- QString activeProj = activeProject();
- IProjectController* projCtrl = ICore::self()->projectController();
- int i=0;
- if (projCtrl->projects().count() == 0) return; // NO-OP if no project loaded
- foreach(IProject* proj, projCtrl->projects()) {
- projSelection->addItem(proj->name());
- if (proj->name() == activeProj) {
- projSelection->setCurrentIndex(i);
- }
- i++;
- }
- lay->addWidget(projSelection, 0, 1);
-
- QLabel* argsLabel = new QLabel(dialog);
- argsLabel->setText(i18n("Flags: "));
- lay->addWidget(argsLabel, 0, 2);
-
- KHistoryComboBox* argsInput = new KHistoryComboBox(true, dialog);
- argsInput->setMaxCount(10);
- argsInput->setDuplicatesEnabled( false );
- argsInput->setMinimumContentsLength( 35 );
- argsInput->setObjectName("CTestFlagsInput");
-
- KConfigGroup cg = KGlobal::config()->group( "CTest" );
- QStringList history = cg.readEntry<QStringList>("args", QStringList());
- lay->addWidget(argsInput, 0, 3);
- foreach(const QString& args, history) {
- argsInput->addToHistory(args);
- }
-
- main->setLayout(lay);
- connect(dialog, SIGNAL(okClicked()), SLOT(startRunJob()));
- connect(dialog, SIGNAL(finished()), dialog, SLOT(deleteLater()));
- dialog->show();
-}
-
-namespace
-{
-
-// helper for startRunJob()
-IProject* fetchProjectFrom(KDialog* dialog)
-{
- Q_ASSERT(dialog->findChildren<QComboBox*>().count() == 2);
- QList<QComboBox*> comboBoxes = dialog->findChildren<QComboBox*>();
- QComboBox* projSelection = comboBoxes[0];
- if (projSelection->objectName() != "ProjectSelection") {
- projSelection = comboBoxes[1];
- Q_ASSERT(projSelection->objectName() == "ProjectSelection");
- }
- QString projName = projSelection->itemText(projSelection->currentIndex());
- IProjectController* projCtrl = ICore::self()->projectController();
- IProject* project = projCtrl->findProjectByName(projName);
- if (!project) {
- kError() << "Failed to retrieve project " << projName << projSelection->currentIndex();
- }
- return project;
-}
-
-// helper for startRunJob()
-KUrl fetchBuildDirFor(IProject* project)
-{
- if (!project->buildSystemManager()) {
- // no buildsystem manager, so no build dir to run ctest in.
- return KUrl();
- }
- IBuildSystemManager* builder = project->buildSystemManager();
- ProjectFolderItem* root = project->projectItem();
- return builder->buildDirectory(root);
-}
-
-// helper for startRunJob()
-QStringList fetchArgs(KDialog* dialog)
-{
- Q_ASSERT(dialog->findChildren<KHistoryComboBox*>().count()==1);
- KHistoryComboBox* argsBox = dialog->findChildren<KHistoryComboBox*>()[0];
- Q_ASSERT(argsBox);
- return argsBox->lineEdit()->text().split(" "); // do the right thing for escaped stuff
-}
-
-void writeArgsToConfig(KDialog* dialog)
-{
- Q_ASSERT(dialog->findChildren<KHistoryComboBox*>().count()==1);
- KHistoryComboBox* argsBox = dialog->findChildren<KHistoryComboBox*>()[0];
- KConfigGroup cg = KGlobal::config()->group( "CTest" );
- argsBox->addToHistory(argsBox->lineEdit()->text());
- cg.writeEntry("args", argsBox->historyItems());
-}
-
-} // namespace
-
-void CTestPlugin::startRunJob()
-{
- Q_ASSERT(sender());
- KDialog* runDialog = qobject_cast<KDialog*>(sender());
- Q_ASSERT(runDialog);
-
- IProject* project = fetchProjectFrom(runDialog);
- if (!project) return;
- KUrl buildDir = fetchBuildDirFor(project);
- if (!buildDir.isValid()) return;
- QStringList args = fetchArgs(runDialog);
- writeArgsToConfig(runDialog);
-
- CTestJob* job = new CTestJob(m_runDelegate); // does not get deleted methinks
- job->setTestRoot(buildDir);
- kDebug() << "args" << args;
- job->setCTestArguments(args);
-
- ICore::self()->runController()->registerJob(job);
-}
-
-#include "ctestplugin.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.cpp (nonexistent)
@@ -1,49 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "ctestlogdelegate.h"
-#include "ctestlogmodel.h"
-#include <QtGui/QPainter>
-#include <QtCore/QModelIndex>
-#include <KDebug>
-
-
-CTestLogDelegate::CTestLogDelegate(QObject* parent)
- : QItemDelegate(parent),
- textBrush(KColorScheme::View, KColorScheme::NormalText),
- errorBrush(KColorScheme::View, KColorScheme::NegativeText),
- passBrush(KColorScheme::View, KColorScheme::PositiveText)
-{
-}
-
-void CTestLogDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
-{
- QString text = index.data(Qt::DisplayRole).toString();
- QStyleOptionViewItem style(option);
- if (text.startsWith("PASS")) { // QTestLib prints this in front of green commands
- style.palette.setBrush(QPalette::Text, passBrush.brush(style.palette));
- } else if (text.startsWith("FAIL!")) { // QTestLib specific output
- style.palette.setBrush(QPalette::Text, errorBrush.brush(style.palette));
- }
- QItemDelegate::paint(painter, style, index);
-}
-
-#include "ctestlogdelegate.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.h (nonexistent)
@@ -1,71 +0,0 @@
-/* KDevelop xUnit plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTWRAPPER_CTESTLOGMODEL_H
-#define CTESTWRAPPER_CTESTLOGMODEL_H
-
-#include <QStandardItemModel>
-#include <outputview/ioutputviewmodel.h>
-
-class QModelIndex;
-class QRegExp;
-class KUrl;
-
-/*! A model item in the verbose model. This represents a single line
- * of text in a ctest-log.*/
-class CTestLogItem : public QStandardItem
-{
-public:
- CTestLogItem(const QString &text);
- ~CTestLogItem();
-};
-
-/*! Holds ctest-log text lines, to be shown in an outputview. */
-class CTestLogModel : public QStandardItemModel, public KDevelop::IOutputViewModel
-{
-Q_OBJECT
-
-public:
- explicit CTestLogModel(QObject *parent=0);
- ~CTestLogModel();
-
- void activate(const QModelIndex &idx);
- QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
- QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
- QVariant data(const QModelIndex& index, int role) const;
-
- /*! Matches lines like
- * [/path/to/file(10)]
- * where '10' is a linenumber
- *
- * If this matches with @p text, returns true and fills
- * @p file and @p line
- * Returns false if not matched. */
- static bool isSourceLocationLine(const QString& text, KUrl& file, int& line);
-
-public Q_SLOTS:
- void appendOutputs(const QStringList &lines);
- void appendErrors(const QStringList &lines);
- void slotCompleted();
- void slotFailed();
-};
-
-#endif // CTESTWRAPPER_LOGMODEL_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevctest.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/CMakeLists.txt (nonexistent)
@@ -1,48 +0,0 @@
-project(CTestWrapper)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CTestWrapper_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR})
-
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-enable_testing()
-
-include_directories(
- ${QT_INCLUDES}
- ${KDE4_INCLUDES}
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR} )
-
-add_subdirectory(tests)
-
-########### next target ###############
-
-set(kdevctest_SRCS
- ctestplugin.cpp
- ctestjob.cpp
- ctestoutdelegate.cpp
- ctestoutmodel.cpp
- ctestlogjob.cpp
- ctestlogmodel.cpp
- ctestlogdelegate.cpp)
-
-qt4_automoc(${kdevctest_SRCS})
-kde4_add_plugin(kdevctest ${kdevctest_SRCS})
-target_link_libraries(kdevctest
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDE4_KDEUI_LIBS}
- ${KDE4_KTEXTEDITOR_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
- ${KDEVPLATFORM_UTIL_LIBRARIES})
-install(TARGETS kdevctest DESTINATION ${PLUGIN_INSTALL_DIR})
-
-########### install files ###############
-
-install( FILES kdevctest.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevctest.rc DESTINATION ${DATA_INSTALL_DIR}/kdevctest )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.h (nonexistent)
@@ -1,64 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTWRAPPER_CTESTLOGJOB_H
-#define CTESTWRAPPER_CTESTLOGJOB_H
-
-#include <outputview/outputjob.h>
-
-#include <KUrl>
-
-class CTestLogModel;
-class CTestLogDelegate;
-class CTestOutItem;
-
-/*! @short Job which extracts a certain relevant part of a full ctest output log
- *
- * This job is started when the users activates an item in the CTestOutModel.
- * Only the ctest output for this item is shown. This ctest-log is typically
- * stored in build-dir/Testing/Temporary/LastTests.log. Once extracted this
- * test output is then shown in a kdevelop-outputview. */
-class CTestLogJob : public KDevelop::OutputJob
-{
-Q_OBJECT
-
-public:
- /*! @p parent controls colorization of items
- * @p testRoot directory ctest was run in
- * @p test test-item from the ctestoutmodel that triggered this job.
- * this job extracts output for this specific item from the global ctest log. */
- CTestLogJob(CTestLogDelegate *delegate, CTestLogModel* model, const KUrl& testRoot, CTestOutItem* test);
- virtual ~CTestLogJob();
-
- virtual void start();
-
-protected:
- CTestLogModel* model() const;
-
-private:
- void readLog(const KUrl& file);
-
-private:
- KUrl m_testRoot;
- CTestOutItem* m_test;
- CTestLogDelegate* m_delegate;
- CTestLogModel* m_model;
-};
-
-#endif // CTESTWRAPPER_CTESTLOGJOB_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.cpp (nonexistent)
@@ -1,65 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "ctestoutdelegate.h"
-#include "ctestoutmodel.h"
-#include <QtGui/QPainter>
-#include <QtCore/QModelIndex>
-#include <KDebug>
-
-CTestOutDelegate::CTestOutDelegate(QObject* parent)
- : QItemDelegate(parent),
- textBrush(KColorScheme::View, KColorScheme::NormalText),
- errorBrush(KColorScheme::View, KColorScheme::NegativeText),
- passBrush(KColorScheme::View, KColorScheme::PositiveText)
-{
-}
-
-void CTestOutDelegate::initStyleFor(const QVariant& stateVariant, QStyleOptionViewItem& style) const
-{
- //CTestOutItem::State state = stateVariant.value<CTestOutItem::State>();
- int state = stateVariant.toInt();
- switch (state) {
- case CTestOutItem::Failed:
- case CTestOutItem::Timeout:
- style.palette.setBrush(QPalette::Text, errorBrush.brush(style.palette));
- break;
- case CTestOutItem::Passed:
- style.palette.setBrush(QPalette::Text, passBrush.brush(style.palette));
- break;
- default:
- style.palette.setBrush(QPalette::Text, textBrush.brush(style.palette));
- }
-}
-
-void CTestOutDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
-{
- QStyleOptionViewItem opt = option;
- QVariant state = index.data(CTestOutItem::StateRole);
- if (state.isValid()) {
- initStyleFor(state, opt);
- } else {
- opt.palette.setBrush(QPalette::Text, textBrush.brush(option.palette));
- }
- QItemDelegate::paint(painter, opt, index);
-}
-
-#include "ctestoutdelegate.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.h (nonexistent)
@@ -1,82 +0,0 @@
-/* KDevelop xUnit plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTOUTMODEL_H
-#define CTESTOUTMODEL_H
-
-#include <QStandardItemModel>
-#include <outputview/ioutputviewmodel.h>
-#include <KUrl>
-
-class QModelIndex;
-
-/*! Item of the CTestOut model. It represents a single
- * ctest test status output line like:
- * ' 4/ 50 Testing FooBar Passed'. */
-class CTestOutItem : public QStandardItem
-{
-public:
- CTestOutItem(const QString &text);
- ~CTestOutItem();
- enum State { NotRun, /** Test did not finish yet */
- Passed, Failed, Timeout };
- virtual QVariant data(int role) const;
- QString m_id; /** The '14/ 52' bit of a ctest output line */
- QString m_name; /** The 'FooTest' bit of a ctest output line */
- State m_state;
- void extractNameAndNumber(); /** Fills m_id and m_name from the Qt::DisplayData ie a line of output */
-
- enum { StateRole = QStandardItem::UserType+1 };
-};
-
-Q_DECLARE_METATYPE(CTestOutItem::State)
-
-/*! Matches lines like '2/ 40 Testing FooTest Passed'
- * '3/ 40 Testing BarTest ***Failed' */
-QRegExp& ctestStatusLineRegExp();
-
-/*! Holds ctest-process output lines, to be shown in an outputview */
-class CTestOutModel : public QStandardItemModel, public KDevelop::IOutputViewModel
-{
-Q_OBJECT
-
-public:
- explicit CTestOutModel(QObject *parent);
- ~CTestOutModel();
-
- void activate(const QModelIndex &idx);
- QModelIndex nextHighlightIndex(const QModelIndex& currentIndex);
- QModelIndex previousHighlightIndex(const QModelIndex& currentIndex);
- QVariant data(const QModelIndex& index, int role) const;
- void setTestRoot(const KUrl& root);
- void startLogJobFor(CTestOutItem* item);
-
-public Q_SLOTS:
- void appendOutputs(const QStringList &lines);
- void appendErrors(const QStringList &lines);
- void slotCompleted();
- void slotFailed();
-
-private:
- KUrl m_testRoot;
-};
-
-#endif // CTESTOUTMODEL_h
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestplugin.h (nonexistent)
@@ -1,46 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTPLUGIN_H
-#define CTESTPLUGIN_H
-
-#include <QVariantList>
-#include <interfaces/iplugin.h>
-
-class CTestOutDelegate;
-
-class CTestPlugin : public KDevelop::IPlugin
-{
-Q_OBJECT
-
-public:
- explicit CTestPlugin(QObject* parent, const QVariantList& = QVariantList());
- virtual ~CTestPlugin();
-
-private slots:
- void showDialog();
- void startRunJob();
-
-private:
- CTestOutDelegate* m_runDelegate; // controls colorization of items in the ctest-run outputview
-};
-
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.cpp (nonexistent)
@@ -1,102 +0,0 @@
-/* KDevelop xUnit plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com> *
- * Copyright 2008 by Hamish Rodda <rodda@kde.org>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-// local
-#include "ctestjob.h"
-#include "ctestoutmodel.h"
-#include "ctestoutdelegate.h"
-
-// KDE
-#include <KLocale>
-#include <KDebug>
-#include <KProcess>
-
-// KDevPlatform
-#include <interfaces/icore.h>
-#include <util/processlinemaker.h>
-
-using KDevelop::OutputJob;
-using KDevelop::ProcessLineMaker;
-
-CTestJob::CTestJob(CTestOutDelegate* parent)
- : OutputJob(parent), m_ctest(0)
-{}
-
-CTestJob::~CTestJob()
-{}
-
-void CTestJob::start()
-{
- Q_ASSERT(m_testRoot.isValid()); Q_ASSERT(m_ctest == 0);
-
- setToolTitle(i18n("CTest"));
- setToolIcon(KIcon("dialog-ok-apply"));
- setViewType(KDevelop::IOutputView::HistoryView);
- setBehaviours(KDevelop::IOutputView::AutoScroll | KDevelop::IOutputView::AllowUserClose);
- setViewType(KDevelop::IOutputView::OneView);
-
- setModel(new CTestOutModel(delegate()), KDevelop::IOutputView::TakeOwnership);
- model()->setTestRoot(m_testRoot);
- setDelegate(delegate());
-
- m_ctest = new KProcess(this);
- m_ctest->setWorkingDirectory(m_testRoot.path());
- m_ctest->setProgram("ctest", m_ctestArgs);
- m_ctest->setOutputChannelMode(KProcess::MergedChannels);
- ProcessLineMaker* plm = new ProcessLineMaker(m_ctest, this);
-
- startOutput();
- connect(plm, SIGNAL(receivedStdoutLines(QStringList)), model(), SLOT(appendOutputs(QStringList)));
- connect(plm, SIGNAL(receivedStderrLines(QStringList)), model(), SLOT(appendErrors(QStringList)));
- connect(m_ctest, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(done()));
- m_ctest->start();
-}
-
-void CTestJob::done()
-{
- model()->slotCompleted();
- emitResult();
-}
-
-void CTestJob::setTestRoot(const KUrl& root)
-{
- Q_ASSERT(root.isValid()); Q_ASSERT(!m_testRoot.isValid());
- m_testRoot = root;
-}
-
-void CTestJob::setCTestArguments(const QStringList& args)
-{
- Q_ASSERT(m_ctestArgs.isEmpty());
- m_ctestArgs = args;
-}
-
-CTestOutDelegate* CTestJob::delegate() const
-{
- return const_cast<CTestOutDelegate*>(static_cast<const CTestOutDelegate*>(parent()));
-}
-
-CTestOutModel* CTestJob::model() const
-{
- return static_cast<CTestOutModel*>(OutputJob::model());
-}
-
-#include "ctestjob.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogmodel.cpp (nonexistent)
@@ -1,123 +0,0 @@
-/* This file is part of KDevelop
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "ctestlogmodel.h"
-
-#include <QModelIndex>
-#include <KGlobalSettings>
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <ktexteditor/cursor.h>
-
-#include <QRegExp>
-
-using KDevelop::ICore;
-using KDevelop::IDocumentController;
-
-CTestLogItem::CTestLogItem(const QString &text)
- : QStandardItem(text)
-{}
-
-CTestLogItem::~CTestLogItem()
-{}
-
-CTestLogModel::CTestLogModel(QObject *parent)
- : QStandardItemModel(parent)
-{}
-
-CTestLogModel::~CTestLogModel()
-{}
-
-QVariant CTestLogModel::data(const QModelIndex& index, int role) const
-{
- if (role != Qt::FontRole) {
- return QStandardItemModel::data(index, role);
- } else {
- return KGlobalSettings::fixedFont();
- }
-}
-
-namespace
-{
- // locRe matches location references in verbose output like:
- // [/path/to/foo.cpp(123)]
- QRegExp g_locRe("\\[(([/].*)+)\\(([0-9]+)\\)\\]"); // TODO not quite portable
-}
-
-bool CTestLogModel::isSourceLocationLine(const QString& text, KUrl& file, int& line)
-{
- Q_ASSERT(g_locRe.isValid());
- QRegExp re = g_locRe;
- if (-1 == re.indexIn(text)) return false;
- // got a match
- file = KUrl(re.cap(1));
- line = re.cap(re.capturedTexts().size()-1).toInt();
- return true;
-}
-
-void CTestLogModel::activate(const QModelIndex &idx)
-{
- QString text = idx.data(Qt::DisplayRole).toString();
- KUrl file;
- int line;
- bool isSrcLine = isSourceLocationLine(text, file, line);
- if (isSrcLine) {
- KTextEditor::Cursor loc(line-1, 0);
- IDocumentController* docCtrl = ICore::self()->documentController();
- docCtrl->openDocument(file, loc);
- }
-}
-
-QModelIndex CTestLogModel::nextHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-QModelIndex CTestLogModel::previousHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-void CTestLogModel::appendOutputs(const QStringList &lines)
-{
- foreach(const QString& line, lines) {
- appendRow(new QStandardItem(line));
- }
-}
-
-void CTestLogModel::appendErrors(const QStringList &lines)
-{
- foreach(const QString& line, lines) {
- appendRow(new QStandardItem(line));
- }
-}
-
-void CTestLogModel::slotCompleted()
-{
-}
-
-void CTestLogModel::slotFailed()
-{
- appendRow(new QStandardItem("Failed"));
-}
-
-#include "ctestlogmodel.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutmodel.cpp (nonexistent)
@@ -1,171 +0,0 @@
-/* This file is part of KDevelop
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "ctestoutmodel.h"
-#include "ctestlogjob.h"
-#include "ctestlogmodel.h"
-#include "ctestlogdelegate.h"
-
-#include <QModelIndex>
-#include <KGlobalSettings>
-#include <interfaces/icore.h>
-#include <QRegExp>
-#include <interfaces/icore.h>
-#include <interfaces/iruncontroller.h>
-
-using namespace KDevelop;
-
-
-namespace
-{
-QRegExp g_ctestStatusLine("^[ ]*([0-9]+/[ ]+[0-9]+)[ ]+Testing[ ](.*)[ ].*$"); // eg: '1/ 52 Testing parsertest PASSED'
-}
-
-QRegExp& ctestStatusLineRegExp()
-{
- return g_ctestStatusLine;
-}
-
-CTestOutItem::CTestOutItem(const QString &text)
- : QStandardItem(text), m_state(NotRun)
-{
- qRegisterMetaType<CTestOutItem::State>();
-}
-
-CTestOutItem::~CTestOutItem()
-{}
-
-#include <KDebug>
-
-void CTestOutItem::extractNameAndNumber()
-{
- // extract test name and test number from a model line like:
- // 1 / 20 Testing Foo
- // name = Foo; number = 1
-
- QRegExp re = ctestStatusLineRegExp();
- #ifndef QT_NO_DEBUG
- int i = re.indexIn(data(Qt::DisplayRole).toString());
- Q_ASSERT(i!=-1);
- #endif
- QStringList captured = re.capturedTexts();
- m_id = captured.value(1).split(" ").join("");
- m_name = captured.value(2).trimmed();
-}
-
-QVariant CTestOutItem::data(int role) const
-{
- if(role == StateRole) {
- return (int)m_state;
- } else {
- return QStandardItem::data(role);
- }
-}
-
-CTestOutModel::CTestOutModel(QObject *parent)
- : QStandardItemModel(parent)
-{}
-
-CTestOutModel::~CTestOutModel()
-{}
-
-QVariant CTestOutModel::data(const QModelIndex& index, int role) const
-{
- if (role != Qt::FontRole) {
- return QStandardItemModel::data(index, role);
- } else {
- return KGlobalSettings::fixedFont();
- }
-}
-
-void CTestOutModel::startLogJobFor(CTestOutItem* item)
-{
- CTestLogDelegate* delegate = new CTestLogDelegate();
- CTestLogModel* model = new CTestLogModel();
- CTestLogJob* job = new CTestLogJob(delegate, model, m_testRoot, item);
- ICore::self()->runController()->registerJob(job);
-}
-
-void CTestOutModel::activate(const QModelIndex &idx)
-{
- // show verbose output when a user clicks on a test
- QStandardItem *stditem = itemFromIndex(idx);
- CTestOutItem *ctestitem = dynamic_cast<CTestOutItem*>(stditem);
- if (!ctestitem) return;
- ctestitem->extractNameAndNumber();
- startLogJobFor(ctestitem);
-}
-
-QModelIndex CTestOutModel::nextHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-QModelIndex CTestOutModel::previousHighlightIndex(const QModelIndex& currentIndex)
-{
- Q_UNUSED(currentIndex);
- return QModelIndex();
-}
-
-void CTestOutModel::appendOutputs(const QStringList &lines)
-{
- foreach(const QString& line, lines) {
- if (ctestStatusLineRegExp().exactMatch(line)) {
- CTestOutItem* item = new CTestOutItem(line);
- if (line.endsWith("Passed")) {
- item->m_state = CTestOutItem::Passed;
- } else if (line.endsWith("***Failed ")) {
- item->m_state = CTestOutItem::Failed;
- } else if (line.endsWith("***Timeout")) {
- item->m_state = CTestOutItem::Timeout;
- } else if (line.contains("***Exception: ")) {
- item->m_state = CTestOutItem::Failed;
- } else {
- item->m_state = CTestOutItem::NotRun;
- }
- appendRow(item);
- } else {
- appendRow(new QStandardItem(line));
- }
- }
-}
-
-void CTestOutModel::appendErrors(const QStringList &lines)
-{
- foreach(const QString& line, lines) {
- appendRow(new QStandardItem(line));
- }
-}
-
-void CTestOutModel::slotCompleted()
-{}
-
-void CTestOutModel::slotFailed()
-{
- appendRow(new QStandardItem("Failed"));
-}
-
-void CTestOutModel::setTestRoot(const KUrl& root)
-{
- m_testRoot = root;
-}
-
-#include "ctestoutmodel.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogdelegate.h (nonexistent)
@@ -1,42 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef QTEST_QTESTOUTPUTDELEGATE_H
-#define QTEST_QTESTOUTPUTDELEGATE_H
-
-#include <QtGui/QItemDelegate>
-#include <kcolorscheme.h>
-
-class CTestLogDelegate : public QItemDelegate
-{
-Q_OBJECT
-
-public:
- CTestLogDelegate(QObject* parent=0);
- void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
-
-private:
- KStatefulBrush textBrush;
- KStatefulBrush errorBrush;
- KStatefulBrush passBrush;
-};
-
-#endif // QTEST_QTESTOUTPUTDELEGATE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctest-wrapper.kdev4 (nonexistent)
@@ -1,3 +0,0 @@
-[Project]
-Name=ctest-wrapper
-Manager=KDevCMakeManager
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestoutdelegate.h (nonexistent)
@@ -1,51 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright (C) 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef QTEST_QTESTOUTPUTDELEGATE_H
-#define QTEST_QTESTOUTPUTDELEGATE_H
-
-#include <QtGui/QItemDelegate>
-#include <kcolorscheme.h>
-
-/*! Is responsible for colorizing items in the primary ctest
- * output view.
- * eg:
- * 2/ 20 Testing Foo Passed << this line is colored green
- * 3/ 20 Testing Bar ***Failed << this one is red.
- */
-class CTestOutDelegate : public QItemDelegate
-{
-Q_OBJECT
-
-public:
- CTestOutDelegate(QObject*);
- void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const;
-
-private:
- void inline initStyleFor(const QVariant& state, QStyleOptionViewItem& style) const;
-
-private:
- KStatefulBrush textBrush;
- KStatefulBrush errorBrush;
- KStatefulBrush passBrush;
-};
-
-#endif // QTEST_QTESTOUTPUTDELEGATE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.desktop (nonexistent)
@@ -1,69 +0,0 @@
-[Desktop Entry]
-Type=Service
-Icon=kdevelop
-Exec=blubb
-Comment=CTest
-Comment[bs]=CTest
-Comment[ca]=CTest
-Comment[ca@valencia]=CTest
-Comment[cs]=CTest
-Comment[de]=CTest
-Comment[el]=CTest
-Comment[en_GB]=CTest
-Comment[eo]=CTest
-Comment[es]=CTest
-Comment[et]=CTest
-Comment[fr]=CTest
-Comment[ga]=CTest
-Comment[gl]=CTest
-Comment[hu]=CTest
-Comment[it]=CTest
-Comment[ja]=CTest
-Comment[ms]=CTest
-Comment[nds]=C-Test
-Comment[nl]=CTest
-Comment[pa]=CTest
-Comment[pl]=CTest
-Comment[pt]=CTest
-Comment[pt_BR]=CTest
-Comment[si]=CTest
-Comment[sk]=CTest
-Comment[sv]=CTest
-Comment[tr]=CTest
-Comment[ug]=CTest
-Comment[uk]=CTest
-Comment[x-test]=xxCTestxx
-
-Name=CTest
-Name[bs]=CTest
-Name[ca]=CTest
-Name[ca@valencia]=CTest
-Name[cs]=CTest
-Name[de]=CTest
-Name[en_GB]=CTest
-Name[eo]=CTest
-Name[es]=CTest
-Name[et]=CTest
-Name[fr]=CTest
-Name[ga]=CTest
-Name[gl]=CTest
-Name[hu]=CTest
-Name[it]=CTest
-Name[nl]=CTest
-Name[pl]=CTest
-Name[pt]=CTest
-Name[pt_BR]=CTest
-Name[sk]=CTest
-Name[sv]=CTest
-Name[ug]=CTest
-Name[uk]=CTest
-Name[x-test]=xxCTestxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevctest
-X-KDE-PluginInfo-Name=kdevctest
-X-KDE-PluginInfo-Author=Manuel Breugelmans
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=LGPL
-X-KDevelop-Version=7
-X-KDevelop-Category=Global
-X-KDevelop-Properties=GlobalFileManagement
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestjob.h (nonexistent)
@@ -1,66 +0,0 @@
-/* This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CTESTWRAPPER_CTESTJOB_H
-#define CTESTWRAPPER_CTESTJOB_H
-
-#include <outputview/outputjob.h>
-
-#include <KUrl>
-
-class CTestOutModel;
-class CTestOutDelegate;
-class KProcess;
-
-/*! Job class which runs ctest in a given directory */
-class CTestJob : public KDevelop::OutputJob
-{
- Q_OBJECT
-
-public:
- /*! @p parent controls colorization of items
- * @p testRoot directory to run ctest in */
- CTestJob(CTestOutDelegate *parent);
- virtual ~CTestJob();
-
- /*! Initialize the directory to run ctest in.
- * This is typically the project's build directory
- * @note Mandatory */
- void setTestRoot(const KUrl& testRoot);
-
- /*! Set extra flags and arguments passed to the ctest
- * process */
- void setCTestArguments(const QStringList& args);
-
- virtual void start();
-
-protected:
- CTestOutModel* model() const;
-
-private slots:
- void done();
-
-private:
- CTestOutDelegate* delegate() const;
- KProcess* m_ctest;
- KUrl m_testRoot;
- QStringList m_ctestArgs;
-};
-
-#endif // CTESTWRAPPER_CTEST_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/ctestlogjob.cpp (nonexistent)
@@ -1,141 +0,0 @@
-/* KDevelop xUnit plugin
- * Copyright 1999-2001 Bernd Gehrmann and the KDevelop Team <bernd@kdevelop.org>
- * Copyright 2007 Dukju Ahn <dukjuahn@gmail.com> *
- * Copyright 2008 by Hamish Rodda <rodda@kde.org>
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-// local
-#include "ctestlogjob.h"
-#include "ctestlogmodel.h"
-#include "ctestlogdelegate.h"
-#include "ctestoutmodel.h"
-
-// KDE/Qt
-#include <KLocale>
-#include <KDebug>
-#include <KProcess>
-#include <QFile>
-
-// KDevPlatform
-#include <interfaces/icore.h>
-
-using KDevelop::OutputJob;
-
-CTestLogJob::CTestLogJob(CTestLogDelegate* delegate, CTestLogModel* model, const KUrl& testRoot, CTestOutItem* test)
- : OutputJob(0), m_testRoot(testRoot), m_test(test), m_delegate(delegate), m_model(model)
-{}
-
-CTestLogJob::~CTestLogJob()
-{}
-
-void CTestLogJob::start()
-{
- Q_ASSERT(m_testRoot.isValid()); Q_ASSERT(m_test != 0);
-
- setToolTitle(i18n("CTest"));
- setToolIcon(KIcon("edit-find"));
- setViewType(KDevelop::IOutputView::HistoryView);
- setStandardToolView(KDevelop::IOutputView::TestView);
- setBehaviours(KDevelop::IOutputView::AutoScroll | KDevelop::IOutputView::AllowUserClose);
-
- setModel(m_model, KDevelop::IOutputView::TakeOwnership);
- setDelegate(m_delegate, KDevelop::IOutputView::TakeOwnership);
-
- KUrl ctestLogFile(m_testRoot, "Testing/Temporary/LastTest.log");
- if (!ctestLogFile.isLocalFile()) {
- kWarning() << "Only local CTest log files supported for now [" << ctestLogFile.path() << "]";
- return;
- }
- if (!QFile::exists(ctestLogFile.path())) {
- kWarning() << "CTest log file does not exist [" << ctestLogFile.path() << "]";
- return;
- }
-
- startOutput();
- readLog(ctestLogFile);
- model()->slotCompleted();
- emitResult();
-}
-
-void CTestLogJob::readLog(const KUrl& ctestLog)
-{
- QFile f(ctestLog.path());
- f.open(QIODevice::ReadOnly);
- if (!f.isOpen()) {
- kError() << "Failed to open test output file for reading [" << ctestLog.path() << "]";
- return;
- }
- QTextStream stream(&f);
-
- // skip until the start of m_test
-
- // 4/52 Testing: duchaintest
- // 4/52 Test: duchaintest
- // Command: "/home/nix/KdeDev/kdevelop/build/languages/cpp/cppduchain/tests/duchaintest.shell"
- // Directory: /home/nix/KdeDev/kdevelop/build/languages/cpp/cppduchain/tests
- // "duchaintest" start time: Oct 28 16:26 CET
- // Output:
- //----------------------------------------------------------
-
- QString marker("----------------------------------------------------------\n");
- bool foundTestStart = false;
- QString line;
- while(!f.atEnd() && !foundTestStart) {
- line = f.readLine();
- if (line.startsWith(m_test->m_id)) {
- kDebug(9003) << "found test id " << m_test->m_id << line;
- // found '4/52' or the likes, now skip until '-----------------'
- while (!f.atEnd() && !foundTestStart) {
- line = f.readLine();
- kDebug(9003) << line;
- if (line == marker) foundTestStart = true;
- }
- }
- }
-
- if (f.atEnd()) {
- kError() << "Failed to find output for" << m_test->m_name << "in ctest log [" << ctestLog.path() << "]";
- return;
- }
-
- bool foundTestEnd = false;
- QStringList lines;
- while (!f.atEnd() && !foundTestEnd) {
- lines.clear();
- for (int i=0; i<1000 && !f.atEnd(); ++i) {
- QString line = f.readLine();
- if (line == marker) {
- // another '-----------------'. this is a bit fragile as stopping criteria ...
- foundTestEnd = true;
- break;
- }
- line.chop(1);
- //kDebug(9003) << "append ->" << line;
- lines.append(line);
- }
- model()->appendOutputs(lines);
- }
-}
-
-CTestLogModel* CTestLogJob::model() const
-{
- return m_model;
-}
-
-#include "ctestlogjob.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/ctest/kdevctest.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="kdevctest" version="1">
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp (nonexistent)
@@ -1,127 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Niko Sams <niko.sams@gmail.com>
-
- 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.
-*/
-#include "includemanagertest.h"
-
-#include <qtest_kde.h>
-
-#include <tests/autotestshell.h>
-#include <tests/testcore.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <includemanager.h>
-
-QTEST_KDEMAIN(IncludeManagerTest, GUI)
-
-void IncludeManagerTest::init()
-{
- KDevelop::AutoTestShell::init();
- m_core = new KDevelop::TestCore();
- m_core->initialize(KDevelop::Core::NoUi);
-}
-
-void IncludeManagerTest::cleanup()
-{
- m_core->cleanup();
- delete m_core;
-}
-
-
-void IncludeManagerTest::testUsed()
-{
- KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
-
- TestFile f1("class xy {}; ", "xyXXXXXXX.h");
-
- QByteArray c;
- c += "#include \"";
- c += QDir::currentPath() + "/" + f1.fileName();
- c+= "\"\nvoid main() { xy i; } ";
- TestFile f2(c, "XXXXXX.cpp");
- f2.parse(features);
- f2.waitForParsed();
-
- QList<IncludeProblemItem> includes = IncludeManager::includes(f2.topContext());
- QCOMPARE(includes.count(), 1);
- QCOMPARE(includes.first().url, KUrl(QDir::currentPath() + "/" + f1.fileName()));
-}
-
-void IncludeManagerTest::testUnused()
-{
- KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
-
- TestFile f1("class xy {}; ", "xyXXXXXXX.h");
-
- QByteArray c;
- c += "#include \"";
- c += QDir::currentPath() + "/" + f1.fileName();
- c+= "\"\nvoid main() { } ";
- TestFile f2(c, "XXXXXX.cpp");
- f2.parse(features);
- f2.waitForParsed();
-
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
-
- QList<IncludeProblemItem> includes = IncludeManager::includes(f2.topContext());
- QCOMPARE(includes.count(), 0);
-}
-
-void IncludeManagerTest::testIndirectUsed()
-{
- KDevelop::TopDUContext::Features features = KDevelop::TopDUContext::AllDeclarationsContextsAndUses;
-
- TestFile f1("class xy {}; ", "xyXXXXXXX.h");
- QByteArray c;
- c += "#include \"";
- c += QDir::currentPath() + "/" + f1.fileName();
- c += "\"\n";
- TestFile f2(c, "xyXXXXXXX.h");
-
- QByteArray c2;
- c2 += "#include \"";
- c2 += QDir::currentPath() + "/" + f2.fileName();
- c2 += "\"\nvoid main() { xy i; } ";
- TestFile f3(c2, "XXXXXX.cpp");
- f3.parse(features);
- f3.waitForParsed();
-
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
-
- QList<IncludeProblemItem> includes = IncludeManager::includes(f3.topContext());
- QCOMPARE(includes.count(), 1);
- QCOMPARE(includes.first().url, KUrl(QDir::currentPath() + "/" + f2.fileName()));
-}
-TestFile::~TestFile() {
- if (m_topContext) {
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
- KDevelop::DUChain::self()->removeDocumentChain(m_topContext.data());
- }
-}
-void TestFile::parse(KDevelop::TopDUContext::Features features) {
- KDevelop::DUChain::self()->updateContextForUrl(KDevelop::IndexedString(m_file.fileName()), features, this);
-}
-void TestFile::waitForParsed() {
- QTime t;
- t.start();
- while (!m_ready) {
- Q_ASSERT(t.elapsed() < 60000);
- QTest::qWait(10);
- }
-}
-
-#include "moc_includemanagertest.cpp"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h (nonexistent)
@@ -1,94 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Niko Sams <niko.sams@gmail.com>
-
- 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.
-*/
-
-
-#ifndef INCLUDEMANAGERTEST_H
-#define INCLUDEMANAGERTEST_H
-
-#include <QObject>
-#include <language/duchain/topducontext.h>
-#include <QTemporaryFile>
-
-namespace KDevelop {
- class TestCore;
-}
-class IncludeManagerTest : public QObject
-{
- Q_OBJECT
-
-public:
- virtual ~IncludeManagerTest() {}
-private slots:
- void init();
- void cleanup();
-
- void testUsed();
- void testUnused();
- void testIndirectUsed();
-
-private:
- KDevelop::TestCore* m_core;
-};
-
-class TestFile : public QObject
-{
- Q_OBJECT
-public:
- TestFile(QByteArray contents, const QString &fileName)
- : m_file(fileName), m_ready(false)
- {
- m_file.open();
- m_file.write(contents);
- m_file.close();
- }
-
- ~TestFile();
-
-
- void parse(KDevelop::TopDUContext::Features features);
-
- void waitForParsed();
-
- QString fileName()
- {
- return m_file.fileName();
- }
-
- KDevelop::ReferencedTopDUContext topContext()
- {
- waitForParsed();
- return m_topContext;
- }
-
-public slots:
- void updateReady(KDevelop::IndexedString url, KDevelop::ReferencedTopDUContext topContext)
- {
- Q_ASSERT(url.str() == m_file.fileName());
- m_ready = true;
- m_topContext = topContext;
- }
-
-private:
- QTemporaryFile m_file;
- bool m_ready;
- KDevelop::ReferencedTopDUContext m_topContext;
-};
-
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/tests/includemanagertest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/CMakeLists.txt (nonexistent)
@@ -1,32 +0,0 @@
-project(includemanager)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}
- ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules
-)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDE4_INCLUDES}
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-#add_definitions(-DKDE_DEFAULT_DEBUG_AREA=)
-
-set(includemanager_SRCS
- includemanagerplugin.cpp
- includemanager.cpp
-)
-
-kde4_add_plugin(kdevincludemanagerplugin ${includemanager_SRCS})
-target_link_libraries(kdevincludemanagerplugin ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_LANGUAGE_LIBRARIES})
-
-install(TARGETS kdevincludemanagerplugin DESTINATION ${PLUGIN_INSTALL_DIR})
-
-install(FILES kdevincludemanager.desktop DESTINATION ${SERVICES_INSTALL_DIR})
-
-add_subdirectory(tests)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/kdevincludemanager.desktop (nonexistent)
@@ -1,68 +0,0 @@
-[Desktop Entry]
-Type=Service
-Comment=This plugin helps you to remove unneeded include directives
-Comment[bs]=Ovaj dodatak vam pomaže da uklonite nepotrebne trenutno uključene direktive.
-Comment[ca]=Aquest connector us ajuda a eliminar les directives d'inclusió no necessàries
-Comment[ca@valencia]=Aquest connector vos ajuda a eliminar les directives d'inclusió no necessàries
-Comment[de]=Diese Modul hilft beim Entfernen unnötiger Include-Anweisungen
-Comment[en_GB]=This plugin helps you to remove unneeded include directives
-Comment[es]=Este complemento le ayuda a eliminar directivas include no necesarias
-Comment[et]=See plugin aitab eemaldada ebavajalikud kaasamisdirektiivid
-Comment[fr]=Ce module externe vous aide à supprimer des directives d'inclusion non nécessaires
-Comment[gl]=Este complemento axúdao a retirar directivas de inclusión innecesarias.
-Comment[it]=Questa estensione ti aiuta a rimuovere le direttive include non necessarie
-Comment[nl]=Deze plugin helpt u met het verwijderen van onnodige include directives
-Comment[pl]=Wtyczka ta pomaga tobie usunąć niepotrzebne dyrektywy plików dołączanych
-Comment[pt]=Este 'plugin' ajuda-o a remover as directivas de inclusão desnecessárias
-Comment[pt_BR]=Este plugin ajuda-o a remover as diretivas de inclusão desnecessárias
-Comment[sv]=Insticksprogrammet hjälper till att ta bort onödiga inkluderingsdirektivInkludera kommentarer
-Comment[uk]=За допомогою цього додатка ви зможете вилучити непотрібні команди include
-Comment[x-test]=xxThis plugin helps you to remove unneeded include directivesxx
-Name=Include Manager
-Name[bs]=Menadžer uključivanja.
-Name[ca]=Gestor d'inclusió
-Name[ca@valencia]=Gestor d'inclusió
-Name[de]=Include-Verwaltung
-Name[en_GB]=Include Manager
-Name[es]=Gestor de inclusiones
-Name[et]=Päisehaldur
-Name[fr]=Gestionnaire d'inclusions
-Name[gl]=Xestor de inclusións
-Name[it]=Include Manager
-Name[nl]=Include-beheer
-Name[pl]=Menadżer dołączania
-Name[pt]=Gestor de Inclusões
-Name[pt_BR]=Gerenciador de inclusões
-Name[sk]=Správca rozšírení
-Name[sv]=Inkluderingshanterare
-Name[uk]=Керування включеннями
-Name[x-test]=xxInclude Managerxx
-GenericName=Include Manager
-GenericName[bs]=Menadžer uključivanja.
-GenericName[ca]=Gestor d'inclusió
-GenericName[ca@valencia]=Gestor d'inclusió
-GenericName[de]=Include-Verwaltung
-GenericName[en_GB]=Include Manager
-GenericName[es]=Gestor de inclusiones
-GenericName[et]=Päisehaldur
-GenericName[fr]=Gestionnaire d'inclusions
-GenericName[gl]=Xestor de inclusións
-GenericName[it]=Gestore Include
-GenericName[nl]=Include-beheer
-GenericName[pl]=Menadżer dołączania
-GenericName[pt]=Gestor de Inclusões
-GenericName[pt_BR]=Gerenciador de inclusões
-GenericName[sk]=Správca rozšírení
-GenericName[sv]=Inkluderingshanterare
-GenericName[uk]=Керування включеннями
-GenericName[x-test]=xxInclude Managerxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevincludemanagerplugin
-X-KDE-PluginInfo-Name=kdevincludemanagerplugin
-X-KDE-PluginInfo-Author=Aleix Pol
-X-KDE-PluginInfo-Email=aleixpol@kde.org
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=11
-X-KDevelop-Category=Global
-X-KDevelop-Mode=NoGUI
-X-KDevelop-LoadMode=AlwaysOn
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.kdev4 (nonexistent)
@@ -1,3 +0,0 @@
-[Project]
-Manager=KDevCMakeManager
-Name=includemanager
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.cpp (nonexistent)
@@ -1,88 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Aleix Pol <aleixpol@kde.org>
-
- 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.
-*/
-
-#include "includemanager.h"
-
-#include <language/duchain/use.h>
-#include <language/duchain/ducontext.h>
-#include <language/duchain/declaration.h>
-#include <interfaces/idocument.h>
-#include <language/duchain/duchain.h>
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <language/duchain/duchainlock.h>
-
-using namespace KDevelop;
-
-QList<const Use*> usesForCtx(const DUContext* ctx)
-{
- QList<const Use*> ret;
- for(int i=0; i<ctx->usesCount(); ++i) {
- ret += &ctx->uses()[i];
- }
-
- foreach(const DUContext* child, ctx->childContexts()) {
- ret += usesForCtx(child);
- }
-
- return ret;
-}
-QList<IncludeProblemItem> IncludeManager::includes(const KDevelop::ReferencedTopDUContext& top)
-{
- DUChainReadLocker lock(DUChain::lock());
- QVector< DUContext::Import > imported=top->importedParentContexts();
- if(imported.isEmpty())
- return QList<IncludeProblemItem>();
-
- IndexedDUContext ctx(imported[0].indexedContext());
- QSet<Declaration*> decls;
-
- IndexedTopDUContext topctx(ctx.topContextIndex());
-
- QList<const Use*> uses=usesForCtx(ctx.data());
- Q_FOREACH(const Use* use, uses) {
- Declaration* decl=use->usedDeclaration(topctx.data());
-
- if(decl && decl->context()!=ctx.data()) //let's just add the ones that are not declared in the same file
- decls.insert(decl);
- }
-
- QList<IncludeProblemItem> ret;
-
- imported.remove(0);
- qDebug() << "hoooooooow" << imported.size();
- foreach(const DUContext::Import& import, imported) {
- IndexedDUContext ctx = import.indexedContext();
-
- Declaration* which=0;
- foreach(Declaration* d, decls) {
- if(ctx.data()->imports(d->context())) {
- which=d;
- }
- }
-
- qDebug() << "fiiiiiirst" << validInclude << ctx.data()->url().toUrl() << (which ? which->toString(): "<null>");
- if(!which) {
- IndexedString inc=ctx.context()->url();
- ret << IncludeProblemItem(inc.toUrl(), import.position);
- }
- }
- return ret;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.h (nonexistent)
@@ -1,51 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Aleix Pol <aleixpol@kde.org>
-
- 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.
-*/
-
-
-#ifndef INCLUDEMANAGER_H
-#define INCLUDEMANAGER_H
-
-#include <QList>
-#include <QPair>
-
-#include <KUrl>
-#include <language/editor/cursorinrevision.h>
-
-namespace KDevelop {
- class ReferencedTopDUContext;
- class IndexedDUContext;
- class Declaration;
-}
-
-struct IncludeProblemItem
-{
- IncludeProblemItem(const KUrl& url, KDevelop::CursorInRevision cursor) : url(url), cursor(cursor) {}
- KUrl url;
-
- KDevelop::CursorInRevision cursor;
-};
-
-class IncludeManager
-{
-public:
- static QList<IncludeProblemItem> includes(const KDevelop::ReferencedTopDUContext &top);
- static bool canReach(const KDevelop::IndexedDUContext& includer, const KDevelop::Declaration* included);
-};
-
-#endif // INCLUDEMANAGER_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.cpp (nonexistent)
@@ -1,153 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Aleix Pol <aleixpol@kde.org>
-
- 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.
-*/
-
-#include "includemanagerplugin.h"
-#include <kpluginfactory.h>
-#include <QDebug>
-#include <QPalette>
-#include <QTreeView>
-#include <KAboutData>
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-#include <kaction.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/ilanguagecontroller.h>
-#include <interfaces/ilanguage.h>
-#include <language/interfaces/ilanguagesupport.h>
-#include <language/backgroundparser/backgroundparser.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/duchain.h>
-#include <language/backgroundparser/parsejob.h>
-#include "includemanager.h"
-#include <QHeaderView>
-
-K_PLUGIN_FACTORY(IncludeManagerFactory, registerPlugin<IncludeManagerPlugin>(); )
-K_EXPORT_PLUGIN(IncludeManagerFactory(
- KAboutData("kdevvcsprojectintegration","kdevvcsprojectintegration",
- ki18n("Include Manager"), "0.1", ki18n("Helps to manage include directories"), KAboutData::License_GPL)))
-
-using namespace KDevelop;
-
-class KDevIncludeManagerFactory: public KDevelop::IToolViewFactory
-{
- public:
- KDevIncludeManagerFactory( IncludeManagerPlugin *plugin ): mplugin( plugin ) {}
-
- virtual QWidget* create( QWidget *parent = 0 )
- {
- QTreeView* view=new QTreeView(parent);
-
- QAction* reloadAction = new QAction(KIcon("reload"), i18n("Reload"), view);
- QObject::connect(reloadAction, SIGNAL(triggered()), mplugin, SLOT(reloadAll()));
-
- view->setModel(mplugin->model());
- view->setEditTriggers(QAbstractItemView::NoEditTriggers);
- view->setSortingEnabled(true);
- view->addAction(reloadAction);
- QObject::connect(view, SIGNAL(activated(QModelIndex)), mplugin, SLOT(activated(QModelIndex)));
- return view;
- }
-
- virtual Qt::DockWidgetArea defaultPosition() { return Qt::LeftDockWidgetArea; }
-
- virtual QString id() const { return "org.kdevelop.IncludeManagerPlugin"; }
-
- private:
- IncludeManagerPlugin *mplugin;
-};
-
-IncludeManagerPlugin::IncludeManagerPlugin(QObject* parent, const QVariantList&)
- : KDevelop::IPlugin(IncludeManagerFactory::componentData(), parent)
-{
- m_model=new QStandardItemModel(this);
- m_model->setHeaderData(0, Qt::Vertical, i18n("File"), Qt::DisplayRole);
- core()->uiController()->addToolView(i18n("Include Manager"), new KDevIncludeManagerFactory(this));
- connect(core()->languageController()->backgroundParser(), SIGNAL(parseJobFinished(KDevelop::ParseJob* )),
- this, SLOT(parsingFinished(KDevelop::ParseJob* )));
-}
-
-void IncludeManagerPlugin::parsingFinished(KDevelop::ParseJob* job)
-{
- KUrl url=job->document().toUrl();
- QStandardItem* root=0;
-
- ReferencedTopDUContext top;
- {
- DUChainReadLocker lock(DUChain::lock());
- top=job->duChain();
- }
-
- if(!top)
- top=core()->languageController()->languagesForUrl(url).first()->languageSupport()->standardContext(url);
-
- QList< QStandardItem* > items = m_model->findItems(url.prettyUrl());
- if(items.isEmpty()) {
- root=new QStandardItem(url.prettyUrl());
- root->setData(QUrl(url));
- m_model->appendRow(root);
- } else {
- root = items.first();
- root->removeRows(0, root->rowCount());
- }
-
- if(!top || top->features()<TopDUContext::AllDeclarationsContextsAndUses) {
- root->setIcon(KIcon("unknown"));
- root->setEnabled(true);
- return;
- }
-
- if(top) {
- QList<IncludeProblemItem> includes = IncludeManager::includes(top);
- Q_FOREACH(const IncludeProblemItem &include, includes) {
- QStandardItem* incItem=new QStandardItem(include.url.prettyUrl());
- incItem->setIcon(KIcon("dialog-error"));
- root->appendRow(incItem);
-
- DUChainWriteLocker lock(DUChain::lock());
- ProblemPointer p(new Problem);
- p->setRange(RangeInRevision(include.cursor, include.cursor));
- p->setFinalLocation(DocumentRange(IndexedString(url), p->range().castToSimpleRange()));
- p->setDescription(i18n("Unused import '%1'", include.url.prettyUrl()));
- p->setSeverity(KDevelop::ProblemData::Hint);
- p->setSource(KDevelop::ProblemData::SemanticAnalysis); //?
- top->addProblem(p);
- }
- }
-
- bool hasproblems = root->rowCount()>0;
- root->setEnabled(hasproblems);
- root->setIcon(hasproblems ? KIcon("dialog-error") : KIcon("dialog-ok"));
-}
-
-void IncludeManagerPlugin::activated(const QModelIndex& idx)
-{
- QUrl docUrl=idx.data().toUrl();
- core()->documentController()->openDocument(docUrl);
-}
-
-void IncludeManagerPlugin::reloadAll()
-{
- for(int i=0; i<m_model->rowCount(); i++) {
- QUrl url = m_model->item(i)->data().toUrl();
-
-// TopDUContext* chain = DUChain::self()->chainForDocument(url);
-// if(!chain || chain->features()!=KDevelop::TopDUContext::AllDeclarationsContextsAndUses)
- core()->languageController()->backgroundParser()->addDocument(url, KDevelop::TopDUContext::AllDeclarationsContextsAndUses, 10);
- }
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager/includemanagerplugin.h (nonexistent)
@@ -1,55 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2010 Aleix Pol <aleixpol@kde.org>
-
- 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.
-*/
-
-#ifndef INCLUDEMANAGERPLUGIN_H
-#define INCLUDEMANAGERPLUGIN_H
-
-#include <interfaces/iplugin.h>
-#include <QVariant>
-#include <QStandardItemModel>
-
-class QModelIndex;
-class KUrl;
-class KJob;
-
-namespace KDevelop
-{
- class IProject;
- class IDocument;
- class ParseJob;
-}
-
-class IncludeManagerPlugin : public KDevelop::IPlugin
-{
- Q_OBJECT
- public:
- IncludeManagerPlugin(QObject *parent, const QVariantList & args);
-
- QAbstractItemModel* model() const { return m_model; }
-
- public slots:
- void parsingFinished(KDevelop::ParseJob*);
- void activated(const QModelIndex& idx);
- void reloadAll();
-
- private:
- QStandardItemModel* m_model;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/includemanager (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/includemanager (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/includemanager
___________________________________________________________________
Deleted: svn:ignore
## -1 +0,0 ##
-.kdev4
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.rc (nonexistent)
@@ -1,27 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<gui name="uistrings" version="1">
-<MenuBar>
- <Menu name="edit">
- <Action name="edit_undo" group="edit_undo_merge" />
- <Action name="edit_redo" group="edit_undo_merge" />
- <Separator group="edit_undo_merge" />
- <Action name="edit_cut" group="edit_paste_merge" />
- <Action name="edit_copy" group="edit_paste_merge" />
- <Action name="edit_paste" group="edit_paste_merge" />
- <Action name="copy_as" group="edit_paste_merge" />
- <Action name="insert" group="edit_paste_merge" />
- <Separator group="edit_paste_merge" />
- <Action name="edit_select_all" group="edit_select_merge" />
- <Action name="edit_deselect" group="edit_select_merge" />
- <Action name="edit_select" group="edit_select_merge" />
- <Separator group="edit_select_merge" />
- <Action name="edit_find" group="edit_find_merge" />
- <Action name="edit_find_next" group="edit_find_merge" />
- <Action name="edit_find_prev" group="edit_find_merge" />
- <Action name="edit_replace" group="edit_find_merge" />
- <Separator group="edit_find_merge" />
- <Action name="set_overwrite" group="edit_select_merge" />
- <Separator group="edit_find_merge" />
- <Action name="goto_offset" group="edit_find_merge" />
- </Menu>
-</gui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.cpp (nonexistent)
@@ -1,60 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringsplugin.h"
-
-// plugin
-#include "uistringscompletionmodel.h"
-#include "uistringstoolviewfactory.h"
-// KDev
-#include <interfaces/icore.h>
-#include <interfaces/iuicontroller.h>
-#include <interfaces/ipartcontroller.h>
-#include <language/codecompletion/codecompletion.h>
-// KDE
-#include <KAboutData>
-#include <KPluginFactory>
-
-
-K_PLUGIN_FACTORY(UiStringsPluginFactory, registerPlugin<KDevelop::UiStringsPlugin>(); )
-K_EXPORT_PLUGIN( UiStringsPluginFactory( KAboutData( "kdevuistrings","kdevuistrings", ki18n("UI Strings"), "0.1", ki18n("Lists UI Strings"), KAboutData::License_GPL)))
-
-namespace KDevelop
-{
-
-UiStringsPlugin::UiStringsPlugin( QObject* parent, const QVariantList& args )
- : IPlugin( UiStringsPluginFactory::componentData(), parent ),
- mUiStringsCompletionModel( new UiStringsCompletionModel(this) )
-{
- Q_UNUSED(args)
-
- UiStringsToolViewFactory* toolViewFactory = new UiStringsToolViewFactory();
- core()->uiController()->addToolView( i18n("UI Strings"), toolViewFactory );
-
- new KDevelop::CodeCompletion( this, mUiStringsCompletionModel, QString() );
-}
-
-UiStringsPlugin::~UiStringsPlugin()
-{
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/CMakeLists.txt (nonexistent)
@@ -1,37 +0,0 @@
-project( uistrings )
-
-set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${uistrings_SOURCE_DIR}/cmake/modules )
-
-find_package(KDE4 4.3.0 REQUIRED)
-find_package(KDevPlatform 0.9.98 REQUIRED)
-
-include_directories( ${KDE4_INCLUDES} ${KDEVPLATFORM_INCLUDE_DIR} )
-include_directories( ${uistrings_SOURCE_DIR} ${uistrings_BINARY_DIR} )
-
-# add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9038 )
-
-SET( kdevuistrings_PART_SRCS
- uistringscompletionmodel.cpp
- i18nusescollector.cpp
- uistringsmodel.cpp
- uistringstool.cpp
- uistringstoolviewfactory.cpp
- uistringstoolviewwidget.cpp
- uistringsplugin.cpp
-)
-
-kde4_add_plugin( kdevuistrings ${kdevuistrings_PART_SRCS} )
-
-TARGET_LINK_LIBRARIES( kdevuistrings
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
-# ${KDEVPLATFORM_SUBLIME_LIBRARIES}
-# ${KDEVPLATFORM_SHELL_LIBRARIES}
- ${KDE4_KDEUI_LIBS}
-)
-
-install(TARGETS kdevuistrings DESTINATION ${PLUGIN_INSTALL_DIR})
-
-
-install(FILES kdevuistrings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install(FILES kdevuistrings.rc DESTINATION ${DATA_INSTALL_DIR}/kdevuistrings )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.h (nonexistent)
@@ -1,65 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSTOOL_H
-#define UISTRINGSTOOL_H
-
-// KDev
-#include <language/duchain/topducontext.h>
-// Qt
-#include <QtCore/QObject>
-#include <QtCore/QStringList>
-
-
-namespace KDevelop
-{
-
-class UiStringsTool: public QObject
-{
- Q_OBJECT
-
- public:
- explicit UiStringsTool( QObject* parent = 0 );
-
- virtual ~UiStringsTool();
-
- public:
- int stringCount() const;
- const QString& string( int index ) const;
- void append( const QString& string );
-
- public Q_SLOTS:
- void update();
-
- Q_SIGNALS:
- void stringsUpdated();
-
- protected:
- QStringList mStrings;
-};
-
-inline int UiStringsTool::stringCount() const { return mStrings.count(); }
-inline const QString& UiStringsTool::string( int index ) const { return mStrings.at(index); }
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsplugin.h (nonexistent)
@@ -1,60 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSPLUGIN_H
-#define UISTRINGSPLUGIN_H
-
-// KDev
-#include <interfaces/iplugin.h>
-// Qt
-#include <QtCore/QVariantList>
-
-namespace KTextEditor {
-class View;
-class Document;
-}
-namespace KParts {
-class Part;
-}
-
-
-namespace KDevelop
-{
-class UiStringsCompletionModel;
-
-
-class UiStringsPlugin: public IPlugin
-{
- Q_OBJECT
-
- public:
- UiStringsPlugin( QObject* parent, const QVariantList& args = QVariantList() );
-
- virtual ~UiStringsPlugin();
-
- protected:
- UiStringsCompletionModel* mUiStringsCompletionModel;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.cpp (nonexistent)
@@ -1,69 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringscompletionmodel.h"
-
-// plugin
-#include "uistringstool.h"
-
-
-namespace KDevelop
-{
-
-UiStringsCompletionModel::UiStringsCompletionModel( QObject* parent )
- : KTextEditor::CodeCompletionModel( parent )
-{
- setHasGroups( false );
-}
-
-QVariant UiStringsCompletionModel::data( const QModelIndex& index, int role ) const
-{
- const int row = index.row();
-
- if( !index.isValid() || row < 0 || row >= rowCount() )
- return QVariant();
-
- return QVariant();//m_snippets.at( index.row() )->data( index, role, 0);
-}
-
-void UiStringsCompletionModel::executeCompletionItem( KTextEditor::Document* document, const KTextEditor::Range& w, int row ) const
-{
-// m_snippets.at( row )->execute( document, w );
-}
-
-void UiStringsCompletionModel::completionInvoked( KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType)
-{
- Q_UNUSED( range );
- Q_UNUSED( invocationType );
- initData( view );
-}
-
-void UiStringsCompletionModel::initData( KTextEditor::View* view )
-{
- // find out if we are cpp, if we are in UI string
- reset();
- setRowCount( 0 );
-}
-
-UiStringsCompletionModel::~UiStringsCompletionModel() {}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.h (nonexistent)
@@ -1,54 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSTOOLVIEWFACTORY_H
-#define UISTRINGSTOOLVIEWFACTORY_H
-
-// KDev
-#include <interfaces/iuicontroller.h>
-
-
-namespace KDevelop
-{
-class UiStringsTool;
-
-
-class UiStringsToolViewFactory : public IToolViewFactory
-{
- public:
- UiStringsToolViewFactory();
-
- virtual ~UiStringsToolViewFactory();
-
- public: // KDevelop::IToolViewFactory API
- virtual QWidget* create( QWidget* parent );
- virtual Qt::DockWidgetArea defaultPosition();
-
- virtual QString id() const;
-
- protected:
- UiStringsTool* mTool;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.h (nonexistent)
@@ -1,54 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef I18NUSESCOLLECTOR_H
-#define I18NUSESCOLLECTOR_H
-
-// KDev
-#include <language/duchain/navigation/usescollector.h>
-
-
-namespace KDevelop
-{
-class UiStringsTool;
-
-
-class I18nUsesCollector : public UsesCollector
-{
- Q_OBJECT
-
- public:
- explicit I18nUsesCollector( UiStringsTool* tool, IndexedDeclaration declaration );
-
- virtual ~I18nUsesCollector();
-
- private: // UsesCollector API
- virtual void processUses( ReferencedTopDUContext topContext );
- virtual void progress( uint processed, uint total );
-
- protected:
- UiStringsTool* mTool;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstool.cpp (nonexistent)
@@ -1,74 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringstool.h"
-
-// plugin
-#include "i18nusescollector.h"
-// KDev
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/persistentsymboltable.h>
-
-
-namespace KDevelop
-{
-
-UiStringsTool::UiStringsTool( QObject* parent )
- : QObject( parent )
-{
-}
-
-void UiStringsTool::update()
-{
- mStrings.clear();
-
- DUChainReadLocker lock( DUChain::lock() );
-
- QualifiedIdentifier qualifiedIdentifier( QString::fromLatin1("i18n") );
- PersistentSymbolTable::Declarations declarations =
- PersistentSymbolTable::self().getDeclarations( qualifiedIdentifier );
-
- for( PersistentSymbolTable::Declarations::Iterator it = declarations.iterator(); it; ++it )
- {
- Declaration* declaration = it->declaration();
-
- UsesCollector* usesCollector = new I18nUsesCollector( this, declaration );
- usesCollector->setCollectDefinitions( false );
-// connect( usesCollector, SIGNAL(processUsesSignal(KDevelop::ReferencedTopDUContext)),
-// SLOT(onProcessUsesSignal(KDevelop::ReferencedTopDUContext)) );
- usesCollector->startCollecting();
- }
-}
-
-void UiStringsTool::append( const QString& string )
-{
-kDebug()<<string;
- mStrings.append( string );
- emit stringsUpdated();
-}
-
-UiStringsTool::~UiStringsTool()
-{
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.cpp (nonexistent)
@@ -1,96 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringstoolviewwidget.h"
-
-// plugin
-#include "uistringstool.h"
-#include "uistringsmodel.h"
-// KDE
-#include <KPushButton>
-#include <KGuiItem>
-#include <KLocale>
-// Qt
-#include <QtGui/QVBoxLayout>
-#include <QtGui/QHBoxLayout>
-#include <QtGui/QTreeView>
-#include <QtGui/QHeaderView>
-
-
-namespace KDevelop
-{
-
-UiStringsToolViewWidget::UiStringsToolViewWidget( UiStringsTool* tool, QWidget* parent )
- : QWidget( parent ),
- mTool( tool )
-{
- QVBoxLayout* layout = new QVBoxLayout( this );
- layout->setMargin( 0 );
-
- // update
- QHBoxLayout* updateLayout = new QHBoxLayout();
- updateLayout->setMargin( 0 );
-
- updateLayout->addStretch();
- const KGuiItem updateGuiItem( i18nc("@action:button","&Extract"), "document-export",
- i18nc("@info:tooltip","Finds the UI strings contained in the project and lists them in the view below."),
- i18nc("@info:whatsthis",
- "If you press the <interface>Extract</interface> button, "
- "the project is searched for all strings used in the UI. "
- "This strings found will be listed in the view below.") );
- KPushButton* mUpdateButton = new KPushButton( updateGuiItem, this );
-// mUpdateButton->setEnabled( mTool->isApplyable() );
- connect( mUpdateButton, SIGNAL(clicked(bool)), mTool, SLOT(update()) );
- updateLayout->addWidget( mUpdateButton );
-
- layout->addLayout( updateLayout );
-
- // table
- UiStringsModel* mUiStringsModel = new UiStringsModel( mTool, this );
-
- QTreeView* mStringView = new QTreeView( this );
-
- mStringView->setObjectName( "StringTable" );
- mStringView->setRootIsDecorated( false );
- mStringView->setItemsExpandable( false );
- mStringView->setUniformRowHeights( true );
- mStringView->setAllColumnsShowFocus( true );
- mStringView->setSelectionMode( QAbstractItemView::ExtendedSelection );
- mStringView->setSortingEnabled( true );
- mStringView->installEventFilter( this );
- QHeaderView* header = mStringView->header();
- header->setResizeMode( QHeaderView::ResizeToContents );
- mStringView->setModel( mUiStringsModel );
- mStringView->sortByColumn( UiStringsModel::StringColumnId, Qt::AscendingOrder );
-// connect( mStringView, SIGNAL(doubleClicked( const QModelIndex& )),
-// SLOT(onStringDoubleClicked( const QModelIndex& )) );
-// connect( mStringView->selectionModel(),
-// SIGNAL(selectionChanged( const QItemSelection &, const QItemSelection & )),
-// SLOT(onStringSelectionChanged()) );
- layout->addWidget( mStringView );
-}
-
-UiStringsToolViewWidget::~UiStringsToolViewWidget()
-{
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewwidget.h (nonexistent)
@@ -1,50 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSTOOLVIEWWIDGET_H
-#define UISTRINGSTOOLVIEWWIDGET_H
-
-// Qt
-#include <QtGui/QWidget>
-
-
-namespace KDevelop
-{
-class UiStringsTool;
-
-
-class UiStringsToolViewWidget : public QWidget
-{
- Q_OBJECT
-
- public:
- explicit UiStringsToolViewWidget( UiStringsTool* tool, QWidget* parent = 0 );
-
- virtual ~UiStringsToolViewWidget();
-
- protected:
- UiStringsTool* mTool;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/kdevuistrings.desktop (nonexistent)
@@ -1,70 +0,0 @@
-[Desktop Entry]
-Type=Service
-
-Name=UI Strings tool
-Name[bs]=Opcije UI stringa(niz znakova)
-Name[ca]=Eina de cadenes d'IU
-Name[ca@valencia]=Eina de cadenes d'IU
-Name[de]=Textwerkzeug für grafische Oberflächen
-Name[en_GB]=UI Strings tool
-Name[es]=Herramienta de cadenas de la interfaz de usuario
-Name[et]=Kasutajaliidese stringide tööriist
-Name[fr]=Outil de chaînes de caractères d'interfaces graphiques
-Name[gl]=Ferramenta de cadeas de interface gráfica
-Name[it]=Strumento Stringhe interfaccia
-Name[nl]=UI Strings hulpmiddel
-Name[pl]=Narzędzie ciągów znaków interfejsu użytkownika
-Name[pt]=Ferramenta de textos da GUI
-Name[pt_BR]=Ferramenta de textos da GUI
-Name[sv]=Verktyg för strängar i grafiskt gränssnitt
-Name[uk]=Інструмент рядків графічного інтерфейсу
-Name[x-test]=xxUI Strings toolxx
-GenericName=UI Strings tool
-GenericName[bs]=Opcije UI stringa(niz znakova)
-GenericName[ca]=Eina de cadenes d'IU
-GenericName[ca@valencia]=Eina de cadenes d'IU
-GenericName[de]=Textwerkzeug für grafische Oberflächen
-GenericName[en_GB]=UI Strings tool
-GenericName[es]=Herramienta de cadenas de la interfaz de usuario
-GenericName[et]=Kasutajaliidese stringide tööriist
-GenericName[fr]=Outil de chaînes de caractères d'interfaces graphiques
-GenericName[gl]=Ferramenta de cadeas de interface gráfica
-GenericName[it]=Strumento Stringhe interfaccia
-GenericName[nl]=UI Strings hulpmiddel
-GenericName[pl]=Narzędzie ciągów znaków interfejsu użytkownika
-GenericName[pt]=Ferramenta de textos da GUI
-GenericName[pt_BR]=Ferramenta de textos da GUI
-GenericName[sv]=Verktyg för strängar i grafiskt gränssnitt
-GenericName[uk]=Інструмент рядків графічного інтерфейсу
-GenericName[x-test]=xxUI Strings toolxx
-Comment=Enables central handling of strings in the UI
-Comment[bs]=Omogućava centralno rukovanje strigovima u UI-u
-Comment[ca]=Habilita la gestió central de cadenes a la IU
-Comment[ca@valencia]=Habilita la gestió central de cadenes a la IU
-Comment[de]=Ermöglicht die zentrale Bearbeitung von Texten in der grafischen Benutzeroberfläche
-Comment[en_GB]=Enables central handling of strings in the UI
-Comment[es]=Habilita el manejo central de cadenas en la interfaz de usuario
-Comment[et]=Kasutajaliidese stringide keskne haldamine
-Comment[fr]=Active la gestion centralisée de chaînes de caractères dans l'interface graphique
-Comment[gl]=Permite xestionar de maneira centralizada as cadeas das interfaces gráficas.
-Comment[it]=Abilita la gestione centralizzata delle stringhe nell'interfaccia utente
-Comment[nl]=Maakt centraal beheer van tekst in de UI mogelijk
-Comment[pl]=Włącza centralną obsługę ciągów znaków w interfejsie użytkownika
-Comment[pt]=Permite o tratamento centralizado de textos na interface gráfica
-Comment[pt_BR]=Permite o tratamento centralizado de textos na interface gráfica
-Comment[sv]=Aktiverar central hantering av strängar i det grafiska gränssnittet
-Comment[uk]=Уможливлює загальну обробку рядків у графічному інтерфейсі
-Comment[x-test]=xxEnables central handling of strings in the UIxx
-Icon=text-plain
-ServiceTypes=KDevelop/Plugin
-
-X-KDE-Library=kdevuistrings
-X-KDE-PluginInfo-Name=kdevuistrings
-X-KDE-PluginInfo-Author=Friedrich W. H. Kossebau
-X-KDE-PluginInfo-Email=kossebau@kde.org
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=9
-X-KDevelop-Category=Global
-# X-KDevelop-SupportedMimeTypes=audio/x-wav;
-X-KDevelop-Mode=GUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/i18nusescollector.cpp (nonexistent)
@@ -1,93 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "i18nusescollector.h"
-
-// plugin
-#include "uistringstool.h"
-// KDev
-#include <language/duchain/declaration.h>
-#include <language/codegen/coderepresentation.h>
-#include <interfaces/icore.h>
-#include <interfaces/iprojectcontroller.h>
-#include <interfaces/iproject.h>
-
-
-namespace KDevelop
-{
-
-I18nUsesCollector::I18nUsesCollector( UiStringsTool* tool, IndexedDeclaration declaration )
- : UsesCollector( declaration ),
- mTool( tool )
-{
-}
-
-void I18nUsesCollector::processUses( ReferencedTopDUContext topContext )
-{
-// kDebug()<<topContext->
-// mTool->append( topContext->url().str() );
-}
-
-void I18nUsesCollector::progress( uint processed, uint total )
-{
- const bool isDone = ( processed == total );
- if( isDone )
- {
- const QList<IProject*> projects = ICore::self()->projectController()->projects();
-
- QMap<IndexedString, QList<SimpleRange> > uses = declaration().data()->uses();
- QMap<IndexedString, QList<SimpleRange> >::ConstIterator it = uses.constBegin();
- QMap<IndexedString, QList<SimpleRange> >::ConstIterator end = uses.constEnd();
- for( ; it != end; ++it )
- {
- const IndexedString& string = it.key();
- bool isInProject = false;
- foreach( IProject* project, projects )
- {
- const QSet<IndexedString> fileSet = project->fileSet();
- if( fileSet.contains(string) )
- {
- isInProject = true;
- break;
- }
- }
- if( ! isInProject )
- continue;
-
- const QString fileName = string.toUrl().fileName();
- CodeRepresentation::Ptr codeRepresentation = createCodeRepresentation( string );
- const QList<SimpleRange>& ranges = it.value();
- foreach( const SimpleRange& range, ranges )
- {
- KTextEditor::Range textRange = range.textRange();
- const int endColumn = textRange.end().column();
- textRange.end().setColumn( endColumn+10 );
- textRange.start().setColumn( endColumn+1 );
- mTool->append( fileName + ':'+ codeRepresentation->rangeText(textRange) );
- }
- }
- }
-}
-
-I18nUsesCollector::~I18nUsesCollector() {}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/cmake/modules/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringscompletionmodel.h (nonexistent)
@@ -1,55 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSCOMPLETIONMODEL
-#define UISTRINGSCOMPLETIONMODEL
-
-// KDE
-#include <ktexteditor/codecompletionmodel.h>
-
-
-namespace KDevelop
-{
-
-class UiStringsCompletionModel : public KTextEditor::CodeCompletionModel
-{
- Q_OBJECT
-
- public:
- explicit UiStringsCompletionModel( QObject* parent );
-
- virtual ~UiStringsCompletionModel();
-
- public: // QAbstractItemModel API
- virtual QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
-
- public: // KTextEditor::CodeCompletionModel API
- virtual void completionInvoked( KTextEditor::View* view, const KTextEditor::Range& range, InvocationType invocationType);
- virtual void executeCompletionItem( KTextEditor::Document* document, const KTextEditor::Range& w, int row ) const;
-
- protected:
- void initData( KTextEditor::View* view );
-};
-
-}
-
-#endif
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringstoolviewfactory.cpp (nonexistent)
@@ -1,57 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringstoolviewfactory.h"
-
-// plugin
-#include "uistringstoolviewwidget.h"
-#include "uistringstool.h"
-// KDE
-#include <KIcon>
-
-
-namespace KDevelop
-{
-
-UiStringsToolViewFactory::UiStringsToolViewFactory()
- : IToolViewFactory(),
- mTool( new UiStringsTool() )
-{
-}
-
-QString UiStringsToolViewFactory::id() const { return QString::fromLatin1("org.kde.okteta."); }
-Qt::DockWidgetArea UiStringsToolViewFactory::defaultPosition() { return Qt::LeftDockWidgetArea; }
-
-QWidget* UiStringsToolViewFactory::create( QWidget* parent )
-{
- QWidget* widget = new UiStringsToolViewWidget( mTool, parent );
- widget->setWindowIcon( KIcon("text-plain") );
- return widget;
-}
-
-
-UiStringsToolViewFactory::~UiStringsToolViewFactory()
-{
- delete mTool;
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.h (nonexistent)
@@ -1,66 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#ifndef UISTRINGSMODEL_H
-#define UISTRINGSMODEL_H
-
-// Qt
-#include <QtCore/QAbstractTableModel>
-
-
-namespace KDevelop
-{
-class UiStringsTool;
-
-
-class UiStringsModel: public QAbstractTableModel
-{
- Q_OBJECT
-
- public:
- enum ColumnIds
- {
- StringColumnId = 0,
- NoOfColumnIds = 1 // TODO: what pattern is usually used to mark number of ids?
- };
-
- public:
- explicit UiStringsModel( UiStringsTool* tool, QObject* parent = 0 );
-
- virtual ~UiStringsModel();
-
- public: // QAbstractTableModel API
- virtual int rowCount( const QModelIndex& parent ) const;
- virtual int columnCount( const QModelIndex& parent ) const;
- virtual QVariant data( const QModelIndex& index, int role ) const;
- virtual QVariant headerData( int section, Qt::Orientation orientation, int role ) const;
-
- public Q_SLOTS:
- void update();
-
- protected:
- UiStringsTool* mTool;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/uistrings/uistringsmodel.cpp (nonexistent)
@@ -1,107 +0,0 @@
-/*
- This file is part of the KDevelop UIStrings module, part of the KDE project.
-
- Copyright 2010 Friedrich W. H. Kossebau <kossebau@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) version 3, or any
- later version accepted by the membership of KDE e.V. (or its
- successor approved by the membership of KDE e.V.), which shall
- act as a proxy defined in Section 6 of version 3 of the license.
-
- 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
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-#include "uistringsmodel.h"
-
-// plugin
-#include "uistringstool.h"
-// KDE
-#include <KLocale>
-
-
-namespace KDevelop
-{
-
-UiStringsModel::UiStringsModel( UiStringsTool* tool, QObject* parent )
- : QAbstractTableModel( parent ),
- mTool( tool )
-{
- connect( mTool, SIGNAL(stringsUpdated()), SLOT(update()) );
-}
-
-void UiStringsModel::update()
-{
- reset();
-}
-
-
-int UiStringsModel::rowCount( const QModelIndex& parent ) const
-{
-Q_UNUSED( parent )
- return mTool->stringCount();
-}
-
-int UiStringsModel::columnCount( const QModelIndex& parent ) const
-{
-Q_UNUSED( parent )
- return NoOfColumnIds;
-}
-
-QVariant UiStringsModel::data( const QModelIndex& index, int role ) const
-{
- QVariant result;
- if( role == Qt::DisplayRole
- || role == Qt::ToolTipRole )
- {
- const int stringIndex = index.row();
-
- if( 0 <= stringIndex && stringIndex < mTool->stringCount() )
- {
- const QString &string = mTool->string( stringIndex );
-
- const int column = index.column();
- switch( column )
- {
- case StringColumnId:
- {
- result = string;
- break;
- }
- default:
- ;
- }
- }
- }
-
- return result;
-}
-
-QVariant UiStringsModel::headerData( int section, Qt::Orientation orientation, int role ) const
-{
- QVariant result;
-
- if( role == Qt::DisplayRole )
- {
- const QString titel =
- section == StringColumnId ? i18nc("@title:column string extracted from the byte array", "String") :
- QString();
- result = titel;
- }
- else
- result = QAbstractTableModel::headerData( section, orientation, role );
-
- return result;
-}
-
-UiStringsModel::~UiStringsModel() {}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevsloc.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/CMakeLists.txt (nonexistent)
@@ -1,32 +0,0 @@
-project(sloc)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${sloc_SOURCE_DIR}/cmake/)
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-
-include_directories(
- ${QT_INCLUDES}
- ${KDE4_INCLUDES}
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR} )
-
-########### next target ###############
-
-set(kdevsloc_SRCS reportmodel.cpp reportwidget.cpp slocplugin.cpp clocparser.cpp)
-qt4_automoc(${kdevsloc_SRCS})
-kde4_add_plugin(kdevsloc ${kdevsloc_SRCS})
-target_link_libraries(kdevsloc
- ${QT_QTCORE_LIBRARY}
- ${QT_QTGUI_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDE4_KDEUI_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES})
-install(TARGETS kdevsloc DESTINATION ${PLUGIN_INSTALL_DIR})
-
-########### install files ###############
-
-install( FILES kdevsloc.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevsloc.rc DESTINATION ${DATA_INSTALL_DIR}/kdevsloc )
-install( PROGRAMS cloc-1.04.pl DESTINATION ${BIN_INSTALL_DIR} )
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.desktop (nonexistent)
@@ -1,71 +0,0 @@
-[Desktop Entry]
-Type=Service
-Icon=kdevelop
-Exec=blubb
-Comment=SLOC
-Comment[bs]=SLOC
-Comment[ca]=SLOC
-Comment[ca@valencia]=SLOC
-Comment[cs]=SLOC
-Comment[de]=SLOC
-Comment[el]=SLOC
-Comment[en_GB]=SLOC
-Comment[es]=SLOC
-Comment[et]=SLOC
-Comment[fr]=SLOC
-Comment[ga]=SLOC
-Comment[gl]=SLOC
-Comment[hne]=एसएलओसी
-Comment[hu]=SLOC
-Comment[it]=SLOC
-Comment[ja]=SLOC
-Comment[nds]=Bornkoderegen
-Comment[nl]=SLOC
-Comment[pa]=SLOC
-Comment[pl]=SLOC
-Comment[pt]=SLOC
-Comment[pt_BR]=SLOC
-Comment[si]=SLOC
-Comment[sk]=SLOC
-Comment[sv]=Antal källkodsrader
-Comment[tr]=SLOC
-Comment[ug]=SLOC
-Comment[uk]=SLOC
-Comment[x-test]=xxSLOCxx
-
-Name=SLOC report
-Name[bs]=SLOC izvještaj
-Name[ca]=Informe d'SLOC
-Name[ca@valencia]=Informe d'SLOC
-Name[cs]=Hlášení SLOC
-Name[de]=SLOC-Bericht
-Name[el]=Αναφορά SLOC
-Name[en_GB]=SLOC report
-Name[es]=Informe SLOC
-Name[et]=SLOC-i aruanne
-Name[fr]=Statistiques sur les lignes de code source (SLOC)
-Name[ga]=Tuairisc SLOC
-Name[gl]=Informe de SLOC
-Name[hu]=SLOC jelentés
-Name[it]=Resoconto SLOC
-Name[ja]=SLOC レポート
-Name[nds]=Bornregenbericht
-Name[nl]=SLOC-rapport
-Name[pa]=SLOC ਰਿਪੋਰਟ
-Name[pl]=Sprawozdanie SLOC
-Name[pt]=Relatório de SLOC's
-Name[pt_BR]=Relatório SLOC
-Name[sk]=Správa SLOC
-Name[sv]=Rapport av antal källkodsrader
-Name[tr]=SLOC bildirimi
-Name[uk]=Звіт SLOC
-Name[x-test]=xxSLOC reportxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevsloc
-X-KDE-PluginInfo-Name=kdevsloc
-X-KDE-PluginInfo-Author=Manuel Breugelmans
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-License=LGPL
-X-KDevelop-Version=7
-X-KDevelop-Category=Global
-X-KDevelop-Properties=GlobalFileManagement
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cloc-1.04.pl
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cloc-1.04.pl (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cloc-1.04.pl (nonexistent)
@@ -1,5787 +0,0 @@
-#!/usr/bin/env perl
-# cloc -- Count Lines of Code {{{1
-# Copyright (C) 2006-2008 Northrop Grumman Corporation
-# Author: Al Danial <al.danial@gmail.com>
-# First release August 2006
-#
-# Includes code from:
-# - SLOCCount v2.26
-# http://www.dwheeler.com/sloccount/
-# by David Wheeler.
-# - Regexp::Common v2.120
-# http://search.cpan.org/~abigail/Regexp-Common-2.120/lib/Regexp/Common.pm
-# by Damian Conway and Abigail
-# - Win32::Autoglob
-# http://search.cpan.org/~sburke/Win32-Autoglob-1.01/Autoglob.pm
-# by Sean M. Burke
-# - Algorithm::Diff
-# http://search.cpan.org/~tyemq/Algorithm-Diff-1.1902/lib/Algorithm/Diff.pm
-# by Tye McQueen
-#
-# 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:
-# http://www.gnu.org/licenses/gpl.txt
-#
-# 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
-# 1}}}
-my $VERSION = 1.04;
-require 5.006;
-# use modules {{{1
-use warnings;
-use strict;
-use Getopt::Long;
-use File::Basename;
-use File::Temp qw { tempfile tempdir };
-use File::Find;
-use File::Path;
-use IO::File;
-
-# Digest::MD5 isn't in the standard distribution. Use it only if installed.
-my $HAVE_Digest_MD5 = 0;
-eval "use Digest::MD5;";
-if (defined $Digest::MD5::VERSION) {
- $HAVE_Digest_MD5 = 1;
-} else {
- warn "Digest::MD5 not installed; will skip file uniqueness checks.\n";
-}
-
-my $HAVE_Rexexp_Common;
-# Regexp::Common isn't in the standard distribution. It will
-# be installed in a temp directory if necessary.
-BEGIN {
- if (eval "use Regexp::Common;") {
- $HAVE_Rexexp_Common = 1;
- } else {
- $HAVE_Rexexp_Common = 0;
- }
-}
-
-my $HAVE_Algorith_Diff = 0;
-# Algorithm::Diff isn't in the standard distribution. It will
-# be installed in a temp directory if necessary.
-eval "use Algorithm::Diff;";
-if (defined $Algorithm::Diff::VERSION) {
- $HAVE_Algorith_Diff = 1;
-} else {
- Install_Algorithm_Diff();
-}
-# print "HAVE_Algorith_Diff = $HAVE_Algorith_Diff\n";
-# test_alg_diff("cloc-0.80.pl", "cloc-0.90.pl", ); die;
-
-# Uncomment next two lines when building Windows executable with perl2exe
-# or if running on a system that already has Regexp::Common.
-#use Regexp::Common;
-#$HAVE_Rexexp_Common = 1;
-
-#perl2exe_include "Regexp/Common/whitespace.pm"
-#perl2exe_include "Regexp/Common/URI.pm"
-#perl2exe_include "Regexp/Common/URI/fax.pm"
-#perl2exe_include "Regexp/Common/URI/file.pm"
-#perl2exe_include "Regexp/Common/URI/ftp.pm"
-#perl2exe_include "Regexp/Common/URI/gopher.pm"
-#perl2exe_include "Regexp/Common/URI/http.pm"
-#perl2exe_include "Regexp/Common/URI/pop.pm"
-#perl2exe_include "Regexp/Common/URI/prospero.pm"
-#perl2exe_include "Regexp/Common/URI/news.pm"
-#perl2exe_include "Regexp/Common/URI/tel.pm"
-#perl2exe_include "Regexp/Common/URI/telnet.pm"
-#perl2exe_include "Regexp/Common/URI/tv.pm"
-#perl2exe_include "Regexp/Common/URI/wais.pm"
-#perl2exe_include "Regexp/Common/CC.pm"
-#perl2exe_include "Regexp/Common/SEN.pm"
-#perl2exe_include "Regexp/Common/number.pm"
-#perl2exe_include "Regexp/Common/delimited.pm"
-#perl2exe_include "Regexp/Common/profanity.pm"
-#perl2exe_include "Regexp/Common/net.pm"
-#perl2exe_include "Regexp/Common/zip.pm"
-#perl2exe_include "Regexp/Common/comment.pm"
-#perl2exe_include "Regexp/Common/balanced.pm"
-#perl2exe_include "Regexp/Common/lingua.pm"
-#perl2exe_include "Regexp/Common/list.pm"
-#perl2exe_include "File/Glob.pm"
-
-use Text::Tabs qw { expand };
-use Cwd qw { cwd };
-# 1}}}
-# Usage information, options processing. {{{1
-my $script = basename $0;
-my $usage = "
-Usage: $script [options] <file(s)/dir(s)> | <report files>
-
- Count physical lines of source code in the given files and/or
- recursively below the given directories.
-
- Options:
- --by-file Report results for every source file encountered
- in addition to reporting by language.
- --categorized=<file> Save names of categorized files to <file>.
- --counted=<file> Save names of processed source files to <file>.
- --exclude-dir=<D1>[,D2,] Exclude the given comma separated directories
- D1, D2, D3, et cetera, from being scanned. For
- example --exclude-dir=.cvs,.svn will skip
- all files that have /.cvs/ or /.svn/ as part of
- their path.
- --exclude-lang=<L1>[,L2,] Exclude the given comma separated languages
- L1, L2, L3, et cetera, from being counted.
- --extract-with=<cmd> Use <cmd> to extract binary archive files (e.g.:
- .tar.gz, .zip, .Z). Use the literal '>FILE<' as
- a stand-in for the actual file(s) to be
- extracted. For example, to count lines of code
- in the input files
- gcc-4.2.tar.gz perl-5.8.8.tar.gz
- on Unix use
- --extract-with='gzip -dc >FILE< | tar xf -'
- or, if you have GNU tar,
- --extract-with='tar zxf >FILE<'
- and on Windows use:
- --extract-with=\"\\\"c:\\Program Files\\WinZip\\WinZip32.exe\\\" -e -o >FILE< .\"
- (if WinZip is installed there).
- --force-lang=<lang>[,<ext>]
- Process all files that have a <ext> extension
- with the counter for language <lang>. For
- example, to count all .f files with the
- Fortran 90 counter (which expects files to
- end with .f90) instead of the default Fortran 77
- counter, use
- --force-lang=\"Fortran 90\",f
- If <ext> is omitted, every file will be counted
- with the <lang> counter. This option can be
- specified multiple times (but that is only
- useful when <ext> is given each time).
- See also --script-lang.
- --found=<file> Save names of every file found to <file>.
- --ignored=<file> Save names of ignored files and the reason they
- were ignored to <file>.
- --no3 Suppress third-generation language output.
- This option can cause report summation to fail
- if some reports were produced with this option
- while others were produced without it.
- --print-filter-stages Print to STDOUT processed source code before and
- after each filter is applied.
- --progress-rate=<n> Show progress update after every <n> files are
- processed (default <n>=100). Set <n> to 0 to
- suppress progress output (useful when redirecting
- output to STDOUT).
- --quiet Suppress all information messages except for
- the final report.
- --report-file=<file> Write the results to <file> instead of STDOUT.
- --read-lang-def=<file> Load from <file> the language processing filters.
- (see also --write-lang-def) then use these filters
- instead of the built-in filters.
- --script-lang=<lang>,<s> Process all files that invoke <s> as a #!
- scripting language with the counter for language
- <lang>. For example, files that begin with
- #!/usr/local/bin/perl5.8.8
- will be counted with the Perl counter by using
- --script-lang=Perl,perl5.8.8
- The language name is case insensitive but the
- name of the script language executable, <s>,
- must have the right case. This option can be
- specified multiple times. See also --force-lang.
- --sdir=<dir> Use <dir> as the scratch directory instead of
- letting File::Temp chose the location. Files
- written to this location are not removed at
- the end of the run (as they are with File::Temp).
- --show-ext[=<ext>] Print information about all known (or just the
- given) file extensions and exit.
- --show-lang[=<lang>] Print information about all known (or just the
- given) languages and exit.
- --strip-comments=<ext> For each file processed, write to the current
- directory a version of the file which has blank
- lines and comments removed. The name of each
- stripped file is the original file name with
- .<ext> appended to it.
- --sum-reports Input arguments are report files previously
- created with the --report-file option. Makes
- a cumulative set of results containing the
- sum of data from the individual report files.
- --unicode Check binary files to see if they contain Unicode
- expanded ASCII text. This causes performance to
- drop noticably.
- --write-lang-def=<file> Writes to <file> the language processing filters
- then exits. Useful as a first step to creating
- custom language definitions (see --read-lang-def).
- -v[=<n>] Verbose switch (optional numeric value).
- --version Print the version of this program and exit.
- --csv Write the results as comma separated values.
- --xml Write the results in XML.
- --yaml Write the results in YAML.
-
-";
-# Help information for options not yet implemented:
-# --diff Shows counts of code and comment changes between
-# successive pairs of inputs:
-# delta(FD_1, FD_2), delta(FD_2, FD_3), etc
-# (FD means 'file, archive, or directory')
-# --html Create HTML files of each input file showing
-# comment and code lines in different colors.
-
-$| = 1; # flush STDOUT
-my $start_time = time();
-my (
- $opt_categorized ,
- $opt_found ,
- @opt_force_lang ,
- @opt_script_lang ,
- $opt_diff ,
- $opt_html ,
- $opt_ignored ,
- $opt_counted ,
- $opt_show_ext ,
- $opt_show_lang ,
- $opt_progress_rate ,
- $opt_print_filter_stages ,
- $opt_v ,
- $opt_version ,
- $opt_exclude_lang ,
- $opt_exclude_dir ,
- $opt_read_lang_def ,
- $opt_write_lang_def ,
- $opt_strip_comments ,
- $opt_quiet ,
- $opt_report_file ,
- $opt_sdir ,
- $opt_sum_reports ,
- $opt_unicode ,
- $opt_no3 ,
- $opt_extract_with ,
- $opt_by_file ,
- $opt_xml ,
- $opt_yaml ,
- $opt_csv ,
- );
-GetOptions(
- "by_file|by-file" => \$opt_by_file ,
- "categorized=s" => \$opt_categorized ,
- "counted=s" => \$opt_counted ,
- "exclude_lang|exclude-lang=s" => \$opt_exclude_lang ,
- "exclude_dir|exclude-dir=s" => \$opt_exclude_dir ,
- "extract_with|extract-with=s" => \$opt_extract_with ,
- "found=s" => \$opt_found ,
- "diff" => \$opt_diff ,
- "html" => \$opt_html ,
- "ignored=s" => \$opt_ignored ,
- "quiet" => \$opt_quiet ,
- "read_lang_def|read-lang-def=s" => \$opt_read_lang_def ,
- "show_ext|show-ext:s" => \$opt_show_ext ,
- "show_lang|show-lang:s" => \$opt_show_lang ,
- "progress_rate|progress-rate=i" => \$opt_progress_rate ,
- "print_filter_stages|print-filter-stages" => \$opt_print_filter_stages ,
- "report_file|report-file=s" => \$opt_report_file ,
- "script_lang|script-lang=s" => \@opt_script_lang ,
- "sdir=s" => \$opt_sdir ,
- "strip_comments|strip-comments=s" => \$opt_strip_comments ,
- "sum_reports|sum-reports" => \$opt_sum_reports ,
- "unicode" => \$opt_unicode ,
- "no3" => \$opt_no3 ,
- "v:i" => \$opt_v ,
- "version" => \$opt_version ,
- "write_lang_def|write-lang-def=s" => \$opt_write_lang_def ,
- "xml" => \$opt_xml ,
- "force_lang|force-lang=s" => \@opt_force_lang ,
- "yaml" => \$opt_yaml ,
- "csv" => \$opt_csv ,
- );
-
-my %Exclude_Language = ();
- %Exclude_Language = map { $_ => 1 } split(/,/, $opt_exclude_lang)
- if $opt_exclude_lang;
-my %Exclude_Dir = ();
- %Exclude_Dir = map { $_ => 1 } split(/,/, $opt_exclude_dir )
- if $opt_exclude_dir ;
-# Options defaults:
-$opt_progress_rate = 100 unless defined $opt_progress_rate;
-$opt_v = 0 unless defined $opt_v;
-die $usage unless defined $opt_version or
- defined $opt_show_lang or
- defined $opt_show_ext or
- defined $opt_write_lang_def or
- scalar @ARGV >= 1;
-die "--diff requires at least two arguments\n"
- if $opt_diff and scalar @ARGV < 2;
-# 1}}}
-# Step 1: Initialize global constants. {{{1
-#
-my $ON_WINDOWS = 0;
- $ON_WINDOWS = 1 if ($^O =~ /^MSWin/) or ($^O eq "Windows_NT");
- $ON_WINDOWS = 0 if $ENV{'SHELL'}; # make Cygwin look like Unix
-
-my $nFiles_Found = 0; # updated in make_file_list
-my (%Language_by_Extension, %Language_by_Script,
- %Filters_by_Language, %Not_Code_Extension, %Not_Code_Filename,
- %Language_by_File, %Scale_Factor, %Known_Binary_Archives,
- );
-my %Error_Codes = ( 'Unable to read' => -1,
- 'Neither file nor directory' => -2, );
-if ($opt_read_lang_def) {
- read_lang_def(
- $opt_read_lang_def , # Sample values:
- \%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
- \%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
- \%Language_by_File , # Language_by_File{makefile} = 'make'
- \%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
- # [ 'remove_matches' , '^\s*#' ]
- \%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
- \%Not_Code_Filename , # Not_Code_Filename{README} = 1
- \%Scale_Factor , # Scale_Factor{Perl} = 4.0
- );
-} else {
- set_constants( #
- \%Language_by_Extension, # Language_by_Extension{f} = 'Fortran 77'
- \%Language_by_Script , # Language_by_Script{sh} = 'Bourne Shell'
- \%Language_by_File , # Language_by_File{makefile} = 'make'
- \%Filters_by_Language , # Filters_by_Language{Bourne Shell}[0] =
- # [ 'remove_matches' , '^\s*#' ]
- \%Not_Code_Extension , # Not_Code_Extension{jpg} = 1
- \%Not_Code_Filename , # Not_Code_Filename{README} = 1
- \%Scale_Factor , # Scale_Factor{Perl} = 4.0
- \%Known_Binary_Archives, # Known_Binary_Archives{.tar} = 1
- );
-}
-
-# Process command line provided extention-to-language mapping overrides.
-# Make a hash of known languages in lower case for easier matching.
-my %Recognized_Language_lc = (); # key = language name in lc, value = true name
-foreach my $language (keys %Filters_by_Language) {
- my $lang_lc = lc $language;
- $Recognized_Language_lc{$lang_lc} = $language;
-}
-my %Forced_Extension = (); # file name extensions which user wants to count
-my $All_One_Language = 0; # set to !0 if --force-lang's <ext> is missing
-foreach my $pair (@opt_force_lang) {
- my ($lang, $extension) = split(',', $pair);
- my $lang_lc = lc $lang;
- if (defined $extension) {
- $Forced_Extension{$extension} = $lang;
-
- die_unknown_lang($lang, "--force-lang")
- unless $Recognized_Language_lc{$lang_lc};
-
- $Language_by_Extension{$extension} = $Recognized_Language_lc{$lang_lc};
- } else {
- # the scary case--count everything as this language
- $All_One_Language = $Recognized_Language_lc{$lang_lc};
- }
-}
-
-foreach my $pair (@opt_script_lang) {
- my ($lang, $script_name) = split(',', $pair);
- my $lang_lc = lc $lang;
- if (!defined $script_name) {
- die "The --script-lang option requires a comma separated pair of ".
- "strings.\n";
- }
-
- die_unknown_lang($lang, "--script-lang")
- unless $Recognized_Language_lc{$lang_lc};
-
- $Language_by_Script{$script_name} = $Recognized_Language_lc{$lang_lc};
-}
-# invert %Language_by_Script hash to get an easy-to-look-up list of known
-# scripting languages
-my %Script_Language = map { $_ => 1 } values %Language_by_Script ;
-# 1}}}
-# Step 2: Early exits for display, summation. {{{1
-#
-if ($opt_version) {
- printf "%.2f\n", $VERSION;
- exit;
-}
-print_extension_info($opt_show_ext ) if defined $opt_show_ext ;
-print_language_info( $opt_show_lang) if defined $opt_show_lang;
-exit if (defined $opt_show_ext) or (defined $opt_show_lang);
-
-# Windows doesn't expand wildcards. Use code from Sean M. Burke's
-# Win32::Autoglob module to do this.
-#print "Before glob have [", join(",", @ARGV), "]\n";
-@ARGV = map {;
- ( defined($_) and m/[\*\?]/ ) ? sort(glob($_)) : $_
- } @ARGV if $ON_WINDOWS;
-;
-#print "after glob have [", join(",", @ARGV), "]\n";
-
-if ($opt_sum_reports) {
- my %Results = ();
- foreach my $type( "by language", "by report file" ) {
- my $found_lang = combine_results(\@ARGV,
- $type,
- \%{$Results{ $type }},
- \%Filters_by_Language );
- next unless %Results;
- my $end_time = time();
- my @results = generate_report($VERSION, $end_time - $start_time,
- $type,
- \%{$Results{ $type }}, \%Scale_Factor);
- if ($opt_report_file) {
- my $ext = ".lang";
- $ext = ".file" unless $type eq "by language";
- next if !$found_lang and $ext eq ".lang";
- write_file($opt_report_file . $ext, @results);
- } else {
- print "\n", join("\n", @results), "\n";
- }
- }
- exit;
-}
-if ($opt_write_lang_def) {
- write_lang_def($opt_write_lang_def ,
- \%Language_by_Extension,
- \%Language_by_Script ,
- \%Language_by_File ,
- \%Filters_by_Language ,
- \%Not_Code_Extension ,
- \%Not_Code_Filename ,
- \%Scale_Factor ,
- );
- exit;
-}
-# 1}}}
-# Step 3: Create a list of files to consider. {{{1
-# a) If inputs are binary archives, first cd to a temp
-# directory, expand the archive with the user-given
-# extraction tool, then add the temp directory to
-# the list of dirs to process.
-# b) Create a list of every file that might contain source
-# code. Ignore binary files, zero-sized files, and
-# any file in a directory the user says to exclude.
-# c) Determine the language for each file in the list.
-#
-my @binary_archive = ();
-if ($opt_extract_with) {
- my $cwd = cwd();
-#print "cwd main = [$cwd]\n";
- my @extract_location = ();
- foreach my $bin_file (@ARGV) {
- my $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
- chdir $extract_dir;
- print "Using temp dir [$extract_dir] to extract $bin_file\n"
- if $opt_v;
- my $bin_file_full_path = "";
- if (File::Spec->file_name_is_absolute( $bin_file )) {
- $bin_file_full_path = $bin_file;
-#print "bin_file_full_path (was ful) = [$bin_file_full_path]\n";
- } else {
- $bin_file_full_path = File::Spec->catfile( $cwd, $bin_file );
-#print "bin_file_full_path (was rel) = [$bin_file_full_path]\n";
- }
- (my $extract_cmd = $opt_extract_with )
- =~ s/>FILE</$bin_file_full_path/g;
- print $extract_cmd, "\n";
- system $extract_cmd;
- push @extract_location, $extract_dir;
- chdir $cwd;
- }
- # It is possible that the binary archive itself contains additional
- # files compressed the same way (true for Java .ear files). Go
- # through all the files that were extracted, see if they are binary
- # archives and try to extract them. Lather, rinse, repeat.
- my $binary_archives_exist = 1;
- my $count_binary_archives = 0;
- my $previous_count = 0;
- while ($binary_archives_exist) {
- @binary_archive = ();
- foreach my $dir (@extract_location) {
- find(\&archive_files, $dir); # populates global @binary_archive
- }
- foreach my $archive (@binary_archive) {
- (my $extract_cmd = $opt_extract_with )
- =~ s/>FILE</$archive/g;
- my $extract_dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
- chdir $extract_dir;
- print $extract_cmd, "\n";
- system $extract_cmd;
- push @extract_location, $extract_dir;
- unlink $archive; # otherwise will be extracting it forever
- }
- $count_binary_archives = scalar @binary_archive;
- if ($count_binary_archives == $previous_count) {
- $binary_archives_exist = 0;
- }
- $previous_count = $count_binary_archives;
- }
- chdir $cwd;
-
- @ARGV = @extract_location;
-}
-# 1}}}
-my @Errors = ();
-my @file_list = (); # global variable updated in files()
-my %Ignored = (); # files that are not counted (language not recognized or
- # problems reading the file)
-if ($opt_diff) {
-# Step 4: Separate code from non-code files. {{{1
-my @fh;
-my @files_for_set = ();
-# make file lists for each separate argument
-for (my $i = 0; $i < scalar @ARGV; $i++) {
- push @fh,
- make_file_list([ $ARGV[$i] ], \%Error_Codes, \@Errors, \%Ignored);
- @{$files_for_set[$i]} = @file_list;
- @file_list = ();
-}
-# 1}}}
-# Step 5: Remove duplicate files. {{{1
-#
-my %Language = ();
-my %unique_source_file = ();
-my $n_set = 0;
-foreach my $FH (@fh) { # loop over each pair of file sets
- ++$n_set;
- remove_duplicate_files($FH,
- \%{$Language{$FH}} ,
- \%{$unique_source_file{$FH}} ,
- \%Error_Codes ,
- \@Errors ,
- \%Ignored );
- printf "%2d: %8d unique file%s. \n",
- $n_set,
- plural_form(scalar keys %unique_source_file)
- unless $opt_quiet;
-}
-# 1}}}
-# Step 6: Count code, comments, blank lines. {{{1
-#
-my %n_Files_Same = ();
-my %n_Files_Added = ();
-my %n_Files_Removed = ();
-my %n_Files_Changed = ();
-my %Results_by_Language = ();
-my %Results_by_File = ();
-foreach (my $F = 0; $F < scalar @fh - 1; $F++) {
- # loop over file sets; do diff between set $F to $F+1
-
- my $nCounted = 0;
-
- my @changed_file_pairs = ();
- align_by_pairs(\%{$unique_source_file{$fh[$F ]}}, # in
- \%{$unique_source_file{$fh[$F+1]}}, # in
- \$n_Files_Same{$fh[$F]} , # out
- \$n_Files_Added{$fh[$F]} , # out
- \$n_Files_Removed{$fh[$F]} , # out
- \$n_Files_Changed{$fh[$F]} , # out
- \@changed_file_pairs , # out
- );
-
- foreach my $pair (@changed_file_pairs) {
- my $file_L = $pair->[0];
- my $file_R = $pair->[1];
-#print "main step 6 file_L=$file_L file_R=$file_R\n";
- ++$nCounted;
- printf "Counting: %d\r", $nCounted
- unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
- next if $Ignored{$file_L};
-
- if ($Exclude_Language{$Language{$fh[$F ]}{$file_L}} or
- $Exclude_Language{$Language{$fh[$F+1]}{$file_R}}
- ) {
- $Ignored{$file_L} = "--exclude_lang=$Language{$fh[$F ]}{$file_L}";
- $Ignored{$file_R} = "--exclude_lang=$Language{$fh[$F+1]}{$file_R}";
- next;
- }
- if (!defined @{$Filters_by_Language{$Language{$fh[$F ]}{$file_L}} } or
- !defined @{$Filters_by_Language{$Language{$fh[$F+1]}{$file_R}} }
- ) {
- if (($Language{$fh[$F ]}{$file_L} eq "(unknown)") or
- ($Language{$fh[$F+1]}{$file_R} eq "(unknown)")
- ) {
- $Ignored{$fh[$F ]}{$file_L} = "language unknown (#1)";
- $Ignored{$fh[$F+1]}{$file_R} = "language unknown (#1)";
- } else {
- $Ignored{$fh[$F ]}{$file_L} = "missing Filters_by_Language{$Language{$file_L}}";
- $Ignored{$fh[$F+1]}{$file_R} = "missing Filters_by_Language{$Language{$file_R}}";
- }
- next;
- }
-
-print "DIFF($file_L, $file_R)\n";
- # step 1: identify comments in both files
- chomp ( my @lines_L = read_file($file_L) );
- my @original_minus_blanks_L
- = rm_blanks( \@lines_L, $Language{$fh[$F]}{$file_L});
- @lines_L = @original_minus_blanks_L;
- @lines_L = rm_comments(\@lines_L, $Language{$fh[$F]}{$file_L}, $file_L);
-
- chomp ( my @lines_R = read_file($file_R) );
- my @original_minus_blanks_R
- = rm_blanks( \@lines_R, $Language{$fh[$F+1]}{$file_R});
- @lines_R = @original_minus_blanks_R;
- @lines_R = rm_comments(\@lines_R, $Language{$fh[$F+1]}{$file_R}, $file_R);
-
- my (@diff_LL, @diff_LR, %count_L);
- file_diff(\@original_minus_blanks_L , # in
- \@lines_L , # in
- "comment" , # in
- \@diff_LL, \@diff_LR, \%count_L); # out
-
- my (@diff_RL, @diff_RR, %count_R);
- file_diff(\@original_minus_blanks_R , # in
- \@lines_R , # in
- "comment" , # in
- \@diff_RL, \@diff_RR, \%count_R); # out
-
-#use Data::Dumper;
-#print Dumper("diff_LL", \@diff_LL, "diff_LR", \@diff_LR, "count", \%count_L);
-#print Dumper("diff_RL", \@diff_RL, "diff_RR", \@diff_RR, "count", \%count_R);
-
-#v# my ($all_line_count,
-#v# $blank_count ,
-#v# $comment_count ,
-#v# ) = call_counter($file_L, $Language{$file_L});
-#v# my $code_count = $all_line_count - $blank_count - $comment_count;
-#v# if ($opt_by_file) {
-#v# $Results_by_File{$file_L}{'code' } = $code_count ;
-#v# $Results_by_File{$file_L}{'blank' } = $blank_count ;
-#v# $Results_by_File{$file_L}{'comment'} = $comment_count ;
-#v# $Results_by_File{$file_L}{'lang' } = $Language{$file_L};
-#v# $Results_by_File{$file_L}{'nFiles' } = 1;
-#v# }
-#v#
-#v# $Results_by_Language{$Language{$file_L}}{'nFiles'}++;
-#v# $Results_by_Language{$Language{$file_L}}{'code'} += $code_count ;
-#v# $Results_by_Language{$Language{$file_L}}{'blank'} += $blank_count ;
-#v# $Results_by_Language{$Language{$file_L}}{'comment'} += $comment_count;
- }
-#v# my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
-#v# write_file($opt_ignored, @ignored_reasons ) if $opt_ignored;
-#v# write_file($opt_counted, sort keys %Language) if $opt_counted;
-}
-# 1}}}
-# Step 7: Print results. {{{1
-#
-my $end_time = time();
-printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
- unless $opt_quiet;
-print_errors(\%Error_Codes, \@Errors) if @Errors;
-exit unless %Results_by_Language;
-
-#use YAML; print YAML::Dump(\%Results_by_Language); die;
-
-my @results = ();
-unless ($opt_by_file) {
- @results = generate_report( $VERSION, $end_time - $start_time,
- "by language",
- \%Results_by_Language, \%Scale_Factor);
- if ($opt_report_file) { write_file($opt_report_file, @results); }
- else { print "\n", join("\n", @results), "\n"; }
-} else {
- @results = generate_report( $VERSION, $end_time - $start_time,
- "by file",
- \%Results_by_File, \%Scale_Factor);
- if ($opt_report_file) { write_file($opt_report_file, @results); }
- else { print "\n", join("\n", @results), "\n"; }
-}
-# 1}}}
-} else {
-# Step 4: Separate code from non-code files. {{{1
-my $fh = make_file_list(\@ARGV, \%Error_Codes, \@Errors, \%Ignored);
-# make_file_list populates global variable @file_list via call to
-# File::Find's find() which in turn calls files()
-# 1}}}
-# Step 5: Remove duplicate files. {{{1
-#
-my %Language = ();
-my %unique_source_file = ();
-remove_duplicate_files($fh,
- \%Language ,
- \%unique_source_file ,
- \%Error_Codes ,
- \@Errors ,
- \%Ignored );
-printf "%8d unique file%s. \n",
- plural_form(scalar keys %unique_source_file)
- unless $opt_quiet;
-# 1}}}
-# Step 6: Count code, comments, blank lines. {{{1
-#
-
-my %Results_by_Language = ();
-my %Results_by_File = ();
-my $nCounted = 0;
-foreach my $file (sort keys %unique_source_file) {
- ++$nCounted;
- printf "Counting: %d\r", $nCounted
- unless (!$opt_progress_rate or ($nCounted % $opt_progress_rate));
- next if $Ignored{$file};
- if ($Exclude_Language{$Language{$file}}) {
- $Ignored{$file} = "--exclude_lang=$Language{$file}";
- next;
- }
- if (!defined @{$Filters_by_Language{$Language{$file}} }) {
- if ($Language{$file} eq "(unknown)") {
- $Ignored{$file} = "language unknown (#1)";
- } else {
- $Ignored{$file} = "missing Filters_by_Language{$Language{$file}}";
- }
- next;
- }
-
- my ($all_line_count,
- $blank_count ,
- $comment_count ,
- ) = call_counter($file, $Language{$file});
- my $code_count = $all_line_count - $blank_count - $comment_count;
- if ($opt_by_file) {
- $Results_by_File{$file}{'code' } = $code_count ;
- $Results_by_File{$file}{'blank' } = $blank_count ;
- $Results_by_File{$file}{'comment'} = $comment_count ;
- $Results_by_File{$file}{'lang' } = $Language{$file};
- $Results_by_File{$file}{'nFiles' } = 1;
- }
-
- $Results_by_Language{$Language{$file}}{'nFiles'}++;
- $Results_by_Language{$Language{$file}}{'code'} += $code_count ;
- $Results_by_Language{$Language{$file}}{'blank'} += $blank_count ;
- $Results_by_Language{$Language{$file}}{'comment'} += $comment_count;
-}
-my @ignored_reasons = map { "$_: $Ignored{$_}" } sort keys %Ignored;
-write_file($opt_ignored, @ignored_reasons ) if $opt_ignored;
-write_file($opt_counted, sort keys %Language) if $opt_counted;
-# 1}}}
-# Step 7: Print results. {{{1
-#
-my $end_time = time();
-printf "%8d file%s ignored.\n", plural_form(scalar keys %Ignored)
- unless $opt_quiet;
-print_errors(\%Error_Codes, \@Errors) if @Errors;
-exit unless %Results_by_Language;
-
-#use YAML; print YAML::Dump(\%Results_by_Language); die;
-
-my @results = ();
-unless ($opt_by_file) {
- @results = generate_report( $VERSION, $end_time - $start_time,
- "by language",
- \%Results_by_Language, \%Scale_Factor);
- if ($opt_report_file) { write_file($opt_report_file, @results); }
- else { print "\n", join("\n", @results), "\n"; }
-} else {
- @results = generate_report( $VERSION, $end_time - $start_time,
- "by file",
- \%Results_by_File, \%Scale_Factor);
- if ($opt_report_file) { write_file($opt_report_file, @results); }
- else { print "\n", join("\n", @results), "\n"; }
-}
-# 1}}}
-}
-
-sub combine_results { # {{{1
- # returns 1 if the inputs are categorized by language
- # 0 if no identifiable language was found
- my ($ra_report_files, # in
- $report_type , # in "by language" or "by report file"
- $rhh_count , # out count{TYPE}{nFiles|code|blank|comment|scaled}
- $rhaa_Filters_by_Language , # in
- ) = @_;
-
- my $found_language = 0;
-
- foreach my $file (@{$ra_report_files}) {
- my $IN = new IO::File $file, "r";
- if (!defined $IN) {
- warn "Unable to read $file; ignoring.\n";
- next;
- }
- while (<$IN>) {
- next if /^(http|Language|SUM|-----)/;
- if (m{^(.*?)\s+ # language
- (\d+)\s+ # files
- (\d+)\s+ # blank
- (\d+)\s+ # comments
- (\d+)\s+ # code
- ( # next four entries missing with -nno3
- x\s+ # x
- \d+\.\d+\s+ # scale
- =\s+ # =
- (\d+\.\d+)\s* # scaled code
- )?
- $}x) {
- if ($report_type eq "by language") {
- next unless defined %{$rhaa_Filters_by_Language->{$1}};
- # above test necessary to avoid trying to sum reports
- # of reports (which have no language breakdown).
- $found_language = 1;
- $rhh_count->{$1 }{'nFiles' } += $2;
- $rhh_count->{$1 }{'blank' } += $3;
- $rhh_count->{$1 }{'comment'} += $4;
- $rhh_count->{$1 }{'code' } += $5;
- $rhh_count->{$1 }{'scaled' } += $7 unless $opt_no3;
- } else {
- $rhh_count->{$file}{'nFiles' } += $2;
- $rhh_count->{$file}{'blank' } += $3;
- $rhh_count->{$file}{'comment'} += $4;
- $rhh_count->{$file}{'code' } += $5;
- $rhh_count->{$file}{'scaled' } += $7 unless $opt_no3;
- }
- }
- }
- }
- return $found_language;
-
-} # 1}}}
-sub generate_report { # {{{1
- # returns an array of lines containing the results
- my ($version , # in
- $elapsed_sec, # in
- $report_type, # in "by language" | "by report file" | "by file"
- $rhh_count , # in count{TYPE}{nFiles|code|blank|comment|scaled}
- $rh_scale , # in
- ) = @_;
-
- my @results = ();
-
- my $languages = ();
-
- my $sum_files = 0;
- my $sum_code = 0;
- my $sum_blank = 0;
- my $sum_comment = 0;
- foreach my $language (keys %{$rhh_count}) {
- $sum_files += $rhh_count->{$language}{'nFiles'} ;
- $sum_blank += $rhh_count->{$language}{'blank'} ;
- $sum_comment += $rhh_count->{$language}{'comment'};
- $sum_code += $rhh_count->{$language}{'code'} ;
- }
- my $sum_lines = $sum_blank + $sum_comment + $sum_code;
- $elapsed_sec = 0.5 unless $elapsed_sec;
-
- my $spacing_1 = 13;
- my $spacing_2 = 9;
- my $spacing_3 = 17;
- if ($opt_no3) {
- $spacing_1 = 19;
- $spacing_2 = 14;
- $spacing_3 = 28;
- }
- my %Format = (
- '1' => { 'xml' => 'name="%s" ',
- 'txt' => '%-23s ' ,
- },
- '2' => { 'xml' => 'name="%s" ',
- 'txt' => "\%-${spacing_3}s ",
- },
- '3' => { 'xml' => 'files_count="%d" ',
- 'txt' => '%5d ',
- },
- '4' => { 'xml' => 'blank="%d" comment="%d" code="%d" ',
- 'txt' => "\%${spacing_2}d \%${spacing_2}d \%${spacing_2}d",
- },
- '5' => { 'xml' => 'factor="%.2f" scaled="%.2f" ',
- 'txt' => ' x %6.2f = %14.2f',
- },
- );
- my $Style = "txt";
- $Style = "xml" if $opt_xml ;
- $Style = "xml" if $opt_yaml; # not a typo; just set to anything but txt
- $Style = "xml" if $opt_csv ; # not a typo; just set to anything but txt
-
- my $URL = "http://cloc.sourceforge.net";
- my $hyphen_line = sprintf "%s", '-' x 79;
- my $data_line = "";
- my $first_column;
- my $BY_LANGUAGE = 0;
- my $BY_FILE = 0;
- if ($report_type eq "by language") {
- $first_column = "Language";
- $BY_LANGUAGE = 1;
- } elsif ($report_type eq "by file") {
- $first_column = "File";
- $BY_FILE = 1;
- } else {
- $first_column = "Report File";
- }
-
- my $header_line = sprintf "%s v %4.2f", $URL, $version;
- $header_line .= sprintf(" T=%.1f s (%.1f files/s, %.1f lines/s)",
- $elapsed_sec ,
- $sum_files/$elapsed_sec,
- $sum_lines/$elapsed_sec) unless $opt_sum_reports;
- if ($opt_xml) {
- push @results, "<?xml version=\"1.0\"?>";
- push @results, "<results>";
- push @results, "<header>$header_line</header>";
- if ($BY_FILE) {
- push @results, "<files>";
- } else {
- push @results, "<languages>";
- }
- } elsif ($opt_yaml) {
- push @results, "---\n# $header_line";
- } elsif ($opt_csv) {
- # append the header to the end of the column headers
- # to keep the output a bit cleaner from a spreadsheet
- # perspective
- } else {
- push @results, $header_line;
- push @results, $hyphen_line;
- }
-
- if ($Style eq "txt") {
- # column headers
- $data_line = sprintf "%-${spacing_1}s ", $first_column;
- if ($BY_FILE) {
- $data_line .= sprintf "%${spacing_2}s " , " " ;
- } else {
- $data_line .= sprintf "%${spacing_2}s " , "files";
- }
- $data_line .= sprintf "%${spacing_2}s %${spacing_2}s %${spacing_2}s",
- "blank" ,
- "comment" ,
- "code";
- $data_line .= sprintf " %8s %14s",
- "scale" ,
- "3rd gen. equiv"
- unless $opt_no3;
- push @results, $data_line;
- push @results, $hyphen_line;
- }
- if ($opt_csv) {
- my $header2 = " ,";
- $header2 = " ,files" unless $BY_FILE;
- $header2 .= ",blank,comment,code";
- $header2 .= ",scale,3rd gen. equiv" unless $opt_no3;
- $header2 .= ',"' . $header_line . '"';
- push @results, $header2;
- }
-
- my $sum_scaled = 0;
- foreach my $lang_or_file (sort {
- $rhh_count->{$b}{'code'} <=>
- $rhh_count->{$a}{'code'}
- }
- keys %{$rhh_count}) {
- my ($factor, $scaled);
- if ($BY_LANGUAGE or $BY_FILE) {
- $factor = 1;
- if ($BY_LANGUAGE) {
- if (defined $rh_scale->{$lang_or_file}) {
- $factor = $rh_scale->{$lang_or_file};
- } else {
- warn "No scale factor for $lang_or_file; using 1.00";
- }
- } else { # by individual code file
- $factor = $rh_scale->{$rhh_count->{$lang_or_file}{'lang'}};
- }
- $scaled = $factor*$rhh_count->{$lang_or_file}{'code'};
- } else {
- if (!defined $rhh_count->{$lang_or_file}{'scaled'}) {
- $opt_no3 = 1;
- # If we're summing together files previously generated
- # with --no3 then rhh_count->{$lang_or_file}{'scaled'}
- # this variable will be undefined. That should only
- # happen when summing together by file however.
- } elsif ($BY_LANGUAGE) {
- warn "Missing scaled language info for $lang_or_file\n";
- }
- unless ($opt_no3) {
- $scaled = $rhh_count->{$lang_or_file}{'scaled'};
- $factor = $scaled/$rhh_count->{$lang_or_file}{'code'};
- }
- }
-
- if ($BY_FILE) {
- $data_line = sprintf $Format{'1'}{$Style}, $lang_or_file;
- } else {
- $data_line = sprintf $Format{'2'}{$Style}, $lang_or_file;
- }
- $data_line .= sprintf $Format{3}{$Style} ,
- $rhh_count->{$lang_or_file}{'nFiles'} unless $BY_FILE;
- $data_line .= sprintf $Format{4}{$Style} ,
- $rhh_count->{$lang_or_file}{'blank'} ,
- $rhh_count->{$lang_or_file}{'comment'},
- $rhh_count->{$lang_or_file}{'code'} ;
- $data_line .= sprintf $Format{5}{$Style} ,
- $factor ,
- $scaled unless $opt_no3;
- $sum_scaled += $scaled unless $opt_no3;
-
- if ($opt_xml) {
- if (defined $rhh_count->{$lang_or_file}{'lang'}) {
- my $lang = $rhh_count->{$lang_or_file}{'lang'};
- if (!defined $languages->{$lang}) {
- $languages->{$lang} = $lang;
- }
- $data_line.=' language="' . $lang . '" ';
- }
- if ($BY_FILE) {
- push @results, "<file " . $data_line . "/>";
- } else {
- push @results, "<language " . $data_line . "/>";
- }
- } elsif ($opt_yaml) {
- push @results, $lang_or_file . ":";
- push @results, " nFiles: " .$rhh_count->{$lang_or_file}{'nFiles'} ;
- push @results, " blank: " .$rhh_count->{$lang_or_file}{'blank'} ;
- push @results, " comment: ".$rhh_count->{$lang_or_file}{'comment'};
- push @results, " code: " .$rhh_count->{$lang_or_file}{'code'}
- unless $BY_FILE;
- if (!$opt_no3) {
- push @results, " scaled: " . $scaled;
- push @results, " factor: " . $factor;
- }
- } elsif ($opt_csv) {
- my $extra_3 = "";
- $extra_3 = ",$factor,$scaled" unless $opt_no3;
- push @results, $lang_or_file . "," .
- $rhh_count->{$lang_or_file}{'nFiles'} . "," .
- $rhh_count->{$lang_or_file}{'blank'} . "," .
- $rhh_count->{$lang_or_file}{'comment'}. "," .
- $rhh_count->{$lang_or_file}{'code'} .
- $extra_3;
- } else {
- push @results, $data_line;
- }
- }
- my $avg_scale = 1; # weighted average of scale factors
- $avg_scale = sprintf("%.2f", $sum_scaled / $sum_code)
- if $sum_code and !$opt_no3;
-
- if ($opt_xml) {
- $data_line = "";
- if (!$BY_FILE) {
- $data_line .= sprintf "sum_files=\"%d\" ", $sum_files;
- }
- $data_line .= sprintf $Format{'4'}{$Style},
- $sum_blank ,
- $sum_comment ,
- $sum_code ;
- $data_line .= sprintf $Format{'5'}{$Style},
- $avg_scale ,
- $sum_scaled unless $opt_no3;
- push @results, "<total " . $data_line . "/>";
-
- if ($BY_FILE) {
- push @results, "</files>";
- } else {
- foreach my $language (keys %{$languages}) {
- push @results, '<language name="' . $language . '"/>';
- }
- push @results, "</languages>";
- }
-
- push @results, "</results>";
- } elsif ($opt_yaml) {
- push @results, "SUM:";
- push @results, " blank: " . $sum_blank ;
- push @results, " code: " . $sum_code ;
- push @results, " comment: ". $sum_comment;
- push @results, " nFiles: " . $sum_files unless $BY_FILE;
- if (!$opt_no3) {
- push @results, " scaled: " . $sum_scaled;
- push @results, " factor: " . $avg_scale ;
- }
- } elsif ($opt_csv) {
- # do nothing
- } else {
-
- if ($BY_FILE) {
- $data_line = sprintf "%-23s ", "SUM:" ;
- } else {
- $data_line = sprintf "%-${spacing_1}s ", "SUM:" ;
- $data_line .= sprintf "%${spacing_2}d ", $sum_files;
- }
- $data_line .= sprintf $Format{'4'}{$Style},
- $sum_blank ,
- $sum_comment ,
- $sum_code ;
- $data_line .= sprintf $Format{'5'}{$Style},
- $avg_scale ,
- $sum_scaled unless $opt_no3;
- push @results, $hyphen_line if $sum_files > 1;
- push @results, $data_line if $sum_files > 1;
- push @results, $hyphen_line;
- }
- return @results;
-} # 1}}}
-sub print_errors { # {{{1
- my ($rh_Error_Codes, # in
- $raa_errors , # in
- ) = @_;
-
- my %error_string = reverse(%{$rh_Error_Codes});
- my $nErrors = scalar @{$raa_errors};
- printf "\n%d error%s:\n", plural_form(scalar @Errors);
- for (my $i = 0; $i < $nErrors; $i++) {
- printf "%s: %s\n",
- $error_string{ $raa_errors->[$i][0] },
- $raa_errors->[$i][1] ;
- }
- print "\n";
-
-} # 1}}}
-sub write_lang_def { # {{{1
- my ($file ,
- $rh_Language_by_Extension , # in
- $rh_Language_by_Script , # in
- $rh_Language_by_File , # in
- $rhaa_Filters_by_Language , # in
- $rh_Not_Code_Extension , # in
- $rh_Not_Code_Filename , # in
- $rh_Scale_Factor , # in
- ) = @_;
-
- my $OUT = new IO::File $file, "w";
- die "Unable to write to $file\n" unless defined $OUT;
-
- foreach my $language (sort keys %{$rhaa_Filters_by_Language}) {
- next if $language eq "MATLAB/Objective C/MUMPS";
- printf $OUT "%s\n", $language;
- foreach my $filter (@{$rhaa_Filters_by_Language->{$language}}) {
- printf $OUT " filter %s", $filter->[0];
- printf $OUT " %s", $filter->[1] if defined $filter->[1];
- print $OUT "\n";
- }
- foreach my $ext (sort keys %{$rh_Language_by_Extension}) {
- if ($language eq $rh_Language_by_Extension->{$ext}) {
- printf $OUT " extension %s\n", $ext;
- }
- }
- foreach my $filename (sort keys %{$rh_Language_by_File}) {
- if ($language eq $rh_Language_by_File->{$filename}) {
- printf $OUT " filename %s\n", $filename;
- }
- }
- foreach my $script_exe (sort keys %{$rh_Language_by_Script}) {
- if ($language eq $rh_Language_by_Script->{$script_exe}) {
- printf $OUT " script_exe %s\n", $script_exe;
- }
- }
- printf $OUT " 3rd_gen_scale %.2f\n", $rh_Scale_Factor->{$language};
- }
-
- $OUT->close;
-} # 1}}}
-sub read_lang_def { # {{{1
- my ($file ,
- $rh_Language_by_Extension , # out
- $rh_Language_by_Script , # out
- $rh_Language_by_File , # out
- $rhaa_Filters_by_Language , # out
- $rh_Not_Code_Extension , # out
- $rh_Not_Code_Filename , # out
- $rh_Scale_Factor , # out
- ) = @_;
-
- my $IN = new IO::File $file, "r";
- die "Unable to read $file.\n" unless defined $IN;
-
- my $language = "";
- while (<$IN>) {
- next if /^\s*#/ or /^\s*$/;
-
- if (/^(\w+.*?)\s*$/) {
- $language = $1;
- next;
- }
- die "Missing computer language name, line $. of $file\n"
- unless $language;
-
- if (/^ filter\s+(\w+)\s*$/) {
- push @{$rhaa_Filters_by_Language->{$language}}, [ $1 ]
-
- } elsif (/^ filter\s+(\w+)\s+(.*?)\s*$/) {
- push @{$rhaa_Filters_by_Language->{$language}}, [ $1 , $2 ]
-
- } elsif (/^ extension\s+(\S+)\s*$/) {
- if (defined $rh_Language_by_Extension->{$1}) {
- die "File extension collision: $1 ",
- "maps to languages '$rh_Language_by_Extension->{$1}' ",
- "and '$language'\n" ,
- "Edit $file and remove $1 from one of these two ",
- "language definitions.\n";
- }
- $rh_Language_by_Extension->{$1} = $language;
-
- } elsif (/^ filename\s+(\S+)\s*$/) {
- $rh_Language_by_File->{$1} = $language;
-
- } elsif (/^ script_exe\s+(\S+)\s*$/) {
- $rh_Language_by_Script->{$1} = $language;
-
- } elsif (/^ 3rd_gen_scale\s+(\S+)\s*$/) {
- $rh_Scale_Factor->{$language} = $1;
-
- } else {
- die "Unexpected data line $. of $file:\n$_\n";
- }
-
- }
- $IN->close;
-} # 1}}}
-sub print_extension_info { # {{{1
- my ($extension,) = @_;
- if ($extension) { # show information on this extension
- foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
- # Language_by_Extension{f} = 'Fortran 77'
- printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext}
- if $ext =~ m{$extension}i;
- }
- } else { # show information on all extensions
- foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
- # Language_by_Extension{f} = 'Fortran 77'
- printf "%-12s -> %s\n", $ext, $Language_by_Extension{$ext};
- }
- }
-} # 1}}}
-sub print_language_info { # {{{1
- my ($language,) = @_;
- my %extensions = (); # the subset matched by the given $language value
- if ($language) { # show information on this language
- foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
- # Language_by_Extension{f} = 'Fortran 77'
- push @{$extensions{$Language_by_Extension{$ext}} }, $ext
- if $Language_by_Extension{$ext} =~ m{$language}i;
- }
- } else { # show information on all languages
- foreach my $ext (sort {lc $a cmp lc $b } keys %Language_by_Extension) {
- # Language_by_Extension{f} = 'Fortran 77'
- push @{$extensions{$Language_by_Extension{$ext}} }, $ext
- }
- }
-
- # add exceptions (one file extension mapping to multiple languages)
- if (!$language or
- $language =~ /^(Objective C|MATLAB|MUMPS)$/i) {
- push @{$extensions{'Objective C'}}, "m";
- push @{$extensions{'MATLAB'}} , "m";
- push @{$extensions{'MUMPS'}} , "m";
- delete $extensions{'MATLAB/Objective C/MUMPS'};
- }
-
- if (%extensions) {
- foreach my $lang (sort {lc $a cmp lc $b } keys %extensions) {
- printf "%-26s (%s)\n", $lang, join(", ", @{$extensions{$lang}});
- }
- }
-} # 1}}}
-sub make_file_list { # {{{1
- my ($ra_arg_list, # in file and/or directory names to examine
- $rh_Err , # in hash of error codes
- $raa_errors , # out errors encountered
- $rh_ignored , # out files not recognized as computer languages
- ) = @_;
-
- my ($fh, $filename);
- if ($opt_categorized) {
- $filename = $opt_categorized;
- $fh = new IO::File $filename, "+>"; # open for read/write
- die "Unable to write to $filename: $!\n" unless defined $fh;
- } elsif ($opt_sdir) {
- # write to the user-defined scratch directory
- $filename = $opt_sdir . '/cloc_file_list.txt';
- $fh = new IO::File $filename, "+>"; # open for read/write
- die "Unable to write to $filename: $!\n" unless defined $fh;
- } else {
- # let File::Temp create a suitable temporary file
- ($fh, $filename) = tempfile(UNLINK => 1); # delete file on exit
- print "Using temp file list [$filename]\n" if $opt_v;
- }
-
- my @dir_list = ();
- foreach my $file_or_dir (@{$ra_arg_list}) {
-#print "make_file_list file_or_dir=$file_or_dir\n";
- my $size_in_bytes = 0;
- if (!-r $file_or_dir) {
- push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file_or_dir];
- next;
- }
- if (is_file($file_or_dir)) {
- if (!(-s $file_or_dir)) { # 0 sized file, named pipe, socket
- $rh_ignored->{$file_or_dir} = 'zero sized file';
- next;
- } elsif (-B $file_or_dir) { # avoid binary files
- if ($opt_unicode) {
- # only ignore if not a Unicode file w/trivial
- # ASCII transliteration
- if (!unicode_file($file_or_dir)) {
- $rh_ignored->{$file_or_dir} = 'binary file';
- next;
- }
- } else {
- $rh_ignored->{$file_or_dir} = 'binary file';
- next;
- }
- }
- push @file_list, "$file_or_dir";
- } elsif (is_dir ($file_or_dir)) {
- push @dir_list, $file_or_dir;
- } else {
- push @{$raa_errors}, [$rh_Err->{'Neither file nor directory'} , $file_or_dir];
- $rh_ignored->{$file_or_dir} = 'not file, not directory';
- }
- }
- foreach my $dir (@dir_list) {
-#print "make_file_list dir=$dir\n";
- find(\&files, $dir); # populates global variable @file_list
- }
- $nFiles_Found = scalar @file_list;
- printf "%8d text file%s.\n", plural_form($nFiles_Found) unless $opt_quiet;
- write_file($opt_found, sort @file_list) if $opt_found;
-
- my $nFiles_Categorized = 0;
- foreach my $file (@file_list) {
- printf "classifying $file\n" if $opt_v > 2;
-
- my $basename = basename $file;
- if ($Not_Code_Filename{$basename}) {
- $rh_ignored->{$file} = "listed in " . '$' .
- "Not_Code_Filename{$basename}";
- next;
- } elsif ($basename =~ m{~$}) {
- $rh_ignored->{$file} = "temporary editor file";
- next;
- }
-
- my $size_in_bytes = (stat $file)[7];
- my $language = "";
- if ($All_One_Language) {
- # user over-rode auto-language detection by using
- # --force-lang with just a language name (no extension)
- $language = $All_One_Language;
- } else {
- $language = classify_file($file ,
- $rh_Err ,
- $raa_errors,
- $rh_ignored);
- }
-die "make_file_list($file) undef size" unless defined $size_in_bytes;
-die "make_file_list($file) undef lang" unless defined $language;
- printf $fh "%d,%s,%s\n", $size_in_bytes, $language, $file;
- ++$nFiles_Categorized;
- #printf "classified %d files\n", $nFiles_Categorized
- # unless (!$opt_progress_rate or
- # ($nFiles_Categorized % $opt_progress_rate));
- }
- printf "classified %d files\n", $nFiles_Categorized
- if !$opt_quiet and $nFiles_Categorized > 1;
-
- return $fh; # handle to the file containing the list of files to process
-} # 1}}}
-sub remove_duplicate_files { # {{{1
- my ($fh , # in
- $rh_Language , # out
- $rh_unique_source_file, # out
- $rh_Err , # in
- $raa_errors , # out errors encountered
- $rh_ignored , # out
- ) = @_;
-
- # Check for duplicate files by comparing file sizes.
- # Where files are equally sized, compare their MD5 checksums.
-
- my $n = 0;
- my %files_by_size = (); # files_by_size{ # bytes } = [ list of files ]
- seek($fh, 0, 0); # rewind to beginning of the temp file
- while (<$fh>) {
- ++$n;
- my ($size_in_bytes, $language, $file) = split(/,/, $_, 3);
- chomp($file);
- $rh_Language->{$file} = $language;
- push @{$files_by_size{$size_in_bytes}}, $file;
- }
- if ($opt_progress_rate and ($n > $opt_progress_rate)) {
- printf "Duplicate file check %d files (%d known unique)\r",
- $n, scalar keys %files_by_size;
- }
- $n = 0;
- foreach my $bytes (sort {$a <=> $b} keys %files_by_size) {
- ++$n;
- printf "Unique: %8d files \r",
- $n unless (!$opt_progress_rate or ($n % $opt_progress_rate));
- $rh_unique_source_file->{$files_by_size{$bytes}[0]} = 1;
- next unless scalar @{$files_by_size{$bytes}} > 1;
- foreach my $F (different_files(\@{$files_by_size{$bytes}},
- $rh_Err ,
- $raa_errors ,
- $rh_ignored ) ) {
- $rh_unique_source_file->{$F} = 1;
- }
- }
-} # 1}}}
-sub files { # {{{1
- # invoked by File::Find's find() Populates global variable @file_list
- if ($opt_exclude_dir) {
- my $return = 0;
- foreach my $skip_dir (keys %Exclude_Dir) {
- if ($File::Find::dir =~ m{/$skip_dir(/|$)} ) {
- $Ignored{$File::Find::name} = "--exclude_dir=$skip_dir";
- $return = 1;
- last;
- }
- }
- return if $return;
- }
- my $nBytes = -s $_ ;
- if (!$nBytes and $opt_v > 5) {
- printf "files(%s) zero size\n", $File::Find::name;
- }
- return unless $nBytes ; # attempting other tests w/pipe or socket will hang
- my $is_dir = is_dir($_);
- my $is_bin = -B $_ ;
- printf "files(%s) size=%d is_dir=%d -B=%d\n",
- $File::Find::name, $nBytes, $is_dir, $is_bin if $opt_v > 5;
- $is_bin = 0 if $opt_unicode and unicode_file($_);
- return if $is_dir or $is_bin;
- ++$nFiles_Found;
- printf "%8d files\r", $nFiles_Found
- unless (!$opt_progress_rate or ($nFiles_Found % $opt_progress_rate));
- push @file_list, $File::Find::name;
-} # 1}}}
-sub archive_files { # {{{1
- # invoked by File::Find's find() Populates global variable @binary_archive
- foreach my $ext (keys %Known_Binary_Archives) {
- push @binary_archive, $File::Find::name
- if $File::Find::name =~ m{$ext$};
- }
-} # 1}}}
-sub is_file { # {{{1
- # portable method to test if item is a file
- # (-f doesn't work in ActiveState Perl on Windows)
- my $item = shift @_;
-
- if ($ON_WINDOWS) {
- my $mode = (stat $item)[2];
- $mode = 0 unless $mode;
- if ($mode & 0100000) { return 1; }
- else { return 0; }
- } else {
- return (-f $item); # works on Unix, Linux, CygWin, z/OS
- }
-} # 1}}}
-sub is_dir { # {{{1
- # portable method to test if item is a directory
- # (-d doesn't work in ActiveState Perl on Windows)
- my $item = shift @_;
-
- if ($ON_WINDOWS) {
- my $mode = (stat $item)[2];
- $mode = 0 unless $mode;
- if ($mode & 0040000) { return 1; }
- else { return 0; }
- } else {
- return (-d $item); # works on Unix, Linux, CygWin, z/OS
- }
-} # 1}}}
-sub classify_file { # {{{1
- my ($full_file , # in
- $rh_Err , # in hash of error codes
- $raa_errors , # out
- $rh_ignored , # out
- ) = @_;
-
- print "-> classify_file($full_file)\n" if $opt_v > 2;
- my $language = "(unknown)";
-
- my $look_at_first_line = 0;
- my $file = basename $full_file;
- return $language if $Not_Code_Filename{$file}; # (unknown)
- return $language if $file =~ m{~$}; # a temp edit file (unknown)
-
- if ($file =~ /\.(\w+)$/) { # has an extension
- print "$full_file extension=[$1]\n" if $opt_v > 2;
- my $extension = $1;
- if ($Not_Code_Extension{$extension} and
- !$Forced_Extension{$extension}) {
- # If .1 (for example) is an extention that would ordinarily be
- # ignored but the user has insisted this be counted with the
- # --force-lang option, then go ahead and count it.
- $rh_ignored->{$full_file} =
- 'listed in $Not_Code_Extension{' . $extension . '}';
- return $language;
- }
- if (defined $Language_by_Extension{$extension}) {
- if ($Language_by_Extension{$extension} eq
- 'MATLAB/Objective C/MUMPS') {
- my $lang_M_or_O = "";
- matlab_or_objective_C($full_file ,
- $rh_Err ,
- $raa_errors,
- \$lang_M_or_O);
- if ($lang_M_or_O) {
- return $lang_M_or_O;
- } else { # an error happened in matlab_or_objective_C()
- $rh_ignored->{$full_file} =
- 'failure in matlab_or_objective_C()';
- return $language; # (unknown)
- }
- } else {
- return $Language_by_Extension{$extension};
- }
- } else { # has an unmapped file extension
- $look_at_first_line = 1;
- }
- } elsif (defined $Language_by_File{lc $file}) {
- return $Language_by_File{lc $file};
- } else { # no file extension
- $look_at_first_line = 1;
- }
-
- if ($look_at_first_line) {
- # maybe it is a shell/Perl/Python/Ruby/etc script that
- # starts with pound bang:
- # #!/usr/bin/perl
- # #!/usr/bin/env perl
- my $script_language = peek_at_first_line($full_file ,
- $rh_Err ,
- $raa_errors);
- if (!$script_language) {
- $rh_ignored->{$full_file} = "language unknown (#2)";
- # returns (unknown)
- }
- if (defined $Language_by_Script{$script_language}) {
- if (defined $Filters_by_Language{
- $Language_by_Script{$script_language}}) {
- $language = $Language_by_Script{$script_language};
- } else {
- $rh_ignored->{$full_file} =
- "undefined: Filters_by_Language{" .
- $Language_by_Script{$script_language} .
- "} for scripting language $script_language";
- # returns (unknown)
- }
- } else {
- $rh_ignored->{$full_file} = "language unknown (#3)";
- # returns (unknown)
- }
- }
- print "<- classify_file($full_file)\n" if $opt_v > 2;
- return $language;
-} # 1}}}
-sub peek_at_first_line { # {{{1
- my ($file , # in
- $rh_Err , # in hash of error codes
- $raa_errors , # out
- ) = @_;
-
- print "-> peek_at_first_line($file)\n" if $opt_v > 2;
-
- my $script_language = "";
- if (!-r $file) {
- push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
- return $script_language;
- }
- my $IN = new IO::File $file, "r";
- if (!defined $IN) {
- push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
- print "<- peek_at_first_line($file)\n" if $opt_v > 2;
- return $script_language;
- }
- chomp(my $first_line = <$IN>);
- if (defined $first_line) {
-#print "peek_at_first_line of [$file] first_line=[$first_line]\n";
- if ($first_line =~ /^#\!\s*(\S.*?)$/) {
-#print "peek_at_first_line 1=[$1]\n";
- my @pound_bang = split(' ', $1);
-#print "peek_at_first_line basename 0=[", basename($pound_bang[0]), "]\n";
- if (basename($pound_bang[0]) eq "env" and
- scalar @pound_bang > 1) {
- $script_language = $pound_bang[1];
-#print "peek_at_first_line pound_bang A $pound_bang[1]\n";
- } else {
- $script_language = basename $pound_bang[0];
-#print "peek_at_first_line pound_bang B $script_language\n";
- }
- }
- }
- $IN->close;
- print "<- peek_at_first_line($file)\n" if $opt_v > 2;
- return $script_language;
-} # 1}}}
-sub different_files { # {{{1
- # See which of the given files are unique by computing each file's MD5
- # sum. Return the subset of files which are unique.
- my ($ra_files , # in
- $rh_Err , # in
- $raa_errors , # out
- $rh_ignored , # out
- ) = @_;
-
- print "-> different_files(@{$ra_files})\n" if $opt_v > 2;
- my %file_hash = (); # file_hash{ md5 hash } = file name
- foreach my $F (@{$ra_files}) {
- next if is_dir($F); # needed for Windows
- my $IN = new IO::File $F, "r";
- if (!defined $IN) {
- push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $F];
- $rh_ignored->{$F} = 'cannot read';
- } else {
- if ($HAVE_Digest_MD5) {
- binmode $IN;
- $file_hash{ Digest::MD5->new->addfile($IN)->hexdigest } = $F;
- } else {
- # all files treated unique
- $file_hash{ $F } = $F;
- }
- $IN->close;
- }
- }
- my @unique = values %file_hash;
- print "<- different_files(@unique)\n" if $opt_v > 2;
- return @unique;
-} # 1}}}
-sub call_counter { # {{{1
- my ($file , # in
- $language, # in
- ) = @_;
-
- # Logic: pass the file through the following filters:
- # 1. remove blank lines
- # 2. remove comments using each filter defined for this language
- # (example: SQL has two, remove_starts_with(--) and
- # remove_c_comments() )
- # 3. compute comment lines as
- # total lines - blank lines - lines left over after all
- # comment filters have been applied
-
- print "-> call_counter($file, $language)\n" if $opt_v > 2;
-#print "call_counter: ", Dumper(@routines), "\n";
-
- my @lines = ();
- my $ascii = "";
- if (-B $file and $opt_unicode) {
- # was binary so must be unicode
-
- $/ = undef;
- my $IN = new IO::File $file, "r";
- my $bin_text = <$IN>;
- $IN->close;
- $/ = "\n";
-
- $ascii = unicode_to_ascii( $bin_text );
- @lines = split("\n", $ascii );
- foreach (@lines) { $_ = "$_\n"; }
-
- } else {
- # regular text file
- @lines = read_file($file);
- $ascii = join('', @lines);
- }
-
- my @original_lines = @lines;
- my $total_lines = scalar @lines;
-
- print_lines($file, "Original file:", \@lines) if $opt_print_filter_stages;
- @lines = rm_blanks(\@lines, $language); # remove blank lines
- my $blank_lines = $total_lines - scalar @lines;
- print_lines($file, "Blank lines removed:", \@lines)
- if $opt_print_filter_stages;
-
- @lines = rm_comments(\@lines, $language, $file);
-
- my $comment_lines = $total_lines - $blank_lines - scalar @lines;
- if ($opt_strip_comments) {
- my $stripped_file = basename $file . ".$opt_strip_comments";
- write_file($stripped_file, @lines);
- }
- if ($opt_html) {
- chomp(@original_lines); # includes blank lines, comments
- chomp(@lines); # no blank lines, no comments
-
- my (@diff_L, @diff_R, %count);
-
- # remove blank lines to get better quality diffs; count
- # blank lines separately
- my @original_lines_minus_white = ();
- # however must keep track of how many blank lines were removed and
- # where they were removed so that the HTML display can include it
- my %blank_line = ();
- my $insert_line = 0;
- foreach (@original_lines) {
- if (/^\s*$/) {
- ++$count{blank}{same};
- ++$blank_line{ $insert_line };
- } else {
- ++$insert_line;
- push @original_lines_minus_white, $_;
- }
- }
-
- file_diff(\@original_lines_minus_white , # in
- \@lines , # in
- "comment" , # in
- \@diff_L, \@diff_R, \%count); # out
- write_comments_to_html($file, \@diff_L, \@diff_R, \%blank_line);
-#print Dumper("count", \%count);
- }
-
- print "<- call_counter($total_lines, $blank_lines, $comment_lines)\n"
- if $opt_v > 2;
- return ($total_lines, $blank_lines, $comment_lines);
-} # 1}}}
-sub write_file { # {{{1
- my ($file , # in
- @lines , # in
- ) = @_;
-
- print "-> write_file($file)\n" if $opt_v > 2;
-
- # Create the destination directory if it doesn't already exist.
- my $abs_file_path = File::Spec->rel2abs( $file );
- my ($volume, $directories, $filename) = File::Spec->splitpath( $abs_file_path );
- mkpath($volume . $directories, 1, 0777);
-
- my $OUT = new IO::File $file, "w";
- if (defined $OUT) {
- chomp(@lines);
- print $OUT join("\n", @lines), "\n";
- $OUT->close;
- } else {
- warn "Unable to write to $file\n";
- }
- print "Wrote $file\n";
-
- print "<- write_file\n" if $opt_v > 2;
-} # 1}}}
-sub read_file { # {{{1
- my ($file, ) = @_;
-
- print "-> read_file($file)\n" if $opt_v > 2;
- my @lines = ();
- my $IN = new IO::File $file, "r";
- if (defined $IN) {
- @lines = <$IN>;
- $IN->close;
- # Some files don't end with a new line. Force this:
- $lines[$#lines] .= "\n" unless $lines[$#lines] =~ m/\n$/;
- } else {
- warn "Unable to read $file\n";
- }
- print "<- read_file\n" if $opt_v > 2;
- return @lines;
-} # 1}}}
-sub rm_blanks { # {{{1
- my ($ra_in, $language) = @_;
-
- my @out = ();
- if ($language eq "COBOL") {
- @out = remove_cobol_blanks($ra_in);
- } else {
- @out = remove_matches($ra_in, '^\s*$'); # removes blank lines
- }
- return @out;
-} # 1}}}
-sub rm_comments { # {{{1
- my ($ra_lines , # in, must be free of blank lines
- $language , # in
- $file , # in (some language counters, eg Haskell, need
- # access to the original file)
- ) = @_;
- my @routines = @{$Filters_by_Language{$language}};
- my @lines = @{$ra_lines};
- my @original_lines = @{$ra_lines};
-
- foreach my $call_string (@routines) {
- my $subroutine = $call_string->[0];
- if (! defined &{$subroutine}) {
- warn "rm_comments undefined subroutine $subroutine for $file\n";
- next;
- }
- print "rm_comments file=$file sub=$subroutine\n" if $opt_v > 1;
- my @args = @{$call_string};
- shift @args; # drop the subroutine name
- if (@args and $args[0] eq '>filename<') {
- shift @args;
- unshift @args, $file;
- }
-
- no strict 'refs';
- @lines = &{$subroutine}(\@lines, @args); # apply filter...
-
- print_lines($file, "After $subroutine(@args)", \@lines)
- if $opt_print_filter_stages;
- @lines = remove_matches(\@lines, '^\s*$'); # then remove blank lines
-
- print_lines($file, "post $subroutine(@args) blank cleanup:", \@lines)
- if $opt_print_filter_stages;
- }
- # Exception for scripting languages: treat the first #! line as code.
- # Will need to add it back in if it was removed earlier.
- if ($Script_Language{$language} and
- $original_lines[0] =~ /^#!/ and
- $lines[0] ne $original_lines[0]) {
- unshift @lines, $original_lines[0]; # add the first line back
- }
- return @lines;
-} # 1}}}
-sub remove_f77_comments { # {{{1
- my ($ra_lines, ) = @_;
- print "-> remove_f77_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- foreach (@{$ra_lines}) {
- next if m{^[*cC]};
- push @save_lines, $_;
- }
-
- print "<- remove_f77_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_f90_comments { # {{{1
- # derived from SLOCCount
- my ($ra_lines, ) = @_;
- print "-> remove_f90_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- foreach (@{$ra_lines}) {
- # a comment is m/^\s*!/
- # an empty line is m/^\s*$/
- # a HPF statement is m/^\s*!hpf\$/i
- # an Open MP statement is m/^\s*!omp\$/i
- if (! m/^(\s*!|\s*$)/ || m/^\s*!(hpf|omp)\$/i) {
- push @save_lines, $_;
- }
- }
-
- print "<- remove_f90_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_matches { # {{{1
- my ($ra_lines, # in
- $pattern , # in Perl regular expression (case insensitive)
- ) = @_;
- print "-> remove_matches(pattern=$pattern)\n" if $opt_v > 2;
-
- my @save_lines = ();
- foreach (@{$ra_lines}) {
-#chomp; print "remove_matches [$pattern] [$_]\n";
- next if m{$pattern}i;
- push @save_lines, $_;
- }
-
- print "<- remove_matches\n" if $opt_v > 2;
-#print "remove_matches returning\n ", join("\n ", @save_lines), "\n";
- return @save_lines;
-} # 1}}}
-sub remove_above { # {{{1
- my ($ra_lines, $marker, ) = @_;
- print "-> remove_above(marker=$marker)\n" if $opt_v > 2;
-
- # Make two passes through the code:
- # 1. check if the marker exists
- # 2. remove anything above the marker if it exists,
- # do nothing if the marker does not exist
-
- # Pass 1
- my $found_marker = 0;
- for (my $line_number = 1;
- $line_number <= scalar @{$ra_lines};
- $line_number++) {
- if ($ra_lines->[$line_number-1] =~ m{$marker}) {
- $found_marker = $line_number;
- last;
- }
- }
-
- # Pass 2 only if needed
- my @save_lines = ();
- if ($found_marker) {
- my $n = 1;
- foreach (@{$ra_lines}) {
- push @save_lines, $_
- if $n >= $found_marker;
- ++$n;
- }
- } else { # marker wasn't found; save all lines
- foreach (@{$ra_lines}) {
- push @save_lines, $_;
- }
- }
-
- print "<- remove_above\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_below { # {{{1
- my ($ra_lines, $marker, ) = @_;
- print "-> remove_below(marker=$marker)\n" if $opt_v > 2;
-
- my @save_lines = ();
- foreach (@{$ra_lines}) {
- last if m{$marker};
- push @save_lines, $_;
- }
-
- print "<- remove_below\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_between { # {{{1
- my ($ra_lines, $marker, ) = @_;
- # $marker must contain one of the balanced pairs understood
- # by Regexp::Common::balanced, namely
- # '{}' '()' '[]' or '<>'
-
- print "-> remove_between(marker=$marker)\n" if $opt_v > 2;
- my %acceptable = ('{}'=>1, '()'=>1, '[]'=>1, '<>'=>1, );
- die "remove_between: invalid delimiter '$marker'\n",
- "the delimiter must be one of these four pairs:\n",
- "{} () [] <>\n" unless
- $acceptable{$marker};
-
- Install_Regexp_Common() unless $HAVE_Rexexp_Common;
-
- my $all_lines = join("", @{$ra_lines});
-
- no strict 'vars';
- # otherwise get:
- # Global symbol "%RE" requires explicit package name at cloc line xx.
- if ($all_lines =~ m/$RE{balanced}{-parens => $marker}/) {
- no warnings;
- $all_lines =~ s/$1//g;
- }
-
- print "<- remove_between\n" if $opt_v > 2;
- return split("\n", $all_lines);
-} # 1}}}
-sub remove_cobol_blanks { # {{{1
- # subroutines derived from SLOCCount
- my ($ra_lines, ) = @_;
-
- my $free_format = 0; # Support "free format" source code.
- my @save_lines = ();
-
- foreach (@{$ra_lines}) {
- next if m/^\s*$/;
- my $line = expand($_); # convert tabs to equivalent spaces
- $free_format = 1 if $line =~ m/^......\$.*SET.*SOURCEFORMAT.*FREE/i;
- if ($free_format) {
- push @save_lines, $_;
- } else {
- push @save_lines, $_ unless m/^\d{6}\s*$/ or
- ($line =~ m/^\d{6}\s{66}/);
- }
- }
- return @save_lines;
-} # 1}}}
-sub remove_cobol_comments { # {{{1
- # subroutines derived from SLOCCount
- my ($ra_lines, ) = @_;
-
- my $free_format = 0; # Support "free format" source code.
- my @save_lines = ();
-
- foreach (@{$ra_lines}) {
- if (m/^......\$.*SET.*SOURCEFORMAT.*FREE/i) {$free_format = 1;}
- if ($free_format) {
- push @save_lines, $_ unless m{^\s*\*};
- } else {
- push @save_lines, $_ unless m{^......\*} or m{^\*};
- }
- }
- return @save_lines;
-} # 1}}}
-sub remove_jcl_comments { # {{{1
- my ($ra_lines, ) = @_;
-
- print "-> remove_jcl_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- my $in_comment = 0;
- foreach (@{$ra_lines}) {
- next if /^\s*$/;
- next if m{^\s*//\*};
- last if m{^\s*//\s*$};
- push @save_lines, $_;
- }
-
- print "<- remove_jcl_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_jsp_comments { # {{{1
- # JSP comment is <%-- body of comment --%>
- my ($ra_lines, ) = @_;
-
- print "-> remove_jsp_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- my $in_comment = 0;
- foreach (@{$ra_lines}) {
-
- next if /^\s*$/;
- s/<\%\-\-.*?\-\-\%>//g; # strip one-line comments
- next if /^\s*$/;
- if ($in_comment) {
- if (/\-\-\%>/) {
- s/^.*?\-\-\%>//;
- $in_comment = 0;
- }
- }
- next if /^\s*$/;
- $in_comment = 1 if /^(.*?)<\%\-\-/;
- next if defined $1 and $1 =~ /^\s*$/;
- next if ($in_comment);
- push @save_lines, $_;
- }
-
- print "<- remove_jsp_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub remove_html_comments { # {{{1
- # HTML comment is <!-- body of comment -->
- # Need to use my own routine until the HTML comment regex in
- # the Regexp::Common module can handle <!-- -- -->
- my ($ra_lines, ) = @_;
-
- print "-> remove_html_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- my $in_comment = 0;
- foreach (@{$ra_lines}) {
-
- next if /^\s*$/;
- s/<!\-\-.*?\-\->//g; # strip one-line comments
- next if /^\s*$/;
- if ($in_comment) {
- if (/\-\->/) {
- s/^.*?\-\->//;
- $in_comment = 0;
- }
- }
- next if /^\s*$/;
- $in_comment = 1 if /^(.*?)<!\-\-/;
- next if defined $1 and $1 =~ /^\s*$/;
- next if ($in_comment);
- push @save_lines, $_;
- }
-
- print "<- remove_html_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub determine_lit_type { # {{{1
- my ($file) = @_;
-
- open (FILE, $file);
- while (<FILE>) {
- if (m/^\\begin{code}/) { close FILE; return 2; }
- if (m/^>\s/) { close FILE; return 1; }
- }
-
- return 0;
-} # 1}}}
-sub remove_haskell_comments { # {{{1
- # Bulk of code taken from SLOCCount's haskell_count script.
- # Strips out {- .. -} and -- comments and counts the rest.
- # Pragmas, {-#...}, are counted as SLOC.
- # BUG: Doesn't handle strings with embedded block comment markers gracefully.
- # In practice, that shouldn't be a problem.
- my ($ra_lines, $file, ) = @_;
-
- print "-> remove_haskell_comments\n" if $opt_v > 2;
-
- my @save_lines = ();
- my $in_comment = 0;
- my $incomment = 0;
- my ($literate, $inlitblock) = (0,0);
-
- $literate = 1 if $file =~ /\.lhs$/;
- if($literate) { $literate = determine_lit_type($file) }
-
- foreach (@{$ra_lines}) {
- if ($literate == 1) {
- if (!s/^>//) { s/.*//; }
- } elsif ($literate == 2) {
- if ($inlitblock) {
- if (m/^\\end{code}/) { s/.*//; $inlitblock = 0; }
- } elsif (!$inlitblock) {
- if (m/^\\begin{code}/) { s/.*//; $inlitblock = 1; }
- else { s/.*//; }
- }
- }
-
- if ($incomment) {
- if (m/\-\}/) { s/^.*?\-\}//; $incomment = 0;}
- else { s/.*//; }
- }
- if (!$incomment) {
- s/--.*//;
- s!{-[^#].*?-}!!g;
- if (m/{-/ && (!m/{-#/)) {
- s/{-.*//;
- $incomment = 1;
- }
- }
- if (m/\S/) { push @save_lines, $_; }
- }
-# if ($incomment) {print "ERROR: ended in comment in $ARGV\n";}
-
- print "<- remove_haskell_comments\n" if $opt_v > 2;
- return @save_lines;
-} # 1}}}
-sub print_lines { # {{{1
- my ($file , # in
- $title , # in
- $ra_lines , # in
- ) = @_;
- printf "->%-30s %s\n", $file, $title;
- for (my $i = 0; $i < scalar @{$ra_lines}; $i++) {
- printf "%5d | %s", $i+1, $ra_lines->[$i];
- print "\n" unless $ra_lines->[$i] =~ m{\n$}
- }
-} # 1}}}
-sub set_constants { # {{{1
- my ($rh_Language_by_Extension , # out
- $rh_Language_by_Script , # out
- $rh_Language_by_File , # out
- $rhaa_Filters_by_Language , # out
- $rh_Not_Code_Extension , # out
- $rh_Not_Code_Filename , # out
- $rh_Scale_Factor , # out
- $rh_Known_Binary_Archives , # out
- ) = @_;
-# 1}}}
-%{$rh_Language_by_Extension} = ( # {{{1
- 'abap' => 'ABAP' ,
- 'ac' => 'm4' ,
- 'ada' => 'Ada' ,
- 'adb' => 'Ada' ,
- 'ads' => 'Ada' ,
- 'adso' => 'ADSO/IDSM' ,
- 'am' => 'make' ,
- 'ample' => 'AMPLE' ,
- 'dofile' => 'AMPLE' ,
- 'startup' => 'AMPLE' ,
- 'asa' => 'ASP' ,
- 'asax' => 'ASP.Net' ,
- 'ascx' => 'ASP.Net' ,
- 'asm' => 'Assembler' ,
- 'asmx' => 'ASP.Net' ,
- 'asp' => 'ASP' ,
- 'aspx' => 'ASP.Net' ,
- 'master' => 'ASP.Net' ,
- 'sitemap' => 'ASP.Net' ,
- 'awk' => 'awk' ,
- 'bash' => 'Bourne Again Shell' ,
- 'bas' => 'Visual Basic' ,
- 'bat' => 'DOS Batch' ,
- 'BAT' => 'DOS Batch' ,
- 'cbl' => 'COBOL' ,
- 'CBL' => 'COBOL' ,
- 'c' => 'C' ,
- 'C' => 'C++' ,
- 'cc' => 'C++' ,
- 'ccs' => 'CCS' ,
- 'cfm' => 'ColdFusion' ,
- 'cl' => 'Lisp' ,
- 'cls' => 'Visual Basic' ,
- 'cob' => 'COBOL' ,
- 'COB' => 'COBOL' ,
- 'config' => 'ASP.Net' ,
- 'cpp' => 'C++' ,
- 'cs' => 'C#' ,
- 'csh' => 'C Shell' ,
- 'css' => "CSS" ,
- 'cxx' => 'C++' ,
- 'da' => 'DAL' ,
- 'def' => 'Teamcenter def' ,
- 'dmap' => 'NASTRAN DMAP' ,
- 'dpr' => 'Pascal' ,
- 'dtd' => 'DTD' ,
- 'ec' => 'C' ,
- 'el' => 'Lisp' ,
- 'exp' => 'Expect' ,
- 'f77' => 'Fortran 77' ,
- 'F77' => 'Fortran 77' ,
- 'f90' => 'Fortran 90' ,
- 'F90' => 'Fortran 90' ,
- 'f95' => 'Fortran 95' ,
- 'F95' => 'Fortran 95' ,
- 'f' => 'Fortran 77' ,
- 'F' => 'Fortran 77' ,
- 'fmt' => 'Oracle Forms' ,
- 'focexec' => 'Focus' ,
- 'frm' => 'Visual Basic' ,
- 'gnumakefile' => 'make' ,
- 'Gnumakefile' => 'make' ,
- 'h' => 'C/C++ Header' ,
- 'H' => 'C/C++ Header' ,
- 'hh' => 'C/C++ Header' ,
- 'hpp' => 'C/C++ Header' ,
- 'hs' => 'Haskell' ,
- 'htm' => 'HTML' ,
- 'html' => 'HTML' ,
- 'i3' => 'Modula3' ,
- 'idl' => 'IDL' ,
- 'ig' => 'Modula3' ,
- 'il' => 'SKILL' ,
- 'ils' => 'SKILL++' ,
- 'inc' => 'inc' , # might be PHP
- 'itk' => 'Tcl/Tk' ,
- 'java' => 'Java' ,
- 'jcl' => 'JCL' , # IBM Job Control Lang.
- 'jl' => 'Lisp' ,
- 'js' => 'Javascript' ,
- 'jsp' => 'JSP' , # Java server pages
- 'ksh' => 'Korn Shell' ,
- 'lhs' => 'Haskell' ,
- 'l' => 'lex' ,
- 'lsp' => 'Lisp' ,
- 'lua' => 'Lua' ,
- 'm3' => 'Modula3' ,
- 'm4' => 'm4' ,
- 'makefile' => 'make' ,
- 'Makefile' => 'make' ,
- 'met' => 'Teamcenter met' ,
- 'mg' => 'Modula3' ,
- 'mli' => 'ML' ,
- 'ml' => 'ML' ,
- 'm' => 'MATLAB/Objective C/MUMPS' ,
- 'wdproj' => 'MSBuild scripts' ,
- 'csproj' => 'MSBuild scripts' ,
- 'mps' => 'MUMPS' ,
- 'mth' => 'Teamcenter mth' ,
- 'oscript' => 'LiveLink OScript' ,
- 'pad' => 'Ada' , # Oracle Ada preprocessor
- 'pas' => 'Pascal' ,
- 'pcc' => 'C++' , # Oracle C++ preprocessor
- 'perl' => 'Perl' ,
- 'pfo' => 'Fortran 77' ,
- 'pgc' => 'C' , # Postgres embedded C/C++
- 'php3' => 'PHP' ,
- 'php4' => 'PHP' ,
- 'php5' => 'PHP' ,
- 'php' => 'PHP' ,
- 'plh' => 'Perl' ,
- 'pl' => 'Perl' ,
- 'PL' => 'Perl' ,
- 'plx' => 'Perl' ,
- 'pm' => 'Perl' ,
- 'p' => 'Pascal' ,
- 'pp' => 'Pascal' ,
- 'psql' => 'SQL' ,
- 'py' => 'Python' ,
- 'rb' => 'Ruby' ,
- # 'resx' => 'ASP.Net' ,
- 'rex' => 'Oracle Reports' ,
- 'rexx' => 'Rexx' ,
- 's' => 'Assembler' ,
- 'S' => 'Assembler' ,
- 'sbl' => 'Softbridge Basic' ,
- 'SBL' => 'Softbridge Basic' ,
- 'sc' => 'Lisp' ,
- 'scm' => 'Lisp' ,
- 'sed' => 'sed' ,
- 'ses' => 'Patran Command Language' ,
- 'pcl' => 'Patran Command Language' ,
- 'sh' => 'Bourne Shell' ,
- 'sql' => 'SQL' ,
- 'SQL' => 'SQL' ,
- 'tcl' => 'Tcl/Tk' ,
- 'tcsh' => 'C Shell' ,
- 'tk' => 'Tcl/Tk' ,
- 'vba' => 'Visual Basic' ,
- 'VBA' => 'Visual Basic' ,
- # 'vbp' => 'Visual Basic' , # .vbp - autogenerated
- 'vb' => 'Visual Basic' ,
- 'VB' => 'Visual Basic' ,
- # 'vbw' => 'Visual Basic' , # .vbw - autogenerated
- 'vbs' => 'Visual Basic' ,
- 'VBS' => 'Visual Basic' ,
- 'webinfo' => 'ASP.Net' ,
- 'xml' => 'XML' ,
- 'XML' => 'XML' ,
- 'build' => 'NAnt scripts' ,
- 'vim' => 'vim script' ,
- 'xsd' => 'XSD' ,
- 'XSD' => 'XSD' ,
- 'xslt' => 'XSLT' ,
- 'XSLT' => 'XSLT' ,
- 'xsl' => 'XSLT' ,
- 'XSL' => 'XSLT' ,
- 'y' => 'yacc' ,
- 'yaml' => 'YAML' ,
- 'yml' => 'YAML' ,
- );
-# 1}}}
-%{$rh_Language_by_Script} = ( # {{{1
- 'awk' => 'awk' ,
- 'bash' => 'Bourne Again Shell' ,
- 'bc' => 'bc' ,# calculator
- 'csh' => 'C Shell' ,
- 'idl' => 'IDL' ,
- 'ksh' => 'Korn Shell' ,
- 'lua' => 'Lua' ,
- 'make' => 'make' ,
- 'octave' => 'Octave' ,
- 'perl5' => 'Perl' ,
- 'perl' => 'Perl' ,
- 'ruby' => 'Ruby' ,
- 'sed' => 'sed' ,
- 'sh' => 'Bourne Shell' ,
- 'tcl' => 'Tcl/Tk' ,
- 'tclsh' => 'Tcl/Tk' ,
- 'tcsh' => 'C Shell' ,
- 'wish' => 'Tcl/Tk' ,
- );
-# 1}}}
-%{$rh_Language_by_File} = ( # {{{1
- 'Makefile' => 'make' ,
- 'makefile' => 'make' ,
- 'gnumakefile' => 'make' ,
- 'Gnumakefile' => 'make' ,
- );
-# 1}}}
-%{$rhaa_Filters_by_Language} = ( # {{{1
- 'ABAP' => [ [ 'remove_matches' , '^\*' ], ],
- 'ASP' => [ [ 'remove_matches' , '^\s*\47'], ], # \47 = '
- 'ASP.Net' => [ [ 'call_regexp_common' , 'C' ], ],
- 'Ada' => [ [ 'remove_matches' , '^\s*--' ], ],
- 'ADSO/IDSM' => [ [ 'remove_matches' , '^\s*\*[\+\!]' ], ],
- 'AMPLE' => [ [ 'remove_matches' , '^\s*//' ], ],
- 'Assembler' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'remove_matches' , '^\s*;' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'awk' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'bc' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'C' => [
- [ 'remove_matches' , '^\s*//' ], # C99
- [ 'call_regexp_common' , 'C' ], ],
- 'C++' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'C/C++ Header' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ], ],
- 'C#' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'CCS' => [ [ 'call_regexp_common' , 'C' ], ],
- 'CSS' => [ [ 'call_regexp_common' , 'C' ], ],
- 'COBOL' => [ [ 'remove_cobol_comments', ], ],
- 'ColdFusion' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'Crystal Reports' => [ [ 'remove_matches' , '^\s*//' ], ],
- 'DAL' => [ [ 'remove_between' , '[]', ], ],
- 'NASTRAN DMAP' => [ [ 'remove_matches' , '^\s*\$' ], ],
- 'DOS Batch' => [ [ 'remove_matches' , '^\s*rem', ], ],
- 'DTD' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'Expect' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Focus' => [ [ 'remove_matches' , '^\s*\-\*' ], ],
- 'Fortran 77' => [ [ 'remove_f77_comments' , ], ],
- 'Fortran 90' => [ [ 'remove_f77_comments' , ],
- [ 'remove_f90_comments' , ], ],
- 'Fortran 95' => [ [ 'remove_f77_comments' , ],
- [ 'remove_f90_comments' , ], ],
- 'HTML' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'Haskell' => [ [ 'remove_haskell_comments', '>filename<' ], ],
- 'IDL' => [ [ 'remove_matches' , '^\s*;' ], ],
- 'JSP' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ],
- [ 'remove_jsp_comments', ], ],
- 'Java' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'Javascript' => [
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'JCL' => [ [ 'remove_jcl_comments' , ], ],
- 'Lisp' => [ [ 'remove_matches' , '^\s*;' ], ],
- 'LiveLink OScript' => [ [ 'remove_matches' , '^\s*//' ], ],
-# 'Lua' => [ [ 'call_regexp_common' , 'lua' ], ],
- 'Lua' => [ [ 'remove_matches' , '^\s*\-\-' ], ],
- 'make' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'MATLAB' => [ [ 'remove_matches' , '^\s*%' ], ],
- 'Modula3' => [ [ 'call_regexp_common' , 'Pascal' ], ],
- # Modula 3 comments are (* ... *) so applying the Pascal filter
- # which also treats { ... } as a comment is not really correct.
- 'Objective C' => [ [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ], ],
- 'MATLAB/Objective C/MUMPS' => [ [ 'die' , ], ], # never called
- 'MUMPS' => [ [ 'remove_matches' , '^\s*;' ], ],
- 'Octave' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Oracle Forms' => [ [ 'call_regexp_common' , 'C' ], ],
- 'Oracle Reports' => [ [ 'call_regexp_common' , 'C' ], ],
- 'Pascal' => [ [ 'call_regexp_common' , 'Pascal' ], ],
- 'Patran Command Language'=> [
- [ 'remove_matches' , '^\s*#' ],
- [ 'remove_matches' , '^\s*\$#' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'Perl' => [ [ 'remove_below' , '^__(END|DATA)__'],
- [ 'remove_matches' , '^\s*#' ], ],
- 'Python' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'PHP' => [
- [ 'remove_matches' , '^\s*#' ],
- [ 'remove_matches' , '^\s*//' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'Rexx' => [ [ 'call_regexp_common' , 'C' ], ],
- 'Ruby' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'SKILL' => [
- [ 'remove_matches' , '^\s*;' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'SKILL++' => [
- [ 'remove_matches' , '^\s*;' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'SQL' => [
- [ 'remove_matches' , '^\s*--' ],
- [ 'call_regexp_common' , 'C' ],
- ],
- 'sed' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Bourne Again Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Bourne Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'm4' => [ [ 'remove_matches' , '^dnl ' ], ],
- 'C Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Korn Shell' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Tcl/Tk' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Teamcenter def' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Teamcenter met' => [ [ 'call_regexp_common' , 'C' ], ],
- 'Teamcenter mth' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'Softbridge Basic' => [ [ 'remove_above' , '^\s*Attribute\s+VB_Name\s+=' ],
- [ 'remove_matches' , '^\s*Attribute\s+'],
- [ 'remove_matches' , '^\s*\47'], ], # \47 = '
- 'vim script' => [ [ 'remove_matches' , '^\s*"' ], ],
- 'Visual Basic' => [ [ 'remove_above' , '^\s*Attribute\s+VB_Name\s+=' ],
- [ 'remove_matches' , '^\s*Attribute\s+'],
- [ 'remove_matches' , '^\s*\47'], ], # \47 = '
- 'yacc' => [ [ 'call_regexp_common' , 'C' ], ],
- 'YAML' => [ [ 'remove_matches' , '^\s*#' ], ],
- 'lex' => [ [ 'call_regexp_common' , 'C' ], ],
- 'XML' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'XSD' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'XSLT' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'NAnt scripts' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- 'MSBuild scripts' => [ [ 'remove_html_comments', ],
- [ 'call_regexp_common' , 'HTML' ], ],
- );
-# 1}}}
-%{$rh_Not_Code_Extension} = ( # {{{1
- '1' => 1, # Man pages (documentation):
- '2' => 1,
- '3' => 1,
- '4' => 1,
- '5' => 1,
- '6' => 1,
- '7' => 1,
- '8' => 1,
- '9' => 1,
- 'a' => 1, # Static object code.
- 'ad' => 1, # X application default resource file.
- 'afm' => 1, # font metrics
- 'arc' => 1, # arc(1) archive
- 'arj' => 1, # arj(1) archive
- 'au' => 1, # Audio sound filearj(1) archive
- 'bak' => 1, # Backup files - we only want to count the "real" files.
- 'bdf' => 1,
- 'bmp' => 1,
- 'bz2' => 1, # bzip2(1) compressed file
- 'csv' => 1, # comma separated values
- 'desktop' => 1,
- 'dic' => 1,
- 'doc' => 1,
- 'elc' => 1,
- 'eps' => 1,
- 'fig' => 1,
- 'gif' => 1,
- 'gz' => 1,
- 'hdf' => 1, # hierarchical data format
- 'in' => 1, # Debatable.
- 'jpg' => 1,
- 'kdelnk' => 1,
- 'man' => 1,
- 'mf' => 1,
- 'mp3' => 1,
- 'n' => 1,
- 'o' => 1, # Object code is generated from source code.
- 'pbm' => 1,
- 'pdf' => 1,
- 'pfb' => 1,
- 'png' => 1,
- 'po' => 1,
- 'ps' => 1, # Postscript is _USUALLY_ generated automatically.
- 'sgm' => 1,
- 'sgml' => 1,
- 'so' => 1, # Dynamically-loaded object code.
- 'Tag' => 1,
- 'tex' => 1,
- 'text' => 1,
- 'tfm' => 1,
- 'tgz' => 1, # gzipped tarball
- 'tiff' => 1,
- 'txt' => 1,
- 'vf' => 1,
- 'wav' => 1,
- 'xbm' => 1,
- 'xpm' => 1,
- 'Y' => 1, # file compressed with "Yabba"
- 'Z' => 1, # file compressed with "compress"
- 'zip' => 1, # zip archive
-); # 1}}}
-%{$rh_Not_Code_Filename} = ( # {{{1
- 'AUTHORS' => 1,
- 'README' => 1,
- 'Readme' => 1,
- 'readme' => 1,
- 'README.tk' => 1, # used in kdemultimedia, it's confusing.
- 'Changelog' => 1,
- 'ChangeLog' => 1,
- 'Repository' => 1,
- 'CHANGES' => 1,
- 'Changes' => 1,
- '.cvsignore' => 1,
- 'Root' => 1, # CVS
- 'BUGS' => 1,
- 'TODO' => 1,
- 'COPYING' => 1,
- 'MAINTAINERS' => 1,
- 'Entries' => 1,
- 'iconfig.h' => 1, # Skip "iconfig.h" files; they're used in Imakefiles
- # (used in xlockmore):
-);
-# 1}}}
-%{$rh_Scale_Factor} = ( # {{{1
- '1032/af' => 5.00,
- '1st generation default' => 0.25,
- '2nd generation default' => 0.75,
- '3rd generation default' => 1.00,
- '4th generation default' => 4.00,
- '5th generation default' => 16.00,
- 'aas macro' => 0.88,
- 'abap/4' => 5.00,
- 'ABAP' => 5.00,
- 'accel' => 4.21,
- 'access' => 2.11,
- 'actor' => 3.81,
- 'acumen' => 2.86,
- 'Ada' => 0.52,
- 'Ada 83' => 1.13,
- 'Ada 95' => 1.63,
- 'adr/dl' => 2.00,
- 'adr/ideal/pdl' => 4.00,
- 'ads/batch' => 4.00,
- 'ads/online' => 4.00,
- 'ADSO/IDSM' => 3.00,
- 'advantage' => 2.11,
- 'ai shell default' => 1.63,
- 'ai shells' => 1.63,
- 'algol 68' => 0.75,
- 'algol w' => 0.75,
- 'ambush' => 2.50,
- 'aml' => 1.63,
- 'AMPLE' => 2.00,
- 'amppl ii' => 1.25,
- 'ansi basic' => 1.25,
- 'ansi cobol 74' => 0.75,
- 'ansi cobol 85' => 0.88,
- 'SQL' => 6.15,
- 'answer/db' => 6.15,
- 'apl 360/370' => 2.50,
- 'apl default' => 2.50,
- 'apl*plus' => 2.50,
- 'applesoft basic' => 0.63,
- 'application builder' => 4.00,
- 'application manager' => 2.22,
- 'aps' => 0.96,
- 'aps' => 4.71,
- 'apt' => 1.13,
- 'aptools' => 4.00,
- 'arc' => 1.63,
- 'ariel' => 0.75,
- 'arity' => 1.63,
- 'arity prolog' => 1.25,
- 'art' => 1.63,
- 'art enterprise' => 1.74,
- 'artemis' => 2.00,
- 'artim' => 1.74,
- 'as/set' => 4.21,
- 'asi/inquiry' => 6.15,
- 'ask windows' => 1.74,
-'asa' => 1.29,
-'ASP' => 1.29,
-'ASP.Net' => 1.29,
-'aspx' => 1.29,
-#'resx' => 1.29,
-'asax' => 1.29,
-'ascx' => 1.29,
-'asmx' => 1.29,
-'config' => 1.29,
-'webinfo' => 1.29,
-'CCS' => 5.33,
-
-# 'assembler (basic)' => 0.25,
- 'Assembler' => 0.25,
-
- 'assembler (macro)' => 0.51,
- 'associative default' => 1.25,
- 'autocoder' => 0.25,
- 'awk' => 3.81,
- 'aztec c' => 0.63,
- 'balm' => 0.75,
- 'base sas' => 1.51,
- 'basic' => 0.75,
- 'basic a' => 0.63,
-# 'basic assembly' => 0.25,
- 'bc' => 1.50,
- 'berkeley pascal' => 0.88,
- 'better basic' => 0.88,
- 'bliss' => 0.75,
- 'bmsgen' => 2.22,
- 'boeingcalc' => 13.33,
- 'bteq' => 6.15,
-
- 'C' => 0.77,
-
- 'c set 2' => 0.88,
-
- 'C#' => 1.36,
-
- 'C++' => 1.51,
-
- 'c86plus' => 0.63,
- 'cadbfast' => 2.00,
- 'caearl' => 2.86,
- 'cast' => 1.63,
- 'cbasic' => 0.88,
- 'cdadl' => 4.00,
- 'cellsim' => 1.74,
-'ColdFusion' => 4.00,
- 'chili' => 0.75,
- 'chill' => 0.75,
- 'cics' => 1.74,
- 'clarion' => 1.38,
- 'clascal' => 1.00,
- 'cli' => 2.50,
- 'clipper' => 2.05,
- 'clipper db' => 2.00,
- 'clos' => 3.81,
- 'clout' => 2.00,
- 'cms2' => 0.75,
- 'cmsgen' => 4.21,
- 'COBOL' => 1.04,
- 'COBOL ii' => 0.75,
- 'COBOL/400' => 0.88,
- 'cobra' => 4.00,
- 'codecenter' => 2.22,
- 'cofac' => 2.22,
- 'cogen' => 2.22,
- 'cognos' => 2.22,
- 'cogo' => 1.13,
- 'comal' => 1.00,
- 'comit ii' => 1.25,
- 'common lisp' => 1.25,
- 'concurrent pascal' => 1.00,
- 'conniver' => 1.25,
- 'cool:gen/ief' => 2.58,
- 'coral 66' => 0.75,
- 'corvet' => 4.21,
- 'corvision' => 5.33,
- 'cpl' => 0.50,
- 'Crystal Reports' => 4.00,
- 'csl' => 1.63,
- 'csp' => 1.51,
- 'cssl' => 1.74,
-
-'CSS' => 1.0,
-
- 'culprit' => 1.57,
- 'cxpert' => 1.63,
- 'cygnet' => 4.21,
- 'DAL' => 1.50,
- 'data base default' => 2.00,
- 'dataflex' => 2.00,
- 'datatrieve' => 4.00,
- 'dbase iii' => 2.00,
- 'dbase iv' => 1.54,
- 'dcl' => 0.38,
- 'decision support default' => 2.22,
- 'decrally' => 2.00,
- 'delphi' => 2.76,
- 'dl/1' => 2.00,
- 'NASTRAN DMAP' => 2.35,
- 'dna4' => 4.21,
- 'DOS Batch' => 0.63,
- 'dsp assembly' => 0.50,
- 'dtabl' => 1.74,
- 'dtipt' => 1.74,
- 'dyana' => 1.13,
- 'dynamoiii' => 1.74,
- 'easel' => 2.76,
- 'easy' => 1.63,
- 'easytrieve+' => 2.35,
- 'eclipse' => 1.63,
- 'eda/sql' => 6.67,
- 'edscheme 3.4' => 1.51,
- 'eiffel' => 3.81,
- 'enform' => 1.74,
- 'englishbased default' => 1.51,
- 'ensemble' => 2.76,
- 'epos' => 4.00,
- 'erlang' => 2.00,
- 'esf' => 2.00,
- 'espadvisor' => 1.63,
- 'espl/i' => 1.13,
- 'euclid' => 0.75,
- 'excel' => 1.74,
- 'excel 12' => 13.33,
- 'excel 34' => 13.33,
- 'excel 5' => 13.33,
- 'express' => 2.22,
- 'exsys' => 1.63,
- 'extended common lisp' => 1.43,
- 'eznomad' => 2.22,
- 'facets' => 4.00,
- 'factorylink iv' => 2.76,
- 'fame' => 2.22,
- 'filemaker pro' => 2.22,
- 'flavors' => 2.76,
- 'flex' => 1.74,
- 'flexgen' => 2.76,
- 'Focus' => 1.90,
- 'foil' => 1.51,
- 'forte' => 4.44,
- 'forth' => 1.25,
- 'Fortran 66' => 0.63,
- 'Fortran 77' => 0.75,
- 'Fortran 90' => 1.00,
- 'Fortran 95' => 1.13,
- 'Fortran II' => 0.63,
- 'foundation' => 2.76,
- 'foxpro' => 2.29,
- 'foxpro 1' => 2.00,
- 'foxpro 2.5' => 2.35,
- 'framework' => 13.33,
- 'g2' => 1.63,
- 'gamma' => 5.00,
- 'genascript' => 2.96,
- 'gener/ol' => 6.15,
- 'genexus' => 5.33,
- 'genifer' => 4.21,
- 'geode 2.0' => 5.00,
- 'gfa basic' => 2.35,
- 'gml' => 1.74,
- 'golden common lisp' => 1.25,
- 'gpss' => 1.74,
- 'guest' => 2.86,
- 'guru' => 1.63,
- 'gw basic' => 0.82,
- 'Haskell' => 2.11,
- 'high c' => 0.63,
- 'hlevel' => 1.38,
- 'hp basic' => 0.63,
-
-'HTML' => 1.90 ,
-'XML' => 1.90 ,
-'XSLT' => 1.90 ,
-'DTD' => 1.90 ,
-'XSD' => 1.90 ,
-'NAnt scripts' => 1.90 ,
-'MSBuild scripts' => 1.90 ,
-
- 'HTML 2' => 5.00,
- 'HTML 3' => 5.33,
- 'huron' => 5.00,
- 'ibm adf i' => 4.00,
- 'ibm adf ii' => 4.44,
- 'ibm advanced basic' => 0.82,
- 'ibm cics/vs' => 2.00,
- 'ibm compiled basic' => 0.88,
- 'ibm vs cobol' => 0.75,
- 'ibm vs cobol ii' => 0.88,
- 'ices' => 1.13,
- 'icon' => 1.00,
- 'ideal' => 1.54,
- 'idms' => 2.00,
- 'ief' => 5.71,
- 'ief/cool:gen' => 2.58,
- 'iew' => 5.71,
- 'ifps/plus' => 2.50,
- 'imprs' => 2.00,
- 'informix' => 2.58,
- 'ingres' => 2.00,
- 'inquire' => 6.15,
- 'insight2' => 1.63,
- 'install/1' => 5.00,
- 'intellect' => 1.51,
- 'interlisp' => 1.38,
- 'interpreted basic' => 0.75,
- 'interpreted c' => 0.63,
- 'iqlisp' => 1.38,
- 'iqrp' => 6.15,
- 'j2ee' => 1.60,
- 'janus' => 1.13,
- 'Java' => 1.36,
-'Javascript' => 1.48,
-'JSP' => 1.48,
- 'JCL' => 1.67,
- 'joss' => 0.75,
- 'jovial' => 0.75,
- 'jsp' => 1.36,
- 'kappa' => 2.00,
- 'kbms' => 1.63,
- 'kcl' => 1.25,
- 'kee' => 1.63,
- 'keyplus' => 2.00,
- 'kl' => 1.25,
- 'klo' => 1.25,
- 'knowol' => 1.63,
- 'krl' => 1.38,
- 'Korn Shell' => 3.81,
- 'ladder logic' => 2.22,
- 'lambit/l' => 1.25,
- 'lattice c' => 0.63,
- 'liana' => 0.63,
- 'lilith' => 1.13,
- 'linc ii' => 5.71,
- 'Lisp' => 1.25,
- 'LiveLink OScript' => 3.5 ,
- 'loglisp' => 1.38,
- 'loops' => 3.81,
- 'lotus 123 dos' => 13.33,
- 'lotus macros' => 0.75,
- 'lotus notes' => 3.64,
- 'lucid 3d' => 13.33,
- 'lyric' => 1.51,
- 'm4' => 1.00,
- 'm' => 5.00,
- 'macforth' => 1.25,
- 'mach1' => 2.00,
- 'machine language' => 0.13,
- 'maestro' => 5.00,
- 'magec' => 5.00,
- 'magik' => 3.81,
- 'Lake' => 3.81,
- 'make' => 2.50,
- 'mantis' => 2.96,
- 'mapper' => 0.99,
- 'mark iv' => 2.00,
- 'mark v' => 2.22,
- 'mathcad' => 16.00,
- 'mdl' => 2.22,
- 'mentor' => 1.51,
- 'mesa' => 0.75,
- 'microfocus cobol' => 1.00,
- 'microforth' => 1.25,
- 'microsoft c' => 0.63,
- 'microstep' => 4.00,
- 'miranda' => 2.00,
- 'model 204' => 2.11,
- 'modula 2' => 1.00,
- 'mosaic' => 13.33,
- # 'ms c ++ v. 7' => 1.51,
- 'ms compiled basic' => 0.88,
- 'msl' => 1.25,
- 'mulisp' => 1.25,
- 'MUMPS' => 4.21,
- 'Nastran' => 1.13,
- 'natural' => 1.54,
- 'natural 1' => 1.51,
- 'natural 2' => 1.74,
- 'natural construct' => 3.20,
- 'natural language' => 0.03,
- 'netron/cap' => 4.21,
- 'nexpert' => 1.63,
- 'nial' => 1.63,
- 'nomad2' => 2.00,
- 'nonprocedural default' => 2.22,
- 'notes vip' => 2.22,
- 'nroff' => 1.51,
- 'object assembler' => 1.25,
- 'object lisp' => 2.76,
- 'object logo' => 2.76,
- 'object pascal' => 2.76,
- 'object star' => 5.00,
- 'Objective C' => 2.96,
- 'objectoriented default' => 2.76,
- 'objectview' => 3.20,
- 'ogl' => 1.00,
- 'omnis 7' => 2.00,
- 'oodl' => 2.76,
- 'ops' => 1.74,
- 'ops5' => 1.38,
- 'oracle' => 2.76,
- 'Oracle Reports' => 2.76,
- 'Oracle Forms' => 2.67,
- 'Oracle Developer/2000' => 3.48,
- 'oscar' => 0.75,
- 'pacbase' => 1.67,
- 'pace' => 2.00,
- 'paradox/pal' => 2.22,
- 'Pascal' => 0.88,
- 'Patran Command Language' => 2.50,
- 'pc focus' => 2.22,
- 'pdl millenium' => 3.81,
- 'pdp11 ade' => 1.51,
- 'peoplesoft' => 2.50,
- 'Perl' => 4.00,
- 'persistance object builder' => 3.81,
- 'pilot' => 1.51,
- 'pl/1' => 1.38,
- 'pl/m' => 1.13,
- 'pl/s' => 0.88,
- 'pl/sql' => 2.58,
- 'planit' => 1.51,
- 'planner' => 1.25,
- 'planperfect 1' => 11.43,
- 'plato' => 1.51,
- 'polyforth' => 1.25,
- 'pop' => 1.38,
- 'poplog' => 1.38,
- 'power basic' => 1.63,
- 'powerbuilder' => 3.33,
- 'powerhouse' => 5.71,
- 'ppl (plus)' => 2.00,
- 'problemoriented default' => 1.13,
- 'proc' => 2.96,
- 'procedural default' => 0.75,
- 'professional pascal' => 0.88,
- 'program generator default' => 5.00,
- 'progress v4' => 2.22,
- 'proiv' => 1.38,
- 'prolog' => 1.25,
- 'prose' => 0.75,
- 'proteus' => 0.75,
- 'qbasic' => 1.38,
- 'qbe' => 6.15,
- 'qmf' => 5.33,
- 'qnial' => 1.63,
- 'quattro' => 13.33,
- 'quattro pro' => 13.33,
- 'query default' => 6.15,
- 'quick basic 1' => 1.25,
- 'quick basic 2' => 1.31,
- 'quick basic 3' => 1.38,
- 'quick c' => 0.63,
- 'quickbuild' => 2.86,
- 'quiz' => 5.33,
- 'rally' => 2.00,
- 'ramis ii' => 2.00,
- 'rapidgen' => 2.86,
- 'ratfor' => 0.88,
- 'rdb' => 2.00,
- 'realia' => 1.74,
- 'realizer 1.0' => 2.00,
- 'realizer 2.0' => 2.22,
- 'relate/3000' => 2.00,
- 'reuse default' => 16.00,
- 'Rexx' => 1.19,
- 'Rexx (mvs)' => 1.00,
- 'Rexx (os/2)' => 1.74,
- 'rm basic' => 0.88,
- 'rm cobol' => 0.75,
- 'rm fortran' => 0.75,
- 'rpg i' => 1.00,
- 'rpg ii' => 1.63,
- 'rpg iii' => 1.63,
- 'rtexpert 1.4' => 1.38,
- 'sabretalk' => 0.90,
- 'sail' => 0.75,
- 'sapiens' => 5.00,
- 'sas' => 1.95,
- 'savvy' => 6.15,
- 'sbasic' => 0.88,
- 'sceptre' => 1.13,
- 'scheme' => 1.51,
- 'screen painter default' => 13.33,
- 'sequal' => 6.67,
- 'Bourne Shell' => 3.81,
- 'Bourne Again Shell' => 3.81,
- 'ksh' => 3.81,
- 'C Shell' => 3.81,
- 'siebel tools ' => 6.15,
- 'simplan' => 2.22,
- 'simscript' => 1.74,
- 'simula' => 1.74,
- 'simula 67' => 1.74,
- 'simulation default' => 1.74,
- 'SKILL' => 2.00,
- 'SKILL++' => 2.00,
- 'slogan' => 0.98,
- 'smalltalk' => 2.50,
- 'smalltalk 286' => 3.81,
- 'smalltalk 80' => 3.81,
- 'smalltalk/v' => 3.81,
- 'snap' => 1.00,
- 'snobol24' => 0.63,
- 'softscreen' => 5.71,
- 'Softbridge Basic' => 2.76,
- 'solo' => 1.38,
- 'speakeasy' => 2.22,
- 'spinnaker ppl' => 2.22,
- 'splus' => 2.50,
- 'spreadsheet default' => 13.33,
- 'sps' => 0.25,
- 'spss' => 2.50,
- 'SQL' => 2.29,
- 'sqlwindows' => 6.67,
- 'statistical default' => 2.50,
- 'strategem' => 2.22,
- 'stress' => 1.13,
- 'strongly typed default' => 0.88,
- 'style' => 1.74,
- 'superbase 1.3' => 2.22,
- 'surpass' => 13.33,
- 'sybase' => 2.00,
- 'symantec c++' => 2.76,
- 'symbolang' => 1.25,
- 'synchroworks' => 4.44,
- 'synon/2e' => 4.21,
- 'systemw' => 2.22,
- 'tandem access language' => 0.88,
- 'Tcl/Tk' => 4.00,
- 'Teamcenter def' => 1.00,
- 'Teamcenter met' => 1.00,
- 'Teamcenter mth' => 1.00,
- 'telon' => 5.00,
- 'tessaract' => 2.00,
- 'the twin' => 13.33,
- 'themis' => 6.15,
- 'tiief' => 5.71,
- 'topspeed c++' => 2.76,
- 'transform' => 5.33,
- 'translisp plus' => 1.43,
- 'treet' => 1.25,
- 'treetran' => 1.25,
- 'trs80 basic' => 0.63,
- 'true basic' => 1.25,
- 'turbo c' => 0.63,
- # 'turbo c++' => 1.51,
- 'turbo expert' => 1.63,
- 'turbo pascal >5' => 1.63,
- 'turbo pascal 14' => 1.00,
- 'turbo pascal 45' => 1.13,
- 'turbo prolog' => 1.00,
- 'turing' => 1.00,
- 'tutor' => 1.51,
- 'twaice' => 1.63,
- 'ucsd pascal' => 0.88,
- 'ufo/ims' => 2.22,
- 'uhelp' => 2.50,
- 'uniface' => 5.00,
- # 'unix shell scripts' => 3.81,
- 'vax acms' => 1.38,
- 'vax ade' => 2.00,
- 'vbscript' => 2.35,
- 'vectran' => 0.75,
- 'vhdl ' => 4.21,
- 'vim script' => 3.00,
- 'visible c' => 1.63,
- 'visible cobol' => 2.00,
- 'visicalc 1' => 8.89,
- 'visual 4.0' => 2.76,
- 'visual basic' => 1.90,
- 'visual basic 1' => 1.74,
- 'visual basic 2' => 1.86,
- 'visual basic 3' => 2.00,
- 'visual basic 4' => 2.22,
- 'visual basic 5' => 2.76,
- 'Visual Basic' => 2.76,
- 'visual basic dos' => 2.00,
- 'visual c++' => 2.35,
- 'visual cobol' => 4.00,
- 'visual objects' => 5.00,
- 'visualage' => 3.81,
- 'visualgen' => 4.44,
- 'vpf' => 0.84,
- 'vsrexx' => 2.50,
- 'vulcan' => 1.25,
- 'vz programmer' => 2.22,
- 'warp x' => 2.00,
- 'watcom c' => 0.63,
- 'watcom c/386' => 0.63,
- 'waterloo c' => 0.63,
- 'waterloo pascal' => 0.88,
- 'watfiv' => 0.94,
- 'watfor' => 0.88,
- 'web scripts' => 5.33,
- 'whip' => 0.88,
- 'wizard' => 2.86,
- 'xlisp' => 1.25,
- 'yacc' => 1.51,
- 'yacc++' => 1.51,
- 'YAML' => 0.90,
- 'zbasic' => 0.88,
- 'zim' => 4.21,
- 'zlisp' => 1.25,
-
-'Expect' => 2.00,
-'C/C++ Header' => 1.00,
-'inc' => 1.00,
-'lex' => 1.00,
-'MATLAB' => 4.00,
-'IDL' => 3.80,
-'Octave' => 4.00,
-'ML' => 3.00,
-'Modula3' => 2.00,
-'PHP' => 3.50,
-'Python' => 4.20,
-'Ruby' => 4.20,
-'sed' => 4.00,
-'Lua' => 4.00,
-);
-# 1}}}
-%{$rh_Known_Binary_Archives} = ( # {{{1
- '.tar' => 1 ,
- '.tar.Z' => 1 ,
- '.tar.gz' => 1 ,
- '.tar.bz2' => 1 ,
- '.zip' => 1 ,
- '.Zip' => 1 ,
- '.ZIP' => 1 ,
- '.ear' => 1 , # Java
- '.war' => 1 , # contained within .ear
- );
-# 1}}}
-} # end sub set_constants()
-sub Install_Regexp_Common { # {{{1
- # Installs portions of Damian Conway's & Abigail's Regexp::Common
- # module, v2.120, into a temporary directory for the duration of
- # this run.
-
- my %Regexp_Common_Contents = ();
-$Regexp_Common_Contents{'Common'} = <<'EOCommon'; # {{{2
-package Regexp::Common;
-
-use 5.00473;
-use strict;
-
-local $^W = 1;
-
-use vars qw /$VERSION %RE %sub_interface $AUTOLOAD/;
-
-($VERSION) = q $Revision: 2.120 $ =~ /([\d.]+)/;
-
-
-sub _croak {
- require Carp;
- goto &Carp::croak;
-}
-
-sub _carp {
- require Carp;
- goto &Carp::carp;
-}
-
-sub new {
- my ($class, @data) = @_;
- my %self;
- tie %self, $class, @data;
- return \%self;
-}
-
-sub TIEHASH {
- my ($class, @data) = @_;
- bless \@data, $class;
-}
-
-sub FETCH {
- my ($self, $extra) = @_;
- return bless ref($self)->new(@$self, $extra), ref($self);
-}
-
-# Modification for cloc: only need a few modules from Regexp::Common.
-my %imports = map {$_ => "Regexp::Common::$_"}
- qw /balanced comment delimited /;
-#my %imports = map {$_ => "Regexp::Common::$_"}
-# qw /balanced CC comment delimited lingua list
-# net number profanity SEN URI whitespace
-# zip/;
-
-sub import {
- shift; # Shift off the class.
- tie %RE, __PACKAGE__;
- {
- no strict 'refs';
- *{caller() . "::RE"} = \%RE;
- }
-
- my $saw_import;
- my $no_defaults;
- my %exclude;
- foreach my $entry (grep {!/^RE_/} @_) {
- if ($entry eq 'pattern') {
- no strict 'refs';
- *{caller() . "::pattern"} = \&pattern;
- next;
- }
- # This used to prevent $; from being set. We still recognize it,
- # but we won't do anything.
- if ($entry eq 'clean') {
- next;
- }
- if ($entry eq 'no_defaults') {
- $no_defaults ++;
- next;
- }
- if (my $module = $imports {$entry}) {
- $saw_import ++;
- eval "require $module;";
- die $@ if $@;
- next;
- }
- if ($entry =~ /^!(.*)/ && $imports {$1}) {
- $exclude {$1} ++;
- next;
- }
- # As a last resort, try to load the argument.
- my $module = $entry =~ /^Regexp::Common/
- ? $entry
- : "Regexp::Common::" . $entry;
- eval "require $module;";
- die $@ if $@;
- }
-
- unless ($saw_import || $no_defaults) {
- foreach my $module (values %imports) {
- next if $exclude {$module};
- eval "require $module;";
- die $@ if $@;
- }
- }
-
- my %exported;
- foreach my $entry (grep {/^RE_/} @_) {
- if ($entry =~ /^RE_(\w+_)?ALL$/) {
- my $m = defined $1 ? $1 : "";
- my $re = qr /^RE_${m}.*$/;
- while (my ($sub, $interface) = each %sub_interface) {
- next if $exported {$sub};
- next unless $sub =~ /$re/;
- {
- no strict 'refs';
- *{caller() . "::$sub"} = $interface;
- }
- $exported {$sub} ++;
- }
- }
- else {
- next if $exported {$entry};
- _croak "Can't export unknown subroutine &$entry"
- unless $sub_interface {$entry};
- {
- no strict 'refs';
- *{caller() . "::$entry"} = $sub_interface {$entry};
- }
- $exported {$entry} ++;
- }
- }
-}
-
-sub AUTOLOAD { _croak "Can't $AUTOLOAD" }
-
-sub DESTROY {}
-
-my %cache;
-
-my $fpat = qr/^(-\w+)/;
-
-sub _decache {
- my @args = @{tied %{$_[0]}};
- my @nonflags = grep {!/$fpat/} @args;
- my $cache = get_cache(@nonflags);
- _croak "Can't create unknown regex: \$RE{"
- . join("}{",@args) . "}"
- unless exists $cache->{__VAL__};
- _croak "Perl $] does not support the pattern "
- . "\$RE{" . join("}{",@args)
- . "}.\nYou need Perl $cache->{__VAL__}{version} or later"
- unless ($cache->{__VAL__}{version}||0) <= $];
- my %flags = ( %{$cache->{__VAL__}{default}},
- map { /$fpat\Q$;\E(.*)/ ? ($1 => $2)
- : /$fpat/ ? ($1 => undef)
- : ()
- } @args);
- $cache->{__VAL__}->_clone_with(\@args, \%flags);
-}
-
-use overload q{""} => \&_decache;
-
-
-sub get_cache {
- my $cache = \%cache;
- foreach (@_) {
- $cache = $cache->{$_}
- || ($cache->{$_} = {});
- }
- return $cache;
-}
-
-sub croak_version {
- my ($entry, @args) = @_;
-}
-
-sub pattern {
- my %spec = @_;
- _croak 'pattern() requires argument: name => [ @list ]'
- unless $spec{name} && ref $spec{name} eq 'ARRAY';
- _croak 'pattern() requires argument: create => $sub_ref_or_string'
- unless $spec{create};
-
- if (ref $spec{create} ne "CODE") {
- my $fixed_str = "$spec{create}";
- $spec{create} = sub { $fixed_str }
- }
-
- my @nonflags;
- my %default;
- foreach ( @{$spec{name}} ) {
- if (/$fpat=(.*)/) {
- $default{$1} = $2;
- }
- elsif (/$fpat\s*$/) {
- $default{$1} = undef;
- }
- else {
- push @nonflags, $_;
- }
- }
-
- my $entry = get_cache(@nonflags);
-
- if ($entry->{__VAL__}) {
- _carp "Overriding \$RE{"
- . join("}{",@nonflags)
- . "}";
- }
-
- $entry->{__VAL__} = bless {
- create => $spec{create},
- match => $spec{match} || \&generic_match,
- subs => $spec{subs} || \&generic_subs,
- version => $spec{version},
- default => \%default,
- }, 'Regexp::Common::Entry';
-
- foreach (@nonflags) {s/\W/X/g}
- my $subname = "RE_" . join ("_", @nonflags);
- $sub_interface{$subname} = sub {
- push @_ => undef if @_ % 2;
- my %flags = @_;
- my $pat = $spec{create}->($entry->{__VAL__},
- {%default, %flags}, \@nonflags);
- if (exists $flags{-keep}) { $pat =~ s/\Q(?k:/(/g; }
- else { $pat =~ s/\Q(?k:/(?:/g; }
- return exists $flags {-i} ? qr /(?i:$pat)/ : qr/$pat/;
- };
-
- return 1;
-}
-
-sub generic_match {$_ [1] =~ /$_[0]/}
-sub generic_subs {$_ [1] =~ s/$_[0]/$_[2]/}
-
-sub matches {
- my ($self, $str) = @_;
- my $entry = $self -> _decache;
- $entry -> {match} -> ($entry, $str);
-}
-
-sub subs {
- my ($self, $str, $newstr) = @_;
- my $entry = $self -> _decache;
- $entry -> {subs} -> ($entry, $str, $newstr);
- return $str;
-}
-
-
-package Regexp::Common::Entry;
-# use Carp;
-
-local $^W = 1;
-
-use overload
- q{""} => sub {
- my ($self) = @_;
- my $pat = $self->{create}->($self, $self->{flags}, $self->{args});
- if (exists $self->{flags}{-keep}) {
- $pat =~ s/\Q(?k:/(/g;
- }
- else {
- $pat =~ s/\Q(?k:/(?:/g;
- }
- if (exists $self->{flags}{-i}) { $pat = "(?i)$pat" }
- return $pat;
- };
-
-sub _clone_with {
- my ($self, $args, $flags) = @_;
- bless { %$self, args=>$args, flags=>$flags }, ref $self;
-}
-#
-# Copyright (c) 2001 - 2005, Damian Conway and Abigail. All Rights
-# Reserved. This module is free software. It may be used, redistributed
-# and/or modified under the terms of the Perl Artistic License
-# (see http://www.perl.com/perl/misc/Artistic.html)
-EOCommon
-# 2}}}
-$Regexp_Common_Contents{'Common/comment'} = <<'EOC'; # {{{2
-# $Id: comment.pm,v 2.116 2005/03/16 00:00:02 abigail Exp $
-
-package Regexp::Common::comment;
-
-use strict;
-local $^W = 1;
-
-use Regexp::Common qw /pattern clean no_defaults/;
-use vars qw /$VERSION/;
-
-($VERSION) = q $Revision: 2.116 $ =~ /[\d.]+/g;
-
-my @generic = (
- {languages => [qw /ABC Forth/],
- to_eol => ['\\\\']}, # This is for just a *single* backslash.
-
- {languages => [qw /Ada Alan Eiffel lua/],
- to_eol => ['--']},
-
- {languages => [qw /Advisor/],
- to_eol => ['#|//']},
-
- {languages => [qw /Advsys CQL Lisp LOGO M MUMPS REBOL Scheme
- SMITH zonefile/],
- to_eol => [';']},
-
- {languages => ['Algol 60'],
- from_to => [[qw /comment ;/]]},
-
- {languages => [qw {ALPACA B C C-- LPC PL/I}],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw /awk fvwm2 Icon mutt Perl Python QML R Ruby shell Tcl/],
- to_eol => ['#']},
-
- {languages => [[BASIC => 'mvEnterprise']],
- to_eol => ['[*!]|REM']},
-
- {languages => [qw /Befunge-98 Funge-98 Shelta/],
- id => [';']},
-
- {languages => ['beta-Juliet', 'Crystal Report', 'Portia'],
- to_eol => ['//']},
-
- {languages => ['BML'],
- from_to => [['<?_c', '_c?>']],
- },
-
- {languages => [qw /C++/, 'C#', qw /Cg ECMAScript FPL Java JavaScript/],
- to_eol => ['//'],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw /CLU LaTeX slrn TeX/],
- to_eol => ['%']},
-
- {languages => [qw /False/],
- from_to => [[qw !{ }!]]},
-
- {languages => [qw /Fortran/],
- to_eol => ['!']},
-
- {languages => [qw /Haifu/],
- id => [',']},
-
- {languages => [qw /ILLGOL/],
- to_eol => ['NB']},
-
- {languages => [qw /INTERCAL/],
- to_eol => [q{(?:(?:PLEASE(?:\s+DO)?|DO)\s+)?(?:NOT|N'T)}]},
-
- {languages => [qw /J/],
- to_eol => ['NB[.]']},
-
- {languages => [qw /Nickle/],
- to_eol => ['#'],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw /Oberon/],
- from_to => [[qw /(* *)/]]},
-
- {languages => [[qw /Pascal Delphi/], [qw /Pascal Free/], [qw /Pascal GPC/]],
- to_eol => ['//'],
- from_to => [[qw !{ }!], [qw !(* *)!]]},
-
- {languages => [[qw /Pascal Workshop/]],
- id => [qw /"/],
- from_to => [[qw !{ }!], [qw !(* *)!], [qw !/* */!]]},
-
- {languages => [qw /PEARL/],
- to_eol => ['!'],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw /PHP/],
- to_eol => ['#', '//'],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw !PL/B!],
- to_eol => ['[.;]']},
-
- {languages => [qw !PL/SQL!],
- to_eol => ['--'],
- from_to => [[qw {/* */}]]},
-
- {languages => [qw /Q-BAL/],
- to_eol => ['`']},
-
- {languages => [qw /Smalltalk/],
- id => ['"']},
-
- {languages => [qw /SQL/],
- to_eol => ['-{2,}']},
-
- {languages => [qw /troff/],
- to_eol => ['\\\"']},
-
- {languages => [qw /vi/],
- to_eol => ['"']},
-
- {languages => [qw /*W/],
- from_to => [[qw {|| !!}]]},
-);
-
-my @plain_or_nested = (
- [Caml => undef, "(*" => "*)"],
- [Dylan => "//", "/*" => "*/"],
- [Haskell => "-{2,}", "{-" => "-}"],
- [Hugo => "!(?!\\\\)", "!\\" => "\\!"],
- [SLIDE => "#", "(*" => "*)"],
-);
-
-#
-# Helper subs.
-#
-
-sub combine {
- local $_ = join "|", @_;
- if (@_ > 1) {
- s/\(\?k:/(?:/g;
- $_ = "(?k:$_)";
- }
- $_
-}
-
-sub to_eol ($) {"(?k:(?k:$_[0])(?k:[^\\n]*)(?k:\\n))"}
-sub id ($) {"(?k:(?k:$_[0])(?k:[^$_[0]]*)(?k:$_[0]))"} # One char only!
-sub from_to {
- local $^W = 1;
- my ($begin, $end) = @_;
-
- my $qb = quotemeta $begin;
- my $qe = quotemeta $end;
- my $fe = quotemeta substr $end => 0, 1;
- my $te = quotemeta substr $end => 1;
-
- "(?k:(?k:$qb)(?k:(?:[^$fe]+|$fe(?!$te))*)(?k:$qe))";
-}
-
-
-my $count = 0;
-sub nested {
- local $^W = 1;
- my ($begin, $end) = @_;
-
- $count ++;
- my $r = '(??{$Regexp::Common::comment ['. $count . ']})';
-
- my $qb = quotemeta $begin;
- my $qe = quotemeta $end;
- my $fb = quotemeta substr $begin => 0, 1;
- my $fe = quotemeta substr $end => 0, 1;
-
- my $tb = quotemeta substr $begin => 1;
- my $te = quotemeta substr $end => 1;
-
- use re 'eval';
-
- my $re;
- if ($fb eq $fe) {
- $re = qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
- }
- else {
- local $" = "|";
- my @clauses = "(?>[^$fb$fe]+)";
- push @clauses => "$fb(?!$tb)" if length $tb;
- push @clauses => "$fe(?!$te)" if length $te;
- push @clauses => $r;
- $re = qr /(?:$qb(?:@clauses)*$qe)/;
- }
-
- $Regexp::Common::comment [$count] = qr/$re/;
-}
-
-#
-# Process data.
-#
-
-foreach my $info (@plain_or_nested) {
- my ($language, $mark, $begin, $end) = @$info;
- pattern name => [comment => $language],
- create =>
- sub {my $re = nested $begin => $end;
- my $prefix = defined $mark ? $mark . "[^\n]*\n|" : "";
- exists $_ [1] -> {-keep} ? qr /($prefix$re)/
- : qr /$prefix$re/
- },
- version => 5.006,
- ;
-}
-
-
-foreach my $group (@generic) {
- my $pattern = combine +(map {to_eol $_} @{$group -> {to_eol}}),
- (map {from_to @$_} @{$group -> {from_to}}),
- (map {id $_} @{$group -> {id}}),
- ;
- foreach my $language (@{$group -> {languages}}) {
- pattern name => [comment => ref $language ? @$language : $language],
- create => $pattern,
- ;
- }
-}
-
-
-
-#
-# Other languages.
-#
-
-# http://www.pascal-central.com/docs/iso10206.txt
-pattern name => [qw /comment Pascal/],
- create => '(?k:' . '(?k:[{]|[(][*])'
- . '(?k:[^}*]*(?:[*][^)][^}*]*)*)'
- . '(?k:[}]|[*][)])'
- . ')'
- ;
-
-# http://www.templetons.com/brad/alice/language/
-pattern name => [qw /comment Pascal Alice/],
- create => '(?k:(?k:[{])(?k:[^}\n]*)(?k:[}]))'
- ;
-
-
-# http://westein.arb-phys.uni-dortmund.de/~wb/a68s.txt
-pattern name => [qw (comment), 'Algol 68'],
- create => q {(?k:(?:#[^#]*#)|} .
- q {(?:\bco\b(?:[^c]+|\Bc|\bc(?!o\b))*\bco\b)|} .
- q {(?:\bcomment\b(?:[^c]+|\Bc|\bc(?!omment\b))*\bcomment\b))}
- ;
-
-
-# See rules 91 and 92 of ISO 8879 (SGML).
-# Charles F. Goldfarb: "The SGML Handbook".
-# Oxford: Oxford University Press. 1990. ISBN 0-19-853737-9.
-# Ch. 10.3, pp 390.
-pattern name => [qw (comment HTML)],
- create => q {(?k:(?k:<!)(?k:(?:--(?k:[^-]*(?:-[^-]+)*)--\s*)*)(?k:>))},
- ;
-
-
-pattern name => [qw /comment SQL MySQL/],
- create => q {(?k:(?:#|-- )[^\n]*\n|} .
- q {/\*(?:(?>[^*;"']+)|"[^"]*"|'[^']*'|\*(?!/))*(?:;|\*/))},
- ;
-
-# Anything that isn't <>[]+-.,
-# http://home.wxs.nl/~faase009/Ha_BF.html
-pattern name => [qw /comment Brainfuck/],
- create => '(?k:[^<>\[\]+\-.,]+)'
- ;
-
-# Squeak is a variant of Smalltalk-80.
-# http://www.squeak.
-# http://mucow.com/squeak-qref.html
-pattern name => [qw /comment Squeak/],
- create => '(?k:(?k:")(?k:[^"]*(?:""[^"]*)*)(?k:"))'
- ;
-
-#
-# Scores of less than 5 or above 17....
-# http://www.cliff.biffle.org/esoterica/beatnik.html
-@Regexp::Common::comment::scores = (1, 3, 3, 2, 1, 4, 2, 4, 1, 8,
- 5, 1, 3, 1, 1, 3, 10, 1, 1, 1,
- 1, 4, 4, 8, 4, 10);
-pattern name => [qw /comment Beatnik/],
- create => sub {
- use re 'eval';
- my ($s, $x);
- my $re = qr {\b([A-Za-z]+)\b
- (?(?{($s, $x) = (0, lc $^N);
- $s += $Regexp::Common::comment::scores
- [ord (chop $x) - ord ('a')] while length $x;
- $s >= 5 && $s < 18})XXX|)}x;
- $re;
- },
- version => 5.008,
- ;
-
-
-# http://www.cray.com/craydoc/manuals/007-3692-005/html-007-3692-005/
-# (Goto table of contents/3.3 Source Form)
-# Fortran, in fixed format. Comments start with a C, c or * in the first
-# column, or a ! anywhere, but the sixth column. Then end with a newline.
-pattern name => [qw /comment Fortran fixed/],
- create => '(?k:(?k:(?:^[Cc*]|(?<!^.....)!))(?k:[^\n]*)(?k:\n))'
- ;
-
-
-# http://www.csis.ul.ie/cobol/Course/COBOLIntro.htm
-# Traditionally, comments in COBOL were indicated with an asteriks in
-# the seventh column. Modern compilers may be more lenient.
-pattern name => [qw /comment COBOL/],
- create => '(?<=^......)(?k:(?k:[*])(?k:[^\n]*)(?k:\n))',
- version => '5.008',
- ;
-
-1;
-#
-# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
-# This module is free software. It may be used, redistributed
-# and/or modified under the terms of the Perl Artistic License
-# (see http://www.perl.com/perl/misc/Artistic.html)
-EOC
-# 2}}}
-$Regexp_Common_Contents{'Common/balanced'} = <<'EOB'; # {{{2
-package Regexp::Common::balanced; {
-
-use strict;
-local $^W = 1;
-
-use vars qw /$VERSION/;
-($VERSION) = q $Revision: 2.101 $ =~ /[\d.]+/g;
-
-use Regexp::Common qw /pattern clean no_defaults/;
-
-my %closer = ( '{'=>'}', '('=>')', '['=>']', '<'=>'>' );
-my $count = -1;
-my %cache;
-
-sub nested {
- local $^W = 1;
- my ($start, $finish) = @_;
-
- return $Regexp::Common::balanced [$cache {$start} {$finish}]
- if exists $cache {$start} {$finish};
-
- $count ++;
- my $r = '(??{$Regexp::Common::balanced ['. $count . ']})';
-
- my @starts = map {s/\\(.)/$1/g; $_} grep {length}
- $start =~ /([^|\\]+|\\.)+/gs;
- my @finishes = map {s/\\(.)/$1/g; $_} grep {length}
- $finish =~ /([^|\\]+|\\.)+/gs;
-
- push @finishes => ($finishes [-1]) x (@starts - @finishes);
-
- my @re;
- local $" = "|";
- foreach my $begin (@starts) {
- my $end = shift @finishes;
-
- my $qb = quotemeta $begin;
- my $qe = quotemeta $end;
- my $fb = quotemeta substr $begin => 0, 1;
- my $fe = quotemeta substr $end => 0, 1;
-
- my $tb = quotemeta substr $begin => 1;
- my $te = quotemeta substr $end => 1;
-
- use re 'eval';
-
- my $add;
- if ($fb eq $fe) {
- push @re =>
- qr /(?:$qb(?:(?>[^$fb]+)|$fb(?!$tb)(?!$te)|$r)*$qe)/;
- }
- else {
- my @clauses = "(?>[^$fb$fe]+)";
- push @clauses => "$fb(?!$tb)" if length $tb;
- push @clauses => "$fe(?!$te)" if length $te;
- push @clauses => $r;
- push @re => qr /(?:$qb(?:@clauses)*$qe)/;
- }
- }
-
- $cache {$start} {$finish} = $count;
- $Regexp::Common::balanced [$count] = qr/@re/;
-}
-
-
-pattern name => [qw /balanced -parens=() -begin= -end=/],
- create => sub {
- my $flag = $_[1];
- unless (defined $flag -> {-begin} && length $flag -> {-begin} &&
- defined $flag -> {-end} && length $flag -> {-end}) {
- my @open = grep {index ($flag->{-parens}, $_) >= 0}
- ('[','(','{','<');
- my @close = map {$closer {$_}} @open;
- $flag -> {-begin} = join "|" => @open;
- $flag -> {-end} = join "|" => @close;
- }
- my $pat = nested @$flag {qw /-begin -end/};
- return exists $flag -> {-keep} ? qr /($pat)/ : $pat;
- },
- version => 5.006,
- ;
-
-}
-
-1;
-#
-# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
-# This module is free software. It may be used, redistributed
-# and/or modified under the terms of the Perl Artistic License
-# (see http://www.perl.com/perl/misc/Artistic.html)
-EOB
-# 2}}}
-$Regexp_Common_Contents{'Common/delimited'} = <<'EOD'; # {{{2
-# $Id: delimited.pm,v 2.104 2005/03/16 00:22:45 abigail Exp $
-
-package Regexp::Common::delimited;
-
-use strict;
-local $^W = 1;
-
-use Regexp::Common qw /pattern clean no_defaults/;
-use vars qw /$VERSION/;
-
-($VERSION) = q $Revision: 2.104 $ =~ /[\d.]+/g;
-
-sub gen_delimited {
-
- my ($dels, $escs) = @_;
- # return '(?:\S*)' unless $dels =~ /\S/;
- if (length $escs) {
- $escs .= substr ($escs, -1) x (length ($dels) - length ($escs));
- }
- my @pat = ();
- my $i;
- for ($i=0; $i < length $dels; $i++) {
- my $del = quotemeta substr ($dels, $i, 1);
- my $esc = length($escs) ? quotemeta substr ($escs, $i, 1) : "";
- if ($del eq $esc) {
- push @pat,
- "(?k:$del)(?k:[^$del]*(?:(?:$del$del)[^$del]*)*)(?k:$del)";
- }
- elsif (length $esc) {
- push @pat,
- "(?k:$del)(?k:[^$esc$del]*(?:$esc.[^$esc$del]*)*)(?k:$del)";
- }
- else {
- push @pat, "(?k:$del)(?k:[^$del]*)(?k:$del)";
- }
- }
- my $pat = join '|', @pat;
- return "(?k:$pat)";
-}
-
-sub _croak {
- require Carp;
- goto &Carp::croak;
-}
-
-pattern name => [qw( delimited -delim= -esc=\\ )],
- create => sub {my $flags = $_[1];
- _croak 'Must specify delimiter in $RE{delimited}'
- unless length $flags->{-delim};
- return gen_delimited (@{$flags}{-delim, -esc});
- },
- ;
-
-pattern name => [qw( quoted -esc=\\ )],
- create => sub {my $flags = $_[1];
- return gen_delimited (q{"'`}, $flags -> {-esc});
- },
- ;
-
-
-1;
-#
-# Copyright (c) 2001 - 2003, Damian Conway. All Rights Reserved.
-# This module is free software. It may be used, redistributed
-# and/or modified under the terms of the Perl Artistic License
-# (see http://www.perl.com/perl/misc/Artistic.html)
-EOD
-# 2}}}
- my $problems = 0;
- $HAVE_Rexexp_Common = 0;
- my $dir = "";
- if ($opt_sdir) {
- # write to the user-defined scratch directory
- $dir = $opt_sdir;
- } else {
- # let File::Temp create a suitable temporary directory
- $dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
- }
- print "Using temp dir [$dir] to install Regexp::Common\n" if $opt_v;
- my $Regexp_dir = "$dir/Regexp";
- my $Regexp_Common_dir = "$dir/Regexp/Common";
- mkdir $Regexp_dir ;
- mkdir $Regexp_Common_dir;
-
- foreach my $module_file (keys %Regexp_Common_Contents) {
- my $OUT = new IO::File "$dir/Regexp/${module_file}.pm", "w";
- if (defined $OUT) {
- print $OUT $Regexp_Common_Contents{$module_file};
- $OUT->close;
- } else {
- warn "Failed to install Regexp::${module_file}.pm\n";
- $problems = 1;
- }
- }
-
- push @INC, $dir;
- eval "use Regexp::Common qw /comment RE_comment_HTML balanced/";
- $HAVE_Rexexp_Common = 1 unless $problems;
-} # 1}}}
-sub Install_Algorithm_Diff { # {{{1
- # Installs Tye McQueen's Algorithm::Diff module, v1.1902, into a
- # temporary directory for the duration of this run.
-
-my $Algorithm_Diff_Contents = <<'EOAlgDiff'; # {{{2
-package Algorithm::Diff;
-# Skip to first "=head" line for documentation.
-use strict;
-
-use integer; # see below in _replaceNextLargerWith() for mod to make
- # if you don't use this
-use vars qw( $VERSION @EXPORT_OK );
-$VERSION = 1.19_02;
-# ^ ^^ ^^-- Incremented at will
-# | \+----- Incremented for non-trivial changes to features
-# \-------- Incremented for fundamental changes
-require Exporter;
-*import = \&Exporter::import;
-@EXPORT_OK = qw(
- prepare LCS LCSidx LCS_length
- diff sdiff compact_diff
- traverse_sequences traverse_balanced
-);
-
-# McIlroy-Hunt diff algorithm
-# Adapted from the Smalltalk code of Mario I. Wolczko, <mario@wolczko.com>
-# by Ned Konz, perl@bike-nomad.com
-# Updates by Tye McQueen, http://perlmonks.org/?node=tye
-
-# Create a hash that maps each element of $aCollection to the set of
-# positions it occupies in $aCollection, restricted to the elements
-# within the range of indexes specified by $start and $end.
-# The fourth parameter is a subroutine reference that will be called to
-# generate a string to use as a key.
-# Additional parameters, if any, will be passed to this subroutine.
-#
-# my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
-
-sub _withPositionsOfInInterval
-{
- my $aCollection = shift; # array ref
- my $start = shift;
- my $end = shift;
- my $keyGen = shift;
- my %d;
- my $index;
- for ( $index = $start ; $index <= $end ; $index++ )
- {
- my $element = $aCollection->[$index];
- my $key = &$keyGen( $element, @_ );
- if ( exists( $d{$key} ) )
- {
- unshift ( @{ $d{$key} }, $index );
- }
- else
- {
- $d{$key} = [$index];
- }
- }
- return wantarray ? %d : \%d;
-}
-
-# Find the place at which aValue would normally be inserted into the
-# array. If that place is already occupied by aValue, do nothing, and
-# return undef. If the place does not exist (i.e., it is off the end of
-# the array), add it to the end, otherwise replace the element at that
-# point with aValue. It is assumed that the array's values are numeric.
-# This is where the bulk (75%) of the time is spent in this module, so
-# try to make it fast!
-
-sub _replaceNextLargerWith
-{
- my ( $array, $aValue, $high ) = @_;
- $high ||= $#$array;
-
- # off the end?
- if ( $high == -1 || $aValue > $array->[-1] )
- {
- push ( @$array, $aValue );
- return $high + 1;
- }
-
- # binary search for insertion point...
- my $low = 0;
- my $index;
- my $found;
- while ( $low <= $high )
- {
- $index = ( $high + $low ) / 2;
-
- # $index = int(( $high + $low ) / 2); # without 'use integer'
- $found = $array->[$index];
-
- if ( $aValue == $found )
- {
- return undef;
- }
- elsif ( $aValue > $found )
- {
- $low = $index + 1;
- }
- else
- {
- $high = $index - 1;
- }
- }
-
- # now insertion point is in $low.
- $array->[$low] = $aValue; # overwrite next larger
- return $low;
-}
-
-# This method computes the longest common subsequence in $a and $b.
-
-# Result is array or ref, whose contents is such that
-# $a->[ $i ] == $b->[ $result[ $i ] ]
-# foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
-
-# An additional argument may be passed; this is a hash or key generating
-# function that should return a string that uniquely identifies the given
-# element. It should be the case that if the key is the same, the elements
-# will compare the same. If this parameter is undef or missing, the key
-# will be the element as a string.
-
-# By default, comparisons will use "eq" and elements will be turned into keys
-# using the default stringizing operator '""'.
-
-# Additional parameters, if any, will be passed to the key generation
-# routine.
-
-sub _longestCommonSubsequence
-{
- my $a = shift; # array ref or hash ref
- my $b = shift; # array ref or hash ref
- my $counting = shift; # scalar
- my $keyGen = shift; # code ref
- my $compare; # code ref
-
- if ( ref($a) eq 'HASH' )
- { # prepared hash must be in $b
- my $tmp = $b;
- $b = $a;
- $a = $tmp;
- }
-
- # Check for bogus (non-ref) argument values
- if ( !ref($a) || !ref($b) )
- {
- my @callerInfo = caller(1);
- die 'error: must pass array or hash references to ' . $callerInfo[3];
- }
-
- # set up code refs
- # Note that these are optimized.
- if ( !defined($keyGen) ) # optimize for strings
- {
- $keyGen = sub { $_[0] };
- $compare = sub { my ( $a, $b ) = @_; $a eq $b };
- }
- else
- {
- $compare = sub {
- my $a = shift;
- my $b = shift;
- &$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
- };
- }
-
- my ( $aStart, $aFinish, $matchVector ) = ( 0, $#$a, [] );
- my ( $prunedCount, $bMatches ) = ( 0, {} );
-
- if ( ref($b) eq 'HASH' ) # was $bMatches prepared for us?
- {
- $bMatches = $b;
- }
- else
- {
- my ( $bStart, $bFinish ) = ( 0, $#$b );
-
- # First we prune off any common elements at the beginning
- while ( $aStart <= $aFinish
- and $bStart <= $bFinish
- and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
- {
- $matchVector->[ $aStart++ ] = $bStart++;
- $prunedCount++;
- }
-
- # now the end
- while ( $aStart <= $aFinish
- and $bStart <= $bFinish
- and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
- {
- $matchVector->[ $aFinish-- ] = $bFinish--;
- $prunedCount++;
- }
-
- # Now compute the equivalence classes of positions of elements
- $bMatches =
- _withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
- }
- my $thresh = [];
- my $links = [];
-
- my ( $i, $ai, $j, $k );
- for ( $i = $aStart ; $i <= $aFinish ; $i++ )
- {
- $ai = &$keyGen( $a->[$i], @_ );
- if ( exists( $bMatches->{$ai} ) )
- {
- $k = 0;
- for $j ( @{ $bMatches->{$ai} } )
- {
-
- # optimization: most of the time this will be true
- if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
- {
- $thresh->[$k] = $j;
- }
- else
- {
- $k = _replaceNextLargerWith( $thresh, $j, $k );
- }
-
- # oddly, it's faster to always test this (CPU cache?).
- if ( defined($k) )
- {
- $links->[$k] =
- [ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
- }
- }
- }
- }
-
- if (@$thresh)
- {
- return $prunedCount + @$thresh if $counting;
- for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
- {
- $matchVector->[ $link->[1] ] = $link->[2];
- }
- }
- elsif ($counting)
- {
- return $prunedCount;
- }
-
- return wantarray ? @$matchVector : $matchVector;
-}
-
-sub traverse_sequences
-{
- my $a = shift; # array ref
- my $b = shift; # array ref
- my $callbacks = shift || {};
- my $keyGen = shift;
- my $matchCallback = $callbacks->{'MATCH'} || sub { };
- my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
- my $finishedACallback = $callbacks->{'A_FINISHED'};
- my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
- my $finishedBCallback = $callbacks->{'B_FINISHED'};
- my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
-
- # Process all the lines in @$matchVector
- my $lastA = $#$a;
- my $lastB = $#$b;
- my $bi = 0;
- my $ai;
-
- for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
- {
- my $bLine = $matchVector->[$ai];
- if ( defined($bLine) ) # matched
- {
- &$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
- &$matchCallback( $ai, $bi++, @_ );
- }
- else
- {
- &$discardACallback( $ai, $bi, @_ );
- }
- }
-
- # The last entry (if any) processed was a match.
- # $ai and $bi point just past the last matching lines in their sequences.
-
- while ( $ai <= $lastA or $bi <= $lastB )
- {
-
- # last A?
- if ( $ai == $lastA + 1 and $bi <= $lastB )
- {
- if ( defined($finishedACallback) )
- {
- &$finishedACallback( $lastA, @_ );
- $finishedACallback = undef;
- }
- else
- {
- &$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
- }
- }
-
- # last B?
- if ( $bi == $lastB + 1 and $ai <= $lastA )
- {
- if ( defined($finishedBCallback) )
- {
- &$finishedBCallback( $lastB, @_ );
- $finishedBCallback = undef;
- }
- else
- {
- &$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
- }
- }
-
- &$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
- &$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
- }
-
- return 1;
-}
-
-sub traverse_balanced
-{
- my $a = shift; # array ref
- my $b = shift; # array ref
- my $callbacks = shift || {};
- my $keyGen = shift;
- my $matchCallback = $callbacks->{'MATCH'} || sub { };
- my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
- my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
- my $changeCallback = $callbacks->{'CHANGE'};
- my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
-
- # Process all the lines in match vector
- my $lastA = $#$a;
- my $lastB = $#$b;
- my $bi = 0;
- my $ai = 0;
- my $ma = -1;
- my $mb;
-
- while (1)
- {
-
- # Find next match indices $ma and $mb
- do {
- $ma++;
- } while(
- $ma <= $#$matchVector
- && !defined $matchVector->[$ma]
- );
-
- last if $ma > $#$matchVector; # end of matchVector?
- $mb = $matchVector->[$ma];
-
- # Proceed with discard a/b or change events until
- # next match
- while ( $ai < $ma || $bi < $mb )
- {
-
- if ( $ai < $ma && $bi < $mb )
- {
-
- # Change
- if ( defined $changeCallback )
- {
- &$changeCallback( $ai++, $bi++, @_ );
- }
- else
- {
- &$discardACallback( $ai++, $bi, @_ );
- &$discardBCallback( $ai, $bi++, @_ );
- }
- }
- elsif ( $ai < $ma )
- {
- &$discardACallback( $ai++, $bi, @_ );
- }
- else
- {
-
- # $bi < $mb
- &$discardBCallback( $ai, $bi++, @_ );
- }
- }
-
- # Match
- &$matchCallback( $ai++, $bi++, @_ );
- }
-
- while ( $ai <= $lastA || $bi <= $lastB )
- {
- if ( $ai <= $lastA && $bi <= $lastB )
- {
-
- # Change
- if ( defined $changeCallback )
- {
- &$changeCallback( $ai++, $bi++, @_ );
- }
- else
- {
- &$discardACallback( $ai++, $bi, @_ );
- &$discardBCallback( $ai, $bi++, @_ );
- }
- }
- elsif ( $ai <= $lastA )
- {
- &$discardACallback( $ai++, $bi, @_ );
- }
- else
- {
-
- # $bi <= $lastB
- &$discardBCallback( $ai, $bi++, @_ );
- }
- }
-
- return 1;
-}
-
-sub prepare
-{
- my $a = shift; # array ref
- my $keyGen = shift; # code ref
-
- # set up code ref
- $keyGen = sub { $_[0] } unless defined($keyGen);
-
- return scalar _withPositionsOfInInterval( $a, 0, $#$a, $keyGen, @_ );
-}
-
-sub LCS
-{
- my $a = shift; # array ref
- my $b = shift; # array ref or hash ref
- my $matchVector = _longestCommonSubsequence( $a, $b, 0, @_ );
- my @retval;
- my $i;
- for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
- {
- if ( defined( $matchVector->[$i] ) )
- {
- push ( @retval, $a->[$i] );
- }
- }
- return wantarray ? @retval : \@retval;
-}
-
-sub LCS_length
-{
- my $a = shift; # array ref
- my $b = shift; # array ref or hash ref
- return _longestCommonSubsequence( $a, $b, 1, @_ );
-}
-
-sub LCSidx
-{
- my $a= shift @_;
- my $b= shift @_;
- my $match= _longestCommonSubsequence( $a, $b, 0, @_ );
- my @am= grep defined $match->[$_], 0..$#$match;
- my @bm= @{$match}[@am];
- return \@am, \@bm;
-}
-
-sub compact_diff
-{
- my $a= shift @_;
- my $b= shift @_;
- my( $am, $bm )= LCSidx( $a, $b, @_ );
- my @cdiff;
- my( $ai, $bi )= ( 0, 0 );
- push @cdiff, $ai, $bi;
- while( 1 ) {
- while( @$am && $ai == $am->[0] && $bi == $bm->[0] ) {
- shift @$am;
- shift @$bm;
- ++$ai, ++$bi;
- }
- push @cdiff, $ai, $bi;
- last if ! @$am;
- $ai = $am->[0];
- $bi = $bm->[0];
- push @cdiff, $ai, $bi;
- }
- push @cdiff, 0+@$a, 0+@$b
- if $ai < @$a || $bi < @$b;
- return wantarray ? @cdiff : \@cdiff;
-}
-
-sub diff
-{
- my $a = shift; # array ref
- my $b = shift; # array ref
- my $retval = [];
- my $hunk = [];
- my $discard = sub {
- push @$hunk, [ '-', $_[0], $a->[ $_[0] ] ];
- };
- my $add = sub {
- push @$hunk, [ '+', $_[1], $b->[ $_[1] ] ];
- };
- my $match = sub {
- push @$retval, $hunk
- if 0 < @$hunk;
- $hunk = []
- };
- traverse_sequences( $a, $b,
- { MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
- &$match();
- return wantarray ? @$retval : $retval;
-}
-
-sub sdiff
-{
- my $a = shift; # array ref
- my $b = shift; # array ref
- my $retval = [];
- my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
- my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
- my $change = sub {
- push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
- };
- my $match = sub {
- push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
- };
- traverse_balanced(
- $a,
- $b,
- {
- MATCH => $match,
- DISCARD_A => $discard,
- DISCARD_B => $add,
- CHANGE => $change,
- },
- @_
- );
- return wantarray ? @$retval : $retval;
-}
-
-########################################
-my $Root= __PACKAGE__;
-package Algorithm::Diff::_impl;
-use strict;
-
-sub _Idx() { 0 } # $me->[_Idx]: Ref to array of hunk indices
- # 1 # $me->[1]: Ref to first sequence
- # 2 # $me->[2]: Ref to second sequence
-sub _End() { 3 } # $me->[_End]: Diff between forward and reverse pos
-sub _Same() { 4 } # $me->[_Same]: 1 if pos 1 contains unchanged items
-sub _Base() { 5 } # $me->[_Base]: Added to range's min and max
-sub _Pos() { 6 } # $me->[_Pos]: Which hunk is currently selected
-sub _Off() { 7 } # $me->[_Off]: Offset into _Idx for current position
-sub _Min() { -2 } # Added to _Off to get min instead of max+1
-
-sub Die
-{
- require Carp;
- Carp::confess( @_ );
-}
-
-sub _ChkPos
-{
- my( $me )= @_;
- return if $me->[_Pos];
- my $meth= ( caller(1) )[3];
- Die( "Called $meth on 'reset' object" );
-}
-
-sub _ChkSeq
-{
- my( $me, $seq )= @_;
- return $seq + $me->[_Off]
- if 1 == $seq || 2 == $seq;
- my $meth= ( caller(1) )[3];
- Die( "$meth: Invalid sequence number ($seq); must be 1 or 2" );
-}
-
-sub getObjPkg
-{
- my( $us )= @_;
- return ref $us if ref $us;
- return $us . "::_obj";
-}
-
-sub new
-{
- my( $us, $seq1, $seq2, $opts ) = @_;
- my @args;
- for( $opts->{keyGen} ) {
- push @args, $_ if $_;
- }
- for( $opts->{keyGenArgs} ) {
- push @args, @$_ if $_;
- }
- my $cdif= Algorithm::Diff::compact_diff( $seq1, $seq2, @args );
- my $same= 1;
- if( 0 == $cdif->[2] && 0 == $cdif->[3] ) {
- $same= 0;
- splice @$cdif, 0, 2;
- }
- my @obj= ( $cdif, $seq1, $seq2 );
- $obj[_End] = (1+@$cdif)/2;
- $obj[_Same] = $same;
- $obj[_Base] = 0;
- my $me = bless \@obj, $us->getObjPkg();
- $me->Reset( 0 );
- return $me;
-}
-
-sub Reset
-{
- my( $me, $pos )= @_;
- $pos= int( $pos || 0 );
- $pos += $me->[_End]
- if $pos < 0;
- $pos= 0
- if $pos < 0 || $me->[_End] <= $pos;
- $me->[_Pos]= $pos || !1;
- $me->[_Off]= 2*$pos - 1;
- return $me;
-}
-
-sub Base
-{
- my( $me, $base )= @_;
- my $oldBase= $me->[_Base];
- $me->[_Base]= 0+$base if defined $base;
- return $oldBase;
-}
-
-sub Copy
-{
- my( $me, $pos, $base )= @_;
- my @obj= @$me;
- my $you= bless \@obj, ref($me);
- $you->Reset( $pos ) if defined $pos;
- $you->Base( $base );
- return $you;
-}
-
-sub Next {
- my( $me, $steps )= @_;
- $steps= 1 if ! defined $steps;
- if( $steps ) {
- my $pos= $me->[_Pos];
- my $new= $pos + $steps;
- $new= 0 if $pos && $new < 0;
- $me->Reset( $new )
- }
- return $me->[_Pos];
-}
-
-sub Prev {
- my( $me, $steps )= @_;
- $steps= 1 if ! defined $steps;
- my $pos= $me->Next(-$steps);
- $pos -= $me->[_End] if $pos;
- return $pos;
-}
-
-sub Diff {
- my( $me )= @_;
- $me->_ChkPos();
- return 0 if $me->[_Same] == ( 1 & $me->[_Pos] );
- my $ret= 0;
- my $off= $me->[_Off];
- for my $seq ( 1, 2 ) {
- $ret |= $seq
- if $me->[_Idx][ $off + $seq + _Min ]
- < $me->[_Idx][ $off + $seq ];
- }
- return $ret;
-}
-
-sub Min {
- my( $me, $seq, $base )= @_;
- $me->_ChkPos();
- my $off= $me->_ChkSeq($seq);
- $base= $me->[_Base] if !defined $base;
- return $base + $me->[_Idx][ $off + _Min ];
-}
-
-sub Max {
- my( $me, $seq, $base )= @_;
- $me->_ChkPos();
- my $off= $me->_ChkSeq($seq);
- $base= $me->[_Base] if !defined $base;
- return $base + $me->[_Idx][ $off ] -1;
-}
-
-sub Range {
- my( $me, $seq, $base )= @_;
- $me->_ChkPos();
- my $off = $me->_ChkSeq($seq);
- if( !wantarray ) {
- return $me->[_Idx][ $off ]
- - $me->[_Idx][ $off + _Min ];
- }
- $base= $me->[_Base] if !defined $base;
- return ( $base + $me->[_Idx][ $off + _Min ] )
- .. ( $base + $me->[_Idx][ $off ] - 1 );
-}
-
-sub Items {
- my( $me, $seq )= @_;
- $me->_ChkPos();
- my $off = $me->_ChkSeq($seq);
- if( !wantarray ) {
- return $me->[_Idx][ $off ]
- - $me->[_Idx][ $off + _Min ];
- }
- return
- @{$me->[$seq]}[
- $me->[_Idx][ $off + _Min ]
- .. ( $me->[_Idx][ $off ] - 1 )
- ];
-}
-
-sub Same {
- my( $me )= @_;
- $me->_ChkPos();
- return wantarray ? () : 0
- if $me->[_Same] != ( 1 & $me->[_Pos] );
- return $me->Items(1);
-}
-
-my %getName;
-BEGIN {
- %getName= (
- same => \&Same,
- diff => \&Diff,
- base => \&Base,
- min => \&Min,
- max => \&Max,
- range=> \&Range,
- items=> \&Items, # same thing
- );
-}
-
-sub Get
-{
- my $me= shift @_;
- $me->_ChkPos();
- my @value;
- for my $arg ( @_ ) {
- for my $word ( split ' ', $arg ) {
- my $meth;
- if( $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/
- || not $meth= $getName{ lc $2 }
- ) {
- Die( $Root, ", Get: Invalid request ($word)" );
- }
- my( $base, $name, $seq )= ( $1, $2, $3 );
- push @value, scalar(
- 4 == length($name)
- ? $meth->( $me )
- : $meth->( $me, $seq, $base )
- );
- }
- }
- if( wantarray ) {
- return @value;
- } elsif( 1 == @value ) {
- return $value[0];
- }
- Die( 0+@value, " values requested from ",
- $Root, "'s Get in scalar context" );
-}
-
-
-my $Obj= getObjPkg($Root);
-no strict 'refs';
-
-for my $meth ( qw( new getObjPkg ) ) {
- *{$Root."::".$meth} = \&{$meth};
- *{$Obj ."::".$meth} = \&{$meth};
-}
-for my $meth ( qw(
- Next Prev Reset Copy Base Diff
- Same Items Range Min Max Get
- _ChkPos _ChkSeq
-) ) {
- *{$Obj."::".$meth} = \&{$meth};
-}
-
-1;
-# This version released by Tye McQueen (http://perlmonks.org/?node=tye).
-#
-# =head1 LICENSE
-#
-# Parts Copyright (c) 2000-2004 Ned Konz. All rights reserved.
-# Parts by Tye McQueen.
-#
-# This program is free software; you can redistribute it and/or modify it
-# under the same terms as Perl.
-#
-# =head1 MAILING LIST
-#
-# Mark-Jason still maintains a mailing list. To join a low-volume mailing
-# list for announcements related to diff and Algorithm::Diff, send an
-# empty mail message to mjd-perl-diff-request@plover.com.
-# =head1 CREDITS
-#
-# Versions through 0.59 (and much of this documentation) were written by:
-#
-# Mark-Jason Dominus, mjd-perl-diff@plover.com
-#
-# This version borrows some documentation and routine names from
-# Mark-Jason's, but Diff.pm's code was completely replaced.
-#
-# This code was adapted from the Smalltalk code of Mario Wolczko
-# <mario@wolczko.com>, which is available at
-# ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
-#
-# C<sdiff> and C<traverse_balanced> were written by Mike Schilli
-# <m@perlmeister.com>.
-#
-# The algorithm is that described in
-# I<A Fast Algorithm for Computing Longest Common Subsequences>,
-# CACM, vol.20, no.5, pp.350-353, May 1977, with a few
-# minor improvements to improve the speed.
-#
-# Much work was done by Ned Konz (perl@bike-nomad.com).
-#
-# The OO interface and some other changes are by Tye McQueen.
-#
-EOAlgDiff
-# 2}}}
- my $problems = 0;
- $HAVE_Algorith_Diff = 0;
- my $dir = "";
- if ($opt_sdir) {
- # write to the user-defined scratch directory
- $dir = $opt_sdir;
- } else {
- # let File::Temp create a suitable temporary directory
- $dir = tempdir( CLEANUP => 1 ); # 1 = delete on exit
- }
- print "Using temp dir [$dir] to install Algorithm::Diff\n" if $opt_v;
- my $Algorithm_dir = "$dir/Algorithm";
- my $Algorithm_Diff_dir = "$dir/Algorithm/Diff";
- mkdir $Algorithm_dir ;
- mkdir $Algorithm_Diff_dir;
-
- my $OUT = new IO::File "$dir/Algorithm/Diff.pm", "w";
- if (defined $OUT) {
- print $OUT $Algorithm_Diff_Contents;
- $OUT->close;
- } else {
- warn "Failed to install Algorithm/Diff.pm\n";
- $problems = 1;
- }
-
- push @INC, $dir; # between this & Regexp::Common only need to do once
- eval "use Algorithm::Diff qw / sdiff /";
- $HAVE_Algorith_Diff = 1 unless $problems;
-} # 1}}}
-sub call_regexp_common { # {{{1
- my ($ra_lines, $language ) = @_;
- print "-> call_regexp_common\n" if $opt_v > 2;
-
- Install_Regexp_Common() unless $HAVE_Rexexp_Common;
-
- my $all_lines = join("", @{$ra_lines});
-
- no strict 'vars';
- # otherwise get:
- # Global symbol "%RE" requires explicit package name at cloc line xx.
- if ($all_lines =~ $RE{comment}{$language}) {
- # Suppress "Use of uninitialized value in regexp compilation" that
- # pops up when $1 is undefined--happens if there's a bug in the $RE
- # This Pascal comment will trigger it:
- # (* This is { another } test. **)
- # Curiously, testing for "defined $1" breaks the substitution.
- no warnings;
- # remove comments
- $all_lines =~ s/$1//g;
- }
- # a bogus use of %RE to avoid:
- # Name "main::RE" used only once: possible typo at cloc line xx.
- print scalar keys %RE if $opt_v < -20;
-#?#print "$all_lines\n";
- print "<- call_regexp_common\n" if $opt_v > 2;
- return split("\n", $all_lines);
-} # 1}}}
-sub plural_form { # {{{1
- # For getting the right plural form on some English nouns.
- my $n = shift @_;
- if ($n == 1) { return ( 1, "" ); }
- else { return ($n, "s"); }
-} # 1}}}
-sub matlab_or_objective_C { # {{{1
- # Decide if code is MATLAB, Objective C, or MUMPS
- my ($file , # in
- $rh_Err , # in hash of error codes
- $raa_errors , # out
- $rs_language , # out
- ) = @_;
-
- print "-> matlab_or_objective_C\n" if $opt_v > 2;
- # matlab markers:
- # first line starts with "function"
- # some lines start with "%"
- # high marks for lines that start with [
- #
- # Objective C markers:
- # must have at least two brace characters, { }
- # has /* ... */ style comments
- # some lines start with @
- # some lines start with #include
- #
- # MUMPS:
- # has ; comment markers
- # do not match: \w+\s*=\s*\w
- # lines begin with \s*\.?\w+\s+\w
- # high marks for lines that start with \s*K\s+ or \s*Kill\s+
-
- ${$rs_language} = "";
- my $IN = new IO::File $file, "r";
- if (!defined $IN) {
- push @{$raa_errors}, [$rh_Err->{'Unable to read'} , $file];
- return;
- }
-
- my $matlab_points = 0;
- my $objective_C_points = 0;
- my $mumps_points = 0;
- my $has_braces = 0;
- while (<$IN>) {
- ++$has_braces if m/[{}]/;
- ++$mumps_points if $. == 1 and m{^[A-Z]};
- if (m{^\s*/\*}) { # /*
- ++$objective_C_points;
- --$matlab_points;
- } elsif (m{^\s*\w+\s*=\s*}) { # definitely not MUMPS
- --$mumps_points;
- } elsif (m{^\s*\.?\w\s+\w}) {
- ++$mumps_points;
- } elsif (m{^\s*;}) {
- ++$mumps_points;
- } elsif (m{^\s*#include}) {
- ++$objective_C_points;
- --$matlab_points;
- } elsif (m{^\s*@(interface|implementation|protocol|public|protected|private|end)\s}o) {
- # Objective C without a doubt
- $objective_C_points = 1;
- $matlab_points = 0;
- last;
- } elsif (m{^\s*\[}) { # line starts with [ -- very matlab
- $matlab_points += 5;
- } elsif (m{^\sK(ill)?\s+}) {
- $mumps_points += 5;
- } elsif (m{^\s*function}) {
- --$objective_C_points;
- ++$matlab_points;
- } elsif (m{^\s*%}) { # %
- --$objective_C_points;
- ++$matlab_points;
- ++$mumps_points;
- }
- }
- $IN->close;
-
- print "<- matlab_or_objective_C(matlab=$matlab_points, C=$objective_C_points, mumps=$mumps_points)\n"
- if $opt_v > 2;
- $objective_C_points = -9.9e20 unless $has_braces >= 2;
- if (($matlab_points > $objective_C_points) and
- ($matlab_points > $mumps_points) ) {
- ${$rs_language} = "MATLAB";
- } elsif (($mumps_points > $objective_C_points) and
- ($mumps_points > $matlab_points) ) {
- ${$rs_language} = "MUMPS";
- } else {
- ${$rs_language} = "Objective C";
- }
-
-} # 1}}}
-sub html_colored_text { # {{{1
- # http://www.pagetutor.com/pagetutor/makapage/pics/net216-2.gif
- my ($color, $text) = @_;
-#?#die "html_colored_text($text)";
- if ($color =~ /^red$/i) {
- $color = "#ff0000";
- } elsif ($color =~ /^green$/i) {
- $color = "#00ff00";
- } elsif ($color =~ /^blue$/i) {
- $color = "#0000ff";
- } elsif ($color =~ /^grey$/i) {
- $color = "#cccccc";
- }
-# return "" unless $text;
- return '<font color="' . $color . '">' . html_metachars($text) . "</font>";
-} # 1}}}
-sub html_metachars { # {{{1
- # Replace HTML metacharacters with their printable forms.
- # Future: use HTML-Encoder-0.00_04/lib/HTML/Encoder.pm
- # from Fabiano Reese Righetti's HTML::Encoder module if
- # this subroutine proves to be too simplistic.
- my ($string, ) = shift @_;
-
- my @in_chars = split(//, $string);
- my @out_chars = ();
- foreach my $c (@in_chars) {
- if ($c eq '<') {
- push @out_chars, '&lt;'
- } elsif ($c eq '>') {
- push @out_chars, '&gt;'
- } elsif ($c eq '&') {
- push @out_chars, '&amp;'
- } else {
- push @out_chars, $c;
- }
- }
- return join "", @out_chars;
-} # 1}}}
-#x#sub diff_two_strings { # {{{1
-#x# # Compute the difference between two strings and return
-#x# # the strings with special markers prefixing characters
-#x# # that differ.
-#x# my ($text_1,
-#x# $text_2,
-#x# ) = @_;
-#x# my $MARKER = "\cA";
-#x#
-#x# my @chars_1 = split '', $text_1;
-#x# my @chars_2 = split '', $text_2;
-#x# my %changed_1 = ();
-#x# my %changed_2 = ();
-#x# my $diff = Algorithm::Diff->new ( \@chars_1, \@chars_2 );
-#x# while( $diff->Next() ) {
-#x# next if $diff->Same();
-#x# my $sep = "";
-#x# if ( ! $diff->Items(2) ) {
-#x# my ($a, $b, $c ) = $diff->Get(qw( Min1 Max1 Max2 ));
-#x# foreach ($a..$b) { $changed_1{$_} = 1; }
-#x# $changed_2{$c} = 1;
-#x# } elsif ( ! $diff->Items(1) ) {
-#x# my ($a, $b, $c ) = $diff->Get(qw( Max1 Min2 Max2 ));
-#x# $changed_1{$a} = 1;
-#x# foreach ($b..$c) { $changed_2{$_} = 1; }
-#x# } else {
-#x# $sep = "---\n";
-#x# my ($a, $b, $c, $d ) = $diff->Get(qw( Min1 Max1 Min2 Max2 ));
-#x# foreach ($a..$b) { $changed_1{$_} = 1; }
-#x# foreach ($c..$d) { $changed_2{$_} = 1; }
-#x# }
-#x# }
-#x# for (my $i = 0; $i < scalar @chars_1; $i++) {
-#x# $chars_1[$i] = $MARKER . $chars_1[$i];
-#x# }
-#x# for (my $i = 0; $i < scalar @chars_2; $i++) {
-#x# $chars_2[$i] = $MARKER . $chars_2[$i];
-#x# }
-#x# my $new_1 = join "", @chars_1;
-#x# my $new_2 = join "", @chars_2;
-#x# return ($new_1, $new_2);
-#x#} # 1}}}
-sub diff_two_arrays { # {{{1
- my ($ra_lines_1 ,
- $ra_lines_2 )
- = @_;
- # returns $raa_diff_1[0..n] = [ u | c | + | - , text ]
- # $raa_diff_2[0..n] = [ u | c | + | - , text ]
- # u = unchanged
- # c = changed
- # + = added
- # - = removed
- my ($raa_diff_1, $raa_diff_2);
-
- my $n_no_change = 0;
- my $n_modified = 0;
- my $n_added = 0;
- my $n_deleted = 0;
- my @min_sdiff = ();
-my $NN = chr(27) . "[0m"; # normal
-my $BB = chr(27) . "[1m"; # bold
-
- my @sdiffs = sdiff( $ra_lines_1, $ra_lines_2 );
- foreach my $entry (@sdiffs) {
- my ($out_1, $out_2) = ('', '');
- if ($entry->[0] eq 'u') {
- ++$n_no_change;
- push @{$raa_diff_1}, [ 'u', $entry->[1]];
- push @{$raa_diff_2}, [ 'u', $entry->[1]];
- next;
- }
- if ($entry->[0] eq 'c') {
- ++$n_modified;
- push @{$raa_diff_1}, [ 'c', $entry->[1]];
- push @{$raa_diff_2}, [ 'c', $entry->[2]];
- } elsif ($entry->[0] eq '+') {
- ++$n_added;
- push @{$raa_diff_1}, [ '+', $entry->[1]];
- push @{$raa_diff_2}, [ '+', $entry->[2]];
- } elsif ($entry->[0] eq '-') {
- ++$n_deleted;
- push @{$raa_diff_1}, [ '-', $entry->[1]];
- push @{$raa_diff_2}, [ '-', $entry->[2]];
- } elsif ($entry->[0] eq 'u') {
- } else { die "diff_two_arrays unknown entry->[0]=[$entry->[0]]\n"; }
- }
-
- return ($raa_diff_1, $raa_diff_2);
-} # 1}}}
-#x#sub test_alg_diff { # {{{1
-#x# my ($file_1 ,
-#x# $file_2 )
-#x# = @_;
-#x# my $fh_1 = new IO::File $file_1, "r";
-#x# die "Unable to read $file_1: $!\n" unless defined $fh_1;
-#x# chomp(my @lines_1 = <$fh_1>);
-#x# $fh_1->close;
-#x#
-#x# my $fh_2 = new IO::File $file_2, "r";
-#x# die "Unable to read $file_2: $!\n" unless defined $fh_2;
-#x# chomp(my @lines_2 = <$fh_2>);
-#x# $fh_2->close;
-#x#
-#x# my $n_no_change = 0;
-#x# my $n_modified = 0;
-#x# my $n_added = 0;
-#x# my $n_deleted = 0;
-#x# my @min_sdiff = ();
-#x#my $NN = chr(27) . "[0m"; # normal
-#x#my $BB = chr(27) . "[1m"; # bold
-#x#
-#x# my @sdiffs = sdiff( \@lines_1, \@lines_2 );
-#x# foreach my $entry (@sdiffs) {
-#x# my ($out_1, $out_2) = ('', '');
-#x# if ($entry->[0] eq 'u') {
-#x# ++$n_no_change;
-#x# # $out_1 = $entry->[1];
-#x# # $out_2 = $entry->[2];
-#x# next;
-#x# }
-#x## push @min_sdiff, $entry;
-#x# if ($entry->[0] eq 'c') {
-#x# ++$n_modified;
-#x# ($out_1, $out_2) = diff_two_strings($entry->[1], $entry->[2]);
-#x# $out_1 =~ s/\cA(\w)/${BB}$1${NN}/g;
-#x# $out_2 =~ s/\cA(\w)/${BB}$1${NN}/g;
-#x# # $out_1 =~ s/\cA//g;
-#x# # $out_2 =~ s/\cA//g;
-#x# } elsif ($entry->[0] eq '+') {
-#x# ++$n_added;
-#x# $out_1 = $entry->[1];
-#x# $out_2 = $entry->[2];
-#x# } elsif ($entry->[0] eq '-') {
-#x# ++$n_deleted;
-#x# $out_1 = $entry->[1];
-#x# $out_2 = $entry->[2];
-#x# } elsif ($entry->[0] eq 'u') {
-#x# } else { die "unknown entry->[0]=[$entry->[0]]\n"; }
-#x# printf "%-80s | %s\n", $out_1, $out_2;
-#x# }
-#x#
-#x## foreach my $entry (@min_sdiff) {
-#x## printf "DIFF: %s %s %s\n", @{$entry};
-#x## }
-#x#} # 1}}}
-sub write_comments_to_html { # {{{1
- my ($filename , # in
- $rah_diff_L , # in see routine file_diff() for explanation
- $rah_diff_R , # in see routine file_diff() for explanation
- $rh_blank , # in location and counts of blank lines
- ) = @_;
-
- print "-> write_comments_to_html($filename)\n" if $opt_v > 2;
- my $file = $filename . ".html";
-#use Data::Dumper;
-#print Dumper("rah_diff_L", $rah_diff_L, "rah_diff_R", $rah_diff_R);
- my $OUT = new IO::File $file, "w";
- if (!defined $OUT) {
- warn "Unable to write to $file\n";
- print "<- write_comments_to_html\n" if $opt_v > 2;
- return;
- }
-
- my $html_out = html_header($filename);
-
- my $comment_line_number = 0;
- for (my $i = 0; $i < scalar @{$rah_diff_R}; $i++) {
- if (defined $rh_blank->{$i}) {
- foreach (1..$rh_blank->{$i}) {
- $html_out .= "<!-- blank -->\n";
- }
- }
- my $line_num = "";
- my $pre = "";
- my $post = "</span>";
-die "undef rah_diff_R[$i]{type} " unless defined $rah_diff_R->[$i]{type};
- if ($rah_diff_R->[$i]{type} eq 'nonexist') {
- ++$comment_line_number;
- $line_num = '<span class="clinenum">' . $comment_line_number . $post;
- $pre = '<span class="comment">';
- $html_out .= $line_num;
- $html_out .= $pre .
- html_metachars($rah_diff_L->[$i]{char}) .
- $post . "\n";
- next;
- }
- if ($rah_diff_R->[$i]{type} eq 'code' and
- $rah_diff_R->[$i]{desc} eq 'same') {
- # entire line remains as-is
- $line_num = '<span class="linenum">' .
- $rah_diff_R->[$i]{lnum} . $post;
- $pre = '<span class="normal">';
- $html_out .= $line_num;
- $html_out .= $pre .
- html_metachars($rah_diff_R->[$i]{char}) . $post;
- } elsif ($rah_diff_R->[$i]{type} eq 'code') { # code+comments
-
- $line_num = '<span class="linenum">' .
- $rah_diff_R->[$i]{lnum} . $post;
- $html_out .= $line_num;
-
- my @strings = @{$rah_diff_R->[$i]{char}{strings}};
- my @type = @{$rah_diff_R->[$i]{char}{type}};
- for (my $i = 0; $i < scalar @strings; $i++) {
- if ($type[$i] eq 'u') {
- $pre = '<span class="normal">';
- } else {
- $pre = '<span class="comment">';
- }
- $html_out .= $pre . html_metachars($strings[$i]) . $post;
- }
-# print Dumper(@strings, @type); die;
-
- } elsif ($rah_diff_R->[$i]{type} eq 'comment') {
- $line_num = '<span class="clinenum">' . $comment_line_number . $post;
- # entire line is a comment
- $pre = '<span class="comment">';
- $html_out .= $pre .
- html_metachars($rah_diff_R->[$i]{char}) . $post;
- }
-#printf "%-30s %s %-30s\n", $line_1, $separator, $line_2;
- $html_out .= "\n";
- }
-
- $html_out .= html_end();
-
- my $out_file = "$filename.html";
- open OUT, ">$out_file" or die "Cannot write to $out_file $!\n";
- print OUT $html_out;
- close OUT;
- print "Wrote $out_file\n" unless $opt_quiet;
- $OUT->close;
-
- print "<- write_comments_to_html\n" if $opt_v > 2;
-} # 1}}}
-sub file_diff { # {{{1
- my ($ra_lines_L , # in array of lines in Left file (no blank lines)
- $ra_lines_R , # in array of lines in Right file (no blank lines)
- $mode , # in "comment" | "revision"
- $rah_diff_L , # in/out if mode = 'revision'
- # out if mode = 'comment'
- $rah_diff_R , # in/out if mode = 'revision'
- # out if mode = 'comment'
- $rh_count , # out count{X}{Y} = number of lines
- # X = code | comment | blank
- # Y = values of {desc} in rah_diff
- # (= same | added | removed | modified)
- # when mode = 'comment', only Y=same is used
- ) = @_;
-
- # This routine operates in two ways:
- # A. Computes diffs of the same file with and without comments.
- # This is used to classify lines as code, comments, or blank.
- # B. Computes diffs of two revisions of a file. This method
- # requires a prior run of method A using the older version
- # of the file because it needs lines to be classified.
-
- # $rah_diff structure:
- # An array with n entries where n equals the number of lines in
- # an sdiff of the two files. Each entry in the array describes
- # the contents of the corresponding line in file Left and file Right:
- # diff[]{type} = blank | code | code+comment | comment | nonexist
- # {lnum} = line number within the original file (1-based)
- # {desc} = same | added | removed | modified
- # {char} = the input line unless {desc} = 'modified' in
- # which case
- # {char}{strings} = [ substrings ]
- # {char}{type} = [ disposition (added, removed, etc)]
- #
-
- print "-> file_diff()\n" if $opt_v > 2;
-
- my @sdiffs = sdiff($ra_lines_L, $ra_lines_R);
-#print Dumper(@sdiffs);
-#print Dumper("sdiffs", \@sdiffs);
- my $COMMENT_MODE = 0;
- $COMMENT_MODE = 1 if $mode eq "comment";
-
- my $n_L = 0;
- my $n_R = 0;
- my $n_sdiff = 0; # index to $rah_diff_L, $rah_diff_R
- if ($COMMENT_MODE) {
- @{$rah_diff_L} = ();
- @{$rah_diff_R} = ();
- }
- foreach my $triple (@sdiffs) {
- my $flag = $triple->[0];
- my $line_L = $triple->[1];
- my $line_R = $triple->[2];
- $rah_diff_L->[$n_sdiff]{char} = $line_L;
- $rah_diff_R->[$n_sdiff]{char} = $line_R;
- if ($flag eq 'u') { # u = unchanged
- ++$n_L;
- ++$n_R;
- if ($COMMENT_MODE) {
- # line exists in both with & without comments, must be code
- $rah_diff_L->[$n_sdiff]{type} = "code";
- $rah_diff_R->[$n_sdiff]{type} = "code";
- }
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
- $rah_diff_L->[$n_sdiff]{desc} = "same";
- $rah_diff_R->[$n_sdiff]{desc} = "same";
- $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
- $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
- } elsif ($flag eq 'c') { # c = changed
- ++$n_L;
- ++$n_R;
-
- if ($COMMENT_MODE) {
- # line has text both with & without comments;
- # count as code
- $rah_diff_L->[$n_sdiff]{type} = "code";
- $rah_diff_R->[$n_sdiff]{type} = "code";
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
- } else {
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{modified};
- }
-
- my @chars_L = split '', $line_L;
- my @chars_R = split '', $line_R;
- my @inline_sdiffs = sdiff( \@chars_L, \@chars_R );
-#use Data::Dumper::Simple;
-#if ($n_R == 6 or $n_R == 1 or $n_R == 2) {
-#print "L=[$line_L]\n";
-#print "R=[$line_R]\n";
-#print Dumper(@chars_L, @chars_R, @inline_sdiffs);
-#}
- my @index = ();
- foreach my $il_triple (@inline_sdiffs) {
- # make an array of u|c|+|- corresponding
- # to each character
- push @index, $il_triple->[0];
- }
-#print Dumper(@index); die;
- # expect problems if arrays @index and $inline_sdiffs[1];
- # (@{$inline_sdiffs->[1]} are the characters of line_L)
- # aren't the same length
- my $prev_type = $index[0];
- my @strings = (); # blocks of consecutive code or comment
- my @type = (); # u (=code) or c (=comment)
- my $j_str = 0;
- $strings[$j_str] .= $chars_L[0];
- $type[$j_str] = $prev_type;
- for (my $i = 1; $i < scalar @chars_L; $i++) {
- if ($index[$i] ne $prev_type) {
- ++$j_str;
-#print "change at j_str=$j_str type=$index[$i]\n";
- $type[$j_str] = $index[$i];
- $prev_type = $index[$i];
- }
- $strings[$j_str] .= $chars_L[$i];
- }
-# print Dumper(@strings, @type); die;
- delete $rah_diff_R->[$n_sdiff]{char};
- @{$rah_diff_R->[$n_sdiff]{char}{strings}} = @strings;
- @{$rah_diff_R->[$n_sdiff]{char}{type}} = @type;
- $rah_diff_L->[$n_sdiff]{desc} = "modified";
- $rah_diff_R->[$n_sdiff]{desc} = "modified";
- $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
- $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
-
- } elsif ($flag eq '+') { # + = added
- ++$n_R;
- if ($COMMENT_MODE) {
- # should never get here
- warn "file_diff: diff failure (diff says the\n";
- warn "comment-free file has added lines).\n";
- warn "$n_sdiff $line_L\n";
- last;
- }
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{added};
- $rah_diff_L->[$n_sdiff]{type} = "nonexist";
- $rah_diff_L->[$n_sdiff]{desc} = "removed";
- $rah_diff_R->[$n_sdiff]{desc} = "added";
- $rah_diff_R->[$n_sdiff]{lnum} = $n_R;
- } elsif ($flag eq '-') { # - = removed
- ++$n_L;
- if ($COMMENT_MODE) {
- # line must be comment because blanks already gone
- $rah_diff_L->[$n_sdiff]{type} = "comment";
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{same};
- } else {
- ++$rh_count->{ $rah_diff_L->[$n_sdiff]{type} }{removed};
- }
- $rah_diff_R->[$n_sdiff]{type} = "nonexist";
- $rah_diff_R->[$n_sdiff]{desc} = "removed";
- $rah_diff_L->[$n_sdiff]{desc} = "added";
- $rah_diff_L->[$n_sdiff]{lnum} = $n_L;
- }
-#printf "%-30s %s %-30s\n", $line_L, $separator, $line_R;
- ++$n_sdiff;
- }
-
- print "<- file_diff\n" if $opt_v > 2;
-} # 1}}}
-sub align_by_pairs { # {{{1
- my ($rh_file_list_L , # in
- $rh_file_list_R , # in
- $rs_nFiles_same , # out
- $rs_nFiles_added , # out
- $rs_nFiles_removed , # out
- $rs_nFiles_modified , # out
- $ra_modified_file_list , # out
- ) = @_;
- @{$ra_modified_file_list} = ();
-
- my @files_L = keys %{$rh_file_list_L};
- my @files_R = keys %{$rh_file_list_R};
- push @{$ra_modified_file_list}, [ $files_L[0], $files_R[0] ];
-} # 1}}}
-sub html_header { # {{{1
- my ($title , ) = @_;
-
- print "-> html_header\n" if $opt_v > 2;
- return
-'<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
-<meta name="GENERATOR" content="cloc http://cloc.sourceforge.net">
-' .
-"
-<!-- Created by $script v$VERSION -->
-<title>$title</title>
-" .
-'
-<style TYPE="text/css">
-<!--
- body {
- color: black;
- background-color: white;
- font-family: monospace
- }
-
- .whitespace {
- background-color: gray;
- }
-
- .comment {
- color: gray;
- font-style: italic;
- }
-
- .clinenum {
- color: red;
- }
-
- .linenum {
- color: green;
- }
- -->
-</style>
-</head>
-<body>
-<pre><tt>
-';
- print "<- html_header\n" if $opt_v > 2;
-} # 1}}}
-sub html_end { # {{{1
-return
-'</tt></pre>
-</body>
-</html>
-';
-} # 1}}}
-sub die_unknown_lang { # {{{1
- my ($lang, $option_name) = @_;
- die "Unknown language '$lang' used with $option_name option. " .
- "The command\n $script --show-lang\n" .
- "will print all recognized languages.\n" ;
-} # 1}}}
-sub unicode_file { # {{{1
- my $file = shift @_;
-
- return 0 if (-s $file > 2_000_000);
- # don't bother trying to test binary files bigger than 2 MB
-
- my $IN = new IO::File $file, "r";
- if (!defined $IN) {
- warn "Unable to read $file; ignoring.\n";
- return 0;
- }
- my @lines = <$IN>;
- $IN->close;
-
- if (unicode_to_ascii( join('', @lines) )) {
- return 1;
- } else {
- return 0;
- }
-
-} # 1}}}
-sub unicode_to_ascii { # {{{1
- my $string = shift @_;
-
- # A trivial attempt to convert Microsoft Windows style Unicode
- # files into ASCII. These files exhibit the following byte
- # sequence:
- # byte 1: 255
- # byte 2: 254
- # byte 3: ord of ASCII character
- # byte 4: 0
- # byte 3+i: ord of ASCII character
- # byte 4+i: 0
-
- my @ascii = ();
- my $looks_like_unicode = 1;
- my $length = length $string;
-# print "length=$length\n";
- if ($length <= 3) {
- $looks_like_unicode = 0;
- return '';
- }
- my @unicode = split(//, $string);
-
- for (my $i = 2; $i < $length; $i += 2) {
-# print "examining [$unicode[$i]] ord ", ord($unicode[$i]), "\n";
- if (32 <= ord($unicode[$i]) and ord($unicode[$i]) <= 127
- or ord($unicode[$i]) == 13
- or ord($unicode[$i]) == 10
- or ord($unicode[$i]) == 9
- ) {
- push @ascii, $unicode[$i];
-# print "adding [$unicode[$i]]\n";
- } else {
- $looks_like_unicode = 0;
- last;
- }
- if ($i+1 < $length) {
- if (!$unicode[$i+1]) {
- $looks_like_unicode = 0;
- last;
- }
- }
- }
- if ($looks_like_unicode) {
- return join("", @ascii);
- } else {
- return '';
- }
-} # 1}}}
-
-# subroutines copied from SLOCCount
-my %lex_files = (); # really_is_lex()
-my %expect_files = (); # really_is_expect()
-my %pascal_files = (); # really_is_pascal(), really_is_incpascal()
-my %php_files = (); # really_is_php()
-sub really_is_lex { # {{{1
-# Given filename, returns TRUE if its contents really is lex.
-# lex file must have "%%", "%{", and "%}".
-# In theory, a lex file doesn't need "%{" and "%}", but in practice
-# they all have them, and requiring them avoid mislabeling a
-# non-lexfile as a lex file.
-
- my $filename = shift;
- chomp($filename);
-
- my $is_lex = 0; # Value to determine.
- my $percent_percent = 0;
- my $percent_opencurly = 0;
- my $percent_closecurly = 0;
-
- # Return cached result, if available:
- if ($lex_files{$filename}) { return $lex_files{$filename};}
-
- open(LEX_FILE, "<$filename") ||
- die "Can't open $filename to determine if it's lex.\n";
- while(<LEX_FILE>) {
- $percent_percent++ if (m/^\s*\%\%/);
- $percent_opencurly++ if (m/^\s*\%\{/);
- $percent_closecurly++ if (m/^\s*\%\}/);
- }
- close(LEX_FILE);
-
- if ($percent_percent && $percent_opencurly && $percent_closecurly)
- {$is_lex = 1;}
-
- $lex_files{$filename} = $is_lex; # Store result in cache.
-
- return $is_lex;
-} # 1}}}
-sub really_is_expect { # {{{1
-# Given filename, returns TRUE if its contents really are Expect.
-# Many "exp" files (such as in Apache and Mesa) are just "export" data,
-# summarizing something else # (e.g., its interface).
-# Sometimes (like in RPM) it's just misc. data.
-# Thus, we need to look at the file to determine
-# if it's really an "expect" file.
-
- my $filename = shift;
- chomp($filename);
-
-# The heuristic is as follows: it's Expect _IF_ it:
-# 1. has "load_lib" command and either "#" comments or {}.
-# 2. {, }, and one of: proc, if, [...], expect
-
- my $is_expect = 0; # Value to determine.
-
- my $begin_brace = 0; # Lines that begin with curly braces.
- my $end_brace = 0; # Lines that begin with curly braces.
- my $load_lib = 0; # Lines with the Load_lib command.
- my $found_proc = 0;
- my $found_if = 0;
- my $found_brackets = 0;
- my $found_expect = 0;
- my $found_pound = 0;
-
- # Return cached result, if available:
- if ($expect_files{$filename}) { return expect_files{$filename};}
-
- open(EXPECT_FILE, "<$filename") ||
- die "Can't open $filename to determine if it's expect.\n";
- while(<EXPECT_FILE>) {
-
- if (m/#/) {$found_pound++; s/#.*//;}
- if (m/^\s*\{/) { $begin_brace++;}
- if (m/\{\s*$/) { $begin_brace++;}
- if (m/^\s*\}/) { $end_brace++;}
- if (m/\};?\s*$/) { $end_brace++;}
- if (m/^\s*load_lib\s+\S/) { $load_lib++;}
- if (m/^\s*proc\s/) { $found_proc++;}
- if (m/^\s*if\s/) { $found_if++;}
- if (m/\[.*\]/) { $found_brackets++;}
- if (m/^\s*expect\s/) { $found_expect++;}
- }
- close(EXPECT_FILE);
-
- if ($load_lib && ($found_pound || ($begin_brace && $end_brace)))
- {$is_expect = 1;}
- if ( $begin_brace && $end_brace &&
- ($found_proc || $found_if || $found_brackets || $found_expect))
- {$is_expect = 1;}
-
- $expect_files{$filename} = $is_expect; # Store result in cache.
-
- return $is_expect;
-} # 1}}}
-sub really_is_pascal { # {{{1
-# Given filename, returns TRUE if its contents really are Pascal.
-
-# This isn't as obvious as it seems.
-# Many ".p" files are Perl files
-# (such as /usr/src/redhat/BUILD/ispell-3.1/dicts/czech/glob.p),
-# others are C extractions
-# (such as /usr/src/redhat/BUILD/linux/include/linux/umsdos_fs.p
-# and some files in linuxconf).
-# However, test files in "p2c" really are Pascal, for example.
-
-# Note that /usr/src/redhat/BUILD/ucd-snmp-4.1.1/ov/bitmaps/UCD.20.p
-# is actually C code. The heuristics determine that they're not Pascal,
-# but because it ends in ".p" it's not counted as C code either.
-# I believe this is actually correct behavior, because frankly it
-# looks like it's automatically generated (it's a bitmap expressed as code).
-# Rather than guess otherwise, we don't include it in a list of
-# source files. Let's face it, someone who creates C files ending in ".p"
-# and expects them to be counted by default as C files in SLOCCount needs
-# their head examined. I suggest examining their head
-# with a sucker rod (see syslogd(8) for more on sucker rods).
-
-# This heuristic counts as Pascal such files such as:
-# /usr/src/redhat/BUILD/teTeX-1.0/texk/web2c/tangleboot.p
-# Which is hand-generated. We don't count woven documents now anyway,
-# so this is justifiable.
-
- my $filename = shift;
- chomp($filename);
-
-# The heuristic is as follows: it's Pascal _IF_ it has all of the following
-# (ignoring {...} and (*...*) comments):
-# 1. "^..program NAME" or "^..unit NAME",
-# 2. "procedure", "function", "^..interface", or "^..implementation",
-# 3. a "begin", and
-# 4. it ends with "end.",
-#
-# Or it has all of the following:
-# 1. "^..module NAME" and
-# 2. it ends with "end.".
-#
-# Or it has all of the following:
-# 1. "^..program NAME",
-# 2. a "begin", and
-# 3. it ends with "end.".
-#
-# The "end." requirements in particular filter out non-Pascal.
-#
-# Note (jgb): this does not detect Pascal main files in fpc, like
-# fpc-1.0.4/api/test/testterminfo.pas, which does not have "program" in
-# it
-
- my $is_pascal = 0; # Value to determine.
-
- my $has_program = 0;
- my $has_unit = 0;
- my $has_module = 0;
- my $has_procedure_or_function = 0;
- my $found_begin = 0;
- my $found_terminating_end = 0;
- my $has_begin = 0;
-
- # Return cached result, if available:
- if ($pascal_files{$filename}) { return pascal_files{$filename};}
-
- open(PASCAL_FILE, "<$filename") ||
- die "Can't open $filename to determine if it's pascal.\n";
- while(<PASCAL_FILE>) {
- s/\{.*?\}//g; # Ignore {...} comments on this line; imperfect, but effective.
- s/\(\*.*?\*\)//g; # Ignore (*...*) comments on this line; imperfect, but effective.
- if (m/\bprogram\s+[A-Za-z]/i) {$has_program=1;}
- if (m/\bunit\s+[A-Za-z]/i) {$has_unit=1;}
- if (m/\bmodule\s+[A-Za-z]/i) {$has_module=1;}
- if (m/\bprocedure\b/i) { $has_procedure_or_function = 1; }
- if (m/\bfunction\b/i) { $has_procedure_or_function = 1; }
- if (m/^\s*interface\s+/i) { $has_procedure_or_function = 1; }
- if (m/^\s*implementation\s+/i) { $has_procedure_or_function = 1; }
- if (m/\bbegin\b/i) { $has_begin = 1; }
- # Originally I said:
- # "This heuristic fails if there are multi-line comments after
- # "end."; I haven't seen that in real Pascal programs:"
- # But jgb found there are a good quantity of them in Debian, specially in
- # fpc (at the end of a lot of files there is a multiline comment
- # with the changelog for the file).
- # Therefore, assume Pascal if "end." appears anywhere in the file.
- if (m/end\.\s*$/i) {$found_terminating_end = 1;}
-# elsif (m/\S/) {$found_terminating_end = 0;}
- }
- close(PASCAL_FILE);
-
- # Okay, we've examined the entire file looking for clues;
- # let's use those clues to determine if it's really Pascal:
-
- if ( ( ($has_unit || $has_program) && $has_procedure_or_function &&
- $has_begin && $found_terminating_end ) ||
- ( $has_module && $found_terminating_end ) ||
- ( $has_program && $has_begin && $found_terminating_end ) )
- {$is_pascal = 1;}
-
- $pascal_files{$filename} = $is_pascal; # Store result in cache.
-
- return $is_pascal;
-} # 1}}}
-sub really_is_incpascal { # {{{1
-# Given filename, returns TRUE if its contents really are Pascal.
-# For .inc files (mainly seen in fpc)
-
- my $filename = shift;
- chomp($filename);
-
-# The heuristic is as follows: it is Pacal if any of the following:
-# 1. really_is_pascal returns true
-# 2. Any usual reserverd word is found (program, unit, const, begin...)
-
- # If the general routine for Pascal files works, we have it
- if (&really_is_pascal ($filename)) {
- $pascal_files{$filename} = 1;
- return 1;
- }
-
- my $is_pascal = 0; # Value to determine.
- my $found_begin = 0;
-
- open(PASCAL_FILE, "<$filename") ||
- die "Can't open $filename to determine if it's pascal.\n";
- while(<PASCAL_FILE>) {
- s/\{.*?\}//g; # Ignore {...} comments on this line; imperfect, but effective.
- s/\(\*.*?\*\)//g; # Ignore (*...*) comments on this line; imperfect, but effective.
- if (m/\bprogram\s+[A-Za-z]/i) {$is_pascal=1;}
- if (m/\bunit\s+[A-Za-z]/i) {$is_pascal=1;}
- if (m/\bmodule\s+[A-Za-z]/i) {$is_pascal=1;}
- if (m/\bprocedure\b/i) {$is_pascal = 1; }
- if (m/\bfunction\b/i) {$is_pascal = 1; }
- if (m/^\s*interface\s+/i) {$is_pascal = 1; }
- if (m/^\s*implementation\s+/i) {$is_pascal = 1; }
- if (m/\bconstant\s+/i) {$is_pascal=1;}
- if (m/\bbegin\b/i) { $found_begin = 1; }
- if ((m/end\.\s*$/i) && ($found_begin = 1)) {$is_pascal = 1;}
- if ($is_pascal) {
- last;
- }
- }
-
- close(PASCAL_FILE);
- $pascal_files{$filename} = $is_pascal; # Store result in cache.
- return $is_pascal;
-} # 1}}}
-sub really_is_php { # {{{1
-# Given filename, returns TRUE if its contents really is php.
-
- my $filename = shift;
- chomp($filename);
-
- my $is_php = 0; # Value to determine.
- # Need to find a matching pair of surrounds, with ending after beginning:
- my $normal_surround = 0; # <?; bit 0 = <?, bit 1 = ?>
- my $script_surround = 0; # <script..>; bit 0 = <script language="php">
- my $asp_surround = 0; # <%; bit 0 = <%, bit 1 = %>
-
- # Return cached result, if available:
- if ($php_files{$filename}) { return $php_files{$filename};}
-
- open(PHP_FILE, "<$filename") ||
- die "Can't open $filename to determine if it's php.\n";
- while(<PHP_FILE>) {
- if (m/\<\?/) { $normal_surround |= 1; }
- if (m/\?\>/ && ($normal_surround & 1)) { $normal_surround |= 2; }
- if (m/\<script.*language="?php"?/i) { $script_surround |= 1; }
- if (m/\<\/script\>/i && ($script_surround & 1)) { $script_surround |= 2; }
- if (m/\<\%/) { $asp_surround |= 1; }
- if (m/\%\>/ && ($asp_surround & 1)) { $asp_surround |= 2; }
- }
- close(PHP_FILE);
-
- if ( ($normal_surround == 3) || ($script_surround == 3) ||
- ($asp_surround == 3)) {
- $is_php = 1;
- }
-
- $php_files{$filename} = $is_php; # Store result in cache.
-
- return $is_php;
-} # 1}}}
-__END__
-mode values (stat $item)[2]
- Unix Windows
-file: 33188 33206
-dir : 16832 16895
-link: 33261 33206
-pipe: 4544 null
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cloc-1.04.pl
___________________________________________________________________
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/kdevsloc.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevSloc" version="1">
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.cpp (nonexistent)
@@ -1,19 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/SlocPlugin.kdev4 (nonexistent)
@@ -1,3 +0,0 @@
-[Project]
-Name=SlocPlugin
-Manager=KDevCMakeManager
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportwidget.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportwidget.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportwidget.cpp (nonexistent)
@@ -1,19 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/reportmodel.h (nonexistent)
@@ -1,55 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include <QStandardItem>
-#include <KUrl>
-
-namespace Sloc
-{
-
-enum
-{
- FileType = QStandardItem::UserType+1
-};
-
-enum
-{
- SortRole = Qt::UserRole+1
-};
-
-}
-
-class SlocFileItem : public QStandardItem
-{
-public:
- SlocFileItem(const KUrl& location) : QStandardItem(location.path()), m_location(location) {
- setData(location.path(), Sloc::SortRole);
- setEditable(false);
- }
- virtual ~SlocFileItem() {}
- virtual int type() const { return Sloc::FileType; }
- virtual void truncate(const KUrl& prefix) {
- if (!prefix.isParentOf(m_location)) return;
- setData(KUrl::relativeUrl(prefix, m_location), Qt::DisplayRole);
- }
-
-private:
- KUrl m_location;
-};
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.cpp (nonexistent)
@@ -1,114 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "slocplugin.h"
-
-#include <KAction>
-#include <KActionCollection>
-#include <KDebug>
-#include <KLocale>
-#include <KPluginFactory>
-#include <KPluginLoader>
-
-#include <project/projectmodel.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <project/interfaces/iprojectfilemanager.h>
-
-#include <interfaces/context.h>
-#include <interfaces/contextmenuextension.h>
-#include <interfaces/iproject.h>
-
-#include <QTreeView>
-#include <QHeaderView>
-#include <QSortFilterProxyModel>
-
-#include "clocparser.h"
-#include "reportmodel.h"
-
-using namespace KDevelop;
-
-K_PLUGIN_FACTORY(SlocPluginFactory, registerPlugin<SlocPlugin>();)
-K_EXPORT_PLUGIN(SlocPluginFactory("kdevsloc"))
-
-SlocPlugin::SlocPlugin(QObject* parent, const QVariantList&)
- : KDevelop::IPlugin( SlocPluginFactory::componentData(), parent )
-{
- setXMLFile("kdevsloc.rc");
- m_report = actionCollection()->addAction("spawn_sloc");
- m_report->setText(i18n("SLOC Report"));
- connect(m_report, SIGNAL(triggered()), this, SLOT(startParser()));
- m_watcher = new QFutureWatcher<QList<QStandardRow> >(this);
- connect(m_watcher, SIGNAL(finished()), SLOT(spawnReport()));
-}
-
-SlocPlugin::~SlocPlugin()
-{}
-
-#include <QtConcurrentRun>
-#include <QFutureWatcher>
-
-void SlocPlugin::startParser()
-{
- ClocParser* parser = new ClocParser;
- QFuture<QList< QStandardRow> > rows = QtConcurrent::run(parser, &ClocParser::parse, m_folder);
- m_watcher->setFuture(rows);
-}
-
-void SlocPlugin::spawnReport()
-{
- QList<QStandardRow> rows = m_watcher->future().result();
- QStandardItemModel* model = new QStandardItemModel();
- model->setHorizontalHeaderLabels(QStringList() << i18nc("Source file", "File") << i18n("Code") << i18n("Comments") << i18nc("Programming language", "Language"));
- foreach(QStandardRow row, rows) {
- model->appendRow(row);
- }
- QTreeView* view = new QTreeView();
- view->header()->setMovable(false);
- view->setUniformRowHeights(true);
- QSortFilterProxyModel* proxy = new QSortFilterProxyModel;
- proxy->setSourceModel(model);
- proxy->setSortRole(Sloc::SortRole);
- view->setModel(proxy);
- view->setSortingEnabled(true);
- view->show();
-}
-
-ContextMenuExtension SlocPlugin::contextMenuExtension(Context* context)
-{
- ContextMenuExtension cm;
- if (context->type() != Context::ProjectItemContext) {
- return cm; // NO-OP
- }
- ProjectItemContext *pc = dynamic_cast<ProjectItemContext*>(context);
- if (!pc) {
- kWarning() << "Context::ProjectItemContext but cast failed. Not good.";
- return cm;
- }
- QList<ProjectBaseItem*> bl = pc->items();
- if (!bl.count() || !bl[0] || !bl[0]->folder()) {
- return cm; // only show Sloc menu action on folders
- }
- m_folder = bl[0]->folder()->url();
- cm.addAction(ContextMenuExtension::ExtensionGroup, m_report);
-
- return cm;
-}
-
-#include "slocplugin.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocplugin.h (nonexistent)
@@ -1,57 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef SLOCPLUGIN_H
-#define SLOCPLUGIN_H
-
-#include <QVariantList>
-#include <KUrl>
-#include <interfaces/iplugin.h>
-#include <QFutureWatcher>
-#include "clocparser.h"
-
-namespace KDevelop
-{
-class ContextMenuExtension;
-class Context;
-}
-class KAction;
-
-class SlocPlugin : public KDevelop::IPlugin
-{
-Q_OBJECT
-
-public:
- explicit SlocPlugin(QObject* parent, const QVariantList& = QVariantList());
- virtual ~SlocPlugin();
- KDevelop::ContextMenuExtension contextMenuExtension(KDevelop::Context* context);
-
-private slots:
- void startParser();
- void spawnReport();
-
-private:
- KUrl m_folder;
- KAction* m_report;
- QFutureWatcher<QList<QStandardRow> >* m_watcher;
-};
-
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.cpp (nonexistent)
@@ -1,19 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/slocproxymodel.h (nonexistent)
@@ -1,19 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.cpp (nonexistent)
@@ -1,132 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "clocparser.h"
-#include "reportmodel.h"
-
-#include <KProcess>
-#include <KUrl>
-#include <KDebug>
-
-namespace
-{
-
-QMap<QString, QString> extensions()
-{
-/*./cloc-1.04.pl --show-ext
-abap -> ABAP
-ac -> m4
-ada -> Ada
-adb -> Ada
-ads -> Ada
-adso -> ADSO/IDSM
-am -> make
-ample -> AMPLE */
-
- KProcess cloc;
- QStringList argv;
- cloc.setProgram("cloc-1.04.pl", QStringList() << "--show-ext");
- cloc.setOutputChannelMode(KProcess::SeparateChannels);
- cloc.start();
- cloc.waitForFinished(-1);
- QString out(cloc.readAllStandardOutput());
- QMap<QString,QString> results;
- foreach(QString line, out.split("\n")) {
- QStringList spl = line.split("->");
- if (spl.count() != 2) continue;
- results[spl[0].simplified()] = spl[1].simplified();
- }
- return results;
-}
-
-QString executeCloc(const KUrl& directory)
-{
- KProcess cloc;
- QStringList argv;
- argv << "--by-file" << "--exclude-dir=.svn,build" << "--no3" << "--quiet" << "--csv" << directory.path();
- cloc.setProgram("cloc-1.04.pl", argv);
- cloc.setOutputChannelMode(KProcess::SeparateChannels);
- cloc.start();
- cloc.waitForFinished(-1);
- return cloc.readAllStandardOutput();
-}
-
-}
-
-QStandardRow ClocParser::parseLine(const QString& line, const Languages& languages)
-{
- QStandardRow row;
- if (line.isEmpty() || line.startsWith(",,")) return row;
- QStringList spl = line.split(",");
- if (spl.count() != 5) return row;
-
- QString file = spl[0];
- QString extension = file.split(".").value(file.split(".").count()-1);
- QString language = (languages.contains(extension)) ? languages[extension] : "unknown";
- int blank = spl[2].toInt();
- int comment = spl[3].toInt();
- int code = spl[4].toInt();
- kDebug() << file << blank << comment << code;
-
- SlocFileItem* fileItem = new SlocFileItem(file);
- fileItem->truncate(m_root);
- QStandardItem* languageItem = new QStandardItem(language);
- languageItem->setData(language, Sloc::SortRole);
- languageItem->setEditable(false);
-// QStandardItem* blankItem = new QStandardItem(QString::number(blank));
-// blankItem->setSortRole(blank, Sloc::SortRole)
-// blankItem->setEditable(false);
- QStandardItem* commentItem = new QStandardItem(QString::number(comment));
- commentItem->setData(comment, Sloc::SortRole);
- commentItem->setEditable(false);
- QStandardItem* codeItem = new QStandardItem(QString::number(code));
- codeItem->setData(code, Sloc::SortRole);
- codeItem->setEditable(false);
-
- return row << fileItem << codeItem << commentItem << languageItem;
-}
-
-QList<QStandardRow> ClocParser::parse(const KUrl& directory)
-{
-
-// ./cloc-1.04.pl --by-file --exclude-dir=build --no3 --quiet --csv .
-//
-// ,,blank,comment,code,"http://cloc.sourceforge.net v 1.04 T=0.5 s (18.0 files/s, 13034.0 lines/s)"
-// ./slocplugin.cpp,1,13,19,61
-// ./slocproxymodel.cpp,1,11,18,34
-// ./clocparser.cpp,1,8,9,34
-// ./slocplugin.h,1,9,19,25
-// ./slocproxymodel.h,1,9,19,20
-
- if (directory.isEmpty()) return QList<QStandardRow>();
- m_root = directory;
-
- QMap<QString,QString> languages = extensions();
- QString out = executeCloc(directory);
- QList<QStandardRow> rows;
-
- foreach(QString line, out.split("\n")) {
- QStandardRow row = parseLine(line, languages);
- if (!row.isEmpty()) rows << row;
- }
-
- return rows;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/sloc/clocparser.h (nonexistent)
@@ -1,43 +0,0 @@
-/*
- * This file is part of KDevelop
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CLOCPARSER_H
-#define CLOCPARSER_H
-
-#include <QStandardItem>
-#include <KUrl>
-
-typedef QList<QStandardItem*> QStandardRow;
-typedef QMap<QString, QString> Languages;
-
-class ClocParser
-{
-public:
- /*! Execute CLOC process and parse output into a QStandardItem tree.
- * @param directory compute sloc for this dir, recursivly
- * @return top rows */
- QList<QStandardRow> parse(const KUrl& directory);
-
-private:
- QStandardRow parseLine(const QString& line, const Languages& languages);
- KUrl m_root;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/CMakeLists.txt (nonexistent)
@@ -1,19 +0,0 @@
-project(KDevPreprocessor)
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${KDevPreprocessor_BINARY_DIR}
-)
-
-set(pp_SRCS preprocessorplugin.cpp preprocessorview.cpp)
-
-kde4_add_plugin(kdevpreprocessor ${pp_SRCS})
-
-target_link_libraries(kdevpreprocessor ${KDE4_KDECORE_LIBS} ${KDE4_KDEUI_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_UTIL_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES})
-
-install(TARGETS kdevpreprocessor DESTINATION ${PLUGIN_INSTALL_DIR})
-install(FILES kdevpreprocessor.desktop DESTINATION ${SERVICES_INSTALL_DIR})
-install(FILES kdevpreprocessor.rc DESTINATION ${DATA_INSTALL_DIR}/kdevpreprocessor)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.cpp (nonexistent)
@@ -1,69 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Preprocessor-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "preprocessorplugin.h"
-
-#include "preprocessorview.h"
-
-#include <KPluginFactory>
-#include <KPluginLoader>
-#include <KAboutData>
-#include <KDebug>
-#include <KActionCollection>
-#include <KAction>
-#include <KLocale>
-
-K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<PreprocessorPlugin>();)
-K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("kdevpreprocessor","kdevpreprocessor", ki18n ("Preprocess the Current File"), "0.1", ki18n ("Preprocess the Current File"), KAboutData::License_GPL)))
-
-PreprocessorPlugin::PreprocessorPlugin (QObject *parent, const QVariantList &)
-:IPlugin (KdevPlugFactory::componentData(), parent)
-{
- setXMLFile ("kdevpreprocessor.rc");
-
- m_actionPreprocess = actionCollection()->addAction ("file_preprocess");
- m_actionPreprocess->setIcon (KIcon ("circle2"));
- m_actionPreprocess->setText (i18n ("Preprocess File"));
- m_actionPreprocess->setShortcut (KShortcut ("Ctrl+Alt+Shift+p"));
- connect (m_actionPreprocess, SIGNAL (triggered (bool)), this, SLOT (preprocess()));
- m_actionPreprocess->setToolTip (i18n ("Preprocess the Current File"));
- m_actionPreprocess->setWhatsThis (i18n ("<b>Preprocessor</b><p> View the preprocessor ouput, the content of included files will not be displayed</p>"));
-
- m_actionPreprocessWithIncludes = actionCollection()->addAction ("file_preprocess_with_includes");
- m_actionPreprocessWithIncludes->setIcon (KIcon ("circle"));
- m_actionPreprocessWithIncludes->setText (i18n ("Preprocess File (with included content)"));
- m_actionPreprocessWithIncludes->setWhatsThis (i18n ("<b>Preprocessor</b><p> View the preprocessor output including all included files</p>"));
- connect (m_actionPreprocessWithIncludes, SIGNAL (triggered (bool)), this, SLOT (preprocessWithIncludes()));
- m_actionPreprocessWithIncludes->setToolTip (i18n ("Preprocess the Current File and Display the Content of Included Files"));
-}
-
-PreprocessorPlugin::~PreprocessorPlugin()
-{
-}
-
-void PreprocessorPlugin::preprocess()
-{
- new PreprocessorView(this, false);
-}
-
-void PreprocessorPlugin::preprocessWithIncludes()
-{
- new PreprocessorView(this, true);
-}
-
-#include "preprocessorplugin.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorplugin.h (nonexistent)
@@ -1,51 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Preprocessor-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef PREPROCESSORPLUGIN_H
-#define PREPROCESSORPLUGIN_H
-
-#include <interfaces/iplugin.h>
-
-#include <QVariantList>
-
-class KAction;
-
-using namespace KDevelop;
-
-namespace KDevelop
-{
- class Declaration;
- class DUContext;
- class ClassDeclaration ;
- class ClassMemberDeclaration ;
-}
-
-class PreprocessorPlugin : public KDevelop::IPlugin
-{
- Q_OBJECT
- public:
- PreprocessorPlugin (QObject *parent, const QVariantList & = QVariantList());
- ~PreprocessorPlugin();
- private slots:
- void preprocess();
- void preprocessWithIncludes();
- private:
- KAction *m_actionPreprocess, *m_actionPreprocessWithIncludes;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.cpp (nonexistent)
@@ -1,180 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Preprocessor-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "preprocessorview.h"
-
-#include <QStringList>
-#include <KTextEditor/View>
-#include <KTextEditor/Document>
-#include <KTextEditor/MarkInterface>
-#include <KTextEditor/Editor>
-#include <KLocale>
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-#include <interfaces/iprojectcontroller.h>
-#include <interfaces/iproject.h>
-#include <project/projectmodel.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <util/commandexecutor.h>
-#include <KDebug>
-
-using namespace KDevelop;
-using namespace KTextEditor;
-
-PreprocessorView::PreprocessorView(QObject* parent, bool showIncludedFiles) : QObject(parent), state(showIncludedFiles ? WithIncludedFiles : InFile), document (KTextEditor::editor ("katepart")->createDocument(this)), view(document->createView (0))
-{
- view->setWindowTitle(i18n("Preprocessor Output"));
- view->setWindowFlags(Qt::Window);
- view->setAttribute(Qt::WA_DeleteOnClose);
- connect(view, SIGNAL(destroyed()), this, SLOT(deleteMe()));
-
- document->setHighlightingMode("cpp");
- IDocument *doc;
- if((doc = ICore::self()->documentController()->activeDocument()) == 0)
- return;
- QString command = "g++";
- QStringList args;
- args << "-E";
- args << (file = doc->url().path());
- QString builddir;
- if(IProject *project = ICore::self()->projectController()->findProjectForUrl(doc->url()))
- {
- if(IBuildSystemManager *buildsystem = project->buildSystemManager())
- {
- builddir = buildsystem->buildDirectory(project->projectItem()).path();
- foreach(const KUrl& include, buildsystem->includeDirectories(project->projectItem()))
- args << "-I" + include.url();
- }
- }
- if(builddir.isEmpty())
- {
- builddir = doc->url().path();
- size_t x = builddir.lastIndexOf('/');
- if(x < 1)
- builddir = '.';
- else
- builddir.remove(x, builddir.length() - x);
- }
- args << "-I.";
- kDebug() << command << " in " << builddir;
- CommandExecutor *cmd = new CommandExecutor (command, this);
- connect(cmd, SIGNAL(receivedStandardOutput(const QStringList&)),
- this, SLOT(addLines(const QStringList&) ), Qt::DirectConnection );
- connect(cmd, SIGNAL(receivedStandardError(const QStringList&)),
- this, SLOT(addErrorLines(const QStringList&) ), Qt::DirectConnection );
- cmd->setWorkingDirectory( builddir );
- cmd->setArguments( args );
- connect( cmd, SIGNAL( failed() ), this, SLOT( failed() ), Qt::DirectConnection );
- connect( cmd, SIGNAL( completed() ), this, SLOT( completed() ), Qt::DirectConnection );
- view->setWindowState(Qt::WindowMaximized | Qt::WindowActive);
- view->show();
- cmd->start();
-}
-
-PreprocessorView::~PreprocessorView()
-{
- if(view)
- delete view;
-}
-
-void PreprocessorView::deleteMe()
-{
- view = 0;
- delete this;
-}
-
-void PreprocessorView::failed()
-{
- document->insertLine(document->lines(), i18n("*FAILED*"));
- qobject_cast<MarkInterface*>(document)->setMark(document->lines() - 1, MarkInterface::Execution | MarkInterface::Error);
-}
-
-void PreprocessorView::completed()
-{
- document->insertLine(document->lines(), i18n("*SUCCEEDED*"));
- qobject_cast<MarkInterface*>(document)->setMark(document->lines() - 1, MarkInterface::Execution);
-}
-
-void PreprocessorView::addErrorLines(const QStringList& list)
-{
- MarkInterface *mi = qobject_cast<MarkInterface*>(document);
- foreach(const QString& line, list)
- {
- document->insertLine(document->lines(), line);
- mi->setMark(document->lines() - 1, MarkInterface::Warning);
- }
-}
-
-inline bool subStartsWith(const QString& str, const QString& pattern, int pos)
-{
- int end = pattern.size() + pos;
- if(end >= str.size())
- return false;
- for(int i = 0; pos != end; ++pos, ++i)
- if(str[pos] != pattern[i])
- return false;
- return true;
-}
-
-inline bool matching(const QString& line, const QString& file)
-{
- int pos = line.indexOf(' ');
- if(pos > 0)
- {
- pos = line.indexOf(' ', pos + 1);
- return pos > 0
- && line.length() > pos + 3
- && line[++pos] == '"'
- && subStartsWith(line, file, ++pos)
- && line[pos + file.length()] == '"';
- }
- return false;
-}
-
-void PreprocessorView::addLines(const QStringList& list)
-{
- if(state == WithIncludedFiles)
- {
- foreach(const QString& line, list)
- document->insertLine(document->lines(), line);
- }
- else
- {
- foreach(const QString& line, list)
- {
- if(state == InFile)
- {
- if(line[0] == '#')
- {
- if(!matching(line, file))
- state = InAnotherFile;
- }
- else
- document->insertLine(document->lines(), line);
- }
- else
- {
- if(line[0] == '#' && matching(line, file))
- state = InFile;
- }
- }
- }
-}
-
-#include "preprocessorview.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/preprocessorview.h (nonexistent)
@@ -1,50 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Preprocessor-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef PREPROCESSORVIEW_H
-#define PREPROCESSORVIEW_H
-
-#include <QObject>
-#include <QStringList>
-
-namespace KTextEditor
-{
- class View;
- class Document;
-}
-
-class PreprocessorView : public QObject
-{
- Q_OBJECT
- public:
- PreprocessorView(QObject* parent, bool showIncludedFiles);
- ~PreprocessorView();
- private slots:
- void addLines(const QStringList& output);
- void addErrorLines(const QStringList& output);
- void completed();
- void failed();
- void deleteMe();
- private:
- enum { WithIncludedFiles, InFile, InAnotherFile } state;
- KTextEditor::Document *document;
- KTextEditor::View *view;
- QString file;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.desktop (nonexistent)
@@ -1,71 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=C/C++ Preprocessing
-Comment[bs]=C/C++ preobrade
-Comment[ca]=Preprocessament C/C++
-Comment[ca@valencia]=Preprocessament C/C++
-Comment[de]=C/C++ Vorverarbeitung
-Comment[en_GB]=C/C++ Preprocessing
-Comment[es]=Preproceso de C/C++
-Comment[et]=C/C++ eelprotsessor
-Comment[fr]=Prétraitement du C / C++
-Comment[gl]=Pre-procesamento de C/C++
-Comment[hu]=C/C++ előfeldolgozás
-Comment[it]=Preprocessazione C/C++
-Comment[nl]=C/C++ Preprocessing
-Comment[pl]=C/C++ Preprocessing
-Comment[pt]=Pré-Processamento de C/C++
-Comment[pt_BR]=Pré-Processamento de C/C++
-Comment[sv]=C och C++ preprocessor
-Comment[uk]=Попередня обробка C/C++
-Comment[x-test]=xxC/C++ Preprocessingxx
-Name=C/C++ Preprocessor
-Name[bs]=C/C++ preobrade
-Name[ca]=Preprocessador C/C++
-Name[ca@valencia]=Preprocessador C/C++
-Name[de]=C/C++ Preprocessor
-Name[en_GB]=C/C++ Preprocessor
-Name[es]=Preprocesador de C/C++
-Name[et]=C/C++ eelprotsessor
-Name[fr]=Préprocesseur C / C++
-Name[gl]=Pre-procesador de C/C++
-Name[hu]=C/C++ előfeldolgozó
-Name[it]=Preprocessore C/C++
-Name[nl]=C/C++ Preprocessor
-Name[pl]=C/C++ Preprocessor
-Name[pt]=Pré-processador de C/C++
-Name[pt_BR]=Pré-processador de C/C++
-Name[sv]=C/C++ preprocessor
-Name[uk]=Попередня обробка у C/C++
-Name[x-test]=xxC/C++ Preprocessorxx
-GenericName=C/C++ Preprocessor
-GenericName[bs]=C/C++ preobrade
-GenericName[ca]=Preprocessador C/C++
-GenericName[ca@valencia]=Preprocessador C/C++
-GenericName[de]=C/C++ Preprocessor
-GenericName[en_GB]=C/C++ Preprocessor
-GenericName[es]=Preprocesador de C/C++
-GenericName[et]=C/C++ eelprotsessor
-GenericName[fr]=Préprocesseur C / C++
-GenericName[gl]=Pre-procesador de C/C++
-GenericName[hu]=C/C++ előfeldolgozó
-GenericName[it]=Preprocessore C/C++
-GenericName[nl]=C/C++ Preprocessor
-GenericName[pl]=C/C++ Preprocessor
-GenericName[pt]=Pré-processador de C/C++
-GenericName[pt_BR]=Pré-processador de C/C++
-GenericName[sv]=C/C++ preprocessor
-GenericName[uk]=Попередня обробка у C/C++
-GenericName[x-test]=xxC/C++ Preprocessorxx
-Icon=kdevelop
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevpreprocessor
-X-KDE-PluginInfo-Name=kdevpreprocessor
-X-KDE-PluginInfo-Author=Jonathan Schmidt-Dominé (The User)
-X-KDE-PluginInfo-Email=devel@the-user.org
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=9
-X-KDevelop-Mode=GUI
-X-KDevelop-Category=Global
-X-KDevelop-Language=C++
Index: trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/preprocessor/kdevpreprocessor.rc (nonexistent)
@@ -1,11 +0,0 @@
-<!DOCTYPE kpartgui>
-<kpartplugin name="kdevpreprocessor" library="libkdevpreprocessor" version="7">
-<MenuBar>
- <Menu name="project">
- <Action name="file_preprocess"
- group="build_operations"/>
- <Action name="file_preprocess_with_includes"
- group="build_operations"/>
- </Menu>
-</MenuBar>
-</kpartplugin>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlang.g
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlang.g (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlang.g (nonexistent)
@@ -1,698 +0,0 @@
--------------------------------------------------------------------------------
--- Copyright (c) 2010 Victor Vicente de Carvalho <victor.v.carvalho at gmail.com>
---
--- This grammar 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 grammar 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
--- Lesser 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.
------------------------------------------------------------
-
-
------------------------------------------------------------
--- Grammar for Erlang
--- Parts taken from KDevelop PHP Grammar, based on
---- erl_parse.yrl found on erlang otp source code
------------------------------------------------------------
-
-
-[:
-
-
-namespace KDevelop
-{
- class DUContext;
-}
-
-:]
-
-%parser_declaration_header "QtCore/QString"
-%parser_declaration_header "kdebug.h"
-%parser_declaration_header "language/interfaces/iproblem.h"
-%parser_declaration_header "parser/tokenstream.h"
-%parser_declaration_header "parser/erlanglexer.h"
-
-------------------------------------------------------------
--- Export macro to use the parser in a shared lib
-------------------------------------------------------------
-%export_macro "KDEVERLANGPARSER_EXPORT"
-%export_macro_header "parser/parserexport.h"
-
-------------------------------------------------------------
--- Ast Node class members
-------------------------------------------------------------
-%ast_extra_members
-[:
- KDevelop::DUContext* ducontext;
-
- virtual ~AstNode() { }
-:]
-
-------------------------------------------------------------
--- Parser class members
-------------------------------------------------------------
-
-%parserclass (public declaration)
-[:
- /**
- * Transform the raw input into tokens.
- * When this method returns, the parser's token stream has been filled
- * and any parse*() method can be called.
- */
- void tokenize(const QString& contents, int initialState = Lexer::DefaultState);
-
- enum ProblemType {
- Error,
- Warning,
- Info
- };
-
-
-
- void reportProblem( Parser::ProblemType type, const QString& message );
- QList<KDevelop::ProblemPointer> problems() {
- return m_problems;
- }
- QString tokenText(qint64 begin, qint64 end);
- void setDebug(bool debug);
- void setCurrentDocument(QString url);
-
- enum InitialLexerState {
- HtmlState = 0,
- DefaultState = 1
- };
-
-:]
-
-%parserclass (private declaration)
-[:
- enum VarExpressionState {
- Normal,
- OnlyVariable,
- OnlyNewObject
- };
-
- struct ParserState {
- VarExpressionState varExpressionState;
- bool varExpressionIsVariable;
- };
-
- QString m_contents;
- bool m_debug;
- QString m_currentDocument;
- QList<KDevelop::ProblemPointer> m_problems;
-
-
- ParserState m_state;
-:]
-
-%parserclass (constructor)
-[:
- m_state.varExpressionState = Normal;
- m_state.varExpressionIsVariable = false;
-:]
-
-
-%token_stream TokenStream ;;
-
------------------------------------------------------------
--- List of defined tokens
------------------------------------------------------------
--- keywords:
-%token AFTER("after"), BEGIN("begin"), CASE("case"), CATCH("catch"), COND("cond"),
- END("end"), FUN("fun"), IF("if"), LET("let"), OF("of"), QUERY("query"),
- RECEIVE("receive"), WHEN("when"), SPEC("spec"), TRY("try");;
-
--- seperators:
-%token LBRACKET ("["), RBRACKET ("]"), LPAREN ("("),
- RPAREN (")"), LBRACE ("{"), RBRACE ("}"),
- COMMA (","), LEADS_TO("->"), QUESTION("?"),
- PIPE("|"), DOUBLE_PIPE("||"), POUND_SIGN("#"), DOT("."),
- SEMICOLON (";"), COLON(":"),DOUBLE_COLON("::"), UNDERLINE("_"),
- BINARY_OPEN("<<"), BINARY_CLOSE(">>");;
-
--- operators:
-%token IS_EQUAL ("=="), IS_NOT_EQUAL ("/="), EXACT_EQUATIONAL ("=:="),
- EXACT_NOT_EQUATIONAL ("=/="), IS_SMALLER ("<"), IS_GREATER (">"),
- IS_SMALLER_OR_EQUAL ("=<"), IS_GREATER_OR_EQUAL (">="),
- ASSIGN ("="), PLUS ("+"), MINUS("-"),
- LIST_ADDITION ("++"), LIST_DIFFERENCE ("--"),
- BIT_OR("bor"), BIT_XOR ("bxor"), XOR("xor"), OR("or"),
- SL ("bsl"), SR ("bsr"), MUL("*"), FORWARD_SLASH("/"), MOD ("%"),
- INT_DIV("div"), INT_REM("rem"), BIT_AND("band"), AND("and"), BIT_NOT("bnot"),
- NOT("not"), EXCLAMATION("!"), LIST_COMPREHENSION_LEADS_TO("<-"),
- ORELSE("orelse"), ANDALSO("andalso");;
-
--- literals and identifiers:
-%token CHAR_LITERAL("char_literal"), COMMENT("comment"),
- WHITESPACE ("whitespace"), VARIABLE ("variable"),
- NUM_STRING ("num string"), INTEGER_LITERAL("integer literal"),
- STRING_LITERAL ("string literal"), ATOM_LITERAL("atom literal"),
- HALT_COMPILER ("halt compiler");;
-
---macros
-
-%token INCLUDE_DIRECTIVE("include"), IMPORT_DIRECTIVE("import"),
- FILE_DIRECTIVE("file directive"), COMPILE_DIRECTIVE("compile directive"),
- DEFINE_DIRECTIVE("define"), MODULE_DIRECTIVE("module"),
- RECORD_DIRECTIVE("record"), UNDEF("undef"),
- IFDEF_DIRECTIVE("ifdef macro directive"),
- IFNDEF_DIRECTIVE("ifndef macro directive"),
- ELSE_DIRECTIVE("else macro directive"),
- ENDIF_DIRECTIVE("endif macro directive"), INCLUDE_LIB("include"),
- EXPORT_DIRECTIVE("exported functions"),
- BEHAVIOUR_DIRECTIVE("module behaviour"),
- FLOAT_LITERAL("float literal");;
-
--- token that makes the parser fail in any case:
-%token INVALID ("invalid token") ;;
-
--- The actual grammar starts here.
-
- attribute=attribute DOT form_next=form
- | functions=functionOrRule DOT form_next=form
- | 0
--> form;;
-
- MINUS ( SPEC type_spec=typeSpec
- | module_declaration=moduleDeclaration
- | export_declaration=exportDeclaration
- | import_declaration=importDeclaration
- | record_declaration=recordDeclaration
- | file_declaration=fileDeclaration
- | define_declaration=defineDeclaration
- | behaviour_declaration=behaviourDeclaration
- | attribute_declaration=attributeDeclaration
- | include_declaration=includeDeclaration )
--> attribute;;
-
- MODULE_DIRECTIVE LPAREN module_name=ATOM_LITERAL RPAREN
--> moduleDeclaration;;
-
- BEHAVIOUR_DIRECTIVE LPAREN behaviour=ATOM_LITERAL RPAREN
--> behaviourDeclaration;;
-
-
- EXPORT_DIRECTIVE LPAREN LBRACKET (#exported_functions=functionSlashArity @ COMMA | 0) RBRACKET RPAREN
--> exportDeclaration;;
-
- function_name=ATOM_LITERAL FORWARD_SLASH function_arity=INTEGER_LITERAL
--> functionSlashArity;;
-
- IMPORT_DIRECTIVE LPAREN module_name=ATOM_LITERAL COMMA #imported_functions=functionSlashArity @ COMMA RPAREN
--> importDeclaration;;
-
- RECORD_DIRECTIVE LPAREN record_name=ATOM_LITERAL COMMA type_record_fields=typedRecordFields RPAREN
--> recordDeclaration;;
-
- FILE_DIRECTIVE LPAREN file_name=STRING_LITERAL COMMA line=INTEGER_LITERAL RPAREN
--> fileDeclaration;;
-
- DEFINE_DIRECTIVE LPAREN define_name=VARIABLE (argument_list=argumentList | 0 ) COMMA expression=expr RPAREN
--> defineDeclaration;;
-
- ATOM_LITERAL LPAREN name=STRING_LITERAL COMMA line=INTEGER_LITERAL RPAREN
--> attributeDeclaration;;
-
- INCLUDE_DIRECTIVE LPAREN STRING_LITERAL RPAREN
--> includeDeclaration;;
-
- SPEC
- | literal=ATOM_LITERAL
--> atom1;;
-
- expr=expr ( COMMA LBRACE typed_exprs=typedExprs RBRACE | DOUBLE_COLON top_type=topType)
--> typedAttrVal;;
-
- try/rollback(LPAREN expr=expr COMMA exprs=exprs RPAREN)
- catch(expr=expr ( COMMA exprs=exprs | 0 ))
--> attrVal;;
-
- (LPAREN | 0) spec_fun=specFun types_sigs=typeSigs (RPAREN | 0)
--> typeSpec;;
-
- atom1 ( COLON ATOM_LITERAL | 0 )
--> specFun;;
-
- #e=exprOrTypedExpr @ COMMA
--> typedExprs;;
-
- typed_expr=typedExpr
- | expr=expr
--> exprOrTypedExpr;;
-
- LBRACE typed_exprs=typedExprs RBRACE
--> typedRecordFields;;
-
- DOUBLE_COLON top_type=topType
--> typedExpr;;
-
- #ts=typeSig @ SEMICOLON
-->typeSigs;;
-
- fun_type=funType (WHEN type_guards=typeGuards | 0)
--> typeSig;;
-
- #tg=typeGuard @ COMMA
--> typeGuards;;
-
- atom1 LPAREN top_type=topTypes RPAREN
--> typeGuard;;
-
- #tt=topType @ COMMA
--> topTypes;;
-
- (VARIABLE DOUBLE_COLON | 0) top_type100=topType100
--> topType;;
-
- type=type ( PIPE top_type100=topType100 | 0 )
-->topType100;;
-
- LPAREN top_type=topType RPAREN
- | VARIABLE
- | atom1 ( LPAREN (top_types=topTypes | 0) RPAREN
- | COLON atom1 LPAREN (top_types=topTypes | 0) RPAREN
- | 0)
- | LBRACKET (top_type=topType (COMMA DOT DOT DOT | 0) | 0) RBRACKET
- | LBRACE (top_types=topTypes | 0 ) RBRACE
- | POUND_SIGN atom1 LBRACE (field_types=fieldTypes | 0 ) RBRACE
- | binary_type=binaryType
- | INTEGER_LITERAL ( DOT DOT INTEGER_LITERAL | 0 )
- | FUN LPAREN (fun_type100=funType100 | 0) RPAREN
--> type;;
-
- LPAREN (DOT DOT DOT | (top_types=topTypes | 0)) RPAREN LEADS_TO top_type=topType
--> funType100;;
-
- LPAREN (top_types=topTypes | 0) RPAREN LEADS_TO top_type=topType
--> funType;;
-
- #ft=fieldType @ COMMA
--> fieldTypes;;
-
- atom1 DOUBLE_COLON top_type=topType
--> fieldType;;
-
- BINARY_OPEN ( VARIABLE COLON ( INTEGER_LITERAL ( COMMA bin_unit_type=binUnitType | 0) | bin_unit_type=binUnitType ) | 0 ) BINARY_CLOSE
--> binaryType;;
-
- VARIABLE COLON
--> binBaseType;;
-
- VARIABLE MUL INTEGER_LITERAL
--> binUnitType;;
-
- #fc=functionOrRuleClause @ SEMICOLON
--> functionOrRule;;
-
- function_name=atom1 clause_args=clauseArgs clause_guard=clauseGuard (body=clauseBody | rule_body=ruleBody)
-->functionOrRuleClause;;
-
- clause_list=clauseList
--> clauseArgs;;
-
- LPAREN (arg_exprs=argExprs | 0) RPAREN
--> clauseList;;
-
- #arg=expr @ COMMA
--> argExprs;;
-
- WHEN (#guards=guard @ SEMICOLON) | 0
--> clauseGuard;;
-
- LEADS_TO exprs=exprs
--> clauseBody;;
-
-%< expr700
-%pre CATCH 50
-%bin ASSIGN 100 %right
-%bin EXCLAMATION 100 %right
-%bin ORELSE 150 %right
-%bin ANDALSO 160 %right
-%bin ?[: compAllowed :] IS_EQUAL [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] IS_GREATER [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] IS_GREATER_OR_EQUAL [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] IS_NOT_EQUAL [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] IS_SMALLER [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] IS_SMALLER_OR_EQUAL [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] EXACT_NOT_EQUATIONAL [: compAllowed = false; :] 200 %left
-%bin ?[: compAllowed :] EXACT_EQUATIONAL [: compAllowed = false; :] 200 %left
-%bin LIST_ADDITION 300 %right
-%bin LIST_DIFFERENCE 300 %right
-%bin PLUS 400 %right
-%bin MINUS 400 %right
-%bin BIT_OR 400 %right
-%bin BIT_XOR 400 %right
-%bin SL 400 %right
-%bin SR 400 %right
-%bin OR 400 %right
-%bin XOR 400 %right
-%bin FORWARD_SLASH 500 %right
-%bin MUL 500 %right
-%bin INT_DIV 500 %right
-%bin INT_REM 500 %right
-%bin BIT_AND 500 %right
-%bin AND 500 %right
-%pre ?[: preAllowed :] PLUS [: preAllowed = false; :] 600
-%pre ?[: preAllowed :] MINUS [: preAllowed = false; :] 600
-%pre ?[: preAllowed :] BIT_NOT [: preAllowed = false; :] 600
-%pre ?[: preAllowed :] NOT [: preAllowed = false; :] 600
-%> expr [:
- bool preAllowed = true;
- bool compAllowed = true;
-:];;
-
- PLUS
- | MINUS
- | BIT_NOT
- | NOT
--> prefixOp ;;
-
- try/rollback(record_expr=recordExpr)
- catch(try/rollback(functionCall=functionCall)
- catch(expr800=expr800))
--> expr700;;
-
- expr900=expr900 ( COLON expr_max=exprMax | 0)
--> expr800;;
-
- DOT atom1 expr900a=expr900a
- | expr_max=exprMax
--> expr900;;
-
- DOT atom1 expr900a=expr900a | expr_max=exprMax expr900a=expr900a | 0
--> expr900a;;
-
- var=variable
- | atomic=atomic
- | try/rollback(binary=binary)
- catch(binary_comprehension=binaryComprehension)
- | try/rollback(LBRACKET (expr=expr tail=tail | RBRACKET))
- catch(list_comprehension=listComprehension)
- | tuple=tuple
- | LPAREN expr=expr RPAREN
- | BEGIN exprs=exprs END
- | if_expr=ifExpr
- | case_expr=caseExpr
- | receive_expr=receiveExpr
- | fun_expr=funExpr
- | try_expr=tryExpr
- | query_expr=queryExpr
- | QUESTION define_name=VARIABLE (define_function=argumentList | 0)
--> exprMax;;
-
- literal=VARIABLE | UNDERLINE
--> variable;;
-
- RBRACKET
- | PIPE expr=expr RBRACKET
- | COMMA expr=expr tail=tail
--> tail;;
-
- BINARY_OPEN ( bin_elements=binElements | 0 ) BINARY_CLOSE
--> binary;;
-
- #be=binElement @ COMMA
--> binElements;;
-
- bit_expr=bitExpr opt_bit_size_expr=optBitSizeExpr opt_bit_type_list=optBitTypeList
--> binElement;;
-
- (prefix_op=prefixOp | 0) expr_max=exprMax
--> bitExpr;;
-
- COLON bit_size_expr=bitSizeExpr | 0
--> optBitSizeExpr;;
-
- FORWARD_SLASH bit_type_list=bitTypeList | 0
--> optBitTypeList;;
-
- bit_type=bitType (MINUS bit_type_list=bitTypeList | 0 )
--> bitTypeList;;
-
- atom1 (COLON INTEGER_LITERAL | 0)
--> bitType;;
-
- expr_max=exprMax
--> bitSizeExpr;;
-
- LBRACKET expr=expr DOUBLE_PIPE lc_exprs=lcExprs RBRACKET
--> listComprehension;;
-
- BINARY_OPEN binary=binary DOUBLE_PIPE lc_exprs=lcExprs BINARY_CLOSE
--> binaryComprehension;;
-
- #lc=lcExpr @ COMMA
--> lcExprs;;
-
-
- try/rollback(expr=expr (LIST_COMPREHENSION_LEADS_TO expr=expr | 0))
- catch(binary=binary LIST_COMPREHENSION_LEADS_TO expr=expr)
--> lcExpr;;
-
- LBRACE (exprs | 0 ) RBRACE
--> tuple;;
-
- POUND_SIGN atom1 ( DOT atom1 | record_tuple=recordTuple )
- | expr_max=exprMax POUND_SIGN atom1 ( DOT atom1 | record_tuple=recordTuple )
--> recordExpr;;
-
- LBRACE (record_fields=recordFields | 0 ) RBRACE
--> recordTuple;;
-
- #rf=recordField @ COMMA
--> recordFields;;
-
- VARIABLE ASSIGN expr=expr
- | atom1 ASSIGN expr=expr
--> recordField;;
-
- expr800=expr800 argument_list=argumentList
--> functionCall;;
-
- IF if_clauses=ifClauses END
--> ifExpr;;
-
- #ic=ifClause @ SEMICOLON
--> ifClauses;;
-
- guard=guard clause_body=clauseBody
--> ifClause;;
-
- CASE expr=expr OF cr_clauses=crClauses END
--> caseExpr;;
-
- #cc=crClause @ SEMICOLON
--> crClauses;;
-
- expr clause_guard=clauseGuard clause_body=clauseBody
--> crClause;;
-
- RECEIVE (cr_clauses=crClauses | 0) (AFTER expr=expr clause_body=clauseBody | 0) END
--> receiveExpr;;
-
- FUN (atom1 (FORWARD_SLASH INTEGER_LITERAL | COLON atom1 FORWARD_SLASH INTEGER_LITERAL)
- | funClauses END)
--> funExpr;;
-
- #fc=funClause @ SEMICOLON
--> funClauses;;
-
- argument_list=argumentList clause_guard=clauseGuard clause_body=clauseBody
--> funClause;;
-
- TRY exprs=exprs (OF cr_clauses=crClauses | 0 ) try_catch=tryCatch
--> tryExpr;;
-
- CATCH try_clauses=tryClauses (AFTER exprs=exprs | 0) END
- | AFTER exprs=exprs END
--> tryCatch;;
-
- #tc=tryClause @ SEMICOLON
--> tryClauses;;
-
--- Using LA(2) to remove ambiguities with expr
- (?[:LA(2).kind == Token_COLON:] atom1 COLON expr=expr | ?[:LA(2).kind == Token_COLON:] VARIABLE COLON expr=expr | expr=expr) clause_guard=clauseGuard clause_body=clauseBody
--> tryClause;;
-
- QUERY list_comprehension=listComprehension END
--> queryExpr;;
-
- LPAREN (exprs=exprs | 0) RPAREN
--> argumentList;;
-
- #e=expr @ COMMA
--> exprs;;
-
- #guard=exprs
--> guard;;
-
- CHAR_LITERAL
- | (PLUS|MINUS|0) INTEGER_LITERAL
- | FLOAT_LITERAL
- | ATOM_LITERAL
- | #strings=STRING_LITERAL
--> atomic;;
-
- #rc=ruleClause @ SEMICOLON
--> ruleClauses;;
-
- atom1 clause_args=clauseArgs clause_guard=clauseGuard rule_body=ruleBody
--> ruleClause;;
-
- COLON MINUS lc_exprs=lcExprs
--> ruleBody;;
-
------------------------------------------------------------------
--- Code segments copied to the implementation (.cpp) file.
--- If existent, kdevelop-pg's current syntax requires this block
--- to occur at the end of the file.
------------------------------------------------------------------
-
-[:
-
-#include <QtCore/QDebug>
-#include <KTextEditor/Range>
-
-namespace erlang
-{
-
-void Parser::tokenize(const QString& contents, int initialState)
-{
- m_contents = contents;
- Lexer lexer(tokenStream, contents, initialState);
- int kind = Parser::Token_EOF;
- int lastDocCommentBegin;
- int lastDocCommentEnd;
-
- do
- {
- lastDocCommentBegin = 0;
- lastDocCommentEnd = 0;
- kind = lexer.nextTokenKind();
- while (kind == Parser::Token_WHITESPACE || kind == Parser::Token_COMMENT) {
- kind = lexer.nextTokenKind();
- }
- if ( !kind ) // when the lexer returns 0, the end of file is reached
- {
- kind = Parser::Token_EOF;
- }
- Parser::Token &t = tokenStream->push();
- t.begin = lexer.tokenBegin();
- t.end = lexer.tokenEnd();
- t.kind = kind;
- if ( m_debug ) qDebug() << kind << tokenText(t.begin,t.end) << t.begin << t.end;
- }
- while ( kind != Parser::Token_EOF );
-
- yylex(); // produce the look ahead token
-}
-
-QString Parser::tokenText(qint64 begin, qint64 end)
-{
- return m_contents.mid(begin,end-begin+1);
-}
-
-void Parser::reportProblem( Parser::ProblemType type, const QString& message )
-{
- if (type == Error)
- qDebug() << "** ERROR:" << message;
- else if (type == Warning)
- qDebug() << "** WARNING:" << message;
- else if (type == Info)
- qDebug() << "** Info:" << message;
-
- qint64 sLine;
- qint64 sCol;
- qint64 index = tokenStream->index()-1;
- tokenStream->startPosition(index, &sLine, &sCol);
- qint64 eLine;
- qint64 eCol;
- tokenStream->endPosition(index, &eLine, &eCol);
- KDevelop::Problem *p = new KDevelop::Problem();
- p->setSource(KDevelop::ProblemData::Parser);
- switch ( type ) {
- case Error:
- p->setSeverity(KDevelop::ProblemData::Error);
- break;
- case Warning:
- p->setSeverity(KDevelop::ProblemData::Warning);
- break;
- case Info:
- p->setSeverity(KDevelop::ProblemData::Hint);
- break;
- }
- p->setDescription(message);
- p->setFinalLocation(KDevelop::DocumentRange(m_currentDocument, KTextEditor::Range(sLine, sCol, eLine, eCol+1)));
- m_problems << KDevelop::ProblemPointer(p);
-}
-
-
-// custom error recovery
-void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
-{
- reportProblem( Parser::Error, QString("Expected token \"%1\"").arg(name));
-}
-
-void Parser::expectedSymbol(int /*expectedSymbol*/, const QString& name)
-{
- qint64 line;
- qint64 col;
- qint64 index = tokenStream->index()-1;
- Token &token = tokenStream->at(index);
- kDebug() << "token starts at:" << token.begin;
- kDebug() << "index is:" << index;
- tokenStream->startPosition(index, &line, &col);
- QString tokenValue = tokenText(token.begin, token.end);
- qint64 eLine;
- qint64 eCol;
- tokenStream->endPosition(index, &eLine, &eCol);
- reportProblem( Parser::Error,
- QString("Expected symbol \"%1\" (current token: \"%2\" [%3] at %4:%5 - %6:%7)")
- .arg(name)
- .arg(token.kind != 0 ? tokenValue : "EOF")
- .arg(token.kind)
- .arg(line)
- .arg(col)
- .arg(eLine)
- .arg(eCol));
-}
-
-void Parser::setDebug( bool debug )
-{
- m_debug = debug;
-}
-
-void Parser::setCurrentDocument(QString url)
-{
- m_currentDocument = url;
-}
-
-Parser::ParserState *Parser::copyCurrentState()
-{
- ParserState *state = new ParserState();
- state->varExpressionState = m_state.varExpressionState;
- state->varExpressionIsVariable = m_state.varExpressionIsVariable;
- return state;
-}
-
-void Parser::restoreState( Parser::ParserState* state)
-{
- m_state.varExpressionState = state->varExpressionState;
- m_state.varExpressionIsVariable = state->varExpressionIsVariable;
-}
-
-} // end of namespace erlang
-
-:]
-
--- kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.cpp (nonexistent)
@@ -1,146 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
- * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "parsesession.h"
-
-#include "kdev-pg-memory-pool.h"
-#include "kdev-pg-token-stream.h"
-
-#include <QFile>
-#include <QTextCodec>
-#include "erlangast.h"
-
-namespace erlang
-{
-
-ParseSession::ParseSession()
- : m_debug(false),
- m_pool(new KDevPG::MemoryPool()),
- m_tokenStream(new TokenStream())
-{
-}
-ParseSession::~ParseSession()
-{
- delete m_pool;
- delete m_tokenStream;
-}
-
-QString ParseSession::contents() const
-{
- return m_contents;
-}
-
-void ParseSession::setContents(const QString& contents)
-{
- m_contents = contents;
-}
-
-void ParseSession::setCurrentDocument(const QString& filename)
-{
- m_currentDocument = filename;
-}
-
-bool ParseSession::readFile(const QString& filename, const char* codec)
-{
- m_currentDocument = filename;
-
- QFile f(filename);
- if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
- kDebug() << "Couldn't open project file:" << filename;
- return false;
- }
- QTextStream s(&f);
- if (codec)
- s.setCodec(QTextCodec::codecForName(codec));
- m_contents = s.readAll();
- return true;
-}
-void ParseSession::setDebug(bool debug)
-{
- m_debug = debug;
-}
-
-TokenStream* ParseSession::tokenStream() const
-{
- return m_tokenStream;
-}
-
-
-Parser* ParseSession::createParser(int initialState)
-{
- Parser* parser = new Parser;
- parser->setTokenStream(m_tokenStream);
- parser->setMemoryPool(m_pool);
- parser->setDebug(m_debug);
- parser->setCurrentDocument(m_currentDocument);
-
- parser->tokenize(m_contents, initialState);
- return parser;
-}
-
-bool ParseSession::parse(erlang::FormAst** ast)
-{
- Parser* parser = createParser();
- FormAst* erlangAst;
- bool matched = parser->parseForm(&erlangAst);
- if (matched) {
- kDebug() << "Successfully parsed";
- *ast = erlangAst;
- } else {
- *ast = 0;
- parser->expectedSymbol(AstNode::FormKind, "module declaration");
- kDebug() << "Couldn't parse content";
- }
- m_problems = parser->problems();
- delete parser;
- return matched;
-}
-
-KDevelop::SimpleCursor ParseSession::positionAt(qint64 offset) const
-{
- qint64 line, column;
- m_tokenStream->locationTable()->positionAt(offset, &line, &column);
- return KDevelop::SimpleCursor(line, column);
-}
-
-QString ParseSession::symbol(qint64 token) const
-{
- const TokenStream::Token& tok = m_tokenStream->at(token);
- return m_contents.mid(tok.begin, tok.end - tok.begin + 1);
-}
-
-QString ParseSession::symbol(AstNode* node) const
-{
- const TokenStream::Token& startTok = m_tokenStream->at(node->startToken);
- const TokenStream::Token& endTok = m_tokenStream->at(node->endToken);
- return m_contents.mid(startTok.begin, endTok.end - startTok.begin + 1);
-}
-
-QString ParseSession::docComment(qint64 token) const
-{
- const TokenStream::Token& tok = m_tokenStream->at(token);
- if (!tok.docCommentEnd) return QString();
- return m_contents.mid(tok.docCommentBegin, tok.docCommentEnd - tok.docCommentBegin + 1);
-}
-
-QList<KDevelop::ProblemPointer> ParseSession::problems()
-{
- return m_problems;
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parsesession.h (nonexistent)
@@ -1,94 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
- * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef ERLANG_PARSESESSION_H
-#define ERLANG_PARSESESSION_H
-
-#include <QtCore/QString>
-#include <language/editor/simplecursor.h>
-#include "erlangparser.h"
-#include "parserexport.h"
-
-namespace KDevPG
-{
-class MemoryPool;
-}
-namespace KDevelop
-{
-class SimpleCursor;
-}
-namespace erlang
-{
-class TokenStream;
-
-typedef QPair<KDevelop::DUContextPointer, KDevelop::SimpleRange> SimpleUse;
-
-class KDEVERLANGPARSER_EXPORT ParseSession
-{
-public:
- ParseSession();
- ~ParseSession();
-
- void setContents(const QString& contents);
- void setCurrentDocument(const QString& filename);
- bool readFile(const QString& filename, const char* charset = 0);
- void setDebug(bool);
- TokenStream* tokenStream() const;
- QString contents() const;
-
- bool parse(erlang::FormAst** ast);
- Parser* createParser(int initialState = Parser::HtmlState);
-
- QString symbol(qint64 token) const;
- QString symbol(AstNode* node) const;
-
- /**
- * Return the DocBlock before this token, if any
- */
- QString docComment(qint64 token) const;
-
- /**
- * Return the position (\a line%, \a column%) of the \a offset in the file.
- *
- * \note the line starts from 0.
- */
- KDevelop::SimpleCursor positionAt(qint64 offset) const;
-
- QList<KDevelop::ProblemPointer> problems();
-
- /// @TODO implement this
- void mapAstUse(AstNode* node, const SimpleUse& use)
- {
- Q_UNUSED(node);
- Q_UNUSED(use);
- }
-
-private:
- QString m_contents;
- bool m_debug;
- QString m_currentDocument;
- KDevPG::MemoryPool* m_pool;
- TokenStream* m_tokenStream;
- QList<KDevelop::ProblemPointer> m_problems;
-};
-
-}
-
-#endif
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.cpp (nonexistent)
@@ -1,192 +0,0 @@
-#include "parsertest.h"
-
-#include <QTest>
-
-#include "../parsesession.h"
-#include "../editorintegrator.h"
-
-QTEST_MAIN(erlang::TestParser)
-
-namespace erlang
-{
-
-TestParser::TestParser()
-{
-}
-
-#ifdef disabled
-void TestParser::functionDeclaration()
-{
- erlang::ParseSession session;
- session.setContents("my_func(VariableA, atom_b) -> ok.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
-}
-
-void TestParser::functionClausesDeclaration()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\n my_func(VariableA, atom_b) -> ok; my_func(VariableA, atom_c) -> then.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\n my_func(VariableA, atom_b) -> ok; my_func() -> other_func().");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-}
-#endif
-
-void TestParser::textExport()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\n -export([start/0, start_loop/0]). function() -> ok.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-}
-
-#ifdef disabled
-void TestParser::list()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_list() -> X = [].");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- /*TODO: problempointer is crashing?
- {
- erlang::ParseSession session;
- FormAst* ast = 0;
- session.setContents("-module(test).\ntest_list() -> X = []].");
- QVERIFY(session.parse(&ast) == false);
- }*/
-
- {
- erlang::ParseSession session;
- FormAst* ast = 0;
-
- session.setContents("-module(test).\ntest_list() -> X = [[]].");
- QVERIFY(session.parse(&ast) == true);
- }
-}
-
-void TestParser::testDefine()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\n-define(MACRO, io:format(\"teste\",[])).\ntest_func() -> ?MACRO, ?MACRO, ?MACRO.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-}
-#endif
-
-void TestParser::testNumeric()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(teste_sup). \n teste(- 1 ) -> ok.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_list() -> X = 1.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_list() -> X = 11234512345235634745745623543244523.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_list() -> X = - 11234512345235634745745623543244523.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_list() -> X = 1..");
- FormAst* ast = 0;
-
- //QVERIFY(session.parse(&ast) == false);
- }
-
-}
-
-#if defined disabled
-void TestParser::testVariable()
-{
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_variable() -> X = 123, @10 = 1.");
- FormAst* ast = 0;
-
- //QVERIFY(session.parse(&ast) == false);
- }
-}
-
-void TestParser::testRecord()
-{
- /*{
- erlang::ParseSession session;
- session.setContents("-module(test).\n-record(test, { a, b, c = 1, d = gb_trees::new() }).");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_record() -> X = #record_definition{}.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_record() -> X = #record_definition{ r_var1 = val1, r_var2 = Y }.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }
-
- {
- erlang::ParseSession session;
- session.setContents("-module(test).\ntest_record() -> X = Y#record_definition.value.");
- FormAst* ast = 0;
-
- QVERIFY(session.parse(&ast));
- }*/
-
-}
-#endif
-
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tests/parsertest.h (nonexistent)
@@ -1,29 +0,0 @@
-#ifndef ERLANG_PARSERTEST_H
-#define ERLANG_PARSERTEST_H
-
-#include <QObject>
-
-namespace erlang
-{
-
-class TestParser : public QObject
-{
- Q_OBJECT
-
-public:
- TestParser();
-
-private Q_SLOTS:
- /*void functionDeclaration();
- void functionClausesDeclaration();
- void list();
- void testVariable();
- void testRecord();
- void testDefine();*/
- void testNumeric();
- void textExport();
-};
-
-}
-
-#endif
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.cpp (nonexistent)
@@ -1,102 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "editorintegrator.h"
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/smartrange.h>
-#include <ktexteditor/smartinterface.h>
-
-#include <language/editor/documentrange.h>
-#include <language/editor/documentrangeobject.h>
-
-#include "erlangast.h"
-#include "parsesession.h"
-
-using namespace KTextEditor;
-using namespace erlang;
-
-EditorIntegrator::EditorIntegrator()
- : m_session(0)
-{
-}
-
-void EditorIntegrator::setParseSession(ParseSession* session)
-{
- m_session = session;
-}
-
-KDevelop::SimpleCursor EditorIntegrator::findPosition(qint64 token, Edge edge) const
-{
- const KDevPG::TokenStream::Token& t = m_session->tokenStream()->at(token);
- return findPosition(t, edge);
-}
-
-KDevelop::SimpleCursor EditorIntegrator::findPosition(const KDevPG::TokenStream::Token & token, Edge edge) const
-{
- if (edge == BackEdge) {
- // Apparently KTE expects a range to go until _after_ the last character that should be included
- // however the parser calculates endCol as the index _before_ the last included character, so adjust here
- return m_session->positionAt(token.end + 1);
- } else {
- return m_session->positionAt(token.begin);
- }
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(AstNode * node, RangeEdge edge)
-{
- Q_UNUSED(edge);
- return KDevelop::SimpleRange(findPosition(node->startToken, FrontEdge), findPosition(node->endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(qint64 token)
-{
- return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(qint64 startToken, qint64 endToken)
-{
- return KDevelop::SimpleRange(findPosition(startToken, FrontEdge), findPosition(endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(AstNode* from, AstNode* to)
-{
- return KDevelop::SimpleRange(findPosition(from->startToken, FrontEdge), findPosition(to->endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(const KDevPG::TokenStream::Token & token)
-{
- return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
-}
-
-QString EditorIntegrator::tokenToString(qint64 token) const
-{
- return m_session->symbol(token);
-}
-
-QString EditorIntegrator::nodeToString(AstNode* node) const
-{
- return m_session->symbol(node);
-}
-
-
-ParseSession * EditorIntegrator::parseSession() const
-{
- return m_session;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/editorintegrator.h (nonexistent)
@@ -1,129 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef ERLANGEDITORINTEGRATOR_H
-#define ERLANGEDITORINTEGRATOR_H
-
-#include <language/editor/editorintegrator.h>
-#include <language/editor/simplerange.h>
-#include "parsesession.h"
-
-#include <erlangast.h>
-#include "parserexport.h"
-#include "kdev-pg-token-stream.h"
-
-namespace erlang
-{
-
-class ParseSession;
-class AstNode;
-
-
-/**
- * Provides facilities for easy integration of a text editor component with
- * the information parsed from a source file.
- *
- * Uses a disguised singleton + stateful design.
- *
- * \todo introduce stacks for the state?
- */
-class KDEVERLANGPARSER_EXPORT EditorIntegrator : public KDevelop::EditorIntegrator
-{
-public:
- EditorIntegrator();
- void setParseSession(ParseSession* session);
- ParseSession* parseSession() const;
-
- /**
- * Finds the location and \a file where the given \a token was parsed from. This function
- * does not change any of the EditorIntegrator's state.
- *
- * \param token token to locate
- * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
- *
- * \returns the requested cursor relating to the start or end of the given token.
- */
- KDevelop::SimpleCursor findPosition(const KDevPG::TokenStream::Token& token, Edge edge = BackEdge) const;
-
- /**
- * Finds the location and \a file where the given \a token was parsed from.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \param token token to locate
- * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
- *
- * \returns the requested cursor relating to the start or end of the given token.
- */
- KDevelop::SimpleCursor findPosition(qint64 token, Edge edge = BackEdge) const;
-
- using KDevelop::EditorIntegrator::createRange;
-
- /**
- * Create a range encompassing the given AstNode \a node.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(AstNode* node, RangeEdge = OuterEdge);
-
- /**
- * Create a range encompassing the given AstNode \a nodes.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(AstNode* from, AstNode* to);
-
- /**
- * Create a range encompassing the given AstNode \a token.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(const KDevPG::TokenStream::Token& token);
-
- /**
- * Create a range encompassing the given AstNode \a token.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(qint64 token);
-
- /**
- * Create a range encompassing the given AstNode \a tokens.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(qint64 start_token, qint64 end_token);
-
- /**
- * Retrieve the string represented by a token.
- */
- QString tokenToString(qint64 token) const;
- QString nodeToString(AstNode *node) const;
-
-private:
- ParseSession* m_session;
-};
-
-}
-
-#endif // PHPEDITORINTEGRATOR_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/CMakeLists.txt (nonexistent)
@@ -1,34 +0,0 @@
-#add_subdirectory(test)
-
-set(parser_STAT_SRCS
- erlanglexer.cpp
- editorintegrator.cpp
- parsesession.cpp
- )
-
-kdevpgqt_generate(_kdevpgList erlang NAMESPACE erlang TOKEN_TEXT
- "${erlang_SOURCE_DIR}/parser/erlang.g"
- "${erlang_SOURCE_DIR}/parser/erlanglexer.h"
-)
-
-set( parser_SRCS
- ${_kdevpgList}
-)
-
-kde4_add_library( kdev4erlangparser SHARED ${parser_SRCS} ${parser_STAT_SRCS} )
-target_link_libraries( kdev4erlangparser
- ${KDE4_KDECORE_LIBS}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
- ${KDE4_KTEXTEDITOR_LIBS}
-)
-
-kde4_add_executable( erlang-parser main.cpp )
-target_link_libraries(erlang-parser ${QT_QTCORE_LIBRARY} kdev4erlangparser)
-
-install(TARGETS kdev4erlangparser DESTINATION ${INSTALL_TARGETS_DEFAULT_ARGS})
-
-### next target
-set(parsertest_SRCS tests/parsertest.cpp)
-kde4_add_unit_test(parsertest ${parsertest_SRCS})
-target_link_libraries(parsertest kdev4erlangparser ${QT_QTTEST_LIBRARY})
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.cpp (nonexistent)
@@ -1,503 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "erlanglexer.h"
-
-#include "erlanglexer.h"
-#include "tokenstream.h"
-#include <erlangparser.h>
-
-#include <QtCore/QString>
-#include <QtCore/QStringList>
-#include <QtCore/QRegExp>
-#include <QtCore/QDebug>
-
-#include <iostream>
-
-namespace erlang
-{
-
-Lexer::Lexer(TokenStream* tokenStream, const QString& content, int initialState):
- m_content(content), m_tokenStream(tokenStream),
- m_curpos(0), m_contentSize(m_content.size()),
- m_tokenBegin(0), m_tokenEnd(0), m_haltCompiler(0)
-{
- pushState(ErrorState);
- pushState(initialState);
-}
-
-int Lexer::state(int deepness) const
-{
- return m_state.at(m_state.size() - deepness - 1);
-}
-void Lexer::printState()
-{
- int s = state();
- if (s == ErrorState)
- qDebug() << "ErrorState";
- else if (s == DefaultState)
- qDebug() << "DefaultState";
- else if (s == String)
- qDebug() << "String";
-}
-
-void Lexer::pushState(int state)
-{
- m_state.push(state);
-}
-
-void Lexer::popState()
-{
- m_state.pop();
-}
-
-bool Lexer::processCharLiteral(QChar* it)
-{
- return it->unicode() != '\n';
-}
-
-bool Lexer::isValidNumeric(QChar* it, bool isExponential, bool hasRadix, bool hasPoint, bool& hasUnusable)
-{
- unsigned int nextValidChar = 1;
-
- bool nextIsValid = m_curpos + 1 < m_contentSize;
-
- while (nextIsValid && (
- (it + nextValidChar)->isSpace()
- || (it + nextValidChar)->unicode() == '\t'
- || (it + nextValidChar)->unicode() == '\n'))
- {
- nextValidChar++;
- nextIsValid = nextValidChar < m_contentSize;
- hasUnusable = true;
- }
-
- return it->isDigit()
- || (it->unicode() == '.' && nextIsValid && (it + 1)->isDigit())
- || (it->unicode() == '#' && nextIsValid && (it + 1)->isDigit())
- || ((it->unicode() == '-' || it->unicode() == '+') && nextIsValid && (it + nextValidChar)->isDigit())
- || (nextIsValid && isExponential && hasPoint && (it->unicode() == '+' || it->unicode() == '-') && (it + nextValidChar)->isDigit())
- || (hasRadix && !hasPoint && (it->toLower() == 'a' || it->toLower() == 'b' ||
- it->toLower() == 'c' || it->toLower() == 'd' ||
- it->toLower() == 'e' || it->toLower() == 'f'));
-
-}
-
-int Lexer::nextTokenKind()
-{
- int token = Parser::Token_INVALID;
- if (m_curpos >= m_contentSize) {
- m_tokenBegin = -1;
- m_tokenEnd = -1;
- createNewline(m_curpos);
- return 0;
- }
- QChar* it = m_content.data();
- it += m_curpos;
- m_tokenBegin = m_curpos;
-
- if (it->isSpace())
- {
- token = Parser::Token_WHITESPACE;
- while (m_curpos < m_contentSize && it->isSpace())
- {
- if (it->unicode() == '\n')
- {
- createNewline(m_curpos);
- }
- it++;
- m_curpos++;
- }
- m_curpos--;
- }
- else if (it->isDigit())
- {
- QRegExp regex("\\d+\\.\\d+|\\d+\\.\\d+|\\d+\\.\\d+e-?\\d+|\\d+\\.\\d+e-?\\d+|[\\dABCDEF]+#\\d{1,2}|\\d+");
-
- if ( regex.indexIn(m_content, m_curpos) != -1)
- {
- kDebug() << "Matched: " << regex.cap();
-
- m_curpos += regex.matchedLength() - 1;
- token = Parser::Token_INTEGER_LITERAL;
- }
- }
- else if (it->unicode() == '-')
- {
- if ((it + 1)->unicode() == '>')
- {
- m_curpos++;
- token = Parser::Token_LEADS_TO;
- }
- else if ((it + 1)->unicode() == '-')
- {
- m_curpos++;
- token = Parser::Token_LIST_DIFFERENCE;
- }
- else
- {
- token = Parser::Token_MINUS;
- }
- }
- else if (it->unicode() == '+')
- {
- if ((it + 1)->unicode() == '+')
- {
- m_curpos++;
- token = Parser::Token_LIST_ADDITION;
- }
- else
- {
- token = Parser::Token_PLUS;
- }
- }
- else if (it->unicode() == '$' && processCharLiteral(it + 1))
- {
- token = Parser::Token_CHAR_LITERAL;
- }
- else if (it->unicode() == '}')
- {
- token = Parser::Token_RBRACE;
- if (state() == Tuple)
- {
- popState();
- }
- }
- else if (it->unicode() == '_')
- {
- token = Parser::Token_UNDERLINE;
- }
- else if (it->unicode() == '{')
- {
- token = Parser::Token_LBRACE;
- pushState(Tuple);
- }
- else if (it->unicode() == ')')
- {
- token = Parser::Token_RPAREN;
- }
- else if (it->unicode() == '(')
- {
- token = Parser::Token_LPAREN;
- }
- else if (it->unicode() == ']')
- {
- token = Parser::Token_RBRACKET;
- }
- else if (it->unicode() == '[')
- {
- token = Parser::Token_LBRACKET;
- }
- else if (it->unicode() == ',')
- {
- token = Parser::Token_COMMA;
- }
- else if (it->unicode() == '#')
- {
- token = Parser::Token_POUND_SIGN;
- }
- else if (it->unicode() == '!')
- {
- token = Parser::Token_EXCLAMATION;
- }
- else if (it->unicode() == '<')
- {
- if ( (it + 1)->unicode() == '-')
- {
- m_curpos += 1;
- token = Parser::Token_LIST_COMPREHENSION_LEADS_TO;
- }
- else if ( (it + 1)->unicode() == '<' )
- {
- m_curpos += 1;
- token = Parser::Token_BINARY_OPEN;
- }
- else
- {
- token = Parser::Token_IS_SMALLER;
- }
- }
- else if (it->unicode() == '>')
- {
- if ((it + 1)->unicode() == '=')
- {
- m_curpos++;
- token = Parser::Token_IS_GREATER_OR_EQUAL;
- }
- else if ( (it + 1)->unicode() == '>' )
- {
- m_curpos += 1;
- token = Parser::Token_BINARY_CLOSE;
- }
- else
- {
- token = Parser::Token_IS_GREATER;
- }
- }
- else if (it->unicode() == '?')
- {
- token = Parser::Token_QUESTION;
- }
- else if (it->unicode() == '%')
- {
- token = Parser::Token_COMMENT;
- while (it->unicode() != '\n')
- {
- m_curpos++;
- it++;
- }
- createNewline(m_curpos);
- }
- else if (it->unicode() == '/')
- {
- if ((it + 1)->unicode() == '=')
- {
- token = Parser::Token_IS_NOT_EQUAL;
- }
- else
- {
- token = Parser::Token_FORWARD_SLASH;
- }
- }
- else if (it->unicode() == '*')
- {
- token = Parser::Token_MUL;
- }
- else if (it->unicode() == '|')
- {
- if ((it + 1)->unicode() == '|')
- {
- m_curpos++;
- token = Parser::Token_DOUBLE_PIPE;
- }
- else
- {
- token = Parser::Token_PIPE;
- }
- }
- else if (it->unicode() == ':')
- {
- if ( (it + 1)->unicode() == ':')
- {
- m_curpos += 1;
- token = Parser::Token_DOUBLE_COLON;
- }
- else
- {
- token = Parser::Token_COLON;
- }
- }
- else if (it->unicode() == '.')
- {
- token = Parser::Token_DOT;
- }
- else if (it->unicode() == ';')
- {
- token = Parser::Token_SEMICOLON;
- }
- else if (it->unicode() == '\'')
- {
- token = Parser::Token_ATOM_LITERAL;
- it++;
- m_curpos++;
- int startPos = m_curpos;
- while (m_curpos < m_contentSize
- && (it->unicode() != '\'')) {
- if (it->unicode() == '\n') createNewline(m_curpos);
- it++;
- m_curpos++;
- }
- // if the string is never terminated, make sure we don't overflow the boundaries
- if ( m_curpos == m_contentSize ) {
- --m_curpos;
- }
- }
- else if (it->unicode() == '"')
- {
- token = Parser::Token_STRING_LITERAL;
- it++;
- m_curpos++;
- while (m_curpos < m_contentSize
- && (it->unicode() != '\"')) {
- if (it->unicode() == '\n') createNewline(m_curpos);
- it++;
- m_curpos++;
- }
- // if the string is never terminated, make sure we don't overflow the boundaries
- if ( m_curpos == m_contentSize ) {
- --m_curpos;
- }
- }
- else if (it->unicode() == '=')
- {
- if ((it + 1)->unicode() == '=')
- {
- m_curpos++;
- token = Parser::Token_IS_EQUAL;
- }
- else if ((it + 1)->unicode() == '<') {
- m_curpos++;
- token = Parser::Token_IS_SMALLER_OR_EQUAL;
- }
- else if ((it + 1)->unicode() == ':' && (it + 2)->unicode() == '=')
- {
- m_curpos += 2;
- token = Parser::Token_EXACT_EQUATIONAL;
- }
- else if ((it + 1)->unicode() == '/' && (it + 2)->unicode() == '=')
- {
- m_curpos += 2;
- token = Parser::Token_EXACT_NOT_EQUATIONAL;
- }
- else
- {
- token = Parser::Token_ASSIGN;
- }
- }
- else if (it->isLetter() && it->isUpper())
- {
- QString name;
- while (m_curpos < m_contentSize && (isValidVariableIdentifier(it))) {
- name.append(*it);
- it++;
- m_curpos++;
- }
- m_curpos--;
- token = Parser::Token_VARIABLE;
- }
- else if (it->isLetter() && it->isLower())
- {
- QString name;
- while (m_curpos < m_contentSize && (isValidVariableIdentifier(it))) {
- name.append(*it);
- it++;
- m_curpos++;
- }
-
- m_curpos--;
-
- if (name == "after") {
- token = Parser::Token_AFTER;
- } else if (name == "begin") {
- token = Parser::Token_BEGIN;
- } else if (name == "case") {
- token = Parser::Token_CASE;
- } else if (name == "if") {
- token = Parser::Token_IF;
- } else if (name == "catch") {
- token = Parser::Token_CATCH;
- } else if (name == "cond") {
- token = Parser::Token_COND;
- } else if (name == "end") {
- token = Parser::Token_END;
- } else if (name == "fun") {
- token = Parser::Token_FUN;
- } else if (name == "let") {
- token = Parser::Token_LET;
- } else if (name == "of") {
- token = Parser::Token_OF;
- } else if (name == "catch") {
- token = Parser::Token_CATCH;
- } else if (name == "receive") {
- token = Parser::Token_RECEIVE;
- } else if (name == "when") {
- token = Parser::Token_WHEN;
- } else if (name == "div") {
- token = Parser::Token_INT_DIV;
- } else if (name == "rem") {
- token = Parser::Token_INT_REM;
- } else if (name == "or") {
- token = Parser::Token_OR;
- } else if (name == "xor") {
- token = Parser::Token_XOR;
- } else if (name == "bor") {
- token = Parser::Token_BIT_OR;
- } else if (name == "bxor") {
- token = Parser::Token_BIT_XOR;
- } else if (name == "query") {
- token = Parser::Token_QUERY;
- } else if (name == "bsl") {
- token = Parser::Token_SL;
- } else if (name == "bsr") {
- token = Parser::Token_SR;
- } else if (name == "and") {
- token = Parser::Token_AND;
- } else if (name == "band") {
- token = Parser::Token_BIT_AND;
- } else if (name == "not") {
- token = Parser::Token_NOT;
- } else if (name == "bnot") {
- token = Parser::Token_BIT_NOT;
- } else if (name == "orelse") {
- token = Parser::Token_ORELSE;
- } else if (name == "andalso") {
- token = Parser::Token_ANDALSO;
- } else if (name == "module") {
- token = Parser::Token_MODULE_DIRECTIVE;
- } else if (name == "include") {
- token = Parser::Token_INCLUDE_DIRECTIVE;
- } else if (name == "export") {
- token = Parser::Token_EXPORT_DIRECTIVE;
- } else if (name == "file") {
- token = Parser::Token_FILE_DIRECTIVE;
- } else if (name == "record") {
- token = Parser::Token_RECORD_DIRECTIVE;
- } else if (name == "include") {
- token = Parser::Token_INCLUDE_DIRECTIVE;
- } else if (name == "behaviour"){
- token = Parser::Token_BEHAVIOUR_DIRECTIVE;
- } else if (name == "define"){
- token = Parser::Token_DEFINE_DIRECTIVE;
- }
- else
- {
- token = Parser::Token_ATOM_LITERAL;
- }
- }
-
- m_tokenEnd = m_curpos;
- m_curpos++;
-
- return token;
-}
-
-qint64 Lexer::tokenBegin() const
-{
- return m_tokenBegin;
-}
-
-qint64 Lexer::tokenEnd() const
-{
- return m_tokenEnd;
-}
-
-bool Lexer::isValidVariableIdentifier(QChar* it)
-{
- return it->isLetter() || it->isDigit() || it->unicode() == '_' || it->unicode() == '@';
-}
-
-void Lexer::createNewline(int pos)
-{
- if (m_tokenStream) m_tokenStream->locationTable()->newline(pos);
-}
-
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tokenstream.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tokenstream.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/tokenstream.h (nonexistent)
@@ -1,41 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef PHPTOKENSTREAM_H
-#define PHPTOKENSTREAM_H
-
-#include <kdev-pg-token-stream.h>
-
-namespace erlang
-{
-
-class Token : public KDevPG::Token
-{
-public:
- qint64 docCommentBegin;
- qint64 docCommentEnd;
-};
-
-class TokenStream : public KDevPG::TokenStreamBase<Token>
-{
-};
-
-}
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/main.cpp (nonexistent)
@@ -1,201 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
- * Copyright 2009 Milian Wolff <mail@milianw.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "parsesession.h"
-#include "erlanglexer.h"
-#include "erlangparser.h"
-//#include "cssdebugvisitor.h"
-#include "erlangast.h"
-//#include "csstokentext.h"
-
-#include <QFile>
-#include <QString>
-#include <QStringList>
-#include <QDebug>
-#include <iostream>
-#include <QTextCodec>
-
-using namespace erlang;
-
-void showUsage(char**);
-
-QTextStream qout(stdout);
-QTextStream qerr(stderr);
-QTextStream qin(stdin);
-
-class ErlangParser {
-public:
- ErlangParser(const bool debug, const bool printTokens)
- : m_debug(debug), m_printTokens(printTokens)
- {
- m_session.setDebug(debug);
- }
-
- /// parse contents of a file
- void parseFile( const QString &fileName )
- {
- if (!m_session.readFile(fileName, "utf-8")) {
- qerr << "Can't open file " << fileName << endl;
- exit(255);
- } else {
- qout << "Parsing file " << fileName << endl;
- }
- runSession();
- }
-
- /// parse code directly
- void parseCode( const QString &code )
- {
- m_session.setContents(code);
-
- qout << "Parsing input" << endl;
- runSession();
- }
-
-private:
- /**
- * actually run the parse session
- */
- void runSession()
- {
- if (m_printTokens) {
- erlang::TokenStream tokenStream;
-
- Lexer lexer(&tokenStream, m_session.contents());
- int token;
- while ((token = lexer.nextTokenKind())) {
- Parser::Token &t = tokenStream.push();
- //t.begin = lexer.tokenBegin();
- //t.end = lexer.tokenEnd();
- t.kind = token;
- printToken(token, lexer);
- }
- printToken(token, lexer);
- if ( tokenStream.size() > 0 ) {
- qint64 line;
- qint64 column;
- tokenStream.endPosition(tokenStream.size() - 1, &line, &column);
- qDebug() << "last token endPosition: line" << line << "column" << column;
- } else {
- qDebug() << "empty token stream";
- }
- }
-
- erlang::FormAst* ast = 0;
- if (!m_session.parse(&ast)) {
- qerr << "parse error" << endl;
- exit(255);
- } else {
- if (m_debug) {
- //erlang::DebugVisitor debugVisitor(m_session.tokenStream(), m_session.contents());
- //debugVisitor.visitStart(ast);
- }
- qout << "successfully parsed" << endl;
- }
- }
-
- void printToken(int token, const Lexer& lexer) const
- {
- /* int begin = lexer.tokenBegin();
- int end = lexer.tokenEnd();
- qout << m_session.contents().mid(begin, end - begin + 1).replace('\n', "\\n")
- << " "+ tokenText(token) << endl;*/
- }
-
- erlang::ParseSession m_session;
- const bool m_debug;
- const bool m_printTokens;
-};
-
-int main(int argc, char* argv[])
-{
- qout.setCodec("UTF-8");
- qin.setCodec("UTF-8");
-
- QStringList files;
- bool debug = false;
- bool printTokens = false;
- QStringList code;
- for (int i = 1; i < argc; i++) {
- QString arg(argv[i]);
- if (arg.startsWith(QString("--"))) {
- arg = arg.mid(2);
- if (arg == "help") {
- showUsage(argv);
- return 0;
- } else if (arg == "debug") {
- debug = true;
- } else if (arg == "print-tokens") {
- printTokens = true;
- } else if (arg == "code") {
- for (int j = i + 1; j < argc; ++j ) {
- code << argv[j];
- }
- if ( code.isEmpty() ) {
- qerr << "no code given" << endl;
- showUsage(argv);
- return 1;
- }
- break;
- } else {
- qerr << "unknown option: " << endl;
- showUsage(argv);
- return 1;
- }
- } else {
- files << arg;
- }
- }
-
- ErlangParser parser(debug, printTokens);
-
- if ( !code.isEmpty() ) {
- parser.parseCode( code.join(" ").replace("\\n", "\n") );
- } else if ( files.isEmpty() ) {
- files << "-";
- }
-
- foreach(const QString &fileName, files) {
- if ( fileName == "-" ) {
- if ( isatty(STDIN_FILENO) ) {
- qerr << "no STDIN given" << endl;
- return 255;
- }
- parser.parseCode( qin.readAll().toUtf8() );
- } else {
- parser.parseFile(fileName);
- }
-
- }
- return 0;
-}
-
-void showUsage(char** argv)
-{
- qout << "Usage: " << argv[0] << " [options] FILE" << endl;
- qout << "" << endl;
- qout << "--print-tokens Print all found tokens" << endl;
- qout << "--debug Print AST" << endl;
- qout << "--code ... All following arguments will be interpreted as CSS code." << endl
- << " Hence put this option at the end of the list." << endl;
- qout << "" << endl;
- qout << "If FILE is empty or -, read from STDIN." << endl;
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/erlanglexer.h (nonexistent)
@@ -1,91 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef ERLANGLEXER_H
-#define ERLANGLEXER_H
-
-#include <QtCore/QStack>
-#include <QtCore/QString>
-
-#include "parserexport.h"
-
-class QString;
-
-namespace KDevPG
-{
-class TokenStream;
-}
-
-namespace erlang
-{
-class TokenStream;
-
-/**
- * Hand-written Lexer that generates the same tokens as php uses.
- * This includes also a whitespace and comment token.
- *
- * For debugging output can be compared to php-tokens using the
- * test/test-tokenize.php script
- **/
-class KDEVERLANGPARSER_EXPORT Lexer
-{
-public:
- Lexer(TokenStream *tokenStream, const QString& contents, int initialState = DefaultState);
-
- int nextTokenKind();
- qint64 tokenBegin() const;
- qint64 tokenEnd() const;
- bool isValidNumeric(QChar* it, bool isExponential, bool hasRadix, bool hasPoint, bool& hasSpaces);
-
-private:
- QString m_content;
- TokenStream* m_tokenStream;
- int m_curpos;
- int m_contentSize;
- qint64 m_tokenBegin;
- qint64 m_tokenEnd;
-
- int state(int deepness = 0) const;
- void pushState(int state);
- void popState();
- void printState();
-
- bool isValidVariableIdentifier(QChar* it);
- void createNewline(int pos);
- bool processCharLiteral(QChar* arg1);
-
- QStack<int> m_state;
-
- QString m_heredocIdentifier;
- int m_haltCompiler;
-public:
- enum State {
- ErrorState = -1,
- DefaultState = 1,
- String = 2,
- Tuple = 3
- };
-};
-
-}
-
-#endif
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/.directory
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/.directory (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/.directory (nonexistent)
@@ -1,3 +0,0 @@
-[Dolphin]
-Timestamp=2010,3,8,18,38,35
-ViewMode=1
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parserexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parserexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parser/parserexport.h (nonexistent)
@@ -1,40 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef PARSEREXPORT_H
-#define PARSEREXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-
-#ifndef KDEVERLANGPARSER_EXPORT
-# ifdef MAKE_KDEV4PHPPARSER_LIB
-# define KDEVERLANGPARSER_EXPORT KDE_EXPORT
-# else
-# define KDEVERLANGPARSER_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif
-
-//kate: space-indent on; indent-width 4; replace-tabs on; auto-insert-doxygen on; indent-mode cstyle;
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc -o -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cpp` -o $podir/kdeverlang.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/CMakeLists.txt (nonexistent)
@@ -1,106 +0,0 @@
-PROJECT(erlang)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${erlang_SOURCE_DIR}/cmake)
-
-enable_testing()
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${QT4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
-)
-
-#Don't error out if the FindXXX are missing for these two
-find_package(KDevelop-PG-Qt REQUIRED)
-
-include_directories(
- ${CMAKE_BINARY_DIR}/parser
- ${KDEVPGQT_INCLUDE_DIR}
-)
-
-add_subdirectory(parser)
-add_subdirectory(app_templates)
-
-set(kdeverlanglanguagesupport_PART_SRCS
- erlanglanguagesupport.cpp
- #completion/model.cpp
- #completion/contentassistdata.cpp
- parsejob.cpp
- duchain/builders/contextbuilder.cpp
- duchain/builders/declarationbuilder.cpp
- duchain/builders/typebuilder.cpp
- duchain/declarations/functiondeclaration.cpp
- duchain/declarations/variabledeclaration.cpp
- duchain/types/objecttype.cpp
- #navigation/fieldnavigationcontext.cpp
- #navigation/navigationwidget.cpp
- #navigation/valuenavigationcontext.cpp
-)
-
-kde4_add_plugin(kdeverlanglanguagesupport ${kdeverlanglanguagesupport_PART_SRCS})
-
-target_link_libraries(kdeverlanglanguagesupport
- ${KDE4_KDEUI_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
- ${KDE4_KTEXTEDITOR_LIBS}
- kdev4erlangparser
-)
-
-install(TARGETS kdeverlanglanguagesupport DESTINATION ${PLUGIN_INSTALL_DIR})
-
-install(FILES kdeverlangsupport.desktop DESTINATION ${SERVICES_INSTALL_DIR})
-
-### next target
-#set(completionmodeltest_SRCS
-# completion/test/modeltest.cpp
-# completion/model.cpp
-# completion/contentassistdata.cpp
-# )
-# kde4_add_unit_test(completionmodeltest ${completionmodeltest_SRCS})
-# target_link_libraries(completionmodeltest
-# kdev4erlangparser
-# ${KDE4_KDEUI_LIBS}
-# ${KDE4_KTEXTEDITOR_LIBS}
-# ${QT_QTGUI_LIBRARY}
-# ${QT_QTTEST_LIBRARY}
-# )
-#
-#
-### next target
-set(duchaintest_SRCS
- duchain/tests/duchain.cpp
- duchain/tests/duchaintestbase.cpp
- duchain/builders/contextbuilder.cpp
- duchain/builders/declarationbuilder.cpp
-)
-kde4_add_unit_test(duchaintest ${duchaintest_SRCS})
-
-target_link_libraries(duchaintest
- kdev4erlangparser
- ${KDE4_KDEUI_LIBS}
- ${KDE4_KTEXTEDITOR_LIBS}
- ${QT_QTGUI_LIBRARY}
- ${QT_QTTEST_LIBRARY}
-)
-
-#
-#
-# ### next target
-# set(parsejobtest_SRCS
-# duchain/tests/parsejobtest.cpp
-# )
-# kde4_add_unit_test(parsejobtest ${parsejobtest_SRCS})
-# target_link_libraries(parsejobtest
-# ${KDEVPLATFORM_INTERFACES_LIBRARIES}
-# ${KDEVPLATFORM_TESTS_LIBRARIES}
-# ${QT_QTTEST_LIBRARY}
-# )
-
-add_subdirectory(debug)
-# add_subdirectory(completion)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.cpp (nonexistent)
@@ -1,82 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "erlanglanguagesupport.h"
-
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-#include <kaboutdata.h>
-#include <KTextEditor/Document>
-
-#include <language/codecompletion/codecompletion.h>
-#include <interfaces/idocument.h>
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-
-//#include "completion/model.h"
-#include "parsejob.h"
-//#include "navigation/navigationwidget.h"
-#include "parser/parsesession.h"
-
-K_PLUGIN_FACTORY(KDevErlangSupportFactory, registerPlugin<erlang::LanguageSupport>();)
-K_EXPORT_PLUGIN(KDevErlangSupportFactory(KAboutData("kdeverlangsupport","kdeverlang", ki18n("Erlang Support"), "0.1", ki18n("Support for Erlang Language"), KAboutData::License_GPL)
- .addAuthor(ki18n("Victor Vicente de Carbalho"), ki18n("Author"), "victor.v.carvalho@gmail.com", "")
-))
-
-namespace erlang
-{
-LanguageSupport* LanguageSupport::m_self = 0;
-
-#if KDE_VERSION > KDE_MAKE_VERSION(4, 3, 80)
-int debugArea() { static int s_area = KDebug::registerArea("kdeverlangsupport"); return s_area; }
-#else
-int debugArea() { return 1; }
-#endif
-
-LanguageSupport::LanguageSupport(QObject* parent, const QVariantList& /*args*/)
- : KDevelop::IPlugin(KDevErlangSupportFactory::componentData(), parent),
- KDevelop::ILanguageSupport()
-{
- KDEV_USE_EXTENSION_INTERFACE(KDevelop::ILanguageSupport)
-
- m_self = this;
-
- //CodeCompletionModel* ccModel = new CodeCompletionModel(this);
- //new KDevelop::CodeCompletion(this, ccModel, name());
-}
-
-QString LanguageSupport::name() const
-{
- return "Erlang";
-}
-
-KDevelop::ParseJob *LanguageSupport::createParseJob(const KUrl &url)
-{
- kDebug(debugArea()) << url;
- return new ParseJob(url);
-}
-
-LanguageSupport *LanguageSupport::self()
-{
- return m_self;
-}
-}
-
-#include "erlanglanguagesupport.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlanglanguagesupport.h (nonexistent)
@@ -1,71 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef KDEVERLANGLANGUAGESUPPORT_H
-#define KDEVERLANGLANGUAGESUPPORT_H
-
-#include <interfaces/iplugin.h>
-#include <language/interfaces/ilanguagesupport.h>
-#include <QtCore/QVariant>
-#include <QReadWriteLock>
-
-#include <language/duchain/indexedstring.h>
-
-namespace KDevelop
-{
-class IDocument;
-class IProject;
-class CodeHighlighting;
-class ReferencedTopDUContext;
-class ParseJob;
-}
-
-
-namespace erlang
-{
-
-class Highlighting;
-
-class LanguageSupport : public KDevelop::IPlugin, public KDevelop::ILanguageSupport
-{
- Q_OBJECT
- Q_INTERFACES(KDevelop::ILanguageSupport)
-
-public:
- explicit LanguageSupport(QObject *parent, const QVariantList& args = QVariantList());
-
- virtual ~LanguageSupport()
- {
- }
-
- /*Name Of the Language*/
- QString name() const;
- /*Parsejob used by background parser to parse given Url*/
- KDevelop::ParseJob *createParseJob(const KUrl &url);
-
- static LanguageSupport* self();
- /*the code highlighter*/
- //const KDevelop::ICodeHighlighting* codeHighlighting() const;
-private:
- static LanguageSupport* m_self;
-};
-
-}
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/COPYING
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/COPYING (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/COPYING (nonexistent)
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/kdeverlangsupport.desktop (nonexistent)
@@ -1,75 +0,0 @@
-[Desktop Entry]
-Encoding=UTF-8
-Type=Service
-Exec=blubb
-Comment=Erlang Language Support
-Comment[bs]=Erlang jezička podrška
-Comment[ca]=Implementació de llenguatge Erlang
-Comment[ca@valencia]=Implementació de llenguatge Erlang
-Comment[de]=Sprachunterstützung für Erlang
-Comment[en_GB]=Erlang Language Support
-Comment[es]=Implementación de lenguaje Erlang
-Comment[et]=Erlangi keele toetus
-Comment[fr]=Prise en charge du langage Erlang
-Comment[gl]=Compatibilidade coa linguaxe Erlang
-Comment[hu]=Erlang nyelvi támogatás
-Comment[it]=Supporto per il linguaggio Erlang
-Comment[nl]=Ondersteuning voor de taal Erlang
-Comment[pl]=Erlang Language Support
-Comment[pt]=Suporte para a Linguagem Erlang
-Comment[pt_BR]=Suporte para a linguagem Erlang
-Comment[sv]=Stöd för språket Erlang
-Comment[uk]=Підтримка мови Erlang
-Comment[x-test]=xxErlang Language Supportxx
-Name=Erlang Support
-Name[bs]=Podrška Erlanga
-Name[ca]=Implementació d'Erlang
-Name[ca@valencia]=Implementació d'Erlang
-Name[de]=Unterstützung für Erlang
-Name[en_GB]=Erlang Support
-Name[es]=Implementación de Erlang
-Name[et]=Erlangi toetus
-Name[fr]=Prise en charge de Erlang
-Name[ga]=Tacaíocht Erlang
-Name[gl]=Compatibilidade con Erlang
-Name[hu]=Erlang támogatás
-Name[it]=Supporto per Erlang
-Name[nl]=Ondersteuning voor Erlang
-Name[pl]=Obsługa Erlang
-Name[pt]=Suporte a Erlang
-Name[pt_BR]=Suporte à Erlang
-Name[sk]=Podpora Erlang
-Name[sv]=Erlang-stöd
-Name[uk]=Підтримка Erlang
-Name[x-test]=xxErlang Supportxx
-GenericName=Erlang Support
-GenericName[bs]=Podrška Erlanga
-GenericName[ca]=Implementació d'Erlang
-GenericName[ca@valencia]=Implementació d'Erlang
-GenericName[de]=Unterstützung für Erlang
-GenericName[en_GB]=Erlang Support
-GenericName[es]=Implementación de Erlang
-GenericName[et]=Erlangi toetus
-GenericName[fr]=Prise en charge de Erlang
-GenericName[ga]=Tacaíocht Erlang
-GenericName[gl]=Compatibilidade con Erlang
-GenericName[hu]=Erlang támogatás
-GenericName[it]=Supporto per Erlang
-GenericName[nl]=Ondersteuning voor Erlang
-GenericName[pl]=Obsługa Erlang
-GenericName[pt]=Suporte a Erlang
-GenericName[pt_BR]=Suporte à Erlang
-GenericName[sk]=Podpora Erlang
-GenericName[sv]=Erlang-stöd
-GenericName[uk]=Підтримка Erlang
-GenericName[x-test]=xxErlang Supportxx
-ServiceTypes=KDevelop/Plugin
-Icon=source
-X-KDE-Library=kdeverlanglanguagesupport
-X-KDevelop-Version=10
-X-KDevelop-Language=Erlang
-X-KDevelop-Args=Erlang
-X-KDevelop-Interfaces=ILanguageSupport
-X-KDevelop-SupportedMimeTypes=text/x-erlang
-X-KDE-PluginInfo-Name=KDevErlangSupport
-X-KDevelop-Mode=NoGUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.cpp (nonexistent)
@@ -1,215 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2007 Piyush verma <piyush.verma@gmail.com> *
- * Copyright (c) 2008 Niko Sams <niko.sams@gmail.com> *
- * Copyright (c) 2010 Milian Wolff <mail@milianw.de> *
- * *
- * 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#include "parsejob.h"
-
-#include <QFile>
-#include <QReadWriteLock>
-#include <QtCore/QReadLocker>
-#include <QtCore/QThread>
-
-#include <kdebug.h>
-#include <KMimeType>
-
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/dumpchain.h>
-#include <language/backgroundparser/urlparselock.h>
-
-#include <interfaces/ilanguage.h>
-#include <language/highlighting/codehighlighting.h>
-#include <interfaces/icore.h>
-#include <interfaces/ilanguagecontroller.h>
-
-#include "parser/parsesession.h"
-#include "erlanglanguagesupport.h"
-#include "duchain/builders/declarationbuilder.h"
-#include "parser/editorintegrator.h"
-
-#include <QtCore/QReadLocker>
-#include <QtCore/QThread>
-
-using namespace KDevelop;
-
-namespace erlang
-{
-
-extern int debugArea();
-#define debug() kDebug(debugArea())
-
-ParseJob::ParseJob ( const KUrl &url )
- : KDevelop::ParseJob ( url )
-{
- kDebug();
-}
-
-ParseJob::~ParseJob()
-{
- kDebug();
-}
-
-LanguageSupport *ParseJob::erlang() const
-{
- return LanguageSupport::self();
-}
-
-
-void ParseJob::run()
-{
- KDevelop::UrlParseLock urlLock ( document() );
-
- if ( ! ( minimumFeatures() & KDevelop::TopDUContext::ForceUpdate ) )
- {
- KDevelop::DUChainReadLocker lock ( KDevelop::DUChain::lock() );
- bool needsUpdate = true;
- foreach ( const KDevelop::ParsingEnvironmentFilePointer &file, KDevelop::DUChain::self()->allEnvironmentFiles ( document() ) )
- {
- if ( file->needsUpdate() )
- {
- needsUpdate = true;
- break;
- }
- else
- {
- needsUpdate = false;
- }
- }
- if ( !needsUpdate )
- {
- debug() << "Already up to date" << document().str();
- return;
- }
- }
-
- debug() << "parsing" << document().str();
-
- bool readFromDisk = !contentsAvailableFromEditor();
-
- QString contents;
-
- if ( readFromDisk )
- {
- QFile file ( document().str() );
-
- if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) )
- {
- /*
- KDevelop::ProblemPointer p(new KDevelop::Problem());
- p->setSource(KDevelop::ProblemData::Disk);
- p->setDescription(i18n("Could not open file '%1'", document().str()));
- switch (file.error()) {
- case QFile::ReadError:
- p->setExplanation(i18n("File could not be read from."));
- break;
- case QFile::OpenError:
- p->setExplanation(i18n("File could not be opened."));
- break;
- case QFile::PermissionsError:
- p->setExplanation(i18n("File permissions prevent opening for read."));
- break;
- default:
- break;
- }
- p->setFinalLocation(KDevelop::DocumentRange(document().str(), KTextEditor::Cursor(0, 0), KTextEditor::Cursor(0, 0)));
- // TODO addProblem(p);
- */
- kWarning() << "Could not open file" << document().str();
- return abortJob();
- }
-
- QTextStream s ( &file );
- contents = s.readAll();
- file.close();
- }
- else
- {
- contents = contentsFromEditor();
- }
-
- KDevelop::ReferencedTopDUContext top;
- {
- KDevelop::DUChainReadLocker lock ( KDevelop::DUChain::lock() );
- top = KDevelop::DUChain::self()->chainForDocument ( document() );
- }
- if ( top )
- {
- debug() << "re-compiling" << document().str();
- KDevelop::DUChainWriteLocker lock ( KDevelop::DUChain::lock() );
- top->clearImportedParentContexts();
- top->parsingEnvironmentFile()->clearModificationRevisions();
- top->clearProblems();
- }
- else
- {
- debug() << "compiling" << document().str();
- }
-
- QReadLocker parseLock ( erlang()->language()->parseLock() );
- FormAst* formAst = 0;
- ParseSession parseSession;
- parseSession.setContents ( contents );
- parseSession.setCurrentDocument ( document().str() );
-
- bool matched = parseSession.parse ( &formAst );
-
- EditorIntegrator editor;
- editor.setParseSession(&parseSession);
- DeclarationBuilder builder;
- builder.setEditor ( &editor );
- top = builder.build ( document(), formAst, top );
- kDebug() << top;
- Q_ASSERT ( top );
-
- setDuChain ( top );
-
- KDevelop::DUChainWriteLocker lock ( KDevelop::DUChain::lock() );
-
- if ( !matched )
- {
- foreach ( const ProblemPointer &p, parseSession.problems() )
- {
- top->addProblem ( p );
- }
- }
-
- cleanupSmartRevision();
-
- top->setFeatures ( minimumFeatures() );
- KDevelop::ParsingEnvironmentFilePointer file = top->parsingEnvironmentFile();
-
- QFileInfo fileInfo ( document().str() );
- QDateTime lastModified = fileInfo.lastModified();
- if ( readFromDisk )
- {
- file->setModificationRevision ( KDevelop::ModificationRevision ( lastModified ) );
- }
- else
- {
- file->setModificationRevision ( KDevelop::ModificationRevision ( lastModified, revisionToken() ) );
- }
- KDevelop::DUChain::self()->updateContextEnvironment ( top->topContext(), file.data() );
-
- cleanupSmartRevision();
-}
-
-}
-
-#include "parsejob.moc"
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/parsejob.h (nonexistent)
@@ -1,56 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>. *
- *****************************************************************************/
-
-#ifndef ERLANG_PARSEJOB_H
-#define ERLANG_PARSEJOB_H
-
-#include <language/backgroundparser/parsejob.h>
-
-// from the parser subdirectory
-#include "erlangast.h"
-
-#include <QStringList>
-
-#include <ksharedptr.h>
-#include <ktexteditor/range.h>
-
-namespace erlang
-{
-
-class AstNode;
-class LanguageSupport;
-class EditorIntegrator;
-
-class ParseJob : public KDevelop::ParseJob
-{
- Q_OBJECT
-
-public:
- explicit ParseJob(const KUrl &url);
- virtual ~ParseJob();
-
- LanguageSupport* erlang() const;
-
-protected:
- virtual void run();
-
-};
-}
-
-#endif
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; auto-insert-doxygen on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/CMakeLists.txt (nonexistent)
@@ -1,5 +0,0 @@
-set(apptemplate_DIRS
- simple_erlangapp
-)
-
-kdevplatform_add_app_templates(${apptemplate_DIRS})
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/simple_erlangapp.kdevtemplate (nonexistent)
@@ -1,39 +0,0 @@
-# KDE Config File
-[General]
-Name=Simple Erlang Application
-Name[ca]=Aplicació Erlang senzilla
-Name[ca@valencia]=Aplicació Erlang senzilla
-Name[en_GB]=Simple Erlang Application
-Name[es]=Aplicación Erlang sencilla
-Name[et]=Lihtne Erlang rakendus
-Name[fr]=Application Erlang simple
-Name[nds]=Eenfach Erlang-Programm
-Name[nl]=Eenvoudig Erlang-programma
-Name[pl]=Prosty program w Erlang
-Name[pt]=Aplicação Simples em Erlang
-Name[pt_BR]=Aplicativo Erlang simples
-Name[ro]=Aplicație Erlang simplă
-Name[sv]=Ett enkelt Erlang-program
-Name[uk]=Проста програма мовою Erlang
-Name[x-test]=xxSimple Erlang Applicationxx
-Name[zh_CN]=简单的 Erlang 应用程序
-Name[zh_TW]=簡單的 Erlang 應用程式
-Category=Erlang
-Comment=Generate filestructure to start a Erlang application
-Comment[ca]=Genera l'estructura de fitxer per iniciar una aplicació Erlang
-Comment[ca@valencia]=Genera l'estructura de fitxer per iniciar una aplicació Erlang
-Comment[en_GB]=Generate filestructure to start a Erlang application
-Comment[es]=Generar una estructura de archivos para iniciar una aplicación Erlang
-Comment[et]=Failistruktuuri genereerimine Erlang rakenduse tarbeks
-Comment[fr]=Génère une structure de fichiers pour démarrer une application Erlang
-Comment[nds]=Dateiopbuu för't Starten vun en Erlang-Programm opstellen
-Comment[nl]=Een bestandsstructuur genereren om een Erlang-programma te starten
-Comment[pl]=Generuje strukturę plików do uruchomienia programu w Erlang
-Comment[pt]=Gerar a estrutura de ficheiros para iniciar uma aplicação em Erlang
-Comment[pt_BR]=Gera a estrutura de arquivos para iniciar um aplicativo Erlang
-Comment[sv]=Skapa filstruktur för att påbörja ett Erlang-program
-Comment[uk]=Створити початкову файлову структуру програми мовою Erlang
-Comment[x-test]=xxGenerate filestructure to start a Erlang applicationxx
-Comment[zh_CN]=生成 Erlang 应用程序的文件结构
-Comment[zh_TW]=開始寫一個 Erlang 應用程式的一般檔案結構
-ShowFilesAfterGeneration=%{dest}/%{APPNAMELC}.erl
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/Emakefile (nonexistent)
@@ -1,3 +0,0 @@
-
-
-{"src/*",[debug_info, {outdir, "ebin"}]}.
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_sup.erl (nonexistent)
@@ -1,15 +0,0 @@
--module(%{APPNAME}_sup).
-
--behaviour(supervisor).
-
--export([start_link/0]).
--export([init/1]).
-
--define(SERVER, ?MODULE).
-
-start_link() ->
- supervisor:start_link({local, ?SERVER}, ?MODULE, []).
-
-init([]) ->
- %%Your code here
- {ok,{{one_for_all,0,1}, []}}.
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/src/%{APPNAME}_app.erl (nonexistent)
@@ -1,19 +0,0 @@
--module(%{APPNAME}_app).
-
--behaviour(application).
-
--export([start/2,stop/1]).
-
-start(Type, StartArgs) ->
- case %{APPNAME}_sup:start_link() of
- {ok, Pid} ->
- {ok, Pid};
- Error ->
- Error
- end.
-
-shutdown() ->
- application:stop(%{APPNAME}_app).
-
-stop(State) ->
- ok.
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/app_templates/simple_erlangapp/%{PROJECTDIRNAME}.kdev4 (nonexistent)
@@ -1,4 +0,0 @@
-[Project]
-Name=%{APPNAME}
-Manager=KDevCustomMakeManager
-VersionControl=%{VERSIONCONTROLPLUGIN}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.h (nonexistent)
@@ -1,47 +0,0 @@
-/*
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef DEBUGGERTESTS_H
-#define DEBUGGERTESTS_H
-
-#include <QObject>
-
-namespace KDevelop
-{
- class TestCore;
-}
-
-class DebuggerTests : public QObject
-{
- Q_OBJECT
-
-public:
- DebuggerTests();
-
-private Q_SLOTS:
- void debuggerIntegration();
-
- virtual void initTestCase();
-
-protected:
- KDevelop::TestCore* m_core;
-};
-
-#endif // DEBUGGERTESTS_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/tests/debuggertests.cpp (nonexistent)
@@ -1,67 +0,0 @@
-/*
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "debuggertests.h"
-#include "../debugger.h"
-#include "../debugsession.h"
-
-#include <QApplication>
-
-#include <KSharedConfig>
-#include <kglobal.h>
-
-#include <KDebug>
-#include <KProcess>
-#include <KConfig>
-#include <qtest_kde.h>
-#include <tests/testcore.h>
-#include <tests/autotestshell.h>
-
-#include <QTest>
-
-QTEST_MAIN(DebuggerTests)
-
-void DebuggerTests::debuggerIntegration()
-{
- ErlangDebugPlugin::ErlangDebugger debugger;
-
- KConfigGroup grp(KGlobal::config(), "Erlang Debugger");
-
- grp.writeEntry(ErlangDebugPlugin::erlangShellExecPath,"");
- grp.writeEntry(ErlangDebugPlugin::rebuildDebuggerInterface, true);
-
- debugger.start(grp);
-
- QApplication::exec();
-}
-
-DebuggerTests::DebuggerTests()
-{
-
-}
-
-void DebuggerTests::initTestCase()
-{
- KDevelop::AutoTestShell::init();
- m_core = new KDevelop::TestCore();
- m_core->initialize(KDevelop::Core::NoUi);
-}
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.cpp (nonexistent)
@@ -1,106 +0,0 @@
-/*
- Copyright 2007 David Nolden <david.nolden.kdevelop@art-master.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include <language/duchain/stringhelpers.h>
-#include <language/duchain/safetycounter.h>
-#include <QString>
-#include <QChar>
-#include <QStringList>
-
-namespace Utils {
-
-enum { T_ACCESS, T_PAREN, T_BRACKET, T_IDE, T_UNKNOWN, T_TEMP };
-
-int expressionAt( const QString& text, int index ) {
-
- if( index == 0 )
- return 0;
-
- int last = T_UNKNOWN;
- int start = index;
- --index;
-
- while ( index > 0 ) {
- while ( index > 0 && text[ index ].isSpace() ) {
- --index;
- }
-
- QChar ch = text[ index ];
- QString ch2 = text.mid( index - 1, 2 );
- if ( ( last != T_IDE ) && ( ch.isLetterOrNumber() || ch == '_' || ch == '$' ) ) {
- while ( index > 0 && ( text[ index ].isLetterOrNumber() || text[ index ] == '_' || text[ index ] == '$' ) ) {
- --index;
- }
- last = T_IDE;
- } else if ( last != T_IDE && ch == ')' ) {
- int count = 0;
- while ( index > 0 ) {
- QChar ch = text[ index ];
- if ( ch == '(' ) {
- ++count;
- } else if ( ch == ')' ) {
- --count;
- }
- --index;
- if ( count == 0 ) {
- //index;
- last = T_PAREN;
- break;
- }
- }
- } else if ( ch == ']' ) {
- int count = 0;
- while ( index > 0 ) {
- QChar ch = text[ index ];
- if ( ch == '[' ) {
- ++count;
- } else if ( ch == ']' ) {
- --count;
- } else if ( count == 0 ) {
- //--index;
- last = T_BRACKET;
- break;
- }
- --index;
- }
- } else if ( ch2 == "::" ) {
- index -= 2;
- last = T_ACCESS;
- } else if ( ch2 == "->" ) {
- index -= 2;
- last = T_ACCESS;
- } else {
- if ( start > index ) {
- ++index;
- }
- last = T_UNKNOWN;
- break;
- }
- }
-
- ///If we're at the first item, the above algorithm cannot be used safely,
- ///so just determine whether the sign is valid for the beginning of an expression, if it isn't reject it.
- if ( index == 0 && start > index && !( text[ index ].isLetterOrNumber() || text[ index ] == '_' || text[ index ] == '$' || text[ index ] == ':' ) ) {
- ++index;
- }
-
- return index;
-}
-
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.cpp (nonexistent)
@@ -1,86 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "breakpointcontroller.h"
-
-#include "debugsession.h"
-#include <kdebug.h>
-#include <debugger/breakpoint/breakpointmodel.h>
-#include "messages.h"
-
-namespace ErlangDebugPlugin
-{
-
-DebugSession* ErlangBreakpointController::debugSession()
-{
- return static_cast<DebugSession*>(KDevelop::IBreakpointController::debugSession());
-}
-
-ErlangBreakpointController::ErlangBreakpointController(DebugSession* parent): IBreakpointController(parent)
-{
- connect(parent, SIGNAL(stateChanged(KDevelop::IDebugSession::DebuggerState)),
- SLOT(stateChanged(KDevelop::IDebugSession::DebuggerState)));
-
- connect(parent, SIGNAL(breakpointUpdate(BreakpointOutput*)),
- SLOT(hitBreakpoint(BreakpointOutput*)));
-}
-
-void ErlangBreakpointController::sendMaybe(KDevelop::Breakpoint* breakpoint)
-{
- if (breakpoint->kind() == KDevelop::Breakpoint::CodeBreakpoint)
- {
- QString module = breakpoint->url().fileName().split(".")[0];
- if (breakpoint->deleted())
- {
- debugSession()->removeBreakpoint(module, breakpoint->line() + 1);
- if (m_ids.contains(breakpoint))
- m_ids.remove(breakpoint);
- }
- else if (!m_ids.contains(breakpoint))
- {
- debugSession()->sendBreakpoint(module, breakpoint->line() + 1);
- m_ids[breakpoint] = breakpoint->url().path() + ":" + QString::number(breakpoint->line());
- }
- }
-}
-
-void ErlangBreakpointController::stateChanged(KDevelop::IDebugSession::DebuggerState state)
-{
- kDebug() << state;
- if (state == KDevelop::IDebugSession::StartingState) {
- m_ids.clear();
- sendMaybeAll();
- }
-}
-
-void ErlangBreakpointController::hitBreakpoint(BreakpointOutput* breakpoint)
-{
- QString id = breakpoint->getModule() + ":" + QString::number(breakpoint->getLine());
-
- KDevelop::Breakpoint* b = m_ids.key(id);
-
- if (b)
- {
- b = breakpointModel()->addCodeBreakpoint(KUrl::fromPath(breakpoint->getModule()), breakpoint->getLine() - 1);
- hit(b);
- }
-}
-
-}
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.cpp (nonexistent)
@@ -1,183 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "launchconfig.h"
-
-#include "debugplugin.h"
-#include "debugjob.h"
-#include "debugsession.h"
-
-#include <execute/iexecuteplugin.h>
-#include <debugger/util/pathmappings.h>
-#include <interfaces/ilaunchconfiguration.h>
-#include <interfaces/iproject.h>
-
-#include <klocale.h>
-#include <kdebug.h>
-
-#include <QBoxLayout>
-#include <KIcon>
-#include <KLocalizedString>
-#include <qheaderview.h>
-#include <project/projectmodel.h>
-
-#include <kmimetype.h>
-#include <kconfiggroup.h>
-#include <QFileInfo>
-#include <QListView>
-
-namespace ErlangDebugPlugin
-{
-
-KDevelop::LaunchConfigurationPage* ConfigPageFactory::createWidget( QWidget* parent )
-{
- return new ConfigPage( parent );
-}
-
-ConfigPage::ConfigPage( QWidget* parent )
- : LaunchConfigurationPage(parent)
-{
- setupUi(this);
-}
-
-KIcon ConfigPage::icon() const
-{
- return KIcon();
-}
-
-void ConfigPage::loadFromConfiguration( const KConfigGroup& cfg, KDevelop::IProject* project )
-{
- KMimeType::Ptr mimetype =KMimeType::mimeType("text/x-erlang");
-
- QStringList itens = cfg.readEntry(ErlangDebugPlugin::interpretedModules, QStringList());
- QStringList includeLibraryPaths = cfg.readEntry(ErlangDebugPlugin::libraryPaths, QStringList());
-
- foreach(KDevelop::ProjectFileItem* item, project->files())
- {
- if (KMimeType::findByUrl(item->fileName())->name() == mimetype->name())
- {
- QFileInfo module(item->fileName());
- QString basename = module.baseName();
- QTreeWidgetItem* i = new QTreeWidgetItem(interpretableTreeWidget, QStringList(basename));
- i->setCheckState(0, itens.contains(basename) ? Qt::Checked : Qt::Unchecked);
- }
- }
-
- foreach(QString path, includeLibraryPaths)
- {
- includeLibraryListWidget->addItem(path);
- }
-
- if (includeLibraryPaths.empty())
- {
- includeLibraryListWidget->addItem(project->folder().path() + "ebin/");
- }
-
- QString moduleName = cfg.readEntry(ErlangDebugPlugin::callableModule, QString());
- QString moduleFunction = cfg.readEntry(ErlangDebugPlugin::callableFunction, QString());
- QString arguments = cfg.readEntry(ErlangDebugPlugin::callableArguments, QString());
-
- moduleNameLineEdit->setText(moduleName);
- moduleFunctionLineEdit->setText(moduleFunction);
- functionArgumentsLineEdit->setText(arguments);
-}
-
-void ConfigPage::saveToConfiguration( KConfigGroup cfg, KDevelop::IProject* project ) const
-{
- QStringList to_be_interpreted;
-
- for(int i = 0; i < interpretableTreeWidget->topLevelItemCount(); ++i)
- {
- QTreeWidgetItem* w_item = interpretableTreeWidget->topLevelItem(i);
- if (w_item->checkState(0) == Qt::Checked)
- to_be_interpreted << w_item->text(0);
- }
-
- QStringList libraryPaths;
-
- for(int i = 0; i < includeLibraryListWidget->count(); ++i)
- {
- if (QFileInfo(includeLibraryListWidget->item(i)->text()).exists())
- {
- libraryPaths << includeLibraryListWidget->item(i)->text();
- }
- }
-
- cfg.writeEntry(ErlangDebugPlugin::interpretedModules, to_be_interpreted);
- cfg.writeEntry(ErlangDebugPlugin::rebuildDebuggerInterface, true);
- cfg.writeEntry(ErlangDebugPlugin::libraryPaths, libraryPaths);
-
- cfg.writeEntry(ErlangDebugPlugin::callableModule, moduleNameLineEdit->text());
- cfg.writeEntry(ErlangDebugPlugin::callableFunction, moduleFunctionLineEdit->text());
- cfg.writeEntry(ErlangDebugPlugin::callableArguments, functionArgumentsLineEdit->text());
-}
-
-QString ConfigPage::title() const
-{
- return i18n( "Erlang Configuration" );
-}
-
-ErlangLauncher::ErlangLauncher(ErlangDebuggerPlugin* plugin)
- : m_plugin(plugin)
-{
- factoryList << new ConfigPageFactory();
-}
-
-KJob* ErlangLauncher::start(const QString& launchMode, KDevelop::ILaunchConfiguration* cfg)
-{
- Q_ASSERT(cfg);
- if( !cfg )
- {
- return 0;
- }
- if( launchMode == "debug" )
- {
- return new ErlangDebugJob( m_plugin->createSession(), cfg, m_plugin);
- }
- kWarning() << "Unknown launch mode" << launchMode << "for config:" << cfg->name();
- return 0;
-}
-
-QList< KDevelop::LaunchConfigurationPageFactory* > ErlangLauncher::configPages() const
-{
- return factoryList;
-}
-
-QStringList ErlangLauncher::supportedModes() const
-{
- return QStringList() << "debug";
-}
-
-QString ErlangLauncher::description() const
-{
- return i18n("Executes a erlang application in debug mode");
-}
-
-QString ErlangLauncher::name() const
-{
- return i18n("Erlang");
-}
-
-QString ErlangLauncher::id()
-{
- return "erlang";
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/CMakeLists.txt (nonexistent)
@@ -1,75 +0,0 @@
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9046 )
-
-enable_testing()
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${QT4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
-)
-
-########### next target ###############
-
-set(kdeverldebugcore_PART_SRCS
- debugger.cpp
- debugsession.cpp
- debugjob.cpp
- framestackmodel.cpp
- breakpointcontroller.cpp
- messages.cpp
- launchconfig.cpp
- variablecontroller.cpp
- variable.cpp
- stringhelpers.cpp
-)
-
-set(kdeverldebug_PART_SRCS
- debugplugin.cpp
- launchconfig.cpp
- #launchconfigurationpage.cpp
-)
-
-set(kdevelerlang_UI_PARTS
- debug_config.ui)
-
-kde4_add_ui_files(kdeverldebugcore_PART_SRCS ${kdevelerlang_UI_PARTS})
-kde4_add_plugin(kdeverldebug ${kdeverldebugcore_PART_SRCS} ${kdeverldebug_PART_SRCS})
-
-target_link_libraries(kdeverldebug
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_DEBUGGER_LIBRARIES}
- ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${KDEVPLATFORM_UTIL_LIBRARIES}
-)
-
-install(TARGETS kdeverldebug DESTINATION ${PLUGIN_INSTALL_DIR})
-install(FILES debug_interpreter.erl DESTINATION ${DATA_INSTALL_DIR}/kdeverlangsupport)
-
-
-########### next target ###############
-
-set(erlangdebuggertests_SRCS
- tests/debuggertests.cpp
-)
-
-kde4_add_unit_test(erlangdebuggertests ${erlangdebuggertests_SRCS} ${kdeverldebugcore_PART_SRCS} ${kdeverldebug_PART_SRCS})
-
-target_link_libraries(erlangdebuggertests
- ${kdeverldebug}
- ${QT_QTTEST_LIBRARY}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_TESTSHELL_LIBRARIES}
- ${KDEVPLATFORM_DEBUGGER_LIBRARIES}
- ${KDEVPLATFORM_TESTS_LIBRARIES}
-)
-
-
-
-########### install files ###############
-
-install(FILES kdeverldebug.desktop DESTINATION ${SERVICES_INSTALL_DIR})
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.h (nonexistent)
@@ -1,63 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANG_VARIABLECONTROLLER_H
-#define ERLANG_VARIABLECONTROLLER_H
-
-#include <debugger/interfaces/ivariablecontroller.h>
-
-class QDomDocument;
-namespace KDevelop {
-class Locals;
-}
-namespace ErlangDebugPlugin {
-
-class Variable;
-class DebugSession;
-class VariableListOutput;
-
-class VariableController : public KDevelop::IVariableController
-{
- Q_OBJECT
-
-public:
- VariableController(DebugSession* parent);
-
- KDevelop::Variable* createVariable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
- const QString& expression,
- const QString& display = "");
-
- virtual QString expressionUnderCursor(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor);
- virtual void addWatch(KDevelop::Variable* variable);
- virtual void addWatchpoint(KDevelop::Variable* variable);
- virtual void update();
-
-private slots:
- void handleLocals(VariableListOutput*);
-
-private:
- DebugSession* debugSession() const;
- void handleEvent(KDevelop::IDebugSession::event_t event);
- VariableListOutput* m_currentVarList;
-};
-
-}
-
-#endif // GDBDEBUGGER_VARIABLECONTROLLER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variablecontroller.cpp (nonexistent)
@@ -1,134 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "variablecontroller.h"
-
-#include <QXmlStreamReader>
-
-#include <debugger/variable/variablecollection.h>
-#include <debugger/breakpoint/breakpointmodel.h>
-#include <interfaces/icore.h>
-#include <interfaces/idebugcontroller.h>
-#include <debugger/interfaces/iframestackmodel.h>
-
-#include "debugsession.h"
-#include "variable.h"
-#include "stringhelpers.h"
-#include "messages.h"
-#include "variable.h"
-
-namespace ErlangDebugPlugin {
-
-VariableController::VariableController(DebugSession* parent)
- : KDevelop::IVariableController(parent) , m_currentVarList(0)
-{
- Q_ASSERT(parent);
- //connect(parent, SIGNAL(variableListUpdate(VariableListOutput*)), SLOT(handleLocals(VariableListOutput*)));
-}
-
-void VariableController::handleLocals(VariableListOutput* variableList)
-{
- /*
- TODO: check with someone if there's a way to make this work
-
- m_currentVarList = new VariableListOutput(*variableList);
-
- QDomDocument& document = variableList->getDocument();
-
- QStringList updatable;
-
- QDomNodeList lst = document.firstChildElement().elementsByTagName("variable");
-
- for (int i = 0; i < lst.size(); ++i)
- {
- updatable << lst.at(i).attributes().namedItem("name").nodeValue();
- kDebug() << "Updating: " << updatable;
-
- QList<KDevelop::Variable*> locals = KDevelop::ICore::self()->debugController()->variableCollection()->locals()->updateLocals(updatable);
-
- Q_ASSERT(locals.size() == 1);
- static_cast<Variable*>(locals.at(0))->handleProperty(lst.at(i));
- updatable.clear();
- }*/
-}
-
-DebugSession *VariableController::debugSession() const
-{
- return static_cast<DebugSession*>(const_cast<QObject*>(QObject::parent()));
-}
-
-void VariableController::update()
-{
- variableCollection()->watches()->reinstall();
-}
-
-QString VariableController::expressionUnderCursor(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor)
-{
- QString line = doc->line(cursor.line());
- int index = cursor.column();
- QChar c = line[index];
- if (!c.isLetterOrNumber() && c != '_' && c != '$')
- return QString();
-
- int start = Utils::expressionAt(line, index);
- int end = index;
- for (; end < line.size(); ++end) {
- QChar c = line[end];
- if (!(c.isLetterOrNumber() || c == '_' || c == '$'))
- break;
- }
- if (!(start < end))
- return QString();
-
- QString expression(line.mid(start, end-start));
- expression = expression.trimmed();
- return expression;
-}
-
-
-void VariableController::addWatch(KDevelop::Variable* variable)
-{
- if (Variable *v = dynamic_cast<Variable*>(variable)) {
- variableCollection()->watches()->add(v->fullName());
- }
-}
-
-void VariableController::addWatchpoint(KDevelop::Variable* variable)
-{
- if (Variable *v = dynamic_cast<Variable*>(variable)) {
- KDevelop::ICore::self()->debugController()->breakpointModel()->addWatchpoint(v->fullName());
- }
-}
-
-KDevelop::Variable* VariableController::
-createVariable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
- const QString& expression, const QString& display)
-{
- return new Variable(model, parent, expression, display);
-}
-
-void VariableController::handleEvent(KDevelop::IDebugSession::event_t event)
-{
- IVariableController::handleEvent(event);
-}
-
-}
-
-#include "variablecontroller.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.h (nonexistent)
@@ -1,63 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGDEBUGGER_H
-#define ERLANGDEBUGGER_H
-
-#include <kconfiggroup.h>
-#include <QString>
-#include <kprocess.h>
-#include "messages.h"
-
-namespace ErlangDebugPlugin
-{
-class ErlangCommand;
-
-class ErlangDebugger : public QObject
-{
- Q_OBJECT
-public:
-
- void start(QString runDir, const KConfigGroup& config);
- void execute(ErlangCommand* command);
- void stop();
-
-signals:
- void outputCommand(ErlangOutput* ouput);
- void stdoutReceived(QString data);
-
-protected:
- QString m_erlShellBinary;
- KProcess* m_erlShellProcess;
- QByteArray m_buffer;
-
- void processLine(QByteArray data);
-
-private Q_SLOTS:
- void readyReadStandardOutput();
- void readyReadStandardError();
- void processFinished(int exitCode, QProcess::ExitStatus exitStatus);
- void processErrored(QProcess::ProcessError);
-
-};
-
-}
-
-#endif // ERLANGDEBUGGER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.h (nonexistent)
@@ -1,67 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-#ifndef ERLANG_DEBUG_JOB_H_
-#define ERLANG_DEBUG_JOB_H_
-
-#include <QProcess>
-#include <KUrl>
-
-#include <outputview/outputjob.h>
-
-class KProcess;
-namespace KDevelop
-{
-class OutputModel;
-class ILaunchConfiguration;
-class ProcessLineMaker;
-}
-
-namespace ErlangDebugPlugin
-{
-
-class DebugSession;
-
-class ErlangDebugJob : public KDevelop::OutputJob
-{
-Q_OBJECT
-public:
- ErlangDebugJob( DebugSession* session, KDevelop::ILaunchConfiguration*, QObject* parent = 0 );
- virtual void start();
-
-protected:
- virtual bool doKill();
-
-private slots:
- void processError(QProcess::ProcessError);
- void processFinished(int, QProcess::ExitStatus);
- void stdoutReceived(QString data);
-
-private:
- KDevelop::ILaunchConfiguration* m_launchConfig;
-
- KDevelop::OutputModel* model();
- KProcess* m_proc;
- QPointer<DebugSession> m_session;
-};
-
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.cpp (nonexistent)
@@ -1,109 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include <QXmlStreamReader>
-
-#include <KDebug>
-
-#include "framestackmodel.h"
-#include "messages.h"
-
-namespace ErlangDebugPlugin {
-
-void FrameStackModel::fetchThreads()
-{
-}
-
-/*
-void FrameStackModel::handleStack(const QDomDocument &xml)
-{
- Q_ASSERT(xml.documentElement().attribute("command") == "stack_get");
-
- QList<KDevelop::FrameStackModel::FrameItem> frames;
- QDomElement el = xml.documentElement().firstChildElement("stack");
- while (!el.isNull()) {
- KDevelop::FrameStackModel::FrameItem f;
- f.nr = el.attribute("level").toInt();
- f.name = el.attribute("where");
- f.file = el.attribute("filename");
- f.line = el.attribute("lineno").toInt() - 1;
- frames << f;
- el = el.nextSiblingElement("stack");
- }
- setFrames(0, frames);
- setHasMoreFrames(0, false);
-}*/
-
-void FrameStackModel::fetchFrames(int threadNumber, int from, int to)
-{
- Q_UNUSED(from); //we fetch always everything
- Q_UNUSED(to);
-}
-
-void FrameStackModel::handleStackList(StackTraceOutput* output)
-{
- QList<KDevelop::FrameStackModel::FrameItem> frames;
-
- foreach(StackInfo item, output->getStackTrace())
- {
- KDevelop::FrameStackModel::FrameItem f;
- f.name = item.function_name;
- f.line = item.line;
- f.nr = item.stack_pos;
- f.file = item.filename;
-
- frames << f;
- }
-
- int threadID;
- if (m_processToThreadID.contains(output->getProcess()))
- {
- threadID = m_processToThreadID[output->getProcess()];
- }
- else
- {
- threadID = m_processToThreadID[output->getProcess()] = m_threadID++;
- }
-
- QList<KDevelop::FrameStackModel::ThreadItem> threads;
- QMap<QString, int>::iterator it = m_processToThreadID.begin();
-
- for (; it != m_processToThreadID.end(); ++it)
- {
- KDevelop::FrameStackModel::ThreadItem item;
- item.name = it.key();
- item.nr = it.value();
- threads << item;
- }
-
- setThreads(threads);
-
- setFrames(threadID, frames);
- setHasMoreFrames(threadID, false);
- setCurrentThread(threadID);
-}
-
-FrameStackModel::FrameStackModel(DebugSession* session) :
- KDevelop::FrameStackModel(session) , m_threadID(0)
-{
- connect(session, SIGNAL(stackTraceUpdate(StackTraceOutput*)), this, SLOT(handleStackList(StackTraceOutput*)));
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.cpp (nonexistent)
@@ -1,150 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "variable.h"
-#include "debugsession.h"
-
-#include <QXmlStreamReader>
-
-#include <interfaces/icore.h>
-#include <debugger/interfaces/ivariablecontroller.h>
-#include <debugger/interfaces/iframestackmodel.h>
-#include "messages.h"
-#include "debugsession.h"
-
-namespace ErlangDebugPlugin
-{
-
-static bool hasStartedSession()
-{
- KDevelop::IDebugSession *session = KDevelop::ICore::self()->debugController()->currentSession();
- if ( !session )
- return false;
-
- KDevelop::IDebugSession::DebuggerState s = session->state();
- return s != KDevelop::IDebugSession::NotStartedState
- && s != KDevelop::IDebugSession::EndedState;
-}
-
-Variable::Variable ( KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
- const QString& expression, const QString& display )
- : KDevelop::Variable ( model, parent, expression, display )
-{
-}
-
-Variable::~Variable()
-{
-}
-
-class VariableListCallback : public DebugCallbackBase
-{
-public:
- VariableListCallback ( Variable *variable, QObject *callback, const char *callbackMethod )
- : m_variable ( variable ), m_callback ( callback ), m_callbackMethod ( callbackMethod ) {}
-
- virtual void execute ( ErlangOutput &output )
- {
- if ( !m_variable )
- return;
-
- VariableListOutput* v_output = static_cast<VariableListOutput*> ( &output );
-
- QDomDocument doc = v_output->getDocument();
- QDomNodeList lst = doc.firstChild().childNodes();
-
-
- for ( int i = 0; i < lst.size(); ++i )
- {
- QDomNode node = lst.at ( i );
- if ( node.attributes().namedItem ( "name" ).nodeValue() == m_variable->expression() &&
- m_variable->handleProperty ( node ) )
- {
- QMetaObject::invokeMethod ( m_callback, m_callbackMethod, Q_ARG ( bool, true ) );
- break;
- }
- }
- }
-
-private:
- QPointer<Variable> m_variable;
- QObject *m_callback;
- const char *m_callbackMethod;
-};
-
-void Variable::attachMaybe ( QObject *callback, const char *callbackMethod )
-{
- if ( hasStartedSession() )
- {
- KDevelop::IDebugSession* is = KDevelop::ICore::self()->debugController()->currentSession();
- DebugSession* s = static_cast<DebugSession*>(is);
- s->requestVariables(new VariableListCallback(this, callback, callbackMethod));
- }
-}
-
-void Variable::fetchMoreChildren()
-{
-}
-
-bool Variable::handleProperty ( QDomNode variable )
-{
- setInScope ( true );
-
- QDomNodeList lst = variable.childNodes();
- QString var_name;
-
- for ( int i = 0; i < lst.size(); ++i )
- {
- QDomNode node = lst.item ( i );
- QString node_name = node.nodeName();
-
- if ( node_name == "item" )
- {
- QString data = node.firstChildElement ( "raw_value" ).firstChild().toCDATASection().data();
-
- Variable* v = new Variable ( model(), this, data);
- appendChild ( v, false );
- v->handleProperty ( node );
- }
- else if ( node_name == "value" )
- {
- QString data = node.firstChild().toCDATASection().data();
-
- if ( variable.attributes().contains ( "kind" ) )
- {
- Variable* v = new Variable ( model(), this, data );
- appendChild ( v, false );
- }
- else
- {
- setValue(data);
- }
- }
- }
-
- return true;
-}
-
-QString Variable::fullName() const
-{
- return m_fullName;
-}
-
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.h (nonexistent)
@@ -1,123 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef DEBUGSESSION_H
-#define DEBUGSESSION_H
-
-#include <debugger/interfaces/idebugsession.h>
-#include <debugger/interfaces/iframestackmodel.h>
-
-#include <interfaces/ilaunchconfiguration.h>
-
-#include <kconfiggroup.h>
-
-#include <QPointer>
-#include <QQueue>
-
-namespace ErlangDebugPlugin
-{
-class ErlangCommand;
-class ErlangDebugger;
-class ErlangDebugger;
-class ErlangOutput;
-class BreakpointOutput;
-class VariableListOutput;
-class StackTraceOutput;
-
-static QString erlangShellExecPath = "Erlang ERTS Path";
-static QString rebuildDebuggerInterface = "Rebuild erlang debugger interface prior staring";
-static QString interpretedModules = "List of modules to be interpreted";
-static QString projectDir = "Current project directory";
-static QString libraryPaths = "Libraries folder to be added on debug runtime";
-static QString callableFunction = "function to be called when debugging";
-static QString callableModule = "module to be called when debugging";
-static QString callableArguments = "function arguments to be called when debugging";
-
-class DebugCallbackBase
-{
-public:
- virtual void execute(ErlangOutput&) = 0;
-
- virtual ~DebugCallbackBase() { }
-};
-
-class DebugSession : public KDevelop::IDebugSession
-{
- Q_OBJECT
-public:
- DebugSession();
- void requestVariables(DebugCallbackBase* callback);
- void startDebugger(KDevelop::ILaunchConfiguration* cfg);
- void sendBreakpoint(QString location, int line);
- void interpretMoule(QString module);
- void spawn(QString module, QString function, QString arguments);
- void removeBreakpoint(QString module, int line);
-
-Q_SIGNALS:
- void breakpointUpdate(BreakpointOutput*);
- void variableListUpdate(VariableListOutput*);
- void stackTraceUpdate(StackTraceOutput*);
- void stdoutReceived(QString data);
-
-public Q_SLOTS:
- ///called when user selects a different process (not thread) on our stack model
- virtual void updateCurrentActiveProcess(QString processID);
-
-
- virtual void stepOut();
- virtual void stepOverInstruction();
- virtual void stepInto();
- virtual void stepIntoInstruction();
- virtual void stepOver();
- virtual void jumpToCursor();
- virtual void runToCursor();
- virtual void run();
- virtual void interruptDebugger();
- virtual void stopDebugger();
- virtual void restartDebugger();
- virtual bool restartAvaliable() const;
- virtual KDevelop::IDebugSession::DebuggerState state() const;
-
-private slots:
-
- void executeCmd();
- void handleDebuggerCommand(ErlangOutput* command);
-
-protected:
- virtual KDevelop::IFrameStackModel* createFrameStackModel();
-
-private:
- QPointer<ErlangDebugger> m_erlDebugger;
- QQueue<ErlangCommand*> m_commands;
-
- ///Stores information about metaprocesses and its relation to
- ///real processes
- QMap<QString, QString> m_processToMeta;
- QMap<qlonglong, DebugCallbackBase* > m_callbacks;
-
- QList<QString> m_interpretedModules;
-
- QString m_currentProcess;
-
- qlonglong m_requestID;
-};
-
-}
-#endif // DEBUGSESSION_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.h (nonexistent)
@@ -1,256 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGCOMMAND_H
-#define ERLANGCOMMAND_H
-
-#include <QString>
-#include <QStringList>
-#include <QDomDocument>
-
-namespace ErlangDebugPlugin
-{
-
-namespace InterpreterCommand
-{
-enum InterpreterCommand
-{
- BREAK,
- CONDITIONAL_BREAK,
- CONTINUE,
- STEP,
- NEXT,
- FINISH,
- INTERPRET,
- VARIABLE_LIST,
- SPAWN_FUNCTION,
- REMOVE_BREAKPOINT
-};
-
-}
-
-enum OutputCommandType
-{
- VariableListOutputType,
- BreakpointOutputType,
- MetaOutputType,
- ProcessStatusUpdateType,
- StackTraceOutputType
-};
-
-namespace ErlangProcessStatus
-{
-enum status
-{
- Running,
- Idle,
- Exit
-};
-
-}
-
-class ErlangOutput
-{
-public:
- ErlangOutput(const QStringList& rawData, OutputCommandType command);
- virtual void parse() = 0;
-
- OutputCommandType getCommandType();
-
- virtual ~ErlangOutput();
-protected:
- QStringList m_rawData;
- OutputCommandType m_command;
-};
-
-class VariableListOutput : public ErlangOutput
-{
- public:
- VariableListOutput(const QStringList& rawData)
- : ErlangOutput(rawData, VariableListOutputType)
- {
- }
- void parse();
-
- QDomDocument& getDocument();
-
- protected:
- QDomDocument m_document;
-};
-
-struct StackInfo
-{
- QString function_name;
- QString filename;
- int line;
- int stack_pos;
-};
-
-class StackTraceOutput : public ErlangOutput
-{
- public:
- StackTraceOutput(const QStringList& rawData)
- : ErlangOutput(rawData, StackTraceOutputType)
- {
- }
- void parse();
-
- QList<StackInfo>& getStackTrace();
- QString& getProcess();
- protected:
- QString m_process;
- QList<StackInfo> m_stackTrace;
-};
-
-class MetaProcessOutput : public ErlangOutput
-{
- public:
- MetaProcessOutput(const QStringList& rawData)
- : ErlangOutput(rawData, MetaOutputType)
- {
- }
-
- void parse();
- QString getProcess();
- QString getMeta();
-};
-
-class BreakpointOutput : public ErlangOutput
-{
-public:
- BreakpointOutput(const QStringList& rawData)
- : ErlangOutput(rawData, BreakpointOutputType)
- {
- }
-
- void parse();
- QString getModule();
- int getLine();
- QString getProcess();
-};
-
-class ProcessStatusUpdateOutput : public ErlangOutput
-{
-public:
- ProcessStatusUpdateOutput(const QStringList& rawData)
- : ErlangOutput(rawData, ProcessStatusUpdateType)
- {
- }
-
- void parse();
- QString getProcess();
- ErlangProcessStatus::status getProcessStatus();
- QString getProcessAdditionalInfo();
-};
-
-class ErlangCommand
-{
-public:
- ErlangCommand(QString meta, InterpreterCommand::InterpreterCommand command);
- virtual QString getCommand() = 0;
- virtual ~ErlangCommand();
-protected:
- QString m_meta;
- InterpreterCommand::InterpreterCommand m_command;
-};
-
-class StepCommand : public ErlangCommand
-{
-public:
- StepCommand(QString meta);
-
- virtual QString getCommand();
-};
-
-class ContinueCommand : public ErlangCommand
-{
-public:
- ContinueCommand(QString meta);
- virtual QString getCommand();
-};
-
-class NextCommand : public ErlangCommand
-{
-public:
- NextCommand (QString meta);
- virtual QString getCommand();
-};
-
-class FinishCommand : public ErlangCommand
-{
-public:
- FinishCommand (QString meta);
- virtual QString getCommand();
-};
-
-class InterpretModuleCommand : public ErlangCommand
-{
-public:
- InterpretModuleCommand (QString moduleName);
- virtual QString getCommand();
-protected:
- QString m_module;
-};
-
-
-class SpawnFunctionCommand : public ErlangCommand
-{
-public:
- SpawnFunctionCommand(QString module, QString function, QString parameters);
- virtual QString getCommand();
-protected:
- QString m_function;
- QString m_module;
- QString m_parameters;
-};
-
-class VariablesInContextCommand : public ErlangCommand
-{
-public:
- VariablesInContextCommand (QString meta);
- virtual QString getCommand();
-
-protected:
- QString m_meta;
-};
-
-class RemoveBreakpoint : public ErlangCommand
-{
-public:
- RemoveBreakpoint(QString module, unsigned int line);
- virtual QString getCommand();
-protected:
- unsigned int m_line;
- QString m_module;
-};
-
-class BreakCommand : public ErlangCommand
-{
-public:
- BreakCommand(QString module, unsigned int line);
- virtual QString getCommand();
-protected:
- QString m_module;
- unsigned int m_line;
-};
-
-}
-
-#endif // ERLANGCOMMAND_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/breakpointcontroller.h (nonexistent)
@@ -1,50 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGBREAKPOINTCONTROLLER_H
-#define ERLANGBREAKPOINTCONTROLLER_H
-
-#include <debugger/interfaces/ibreakpointcontroller.h>
-#include <debugger/interfaces/idebugsession.h>
-
-namespace ErlangDebugPlugin
-{
-class DebugSession;
-class BreakpointOutput;
-
-class ErlangBreakpointController : public KDevelop::IBreakpointController
-{
- Q_OBJECT
-public:
- ErlangBreakpointController(DebugSession* parent);
- virtual void sendMaybe(KDevelop::Breakpoint* breakpoint);
-
-private slots:
- void stateChanged(KDevelop::IDebugSession::DebuggerState state);
- void hitBreakpoint(BreakpointOutput* breakpoint);
-
-private:
- DebugSession *debugSession();
- QMap<KDevelop::Breakpoint*, QString> m_ids;
-
-};
-
-}
-#endif // ERLANGBREAKPOINTCONTROLLER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/framestackmodel.h (nonexistent)
@@ -1,57 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANG_FRAMESTACKMODEL_H
-#define ERLANG_FRAMESTACKMODEL_H
-
-#include <debugger/framestack/framestackmodel.h>
-
-#include "debugsession.h"
-#include "messages.h"
-
-class QDomDocument;
-namespace ErlangDebugPlugin {
-
-class FrameStackModel : public KDevelop::FrameStackModel
-{
- Q_OBJECT
-public:
- FrameStackModel(DebugSession* session) ;
-
-public:
- DebugSession* session() { return static_cast<DebugSession*>(KDevelop::FrameStackModel::session()); }
-
-
-protected slots:
- void handleStackList(StackTraceOutput*);
-
-protected: // KDevelop::FrameStackModel overrides
- virtual void fetchThreads();
- virtual void fetchFrames(int threadNumber, int from, int to);
-
- QMap< QString, int > m_processToThreadID;
- int m_threadID;
-private:
- //void handleStack(const QDomDocument &xml);
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/launchconfig.h (nonexistent)
@@ -1,78 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGLAUNCHCONFIG_H
-#define ERLANGLAUNCHCONFIG_H
-
-#include <interfaces/ilauncher.h>
-#include <interfaces/launchconfigurationpage.h>
-#include <QTreeWidget>
-
-#include "ui_debug_config.h"
-
-namespace KDevelop {
- class PathMappingsWidget;
-}
-
-namespace ErlangDebugPlugin
-{
-class ErlangDebuggerPlugin;
-
-class ConfigPageFactory : public KDevelop::LaunchConfigurationPageFactory
-{
-public:
- virtual KDevelop::LaunchConfigurationPage* createWidget(QWidget* parent);
-};
-
-class ConfigPage : public KDevelop::LaunchConfigurationPage , public Ui::ErlangDebugConfigDialog
-{
-Q_OBJECT
-public:
- ConfigPage( QWidget* parent = 0 );
- virtual KIcon icon() const;
- virtual void loadFromConfiguration(const KConfigGroup& cfg, KDevelop::IProject* = 0);
- virtual void saveToConfiguration(KConfigGroup, KDevelop::IProject* = 0 ) const;
- virtual QString title() const;
-private:
- KDevelop::PathMappingsWidget *m_pathMappings;
- QTreeView* m_treeView;
-};
-
-
-class ErlangLauncher : public KDevelop::ILauncher
-{
-public:
- ErlangLauncher(ErlangDebugPlugin::ErlangDebuggerPlugin* plugin);
-
- virtual KJob* start(const QString& launchMode, KDevelop::ILaunchConfiguration* cfg);
- virtual QList< KDevelop::LaunchConfigurationPageFactory* > configPages() const;
- virtual QStringList supportedModes() const;
- virtual QString description() const;
- virtual QString name() const;
- virtual QString id();
-
-private:
- QList<KDevelop::LaunchConfigurationPageFactory*> factoryList;
- ErlangDebuggerPlugin* m_plugin;
-};
-
-}
-
-#endif // ERLANGLAUNCHCONFIG_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.cpp (nonexistent)
@@ -1,70 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-#include "debugplugin.h"
-
-#include <interfaces/icore.h>
-#include <interfaces/idebugcontroller.h>
-#include <kpluginfactory.h>
-#include <klocalizedstring.h>
-#include <kaboutdata.h>
-
-#include <execute/iexecuteplugin.h>
-#include <interfaces/launchconfigurationtype.h>
-#include <interfaces/icore.h>
-#include <interfaces/iplugincontroller.h>
-
-#include "debugsession.h"
-#include "launchconfig.h"
-
-namespace ErlangDebugPlugin
-{
-K_PLUGIN_FACTORY(ErlangDebuggerFactory, registerPlugin<ErlangDebuggerPlugin>(); )
-K_EXPORT_PLUGIN(ErlangDebuggerFactory(KAboutData("kdeverldebug","kdeverldebug", ki18n("Erlang debug support"), "0.1", ki18n("Support for debugging erlang apps"), KAboutData::License_GPL)))
-
-
-ErlangDebuggerPlugin::ErlangDebuggerPlugin(QObject* parent, const QVariantList& ): IPlugin(ErlangDebuggerFactory::componentData(), parent )
-{
- {
- IExecutePlugin* iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
- Q_ASSERT(iface);
- KDevelop::LaunchConfigurationType* type = core()->runController()->launchConfigurationTypeForId( iface->nativeAppConfigTypeId() );
- Q_ASSERT(type);
- type->addLauncher( new ErlangLauncher( this ) );
- }
-}
-
-DebugSession* ErlangDebuggerPlugin::createSession() const
-{
- DebugSession *session = new DebugSession();
- KDevelop::ICore::self()->debugController()->addSession(session);
- //connect(session, SIGNAL(showMessage(QString,int)), SLOT(controllerMessage(QString,int)));
- //connect(session, SIGNAL(reset()), SIGNAL(reset()));
- connect(session, SIGNAL(finished()), SLOT(slotFinished()));
- //connect(session, SIGNAL(raiseOutputViews()), SIGNAL(raiseOutputViews()));
- //connect(session, SIGNAL(raiseVariableViews()), SIGNAL(raiseVariableViews()));
- return session;
-}
-
-ErlangDebuggerPlugin::~ErlangDebuggerPlugin()
-{
-
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugger.cpp (nonexistent)
@@ -1,231 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "debugger.h"
-
-#include "debugsession.h"
-#include "kdebug.h"
-#include <kstandarddirs.h>
-
-namespace ErlangDebugPlugin
-{
-
-void ErlangDebugger::start(QString runDir, const KConfigGroup& config)
-{
- KUrl erlangdebuggerUrl = config.readEntry(ErlangDebugPlugin::erlangShellExecPath, KUrl());
- if (erlangdebuggerUrl.isEmpty()) {
- m_erlShellBinary = "/usr/bin/erl";
- } else {
- // FIXME: verify its' a local path.
- m_erlShellBinary = erlangdebuggerUrl.toLocalFile(KUrl::RemoveTrailingSlash);
- }
-
- m_erlShellProcess = new KProcess(this);
- m_erlShellProcess->setWorkingDirectory(runDir);
-
- m_erlShellProcess->setOutputChannelMode( KProcess::SeparateChannels );
- connect(m_erlShellProcess, SIGNAL(readyReadStandardOutput()),
- SLOT(readyReadStandardOutput()));
-
- connect(m_erlShellProcess, SIGNAL(readyReadStandardError()),
- SLOT(readyReadStandardError()));
-
- connect(m_erlShellProcess,
- SIGNAL(finished(int, QProcess::ExitStatus)),
- SLOT(processFinished(int, QProcess::ExitStatus)));
-
- connect(m_erlShellProcess, SIGNAL(error(QProcess::ProcessError)),
- SLOT(processErrored(QProcess::ProcessError)));
-
- QString debuggerInterpreterBeamPath = KStandardDirs::locateLocal("data", "kdeverlangsupport/debug_interpreter.beam");
- QString debuggerInterpreterFolder = KStandardDirs::locateLocal("data", "kdeverlangsupport/");
- Q_ASSERT(KStandardDirs::exists(debuggerInterpreterFolder));
-
- //if we dont have the precompiled beam, invoke erlc to build it
- if (!KStandardDirs::exists(debuggerInterpreterBeamPath) ||
- (config.hasKey(rebuildDebuggerInterface) && config.readEntry(rebuildDebuggerInterface, false)))
- {
- kDebug() << "Trying to build debugger interpreter source... ";
-
- QString debuggerInterpreterErlPath = KStandardDirs::locate("data", "kdeverlangsupport/debug_interpreter.erl");
-
- Q_ASSERT(KStandardDirs::exists(debuggerInterpreterErlPath));
-
- KProcess erlcProcess;
- erlcProcess << "/usr/bin/erlc" << "-o" << debuggerInterpreterFolder << debuggerInterpreterErlPath ;
- erlcProcess.execute();
- erlcProcess.waitForFinished();
-
- kDebug() << "process exit code: " << erlcProcess.exitCode();
-
- kDebug() << "erlc stdout: " << erlcProcess.readAll();
- kDebug() << "erlc stderr: " << erlcProcess.readAllStandardError();
- }
-
-
- //Passing as ERL_FLAGS since somehow the KProcess isn't providing them to the erlang shell
- QStringList arguments;
- arguments << "-noshell" << "-eval \"debug_interpreter:start()\"" << "-pa" << debuggerInterpreterFolder;
-
- QStringList libraryIncludePaths = config.readEntry(ErlangDebugPlugin::libraryPaths, QStringList());
-
- foreach(QString path, libraryIncludePaths)
- {
- arguments << "-pa" << path;
- }
-
- kDebug() << "ERL_FLAGS are: " << arguments.join(" ");
-
- m_erlShellProcess->setEnv("ERL_FLAGS", arguments.join(" "), true);
-
- m_erlShellProcess->setProgram(m_erlShellBinary);
- m_erlShellProcess->start();
-
- kDebug() << "Erlang shell PID is: " << m_erlShellProcess->pid();
- kDebug() << "STARTING ERLANG SHELL\n";
-}
-
-void ErlangDebugger::processErrored(QProcess::ProcessError )
-{
- kDebug() << "erlang shell process error: " << m_erlShellProcess->readAllStandardError();
-}
-
-void ErlangDebugger::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
-{
- kDebug() << "erlang shell process finished: " << ((exitCode == 0) ? m_erlShellProcess->readAllStandardOutput() : m_erlShellProcess->readAllStandardError());
-}
-
-void ErlangDebugger::readyReadStandardError()
-{
- kDebug() << "erlang shell process error: " << m_erlShellProcess->readAllStandardError();
-}
-
-void ErlangDebugger::readyReadStandardOutput()
-{
- m_erlShellProcess->setReadChannel(QProcess::StandardOutput);
- m_buffer += m_erlShellProcess->readAll();
- int i;
- for (;;)
- {
- i = m_buffer.indexOf('\0');
- if (i == -1 || i && i > 0)
- {
- if (m_buffer.size())
- {
- kDebug() << "Received standard output from processes. Signaling:" << m_buffer;
- if (i > 0)
- {
- emit stdoutReceived(m_buffer.left(i).trimmed());
- m_buffer = m_buffer.mid(i);
- }
- else
- {
- emit stdoutReceived(QString(m_buffer).trimmed());
- m_buffer.clear();
- }
- }
-
- if (i == -1)
- break;
- }
- else
- {
- if ((i = m_buffer.indexOf('\0', i + 1)) >= 0)
- {
- QByteArray reply(m_buffer.left(i));
- m_buffer = m_buffer.mid(i + 1);
-
- reply.remove(0,1);
- reply.remove(i - 1, 1);
-
- processLine(reply);
- }
- else
- {
- break;
- }
- }
- }
-}
-
-void ErlangDebugger::execute(ErlangCommand* command)
-{
- QString cmdStr = command->getCommand();
-
- kDebug() << "Sending command to erlang process: " << cmdStr;
- m_erlShellProcess->write(cmdStr.toLatin1(), cmdStr.size());
- m_erlShellProcess->write("\n");
-
- delete command;
-}
-
-void ErlangDebugger::processLine(QByteArray data)
-{
- if (data.contains("---"))
- {
- kDebug() << "Debug information from erlang debugger process: " << data;
- }
- else
- {
- kDebug() << "Received command: " << data;
- QString command(data);
-
- QStringList items = command.split("|");
-
- //todo: shared ptrs?
- ErlangOutput* output = 0;
-
- if (items[0] == "break")
- {
- output = new BreakpointOutput(items);
- }
- else if (items[0] == "meta")
- {
- output = new MetaProcessOutput(items);
- }
- else if (items[0] == "process_status_update")
- {
- output = new ProcessStatusUpdateOutput(items);
- }
- else if (items[0] == "variables_list")
- {
- output = new VariableListOutput(items);
- }
- else if (items[0] == "stack_trace")
- {
- output = new StackTraceOutput(items);
- }
-
- if (output)
- {
- output->parse();
- emit outputCommand(output);
- }
-
- delete output;
- }
-}
-
-void ErlangDebugger::stop()
-{
- m_erlShellProcess->kill();
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/stringhelpers.h (nonexistent)
@@ -1,35 +0,0 @@
-/*
- Copyright 2007 David Nolden <david.nolden.kdevelop@art-master.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef __STRINGHELPERS_H__
-#define __STRINGHELPERS_H__
-
-class QString;
-class QChar;
-class QStringList;
-
-namespace Utils {
-
-/**
- * Copied from kdevelop-3.4, should be redone
- * @param index should be the index BEHIND the expression
- * */
-int expressionAt( const QString& contents, int index );
-
-}
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugplugin.h (nonexistent)
@@ -1,43 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGDEBUGPLUGIN_H
-#define ERLANGDEBUGPLUGIN_H
-
-#include <interfaces/iplugin.h>
-#include <debugger/interfaces/idebugsession.h>
-
-namespace ErlangDebugPlugin
-{
-class DebugSession;
-
-class ErlangDebuggerPlugin : public KDevelop::IPlugin
-{
- Q_OBJECT
-public:
- ErlangDebuggerPlugin( QObject* parent, const QVariantList & = QVariantList() );
- ~ErlangDebuggerPlugin();
-
- DebugSession* createSession() const;
-};
-
-}
-
-#endif // ERLANGDEBUGPLUGIN_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/kdeverldebug.desktop (nonexistent)
@@ -1,77 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=This plugin provides a frontend for Erlang debugger
-Comment[bs]=Ovaj dodatak daje sučelje za Erlang debugger.
-Comment[ca]=Aquest connector proveeix d'un frontal pel depurador Erlang
-Comment[ca@valencia]=Aquest connector proveeix d'un frontal pel depurador Erlang
-Comment[de]=Dieses Modul stellt eine Oberfläche für den Erland-Debugger zur Verfügung
-Comment[en_GB]=This plugin provides a frontend for Erlang debugger
-Comment[es]=Este complemento proporciona una interfaz para el depurador de Erlang
-Comment[et]=Erlangi siluri kasutajaliidese plugin
-Comment[fr]=Ce module externe fournit une interface pour Erlang
-Comment[gl]=Este complemento fornece unha interface para o depurador de Erlang.
-Comment[it]=Questa estensione fornisce un'interfaccia per il debugger Erlang
-Comment[nl]=Deze plugin geeft een frontend voor de Erlang debugger
-Comment[pl]=Wtyczka ta dostarcza interfejs dla debugowania Erlang
-Comment[pt]=Este 'plugin' oferece uma interface para o depurador de Erlang
-Comment[pt_BR]=Este plugin fornece uma interface para o depurador Erlang
-Comment[sv]=Insticksprogrammet tillhandahåller ett gränssnitt för Erlang avlusare
-Comment[uk]=Цей додаток є оболонкою до зневадника Erlang
-Comment[x-test]=xxThis plugin provides a frontend for Erlang debuggerxx
-Name=Erlang Debugger Support
-Name[bs]=Podrška Erlang Debugger-u
-Name[ca]=Implementació del depurador Erlang
-Name[ca@valencia]=Implementació del depurador Erlang
-Name[de]=Sprachunterstützung für Erlang-Debugger
-Name[en_GB]=Erlang Debugger Support
-Name[es]=Implementación del depurador Erlang
-Name[et]=Erlangi siluri toetus
-Name[fr]=Prise en charge du débogueur Erlang
-Name[gl]=Compatibilidade co depurador de Erlang
-Name[it]=Supporto per debugger Erlang
-Name[nl]=Ondersteuning voor Erlang debugger
-Name[pl]=Obsługa debuggera Erlang
-Name[pt]=Suporte para o Depurador de Erlang
-Name[pt_BR]=Suporte para a depurador Erlang
-Name[sv]=Stöd för Erlang avlusare
-Name[uk]=Підтримка зневадника мови Erlang
-Name[x-test]=xxErlang Debugger Supportxx
-GenericName=Debugger Frontend
-GenericName[bs]=Korisničko okruženje za ispravljač grešaka
-GenericName[ca]=Frontal del depurador
-GenericName[ca@valencia]=Frontal del depurador
-GenericName[cs]=Rozhraní pro ladicí nástroj
-GenericName[de]=Oberfläche für Debugger
-GenericName[en_GB]=Debugger Frontend
-GenericName[es]=Interfaz del depurador
-GenericName[et]=Siluri kasutajaliides
-GenericName[fr]=Interface du débogueur
-GenericName[ga]=Comhéadan Dífhabhtóra
-GenericName[gl]=Interface para o depurador
-GenericName[hu]=Hibakereső előtétprogram
-GenericName[it]=Interfaccia debugger
-GenericName[ja]=デバッガのフロントエンド
-GenericName[nds]=Fehlersöker-Böversiet
-GenericName[nl]=Frontend voor debugger
-GenericName[pa]=ਡੀਬੱਗਰ ਫਰੰਟਐਂਡ
-GenericName[pl]=Interfejs do debuggera
-GenericName[pt]=Interface do Depurador
-GenericName[pt_BR]=Interface do depurador
-GenericName[sk]=Rozhranie debuggera
-GenericName[sv]=Avlusargränssnitt
-GenericName[tr]=Hata Ayıklayıcı Önucu
-GenericName[ug]=سازلىغۇچ ئالدى ئۇچى
-GenericName[uk]=Клієнтська програма зневадника
-GenericName[x-test]=xxDebugger Frontendxx
-
-Icon=debugger
-X-KDE-Library=kdeverldebug
-X-KDevelop-Category=Global
-X-KDevelop-Version=10
-X-KDE-PluginInfo-Name=kdeverldebug
-X-KDE-PluginInfo-License=GPL
-ServiceTypes=KDevelop/Plugin
-X-KDevelop-Interfaces=org.kdevelop.IRunProvider
-X-KDevelop-IRequired=org.kdevelop.IExecutePlugin
-X-KDevelop-Mode=GUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugjob.cpp (nonexistent)
@@ -1,153 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-
-#include "debugjob.h"
-
-#include <QFileInfo>
-#include <QDesktopServices>
-
-#include <KProcess>
-#include <kconfiggroup.h>
-#include <kicon.h>
-#include <klocale.h>
-#include <kshell.h>
-#include <KMessageBox>
-#include <KParts/MainWindow>
-
-#include <outputview/outputmodel.h>
-#include <interfaces/ilaunchconfiguration.h>
-#include <util/environmentgrouplist.h>
-#include <execute/iexecuteplugin.h>
-#include <interfaces/iproject.h>
-#include <project/interfaces/iprojectbuilder.h>
-#include <project/builderjob.h>
-#include <interfaces/iuicontroller.h>
-#include <project/interfaces/ibuildsystemmanager.h>
-#include <util/executecompositejob.h>
-#include <interfaces/iplugincontroller.h>
-#include <interfaces/icore.h>
-#include <util/processlinemaker.h>
-
-#include "debugsession.h"
-#include "debugplugin.h"
-
-#include <kdebug.h>
-
-namespace ErlangDebugPlugin {
-
-ErlangDebugJob::ErlangDebugJob( DebugSession* session, KDevelop::ILaunchConfiguration* cfg, QObject* parent)
- : m_proc(0), m_session(session), m_launchConfig(cfg)
-{
- setCapabilities(Killable);
-
- connect(m_session, SIGNAL(stdoutReceived(QString)), SLOT(stdoutReceived(QString)));
-
- setObjectName(cfg->name());
-
-
-}
-
-void ErlangDebugJob::start()
-{
- setBehaviours(KDevelop::IOutputView::AllowUserClose | KDevelop::IOutputView::AutoScroll);
- setStandardToolView(KDevelop::IOutputView::DebugView);
- setModel( new KDevelop::OutputModel(), KDevelop::IOutputView::TakeOwnership );
-
- KDevelop::EnvironmentGroupList l(KGlobal::config());
- IExecutePlugin * iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
-
- Q_ASSERT(iface);
- QString err;
- QString envgrp = iface->environmentGroup( m_launchConfig );
-
- if( envgrp.isEmpty() )
- {
- kWarning() << i18n("No environment group specified, looks like a broken "
- "configuration, please check run configuration '%1'. "
- "Using default environment group.", m_launchConfig->name() );
- envgrp = l.defaultGroup();
- }
-
- QStringList arguments = iface->arguments( m_launchConfig, err );
-
- if( !err.isEmpty() )
- {
- setError( -1 );
- setErrorText( err );
- }
-
- if( error() != 0 )
- {
- emitResult();
- return;
- }
-
- startOutput();
-
- m_session->startDebugger(m_launchConfig);
-}
-
-bool ErlangDebugJob::doKill()
-{
- kDebug();
- if (m_session) m_session->stopDebugger();
- return true;
-}
-
-void ErlangDebugJob::processFinished( int exitCode , QProcess::ExitStatus status )
-{
- emitResult();
-
- if (m_session) delete m_session;
-}
-
-void ErlangDebugJob::processError( QProcess::ProcessError error )
-{
- if( error == QProcess::FailedToStart )
- {
- setError( -1 );
- QString errmsg = i18n("Could not start program '%1'. Make sure that the "
- "path is specified correctly.", m_proc->property("executable").toString() );
- KMessageBox::error( KDevelop::ICore::self()->uiController()->activeMainWindow(), errmsg, i18n("Could not start application") );
- setErrorText( errmsg );
- emitResult();
- }
- kDebug() << "Process error";
-
- if (m_session) delete m_session;
-}
-
-KDevelop::OutputModel* ErlangDebugJob::model()
-{
- return dynamic_cast<KDevelop::OutputModel*>( KDevelop::OutputJob::model() );
-}
-
-void ErlangDebugJob::stdoutReceived(QString data)
-{
- if (KDevelop::OutputModel* m = model()) {
- m->appendLine(data);
- }
-}
-
-
-}
-
-#include "debugjob.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_interpreter.erl (nonexistent)
@@ -1,170 +0,0 @@
--module(debug_interpreter).
-
--export([start/0, start_loop/0]).
-
--define(DEBUG(Text,Parameters), io:format( [0] ++ "---" ++ Text ++ [0], Parameters )).
--define(OUTPUT(Text, Parameters), io:format([0] ++ Text ++ [0] , Parameters )).
-
-
-start() ->
- application:start(sasl),
- ?DEBUG("starting debug system on: ~w",[self()]),
- ?DEBUG("erlang:register: [~w]", [erlang:register(internal_meta, spawn(fun() -> start_loop() end))]),
- ?DEBUG("erlang:register: [~w]", [erlang:register(input_reader_proc, spawn(fun() -> input_reader_sync() end))]).
-
-input_reader_sync() ->
- receive
- started ->
- input_reader()
- end.
-
-input_reader() ->
- case io:read("") of
- eof ->
- ok;
- { error, Reason } ->
- ?DEBUG("ERROR INPUT ~w", [Reason]);
- { ok, Term } ->
- ?DEBUG("Readed term ~w",[Term]),
- internal_meta ! { user_input, Term }
- end,
- input_reader().
-
-start_loop() ->
- ?DEBUG("Starting debug loop", []),
- ?DEBUG("Starting int: [~w]", [int:start()]),
- ?DEBUG("Subscribe: ~w", [int:subscribe()]),
- %?DEBUG("Stack trace: ~w", [int:stack_trace(all)]),
- input_reader_proc ! started,
- loop().
-
-process_user_input({ interpret , Module }) ->
- ?DEBUG("Trying to interpret module [~w]", [Module]),
- case int:i(Module) of
- { module, M } ->
- ?OUTPUT("interpret|ok|~w", [M]);
- error ->
- ?OUTPUT("interpret|error|~w }", [Module])
- end;
-
-process_user_input({launch, { Module, Function, Parameters }}) ->
- ?DEBUG("Trying launch function [~w] from module [~w] and parameters ~w", [Module, Function, Parameters] ),
- ?DEBUG("spawn result: [~w]", [spawn(Module, Function, Parameters)]);
-
-process_user_input({ action, Action, Pid }) ->
- PID = list_to_pid(Pid),
- ?DEBUG("Sending action [~w] to pid [~w]:[~w]", [Action, PID, int:meta(PID, Action)]);
-
-process_user_input({ var_list , Meta }) ->
- ?DEBUG("Trying to convert to meta pid: [~s]", [Meta]),
- META = list_to_pid(Meta),
- ?DEBUG("Trying to get variable list for MetaProcess [~w]", [META]),
- VariablesList = int:meta(META, bindings, nostack),
- ?DEBUG("Variable list is : ~w",[VariablesList]),
- ParsedData = start_parsing_variables(VariablesList),
- ?DEBUG("Parsed data is : ~s", [ParsedData]),
- ?OUTPUT("variables_list|~s", [ParsedData]);
-
-process_user_input({ break_remove , Module , Line }) ->
- ?DEBUG("Trying remove a breakpoint for module [~w] on line [~p] ", [Module, Line] ),
- ?OUTPUT("break_remove|~w|~w|~p", [int:delete_break(Module, Line), Module, Line]);
-
-process_user_input({ break , Module , Line }) ->
- ?DEBUG("Trying create a breakpoint for module [~s] on line [~p] ", [Module, Line] ),
- case int:break(Module, Line) of
- ok ->
- ?OUTPUT("break_set|ok|~w", [Module]);
- { error, break_exists } ->
- ?OUTPUT("break_set|ok|~w", [Module])
- end.
-
-%%% Message handling
-
-handle({ user_input , UserInput }) ->
- process_user_input(UserInput);
-
-handle({int, {new_process, { Process , FunctionInfo , Status , Info} } }) ->
- ?DEBUG("Trapped a new process info, trying to attach it to debugger... [~w] [~w] [~w]", [FunctionInfo, Status, Info]),
- case int:attached(Process) of
- { ok, Meta } ->
- ?DEBUG("Got MetaProcess [~w] for process [~w]", [Meta, Process]),
- ?OUTPUT("meta|~w|~w", [ Process, Meta ] );
- error ->
- ignore
- end;
-
-handle({ int, { new_status, Process ,break, { Module, Line } } }) ->
- ?DEBUG("Trapped a break on module [~w] and line [~w]", [Module, Line ]),
- {ok, Meta} = dbg_iserver:call({get_meta, Process}),
-% TODO: check problems with variable controller
-% VariablesList = int:meta(Meta, bindings, nostack),
-% ?DEBUG("Variable list is : ~w", [VariablesList]),
-% ParsedData = start_parsing(VariablesList),
-% ?DEBUG("Parsed data is : ~s", [ParsedData]),
-% ?OUTPUT("variables_list|~s", [ParsedData]),
- Backtrace = int:meta(Meta, backtrace, 40),
- ?DEBUG("backtrace message is: [~w]", [Backtrace]),
- ?OUTPUT("stack_trace|~w|~s", [ Process, start_parsing_stack(Meta, Backtrace)]),
- ?OUTPUT("break|~s|~w|~w",[int:file(Module), Line, Process]);
-
-handle({ int, { new_status, Process , exit, Info } }) ->
- ?DEBUG("Trapped a process exit for process [~w] and info [~w]", [ Process, Info]),
- ?OUTPUT("process_status_update|~w|~w|~w",[Process, exit, Info]);
-
-handle({ int, { new_status, _ , _ , _ } }) -> ok;
-
-handle(Unknown) -> ok.
-
-%%%%%%%%%%%%%%%%%%%%%%%% STACK TRACE PARSING %%%%%%%%%%%%%%%%%%%%%%
-
-start_parsing_stack(Meta, [ { SP , { Module, Function, _ } } | T ]) ->
- Item = int:meta(Meta, stack_frame, { up , SP + 1 }),
- ?DEBUG("Item is: [~w]", [Item]),
- { _ , { _ , Line } , _ } = Item,
- Name = case int:file(Module) of
- { error, _ } -> "";
- Ok -> Ok
- end,
- io_lib:format("~p,~s:~s,~s,~p ", [ SP, Module, Function, Name, Line ]) ++ start_parsing_stack(Meta, T);
-
-start_parsing_stack( _ , [ ]) -> "".
-
-%%%%%%%%%%%%%%%%%%%%%%%% STACK TRACE PARSING END %%%%%%%%%%%%%%%%%%%%%%
-
-%%%%%%%%%%% VARIABLE LIST TO XML CONVERSION %%%%%%%%%%%%%%%%%%
-
-start_parsing_variables(Data) ->
- io_lib:format("<variables>~s</variables>" , [ parse(Data) ]).
-
-parse([]) -> "";
-
-parse([H|T]) ->
- parse(H) ++ parse(T);
-
-parse({ VariableName , Variable }) ->
- io_lib:format("<variable name=\"~s\"><raw_value><![CDATA[~w]]></raw_value>~s</variable>",[erlang:atom_to_list(VariableName), Variable, parse_variable(Variable)]).
-
-parse_variable(RawValue) when is_list(RawValue) ->
- io_lib:format("<item kind=\"list\"><raw_value><![CDATA[~w]]></raw_value>~s</item>",[RawValue, parse_list_items(RawValue)]);
-
-parse_variable( RawValue ) when is_tuple(RawValue) ->
- io_lib:format("<item kind=\"tuple\"><raw_value><![CDATA[~w]]></raw_value>~s</item>",[RawValue, parse_list_items(erlang:tuple_to_list(RawValue))]);
-
-parse_variable( Other )->
- io_lib:format("<value><![CDATA[~w]]></value>", [Other]).
-
-parse_list_items([]) -> "";
-
-parse_list_items([ H | T ]) ->
- parse_variable(H) ++ parse_list_items(T).
-
-%%%%%%%%%%% END VARIABLE LIST TO XML CONVERSION %%%%%%%%%%%%%%%%%%
-
-%%% End message handling
-
-loop() ->
- receive
- Data ->
- handle(Data),
- loop()
- end.
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_config.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_config.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debug_config.ui (nonexistent)
@@ -1,174 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>ErlangDebugConfigDialog</class>
- <widget class="QWidget" name="ErlangDebugConfigDialog">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>438</width>
- <height>496</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>200</width>
- <height>200</height>
- </size>
- </property>
- <layout class="QFormLayout" name="formLayout">
- <property name="sizeConstraint">
- <enum>QLayout::SetDefaultConstraint</enum>
- </property>
- <property name="fieldGrowthPolicy">
- <enum>QFormLayout::ExpandingFieldsGrow</enum>
- </property>
- <property name="rowWrapPolicy">
- <enum>QFormLayout::WrapLongRows</enum>
- </property>
- <item row="1" column="0" colspan="2">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Interpretable Modules:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0" colspan="2">
- <widget class="QTreeWidget" name="interpretableTreeWidget">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="acceptDrops">
- <bool>false</bool>
- </property>
- <property name="alternatingRowColors">
- <bool>false</bool>
- </property>
- <attribute name="headerVisible">
- <bool>true</bool>
- </attribute>
- <attribute name="headerVisible">
- <bool>true</bool>
- </attribute>
- <column>
- <property name="text">
- <string>Module</string>
- </property>
- </column>
- </widget>
- </item>
- <item row="3" column="0" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <property name="sizeConstraint">
- <enum>QLayout::SetMaximumSize</enum>
- </property>
- <property name="leftMargin">
- <number>0</number>
- </property>
- <property name="topMargin">
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="label_3">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="layoutDirection">
- <enum>Qt::LeftToRight</enum>
- </property>
- <property name="text">
- <string>Library include directories:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignCenter</set>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Expanding</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>100</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QToolButton" name="toolButton_2">
- <property name="text">
- <string>...</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="4" column="0" colspan="2">
- <widget class="QListWidget" name="includeLibraryListWidget"/>
- </item>
- <item row="0" column="1">
- <widget class="QGroupBox" name="groupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="title">
- <string>Entry Point</string>
- </property>
- <layout class="QFormLayout" name="formLayout_3">
- <item row="0" column="0" colspan="2">
- <layout class="QFormLayout" name="formLayout_2">
- <item row="0" column="0">
- <widget class="QLabel" name="moduleNameLabel">
- <property name="text">
- <string>Module name:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="moduleNameLineEdit"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="moduleFunctionLabel">
- <property name="text">
- <string>Module function:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QLineEdit" name="moduleFunctionLineEdit"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="functionArgumentsLabel">
- <property name="text">
- <string>Function Arguments</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLineEdit" name="functionArgumentsLineEdit"/>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/variable.h (nonexistent)
@@ -1,58 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef ERLANGVARIABLE_H
-#define ERLANGVARIABLE_H
-
-#include <QtCore/QMap>
-
-#include <debugger/variable/variablecollection.h>
-
-
-namespace ErlangDebugPlugin
-{
-class VariableListOutput;
-class VariableListCallback;
-
-class Variable : public KDevelop::Variable
-{
-public:
- Variable(KDevelop::TreeModel* model, KDevelop::TreeItem* parent,
- const QString& expression,
- const QString& display = "");
-
- ~Variable();
-public: // Variable overrides
- virtual void attachMaybe(QObject *callback = 0, const char *callbackMethod = 0);
- virtual void fetchMoreChildren();
- QString fullName() const;
- bool handleProperty(QDomNode variable);
-
-private: // Internal
- friend class VariableListCallback;
- QString m_fullName;
-
- QObject* m_callback;
- const char* m_callbackMethod;
- unsigned int m_iter;
-};
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/debugsession.cpp (nonexistent)
@@ -1,276 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "debugsession.h"
-
-#include "debugger.h"
-#include "messages.h"
-#include "breakpointcontroller.h"
-#include "variablecontroller.h"
-#include "framestackmodel.h"
-
-#include <kdebug.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/iplugincontroller.h>
-#include <execute/iexecuteplugin.h>
-#include <QFileInfo>
-
-namespace ErlangDebugPlugin
-{
-
-KDevelop::IFrameStackModel* DebugSession::createFrameStackModel()
-{
- return new FrameStackModel(this);
-}
-
-void DebugSession::requestVariables(ErlangDebugPlugin::DebugCallbackBase* callback)
-{
- m_callbacks.insert(m_requestID++, callback);
- m_commands.enqueue(new VariablesInContextCommand(m_processToMeta[m_currentProcess]));
- executeCmd();
-}
-
-void DebugSession::removeBreakpoint(QString module, int line)
-{
- m_commands.enqueue(new RemoveBreakpoint(module,line));
- executeCmd();
-}
-
-void DebugSession::interpretMoule(QString module)
-{
- if (!m_interpretedModules.contains(module))
- {
- m_interpretedModules.append(module);
- m_commands.enqueue(new InterpretModuleCommand(module));
- executeCmd();
- }
-}
-
-void DebugSession::spawn(QString module, QString function, QString arguments)
-{
- m_commands.enqueue(new SpawnFunctionCommand(module,function, arguments));
- executeCmd();
-}
-
-void DebugSession::startDebugger(KDevelop::ILaunchConfiguration* config)
-{
- IExecutePlugin* iface = KDevelop::ICore::self()->pluginController()->pluginForExtension("org.kdevelop.IExecutePlugin")->extension<IExecutePlugin>();
- Q_ASSERT(iface);
-
- // Only dummy err here, actual erros have been checked already in the job and we don't get here if there were any
- QString err;
- QString executable = iface->executable(config, err).toLocalFile();
- QString envgrp = iface->environmentGroup(config);
-
- QStringList arguments = iface->arguments(config, err);
- // Change the "Working directory" to the correct one
- QString dir = iface->workingDirectory(config).toLocalFile();
- if (dir.isEmpty() || !KUrl(dir).isValid())
- {
- dir = QFileInfo(executable).absolutePath();
- }
-
- kDebug() << "current directory is: " << dir;
-
- m_erlDebugger = new ErlangDebugger();
-
- connect(m_erlDebugger, SIGNAL(outputCommand(ErlangOutput*)), this, SLOT(handleDebuggerCommand(ErlangOutput*)));
- connect(m_erlDebugger, SIGNAL(stdoutReceived(QString)), this, SIGNAL(stdoutReceived(QString)));
-
- m_erlDebugger->start(dir, config->config());
-
- stateChanged(KDevelop::IDebugSession::StartingState);
-
- QStringList to_be_interpreted = config->config().readEntry(interpretedModules,QStringList());
-
- kDebug() << "interpreted modules: " << to_be_interpreted;
-
- foreach(QString module, to_be_interpreted)
- {
- interpretMoule(module);
- }
-
- QString module = config->config().readEntry(callableModule,"");
- QString function = config->config().readEntry(callableFunction,"");
- QString functionArguments = config->config().readEntry(callableArguments,"");
-
- spawn(module, function, functionArguments);
-}
-
-void DebugSession::stepOut()
-{
- m_commands.enqueue(new FinishCommand(m_processToMeta[m_currentProcess]));
- executeCmd();
-}
-
-void DebugSession::updateCurrentActiveProcess(QString processID)
-{
- m_currentProcess = processID;
-}
-
-void DebugSession::stepOverInstruction()
-{
-}
-
-DebugSession::DebugSession() : m_requestID(0)
-{
- m_breakpointController = new ErlangBreakpointController(this);
- m_variableController = new VariableController(this);
-}
-
-void DebugSession::sendBreakpoint(QString location, int line)
-{
- if (!m_interpretedModules.contains(location))
- {
- m_commands.enqueue(new InterpretModuleCommand(location));
- m_interpretedModules.append(location);
- executeCmd();
- }
-
- m_commands.enqueue(new BreakCommand(location, line));
- executeCmd();
-}
-
-void DebugSession::stepInto()
-{
- m_commands.enqueue(new StepCommand(m_processToMeta[m_currentProcess]));
- executeCmd();
-}
-
-void DebugSession::stepIntoInstruction()
-{
-
-}
-
-void DebugSession::stepOver()
-{
- m_commands.enqueue(new NextCommand(m_processToMeta[m_currentProcess]));
- executeCmd();
-}
-
-void DebugSession::jumpToCursor()
-{
-
-}
-
-void DebugSession::runToCursor()
-{
-
-}
-
-void DebugSession::run()
-{
- m_commands.enqueue(new ContinueCommand(m_processToMeta[m_currentProcess]));
- executeCmd();
-}
-
-void DebugSession::interruptDebugger()
-{
-
-}
-
-void DebugSession::stopDebugger()
-{
- if (m_erlDebugger)
- {
- m_erlDebugger->stop();
- delete m_erlDebugger;
- }
-
- emit stateChanged(KDevelop::IDebugSession::EndedState);
-}
-
-void DebugSession::restartDebugger()
-{
-
-}
-
-bool DebugSession::restartAvaliable() const
-{
- return false;
-}
-
-KDevelop::IDebugSession::DebuggerState DebugSession::state() const
-{
- return KDevelop::IDebugSession::ActiveState;
-}
-
-void DebugSession::executeCmd()
-{
- m_erlDebugger->execute(m_commands.dequeue());
-}
-
-void DebugSession::handleDebuggerCommand(ErlangOutput* command)
-{
- switch (command->getCommandType())
- {
- case BreakpointOutputType:
- {
- BreakpointOutput* i_cmd = static_cast<BreakpointOutput*>(command);
-
- m_currentProcess = i_cmd->getProcess();
-
- emit breakpointUpdate(i_cmd);
- emit showStepInSource(KUrl::fromPath(i_cmd->getModule()), i_cmd->getLine() - 1);
-
- stateChanged(KDevelop::IDebugSession::PausedState);
- raiseEvent(program_state_changed);
- }
- break;
- case MetaOutputType:
- {
- MetaProcessOutput* i_cmd = static_cast<MetaProcessOutput*>(command);
- m_processToMeta[i_cmd->getProcess()] = i_cmd->getMeta();
- }
- break;
- case ProcessStatusUpdateType:
- {
- ProcessStatusUpdateOutput* i_cmd = static_cast<ProcessStatusUpdateOutput*>(command);
- if (i_cmd->getProcessStatus() == ErlangProcessStatus::Running)
- {
- emit stateChanged(KDevelop::IDebugSession::ActiveState);
- raiseEvent(program_state_changed);
- }
- }
- break;
- case VariableListOutputType:
- {
- VariableListOutput* i_cmd = static_cast<VariableListOutput*>(command);
-
- foreach(DebugCallbackBase* callback, m_callbacks)
- {
- callback->execute(*command);
- }
-
- m_callbacks.clear();
-
- emit variableListUpdate(i_cmd);
- }
- break;
- case StackTraceOutputType:
- {
- StackTraceOutput* i_cmd = static_cast<StackTraceOutput*>(command);
- emit stackTraceUpdate(i_cmd);
- }
- }
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/debug/messages.cpp (nonexistent)
@@ -1,259 +0,0 @@
-/*
- Erlang Debugger support for KDevelop
- Copyright (C) 2010 Victor Vicente de Carvalho
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "messages.h"
-#include "kdebug.h"
-#include <QXmlReader>
-#include <QString>
-
-namespace ErlangDebugPlugin
-{
-
-ErlangOutput::ErlangOutput(const QStringList& rawData, ErlangDebugPlugin::OutputCommandType command)
- : m_rawData(rawData)
- , m_command(command)
-{
-}
-
-OutputCommandType ErlangOutput::getCommandType()
-{
- return m_command;
-}
-
-ErlangOutput::~ErlangOutput()
-{
-}
-
-void BreakpointOutput::parse()
-{
-}
-
-QString BreakpointOutput::getProcess()
-{
- return m_rawData[3];
-}
-
-int BreakpointOutput::getLine()
-{
- return m_rawData[2].toInt();
-}
-
-QString BreakpointOutput::getModule()
-{
- return m_rawData[1];
-}
-
-ErlangCommand::ErlangCommand(QString meta, InterpreterCommand::InterpreterCommand command)
- : m_meta(meta)
-,m_command(command)
-{
-}
-
-QString MetaProcessOutput::getMeta()
-{
- return m_rawData[2];
-}
-
-QString MetaProcessOutput::getProcess()
-{
- return m_rawData[1];
-}
-
-void MetaProcessOutput::parse()
-{
-}
-
-ErlangCommand::~ErlangCommand()
-{
-}
-
-StepCommand::StepCommand(QString meta): ErlangCommand(meta, InterpreterCommand::STEP)
-{
-}
-
-QString StepCommand::getCommand()
-{
- return QString("{ action, step , \"%1\" }.").arg(m_meta);
-}
-
-ContinueCommand::ContinueCommand(QString meta) :
- ErlangCommand(meta, InterpreterCommand::CONTINUE)
-{
-}
-
-QString ContinueCommand::getCommand()
-{
- return QString("{ action, continue , \"%1\" }.").arg(m_meta);
-}
-
-QString ProcessStatusUpdateOutput::getProcess()
-{
- return m_rawData[1];
-}
-
-QString ProcessStatusUpdateOutput::getProcessAdditionalInfo()
-{
- return m_rawData[3];
-}
-
-ErlangProcessStatus::status ProcessStatusUpdateOutput::getProcessStatus()
-{
- if (m_rawData[2] == "running")
- return ErlangProcessStatus::Running;
- else if (m_rawData[2] == "exit")
- return ErlangProcessStatus::Exit;
- else
- return ErlangProcessStatus::Idle;
-}
-
-void ProcessStatusUpdateOutput::parse()
-{
-}
-
-QList< StackInfo >& StackTraceOutput::getStackTrace()
-{
- return m_stackTrace;
-}
-
-void StackTraceOutput::parse()
-{
- m_process = m_rawData[1];
-
- QStringList frames = m_rawData[2].trimmed().split(" ");
-
- foreach(QString frame, frames)
- {
- QStringList frame_itens = frame.split(",");
- StackInfo info;
-
- info.stack_pos = frame_itens[0].toInt();
- info.function_name = frame_itens[1];
- info.filename = frame_itens[2];
- info.line = frame_itens[3].toInt() - 1;
-
- m_stackTrace.append(info);
- }
-}
-
-QString& StackTraceOutput::getProcess()
-{
- return m_process;
-}
-
-BreakCommand::BreakCommand(QString module, unsigned int line):
- ErlangCommand("", InterpreterCommand::BREAK)
- ,m_module(module)
- ,m_line(line)
-{
-}
-
-NextCommand::NextCommand(QString meta):
- ErlangCommand(meta, InterpreterCommand::NEXT)
-{
-}
-
-QString NextCommand::getCommand()
-{
- return QString("{ action, next, \"%1\" }.").arg(m_meta);
-}
-
-QString BreakCommand::getCommand()
-{
- return QString("{ break, %1, %2 }.").arg(m_module).arg(m_line);
-}
-
-
-QDomDocument& VariableListOutput::getDocument()
-{
- return m_document;
-}
-
-void VariableListOutput::parse()
-{
- QString errorMsg;
- int errorLine;
- int errorColumn;
-
- if (!m_document.setContent(m_rawData[1], &errorMsg, &errorLine, &errorColumn))
- {
- kError() << "Error parsing variables list on line " << errorLine << " and column " << errorColumn << ": " << errorMsg;
- }
-
- //kDebug() << m_document.toString(2);
-}
-
-FinishCommand::FinishCommand(QString meta):
- ErlangCommand(meta, InterpreterCommand::FINISH)
-{
-}
-
-QString FinishCommand::getCommand()
-{
- return QString("{ action, finish, \"%1\" }.").arg(m_meta);
-}
-
-QString InterpretModuleCommand::getCommand()
-{
- return QString("{ interpret, %1 }.").arg(m_module);
-}
-
-InterpretModuleCommand::InterpretModuleCommand(QString moduleName)
- : ErlangCommand("", InterpreterCommand::INTERPRET)
- , m_module(moduleName)
-{
-}
-
-QString VariablesInContextCommand::getCommand()
-{
- return QString("{ var_list, \"%1\" }.").arg(m_meta);
-}
-
-VariablesInContextCommand::VariablesInContextCommand(QString meta)
- : ErlangCommand("",InterpreterCommand::VARIABLE_LIST) , m_meta(meta)
-{
-}
-
-SpawnFunctionCommand::SpawnFunctionCommand(QString module, QString function, QString parameters)
- : ErlangCommand("", InterpreterCommand::SPAWN_FUNCTION)
- , m_module(module)
- , m_function(function)
- , m_parameters(parameters)
-{
-}
-
-QString SpawnFunctionCommand::getCommand()
-{
- return QString("{ launch , { %1 , %2, [ %3 ] } }.").arg(m_module).arg(m_function).arg(m_parameters);
-}
-
-QString RemoveBreakpoint::getCommand()
-{
- return QString("{ break_remove, %1 , %2 }.").arg(m_module).arg(m_line);
-}
-
-RemoveBreakpoint::RemoveBreakpoint(QString module, unsigned int line)
-: ErlangCommand("", InterpreterCommand::REMOVE_BREAKPOINT),
- m_module(module),
- m_line(line)
-{
-}
-
-
-}
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.cpp (nonexistent)
@@ -1,49 +0,0 @@
-/*
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#include "duchain.h"
-
-#include <QtTest/QtTest>
-
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/declaration.h>
-
-QTEST_MAIN(erlang::TestDUChain)
-
-namespace erlang
-{
-
-void TestDUChain::testDuchain()
-{
- // 012345678901234
- QByteArray function("myfunc() -> ok.");
-
- KDevelop::TopDUContext* top = parse(function, DumpAll);
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
-
- QCOMPARE(top->childContexts().count(), 1);
- KDevelop::DUContext *dec = top->childContexts().at(0);
- QVERIFY(top->childContexts().first()->range() == KDevelop::SimpleRange(0, 0, 0, 5));
-}
-
-}
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.cpp (nonexistent)
@@ -1,96 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Hamish Rodda <rodda@kde.org>
- Copyright 2008 Niko Sams <niko.sams@gmail.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "duchaintestbase.h"
-
-#include <QtTest/QtTest>
-
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/indexedstring.h>
-#include <kstandarddirs.h>
-#include <kcomponentdata.h>
-
-#include "../../parser/parsesession.h"
-#include "../builders/declarationbuilder.h"
-
-namespace erlang
-{
-
-DUChainTestBase::DUChainTestBase()
-{
- KComponentData kd("kdeverlangsupport");
-}
-
-void DUChainTestBase::initTestCase()
-{
- KDevelop::DUChain::self()->disablePersistentStorage();
-}
-
-KDevelop::TopDUContext* DUChainTestBase::parse(const QByteArray& unit, DumpAreas dump, QString url)
-{
- if (dump)
- kDebug() << "==== Beginning new test case...:" << endl << unit;
-
- ParseSession* session = new ParseSession();
- session->setContents(unit);
- FormAst* ast = 0;
- if (!session->parse(&ast)) {
- kDebug() << "Parse failed:";
- foreach(KDevelop::ProblemPointer p, session->problems())
- {
- kDebug() << p;
- }
-
- return 0;
- }
-
- if (dump & DumpAST) {
- kDebug() << "===== AST:";
- //DebugVisitor debugVisitor(session->tokenStream(), session->contents());
- //debugVisitor.visitNode(ast);
- }
-
- static int testNumber = 0;
- if (url.isEmpty()) url = QString("file:///internal/%1").arg(testNumber++);
-
- EditorIntegrator editor;
- editor.setParseSession(session);
- DeclarationBuilder builder(&editor);
- KDevelop::TopDUContext* top = builder.build(KDevelop::IndexedString(url), ast);
-
- if (dump & DumpDUChain) {
- kDebug() << "===== DUChain:";
-
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
- dumper.dump(top);
- }
-
- if (dump)
- kDebug() << "===== Finished test case.";
-
- delete session;
-
- return top;
-}
-}
-
-#include "duchaintestbase.moc"
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchain.h (nonexistent)
@@ -1,38 +0,0 @@
-/*
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-*/
-
-#ifndef TESTERLANGDUCHAIN_H
-#define TESTERLANGDUCHAIN_H
-
-#include "duchaintestbase.h"
-
-namespace erlang
-{
-
-class TestDUChain : public DUChainTestBase
-{
- Q_OBJECT
-
-private slots:
- void testDuchain();
-};
-
-}
-#endif // TESTERLANGDUCHAIN_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/tests/duchaintestbase.h (nonexistent)
@@ -1,77 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Hamish Rodda <rodda@kde.org>
- Copyright 2008,2010 Niko Sams <niko.sams@gmail.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef DUCHAINTESTBASE_H
-#define DUCHAINTESTBASE_H
-
-#include <QObject>
-#include <QByteArray>
-#include <QTest>
-#include <language/duchain/dumpchain.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-
-namespace KDevelop
-{
-class TopDUContext;
-}
-
-namespace erlang
-{
-/**
- * Manage pointer to TopDUContexts and release them properly, even if a test fails
- */
-struct DUChainReleaser {
- DUChainReleaser(KDevelop::TopDUContext* top) : m_top(top) {}
- ~DUChainReleaser() {
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
- KDevelop::DUChain::self()->removeDocumentChain(m_top);
- }
- KDevelop::TopDUContext* m_top;
-};
-
-class DUChainTestBase : public QObject
-{
- Q_OBJECT
-
-public:
- DUChainTestBase();
-
-public:
- enum DumpArea {
- DumpNone = 0,
- DumpAST = 1,
- DumpDUChain = 2,
- DumpAll = 3
- };
- Q_DECLARE_FLAGS(DumpAreas, DumpArea)
-
-public slots:
- void initTestCase();
-
-protected:
- KDevelop::TopDUContext* parse(const QByteArray& unit, DumpAreas dump = static_cast<DumpAreas>(DumpAST | DumpDUChain), QString fileName = QString());
-
- KDevelop::DumpChain dumper;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(DUChainTestBase::DumpAreas)
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.cpp (nonexistent)
@@ -1,146 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "contextbuilder.h"
-
-
-
-#include <language/duchain/duchain.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/classdeclaration.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/ilanguagecontroller.h>
-#include <interfaces/icompletionsettings.h>
-
-#include <klocalizedstring.h>
-
-#include "../../parser/parsesession.h"
-#include "../../parser/editorintegrator.h"
-#include "erlangast.h"
-
-namespace erlang
-{
-
-ContextBuilder::ContextBuilder() : m_reportErrors(true)
-{
-}
-
-ContextBuilder::~ContextBuilder()
-{
-}
-
-KDevelop::QualifiedIdentifier ContextBuilder::identifierForNode(erlang::AstNode* id)
-{
- Atom1Ast* atom = 0;
- VariableAst* variable = 0;
- if (( atom = dynamic_cast<Atom1Ast*>(id)) != 0)
- {
- return KDevelop::QualifiedIdentifier(editor()->parseSession()->symbol(atom->literal));
- }
- else if ((variable = dynamic_cast<VariableAst*>(id)) != 0)
- {
- return KDevelop::QualifiedIdentifier(editor()->parseSession()->symbol(variable->literal));
- }
- else
- {
- return KDevelop::QualifiedIdentifier();
- }
-}
-
-KDevelop::ReferencedTopDUContext ContextBuilder::build(const KDevelop::IndexedString& url, AstNode* node,
- KDevelop::ReferencedTopDUContext updateContext, bool useSmart)
-{
- if ( KDevelop::ICore::self() ) {
- m_reportErrors = KDevelop::ICore::self()->languageController()->completionSettings()->highlightSemanticProblems();
- }
- return ContextBuilderBase::build(url, node, updateContext, useSmart);
-}
-
-void ContextBuilder::setEditor(EditorIntegrator* editor)
-{
- ContextBuilderBase::setEditor(editor, false);
-}
-
-KDevelop::TopDUContext* ContextBuilder::newTopContext(const KDevelop::SimpleRange& range, KDevelop::ParsingEnvironmentFile* file)
-{
- if (!file) {
- file = new KDevelop::ParsingEnvironmentFile(editor()->currentUrl());
- file->setLanguage(KDevelop::IndexedString("Erlang"));
- }
- return new KDevelop::TopDUContext(editor()->currentUrl(), range, file);
-}
-
-void ContextBuilder::setContextOnNode(AstNode* node, KDevelop::DUContext* ctx)
-{
- if (node)
- {
- node->ducontext = ctx;
- }
-}
-
-KDevelop::DUContext* ContextBuilder::contextFromNode(erlang::AstNode* node)
-{
- if (node)
- {
- return node->ducontext;
- }
-
- return NULL;
-}
-
-EditorIntegrator* ContextBuilder::editor() const
-{
- return static_cast<EditorIntegrator*>(ContextBuilderBase::editor());
-}
-
-KTextEditor::Range ContextBuilder::editorFindRange(AstNode* fromRange, AstNode* toRange)
-{
- return editor()->findRange(fromRange, toRange).textRange();
-}
-
-KDevelop::SimpleCursor ContextBuilder::startPos(AstNode* node)
-{
- return editor()->findPosition(node->startToken, KDevelop::EditorIntegrator::FrontEdge);
-}
-
-void ContextBuilder::startVisiting(AstNode* node)
-{
- visitNode(node);
-}
-
-void ContextBuilder::visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node)
-{
- if (node->function_name)
- {
- openContext(node, editorFindRange(node, node), KDevelop::DUContext::Function, node->function_name);
- DefaultVisitor::visitFunctionOrRuleClause(node);
- closeContext();
- }
- else
- {
- DefaultVisitor::visitFunctionOrRuleClause(node);
- }
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/contextbuilder.h (nonexistent)
@@ -1,68 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef CONTEXTBUILDER_H
-#define CONTEXTBUILDER_H
-
-#include "erlangdefaultvisitor.h"
-#include <language/duchain/builders/abstractcontextbuilder.h>
-#include <parser/editorintegrator.h>
-
-namespace erlang
-{
-class EditorIntegrator;
-class ParseSession;
-
-typedef KDevelop::AbstractContextBuilder<AstNode, AstNode> ContextBuilderBase;
-
-class ContextBuilder : public ContextBuilderBase, public DefaultVisitor
-{
- public:
-
- ContextBuilder();
- virtual ~ContextBuilder();
-
- void setEditor(EditorIntegrator* editor);
- virtual KDevelop::ReferencedTopDUContext build(const KDevelop::IndexedString& url, AstNode* node,
- KDevelop::ReferencedTopDUContext updateContext
- = KDevelop::ReferencedTopDUContext(), bool useSmart = true);
-
- protected:
- EditorIntegrator* editor() const;
- virtual void visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node);
- void startVisiting(AstNode* node);
-
- virtual KDevelop::QualifiedIdentifier identifierForNode(AstNode* id);
-
- virtual KDevelop::TopDUContext* newTopContext(const KDevelop::SimpleRange& range, KDevelop::ParsingEnvironmentFile* file = 0);
-
- virtual void setContextOnNode(AstNode* node, KDevelop::DUContext* ctx);
- virtual KDevelop::DUContext* contextFromNode(AstNode* node);
- virtual KTextEditor::Range editorFindRange(AstNode* fromRange, AstNode* toRange);
- /// Find Cursor for start of a node, useful to limit findLocalDeclarations() searches.
- KDevelop::SimpleCursor startPos(AstNode* node);
-
- /// Whether semantic problems should get reported
- bool m_reportErrors;
-};
-
-}
-#endif // CONTEXTBUILDER_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.cpp (nonexistent)
@@ -1,78 +0,0 @@
-/*
-* This file is part of KDevelop
-*
-* Copyright 2010 Victor Vicente de Carvalho
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-#include "typebuilder.h"
-
-#include <language/duchain/types/functiontype.h>
-#include "../types/objecttype.h"
-
-namespace erlang {
-
-TypeBuilder::TypeBuilder(): TypeBuilderBase()
-{
-}
-
-
-void TypeBuilder::visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node)
-{
- KDevelop::FunctionType::Ptr functionType = KDevelop::FunctionType::Ptr(new KDevelop::FunctionType());
- openType(functionType);
- KDevelop::AbstractType::Ptr returnType(new ObjectType());
- functionType->setReturnType(returnType);
-
- TypeBuilderBase::visitFunctionOrRuleClause(node);
-
- updateCurrentType();
- closeType();
-
-}
-
-void TypeBuilder::visitArgExprs(ArgExprsAst* node)
-{
- if (hasCurrentType())
- {
- KDevelop::DelayedType::Ptr type(new KDevelop::DelayedType());
- QString id = editor()->parseSession()->symbol(node);
-
-
- //We have to prevent automatic parsing and splitting by QualifiedIdentifier and Identifier
- KDevelop::Identifier idd;
- idd.setIdentifier(id);
-
- KDevelop::QualifiedIdentifier ident;
- ident.push(idd);
-
- type->setIdentifier( KDevelop::IndexedTypeIdentifier(ident) );
-
- openType<KDevelop::DelayedType>(type);
- closeType();
-
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
- TypePtr<KDevelop::FunctionType> ctype = currentType<KDevelop::FunctionType>();
- ctype->addArgument(TypePtr<KDevelop::AbstractType>::staticCast(type));
- }
-}
-
-void TypeBuilder::updateCurrentType()
-{
- //reimplemented in DeclarationBuilder
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/typebuilder.h (nonexistent)
@@ -1,44 +0,0 @@
-/*
-* This file is part of KDevelop
-*
-* Copyright 2010 Victor Vicente de Carvalho
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-#ifndef TYPEBUILDER_H
-#define TYPEBUILDER_H
-
-#include "contextbuilder.h"
-
-#include <language/duchain/builders/abstracttypebuilder.h>
-
-namespace erlang {
-
-typedef KDevelop::AbstractTypeBuilder<AstNode, AstNode, ContextBuilder> TypeBuilderBase;
-
-class TypeBuilder: public TypeBuilderBase {
-public:
- TypeBuilder();
-
-protected:
- virtual void visitFunctionOrRuleClause(FunctionOrRuleClauseAst* node);
- virtual void visitArgExprs(ArgExprsAst* node);
- virtual void updateCurrentType();
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.cpp (nonexistent)
@@ -1,85 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "declarationbuilder.h"
-
-#include <interfaces/icore.h>
-#include <language/duchain/functiondeclaration.h>
-
-#include "erlangast.h"
-#include "../../parser/parsesession.h"
-#include "../../parser/editorintegrator.h"
-#include "../declarations/functiondeclaration.h"
-#include "../declarations/variabledeclaration.h"
-
-using namespace KTextEditor;
-using namespace KDevelop;
-namespace erlang
-{
-DeclarationBuilder::DeclarationBuilder(EditorIntegrator* editor)
-{
- setEditor(editor);
-}
-
-DeclarationBuilder::DeclarationBuilder()
-{
-}
-
-void DeclarationBuilder::visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node)
-{
- if (node->function_name)
- {
- FunctionDeclaration* func = openDeclaration<FunctionDeclaration>(node->function_name, node->body);
- func->setDeclarationIsDefinition(true);
- func->setKind(KDevelop::Declaration::Type);
-
- DeclarationBuilderBase::visitFunctionOrRuleClause(node);
- closeDeclaration();
- }
- else
- {
- DeclarationBuilderBase::visitFunctionOrRuleClause(node);
- }
-}
-
-void DeclarationBuilder::visitExprMax(ExprMaxAst* node)
-{
- if (node->var)
- {
- SimpleRange range = editorFindRange(node->var, node->var);
- VariableDeclaration *dec = openDeclaration<VariableDeclaration>(identifierForNode(node->var), range);
- dec->setKind(Declaration::Instance);
- eventuallyAssignInternalContext();
- closeDeclaration();
- }
- else
- {
- DeclarationBuilderBase::visitExprMax(node);
- }
-}
-
-void DeclarationBuilder::updateCurrentType()
-{
- KDevelop::DUChainWriteLocker lock(KDevelop::DUChain::lock());
- currentDeclaration()->setAbstractType(currentAbstractType());
-}
-
-
-}
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/builders/declarationbuilder.h (nonexistent)
@@ -1,59 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2010 Victor Vicente de Carvalho *
- * <victor.v.carvalho@gmail.com> *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef DECLARATIONBUILDER_H
-#define DECLARATIONBUILDER_H
-
-#include "contextbuilder.h"
-#include <language/duchain/builders/abstractdeclarationbuilder.h>
-#include <erlangast.h>
-#include <language/duchain/builders/abstractdeclarationbuilder.h>
-#include "typebuilder.h"
-
-namespace KDvelop
-{
-class Declaration;
-}
-namespace erlang
-{
-class ParseSession;
-class EditorIntegrator;
-class ClassDeclaration;
-class FunctionDeclaration;
-
-typedef KDevelop::AbstractDeclarationBuilder<AstNode, AstNode, TypeBuilder > DeclarationBuilderBase;
-
-class DeclarationBuilder : public DeclarationBuilderBase
-{
-public:
- DeclarationBuilder(EditorIntegrator* editor);
- DeclarationBuilder();
-
-protected:
- virtual void visitExprMax(ExprMaxAst* node);
- virtual void visitFunctionOrRuleClause(erlang::FunctionOrRuleClauseAst* node);
-
- virtual void updateCurrentType();
-};
-
-}
-
-#endif // DECLARATIONBUILDER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.cpp (nonexistent)
@@ -1,89 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Milian Wolff <mail@milianw.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "functiondeclaration.h"
-
-#include <language/duchain/duchainregister.h>
-#include <language/duchain/types/functiontype.h>
-
-namespace erlang {
-REGISTER_DUCHAIN_ITEM(FunctionDeclaration);
-
-FunctionDeclaration::FunctionDeclaration(const FunctionDeclaration& rhs)
- : KDevelop::FunctionDeclaration(*new FunctionDeclarationData(*rhs.d_func()))
-{
- setSmartRange(rhs.smartRange(), DocumentRangeObject::DontOwn);
-}
-
-FunctionDeclaration::FunctionDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
- : KDevelop::FunctionDeclaration(*new FunctionDeclarationData, range)
-{
- d_func_dynamic()->setClassId(this);
- if (context) {
- setContext(context);
- }
-}
-
-FunctionDeclaration::FunctionDeclaration(FunctionDeclarationData& data)
- : KDevelop::FunctionDeclaration(data)
-{
-}
-
-FunctionDeclaration::FunctionDeclaration(FunctionDeclarationData& data, const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
- : KDevelop::FunctionDeclaration(data, range)
-{
- if (context) {
- setContext(context);
- }
-}
-
-FunctionDeclaration::~FunctionDeclaration()
-{
-}
-
-KDevelop::Declaration* FunctionDeclaration::clonePrivate() const
-{
- return new FunctionDeclaration(*this);
-}
-
-KDevelop::IndexedString FunctionDeclaration::prettyName() const
-{
- return d_func()->prettyName;
-}
-
-void FunctionDeclaration::setPrettyName( const KDevelop::IndexedString& name )
-{
- d_func_dynamic()->prettyName = name;
-}
-
-QString FunctionDeclaration::toString() const
-{
- if( !abstractType() )
- return Declaration::toString();
-
- TypePtr<KDevelop::FunctionType> function = type<KDevelop::FunctionType>();
- Q_ASSERT(function);
-
- return QString("%1 %2 %3").arg(function->partToString( KDevelop::FunctionType::SignatureReturn ))
- .arg(prettyName().str())
- .arg(function->partToString( KDevelop::FunctionType::SignatureArguments ));
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.h (nonexistent)
@@ -1,77 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef VARIABLEDECLARATION_H
-#define VARIABLEDECLARATION_H
-
-#include <language/duchain/declaration.h>
-#include <language/duchain/declarationdata.h>
-
-namespace erlang
-{
-
-class VariableDeclarationData : public KDevelop::DeclarationData
-{
-public:
- VariableDeclarationData()
- : KDevelop::DeclarationData(), m_isSuperglobal(false) {
- }
-
- VariableDeclarationData(const VariableDeclarationData& rhs)
- : KDevelop::DeclarationData(rhs) {
- m_isSuperglobal = rhs.m_isSuperglobal;
- }
-
- ~VariableDeclarationData() {
- }
-
-bool m_isSuperglobal;
-};
-
-/**
- * Declaration used for Php variables eg. $a = 0;
- */
-class VariableDeclaration : public KDevelop::Declaration
-{
-public:
- VariableDeclaration(const VariableDeclaration& rhs);
- VariableDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context);
- VariableDeclaration(VariableDeclarationData& data);
- VariableDeclaration(VariableDeclarationData& data, const KDevelop::SimpleRange&);
- virtual ~VariableDeclaration();
-
- bool isSuperglobal() const;
- void setSuperglobal(bool superglobal);
-
- virtual uint additionalIdentity() const;
- virtual KDevelop::DeclarationId id(bool forceDirect = false) const;
-
- enum {
- Identity = 83
- };
- typedef KDevelop::Declaration Base;
-
-private:
- DUCHAIN_DECLARE_DATA(VariableDeclaration)
-};
-
-}
-
-#endif // VARIABLEDECLARATION_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/functiondeclaration.h (nonexistent)
@@ -1,76 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Milian Wolff <mail@milianw.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef ERLANG_FUNCTIONDECLARATION_H
-#define ERLANG_FUNCTIONDECLARATION_H
-
-#include <language/duchain/functiondeclaration.h>
-
-#include <language/duchain/declaration.h>
-#include <language/duchain/declarationdata.h>
-#include <language/duchain/indexedstring.h>
-
-
-namespace erlang
-{
-
-class FunctionDeclarationData : public KDevelop::FunctionDeclarationData
-{
-public:
- FunctionDeclarationData()
- : KDevelop::FunctionDeclarationData() {}
-
- FunctionDeclarationData(const FunctionDeclarationData& rhs)
- : KDevelop::FunctionDeclarationData(rhs)
- {
- prettyName = rhs.prettyName;
- }
-
- ~FunctionDeclarationData() {}
-
- KDevelop::IndexedString prettyName;
-};
-
-class FunctionDeclaration : public KDevelop::FunctionDeclaration
-{
-public:
- FunctionDeclaration(const FunctionDeclaration &rhs);
- FunctionDeclaration(const KDevelop::SimpleRange &range, KDevelop::DUContext *context);
- FunctionDeclaration(FunctionDeclarationData &data);
- FunctionDeclaration(FunctionDeclarationData &data, const KDevelop::SimpleRange &range, KDevelop::DUContext *context);
- ~FunctionDeclaration();
-
- virtual QString toString() const;
-
- void setPrettyName(const KDevelop::IndexedString& name);
- KDevelop::IndexedString prettyName() const;
-
- enum {
- Identity = 86
- };
-
- virtual KDevelop::Declaration* clonePrivate() const;
-private:
- DUCHAIN_DECLARE_DATA(FunctionDeclaration)
-};
-
-}
-
-#endif // PHP_FUNCTIONDECLARATION_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/declarations/variabledeclaration.cpp (nonexistent)
@@ -1,82 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Niko Sams <niko.sams@gmail.com> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "variabledeclaration.h"
-
-#include <language/duchain/ducontext.h>
-#include <language/duchain/duchainregister.h>
-
-using namespace KDevelop;
-namespace erlang
-{
-REGISTER_DUCHAIN_ITEM(VariableDeclaration);
-
-VariableDeclaration::VariableDeclaration(VariableDeclarationData& data) : KDevelop::Declaration(data)
-{
-}
-
-VariableDeclaration::VariableDeclaration(VariableDeclarationData& data, const KDevelop::SimpleRange& range)
- : KDevelop::Declaration(data, range)
-{
-}
-
-VariableDeclaration::VariableDeclaration(const VariableDeclaration& rhs)
- : KDevelop::Declaration(*new VariableDeclarationData(*rhs.d_func()))
-{
- setSmartRange(rhs.smartRange(), DocumentRangeObject::DontOwn);
-}
-
-VariableDeclaration::VariableDeclaration(const KDevelop::SimpleRange& range, KDevelop::DUContext* context)
- : KDevelop::Declaration(*new VariableDeclarationData, range)
-{
- d_func_dynamic()->setClassId(this);
- if (context)
- setContext(context);
-}
-VariableDeclaration::~VariableDeclaration()
-{
-}
-
-uint VariableDeclaration::additionalIdentity() const
-{
- return 2;
-}
-
-KDevelop::DeclarationId VariableDeclaration::id(bool forceDirect) const
-{
- Q_UNUSED(forceDirect);
- //always forceDirect, because there can exist multiple declarations with the
- //same identifier within one context, and uses wouldn't work correctly else
- return KDevelop::Declaration::id(true);
-}
-
-bool VariableDeclaration::isSuperglobal() const
-{
- DUCHAIN_D(VariableDeclaration);
- return d->m_isSuperglobal;
-}
-
-void VariableDeclaration::setSuperglobal(bool superglobal)
-{
- DUCHAIN_D_DYNAMIC(VariableDeclaration);
- d->m_isSuperglobal = superglobal;
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.cpp (nonexistent)
@@ -1,73 +0,0 @@
-/*
-* This file is part of KDevelop
-*
-* Copyright 2010 Victor Vicente de Carvalho
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-#include "objecttype.h"
-
-#include <language/duchain/types/typeregister.h>
-
-using namespace KDevelop;
-
-namespace erlang {
-
-REGISTER_TYPE(ObjectType);
-
-ObjectType::ObjectType()
- :KDevelop::StructureType(createData<ObjectType>())
-{
-}
-
-ObjectType::ObjectType(const ObjectType& rhs)
- :KDevelop::StructureType(copyData<ObjectType>(*rhs.d_func()))
-{
-}
-
-ObjectType::ObjectType(ObjectTypeData& data)
- :KDevelop::StructureType(data)
-{
-}
-
-KDevelop::AbstractType* ObjectType::clone() const
-{
- return new ObjectType(*this);
-}
-
-uint ObjectType::hash() const
-{
- return 8 * KDevelop::StructureType::hash();
-}
-
-QString ObjectType::toString() const
-{
- return d_func()->m_prettyName;
-}
-
-void ObjectType::setPrettyName(const QString& name)
-{
- d_func_dynamic()->setPrettyName(name);
-}
-
-void ObjectTypeData::setPrettyName(QString arg1)
-{
- m_prettyName = arg1;
-}
-
-
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/duchain/types/objecttype.h (nonexistent)
@@ -1,64 +0,0 @@
-/*
-* This file is part of KDevelop
-*
-* Copyright 2010 Victor Vicente de Carvalho
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-#ifndef OBJECTTYPE_H
-#define OBJECTTYPE_H
-
-#include <language/duchain/types/structuretype.h>
-
-namespace erlang {
-
-class ObjectTypeData: public KDevelop::StructureTypeData {
-public:
- ObjectTypeData(): KDevelop::StructureTypeData() { }
- ObjectTypeData(const ObjectTypeData& rhs): KDevelop::StructureTypeData(rhs) { }
- void setPrettyName(QString arg1);
- QString m_prettyName;
-};
-
-class ObjectType: public KDevelop::StructureType {
-public:
- typedef TypePtr<ObjectType> Ptr;
-
- /// Default constructor
- ObjectType();
- /// Copy constructor. \param rhs type to copy
- ObjectType(const ObjectType& rhs);
- /// Constructor using raw data. \param data internal data.
- ObjectType(ObjectTypeData& data);
-
- virtual AbstractType* clone() const;
- virtual QString toString() const;
- virtual uint hash() const;
- void setPrettyName(const QString& name);
- enum {
- Identity = 60
- };
-
- typedef ObjectTypeData Data;
- typedef KDevelop::StructureType BaseType;
-
-protected:
- TYPE_DECLARE_DATA(ObjectType);
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlang.kdev4
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlang.kdev4 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/erlang/erlang.kdev4 (nonexistent)
@@ -1,4 +0,0 @@
-[Project]
-Name=erlang
-Manager=KDevCMakeManager
-VersionControl=
Index: trunk/playground/devtools/kdevelop4-extra-plugins/foobar/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/foobar/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/foobar/CMakeLists.txt (nonexistent)
@@ -1,21 +0,0 @@
-project(KDevPreprocessor)
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
-)
-
-set(foobar_SRCS foobarplugin.cpp)
-
-kde4_add_plugin(kdevfoobar ${foobar_SRCS})
-
-target_link_libraries(kdevfoobar
- -lQtCore -lkdevplatforminterfaces
- -lkdevplatformutil -lkdevplatformlanguage -lkdecore -lkparts
- ${KDE4_KTEXTEDITOR_LIBS})
-
-install(TARGETS kdevfoobar DESTINATION ${PLUGIN_INSTALL_DIR})
-install(FILES kdevfoobar.desktop DESTINATION ${SERVICES_INSTALL_DIR})
-install(FILES kdevfoobar.rc DESTINATION ${DATA_INSTALL_DIR}/kdevfoobar)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.cpp (nonexistent)
@@ -1,126 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Foobar-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "foobarplugin.h"
-
-#include <KPluginFactory>
-#include <KPluginLoader>
-#include <KAboutData>
-#include <KDebug>
-#include <KActionCollection>
-#include <KAction>
-#include <KLocale>
-
-#include <kdevplatform/interfaces/icore.h>
-#include <kdevplatform/interfaces/idocument.h>
-#include <kdevplatform/interfaces/idocumentcontroller.h>
-#include <kdevplatform/language/duchain/duchain.h>
-#include <kdevplatform/language/duchain/ducontext.h>
-#include <kdevplatform/language/duchain/parsingenvironment.h>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-
-#include <QVector>
-
-K_PLUGIN_FACTORY (KdevPlugFactory, registerPlugin<KDevFoobarPlugin>();)
-K_EXPORT_PLUGIN (KdevPlugFactory (KAboutData ("kdevfoobar","kdevfoobar", ki18n ("Foo, Bar, Baz creation"), "0.1", ki18n ("Insert dummies according to RFC 3092"), KAboutData::License_GPL)))
-
-KDevFoobarPlugin::KDevFoobarPlugin (QObject *parent, const QVariantList &)
-:IPlugin (KdevPlugFactory::componentData(), parent)
-{
- setXMLFile ("kdevfoobar.rc");
-
- m_actionInsert = actionCollection()->addAction ("kdevfoobar_insertfoobar");
- m_actionInsert->setText (i18n ("Insert Foobar"));
- connect (m_actionInsert, SIGNAL (triggered (bool)), this, SLOT (insert()));
- m_actionInsert->setToolTip (i18n ("Insert the Current File"));
-}
-
-KDevFoobarPlugin::~KDevFoobarPlugin()
-{
-}
-
-#define NC(...) __VA_ARGS__
-
-static bool declExists(const QString& name)
-{
- foreach(NC(const ParsingEnvironmentFilePointer &env), NC(DUChain::self()->allEnvironmentFiles(IndexedString((ICore::self()->documentController()->activeDocument()->url())))))
- {
- TopDUContext* top = env->topContext();
- if(!top) continue;
- if(!top->findDeclarations(QualifiedIdentifier(name)).isEmpty())
- return true;
- }
- return false;
-}
-
-void KDevFoobarPlugin::insert()
-{
- static QString foos[] = {
- "foo", "bar", "baz", "qux", "quux", "corge", "grault",
- "garply", "waldo", "fred", "plugh", "xyzzy", "thud"
- };
- static const int size = 13;
- QString name;
- for(int num = 1; ; ++num)
- {
- QVector<int> vec(num, -1);
- int idx = 0;
- bool used[size] = {};
- while(idx != -1)
- {
- while(++vec[idx] != size)
- {
- kDebug() << num << idx << vec[idx];
- if(!used[vec[idx]])
- {
- used[vec[idx]] = true;
- ++idx;
- if(idx == num)
- {
- for(int i = 0; i != num; ++i)
- name += foos[vec[i]];
- kDebug() << "Check: " << name;
- if(!declExists(name))
- goto done;
- name = "";
- --idx;
- }
- else
- goto next;
- }
- }
- used[vec[idx]] = false;
- vec[idx] = -1;
- --idx;
- next:
- ;
- }
- if(num == size)
- {
- // fail, seems to be impossible, you'd need _a lot_ of usages :D
- Q_ASSERT(0);
- return;
- }
- }
- done:;
- KTextEditor::Document *d = ICore::self()->documentController()->activeDocument()->textDocument();
- d->insertText(d->activeView()->cursorPosition(), name);
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/foobar/foobarplugin.h (nonexistent)
@@ -1,50 +0,0 @@
-/***************************************************************************
- * This file is part of the KDevelop-Foobar-Plugin *
- * Copyright 2009-2010 Jonathan Schmidt-Dominé <devel@the-user.org> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 3 of *
- * the License or (at your option) any later version accepted. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef FOOBARPLUGIN_H
-#define FOOBARPLUGIN_H
-
-#include <interfaces/iplugin.h>
-
-#include <QVariantList>
-
-class KAction;
-
-using namespace KDevelop;
-
-namespace KDevelop
-{
- class Declaration;
- class DUContext;
- class ClassDeclaration ;
- class ClassMemberDeclaration ;
-}
-
-class KDevFoobarPlugin : public KDevelop::IPlugin
-{
- Q_OBJECT
- public:
- KDevFoobarPlugin (QObject *parent, const QVariantList & = QVariantList());
- ~KDevFoobarPlugin();
- private slots:
- void insert();
- private:
- KAction *m_actionInsert;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.rc (nonexistent)
@@ -1,6 +0,0 @@
-<!DOCTYPE kpartgui>
-<kpartplugin name="kdevfoobar" library="libkdevfoobar" version="1">
-<Menu name="ktexteditor_popup">
- <Action name="kdevfoobar_insertfoobar" group="popup_operations"/>
-</Menu>
-</kpartplugin>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/foobar/kdevfoobar.desktop (nonexistent)
@@ -1,67 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=Insert dummies according to RFC 3092
-Comment[bs]=Ubacite makete saglasno sa RFC 3092
-Comment[ca]=Insereix elements de simulació d'accord a la RFC 3092
-Comment[ca@valencia]=Insereix elements de simulació d'accord a la RFC 3092
-Comment[de]=Fügt Dummies nach RFC 3092 ein
-Comment[en_GB]=Insert dummies according to RFC 3092
-Comment[es]=Insertar términos que sigan la RFC 3092
-Comment[et]=Libade sisestamine vastavalt RFC 3092-le
-Comment[fr]=Insère des paramètres fictifs selon la RFC 3092
-Comment[gl]=Inserir datos de exemplo de acordo co RFC 3092.
-Comment[nl]=Voegt dummies volgens RFC 3092 toe
-Comment[pl]=Wstaw dummies według RFC 3092
-Comment[pt]=Insere valores de testes de acordo com o RFC 3092
-Comment[pt_BR]=Inserir valores fictícios de acordo com a RFC 3092
-Comment[sv]=Infoga platsmarkörer enligt RFC 3092
-Comment[uk]=Вставка тестових фрагментів відповідно до RFC 3092
-Comment[x-test]=xxInsert dummies according to RFC 3092xx
-Name=Foobar
-Name[bs]=Foobar
-Name[ca]=Foobar
-Name[ca@valencia]=Foobar
-Name[de]=Foobar
-Name[en_GB]=Foobar
-Name[es]=Foobar
-Name[et]=Foobar
-Name[fr]=Barre fictive
-Name[gl]=Foobar
-Name[nl]=Foobar
-Name[pl]=Foobar
-Name[pt]=XPTO
-Name[pt_BR]=Foobar
-Name[sk]=Foobar
-Name[sv]=Flärp
-Name[uk]=Щось там
-Name[x-test]=xxFoobarxx
-GenericName=Foobar
-GenericName[bs]=Foobar
-GenericName[ca]=Foobar
-GenericName[ca@valencia]=Foobar
-GenericName[de]=Foobar
-GenericName[en_GB]=Foobar
-GenericName[es]=Foobar
-GenericName[et]=Foobar
-GenericName[fr]=Barre fictive
-GenericName[gl]=Foobar
-GenericName[nl]=Foobar
-GenericName[pl]=Foobar
-GenericName[pt]=XPTO
-GenericName[pt_BR]=Foobar
-GenericName[sk]=Foobar
-GenericName[sv]=Flärp
-GenericName[uk]=Щось там
-GenericName[x-test]=xxFoobarxx
-Icon=kdevelop
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevfoobar
-X-KDE-PluginInfo-Name=kdevfoobar
-X-KDE-PluginInfo-Author=Jonathan Schmidt-Dominé (The User)
-X-KDE-PluginInfo-Email=devel@the-user.org
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=10
-X-KDevelop-Mode=GUI
-X-KDevelop-Category=Global
-# X-KDevelop-Language=C++
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.cpp (nonexistent)
@@ -1,225 +0,0 @@
-/***************************************************************************
- * This file was partly taken from KDevelop's cvs plugin *
- * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
- * *
- * Adapted for Bazaar *
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "initTest.h"
-
-#include <qtest_kde.h>
-#include <QtTest/QtTest>
-
-#include <KUrl>
-#include <KDebug>
-#include <kio/netaccess.h>
-
-#include <interfaces/iplugincontroller.h>
-#include <interfaces/iplugin.h>
-
-#include <vcs/interfaces/ibasicversioncontrol.h>
-
-#include <vcs/dvcs/dvcsjob.h>
-#include "../bzrexecutor.h"
-
-const QString tempDir = QDir::tempPath();
-const QString bzrTest_BaseDir(tempDir + "/kdevBazaar_testdir/");
-const QString bzrTest_BaseDir2(tempDir + "/kdevBazaar_testdir2/");
-const QString bzrRepo(bzrTest_BaseDir + ".bzr");
-const QString bzrTest_FileName("testfile");
-
-
-//TODO: bugs, this test didn't notice:
-//* git commit home/... wasn't notice
-// test for isValidDirectory is required!!!
-
-void BzrInitTest::initTestCase()
-{
- m_proxy = new BzrExecutor;
-
- // If the basedir for this cvs test exists from a
- // previous run; remove it...
- if ( QFileInfo(bzrTest_BaseDir).exists() )
- KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0);
- if ( QFileInfo(bzrTest_BaseDir2).exists() )
- KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0);
-
- // Now create the basic directory structure
- QDir tmpdir(tempDir);
- tmpdir.mkdir(bzrTest_BaseDir);
- tmpdir.mkdir(bzrTest_BaseDir2);
-}
-
-void BzrInitTest::cleanupTestCase()
-{
- delete m_proxy;
-
- if ( QFileInfo(bzrTest_BaseDir).exists() )
- KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0);
- if ( QFileInfo(bzrTest_BaseDir2).exists() )
- KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0);
-}
-
-void BzrInitTest::repoInit()
-{
- // make job that creates the local repository
- DVCSjob* j = m_proxy->init(KUrl(bzrTest_BaseDir));
- QVERIFY( j );
-
- // try to start the job
- QVERIFY( j->exec() );
-
- //check if the CVSROOT directory in the new local repository exists now
- QVERIFY( QFileInfo(QString(bzrRepo)).exists() );
-}
-
-void BzrInitTest::addFiles()
-{
- //we start it after repoInit, so we still have empty bazaar repo
- //First let's create a file
- QFile f(bzrTest_BaseDir + bzrTest_FileName);
- if(f.open(QIODevice::WriteOnly)) {
- QTextStream input( &f );
- input << "HELLO WORLD";
- }
- f.flush();
-
- DVCSjob* j = m_proxy->add(QString(bzrTest_BaseDir), KUrl::List(QStringList(bzrTest_FileName)));
- QVERIFY( j );
-
- // try to start the job
- QVERIFY( j->exec() );
-
-//TODO: Bazaar just change checkout/dirstate created by bzr init
-// //TODO: maybe other method should be used
-// QString testfile(BZR_REPO"/dirstate");
-// QVERIFY( QFileInfo(testfile).exists() );
-}
-
-void BzrInitTest::commitFiles()
-{
- //we start it after addFiles, so we just have to commit
- DVCSjob* j = m_proxy->commit(QString(bzrTest_BaseDir), QString("KDevelop's Test commit"),
- KUrl::List(QStringList(bzrTest_FileName)));
- QVERIFY( j );
-
- // try to start the job
- QVERIFY( j->exec() );
-
- //since we commited the file to the "pure" repository, .bzr/store/data/BZR_TESTFILE_NAME.i should exist
- //TODO: maybe other method should be used
- QString headRefName(bzrRepo + "/repository/indices/");
- QVERIFY( QFileInfo(headRefName).exists() );
-
- QString firstCommit;
- QFile headRef(headRefName);
- if(headRef.open(QIODevice::ReadOnly)) {
- QTextStream output( &headRef );
- output>>firstCommit;
- }
- headRef.flush();
- headRef.close();
-
-// QVERIFY(firstCommit!="");
-
- //let's try to change the file and test "bazaar commit -A"
- QFile f(bzrTest_BaseDir + bzrTest_FileName);
- if(f.open(QIODevice::WriteOnly)) {
- QTextStream input( &f );
- input << "Just another HELLO WORLD";
- }
- f.flush();
-
- //Since KJob uses delete later we don't care about deleting pld *j
- j = m_proxy->commit(QString(bzrTest_BaseDir), QString("KDevelop's Test commit2"));
- QVERIFY( j );
-
- // try to start the job
- QVERIFY( j->exec() );
-
-// QString secondCommit;
-// if(headRef.open(QIODevice::ReadOnly)) {
-// QTextStream output( &headRef );
-// output>>secondCommit;
-// }
-// headRef.flush();
-// headRef.close();
-//
-// QVERIFY(secondCommit!="");
-// QVERIFY(firstCommit != secondCommit);
-}
-
-void BzrInitTest::cloneRepository()
-{
- // make job that clones the local repository, created in the previous test
- DVCSjob* j = m_proxy->clone(KUrl(bzrTest_BaseDir), KUrl(bzrTest_BaseDir2));
- QVERIFY( j );
-
- // try to start the job
- QVERIFY( j->exec() );
-
- //check if the .bzr directory in the new local repository exists now
- QVERIFY( QFileInfo(QString(bzrTest_BaseDir2 + "kdevBazaar_testdir/.bzr/")).exists() );
-}
-
-void BzrInitTest::testInitAndCommit()
-{
- repoInit();
- addFiles();
- commitFiles();
- cloneRepository();
-}
-
-using namespace KDevelop;
-
-void BzrInitTest::testPlugin()
-{
-// Core::initialize();
-// Core *core;
-// core->initialize();
-// IPluginController* controller = core->pluginController();
-
-// IPlugin* bzrPlugin = controller->loadPlugin(QString("kdevbzr"));
-// QVERIFY(bzrPlugin);
-//
-// KPluginInfo bzrInfo = controller->pluginInfo(bzrPlugin);
-// QVERIFY(bzrInfo.isValid());
-//
-// //TODO: compare name() etc
-// kDebug()<<"name: "<<bzrInfo.name()<<" pluginName: "<<bzrInfo.pluginName();
-//
-// IBasicVersionControl* iface = bzrPlugin->extension<IBasicVersionControl>();
-// QVERIFY(iface);
-}
-
-void BzrInitTest::removeTempDirs()
-{
- if (QFileInfo(bzrTest_BaseDir).exists() )
- if (!KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir)), 0) )
- qDebug() << "KIO::NetAccess::del(" << bzrTest_BaseDir << ") returned false";
- if (QFileInfo(bzrTest_BaseDir2).exists() )
- if (!KIO::NetAccess::del(KUrl(QString(bzrTest_BaseDir2)), 0) )
- qDebug() << "KIO::NetAccess::del(" << bzrTest_BaseDir2 << ") returned false";
-}
-
-QTEST_KDEMAIN(BzrInitTest, GUI)
-
-
-#include "initTest.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/initTest.h (nonexistent)
@@ -1,53 +0,0 @@
-/***************************************************************************
- * This file was partly taken from KDevelop's cvs plugin *
- * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
- * *
- * Adapted for Bazaar *
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef GIT_INIT_H
-#define GIT_INIT_H
-
-#include <QtCore/QObject>
-
-class BzrExecutor;
-
-class BzrInitTest: public QObject
-{
- Q_OBJECT
-
- private:
- void repoInit();
- void addFiles();
- void commitFiles();
- void cloneRepository();
-
- private slots:
- void initTestCase();
- void testInitAndCommit();
- void testPlugin();
- void cleanupTestCase();
-
- private:
- BzrExecutor* m_proxy;
- void removeTempDirs();
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/tests/CMakeLists.txt (nonexistent)
@@ -1,31 +0,0 @@
-# Due to the use of system() and some unix-style paths this test will only run
-# under Linux. (Maybe this can be fixed later)
-#
-# Moreover, I'm not sure if there is a cvs commandline client for windows
-# (need to check this out ...)
-
-if (UNIX)
-
-# Running the test only makes sense if the git command line client
-# is present. So check for it before adding the test...
-FIND_PROGRAM(BZR NAMES bzr
- PATHS
- /bin
- /usr/bin
- /usr/local/bin
-)
-
-if (BZR)
-
- set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
- set(bzrInitTest_SRCS initTest.cpp ${CMAKE_SOURCE_DIR}/vcs/dvcs/dvcsjob.cpp ../bzrexecutor.cpp)
- kde4_add_unit_test(kdevbzr-test ${bzrInitTest_SRCS})
- target_link_libraries(kdevbzr-test
- ${QT_QTTEST_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- kdevplatformutil
- kdevplatformvcs
- )
-endif (BZR)
-
-endif (UNIX)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevbazaar.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/CMakeLists.txt (nonexistent)
@@ -1,42 +0,0 @@
-project(bazaar)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${bazaar_SOURCE_DIRECTORY}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-add_definitions(-DKDE_DEFAULT_DEBUG_AREA=9527)
-#add_subdirectory(tests)
-
-########### next target ###############
-
-set(kdevbzr_PART_SRCS
- bzrplugin.cpp
-# bzrexecutor.cpp
-)
-
-kde4_add_plugin(kdevbzr ${kdevbzr_PART_SRCS})
-
-
-target_link_libraries(kdevbzr
- ${KDE4_KDEUI_LIBS}
- kdevplatformutil
- kdevplatforminterfaces
- kdevplatformvcs
- kdevplatformshell
- kdevplatformproject
-)
-
-install(TARGETS kdevbzr DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-
-########### install files ###############
-install( FILES kdevbzr.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevbzr.rc DESTINATION ${DATA_INSTALL_DIR}/kdevbzr )
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.cpp (nonexistent)
@@ -1,181 +0,0 @@
-/***************************************************************************
- * This file was partly taken from KDevelop's cvs plugin *
- * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
- * *
- * Adapted for Bazaar *
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "bzrexecutor.h"
-
-#include <QFileInfo>
-#include <QDir>
-#include <QString>
-#include <QDateTime>
-#include <KLocale>
-#include <KUrl>
-#include <KMessageBox>
-#include <kshell.h>
-#include <KDebug>
-
-#include <vcs/vcsexport.h>
-#include <vcs/vcsstatusinfo.h>
-#include <vcs/dvcs/dvcsplugin.h>
-
-#include <vcs/dvcs/dvcsjob.h>
-#include <interfaces/iplugin.h>
-
-BzrExecutor::BzrExecutor(KDevelop::IPlugin* parent)
- : QObject(parent), vcsplugin(parent)
-{
-}
-
-BzrExecutor::~BzrExecutor()
-{
-}
-
-//TODO: write tests for this method!
-//maybe func()const?
-bool BzrExecutor::isValidDirectory(const KUrl & dirPath)
-{
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (job)
- {
- QString path = dirPath.path();
- QFileInfo fsObject(path);
- if (fsObject.isFile())
- path = fsObject.path();
-
- job->clear();
- job->setDirectory(path);
- *job << "bzr";
- *job << "root";
- job->exec();
- if (job->status() == KDevelop::VcsJob::JobSucceeded)
- {
- kDebug() << "Dir:" << path << " is inside work tree of bzr" ;
- return true;
- }
- }
- kDebug() << "Dir:" << dirPath.path() << " is not inside work tree of bzr" ;
- return false;
-}
-
-QString BzrExecutor::name() const
-{
- return QLatin1String("Bazaar");
-}
-
-DVCSjob* BzrExecutor::init(const KUrl &directory)
-{
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, directory.toLocalFile(), BzrExecutor::Init) ) {
- *job << "bzr";
- *job << "init";
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVCSjob* BzrExecutor::clone(const KUrl &repository, const KUrl directory)
-{
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, directory.toLocalFile(), BzrExecutor::Init) ) {
- *job << "bzr";
- *job << "clone";
- *job << repository.path();
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVCSjob* BzrExecutor::add(const QString& repository, const KUrl::List &files)
-{
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "add";
- addFileList(job, files);
-
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-//TODO: bzr doesn't like empty messages, but "KDevelop didn't provide any message, it may be a bug" looks ugly...
-//If no files specified then commit already added files
-DVCSjob* BzrExecutor::commit(const QString& repository,
- const QString &message, /*= "KDevelop didn't provide any message, it may be a bug"*/
- const KUrl::List &files /*= QStringList("-a")*/)
-{
- Q_UNUSED(files)
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "commit";
- *job << "-m";
- *job << KShell::quoteArg( message );
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVCSjob* BzrExecutor::remove(const QString& repository, const KUrl::List &files)
-{
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "rm";
- addFileList(job, files);
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVCSjob* BzrExecutor::status(const QString & repository, const KUrl::List & files, bool recursive, bool taginfo)
-{
- Q_UNUSED(recursive)
- Q_UNUSED(taginfo)
- DVCSjob* job = new DVCSjob(vcsplugin);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "status";
- addFileList(job, files);
-
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVCSjob* BzrExecutor::empty_cmd() const
-{
- ///TODO: maybe just "" command?
- DVCSjob* job = new DVCSjob(vcsplugin);
- *job << "echo";
- *job << "-n";
- return job;
-}
-
-// #include "bzrexecutor.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.desktop (nonexistent)
@@ -1,84 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=This plugin integrates Bazaar
-Comment[bs]=Ovaj dodatak integrira Bazaar
-Comment[ca]=Aquest connector integra Bazaar
-Comment[ca@valencia]=Aquest connector integra Bazaar
-Comment[de]=Dieses Modul integriert Bazaar
-Comment[en_GB]=This plugin integrates Bazaar
-Comment[es]=Este complemento integra Bazaar
-Comment[et]=See plugin lõimib Bazaari
-Comment[fr]=Ce module externe intègre Bazaar
-Comment[gl]=Complemento de integración con Bazaar.
-Comment[it]=Questa estensione integra Bazaar
-Comment[nl]=Deze plugin integreert Bazaar
-Comment[pl]=Wtyczka ta integruje Bazaar
-Comment[pt]=Este 'plugin' integra o Bazaar
-Comment[pt_BR]=Este plugin integra o Bazaar
-Comment[sv]=Insticksprogrammet integrerar Bazaar
-Comment[uk]=За допомогою цього додатка можна інтегрувати Bazaar
-Comment[x-test]=xxThis plugin integrates Bazaarxx
-Name=Bazaar Support
-Name[bs]=Bazaar podrška
-Name[ca]=Implementació de Bazaar
-Name[ca@valencia]=Implementació de Bazaar
-Name[cs]=Podpora Bazaar
-Name[de]=Bazaar-Unterstützung
-Name[en_GB]=Bazaar Support
-Name[es]=Implementación de Bazaar
-Name[et]=Bazaari toetus
-Name[fr]=Gestion de Bazaar
-Name[ga]=Tacaíocht Bazaar
-Name[gl]=Compatibilidade con Bazaar
-Name[hu]=Bazaar támogatás
-Name[it]=Supporto per Bazaar
-Name[ja]=Bazaar サポート
-Name[ms]=Penyokong Bazaar
-Name[nds]=Bazaar-Ünnerstütten
-Name[nl]=Ondersteuning van Bazaar
-Name[pa]=ਬਜ਼ਾਰ ਸਹਿਯੋਗ
-Name[pl]=Obsługa Bazaar
-Name[pt]=Suporte para Bazaar
-Name[pt_BR]=Suporte a Bazaar
-Name[sk]=Podpora Bazaar
-Name[sv]=Bazaar-stöd
-Name[tr]=Bazaar Desteği
-Name[ug]=Bazaar قوللىشى
-Name[uk]=Підтримка Bazaar
-Name[x-test]=xxBazaar Supportxx
-GenericName=Bazaar frontend
-GenericName[bs]=Bazaar prikaz
-GenericName[ca]=Frontal de Bazaar
-GenericName[ca@valencia]=Frontal de Bazaar
-GenericName[de]=Bazaar-Oberfläche
-GenericName[en_GB]=Bazaar frontend
-GenericName[es]=Interfaz Bazaar
-GenericName[et]=Bazaari kasutajaliides
-GenericName[fr]=Interface pour Bazaar
-GenericName[gl]=Interface para Bazaar
-GenericName[hu]=Bazaar előtétprogram
-GenericName[it]=Interfaccia di Bazaar
-GenericName[ja]=Bazaar フロントエンド
-GenericName[ms]=Mukadepan Bazaar
-GenericName[nds]=Bazaar-Böversiet
-GenericName[nl]=Frontend voor Bazaar
-GenericName[pa]=ਬਜ਼ਾਰ ਫਰੰਟਐਂਡ
-GenericName[pl]=Interfejs do Bazaar
-GenericName[pt]=Interface para o Bazaar
-GenericName[pt_BR]=Interface do Bazaar
-GenericName[sv]=Bazaar-gränssnitt
-GenericName[tr]=Bazaar Önucu
-GenericName[uk]=Графічна оболонка для Bazaar
-GenericName[x-test]=xxBazaar frontendxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevbzr
-X-KDE-PluginInfo-Name=kdevbzr
-X-KDE-PluginInfo-Author=Evgeniy Ivanov
-X-KDE-PluginInfo-Email=powerfox@kde.ru
-X-KDE-PluginInfo-Version=0.5
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=7
-X-KDevelop-Category=Global
-X-KDevelop-Mode=NoGUI
-X-KDevelop-Interfaces=org.kdevelop.IBasicVersionControl, org.kdevelop.IDistributedVersionControl
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrexecutor.h (nonexistent)
@@ -1,92 +0,0 @@
-/***************************************************************************
- * This file was partly taken from KDevelop's cvs plugin *
- * Copyright 2007 Robert Gruber <rgruber@users.sourceforge.net> *
- * *
- * Adapted for Bazaar *
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef BZR_EXECUTOR_H
-#define BZR_EXECUTOR_H
-
-#include <KUrl>
-#include <KJob>
-#include <QStringList>
-
-#include <vcs/dvcs/idvcsexecutor.h>
-#include <vcs/vcsrevision.h>
-
-class DVCSjob;
-
-namespace KDevelop
-{
- class IPlugin;
-}
-
-/**
- * This proxy acts as a single point of entry for most of the common hg commands.
- * It is very easy to use, as the caller does not have to deal which the DVCSjob class directly.
- * All the command line generation and job handling is done internally. The caller gets a DVCSjob
- * object returned from the proxy and can then call it's start() method.
- *
- * Here is and example of how to user the proxy:
- * @code
- * DVCSjob* job = proxy->editors( repo, urls );
- * if ( job ) {
- * connect(job, SIGNAL( result(KJob*) ),
- * this, SIGNAL( jobFinished(KJob*) ));
- * job->start();
- * }
- * @endcode
- *
- * @note All actions that take a KUrl::List also need an url to the repository which
- * must be a common base directory to all files from the KUrl::List.
- * Actions that just take a single KUrl don't need a repository, the hg command will be
- * called directly in the directory of the given file
- *
- * @author Robert Gruber <rgruber@users.sourceforge.net>
- * @author Evgeniy Ivanov <powerfox@kde.ru>
- */
-class BzrExecutor : public QObject, public KDevelop::IDVCSexecutor
-{
- Q_OBJECT
-public:
- explicit BzrExecutor(KDevelop::IPlugin* parent = 0);
- ~BzrExecutor();
-
- bool isValidDirectory(const KUrl &dirPath);
- QString name() const;
-
- DVCSjob* init(const KUrl & directory);
- DVCSjob* clone(const KUrl &directory, const KUrl repository);
- DVCSjob* add(const QString& repository, const KUrl::List &files);
- DVCSjob* commit(const QString& repository,
- const QString& message = "KDevelop did not provide any message, it may be a bug",
- const KUrl::List& files = QStringList());
- DVCSjob* remove(const QString& repository, const KUrl::List& files);
- DVCSjob* status(const QString & repo, const KUrl::List & files,
- bool recursive=false, bool taginfo=false);
- DVCSjob* empty_cmd() const;
-
-private:
- KDevelop::IPlugin* vcsplugin;
-
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.cpp (nonexistent)
@@ -1,378 +0,0 @@
-/***************************************************************************
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#include "bzrplugin.h"
-
-#include <KPluginFactory>
-#include <KPluginLoader>
-#include <KAboutData>
-#include <klocalizedstring.h>
-
-
-#include <QtCore/QDir>
-#include <QtCore/QDateTime>
-#include <QtCore/QFileInfo>
-
-
-#include <interfaces/icore.h>
-
-#include <vcs/dvcs/dvcsjob.h>
-
-//#include "bzrexecutor.h"
-
-#include <memory>
-
-K_PLUGIN_FACTORY(KDevBzrFactory, registerPlugin<BzrPlugin>(); )
-K_EXPORT_PLUGIN(KDevBzrFactory(KAboutData("kdevbzr","kdevbazaar", ki18n("Bazaar Plugin"), "0.1", ki18n("Bazaar version control system support"), KAboutData::License_GPL, ki18n("Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru>") ) ) )
-
-BzrPlugin::BzrPlugin( QObject *parent, const QVariantList & )
- : DistributedVersionControlPlugin(parent, KDevBzrFactory::componentData())
-{
- KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
- KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )
-
- core()->uiController()->addToolView(i18n("Bazaar"), DistributedVersionControlPlugin::dvcsViewFactory());
-
- setXMLFile("kdevbzr.rc");
-
-// m_exec = new BzrExecutor(this);
-}
-
-BzrPlugin::~BzrPlugin()
-{
-// delete m_exec;
-}
-
-QString BzrPlugin::name() const
-{
- return QLatin1String("Bazaar");
-}
-
-
-KDevelop::VcsJob* BzrPlugin::add(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
-{
- Q_UNUSED(recursion)
- if (localLocations.empty())
- return NULL;
-
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, localLocations.front().path()) ) {
- *job << "bzr";
- *job << "add";
- addFileList(job, localLocations);
-
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::remove(const KUrl::List& files)
-{
- if (files.empty())
- return NULL;
-
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, files.front().path()) ) {
- *job << "bzr";
- *job << "rm";
- addFileList(job, files);
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::status(const KUrl::List& localLocations,
- KDevelop::IBasicVersionControl::RecursionMode recursion)
-{
- Q_UNUSED(recursion)
- //it's a hack!!! See VcsCommitDialog::setCommitCandidates and the usage of DVcsJob/IDVCSexecutor
- //We need results just in status, so we set them here before execution in VcsCommitDialog::setCommitCandidates
- QString repo = localLocations[0].toLocalFile();
- QList<QVariant> statuses;
- qDebug("BzrPlugin::status");
- statuses << getCachedFiles(repo)
- << getModifiedFiles(repo)
- << getOtherFiles(repo);
- DVcsJob * noOp = empty_cmd();
- noOp->setResults(QVariant(statuses));
- return noOp;
-}
-
-KDevelop::VcsJob* BzrPlugin::commit(const QString& message,
- const KUrl::List& localLocations,
- KDevelop::IBasicVersionControl::RecursionMode recursion)
-{
- Q_UNUSED(recursion)
-
- if (localLocations.empty() || message.isEmpty())
- return NULL;
-
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, localLocations.front().path()) ) {
- *job << "bzr";
- *job << "commit";
- *job << "-m";
- *job << message;
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::log(const KUrl& localLocation,
- const KDevelop::VcsRevision& rev,
- unsigned long limit)
-{
- Q_UNUSED(rev)
- Q_UNUSED(limit)
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, localLocation.path()) ) {
- *job << "bzr";
- *job << "log";
- addFileList(job, localLocation);
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::init(const KUrl &directory)
-{
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, directory.toLocalFile(), BzrPlugin::Init) ) {
- *job << "bzr";
- *job << "init";
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::clone(const KDevelop::VcsLocation & localOrRepoLocationSrc, const KUrl& localRepositoryRoot)
-{
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, localRepositoryRoot.toLocalFile(), BzrPlugin::Init) ) {
- *job << "bzr";
- *job << "clone";
- *job << localOrRepoLocationSrc.localUrl().pathOrUrl();
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-KDevelop::VcsJob* BzrPlugin::reset(const KUrl& repository, const QStringList &args, const KUrl::List& files)
-{
- if (files.empty())
- return NULL;
-
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, repository.path()) ) {
- *job << "bzr";
- *job << "revert";
- //Empty branch has 'something' so it breaks the command
- if (!args.isEmpty())
- *job << args;
- addFileList(job, files);
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-void BzrPlugin::parseLogOutput(const DVcsJob * job, QList<DVcsEvent>& commits) const
-{
-// static QRegExp rx_sep( "[-=]+" );
-// static QRegExp rx_date( "date:\\s+([^;]*);\\s+author:\\s+([^;]*).*" );
-
- QStringList lines = job->output().split('\n', QString::SkipEmptyParts);
-
- QString commitLog;
-
- for (int i=0; i<lines.count(); ++i) {
- ++i; // skip line of --------------s
- QString rev = lines[i++]; // revno
- QString author = lines[i++]; // committer
- ++i; // branch nick
- QString date = lines[i++]; // timestamp
- ++i; // the word 'message'
- QString desc = lines[i];
-
- DVcsEvent commit;
- commit.setCommit(rev);
- commit.setAuthor(author);
- commit.setDate(date);
- if (!desc.startsWith("--")) {
- commit.setLog(desc); // only put on message if there was one
- } else {
- --i; // rewind by one if the message was blank
- }
-
- commits.push_front(commit);
- }
-}
-
-DVcsJob* BzrPlugin::switchBranch(const QString &repository, const QString &branch)
-{
- ///TODO Check if the branch exists. or send only existed branch names here!
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "merge";
- *job << repository;
- *job << branch;
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-DVcsJob* BzrPlugin::branch(const QString &repository, const QString &basebranch, const QString &branch, const QStringList &args)
-{
- Q_UNUSED(basebranch)
-
- DVcsJob* job = new DVcsJob(this);
- if (prepareJob(job, repository) ) {
- *job << "bzr";
- *job << "branch";
- if (!args.isEmpty())
- *job << args;
- *job << branch;
- return job;
- }
- if (job) delete job;
- return NULL;
-}
-
-QString BzrPlugin::curBranch(const QString &repository)
-{
- std::auto_ptr<DVcsJob> job(new DVcsJob(this));
-
- if (!prepareJob(job.get(), repository)) {
- return NULL;
- }
- *job << "bzr" << "nick";
-
- if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
- return QString();
-
- return job->output();
-}
-
-QStringList BzrPlugin::branches(const QString &repository)
-{
- QStringList toReturn;
-
- QString currName = curBranch(repository);
- if (!currName.isEmpty()) {
- toReturn.push_back(currName);
- }
- return toReturn;
-
-}
-
-bool BzrPlugin::isValidDirectory(const KUrl & directory)
-{
- static const QString bzrDir(".bzr");
- const QString initialPath(directory.toLocalFile());
- const QFileInfo finfo(initialPath);
- QDir dir;
- if (finfo.isFile()) {
- dir = finfo.absoluteDir();
- } else {
- dir = QDir(initialPath);
- dir.makeAbsolute();
- }
-
- while (!dir.cd(bzrDir) && dir.cdUp()) ;
-
- return bzrDir == dir.dirName();
-}
-
-
-QList<DVcsEvent> BzrPlugin::getAllCommits(const QString &repo)
-{
- std::auto_ptr<DVcsJob> job(new DVcsJob(this));
- job->setAutoDelete(false);
-
- if (!prepareJob(job.get(), repo)) {
- return QList<DVcsEvent>();
- }
-
- *job << "bzr" << "log";
-
- if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
- return QList<DVcsEvent>();
-
- QList<DVcsEvent> commits;
-
- parseLogOutput(job.get(), commits);
-
- return commits;
-}
-
-bool BzrPlugin::isVersionControlled(const KUrl & url)
-{
- const QFileInfo fsObject(url.path());
-
- if (!fsObject.isFile()) {
- return isValidDirectory(url);
- }
-
- // Clean, Added, Modified. Escape possible files starting with "-"
- const QString absolutePath = fsObject.absolutePath();
- const QStringList filesInDir = getLsFiles(absolutePath);
-
- return !filesInDir.empty();
-}
-
-QStringList BzrPlugin::getLsFiles(const QString &directory, const QStringList &args)
-{
- std::auto_ptr<DVcsJob> job(new DVcsJob(this));
-
- if (!prepareJob(job.get(), directory)) {
- return QStringList();
- }
-
- *job << "bzr" << "ls" << "--non-recursive";
-
- if (!args.isEmpty())
- *job << args;
-
- if (!job->exec() || job->status() != KDevelop::VcsJob::JobSucceeded)
- return QStringList();
-
- const QString prefix = directory.endsWith(QDir::separator()) ? directory : directory + QDir::separator();
- QStringList fileList = job->output().split('\n', QString::SkipEmptyParts);
- for (QStringList::iterator it = fileList.begin(); it != fileList.end(); ++it) {
- it->prepend(prefix);
- }
- return fileList;
-}
-
-KDevelop::VcsJob* BzrPlugin::log(const KUrl& localLocation,
- const KDevelop::VcsRevision& rev,
- const KDevelop::VcsRevision& limit)
-{
- Q_UNUSED(limit)
- return log(localLocation, rev, 0);
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/kdevbzr.rc (nonexistent)
@@ -1,10 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevBazaar" version="1">
-
- <Menu name="dvcs_popup">
- <text context="@title:menu">Bazaar</text>
- <Action name="dvcs_init" />
- <Action name="dvcs_clone" />
- </Menu>
-
-</kpartgui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/bazaar/bzrplugin.h (nonexistent)
@@ -1,97 +0,0 @@
-/***************************************************************************
- * Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru> *
- * *
- * This program is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU General Public License as *
- * published by the Free Software Foundation; either version 2 of *
- * the License or (at your option) version 3 or any later version *
- * accepted by the membership of KDE e.V. (or its successor approved *
- * by the membership of KDE e.V.), which shall act as a proxy *
- * defined in Section 14 of version 3 of the license. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program. If not, see <http://www.gnu.org/licenses/>. *
- ***************************************************************************/
-
-#ifndef BZR_PLUGIN_H
-#define BZR_PLUGIN_H
-
-#include <QtCore/QObject>
-
-#include <vcs/interfaces/idistributedversioncontrol.h>
-#include <vcs/interfaces/ibasicversioncontrol.h>
-
-#include <vcs/vcsexport.h>
-#include <vcs/vcsstatusinfo.h>
-#include <vcs/dvcs/dvcsplugin.h>
-
-//class BzrExecutor;
-
-/**
- * This is the main class of KDevelop's Git plugin.
- *
- * It implements the DVCS dependent things not implemented in KDevelop::DistributedVersionControlPlugin
- * @author Evgeniy Ivanov <powerfox@kde.ru>
- */
-class BzrPlugin: public KDevelop::DistributedVersionControlPlugin
-{
- Q_OBJECT
- Q_INTERFACES(KDevelop::IBasicVersionControl KDevelop::IDistributedVersionControl)
-
-//friend class BzrExecutor;
-
-public:
- BzrPlugin(QObject *parent, const QVariantList & args = QVariantList() );
- ~BzrPlugin();
-
- virtual QString name() const;
- virtual bool isVersionControlled(const KUrl& localLocation);
- virtual KDevelop::VcsJob* add(const KUrl::List& localLocations,
- KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
- virtual KDevelop::VcsJob* remove(const KUrl::List& localLocations);
- virtual KDevelop::VcsJob* status(const KUrl::List& localLocations,
- KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
-
- virtual KDevelop::VcsJob* commit(const QString& message,
- const KUrl::List& localLocations,
- KDevelop::IBasicVersionControl::RecursionMode recursion = KDevelop::IBasicVersionControl::Recursive);
- virtual KDevelop::VcsJob* log(const KUrl& localLocation,
- const KDevelop::VcsRevision& rev,
- const KDevelop::VcsRevision& limit);
- virtual KDevelop::VcsJob* log(const KUrl& localLocation,
- const KDevelop::VcsRevision& rev,
- unsigned long limit);
- virtual KDevelop::VcsJob* init(const KUrl& localRepositoryRoot);
- virtual KDevelop::VcsJob* clone(const KDevelop::VcsLocation& localOrRepoLocationSrc,
- const KUrl& localRepositoryRoot);
- virtual KDevelop::VcsJob* reset(const KUrl& repository,
- const QStringList &args, const KUrl::List& files);
-
- virtual void parseLogOutput(const DVcsJob * job,
- QList<DVcsEvent>& revisions) const;
-
- virtual DVcsJob* switchBranch(const QString &repository,
- const QString &branch);
- virtual DVcsJob* branch(const QString &repository,
- const QString &basebranch = QString(),
- const QString &branch = QString(),
- const QStringList &args = QStringList());
-
- virtual QString curBranch(const QString &repository);
- virtual QStringList branches(const QString &repository);
-
- virtual bool isValidDirectory(const KUrl &dirPath);
- virtual QList<DVcsEvent> getAllCommits(const QString &repo);
- QStringList getLsFiles(const QString &directory, const QStringList &args = QStringList());
-//
-//private:
-// BzrExecutor * m_exec;
-
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.h (nonexistent)
@@ -1,226 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SERIALIZATION_UTILS_H
-#define SERIALIZATION_UTILS_H
-
-///Unfortunately it seems that boost doesn't like the things that Qt syntactically does to the xml-syntax.
-///It fails to load logically same documents when they come from QDom, so we embed the data as simple text into the xml-document.
-
-#define XML_USE_TEXT_ARCHIVE
-
-#ifdef XML_USE_TEXT_ARCHIVE
-#include <boost/archive/polymorphic_text_iarchive.hpp>
-#include <boost/archive/polymorphic_text_oarchive.hpp>
-typedef boost::archive::polymorphic_text_iarchive XmlIArchive;
-typedef boost::archive::polymorphic_text_oarchive XmlOArchive;
-#else
-#include <boost/archive/polymorphic_xml_iarchive.hpp>
-#include <boost/archive/polymorphic_xml_oarchive.hpp>
-typedef boost::archive::polymorphic_xml_iarchive XmlIArchive;
-typedef boost::archive::polymorphic_xml_oarchive XmlOArchive;
-#endif
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/base_object.hpp>
-//#include <boost/serialization/extended_type_info.hpp>
-#include <boost/serialization/utility.hpp>
-#include <boost/serialization/list.hpp>
-#include <boost/serialization/vector.hpp>
-#include <boost/serialization/level.hpp>
-#include "nvp.h"
-
-#include <QString>
-#include <QDomDocument>
-#include <QDomNode>
-#include <QTextStream>
-
-///All these functions throw QString's as error-descriptions on error
-
-template <class Type>
-void xmlTextDeserialize( QString& buffer, Type& object ) throw( QString ) {
- QByteArray bufLocal = buffer.toUtf8().data();
- std::istringstream str;
- str.str( bufLocal.data() );
- try {
- XmlIArchive arch( str );
- arch & object;
- } catch ( std::exception & exc ) {
- throw QString( "exception occurred while deserialization: " ) + exc.what();
- }
-}
-
-template <class Type>
-void xmlTextSerialize( QString& buffer, Type& object ) throw( QString ) {
- buffer.clear();
-
- std::ostringstream str;
-
- try {
- XmlOArchive arch( str );
-
- arch & object;
- } catch ( std::exception & exc ) {
- throw QString( "exception occurred while serialization: " ) + exc.what();
- }
-
- buffer = str.str().c_str();
-}
-
-template <class Type>
-void xmlDeserialize( QDomNode& node, Type& object ) throw( QString ) {
- QDomNode header = node.namedItem( "header" );
- ///QDomNode type = node.namedItem( "doctype" );
- QDomNode serializationNode = node.namedItem( "boost_serialization" );
- if ( header.isNull() )
- throw QString( "document does not contain header" );
- /* if( type.isNull() )
- throw QString( "document does not contain type" );*/
- if ( serializationNode.isNull() )
- throw QString( "document does not contain serialization-node" );
- if ( !header.isElement() && !header.isText() )
- throw QString( "header is no element" );
- /*if( type.isElement() && !type.isText() )
- throw QString( "type is no element" );*/
- /* if( serializationNode.isElement() )
- throw QString( "serialization-node is no element" );*/
-
- QDomNode headerText = header;
- if ( !header.isText() )
- headerText = header.firstChild();
- /*QDomNode typeText = type;
- if( !type.isText() )
- typeText = header.firstChild();*/
-
- if ( headerText.isNull() /*|| typeText.isNull()*/ || !headerText.isText() /*|| !typeText.isText()*/ )
- throw QString( "header- or type-elements have wrong type" );
-
- QString text;
- {
- QTextStream stream( &text );
- serializationNode.save( stream, 1 );
- }
-
- //text = headerText.data() +"\n" + typeText.data() + "\n" + text;
- if ( text.isEmpty() )
- throw QString( "text is empty" );
- text = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n <!DOCTYPE boost_serialization>\n" + text;
- cout << "deserializing: " << endl << text.toUtf8().data();
- xmlTextDeserialize( text, object );
-}
-
-template <class Type>
-void xmlSerialize( QDomNode& container, Type& object, const QString& nodeName = "" ) throw( QString ) {
- QString buf;
- xmlTextSerialize( buf, object );
- if ( buf.isEmpty() )
- throw QString( "serialized buffer is empty" );
-
- QDomDocument doc( nodeName );
- doc.setContent( buf );
-
- QDomNode header = doc.firstChild();
- QDomDocumentType type = doc.doctype();
- QString headerText, typeText;
-
- cout << "full serialized data: \n" << buf.toUtf8().data() << endl;
-
- {
- QTextStream stream( &headerText );
- header.save( stream, 1 );
- }
- {
- QTextStream stream( &typeText );
- type.save( stream, 1 );
- }
-
- QDomDocument domDoc = container.ownerDocument();
- QDomElement storedHeaderNode = domDoc.createElement( "header" );
- QDomElement storedTypeNode = domDoc.createElement( "doctype" );
- storedHeaderNode.appendChild( domDoc.createTextNode( headerText + "\n" + typeText ) );
- storedTypeNode.appendChild( domDoc.createTextNode( typeText ) );
-
- container.appendChild( storedHeaderNode );
- // container.appendChild( storedTypeNode );
- container.appendChild( doc.firstChildElement().cloneNode() ); ///While serialization, there is one "boost_serialization"-child created. Only that should be exported.
-}
-
-/**This deletes the previous element of the given name, and replaces it with a new one containing the data.
- *the given object-type must already be a name-value-pair(see NVP(...) )
- * Errors are thrown as QString
-*/
-
-template <class Type>
-void xmlSerializeToElementItem( QDomElement* el, const QString& item, Type& object ) throw( QString ) {
- QDomDocument domDoc = el->ownerDocument();
- {
- QDomNode containerNode = el->namedItem( item );
-
- if ( !containerNode.isNull() )
- el->removeChild( containerNode );
- }
-
- QDomElement containerNode = domDoc.createElement( item );
- el->appendChild( containerNode );
-
-#ifdef XML_USE_TEXT_ARCHIVE
-
- QString buffer;
- xmlTextSerialize( buffer, object );
- if ( buffer.isEmpty() )
- throw QString( "deserialized buffer is empty" );
- containerNode.appendChild( domDoc.createTextNode( buffer ) );
-#else
-
- xmlSerialize( containerNode, object, item );
-
-#endif
-}
-
-/**is invoked the same way as xmlSerializeToElementItem(...)
- * Errors are thrown as QString
- */
-
-template <class Type>
-void xmlDeserializeFromElementItem( const QDomElement* el, const QString& item, Type& object ) throw( QString ) {
- QDomNode containerNode = el->namedItem( item );
- if ( containerNode.isNull() )
- throw "container-node of name \"" + item + "\" is missing";
-
-#ifdef XML_USE_TEXT_ARCHIVE
-
- QDomNode node = containerNode.firstChild();
- if ( node.isNull() )
- throw "the container-node of name \"" + item + "\" does not contain the correct data";
-
- QString data;
-
- QDomText textNode = node.toText();
- if ( textNode.isNull() )
- throw "the container-node of name \"" + item + "\" does not contain the correct data";
-
- data = textNode.data();
- if ( data.isEmpty() )
- throw QString( "stored data is empty" );
- xmlTextDeserialize( data, object );
-#else
-
- xmlDeserialize( containerNode, object );
-
-#endif
-
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h (nonexistent)
@@ -1,189 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef FILECOLLABORATIONSESSION_H
-#define FILECOLLABORATIONSESSION_H
-
-#include <QStringList>
-#include <QList>
-
-#include "teamworkfwd.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/weaksafesharedptr.h"
-
-#include "filecollaborationmessages.h"
-#include "lib/network/crossmap.h"
-#include "safelogger.h"
-
-class VectorTimestamp;
-class FileCollaboration;
-typedef SharedPtr<FileCollaboration> FileCollaborationPointer;
-class FileCollaborationSession;
-typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
-class DocumentWrapper;
-class FileCollaborationManager;
-typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
-
-NAMED_TYPE( SessionName, QString );
-
-class FileCollaborationSession : public QObject, public WeakShared, public SafeLogger {
- Q_OBJECT
- public:
-
- enum State {
- Running,
- Finished
- };
-
- ///Collaboration-class, the associated user
- BIND_LIST_2( Keys, FileCollaborationPointer, UserPointer )
- ///Document-Wrapper, its index, filename
- BIND_LIST_3( FileKeys, DocumentWrapperPointer, uint, QString )
- BIND_LIST_3( Messages, FileCollaborationMessage, DocumentWrapperMessage, FileListMessage )
-
- typedef Utils::CrossMap<DocumentWrapperPointer, FileKeys> FileSet;
-
- FileCollaborationSession( QString name, CollabFileList files, FileCollaborationManager* manager, uint primaryIndex, CollabSessionId id = 0 );
-
- void inviteUser( const KDevTeamworkUserPointer& user );
-
- void kickUser( const KDevTeamworkUserPointer& user );
-
- FileCollaborationManager* manager();
-
- bool acceptMessage( const FileCollaborationRequestPointer& msg );
-
- const FileSet& files() const;
-
- QString name() const;
-
- QList<KDevTeamworkUserPointer> users() const;
-
- //void processMessage( const FileCollaborationMessagePointer& msg );
- int processMessage( FileCollaborationMessage* msg );
-
- CollabFileList fileNames() const;
-
- QStringList plainFileNames() const;
-
- QList<uint> plainIds() const;
-
- CollabSessionId id() const;
-
- State state() const;
-
- QIcon icon() const;
-
- bool isMasterSession() const;
-
- uint primaryIndex() const;
-
- void updateTree( QModelIndex& i, QStandardItemModel* model );
-
- void fillContextMenu( int i, QMenu* menu );
-
- ///Allocates a new timestamp-index(for a new collaborator)
- uint allocateIndex();
-
- uint allocateWrapperIndex();
-
- ///Returns the name of the first online peer-user, or empty string
- QString firstPeerName();
-
- ///This allows/disallows connected users to add own files to the collaboration
- void setAllowSentDocuments( bool allow );
- signals:
- void userJoined( const KDevTeamworkUserPointer& );
- void userLeft( const KDevTeamworkUserPointer& );
- ///Emitted whenever an important information(file-set, user-set, etc.) changed
- void stateChanged( const FileCollaborationSessionPointer& );
- void documentSetChanged();
-
- public slots:
- void saveAsFiles();
- void saveAsPatch();
- void disableEditing();
- void enableEditing();
- void removeAllFiles();
- void slotPublishFileList();
- void publishStateChange();
- void addFile();
- void stopSession();
- void closeSession();
- void publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender );
- void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
- void slotConnectionResult( FileCollaboration*, bool ); ///If true, connection was successful. If false, connection failed.
- private slots:
- void removeUserAction();
- private:
- int receiveMessage( MessageInterface* msg );
- int receiveMessage( FileListMessage* msg );
- int receiveMessage( FileCollaborationMessage* msg );
- int receiveMessage( DocumentWrapperMessage* msg );
-
- void removeCollaboration( const FileCollaborationPointer& collab );
-
- QAction* getRemoveUserAction( const UserPointer& user );
-
- void publishFileRemove( uint id );
- void publishFileList( const CollabFileList& files );
-
- bool synchronizeFile( const FileCollaborationPointer& collab, const DocumentWrapperPointer& wrapper );
-
- ///Does not necessarily remove the file, maybe it only disables collaboration on it.
- bool killFile( uint id );
- bool removeFile( uint id );
- uint addFileInternal( const CollabFile& file, bool fromBuffer, bool readFile );
-
- void aboutToClose();
-
- virtual std::string logPrefix();
-
- DocumentWrapperPointer getDocument( const QString& fileName );
-
- friend class FileCollaboration;
- friend class FileCollaborationManager;
-
- ///May throw QString on error
- FileCollaborationPointer newCollaboration( const KDevTeamworkUserPointer& u, const FileCollaborationRequestPointer& request = 0 );
-
-
- FileSet m_files;
- typedef Utils::CrossMap
- <FileCollaborationPointer, Keys> CollaborationSet;
- /*UserSet m_ivitedUsers; ///All users that are invited to join
- UserSet m_users; ///All users that are actively collaborating*/
- CollaborationSet m_collaborations;
- FileCollaborationManager* m_manager;
- CollabSessionId m_id;
-
- bool m_allowSentDocuments;
- bool m_isMasterSession;
- uint m_primaryIndex;
- uint m_indexCount;
- uint m_wrapperIndexCount;
- QString m_name;
- QTimer* m_publishFileListTimer;
- QTimer* m_stateChangeTimer;
-
- QAction* m_removeUserAction;
-
- friend class MessageDispatcher< FileCollaborationSession, Messages >;
- MessageDispatcher< FileCollaborationSession, Messages > m_dispatcher;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h (nonexistent)
@@ -1,105 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef AUTO_CONSTRUCT_POINTER_H
-#define AUTO_CONSTRUCT_POINTER_H
-
-/**This is a pointer-class that can be used as a simple wrapper to have the same safety
-*as using normal element-classes, but allows the classes to be forward-declared. Also
-*it features serialization.
-*It cannot be zero! */
-
-class NormalSerialization;
-
-template <class T, class Serialization = NormalSerialization>
-class AutoConstructPointer {
- T* m_data;
-
- public:
-
- AutoConstructPointer() {
- m_data = new T();
- }
-
- AutoConstructPointer( const AutoConstructPointer& rhs ) {
- m_data = new T( *rhs );
- }
-
- AutoConstructPointer& operator = ( const AutoConstructPointer& rhs ) {
- return * this;
- }
-
- template <class Param>
- AutoConstructPointer( Param& param ) {
- m_data = new T( param );
- }
-
- template <class Param>
- AutoConstructPointer( const Param& param ) {
- m_data = new T( param );
- }
- template <class Param, class Param2>
- AutoConstructPointer( Param& param, Param2& param2 ) {
- m_data = new T( param, param2 );
- }
-
- ~AutoConstructPointer() {
- delete m_data;
- }
-
- void reset( T* t ) {
- m_data = t;
- }
-
- T& operator *() {
- return * m_data;
- }
-
- const T& operator *() const {
- return * m_data;
- }
-
- T* data() {
- return m_data;
- }
-
- operator const T* () const {
- return m_data;
- }
-
- operator T* () {
- return m_data;
- }
-
- const T* data() const {
- return m_data;
- }
-
- T* operator -> () {
- return m_data;
- }
-
- const T* operator -> () const {
- return m_data;
- }
-
- template <class Archive>
- void serialize( Archive& arch, uint /*version*/ ) {
- arch & ( *data() );
- }
-};
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/autoconstructpointer.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.h (nonexistent)
@@ -1,304 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_H
-#define KDEVTEAMWORK_H
-
-#include <QObject>
-#include <QMap>
-#include <QMenu>
-#include <QDomDocument>
-#include <memory>
-#include <kiconloader.h>
-#include <set>
-#include <list>
-
-#include "teamworkfwd.h"
-#include "loglevel.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/messageinterface.h"
-#include "autoconstructpointer.h"
-
-using namespace Teamwork;
-class KUrl;
-
-namespace Ui {
-class Teamwork;
-}
-
-class QModelIndex;
-
-class KDevTeamwork : public QObject {
- static KDevTeamwork* m_self;
- enum MessageTypes {
- Message = 0,
- SourceMessage = 1
- };
-
- Q_OBJECT
- public:
- typedef SafeSharedPtr<KDevTeamworkClient> TeamworkClientPointer;
- KDevTeamwork( const KUrl& workspaceDirectory, KDevTeamworkPlugin *plugin, QWidget *parent );
- virtual ~KDevTeamwork();
-
- KDevTeamworkPlugin *plugin() const;
-
- static KDevTeamwork* self() ;
-
- /**Sets the whole teamwork-part(client plus server) active/inactive. When set inactive, all connetions are closed.
- on success returns the given activity-state. */
- bool setActive( bool active );
- //
- /**enables/disables the server. */
- bool setServerActive( bool active );
-
- void showUserInfo( const UserPointer& user );
-
- ///@todo: make this a signal
- void fillUserMenu( QMenu* menu, const UserPointer& user );
-
- ///The main fillMessageMenu is the one in the MessageManager. That also invokes this one.
- void fillMessageMenu( QMenu* menu, const MessagePointer& msg );
-
- ///@todo remove
- Ui::Teamwork& widgets();
-
- QWidget* widget();
-
- IconCache& icons();
-
- void log( const QString& str, LogLevel level = Info );
-
- void err( const QString& str );
-
- QIcon iconFromUser( User* user, KIconLoader::Group size = KIconLoader::Small );
-
- ///Starts the update-timer for the developer-lists
- void startUpdateTimer();
-
- TeamworkClientPointer& client();
-
- PatchesManager* patchesManager();
-
- CollaborationManager* collaborationManager();
-
- MessageManager* messageManager();
-
- void handlePatchesList( PatchesListMessage* msg );
- void getPatchesList( const UserPointer& user );
-
- LoggerPointer logger();
-
- ///Inserts the given message into the various GUI-structures. It should be based on AbstractGUIMessage.
- void addMessageToList( const MessagePointer& smsg );
-
- virtual void restorePartialProjectSession( const QDomElement* el );
-
- virtual void savePartialProjectSession( QDomElement* el );
-
- UserPointer localUser();
-
- UserIdentity currentUserIdentity();
-
- public slots:
-
- /**Prepares the GUI for sending a message to the given user. Second parameter may be zero
- * @param target The user the message should be sent to
- * @param answerTo which message this one is a reply to.
- * */
- void guiSendMessageTo( const UserPointer& target, const MessagePointer& answerTo = MessagePointer() );
-
- ///This can be used by messages in other threads to send a request that their state(currently only icon) has changed
- void updateMessageInfo( MessagePointer );
-
- signals:
- ///This is called whenever the local client was destroyed or created, the current client is given as parameter(may be null). Whenever this is emitted, all UserPointers become invalid.
- void updateConnection( TeamworkClientPointer client );
- ///Called once KDevTeamwork is completely constructed
- void init();
- void deInit();
-
- private slots:
- void documentActivated( KDevelop::IDocument* file );
- void popupContextMenu( const QPoint &pos );
- void allowIncomingChanged( int state );
- void enableCollaborationChanged( int state );
- void connectServer();
-
- void uiShowPatches();
- void uiUserInfo();
-
- void uiFilterLog();
-
- void connectionRequest( ConnectionRequestPointer request );
-
- void developerClicked( const QModelIndex& index );
- void developerDoubleClicked( const QModelIndex& index );
- void developerContextMenu( const QPoint& );
-
- void serverClicked( const QModelIndex& index );
- void clientClicked( const QModelIndex& index );
- void messageClicked( const QModelIndex& index );
-
- void serverDoubleClicked( const QModelIndex& index );
- void clientDoubleClicked( const QModelIndex& index );
- void messageDoubleClicked( const QModelIndex& index );
-
- void receiveMessage( SafeSharedPtr<KDevSystemMessage> msg );
-
- void clearLogButton();
- void saveLogButton();
-
- void messageReplyTimeout();
- void sendMessageButton();
- void messageTypeIndexChanged( const int index );
-
- void slotClearMessageText();
-
- void slotClearMessages();
- void slotMessageHistory();
-
- void disconnectFromServer();
- void disconnectAllServers();
-
- void sendAnswerMessage();
- void sendMessageToUser();
- void kickClient();
- void banClient();
- void kickAllClients();
-
- void messageTargetUserChanged();
- void updateAnswerMenu();
-
- void handleTextMessage( SafeSharedPtr<KDevTeamworkTextMessage> msg );
-
- void guiUserConnected( Teamwork::UserPointer );
- void guiUserDisconnected( Teamwork::UserPointer );
- void guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
- void guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
- void guiUserList( std::list<UserPointer> );
- void guiLog( QString str, int level ) {
- log( str, ( LogLevel ) level );
- }
-
- ///Should be called time by time after the state of users changes. This updates all lists that contain users.
- void updateTimeout();
-
- void messageUpdated( const MessagePointer& msg );
-
- void maybeDeveloperContextMenu();
-
- void answerMenuToggled( bool state );
- void answerMenuTriggered( bool );
-
- private:
- void contextMenu( const QPoint& p, const QModelIndex& index );
-
- void lockMessageGui( const MessagePointer& msg );
- void unlockMessageGui();
-
- friend class KDevTeamworkLogger;
- friend class KDevTeamworkClient;
-
- void addSentMessageToList( const MessagePointer&, QStandardItemModel* model );
-
- void addReceivedMessageToList( const MessagePointer&, QStandardItemModel* model );
-
- QAction* sendAnswerAction;
- QAction* sendMessageToUserAction;
- QAction* disconnectFromServerAction;
- QAction* disconnectAllServersAction;
-
- QAction* kickClientAction;
- QAction* banClientAction;
- QAction* kickAllClientsAction;
- QAction* m_userInfoAction;
- QAction* showPatchesAction;
-
- UserPointer sendingUser();
-
- MessagePointer sendingMessage();
-
- void addSentMessageToList( const MessagePointer& );
-
- void addReceivedMessageToList( const MessagePointer& );
-
- void addDeveloper( const Teamwork::UserPointer& u );
-
- void enableActiveGUI( bool active );
-
- void enableMessageGUI( bool active );
-
- void filterLog( int max = 0 );
-
- void registerPatches( PatchesListMessage* msg, QStandardItemModel* model );
-
- UserPointer currentMessageTargetUser();
-
- QMenu* m_messageFilterMenu;
-
- AutoConstructPointer<TeamworkFolderManager> m_folderManager;
-
- SafeSharedPtr<KDevTeamworkLogger> m_logger;
-
- bool m_destroyed;
- KDevTeamworkPlugin *m_plugin;
- QWidget* m_widget;
- AutoConstructPointer<Ui::Teamwork> m_widgets;
- bool m_active, m_serverActive;
- TeamworkClientPointer m_client;
- QStandardItemModel* m_logModel;
- QStandardItemModel* m_messagesModel;
- QStandardItemModel* m_clientsModel;
- QStandardItemModel* m_serversModel;
- QStandardItemModel* m_developersModel;
-
- ///The next message to send is answer to:
- MessagePointer m_answerTo;
- MessagePointer m_waitingForReply; ///This message is blocking the message-gui waiting for a reply
- QTimer* m_replyWaitingTimeout;
-
-
- friend class MessageUserTab;
-
- KDevTeamworkUserPointer currentTabUser();
-
- typedef QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> > UserTabMap;
-
- UserTabMap m_userTabs;
-
- MessagePointer m_actionMessage;
-
- QTimer* m_updateTimer;
- QTimer* m_updateAnswerTimer; ///Timer for updating the list of possible messages the user can reply to
- AutoConstructPointer<PatchesManager> m_patchesManager;
- AutoConstructPointer<CollaborationManager> m_collaborationManager;
- AutoConstructPointer<MessageManager> m_messageManager;
- AutoConstructPointer<MessageSendManager> m_messageSendManager;
-
- std::set<UserPointer, UserPointer::ValueSmallerCompare> m_persistentUsers;
-
- LogLevel m_currentLogFilter;
-
- AutoConstructPointer<IconCache> m_icons;
- std::auto_ptr<QPersistentModelIndex> m_contextMenuIndex;
-
- enum MessageTypeIndex {
- NormalMessage,
- DocumentMessage
- };
-};
-
-#endif // KDEVCODEVIEW_H
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp (nonexistent)
@@ -1,152 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "kdevteamwork_client.h"
-#include <list>
-#include <kdebug.h>
-
-#include "kdevteamwork.h"
-#include "helpers.h"
-
-#include "patchmessage.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/teamworkmessages.h"
-#include "lib/network/defines.h"
-#include "kdevteamwork_user.h"
-#include "kdevteamwork_helpers.h"
-
-BIND_LIST_5( KDevTeamworkDispatchMessages, KDevTeamworkTextMessage, KDevSystemMessage, ConnectionRequest, PatchesManagerMessage, CollaborationMessage )
-
-std::string stringToAddr( const QString& txt ) {
- if ( txt.indexOf( ':' ) != -1 )
- return txt.left( txt.indexOf( ':' ) ).toUtf8().data();
- return txt.toUtf8().data();
-}
-
-int stringToPort( const QString& txt ) {
- if ( txt.indexOf( ':' ) == -1 )
- return STANDARDPORT;
- else
- return txt.mid( txt.indexOf( ':' ) + 1 ).toLong();
-}
-
-
-KDevTeamworkClient::KDevTeamworkClient( KDevTeamwork* teamwork ) : Client( ServerInformation( "0.0.0.0", STANDARDPORT ), teamwork->m_logger.cast<Logger>() ), m_teamwork( teamwork ) {
- qRegisterMetaType<Teamwork::UserPointer>( "Teamwork::UserPointer" );
- qRegisterMetaType<Teamwork::ClientSessionDesc>( "Teamwork::ClientSessionDesc" );
- qRegisterMetaType<Teamwork::ServerInformation>( "Teamwork::ServerInformation" );
- qRegisterMetaType<SafeSharedPtr<KDevTeamworkTextMessage> >( "SafeSharedPtr<KDevTeamworkTextMessage>" );
- qRegisterMetaType<ConnectionRequestPointer >( "ConnectionRequestPointer" );
- qRegisterMetaType<std::list<UserPointer> >( "std::list<UserPointer>" );
- qRegisterMetaType<SafeSharedPtr<KDevSystemMessage> >( "SafeSharedPtr<KDevSystemMessage>" );
- qRegisterMetaType<PatchesManagerMessagePointer >( "PatchesManagerMessagePointer" );
- qRegisterMetaType<CollaborationMessagePointer >( "CollaborationMessagePointer" );
-
- connect( this, SIGNAL( guiUserConnected( Teamwork::UserPointer ) ), m_teamwork, SLOT( guiUserConnected( Teamwork::UserPointer ) ), Qt::QueuedConnection );
- connect( this, SIGNAL( guiUserDisconnected( Teamwork::UserPointer ) ), m_teamwork, SLOT( guiUserDisconnected( Teamwork::UserPointer ) ), Qt::QueuedConnection );
- connect( this, SIGNAL( guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), m_teamwork, SLOT( guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), Qt::QueuedConnection );
- connect( this, SIGNAL( guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), m_teamwork, SLOT( guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation ) ), Qt::QueuedConnection );
- connect( this, SIGNAL( guiUserList( std::list<UserPointer> ) ), m_teamwork, SLOT( guiUserList( std::list<UserPointer> ) ), Qt::QueuedConnection );
-
- // messageTypes().registerMessageTypes<KDevTeamworkMessages>();
- setIdentity( new User( "server&client" ) );
-}
-
-int KDevTeamworkClient::receiveMessage( KDevSystemMessage* msg ) {
- if ( m_teamwork )
- QMetaObject::invokeMethod( m_teamwork, "receiveMessage", Qt::QueuedConnection, Q_ARG( SafeSharedPtr<KDevSystemMessage>, msg ) );
- return 1;
-}
-
-int KDevTeamworkClient::receiveMessage( CollaborationMessage* msg ) {
- emit signalDispatchMessage( CollaborationMessagePointer( msg ) );
- return 1;
-}
-
-int KDevTeamworkClient::receiveMessage( PatchesManagerMessage* msg ) {
- emit signalDispatchMessage( PatchesManagerMessagePointer( msg ) );
- return 1;
-}
-
-int KDevTeamworkClient::receiveMessage( KDevTeamworkTextMessage* msg ) {
- if ( m_teamwork )
- QMetaObject::invokeMethod( m_teamwork, "handleTextMessage", Qt::QueuedConnection, Q_ARG( SafeSharedPtr<KDevTeamworkTextMessage>, msg ) );
- return 1;
-}
-
-int KDevTeamworkClient::receiveMessage( ConnectionRequest* msg ) {
- out( Logger::Debug ) << "dispatching connection-request";
- if ( m_teamwork )
- QMetaObject::invokeMethod( m_teamwork, "connectionRequest", Qt::QueuedConnection, Q_ARG( ConnectionRequestPointer, msg ) );
- return 1;
-}
-
-void KDevTeamworkClient::gotUserList( const std::list<UserPointer>& users ) {
- emit guiUserList( users );
-}
-
-UserPointer KDevTeamworkClient::createUser( IdentificationMessage* msg ) {
- return new KDevTeamworkUser( msg );
-}
-
-
-UserPointer KDevTeamworkClient::createUser( const User* user ) {
- return new KDevTeamworkUser( user );
-}
-
-///this is called whenever a new user successfully logged into the server
-void KDevTeamworkClient::userConnected( const Teamwork::UserPointer& user ) {
- kDebug(9500) << "userConnected";
-
- emit guiUserConnected( user );
-
- Client::userConnected( user );
-
-}
-
-///called whenever a user leaves the server
-void KDevTeamworkClient::userDisconnected( const Teamwork::UserPointer& user ) {
- kDebug(9500) << "userDisconnected";
-
- emit guiUserDisconnected( user );
-
- Client::userDisconnected( user );
-}
-
-///this is called whenever a connection is successfully established to a server
-void KDevTeamworkClient::connectedToServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server ) {
- kDebug(9500) << "connectedToServer";
-
- emit guiServerConnected( session, server );
-
- Client::connectedToServer( session, server );
-}
-
-///this is called whenever a server the client disconnects from a connected server in any way
-void KDevTeamworkClient::disconnectedFromServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server ) {
- kDebug(9500) << "disconnectedFromServer";
-
- emit guiServerDisconnected( session, server );
-
- Client::disconnectedFromServer( session, server );
-}
-
-void KDevTeamworkClient::processMessage( MessageInterface* msg ) throw() {
- Teamwork::MessageDispatcher< KDevTeamworkClient, KDevTeamworkDispatchMessages> dispatcher( *this );
- if( !dispatcher( msg ) )
- Teamwork::Client::processMessage( msg );
-}
-
-#include "kdevteamwork_client.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui (nonexistent)
@@ -1,441 +0,0 @@
-<ui version="4.0" >
- <class>EditPatch</class>
- <widget class="QDialog" name="EditPatch" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>502</width>
- <height>688</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Edit Patch</string>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QTabWidget" name="tabWidget" >
- <property name="currentIndex" >
- <number>1</number>
- </property>
- <widget class="QWidget" name="fileTab" >
- <attribute name="title" >
- <string>File</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="1" column="0" colspan="2" >
- <widget class="QLabel" name="mimetype" >
- <property name="text" >
- <string/>
- </property>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="QLabel" name="label_2" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">File:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item row="0" column="1" >
- <widget class="KUrlRequester" name="filename" />
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="commandTab" >
- <attribute name="title" >
- <string>command-output</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="label_9" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Command:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="command" />
- </item>
- <item>
- <widget class="QPushButton" name="commandToFile" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>To File</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item row="12" column="0" >
- <widget class="QGroupBox" name="filesGroup" >
- <property name="title" >
- <string>Files</string>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>2</number>
- </property>
- <property name="spacing" >
- <number>4</number>
- </property>
- <item row="0" column="1" >
- <widget class="QListView" name="filesList" >
- <property name="editTriggers" >
- <set>QAbstractItemView::NoEditTriggers</set>
- </property>
- </widget>
- </item>
- <item row="0" column="0" >
- <layout class="QVBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="highlightFiles" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Highlight</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="previousHunk" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Previous Hunk</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="nextHunk" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Next Hunk</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item row="10" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="label_11" >
- <property name="text" >
- <string>Author:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="author" />
- </item>
- <item>
- <widget class="QPushButton" name="userButton" >
- <property name="text" >
- <string>User</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="11" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="determineState" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Determine</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="label_10" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>State:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="state" />
- </item>
- <item>
- <widget class="QLabel" name="label" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Access:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KComboBox" name="accessRights" />
- </item>
- </layout>
- </item>
- <item row="9" column="0" >
- <widget class="QTextEdit" name="description" />
- </item>
- <item row="4" column="0" >
- <widget class="QLabel" name="label_6" >
- <property name="text" >
- <string>recommended unapply-command:</string>
- </property>
- </widget>
- </item>
- <item row="5" column="0" >
- <widget class="QLineEdit" name="unapplyCommand" />
- </item>
- <item row="6" column="0" >
- <widget class="QLabel" name="label_7" >
- <property name="text" >
- <string>Dependencies:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0" >
- <widget class="QLineEdit" name="applyCommand" />
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="label_5" >
- <property name="text" >
- <string>recommended apply-command:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="label_8" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">N&lt;span style=" font-weight:600;">ame:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="name" />
- </item>
- <item>
- <widget class="QLabel" name="label_3" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;/head>&lt;body style=" white-space: pre-wrap; font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Type:&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="type" />
- </item>
- <item>
- <widget class="QPushButton" name="chooseType" >
- <property name="text" >
- <string>Choose</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="8" column="0" >
- <widget class="QLabel" name="label_4" >
- <property name="text" >
- <string>Description:</string>
- </property>
- </widget>
- </item>
- <item row="7" column="0" >
- <widget class="QLineEdit" name="dependencies" />
- </item>
- <item row="13" column="0" >
- <widget class="QDockWidget" name="konsoleDock" >
- <property name="features" >
- <set>QDockWidget::AllDockWidgetFeatures</set>
- </property>
- <widget class="QWidget" name="dockWidgetContents" />
- </widget>
- </item>
- <item row="14" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="applyButton" >
- <property name="text" >
- <string>Apply</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="unApplyButton" >
- <property name="text" >
- <string>Unapply</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="showButton" >
- <property name="text" >
- <string>Show</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>40</width>
- <height>31</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="okButton" >
- <property name="text" >
- <string>Close</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KUrlRequester</class>
- <extends>QFrame</extends>
- <header>kurlrequester.h</header>
- </customwidget>
- <customwidget>
- <class>KComboBox</class>
- <extends>QComboBox</extends>
- <header>kcombobox.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections>
- <connection>
- <sender>okButton</sender>
- <signal>clicked()</signal>
- <receiver>EditPatch</receiver>
- <slot>accept()</slot>
- <hints>
- <hint type="sourcelabel" >
- <x>278</x>
- <y>253</y>
- </hint>
- <hint type="destinationlabel" >
- <x>96</x>
- <y>254</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_editpatch.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui (nonexistent)
@@ -1,52 +0,0 @@
-<ui version="4.0" >
- <class>InDocumentContextLines</class>
- <widget class="QWidget" name="InDocumentContextLines" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>611</width>
- <height>137</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QGroupBox" name="groupBox" >
- <property name="font" >
- <font>
- <family>Sans Serif</family>
- <pointsize>9</pointsize>
- <weight>75</weight>
- <italic>false</italic>
- <bold>true</bold>
- <underline>false</underline>
- <strikeout>false</strikeout>
- </font>
- </property>
- <property name="title" >
- <string>Context-Lines:</string>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>2</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QTextEdit" name="contextLines" />
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentcontextlines.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.cpp (nonexistent)
@@ -1,29 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "verify.h"
-#include <sstream>
-
-ExpressionError::ExpressionError( const std::string& fun, int l, const std::string& f, const std::string& exp, const std::string& realExp ) : function( fun ), line( l ), file( f ), expression( exp ), realExpression( realExp ) {}
-
-std::string ExpressionError::what() const {
- std::ostringstream os;
- os << "DynamicTextError in" << function << "," << file << ":" << line;
- if ( !expression.empty() )
- os << ", expression \"" << expression << "\" failed";
- if ( !realExpression.empty() )
- os << ", values:" << realExpression;
- return os.str();
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/loglevel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/loglevel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/loglevel.h (nonexistent)
@@ -1,26 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef LOGLEVEL_H
-#define LOGLEVEL_H
-
-#include <QIcon>
-enum LogLevel {
- Info = 1,
- Warning = 2,
- Error = 4,
- Debug = 8
-};
-
-QIcon iconFromLevel( LogLevel lv );
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/loglevel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qtserialization.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qtserialization.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qtserialization.h (nonexistent)
@@ -1,133 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef QTSERIALIZATION_H
-#define QTSERIALIZATION_H
-
-#include "lib/network/serialization.h"
-#include <boost/serialization/split_free.hpp>
-#include <boost/serialization/level.hpp>
-#include <boost/serialization/binary_object.hpp>
-#include <QDataStream>
-#include <QTextStream>
-#include <QByteArray>
-#include <QVariant>
-#include <vector>
-#include <QString>
-#include <string>
-#include <iostream>
-
-namespace boost {
-namespace serialization {
-template <class Archive>
-void load( Archive & arch, QByteArray& b, const unsigned int /*version*/ ) {
- uint size;
- arch & size;
- b.resize( size );
-
- binary_object o( b.data(), b.size() );
- arch & o;
-}
-
-template <class Archive>
-void save( Archive & arch, const QByteArray& b, const unsigned int /*version*/ ) {
- uint size = b.size();
- arch & size;
- binary_object o( const_cast<QByteArray&>( b ).data(), b.size() );
- arch & o;
-}
-}
-}
-
-BOOST_SERIALIZATION_SPLIT_FREE( QByteArray )
-
-///Usually uses a QDataStream to convert to a binary object, and stores that.
-template <class Type>
-class QSerialize {
- Type& m_t;
- public:
- QSerialize( const Type& t ) : m_t( const_cast<Type&>( t ) ) {}
-
- template <class Archive>
- void save( Archive& arch, unsigned int /*version*/ ) const {
- QByteArray b;
- QDataStream s( &b, QIODevice::WriteOnly );
- s << m_t;
- arch & b;
- }
-
- template <class Archive>
- void load( Archive& arch, unsigned int /*version*/ ) {
- QByteArray b;
- arch & b;
-
- QDataStream s( &b, QIODevice::ReadOnly );
- s >> m_t;
- }
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-};
-
-/**This function returns a temporary serialization-object that can be used to serialize Qt-Types using the boost-serialization-library. */
-template <class Type>
-QSerialize<Type> qStore( const Type& t ) {
- return QSerialize<Type>( t );
-}
-
-namespace boost {
-namespace serialization {
-
-template <class Archive>
-void serialize( Archive & ar, QString& str, const unsigned int /*version*/ ) {
- QSerialize<QString> s( str );
- ar & s;
-}
-
-template <class Archive>
-void serialize( Archive & ar, QStringList& t, const unsigned int /*version*/ ) {
- QSerialize<QStringList> s( t );
- ar & s;
-}
-
-template <class Archive>
-void serialize( Archive & ar, QVariant& t, const unsigned int /*version*/ ) {
- QSerialize<QVariant> s( t );
- ar & s;
-}
-} // namespace serialization
-} // namespace
-
-///Tell boost not to store type-information for QSerialize<T>
-namespace boost {
-namespace serialization {
-template <class T>
-struct implementation_level< QSerialize<T> > {
- typedef mpl::integral_c_tag tag;
- typedef mpl::int_< object_serializable > type;
- BOOST_STATIC_CONSTANT(
- int,
- value = implementation_level::type::value
- );
-};
-}
-}
-
-BOOST_CLASS_IMPLEMENTATION(QString, object_serializable)
-BOOST_CLASS_IMPLEMENTATION(QStringList, object_serializable)
-BOOST_CLASS_IMPLEMENTATION(QVariant, object_serializable)
-BOOST_CLASS_IMPLEMENTATION(QByteArray, object_serializable)
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qtserialization.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.h (nonexistent)
@@ -1,137 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef COLLABORATIONMANAGER_H
-#define COLLABORATIONMANAGER_H
-
-#include "lib/network/safesharedptr.h"
-#include "filecollaborationmessages.h"
-#include "kdevteamwork.h"
-#include "utils.h"
-#include <QObject>
-#include <set>
-#include "safelogger.h"
-#include <QPointer>
-#include <memory>
-
-
-class QPoint;
-class QModelIndex;
-class QMenu;
-class QStandardItemModel;
-
-///These helpers can be used to plug own actions into the tree-structure of the collaboration-manager. To get active, a CollaborationTreeActionPointer must be set as the UserData-entry in the model.
-struct CollaborationTreeAction : public Shared {
- virtual void fillContextMenu( QMenu* menu ) = 0;
- virtual void doubleClicked() {
- }
- virtual void clicked() {
- }
-};
-
-///This class will call a fillContextMenu-function in the targetet-class
-template <class targetet, class ValueType = int>
-struct StandardCollaborationTreeAction : public CollaborationTreeAction {
- QPointer<targetet> target;
- ValueType var;
-
- StandardCollaborationTreeAction( targetet* t, const ValueType& v ) : var( v ), target( t ) {}
- StandardCollaborationTreeAction( targetet* t ) : target( t ) {}
-
- virtual void fillContextMenu( QMenu* menu ) {
- if ( target ) {
- target->fillContextMenu( var, menu );
- }
- };
-};
-
-typedef SharedPtr< CollaborationTreeAction > CollaborationTreeActionPointer;
-
-Q_DECLARE_METATYPE( CollaborationTreeActionPointer )
-
-using namespace Teamwork;
-class KDevTeamwork;
-class FileCollaborationManager;
-class FileCollaborationSession;
-typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
-
-using namespace std;
-
-class CollaborationManager : public QObject, public SafeLogger {
- Q_OBJECT
- public:
- CollaborationManager( KDevTeamwork* tw );
- ~CollaborationManager();
-
-
- void addCollaboratingUser( const UserPointer& u );
-
- void removeCollaboratingUser( const UserPointer& user );
-
- bool isCollaborating( const UserPointer& user );
-
- void updateList();
-
- void restorePartialProjectSession( const QDomElement* el );
-
- void savePartialProjectSession( QDomElement* el );
-
- void fillUserMenu( QMenu* menu, const UserPointer& user );
-
- FileCollaborationManager& fileCollaborationManager() ;
-
- QStandardItemModel* developersModel();
-
- KDevTeamwork* teamwork();
- signals:
- void fillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
- void updateModel( QStandardItemModel* model );
-
- public slots:
- void maybeContextMenu();
- void init();
- void collaboratingDeveloperClicked( const QModelIndex& i );
- void collaboratingDeveloperDoubleClicked( const QModelIndex& i );
- void collaboratingDeveloperContextMenu( const QPoint& );
- void uiCloseCollaboration();
- void updateConnection( const TeamworkClientPointer& );
- void processMessage( const CollaborationMessagePointer& );
- void sessionStateChanged( const FileCollaborationSessionPointer& session );
-
- void uiAcceptCollaboration();
- void uiDenyCollaboration();
- void uiRequestCollaboration();
-
- private:
- void contextMenu( const QPoint& pos, const QModelIndex& index );
- friend class ConnectionRequest;
- KDevTeamwork* m_teamwork;
- typedef set
- <UserPointer> UserSet;
- UserSet m_collaboratingUsers;
- AutoConstructPointer<FileCollaborationManager> m_fileCollaboration;
- QStandardItemModel* m_developersModel; ///Model for the collaborating-developers tree-view
- auto_ptr<QPersistentModelIndex> m_contextMenuIndex; ///Only used for the timer
-
- QAction* m_requestCollaborationAction;
- QAction* m_closeCollaborationAction;
- QAction* m_acceptConnectionAction;
- QAction* m_denyConnectionAction;
-
- QTimer* m_contextMenuTimer;
- bool m_ignoreClick;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.h (nonexistent)
@@ -1,26 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVUTILS_H
-#define KDEVUTILS_H
-#include <QString>
-
-/** Returns the path of the current document,
- * relative to the workspace-directory.
- *
- * Throws a QString on error */
-QString currentDocumentPath();
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.h (nonexistent)
@@ -1,187 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef DOCUMENT_WRAPPER_H
-#define DOCUMENT_WRAPPER_H
-
-#include <QObject>
-#include <QFile>
-
-#include <KParts/MainWindow>
-#include <map>
-#include <string>
-
-#include "lib/dynamictext/vectortimestamp.h"
-#include "lib/dynamictext/flexibletextnotifier.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/weaksafesharedptr.h"
-#include "safelogger.h"
-
-#include <autoconstructpointer.h>
-#include "filesynchronizemessage.h"
-
-namespace Teamwork {
-class Logger;
-typedef SafeSharedPtr<Logger> LoggerPointer;
-}
-
-namespace KTextEditor {
-class Document;
-class Range;
-}
-
-class FileSynchronize;
-class DynamicText;
-class QStandardItemModel;
-class QModelIndex;
-class QMenu;
-class QVariant;
-class DocumentWrapperTreeAction;
-namespace KDevelop {
-class IDocument;
-}
-class DocumentWrapperMessage;
-class QDynamicText;
-class FileCollaborationSession;
-class LocalPatchSource;
-class K3Process;
-
-using namespace Teamwork;
-
-typedef SafeSharedPtr<LocalPatchSource> LocalPatchSourcePointer;
-typedef SharedPtr<QDynamicText, BoostSerializationNormal> QDynamicTextPointer;
-
-class OutputFileWriter : public QObject {
- Q_OBJECT
- public:
- OutputFileWriter( const QString& file );
- bool failed() const;
- public slots:
- void receivedStdout(K3Process *proc, char *buffer, int buflen);
- private:
- QFile m_file;
- bool m_failed;
-};
-
-///A class that cares about the state of a document and it's history
-class DocumentWrapper : public QObject, public SafeLogger, public Shared, public SumTree::FlexibleTextNotifier<std::string> {
- Q_OBJECT
- public:
- ///If readFile is true, the file is read from disk. Else we wait for the file from the other side. May throw QString on error.
- BIND_LIST_3( Messages, FileEditMessage, FileEditRejectMessage, FileSynchronize )
-
- DocumentWrapper( uint id, const LoggerPointer& logger, QString fileName, uint ownIndex, bool readFile, FileCollaborationSession* session, bool fromBuffer );
-
- QString fileName() const;
-
- KDevelop::IDocument* document();
-
- void updateTree( QModelIndex& i, QStandardItemModel* model );
-
- void fillContextMenu( int var, QMenu* menu );
-
- bool hadError() const;
-
- QString text() const;
-
- VectorTimestamp state() const;
-
- const QDynamicText& dynamicText() const;
-
- ///Returns an id that is unique within the wrapper's parent-session, and is equal on all collaborating peers.
- uint id() const;
-
- void processMessage( DocumentWrapperMessage* msg );
-
- ///If the document-wrapper is dead, that means the it is not part of the session anymore
- void setDead( bool dead );
-
- bool dead() const;
- ///This can be usedto completely disable the file(no editing is allowed anymore)
- void setDisabled( bool disabled );
-
- bool disabled() const;
-
- QIcon icon() const;
-
- bool synchronize( const UserPointer& user );
-
- signals:
- void publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender );
-
- public slots:
- void saveAsBufferFile();
- LocalPatchSourcePointer saveAsPatch( bool addToList = true, bool edit = true );
-
- private slots:
- void remove();
- void toggleEnabled();
- void saveNewBuffer();
- void manageDynamicText();
-
- void stateChanged();
- void documentDestroyed();
- void textChanged ( KTextEditor::Document * document,
- const KTextEditor::Range & oldRange,
- const KTextEditor::Range & newRange );
- void textRemoved ( KTextEditor::Document * document,
- const KTextEditor::Range & range );
- void textInserted ( KTextEditor::Document * document,
- const KTextEditor::Range & range );
- private:
- ///Notifications from FlexibleText
- virtual void notifyFlexibleTextErase( int position, int length );
- virtual void notifyFlexibleTextInsert( int position, const std::string& text );
- virtual void notifyFlexibleTextReplace( int position, int length, const std::string& replacement );
-
-
- int receiveMessage( FileEditMessage* msg );
- int receiveMessage( FileSynchronize* msg );
- int receiveMessage( FileEditRejectMessage* msg );
- int receiveMessage( MessageInterface* msg );
-
- bool checkDocumentSync() const; ///Expensive, only for debugging
-
- void fillDocumentText();
- void openDocument( bool toForeground = false );
-
- ///If fromBuffer is true, it is tried to get the content from an already open buffer (@todo)
- void readFile( bool fromBuffer ) throw ( QString );
-
- virtual std::string logPrefix();
-
- QDynamicTextPointer m_text;
-
- bool m_block;
-
- bool m_realFile;
- QString m_fileName; ///Relative path of the file(from project-dir)
- KDevelop::IDocument* m_document;
- WeakSharedPtr<FileCollaborationSession> m_session;
- uint m_ownIndex;
- uint m_id;
- bool m_hadError, m_disabled, m_dead;
-
- QString m_tempFile;
-
- friend class DocumentWrapperTreeAction;
-
- friend class MessageDispatcher< DocumentWrapper, Messages > ;
- MessageDispatcher< DocumentWrapper, Messages > m_dispatcher;
-};
-
-typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp (nonexistent)
@@ -1,283 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "filecollaboration.h"
-#include <QAction>
-#include <QMenu>
-#include <QFileInfo>
-#include <QStandardItemModel>
-#include <QModelIndex>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/cursor.h>
-
-#include "filecollaborationmanager.h"
-#include "kdevteamwork_user.h"
-#include "kdevutils.h"
-#include "documentwrapper.h"
-#include "kdevteamwork_helpers.h"
-
-#include "lib/dynamictext/verify.h"
-#include "lib/network/messagesendhelper.h"
-#include "lib/network/messagetypeset.h"
-
-
-
-FileCollaboration::FileCollaboration( KDevTeamworkUserPointer user, FileCollaborationSession* session, const FileCollaborationRequestPointer& request ) : SafeLogger( session->manager() ->teamwork() ->logger() ), m_user( user ), m_session( session ), /*m_dispatcher( *this ),*/ m_index( 0 ), m_connectionActive( false ), m_userConnected( false ), m_invited( false ) {
- connect( session->manager(), SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
-
- KDevTeamworkUserPointer::Locked l = user;
- if ( !l )
- throw QString( "in FileCollaboration(): could not lock user" );
-
- connect( l.data(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
-
- m_userName = ~l->User::name();
-
- if ( !l->online().session() )
- throw QString( "in FileCollaboration(): user is not online" );
-
- if ( !request ) {
- m_index = session->allocateIndex(); ///Create a new index
- } else {
- FileCollaborationRequestPointer::Locked lr = request;
- if ( !lr )
- throw QString( "could not lock request-message" );
- m_index = lr->senderIndex(); ///The other side is the master, so the index is zero.
- }
-
- invite( request, false );
-}
-
-uint FileCollaboration::primaryIndex() const {
- return m_index;
-}
-
-std::string FileCollaboration::logPrefix() {
- return ~( "FileCollaboration(" + m_userName + ", " + m_session->name() + "): " );
-}
-
-void FileCollaboration::processMessage( const MessagePointer& msg ) {
- MessagePointer::Locked l = msg;
- if ( l ) {
- //m_dispatcher( l );
- } else {
- err() << "could not lock a message";
- }
-}
-/*
-int FileCollaboration::receiveMessage( MessageInterface* msg ) {
- out( Logger::Warning ) << "got unknown message of type" << msg->name();
- return 0;
-}
-
-int FileCollaboration::receiveMessage( FileCollaborationMessage* msg ) {
- ///@todo clean/remove
- out( Logger::Debug ) << "got FileCollaborationMessage";
- if ( msg->isDerived() ) {
- out( Logger::Warning ) << "dispatched a message of type" << msg->name() << "as FileCollaborationMessage";
- return 0;
- }
- try {
- switch ( msg->message() ) {
- case FileCollaborationMessageData::Synchronize: {
- if ( !msg->messageData().canConvert<QString>() )
- throw "wrong messageData in Synchronize-request(cannot extract filename)";
- QString fileName = msg->messageData().value<QString>();
-
- KDevTeamworkUserPointer::Locked l = m_user;
- if ( !l )
- throw "could not lock user";
-
- if ( !l->online().session() )
- throw "user is not online";
-
- if ( !l->online().session().unsafe() ->isOk() )
- throw "user is not online, session is dead";
-
- }
- break;
- default:
- out( Logger::Warning ) << "got unhandled FileCollaborationMessage with message" << msg->messageAsString();
- break;
- }
- } catch ( const QString & str ) {
- err() << "in receiveMessage( FileCollaborationMessage* ):" << str;
- } catch ( const char * str ) {
- err() << "in receiveMessage( FileCollaborationMessage* ):" << str;
- }
- return 0;
-}
-
-int FileCollaboration::receiveMessage( FileCollaborationRequest* msg ) {
- out( Logger::Debug ) << "got FileCollaborationRequest";
- return 0;
-}*/
-
-bool FileCollaboration::connectionActive() const {
- return m_connectionActive;
-}
-
-void FileCollaboration::userStateChanged() {
- try {
- KDevTeamworkUserPointer::Locked l = m_user;
- if ( !l )
- throw "could not lock user";
-
- if ( l->online() && l->online().session().unsafe() ->isOk() ) {
- if ( !m_userConnected ) {
- ///Automatically re-invite the user to connect
- invite( 0, true );
- }
- } else {
- m_connectionActive = false;
- m_userConnected = false;
-
- emit connectionResult( this, false );
- }
- } catch ( const QString & str ) {
- err() << "error in userStateChanged():" << str;
- } catch ( const char * str ) {
- err() << "error in userStateChanged():" << str;
- }
-}
-
-void FileCollaboration::slotConnectionResult( bool result ) {
- out( Logger::Debug ) << "slotConnectionResult" << result;
- m_userConnected = result;
- if ( result )
- m_connectionActive = true;
- else
- m_connectionActive = false;
- emit connectionResult( this, result );
-}
-
-KDevTeamworkUserPointer FileCollaboration::user() const {
- return m_user;
-}
-
-FileCollaborationSessionPointer FileCollaboration::session() const {
- return m_session;
-}
-
-void FileCollaboration::slotFillCollaboratingUserMenu( QMenu * /*menu*/, const UserPointer & /*user*/ ) {}
-
-bool FileCollaboration::invited() const {
- return m_invited;
-}
-
-void FileCollaborationUserTreeAction::doubleClicked() {
- if ( target )
- target->doubleClicked();
-}
-
-void FileCollaborationUserTreeAction::fillContextMenu( QMenu* menu ) {
- if ( target )
- target->fillContextMenu( var, menu );
-}
-
-void FileCollaboration::fillContextMenu( int /*i*/, QMenu* menu ) {
- KDevTeamwork::self()->fillUserMenu( menu, user().cast<User>() );
- if( m_session->isMasterSession() ) {
- menu->addAction( m_session->getRemoveUserAction( m_user.cast<User>() ) );
- menu->addSeparator();
- }
-}
-
-void FileCollaboration::doubleClicked() {
- if ( m_user ) {
- KDevTeamwork::self() ->guiSendMessageTo( m_user );
- }
-}
-
-void FileCollaboration::invite( const FileCollaborationRequestPointer& request, bool automatic ) throw( QString ) {
- KDevTeamworkUserPointer::Locked l = m_user;
- if ( !l )
- throw QString( "in FileCollaboration(): could not lock user" );
-
- LockedSharedPtr<FileCollaborationRequest> lmsg = new FileCollaborationRequest( globalMessageTypeSet(), this, m_index, m_session->primaryIndex(), m_session->id() );
- if ( !lmsg )
- throw QString( "in FileCollaboration(): could not create message" );
-
- Q_VERIFY_SAME( lmsg->sessionId(), m_session->id() );
- Q_VERIFY_SAME( lmsg->index(), m_index );
-
- if ( automatic ) {
- if ( m_index != 0 ) {
- out( Logger::Info ) << "re-inviting user to join the session";
- } else {
- out( Logger::Info ) << "inviting session-host to continue the session";
- }
-
- lmsg->setAutomatic( true );
- }
-
- m_request = lmsg.freeCast<FileCollaborationRequest>();
-
-
- if ( request ) {
- ///When answering to a request, this will tell the other side that the request was accepted.
- LockedSharedPtr<FileCollaborationRequest> lrequest = request;
- if ( !lrequest )
- throw QString( "in FileCollaboration(): could not lock request" );
-
- lmsg->info().setReply( lrequest->info().uniqueId() );
- lmsg->info().setReplyMessage( request );
- } else {
- m_invited = true;
- }
- l->online().session().unsafe() ->send( lmsg );
-
- if ( !request && !automatic ) {
- m_session->manager() ->teamwork() ->addMessageToList( lmsg.data() );
- }
-
-}
-
-void FileCollaboration::close( const QString & /*reason*/ ) {
- KDevTeamworkUserPointer::Locked l = m_user;
- if ( l && l->online().session() ) {
- l->online().session().unsafe()->send( new FileCollaborationMessage( globalMessageTypeSet(), m_session->id(), FileCollaborationMessageData::CloseSession ) );
- }
-}
-
-QIcon FileCollaboration::icon() const {
- if( m_connectionActive ) {
- KDevTeamworkUserPointer::Locked l = m_user;
- if( l )
- return l->icon();
- else
- return QIcon();
- } else
- return IconCache::getIconStatic( "fileusercollaboration_inactive" );
-}
-
-void FileCollaboration::updateTree( QModelIndex& i, QStandardItemModel* model ) {
- KDevTeamworkUserPointer::Locked l = user();
- if ( !l ) {
- model->setData( i, "lost user", Qt::DisplayRole );
- model->setData( i, QIcon(), Qt::DecorationRole ); ///Maybe use some other icons indicating the state of the collaboration
- } else {
- model->setData( i, ~l->User::name(), Qt::DisplayRole );
- model->setData( i, icon(), Qt::DecorationRole ); ///Maybe use some other icons indicating the state of the collaboration
- QVariant v;
- v.setValue<CollaborationTreeActionPointer>( new FileCollaborationUserTreeAction( this ) );
- model->setData( i, v, Qt::UserRole );
- }
-}
-
-
-#include "filecollaboration.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp (nonexistent)
@@ -1,112 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "kdevteamwork_helpers.h"
-#include <QIcon>
-#include <kiconloader.h>
-#include "lib/network/messagetypeset.h"
-
-IconCache* IconCache::m_instance = 0;
-
-
-IconCache::IconCache() {
- ///Here, the appropriate icon-names can be chosen by mapping
- m_instance = this;
- maps_[ "unknown" ] = "unknown";
- maps_[ "text_message_in" ] = "mail-receive";
- maps_[ "text_message_out" ] = "mail-send";
-
- maps_[ "document_message_in" ] = "folder_inbox";
- maps_[ "document_message_out" ] = "folder_outbox";
-
- maps_[ "generalrequest_in" ] = "bookmarks";
- maps_[ "generalrequest_out" ] = "tools-wizard";
- maps_[ "generalrequest_in_denied" ] = "fileclose";
- maps_[ "generalrequest_in_accepted" ] = "dialog-ok";
- maps_[ "generalrequest_out_denied" ] = "fileclose";
- maps_[ "generalrequest_out_accepted" ] = "dialog-ok";
- maps_[ "generalrequest_out_failed" ] = "remove";
- maps_[ "generalrequest_in_failed" ] = "remove";
-
- maps_[ "collaborationrequest_in" ] = "bookmarks";
- maps_[ "collaborationrequest_out" ] = "tools-wizard";
- maps_[ "collaborationrequest_accepted" ] = "dialog-ok";
- maps_[ "collaborationrequest_denied" ] = "fileclose";
- maps_[ "collaborationrequest_in_denied" ] = "fileclose";
- maps_[ "collaborationrequest_in_accepted" ] = "dialog-ok";
- maps_[ "collaborationrequest_out_denied" ] = "fileclose";
- maps_[ "collaborationrequest_out_accepted" ] = "dialog-ok";
- maps_[ "collaborationrequest_out_failed" ] = "remove";
- maps_[ "collaborationrequest_in_failed" ] = "remove";
-
- maps_[ "collaboration_file" ] = "completion";
- maps_[ "collaboration_file_disabled" ] = "remove";
- maps_[ "collaboration_file_dead" ] = "fileclose";
- maps_[ "collaboration_session" ] = "system-switch-user";
- maps_[ "collaboration_session_finished" ] = "remove";
- maps_[ "collaboration_session_connectionlost" ] = "fileclose";
-
- maps_[ "filecollaborationrequest_in" ] = "bookmarks";
- maps_[ "filecollaborationrequest_out" ] = "tools-wizard";
- maps_[ "filecollaborationrequest_accepted" ] = "dialog-ok";
- maps_[ "filecollaborationrequest_denied" ] = "fileclose";
- maps_[ "filecollaborationrequest_in_denied" ] = "fileclose";
- maps_[ "filecollaborationrequest_in_accepted" ] = "dialog-ok";
- maps_[ "filecollaborationrequest_out_denied" ] = "fileclose";
- maps_[ "filecollaborationrequest_out_accepted" ] = "dialog-ok";
- maps_[ "filecollaborationrequest_out_failed" ] = "remove";
- maps_[ "filecollaborationrequest_in_failed" ] = "remove";
- maps_[ "filecollaborationrequest_in_failed" ] = "remove";
- maps_[ "fileusercollaboration_inactive" ] = "presence_unknown";
-
- maps_[ "patch" ] = "text-x-generic";
- maps_[ "failed" ] = "fileclose";
-
- maps_[ "error" ] = "stop";
-}
-
-void SafeTeamworkEmitter::updateMessageInfo( const MessagePointer& msg ) {
- emit signalUpdateMessageInfo( msg );
-}
-
-QIcon IconCache::operator () ( const QString& name, KIconLoader::Group grp ) {
- return getIcon( name, grp );
-}
-
-QIcon IconCache::getIconStatic( QString name, KIconLoader::Group grp ) {
- return IconCache::instance() ->getIcon( name, grp );
-}
-
-QIcon IconCache::getIcon( QString name, KIconLoader::Group grp ) {
- {
- QMap<QString, QString>::iterator it = maps_.find( name );
-
- if ( it != maps_.end() )
- name = *it;
- }
-
- QPair<QString, KIconLoader::Group> pos( name, grp );
- IconMap::iterator it = m_icons.find( pos );
- if ( it != m_icons.end() ) {
- return * it;
- } else {
- m_icons[ pos ] = QIcon( KIconLoader::global() ->loadIcon( name, grp ) );
- return m_icons[ pos ];
- }
-}
-
-IconCache* IconCache::instance() {
- return m_instance;
-}
-
-
-#include "kdevteamwork_helpers.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp (nonexistent)
@@ -1,789 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "filecollaborationsession.h"
-
-Q_DECLARE_METATYPE( Teamwork::UserPointer )
-
-#include <sstream>
-#include <QAction>
-#include <QMenu>
-#include <QTimer>
-#include <QStandardItemModel>
-#include <QModelIndex>
-
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-
-#include <krandom.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/cursor.h>
-
-#include "lib/network/messagesendhelper.h"
-#include "lib/network/messagetypeset.h"
-
-#include "filecollaborationmanager.h"
-#include "lib/dynamictext/vectortimestamp.h"
-#include "kdevteamwork_user.h"
-#include "kdevteamworkplugin.h"
-#include "documentwrapper.h"
-#include "patchesmanager.h"
-#include "kdevteamwork_helpers.h"
-
-
-#include "filesynchronizemessage.h"
-#include "teamworkfoldermanager.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-using namespace KDevelop;
-
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationPointer, FileCollaborationPointer, 0, value )
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationPointer, UserPointer, 0, value->user() )
-
-CROSSMAP_KEY_EXTRACTOR( DocumentWrapperPointer, QString, 0, value->fileName() )
-CROSSMAP_KEY_EXTRACTOR( DocumentWrapperPointer, uint, 0, value->id() )
-
-FileCollaborationSession::FileCollaborationSession( QString name, CollabFileList files, FileCollaborationManager* manager, uint primaryIndex, CollabSessionId id ) :
- SafeLogger( manager->teamwork() ->logger(), "in FileCollaborationSession:" ),
- m_manager( manager ),
- m_allowSentDocuments( false ),
- m_isMasterSession( primaryIndex == 0 ),
- m_primaryIndex( primaryIndex ),
- m_indexCount( primaryIndex ? 0 : 1 ),
- m_wrapperIndexCount( primaryIndex ? 0 : 1 ),
- m_name( name ),
- m_dispatcher( *this ) {
- m_publishFileListTimer = new QTimer( this );
- connect( m_publishFileListTimer, SIGNAL( timeout() ), this, SLOT( slotPublishFileList() ) );
- m_publishFileListTimer->setSingleShot( true );
- m_stateChangeTimer = new QTimer( this );
- connect( m_stateChangeTimer, SIGNAL( timeout() ), this, SLOT( publishStateChange() ) );
- m_publishFileListTimer->setSingleShot( true );
-
- connect( m_manager, SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
-
- m_removeUserAction = new QAction( IconCache::getIconStatic( "remove" ), "Remove User", this );
- connect( m_removeUserAction, SIGNAL( triggered( bool ) ), this, SLOT( removeUserAction() ) );
-
- if ( id != 0 )
- m_id = id;
- else {
- QString str = KRandom::randomString( 8 ).toLatin1();
- m_id = *( ( CollabSessionId* ) & ( str.toAscii().data() [ 0 ] ) ); ///Not a good way of generating a 64-bit random-number..
- }
-
- out( Logger::Debug ) << "starting session";
-
- for ( CollabFileList::iterator it = files.begin(); it != files.end(); ++it ) {
- addFileInternal( *it, true, m_isMasterSession );
- }
-
-}
-
-void FileCollaborationSession::slotConnectionResult( FileCollaboration* collab, bool result ) {
- if ( result && collab->invited() ) {
- for ( FileSet::Iterator it = m_files.values(); it; ++it ) {
- synchronizeFile( collab, *it );
- }
- }
-
- emit stateChanged( this );
-}
-
-void FileCollaborationSession::setAllowSentDocuments( bool allow ) {
- m_allowSentDocuments = allow;
-}
-
-
-bool FileCollaborationSession::synchronizeFile( const FileCollaborationPointer& collab, const DocumentWrapperPointer& wrapper ) {
- return wrapper->synchronize( collab->user() );
-}
-
-QStringList FileCollaborationSession::plainFileNames() const {
- QStringList ret;
- for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it )
- ret << ( *it ).second.value->fileName();
- return ret;
-}
-
-QList<uint> FileCollaborationSession::plainIds() const {
- QList<uint> ret;
- for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it )
- ret << ( *it ).second.value->id();
- return ret;
-}
-
-void FileCollaborationSession::removeUserAction() {
- try {
- QAction* act = qobject_cast<QAction*>( sender() );
- if( !act ) throw "no sender-action";
-
- QVariant v = act->data();
- UserPointer u = v.value<UserPointer>();
- if( !u ) throw "could not get user";
-
- FileCollaborationPointer collab = m_collaborations.value( u );
- if( !collab ) throw "no file-collaboration for the specified user";
-
- removeCollaboration( collab );
- } catch( const char* str ) {
- err() << "removeUserAction:" << str;
- } catch( const QString& str ) {
- err() << "removeUserAction:" << str;
- }
-}
-
-void FileCollaborationSession::removeCollaboration( const FileCollaborationPointer& collab ) {
- collab->close( "goodbye" );
- m_collaborations.remove( collab );
- emit stateChanged( this );
-}
-
-
-CollabFileList FileCollaborationSession::fileNames() const {
- CollabFileList ret;
- for ( FileSet::ValueMap::const_iterator it = m_files.begin(); it != m_files.end(); ++it ) {
- ret.push_back( CollabFile( ( *it ).second.value->id(), ( *it ).second.value->fileName() ) );
- }
- return ret;
-}
-
-const FileCollaborationSession::FileSet& FileCollaborationSession::files() const {
- return m_files;
-}
-
-
-void FileCollaborationSession::fillContextMenu( int /*i*/, QMenu* menu ) {
- IDocument * d = KDevTeamworkPlugin::staticDocumentController() ->activeDocument();
- if ( d && d->textDocument() ) {
- KUrl u = TeamworkFolderManager::workspaceRelative( d->url() );
-
- if ( !m_files.values( u.toLocalFile() ) )
- menu->addAction( "Add Current File", this, SLOT( addFile() ) );
- }
- QMenu* m = new QMenu( menu );
- m->setTitle( "Save Result" );
- m->addAction( "As Files", this, SLOT( saveAsFiles() ) );
- m->addAction( "As Patch", this, SLOT( saveAsPatch() ) );
- menu->addSeparator();
- FileSet::Iterator it = m_files.values();
- if ( m_isMasterSession && it ) {
- while ( it && ( *it ) ->dead() )
- ++it;
- if ( it ) {
- if ( ( *it ) ->disabled() )
- menu->addAction( "Enable Editing", this, SLOT( enableEditing() ) );
- else
- menu->addAction( "Disable Editing", this, SLOT( disableEditing() ) );
- }
- }
- m = new QMenu( menu );
- m->setTitle( "Remove" );
- m->addAction( "All Users", this, SLOT( stopSession() ) );
- m->addAction( "All Files", this, SLOT( removeAllFilesSession() ) );
- menu->addSeparator();
- menu->addAction( "Close", this, SLOT( closeSession() ) );
-}
-
-bool FileCollaborationSession::acceptMessage( const FileCollaborationRequestPointer& msg ) {
- try {
- FileCollaborationRequestPointer::Locked l = msg;
- if ( !l )
- throw "could not lock message";
-
- KDevTeamworkUserPointer u = l->info().user().cast<KDevTeamworkUser>();
- if ( !u )
- throw "message has no user";
-
- FileCollaborationPointer collab = newCollaboration( u, msg );
- if ( !collab )
- throw "could not create collaboration";
-
- return true;
- } catch ( const QString & str ) {
- err() << "error in acceptMessage:" << str;
- return false;
- } catch ( const char * str ) {
- err() << "error in acceptMessage:" << str;
- return false;
- }
- return false;
-}
-
-DocumentWrapperPointer FileCollaborationSession::getDocument( const QString& fileName ) {
- if ( ! m_files.values( fileName ) ) {
- out( Logger::Warning ) << "getDocument: Document-wrapper for a file not being collaborated was requested:" << fileName;
- return 0;
- }
-
- return m_files[ fileName ];
-}
-
-std::string FileCollaborationSession::logPrefix() {
- ostringstream str;
- str << "FileCollaborationSession(" << name() << "," << id() << "): ";
- return str.str();
-}
-
-FileCollaborationPointer FileCollaborationSession::newCollaboration( const KDevTeamworkUserPointer & u, const FileCollaborationRequestPointer& request ) {
- try {
- FileCollaborationPointer ret = new FileCollaboration( u, this, request );
- connect( ret, SIGNAL( connectionResult( FileCollaboration*, bool ) ), this, SLOT( slotConnectionResult( FileCollaboration*, bool ) ) );
- m_collaborations.insert( ret );
- return ret;
- } catch ( const QString & str ) {
- err() << "error while creating file-collaboration:" << str;
- return 0;
- }
-}
-
-void FileCollaborationSession::updateTree( QModelIndex& i, QStandardItemModel* model ) {
- QMap<DocumentWrapperPointer, QPersistentModelIndex> positions;
- QMap<FileCollaborationPointer, QPersistentModelIndex> userPositions;
- try {
- if ( model->columnCount( i ) == 0 )
- model->insertColumn( 0, i );
- ///Locate all files that are already there
- for ( int a = model->rowCount( i ) - 1; a >= 0; a-- ) {
- QModelIndex ind = model->index( a, 0, i );
- QVariant v = model->data( ind, Qt::UserRole );
- if ( v.canConvert<CollaborationTreeActionPointer>() ) {
- StandardCollaborationTreeAction<DocumentWrapper>* d = dynamic_cast< StandardCollaborationTreeAction<DocumentWrapper>* >( v.value<CollaborationTreeActionPointer>().data() );
- if ( d && d->target ) {
- if ( m_files.values<DocumentWrapperPointer>( ( DocumentWrapper* ) d->target ) ) {
- positions[ ( DocumentWrapper* ) d->target ] = ind;
- } else {
- ///Remove the old item
- model->removeRow( a, i );
- }
- }
- FileCollaborationUserTreeAction * userAction = dynamic_cast< FileCollaborationUserTreeAction* >( v.value<CollaborationTreeActionPointer>().data() );
- if( userAction ) {
- if( userAction->target && m_collaborations.value( (FileCollaborationPointer)userAction->target ) ) {
- ///user is still collaborating
- userPositions[(FileCollaborationPointer)userAction->target] = ind;
- } else {
- ///User must be removed
- model->removeRow( a, i );
- }
- }
- } else {
- model->removeRow( a, i );
- err() << "unexepected entry-type in tree, removing";
- }
- }
- ///Add missing files
- for ( FileSet::ValueMap::iterator it = m_files.begin(); it != m_files.end(); ++it ) {
- if ( !positions.contains( ( *it ).second.value ) ) {
- model->insertRow( 0, i ); ///Documents are inserted at the top, users at the bottom.
- QModelIndex ind = model->index( 0, 0, i );
- ;
- if ( !ind.isValid() )
- throw "index-error";
- positions[ ( *it ).second.value ] = ind;
- }
- }
-
- ///Add missing users
- for( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
- if ( !userPositions.contains( *it ) ) {
- int num = model->rowCount( i );
- model->insertRow( num, i );
- QModelIndex ind = model->index( num, 0, i );
-
- if ( !ind.isValid() )
- throw "index-error";
- userPositions[ *it ] = ind;
- }
- }
-
- ///Update documents
- for ( QMap<DocumentWrapperPointer, QPersistentModelIndex>::iterator it = positions.begin(); it != positions.end(); ++it ) {
- QModelIndex i( *it );
- const_cast<DocumentWrapperPointer&>( it.key() ) ->updateTree( i, model );
- }
-
- ///Update users
- for ( QMap<FileCollaborationPointer, QPersistentModelIndex>::iterator it = userPositions.begin(); it != userPositions.end(); ++it ) {
- QModelIndex i(*it);
- it.key()->updateTree( i , model );
-
- }
-
- } catch ( const char * str ) {
- err() << "in updateTree:" << str;
- } catch ( const QString & str ) {
- err() << "in updateTree:" << str;
- }
-}
-
-QIcon FileCollaborationSession::icon() const {
- if ( state() == Finished )
- return IconCache::getIconStatic( "collaboration_session_finished" );
- else {
- if ( !m_isMasterSession ) {
- CollaborationSet::Iterator it = m_collaborations.values();
- if ( !( *it ) ->connectionActive() )
- return IconCache::getIconStatic( "collaboration_session_connectionlost" );
- }
- return IconCache::getIconStatic( "collaboration_session" );
- }
-}
-
-bool FileCollaborationSession::isMasterSession() const {
- return m_isMasterSession;
-}
-
-uint FileCollaborationSession::primaryIndex() const {
- return m_primaryIndex;
-}
-
-FileCollaborationSession::State FileCollaborationSession::state() const {
- if ( !m_collaborations.empty() )
- return Running;
- return Finished;
-}
-
-bool FileCollaborationSession::removeFile( uint id ) {
- DocumentWrapperPointer wrapper = m_files[ id ];
- if ( !wrapper )
- return false;
- ///@todo ask if content should be saved or if the file should stay completely
- m_files.remove( wrapper );
-
- publishFileRemove( id );
- m_stateChangeTimer->start( 100 );
- return true;
-}
-
-bool FileCollaborationSession::killFile( uint id ) {
- DocumentWrapperPointer wrapper = m_files[ id ];
- if ( !wrapper )
- return false;
- ///@todo ask if content should be saved or if the file should stay completely
- wrapper->setDisabled( true );
- wrapper->setDead( true );
-
- m_stateChangeTimer->start( 100 );
- return true;
-}
-
-uint FileCollaborationSession::addFileInternal( const CollabFile& f, bool fromBuffer, bool readFile ) {
- try {
- if ( f.id > m_wrapperIndexCount )
- m_wrapperIndexCount = f.id + 1;
- QString file = f.file;
- /*if ( KDevCore::projectController() ->activeProject() ) {
- KUrl u( file );
-
- if ( u.isParentOf( KDevCore::projectController() ->activeProject() ->projectDirectory() ) ) {
- QString d = KDevCore::projectController() ->activeProject() ->projectDirectory().toLocalFile();
- if( !d.endsWith( "/" ) ) d += "/";
- file = KUrl::relativeUrl( d, u );
- }
- }*/
-
- DocumentWrapperPointer p = new DocumentWrapper( f.id, m_manager->teamwork() ->logger(), file, m_primaryIndex, readFile, this, fromBuffer );
- connect( p.data(), SIGNAL( publishEdit( const VectorTimestamp&, const SimpleReplacement&, DocumentWrapper* ) ), this, SLOT( publishEdit( const VectorTimestamp&, const SimpleReplacement&, DocumentWrapper* ) ) );
- m_files.insert( p );
- m_publishFileListTimer->start( 100 );
- m_stateChangeTimer->start( 100 );
- return f.id;
- } catch ( const QString & str ) {
- err() << "failed to create document-wrapper for" << f.file << ":" << str;
- return 0;
- }
-}
-
-void FileCollaborationSession::saveAsFiles() {
- FileSet::Iterator it = m_files.values();
- while ( it ) {
- ( *it ) ->saveAsBufferFile();
-
- ++it;
- }
-}
-
-void FileCollaborationSession::saveAsPatch() {
- FileSet::Iterator it = m_files.values();
- QList<LocalPatchSourcePointer> patches;
- while ( it ) {
-
- LocalPatchSourcePointer p = ( *it ) ->saveAsPatch( false, false );
-
- ++it;
- }
-
- QString patchName = name();
-
- if ( !m_isMasterSession ) {
- CollaborationSet::Iterator it = m_collaborations.values();
- if ( ( *it ) ->user() )
- patchName += "@" + ~( *it ) ->user().unsafe() ->safeName() + "_" + QDateTime::currentDateTime().toString( Qt::ISODate );
- }
-
- LocalPatchSourcePointer p = manager() ->teamwork() ->patchesManager() ->merge( patchName, patches );
- if ( p ) {
- manager() ->teamwork() ->patchesManager() ->addPatch( p );
- } else {
- err() << "could not merge the file-patches to one";
- }
-}
-void FileCollaborationSession::addFile() {
- try {
- IDocument * document = KDevTeamworkPlugin::staticDocumentController() ->activeDocument();
- Q_ASSERT( document != 0 );
- Q_ASSERT( document->textDocument() != 0 );
-
- KUrl u = TeamworkFolderManager::workspaceRelative( document->url() );
-
- out( Logger::Debug ) << "adding" << u.toLocalFile() << "to the session";
-
- uint index = allocateWrapperIndex();
- QString fileName = TeamworkFolderManager::teamworkRelative( u );
-
- if ( !addFileInternal( CollabFile( index, fileName ), true, true ) )
- throw "could not add file " + u.toLocalFile();
-
- DocumentWrapperPointer wrapper = m_files[ index ];
- if ( !wrapper )
- throw "could not get document-wrapper for " + fileName;
-
- ///Synchronize the newly created file
- for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it )
- synchronizeFile( *it, wrapper );
-
-
- } catch ( const QString & str ) {
- err() << "addFile():" << str;
- } catch ( const char * str ) {
- err() << "addFile():" << str;
- }
-}
-
-void FileCollaborationSession::stopSession() {
- out() << "stopping session, disconnecting all users";
- CollaborationSet::Iterator it = m_collaborations.values();
- while ( it ) {
- it.edit() ->data() ->close( "stop" );
- ++it;
- }
- m_collaborations.clear();
-
- emit stateChanged( this );
-}
-
-void FileCollaborationSession::disableEditing() {
- FileSet::Iterator it = m_files.values();
- while ( it ) {
- if ( !( *it ) ->dead() ) {
- ( *it ) ->setDisabled( true );
- }
- ++it;
- }
-}
-
-void FileCollaborationSession::enableEditing() {
- FileSet::Iterator it = m_files.values();
- while ( it ) {
- if ( !( *it ) ->dead() ) {
- ( *it ) ->setDisabled( false );
- }
- ++it;
- }
-}
-
-void FileCollaborationSession::removeAllFiles() {
- FileSet::Iterator it = m_files.values();
- while ( it ) {
- removeFile( ( *it ) ->id() );
- ++it;
- }
-}
-
-void FileCollaborationSession::closeSession() {
- manager() ->closeSession( this );
-}
-
-void FileCollaborationSession::publishStateChange() {
- emit stateChanged( this );
-}
-
-QAction* FileCollaborationSession::getRemoveUserAction( const UserPointer& user ) {
- QVariant v;
- v.setValue( user );
- m_removeUserAction->setData( v );
- return m_removeUserAction;
-}
-
-void FileCollaborationSession::publishFileRemove( uint id ) {
- CollabFileList files = fileNames();
- files.push_back( CollabFile( id, "" ) );
- publishFileList( files );
-}
-
-void FileCollaborationSession::slotPublishFileList() {
- publishFileList( fileNames() );
-}
-
-void FileCollaborationSession::publishFileList( const CollabFileList& files ) {
- for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
- FileCollaborationPointer collab = *it;
- KDevTeamworkUserPointer::Locked l = collab->user();
- if ( l ) {
- if ( l->online().session() ) {
- globalMessageSendHelper().send<FileListMessage>( l->online().session().unsafe(), files, id() );
- }
- } else {
- err() << "publishFileList(..): could not lock user";
- }
- }
-}
-
-void FileCollaborationSession::publishEdit( const VectorTimestamp& state, const SimpleReplacement& replacement, DocumentWrapper* sender ) {
- for ( CollaborationSet::ValueMap::iterator it = m_collaborations.begin(); it != m_collaborations.end(); ++it ) {
- FileCollaborationPointer collab = ( *it ).second.value;
- if ( state.primaryIndex() != collab->primaryIndex() ) {
- KDevTeamworkUserPointer::Locked l = collab->user();
- if ( l ) {
- if ( l->online().session() ) {
- globalMessageSendHelper().send<FileEditMessage>( l->online().session().unsafe(), state, replacement, sender->id(), id() );
- }
- } else {
- err() << "publishEdit(..): could not lock user";
- }
- }
- }
-}
-
-void FileCollaborationSession::slotFillCollaboratingUserMenu( QMenu * /*menu*/, const UserPointer & /*user*/ ) {}
-
-CollabSessionId FileCollaborationSession::id() const {
- return m_id;
-}
-
-QList< KDevTeamworkUserPointer > FileCollaborationSession::users() const {
- QList<KDevTeamworkUserPointer> ret;
- for ( CollaborationSet::ValueMap::const_iterator it = m_collaborations.begin(); it != m_collaborations.end(); ++it ) {
- ret << ( *it ).second.value->user();
- }
- return ret;
-}
-
-void FileCollaborationSession::inviteUser( const KDevTeamworkUserPointer & user ) {
- try {
- if ( !m_isMasterSession )
- throw "cannot invite user to a remote session";
-
- KDevTeamworkUserPointer::Locked lu = user;
- if ( !lu )
- throw "could not lock user";
-
- if ( !lu->online().session() )
- throw "no session to user " + ~lu->User::name();
-
- SessionPointer session = lu->online().session();
-
- FileCollaborationPointer collab = newCollaboration( user );
-
- } catch ( const char * str ) {
- err() << "inviteUser:" << str;
- } catch ( QString str ) {
- err() << "inviteUser:" << str;
- }
-}
-
-QString FileCollaborationSession::firstPeerName() {
- CollaborationSet::ValueMap::iterator it = m_collaborations.begin();
- if ( it != m_collaborations.end() ) {
- KDevTeamworkUserPointer::Locked l = ( *it ).second.value->user();
- if ( l ) {
- return ~l->User::name();
- } else {
- err() << "firstPeerUserName() could not lock user";
- return "";
- }
- }
- return "";
-}
-
-uint FileCollaborationSession::allocateIndex() {
- if ( m_primaryIndex != 0 ) {
- err() << "allocateIndex() called although session is not master";
- }
- return m_indexCount++;
-}
-
-uint FileCollaborationSession::allocateWrapperIndex() {
- /*if ( m_primaryIndex != 0 ) {
- err() << "allocateWrapperIndex() called although session is not master";
- }*/
-
- uint ret = 0;
- if ( m_isMasterSession )
- ret = m_wrapperIndexCount++;
- else
- ret = m_wrapperIndexCount++ + KRandom::random() % 10 + 5; ///Return a higher number to avoid conflicts
- if( m_files[ret] )
- return allocateWrapperIndex();
- else
- return ret;
-
-}
-
-void FileCollaborationSession::kickUser( const KDevTeamworkUserPointer & /*user*/ ) {}
-
-QString FileCollaborationSession::name() const {
- return m_name;
-}
-
-FileCollaborationManager * FileCollaborationSession::manager() {
- return m_manager;
-}
-/*
-void FileCollaborationSession::processMessage( const FileCollaborationMessagePointer& msg ) {
- try {
- FileCollaborationMessagePointer::Locked lmsg = msg;
- if ( !lmsg )
- throw "could not lock message";
-
- UserPointer u = lmsg->info().user();
- if ( !u )
- throw QString( "no user-information" );
-
- FileCollaborationPointer collab = m_collaborations[ u ];
- if ( !collab )
- throw ~( "got message from not involved user \"" + u.unsafe() ->safeName() + "\"" );
-
- collab->processMessage( msg );
-
- } catch ( QString str ) {
- err() << "could not process message:" << str;
- }
-}*/
-int FileCollaborationSession::receiveMessage( MessageInterface* /*msg*/ ) {
- err() << "got unknown message-type";
- return 1;
-}
-
-int FileCollaborationSession::receiveMessage( FileListMessage* msg ) {
- for ( CollabFileList::iterator it = msg->m_files.begin(); it != msg->m_files.end(); ++it ) {
- FileSet::Iterator doc = m_files.values( it->id );
- if ( doc ) {
- if ( it->file.isEmpty() ) {
- if( m_isMasterSession ) {
- out( Logger::Debug ) << "file" << it->file << "was tried to be removed from the session";
- } else {
- out( Logger::Debug ) << "file" << it->file << "has been removed from the session";
- killFile( it->id );
- }
- }
- } else {
- out( Logger::Warning ) << "unknown reference in file-list-message:" << it->id << "" << it->file;
- /*if ( !it->file.isEmpty() ) {
- ///Add the new file
- addFileInternal( *it, false, false );
- } else {
- out( Logger::Warning ) << "unknown referenced in file-list-message:" << it->id;
- }*/
- }
- }
- return 1;
-}
-
-int FileCollaborationSession::receiveMessage( FileCollaborationMessage* msg ) {
- switch ( msg->message() ) {
- case FileCollaborationMessageData::CloseSession:
- if ( !m_isMasterSession ) {
- out() << "finishing session";
- aboutToClose();
- } else {
- CollaborationSet::Iterator it = m_collaborations.values( msg->info().user() );
- if ( it ) {
- it.edit() ->data() ->close( "requested" );
- m_collaborations.remove( it );
- } else {
- err() << "got message from a user that is not part of the collaboration-session";
- }
- }
- default:
- out() << "got unhandled file-collaboration-message:" << msg->messageAsString();
- }
- return 1;
-}
-
-int FileCollaborationSession::receiveMessage( DocumentWrapperMessage* msg ) {
- CollaborationSet::Iterator sender = m_collaborations.values( msg->info().user() );
- if ( !sender ) {
- err() << "got FileSynchronize from a not collaborating user";
- return 0;
- }
-
- FileSet::Iterator it = m_files.values<uint>( msg->wrapperId() );
- if ( it ) {
- it.edit() ->data() ->processMessage( msg );
- } else {
- FileSynchronize* smsg = dynamic_cast<FileSynchronize*>( msg );
- if ( smsg ) {
- ///This has to be unterstood as an invitation to add a new document.
- if ( m_isMasterSession && !m_allowSentDocuments ) {
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionDenied );
- QString userName = "anonymous user";
- if ( msg->info().user() )
- userName = ~msg->info().user().unsafe() ->safeName();
- out( Logger::Warning ) << "got a file-synchronization from" << userName << "for \"" << smsg->fileName() << "\", but new files from collaborators are not allowed.";
- return 1;
- }
- if ( addFileInternal( CollabFile( smsg->wrapperId(), smsg->fileName() ), false, false ) ) {
- DocumentWrapperPointer wrapper = m_files[ smsg->wrapperId() ];
- if ( !wrapper ) {
- err() << "could not create wrapper";
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
- return 1;
- }
- wrapper->processMessage( smsg );
-
- if ( m_isMasterSession ) {
- ///publish the new file to all other clients
- for ( CollaborationSet::Iterator it = m_collaborations.values(); it; ++it ) {
- if ( sender == it )
- continue;
- synchronizeFile( *it, wrapper );
- }
- }
- } else {
- err() << "failed to add file on synchronization:" << smsg->fileName();
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
- }
- } else {
- out( Logger::Warning ) << "could not locate the correct document-wrapper for a message of type" << msg->name() << "wrapper-id:" << msg->wrapperId();
- }
- }
- return 1;
-}
-
-int FileCollaborationSession::processMessage( FileCollaborationMessage* msg ) {
- return m_dispatcher( msg );
-}
-
-void FileCollaborationSession::aboutToClose() {
- stopSession();
-}
-
-#include "filecollaborationsession.moc"
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationsession.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.h (nonexistent)
@@ -1,54 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_UTILS
-#define KDEVTEAMWORK_UTILS
-
-#include <QString>
-#include <string>
-#include <ostream>
-
-QString toQ( const std::string& rhs );
-std::string fromQ( const QString& str );
-
-///This operator converts between Q- and std-classes
-std::string operator ~ ( const QString& rhs );
-
-QString operator ~ ( const std::string& rhs );
-
-std::ostream& operator << ( std::ostream& stream, const QString& str );
-
-void indexToLineCol( int index, const QString& text, int& line, int& col );
-
-///Returns -1 if the index does not exist
-int lineColToIndex( const QString& text, int line, int col );
-
-void indexToLineCol( int index, const std::string& text, int& line, int& col );
-
-///Returns -1 if the index does not exist
-int lineColToIndex( const std::string& text, int line, int col );
-
-struct Block {
- bool& b;
- bool old;
- Block( bool& bl ) : b( bl ), old(bl) {
- b = true;
- }
- ~Block() {
- b = old;
- }
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/test.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/test.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/test.cpp (nonexistent)
@@ -1,274 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <string>
-#include "lib/network/crossmap.h"
-#include <assert.h>
-#include <iostream>
-#include <list>
-
-using namespace Utils;
-using namespace std;
-
-struct TestMappable {
- NAMED_TYPE( Name, std::string );
- int ints[ 2 ];
-
- char* bla;
- std::string string;
- template <class Type, int number>
- Type getKey() const {
- return Type::Error;
- }
-
- std::list<int> intList;
-
- Name name;
-
- bool operator == ( const TestMappable& rhs ) const {
- return ints[ 0 ] == rhs.ints[ 0 ] && ints[ 1 ] == rhs.ints[ 1 ] && bla == rhs.bla && string == rhs.string && name == rhs.name;
- }
-};
-
-
-BIND_LIST_6( KeyList, TestMappable::Name, int, char*, std::string, int, std::list<int> )
-
-///A little test for GetListItem
-Assert< IfSame< GetListItem< 0, KeyList >::Result, TestMappable::Name, Success, Fail >::Result::value >::OK ok1;
-Assert<IfSame< GetListItem< 1, KeyList >::Result, int, Success, Fail >::Result::value >::OK ok2;
-Assert<IfSame< GetListItem< 2, KeyList >::Result, char*, Success, Fail >::Result::value >::OK ok3;
-Assert<IfSame< GetListItem< 3, KeyList >::Result, std::string, Success, Fail >::Result::value >::OK ok4;
-Assert<IfSame< GetListItem< 4, KeyList >::Result, int, Success, Fail >::Result::value >::OK ok42;
-
-Assert < FindInList< TestMappable::Name, KeyList >::value == 0 > ::OK ok5;
-Assert < FindInList< int, KeyList >::value == 1 > ::OK ok6;
-Assert < FindInList< char*, KeyList >::value == 2 > ::OK ok7;
-Assert < FindInList< std::string, KeyList >::value == 3 > ::OK ok8;
-Assert < FindInList< int, KeyList, 1 >::value == 4 > ::OK ok62;
-
-Assert < FindRelativeInList< TestMappable::Name, KeyList >::value == 0 > ::OK ok51;
-Assert < FindRelativeInList< int, KeyList, 1 >::value == 1 > ::OK ok61;
-Assert < FindRelativeInList< char*, KeyList, 2 >::value == 2 > ::OK ok71;
-Assert < FindRelativeInList< std::string, KeyList, 3 >::value == 3 > ::OK ok81;
-Assert < FindRelativeInList< int, KeyList, 4 >::value == 4 > ::OK ok621;
-
-AssertSame< FindRelativeInList< TestMappable::Name, KeyList >::relativeIndex, 0 >::OK ok52;
-AssertSame< FindRelativeInList< int, KeyList, 1 >::relativeIndex, 0 >::OK ok623;
-AssertSame< FindRelativeInList< char*, KeyList, 2 >::relativeIndex, 0 >::OK ok72;
-AssertSame< FindRelativeInList< std::string, KeyList, 3 >::relativeIndex, 0 >::OK ok82;
-AssertSame< FindRelativeInList< int, KeyList, 4 >::relativeIndex, 1 >::OK ok622;
-
-template<class Type>
-std::list<Type> make_list( const Type& t ) {
- std::list<Type> ret;
- ret.push_back( t );
- return ret;
-}
-
-template<class Type>
-std::list<Type> make_list( const Type& i, const Type& i2 ) {
- std::list<Type> ret;
- ret.push_back( i );
- ret.push_back( i2 );
- return ret;
-}
-
-template<class Type>
-std::list<Type> make_list( const Type& i, const Type& i2, const Type& i3 ) {
- std::list<Type> ret;
- ret.push_back( i );
- ret.push_back( i2 );
- ret.push_back( i3 );
- return ret;
-}
-
-template<class Type>
-std::list<Type> make_list( const Type& i, const Type& i2, const Type& i3, const Type& i4 ) {
- std::list<Type> ret;
- ret.push_back( i );
- ret.push_back( i2 );
- ret.push_back( i3 );
- ret.push_back( i4 );
- return ret;
-}
-
-template <>
-int TestMappable::getKey<int, 0>() const {
- return ints[ 0 ];
-}
-
-template <>
-int TestMappable::getKey<int, 1>() const {
- return ints[ 1 ];
-}
-
-template <>
-TestMappable::Name TestMappable::getKey<TestMappable::Name, 0>() const {
- return name;
-}
-
-template <>
-std::string TestMappable::getKey<std::string, 0>() const {
- return string;
-}
-
-template <>
-char* TestMappable::getKey<char*, 0>() const {
- return bla;
-}
-
-template <>
-std::list<int> TestMappable::getKey<std::list<int>, 0>() const {
- return intList;
-}
-
-typedef CrossMap< TestMappable, KeyList> TestSet;
-CrossMap< TestMappable, KeyList> testSet;
-
-
-TestMappable randomMappable() {
- TestMappable t1;
- int r = rand() % 5;
- switch ( r ) {
- case 0:
- t1.name = "honk";
- break;
- case 1:
- t1.name = "peter";
- break;
- case 2:
- t1.name = "frank";
- break;
- case 3:
- t1.name = "guildo";
- break;
- case 4:
- t1.name = "joschi";
- break;
- }
- t1.ints[ 0 ] = rand() % 100;
- t1.ints[ 1 ] = rand() % 100;
- r = rand() % 5;
-
- switch ( r ) {
- case 0:
- t1.string = "urug";
- break;
- case 1:
- t1.string = "welsch";
- break;
- case 2:
- t1.string = "ick";
- break;
- case 3:
- t1.string = "harr";
- break;
- case 4:
- t1.string = "bloog";
- break;
- }
- return t1;
-}
-
-
-int main() {
-
- cout << "testing" << endl;
- TestMappable t1;
- t1.name = "honk";
- t1.ints[ 0 ] = 15;
- t1.ints[ 1 ] = 16;
- t1.string = "someString";
-
- TestMappable t2;
- t2.name = "noHonk";
- t2.ints[ 0 ] = 15;
- t2.ints[ 1 ] = 27;
- t2.string = "no string";
-
- t1.intList = make_list<int>( 10, 11, 12, 13 );
- t2.intList = make_list<int>( 11, 13, 17 );
-
- testSet.insert( t1 );
-
- assert( (testSet.value<2, int>( 10 ) == t1) );
- assert( (testSet.value<2, int>( 11 ) == t1) );
- assert( (testSet.value<2, int>( 12 ) == t1) );
- assert( (testSet.value<2, int>( 13 ) == t1) );
- assert( !(testSet.value<2, int>( 14 ) == t1) );
-
- assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
- assert( testSet.value<std::string> ( "someString" ) == t1 );
- assert( testSet.value<int> ( 15 ) == t1 );
- assert( ( testSet.value<1, int>( 16 ) == t1 ) );
-
- testSet.update( testSet.find( t1 ) );
-
- assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
- assert( testSet.value<std::string> ( "someString" ) == t1 );
- assert( testSet.value<int> ( 15 ) == t1 );
- assert( ( testSet.value<1, int>( 16 ) == t1 ) );
-
- assert( testSet.update( testSet.find( testSet[ 15 ] ) ) );
-
- assert( testSet.hasContent() );
-
- testSet.remove( testSet.value<1, int>( 16 ) );
-
- assert( !testSet.hasContent() );
-
- testSet.insert( t1 );
- testSet.insert( t1 );
- testSet.insert( t2 );
-
- assert( (testSet.value<2, int>( 10 ) == t1) );
- assert( (testSet.value<2, int>( 17 ) == t2) );
- assert( (testSet.values<2, int>( 11 ).count() == 3) );
-
- CrossMap< TestMappable, KeyList>::Iterator it = testSet.values<int>( 15 );
- assert( it.count() == 3 );
- while ( it ) {
- cout << "Item:" << ( *it ).name.value << endl;
- ++it;
- }
-
- assert( testSet.remove( t2 ) );
-
- assert( testSet.count() == 2 );
-
- assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
- assert( testSet.value<std::string> ( "someString" ) == t1 );
- assert( testSet.value<int> ( 15 ) == t1 );
- assert( ( testSet.value<1, int>( 16 ) == t1 ) );
-
- testSet.remove( t1 );
-
- assert( testSet.value<TestMappable::Name> ( "honk" ) == t1 );
- assert( testSet.value<std::string> ( "someString" ) == t1 );
- assert( testSet.value<int> ( 15 ) == t1 );
- assert( ( testSet.value<1, int>( 16 ) == t1 ) );
-
- testSet.remove( t1 );
-
- assert( testSet.count() == 0 );
- assert( !testSet.hasContent() );
-
- cout << "success" << endl;
-
- return 0;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/test.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc (nonexistent)
@@ -1,3 +0,0 @@
-<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
-<kpartgui name="KDevTeamwork" version="8">
-</kpartgui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.rc
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.h (nonexistent)
@@ -1,85 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef INDOCUMENTMESSAGE_H
-#define INDOCUMENTMESSAGE_H
-
-#include "kdevteamwork_messages.h"
-#include "indocumentreference.h"
-
-class DocumentMessageInternal;
-class InDocumentConversation;
-
-class InDocumentMessage : public KDevTeamworkTextMessage {
- DECLARE_MESSAGE( InDocumentMessage, KDevTeamworkTextMessage, 3 );
- InDocumentReference m_start, m_end;
- string m_context;
- auto_ptr<DocumentMessageInternal> m_internal;
-
- DocumentContextLines m_contextLines;
-
- enum {
- MessageVersion = 1
- };
-
- template <class Arch>
- void serial( Arch& arch ) {
- int v = MessageVersion;
- arch & v;
-
- arch & m_start & m_end & m_context;
-
- if ( v >= 1 )
- arch & m_contextLines;
- }
-
- public:
-
- InDocumentMessage( const Teamwork::MessageConstructionInfo& info, const QString& text, const InDocumentReference& startRef, const InDocumentReference& endRef, const QString& context );
-
- InDocumentMessage( InArchive& from, const Teamwork::MessageInfo& info );
-
- virtual void serialize( OutArchive& arch );
-
- ///Context means the name of a conversation-thread
- QString context();
-
- ///Can be used to get and set the context-lines
- DocumentContextLines& contextLines() ;
-
- QString document();
-
- InDocumentReference& start();
-
- InDocumentReference& end() ;
-
- virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
-
- virtual QIcon messageIcon() const;
-
- void setConversation( InDocumentConversation* conv );
-
- virtual bool needReply() const;
-
- virtual void result( bool success );
-
- virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
-
- virtual QString shortName() const;
-
- virtual void showInWidget( QWidget* widget, KDevTeamwork* tw );
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp (nonexistent)
@@ -1,552 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "guimessagehistory.h"
-#include "messagemanager.h"
-#include <QMetaObject>
-#include <QStandardItemModel>
-#include "messagehistorymanager.h"
-#include <QTimer>
-#include "kdevteamwork_client.h"
-#include "kdevteamwork.h"
-#include "utils.h"
-#include <QMenu>
-#include <QHeaderView>
-#include "kdevteamwork_messageshower.h"
-#include <kdialog.h>
-
-using namespace Teamwork;
-
-Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
-Q_DECLARE_METATYPE( HistoryMessagePointer )
-Q_DECLARE_METATYPE( Teamwork::MessageType )
-
-GuiMessageHistory::GuiMessageHistory( MessageManager* manager, UserList users, const QString& context ) : SafeLogger( manager->teamwork() ->logger() ), m_manager( manager ), m_defaultContext( context ) {
- foreach( const KDevTeamworkUserPointer &user, users )
- addUser( user );
-
- if ( users.isEmpty() )
- m_allUsers = true;
-
- m_dialog = new KDialog( manager->teamwork() ->widget() );
- m_dialog->setButtons( KDialog::Close );
- m_widgetData.setupUi( m_dialog->mainWidget() );
-
- m_developersModel = new QStandardItemModel( 0, 1, m_widgetData.developers );
- m_widgetData.developers->setModel( m_developersModel );
- m_widgetData.developers->setSelectionMode( QAbstractItemView::MultiSelection );
-
- m_messagesModel = new QStandardItemModel( 0, 1, m_widgetData.messages );
- m_widgetData.messages->setModel( m_messagesModel );
-
- m_updateTimer = new QTimer( this );
- m_userIconUpdateTimer = new QTimer( this );
- m_updateTimer->setSingleShot( true );
- m_userIconUpdateTimer->setSingleShot( true );
- //m_widgetData.messages->header()->hide();
-
-
- qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
- qRegisterMetaType<HistoryMessagePointer>( "HistoryMessagePointer" );
- qRegisterMetaType<Teamwork::MessageType>( "Teamwork::MessageType" );
-
- connect( m_widgetData.developers->selectionModel(), SIGNAL( selectionChanged ( const QItemSelection &, const QItemSelection & ) ), this, SLOT( slotSelectionChanged() ) );
- connect( m_widgetData.untilDate, SIGNAL( dateChanged ( const QDate & ) ), this, SLOT( slotSelectionChanged() ) );
- connect( m_widgetData.fromDate, SIGNAL( dateChanged ( const QDate & ) ), this, SLOT( slotSelectionChanged() ) );
- connect( m_widgetData.allMessagesButton, SIGNAL( clicked( bool ) ), this, SLOT( slotAllMessages() ) );
- connect( m_widgetData.allDevelopersButton, SIGNAL( clicked( bool ) ), this, SLOT( slotAllDevelopers() ) );
- connect( m_widgetData.typeFilter, SIGNAL( currentIndexChanged ( int ) ), this, SLOT( typeFilterChanged( int ) ) );
- connect( m_widgetData.contextFilter, SIGNAL( currentIndexChanged ( int ) ), this, SLOT( contextFilterChanged( int ) ) );
-
- connect( &m_manager->historyManager(), SIGNAL( newMessage( HistoryMessagePointer ) ), this, SLOT( slotNewMessage( const HistoryMessagePointer& ) ), Qt::QueuedConnection );
- connect( m_updateTimer, SIGNAL( timeout() ), this, SLOT( slotUpdateMessages() ) );
- connect( m_userIconUpdateTimer, SIGNAL( timeout() ), this, SLOT( updateMessageUserIcons() ) );
-// connect( m_widgetData.exitButton, SIGNAL( clicked( bool ) ), this, SLOT( slotExit() ) );
- connect( m_dialog, SIGNAL( finished() ), this, SLOT( slotExit() ) );
- connect( m_widgetData.messages, SIGNAL( clicked ( const QModelIndex & ) ), this, SLOT( messageItemClicked( const QModelIndex& ) ) );
-
-
- m_widgetData.messages->setAlternatingRowColors( true );
- m_widgetData.messages->setSelectionBehavior( QAbstractItemView::SelectItems );
- m_widgetData.messages->setRootIsDecorated( false );
- m_widgetData.messages->setIndentation( 0 );
- m_widgetData.messages->header() ->setResizeMode( QHeaderView::Stretch );
-
- slotAllMessages();
- fillDeveloperList();
- m_dialog->show();
-}
-
-GuiMessageHistory::~GuiMessageHistory() {
- delete m_dialog;
-}
-
-void GuiMessageHistory::showMessage( const HistoryMessagePointer& msg ) {
- HistoryMessagePointer::Locked l = msg;
- if ( l ) {
- if ( m_messagesModel->columnCount() == 0 ) {
- /*if( m_widget ) {
- m_widgetData.messages->header()->show();
- }*/
- m_messagesModel->insertColumns( 0, ColumnCount );
-
- m_messagesModel->setHeaderData( TimeColumn, Qt::Horizontal, QString( "Time" ) );
- m_messagesModel->setHeaderData( UserColumn, Qt::Horizontal, QString( "User" ) );
- m_messagesModel->setHeaderData( TypeColumn, Qt::Horizontal, QString( "Type" ) );
- m_messagesModel->setHeaderData( TextColumn, Qt::Horizontal, QString( "Text" ) );
- }
- m_messagesModel->insertRow( 0 );
-
- ///Time
- {
- UserPointer::Locked lu = l->info().user();
- QString userName;
-
- QModelIndex index = m_messagesModel->index( 0, TimeColumn );
-
- m_messagesModel->setData( index, l->creationTime().toString( Qt::LocalDate ), Qt::DisplayRole );
- //m_messagesModel->setData( index, l->messageIcon(), Qt::DecorationRole );
-
- QVariant v;
- v.setValue( msg );
- m_messagesModel->setData( index, v, Qt::UserRole );
- }
-
- ///Message-Type
- {
- UserPointer::Locked lu = l->info().user();
- QString userName;
-
- QModelIndex index = m_messagesModel->index( 0, TypeColumn );
- if ( lu ) {
- userName = ~lu->name();
- } else {
- userName = "unknown user";
- }
-
- m_messagesModel->setData( index, l->shortName(), Qt::DisplayRole );
- m_messagesModel->setData( index, l->messageIcon(), Qt::DecorationRole );
-
- QVariant v;
- v.setValue( msg );
- m_messagesModel->setData( index, v, Qt::UserRole );
- }
-
- ///User
- {
- UserPointer::Locked lu = l->info().user();
- QString userName;
-
- QModelIndex index = m_messagesModel->index( 0, UserColumn );
- if ( lu ) {
- userName = ~lu->name();
- } else {
- userName = "unknown";
- }
-
- m_messagesModel->setData( index, userName, Qt::DisplayRole );
-
- if ( lu.cast<KDevTeamworkUser>() )
- m_messagesModel->setData( index, lu.cast<KDevTeamworkUser>() ->icon(), Qt::DecorationRole );
-
- QVariant v;
- v.setValue( l->info().user() );
- m_messagesModel->setData( index, v, Qt::UserRole );
- }
-
-
- ///Text
- {
- QModelIndex index = m_messagesModel->index( 0, TextColumn );
-
- m_messagesModel->setData( index, ~l->text(), Qt::DisplayRole );
-
- QVariant v;
- v.setValue( msg );
- m_messagesModel->setData( index, v, Qt::UserRole );
- }
- } else {
- ///error
- err() << "could not lock Message in showMessage";
- }
-}
-
-void GuiMessageHistory::updateMessageUserIcons() {
- QMap<KDevTeamworkUserPointer, KDevTeamworkUserPointer::Locked> lockedUsers;
- foreach( KDevTeamworkUserPointer u, m_changedUsers ) {
- KDevTeamworkUserPointer::Locked l = u;
- lockedUsers[ u ] = l;
- }
-
- for ( int a = 0; a < m_messagesModel->rowCount(); a++ ) {
- QModelIndex i = m_messagesModel->index( a, UserColumn );
- if ( i.isValid() ) {
- QVariant v = m_messagesModel->data( i , Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- QMap<KDevTeamworkUserPointer, KDevTeamworkUserPointer::Locked>::iterator it = lockedUsers.find( v.value<UserPointer>().cast<KDevTeamworkUser>() );
- if ( it != lockedUsers.end() ) {
- if ( *it ) {
- m_messagesModel->setData( i, ( *it ) ->icon(), Qt::DecorationRole );
- } else {
- m_messagesModel->setData( i, QIcon(), Qt::DecorationRole );
- }
- }
-
- }
- }
- }
- m_changedUsers.clear();
-}
-
-
-void GuiMessageHistory::messageItemClicked( const QModelIndex& index ) {
- QVariant v = m_messagesModel->data( index, Qt::UserRole );
-
- if ( v.canConvert<UserPointer>() ) {
- KDevTeamworkUserPointer::Locked lu = v.value<UserPointer>().cast<KDevTeamworkUser>();
- if ( lu ) {
- QWidget * w = m_widgetData.messageFrame->widget();
- m_widgetData.messageFrame->setWidget( 0 );
- if ( w )
- delete w;
-
- w = new QWidget( m_widgetData.messageFrame );
- new KDevTeamworkUserInfoShower( lu, w, m_manager->teamwork() );
- m_widgetData.messageFrame->setWidget( w );
-
- /*QMenu* menu = new QMenu( m_dialog );
- m_manager->teamwork()->fillUserMenu( menu, lu.data() );
- menu->exec( QCursor::pos() );*/
- } else {
- err() << "could not lock user in messageItemClicked";
- }
- }
-
- if ( v.canConvert<HistoryMessagePointer>() ) {
- HistoryMessagePointer::Locked lmsg = v.value<HistoryMessagePointer>();
- if ( lmsg ) {
- QWidget * w = m_widgetData.messageFrame->widget();
- m_widgetData.messageFrame->setWidget( 0 );
- if ( w )
- delete w;
-
- AbstractGUIMessage* gmsg = lmsg.freeCast<AbstractGUIMessage>();
- if ( gmsg ) {
- w = new QWidget( m_widgetData.messageFrame );
- gmsg->showInWidget( w, m_manager->teamwork() );
- m_widgetData.messageFrame->setWidget( w );
- }
-
- /*QMenu* menu = new QMenu( m_dialog );
- m_manager->fillMessageMenu( menu, lmsg.data() );
- menu->exec( QCursor::pos() );*/
- } else {
- err() << "could not lock message in messageItemClicked";
- }
- }
-}
-
-
-bool GuiMessageHistory::fitMessageDate( const HistoryMessagePointer& msg ) {
- HistoryMessagePointer::Locked l = msg;
-
- if ( l ) {
- return m_widgetData.fromDate->date() <= l->creationTime().date() && m_widgetData.untilDate->date() >= l->creationTime().date();
- } else {
- err() << "could not lock Message in fitMessageDate";
- return false;
- }
-}
-
-void GuiMessageHistory::slotExit() {
- deleteLater();
-}
-
-void GuiMessageHistory::slotAllMessages() {
- m_widgetData.fromDate->setDate( QDate( 2000, 1, 1 ) );
- m_widgetData.untilDate->setDate( QDate::currentDate() );
- slotSelectionChanged();
-}
-
-
-void GuiMessageHistory::slotAllDevelopers() {
- if ( selectedUsers().isEmpty() ) {
- m_users.clear();
- m_allUsers = true;
- }
-
- m_widgetData.developers->selectionModel() ->clear();
- slotSelectionChanged();
-}
-
-void GuiMessageHistory::slotNewMessage( const HistoryMessagePointer& msg ) {
- HistoryMessagePointer::Locked l = msg;
- if ( l ) {
- UserPointer u = userFromSession( l->info().session() );
- if ( m_users.contains( u.cast<KDevTeamworkUser>() ) || m_allUsers ) {
- if ( fitMessageDate( msg ) ) {
- showMessage( msg );
- applyFilters( 1 );
- }
- }
- } else {
- m_manager->log( "GuiMessageHistory: could not lock a new message", Error );
- }
-}
-
-void GuiMessageHistory::typeFilterChanged( int /*index*/ ) {
- applyFilters();
-}
-
-
-void GuiMessageHistory::contextFilterChanged( int /*index*/ ) {
- applyFilters();
-}
-
-
-void GuiMessageHistory::clearFilters() {
- m_widgetData.typeFilter->clear();
- m_widgetData.contextFilter->clear();
-}
-
-
-void GuiMessageHistory::applyFilters( int firstN ) {
- QString type = m_widgetData.typeFilter->currentText();
- Teamwork::MessageType id;
-
- if ( m_widgetData.typeFilter->currentIndex() != -1 ) {
- QVariant v = m_widgetData.typeFilter->itemData( m_widgetData.typeFilter->currentIndex() );
- if ( v.canConvert<Teamwork::MessageType>() ) {
- id = v.value<Teamwork::MessageType>();
- }
- }
- QString context = m_widgetData.contextFilter->currentText();
-
- int count = m_messagesModel->rowCount();
- if ( firstN != 0 && firstN < count )
- count = firstN;
-
- for ( int a = 0; a < count; a++ ) {
- QModelIndex index = m_messagesModel->index( a, TypeColumn );
- bool typeFits = false;
- bool contextFits = false;
-
- QVariant v = m_messagesModel->data( index, Qt::UserRole );
- if ( HistoryMessagePointer::Locked lmsg = v.value<HistoryMessagePointer>() ) {
- if ( !type.isEmpty() ) {
- if ( lmsg->info().type().startsWith( id ) )
- typeFits = true;
- } else {
- typeFits = true;
- }
-
- if ( context.isEmpty() ) {
- contextFits = true;
- } else {
- InDocumentMessage* dmsg = lmsg.freeCast< InDocumentMessage >();
- if ( dmsg && dmsg->context() == context )
- contextFits = true;
- }
- } else {
- typeFits = true;
- contextFits = true;
- }
-
- m_widgetData.messages->setRowHidden( a, QModelIndex(), !typeFits || !contextFits );
- }
-}
-
-
-void GuiMessageHistory::slotSelectionChanged() {
- ///Update the list of messages according to the selected users
- m_updateTimer->start( 100 );
-}
-
-void GuiMessageHistory::slotUpdateMessages() {
- fillMessages();
-}
-
-void GuiMessageHistory::slotUserStateChanged( const KDevTeamworkUserPointer& user ) {
- m_changedUsers << user;
- updateUserIcon( user );
- m_userIconUpdateTimer->start( 100 );
-}
-
-void GuiMessageHistory::fillMessages() {
- QString oldTypeFilter = m_widgetData.typeFilter->currentText();
- QString oldContextFilter = m_widgetData.contextFilter->currentText();
-
- clearFilters();
-
- UserSet selected = selectedUsers();
- m_messagesModel->clear();
- if ( m_allUsers && selected.isEmpty() ) {
- m_developersModel->clear();
- clearUsers();
- }
-
- QMap<UserIdentity, bool> users;
- for ( UserSet::iterator it = selected.begin(); it != selected.end(); ++it ) {
- KDevTeamworkUserPointer::Locked l = it.key();
- if ( l ) {
- users[ l->identity() ] = true;
- } else {
- //error
- err() << "failed to lock a user on slotUserStateChanged";
- }
- }
-
- QMap<QString, bool> contexts;
- QMap<QString, Teamwork::MessageType> types;
- QMap<UserPointer, bool> grabbedUsers;
-
- QList<HistoryMessagePointer> messages = m_manager->historyManager().getMessages( m_manager->teamwork() ->client(), m_widgetData.fromDate->date(), m_widgetData.untilDate->date(), users );
-
- foreach( HistoryMessagePointer msg, messages ) {
- showMessage( msg );
-
- HistoryMessagePointer::Locked l = msg;
- if ( l ) {
- types[ QString( l->name() ) ] = l->info().type();
- if ( InDocumentMessage * dmsg = l.freeCast<InDocumentMessage>() ) {
- contexts[ dmsg->context() ] = true;
- }
- }
-
- if ( m_allUsers ) {
- HistoryMessagePointer::Locked l = msg;
- if ( msg ) {
- if ( l->info().user() ) {
- grabbedUsers[ l->info().user() ] = true;
- } else {
- err() << "a message has no associated user";
- }
- } else {
- err() << "a message cannot be locked";
- }
- }
- }
-
- if ( !grabbedUsers.isEmpty() ) {
- TeamworkClientPointer::Locked l = m_manager->teamwork() ->client();
- if ( l ) {
- for ( QMap<UserPointer, bool>::iterator it = grabbedUsers.begin(); it != grabbedUsers.end(); ++it ) {
-
- SafeSharedPtr<KDevTeamworkUser> user = it.key().cast<KDevTeamworkUser>();
- if ( user ) {
- addUser( user );
- } else {
- err() << "could not cast user to KDevTeamworkUSer";
- }
- }
- } else {
- err() << "could not lock client-session";
- }
- }
-
- if ( ( m_allUsers || !grabbedUsers.isEmpty() ) && selected.isEmpty() )
- fillDeveloperList();
-
- m_widgetData.typeFilter->insertItem( 0, "" );
- for ( QMap<QString, Teamwork::MessageType>::iterator it = types.begin(); it != types.end(); ++it ) {
- m_widgetData.typeFilter->insertItem( m_widgetData.typeFilter->count(), it.key() );
- QVariant v;
- v.setValue( *it );
- m_widgetData.typeFilter->setItemData( m_widgetData.typeFilter->count() - 1, v );
- }
-
- m_widgetData.contextFilter->insertItem( 0, m_defaultContext );
- if ( !m_defaultContext.isEmpty() )
- m_widgetData.contextFilter->insertItem( 1, "" );
- for ( QMap<QString, bool>::iterator it = contexts.begin(); it != contexts.end(); ++it ) {
- m_widgetData.contextFilter->insertItem( m_widgetData.contextFilter->count(), it.key() );
- }
-
- int i = m_widgetData.contextFilter->findText( oldContextFilter );
- if ( i != -1 )
- m_widgetData.contextFilter->setCurrentIndex( i );
-
- i = m_widgetData.typeFilter->findText( oldTypeFilter );
- if ( i != -1 )
- m_widgetData.contextFilter->setCurrentIndex( i );
-
- applyFilters();
-}
-
-GuiMessageHistory::UserSet GuiMessageHistory::selectedUsers() {
- QModelIndexList selected = m_widgetData.developers->selectionModel() ->selectedIndexes();
- if ( selected.isEmpty() ) {
- return m_users;
- } else {
- UserSet ret;
- foreach( QModelIndex index, selected ) {
- QVariant v = m_developersModel->data( index, Qt::UserRole );
- if ( v.canConvert<KDevTeamworkUserPointer>() )
- ret[ v.value<KDevTeamworkUserPointer>() ] = true;
- }
- return ret;
- }
-}
-
-void GuiMessageHistory::fillDeveloperList() {
- m_developersModel->clear();
- m_developersModel->insertColumn( 0 );
- for ( UserSet::iterator it = m_users.begin(); it != m_users.end(); ++it ) {
- m_developersModel->insertRow( 0 );
- QModelIndex index = m_developersModel->index( 0, 0 );
-
- KDevTeamworkUserPointer::Locked l = it.key();
- if ( l ) {
- m_developersModel->setData( index, ~l->User::name(), Qt::DisplayRole );
-
- QVariant v;
- v.setValue( it.key() );
- m_developersModel->setData( index, v, Qt::UserRole );
-
- m_developersModel->setData( index, l->icon(), Qt::DecorationRole );
- } else {
- m_developersModel->setData( index, QString( "lock_failed" ) );
- }
- }
-}
-
-void GuiMessageHistory::clearUsers() {
- for ( UserSet::iterator it = m_users.begin(); it != m_users.end(); ++it ) {
- disconnect( it.key().unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( slotUserStateChanged( const KDevTeamworkUserPointer& ) ) );
- }
- m_users.clear();
-}
-
-void GuiMessageHistory::addUser( const KDevTeamworkUserPointer& user ) {
- m_users[ user ] = true;
- connect( user.unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( slotUserStateChanged( const KDevTeamworkUserPointer& ) ), Qt::QueuedConnection );
-}
-
-void GuiMessageHistory::updateUserIcon( const KDevTeamworkUserPointer& user ) {
- KDevTeamworkUserPointer::Locked l = user;
- for ( int a = 0; a < m_developersModel->rowCount(); a++ ) {
- QModelIndex index = m_developersModel->index( a, 0 );
- if ( !index.isValid() )
- break;
- QVariant v = m_developersModel->data( index, Qt::UserRole );
- if ( v.canConvert<KDevTeamworkUserPointer>() ) {
- if ( user == v.value<KDevTeamworkUserPointer>() ) {
- m_developersModel->setData( index, l->icon() , Qt::DecorationRole );
- }
- }
- }
-}
-
-#include "guimessagehistory.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.cpp (nonexistent)
@@ -1,43 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "kdevutils.h"
-#include "teamworkfoldermanager.h"
-#include "kdevteamworkplugin.h"
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-#include <ktexteditor/cursor.h>
-
-using namespace KDevelop;
-
-QString currentDocumentPath() {
- IDocumentController * docControl = KDevTeamworkPlugin::staticDocumentController();
-
- IDocument* d = docControl->activeDocument();
- if ( !d )
- throw QString( "no active document" );
-
- KTextEditor::Document* doc = d->textDocument();
- if ( !doc )
- throw QString( "active document is no text-document" );
-
- KTextEditor::View* view = doc->activeView();
- if ( !view )
- throw QString( "no active document-view" );
-
- return TeamworkFolderManager::workspaceRelative( d->url() );
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevutils.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h (nonexistent)
@@ -1,87 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_PART_H
-#define KDEVTEAMWORK_PART_H
-
-#include <QtCore/QPointer>
-
-#include <interfaces/iplugin.h>
-#include <QtCore/QVariant>
-
-class KDevTeamworkViewFactory;
-class KUrl;
-class QModelIndex;
-class KDevTeamwork;
-class KDevTeamworkPluginFactory;
-
-namespace KDevelop {
- class ICore;
- class IDocumentController;
- class IProject;
-}
-
-class KDevTeamworkPlugin: public KDevelop::IPlugin
-{
- Q_OBJECT
-public:
- enum RefreshPolicy
- {
- Refresh,
- NoRefresh,
- ForceRefresh
- };
-
-public:
- KDevTeamworkPlugin( QObject *parent, const QVariantList & = QVariantList() );
- virtual ~KDevTeamworkPlugin();
-
- //KDevPlugin methods
- virtual QWidget* pluginView() const;
-
- void import( RefreshPolicy policy = Refresh );
-
- static KDevelop::ICore* staticCore();
-
- static KDevelop::IDocumentController* staticDocumentController();
-
- virtual void restorePartialProjectSession(const QDomElement* el);
-
- virtual void savePartialProjectSession(QDomElement* el);
-
- void setView( QWidget* view );
-
- // KDevelop::Plugin methods
- virtual void unload();
-
- signals:
- void refresh();
-
-private slots:
- void projectOpened( KDevelop::IProject* );
- void projectClosed( KDevelop::IProject* );
-
-private:
- void destroyTeamwork();
- void startTeamwork( KDevelop::IProject* );
-
- KDevelop::IProject* m_currentProject;
- static KDevTeamworkPlugin* m_self;
- QPointer<KDevTeamwork> m_teamwork;
- QPointer<QWidget> m_window;
- KDevTeamworkViewFactory* m_factory;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp (nonexistent)
@@ -1,68 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "kdevteamwork_user.h"
-#include "lib/network/teamworkmessages.h"
-#include "kdevteamwork.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/export.hpp>
-#include "kdevteamwork_helpers.h"
-#include "lib/network/sessioninterface.h"
-
-
-KDevTeamworkUser::KDevTeamworkUser( const User* user ) {
- qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
- if( user ) {
- (*(User*)this) = *user;
- }
-}
-
-KDevTeamworkUser::KDevTeamworkUser( IdentificationMessage* msg ) : User((User)*msg) {
- qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
-}
-
-void KDevTeamworkUser::setSession( const SessionPointer& sess ) {
- User::setSession( sess );
- emit userStateChanged( this );
-}
-
-QIcon KDevTeamworkUser::icon( KIconLoader::Group size ) {
- SessionPointer s = online().session();
-
- if( s && s.unsafe()->isOk() ) {
- SessionPointer::Locked l = s;
- if( l ) {
- if( l->sessionType() == SessionInterface::Direct )
- return IconCache::instance()->getIcon( "presence_online", size );
- else
- return IconCache::instance()->getIcon( "presence_away", size );
- } else {
- return IconCache::instance()->getIcon( "presence_offline", size );
- }
- } else {
- return IconCache::instance()->getIcon( "presence_offline", size );
- }
- return IconCache::instance()->getIcon( "remove" );
-}
-
-QString KDevTeamworkUser::toolTip() {
- return "";
-}
-
-Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
-BOOST_CLASS_EXPORT_GUID(KDevTeamworkUser, "KDevTeamworkUser")
-
-
-#include "kdevteamwork_user.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h (nonexistent)
@@ -1,62 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef FILESYNCHRONIZEMESSAGE_H
-#define FILESYNCHRONIZEMESSAGE_H
-
-#include "filecollaborationmessages.h"
-#include "qdynamictext.h"
-
-class DynamicText;
-
-class FileSynchronizeData {
-
- public:
- explicit FileSynchronizeData( const QString& fileName = "", const QDynamicText& text = QDynamicText(), bool sendDynamic = true );
-
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- try {
- arch & m_text;
- }
- catch( const DynamicTextError& err ) {
- throw Teamwork::NonFatalSerializationError( "FileSynchronizeData::serialize(): " + err.what() );
- }
- arch & m_fileName;
- arch & m_fileText;
- arch & m_state;
- }
-
- QString fileName() {
- return m_fileName;
- }
-
- VectorTimestamp state() {
- return m_state;
- }
-
- QDynamicTextPointer createDynamicText();
- private:
- QString m_fileText;
- QString m_fileName;
- VectorTimestamp m_state;
- SharedPtr<QDynamicText, BoostSerializationNormal> m_text;
-};
-
-EASY_DECLARE_MESSAGE( FileSynchronize, DocumentWrapperMessage, 3, FileSynchronizeData, 3 );
-
-BOOST_CLASS_IMPLEMENTATION( FileSynchronizeData, boost::serialization::object_serializable )
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-///Eventually think about sending a whole history with a FileSynchronize
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui (nonexistent)
@@ -1,170 +0,0 @@
-<ui version="4.0" >
- <class>InDocumentState</class>
- <widget class="QWidget" name="InDocumentState" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>609</width>
- <height>80</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="1" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="label" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">File&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KUrlLabel" name="file" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration: underline;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" text-decoration:none;">file&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="label_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:Sans;">&lt;span style=" font-weight:600;">Position&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="position" >
- <property name="text" >
- <string>position</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="3" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="label_5" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:Sans;">&lt;span style=" font-weight:600;">Context&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KUrlLabel" name="context" >
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration: underline;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" text-decoration:none;">Context&lt;/span>&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="label_3" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Reference-Type&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="referenceType" >
- <property name="text" >
- <string>referenceType</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0" >
- <widget class="Line" name="line_2" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="Line" name="line" >
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KUrlLabel</class>
- <extends>QLabel</extends>
- <header>kurllabel.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagestate.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp (nonexistent)
@@ -1,258 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "teamworkfoldermanager.h"
-#include <interfaces/icore.h>
-#include "kdevteamworkplugin.h"
-#include <kio/netaccess.h>
-#include <krandom.h>
-#include <QStringList>
-#include <QFileInfo>
-#include <QFile>
-#include <QDateTime>
-#include <kdebug.h>
-#include <kurl.h>
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-TeamworkFolderManager* TeamworkFolderManager::m_self = 0;
-
-KUrl TeamworkFolderManager::workspaceDirectory() {
- return m_self->m_workspaceDir;
-}
-
-TeamworkFolderManager::TeamworkFolderManager( const KUrl& directory ) {
- m_self = this;
-
- KUrl u = directory;
- u.cleanPath();
-
- m_workspaceDir = u;
- u.addPath( ".teamwork" );
- u.cleanPath();
- m_teamworkDir = u;
-}
-
-TeamworkFolderManager* TeamworkFolderManager::self() {
- return m_self;
-}
-
-KUrl TeamworkFolderManager::teamworkAbsolute( const QString& subDirectory, const QString& subFolder ) {
- KUrl ret( self()->m_teamworkDir );
- ret.addPath( subFolder );
- if( subDirectory.startsWith( ret.toLocalFile() ) ) return subDirectory;
- ret.addPath( subDirectory );
- ret.cleanPath();
- return ret;
-}
-
-KUrl TeamworkFolderManager::workspaceAbsolute( const QString& subDirectory, const QString& subFolder ) {
- KUrl ret( self()->m_workspaceDir );
- ret.addPath( subFolder );
- if( subDirectory.startsWith( ret.toLocalFile() ) ) return subDirectory;
- ret.addPath( subDirectory );
- ret.cleanPath();
- return ret;
-}
-
-void TeamworkFolderManager::createTeamworkFolder() throw(QString) {
- KUrl ul = self()->m_workspaceDir;
-
- ul.addPath( ".teamwork" );
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- if( !KIO::NetAccess::mkdir( ul, 0 ) )
- throw QString( "could not create \"%1\"" ).arg( ul.prettyUrl() );
-}
-
-
-KUrl TeamworkFolderManager::createUniqueDirectory( const QString& subFolder, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
- if( self()->m_workspaceDir.isEmpty() )
- throw QString( "no teamwork-workspace-directory set" );
- KUrl ul = self()->m_workspaceDir;
-
- ul.addPath( ".teamwork" );
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- KIO::NetAccess::mkdir( ul, 0 );
-
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- throw QString( "could not create .teamwork-directory" );
-
-
- QStringList sub = subFolder.split( "/" );
- while( !sub.isEmpty() ) {
- ul.addPath( sub.front() );
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- KIO::NetAccess::mkdir( ul, 0 );
-
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- throw QString( "could not create directory %1 directory" ).arg( ul.prettyUrl() );
-
- sub.pop_front();
- }
-
-
- KUrl nu = ul;
- nu.addPath( namePrefix + name + nameSuffix );
- nu.cleanPath();
-
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
- KIO::NetAccess::mkdir( nu, 0 );
-
- if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
- return nu;
- }
-
- ///If the file exists try it with additional date/time
- nu = ul;
- nu.addPath( namePrefix + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix );
-
- nu.cleanPath();
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ) {
- KIO::NetAccess::mkdir( nu, 0 );
-
- if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
- return nu;
- }
-
- ///If even this file exists, add a suffix behind the date
- for( int a = 0; a < 100; a++ ) {
- nu = ul;
- nu.addPath( namePrefix + QString("_%1_").arg( a ) + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix );
- nu.cleanPath();
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
- KIO::NetAccess::mkdir( nu, 0 );
-
- if ( KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) )
- return nu;
- }
- }
-
- throw QString( "failed to allocate filename for %1" ).arg( name + "." + nameSuffix );
-}
-
-KUrl TeamworkFolderManager::createUniqueFile( const QString& subFolder, const QString& extension, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
- if( self()->m_workspaceDir.isEmpty() )
- throw QString( "no teamwork-workspace-directory set" );
- KUrl ul = self()->m_workspaceDir;
-
- ul.addPath( ".teamwork" );
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- KIO::NetAccess::mkdir( ul, 0 );
-
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- throw QString( "could not create .teamwork-directory" );
-
-
- QStringList sub = subFolder.split( "/" );
- while( !sub.isEmpty() ) {
- ul.addPath( sub.front() );
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- KIO::NetAccess::mkdir( ul, 0 );
-
- if ( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- throw QString( "could not create directory %1 directory" ).arg( ul.prettyUrl() );
-
- sub.pop_front();
- }
-
-
- KUrl nu = ul;
- nu.addPath( namePrefix + name + nameSuffix + "." + extension );
-
- nu.cleanPath();
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
- if( createFile( nu ) )
- return nu;
- }
-
- ///If the file exists try it with additional date/time
- nu = ul;
- nu.addPath( namePrefix + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix + "." + extension );
-
- nu.cleanPath();
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ) {
- if( createFile( nu ) )
- return nu;
- }
-
- ///If even this file exists, add a suffix behind the date
- for( int a = 0; a < 100; a++ ) {
- nu = ul;
- nu.addPath( namePrefix + QString("_%1_").arg( a ) + name + QDateTime::currentDateTime().toString( Qt::ISODate ) + nameSuffix + "." + extension );
- nu.cleanPath();
- if( !KIO::NetAccess::exists( nu, KIO::NetAccess::SourceSide, 0 ) ){
- if( createFile( nu ) )
- return nu;
- }
- }
-
- throw QString( "failed to allocate filename for %1" ).arg( name + "." + nameSuffix );
-}
-
-KUrl TeamworkFolderManager::createUniqueFile( const QString& subFolder, const QString& fileName, const QString& namePrefix, const QString& nameSuffix ) throw(QString) {
- QFileInfo i( fileName );
- KUrl u( subFolder );
- u.addPath( i.path() );
- return createUniqueFile( u.toLocalFile(), i.completeSuffix(), i.baseName(), namePrefix, nameSuffix );
-}
-
-void TeamworkFolderManager::registerTempItem( const KUrl& u ) {
- if( u.isRelative() )
- self()->m_tempItems[teamworkAbsolute(u.toLocalFile()).pathOrUrl()] = true;
- else
- self()->m_tempItems[u.pathOrUrl()] = true;
-}
-
-QString TeamworkFolderManager::teamworkRelative( const KUrl& url, const QString& subfolder ) {
- KUrl u = self()->m_teamworkDir;
- u.addPath( subfolder );
- u.adjustPath( KUrl::AddTrailingSlash );
- return KUrl::relativeUrl( u, url );
-}
-
-QString TeamworkFolderManager::workspaceRelative( const KUrl& url, const QString& subfolder ) {
- KUrl u = self()->m_workspaceDir;
- u.addPath( subfolder );
- u.adjustPath( KUrl::AddTrailingSlash );
- //kDebug(9500) << "workspaceRelative(" << url << "," << subfolder << ") called. Worspace:" << self()->m_workspaceDir << "base:" << u << "result:" << KUrl::relativeUrl( u, url );
- return KUrl::relativeUrl( u, url );
-}
-
-TeamworkFolderManager::~TeamworkFolderManager() {
- for( QMap< QString, bool >::iterator it = m_tempItems.begin();it != m_tempItems.end(); ++it ) {
- ///First, make sure that the file is really a subfolder of the .teamwork-directory
- KUrl f( it.key() );
- f.cleanPath();
- if( (f.path()).startsWith( m_teamworkDir.path(KUrl::AddTrailingSlash) ) && (f.pathOrUrl()).startsWith( m_teamworkDir.pathOrUrl() ) ) {
- if( ! KIO::NetAccess::del( f, 0 ) )
- kDebug(9500) << "TeamworkFolderManager error: File" << f.prettyUrl() << "could not be deleted";
- } else {
- kDebug(9500) << "TeamworkFolderManager error: File" << f.prettyUrl() << "was registered as temporary file, but is not in folder" << m_teamworkDir;
- }
- }
- m_tempItems.clear();
-}
-
-///@todo use netaccess!
-bool TeamworkFolderManager::createFile( const KUrl& url ) {
- QFile f( url.path() );
- if( f.open(QIODevice::WriteOnly) )
- return true;
- else
- return false;
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.h (nonexistent)
@@ -1,156 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef EDITPATCH_H
-#define EDITPATCH_H
-
-#include <QObject>
-#include "lib/network/sharedptr.h"
-#include "ui_kdevteamwork_editpatch.h"
-#include <QPointer>
-#include "safelogger.h"
-#include <memory>
-#include "patchmessage.h"
-
-
-namespace KParts{
- class Part;
-}
-
-class QDialog;
-
-class PatchesManager;
-namespace Diff2 {
-class KompareModelList;
-class DiffModel;
-}
-namespace KTextEditor {
- class SmartRange;
-}
-namespace Kompare {
- class Info;
-}
-namespace KDevelop {
-class IDocument;
-}
-
-///Delete itself when the document(or textDocument), or Diff-Model is deleted.
-class DocumentHighlighter : public QObject {
- Q_OBJECT
- public:
- DocumentHighlighter( const Diff2::DiffModel* model, KDevelop::IDocument* doc, bool isSource ) throw( QString );
- ~DocumentHighlighter();
- KDevelop::IDocument* doc();
- private slots:
- void documentDestroyed();
- private:
- QList<KTextEditor::SmartRange*> m_ranges;
- KDevelop::IDocument* m_doc;
-};
-
-class DiffSettings;
-
-class EditPatch : public QObject, public Shared, public SafeLogger {
- Q_OBJECT
- public:
- EditPatch( PatchesManager* parent, LocalPatchSourcePointer patch, bool local );
- ~EditPatch();
-
- void apply( bool reverse = false, const QString& fileName = "" );
-
- LocalPatchSourcePointer patch() const;
- signals:
- void dialogClosed( EditPatch* );
- void stateChanged( EditPatch* );
- private slots:
- void receivedTerminalData( const QString& s );
- void slotEditOk();
- void slotEditCancel();
- void slotEditFileNameChanged( const QString& str );
- void slotEditCommandChanged( const QString& str );
- void slotFileNameEdited();
- void slotCommandEdited();
- void slotEditMimeType( const QString& str );
- void slotEditDialogFinished( int result );
- void slotChooseType();
- void slotStateChanged();
- void slotApplyEditPatch();
- void slotUnapplyEditPatch();
- void slotShowEditPatch();
- void dialogDestroyed();
- void slotDetermineState();
- void slotToFile();
- void slotUserButton();
-
- void fileDoubleClicked( const QModelIndex& i );
- void fileSelectionChanged();
-
- void nextHunk();
- void prevHunk();
- void highlightFile();
-
- void updateKompareModel();
-
- void updateByType();
- private:
- void seekHunk( bool forwards, bool isSource, const QString& file = QString() );
-
- virtual std::string logPrefix();
-
- void showEditDialog();
- void hideEditDialog();
- void editPatchReadOnly();
- LocalPatchSource::State editState();
- void fillEditFromPatch();
- LocalPatchSourcePointer patchFromEdit();
-
- void removeHighlighting( const QString& file = QString() );
-
- LocalPatchSource::State m_actionState;
-
- ///Gets local patches via a fake-session
- SafeSharedPtr<PatchMessage> getPatchMessage( PatchRequestData::RequestType type );
- ///Tries to locally get the patch-message and then store it to a temporary file. If successful returns the filename.
- KUrl getPatchFile(bool temp = false);
-
- PatchesManager* m_parent;
- LocalPatchSourcePointer m_editingPatch;
- bool m_editPatchLocal;
-
- Ui_EditPatch m_editPatch;
- QDialog* m_editDlg;
-
- QTime m_lastDataTime;
- QString m_lastTerminalData;
-
- QPointer<KParts::Part> m_konsolePart;
-
- QTimer* m_updateKompareTimer;
-
- bool m_reversed;
- bool m_started;
- QStandardItemModel* m_filesModel;
- QPointer<DiffSettings> m_diffSettings;
- auto_ptr<Kompare::Info> m_kompareInfo;
- auto_ptr<Diff2::KompareModelList> m_modelList;
- QString m_lastModelCommand, m_lastModelFile;
- typedef QMap<QString, QPointer<DocumentHighlighter> > HighlightMap;
- HighlightMap m_highlighters;
- bool m_isSource;
-};
-
-typedef SharedPtr<EditPatch> EditPatchPointer;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp (nonexistent)
@@ -1,43 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "indocumentmessage.h"
-#include "lib/network/messagetypeset.h"
-#include "kdevteamwork_messageshower.h"
-
-///@todo move some stuff from conversationmanager.cpp here
-
-///Can be used to get and set the context-lines
-DocumentContextLines& InDocumentMessage::contextLines() {
- return m_contextLines;
-}
-
-InDocumentReference& InDocumentMessage::start() {
- return m_start;
-}
-
-InDocumentReference& InDocumentMessage::end() {
- return m_end;
-}
-
-QString InDocumentMessage::shortName() const {
- return "Document-Message";
-}
-
-void InDocumentMessage::showInWidget( QWidget* widget, KDevTeamwork* tw ) {
- new InDocumentMessageShower( this, widget, tw );
-}
-
-REGISTER_MESSAGE( InDocumentMessage )
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentmessage.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.cpp (nonexistent)
@@ -1,51 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "serializationutils.h"
-#include <sstream>
-
-#ifdef XML_USE_TEXT_ARCHIVE
-#include <boost/archive/polymorphic_text_iarchive.hpp>
-#include <boost/archive/polymorphic_text_oarchive.hpp>
-typedef boost::archive::polymorphic_text_iarchive XmlIArchive;
-typedef boost::archive::polymorphic_text_oarchive XmlOArchive;
-#else
-#include <boost/archive/polymorphic_xml_iarchive.hpp>
-#include <boost/archive/polymorphic_xml_oarchive.hpp>
-typedef boost::archive::polymorphic_xml_iarchive XmlIArchive;
-typedef boost::archive::polymorphic_xml_oarchive XmlOArchive;
-#endif
-
-struct IArchiveContainer::Private {
- XmlIArchive arch;
- Private( istream& str ) : arch( str ) {
- }
-};
-
-struct OArchiveContainer::Private {
- XmlOArchive arch;
- Private( ostream& str ) : arch( str ) {
- }
-};
-IArchiveContainer::IArchiveContainer( istream& str ) : priv( new Private( str ) ), arch( priv->arch ) {
-}
-
-IArchiveContainer::~IArchiveContainer() {
- delete priv;
-}
-
-OArchiveContainer::OArchiveContainer( ostream& str ) : priv( new Private( str ) ), arch( priv->arch ) {
-}
-
-OArchiveContainer::~OArchiveContainer() {
- delete priv;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/serializationutils.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui (nonexistent)
@@ -1,172 +0,0 @@
-<ui version="4.0" >
- <class>VectorTimestampWidget</class>
- <widget class="QWidget" name="VectorTimestampWidget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>760</width>
- <height>172</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QGroupBox" name="timestampsGroup" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Expanding" hsizetype="Preferred" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="title" >
- <string>Timestamps</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="groupBox_2" >
- <property name="title" >
- <string>Log</string>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QListView" name="log" >
- <property name="selectionMode" >
- <enum>QAbstractItemView::NoSelection</enum>
- </property>
- <property name="selectionBehavior" >
- <enum>QAbstractItemView::SelectRows</enum>
- </property>
- <property name="resizeMode" >
- <enum>QListView::Fixed</enum>
- </property>
- <property name="layoutMode" >
- <enum>QListView::Batched</enum>
- </property>
- <property name="batchSize" >
- <number>50</number>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QPushButton" name="toTailTimestamp" >
- <property name="text" >
- <string>To Tail State</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="clearLog" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Minimum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Clear Log</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="stateInfo" >
- <property name="text" >
- <string>Current State: Tail State: </string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>301</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_vectortimestampwidget.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui (nonexistent)
@@ -1,875 +0,0 @@
-<ui version="4.0" >
- <class>Teamwork</class>
- <widget class="QWidget" name="Teamwork" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>321</width>
- <height>748</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="1" column="0" >
- <widget class="QToolBox" name="toolBox" >
- <property name="currentIndex" >
- <number>1</number>
- </property>
- <widget class="QWidget" name="connection" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>204</width>
- <height>245</height>
- </rect>
- </property>
- <attribute name="label" >
- <string>Connection</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QTabWidget" name="connectionTab" >
- <property name="enabled" >
- <bool>true</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="maximumSize" >
- <size>
- <width>16777215</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="currentIndex" >
- <number>1</number>
- </property>
- <widget class="QWidget" name="localTab" >
- <attribute name="title" >
- <string>Local server</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="2" column="0" >
- <widget class="QListView" name="connectedClients" />
- </item>
- <item row="1" column="0" >
- <widget class="QLabel" name="connectedClientsLabel" >
- <property name="text" >
- <string>Connected clients:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="QCheckBox" name="allowIncoming" >
- <property name="text" >
- <string>Allow incoming</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="remoteTab" >
- <attribute name="title" >
- <string>Servers</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="3" column="0" colspan="3" >
- <widget class="QListView" name="connectedServers" />
- </item>
- <item row="1" column="1" >
- <widget class="KLineEdit" name="loginPassword" >
- <property name="toolTip" >
- <string>the password for logging into the server</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2" >
- <widget class="QPushButton" name="connectServer" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Fixed" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip" >
- <string>connect to the given server using the given login-information(if the name is blank the local name is used)</string>
- </property>
- <property name="text" >
- <string>Connect</string>
- </property>
- </widget>
- </item>
- <item row="0" column="0" colspan="3" >
- <widget class="QComboBox" name="serverBox" >
- <property name="toolTip" >
- <string>the server to connect</string>
- </property>
- <property name="editable" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="0" colspan="3" >
- <widget class="QLabel" name="connectedServersLabel" >
- <property name="text" >
- <string>Connected servers:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="KLineEdit" name="loginName" >
- <property name="toolTip" >
- <string>the user-name for logging into the server</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="developers" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>303</width>
- <height>335</height>
- </rect>
- </property>
- <attribute name="label" >
- <string>Developers</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QLabel" name="availableLabel" >
- <property name="text" >
- <string>Available:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="QTreeView" name="availableDevelopers" >
- <property name="enabled" >
- <bool>true</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>16777215</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="sizeIncrement" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="baseSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="lineWidth" >
- <number>1</number>
- </property>
- <property name="editTriggers" >
- <set>QAbstractItemView::NoEditTriggers</set>
- </property>
- <property name="alternatingRowColors" >
- <bool>true</bool>
- </property>
- <property name="indentation" >
- <number>15</number>
- </property>
- <property name="rootIsDecorated" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="3" column="0" >
- <widget class="QTreeView" name="connectedDevelopers" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Expanding" hsizetype="Expanding" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>16777215</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="editTriggers" >
- <set>QAbstractItemView::NoEditTriggers</set>
- </property>
- <property name="alternatingRowColors" >
- <bool>true</bool>
- </property>
- <property name="indentation" >
- <number>15</number>
- </property>
- <property name="rootIsDecorated" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="connectedLabel" >
- <property name="text" >
- <string>Collaborating:</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="messaging" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>226</width>
- <height>286</height>
- </rect>
- </property>
- <attribute name="label" >
- <string>Messaging</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="KComboBox" name="messageTargetUser" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Fixed" hsizetype="Preferred" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip" >
- <string>target-user</string>
- </property>
- <property name="editable" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="answeringToButton" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Maximum" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="contextMenuPolicy" >
- <enum>Qt::NoContextMenu</enum>
- </property>
- <property name="autoFillBackground" >
- <bool>true</bool>
- </property>
- <property name="text" >
- <string>Answer To</string>
- </property>
- <property name="checkable" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="typeLabel" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>50</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="layoutDirection" >
- <enum>Qt::LeftToRight</enum>
- </property>
- <property name="text" >
- <string>Type:</string>
- </property>
- <property name="alignment" >
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="messageType" >
- <item>
- <property name="text" >
- <string>Message</string>
- </property>
- </item>
- <item>
- <property name="text" >
- <string>Comment</string>
- </property>
- </item>
- <item>
- <property name="text" >
- <string>Source-discussion</string>
- </property>
- </item>
- </widget>
- </item>
- </layout>
- </item>
- <item row="3" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="contextLabel" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Thread:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="context" />
- </item>
- </layout>
- </item>
- <item row="2" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>2</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="referenceLabel" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Reference:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="reference" />
- </item>
- </layout>
- </item>
- <item row="5" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QPushButton" name="clearMessageButton" >
- <property name="text" >
- <string>Clear</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>71</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="sendMessage" >
- <property name="text" >
- <string>&amp;Send message</string>
- </property>
- <property name="shortcut" >
- <string>S</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="4" column="0" >
- <widget class="KTextEdit" name="messageText" >
- <property name="toolTip" >
- <string>the message you wish to send</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="localstate" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>179</width>
- <height>49</height>
- </rect>
- </property>
- <attribute name="label" >
- <string>Local state</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QPushButton" name="managePatches" >
- <property name="text" >
- <string>Manage local patches</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QTabWidget" name="historyTab" >
- <property name="currentIndex" >
- <number>0</number>
- </property>
- <widget class="QWidget" name="messagesTab" >
- <attribute name="title" >
- <string>Messages</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QTabWidget" name="messageUsers" >
- <property name="currentIndex" >
- <number>0</number>
- </property>
- <widget class="QWidget" name="allUsersTab" >
- <attribute name="title" >
- <string>All Users</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QTreeView" name="messageList" >
- <property name="isWrapping" stdset="0" >
- <bool>false</bool>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item row="1" column="0" >
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QPushButton" name="clearMessages" >
- <property name="text" >
- <string>Clear</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="messageHistory" >
- <property name="text" >
- <string>History</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="logTab" >
- <attribute name="title" >
- <string>Log</string>
- </attribute>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QListView" name="logList" />
- </item>
- <item>
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QPushButton" name="clearLog" >
- <property name="text" >
- <string>Clear</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="saveLog" >
- <property name="text" >
- <string>Save</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="logFilter" >
- <property name="text" >
- <string>Filter</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="QCheckBox" name="enableCollaboration" >
- <property name="text" >
- <string>Enable Collaboration</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KComboBox</class>
- <extends>QComboBox</extends>
- <header>kcombobox.h</header>
- </customwidget>
- <customwidget>
- <class>KTextEdit</class>
- <extends>QTextEdit</extends>
- <header>ktextedit.h</header>
- </customwidget>
- <customwidget>
- <class>KLineEdit</class>
- <extends>QLineEdit</extends>
- <header>klineedit.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_interface.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.h (nonexistent)
@@ -1,27 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef HELPERS_H
-#define HELPERS_H
-
-#include "teamworkfwd.h"
-
-///This header contains little helper-functions that have no other dependencies than teamworkfwd.h
-
-/**Returns the user the session is pointing to, and returns zero if the session is zero.
- * */
-Teamwork::UserPointer userFromSession( const Teamwork::SessionPointer& session );
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/README
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/README (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/README (nonexistent)
@@ -1,51 +0,0 @@
-Some notes about this plugin from commit-digest/2006-09-10:
-When I first heard about Summer Of Code I thought about proposing a project called "Advanced Code Completion for KDevelop 3"(with full support for templates, comments, etc.), but when that didn't go down well with most of the KDevelop developers (since they were already focused on KDevelop 4), I just started implementing it. I spent a lot of time working on that until SOC started (and even quite some time since then), and you can see the result in the current KDevelop 3.4 SVN tree. I finished everything I planned and more.
-
-Some of the features:
-Intelligent resolution of types.
-Support for templates like for example shared pointers.
-Support for implicit template-instatiation
-Nicer and more useful completion-list with items ordered in a useful way and indented by inheritance-depth, with popups that include comments and any other interesting information
-Many improvements in the parser, for example all comments are extracted and used in any possible way, macros are dealt with correctly, Enums are handled in a more useful way, and much more
-A powerful navigation-menu: Click any item within a function and see it's real type, a trace of all typedefs on the way to that type, information on all involved typedefs, classes, variables, functions, etc., and the same as a submenu for all involved template-parameters, argument-types, base-classes, etc.
-Improved jump-to-menus and navigation-bar.
-Highlighting of function-names in the navigation-bar and class-tree.
-And countless other major improvements in code-completion and navigation.. see the feature list of the beta releases or the commit log to see all of them.
-
-KDevelop 3 is doing well feature-wise, but currently lacks developers since the focus already is on KDevelop 4, but it'll take a long time until that is really usable, so I hereby encourage anyone interested to start using the SVN version of KDevelop 3.4 and hunt down a few bugs, to make sure that a stable version can be released soon.
-
-Collaboration through the internet is fundamental to most open-source-software. Almost any open- and even closed-source-software might profit from better collaboration-possibilities. If you work for a project that has a collaboration-server, you can directly ask other developers working on the same project for very specific help, patches can be reviewed very quickly, and discussion can instantly take place within the documents themselves. File Collaboration may also be useful for discussion of new ideas, teaching, for friends less experienced in programming requesting help (Or am I the only one who is asked how to program something through ICQ again and again?), and simply because it's cool ;)
-
-So I took the basic Idea for the Summer Of Code project "KDevelop Teamwork" from the Wiki where someone proposed it, and developed it using my own Ideas, trying to add some of the teamwork features I always missed in any IDE I ever used. :)
-
-Generally it consists of four parts:
-Client/Server Architecture
-I created a multi-threaded library for networking, including client/server- and user-management, and a standalone server not dependent on Qt which can be run on any webserver and administrated using the console.
-
-File Collaboration
-An arbitrary count of developers can collaboratively edit a dynamic set of files, and the edited documents can be dynamically transformed (for example chosen changes made by exactly one user could be undone, which will allow single-user undo, redo, etc.)
-
-Conversation
-All users connected to any of the connected servers, as well as the servers themselves (in the case they are not standalone) can be contacted by using instant messages, collaboration-requests, patch-requests, in-document messages, etc.
-
-The most interesting message for conversation is the in-document message: It can reference a position or piece of text within any document, and the receiver of the message automatically jumps to that document and highlights the referenced piece of text as the message is selected, and pops up a chat-window within the document itself at the found position, where other messages of the same thread may be selected and discussion can take place.
-
-Any answers written into the chat will automatically reference the currently selected text. Referencing is simply done by marking a piece of text before sending a message, and the reference-position is being found by a fuzzy algorithm I developed which tries to find the correct place even within totally different documents (and is pretty successful at doing so).
-
-Patch Management
-Every user can manage a set of patches (or other file types) for each project. They can either be files or dynamic patches which are automatically retrieved from commands on request (for example "svn diff"). Patches can be easily shared directly through the developer-list, using different access-levels.
-
-A modified version of Kompare's diff3-library is used to get information from patches. Using that the patch-manager can automatically highlight all changes made by an applied patch within all documents, and allows you to easily browse through those positions so you can review the patch within the correct context and directly discuss about it using in-document messages.
-
-They can be applied/reverted to the local tree using single buttons, and for diff-files it is possible to automatically determine whether the patch is already applied or not. If problems arise within the patching process they can be dealt with using an embedded console in the patch-management-window.
-It is important that all those features are well integrated: For example you can store the results of a file-collaboration-session as a patch into your local patches-list, and thereby share it with other developers and easily revert it at any time, and you can use in-document messages directly within the temporary file-collaboration files.
-
-To store all the project-specific data (like patches), a ".teamwork" subfolder is created within the project directory.
-
-I encountered many problems during development. Apart from one harddisk crash, the most annoying problem was the very unstable and (in the begginning) difficult to compile kdelibs/qt-copy/qdbus/kdesupport etc. combination, which again and again cost me days and hours just to get it working.
-
-The most challenging part was the file-collaboration. Getting a simple form of collaborative editing to work was quite fast, but making the document-transformation work correctly in all test-cases really took some time, and I had to finish it after the deadline without stress (luckily I didn't mention anything like it in my application ;)). The trick was writing everything down and trying to solve it mathematically as I learnt at university, unfortunately I got that idea after days of unsuccessful hacking and trying - well... you live and learn :)
-
-I was able to finish nearly everything I planned until the deadline, but unfortunately I missed the week I planned in my application for "debug, make it perfect", so that work is missing, and it shows :) Most of the work I did after the Summer Of Code ended was in other, more important parts (finishing the text-transformation algorithm, or fixing file-collaboration which stopped working after a kdelibs-update), but it is work I'll surely do. Then there's one other big problem, the executable-size when the executable is built with debug-information. During my work on this project I fell in love with templates and meta-programming, but I think the main reason is my use of boost serialization, I'll still have to work on that. Then of course i'll need some nice icons. :)
-
- Now that the Summer Of Code has concluded, the first thing I will do is working intensively for the institute of my university that paid me the whole year, and that I neglected since March because of my work for KDevelop 3 Code Completion and then the Summer Of Code. Of course, I won't forget KDevelop and KDE in general, since I like the Open-Source Idea a lot. I started working on Open-Source Software before I started the Summer Of Code, and I won't stop it now that it's over :) I'll keep maintaining the teamwork-module (and of course finish it), I'll keep caring about KDevelop, and maybe I'll start a project to make KDE more Tablet PC friendly if I can find the time for it.
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/README
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/sumsearch.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/sumsearch.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/sumsearch.h (nonexistent)
@@ -1,624 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SUMSEARCH_H
-#define SUMSEARCH_H
-
-#include <cstdio>
-#include <cstdlib>
-#include <string>
-#include <vector>
-
-///For higher orders to work, the sum-type has to be signed
-#define DEFAULTSUMTYPE int
-#define DEFAULTORDER 2
-
-
-///State-based-build can only nearly complete with extreme compiler-parameters set, although it should theoretically be faster, if the compile would optimize it the right way.
-
-//#define STATEBASEDBUILD
-
-namespace FuzzySearch {
-
-/**
- * How should all the differences be weighed together to a compound difference?
- *
- * The weighting still needs some work.
- *
- * */
-
-template < class Compare1, class Compare2, class Then, class Else >
-class IfEqual {
-public:
- typedef Else Result;
-};
-
-template < class Compare, class Then, class Else >
-class IfEqual<Compare, Compare, Then, Else> {
-public:
- typedef Then Result;
-};
-
-template <class Item>
-class PrimitiveVector {
- Item* data_;
- uint size_;
- public:
- PrimitiveVector() : data_( 0 ), size_( 0 ) {}
- ;
-
- ~PrimitiveVector() {
- if ( data_ )
- delete[] data_;
- }
-
- ///All data is lost when this is called
- void rawResize( unsigned int i ) {
- if ( size_ == i )
- return ;
- size_ = i;
- if ( data_ )
- delete[] data_;
- if ( !i ) {
- data_ = 0;
- } else {
- data_ = new Item[ i ];
- }
- };
-
- Item& operator [] ( uint index ) {
- return data_[ index ];
- }
-
- const Item& operator [] ( uint index ) const {
- return data_[ index ];
- }
-
- uint size() const {
- return size_;
- }
-};
-
-///unsigned int is ok for document-sizes of up to about 16 Megabytes, 64-bit integers create problems here
-using namespace std;
-template <int maxDepth, class SumType = DEFAULTSUMTYPE>
-struct SumGroup {
- SumType sums[ maxDepth ];
-
- SumGroup( SumType* _sums = 0 ) {
- if ( _sums ) {
- for ( int a = 0; a < maxDepth; a++ ) {
- sums[ a ] = _sums[ a ];
- }
- } else {
- for ( int a = 0; a < maxDepth; a++ )
- sums[ a ] = 0;
- }
- }
-
- /*
- SumType sumDifference( const SumGroup& rhs ) const {
- SumType ret = 0;
- for( int a = 0; a < maxDepth; a++ ) {
- SumType dif;
- if( sums[a] > rhs.sums[a] )
- dif = sums[a] - rhs.sums[a];
- else
- dif = rhs.sums[a] - sums[a];
-
- ret += ( dif * (maxDepth - a ) ) >> a;
- }
- return ret;
- };*/
-
- struct VecSumGetter {
- SumType** sumVec;
- VecSumGetter() : sumVec( 0 ) {}
- VecSumGetter( SumType** vec ) : sumVec( vec ) {}
-
- inline bool sumValid( const uint num ) const {
- return ( bool ) sumVec[ num ];
- }
-
-
- inline SumType sum( const uint num ) const {
- return * ( sumVec[ num ] );
- }
- };
-
- struct ZeroGetter {
- inline bool sumValid( const uint num ) const {
- return false;
- }
- inline SumType sum( const uint num ) const {
- return 0;
- }
- };
-
- struct GroupSumGetter {
- SumGroup& group;
- GroupSumGetter( SumGroup& grp ) : group( grp ) {}
-
- inline bool sumValid( const uint num ) const {
- return true;
- }
-
-
- inline SumType sum( const uint num ) const {
- return group.sums[ num ];
- }
- };
-
- template <class SumGetter>
- SumType sumDifference( const SumGetter& getter ) const {
- SumType ret = 0;
- for ( int a = 0; a < maxDepth; a++ ) {
- SumType dif;
- if ( getter.sumValid( a ) ) {
- if ( sums[ a ] > getter.sum( a ) )
- dif = sums[ a ] - getter.sum( a );
- else
- dif = getter.sum( a ) - sums[ a ];
- } else {
- dif = sums[ a ];
- }
-
- ///The weighting is a bit primitive at the moment
- ret += ( dif * ( ( maxDepth - a ) + 1 ) ) /* >> a*/;
- }
- return ret;
- }
-
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & sums;
- }
-};
-
-template < int Condition, class Then, class Else >
-struct IfThen {
- typedef Then Result;
-};
-
-template < class Then, class Else >
-struct IfThen <0, Then, Else> {
- typedef Else Result;
-};
-
-
-template <int maxDepth, typename SumType, int order, bool dummy>
-class DifferenceSumReference {
- public:
- template <class Archive>
- void serialize( Archive& /*arch*/, const uint /*version*/ ) {}
-}
-;
-
-template <int maxDepth, class SumType = DEFAULTSUMTYPE, int order = DEFAULTORDER>
-class SumReference {
- bool valid_;
- public:
- SumGroup<maxDepth, SumType> leftMarker;
- SumGroup<maxDepth, SumType> rightMarker;
-
- DifferenceSumReference < maxDepth, SumType, order - 1, ( order - 1 ) == 0 > nextOrder_;
-
- SumReference() : valid_( false ) {}
-
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & valid_ & leftMarker & rightMarker;
- arch & nextOrder_;
- }
-
- void setValid( bool valid ) {
- valid_ = valid;
- }
-
- bool isValid() const {
- return valid_;
- }
-};
-
-
-template <int maxDepth, typename SumType, int order>
-struct DifferenceSumReference<maxDepth, SumType, order, false> {
- SumReference<maxDepth, SumType, order> reference_;
-public:
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & reference_;
- }
-};
-
-/** The problem with a single sum-search: 123456| is detected as exactly same as 124356|.
- * For that reason a parallel difference-sum-search can be used, which would look like 111111| in the first, and 112(-1)21| in the second case.
- * SumType must be signed for that to work.
- * */
-
-
-template <int maxDepth, typename SumType, int order, bool dummy>
-class DifferenceSumSearch {
- public:
- DifferenceSumSearch( const string& /*text*/ ) {}
- template <class Type>
- void fillReference( Type& /*t*/, int /*position*/ ) {}
-
- template <class PrevType, class Evaluator>
- struct FindRefProgress {
- FindRefProgress( PrevType& /*t*/, const SumReference < maxDepth, SumType, order + 1 > & /*_ref*/, Evaluator& /*_eval*/ ) {}
- SumType leftDiff() {
- return 0;
- }
-
- SumType rightDiff() {
- return 0;
- }
-
- void next() {}
- }
- ;
-};
-
-
-template <class SumType, int Depth, int EndDepth>
-struct SumBuildState : public SumBuildState < SumType, Depth + 1, EndDepth > {
- typedef SumBuildState< SumType, Depth, EndDepth> Self;
- typedef SumBuildState < SumType, Depth + 1, EndDepth > Next;
- typedef SumBuildState< SumType, 0, EndDepth> Head;
- SumType* v;
-
- uint tempSumC;
- SumType tempSum;
- const char* text;
- const char* ctext;
- uint offset;
-
- //uint maxCount = 1<<b;
-
- SumBuildState( PrimitiveVector<SumType>* sumVecs_, const char* tx ) : Next( sumVecs_, tx ), tempSumC( 0 ), tempSum( 0 ), text( tx ), ctext( tx ), offset( 0 ) {
- v = &( sumVecs_[ Depth ][ 0 ] );
- }
-
- inline void go1( register const char* ctex, register const uint offset ) {
- Next::go1( ctex, offset );
- {
- if ( tempSumC == ( uint ) ( 1 << Depth ) ) {
- ///remove the first summand
- tempSum -= *( ctex - ( 1 << Depth ) );
- } else {
- tempSumC ++;
- }
-
- tempSum += *ctex;
- ( * ( v + offset ) ) = tempSum;
- }
- }
-
- /* inline void go2( register uint offset ) {
- Next::go2( offset );
- //++v;
- }*/
-
- inline void go() {
- go1( ctext, offset );
-
- //go2( offset );
-
- ++ctext;
- ++offset;
- }
-};
-
-template <class SumType, int Depth>
-struct SumBuildState<SumType, Depth, Depth> {
- SumBuildState( PrimitiveVector<SumType>*, const char* ) {}
- ;
-
- inline void go1( register const char* ctex, register const uint offset ) {}
- // inline void go2() {
- // }
-}
-;
-
-
-template <int maxDepth, typename SumType = DEFAULTSUMTYPE, int order = DEFAULTORDER>
-class SumSearch {
- typedef SumSearch<maxDepth, SumType, order> SelfSumSearch;
- typedef PrimitiveVector< SumType > SumVector;
- string text_;
- SumVector sumVecs_[ maxDepth ];
- typedef DifferenceSumSearch < maxDepth, SumType, order - 1, ( order - 1 ) == 0 > NextOrderType;
-
-#ifdef STATEBASEDBUILD
-
- void buildSumGroups() {
- for ( int a = 0; a < maxDepth; a++ ) {
- sumVecs_[ a ].rawResize( text_.size() );
- }
-
- SumBuildState< SumType, 0, maxDepth > state( sumVecs_, text_.c_str() );
-
- uint textSize = text_.size();
-
- for ( uint a = 0; a < textSize; a++ ) {
- state.go();
- }
- }
-#else
- void buildSumGroups() {
- for ( int a = 0; a < maxDepth; a++ ) {
- sumVecs_[ a ].rawResize( text_.size() );
- }
-
- const char* text = text_.c_str();
- uint textSize = text_.size();
-
- for ( uint b = 0; b < maxDepth; b++ ) {
-
- SumType* v = &( sumVecs_[ b ][ 0 ] );
- uint tempSumC = 0;
- SumType tempSum = 0;
- uint maxCount = 1 << b;
-
- const char* ctext = text;
-
- for ( uint a = 0; a < textSize; a++ ) {
- if ( tempSumC == maxCount ) {
- ///remove the first summand
- tempSum -= *( ctext - maxCount );
- } else {
- tempSumC ++;
- }
-
- tempSum += ( *ctext );
-
- ( *v ) = tempSum;
- ++v;
- ++ctext;
- }
- }
- }
-#endif
-
- public:
- NextOrderType nextOrder_;
-
- SumSearch( const string& text ) : nextOrder_( text ) {
- text_ = text;
- buildSumGroups();
- }
-
- ///position != 0
- SumReference<maxDepth, SumType, order> getReference( int position ) {
- SumReference<maxDepth, SumType, order> ret;
- fillReference( ret, position );
-
- nextOrder_.fillReference( ret, position );
- return ret;
- }
-
-
- ///Should not be used from outside
- void fillReference( SumReference<maxDepth, SumType, order>& ret, int position ) {
- int leftPos = position - 1;
- SumType leftSums[ maxDepth ];
- SumType rightSums[ maxDepth ];
-
- if ( leftPos >= 0 ) {
- for ( int a = 0; a < maxDepth; a++ )
- leftSums[ a ] = sumVecs_[ a ] [ leftPos ];
- } else {
- for ( int a = 0; a < maxDepth; a++ )
- leftSums[ a ] = 0;
- }
-
- for ( int a = 0; a < maxDepth; a++ ) {
- uint pos = leftPos + ( 1 << a );
- if ( pos < sumVecs_[ 0 ].size() )
- rightSums[ a ] = sumVecs_[ a ][ pos ];
- else
- rightSums[ a ] = 0;
- }
-
- ret.leftMarker = SumGroup<maxDepth, SumType>( leftSums );
- ret.rightMarker = SumGroup<maxDepth, SumType>( rightSums );
- ret.setValid( true );
- }
-
-
- struct SimpleEvaluator {
- SumType minDif;
- uint minDifPos;
-
- SimpleEvaluator() : minDif( 100000 ), minDifPos( -1 ) {}
- /**This should return a new compound difference-value. In the end, the position with the lowest difference will be returned,
- *so this may be used to implement some weighting, maybe according to the position */
- inline void operator () ( const SumType leftDifference, const SumType rightDifference, const uint position ) {
- SumType dif = ( leftDifference + 1 ) * ( rightDifference + 1 );
-
- if ( dif < minDif ) {
- //cout << "best dif: " << dif << endl;
- minDif = dif;
- minDifPos = position;
- }
- }
-
- uint result() {
- return minDifPos;
- }
- };
-
- SumVector* sumVecs() {
- return sumVecs_;
- }
-
- template <class Evaluator>
- struct FindReferenceProgress {
- SumReference<maxDepth, SumType, order>& ref;
- Evaluator& eval;
-
- typename NextOrderType::template FindRefProgress<SelfSumSearch, Evaluator>
- nextOrder_;
-
- SumType* leftOffset[ maxDepth ];
- SumType* rightOffset[ maxDepth ];
-
- SumType* firstItem;
- SumType* finalRight[ maxDepth ];
-
- SumVector* sumVecs_;
-
- typename SumGroup<maxDepth, SumType>::VecSumGetter leftGetter;
- typename SumGroup<maxDepth, SumType>::VecSumGetter rightGetter;
- typedef typename SumGroup<maxDepth, SumType>::ZeroGetter ZeroGetter;
-
- FindReferenceProgress( SelfSumSearch& search, const SumReference<maxDepth, SumType, order>& _ref, Evaluator& _eval ) : ref( const_cast<SumReference<maxDepth, SumType, order>&>( _ref ) ), eval( _eval ), nextOrder_( search, ref, _eval ), sumVecs_( search.sumVecs() ) {
- for ( uint a = 0; a < maxDepth; a++ ) {
- leftOffset[ a ] = &( sumVecs_[ a ][ 0 - 1 ] );
-
- if ( ( uint ) ( 1 << a ) < ( uint ) sumVecs_[ 0 ].size() ) {
- rightOffset[ a ] = &( sumVecs_[ a ][ ( 1 << a ) - 1 ] );
- } else {
- rightOffset[ a ] = 0;
- }
- }
-
- firstItem = &sumVecs_[ 0 ][ 0 ];
-
- for ( int a = 0; a < maxDepth; a++ )
- finalRight[ a ] = &( sumVecs_[ a ][ sumVecs_[ a ].size() - 1 ] );
-
- leftGetter = typename SumGroup<maxDepth, SumType>::VecSumGetter( leftOffset );
- rightGetter = typename SumGroup<maxDepth, SumType>::VecSumGetter( rightOffset );
- }
-
- operator bool() {
- return ( bool ) rightOffset[ 0 ];
- }
-
- void next() {
- for ( int a = 0; a < maxDepth; a++ ) {
- ++leftOffset[ a ];
- if ( !rightOffset[ a ] )
- break;
- ++rightOffset[ a ];
- if ( rightOffset[ a ] > finalRight[ a ] )
- rightOffset[ a ] = 0;
- }
- nextOrder_.next();
- }
-
- SumType leftDiff() {
- if ( leftOffset[ 0 ] < firstItem ) {
- return ref.leftMarker.sumDifference( ZeroGetter() ) + nextOrder_.leftDiff();
- }
- return ref.leftMarker.sumDifference( leftGetter ) + nextOrder_.leftDiff();
- }
-
- SumType rightDiff() {
- return ref.rightMarker.sumDifference( rightGetter ) + nextOrder_.rightDiff();
- }
-
- uint difPos() {
- return ( ((unsigned long)rightOffset[ 0 ] ) - (unsigned long)firstItem ) / sizeof( uint* );
- }
- };
-
- template <class Evaluator>
- int findReference( const SumReference<maxDepth, SumType, order>& ref, Evaluator& eval ) {
- if ( !ref.isValid() )
- return -1;
- if ( sumVecs_[ 0 ].size() < 2 )
- return -1;
-
- FindReferenceProgress<Evaluator> prog( *this, ref, eval );
-
- while ( prog ) {
- SumType leftDif = 0; //prog.leftDiff();
- SumType rightDif = prog.rightDiff();
- uint difPos = prog.difPos();
-
- eval( leftDif, rightDif, difPos );
-
- prog.next();
- }
- return eval.result();
- }
-
- ///This uses the default-evaluator
- inline int findReference( const SumReference<maxDepth, SumType, order>& ref ) {
- SimpleEvaluator eval;
- return findReference( ref, eval );
- }
-};
-
-
-template <int maxDepth, typename SumType, int order>
-class DifferenceSumSearch<maxDepth, SumType, order, false> {
- typedef SumSearch<maxDepth, SumType, order> MySearch;
- typedef SumSearch < maxDepth, SumType, order + 1 > MyPrevSearch;
- MySearch search_;
-
- static string makeDifference( const string& str ) {
- string ret = str;
- uint len = ret.length();
- char last = 0;
- if ( !ret.empty() )
- last = ret[ 0 ];
-
- for ( uint n = 0; n < len; n++ ) {
- char r = ret[ n ];
- ret[ n ] = r - last;
- last = r;
- }
- return ret;
- }
-
- public:
- DifferenceSumSearch( const string& text ) : search_( makeDifference( text ) ) {}
-
- template <class Type>
- void fillReference( Type& t, int position ) {
- search_.fillReference( t.nextOrder_.reference_, position );
- }
-
- template <class PrevSearch, class Evaluator>
- struct FindRefProgress {
- typename MySearch:: template FindReferenceProgress<Evaluator>
- find;
-
- FindRefProgress( PrevSearch& search, const SumReference < maxDepth, SumType, order + 1 > & _ref, Evaluator& _eval ) : find( search.nextOrder_.search_, _ref.nextOrder_.reference_, _eval )
- {}
-
- SumType leftDiff() {
- return find.leftDiff();
- }
- SumType rightDiff() {
- return find.rightDiff();
- }
-
- void next() {
- find.next();
- }
- };
-};
-
-
-} //FuzzySearch
-
-using namespace FuzzySearch;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/sumsearch.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.cpp (nonexistent)
@@ -1,173 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "messagemanager.h"
-#include "kdevteamwork.h"
-#include "serializationutils.h"
-#include "conversationmanager.h"
-#include "guimessagehistory.h"
-#include "messagehistorymanager.h"
-#include "lib/network/messagetypeset.h"
-#include <kdialog.h>
-#include <QMenu>
-#include "kdevteamwork_messageshower.h"
-
-#include <QList>
-#include <QAction>
-
-Q_DECLARE_METATYPE( MessagePointer )
-
-
-
-MessageManager::MessageManager( KDevTeamwork* tw ) : dispatcher_( *this ), m_teamwork( tw ), m_conversationManager( this ), m_historyManager( m_teamwork->logger() ) {
- m_showMessageAction = new QAction( i18n("Show"), this );
- connect( m_showMessageAction, SIGNAL( triggered() ), this, SLOT( slotShowMessage() ) );
- connect( m_teamwork, SIGNAL( init() ), this, SLOT( init() ) );
- m_showMessageAction->setToolTip( i18n("Show the message.") );
-}
-
-void MessageManager::init() {
-}
-
-MessageManager::~MessageManager() {}
-
-void MessageManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {
- /*try {
- xmlDeserializeFromElementItem( el, "ConversationManager", m_conversationManager );
- } catch ( const QString & str ) {
- log( "failed to restore the conversation-manager: " + str, Error );
- }*/
-}
-
-void MessageManager::savePartialProjectSession( QDomElement* /*el*/ ) {
- /*try {
- xmlSerializeToElementItem( el, "ConversationManager", m_conversationManager );
- } catch ( const QString & str ) {
- log( "failed to store the conversation-manager: " + str, Error );
- }*/
-}
-
-void MessageManager::showMessage( const MessagePointer& msg ) {
- MessagePointer::Locked l = msg;
- if ( !l )
- throw "cannot lock message";
- if ( !l.freeCast<AbstractGUIMessage>() )
- throw "message is no GUI-message";
-
- KDialog* d = new KDialog( m_teamwork->widget() );
- d->setAttribute( Qt::WA_DeleteOnClose, true );
-
- l.freeCast<AbstractGUIMessage>() ->showInWidget( d->mainWidget(), m_teamwork );
-
- d->show();
-}
-
-void MessageManager::slotShowMessage() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<MessagePointer>() )
- throw "cannot convert";
-
- showMessage( v.value<MessagePointer>() );
- } catch ( const char * str ) {
- log( QString( "error in showMessage: " ) + str, Error );
- }
-}
-
-
-int MessageManager::receiveMessage( MessageInterface* /*msg*/ ) {
- return 0;
-}
-
-int MessageManager::receiveMessage( KDevTeamworkTextMessage* /*msg*/ ) {
- return 0;
-}
-
-int MessageManager::receiveMessage( InDocumentMessage* msg ) {
- return m_conversationManager->processMessage( msg );
-}
-
-int MessageManager::processMessage( KDevTeamworkTextMessage* msg ) {
- if ( !msg )
- return 0;
- m_historyManager->addMessage( msg );
- return dispatcher_( msg );
-}
-
-void MessageManager::log( const QString& str, LogLevel level ) {
- m_teamwork->log( "MessageManager: " + str, level );
-}
-
-KDevTeamwork* MessageManager::teamwork() {
- return m_teamwork;
-}
-
-MessageHistoryManager& MessageManager::historyManager() {
- return * m_historyManager;
-}
-
-ConversationManager& MessageManager::conversationManager() {
- return * m_conversationManager;
-}
-
-void MessageManager::showMessageHistory( const QList<KDevTeamworkUserPointer>& users, const QString& context ) {
- new GuiMessageHistory( this, users, context );
-}
-
-void MessageManager::fillMessageMenu( QMenu* menu, MessagePointer msg ) {
- QVariant v;
- v.setValue( msg );
- m_showMessageAction->setData( v );
- menu->addAction( m_showMessageAction );
-
- teamwork() ->fillMessageMenu( menu, msg );
-
-
-
- MessagePointer::Locked l = msg;
- if ( l ) {
- UserPointer u = l->info().user();
- if ( u ) {
- if ( /*l->info().isIncoming() &&*/ l.freeCast<AbstractGUIMessage>() ) {
- AbstractGUIMessage * request = l.freeCast<AbstractGUIMessage>();
- request->fillContextMenu( menu, teamwork() );
- }
-
- if ( !menu->children().isEmpty() )
- menu->addSeparator();
-
- if ( l->info().session() && l->info().session().unsafe() ->isOk() ) {
- QMenu * m = new QMenu( ~u.unsafe() ->safeName(), menu );
- menu->addMenu( m );
- m_teamwork->fillUserMenu( m, u );
- }
- } else
- log( "could not get user from message", Error );
-
- } else {
- if ( !l )
- log( "could not lock message", Error );
- }
-}
-
-void MessageManager::updateMessage( const MessagePointer& msg ) {
- emit messageUpdated( msg );
-}
-
-#include "messagemanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h (nonexistent)
@@ -1,92 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include <QStringList>
-#include <QList>
-
-#ifndef FILECOLLABORATIONMANAGER_H
-#define FILECOLLABORATIONMANAGER_H
-
-#include "lib/network/messagetypeset.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/weaksafesharedptr.h"
-#include "lib/network/crossmap.h"
-
-#include "filecollaborationmessages.h"
-#include "safelogger.h"
-
-#include "filecollaboration.h"
-#include "filecollaborationsession.h"
-
-
-///There's not many messages that need to be dispatched right now
-BIND_LIST_2( FileCollaborationMessages, FileCollaborationMessage, FileCollaborationRequest )
-CROSSMAP_DEFINE_CONTAINER( QList )
-
-class FileCollaborationManager : public QObject, public SafeLogger {
- Q_OBJECT
- public:
- ///FileCollaborationSession itself is used as key too, so sessions can always be found even if all Files und Users change.
- BIND_LIST_5( SessionKeys, FileCollaborationSessionPointer, CollabSessionId, QList<QString>, QList<KDevTeamworkUserPointer>, SessionName )
-
- typedef Utils::CrossMap< FileCollaborationSessionPointer, SessionKeys > SessionSet;
-
- FileCollaborationManager( CollaborationManager* manager );
-
- const SessionSet& sessions();
-
- ///May return zero on failure
- FileCollaborationSession* startSession( const QString& name, CollabFileList files , uint primaryIndex = 0, CollabSessionId id = 0 );
-
- KDevTeamwork* teamwork();
-
- bool acceptCollaboration( const FileCollaborationRequestPointer& msg );
-
- void denyCollaboration( const FileCollaborationRequestPointer& msg );
-
- void closeSession( const FileCollaborationSessionPointer& session );
-
- public slots:
- void updateCollaborationModel( QStandardItemModel* model );
- void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
- void slotStartCollaborationSession();
- void slotSessionStateChanged( const FileCollaborationSessionPointer& );
-
- signals:
- void fillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
-
- private:
-
- void processMessage( FileCollaborationMessagePointer msg );
-
- int receiveMessage( MessageInterface* msg );
-
- int receiveMessage( FileCollaborationRequest* msg );
-
- int receiveMessage( FileCollaborationMessage* msg );
-
- CollaborationManager* m_manager;
- SessionSet m_sessions;
- QAction* m_startCollaborationSessionAction;
-
- MessageDispatcher< FileCollaborationManager, FileCollaborationMessages > m_dispatcher;
- friend class MessageDispatcher< FileCollaborationManager, FileCollaborationMessages >;
- friend class CollaborationManager;
-
- typedef std::multimap< CollabSessionId, FileCollaborationRequestPointer> RequestMap;
- RequestMap m_requests; ///Here, requests are stored so all requests for the same session can be grouped together once that session is accepted
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui (nonexistent)
@@ -1,139 +0,0 @@
-<ui version="4.0" >
- <class>ManagePatches</class>
- <widget class="QWidget" name="ManagePatches" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>537</width>
- <height>432</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Manage Patches</string>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="label" >
- <property name="text" >
- <string>Available patches:</string>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QTreeView" name="patchesList" />
- </item>
- <item>
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QPushButton" name="add" >
- <property name="text" >
- <string>Add</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="edit" >
- <property name="text" >
- <string>Edit</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="remove" >
- <property name="text" >
- <string>Remove</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>20</width>
- <height>231</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_managepatches.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.h (nonexistent)
@@ -1,64 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef VERIFY_H
-#define VERIFY_H
-
-#include <string>
-#include <sstream>
-
-struct ExpressionError {
- std::string function;
- int line;
- std::string file;
- std::string expression;
- std::string realExpression;
- ExpressionError( const std::string& fun, int l, const std::string& f, const std::string& exp, const std::string& realExp = "" );
- std::string what() const;
-};
-
-#ifndef HAVE_TOTEXT
-#define HAVE_TOTEXT
-
-template <class Item>
-std::string toText( const Item& it ) {
- std::ostringstream os;
- os << it;
- return os.str();
-}
-#endif
-
-#define VERIFY( x ) if( x ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ); }
-#define VERIFY_SAME( a, b ) if( a == b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ); }
-#define VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ); }
-#define VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ); }
-#define VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ); }
-
-
-///These throw a std::string
-#define S_VERIFY( x ) if( x ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ).what(); }
-#define S_VERIFY_SAME( a, b ) if( a == b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ).what(); }
-#define S_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ).what(); }
-#define S_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ).what(); }
-#define S_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ).what(); }
-
-///These throw a QString
-#define Q_VERIFY( x ) if( x ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #x ).what().c_str() ); }
-#define Q_VERIFY_SAME( a, b ) if( a == b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, toText( a ) + std::string( " == " ) + toText( b ) ).what().c_str() ); }
-#define Q_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, toText( a ) + std::string( " < " ) + toText( b ) ).what().c_str() ); }
-#define Q_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, toText( a ) + std::string( " <= " ) + toText( b ) ).what().c_str() ); }
-#define Q_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw QString( ExpressionError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, toText( a ) + std::string( " != " ) + toText( b ) ).what().c_str() ); }
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/verify.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h (nonexistent)
@@ -1,105 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_CLIENT_H
-#define KDEVTEAMWORK_CLIENT_H
-
-
-#include "teamworkfwd.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/teamworkclient.h"
-#include "kdevteamwork_messages.h"
-#include <list>
-
-
-#include <QTimer>
-
-///@TODO: Dispatch the messages in a more flexible way: Allow any client to register with an arbitrary message-type that he wants to get(including all sub-messages). DynamicMessageDispatcher can do this. Use that, and make the way messages are connected more flexible.
-
-Q_DECLARE_METATYPE( Teamwork::ServerInformation )
-Q_DECLARE_METATYPE( Teamwork::UserPointer )
-Q_DECLARE_METATYPE( ConnectionRequestPointer )
-Q_DECLARE_METATYPE( SafeSharedPtr<KDevTeamworkTextMessage> )
-Q_DECLARE_METATYPE( std::list<UserPointer> )
-Q_DECLARE_METATYPE( SafeSharedPtr<KDevSystemMessage> )
-Q_DECLARE_METATYPE( CollaborationMessagePointer )
-
-///most of the functions in this class are called from within another thread
-class KDevTeamworkClient : public QObject, public Teamwork::Client
-{
- public:
- KDevTeamworkClient( KDevTeamwork* teamwork );
-
- void invalidateTeamwork() {
- disconnectAllServers();
- closeAllIncomingSessions();
- stopRunning();
- m_teamwork = 0;
- }
-
- int receiveMessage( CollaborationMessage* msg );
-
- int receiveMessage( PatchesManagerMessage* msg );
-
- int receiveMessage( KDevTeamworkTextMessage* msg );
-
- int receiveMessage( KDevSystemMessage* msg );
-
- int receiveMessage( ConnectionRequest* msg );
-
- int receiveMessage( MessageInterface* /*msg*/ ) {
- return 0;
- }
-
- signals:
- ///All connections made to these signals must be queued, since these signals are emitted from within another thread
- void guiUserConnected( Teamwork::UserPointer );
- void guiUserDisconnected( Teamwork::UserPointer );
- void guiServerConnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
- void guiServerDisconnected( Teamwork::ClientSessionDesc, Teamwork::ServerInformation );
- void guiUserList( std::list<UserPointer> );
-
- void signalDispatchMessage( PatchesManagerMessagePointer );
- void signalDispatchMessage( CollaborationMessagePointer );
-
- protected:
- virtual UserPointer createUser( IdentificationMessage* msg );
- virtual UserPointer createUser( const User* user );
-
- ///this is called whenever a new user successfully logged into the server
- virtual void userConnected( const Teamwork::UserPointer& user );
-
- ///called whenever a user leaves the server
- virtual void userDisconnected( const Teamwork::UserPointer& user );
-
- ///this is called whenever a connection is successfully established to a server
- virtual void connectedToServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server );
-
- ///this is called whenever a server the client disconnects from a connected server in any way
- virtual void disconnectedFromServer( const Teamwork::ClientSessionDesc& session, const Teamwork::ServerInformation& server );
-
- virtual void gotUserList( const std::list<UserPointer>& users );
-
- void processMessage( MessageInterface* msg ) throw();
-
- private:
-
- //AllKDevTeamworkMessages, KDevTeamworkMessages
- Q_OBJECT
- KDevTeamwork* m_teamwork;
-
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_client.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp (nonexistent)
@@ -1,385 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "kdevteamwork_messageshower.h"
-#include <QWidget>
-#include <QObject>
-#include "kdevteamwork_messages.h"
-#include "ui_kdevteamwork_textmessage.h"
-#include "ui_kdevteamwork_indocumentcontextlines.h"
-#include "ui_kdevteamwork_indocumentmessagebuttons.h"
-#include "ui_kdevteamwork_indocumentmessagestate.h"
-#include <klocalizedstring.h>
-#include <QPointer>
-#include "kdevteamwork.h"
-#include "utils.h"
-#include "kdevteamwork_user.h"
-#include "messagemanager.h"
-#include <QPixmap>
-#include <QMenu>
-#include "messagehistorymanager.h"
-#include <kdialog.h>
-#include <QMetaType>
-#include "conversationmanager.h"
-#include <qtextdocument.h>
-#include <krandom.h>
-
-
-KDevTeamworkMessageShower::KDevTeamworkMessageShower( KDevTeamworkTextMessage* msg, QWidget* widget, KDevTeamwork* teamwork ) : QObject( widget ), m_message( msg ), m_widget( widget ), m_teamwork( teamwork ) {
- m_widgetData.setupUi( m_widget );
-
- fill();
-
- connect( m_widgetData.menuButton, SIGNAL( clicked() ), this, SLOT( menuButton() ) );
- connect( m_widgetData.historyButton, SIGNAL( clicked() ), this, SLOT( historyButton() ) );
- connect( m_widgetData.isReplyToButton, SIGNAL( clicked() ), this, SLOT( isReplyToButton() ) );
- connect( teamwork->messageManager(), SIGNAL( messageUpdated( const MessagePointer& ) ), this, SLOT( messageUpdated( const MessagePointer& ) ) );
-}
-
-void KDevTeamworkMessageShower::fillData() {
- fill();
-}
-
-void KDevTeamworkMessageShower::fill() {
- LockedSharedPtr<KDevTeamworkTextMessage> msg = m_message;
- if ( msg ) {
- m_widgetData.text->setText( ~msg->text() );
- m_widgetData.state->setText( QString( "ok" ) );
- QString user = QString( "Unknown" );
-
- if ( msg->info().user() ) {
- user = ~msg->info().user().unsafe() ->safeName();
- if ( msg->info().user().cast<KDevTeamworkUser>() ) {
- connect( msg->info().user().cast<KDevTeamworkUser>().unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
- }
- }
-
- LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
- if ( l ) {
- m_widget->setWindowIcon( l->messageIcon() );
- }
-
- m_widgetData.user->setText( QString( user ) );
- m_widgetData.time->setText( QString( msg->creationTime().toString() ) );
-
- QString direction;
- if ( msg->info().isIncoming() )
- direction = QString( "incoming" );
- else
- direction = QString( "outgoing" );
-
-
- m_widgetData.direction->setText( QString( direction ) );
-
- //m_widgetData.answerTo->setText( QString( "Answer to: %1" ).arg( msg->info().isReplyTo() ) );
-
- if ( !msg->info().isReplyTo() ) {
- m_widgetData.isReplyToButton->setEnabled( false );
- }
- }
-}
-
-void KDevTeamworkMessageShower::messageUpdated( const MessagePointer& msg ) {
- if ( msg.unsafe() == m_message.unsafe() ) {
- fillData();
- }
-}
-
-
-void KDevTeamworkMessageShower::isReplyToButton() {
- LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
- if ( l ) {
- if ( l->info().isReplyTo() ) {
- MessagePointer repliedMessage = l->info().replyToMessage();
- if ( !repliedMessage && m_teamwork )
- repliedMessage = m_teamwork->messageManager() ->historyManager().getMessageFromId( l->info().isReplyTo() , m_teamwork->client() );
-
- if ( LockedSharedPtr<KDevTeamworkTextMessage> lrep = repliedMessage.cast<KDevTeamworkTextMessage>() ) {
- KDialog * dialog = new KDialog( m_widget );
- dialog->setAttribute( Qt::WA_DeleteOnClose, true );
- new KDevTeamworkMessageShower( lrep, dialog->mainWidget(), m_teamwork );
- dialog->show();
- }
- }
- } else {}
-}
-
-void KDevTeamworkMessageShower::menuButton() {
- if ( m_teamwork && m_message ) {
- QMenu * menu = new QMenu( m_widget );
-
- m_teamwork->messageManager() ->fillMessageMenu( menu, m_message );
-
- menu->exec( QCursor::pos() );
- }
-}
-
-void KDevTeamworkMessageShower::historyButton() {
- LockedSharedPtr<KDevTeamworkTextMessage> l = m_message;
- if ( l && m_teamwork ) {
- KDevTeamworkUserPointer u = l->info().user().cast<KDevTeamworkUser>();
- if ( u ) {
- QList<KDevTeamworkUserPointer> users;
- users << u;
- m_teamwork->messageManager() ->showMessageHistory( users );
- } else {}
- }
-}
-
-void KDevTeamworkMessageShower::userStateChanged() {
- LockedSharedPtr<KDevTeamworkTextMessage> lmsg = m_message;
- if ( lmsg ) {
- LockedSharedPtr<KDevTeamworkUser> l = lmsg->info().user().cast<KDevTeamworkUser>();
- if ( l ) {
- m_widgetData.userIcon->setPixmap( l->icon().pixmap( 32, 32 ) );
- return ;
- }
- }
- m_widgetData.userIcon->setPixmap( QPixmap() );
-}
-
-
-KDevTeamworkUserInfoShower::KDevTeamworkUserInfoShower( KDevTeamworkUser* user, QWidget* widget, KDevTeamwork* teamwork ) : QObject( widget ), m_user( user ), m_widget( widget ), m_teamwork( teamwork ) {
- m_widgetData.setupUi( m_widget );
- m_widgetData.description->setText( ~user->description() );
- m_widgetData.name->setText( ~( ( Teamwork::User* ) user ) ->name() );
- m_widgetData.email->setText( QString( ~user->email() ) );
- m_widgetData.rights->setText( QString( ~user->rightsAsString() ) );
-
- setIp();
- setStatus();
- setIcon();
-
- connect( m_widgetData.menuButton, SIGNAL( clicked(bool) ), this, SLOT( menuButton() ) );
- connect( m_widgetData.historyButton, SIGNAL( clicked(bool) ), this, SLOT( historyButton() ) );
- connect( m_user.unsafe(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged() ) );
-}
-
-void KDevTeamworkUserInfoShower::menuButton() {
- if ( m_teamwork && m_user ) {
- QMenu * menu = new QMenu( m_widget );
-
- m_teamwork->fillUserMenu( menu, m_user );
-
- menu->exec( QCursor::pos() );
- }
-}
-
-
-void KDevTeamworkUserInfoShower::userStateChanged() {
- setIp();
- setStatus();
- setIcon();
-}
-
-
-void KDevTeamworkUserInfoShower::historyButton() {
- if ( m_teamwork && m_user ) {
- QList<KDevTeamworkUserPointer> users;
- users << m_user;
- m_teamwork->messageManager() ->showMessageHistory( users );
- }
-}
-
-void KDevTeamworkUserInfoShower::setIp() {
- LockedSharedPtr<KDevTeamworkUser> l = m_user;
- QString address = QString( "Unknown" );
- if ( l ) {
- SessionPointer::Locked ls = l->online().session();
- if ( ls )
- address = ~ls->peerDesc();
- }
- m_widgetData.ipadress->setText( QString( address ) );
-}
-
-
-void KDevTeamworkUserInfoShower::setStatus() {
- LockedSharedPtr<KDevTeamworkUser> l = m_user;
- if ( l ) {
- QStringList available;
- if ( !l->online() ) {
- available << QString( "not available" );
- } else {
- if ( l->online().session().unsafe() ->sessionType() == SessionInterface::Direct ) {
- available << QString( "direct" );
- } else {
- available << QString( "indirect" );
- }
-
- if ( l->online().session().unsafe() ->sessionDirection() == SessionInterface::Incoming ) {
- available << QString( "incoming" );
- } else {
- available << QString( "Outgoing" );
- }
- }
-
- m_widgetData.state->setText( QString( available.join( ", " ) ) );
- } else {
- m_widgetData.state->setText( QString( "Lock Failed" ) );
- }
-}
-
-
-void KDevTeamworkUserInfoShower::setIcon() {
- LockedSharedPtr<KDevTeamworkUser> l = m_user;
- if ( l ) {
- m_widgetData.icon->setPixmap( l->icon().pixmap( 32, 32 ) );
- m_widget->setWindowIcon( l->icon() );
- } else {
- m_widgetData.icon->setPixmap( QPixmap() );
- m_widget->setWindowIcon( QIcon() );
- }
-}
-
-struct InDocumentMessageShowerData {
- Ui_InDocumentButtons buttons;
- Ui_InDocumentContextLines contextLines;
- Ui_InDocumentState state;
- InDocumentMessageShowerData() : m_initialized( false ) {}
- void initialize( Ui_TextMessageShower* widgetData ) {
- if ( !m_initialized ) {
-
- buttons.setupUi( widgetData->buttonSpace );
- widgetData->buttonSpace->show();
-
- contextLines.setupUi( widgetData->middleSpace );
- widgetData->middleSpace->setMinimumHeight( widgetData->middleSpace->sizeHint().height() );
- widgetData->middleSpace->show();
-
- state.setupUi( widgetData->stateSpace );
- widgetData->stateSpace->setMinimumHeight( widgetData->stateSpace->sizeHint().height() );
- widgetData->stateSpace->show();
-
- m_initialized = true;
- }
- }
-
-private:
- bool m_initialized;
-};
-
-InDocumentMessageShower::InDocumentMessageShower( InDocumentMessage* msg, QWidget* widget, KDevTeamwork* teamwork ) : KDevTeamworkMessageShower( msg, widget, teamwork ), SafeLogger( teamwork->logger() , "InDocumentMessage: " ) {
- m_data->initialize( &m_widgetData );
- connect( m_data->state.file, SIGNAL( leftClickedUrl( const QString& ) ), this, SLOT( fileClicked() ) );
- connect( m_data->state.context, SIGNAL( leftClickedUrl( const QString& ) ), this, SLOT( contextClicked() ) );
- connect( m_data->buttons.jumpToPosition, SIGNAL( clicked() ), this, SLOT( fileClicked() ) );
- fill();
-}
-
-void InDocumentMessageShower::fillData() {
- KDevTeamworkMessageShower::fillData();
- fill();
-}
-
-void InDocumentMessageShower::fileClicked() {
- try {
- if ( !m_teamwork )
- throw "no teamwork";
-
- LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
- if ( !l )
- throw "could not lock message";
-
- InDocumentConversationPointer conv = m_teamwork->messageManager() ->conversationManager().getConversation( l );
-
- if ( !conv )
- throw "could not get conversation";
-
- conv->selectMessage( l );
- } catch ( QString str ) {
- err() << str;
- }
-}
-
-
-void InDocumentMessageShower::contextClicked() {
- try {
- if ( !m_teamwork )
- throw "no teamwork";
-
- LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
- if ( !l )
- throw "could not lock message";
-
- m_teamwork->messageManager() ->showMessageHistory( QList<KDevTeamworkUserPointer>(), l->context() );
- } catch ( QString str ) {
- err() << str;
- }
-}
-
-QString escapeWithoutLineBreaks( const QString& str ) {
- const QStringList lines = str.split( '\n' );
- QStringList ret;
- foreach( const QString& line, lines ) {
- ret << Qt::escape( line );
- }
- return ret.join( "<br>\n" );
-}
-
-void InDocumentMessageShower::fill() {
- LockedSharedPtr<InDocumentMessage> l = m_message.cast<InDocumentMessage>();
- if ( l ) {
- int offset = l->contextLines().lineOffset();
-
- QString marker1 = KRandom::randomString( 30 );
- QString marker2 = KRandom::randomString( 30 );
-
- QString lines = l->contextLines().text();
- if ( l->start() && l->end() ) {
- int startIndex = lineColToIndex( lines, l->start().line() - offset, l->start().col() );
- int endIndex = lineColToIndex( lines, l->end().line() - offset, l->end().col() );
- if ( startIndex != -1 && endIndex != -1 ) {
- lines = lines.mid( 0, startIndex ) + marker1 + lines.mid( startIndex, endIndex - startIndex ) + marker2 + lines.mid( endIndex );
- }
- }
-
- QString txt = escapeWithoutLineBreaks( lines );
-
- txt = txt.replace( marker1, "<font color=\"red\">" );
- txt = txt.replace( marker2, "</font>" );
-
- m_data->contextLines.contextLines->setHtml( txt );
- m_data->state.file->setText( l->document() );
- m_data->state.context->setText( l->context() );
- m_data->state.file->setUrl( "hallo" );
- m_data->state.context->setUrl( "hallo" );
-
- QString refType = "static";
- if ( !l->start().isValid() ) {
- refType = "invalid";
- } else if ( l->start().isDynamic() ) {
- refType = "dynamic";
- if ( l->end().isValid() ) {
- refType += " range";
- }
- } else {
- refType = "static";
- if ( l->end().isValid() ) {
- refType += " range";
- }
- }
-
- m_data->state.referenceType->setText( refType );
-
- QString position = l->start().asText();
- if ( l->end().isValid() )
- position += " to " + l->end().asText();
-
- m_data->state.position->setText( position );
-
- } else {}
-}
-
-#include "kdevteamwork_messageshower.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h (nonexistent)
@@ -1,310 +0,0 @@
-
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#ifndef FILECOLLABORATIONMESSAGES_H
-#define FILECOLLABORATIONMESSAGES_H
-
-#include <QPointer>
-#include <QObject>
-#include <QAction>
-
-//#include <boost/serialization/extended_type_info_typeid.hpp>
-#include "kdevteamwork_messages.h"
-#include "lib/network/easymessage.h"
-#include "utils.h"
-#include "lib/dynamictext/vectortimestamp.h"
-#include "lib/dynamictext/dynamictexthelpers.h"
-#include <list>
-//#include <boost/serialization/extended_type_info.hpp>
-
-namespace KTextEditor {
-class Document;
-}
-
-struct CollabFile {
- uint id;
- QString file;
- CollabFile() : id(0) {
- }
- CollabFile( uint i, const QString& f ) : id(i), file(f) {
- }
- template <class Archive>
- void serialize( Archive& arch, const uint ) {
- arch & id;
- arch & file;
- }
-};
-
-typedef std::list<CollabFile> CollabFileList;
-
-typedef quint64 CollabSessionId;
-
-class FileCollaborationMessageData {
- public:
- enum Message {
- NoMessage,
- Synchronize, ///messageData contains a QString containing the name of the file to synchronize
- CloseSession
- };
-
- explicit FileCollaborationMessageData( CollabSessionId sessionId = 0, Message message = NoMessage, const QVariant& messageData = QVariant() ) : m_sessionId( sessionId ), m_message( message ), m_messageData( messageData ) {}
-
-
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & m_sessionId;
- arch & m_message;
- arch & m_messageData;
- }
-
- ///Returns zero if the message is not associated to a session
- CollabSessionId sessionId() {
- return m_sessionId;
- };
-
- const QVariant& messageData() const {
- return m_messageData;
- }
-
- void setMessageData( const QVariant& v ) {
- m_messageData = v;
- }
-
- Message message() const {
- return m_message;
- }
-
- QString messageAsString() const {
- switch ( m_message ) {
- case NoMessage:
- return "NoMessage";
- case Synchronize:
- return "Synchronize";
- case CloseSession:
- return "CloseSession";
- default:
- return "unknown";
- };
- }
-
- private:
- CollabSessionId m_sessionId;
- Message m_message;
- QVariant m_messageData;
-};
-
-class FileCollaborationSession;
-class FileCollaboration;
-
-EASY_DECLARE_MESSAGE( FileCollaborationMessage, CollaborationMessage, 6, FileCollaborationMessageData, 3 );
-
-/**A file-collaboration-request is sent to request collaboration. The request stays alive
- * in the session and keeps forwarding all replies to the FileCollaboration-object, until that
- * object is deleted. When the request is accepted, a FileCollaborationRequest is sent back
- * and stays alive in the other session, forwarding messages directly to the peer
- * FileCollaboration-object. That way the connection is established without the messages having
- * to go a very long way.
-*/
-
-
-
-class FileCollaborationRequestData : public QObject, public AbstractGUIMessage {
- Q_OBJECT
- public:
- struct AcceptSignal {
- };
- struct DenySignal {
- };
- enum State {
- Unknown,
- Accepted,
- Denied,
- Failed
- };
-
- explicit FileCollaborationRequestData( FileCollaboration* collab = 0, uint index = 0, uint senderIndex = 0 );
-
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- arch & m_name;
- arch & m_files;
- arch & m_index;
- arch & m_senderIndex;
- arch & m_isAutomatic;
- }
-
- void setName( const QString& theValue );
-
- QString name() const;
-
- void setFiles( const CollabFileList& theValue );
-
- CollabFileList files() const;
-
- ///If the request is automatic that means that it was sent automatically by a session that discovered that a user came back online
- bool isAutomatic() const;
-
- void setAutomatic( bool automatic );
-
- State state() const;
-
- ///the index assigned to the side that is requested to collaborate
- uint index() const;
-
- void dispatchSignal( const AcceptSignal& sig );
- void dispatchSignal( const DenySignal& sig );
-
- ///The index of the sender of this message
- uint senderIndex() const;
- signals:
- void processReply( const MessagePointer& msg );
- void stateChanged( const MessagePointer& msg );
- void connectionResult( bool );
-
- public slots:
- void acceptCollaboration();
- void denyCollaboration();
- private:
- void updateState();
- ///Data:
- CollabFileList m_files;
- QString m_name;
- State m_state;
- uint m_index;
- uint m_senderIndex;
- bool m_isAutomatic;
-
- ///Internal:
- QPointer<FileCollaborationSession> m_session;
- QPointer<FileCollaboration> m_collab;
- QPointer<KDevTeamwork> m_teamwork;
- friend class FileCollaborationRequest;
-
- QAction* m_acceptAction;
- QAction* m_denyAction;
-};
-
-///A FileCollaborationRequest is an invitation to a local file-collaboration-session.
-EASY_DECLARE_MESSAGE_BEGIN( FileCollaborationRequest, FileCollaborationMessage, 2, FileCollaborationRequestData, 3 )
-
-virtual bool needReply() const;
-
-virtual void result( bool success ) {
- if ( !success ) {
- m_state = Failed;
- updateState();
- }
-}
-
-virtual QString messageText() const;
-
-virtual QIcon messageIcon() const;
-
-virtual ReplyResult gotReply( const MessagePointer& p );
-
-virtual void fillContextMenu( QMenu* /*menu*/, KDevTeamwork* /*teamwork*/ );
-
-END();
-
-typedef SafeSharedPtr<FileCollaborationMessage> FileCollaborationMessagePointer;
-typedef SafeSharedPtr<FileCollaborationRequest> FileCollaborationRequestPointer;
-
-
-class DocumentWrapperMessageData {
- public:
- DocumentWrapperMessageData( uint wrapperId = 0 ) : m_wrapperId( wrapperId ) {}
-
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- arch & m_wrapperId;
- }
- uint wrapperId() {
- return m_wrapperId;
- }
- private:
- uint m_wrapperId;
-};
-
-EASY_DECLARE_MESSAGE( DocumentWrapperMessage, FileCollaborationMessage, 4, DocumentWrapperMessageData, 1 );
-
-class FileEditMessageData {
- public:
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- arch & m_replacement & m_state;
- }
-
- explicit FileEditMessageData( const VectorTimestamp& state = VectorTimestamp(), const SimpleReplacement& rep = SimpleReplacement() ) : m_replacement( rep ), m_state(state) {
- }
-
- const SimpleReplacement& replacement () const {
- return m_replacement;
- }
-
- const VectorTimestamp& timeStamp() const {
- return m_state;
- }
-
- private:
- SimpleReplacement m_replacement;
- VectorTimestamp m_state;
-};
-
-EASY_DECLARE_MESSAGE( FileEditMessage, DocumentWrapperMessage, 1, FileEditMessageData, 2 );
-
-struct FileEditRejectMessageData {
- public:
- FileEditRejectMessageData( const VectorTimestamp& vec = VectorTimestamp() ) : m_state( vec ) {
- }
-
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- arch & m_state;
- }
-
- const VectorTimestamp& timeStamp() const {
- return m_state;
- }
- private:
- VectorTimestamp m_state;
-};
-
-EASY_DECLARE_MESSAGE( FileEditRejectMessage, DocumentWrapperMessage, 2, FileEditRejectMessageData, 1 );
-
-struct FileListMessageData {
- FileListMessageData( const CollabFileList& files = CollabFileList() ) : m_files( files ) {
- }
-
- template <class Archive>
- void serialize( Archive& arch, unsigned int /*version*/ ) {
- arch & m_files;
- }
-
- CollabFileList m_files;
-};
-
-
-EASY_DECLARE_MESSAGE( FileListMessage, FileCollaborationMessage, 5, FileListMessageData, 1 );
-
-BOOST_CLASS_IMPLEMENTATION( FileEditRejectMessageData, boost::serialization::object_serializable )
-BOOST_CLASS_IMPLEMENTATION( SimpleReplacement, boost::serialization::object_serializable )
-BOOST_CLASS_IMPLEMENTATION( FileCollaborationMessageData, boost::serialization::object_serializable )
-BOOST_CLASS_IMPLEMENTATION( FileCollaborationRequestData, boost::serialization::object_serializable )
-BOOST_CLASS_IMPLEMENTATION( FileEditMessageData, boost::serialization::object_serializable )
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h (nonexistent)
@@ -1,188 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#ifndef KDEVTEAMWORK_MESSAGES_H
-#define KDEVTEAMWORK_MESSAGES_H
-
-//#include <boost/serialization/extended_type_info_typeid.hpp>
-
-#include "lib/network/serialization.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/teamworkmessages.h"
-#include "lib/network/forwardsession.h"
-
-#include <QString>
-#include <QDateTime>
-#include "utils.h"
-#include <QIcon>
-#include <QVariant>
-#include "lib/network/easymessage.h"
-#include <string>
-#include <boost/serialization/level.hpp>
-#include "loglevel.h"
-
-/*#define BOOST_SERIALIZATION_DEFAULT_TYPE_INFO(T) \
- extended_type_info_typeid<const T>*/
-/**/
-
-using namespace Teamwork;
-
-class KDevTeamwork;
-class QMenu;
-class QModelIndex;
-class QWidget;
-
-class SafeTeamworkEmitter;
-typedef SharedPtr<SafeTeamworkEmitter> SafeTeamworkEmitterPointer;
-
-class IconCache;
-
-class KDevSystemMessage : public SystemMessage {
- DECLARE_MESSAGE( KDevSystemMessage, SystemMessage, 5 );
- public:
- enum Message {
- CollaborationAccepted,
- CollaborationRefused,
- CollaborationClosed,
- ActionFailed, ///An Action failed
- ActionSuccessful,
- ActionDenied
- };
- KDevSystemMessage( InArchive& arch, const Teamwork::MessageInfo& info );
-
- KDevSystemMessage( const Teamwork::MessageConstructionInfo& info, Message msg , const string& str = "" );
-
- Message message();
-
- QString messageAsString();
-
- QString text();
-};
-
-typedef SafeSharedPtr<KDevSystemMessage> KDevSystemMessagePointer;
-
-struct AbstractGUIMessage {
- QVariant data; ///@todo remove
- virtual QString messageText() const = 0;
- virtual QIcon messageIcon() const;
- virtual void fillContextMenu( QMenu* /*menu*/, KDevTeamwork* /*teamwork*/ ) {}
- ;
- virtual ~AbstractGUIMessage() {}
- ;
- virtual bool show() {
- return true;
- }
- virtual QString shortName() const {
- return "Message";
- }
- ///This should return an icon that represents the message-type and has nothing to do with the message-instance
- virtual QIcon messageTypeIcon() const;
-
- virtual bool canShowInWidget() {
- return false;
- }
-
- virtual void showInWidget( QWidget* /*widget*/, KDevTeamwork* /*tw*/ ) {}
-};
-
-class KDevTeamworkTextMessage : public TextMessage, public AbstractGUIMessage {
- DECLARE_MESSAGE( KDevTeamworkTextMessage, TextMessage, 6 );
- public:
-
- KDevTeamworkTextMessage( const Teamwork::MessageConstructionInfo& info, const QString& text );
-
- KDevTeamworkTextMessage( InArchive& from, const Teamwork::MessageInfo& info );
-
- virtual QString messageText() const;
-
- virtual QIcon messageIcon() const;
-
- void setAnswered( bool );
-
- bool answered() const;
-
- virtual void serialize( OutArchive& arch );
-
- virtual bool needReply() const;
-
- QDateTime creationTime();
-
- virtual bool canShowInWidget();
-
- ///If this returns false, the widget is not shown.
- virtual void showInWidget( QWidget* widget, KDevTeamwork* tw );
-
- private:
- QDateTime creationTime_;
- bool m_answered;
-};
-
-///Just a dummy for compatible insertion of error-messages to the message-list
-class FailureMessage : public KDevTeamworkTextMessage {
- public:
- FailureMessage( const QString& text, const MessagePointer& msg );
-
- virtual QIcon messageIcon() const;
-};
-
-class ConnectionRequest : public KDevTeamworkTextMessage {
- public:
- enum State {
- Waiting,
- Denied,
- Accepted,
- Unknown
- };
-
- ConnectionRequest( const Teamwork::MessageConstructionInfo& info, const Teamwork::UserPointer& self, const Teamwork::UserPointer& target, const QString& text, KDevTeamwork* teamwork );
-
- ConnectionRequest( InArchive& arch, const Teamwork::MessageInfo& info );
-
- virtual void serialize( OutArchive& arch );
-
- const Teamwork::User& user();
-
- virtual bool needReply() const;
-
- virtual QIcon messageIcon() const;
-
- virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
-
- void setState( State s );
-
- State state();
-
- virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
- private:
- DECLARE_MESSAGE( ConnectionRequest, KDevTeamworkTextMessage, 1 );
- Teamwork::User user_;
- State m_state;
- SafeTeamworkEmitterPointer m_emitter;
-};
-
-BOOST_CLASS_IMPLEMENTATION( NoData, boost::serialization::object_serializable )
-
-EASY_DECLARE_MESSAGE( CollaborationMessage, TextMessage, 9, NoData, 0 );
-
-typedef SafeSharedPtr<CollaborationMessage> CollaborationMessagePointer;
-
-UserPointer userFromSession( const SessionPointer& session );
-
-typedef KDevTeamworkTextMessage KDevTeamworkMessages;
-
-//typedef Teamwork::Binder<Teamwork::AllTeamworkClientMessages, KDevTeamworkMessages >::Append<ConnectionRequest>::Result::Append<KDevSystemMessage>::Result::Append<KDevSystemMessage>::Result AllKDevTeamworkMessages;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h (nonexistent)
@@ -1,60 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_USER_H
-#define KDEVTEAMWORK_USER_H
-
-#include <QObject>
-#include <QMetaType>
-#include <QString>
-#include <kiconloader.h>
-
-#include "lib/network/networkfwd.h"
-#include "teamworkfwd.h"
-#include "lib/network/user.h"
-
-using namespace Teamwork;
-class QIcon;
-
-namespace Teamwork {
- class IdentificationMessage;
-}
-
-class KDevTeamworkUser : public QObject, public User {
- Q_OBJECT
- public:
- KDevTeamworkUser( const User* user = 0 );
-
- KDevTeamworkUser( IdentificationMessage* msg );
-
- virtual void setSession( const SessionPointer& sess );
-
- QIcon icon( KIconLoader::Group = KIconLoader::Small );
-
- QString toolTip();
-
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & boost::serialization::base_object<User>( *this );
- }
-
- signals:
- ///All signals in this class should be connected using queued connections, because they get called from other threads
- void userStateChanged( KDevTeamworkUserPointer user );
-};
-
-typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_user.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui (nonexistent)
@@ -1,26 +0,0 @@
-<ui version="4.0" >
- <class>List</class>
- <widget class="QWidget" name="widget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>300</width>
- <height>319</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QListView" name="list" />
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_list.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui (nonexistent)
@@ -1,100 +0,0 @@
-<ui version="4.0" >
- <class>InternalMessage</class>
- <widget class="QWidget" name="InternalMessage" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>463</width>
- <height>193</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Internal Message</string>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QFrame" name="frame" >
- <property name="autoFillBackground" >
- <bool>true</bool>
- </property>
- <property name="frameShape" >
- <enum>QFrame::Panel</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Plain</enum>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QToolButton" name="actionsButton" >
- <property name="text" >
- <string>actions</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1" >
- <widget class="QComboBox" name="talkingUsers" />
- </item>
- <item row="1" column="0" colspan="2" >
- <widget class="QTreeView" name="messages" >
- <property name="editTriggers" >
- <set>QAbstractItemView::NoEditTriggers</set>
- </property>
- <property name="alternatingRowColors" >
- <bool>true</bool>
- </property>
- <property name="indentation" >
- <number>2</number>
- </property>
- <property name="animationsEnabled" stdset="0" >
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="0" colspan="2" >
- <widget class="QLineEdit" name="message" />
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_internalmessage.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.cpp (nonexistent)
@@ -1,37 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "safesignaller.h"
-#include"kdevteamwork.h"
-#include "lib/network/weaksafesharedptr.h"
-
-QSafeSignaller::~QSafeSignaller() {
- delete m_proxy;
-}
-
-void QSafeSignaller::signal() {
- if(!KDevTeamwork::self())return;
- KDevTeamwork::self()->log( "QSafeSignaller::signal()" );
- m_proxy->signal();
-}
-
-QSafeSignaller& QSafeSignaller::operator = ( const QSafeSignaller& /*rhs*/ ) {
- return *this;
-}
-
-QSafeSignaller::QSafeSignaller( const QSafeSignaller& /*rhs*/ ) : QObject() {
-}
-
-#include "safesignaller.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp (nonexistent)
@@ -1,1012 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "patchesmanager.h"
-#include <boost/archive/polymorphic_xml_oarchive.hpp>
-#include <boost/archive/polymorphic_xml_iarchive.hpp>
-
-#include <QPersistentModelIndex>
-#include <QMenu>
-#include <QFile>
-#include <QTimer>
-
-#include <kmimetype.h>
-#include <kmimetypetrader.h>
-#include <kopenwithdialog.h>
-#include <k3process.h>
-#include <kprocess.h>
-#include <kdialog.h>
-
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/iplugincontroller.h>
-
-#include "lib/network/sessioninterface.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/messagesendhelper.h"
-
-#include "kdevteamworkplugin.h"
-#include "kdevteamwork_user.h"
-#include "ui_kdevteamwork_interface.h"
-#include "collaborationmanager.h"
-#include "messagemanager.h"
-#include "kdevteamwork_client.h"
-#include "kdevteamwork_helpers.h"
-#include "teamworkfoldermanager.h"
-#include "editpatch.h"
-
-#include "serializationutils.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-QString userNameFromSession( const SessionPointer& session ) {
- UserPointer::Locked lu = userFromSession( session );
- if ( lu ) {
- return ~lu->name();
- } else {
- return "unlockable-user";
- }
-}
-
-///Tries to extract the default-extension from a pattern-list. The returned extension includes the dot.
-QString getDefaultExtension( const QStringList& patterns ) {
- if ( patterns.isEmpty() )
- return "";
- for ( QStringList::const_iterator it = patterns.begin(); it != patterns.end(); ++it ) {
- QString s = *it;
- int i = s.lastIndexOf( "*." );
- if ( i == -1 )
- continue;
- return s.mid( i + 1 );
- }
- return "";
-}
-
-
-///currently, KOpenWithDlg crashes.
-//#define USE_KOPENWITHDLG
-
-REGISTER_MESSAGE( PatchesManagerMessage )
-REGISTER_MESSAGE( PatchesListMessage )
-EASY_IMPLEMENT_MESSAGE( PatchRequestMessage )
-EASY_IMPLEMENT_MESSAGE( PatchMessage )
-
-Q_DECLARE_METATYPE( QPersistentModelIndex )
-Q_DECLARE_METATYPE( LocalPatchSourcePointer )
-Q_DECLARE_METATYPE( MessagePointer )
-
-PatchesManager::PatchesManager( KDevTeamwork* tw ) : QObject( tw ), m_teamwork( tw ), dispatcher_( *this ), m_manageDlg( 0 ) {
-
- connect( m_teamwork, SIGNAL( init() ), this, SLOT( init() ) );
-
- qRegisterMetaType<PatchesManagerMessagePointer>( "PatchesManagerMessagePointer" );
- qRegisterMetaType<LocalPatchSourcePointer>( "LocalPatchSourcePointer" );
-
- m_showPatchAction = new QAction( i18n("Show"), this );
- connect( m_showPatchAction, SIGNAL( triggered() ), this, SLOT( slotShowPatch() ) );
- m_showPatchAction->setToolTip( i18n("Request and show the selected file.") );
-
- m_showPatchInfoAction = new QAction( i18n("Show Info"), this );
- connect( m_showPatchInfoAction, SIGNAL( triggered() ), this, SLOT( slotShowPatchInfo() ) );
- m_showPatchInfoAction->setToolTip( i18n("Show Information about the selected file.") );
-
- m_downloadPatchAction = new QAction( i18n("Download Item"), this );
- connect( m_downloadPatchAction, SIGNAL( triggered() ), this, SLOT( slotDownloadPatch() ) );
- m_downloadPatchAction->setToolTip( i18n("Download the item and store it into the list of local items.") );
-
- m_applyPatchAction = new QAction( i18n("Apply Locally"), this );
- connect( m_applyPatchAction, SIGNAL( triggered() ), this, SLOT( slotApplyPatch() ) );
- m_applyPatchAction->setToolTip( i18n("Apply the item/patch to the local workspace/project and store it into the list of local patches.") );
-
- m_allowPatchAction = new QAction( i18n("Allow"), this );
- connect( m_allowPatchAction, SIGNAL( triggered() ), this, SLOT( slotAllowPatch() ) );
- m_allowPatchAction->setToolTip( i18n("Send the requested patch to the user.") );
-
- m_denyPatchAction = new QAction( i18n("Deny"), this );
- connect( m_denyPatchAction, SIGNAL( triggered() ), this, SLOT( slotDenyPatch() ) );
- m_denyPatchAction->setToolTip( i18n("Do not send the requested patch to the user.") );
-
- m_showRequestedPatchAction = new QAction( i18n("Show Patch-Info"), this );
- connect( m_showRequestedPatchAction, SIGNAL( triggered() ), this, SLOT( slotShowRequestedPatch() ) );
- m_showRequestedPatchAction->setToolTip( i18n("Show the requested patch.") );
-
- m_updateTimer = new QTimer( this );
- m_updateTimer->setSingleShot( true );
- connect( m_updateTimer, SIGNAL(timeout()), this, SLOT(guiUpdatePatchesList() ) );
- connect( m_teamwork, SIGNAL( deInit() ), this, SLOT( save() ) );
-}
-
-void PatchesManager::init() {
- connect( m_teamwork->widgets().managePatches, SIGNAL( pressed() ), this, SLOT( slotManagePatches() ) );
- connect( m_teamwork, SIGNAL( updateConnection( TeamworkClientPointer ) ), this, SLOT( slotUpdateConnection( TeamworkClientPointer ) ) );
- load();
-}
-
-void PatchesManager::slotManagePatches() {
- m_manageDlg = new KDialog( m_teamwork->widget() );
- m_manageDlg->setButtons( KDialog::Close );
- m_manageDlg->setCaption( i18n("Manage Patches") );
- m_managePatches.setupUi( m_manageDlg->mainWidget() );
- m_managePatches.patchesList->setEditTriggers( QAbstractItemView::NoEditTriggers );
- connect( m_managePatches.edit, SIGNAL( pressed() ), this, SLOT( slotEditPatch() ) );
- connect( m_managePatches.add, SIGNAL( pressed() ), this, SLOT( slotAddPatch() ) );
- connect( m_managePatches.remove, SIGNAL( pressed() ), this, SLOT( slotRemovePatch() ) );
- connect( m_manageDlg, SIGNAL( finished() ), this, SLOT( slotCloseManagement() ) );
- m_manageDlg->show();
- m_patchesModel = new QStandardItemModel( 0, 1, m_managePatches.patchesList );
- m_managePatches.patchesList->setModel( m_patchesModel );
- guiUpdatePatchesList();
-}
-
-void PatchesManager::slotUpdateConnection( TeamworkClientPointer newClient ) {
- if ( newClient ) {
- log( "slotUpdateConnection", Debug );
- connect( newClient.unsafe(), SIGNAL( signalDispatchMessage( PatchesManagerMessagePointer ) ), this, SLOT( processMessage( PatchesManagerMessagePointer ) ), Qt::QueuedConnection );
- }
-}
-
-void PatchesManager::log( const QString& str, LogLevel level ) {
- m_teamwork->log( "patchesmanager: " + str, level );
-}
-
-void PatchesManager::addPatch( const LocalPatchSourcePointer& patch ) {
- if( !hasPatch( patch ) ) {
- m_config.addPatch( patch );
- guiUpdatePatchesList();
- }
-}
-
-void PatchesManager::editStateChanged( EditPatch* ) {
- m_updateTimer->start( 100 );
-}
-
-void PatchesManager::editDialogClosed( EditPatch* dialog ) {
- m_editing.removeAll( dialog );
- m_updateTimer->start( 100 );
-}
-
-bool PatchesManager::hasPatch( const LocalPatchSourcePointer& patch ) {
- return m_config.hasPatch( patch );
-}
-
-void PatchesManager::slotAddPatch() {
- showEditDialog( new LocalPatchSource(), true );
-}
-
-void PatchesManager::showPatchInfo( const LocalPatchSourcePointer & patch, bool local ) {
- showEditDialog( patch, local );
-}
-
-EditPatchPointer PatchesManager::showEditDialog( const LocalPatchSourcePointer & patch, bool local ) {
- if( !patch ) return 0;
- for( QList<EditPatchPointer>::iterator it = m_editing.begin(); it != m_editing.end(); ++it ) {
- if( (*it)->patch() == patch ) return *it;
- }
- EditPatchPointer p = new EditPatch( this, patch, local );
-
- connect( p.data(), SIGNAL(dialogClosed( EditPatch* )), this, SLOT( editDialogClosed( EditPatch* ) ) );
- connect( p.data(), SIGNAL(stateChanged( EditPatch* )), this, SLOT( editStateChanged( EditPatch* ) ) );
- m_editing << p;
- return p;
-}
-
-void PatchesManager::slotEditPatch() {
- showEditDialog( selectedPatch(), true );
-}
-
-void PatchesManager::slotRemovePatch() {
- LocalPatchSourcePointer p = selectedPatch();
-
- if ( p )
- m_config.patchSources.remove( p );
-
- guiUpdatePatchesList();
-}
-
-void PatchesManager::slotCloseManagement() {}
-
-void PatchesManager::slotManagementFinished( int /*result*/ ) {
- m_manageDlg = 0;
-}
-
-LocalPatchSourcePointer PatchesManager::selectedPatch() {
- if ( !m_manageDlg )
- return LocalPatchSourcePointer();
- QModelIndex i = m_managePatches.patchesList->currentIndex();
- if ( i.isValid() )
- i = m_patchesModel->index( i.row(), 0 );
-
- if ( i.isValid() ) {
- QVariant v = m_patchesModel->data( i, Qt::UserRole );
- if ( v.canConvert<LocalPatchSourcePointer>() ) {
- return v.value<LocalPatchSourcePointer>();
- } else {
- log( "bad data in patches-list" );
- }
- }
-
- return LocalPatchSourcePointer();
-}
-
-///The following three functions are nearly the same, maybe they should be put together
-void PatchesManager::slotApplyPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<LocalPatchSourcePointer>() )
- throw "cannot convert to patch-source";
-
- LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
- if ( !lpatch )
- throw "could not lock patch-source";
-
- UserPointer::Locked user = lpatch->user();
- if ( !user )
- throw "the patch has no associated user";
- if ( !user->online() )
- throw "the user is not online";
-
- SessionPointer::Locked lsession = user->online().session();
- if ( !lsession )
- throw "the session could not be locked";
-
- SafeSharedPtr<PatchRequestMessage>::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork, PatchRequestData::Apply );
- lsession->send( mp );
- m_teamwork->addMessageToList( ( PatchRequestMessage* ) mp );
- } catch ( const char * str ) {
- log( QString( "error in slotApplyPatch: " ) + str, Error );
- }
-}
-
-void PatchesManager::slotDownloadPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<LocalPatchSourcePointer>() )
- throw "cannot convert to patch-source";
-
- LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
- if ( !lpatch )
- throw "could not lock patch-source";
-
- UserPointer::Locked user = lpatch->user();
- if ( !user )
- throw "the patch has no associated user";
- if ( !user->online() )
- throw "the user is not online";
-
- SessionPointer session = user->online().session();
- if ( !session )
- throw "the session could not be acquired";
-
- MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork, PatchRequestData::Download );
- session.unsafe() ->send( mp );
- m_teamwork->addMessageToList( mp );
- } catch ( const char * str ) {
- log( QString( "error in slotDownloadPatch: " ) + str, Error );
- }
-}
-
-void PatchesManager::slotShowPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<LocalPatchSourcePointer>() )
- throw "cannot convert to patch-source";
-
- LocalPatchSourcePointer::Locked lpatch = v.value<LocalPatchSourcePointer>();
- if ( !lpatch )
- throw "could not lock patch-source";
-
- UserPointer::Locked user = lpatch->user();
- if ( !user )
- throw "the patch has no associated user";
- if ( !user->online() )
- throw "the user is not online";
-
- SessionPointer session = user->online().session();
- if ( !session )
- throw "the session could not be acquired";
-
- MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_teamwork );
- session.unsafe() ->send( mp );
- m_teamwork->addMessageToList( mp );
- } catch ( const char * str ) {
- log( QString( "error in slotShowPatch: " ) + str, Error );
- }
-}
-
-void PatchesManager::slotShowPatchInfo() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<LocalPatchSourcePointer>() )
- throw "cannot convert to patch-source";
-
- showPatchInfo( v.value<LocalPatchSourcePointer>(), false );
- } catch ( const char * str ) {
- log( QString( "error in slotShowPatchInfo: " ) + str, Error );
- }
-}
-
-void PatchesManager::processMessage( PatchesManagerMessagePointer msg ) {
- log( "dispatching message", Debug );
- PatchesManagerMessagePointer::Locked l = msg;
- if ( l ) {
- dispatcher_( l );
- } else {
- log( "PatchesManager could not lock a message-pointer", Error );
- }
-}
-
-int PatchesManager::receiveMessage( MessageInterface* msg ) {
- m_teamwork->log( QString( "PatchesManager got unknown message of type " ) + msg->name() );
- return 0;
-}
-
-int PatchesManager::receiveMessage( PatchMessage* msg ) {
- try {
- SafeSharedPtr<PatchRequestMessage>::Locked request = msg->info().replyToMessage().cast<PatchRequestMessage>();
- if ( !request )
- throw QString( "got unrequested patch-message, or could not lock patch-request" );
-
- LocalPatchSourcePointer::Locked patchInfo = request->request(); ///For security, information like apply-command etc. are cached
- if ( !patchInfo )
- throw QString( "could not get or lock patch-information" );
-
- LocalPatchSourcePointer::Locked patchInfoNew = msg->patch(); ///For security, information like apply-command etc. are cached
- if ( !patchInfo )
- throw QString( "could not get or lock patch-information" );
-
- if ( !( patchInfoNew->identity() == request->patchIdentity() ) )
- throw QString( "identity of received patch does not match the identity of the corresponding request" );
-
- KMimeType::Ptr mime = KMimeType::mimeType( ~patchInfo->type );
- if ( !mime )
- throw QString( "Error in kdelibs: could not create mime-type" ); ///according to the documentation this should never happen, but it does
-
- QString userName;
- if( msg->info().session().cast<FakeSession>() )
- userName = "local";
- else
- userName = userNameFromSession( msg->info().session() );
- QString fileName = ~patchInfo->name;
- if( !patchInfo->filename.empty() )
- fileName += "_" + QFileInfo(~patchInfo->filename).fileName();
- else
- fileName += getDefaultExtension( mime->patterns() );
-
- log( QString( "creating file for patch: %1" ).arg( fileName ), Debug );
-
- KUrl filePath = TeamworkFolderManager::createUniqueFile( "patches/"+userName, fileName );
-
- {
- ///@todo make this work with remove files
- QFile file( filePath.toLocalFile() );
-
- file.open( QIODevice::WriteOnly );
- if ( !file.isOpen() )
- throw QString( "could not open %1" ).arg( filePath.prettyUrl() );
-
- file.write( msg->data() );
- log( QString( "writing patch of size %1 to %2" ).arg( msg->data().size() ).arg( filePath.prettyUrl() ), Debug );
- }
- if ( request->requestType() == PatchRequestData::View )
- TeamworkFolderManager::registerTempItem( filePath );
-
- switch ( request->requestType() ) {
- case PatchRequestData::Apply: {
- ///Apply the patch to the local tree
- if ( patchFromIdentity( patchInfo->identity() ) )
- throw QString( "there already is another local patch with identity \"%1\"" ).arg( ~patchInfo->identity().desc() );
-
- //LocalPatchSourcePointer::Locked newPatchInfo( patchInfo );//new LocalPatchSource( *patchInfo ) );
- if( !hasPatch( patchInfo ) ) {
- ///@todo make work with remote files
- patchInfo->setFileName( ~filePath.toLocalFile() );
- addPatch( patchInfo);
- }
-
- EditPatch* p = showEditDialog( patchInfo, true );
- if( !p ) throw QString( "cannot edit received patch" );
- ///@todo ...
- p->apply( false, filePath.toLocalFile() );
-
- guiUpdatePatchesList();
- };
- break;
- case PatchRequestData::Download: {
- if ( patchFromIdentity( patchInfo->identity() ) )
- throw QString( "there already is another local patch with identity \"%1\"" ).arg( ~patchInfo->identity().desc() );
- ///Store the patch locally
- LocalPatchSourcePointer::Locked newPatchInfo( new LocalPatchSource( *patchInfo ) );
- ///@todo make work with remote files
- newPatchInfo->setFileName( ~filePath.toLocalFile() );
- m_config.patchSources.push_back( newPatchInfo );
- guiUpdatePatchesList();
- }
- break;
- case PatchRequestData::View: {
- ///Show the patch
-
- ///@todo where has KDevDiffFrontend gone? When will it be back?
-// if ( patchInfo->type == "text/x-diff" ) {
-// QString str = msg->data();
-//
-// KDevDiffFrontend *df = KDevTeamworkPlugin::staticCore()->pluginController()->pluginForExtension<KDevDiffFrontend>( "KDevelop/DiffFrontend" );
-// if ( df ) {
-// df->showDiff( str );
-// return 1;
-// } else {
-// log( "no diff-interface available!", Error );
-// }
-// }
-
- if( !KDevTeamworkPlugin::staticDocumentController()->openDocument( filePath, KTextEditor::Cursor()) ) {
- log( QString( "could not open %1 with the document-controller" ).arg( filePath.prettyUrl() ), Warning );
-
- auto_ptr<KOpenWithDialog> d( new KOpenWithDialog( ~patchInfo->type, "" ) );
-
- if ( d->exec() == QDialog::Accepted ) {
- QString app = d->text();
- if ( !app.isEmpty() ) {
- ///@todo How to run this in a better way, so that .desktop-files are accepted etc.?
- // Use KRun, of course!
- KProcess proc;
- proc << app;
-
- proc << fileName;
- proc.startDetached();
- } else {
- log( "no application was chosen for opening " + fileName, Warning );
- }
- } else {
- throw QString( "open-with dialog was closed" );
- }
- d.reset(0);
-
-/* ///Open with KRun instead
- if( KRun::runUrl( KUrl(filePath), ~patchInfo->type, KDevTeamworkPlugin::staticCore()->uiController()->activeMainWindow() ) == 0 ) {
- log( QString( "Failed to open %1 with an application" ).arg( filePath ), Warning );
- }*/
- }
- ///Find an application that is able to open the selected mime-type
- /*
- QString tempFileName;
- KTempFile tempFile( QString(), getDefaultExtension( mime->patterns() ) );
-
- if ( tempFile.status() != 0 ) {
- throw QString( "could not create temporary file" );
- } else {
- tempFileName = tempFile.name();
- log( "name of the temp-file: " + tempFileName, Debug );
- QDataStream* stream = tempFile.dataStream();
- if ( stream ) {
- *stream << msg->data();
- if ( tempFile.status() != 0 )
- throw QString( "writing to the temporary file failed" );
- } else {
- throw QString( "could not get stream" );
- }
- }
-
- if ( !mime->isValid() )
- throw "service-type is not valid, file: " + tempFileName;
-
- QString app;
-
-#ifdef USE_KOPENWITHDLG
-
- auto_ptr<KOpenWithDlg> d = new KOpenWithDlg( ~patchInfo->type, "" );
-
- if ( d->exec() == QDialog::Accepted ) {
- app = d->text();
- } else {
- throw QString( "open-with dialog was closed" );
- }
- d = 0;
-#else
-
- KService::Ptr service = KMimeTypeTrader::self() ->preferredService( ~patchInfo->type , "KPlugins/ReadOnlyPlugin" );
- if ( !service )
- throw QString( "could not get a service that can handle " + ~patchInfo->type );
-
- app = service->exec();
-
-#endif
-
- if ( !app.isEmpty() ) {
- KProcess proc;
- proc << app;
-
- proc << tempFileName;
- proc.startDetached();
- } else {
- log( "no application was chosen for opening " + tempFileName, Warning );
- }*/
- }
- break;
- }
- } catch ( const QString & str ) {
- log( QString( "dispatch of patch-message from %1 failed: " ).arg( userFromSession( msg->info().session() ) ) + str , Error );
- }
-
- return 0;
-}
-
-LocalPatchSourcePointer::Locked PatchesManager::patchFromIdentity( const LocalPatchSource::Identity& ident ) {
- for ( list<LocalPatchSourcePointer>::iterator it = m_config.patchSources.begin(); it != m_config.patchSources.end(); ++it ) {
- LocalPatchSourcePointer::Locked l = ( *it );
- if ( l ) {
- if ( ident == l->identity() ) {
- return l;
- }
- } else {
- log( "could not lock patch-source", Warning );
- }
- }
- return 0;
-}
-
-LocalPatchSourcePointer PatchesManager::merge( const QString& name, const QList<LocalPatchSourcePointer>& patches ) {
- try {
- LocalPatchSourcePointer::Locked lp = new LocalPatchSource();
-
- foreach( LocalPatchSourcePointer patch, patches ) {
- LocalPatchSourcePointer::Locked l = patch;
- if ( !l )
- throw "could not lock patch-source";
- if ( l->type != "text/x-diff" )
- throw "a mime-type is not text/x-diff, only that types can be merged";
- if(l->userIdentity) lp->userIdentity = l->userIdentity;
- }
-
-
- QString user = "local";
- if( lp->userIdentity )
- user = ~lp->userIdentity.name();
-
- KUrl file = TeamworkFolderManager::createUniqueFile( "patches/"+user, name+".diff" );
-
- ///@todo make this work with remove Urls
- QFile target( file.toLocalFile() );
- if ( !target.open( QIODevice::WriteOnly ) )
- throw QString( "could not open file %1" ).arg( file.prettyUrl() );
-
- foreach( LocalPatchSourcePointer patch, patches ) {
- LocalPatchSourcePointer::Locked l = patch;
- if ( !l )
- throw "could not lock patch-source";
-
-
-
- KUrl u = TeamworkFolderManager::teamworkAbsolute( ~l->filename, "patches" );
- ///@todo make this work with remove Urls
- QFile f( u.toLocalFile() );
- if ( !f.open( QIODevice::ReadOnly ) )
- throw QString( "could not open file %1" ).arg( u.prettyUrl() );
-
- target.write( f.readAll() );
- target.write( "\n", 1 );
- }
-
- lp->name = ~name;
- lp->filename = ~TeamworkFolderManager::teamworkRelative( file, "patches" );
- lp->type = "text/x-diff";
-
- return lp;
- } catch ( const char * str ) {
- log( QString( "error while trying to merge patches: %1" ).arg( str ) , Error );
- } catch ( const QString & str ) {
- log( QString( "error while trying to merge patches: %1" ).arg( str ) , Error );
- }
- return 0;
-}
-
-
-int PatchesManager::receiveMessage( PatchRequestMessage* msg ) {
- ///Send the patch to the target.
- LocalPatchSourcePointer::Locked patch = patchFromIdentity( msg->patchIdentity() );
-
- bool overrideAccess = false;
- if( msg->info().session().cast<FakeSession>() ) overrideAccess = true;
-
- LocalPatchSourcePointer::Locked lpatch = patch;
- if ( patch && lpatch ) {
- if( !overrideAccess ) {
- switch ( lpatch->access ) {
- case Public:
- break;
- case ConnectedOnly: {
- if ( !m_teamwork->collaborationManager() ->isCollaborating( userFromSession( msg->info().session() ) ) ) {
- log( "not sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) + " because the user is not collaborating" );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "access only for collaborating users" );
- return 1;
- }
- }
- break;
- case Ask:
- m_teamwork->addMessageToList( msg );
- return 1;
- break;
- default: {
- log( "not sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) + " because the patch is private" );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "the patch is private" );
- return 1;
- }
- break;
- }
- }
- log( "sending patch " + ~patch->name + " to " + userNameFromSession( msg->info().session() ) );
- globalMessageSendHelper().sendReply<PatchMessage>( msg, ( LocalPatchSourcePointer ) patch, m_teamwork->logger() );
- } else {
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "no fitting patch available, or patch could not be locked" );
- log( "got a patch-request, but the requested patch could not be found or could not be locked", Warning );
- }
-
- return 1;
-}
-
-int PatchesManager::receiveMessage( PatchesListMessage* msg ) {
- ///Give the list to the GUI or whoever was waiting for it
- m_teamwork->handlePatchesList( msg );
- return 0;
-}
-
-int PatchesManager::receiveMessage( PatchesManagerMessage* msg ) {
- if ( !msg->isDerived() ) {
- switch ( msg->message() ) {
- case PatchesManagerMessage::None:
- break;
- case PatchesManagerMessage::GetPatchesList: {
- SessionPointer::Locked l = msg->info().session();
- if ( l && l->isRunning() ) {
- l->send( new PatchesListMessage( globalMessageTypeSet(), m_config.patchSources ) );
-
- UserPointer::Locked pl = l->safeUser();
- if ( pl ) {
- log( QString( "sending patches-list to " ) + pl->name().c_str() );
- } else {
- log( "sent patches-list through anonymous session" );
- }
-
- } else {
- log( QString( "could not answer a patches-list-request" ) );
- }
- }
- break;
- }
- } else {
- log( QString( "could not handle a PatchesManagerMessage of real type " ) + msg->name() );
- }
- return 0;
-}
-
-void PatchesManager::guiUpdatePatchesList() {
- if ( !m_manageDlg )
- return ;
-
- m_patchesModel->clear();
- m_patchesModel->insertColumns( 0, 5 );
-
- m_patchesModel->setHeaderData( 0, Qt::Horizontal, QString( "Name" ) );
- m_patchesModel->setHeaderData( 1, Qt::Horizontal, QString( "File/Command" ) );
- m_patchesModel->setHeaderData( 2, Qt::Horizontal, QString( "Access" ) );
- m_patchesModel->setHeaderData( 3, Qt::Horizontal, QString( "Type" ) );
- m_patchesModel->setHeaderData( 4, Qt::Horizontal, QString( "State" ) );
-
- for ( std::list<LocalPatchSourcePointer>::iterator it = m_config.patchSources.begin(); it != m_config.patchSources.end(); ++it ) {
- LocalPatchSourcePointer::Locked l = *it;
- m_patchesModel->insertRow( 0 );
- if ( l ) {
- m_patchesModel->setData( m_patchesModel->index( 0, 0 ), ~l->name, Qt::DisplayRole );
- m_patchesModel->setData( m_patchesModel->index( 0, 1 ), ~( l->filename + l->command ), Qt::DisplayRole );
- m_patchesModel->setData( m_patchesModel->index( 0, 2 ), ~l->accessAsString(), Qt::DisplayRole );
- m_patchesModel->setData( m_patchesModel->index( 0, 3 ), ~l->type, Qt::DisplayRole );
- m_patchesModel->setData( m_patchesModel->index( 0, 4 ), ~l->stateAsString(), Qt::DisplayRole );
- } else {
- m_patchesModel->setData( m_patchesModel->index( 0, 0 ), "lock failed", Qt::DisplayRole );
- }
- QVariant v;
- v.setValue( *it );
-
- m_patchesModel->setData( m_patchesModel->index( 0, 0 ), v, Qt::UserRole );
- }
-
- m_patchesModel->sort( 4 );
-}
-
-PatchesManager::~PatchesManager() {
-}
-
-QIcon LocalPatchSource::getIcon( IconCache& icons ) {
- return icons( "patch" );
-}
-
-void PatchesManager::slotShowRequestedPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant userVar = act->data();
- if ( !userVar.canConvert<MessagePointer>() )
- throw "cannot convert to message-pointer";
-
- SafeSharedPtr<PatchRequestMessage>::Locked msg = userVar.value<MessagePointer>().cast<PatchRequestMessage>();
- if ( !msg )
- throw "cannot lock/cast message";
-
- LocalPatchSourcePointer::Locked lpatch = patchFromIdentity( msg->patchIdentity() );
- if ( !lpatch )
- throw "could not find the requested patch";
-
- showEditDialog( lpatch, false );
-
- } catch ( const char * str ) {
- log( QString( "slotShowRequestedPatch failed: " ) + str );
- }
-}
-
-void PatchesManager::slotAllowPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant userVar = act->data();
-
- if ( !userVar.canConvert<MessagePointer>() )
- throw "cannot convert to message-pointer";
-
- SafeSharedPtr<PatchRequestMessage>::Locked msg = userVar.value<MessagePointer>().cast<PatchRequestMessage>();
- if ( !msg )
- throw "cannot lock/cast message";
-
- LocalPatchSourcePointer::Locked lpatch = patchFromIdentity( msg->patchIdentity() );
- if ( !lpatch )
- throw "could not find the requested patch";
-
- log( "sending patch " + ~lpatch->name + " to " + userNameFromSession( msg->info().session() ) );
- globalMessageSendHelper().sendReply<PatchMessage>( msg, ( LocalPatchSourcePointer ) lpatch, m_teamwork->logger() );
-
- msg->setStatus( PatchRequestData::Accepted );
-
- m_teamwork->messageManager() ->updateMessage( msg.data() );
- } catch ( const char * str ) {
- log( QString( "slotAllowPatch failed: " ) + str );
- }
-}
-
-
-void PatchesManager::slotDenyPatch() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
-
- if ( v.canConvert<MessagePointer>() )
- throw "cannot convert to message-pointer";
-
- SafeSharedPtr<PatchRequestMessage>::Locked msg = v.value<MessagePointer>().cast<PatchRequestMessage>();
- if ( !msg )
- throw "cannot lock/cast message";
-
- log( "denying patch to " + userNameFromSession( msg->info().session() ) );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed, "access denied" );
-
- msg->setStatus( PatchRequestData::Denied );
-
- m_teamwork->messageManager() ->updateMessage( msg.data() );
- } catch ( const char * str ) {
- log( QString( "slotAllowPatch failed: " ) + str );
- }
-}
-
-void PatchesManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {
- /*try {
- xmlDeserializeFromElementItem( el, "PatchesManager", NVP( m_config ) );
- } catch ( const QString & str ) {
- log( "could not restore the patch-information: " + str, Error );
- }*/
-}
-
-void PatchesManager::savePartialProjectSession( QDomElement* /*el*/ ) {
- /*try {
- xmlSerializeToElementItem( el, "PatchesManager", NVP( m_config ) );
- } catch ( const QString & str ) {
- log( "could not save the patch-information: " + str, Error );
- }*/
-}
-
-KDevTeamwork* PatchesManager::teamwork() {
- return m_teamwork;
-}
-
-void PatchesManager::fillDeveloperActions( const QModelIndex& index, QMenu* menu ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
-
- m_showPatchInfoAction->setData( v );
- m_showPatchAction->setData( v );
- m_downloadPatchAction->setData( v );
- m_applyPatchAction->setData( v );
-
- menu->addAction( m_showPatchInfoAction );
- menu->addAction( m_showPatchAction );
- menu->addAction( m_downloadPatchAction );
- menu->addAction( m_applyPatchAction );
-}
-
-void PatchRequestData::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
- QVariant v;
-
- v.setValue( MessagePointer( selfMessage() ) );
- teamwork->patchesManager() ->m_denyPatchAction->setData( v );
- menu->addAction( teamwork->patchesManager() ->m_denyPatchAction );
-
- teamwork->patchesManager() ->m_allowPatchAction->setData( v );
- menu->addAction( teamwork->patchesManager() ->m_allowPatchAction );
-
- teamwork->patchesManager() ->m_showRequestedPatchAction->setData( v );
- menu->addAction( teamwork->patchesManager() ->m_showRequestedPatchAction );
-}
-
-QStringList splitArgs( const QString& str );
-
-LocalPatchSource::State PatchesManager::determineState( const LocalPatchSourcePointer& patch ) {
- LocalPatchSourcePointer::Locked lpatch = patch;
- if( !lpatch ) {
- log( "determineState(..) could not lock patch", Error );
- return LocalPatchSource::Unknown;
- }
- try {
- if( lpatch->type != "text/x-diff" )
- throw "state can only be determined for files of type \"text/x-diff\"";
- if( lpatch->filename.empty() )
- throw "state can only be determined for file-patches";
-
-/* KUrl fileUrl = projectDir();
- if( (~lpatch->filename).startsWith( fileUrl.toLocalFile() ) )
- fileUrl = KUrl( ~lpatch->filename );
- else
- fileUrl.addPath( ~lpatch->filename );*/
- KUrl fileUrl = ~lpatch->filename;
-
- if( lpatch->patchTool() != "patch" || lpatch->patchTool(true) != "patch" ) throw QString( "cannot determine state with other tool than patch: \"%1\" \"%2\"").arg(~lpatch->patchTool()).arg(~lpatch->patchTool(true)) ;
-
- {
- K3Process proc;
- ///@todo does not work with remove directories
- proc.setWorkingDirectory( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
- // proc << ~lpatch->patchTool();
- bool hadFile = false;
- QString applyParams = ~lpatch->patchParams(false);
- if( applyParams.contains( "$FILE" ) )
- hadFile = true;
- //applyParams.replace( "$FILE", fileUrl.toLocalFile() );
- proc.setEnvironment( "FILE", fileUrl.toLocalFile() );
- //proc << "--dry-run" << "-s" << "-f";
- QString cmd = ~lpatch->patchTool() + " --dry-run " + applyParams + " -s -f";
- if( !hadFile ) {
- //proc << "-i" << fileUrl.toLocalFile();
- cmd += " -i " + fileUrl.toLocalFile();
- }
- proc << splitArgs( cmd );
-
- log( "determineState(...) calling " + cmd, Debug );
-
- if( !proc.start( K3Process::Block ) ) throw "could not start process";
- if( !proc.normalExit() ) throw "process did not exit normally";
- log( QString( "exit-status: %1").arg( proc.exitStatus() ), Debug );
- if( proc.exitStatus() == 0 ) {
- lpatch->state = LocalPatchSource::NotApplied;
- return LocalPatchSource::NotApplied;
- }
- }
-
- {
- K3Process proc;
- ///@todo does not work with remove directories
- proc.setWorkingDirectory( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
- //proc << ~lpatch->patchTool(true);
-
- bool hadFile = false;
- QString applyParams = ~lpatch->patchParams(true);
- if( applyParams.contains( "$FILE" ) ) {
- hadFile = true;
- }
- proc.setEnvironment( "FILE", fileUrl.toLocalFile() );
-
- //proc << "--dry-run" << "-s" << "-f" << applyParams;
- QString cmd = ~lpatch->patchTool(true) + " --dry-run -s -f " + applyParams;
- if( !hadFile ) {
- //proc << "-i" << fileUrl.toLocalFile();
- cmd += " -i " + fileUrl.toLocalFile();
- }
- proc << splitArgs( cmd );
- log( "determineState(...) calling " + cmd, Debug );
-
- if( !proc.start( K3Process::Block ) ) throw "could not start patch-process";
- if( !proc.normalExit() ) throw "process did not exit normally";
- log( QString( "exit-status: %1").arg( proc.exitStatus() ), Debug );
- if( proc.exitStatus() == 0 ) {
- lpatch->state = LocalPatchSource::Applied;
- return LocalPatchSource::Applied;
- }
- }
- } catch( const QString& str ) {
- log( "Error in determineState: " + str, Error );
- } catch( const char* str ) {
- log( QString("Error in determineState: ") + str, Error );
- }
- lpatch->state = LocalPatchSource::Unknown;
- return LocalPatchSource::Unknown;
-}
-
-void PatchesManager::save() {
- try {
- KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "patches.database" );
- ///@todo does not work with remote files
- if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
-
- std::ofstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::out | ios_base::binary );
- if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for writing";
- boost::archive::polymorphic_xml_oarchive arch( file );
- arch << NVP(m_config);
- } catch ( std::exception & exc ) {
- log( QString("save(): exception occurred while serialization: %1").arg( exc.what() ), Error );
- } catch( const char* str ) {
- log( QString("save(): %1").arg( str ), Error );
- } catch( const QString& str ) {
- log( QString( "save(): %1").arg( str ), Error );
- }
-}
-
-void PatchesManager::load() {
- try {
- KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "patches.database" );
- ///@todo does not work with remote files
- if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
-
- std::ifstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::binary );
- if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for reading";
- boost::archive::polymorphic_xml_iarchive arch( file );
- arch >> NVP(m_config);
- } catch ( std::exception & exc ) {
- log( QString("load(): exception occurred while serialization: %1").arg( exc.what() ), Error );
- } catch( const char* str ) {
- log( QString("load(): %1").arg( str ), Error );
- } catch( const QString& str ) {
- log( QString( "load(): %1").arg( str ), Error );
- }
- guiUpdatePatchesList();
-}
-
-#include "patchesmanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp (nonexistent)
@@ -1,502 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#include "messagehistorymanager.h"
-#include <fstream>
-#include <QDate>
-#include <QMap>
-#include <QTimer>
-#include <kurl.h>
-#include <klockfile.h>
-#include <kio/netaccess.h>
-
-#include "lib/network/serialization.h"
-#include "lib/network/messageserialization.h"
-
-#include "kdevteamwork_messages.h"
-#include "kdevteamwork_user.h"
-#include "teamworkfoldermanager.h"
-
-
-#include <boost/serialization/vector.hpp>
-#include <boost/serialization/map.hpp>
-#include <boost/archive/xml_iarchive.hpp>
-#include <boost/archive/xml_oarchive.hpp>
-#include <boost/archive/binary_iarchive.hpp>
-#include <boost/archive/binary_oarchive.hpp>
-#include <boost/serialization/level.hpp>
-
-#include <QDir>
-#include "kdevteamwork_client.h"
-//#include <map>
-
-using namespace Teamwork;
-
-struct FileEntryHeader {
- int version;
- int messages;
- FileEntryHeader( int _messages=0 ) : version(1), messages(_messages) {
- }
-
- void read( istream& str ) {
- str >> version >> messages;
- }
- void write( ostream& str ) {
- str << version << endl << messages << endl;
- }
-};
-
-HistoryMessageDesc::HistoryMessageDesc() {
-}
-
-HistoryMessageDesc::HistoryMessageDesc( const HistoryMessagePointer& msg )
-{
- message = msg;
- HistoryMessagePointer::Locked l = msg;
- if( l ) {
- isIncoming = l->info().isIncoming();
-
- UserPointer::Locked lu = userFromSession( l->info().session() );
- if( lu ) {
- user = lu->identity();
- } else {
- }
- } else {
- }
-}
-
-MessageHistoryManager::MessageHistoryManager( Teamwork::LoggerPointer logger ) : m_logger(logger) {
- m_pendingTimer = new QTimer();
- m_pendingTimer->start( 1000 );
- m_lockFile = new KLockFile( lockFileName() );
- connect( m_pendingTimer, SIGNAL( timeout() ), this, SLOT( writePending() ) );
-}
-
-MessageHistoryManager::~MessageHistoryManager() {
-}
-
-void MessageHistoryManager::addMessage( KDevTeamworkTextMessage* msg ) {
- HistoryMessageDesc m( msg );
- m_pending << m;
- emit newMessage( msg );
-}
-
-QList< HistoryMessagePointer > MessageHistoryManager::getMessages( const KDevTeamworkClientPointer& client, const QDate& from, const QDate& until, UserSet users ) {
- writePending();
- QStringList interestingFiles;
- QList< HistoryMessageDesc > ret;
- try {
- KUrl kdir = directory();
-
- if( !kdir.isLocalFile() )
- throw QString( "directory \"%1\" is not local" ).arg( kdir.prettyUrl() );
-
- QDir dir( kdir.toLocalFile() );
- if( !dir.isReadable() ) throw QString( "directory \"%1\" is not readable" ).arg( dir.path() );
-
- QStringList files = dir.entryList( QDir::Files );
-
- for( QStringList::iterator it = files.begin(); it != files.end(); ++it ) {
- QDate date = QDate::fromString( *it, Qt::ISODate );
- if( !date.isValid() ) continue;
- if( from.isValid() ) {
- if( until.isValid() ) {
- ///from "from" until "until"
- if( date >= from && date <= until )
- interestingFiles << *it;
- } else {
- ///from "from" until now
- if( date >= from )
- interestingFiles << *it;
- }
- } else {
- if( until.isValid() ) {
- ///from begin until "until"
- if( date <= until )
- interestingFiles << *it;
- } else {
- ///All messages
- interestingFiles << *it;
- }
- }
- }
-
- for( QStringList::iterator it = interestingFiles.begin(); it != interestingFiles.end(); ++it ) {
- KUrl fileUrl = kdir;
- fileUrl.addPath( *it );
- std::ifstream f( fileUrl.toLocalFile().toLatin1(), ios_base::binary );
- if( !f.good() ) {
- err() << "could not open" << ~fileUrl.toLocalFile();
- }
- while( !f.eof() ) {
- if( !f.good() ) {
- err() << "error while reading" << ~fileUrl.toLocalFile();
- break;
- }
-
- FileEntryHeader header;
- header.read( f );
-
- //f.read( (char*)&header, sizeof( FileEntryHeader ) );
- if( f.eof() ) break;
-
- if( !f.good() ) {
- err() << "could not read a header from file \"" << ~*it << "\"";
- break;
- } else {
- out( Logger::Debug ) << "successfully read a header";
- }
-
- try {
- ///read the message from the archive
- boost::archive::xml_iarchive arch( f );
- QList<HistoryMessageDesc> messages;
- for( int a = 0; a < header.messages; a++ ) {
- HistoryMessageDesc msg;
- arch >> boost::serialization::make_nvp( "message", msg );
- if( users.empty() || users.contains( msg.user ) )
- ret << msg;
- }
- }
- catch( std::exception& exc ) {
- err() << "error while deserializing from \"" << ~*it << "\":" << exc.what();
- break;
- }
- }
- }
-
- }
- catch( QString str ) {
- err() << "error in MessageHistoryManager::getMessages:" << ~str;
- }
-
- return fillMessageUsers( ret, client );
-}
-
-struct WaitError {
- QString str;
- WaitError( const QString& stri ) : str( stri ) {
- }
-};
-
-void MessageHistoryManager::writePending()
-{
- try
- {
- KUrl dir = directory();
- if( !dir.isLocalFile() ) throw QString( "the directory %1 is not local" ).arg( dir.prettyUrl() );
-
- m_pendingTimer->start( 1000 );
- QMap< QDate, QList<HistoryMessageDesc> > map;
- std::map< Teamwork::UniqueMessageId, HistoryGroupLocation > insertions;
-
- for( QList<HistoryMessageDesc>::iterator it = m_pending.begin(); it != m_pending.end(); ++it ) {
- HistoryMessagePointer::Locked l = it->message;
- if( l ) {
- QDate key( l->creationTime().date() );
- map[ key ] << *it;
- } else {
- err() << "could not lock a message for storing it into the history, the message will be lost";
- }
- }
-
- for( QMap< QDate, QList<HistoryMessageDesc> >::iterator it = map.begin(); it != map.end(); ++it ) {
- QDate date( it.key() );
-
- if( !date.isValid() ) {
- err() << "tried to store" << it->count() << "messages with invalid date";
- continue;
- }
-
- if( !m_lockFile->isLocked() ) {
- switch( m_lockFile->lock( KLockFile::NoBlockFlag | KLockFile::ForceFlag ) ) {
- case KLockFile::LockOK:
- break;
- case KLockFile::LockFail:
- throw WaitError( "locking the lockfile " + lockFileName() + " failed" );
- break;
- case KLockFile::LockError:
- throw "an error occurred while locking the lockfile " + lockFileName();
- break;
- case KLockFile::LockStale:
- throw WaitError( "the lockfile " + lockFileName() + " is stale" );
- }
- }
-
- KUrl file = dir;
- QString localFileName = date.toString( Qt::ISODate );
- file.addPath( localFileName );
- std::string fileName = ~file.toLocalFile();
-
- if( fileName.empty() ) {
- err() << "empty file-path for date" << ~date.toString( Qt::ISODate );
- continue;
- }
-
- std::ofstream f( fileName.c_str(), ios_base::binary | ios_base::app );
-
- if( !f.good() ) {
- err() << "could not open file \"" << fileName << "\" for read/write";
- continue;
- }
- f.seekp( 0, std::ios_base::end );
-
- FileEntryHeader header( it->count() );
-
- HistoryGroupLocation location;
- location.fileName = ~localFileName;
- location.offset = f.tellp();
-
- header.write( f );
- //f.write( (char*)&header, sizeof( FileEntryHeader ) );
-
- if( !f.good() ) {
- err() << "could not write header into file \"" << fileName << "\"";
- continue;
- }
-
- try {
- ///Store the messages into the archive
- boost::archive::xml_oarchive arch( f );
- for( QList<HistoryMessageDesc>::iterator it2 = it->begin(); it2 != it->end(); ++it2 ) {
- arch << boost::serialization::make_nvp( "message", *it2 );
-
- HistoryMessagePointer::Locked l = it2->message;
- if( l ) {
- insertions[ l->info().uniqueId() ] = location;
- } else {
- err() << "could not lock a message while storing it into the history";
- }
- }
- }
- catch( std::exception& exc ) {
- err() << "error while serializing into \"" << fileName << "\":" << exc.what();
- }
- }
-
- ///The index maps unique-message-ids to the files they can be found in(including offset to the FileEntryHeader)
- std::map<Teamwork::UniqueMessageId, HistoryGroupLocation> index;
-
- if( !insertions.empty() ) {
- try {
- readIndex( index );
- }
- catch( QString str ) {
- out( Logger::Warning ) << "error in readIndex:" << str;
- }
-
- index.insert( insertions.begin(), insertions.end() );
-
- writeIndex( index );
- }
-
-
- m_pending.clear();
- }
- catch( WaitError err ) {
- out( Logger::Warning ) << "in MessageHistoryManager::writePending:" << err.str;
- }
- catch( QString str )
- {
- err() << "error in MessageHistoryManager::writePending:" << str;
- m_pending.clear();
- }
-
- if( m_lockFile->isLocked() )
- m_lockFile->unlock();
-}
-
-QString MessageHistoryManager::lockFileName() {
- KUrl file = directory();
- file.addPath( ".lock" );
- return file.toLocalFile();
-}
-
-void MessageHistoryManager::readIndex( std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString) {
- KUrl ind = directory();
- ind.addPath( "index" );
- if( !ind.isLocalFile() ) throw QString( "the index-file is not local" );
-
- std::string indexFile = ~ind.toLocalFile();
-
- {
- std::ifstream f( indexFile.c_str(), ios_base::binary );
- if( !f.good() ) throw QString( "could not open index-file for reading" );
-
- try {
- boost::archive::binary_iarchive arch( f );
- arch & index;
- }
- catch( std::exception& exc ) {
- err() << "error while deserializing the index \"" << indexFile << "\":" << exc.what();
- throw QString( "error in readIndex" );
- }
- }
-}
-
-void MessageHistoryManager::writeIndex( const std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString) {
- {
- KUrl ind = directory();
- ind.addPath( "index" );
- if( !ind.isLocalFile() ) throw QString( "the index-file is not local" );
-
- std::string indexFile = ~ind.toLocalFile();
-
- std::ofstream f( indexFile.c_str(), ios_base::binary );
- if( !f.good() ) throw QString( "could not open index-file for writing" );
-
- try {
- ///Store the messages into the archive
- boost::archive::binary_oarchive arch( f );
- arch & index;
- }
- catch( std::exception& exc ) {
- err() << "error while serializing the index \"" << indexFile << "\":" << exc.what();
- throw QString( "error in writeIndex" );
- }
- }
-}
-
-KUrl MessageHistoryManager::directory() throw(QString)
-{
- KUrl ul = TeamworkFolderManager::teamworkAbsolute( "messages" );
- TeamworkFolderManager::createTeamworkFolder();
-
- if( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- KIO::NetAccess::mkdir( ul, 0 );
-
- if( !KIO::NetAccess::exists( ul, KIO::NetAccess::SourceSide, 0 ) )
- throw QString( "could not create messages-directory " ) + ul.toLocalFile();
-
- return ul;
-}
-
-void MessageHistoryManager::readMessages( const QString& file, uint offset, QList<HistoryMessageDesc>& messages ) throw(QString)
-{
- KUrl path = directory();
- path.addPath( file );
-
- if( !path.isLocalFile() ) throw QString( "message is not local" );
- if( !KIO::NetAccess::exists( path, KIO::NetAccess::SourceSide, 0 ) ) throw QString( "index does not exist" );
-
- std::ifstream f( path.toLocalFile().toLatin1(), ios_base::binary );
- f.seekg( offset );
- if( !f.good() || f.eof() ) throw QString( "could not open file and seek to offset %1 in file %2" ).arg( offset ).arg( path.toLocalFile() );
-
- FileEntryHeader header;
-
- header.read( f );
- if( !f.eof() ) {
- if( !f.good() || f.eof() )
- throw QString( "could not read a header from file \"%1\"" ).arg( path.toLocalFile() );
-
- try {
- boost::archive::xml_iarchive arch( f );
- for( int a = 0; a < header.messages; a++ ) {
- HistoryMessageDesc msg;
- arch >> boost::serialization::make_nvp( "message", msg );
- messages << msg;
- }
- }
- catch( std::exception& exc ) {
- err() << "error while deserializing from \"" << ~path.toLocalFile() << "\":" << exc.what();
- }
- }
-}
-
-HistoryMessagePointer MessageHistoryManager::getMessageFromId( Teamwork::UniqueMessageId id, const KDevTeamworkClientPointer& client ) {
- std::map<Teamwork::UniqueMessageId, HistoryGroupLocation> index;
- try {
- readIndex( index );
- std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>::iterator it = index.find( id );
- if( it != index.end() ) {
- QList<HistoryMessageDesc> messages;
- readMessages( ~it->second.fileName, it->second.offset, messages );
-
- for( QList<HistoryMessageDesc>::iterator it = messages.begin(); it != messages.end(); ++it ) {
- HistoryMessagePointer::Locked l = it->message;
- if( l ){
- if( l->info().uniqueId() == id ) {
- return fillMessageUser( *it, client );
- }
- }
- }
-
- return HistoryMessagePointer();
- } else {
- return HistoryMessagePointer();
- }
- }
- catch( QString str ) {
- err() << "error in messageFromId:" << ~str;
- return HistoryMessagePointer();
- }
-}
-
-HistoryMessagePointer MessageHistoryManager::fillMessageUser( const HistoryMessageDesc& desc, const KDevTeamworkClientPointer& client ) {
- HistoryMessagePointer::Locked lmsg = desc.message;
- KDevTeamworkClientPointer::Locked l = client;
- if( !l ) {
- err() << "could not lock KDevTeamworkClient";
- return HistoryMessagePointer();
- }
- if( lmsg ) {
- lmsg->info().setUser( l->getUser( desc.user ) );
- return lmsg;
- } else {
- err() << "could not lock a message in fillMessageUsers";
- }
-
- return HistoryMessagePointer();
-}
-
-QList<HistoryMessagePointer> MessageHistoryManager::fillMessageUsers( const QList<HistoryMessageDesc>& messages, const KDevTeamworkClientPointer& client ) {
- QList<HistoryMessagePointer> ret;
- KDevTeamworkClientPointer::Locked l = client;
-
- if( l ) {
- foreach( const HistoryMessageDesc& desc, messages ) {
- HistoryMessagePointer::Locked lmsg = desc.message;
- if( lmsg ) {
- lmsg->info().setUser( l->getUser( desc.user ) );
- ret << lmsg;
- } else {
- err() << "could not lock a message in fillMessageUsers";
- }
- }
- } else {
- err() << "could not lock teamwork-client";
- }
-
- return ret;
-}
-
-Teamwork::LoggerPrinter MessageHistoryManager::out( Teamwork::Logger::Level level ) {
- Teamwork::LoggerPrinter ret( m_logger, level );
- ret << "in MessageHistoryManager: ";
- return ret;
-}
-
-
-Teamwork::LoggerPrinter MessageHistoryManager::err() {
- Teamwork::LoggerPrinter ret( m_logger, Teamwork::Logger::Error );
- ret << "Error in MessageHistoryManager: ";
- return ret;
-}
-
-BOOST_CLASS_IMPLEMENTATION(HistoryMessageDesc, boost::serialization::object_serializable)
-
-#include "messagehistorymanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui (nonexistent)
@@ -1,417 +0,0 @@
-<ui version="4.0" >
- <class>TextMessageShower</class>
- <widget class="QWidget" name="TextMessageShower" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>582</width>
- <height>173</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="4" column="0" >
- <widget class="QFrame" name="bottomSpace" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>4</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>16</width>
- <height>0</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- </widget>
- </item>
- <item row="5" column="0" >
- <widget class="QFrame" name="frame_2" >
- <property name="sizeIncrement" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <property name="lineWidth" >
- <number>1</number>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>2</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="menuButton" >
- <property name="text" >
- <string>Menu</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="historyButton" >
- <property name="text" >
- <string>History</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>331</width>
- <height>27</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QFrame" name="buttonSpace" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="isReplyToButton" >
- <property name="text" >
- <string>Is Reply To</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="QFrame" name="topSpace" >
- <property name="enabled" >
- <bool>true</bool>
- </property>
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>4</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>16</width>
- <height>0</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="QGroupBox" name="textBox" >
- <property name="font" >
- <font>
- <family>Sans Serif</family>
- <pointsize>9</pointsize>
- <weight>75</weight>
- <italic>false</italic>
- <bold>true</bold>
- <underline>false</underline>
- <strikeout>false</strikeout>
- </font>
- </property>
- <property name="title" >
- <string>Text</string>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>2</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QLabel" name="text" >
- <property name="font" >
- <font>
- <family>Sans Serif</family>
- <pointsize>9</pointsize>
- <weight>50</weight>
- <italic>false</italic>
- <bold>false</bold>
- <underline>false</underline>
- <strikeout>false</strikeout>
- </font>
- </property>
- <property name="text" >
- <string>Text</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QFrame" name="middleSpace" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>4</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>16</width>
- <height>0</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- </widget>
- </item>
- <item row="3" column="0" >
- <widget class="QFrame" name="frame" >
- <property name="frameShape" >
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>2</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="1" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="state_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">State&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="state" >
- <property name="text" >
- <string>State</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="time_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Time&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="time" >
- <property name="text" >
- <string>Time</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="user_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">User&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="userIcon" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string/>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="user" >
- <property name="text" >
- <string>User</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="direction_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Direction&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="direction" >
- <property name="text" >
- <string>Direction</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0" >
- <widget class="QFrame" name="stateSpace" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>4</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize" >
- <size>
- <width>0</width>
- <height>1</height>
- </size>
- </property>
- <property name="frameShape" >
- <enum>QFrame::NoFrame</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <property name="lineWidth" >
- <number>0</number>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_textmessage.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp (nonexistent)
@@ -1,165 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright 2006 Adam Treat <treat@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "kdevteamworkplugin.h"
-#include "kdevteamwork.h"
-
-#include <QMenu>
-#include <QAction>
-#include <QToolButton>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-
-#include <kaction.h>
-#include <klocale.h>
-#include <kmimetype.h>
-#include <kaboutdata.h>
-#include <kiconloader.h>
-#include <kpluginfactory.h>
-#include <kaboutdata.h>
-#include <kpluginloader.h>
-#include <interfaces/icore.h>
-#include <interfaces/iprojectcontroller.h>
-#include <interfaces/iproject.h>
-#include <interfaces/iuicontroller.h>
-
-// #include <kplugininfo.h>
-
-KDevTeamworkPlugin* KDevTeamworkPlugin::m_self = 0;
-
-K_PLUGIN_FACTORY(KDevTeamworkFactory, registerPlugin<KDevTeamworkPlugin>(); )
-K_EXPORT_PLUGIN(KDevTeamworkFactory(KAboutData("kdevteamwork","kdevteamwork", ki18n("Teamwork"), "0.1", ki18n("Collaboration support"), KAboutData::License_GPL)))
-
-
-class KDevTeamworkViewFactory : public KDevelop::IToolViewFactory
-{
-public:
- KDevTeamworkViewFactory(KDevTeamworkPlugin *plugin): m_plugin(plugin) {}
-
- virtual QWidget* create(QWidget *parent = 0)
- {
- QWidget* view = new QWidget(parent);
- view->setObjectName("Teamwork");
- view->setWindowTitle(i18n("Teamwork"));
- m_plugin->setView( view );
- return view;
- }
-
- virtual Qt::DockWidgetArea defaultPosition()
- {
- return Qt::RightDockWidgetArea;
- }
-
- virtual QString id() const
- {
- return "org.kdevelop.Teamwork";
- }
-
-private:
- KDevTeamworkPlugin *m_plugin;
-};
-
-void KDevTeamworkPlugin::unload()
-{
- core()->uiController()->removeToolView(m_factory);
-}
-
-KDevTeamworkPlugin::KDevTeamworkPlugin( QObject *parent,
- const QVariantList& )
- : KDevelop::IPlugin( KDevTeamworkFactory::componentData(), parent ), m_currentProject( 0 ), m_window(0), m_factory( new KDevTeamworkViewFactory(this) )
-{
- m_self = this;
- setXMLFile( "kdevteamwork.rc" );
- core()->uiController()->addToolView(i18n("Teamwork"), m_factory);
- m_window = 0;
-
- connect( core()->projectController(), SIGNAL( projectOpened( KDevelop::IProject* ) ), this, SLOT( projectOpened( KDevelop::IProject* ) ) );
- connect( core()->projectController(), SIGNAL( projectClosed( KDevelop::IProject* ) ), this, SLOT( projectClosed( KDevelop::IProject* ) ) );
-}
-
-KDevelop::ICore * KDevTeamworkPlugin::staticCore( )
-{
- return m_self->core();
-}
-
-void KDevTeamworkPlugin::setView( QWidget* view ) {
- KDevelop::IProject* oldProject = m_currentProject;
- destroyTeamwork();
- m_window = view;
-
- if( oldProject )
- startTeamwork( oldProject );
-}
-
-void KDevTeamworkPlugin::destroyTeamwork() {
- delete m_teamwork;
- m_teamwork = 0;
- m_currentProject = 0;
- if( m_window )
- m_window->hide();
-}
-
-void KDevTeamworkPlugin::startTeamwork( KDevelop::IProject* project ) {
- destroyTeamwork();
- m_currentProject = project;
- if( !m_window ) return;
- m_teamwork = new KDevTeamwork( project->folder(), this, m_window );
- m_window->show();
-}
-
-KDevelop::IDocumentController* KDevTeamworkPlugin::staticDocumentController() {
- return staticCore()->documentController();
-}
-
-KDevTeamworkPlugin::~KDevTeamworkPlugin()
-{
- destroyTeamwork();
-}
-
-QWidget* KDevTeamworkPlugin::pluginView() const
-{
- return m_window;
-}
-
-void KDevTeamworkPlugin::import( RefreshPolicy /*policy*/ )
-{}
-
-void KDevTeamworkPlugin::restorePartialProjectSession(const QDomElement* el) {
- m_teamwork->restorePartialProjectSession( el );
-}
-
-void KDevTeamworkPlugin::savePartialProjectSession(QDomElement* el) {
- m_teamwork->savePartialProjectSession( el );
-}
-
-void KDevTeamworkPlugin::projectOpened( KDevelop::IProject* project ) {
- if( !m_currentProject )
- startTeamwork( project );
-}
-
-void KDevTeamworkPlugin::projectClosed( KDevelop::IProject* project ) {
- if( project == m_currentProject )
- destroyTeamwork();
-}
-
-
-#include "kdevteamworkplugin.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamworkplugin.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp (nonexistent)
@@ -1,263 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "filecollaborationmessages.h"
-#include "filecollaborationmanager.h"
-#include "kdevteamwork.h"
-#include "collaborationmanager.h"
-#include <QMenu>
-#include <ktexteditor/document.h>
-#include "lib/network/messagesendhelper.h"
-#include "lib/network/messagetypeset.h"
-#include "kdevteamwork_helpers.h"
-#include "safesignaller.h"
-#include <boost/serialization/list.hpp>
-#include <boost/serialization/string.hpp>
-#include <boost/serialization/vector.hpp>
-#include "qtserialization.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-Q_DECLARE_METATYPE( MessagePointer )
-
-FileCollaborationRequestData::FileCollaborationRequestData( FileCollaboration* collab, uint index, uint senderIndex ) : m_state( Unknown ), m_index( index ), m_senderIndex( senderIndex ), m_isAutomatic( false ), m_collab( collab ), m_acceptAction( 0 ), m_denyAction( 0 ) {
-
- if ( collab ) {
- m_files = collab->session() ->fileNames();
- if ( collab->session() ) {
- m_session = collab->session();
- m_name = collab->session() ->name();
- connect( ( QObject* ) this, SIGNAL( stateChanged( const MessagePointer& ) ), ( QObject* ) collab->session() ->manager() ->teamwork() ->messageManager(), SLOT( updateMessage( const MessagePointer& ) ), Qt::QueuedConnection );
- connect( ( QObject* ) this, SIGNAL( connectionResult( bool ) ), ( QObject* ) collab, SLOT( slotConnectionResult( bool ) ), Qt::QueuedConnection );
- }
-
- connect( this, SIGNAL( processReply( const MessagePointer& ) ), collab, SLOT( processMessage( const MessagePointer& ) ), Qt::QueuedConnection );
-
- }
-}
-
-uint FileCollaborationRequestData::index( ) const {
- return m_index;
-}
-
-uint FileCollaborationRequestData::senderIndex( ) const {
- return m_senderIndex;
-}
-
-bool FileCollaborationRequestData::isAutomatic() const {
- return m_isAutomatic;
-}
-
-void FileCollaborationRequestData::setAutomatic( bool automatic ) {
- m_isAutomatic = automatic;
-}
-
-CollabFileList FileCollaborationRequestData::files() const {
- return m_files;
-}
-
-void FileCollaborationRequestData::setFiles( const CollabFileList& theValue ) {
- m_files = theValue;
-}
-
-QString FileCollaborationRequestData::name() const {
- return m_name;
-}
-
-void FileCollaborationRequestData::setName( const QString& theValue ) {
- m_name = theValue;
-}
-
-QString FileCollaborationRequest::messageText() const {
- QString name = "unknown";
- if ( info().user() )
- name = ~info().user().unsafe() ->safeName();
- QString files;
- for( CollabFileList::const_iterator it = m_files.begin(); it != m_files.end(); ++it ) {
- if( !files.isEmpty() ) files += "\n";
- files += (*it).file;
- }
- if ( info().isIncoming() ) {
- return QString( "File-collaboration-request from %1 on:\n%2" ).arg( name ).arg( files );
- } else {
- return QString( "File-collaboration-request to %1 on:\n%2" ).arg( name ).arg( files );
- }
-}
-
-QIcon FileCollaborationRequest::messageIcon() const {
- switch ( m_state ) {
- case Unknown:
- if ( info().isIncoming() )
- return IconCache::getIconStatic( "filecollaborationrequest_in" );
- else
- return IconCache::getIconStatic( "filecollaborationrequest_out" );
- case Accepted:
- if ( info().isIncoming() )
- return IconCache::getIconStatic( "filecollaborationrequest_in_accepted" );
- else
- return IconCache::getIconStatic( "filecollaborationrequest_out_accepted" );
- case Denied:
- if ( info().isIncoming() )
- return IconCache::getIconStatic( "filecollaborationrequest_in_denied" );
- else
- return IconCache::getIconStatic( "filecollaborationrequest_out_denied" );
- case Failed:
- if ( info().isIncoming() )
- return IconCache::getIconStatic( "filecollaborationrequest_in_failed" );
- else
- return IconCache::getIconStatic( "filecollaborationrequest_out_failed" );
- }
- return IconCache::getIconStatic( "unknown" );
-}
-
-FileCollaborationRequestData::State FileCollaborationRequestData::state() const {
- return m_state;
-}
-
-void FileCollaborationRequestData::updateState() {
- emit stateChanged( ( FileCollaborationRequest* ) this );
-}
-
-bool FileCollaborationRequest::needReply() const {
- if ( m_collab )
- return true;
- else
- return false;
-}
-
-
-MessageInterface::ReplyResult FileCollaborationRequest::gotReply( const MessagePointer& p ) {
- if ( !m_collab )
- return ReplyResult();
- bool handled = false;
- MessagePointer msg = p;
- if ( m_state == Unknown ) {
- if ( msg.cast<KDevSystemMessage>() ) {
- LockedSharedPtr<KDevSystemMessage> lmsg = msg.cast<KDevSystemMessage>();
- if ( lmsg ) {
- if ( lmsg->message() == KDevSystemMessage::ActionSuccessful ) {
- m_state = Accepted;
- emit connectionResult( true );
- } else if ( lmsg->message() == KDevSystemMessage::ActionDenied ) {
- m_state = Denied;
- emit connectionResult( false );
- } else {
- m_state = Failed;
- emit connectionResult( false );
- }
- } else {
- m_state = Failed;
- emit connectionResult( false );
- }
- handled = true;
- }
-
- if ( m_state == Unknown && msg.cast<FileCollaborationRequest>() ) {
- LockedSharedPtr<FileCollaborationRequest> lmsg = msg.cast<FileCollaborationRequest>();
- if ( lmsg ) {
- globalMessageSendHelper().sendReply<KDevSystemMessage>( lmsg, KDevSystemMessage::ActionSuccessful );
- m_state = Accepted;
- emit connectionResult( true );
- } else {
- m_state = Failed;
- emit connectionResult( false );
- }
- handled = true;
- }
-
- updateState();
- }
-
- emit processReply( p );
-
- if ( m_state != Denied && m_state != Failed && m_collab && m_session )
- return ReplyResult( true, true );
- else
- return ReplyResult( handled );
-}
-
-void FileCollaborationRequestData::dispatchSignal( const AcceptSignal& /*sig*/ ) {
- acceptCollaboration();
-}
-
-void FileCollaborationRequestData::dispatchSignal( const DenySignal& /*sig*/ ) {
- denyCollaboration();
-}
-
-
-void FileCollaborationRequestData::acceptCollaboration() {
- cout << "acceptCollaboration" << endl;
-
- MessagePointer::Locked l = ( FileCollaborationRequest* ) this;
- if ( l && m_teamwork ) {
- m_state = Accepted;
- if ( !m_teamwork->collaborationManager() ->fileCollaborationManager().acceptCollaboration( ( FileCollaborationRequest* ) this ) )
- m_state = Failed;
- } else {
- m_state = Failed;
- }
-
- updateState();
-}
-
-void FileCollaborationRequestData::denyCollaboration() {
- cout << "denyCollaboration" << endl;
- MessagePointer::Locked l = ( FileCollaborationRequest* ) this;
- if ( l && m_teamwork ) {
- globalMessageSendHelper().sendReply<KDevSystemMessage> ( l, KDevSystemMessage::ActionDenied );
- m_state = Denied;
- m_teamwork->collaborationManager() ->fileCollaborationManager().denyCollaboration( ( FileCollaborationRequest* ) this );
- } else {
- m_state = Failed;
- }
-
- updateState();
-}
-
-void FileCollaborationRequest::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
- m_teamwork = teamwork;
- if ( m_state == Unknown && info().isIncoming() ) {
-
- /*QAction* a = menu->addAction( "Accept File-Collaboration", this, SLOT(acceptCollaboration()) );
- QAction* d = menu->addAction( "Deny File-Collaboration", this, SLOT( denyCollaboration() ) );*/
- QAction* a = menu->addAction( "Accept File-Collaboration", new QSafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::AcceptSignal(), menu ), SLOT( signal() ) );
- QAction* d = menu->addAction( "Deny File-Collaboration", new QSafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::DenySignal(), menu ), SLOT( signal() ) );
-
-/*
- connect( a, SIGNAL( triggered( bool ) ), new SafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::AcceptSignal(), menu ), SLOT( signal() ) );
- connect( d, SIGNAL( triggered( bool ) ), new SafeSignaller( FileCollaborationRequestPointer(this), FileCollaborationRequestData::DenySignal(), menu ), SLOT( signal() ) );*/
-
- connect( ( QObject* ) this, SIGNAL( stateChanged( const MessagePointer& ) ), ( QObject* ) teamwork->messageManager(), SLOT( updateMessage( const MessagePointer& ) ), Qt::QueuedConnection );
-
- QVariant v;
- v.setValue<MessagePointer>( this );
- a->setData( v );
- d->setData( v ); ///This makes sure that the message is not deleted in the wrong moment, and the slots can be called safely by the actions.
- }
-}
-
-EASY_IMPLEMENT_MESSAGE( FileCollaborationMessage )
-EASY_IMPLEMENT_MESSAGE( DocumentWrapperMessage )
-EASY_IMPLEMENT_MESSAGE( FileCollaborationRequest )
-EASY_IMPLEMENT_MESSAGE( FileEditMessage )
-EASY_IMPLEMENT_MESSAGE( FileListMessage )
-EASY_IMPLEMENT_MESSAGE( FileEditRejectMessage )
-
-#include "filecollaborationmessages.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmessages.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp (nonexistent)
@@ -1,237 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "kdevteamwork_messages.h"
-#include "kdevteamwork.h"
-#include <QDateTime>
-#include "kdevteamwork_messageshower.h"
-#include "kdevteamwork_helpers.h"
-#include "indocumentreference.h"
-#include "lib/network/teamworkserver.h"
-#include "lib/network/teamworkclient.h"
-#include <boost/serialization/list.hpp>
-#include <boost/serialization/string.hpp>
-
-REGISTER_MESSAGE( KDevSystemMessage )
-REGISTER_MESSAGE( KDevTeamworkTextMessage )
-REGISTER_MESSAGE( ConnectionRequest )
-EASY_IMPLEMENT_MESSAGE( CollaborationMessage )
-
-
-KDevSystemMessage::KDevSystemMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : SystemMessage( arch, info ) {}
-KDevSystemMessage::KDevSystemMessage( const Teamwork::MessageConstructionInfo& info, Message msg , const string& str ) : SystemMessage( info(this), ( Teamwork::SystemMessage::Message ) msg, str ) {}
-
-KDevSystemMessage::Message KDevSystemMessage::message() {
- return ( Message ) SystemMessage::message();
-}
-
-QString KDevSystemMessage::messageAsString() {
- switch ( message() ) {
- case CollaborationAccepted:
- return "collaboration accepted";
- case CollaborationRefused:
- return "collaboration refused";
- case CollaborationClosed:
- return "collaboration stopped";
- case ActionFailed:
- return "action failed";
- case ActionSuccessful:
- return "action successful";
- case ActionDenied:
- return "action denied";
- }
- return "unknown kdev-system-message";
-}
-
-QString KDevSystemMessage::text() {
- return SystemMessage::text().c_str();
-}
-
-typedef SafeSharedPtr<KDevSystemMessage> KDevSystemMessagePointer;
-
-KDevTeamworkTextMessage::KDevTeamworkTextMessage( const Teamwork::MessageConstructionInfo& info, const QString& text ) : TextMessage( info(this), text.toUtf8().data() ), creationTime_( QDateTime::currentDateTime() ), m_answered( false ) {}
-
-KDevTeamworkTextMessage::KDevTeamworkTextMessage( InArchive& from, const Teamwork::MessageInfo& info ) : TextMessage( from, info ), m_answered( false ) {
- std::string date;
- from & date;
- creationTime_ = QDateTime::fromString( ~date, Qt::ISODate );
-}
-
-void KDevTeamworkTextMessage::setAnswered( bool a ) {
- m_answered = a;
-}
-
-bool KDevTeamworkTextMessage::answered() const {
- return m_answered;
-}
-
-QString KDevTeamworkTextMessage::messageText() const {
- return ~Teamwork::TextMessage::text();
-}
-
-class DocumentMessageInternal;
-class InDocumentConversation;
-
-bool KDevTeamworkTextMessage::needReply() const {
- return true;
-}
-
-ConnectionRequest::ConnectionRequest( InArchive& arch, const Teamwork::MessageInfo& info ) : KDevTeamworkTextMessage( arch, info ), m_state( Waiting ) {
- arch & user_;
- //user_.load( arch, 0 );
-}
-
-void ConnectionRequest::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- //user_.save( arch, version );
- arch & user_;
-}
-
-const Teamwork::User& ConnectionRequest::user() {
- return user_;
-}
-
-bool ConnectionRequest::needReply() const {
- return true;
-}
-
-void ConnectionRequest::setState( State s ) {
- m_state = s;
-}
-
-ConnectionRequest::State ConnectionRequest::state() {
- return m_state;
-}
-
-bool KDevTeamworkTextMessage::canShowInWidget() {
- return true;
-}
-
-
-void KDevTeamworkTextMessage::showInWidget( QWidget* widget, KDevTeamwork* tw ) {
- new KDevTeamworkMessageShower( this, widget, tw );
-}
-
-QDateTime KDevTeamworkTextMessage::creationTime() {
- return creationTime_;
-}
-
-void KDevTeamworkTextMessage::serialize( OutArchive& arch ) {
- TextMessage::serialize( arch );
- std::string date = ~creationTime_.toString( Qt::ISODate );
- arch & date;
-}
-
-QIcon KDevTeamworkTextMessage::messageIcon() const {
- IconCache & cache( *IconCache::instance() );
-
- if ( info().isIncoming() )
- return cache( "text_message_in" );
- else
- return cache( "text_message_out" );
-}
-
-ConnectionRequest::ConnectionRequest( const Teamwork::MessageConstructionInfo& info, const Teamwork::UserPointer& self, const Teamwork::UserPointer& target, const QString& text, KDevTeamwork* teamwork ) : KDevTeamworkTextMessage( info(this), text ), m_state( Waiting ), m_emitter( new SafeTeamworkEmitter( teamwork ) ) {
- Teamwork::UserPointer::Locked l = self;
- Teamwork::UserPointer::Locked tl = target;
- if ( l ) {
- user_ = *l;
- user_.stripForTarget( *tl );
- } else {
- user_ = Teamwork::User( "unlockable" );
- }
-}
-
-MessageInterface::ReplyResult ConnectionRequest::gotReply( const MessagePointer& p ) {
- KDevSystemMessagePointer::Locked lmessage = ( ( MessagePointer ) p ).cast<KDevSystemMessage>();
-
- if ( lmessage ) {
- switch ( lmessage->message() ) {
- case KDevSystemMessage::CollaborationRefused:
- m_state = Denied;
- break;
- case KDevSystemMessage::CollaborationAccepted:
- m_state = Accepted;
- break;
- case KDevSystemMessage::ActionFailed:
- m_state = Unknown;
- break;
- default:
- m_state = Unknown;
- break;
- }
- } else {
- return ReplyResult( false, true ); ///Messages other than KDevSystemMessage are not accepted
- }
-
- if ( m_emitter.data() )
- m_emitter->updateMessageInfo( this );
- return ReplyResult();
-}
-
-QIcon ConnectionRequest::messageIcon() const {
- IconCache & cache( *IconCache::instance() );
-
- if ( !info().isIncoming() ) {
- if ( m_state == Denied ) {
- return cache( "collaborationrequest_out_denied" );
- } else if ( m_state == Accepted ) {
- return cache( "collaborationrequest_out_accepted" );
- } else if ( m_state == Unknown ) {
- return cache( "unknown" );
- } else {
- return cache( "collaborationrequest_out" );
- }
- } else {
- if ( m_state == Denied ) {
- return cache( "collaborationrequest_in_denied" );
- } else if ( m_state == Accepted ) {
- return cache( "collaborationrequest_in_accepted" );
- } else if ( m_state == Unknown ) {
- return cache( "unknown" );
- } else {
- return cache( "collaborationrequest_in" );
- }
- }
-
- if ( info().isIncoming() )
- return cache( "collaborationrequest_in" );
- else
- return cache( "collaborationrequest_out" );
-}
-
-QIcon AbstractGUIMessage::messageTypeIcon() const {
- IconCache & cache( *IconCache::instance() );
- return cache( "message" );
-}
-
-QIcon AbstractGUIMessage::messageIcon() const {
- IconCache & cache( *IconCache::instance() );
- return cache( "message" );
-}
-
-FailureMessage::FailureMessage( const QString& text, const MessagePointer& msg ) : KDevTeamworkTextMessage( globalMessageTypeSet(), text ) {
- info().setReplyMessage( msg );
- MessagePointer::Locked l = msg;
- if( l ) {
- info().setReply( l->info().uniqueId() );
- info().setUser( l->info().user() );
- }
-}
-
-QIcon FailureMessage::messageIcon() const {
- return IconCache::getIconStatic( "failed" );
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messages.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.cpp (nonexistent)
@@ -1,25 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "helpers.h"
-#include "lib/network/networkfwd.h"
-#include "lib/network/sessioninterface.h"
-#include "lib/network/user.h"
-
-Teamwork::UserPointer userFromSession( const Teamwork::SessionPointer& session ) {
- if( !session ) return 0;
- return session.unsafe() ->safeUser();
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/helpers.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp (nonexistent)
@@ -1,323 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "vectortimestampeditor.h"
-#include <QStandardItemModel>
-#include <QModelIndex>
-#include <QVBoxLayout>
-#include <kdialog.h>
-#include "qdynamictext.h"
-#include "verify.h"
-#include "utils.h"
-
-std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs );
-
-VectorTimestampEditorLogger::VectorTimestampEditorLogger( VectorTimestampEditor* ed ) : m_editor(ed) {
-}
-
-void VectorTimestampEditorLogger::log( const std::string& str , Level lv ) {
- m_editor->log( ~str, (LogLevel)lv );
-}
-
-TimestampEditor::TimestampEditor( Teamwork::LoggerPointer logger, VectorTimestampEditor* parent, uint index ) : SafeLogger( logger, ~QString("TimestampEditor %1: ").arg( index ) ), m_parent( parent ), m_index( index ), m_currentStamp( 0 ), m_block( false ) {
- QWidget* w = new QWidget( parent->m_widgets.timestampsGroup );
- m_widgets.setupUi( w );
- connect( m_widgets.stamp, SIGNAL( valueChanged(int) ), this, SLOT( stampChanged() ) );
- connect( m_widgets.date, SIGNAL( dateTimeChanged( const QDateTime& ) ), this, SLOT( dateChanged( const QDateTime& ) ) );
- connect( m_widgets.tail, SIGNAL( clicked( bool ) ), this, SLOT( tail() ) );
- connect( m_widgets.none, SIGNAL( clicked( bool ) ), this, SLOT( none() ) );
- connect( m_widgets.enableAll, SIGNAL( clicked( bool ) ), this, SLOT( enableAll() ) );
- connect( m_widgets.enableBox, SIGNAL( toggled( bool ) ), this, SLOT( enableChanged( bool ) ) );
- fillWidgets();
- m_parent->m_layout->addWidget( w );
-}
-
-ReplacementPointer TimestampEditor::replacement() {
- return m_parent->text()->firstUnapplied( m_index );
-}
-
-Timestamp TimestampEditor::stamp() {
- return m_parent->text()->state()[m_index] + 1;
-}
-
-bool TimestampEditor::trySeekTo( Timestamp s ) {
- VectorTimestamp state = m_parent->text()->state();
- state.setStamp( m_index, s ); state.setPrimaryIndex( m_index );
- try {
- return m_parent->text()->changeState( state );
- } catch( const DynamicTextError& err ) {
- m_parent->log( "TimestampEditor::trySeekTo( " + ~toText( s ) + " ) error: " + ~err.what(), Error );
- return false;
- }
-}
-
-void TimestampEditor::fillWidgets() {
- QDynamicTextPointer t = m_parent->text();
-
- ReplacementPointer p = replacement();
-
- {
- Block b( m_block );
- m_widgets.stamp->setValue( stamp() );
- }
-
- if( p ) {
- {
- Block b( m_block );
- m_widgets.enableBox->setChecked( p->enabled() );
- }
- m_widgets.replacementText->setText( ~toText( p->replacement() ) );
- m_widgets.tail->setEnabled( true );
- } else {
- m_widgets.replacementText->setText( "" );
- m_widgets.tail->setEnabled( false );
- }
-
- m_widgets.stampCount->setText( QString("(%1)").arg( t->highestStamp( m_index ) ) );
- m_currentStamp = stamp();
-
- if( m_currentStamp == 1 ) {
- m_widgets.none->setEnabled( false );
- } else {
- m_widgets.none->setEnabled( true );
- }
-
- uint disabledCount = 0;
- ///Now count all disabled replacements lower than the current together
- ReplacementPointer p2 = t->first( m_index );
- while( p2 != p && p2 != 0 ) {
- if( !p2->enabled() ) disabledCount++;
-
- p2 = p2->next();
- }
-
- m_widgets.enableAll->setText( i18n( "Enable Disabled (%1)" , disabledCount ) );
- if( disabledCount == 0 )
- m_widgets.enableAll->hide();
- else
- m_widgets.enableAll->show();
-}
-
-void TimestampEditor::update() {
- if( m_currentStamp != stamp() ) fillWidgets();
-}
-
-void TimestampEditor::tail() {
- QDynamicTextPointer t = m_parent->text();
- ReplacementPointer p = t->last( m_index );
- if( p ) {
- if( !trySeekTo( p->primaryStamp() ) )
- m_parent->log( "could not seek to current state", Error );
- }
-
- fillWidgets();
-}
-
-void TimestampEditor::none() {
- QDynamicTextPointer t = m_parent->text();
- if( !trySeekTo( t->initialState()[m_index] ) )
- m_parent->log( "could not seek to initial state", Error );
-
- fillWidgets();
-}
-
-void TimestampEditor::enableAll() {
- QDynamicTextPointer t = m_parent->text();
-
- VectorTimestamp cur = t->state();
-
- ReplacementPointer p = replacement();
-
- ReplacementPointer p2 = t->first( m_index );
- if( !p2 ) {
- m_parent->log( "enableAll: error", Error );
- return;
- }
-
- ///Find the lowest disabled stamp
- Timestamp lowest = stamp();
-
- {
- ReplacementPointer cur = t->lastApplied( m_index );
- while( cur != 0 ) {
- if( lowest > cur->primaryStamp() ) lowest = cur->primaryStamp();
- cur = cur->prev();
- }
- }
-
- if( lowest == stamp() ) return;
-
- if( !trySeekTo( lowest - 1 ) ) {
- m_parent->log( QString( "enableAll: could not seek to bottom-state %1").arg( lowest-1 ), Error );
- fillWidgets();
- return;
- }
-
- while( p2 != p && p2 != 0 ) {
- if( !p2->enabled() ) p2->setEnabled( true );
-
- p2 = p2->next();
- }
-
- if( !trySeekTo( cur[m_index] ) ) {
- m_parent->log( "enableAll: seek back failed", Error );
- }
-
- fillWidgets();
-}
-
-void TimestampEditor::stampChanged() {
- if( m_block ) return;
- Timestamp t = m_widgets.stamp->value();
- if( t != 0 ) t-=1;
-
- Timestamp maxStamp = m_parent->text()->highestStamp( m_index );
- if( t > maxStamp ) t = maxStamp;
-
- if( !trySeekTo( t ) )
- m_parent->log( "TimestampEditor::TimestampEditor::stampChanged(): trySeekTo failed", Error );
-
- fillWidgets();
-}
-
-void TimestampEditor::dateChanged( const QDateTime& ) {
-}
-
-void TimestampEditor::enableChanged( bool enabled ) {
- ReplacementPointer r = replacement();
- try {
- ReplacementPointer firstUnapplied = m_parent->text()->firstUnapplied( m_index );
- if( r && firstUnapplied && (*firstUnapplied) <= (*r) ) {
- r->setEnabled( enabled );
- }
- } catch( const DynamicTextError& err ) {
- m_parent->log( "TimestampEditor::enableChanged(..): serious corruption-error: " + ~err.what(), Error );
- }
-
- fillWidgets();
-}
-
-
-VectorTimestampEditor::VectorTimestampEditor( Teamwork::LoggerPointer logger, QObject* parent, bool embed, QDynamicTextPointer text , bool editable ) : QObject( parent ), SafeLogger( logger, "VectorTimestampEditor: " ), m_text( text ), m_editable( editable ), m_embed( embed ), m_layout( 0 ), m_dialog( 0 ) {
- QWidget* widget;
- if( embed && qobject_cast<QWidget*>( parent ) )
- {
- widget = qobject_cast<QWidget*>( parent );
- if( !widget ) {
- err() << "parent is no QWidget";
- deleteLater();
- return;
- }
- } else {
- m_dialog = new KDialog;
- m_dialog->setButtons( KDialog::Close );
- m_dialog->setAttribute( Qt::WA_DeleteOnClose, true );
- widget = m_dialog->mainWidget();
- connect( m_dialog, SIGNAL( closeClicked() ), this, SLOT( finish() ) );
- }
- m_widgets.setupUi( widget );
- m_layout = new QVBoxLayout( m_widgets.timestampsGroup );
- m_widgets.timestampsGroup->setLayout( m_layout );
- widget->show();
-
- m_logModel = new QStandardItemModel( m_widgets.log );
- m_widgets.log->setModel( m_logModel );
- m_logModel->insertColumn( 0 );
- m_logModel->insertRow( 0 );
- m_logModel->setData( m_logModel->index( 0, 0 ), "welcome", Qt::DisplayRole );
-
- connect( m_widgets.toTailTimestamp, SIGNAL( clicked( bool ) ), this, SLOT( toTailTimestamp() ) );
- connect( m_widgets.clearLog, SIGNAL( clicked( bool ) ), this, SLOT( clearLog() ) );
- connect( text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( textChanged() ) );
- connect( text.data(), SIGNAL( inserted( const ReplacementPointer&, QDynamicText& ) ), this, SLOT( textChanged() ) );
- connect( m_text, SIGNAL( destroyed( QObject* ) ), this, SLOT( textDestroyed() ) );
- connect( widget, SIGNAL( destroyed( QObject* ) ), this, SLOT( finish() ) );
-
- fillWidgets();
-}
-
-VectorTimestampEditor::~VectorTimestampEditor() {
-}
-
-void VectorTimestampEditor::fillWidgets() {
- uint cnt = m_timestamps.count();
- uint sz = m_text->state().size();
- if( cnt < sz ) { ///Add missing widgets
- for( uint a = 0; a < sz - cnt; a++ ) {
- m_timestamps << new TimestampEditor( new VectorTimestampEditorLogger( this ), this, a+cnt );
- }
- }
-
- for( QList< TimestampEditorPointer >::iterator it = m_timestamps.begin(); it != m_timestamps.end(); ++it ) {
- (*it)->update();
- }
-
- VectorTimestamp state = m_text->state();
- VectorTimestamp tailState = m_text->tailState();
-
- QString txt = QString( "Current State: %1 Tail-State: %2" ).arg( ~toText( state ) ).arg( ~toText( tailState ) );
- m_widgets.stateInfo->setText( txt );
-
- if( state == tailState ) {
- m_widgets.toTailTimestamp->setEnabled( false );
- } else {
- m_widgets.toTailTimestamp->setEnabled( true );
- }
-}
-
-void VectorTimestampEditor::log( const QString& str, LogLevel level ) {
- m_logModel->insertRow( 0 );
- QModelIndex i = m_logModel->index( 0, 0 );
- if( i.isValid() ) {
- m_logModel->setData( i, str, Qt::DisplayRole );
- m_logModel->setData( i, iconFromLevel( level ), Qt::DecorationRole );
- }
-}
-
-void VectorTimestampEditor::textDestroyed() {
- m_text = 0;
- finish();
-}
-
-void VectorTimestampEditor::textChanged() {
- fillWidgets();
-}
-
-QDynamicTextPointer VectorTimestampEditor::text() {
- return m_text;
-}
-
-void VectorTimestampEditor::toTailTimestamp() {
- try {
- m_text->changeState();
- } catch( const DynamicTextError& error ) {
- log( "error in toTailTimestamp: " + ~error.what(), Error );
- }
-}
-
-void VectorTimestampEditor::clearLog() {
- m_logModel->clear();
- m_logModel->insertColumn( 0 );
-}
-
-void VectorTimestampEditor::finish() {
- if( m_text ) m_text->changeState();
- if( m_dialog ) m_dialog->deleteLater();
- deleteLater();
-}
-
-
-
-#include "vectortimestampeditor.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.h (nonexistent)
@@ -1,420 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef PATCHMESSAGE
-#define PATCHMESSAGE
-
-#include <list>
-#include <string>
-#include <vector>
-#include <QObject>
-#include <QDataStream>
-#include <QByteArray>
-#include <QMetaType>
-#include <QStandardItemModel>
-#include <kurl.h>
-#include <ksharedptr.h>
-
-#include "lib/network/serialization.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/easymessage.h"
-
-#include "kdevteamwork_messages.h"
-#include "utils.h"
-#include "nvp.h"
-
-#include <boost/serialization/split_member.hpp>
-
-namespace KIO {
- class Job;
-}
-class KMimeType;
-class KJob;
-
-QStringList splitArgs( const QString& str );
-
-enum PatchAccessRights {
- None,
- Public,
- ConnectedOnly,
- Private,
- Ask ///This means that the patch is publically visible, but on request, the owner is asked whether it really should be sent.
-};
-
-class LocalPatchSource : public SafeShared {
-
- ///This class should be used for identification instead of just the name, because the type of comparison might change in future
- public:
- class Identity {
- private:
- string name_;
- public:
- Identity( const LocalPatchSource& src ) : name_(src.name) {
- }
-
- template<class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & name_;
- }
-
- Identity() {
- }
-
- bool operator == ( const Identity& rhs ) const {
- return name_ == rhs.name_;
- }
-
- string desc() const {
- return name_;
- }
- };
-
- enum State {
- Applied,
- NotApplied,
- Unknown
- };
-
- string stateAsString() {
- switch( state ) {
- case Applied:
- return "Applied";
- case NotApplied:
- return "NotApplied";
- default:
- return "Unknown";
- };
- }
-
- Identity identity() {
- return Identity( *this );
- }
- string name;
- string filename;
- string command;
- string type; ///This is the mime-type that was chosen for this item
- string applyCommand;
- string unApplyCommand;
- string dependencies;
- string description;
- string author;
- State state;
-
- UserIdentity userIdentity;
- PatchAccessRights access;
-
- LocalPatchSource() : state( Unknown ), access( Private ) {
- }
-
- void setFileName( const string& str ) {
- filename = str;
- command = "";
- }
-
-
- ///Tries to determine the patch-depth(by searching for -pX parameters in the apply-command. Defaults to zero.
- uint patchDepth() const;
-
- ///Tries to determine the tool to be used for applying the patch. Defaults to "patch"
- string patchTool( bool reverse = false ) const;
-
- ///Tries to determine the params for applying the patch. If none are given, uses reasonable default-parameters. If reverse is true, the unapply-parameters are given.
- string patchParams( bool reverse = false ) const;
-
- template<class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- KUrl u( ~filename );
- filename = ~u.prettyUrl(); ///If there is a password, leave it out
-
- arch & NVP( filename );
- arch & NVP( command );
- arch & NVP( name );
- arch & NVP( type );
- arch & NVP( applyCommand );
- arch & NVP( unApplyCommand );
- arch & NVP( dependencies );
- arch & NVP( description );
-// arch & NVP( mimetype );
- arch & NVP( access );
- arch & NVP( state );
- arch & NVP( author );
- arch & NVP( userIdentity );
- }
-
- static string accessToString( PatchAccessRights access ) {
- switch( access ) {
- case None:
- return "none";
- case Public:
- return "public";
- case ConnectedOnly:
- return "connected only";
- case Private:
- return "private";
- case Ask:
- return "request";
- };
- return "unknown";
- }
-
- static PatchAccessRights accessFromString( const string& txt ) {
- if( txt == "public")
- return Public;
-
- if( txt == "connected only" )
- return ConnectedOnly;
-
- if( txt == "request" )
- return Ask;
-
- if( txt == "private" )
- return Private;
-
- return None;
- }
-
- string accessAsString() {
- return accessToString( access );
- }
-
- bool operator == ( const LocalPatchSource& rhs ) const {
- return name == rhs.name;
- }
-
- QIcon getIcon( IconCache& icons );
-
- void setUser( const UserPointer& u ) {
- user_ = u;
- }
-
- const UserPointer& user() {
- return user_;
- }
-
- /*void setMimeType( KSharedPtr<KMimeType> mimeType );
-
- KSharedPtr<KMimeType> getMimeType();*/
-
- private:
- UserPointer user_;
-};
-
-//BOOST_CLASS_EXPORT( LocalPatchSource )
-
-typedef SafeSharedPtr<LocalPatchSource> LocalPatchSourcePointer;
-
-
-///This message is just a base-class for all messages that should be forwarded to the PatchesListManager
-class PatchesManagerMessage : public SystemMessage
-{
- DECLARE_MESSAGE( PatchesManagerMessage, SystemMessage, 6 );
-
- enum Message {
- None = 50,
- GetPatchesList
- };
-
- PatchesManagerMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) {
- }
-
- explicit PatchesManagerMessage( const Teamwork::MessageConstructionInfo& info, Message msg = None ) : Precursor( info(this), (SystemMessage::Message)msg, "" ) {
- }
-
- Message message() {
- return (Message) SystemMessage::message();
- }
-};
-
-typedef SafeSharedPtr<PatchesManagerMessage> PatchesManagerMessagePointer;
-
-
-class PatchesListMessage : public PatchesManagerMessage
-{
- DECLARE_MESSAGE( PatchesListMessage, PatchesManagerMessage, 1 );
- private:
-
- template<class Arch>
- void serial( Arch& arch ) {
- arch & patches;
- }
-
- public:
- list<LocalPatchSource> patches;
-
- PatchesListMessage( InArchive& arch, const Teamwork::MessageInfo& info );
-
- PatchesListMessage( const Teamwork::MessageConstructionInfo& info, list<LocalPatchSourcePointer>& _patches ) : Precursor( info(this), None ) {
- for( list<LocalPatchSourcePointer>::iterator it = _patches.begin(); it != _patches.end(); ++it ) {
- LocalPatchSourcePointer::Locked l = *it;
- if( l ) {
- patches.push_back( *l );
- } else {
- ///could not lock the patch-source
- }
- }
- }
-
- virtual void serialize( OutArchive& arch );
-};
-
-class PatchRequestMessage;
-
-class PatchRequestData : public AbstractGUIMessage {
- public:
- enum Status {
- Waiting,
- Denied,
- Accepted,
- Failed,
- Unknown
- };
-
- enum RequestType {
- View,
- Download,
- Apply
- };
-
- explicit PatchRequestData( const LocalPatchSourcePointer& id = LocalPatchSourcePointer(), KDevTeamwork* tw = 0, RequestType req = View );
- virtual ~PatchRequestData();
-
- template<class Arch>
- void serialize( Arch& arch, const uint /*version*/ ) {
- arch & ident_;
- arch & requestType_;
- }
-
- LocalPatchSource::Identity patchIdentity() {
- return ident_;
- }
-
- void setStatus( Status st ) {
- stat = st;
- }
-
- string patchDesc() const {
- return ident_.desc();
- }
-
- RequestType requestType() const {
- return requestType_;
- }
-
- ///This returns the LocalPatchSourcePointer which was used to request the patch(only valid on sender-side, to cache the apply-commands etc. for security)
- LocalPatchSourcePointer request() const {
- return request_;
- }
-
- virtual void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork );
-
- virtual QIcon messageIcon() const;
-
- virtual QString messageText() const;
-
- PatchRequestMessage* selfMessage() ;
- const PatchRequestMessage* selfMessage() const;
-
- private:
- LocalPatchSource::Identity ident_;
- LocalPatchSourcePointer request_;
- RequestType requestType_;
- protected:
- Status stat;
- SafeTeamworkEmitterPointer emitter;
-};
-
-EASY_DECLARE_MESSAGE_BEGIN( PatchRequestMessage, PatchesManagerMessage, 11, PatchRequestData, 3 )
- virtual bool needReply () const { return true; }
- virtual ReplyResult gotReply( const MessagePointer& /*p*/ );
-END();
-
-class PatchData;
-class K3Process;
-
-///This needs a helper, because the object must be created in the same thread.
-class PatchDataReceiver : public QObject {
- Q_OBJECT
- PatchData* data;
- public:
- PatchDataReceiver( PatchData* d );
- public slots:
- void receivedStdout(K3Process *proc, char *buffer, int buflen);
- void transferData( KIO::Job*, const QByteArray& );
- void transferFinished( KJob *job );
-// void transferSpeed( KIO::Job *job, unsigned long speed );
-};
-
-
-class PatchData {
- public:
- explicit PatchData( const LocalPatchSourcePointer& p = LocalPatchSourcePointer(), LoggerPointer logg = LoggerPointer() );
-
- //template<class Arch>
- void load( InArchive& arch, const uint /*version*/ );
-
- //template<class Arch>
- void save( OutArchive& arch, const uint version ) const {
- const_cast<PatchData*>(this)->saveInternal( arch, version );
- }
-
- void receivedStdout(K3Process *proc, char *buffer, int buflen);
-
- ///This is only valid if the message was not created locally.
- const QByteArray& data();
-
- bool isBinary();
-
- ///Here the signals from TransferJob arrive.
- void transferData( KIO::Job*, const QByteArray& );
-
- void transferFinished();
-
- void transferCanceled();
-
- LocalPatchSourcePointer patch();
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
- private:
-
- //template<class Arch>
- void saveInternal( OutArchive& arch, const uint /*version*/ );
-
- LocalPatchSourcePointer m_patch;
- LoggerPointer logger;
- OutArchive* currentArchive;
- bool errored;
- bool deserialized, finished, isBinary_;
- QByteArray m_data; ///When this has no content, the patch should be computed from the information in LocalPatchSource while serializing.
- KUrl projectDir;
-
-
- enum EntryType {
- End,
- BinaryHeader,
- TextHeader,
- Text,
- Vector,
- None
- };
-
- LoggerPrinter log( Logger::Level level = Logger::Debug ) {
- return LoggerPrinter( logger, level ) << "PatchMessage: ";
- }
-};
-
-EASY_DECLARE_MESSAGE( PatchMessage, PatchesManagerMessage, 6, PatchData, 2 );
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.h (nonexistent)
@@ -1,70 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SAFELOGGER_H
-#define SAFELOGGER_H
-
-#include <string>
-#include <vector>
-
-#include "lib/network/safesharedptr.h"
-#include "lib/network/logger.h"
-
-class LogSuffix;
-
-/** This class can be used for very comfortable and safe logging: Just derive your own class from it initialize
- * it with the logger-pointer, and give a log-prefix or override logPrefix(..) for flexible prefixing.
- *
- * Then you can use 'out(...) << "your text"' or 'err() << "your text"' to log.
- * */
-class SafeLogger {
- public:
- friend class LogSuffix;
-
- explicit SafeLogger( Teamwork::LoggerPointer logger, std::string logPrefix = "" );
-
- virtual ~SafeLogger();
-
- ///Returns a temporary stream-object(see documentation of Teamwork::LoggerPrinter) for the given log-level.
- Teamwork::LoggerPrinter out( Teamwork::Logger::Level level = Teamwork::Logger::Info );
-
- ///Returns a temporary stream-object(see documentation of Teamwork::LoggerPrinter) for error-messages.
- Teamwork::LoggerPrinter err();
-
- ///Returns the used logger
- Teamwork::LoggerPointer logger() const;
-
- protected:
- virtual std::string logPrefix();
- private:
- Teamwork::LoggerPointer m_logger;
- std::string m_logPrefix;
- std::vector<const char*> m_logSuffix;
-};
-
-/**This class can be used to temporarily extend the log-prefix(it can be created locally, and the prefix-suffix is removed as lifetime ends ends)
- * Warning: For performance-reasons the given text is not copied, so it must live at least as long as this object.
- * */
-class LogSuffix {
- public:
- LogSuffix( const char* txt, SafeLogger* logger );
- ~LogSuffix();
- private:
- LogSuffix& operator = ( const LogSuffix& /*rhs */);
- LogSuffix( const LogSuffix& /*rhs */);
- SafeLogger* m_logger;
-};
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h (nonexistent)
@@ -1,96 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KDEVTEAMWORK_HELPERS
-#define KDEVTEAMWORK_HELPERS
-
-#include"teamworkfwd.h"
-#include <QString>
-#include <QIcon>
-#include <QMap>
-#include <QPair>
-#include <QObject>
-#include <kicontheme.h>
-#include "lib/network/logger.h"
-
-///This file contains a few classes that I currently don't know where else to put
-
-using namespace Teamwork;
-
-///Since deleting the client by a reference-counter in some meta-object leads to crashes, this is used to keep the client alive longer and delete it as last.
-class LaterDeleter : public QObject {
- Q_OBJECT
- public:
- LaterDeleter( const KDevTeamworkClientPointer& c );
- ~LaterDeleter();
- KDevTeamworkClientPointer m_c;
-};
-
-class SafeTeamworkEmitter : public QObject, public Shared {
- Q_OBJECT
- public:
- SafeTeamworkEmitter( KDevTeamwork* tw );
-
- void updateMessageInfo( const MessagePointer& msg );
- signals:
- void signalUpdateMessageInfo( MessagePointer );
-};
-
-typedef SharedPtr<SafeTeamworkEmitter> SafeTeamworkEmitterPointer;
-
-
-class IconCache {
- typedef QMap<QPair<QString, KIconLoader::Group>, QIcon> IconMap;
- QMap<QString, QString> maps_;
- IconMap m_icons;
- static IconCache* m_instance;
- public:
- IconCache();
-
- QIcon operator () ( const QString& name, KIconLoader::Group grp = KIconLoader::Small );
-
- static QIcon getIconStatic( QString name, KIconLoader::Group grp = KIconLoader::Small );
-
- QIcon getIcon( QString name, KIconLoader::Group grp = KIconLoader::Small );
-
- static IconCache* instance();
-};
-
-
-class KDevTeamworkLogger : public QObject, public Teamwork::Logger {
- Q_OBJECT
- KDevTeamwork* m_teamwork;
- public:
- ///This can be overridden for custom logging
- KDevTeamworkLogger( KDevTeamwork* tw );
-
- virtual void log( const std::string& str , Level lv );
-
- void invalidate() {
- m_teamwork = 0;
- }
-
- ///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
- virtual void safeErrorLog( const std::string& str, Level lv );
-};
-
-/** This is a helper-class for easy logging
- * Easiest way of using it: use it as a base-class in a class that should do logging,
- * initialize it with the name of the class and the correct logger-object, and than start
- * logging by streaming to out(..) or err(). ( Example: err() << "could not open file"; )
- *
- * */
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_helpers.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.h (nonexistent)
@@ -1,102 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef INDOCUMENTREFERENCE_H
-#define INDOCUMENTREFERENCE_H
-
-#include <QString>
-#include <string>
-#include "lib/network/sharedptr.h"
-#include "sumsearch.h"
-
-class InDocumentReference {
- int m_line;
- int m_col;
- string m_document;
- typedef SumReference<10> WeakReference;
- WeakReference m_position;
- public:
-
- ///This can be used to speed up the search if multiple positions should be found within one text(then this object should be created outside and reached to findInText.
- class TextSearchInstance {
- public:
- TextSearchInstance( const QString& txt );
- TextSearchInstance( const TextSearchInstance& rhs );
- TextSearchInstance();
- ~TextSearchInstance();
- operator bool() const;
- QString text() const;
- TextSearchInstance& operator = ( const TextSearchInstance& rhs );
- private:
- friend class InDocumentReference;
- class Private;
- SharedPtr<Private> m_data;
- };
-
- static QString createReference( const QString& file, int startLine, int startCol, int endLine, int endCol );
- static void parseReference( const QString& ref, QString& file, int& startLine, int& startCol, int& endLine, int& endCol );
-
- ///This creates a reference that refers to a position, but not intelligently.
- explicit InDocumentReference( bool start = true, const QString& ref = "" );
-
- InDocumentReference( const QString& document, int line, int col = 0, const QString& text = "" );
-
- void useText( const QString& text );
-
- template <class ArchType>
- void serialize( ArchType& arch, uint /*version*/ ) {
- arch & m_line & m_col & m_document & m_position;
- }
-
- QString document() const;
-
- ///Finds the reference-position dynamically within the given text. If the search fails, puts -1 -1.
- void findInText( const TextSearchInstance& text, int& line, int& col ) const;
-
- bool isValid() const;
-
- bool isDynamic() const;
-
- operator bool() const;
-
- ///findInText(..) should be preferred, because it can find the correct position even if the text changed.
- int line() const;
-
- QString asText() const;
-
- int col() const;
-};
-
-class DocumentContextLines {
- int m_lineOffset;
- std::string m_lines;
-
- public:
- DocumentContextLines();
-
- DocumentContextLines( const InDocumentReference& beginRef, const InDocumentReference& endRef, const QString& text, int /*contextSize*/ = 5 );
-
- template <class Arch>
- void serialize( Arch& arch, uint /*version*/ ) {
- arch & m_lineOffset & m_lines;
- }
-
- operator bool() const ;
-
- QString text() const;
-
- int lineOffset() const;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/CMakeLists.txt (nonexistent)
@@ -1,108 +0,0 @@
-project(teamwork)
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${teamwork_SOURCE_DIR}/cmake/)
-
-
-find_package(KDE4 REQUIRED)
-include (KDE4Defaults)
-find_package(KDevPlatform REQUIRED)
-
-find_package(Threads REQUIRED)
-macro_optional_find_package(Commoncpp)
-
-macro_log_feature(COMMONCPP_FOUND "CommonCpp" "KDevelop4 extra plugin teamwork" "http://TODO" FALSE "" "")
-
-if (COMMONCPP_FOUND)
-find_package(Boost 1.34.0 COMPONENTS iostreams serialization REQUIRED)
-#if(COMMONCPP2_FOUND AND Boost_FOUND)
-# macro_optional_add_subdirectory(teamwork)
-# endif(COMMONCPP2_FOUND AND Boost_FOUND)
-# macro_log_feature( COMMONCPP2_FOUND "Common C++2" "Support for Teamwork plugin integration" "http://ftp.gnu.org/pub/gnu/commoncpp/" FALSE "1.5.9" "The commoncpp2 libraries are needed for the Teamwork plugin" )
-# macro_log_feature( Boost_FOUND "Boost" "Support for Teamwork plugin integration" "http://www.boost.org/" FALSE "1.34.0" "The iostreams and serialization components of the boost C++ libraries are needed for the Teamwork plugin" )
-
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9523 )
-
-include_directories (${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${KDE4_INCLUDES} )
-
-include_directories(
- ${COMMONCPP2_INCLUDE_DIRS}
- ${Boost_INCLUDE_DIRS}
- ${KDEVPLATFORM_INCLUDE_DIR}
- )
-
-add_subdirectory(lib)
-
-########### next target ###############
-
-set(kdevteamwork_PART_SRCS
- kdevteamwork.cpp
- kdevteamworkplugin.cpp
- kdevteamwork_client.cpp
- kdevteamwork_messages.cpp
- kdevteamwork_user.cpp
- patchesmanager.cpp
- utils.cpp
- collaborationmanager.cpp
- patchmessage.cpp
- messagemanager.cpp
- conversationmanager.cpp
- guimessagehistory.cpp
- messagehistorymanager.cpp
- kdevteamwork_messageshower.cpp
- filecollaborationmessages.cpp
- filecollaborationmanager.cpp
- filecollaborationsession.cpp
- filecollaboration.cpp
- kdevutils.cpp
- documentwrapper.cpp
- indocumentmessage.cpp
- indocumentreference.cpp
- kdevteamwork_helpers.cpp
- helpers.cpp
- messageusertab.cpp
- verify.cpp
- filesynchronizemessage.cpp
- vectortimestampeditor.cpp
- qdynamictext.cpp
- teamworkfoldermanager.cpp
- editpatch.cpp
- messagesendmanager.cpp
- safelogger.cpp
- safesignaller.cpp
-)
-
-set (
- kdevteamwork_UI
- kdevteamwork_editpatch.ui
- kdevteamwork_managepatches.ui
- kdevteamwork_filecollaborationsession.ui
- kdevteamwork_indocumentcontextlines.ui
- kdevteamwork_messagehistory.ui
- kdevteamwork_indocumentmessagebuttons.ui
- kdevteamwork_textmessage.ui
- kdevteamwork_indocumentmessagestate.ui
- kdevteamwork_timestampwidget.ui
- kdevteamwork_interface.ui
- kdevteamwork_userinfo.ui
- kdevteamwork_internalmessage.ui
- kdevteamwork_vectortimestampwidget.ui
- kdevteamwork_list.ui
-)
-
-
-#ADD_DEFINITIONS(${KDE4_ENABLE_EXCEPTIONS} -Wall -fno-inline)
-ADD_DEFINITIONS(${KDE4_ENABLE_EXCEPTIONS} -Wall)
-
-kde4_add_ui_files(kdevteamwork_PART_SRCS ${kdevteamwork_UI} )
-kde4_add_plugin(kdevteamwork ${kdevteamwork_PART_SRCS})
-
-target_link_libraries(kdevteamwork ${KDE4_KDEUI_LIBS} ${KDE4_KHTML_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} kdevteamwork_network kdevteamwork_dynamictext kdevteamwork_diff2 ${KDE4_KDE3SUPPORT_LIBS} ${KDE4_KTEXTEDITOR_LIBS})
-
-install(TARGETS kdevteamwork DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-########### install files ###############
-
-install( FILES kdevteamwork.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES kdevteamwork.rc DESTINATION ${DATA_INSTALL_DIR}/kdevteamwork )
-
-endif()
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.h (nonexistent)
@@ -1,95 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGEMANAGER_H
-#define MESSAGEMANAGER_H
-#include <list>
-#include "kdevteamwork_messages.h"
-#include "utils.h"
-#include "indocumentmessage.h"
-#include "autoconstructpointer.h"
-
-class QDomElement;
-class KDevTeamwork;
-class LocalPatchSource;
-class KDevTeamworkTextMessage;
-class MessageHistory;
-class MessageHistoryManager;
-class QAction;
-//class LocalPatchSource::Identity;
-
-class KDevTeamworkUser;
-
-typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
-
-class ConversationManager;
-
-
-BIND_LIST_2( MessageManagerMessages, KDevTeamworkTextMessage, InDocumentMessage )
-
-/** This class manages the KDevTeamworkTextMessage-based messages
- */
-
-class MessageManager : public QObject {
- Q_OBJECT
- public:
- MessageManager( KDevTeamwork* tw );
- ~MessageManager();
-
- void restorePartialProjectSession( const QDomElement* el );
-
- void savePartialProjectSession( QDomElement* el );
-
- int receiveMessage( MessageInterface* msg );
- int receiveMessage( KDevTeamworkTextMessage* msg );
- int receiveMessage( InDocumentMessage* msg );
-
- int processMessage( KDevTeamworkTextMessage* msg );
-
- KDevTeamwork* teamwork();
-
- void log( const QString& str, LogLevel level = Info );
-
- MessageHistoryManager& historyManager();
- ConversationManager& conversationManager();
-
- void showMessageHistory( const QList<KDevTeamworkUserPointer>& users = QList<KDevTeamworkUserPointer>(), const QString& context = "" );
-
- void fillMessageMenu( QMenu* menu, MessagePointer msg );
-
- void showMessage( const MessagePointer& msg );
-
- public slots:
- ///This can be used to indicate that information about the message(like icon, text, etc.) has been changed.
- void updateMessage( const MessagePointer& msg );
- void slotShowMessage();
- void init();
-
- signals:
- ///Is emitted whenver a message is reported to have changed.(through updateMessage(..))
- void messageUpdated( const MessagePointer& msg );
-
- private:
- MessageDispatcher<MessageManager, MessageManagerMessages> dispatcher_;
- KDevTeamwork* m_teamwork;
-
- AutoConstructPointer<ConversationManager> m_conversationManager;
- AutoConstructPointer<MessageHistoryManager> m_historyManager;
-
- QAction* m_showMessageAction;
-};
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagemanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.h (nonexistent)
@@ -1,49 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef QDYNAMICTEXT_H
-#define QDYNAMICTEXT_H
-
-#include <QObject>
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/base_object.hpp>
-#include "lib/dynamictext/dynamictext.h"
-
-class QDynamicText : public QObject, public DynamicText {
- Q_OBJECT
- public:
- explicit QDynamicText( const VectorTimestamp& initialState = VectorTimestamp(), const std::string& initialText = std::string() );
-
- QDynamicText( const QDynamicText& rhs );
-
- QDynamicText& operator = ( const QDynamicText& rhs );
-
- template<class Archive>
- void serialize( Archive& arch, const unsigned int ) {
- arch & boost::serialization::base_object<DynamicText>(*this);
- }
-
- signals:
- void stateChanged( QDynamicText& text );
- void inserted( const ReplacementPointer& replacement, QDynamicText& text );
- private:
- virtual void notifyInserted( const ReplacementPointer& rep );
- virtual void notifyStateChanged();
-};
-
-typedef SharedPtr<QDynamicText, BoostSerializationNormal> QDynamicTextPointer;
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp (nonexistent)
@@ -1,1280 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "conversationmanager.h"
-#include "lib/network/serialization.h"
-
-#include <boost/archive/polymorphic_xml_oarchive.hpp>
-#include <boost/archive/polymorphic_xml_iarchive.hpp>
-#include <boost/serialization/list.hpp>
-
-#include <QPalette>
-#include <QColor>
-#include <QPoint>
-#include <QMenu>
-#include <QTimer>
-#include <QStandardItemModel>
-#include <QHeaderView>
-#include <QBrush>
-#include <QMutexLocker>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-#include <ktexteditor/cursor.h>
-#include <ktexteditor/markinterface.h>
-#include <ktexteditor/attribute.h>
-
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-
-#include "lib/network/messageserialization.h"
-
-#include "messagemanager.h"
-#include "kdevteamwork_user.h"
-#include "kdevteamworkplugin.h"
-#include "kdevteamwork_messages.h"
-#include "kdevteamwork.h"
-#include "kdevteamwork_helpers.h"
-#include "teamworkfoldermanager.h"
-
-using namespace KDevelop;
-
-Q_DECLARE_METATYPE( Teamwork::UserPointer )
-
-Q_DECLARE_METATYPE( MessagePointer )
-Q_DECLARE_METATYPE( InDocumentMessagePointer )
-
-CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, int, 0, value.position )
-CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, InDocumentMessagePointer, 0, value.message )
-CROSSMAP_KEY_EXTRACTOR( OrderedDocumentMessage, QString, 0, value.message.lock()->start().document() )
-
-template <class ArchType>
-void InDocumentConversation::load( ArchType& arch, unsigned int version ) {
- m_messageCount = 0;
- serial( arch, version );
- std::list<Teamwork::UniqueMessageId> ids;
- arch & ids;
- log( QString( "loading %1 ids" ).arg( ids.size() ), Debug );
- m_messages.clear();
- for ( std::list<Teamwork::UniqueMessageId>::iterator it = ids.begin(); it != ids.end(); ++it ) {
- InDocumentMessagePointer msg = ConversationManager::instance() ->manager() ->historyManager().getMessageFromId( *it, ConversationManager::instance() ->manager() ->teamwork() ->client() );
- if ( msg )
- pushMessage( msg );
- else
- log( QString( "Could not get the message with id %1 from the history" ).arg( *it ), Warning );
- }
-}
-
-KTextEditor::Cursor InDocumentConversation::currentDocCursor() const {
- if( !m_currentConnectedDocument || !m_currentConnectedDocument->activeView() ) return KTextEditor::Cursor();
- return m_currentConnectedDocument->activeView()->cursorPosition();
-}
-
-void InDocumentConversation::pushMessage( const InDocumentMessagePointer& msg ) {
- m_messages.insert( OrderedDocumentMessage( m_messageCount++, msg ) );
-}
-
-template <class ArchType>
-void InDocumentConversation::save( ArchType& arch, unsigned int version ) const {
- const_cast<InDocumentConversation*>( this ) ->serial( arch, version );
-
- std::list<Teamwork::UniqueMessageId> ids;
-
- ;
- for ( MessageSet::Iterator it = m_messages.orderedValues<int>(); it; ++it ) {
- InDocumentMessagePointer::Locked l = it->message;
- if ( l ) {
- ids.push_back( l->info().uniqueId() );
- } else {
- log( "could not lock InDocumentMessage for getting id", Error );
- }
- }
-
- log( QString( "saving %1 ids" ).arg( ids.size() ), Debug );
- arch & ids;
-}
-
-template void InDocumentConversation::load( InArchive& arch, unsigned int version )
-;
-template void InDocumentConversation::save( OutArchive& arch, unsigned int version )
-const;
-
-///This helper-class helps tracking connected user-signals and cleanly disconnecting them once they are not needed anymore
-struct TemporaryConversationConnector : public Shared {
- KDevTeamworkUserPointer user;
- InDocumentConversation* target;
- TemporaryConversationConnector() : target( 0 ) {}
- TemporaryConversationConnector( const KDevTeamworkUserPointer& u, InDocumentConversation* t ) : user( u ), target( t ) {
- if ( user && target ) {
- KDevTeamworkUserPointer::Locked l = user;
- if ( l ) {
- QObject::connect( l, SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), target, SLOT( userStateChanged( KDevTeamworkUserPointer ) ), Qt::QueuedConnection );
- }
- }
- }
- ~TemporaryConversationConnector() {
- cleanup();
- }
- private:
-
- void cleanup() {
- if ( user && target ) {
- KDevTeamworkUserPointer::Locked l = user;
- if ( l ) {
- QObject::disconnect( l, SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), target, SLOT( userStateChanged( KDevTeamworkUserPointer ) ) );
- }
- }
- user = 0;
- target = 0;
- }
-
- void invalidate() {
- user = 0;
- target = 0;
- }
-
- TemporaryConversationConnector ( const TemporaryConversationConnector& rhs ) : Shared(rhs) {}
-}
-;
-
-using namespace std;
-using namespace Teamwork;
-
-ConversationManager* ConversationManager::m_instance;
-
-ConversationManager::ConversationManager( MessageManager* mng ) {
- m_manager = mng;
- m_instance = this;
- IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
- if ( docControl ) {
- connect( docControl, SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- connect( docControl, SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- }
- connect( mng->teamwork(), SIGNAL( init() ), this, SLOT( load() ) );
- connect( mng->teamwork(), SIGNAL( deInit() ), this, SLOT( save() ) );
-}
-
-ConversationManager::~ConversationManager() {
-}
-
-InDocumentConversationPointer ConversationManager::findConversation( const QString& context ) {
- ConversationSet::iterator it = m_conversations.find( ~context );
-
- if ( it != m_conversations.end() ) {
- return ( *it ).second;
- } else {
- return 0;
- }
-}
-
-InDocumentConversationPointer ConversationManager::getConversation( InDocumentMessage* msg ) {
- SharedPtr<InDocumentConversation> ret = findConversation( msg->context() );
- if ( ret ) {
- return ret;
- } else {
- m_conversations[ ~msg->context() ] = new InDocumentConversation( msg );
- return m_conversations[ ~msg->context() ];
- }
-}
-
-int ConversationManager::processMessage( InDocumentMessage* msg ) {
- getConversation( msg ) ->addMessage( msg );
-
- return 0;
-}
-
-void ConversationManager::save() {
- try {
- KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "conversation.database" );
- ///@todo make this work with remote Urls
- if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
-
- std::ofstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::out | ios_base::binary );
- if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for writing";
- boost::archive::polymorphic_xml_oarchive arch( file );
- arch << NVP(m_conversations);
- } catch ( std::exception & exc ) {
- log( QString("save(): exception occurred while serialization: %1").arg( exc.what() ), Error );
- } catch( const char* str ) {
- log( QString("save(): %1").arg( str ), Error );
- } catch( const QString& str ) {
- log( QString( "save(): %1").arg( str ), Error );
- }
-}
-
-void ConversationManager::load() {
- try {
- KUrl fileName = TeamworkFolderManager::teamworkAbsolute( "conversation.database" );
- ///@todo make this work with remote Urls
- if( !fileName.isLocalFile() ) throw QString( "file is not a local Url: %1" ).arg( fileName.prettyUrl() );
-
- std::ifstream file(fileName.toLocalFile().toLocal8Bit(), ios_base::binary );
- if( !file.good() ) throw "could not open " + fileName.prettyUrl() + " for reading";
- boost::archive::polymorphic_xml_iarchive arch( file );
- arch >> NVP(m_conversations);
- } catch ( std::exception & exc ) {
- log( QString("load(): exception occurred while serialization: %1").arg( exc.what() ), Error );
- } catch( const char* str ) {
- log( QString("load(): %1").arg( str ), Error );
- } catch( const QString& str ) {
- log( QString( "load(): %1").arg( str ), Error );
- }
-}
-
-void ConversationManager::documentActivated( IDocument* /*document*/ ) {
- //document->
- /*for( ConversationSet::iterator it = m_conversations.begin(); it != m_conversations.end(); ++it ) {
- (*it)->documentActivated( document );
- }*/
-}
-
-void ConversationManager::log( const QString& str, LogLevel level ) {
- m_manager->log( str, level );
-}
-
-ConversationManager* InDocumentConversation::manager() const {
- return ConversationManager::instance();
-}
-
-std::string InDocumentConversation::logPrefix() {
- return "InDocumentConversation(" + ~context() + "): ";
-}
-
-void InDocumentConversation::messageSelected( const MessagePointer& msg ) {
- LogSuffix( "messageSelected: ", this );
- try {
- m_selectNearestMessageTimer->stop();
-
- if( !m_currentConnectedDocument )
- throw "no connected document";
-
- KTextEditor::View* view = m_currentConnectedDocument->activeView();
- if( !view )
- throw "current document has no view";
-
- MessagePointer::Locked l = msg;
- if( !l )
- throw "messageSelected: could not lock message";
-
- KTextEditor::Cursor c, endC;
- c = findPositionInDocument( l.cast<InDocumentMessage>(), &endC );
-
- KTextEditor::SmartInterface* smart = dynamic_cast<KTextEditor::SmartInterface*>( (KTextEditor::Document*)m_currentConnectedDocument );
- if ( smart ) {
- if ( endC.isValid() && c.isValid() ) {
- KTextEditor::Document* d = m_currentConnectedDocument;
- disconnect( d, SIGNAL(destroyed( QObject* )), this, SLOT(rangeDeleted()) );
- connect( d, SIGNAL(destroyed( QObject* )), this, SLOT(rangeDeleted()) );
-
- QMutexLocker lock(smart->smartMutex());
-
- if(m_currentRange)
- delete m_currentRange;
-
- m_currentRange = smart->newSmartRange(d->documentRange(), 0, KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight);
- KTextEditor::SmartRange* highlightRange = smart->newSmartRange( c, endC, m_currentRange );
- KSharedPtr<KTextEditor::Attribute> t( new KTextEditor::Attribute() );
-
- t->setProperty( QTextFormat::BackgroundBrush, QBrush( Qt::yellow ) );
- highlightRange->setAttribute( t );
-
- smart->addHighlightToDocument( /*view, */m_currentRange );//, true );
- }
- } else {
- throw "no smart-interface";
- }
-
- ///Select the message in the widget
- if( m_widget && m_messagesModel ) {
- for( int a = 0; a < m_messagesModel->rowCount(); a++ ) {
- QModelIndex i = m_messagesModel->index( a, 0 );
- if( i.isValid() ) {
- QVariant v = m_messagesModel->data( i, Qt::UserRole );
- if ( v.canConvert<MessagePointer>() ) {
- InDocumentMessagePointer smsg = v.value<MessagePointer>().cast<InDocumentMessage>();
- if( smsg.unsafe() == msg.unsafe() ) {
- m_widgets.messages->selectionModel()->clear();
- m_widgets.messages->selectionModel()->select( i, QItemSelectionModel::Select );
- break;
- }
- }
- }
- }
- }
-
- c = currentDocCursor();
- placeWidget( view, &c, true );
- } catch( const char* str ) {
- err() << str;
- } catch( const QString& str ) {
- err() << str;
- }
-}
-
-void InDocumentConversation::selectMessage( InDocumentMessagePointer msg ) {
- LogSuffix( "selectMessage: ", this );
- try {
- setActive( true );
-
- InDocumentMessagePointer::Locked l = msg;
- if ( !l )
- throw "could not lock message";
-
- if( l->document().isEmpty() ) {
- out( Logger::Warning ) << "the selected message has no text-reference";
- return;
- }
-
- KUrl url = TeamworkFolderManager::workspaceAbsolute( l->document() );
-
- out( Logger::Debug ) << "opening:" << url.toLocalFile();
-
-
- IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
-
- IDocument* doc = docControl->documentForUrl( url );
- if(!doc) doc = docControl->openDocument( url );
- if ( doc ) {
- docControl->activateDocument( doc );
- documentActivated( doc, msg );
-
- KTextEditor::View* view = doc->textDocument() ->activeView();
- if( !view ) {
- out( Logger::Debug ) << "no view for the activated document available";
- QList<KTextEditor::View*> views = doc->textDocument() ->views();
- if( views.isEmpty() ) throw "no views available for document";
- view = dynamic_cast<KTextEditor::View*>( views.front() );
- }
-
- if ( view ) {
- KTextEditor::Cursor endC = KTextEditor::Cursor::invalid();
- KTextEditor::Cursor c = findPositionInDocument( l, l->end().isValid() ? &endC : 0 );
- view->setCursorPosition( c );
- //view->setCursorPosition( KTextEditor::Cursor( c.line() > 10 ? c.line() - 10 : c.line(), c.column() ) );
- if ( !c.isValid() )
- throw "could not find current position, cursor is invalid";
-
- {
- Block b( m_block );
- view->setCursorPosition( c );
- }
-
- messageSelected( msg );
- } else {
- throw "could not get view for " + url.toLocalFile();
- }
- } else {
- throw "could not open document " + url.toLocalFile();
- }
- } catch ( const char * str ) {
- err() << str;
- } catch ( QString str ) {
- err() << str;
- }
-}
-void InDocumentConversation::userInfo() {
- manager() ->manager() ->teamwork() ->showUserInfo( primaryUser() );
-}
-
-void InDocumentConversation::messageContextMenu ( const QPoint &p ) {
- log( "messageContextMenu", Debug );
- QMenu menu( m_widget );
- QModelIndex i = m_widgets.messages->indexAt( p );
- if( !i.isValid() ) {
- log( "messageContextMenu: index is invalid", Error );
- return;
- }
- QVariant v = m_messagesModel->data( i, Qt::UserRole );
- if ( v.canConvert<MessagePointer>() ) {
- InDocumentMessagePointer msg = v.value<MessagePointer>().cast<InDocumentMessage>();
- manager() ->manager() ->fillMessageMenu( &menu, msg );
- menu.exec( p );
- }
-}
-
-InDocumentMessagePointer InDocumentConversation::selectedMessage() {
- if( !m_widget ) return 0;
- QModelIndexList il = m_widgets.messages->selectionModel()->selectedIndexes ();
- if( il.isEmpty() ) return 0;
- return m_messagesModel->data( il.front(), Qt::UserRole ).value<MessagePointer>().cast<InDocumentMessage>();
-}
-
-
-void InDocumentConversation::messageClicked( const QModelIndex& index ) {
- log( "messageClicked", Debug );
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<MessagePointer>() ) {
- InDocumentMessagePointer msg = v.value<MessagePointer>().cast<InDocumentMessage>();
-
- QMetaObject::invokeMethod( this, "selectMessage", Qt::QueuedConnection, Q_ARG( InDocumentMessagePointer, msg ) );
- } else {
- manager() ->log( "cannot convert a list-item to a MessagePointer", Error );
- }
-}
-
-void InDocumentConversation::gotReply( MessagePointer smsg ) {
- MessagePointer::Locked msg = smsg;
- if ( !msg ) {
- addListItem( "failed to send, got no reply" );
- } else {
- if ( msg->info().replyToMessage().unsafe() == ( MessageInterface* ) m_sendingMessage.unsafe() ) {
- SafeSharedPtr<KDevSystemMessage>::Locked sysMsg = msg.cast<KDevSystemMessage>();
- if ( sysMsg ) {
- if ( sysMsg->message() == KDevSystemMessage::ActionSuccessful ) {
- messageSendReady( true );
- SafeSharedPtr<InDocumentMessage>::Locked l = msg->info().replyToMessage().cast<InDocumentMessage>();
- addMessage( l );
- return ;
- } else {
- addListItem( "failed to send, reply: " + sysMsg->messageAsString() );
- }
- } else {
- manager() ->log( "could not lock the received message as kdev-system-message", Error );
- }
- } else {
- manager() ->log( "got unexpected reply-message", Error );
- return ;
- }
- }
-
- messageSendReady( false );
-}
-
-void InDocumentConversation::messageSendReady( bool success ) {
- if ( m_widget ) {
- if ( success ) {
- m_widgets.message->clear();
- }
- m_widgets.message->setEnabled( true );
- }
-
- m_sendingMessage = 0;
- if( !m_lastSendTime.isValid() || m_lastSendTime.msecsTo( QTime::currentTime() ) < 400 ) {
- m_widgets.message->setFocus();
- }
-}
-
-void InDocumentConversation::hide() {
- setActive( false );
- if ( m_widget )
- m_widget->hide();
-}
-
-void InDocumentConversation::sendMessage() {
- try {
- LogSuffix( "sendMessage(): ", this );
- if ( !m_widget )
- throw QString( "no widget" );
- QString text = m_widgets.message->text();
- if ( text.isEmpty() )
- throw "no text";
-
- IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
-
- IDocument* d = docControl->activeDocument();
- if ( !d )
- throw "no active document";
-
- KTextEditor::Document* doc = d->textDocument();
- if ( !doc )
- throw "no active text-document";
-
- KTextEditor::View* view = doc->activeView();
- if ( !view )
- throw "no active view";
-
- InDocumentReference start( "" );
- InDocumentReference end;
- /*
- KTextEditor::MarkInterface* mark = dynamic_cast<KTextEditor::MarkInterface*>( view );
- if( !mark ) {
- log( "no MarkInterface", Warning );
- } else {
- mark->
- }*/
- KTextEditor::Range r = view->selectionRange();
- if ( r.isValid() ) {
- KTextEditor::Cursor b = r.start();
- KTextEditor::Cursor e = r.end();
- QString txt = doc->text();
- QString path = TeamworkFolderManager::workspaceRelative( doc->url() );
- start = InDocumentReference( path, b.line(), b.column(), txt );
- end = InDocumentReference( path, e.line(), e.column(), txt );
- out( Logger::Debug ) << "sending references:" << start.asText() << "" << end.asText();
- }
-
- MessagePointer::Locked stdMsg = new InDocumentMessage( globalMessageTypeSet(), text, start, end, context() );
-
- InDocumentMessagePointer::Locked msg = stdMsg.cast<InDocumentMessage>();
-
- if ( !msg )
- throw QString( "could not create InDocumentMessage" );
-
- if ( r.isValid() )
- msg->contextLines() = DocumentContextLines( start, end, doc->text(), 5 );
-
-
- msg->setConversation( this );
-
- SessionPointer s = session();
-
- if ( !s )
- throw QString( "no session to send the message" );
-
- s.unsafe() ->send( msg );
- m_widgets.message->setEnabled( false );
- m_sendingMessage = msg;
-
- manager()->manager()->teamwork()->addMessageToList( msg.data() );
- } catch ( const char * str ) {
- err() <<"error while sending message:" << str;
- } catch ( QString str ) {
- err() <<"error while sending message:" << str;
- }
-}
-
-void InDocumentConversation::jumpTo() {
- try {
- if( m_messages.empty() )
- throw "no messages";
- //setActive( true );
- QAction* action = qobject_cast<QAction*>( sender() );
- if ( !action )
- throw "no sender-action";
-
- QVariant v = action->data();
- if ( !v.canConvert<MessagePointer>() )
- throw "cannot convert variant to message";
-
- MessagePointer mp = v.value<MessagePointer>();
- if ( !mp.cast<InDocumentMessage>( ) )
- throw "wrong message-type";
-
- selectMessage( mp.cast<InDocumentMessage>() );
- } catch ( const char * str ) {
- manager() ->log( QString( "error in jumpTo: " ) + str, Error );
- }
-}
-
-void InDocumentConversation::fillContextMenu( QMenu* menu, KDevTeamwork* /*teamwork*/, MessagePointer msg ) {
- if ( !m_jumpToAction ) {
- m_jumpToAction = new QAction( i18n("Show in Document"), this );
- connect( m_jumpToAction, SIGNAL( triggered() ), this, SLOT( jumpTo() ), Qt::QueuedConnection );
- m_jumpToAction->setToolTip( i18n("Open the document and jump to the references position.") );
-
- QVariant v;
- v.setValue( msg );
- m_jumpToAction->setData( v );
- }
-
- menu->addAction( m_jumpToAction );
-}
-
-void InDocumentConversation::cursorPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos ) {
- if( !m_active ) return;
- if ( m_smartCursor ) {
- int diff = m_smartCursor->line() - newPos.line();
- if ( diff > -10 && diff < 20 ) {
- placeWidget( view, &newPos ); ///Move the widget away from the cursor
- }
- }
-
- if( m_currentConnectedDocument ) ///Eventually select another message that is nearer
- m_selectNearestMessageTimer->start( 400 );
-
-}
-
-void InDocumentConversation::verticalScrollPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& /*newPos*/ ) {
- if( !m_active || m_block ) return;
- KTextEditor::Cursor c = currentDocCursor();
- placeWidget( view, &c );
- //manager()->log( "verticalScrollPositionChanged", Debug );
-}
-
-void InDocumentConversation::log( const QString& str, LogLevel level ) const {
- const_cast<ConversationManager*>( manager() ) ->log( "InDocumentConversation: " + str, level );
-}
-
-
-void InDocumentConversation::horizontalScrollPositionChanged ( KTextEditor::View */*view*/ ) {
- //manager()->log( "horizontalScrollPositionChanged", Debug );
-}
-
-void InDocumentConversation::fillMessageModel() {
- for ( MessageSet::Iterator it = m_messages.orderedValues<int>(); it; ++it ) {
- fillMessageToModel( it->message );
- }
-}
-
-void InDocumentConversation::selectNearestMessage() {
- if( !m_currentConnectedDocument ) {
- err() << "selectNearestMessage() called without active document";
- return;
- }
- InDocumentMessagePointer msg;
-
- KTextEditor::Cursor c = m_currentConnectedDocument->activeView()->cursorPosition();
- int nearestDiff = 1000000;
- KTextEditor::Cursor nearestCursor;
-
- QString file = TeamworkFolderManager::workspaceRelative( m_currentConnectedDocument->url() );
-
- MessageSet::Iterator it = m_messages.values( file );
-
- while( it ) {
- InDocumentMessagePointer::Locked l = it->message;
- if( l ) {
- KTextEditor::Cursor end;
- KTextEditor::Cursor start = findPositionInDocument( l, &end );
- int diff = c.line() - start.line();
- if( diff < 0 ) diff = -diff;
- if( diff < nearestDiff ) {
- nearestDiff = diff;
- nearestCursor = start;
- msg = it->message;
- }
- }
- ++it;
- }
- if( msg )
- messageSelected( msg );
-}
-
-void InDocumentConversation::userStateChanged( KDevTeamworkUserPointer /*user*/ ) {
- log( "userStateChanged" );
- fillUserBox();
-}
-
-void InDocumentConversation::fillUserBox() {
- try {
- if ( !m_widget )
- throw "no widget";
- m_widgets.talkingUsers->clear();
-
- UserPointer user = primaryUser();
- if ( !user )
- throw "could not figure out primary user";
-
- UserPointer::Locked l = user;
- if ( !l )
- throw "could not lock user";
- QVariant v;
- v.setValue<UserPointer>( user );
-
-
- KDevTeamworkUserPointer::Locked us = user.cast<KDevTeamworkUser>();
- if ( !us )
- throw "could not cast to KDevTeamworkUser, and lock.";
-
- m_widgets.talkingUsers->addItem( us->icon(), ~l->name(), v );
- m_userConnector = 0;
- m_userConnector = new TemporaryConversationConnector( us, this );
- } catch ( const char * str ) {
- log( QString( "error in fillUserBox: " ) + str , Error );
- }
-}
-
-void InDocumentConversation::rangeDeleted() {
- m_currentRange = 0;
-}
-
-
-void InDocumentConversation::fillMessageToModel( const InDocumentMessagePointer::Locked& msg ) {
- if ( !m_messagesModel )
- return ;
- if ( msg ) {
- int row = 0; //m_messagesModel->rowCount();
- m_messagesModel->insertRow( row );
- QModelIndex i = m_messagesModel->index( row, 0 );
- m_messagesModel->setData( i, msg->messageText(), Qt::DisplayRole );
- m_messagesModel->setData( i, msg->messageIcon() , Qt::DecorationRole );
- QVariant v;
- MessagePointer m( ( MessageInterface* ) msg.data() );
- v.setValue( m );
- m_messagesModel->setData( i, v , Qt::UserRole );
- } else {}
-}
-
-void InDocumentConversation::addListItem( const QString& txt , const QString& icon ) {
- manager() ->log( txt, Debug );
- if ( !m_messagesModel )
- return ;
- int row = 0; //m_messagesModel->rowCount();
- m_messagesModel->insertRow( row );
- QModelIndex i = m_messagesModel->index( row, 0 );
- m_messagesModel->setData( i, txt, Qt::DisplayRole );
- m_messagesModel->setData( i, IconCache::instance() ->getIcon( icon ) , Qt::DecorationRole );
-}
-
-void InDocumentConversation::setupWidget( QWidget* parent ) {
- m_widget = new QWidget( parent );
- m_widgets.setupUi( m_widget );
-
- QPalette p = m_widgets.frame->palette();
- p.setColor( QPalette::Background, QColor::fromRgb( 190, 190, 0, 150 ) );
- m_widgets.frame->setPalette( p );
- m_widgets.messages->header() ->hide();
- //m_widgets.messages->setWrapping( true );
-
- connect( m_widgets.message, SIGNAL( returnPressed() ), this, SLOT( sendMessage() ), Qt::QueuedConnection );
- connect( m_widgets.messages, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( messageClicked( const QModelIndex& ) ) );
- connect( m_widgets.messages, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT( messageContextMenu ( const QPoint & ) ) );
-
- if ( !m_messagesModel ) {
- m_messagesModel = new QStandardItemModel( 0, 1, 0 );
- fillMessageModel();
- }
- m_widgets.messages->setModel( m_messagesModel );
-
- if ( !m_userInfoAction ) {
- m_userInfoAction = new QAction( i18n("User Info"), this );
- connect( m_userInfoAction, SIGNAL( triggered() ), this, SLOT( userInfo() ) );
- m_userInfoAction->setToolTip( i18n("Show information about the selected user.") );
- }
-
- if ( !m_hideAction ) {
- m_hideAction = new QAction( i18n("Hide"), this );
- connect( m_hideAction, SIGNAL( triggered() ), this, SLOT( hide() ) , Qt::QueuedConnection );
- m_hideAction->setToolTip( i18n("Hide this conversation.") );
- }
-
- QMenu *actionMenu = new QMenu( "Actions", m_widgets.actionsButton );
-
- actionMenu->addAction( m_hideAction );
- actionMenu->addSeparator();
- actionMenu->addAction( m_userInfoAction );
-
- m_widgets.actionsButton->setMenu( actionMenu );
- m_widgets.actionsButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
- m_widgets.actionsButton->setArrowType( Qt::DownArrow );
- m_widgets.actionsButton->setPopupMode( QToolButton::InstantPopup );
-
- fillUserBox();
-}
-
-void InDocumentConversation::embedInView( KTextEditor::View* view, IDocument* document, KTextEditor::Cursor position ) {
- LogSuffix( "embedInView: ", this );
- try {
- if ( !view )
- throw "no view";
- if ( m_messages.empty() )
- throw "no messages";
- if ( m_widget )
- delete m_widget;
-
- disconnect( view, 0, this, 0 );
- // KTextEditor::Cursor cursor( line, 0 );
- setupWidget( view );
-
- if ( !m_widget )
- throw "could not setup widget";
-
- connect( view, SIGNAL( verticalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( verticalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
-
- connect( view, SIGNAL( horizontalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( horizontalScrollPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
-
- connect( view, SIGNAL( cursorPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ), this, SLOT( cursorPositionChanged ( KTextEditor::View*, const KTextEditor::Cursor& ) ) );
-
- m_smartCursor = SmartCursorContainer( document->textDocument() );
-
- if ( !m_smartCursor )
- throw "smart-cursor could not be created, maybe the editor is missing the interface";
-
- if( !document->textDocument() )
- throw "no text-document";
-
- if ( !position.isValid() )
- throw "the cursor-position is not valid";
-
- if( position > document->textDocument()->documentEnd() ) {
- out( Logger::Debug ) << "found position behind end of document";
- position = document->textDocument()->documentEnd();
- }
-
- m_smartCursor->setPosition( position );
-
- KTextEditor::Cursor c = currentDocCursor();
-
- placeWidget( view, &c, true );
- } catch ( const char * str ) {
- err() << str;
- }
-}
-
-bool isCovered(int line1, int line2, int position, int length) {
- if( line1 >= position-1 && line1 <= position+length+1 )
- return true;
- if( line2 >= position-1 && line2 <= position+length+1 )
- return true;
- return false;
-}
-
-void InDocumentConversation::placeWidget( KTextEditor::View* view, const KTextEditor::Cursor* awayFrom, bool forceShow ) {
- try {
- if ( !m_smartCursor )
- throw "smartcursor is invalid";
- if ( !m_widget )
- throw "no widget";
-
- QPoint p = view->cursorToCoordinate( *m_smartCursor );
- if ( p == QPoint( -1, -1 ) ) {
- if( !forceShow ) m_widget->hide();
- } else {
- if ( awayFrom ) {
- int sline = m_smartCursor->line();
- int widgetLines = 12; ///@todo Determine this better: How many lines does the widget cover?
- int cline = awayFrom->line();
- p = QPoint( -1, -1 );
- //Find any line-position where neither cline nor sline are coverd
-
- //Try 1; Above cline
- int resultLine = -1;
- if( !isCovered(cline, cline, sline+1, widgetLines) ) {
- resultLine = sline+1;
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline - 5 - widgetLines, widgetLines) ) {
- resultLine = cline - 5 - widgetLines; //Above cursor
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
- view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
- resultLine = -1; //Make sure the lower end of the widget is visible too
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline - 2 - widgetLines, widgetLines) ) {
- resultLine = sline - 5 - widgetLines; //Above target-position
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
- view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
- resultLine = -1; //Make sure the lower end of the widget is visible too
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline + 5, widgetLines) ) {
- resultLine = cline + 5; //Below cursor
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
- view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
- resultLine = -1; //Make sure the lower end of the widget is visible too
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline + 2, widgetLines) ) {
- resultLine = sline + 5; //Below target-position
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
-
- ///Try exactly the same positions as above, using less distance
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline - 2 - widgetLines, widgetLines) ) {
- resultLine = cline - 2 - widgetLines; //Above cursor
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
- view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
- resultLine = -1; //Make sure the lower end of the widget is visible too
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, cline + 2, widgetLines) ) {
- resultLine = cline + 2; //Below cursor
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- if( resultLine+widgetLines < 1 || resultLine+widgetLines > view->document()->lines() ||
- view->cursorToCoordinate( KTextEditor::Cursor( resultLine+widgetLines, 0 ) ) == QPoint( -1, -1 ) )
- resultLine = -1; //Make sure the lower end of the widget is visible too
-
- if( (p == QPoint( -1, -1 ) || resultLine == -1) && !isCovered(cline, sline, sline + 2, widgetLines) ) {
- resultLine = sline + 2; //Below target-position
- if(resultLine >= 1 && resultLine < view->document()->lines())
- p = view->cursorToCoordinate( KTextEditor::Cursor( resultLine, 0 ) );
- }
-
- }
-
- if( p == QPoint( -1, -1 ) ) {
- if( !forceShow ) {
- err() << "could not determine a good position to show the widget";
- p.setX( 50 );
- } else {
- p.setX( 50 );
- p.setY( 50 );
- }
- }
-
- //manager()->log( QString("smartcursor coordinates: %1 %2").arg( p.x() ).arg( p.y() ), Debug );
- m_widget->move( p );
- m_widget->show();
- }
-
- } catch ( const char * str ) {
- err() << "placeWidget:" << str;
- }
-}
-
-KTextEditor::Cursor InDocumentConversation::findPositionInDocument( InDocumentMessagePointer::Locked l, KTextEditor::Cursor* endTarget ) {
- LogSuffix s( "findPositionInDocument: ", this );
- if( !m_currentConnectedDocument ) {
- err() << "no connected document";
- return KTextEditor::Cursor();
- }
- if( !m_currentSearchInstance )
- m_currentSearchInstance = InDocumentReference::TextSearchInstance( m_currentConnectedDocument->text() );
-
- if ( l ) {
- int line, col;
- l->start().findInText( m_currentSearchInstance, line, col );
- int endLine = -1, endCol = -1;
- if ( l->end().isValid() && endTarget ) {
- l->end().findInText( m_currentSearchInstance, endLine, endCol );
- if ( endLine < line || ( endLine == line && endCol < col ) ) {
- int l = line, c = col;
- line = endLine;
- col = endCol;
- endLine = l;
- endCol = c;
- out( Logger::Warning ) << "Found end-marker before start-marker:" << line << ":" << col << "-" << endLine << ":" << endCol;
- }
- }
-
- if ( line == -1 ) {
- out( Logger::Warning ) << "Could not find reference-position for" << l->start().asText() << "in text of length "<< m_currentSearchInstance.text().length();
- line = l->start().line();
- col = l->start().col();
- if ( l->end().isValid() && endTarget ) {
- endLine = l->end().line();
- endCol = l->end().col();
- }
- }
-
- if ( endTarget && endLine != -1 ) {
- *endTarget = KTextEditor::Cursor( endLine, endCol == -1 ? 0 : endCol );
- }
-
- if ( line == -1 ) {
- err() << "cursor is invalid";
- line = 0;
- col = 0;
- return KTextEditor::Cursor::invalid();
- }
- if ( line != -1 )
- return KTextEditor::Cursor( line, col );
- } else {
- if ( !l )
- err() << "could not lock first message";
- else
- err() << "kdev-document has no text-document";
- }
- return KTextEditor::Cursor::invalid();
-}
-
-InDocumentConversation::InDocumentConversation( InDocumentMessage* msg ) : SafeLogger( KDevTeamwork::self()->logger() ), m_messageCount( 0 ), m_jumpToAction( 0 ), m_hideAction( 0 ), m_userInfoAction( 0 ), m_messagesModel( 0 ), m_block( false ), m_currentRange(0) {
- setActive( true );
- LogSuffix s( "constructor: ", this );
-
- m_selectNearestMessageTimer = new QTimer( this );
- m_selectNearestMessageTimer->setSingleShot( true );
- connect( m_selectNearestMessageTimer, SIGNAL( timeout() ), this, SLOT( selectNearestMessage() ) );
-
- qRegisterMetaType<InDocumentMessagePointer>( "InDocumentMessagePointer" );
-
- if ( msg ) {
- m_line = msg->start().line();
- m_documentName = ~msg->document();
- manager() ->log( "document-name: " + ~m_documentName, Debug );
- addMessage( msg );
-
- try {
- QString document = msg->document();
- if ( document.isEmpty() )
- throw "in-document-message has no document-information";
-
- int line = msg->start().line();
- if ( line == -1 )
- throw "in-document-message has no line-information";
-
- IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
- if ( !docControl )
- throw "no document-controller";
-
- IDocument* kdevDoc = docControl->activeDocument();
- if ( kdevDoc )
- documentActivated( kdevDoc, msg );
- }
- catch ( const char * str ) {
- manager() ->log( QString( "error while dispatching InDocumentMessage: " ) + str, Error );
- }
- }
-}
-
-InDocumentConversation::~InDocumentConversation() {
- if ( m_messagesModel )
- delete m_messagesModel;
- if( m_currentRange )
- delete m_currentRange;
-}
-
-SessionPointer InDocumentConversation::session() {
- try {
- if ( m_messages.empty() )
- throw "no messages";
- InDocumentMessagePointer::Locked lmsg = m_messages.value<int>( m_messageCount-1 ).message;
- if ( !lmsg )
- throw "could not lock message";
- return lmsg->info().session();
- } catch ( const char * str ) {
- err() << "could not get session:" << str;
- return 0;
- }
-}
-
-UserPointer InDocumentConversation::primaryUser() {
- if ( m_messages.empty() )
- return 0;
- InDocumentMessagePointer::Locked l = m_messages.value<int>(m_messageCount-1).message;
- if ( !l )
- return 0;
- return l->info().user();
-}
-
-void InDocumentConversation::textChanged ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*oldRange*/, const KTextEditor::Range & /*newRange*/ ) {
- m_currentSearchInstance = InDocumentReference::TextSearchInstance();
-}
-
-void InDocumentConversation::textRemoved ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*range*/ ) {
- m_currentSearchInstance = InDocumentReference::TextSearchInstance();
-}
-
-void InDocumentConversation::textInserted ( KTextEditor::Document * /*document*/, const KTextEditor::Range & /*range*/ ) {
- m_currentSearchInstance = InDocumentReference::TextSearchInstance();
-}
-
-void InDocumentConversation::documentActivated( IDocument* document ) {
- documentActivated( document, 0 );
-}
-
-void InDocumentConversation::documentActivated( IDocument* document, const InDocumentMessagePointer& msg_ ) {
- LogSuffix s( "documentActivated: " , this );
- if ( !m_active ) {
- err() << "This conversation is not active";
- return;
- }
- if( !document ) {
- err() << "got document-pointer with value zero";
- return;
- }
- if( !document->textDocument() || ! document->textDocument() ->activeView() ) {
- err() << "Document is no text-document";
- return ;
- }
- QString file = TeamworkFolderManager::workspaceRelative( document->url() );
-
- MessageSet::Iterator it = m_messages.values( file );
-
- if( !it /*&& !msg_*/ ) {
- /* out( Logger::Debug ) << "comparing" << file << "failed: is not part of conversation";
- MessageSet::Iterator it = m_messages.orderedValues<QString>();
- QString current = "__/__";
- while( it ) {
- InDocumentMessagePointer::Locked l = it->message;
- if( l ) {
- if( current != l->document() ) {
- out( Logger::Debug ) << "files are: \"" << l->document() << "\"";
- current = l->document();
- }
- }
-
- ++it;
- }*/
- return; ///Document contains none of our messages
- }
- out( Logger::Debug ) << "comparing" << file << "successful";
-
- KTextEditor::Document* doc = document->textDocument();
-
- InDocumentMessagePointer msg = msg_;
-
- if( doc != m_currentConnectedDocument ) {
-
- if( m_currentConnectedDocument )
- disconnect( m_currentConnectedDocument, 0, this, 0 );
-
- connect( doc, SIGNAL( textInserted ( KTextEditor::Document *,
- const KTextEditor::Range & ) ), this, SLOT( textInserted ( KTextEditor::Document *,
- const KTextEditor::Range & ) ) );
- connect( doc, SIGNAL( textRemoved ( KTextEditor::Document *,
- const KTextEditor::Range & ) ), this, SLOT( textRemoved ( KTextEditor::Document *,
- const KTextEditor::Range & ) ) );
- connect( doc, SIGNAL( textChanged ( KTextEditor::Document *,
- const KTextEditor::Range &,
- const KTextEditor::Range & ) ), this, SLOT( textChanged ( KTextEditor::Document *,
- const KTextEditor::Range &,
- const KTextEditor::Range & ) ) );
- }
-
- if( m_currentConnectedDocument != doc )
- m_currentSearchInstance = InDocumentReference::TextSearchInstance();
-
- m_currentConnectedDocument = doc;
-
- ///Determine the nearest message to the cursor
-
- if( msg ) {
- ///Always re-embed, because it's possible that documentActivated was called earlier without a given message
- embedInView( doc ->activeView(), document, findPositionInDocument( msg ) );
-
- messageSelected( msg );
- } else {
- m_selectNearestMessageTimer->start( 300 );
- }
-}
-
-void InDocumentConversation::setActive( bool active ) {
- if ( m_active == active )
- return ;
-
- m_active = active;
- IDocumentController* docControl = KDevTeamworkPlugin::staticDocumentController();
-
- if ( active ) {
- if( m_widget ) m_widget->show();
- connect( docControl, SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- connect( docControl, SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- connect( manager() ->manager() ->teamwork(), SIGNAL( updateConnection( TeamworkClientPointer ) ), this, SLOT( updateAllUsers() ) );
- if( docControl->activeDocument() )
- documentActivated( docControl->activeDocument() );
- } else {
- if( m_currentConnectedDocument ) {
- if( m_currentConnectedDocument->activeView() )
- disconnect( m_currentConnectedDocument->activeView(), 0, this, 0 );
- disconnect( m_currentConnectedDocument, 0, this, 0 );
-
- }
- m_currentConnectedDocument = 0;
-
- m_currentSearchInstance = InDocumentReference::TextSearchInstance();
-
- disconnect( docControl, 0, this, 0 );
- disconnect( manager() ->manager() ->teamwork(), 0, this, 0 );
-
- if(m_currentRange)
- delete m_currentRange;
- m_currentRange = 0;
- }
-}
-
-QString InDocumentConversation::context() const {
- if ( m_messages.empty() )
- return "";
- InDocumentMessagePointer::Locked l = const_cast<InDocumentMessagePointer&>( m_messages.value<int>(m_messageCount-1).message );
- if ( l )
- return l->context();
- else
- return "";
-}
-
-bool InDocumentConversation::match( InDocumentMessage* msg ) const {
- return context() == msg->context();
-}
-
-void InDocumentConversation::addMessage( InDocumentMessage* msg ) {
- msg->setConversation( this );
- if( m_messages[(InDocumentMessagePointer)msg] ) return;
- pushMessage( msg );
- if ( m_messagesModel )
- fillMessageToModel( msg );
-
- if ( msg->info().isIncoming() && msg->info().session() ) {
- ///Send a notification that the message arrived to the other side.
- //globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful ); //this is also done for KDevTeamworkTextMessage now
- }
-}
-
-
-struct DocumentMessageInternal {
- QPointer<InDocumentConversation> m_conversation;
-};
-
-QIcon InDocumentMessage::messageIcon() const {
- IconCache & cache( *IconCache::instance() );
- if ( info().isIncoming() ) {
- return cache( "document_message_in" ).pixmap( QSize( 16, 16 ), m_start ? QIcon::Normal : QIcon::Disabled );
- } else {
- return cache( "document_message_out" ).pixmap( QSize( 16, 16 ), m_start ? QIcon::Normal : QIcon::Disabled );
- }
-}
-
-void InDocumentMessage::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
- if ( m_internal.get() ) {
- if ( m_internal->m_conversation ) {
- m_internal->m_conversation->fillContextMenu( menu, teamwork, this );
- }
- }
- KDevTeamworkTextMessage::fillContextMenu( menu, teamwork );
-}
-
-void InDocumentMessage::setConversation( InDocumentConversation* conv ) {
- if ( !m_internal.get() )
- m_internal = auto_ptr<DocumentMessageInternal>( new DocumentMessageInternal );
- m_internal->m_conversation = conv;
-}
-
-QString InDocumentMessage::context() {
- return ~m_context;
-}
-
-QString InDocumentMessage::document() {
- return m_start.document();
-}
-
-InDocumentMessage::InDocumentMessage( const Teamwork::MessageConstructionInfo& info, const QString& text, const InDocumentReference& startRef, const InDocumentReference& endRef, const QString& context ) : KDevTeamworkTextMessage( info(this), text ), m_start( startRef ), m_end( endRef ), m_context( ~context ) {}
-
-InDocumentMessage::InDocumentMessage( InArchive& from, const Teamwork::MessageInfo& info ) : KDevTeamworkTextMessage( from, info ) {
- serial( from );
-}
-
-void InDocumentMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-
-bool InDocumentMessage::needReply() const {
- return m_internal.get() && m_internal->m_conversation;
-}
-
-void InDocumentMessage::result( bool success ) {
- if ( !success ) {
- QMetaObject::invokeMethod( ( InDocumentConversation* ) m_internal->m_conversation, "gotReply", Qt::QueuedConnection, Q_ARG( MessagePointer, ( MessagePointer ) 0 ) );
- }
-}
-
-MessageInterface::ReplyResult InDocumentMessage::gotReply( const MessagePointer& p ) {
- if ( m_internal.get() && m_internal->m_conversation ) {
- QMetaObject::invokeMethod( ( InDocumentConversation* ) m_internal->m_conversation, "gotReply", Qt::QueuedConnection, Q_ARG( MessagePointer, ( MessagePointer ) p ) );
- }
-
- return KDevTeamworkTextMessage::gotReply( p );
-}
-
-#include "conversationmanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.h (nonexistent)
@@ -1,113 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 header implements a very simple signalling-system that uses the SafeSharedPtr or WeakSafeSharedPtr-facilities to be thread-safe.
-*/
-
-#ifndef SAFESIGNALLER_H
-#define SAFESIGNALLER_H
-
-#include <QObject>
-#include <ext/hash_set>
-#include "lib/network/safesharedptr.h"
-#include "lib/network/weaksafesharedptr.h"
-
-struct SignalProxyBase {
- virtual void signal() = 0;
- virtual ~SignalProxyBase() {
- };
-};
-
-template<class Type>
-struct hashCall {
- size_t operator() ( const Type& rhs ) const {
- return (size_t)rhs.unsafe();
- }
-};
-
-///An object of this type represents a signal that multiple receiver-objects can be bound to. To get a function similar to qt's auto-disconnect, WeakSharedPtr<...> may be used as Target-type. If SafeSharedPtr is used, connected objects will be kept alive until the SafeSignal is destroyed or the object disconnected.
-template<class TargetType, class Signal>
-class SafeSignal {
- SafeSignal& operator = ( const SafeSignal& rhs ) {
- return *this;
- }
- SafeSignal( const SafeSignal& rhs ) {
- }
-
-public:
- SafeSignal() {
- }
-
- void connect( const TargetType& targ ) {
- if( isConnected( targ ) ) return;
- m_connected.insert( targ );
- }
-
- void disconnect( const TargetType& targ ) {
- typename ConnectionMap::iterator it = m_connected.find( targ );
- if( it != m_connected.end() )
- m_connected.erase( it );
- }
-
- bool isConnected( const TargetType& targ ) {
- return m_connected.find( targ ) != m_connected.end();
- }
-
- void operator() ( const Signal& signal = Signal() ) {
- for( typename ConnectionMap::iterator it = m_connected.begin(); it != m_connected.end(); ++it ) {
- typename TargetType::Locked l = *it;
- if( l )
- l->dispatchSignal( signal );
- }
- }
-
-private:
- SignalProxyBase* m_proxy;
- typedef __gnu_cxx::hash_set< TargetType, hashCall<TargetType> > ConnectionMap;
- ConnectionMap m_connected;
-};
-
-template<class TargetType, class Signal>
-struct SignalProxy : public SignalProxyBase {
- SafeSignal<TargetType, Signal> s;
- Signal sign;
- SignalProxy( const TargetType& target, const Signal& sig ) : sign( sig ) {
- s.connect( target );
- }
- virtual void signal() {
- s( sign );
- }
-};
-
-///This is a very simple safe-signaller object that can be used to easily bind safe signals into QActions etc. The signal-type may be any copyable object. The given object will be copied, and sent once the signal is emitted.
-class QSafeSignaller : public QObject {
- Q_OBJECT
- QSafeSignaller& operator = ( const QSafeSignaller& rhs );
- QSafeSignaller( const QSafeSignaller& rhs );
-public:
- template<class Target, class Signal>
- QSafeSignaller( const Target& target, const Signal& signal, QObject* parent ) : QObject( parent ) {
- m_proxy = new SignalProxy<Target, Signal>( target, signal );
- }
- ~QSafeSignaller();
-public slots:
- void signal();
-private:
- SignalProxyBase* m_proxy;
-};
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safesignaller.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.cpp (nonexistent)
@@ -1,1214 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "editpatch.h"
-
-#include <kmimetype.h>
-#include <klineedit.h>
-#include <kmimetypechooser.h>
-#include <kmimetypetrader.h>
-#include <k3process.h>
-#include <krandom.h>
-#include <QTabWidget>
-#include <QMenu>
-#include <QFile>
-#include <QTimer>
-#include <QMutexLocker>
-#include <QPersistentModelIndex>
-//#include <lib/kdevappintterface.h>
-#include "patchesmanager.h"
-#include <kfiledialog.h>
-#include "kdevteamwork.h"
-#include <interfaces/idocument.h>
-//#include "kdevdiffinterface.h"
-#include "kdevteamworkplugin.h"
-#include "collaborationmanager.h"
-#include <QStandardItemModel>
-#include <interfaces/icore.h>
-#include "serializationutils.h"
-#include "kdevteamwork_user.h"
-#include "messagemanager.h"
-#include "lib/network/messagetypeset.h"
-#include "kdevteamwork_helpers.h"
-#include "teamworkfoldermanager.h"
-#include <kde_terminal_interface.h>
-#include <kparts/part.h>
-#include <kparts/factory.h>
-#include <kservice.h>
-#include <kdialog.h>
-
-#include "lib/libdiff2/komparemodellist.h"
-#include "lib/libdiff2/kompare.h"
-#include <kmessagebox.h>
-#include <QMetaType>
-#include <QVariant>
-#include "lib/libdiff2/diffsettings.h"
-#include <ktexteditor/cursor.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-#include <ktexteditor/markinterface.h>
-#include <ktexteditor/smartinterface.h>
-#include <interfaces/idocumentcontroller.h>
-
-#include "kdevteamwork_client.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-///Whether arbitrary exceptions that occurred while diff-parsing within the library should be caught
-#define CATCHLIBDIFF
-
-using namespace KDevelop;
-
-QString getDefaultExtension( const QStringList& patterns );
-
-Q_DECLARE_METATYPE( const Diff2::DiffModel* )
-
-EditPatch::EditPatch( PatchesManager* parent, LocalPatchSourcePointer patch, bool local ) : QObject( parent ), SafeLogger( parent->teamwork() ->logger(), "EditPatch: " ), m_actionState( LocalPatchSource::Unknown ), m_parent( parent ), m_editingPatch( patch ), m_editPatchLocal( local ), m_editDlg( 0 ), m_reversed( false ), m_started( false ), m_isSource( false ) {
- m_updateKompareTimer = new QTimer( this );
- m_updateKompareTimer->setSingleShot( true );
- connect( m_updateKompareTimer, SIGNAL( timeout() ), this, SLOT( updateKompareModel() ) );
- showEditDialog();
- if ( m_editingPatch )
- fillEditFromPatch();
- m_started = true;
-}
-
-EditPatch::~EditPatch() {
- removeHighlighting();
-}
-
-void EditPatch::slotEditOk() {
-
- LocalPatchSourcePointer p = patchFromEdit();
-
- if ( p && !m_parent->hasPatch( p ) )
- m_parent->addPatch( p );
- //emit dialogClosed( this );
- emit stateChanged( this );
-}
-
-void EditPatch::slotEditCancel() {
- //emit dialogClosed( this );
-}
-
-LocalPatchSourcePointer EditPatch::patchFromEdit() {
- if ( !m_editDlg )
- return 0;
- LocalPatchSourcePointer::Locked ps;
-
- if ( m_editingPatch )
- ps = m_editingPatch;
- else {
- ps = new LocalPatchSource();
- ps->userIdentity = m_parent->teamwork() ->currentUserIdentity();
- }
-
- if ( !ps ) {
- err() << "could not lock edited patch";
- return 0;
- }
-
- LocalPatchSource& ls( *ps );
- ls.name = ~m_editPatch.name->text();
- ls.unApplyCommand = ~m_editPatch.unapplyCommand->text();
- ls.type = ~m_editPatch.type->text();
- if( !m_editPatch.filename->url().toLocalFile().isEmpty() )
- ls.filename = ~TeamworkFolderManager::teamworkRelative( ( m_editPatch.filename->url() ) );
- else
- ls.filename = "";
- ls.description = ~m_editPatch.description->toPlainText();
- ls.dependencies = ~m_editPatch.dependencies->text();
- ls.command = ~m_editPatch.command->text();
- ls.applyCommand = ~m_editPatch.applyCommand->text();
- ls.state = editState();
- ls.author = ~m_editPatch.author->text();
- QString txt = m_editPatch.accessRights->currentText();
-
- ls.access = LocalPatchSource::accessFromString( ~txt );
-
- m_editingPatch = ps;
- return ps;
-}
-
-void EditPatch::fillEditFromPatch() {
- out( Logger::Debug ) << "filling edit from patch";
-
- LocalPatchSourcePointer _patch = m_editingPatch;
- bool local = m_editPatchLocal;
- LocalPatchSourcePointer::Locked l = _patch;
- if ( !m_editDlg || !_patch || !l )
- return ;
- LocalPatchSource& patch( *l );
- m_editPatchLocal = local;
-
- m_editPatch.name->setText( ~patch.name );
- m_editPatch.unapplyCommand->setText( ~patch.unApplyCommand );
- m_editPatch.type->setText( ~patch.type );
- if( !patch.filename.empty() )
- m_editPatch.filename->setUrl( TeamworkFolderManager::teamworkAbsolute( ~patch.filename ) );
- else
- m_editPatch.filename->setUrl( KUrl() );
- m_editPatch.description->setText( ~patch.description );
- m_editPatch.dependencies->setText( ~patch.dependencies );
- m_editPatch.command->setText( ~patch.command );
- m_editPatch.applyCommand->setText( ~patch.applyCommand );
- m_editPatch.author->setText( ~patch.author );
-
- int stateIndex = 0;
-
- switch ( patch.state ) {
- case LocalPatchSource::Applied:
- stateIndex = 1;
- break;
- case LocalPatchSource::NotApplied:
- stateIndex = 2;
- break;
- default:
- stateIndex = 0;
- }
-
- m_editPatch.state->setCurrentIndex( stateIndex );
- slotStateChanged();
-
- if ( !patch.filename.empty() )
- m_editPatch.tabWidget->setCurrentIndex( m_editPatch.tabWidget->indexOf( m_editPatch.fileTab ) );
- else
- m_editPatch.tabWidget->setCurrentIndex( m_editPatch.tabWidget->indexOf( m_editPatch.commandTab ) );
-
- m_editPatch.accessRights->setEditText( ~patch.accessAsString() );
-
- UserIdentity id = l->userIdentity;
- if ( id ) {
- m_editPatch.userButton->setEnabled( true );
- m_editPatch.userButton->setText( ~id.name() );
- } else {
- m_editPatch.userButton->setEnabled( false );
- }
-
- updateByType();
- m_updateKompareTimer->start( 400 );
-}
-
-void EditPatch::slotFileNameEdited() {
- m_updateKompareTimer->start( 100 );
-}
-
-void EditPatch::slotCommandEdited() {
- m_updateKompareTimer->start( 100 );
-}
-
-void EditPatch::slotEditMimeType( const QString& /*str*/ ) {
- if ( !m_started )
- return ;
- m_editingPatch = patchFromEdit();
- updateByType();
- m_updateKompareTimer->start( 100 );
-}
-
-void EditPatch::slotEditCommandChanged( const QString& /*str*/ ) {
- if ( !m_started )
- return ;
- m_editPatch.filename->setUrl( QString( "" ) );
- emit stateChanged( this );
-
- //m_updateKompareTimer->start( 100 );
-}
-
-void EditPatch::slotUserButton() {
- LocalPatchSourcePointer::Locked patch = patchFromEdit();
- try {
- if ( !patch )
- throw "could not lock patch";
- UserPointer u;
- {
- TeamworkClientPointer::Locked client = m_parent->teamwork() ->client();
- if ( !client )
- throw "no client";
- u = client->findUser( patch->userIdentity );
- }
- if ( !u )
- throw "could not get user";
- if ( !u.cast<KDevTeamworkUser>() )
- throw "user has wrong type";
-
- m_parent->teamwork() ->showUserInfo( u.cast<KDevTeamworkUser>() );
- } catch ( const QString & str ) {
- err() << "slotUserButton():" << str;
- } catch ( const char * str ) {
- err() << "slotUserButton():" << str;
- }
-}
-
-void EditPatch::slotApplyEditPatch() {
- LocalPatchSourcePointer patch = patchFromEdit();
- if ( m_editPatchLocal ) {
- LocalPatchSourcePointer::Locked l = m_editingPatch;
- if ( !m_parent->hasPatch( patch ) )
- m_parent->addPatch( patch );
-
- if ( l && l->filename.empty() ) {
- ///The patch has to be serialized first before it can be applied
-
- SafeSharedPtr<PatchMessage>::Locked l = getPatchMessage( PatchRequestData::Apply );
- if ( !l )
- throw "could not get the patch-message";
- m_parent->processMessage( l.data() );
- } else {
- apply();
- fillEditFromPatch();
- }
- } else {
- ///Request the patch from the peer and apply it
- try {
- LocalPatchSourcePointer::Locked lpatch = patch;
- if ( !lpatch )
- throw "could not lock patch-source";
-
- UserPointer::Locked user = lpatch->user();
- if ( !user )
- throw "the patch has no associated user";
- if ( !user->online() )
- throw "the user is not online";
-
- SessionPointer session = user->online().session();
- if ( !session )
- throw "the session could not be acquired";
-
- MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork(), PatchRequestData::Apply );
- session.unsafe() ->send( mp );
- m_parent->teamwork() ->addMessageToList( mp );
- } catch ( const char * str ) {
- err() << "error in slotApplyEditPatch:" << str;
- }
- }
- emit stateChanged( this );
-}
-
-void EditPatch::slotUnapplyEditPatch() {
- if ( !m_editPatchLocal )
- return ;
-
- LocalPatchSourcePointer patch = patchFromEdit();
- if ( !m_parent->hasPatch( patch ) )
- m_parent->addPatch( patch );
- LocalPatchSourcePointer::Locked l = patch;
- if ( l ) {
- if ( !l->command.empty() ) {
- int result = KMessageBox::warningContinueCancel( m_editDlg, i18n( "You are about to unapply a dynamic patch created by the command \"%1\". That can be very dangerous. If the same command will not produce the same text after the unapply, the patch cannot be reapplied and all data may be lost. \nRecommendation: Make the patch a file-patch before unapplying it.", l->command.c_str() ), i18n("Warning") );
- if ( result != KMessageBox::Continue )
- return ;
- }
- }
- apply( true );
- fillEditFromPatch();
-
- emit stateChanged( this );
-}
-
-SafeSharedPtr<PatchMessage> EditPatch::getPatchMessage( PatchRequestData::RequestType /*type*/ ) {
- try {
- LocalPatchSourcePointer::Locked lpatch = patchFromEdit();
- if ( !lpatch )
- throw "could not lock patch";
-
- UserPointer::Locked fakeUser( new KDevTeamworkUser( UserPointer::Locked( new User( "local" ) ) ) );
- SafeSharedPtr<Teamwork::FakeSession>::Locked fakeSession( new Teamwork::FakeSession( fakeUser, m_parent->teamwork() ->logger(), globalMessageTypeSet(), 0 ) );
- fakeUser->setSession( ( SessionInterface* ) fakeSession );
-
- SafeSharedPtr<PatchRequestMessage>::Locked request = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork() );
-
- request->info().setSession( ( SessionInterface* ) fakeSession );
-
- m_parent->processMessage( request.data() );
-
- MessagePointer::Locked msg = fakeSession->getFirstMessage();
- if ( !msg.cast<PatchMessage>() ) {
- if ( KDevSystemMessagePointer::Locked l = msg.cast<KDevSystemMessage>() ) {
- throw QString( "Requesting the message from self failed: %1: %2" ).arg( l->messageAsString() ).arg( l->text() );
- } else {
- throw QString( "answer-message is not of type PatchMessage: " ) + ( msg ? msg->name() : "" );
- }
- }
-
- return msg.cast<PatchMessage>().data();
- } catch ( const char * str ) {
- err() << "getPatchMessage: error:" << str;
- } catch ( const QString & str ) {
- err() << "getPatchMessage: error:" << str;
- } catch ( const TeamworkError & error ) {
- err() << "getPatchMessage: failed to serialize and deserialize the patch locally:" << error.what();
- }
- return 0;
-}
-
-KUrl EditPatch::getPatchFile( bool temp ) {
- try {
- LocalPatchSourcePointer patch = patchFromEdit();
- if ( !m_parent->hasPatch( patch ) )
- m_parent->addPatch( patch );
- SafeSharedPtr<PatchMessage> smsg = getPatchMessage( PatchRequestData::View );
- SafeSharedPtr<PatchMessage>::Locked msg = smsg;
- if ( !msg )
- throw QString( "could not serialize patch-message" );
- LocalPatchSourcePointer::Locked patchInfo = m_editingPatch;
- if ( !patchInfo )
- throw QString( "could not lock patchi-info" );
-
- QString mimeName = ~patchInfo->type;
- if ( mimeName.trimmed().isEmpty() )
- mimeName = "text/x-diff";
-
- KMimeType::Ptr mime = KMimeType::mimeType( mimeName );
- if ( !mime )
- throw QString( "Error in kdelibs: could not create mime-type" ); ///according to the documentation this should never happen, but it does
-
- QString fileName = ~patchInfo->name;
- if ( !patchInfo->filename.empty() )
- fileName += "_" + QFileInfo( ~patchInfo->filename ).fileName();
- else
- fileName += getDefaultExtension( mime->patterns() );
-
- out( Logger::Debug ) << "getPatchFile() creating file for patch:" << fileName;
-
- QString subFolder = "local";
- if ( temp )
- subFolder = "temp";
-
- KUrl filePath = TeamworkFolderManager::createUniqueFile( "patches/" + subFolder, fileName );
- if ( temp )
- TeamworkFolderManager::registerTempItem( filePath );
-
- {
- ///@todo use NetAccess
- QFile file( filePath.toLocalFile() );
-
- file.open( QIODevice::WriteOnly );
- if ( !file.isOpen() )
- throw QString( "could not open %1" ).arg( filePath.toLocalFile() );
-
- if ( file.write( msg->data() ) != msg->data().size() )
- throw "writing the file " + filePath.toLocalFile() + " failed";
- }
- return filePath;
- } catch ( const QString & str ) {
- err() << "getPatchFile(" << temp << ") failed:" << str;
- return QString();
- } catch ( const char * str ) {
- err() << "getPatchFile(" << temp << ") failed:" << str;
- return QString();
- }
-}
-void EditPatch::slotShowEditPatch() {
- LocalPatchSourcePointer patch = patchFromEdit();
- if ( !m_parent->hasPatch( patch ) )
- m_parent->addPatch( patch );
- try {
-
- if ( m_editPatchLocal ) {
- SafeSharedPtr<PatchMessage>::Locked l = getPatchMessage( PatchRequestData::View );
- if ( !l )
- throw "could not get the patch-message";
- m_parent->processMessage( l.data() );
- } else {
- ///Request the patch from the peer and show it
- LocalPatchSourcePointer::Locked lpatch = patch;
- if ( !lpatch )
- throw "could not lock patch-source";
-
- UserPointer::Locked user = lpatch->user();
- if ( !user )
- throw "the patch has no associated user";
- if ( !user->online() )
- throw "the user is not online";
-
- SessionPointer session = user->online().session();
- if ( !session )
- throw "the session could not be acquired";
-
- MessagePointer::Locked mp = new PatchRequestMessage( globalMessageTypeSet(), lpatch, m_parent->teamwork() );
- session.unsafe() ->send( mp );
- m_parent->teamwork() ->addMessageToList( mp );
- }
- } catch ( const QString & str ) {
- err() << "error in slotShowEditPatch:" << str;
- } catch ( const char * str ) {
- err() << "error in slotShowEditPatch:" << str;
- }
-}
-
-void EditPatch::slotStateChanged() {
- if ( !m_started )
- return ;
- if ( !m_editDlg )
- return ;
- patchFromEdit();
-
- switch ( editState() ) {
- case LocalPatchSource::Unknown:
- m_editPatch.applyButton->setEnabled( true );
- m_editPatch.unApplyButton->setEnabled( true );
- break;
- case LocalPatchSource::Applied:
- m_editPatch.applyButton->setEnabled( false );
- m_editPatch.unApplyButton->setEnabled( true );
- break;
- case LocalPatchSource::NotApplied:
- m_editPatch.applyButton->setEnabled( true );
- m_editPatch.unApplyButton->setEnabled( false );
- break;
- }
-
- if ( !m_editPatchLocal ) {
- m_editPatch.unApplyButton->setEnabled( false );
- }
-
- m_updateKompareTimer->start( 100 );
-
- updateByType();
- emit stateChanged( this );
-}
-
-void EditPatch::slotEditFileNameChanged( const QString& str ) {
- if ( !m_editDlg || !m_started )
- return ;
- QString txt;
-
- KSharedPtr<KMimeType> mt = KMimeType::findByUrl( KUrl( str ) );
-
- if ( !str.isEmpty() ) {
- txt = "mime-type: " + mt->name();
- m_editPatch.type->setText( mt->name() );
- }
-
- m_editPatch.mimetype->setPixmap( m_parent->teamwork() ->icons().getIcon( mt->iconName(), KIconLoader::Desktop ).pixmap( 16, 16 ) );
-
- m_editPatch.mimetype->setText( txt );
- m_editPatch.command->setText( "" );
- emit stateChanged( this );
-
- //m_updateKompareTimer->start( 100 );
-}
-
-void EditPatch::slotEditDialogFinished( int /*result*/ ) {
- if ( !m_started )
- return ;
- LocalPatchSourcePointer patch = patchFromEdit();
-
- m_editDlg = 0;
- emit dialogClosed( this );
-}
-
-void EditPatch::slotChooseType() {
- if ( !m_started )
- return ;
- if ( !m_editDlg )
- return ;
-
- QString text = "Select the MimeType for this item.";
- QStringList list;
- list << m_editPatch.type->text();
- KMimeTypeChooserDialog *d = new KMimeTypeChooserDialog( text, "", list , "text", QStringList(), KMimeTypeChooser::Comments | KMimeTypeChooser::Patterns | KMimeTypeChooser::EditButton, m_editDlg );
- if ( d->exec() == QDialog::Accepted ) {
- if ( !d->chooser() ->mimeTypes().isEmpty() ) {
- ///It would be perfect to have a mime-type-chooser that allows only one choice.
- if ( d->chooser() ->mimeTypes().back() == m_editPatch.type->text() ) {
- m_editPatch.type->setText( d->chooser() ->mimeTypes().front() );
- } else {
- m_editPatch.type->setText( d->chooser() ->mimeTypes().back() );
- }
- }
- }
-
- delete d;
- updateByType();
-}
-
-std::string EditPatch::logPrefix() {
- LocalPatchSourcePointer::Locked l = m_editingPatch;
- if ( !l )
- return "EditPatch: ";
- else
- return "EditPatch(" + l->name + "): ";
-}
-
-void EditPatch::slotToFile() {
- LocalPatchSourcePointer::Locked l = patchFromEdit();
- if ( !l ) {
- err() << "slotToFile() could not lock edited patch";
- return ;
- }
- KUrl f = getPatchFile();
- if ( f.isEmpty() ) {
- err() << "slotToFile() could not get create patch-file";
- return ;
- }
- out( Logger::Debug ) << "converting patch with command \"" << l->command << "\" to file \"" << f.prettyUrl() << "\"";
- if( !f.isEmpty() )
- l->setFileName( ~TeamworkFolderManager::teamworkRelative( f ) );
- else
- l->setFileName( "" );
-
- m_editPatch.tabWidget->setCurrentIndex( 0 );
- m_editPatch.filename->setUrl( f );
- fillEditFromPatch();
-}
-
-
-void EditPatch::slotDetermineState() {
- m_parent->determineState( patchFromEdit() );
- fillEditFromPatch();
- emit stateChanged( this );
-}
-
-void EditPatch::dialogDestroyed() {
- m_editDlg = 0;
- EditPatchPointer p = this;
- emit dialogClosed( this );
-}
-
-void EditPatch::updateByType() {
- LocalPatchSourcePointer::Locked l = m_editingPatch;
- if ( !l )
- return ;
- l->applyCommand = ~m_editPatch.applyCommand->text();
- l->unApplyCommand = ~m_editPatch.unapplyCommand->text();
- l->type = ~m_editPatch.type->text();
-
- if ( l->type == "text/x-diff" ) {
- if ( l->state == LocalPatchSource::Applied ) {
- m_editPatch.filesGroup->show();
- } else {
- m_editPatch.filesGroup->hide();
- }
- if ( l->patchTool( false ) == "patch" && l->patchTool( true ) == "patch" ) {
- m_editPatch.determineState->setEnabled( true );
- } else {
- m_editPatch.determineState->setEnabled( false );
- }
- } else {
- m_editPatch.determineState->setEnabled( false );
- m_editPatch.filesGroup->hide();
- }
-}
-
-void EditPatch::showEditDialog() {
- if ( m_editDlg ) {
- out( Logger::Warning ) << "there is still another edit-dialog open";
- return ;
- }
-
-
- m_editDlg = new QDialog( m_parent->teamwork() ->widget() );
-
- connect( m_editDlg, SIGNAL( destroyed( QObject* ) ), this, SLOT( dialogDestroyed() ) );
- m_editPatch.setupUi( m_editDlg );
-
- m_filesModel = new QStandardItemModel( m_editPatch.filesList );
- m_editPatch.filesList->setModel( m_filesModel );
-
- connect( m_editPatch.previousHunk, SIGNAL( clicked( bool ) ), this, SLOT( prevHunk() ) );
- connect( m_editPatch.nextHunk, SIGNAL( clicked( bool ) ), this, SLOT( nextHunk() ) );
- connect( m_editPatch.filesList, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( fileDoubleClicked( const QModelIndex& ) ) );
- connect( m_editPatch.filesList->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( fileSelectionChanged() ) );
- connect( m_editPatch.okButton, SIGNAL( pressed() ), this, SLOT( slotEditOk() ) );
- //connect( m_editPatch.cancelButton, SIGNAL( pressed() ), this, SLOT( slotEditCancel() ) );
-
- connect( m_editPatch.highlightFiles, SIGNAL( clicked( bool ) ), this, SLOT( highlightFile() ) );
- connect( m_editPatch.applyButton, SIGNAL( pressed() ), this, SLOT( slotApplyEditPatch() ) );
- connect( m_editPatch.unApplyButton, SIGNAL( pressed() ), this, SLOT( slotUnapplyEditPatch() ) );
- connect( m_editPatch.showButton, SIGNAL( pressed() ), this, SLOT( slotShowEditPatch() ) );
-
- connect( m_editPatch.type, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditMimeType( const QString& ) ) );
- connect( m_editPatch.chooseType, SIGNAL( pressed() ), this, SLOT( slotChooseType() ) );
- connect( m_editDlg, SIGNAL( finished( int ) ), this, SLOT( slotEditDialogFinished( int ) ) );
- connect( m_editPatch.filename, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditFileNameChanged( const QString& ) ) );
- connect( m_editPatch.command, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotEditCommandChanged( const QString& ) ) );
- connect( m_editPatch.state, SIGNAL( currentIndexChanged( int ) ), this, SLOT( slotStateChanged() ) );
- connect( m_editPatch.determineState, SIGNAL( clicked( bool ) ), this, SLOT( slotDetermineState() ) );
- connect( m_editPatch.commandToFile, SIGNAL( clicked( bool ) ), this, SLOT( slotToFile() ) );
-
- connect( m_editPatch.filename->lineEdit(), SIGNAL( returnPressed() ), this, SLOT( slotFileNameEdited() ) );
- connect( m_editPatch.filename->lineEdit(), SIGNAL( editingFinished() ), this, SLOT( slotFileNameEdited() ) );
- connect( m_editPatch.filename, SIGNAL( urlSelected( const QString& ) ), this, SLOT( slotCommandEdited() ) );
- connect( m_editPatch.command, SIGNAL( editingFinished() ), this, SLOT( slotCommandEdited() ) );
- connect( m_editPatch.command, SIGNAL( returnPressed() ), this, SLOT( slotCommandEdited() ) );
- connect( m_editPatch.command, SIGNAL( () ), this, SLOT( slotCommandEdited() ) );
-
- connect( m_editPatch.userButton, SIGNAL( clicked( bool ) ), this, SLOT( slotUserButton() ) );
- connect( m_editPatch.applyCommand, SIGNAL( textEdited( const QString& ) ), this, SLOT( updateByType() ) );
- connect( m_editPatch.unapplyCommand, SIGNAL( textEdited( const QString& ) ), this, SLOT( updateByType() ) );
-
- bool blocked = blockSignals( true );
- m_editPatch.accessRights->insertItem( 0, ~LocalPatchSource::accessToString( Public ) );
- m_editPatch.accessRights->insertItem( 1, ~LocalPatchSource::accessToString( ConnectedOnly ) );
- m_editPatch.accessRights->insertItem( 2, ~LocalPatchSource::accessToString( Ask ) );
- m_editPatch.accessRights->insertItem( 3, ~LocalPatchSource::accessToString( Private ) );
-
- m_editPatch.state->insertItem( 0, "Unknown" );
- m_editPatch.state->insertItem( 1, "Applied" );
- m_editPatch.state->insertItem( 2, "Not Applied" );
-
-
- m_editPatch.filename->fileDialog() ->setUrl( TeamworkFolderManager::workspaceDirectory() );
-
- m_editPatch.type->setText( "text/x-diff" );
-
- m_editDlg->show();
- blockSignals( blocked );
-}
-
-void EditPatch::hideEditDialog() {
- if ( !m_editDlg )
- return ;
- m_editDlg->close();
- delete m_editDlg;
- m_editDlg = 0;
-}
-
-void EditPatch::editPatchReadOnly() {
- if ( !m_editDlg )
- return ;
-
- m_editPatch.applyCommand->setReadOnly( true );
- m_editPatch.unapplyCommand->setReadOnly( true );
- m_editPatch.name->setReadOnly( true );
- m_editPatch.dependencies->setReadOnly( true );
- m_editPatch.command->setReadOnly( true );
- m_editPatch.accessRights->setEditable( false );
- if ( m_editPatch.accessRights->lineEdit() )
- m_editPatch.accessRights->lineEdit() ->setReadOnly( true );
- m_editPatch.type->setReadOnly( true );
- /*if( m_editPatch.type->lineEdit() )
- m_editPatch.type->lineEdit()->setReadOnly( true );*/
- m_editPatch.description->setReadOnly( true );
- if ( m_editPatch.filename->lineEdit() )
- m_editPatch.filename->lineEdit() ->setReadOnly( true );
- if ( m_editPatch.filename->comboBox() )
- m_editPatch.filename->comboBox() ->setEditable( false );
- if ( m_editPatch.filename->lineEdit() )
- m_editPatch.filename->lineEdit() ->setReadOnly( true );
- /*m_editPatch.applyButton->setEnabled( false );
- m_editPatch.unApplyButton->setEnabled( false );
- m_editPatch.showButton->setEnabled( false );*/
- if ( !m_editPatchLocal ) {
- m_editPatch.unApplyButton->setEnabled( true );
- m_editPatch.applyButton->setEnabled( true );
- m_editPatch.showButton->setEnabled( true );
- }
- // m_editPatch.cancelButton->setEnabled( false );
-}
-
-LocalPatchSource::State EditPatch::editState() {
- if ( !m_editDlg )
- return LocalPatchSource::Unknown;
- switch ( m_editPatch.state->currentIndex() ) {
- case 0:
- return LocalPatchSource::Unknown;
- case 1:
- return LocalPatchSource::Applied;
- default:
- return LocalPatchSource::NotApplied;
- }
-}
-
-LocalPatchSourcePointer EditPatch::patch() const {
- return m_editingPatch;
-}
-
-const QString terminalSuccessMarker = "TERMINAL_ACTION_SUCCESSFUL";
-const QString reversedMarker = "Reversed (or previously applied) patch detected";
-
-void EditPatch::apply( bool reverse, const QString& _fileName ) {
- try {
- if ( m_lastDataTime.isValid() ) {
- if ( m_lastDataTime.msecsTo( QTime::currentTime() ) < 100 ) {
- m_editPatch.konsoleDock->showNormal();
- throw "terminal is still in use";
- }
- }
- LocalPatchSourcePointer::Locked patch = patchFromEdit();
- if ( !patch )
- throw "could not lock patch";
-
- QString fileName = _fileName;
- if ( fileName.trimmed().isEmpty() )
- fileName = ( ~patch->filename ).trimmed();
-
- if ( fileName.isEmpty() )
- throw "cannot apply patch without a filename";
-
- out() << "Applying patch" << patch->name << "from file" << fileName;
-
- if ( ( !reverse && patch->state == LocalPatchSource::Applied ) )
- throw QString( "tried to apply an already applied patch: %1" ).arg( ~patch->name );
- if ( ( reverse && patch->state == LocalPatchSource::NotApplied ) )
- throw QString( "tried to unapply a not applied patch: %1" ).arg( ~patch->name );
-
- KPluginFactory* factory = 0;
- KService::Ptr service = KService::serviceByDesktopName("konsolepart");
- if (service) {
- factory = KPluginLoader(service->library()).factory();
- }
- if ( factory == 0L )
- throw "no factory for konsolepart available";
-
- KParts::Part* p;
- if ( !m_konsolePart ) {
- p = static_cast<KParts::Part*>( factory->create( ( QObject* ) m_editDlg ) );
- } else {
- p = m_konsolePart;
- }
-
- if ( !p )
- throw "could not create konsole-part";
-
- p->widget() ->setFocusPolicy( Qt::WheelFocus );
- p->widget() ->setFocus();
-
- if ( QFrame * frame = qobject_cast<QFrame*>( p->widget() ) )
- frame->setFrameStyle( QFrame::Panel | QFrame::Sunken );
-
- m_konsolePart = p;
-
- TerminalInterface* terminal = static_cast<TerminalInterface*>( p->qt_metacast( "TerminalInterface" ) );
- if ( !terminal )
- throw "could not get terminal-interface";
-
- m_editPatch.konsoleDock->show();
- m_editPatch.konsoleDock->setWidget( p->widget() );
- p->widget() ->show();
- m_editPatch.konsoleDock->showNormal();
-
- m_reversed = false;
-
- QString params = ~patch->patchParams( reverse );
-
- bool hadFile = params.indexOf( "$FILE" ) != -1;
- //params.replace( "$FILE", fileName );
-
- if ( !hadFile ) {
- if ( patch->patchTool( reverse ) == "patch" )
- params += " -i";
- params += " " + fileName;
- }
- QString command = "FILE=" + fileName + " " + ~patch->patchTool( reverse ) + " " + params + " && echo " + QString( terminalSuccessMarker ) + "\n";
-
- ///@todo not working with remove directories
- terminal->showShellInDir( TeamworkFolderManager::workspaceDirectory().toLocalFile() );
-
- if ( reverse )
- m_actionState = LocalPatchSource::NotApplied;
- else
- m_actionState = LocalPatchSource::Applied;
-
- connect( p, SIGNAL( receivedData( const QString& ) ), this, SLOT( receivedTerminalData( const QString& ) ) );
-
- patch->state = LocalPatchSource::Unknown;
-
- m_lastTerminalData.clear();
- terminal->sendInput( command );
- //terminal->startProgram( ~patch->patchTool( reverse ), l );
-
- fillEditFromPatch();
- } catch ( const QString & str ) {
- err() << QString( "error in applyPatch(reverse = %1): %2" ).arg( reverse ).arg( str );
- } catch ( const char * str ) {
- err() << QString( "error in applyPatch(reverse = %1): %2" ).arg( reverse ).arg( str );
- }
-}
-
-///This ugly hacking is necerssary because the status-output cannot be retrieved anymore
-void EditPatch::receivedTerminalData( const QString& s ) {
- m_lastDataTime = QTime::currentTime();
- m_lastTerminalData += s;
- if ( m_lastTerminalData.contains( reversedMarker ) )
- m_reversed = true;
-
- if ( m_lastTerminalData.contains( terminalSuccessMarker ) ) {
- m_lastTerminalData.replace( "echo " + terminalSuccessMarker, "" );
- if ( m_lastTerminalData.contains( terminalSuccessMarker ) ) {
- LocalPatchSourcePointer::Locked l = patchFromEdit();
- if ( !l )
- return ;
- m_editPatch.konsoleDock->hide();
- if ( m_reversed ) {
- if ( m_actionState == LocalPatchSource::Applied )
- m_actionState = LocalPatchSource::NotApplied;
- else if ( m_actionState == LocalPatchSource::NotApplied )
- m_actionState = LocalPatchSource::Applied;
- }
- l->state = m_actionState;
- fillEditFromPatch();
- emit stateChanged( this );
- }
- }
-
- m_lastTerminalData = m_lastTerminalData.right( terminalSuccessMarker.length() + reversedMarker.length() );
-}
-
-void EditPatch::nextHunk() {
- updateKompareModel();
- seekHunk( true, m_isSource );
-}
-
-void EditPatch::prevHunk() {
- updateKompareModel();
- seekHunk( false, m_isSource );
-}
-
-void EditPatch::seekHunk( bool forwards, bool isSource, const QString& fileName ) {
- try {
- QModelIndexList il = m_editPatch.filesList->selectionModel() ->selectedIndexes();
- if ( il.isEmpty() )
- throw "selection is empty";
- if ( !m_modelList.get() )
- throw "no model";
-
- for ( QModelIndexList::iterator it = il.begin(); it != il.end(); ++it ) {
- QVariant v = m_filesModel->data( *it, Qt::UserRole );
- if ( !v.canConvert<const Diff2::DiffModel*>() )
- continue;
- const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
- if ( !model || !model->differences() )
- continue;
-
- KUrl file = TeamworkFolderManager::workspaceDirectory();
- if ( isSource ) {
- file.addPath( model->sourcePath() );
- file.addPath( model->sourceFile() );
- } else {
- file.addPath( model->destinationPath() );
- file.addPath( model->destinationFile() );
- }
- if ( !fileName.isEmpty() && fileName != file.toLocalFile() )
- continue;
-
- //out( Logger::Debug ) << "highlighting" << file.toLocalFile();
-
- IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( file );
-
- if ( doc ) {
- KDevTeamworkPlugin::staticDocumentController()->activateDocument( doc );
- if ( doc->textDocument() ) {
- KTextEditor::View * v = doc->textDocument() ->activeView();
- int bestLine = -1;
- if ( v ) {
- KTextEditor::Cursor c = v->cursorPosition();
- for ( Diff2::DifferenceList::const_iterator it = model->differences() ->begin(); it != model->differences() ->end(); ++it ) {
- int line;
- Diff2::Difference* diff = *it;
- if ( isSource )
- line = diff->sourceLineNumber();
- else
- line = diff->destinationLineNumber();
- if ( line > 0 )
- line -= 1;
-
- if ( forwards ) {
- if ( line > c.line() && ( bestLine == -1 || line < bestLine ) )
- bestLine = line;
- } else {
- if ( line < c.line() && ( bestLine == -1 || line > bestLine ) )
- bestLine = line;
- }
- }
- if ( bestLine != -1 ) {
- v->setCursorPosition( KTextEditor::Cursor( bestLine, 0 ) );
- return ;
- }
- }
- }
- }
- }
-
- } catch ( const QString & str ) {
- err() << "seekHunk():" << str;
- } catch ( const char * str ) {
- err() << "seekHunk():" << str;
- }
- out() << "no matching hunk found";
-}
-
-void EditPatch::highlightFile() {
- updateKompareModel();
- try {
- QModelIndexList il = m_editPatch.filesList->selectionModel() ->selectedIndexes();
- if ( il.isEmpty() )
- throw "selection is empty";
- if ( !m_modelList.get() )
- throw "no model";
-
- for ( QModelIndexList::iterator it = il.begin(); it != il.end(); ++it ) {
- QVariant v = m_filesModel->data( *it, Qt::UserRole );
- if ( !v.canConvert<const Diff2::DiffModel*>() )
- continue;
- const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
- if ( !model )
- continue;
-
- KUrl file = TeamworkFolderManager::workspaceDirectory();
- if ( m_isSource ) {
- file.addPath( model->sourcePath() );
- file.addPath( model->sourceFile() );
- } else {
- file.addPath( model->destinationPath() );
- file.addPath( model->destinationFile() );
- }
-
- out( Logger::Debug ) << "highlighting" << file.toLocalFile();
-
- IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( file );
-
- if ( !doc ) {
- doc = KDevTeamworkPlugin::staticDocumentController() ->openDocument( file, KTextEditor::Cursor() );
- seekHunk( true, m_isSource, file.toLocalFile() );
- }
- removeHighlighting( file.toLocalFile() );
-
- m_highlighters[ file.toLocalFile() ] = new DocumentHighlighter( model, doc, m_isSource );
- }
-
- } catch ( const QString & str ) {
- err() << "highlightFile():" << str;
- } catch ( const char * str ) {
- err() << "highlightFile():" << str;
- }
-}
-
-void EditPatch::fileDoubleClicked( const QModelIndex& i ) {
- try {
- if ( !m_modelList.get() )
- throw "no model";
- QVariant v = m_filesModel->data( i, Qt::UserRole );
- if ( !v.canConvert<const Diff2::DiffModel*>() )
- throw "cannot convert";
- const Diff2::DiffModel* model = v.value<const Diff2::DiffModel*>();
- if ( !model )
- throw "bad model-value";
-
- KUrl file = TeamworkFolderManager::workspaceDirectory();
- if ( m_isSource ) {
- file.addPath( model->sourcePath() );
- file.addPath( model->sourceFile() );
- } else {
- file.addPath( model->destinationPath() );
- file.addPath( model->destinationFile() );
- }
-
- out( Logger::Debug ) << "opening" << file.toLocalFile();
-
- KDevTeamworkPlugin::staticDocumentController() ->openDocument( file, KTextEditor::Cursor() );
-
- seekHunk( true, m_isSource, file.toLocalFile() );
- } catch ( const QString & str ) {
- err() << "fileDoubleClicked():" << str;
- } catch ( const char * str ) {
- err() << "fileDoubleClicked():" << str;
- }
-}
-
-void EditPatch::fileSelectionChanged() {
- QModelIndexList i = m_editPatch.filesList->selectionModel() ->selectedIndexes();
- m_editPatch.nextHunk->setEnabled( false );
- m_editPatch.previousHunk->setEnabled( false );
- m_editPatch.highlightFiles->setEnabled( false );
- if ( !m_modelList.get() )
- return ;
- for ( QModelIndexList::iterator it = i.begin(); it != i.end(); ++it ) {
- QVariant v = m_filesModel->data( *it, Qt::UserRole );
- if ( v.canConvert<const Diff2::DiffModel*>() ) {
- const Diff2::DiffModel * model = v.value<const Diff2::DiffModel*>();
- if ( model ) {
- if ( model->differenceCount() != 0 ) {
- m_editPatch.nextHunk->setEnabled( true );
- m_editPatch.previousHunk->setEnabled( true );
- m_editPatch.highlightFiles->setEnabled( true );
- }
- }
- }
- }
-}
-
-DocumentHighlighter::DocumentHighlighter( const Diff2::DiffModel* model, IDocument* kdoc, bool isSource ) throw( QString ) : m_doc( kdoc ) {
-// connect( kdoc, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
- connect( kdoc->textDocument(), SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
- connect( model, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
-
- KTextEditor::Document* doc = kdoc->textDocument();
- if ( doc->lines() == 0 )
- return ;
- if( doc->activeView() == 0 ) return;
-
- if ( !model->differences() )
- return ;
- KTextEditor::SmartInterface* smart = dynamic_cast<KTextEditor::SmartInterface*>( doc );
- if ( !smart )
- throw QString( "no smart-interface" );
-
- QMutexLocker lock(smart->smartMutex());
-
- KTextEditor::SmartRange* topRange = smart->newSmartRange(doc->documentRange(), 0, KTextEditor::SmartRange::ExpandLeft | KTextEditor::SmartRange::ExpandRight);
-
- for ( Diff2::DifferenceList::const_iterator it = model->differences() ->begin(); it != model->differences() ->end(); ++it ) {
- Diff2::Difference* diff = *it;
- int line, lineCount;
- if ( isSource ) {
- line = diff->sourceLineNumber();
- lineCount = diff->sourceLineCount();
- } else {
- line = diff->destinationLineNumber();
- lineCount = diff->destinationLineCount();
- }
- if ( line > 0 )
- line -= 1;
-
- KTextEditor::Cursor c( line, 0 );
- KTextEditor::Cursor endC( line + lineCount, 0 );
- if ( doc->lines() <= c.line() )
- c.setLine( doc->lines() - 1 );
- if ( doc->lines() <= endC.line() )
- endC.setLine( doc->lines() - 1 );
- endC.setColumn( doc->lineLength( endC.line() ) ) ;
-
- if ( endC.isValid() && c.isValid() ) {
- KTextEditor::SmartRange * r = smart->newSmartRange( c, endC );
- r->setParentRange(topRange);
- KSharedPtr<KTextEditor::Attribute> t( new KTextEditor::Attribute() );
-
- t->setProperty( QTextFormat::BackgroundBrush, QBrush( QColor( 200, 200, 255 ) ) );
- r->setAttribute( t );
- }
- }
-
- m_ranges << topRange;
-
- smart->addHighlightToDocument(topRange);
-}
-
-DocumentHighlighter::~DocumentHighlighter() {
- for ( QList<KTextEditor::SmartRange*>::iterator it = m_ranges.begin(); it != m_ranges.end(); ++it )
- delete *it;
-
- m_ranges.clear();
-}
-
-IDocument* DocumentHighlighter::doc() {
- return m_doc;
-}
-
-void DocumentHighlighter::documentDestroyed() {
- m_ranges.clear();
-}
-
-void EditPatch::removeHighlighting( const QString& file ) {
- if ( file.isEmpty() ) {
- ///Remove all highlighting
- for ( HighlightMap::iterator it = m_highlighters.begin(); it != m_highlighters.end(); ++it ) {
- delete *it;
- }
- m_highlighters.clear();
- } else {
- HighlightMap::iterator it = m_highlighters.find( file );
- if ( it != m_highlighters.end() ) {
- delete * it;
- m_highlighters.erase( it );
- }
- }
-}
-
-
-void EditPatch::updateKompareModel() {
- try {
- LocalPatchSourcePointer::Locked l = m_editingPatch;
- if ( l ) {
- if ( l->state != LocalPatchSource::Applied )
- return ;
- if ( l->type != "text/x-diff" )
- return ;
- if ( l->command == ~m_lastModelCommand && l->filename == ~m_lastModelFile && m_modelList.get() )
- return ; ///We already have the correct model
- m_lastModelCommand = ~l->command;
- m_lastModelFile = ~l->filename;
- }
-
-
- m_modelList.reset( 0 );
- qRegisterMetaType<const Diff2::DiffModel*>( "const Diff2::DiffModel*" );
- if ( m_diffSettings )
- delete m_diffSettings;
- m_diffSettings = new DiffSettings( m_editDlg );
- m_kompareInfo.reset( new Kompare::Info() );
- removeHighlighting();
- m_modelList.reset( new Diff2::KompareModelList( m_diffSettings, *m_kompareInfo, ( QObject* ) this ) );
- KUrl diffFile = getPatchFile( true );
- if ( diffFile.isEmpty() )
- return ;
- try {
- ///@todo does not work with remote URLs
- if ( !m_modelList->openDirAndDiff( TeamworkFolderManager::workspaceDirectory().toLocalFile(), diffFile.toLocalFile() ) )
- throw "could not open diff " + diffFile.toLocalFile();
- } catch ( const QString & str ) {
- throw;
- } catch ( ... ) {
- throw QString( "lib/libdiff2 crashed, memory may be corrupted. Please restart kdevelop." );
- }
- m_filesModel->clear();
- m_filesModel->insertColumns( 0, 1 );
-
- const Diff2::DiffModelList* models = m_modelList->models();
- if ( !models )
- throw "no diff-models";
- Diff2::DiffModelList::const_iterator it = models->begin();
- while ( it != models->end() ) {
- Diff2::DifferenceList * diffs = ( *it ) ->differences();
- int cnt = 0;
- if ( diffs )
- cnt = diffs->count();
-
- KUrl file;
- if ( m_isSource ) {
- file.addPath( ( *it ) ->sourcePath() );
- file.addPath( ( *it ) ->sourceFile() );
- } else {
- file.addPath( ( *it ) ->destinationPath() );
- file.addPath( ( *it ) ->destinationFile() );
- }
-
- m_filesModel->insertRow( 0 );
- QModelIndex i = m_filesModel->index( 0, 0 );
- if ( i.isValid() ) {
- //m_filesModel->setData( i, file, Qt::DisplayRole );
- m_filesModel->setData( i, QString( "%1 (%2 hunks)" ).arg( file.toLocalFile() ).arg( cnt ), Qt::DisplayRole );
- QVariant v;
- v.setValue<const Diff2::DiffModel*>( *it );
- m_filesModel->setData( i, v, Qt::UserRole );
- }
- ++it;
- }
- fileSelectionChanged();
- return ;
- } catch ( const QString & str ) {
- err() << "updateKompareModel:" << str;
- } catch ( const char * str ) {
- err() << "updateKompareModel:" << str;
- }
- m_modelList.reset( 0 );
- delete m_diffSettings;
- m_kompareInfo.reset( 0 );
-}
-
-#include "editpatch.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/editpatch.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.h (nonexistent)
@@ -1,100 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef MESSAGEHISTORY_H
-#define MESSAGEHISTORY_H
-
-#include "ui_kdevteamwork_messagehistory.h"
-#include <QList>
-#include <QObject>
-#include <QWidget>
-#include "kdevteamwork_user.h"
-#include "safelogger.h"
-
-namespace Teamwork {
- class Logger;
- typedef SafeSharedPtr<Logger> LoggerPointer;
-}
-
-class KDialog;
-class MessageManager;
-class KDevTeamworkTextMessage;
-
-typedef SafeSharedPtr<KDevTeamworkTextMessage, MessageSerialization> HistoryMessagePointer;
-
-class QStandardItemModel;
-
-class GuiMessageHistory : public QObject, public SafeLogger {
- Q_OBJECT
- public:
- typedef QList<KDevTeamworkUserPointer> UserList;
- typedef QMap<KDevTeamworkUserPointer, bool> UserSet;
- ///Empty list means All Users
- explicit GuiMessageHistory( MessageManager* manager, UserList users = UserList(), const QString& context = "" );
- ~GuiMessageHistory();
-
- public slots:
- void slotAllMessages();
- void slotAllDevelopers();
- void slotNewMessage( const HistoryMessagePointer& );
- void slotUserStateChanged( const KDevTeamworkUserPointer& user );
- void slotSelectionChanged();
- void slotUpdateMessages();
- void slotExit();
- void messageItemClicked( const QModelIndex& index );
- void updateMessageUserIcons();
-
- ///Filters:
- void typeFilterChanged( int index );
- void contextFilterChanged( int index );
-
- private:
- bool fitMessageDate( const HistoryMessagePointer& msg );
- void showMessage( const HistoryMessagePointer& msg );
- void fillDeveloperList();
- void updateUserIcon( const KDevTeamworkUserPointer& user );
- UserSet selectedUsers();
- void fillMessages();
-
- void clearFilters();
- void applyFilters( int firstN = 0 );
-
- virtual std::string logPrefix() {
- return "GuiMessageHistory: ";
- }
-
- void clearUsers();
- void addUser( const KDevTeamworkUserPointer& user );
-
- bool m_allUsers;
- UserSet m_users;
- MessageManager* m_manager;
- Ui_MessageHistory m_widgetData;
- QStandardItemModel* m_developersModel;
- QStandardItemModel* m_messagesModel;
- QTimer* m_updateTimer;
- QTimer* m_userIconUpdateTimer;
- KDialog* m_dialog;
- QString m_defaultContext;
-
- enum TableColumns {
- TimeColumn = 0,
- TypeColumn,
- UserColumn,
- TextColumn,
- ColumnCount
- };
-
- QList<KDevTeamworkUserPointer> m_changedUsers;
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/guimessagehistory.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h (nonexistent)
@@ -1,132 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGEHISTORYMANAGER_H
-#define MESSAGEHISTORYMANAGER_H
-
-
-#include <QList>
-#include <QMap>
-
-#include <klockfile.h>
-#include <kurl.h>
-
-#include "lib/network/user.h"
-#include "kdevteamwork_messages.h"
-#include "teamworkfwd.h"
-#include <nvp.h>
-
-
-class QTimer;
-class KDevTeamworkTextMessage;
-
-typedef SafeSharedPtr<KDevTeamworkTextMessage, MessageSerialization> HistoryMessagePointer;
-
-struct HistoryMessageDesc
-{
- UserIdentity user;
- bool isIncoming;
- HistoryMessagePointer message;
-
- HistoryMessageDesc();
-
- HistoryMessageDesc( const HistoryMessagePointer& msg );
-
- template<class Archive>
- void load( Archive& arch, const uint /*version*/ ) {
- arch & NVP( user );
- arch & NVP( isIncoming );
- arch & NVP( message );
- HistoryMessagePointer::Locked l = message;
- if( l ) {
- l->info().setIsIncoming( isIncoming );
- }
- }
-
- template<class Archive>
- void save( Archive& arch, const uint /*version*/ ) const {
- arch & NVP( user );
- arch & NVP( isIncoming );
- arch & NVP( message );
- }
-
- operator bool() {
- return (bool) message;
- }
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-};
-
-struct HistoryGroupLocation {
- string fileName;
- uint offset;
-
- template<class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & fileName;
- arch & offset;
- }
-};
-
-
-class MessageHistoryManager : public QObject {
- Q_OBJECT
- public:
- typedef QMap<Teamwork::UserIdentity, bool > UserSet;
-
-
- MessageHistoryManager( Teamwork::LoggerPointer logger );
- ~MessageHistoryManager();
-
- void addMessage( KDevTeamworkTextMessage* msg );
-
- ///Returns all matching messages. If user is zero, returns messages from/to all users. This is slow(always reads the messages from disk)
- QList<HistoryMessagePointer> getMessages( const KDevTeamworkClientPointer& client, const QDate& from = QDate(), const QDate& until = QDate(), UserSet users = UserSet() );
-
- HistoryMessagePointer getMessageFromId( Teamwork::UniqueMessageId id, const KDevTeamworkClientPointer& client );
-
- signals:
- void newMessage( HistoryMessagePointer msg ); ///This is emitted whenever a new message should be added to the history
-
- private slots:
- void writePending();
-
- private:
- HistoryMessagePointer fillMessageUser( const HistoryMessageDesc& message, const KDevTeamworkClientPointer& client );
-
- QString lockFileName();
-
- QList<HistoryMessagePointer> fillMessageUsers( const QList<HistoryMessageDesc>& messages, const KDevTeamworkClientPointer& client );
- ///Reads out the messages of just one chunk(the messages that follow a single header)
- void readMessages( const QString& file, uint offset, QList<HistoryMessageDesc>& messages ) throw(QString);
-
- void readIndex( std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString);
-
- void writeIndex( const std::map<Teamwork::UniqueMessageId, HistoryGroupLocation>& index ) throw( QString);
-
- ///May throw QString
- KUrl directory() throw(QString);
-
- QTimer* m_pendingTimer;
- QList< HistoryMessageDesc > m_pending;
- Teamwork::LoggerPointer m_logger;
- KLockFile::Ptr m_lockFile;
-
- Teamwork::LoggerPrinter out( Teamwork::Logger::Level = Teamwork::Logger::Info );
-
- Teamwork::LoggerPrinter err();
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagehistorymanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h (nonexistent)
@@ -1,103 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGESHOWER_H
-#define MESSAGESHOWER_H
-
-class QWidget;
-class KDevTeamworkTextMessage;
-class KDevTeamwork;
-class KDevTeamworkUser;
-class InDocumentMessage;
-
-#include <QObject>
-#include "ui_kdevteamwork_textmessage.h"
-#include "ui_kdevteamwork_userinfo.h"
-#include <QPointer>
-#include "lib/network/safesharedptr.h"
-#include "kdevteamwork_helpers.h"
-#include "safelogger.h"
-#include "autoconstructpointer.h"
-
-
-class MessageSerialization;
-
-class InDocumentMessageShowerData;
-
-namespace Teamwork {
-class MessageInterface;
-typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
-}
-
-using namespace Teamwork;
-
-class KDevTeamworkMessageShower : public QObject {
- Q_OBJECT
- public:
- KDevTeamworkMessageShower( KDevTeamworkTextMessage* msg, QWidget* widget, KDevTeamwork* teamwork );
- public slots:
- virtual void isReplyToButton();
- virtual void menuButton();
- virtual void historyButton();
- virtual void userStateChanged();
- virtual void messageUpdated( const MessagePointer& msg );
- protected:
- SafeSharedPtr<KDevTeamworkTextMessage> m_message;
- QWidget* m_widget;
- Ui_TextMessageShower m_widgetData;
- QPointer<KDevTeamwork> m_teamwork;
-
- virtual void fillData();
-
- private:
- void fill();
-};
-
-
-class KDevTeamworkUserInfoShower : public QObject {
- Q_OBJECT
- public:
- KDevTeamworkUserInfoShower( KDevTeamworkUser* user, QWidget* widget, KDevTeamwork* teamwork );
- public slots:
- virtual void menuButton();
- virtual void historyButton();
- virtual void userStateChanged();
- private:
- void setIp();
- void setStatus();
- void setIcon();
-
- SafeSharedPtr< KDevTeamworkUser > m_user;
- QWidget* m_widget;
- Ui_UserInfo m_widgetData;
- QPointer<KDevTeamwork> m_teamwork;
-};
-
-class InDocumentMessageShower : public KDevTeamworkMessageShower, private SafeLogger {
- Q_OBJECT
- public:
- InDocumentMessageShower( InDocumentMessage* msg, QWidget* widget, KDevTeamwork* teamwork );
- public slots:
- void fileClicked();
- void contextClicked();
- protected:
-
- virtual void fillData();
- private:
- void fill();
- AutoConstructPointer<InDocumentMessageShowerData> m_data;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messageshower.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/nvp.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/nvp.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/nvp.h (nonexistent)
@@ -1,26 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef NVP_H
-#define NVP_H
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/nvp.hpp>
-
-///NVP means Name-Value-Pair, and is used for serialization into Xml-Archives
-#undef NVP
-#define NVP(x) BOOST_SERIALIZATION_NVP(x)
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/nvp.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.cpp (nonexistent)
@@ -1,455 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "patchmessage.h"
-#include "lib/network/serialization.h"
-#include <boost/serialization/list.hpp>
-#include <boost/serialization/string.hpp>
-#include <boost/serialization/vector.hpp>
-#include <memory>
-
-#include <k3process.h>
-#include <kurl.h>
-#include <kmimetype.h>
-#include <memory.h>
-#include <kio/netaccess.h>
-#include <kio/job.h>
-#include <kio/jobclasses.h>
-#include "teamworkfoldermanager.h"
-
-#include "kdevteamwork.h"
-
-#include "kdevteamwork_helpers.h"
-
-PatchData::PatchData( const LocalPatchSourcePointer& p, LoggerPointer logg ) : m_patch( p ), logger( logg ), deserialized( false ), finished( false ), isBinary_( false ) {
- projectDir = TeamworkFolderManager::workspaceDirectory();
-}
-
-LocalPatchSourcePointer PatchData::patch() {
- return m_patch;
-}
-
-PatchesListMessage::PatchesListMessage( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) {
- serial( arch );
-}
-
-void PatchesListMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-
-uint LocalPatchSource::patchDepth() const {
- QString cmd = ~applyCommand;
- int i = cmd.indexOf( "-p" );
- if( i == -1 ) return 0;
- if( i+1 >= cmd.length() ) return 0;
- QString f = cmd.mid( i+2 ).trimmed();
- if( f.isEmpty() ) return 0;
- f.truncate( 1 );
- bool b = false;
- uint ret = f.toUInt( &b );
- if( !b ) return 0;
- else
- return ret;
-}
-
-string LocalPatchSource::patchTool( bool reverse ) const {
- QString cmd;
- if( reverse )
- cmd = (~unApplyCommand).trimmed();
-
- if( cmd.isEmpty() )
- cmd = (~applyCommand).trimmed();
-
- if( cmd[0] == '-' ) return "patch";
- int firstWhite = cmd.indexOf( " " );
- QString ret;
- if( firstWhite == -1 )
- ret = cmd;
- else
- ret = cmd.mid( 0, firstWhite );
-
- ret = ret.trimmed();
- if( ret.isEmpty() )
- return "patch";
- else
- return ~ret;
-}
-
-string LocalPatchSource::patchParams( bool reverse ) const {
-
- QString cmd;
- bool normalCommand = false;
- if( reverse )
- cmd = (~unApplyCommand).trimmed();
- if( cmd.isEmpty() ) {
- cmd = (~applyCommand).trimmed();
- normalCommand = true;
- }
- if( cmd.isEmpty() )
- return string("-p0 --backup") + (reverse ? " --reverse" : "");
- else
- if( reverse && normalCommand )
- cmd += " --reverse";
-
- if( cmd.startsWith( ~patchTool(reverse) ) )
- return ~cmd.mid( patchTool(reverse).length() ).trimmed();
- else
- return ~cmd.trimmed();
-}
-
-/*
-void LocalPatchSource::setMimeType( KMimeType::Ptr mimeType ) {
- QByteArray array;
- {
- QDataStream str( &array, QIODevice::WriteOnly );
- mimeType->save( str );
- }
- mimetype.resize( array.count() );
- memcpy( &( mimetype[ 0 ] ), array.data(), array.count() );
-}
-
-KMimeType::Ptr LocalPatchSource::getMimeType() {
- QByteArray array( &( mimetype[ 0 ] ), mimetype.size() );
- QDataStream str( &array, QIODevice::ReadOnly );
- return KMimeType::Ptr( new KMimeType( str, 0 ) );
-}*/
-
-class AbstractPatchArchiver {
- virtual void put( QByteArray& data );
- virtual void put( int i );
- virtual ~AbstractPatchArchiver() {
- };
- };
- /*
-template<class Archive>
-class PatchArchiver {
- Archive& arch;
- PatchArchiver( Archive& a ) : arch(a) {
- }
-
- virtual void put( QByteArray& data ) {
- arch & data;
- }
-
- virtual void put( int i ) {
- arch & i;
- }
- };
- */
-void PatchData::transferData( KIO::Job* /*job*/, const QByteArray& data ) {
- std::vector<char> vec;
- vec.resize( data.size() ); ///a serialization-function for QByteArray should be written instead of moving the data through std::vector
- memcpy( &(vec[0]), data.data(), data.size() );
- EntryType v = Vector;
- *currentArchive << v;
- *currentArchive & vec;
-}
-
-void PatchData::transferFinished() {
- finished = true;
-}
-
-void PatchData::transferCanceled() {
- errored = true;
-}
-
-//template<class Arch>
-void PatchData::saveInternal( OutArchive& arch, const uint /*version*/ ) {
- auto_ptr<PatchDataReceiver> rec( new PatchDataReceiver( this ) );
-
- if ( !m_patch || deserialized )
- throw CannotReserialize(); ///This type of Message can only be serialized after being constructed with a local patch-source
- try {
- arch & m_patch;
- currentArchive = &arch;
- errored = false;
- finished = false;
- if ( !m_patch )
- throw "invalid patch-source";
- LocalPatchSourcePointer::Locked lpatch = m_patch;
- if ( !lpatch )
- throw "patch-source could not be locked";
-
- if ( !lpatch->filename.empty() ) {
- ///Load a file
- isBinary_ = true;
- EntryType v = BinaryHeader;
- arch << v;
- KUrl url = TeamworkFolderManager::teamworkAbsolute( ~lpatch->filename );
- log( Logger::Debug ) << "opening file for sending:" << ~url.prettyUrl();
-
- //(QWidget*)KDevApi::self()->mainWindow()->main()
- if ( !KIO::NetAccess::exists( url, KIO::NetAccess::SourceSide, 0 ) )
- throw ( "the file \"" + url.prettyUrl() + "\" seems not to exist, or is not accessible" );
-
- auto_ptr<KIO::TransferJob> transfer( KIO::get
- ( url, KIO::NoReload, KIO::HideProgressInfo ) );
- if ( !transfer.get() )
- throw ( "could not create transfer-job for reading " + url.prettyUrl() );
- //transfer->setWindow( (QWidget*)KDevApi::self()->mainWindow()->main() );
- QObject::connect( &( *transfer ), SIGNAL( data( KIO::Job *, const QByteArray & ) ), &( *rec ), SLOT( transferData( KIO::Job*, const QByteArray& ) ), Qt::DirectConnection );
- QObject::connect( &( *transfer ), SIGNAL( result( KJob * ) ), &( *rec ), SLOT( transferFinished( KJob* ) ), Qt::DirectConnection );
- if ( !transfer->exec() )
- errored = true;
-
- QString errorText;
- int error = transfer->error();
- if ( error )
- errorText = transfer->errorString();
-
- transfer->kill();
-
- if ( error )
- throw ( "failed reading the file \"" + url.prettyUrl() + "\" reason: \"" + errorText + "\"" );
-
- EntryType t = End;
- arch << t;
-
- } else if ( !lpatch->command.empty() ) {
- ///Execute a command and send it's output
- isBinary_ = false;
- EntryType v = TextHeader;
- arch << v;
- QStringList args = splitArgs( ~lpatch->command );
- {
- LoggerPrinter l = log() << "calling process: \"" << lpatch->command << "\" params: ";
- for ( QStringList::iterator it = args.begin(); it != args.end(); ++it )
- l << "\"" << ~( *it ) << "\"";
- l << "in folder" << ~projectDir.toLocalFile();
- }
-
- auto_ptr<K3Process> proc( new K3Process() );
- QObject::connect( &( *proc ), SIGNAL( receivedStdout( K3Process*, char*, int ) ), &( *rec ), SLOT( receivedStdout( K3Process*, char*, int ) ), Qt::DirectConnection );
-
- proc->setPriority( K3Process::PrioLowest );
- proc->setWorkingDirectory( projectDir.toLocalFile() );
- *proc << args;
- if ( !proc->start( K3Process::Block, K3Process::Stdout ) )
- throw "the process could not be started";
-
- if ( !proc->normalExit() )
- throw "process did not exit normally";
- if ( proc->exitStatus() != 0 )
- throw QString( "process returned with exit-status " + QString::number( proc->exitStatus() ) );
-
- log() << lpatch->command << ": successful";
-
- EntryType t = End;
- arch << t;
- } else {
- throw "the patch-data cannot be sent: missing command or url";
- }
- } catch ( const char * str ) {
- currentArchive = 0;
- throw NonFatalSerializationError( ( string( "PatchData::serialize: " ) + str ).c_str() );
- } catch( QString str ) {
- currentArchive = 0;
- throw NonFatalSerializationError( ( string( "PatchData::serialize: " ) + str.toUtf8().data() ).c_str() );
- }
- currentArchive = 0;
-}
-
-//template<class Arch>
-void PatchData::load( InArchive& arch, const uint /*version*/ ) {
- deserialized = true;
- //cout << "got patch: ";
-
- arch & m_patch;
-
- EntryType t;
- arch >> t;
- if ( t == BinaryHeader ) {
- isBinary_ = true;
- while ( 1 ) {
- arch >> t;
- if ( t == Vector ) {
- vector<char> vec;
- arch & vec;
- //cout << str;
- m_data.append( QByteArray( &( vec[ 0 ] ), vec.size() ) );
- } else {
- if ( t != End )
- throw NonFatalSerializationError( "stream-error in PatchData(Text)" );
- else
- break;
- }
- }
- } else {
- isBinary_ = false;
- while ( 1 ) {
- arch >> t;
- if ( t == Text ) {
- string str;
- arch & str;
- //cout << str;
- m_data.append( str.c_str() );
- } else {
- if ( t != End )
- throw NonFatalSerializationError( "stream-error in PatchData(Text)" );
- else
- break;
- }
- }
- }
-}
-
-/*
-template void PatchData::load( boost::archive::polymorphic_iarchive& arch, const uint );
-
-template void PatchData::saveInternal( boost::archive::polymorphic_oarchive& arch, const uint );
-
-template void PatchData::load( boost::archive::text_iarchive& arch, const uint );
-
-template void PatchData::saveInternal( boost::archive::text_oarchive& arch, const uint );
-
-template void PatchData::load( boost::archive::binary_iarchive& arch, const uint );
-
-template void PatchData::saveInternal( boost::archive::binary_oarchive& arch, const uint );
-*/
-
-void PatchData::receivedStdout( K3Process */*proc*/, char *buffer, int /*buflen*/ ) {
- if ( !currentArchive || errored ) {
- if ( !errored ) {
- log() << "received unexpected stdout-data";
- errored = true;
- }
- return ;
- }
- EntryType t = Text;
- *currentArchive << t;
- string str( buffer );
- *currentArchive << str;
-}
-
-bool PatchData::isBinary() {
- return isBinary_;
-}
-
-const QByteArray& PatchData::data() {
- return m_data;
-}
-
-QStringList splitArgs( const QString& str ) {
- QStringList ret;
- QString current = str;
- int pos = 0;
- while ( ( pos = current.indexOf( ' ', pos ) ) != -1 ) {
- if ( current[ 0 ] == '"' ) {
- int end = current.indexOf( '"' );
- if ( end > pos )
- pos = end;
- }
- QString s = current.left( pos );
- if ( s.length() > 0 )
- ret << s;
- current = current.mid( pos + 1 );
- pos = 0;
- }
- if ( current.length() )
- ret << current;
- return ret;
-}
-
-PatchRequestData::PatchRequestData( const LocalPatchSourcePointer& id, KDevTeamwork* tw, RequestType req ) : request_( id ), requestType_( req ), stat( Waiting ), emitter( new SafeTeamworkEmitter( tw ) ) {
- LocalPatchSourcePointer::Locked l = id;
- if( l ) {
- ident_ = l->identity();
- }
-}
-
-PatchDataReceiver::PatchDataReceiver( PatchData* d ) : data( d ) {}
-void PatchDataReceiver::receivedStdout( K3Process *proc, char *buffer, int buflen ) {
- data->receivedStdout( proc, buffer, buflen );
-}
-
-void PatchDataReceiver::transferData( KIO::Job* job, const QByteArray& array ) {
- data->transferData( job, array );
-}
-
-void PatchDataReceiver::transferFinished( KJob */*job*/ ) {
- data->transferFinished();
-}
-
-QString PatchRequestData::messageText() const {
- return "patch-request: " + ~patchDesc();
-}
-
-
-QIcon PatchRequestData::messageIcon() const {
- IconCache & cache( *IconCache::instance() );
-
- if ( !selfMessage() ->info().isIncoming() ) {
- return cache( "generalrequest_out" );
- if ( stat == Denied ) {
- return cache( "generalrequest_out_denied" );
- } else if ( stat == Accepted ) {
- return cache( "generalrequest_out_accepted" );
- } else if ( stat == Unknown ) {
- return cache( "unknown" );
- } else {
- return cache( "generalrequest_out" );
- }
- } else {
- if ( stat == Denied ) {
- return cache( "generalrequest_in_denied" );
- } else if ( stat == Accepted ) {
- return cache( "generalrequest_in_accepted" );
- } else if ( stat == Unknown ) {
- return cache( "unknown" );
- } else {
- return cache( "generalrequest_in" );
- }
- }
-}
-
-PatchRequestMessage* PatchRequestData::selfMessage() {
- return dynamic_cast<PatchRequestMessage*>( this );
-}
-
-const PatchRequestMessage* PatchRequestData::selfMessage() const {
- return dynamic_cast<const PatchRequestMessage*>( this );
-}
-
-MessageInterface::ReplyResult PatchRequestMessage::gotReply( const MessagePointer& p ) {
- KDevSystemMessagePointer::Locked lmessage = ( ( MessagePointer ) p ).cast<KDevSystemMessage>();
-
- if ( lmessage ) {
- switch ( lmessage->message() ) {
- case KDevSystemMessage::ActionFailed:
- stat = Failed;
- break;
- case KDevSystemMessage::ActionSuccessful:
- stat = Accepted;
- break;
- case KDevSystemMessage::ActionDenied:
- stat = Denied;
- break;
- default:
- stat = Unknown;
- break;
- }
- }
-
- if ( emitter.data() )
- emitter->updateMessageInfo( this );
-
- return ReplyResult();
-}
-
-PatchRequestData::~PatchRequestData() {
-}
-
-#include "patchmessage.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchmessage.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfwd.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfwd.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfwd.h (nonexistent)
@@ -1,65 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef TEAMWORKFWD_H
-#define TEAMWORKFWD_H
-
-#include "lib/network/networkfwd.h"
-
-class MessageManager;
-class CollaborationManager;
-class MessageSendManager;
-class PatchesManager;
-class KUrl;
-class KDevTeamworkPlugin;
-class KDevTeamwork;
-class QStandardItemModel;
-class QTimer;
-class QListView;
-class QWidget;
-class QModeIndex;
-class MessageSerialization;
-class BoostSerialization;
-class Ui_List;
-class KDevTeamworkLogger;
-class MessageUserTab;
-class QPersistentModelIndex;
-class TeamworkFolderManager;
-class IconCache;
-class PatchesListMessage;
-class KDevSystemMessage;
-class KDevTeamworkTextMessage;
-class PatchesManagerMessage;
-
-namespace KDevelop {
- class ICore;
- class IDocumentController;
- class IDocument;
-}
-
-class KDevTeamworkUser;
-typedef SafeSharedPtr< KDevTeamworkUser, BoostSerialization > KDevTeamworkUserPointer;
-class KDevTeamworkClient;
-typedef SafeSharedPtr< KDevTeamworkClient > KDevTeamworkClientPointer;
-typedef SafeSharedPtr< KDevTeamworkClient > TeamworkClientPointer;
-
-class ConnectionRequest;
-typedef SafeSharedPtr<ConnectionRequest > ConnectionRequestPointer;
-
-typedef SafeSharedPtr< KDevTeamworkTextMessage > KDevTextMessagePointer;
-typedef SafeSharedPtr< ConnectionRequest > ConnectionRequestPointer;
-typedef SafeSharedPtr< PatchesManagerMessage > PatchesManagerMessagePointer;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfwd.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h (nonexistent)
@@ -1,116 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef VECTORTIMESTAMPEDITOR_H
-#define VECTORTIMESTAMPEDITOR_H
-
-#include "lib/network/sharedptr.h"
-#include <QObject>
-#include "ui_kdevteamwork_vectortimestampwidget.h"
-#include "ui_kdevteamwork_timestampwidget.h"
-#include "safelogger.h"
-#include <QList>
-#include <QDateTime>
-#include <QPointer>
-#include "loglevel.h"
-#include "lib/dynamictext/vectortimestamp.h"
-#include "lib/network/logger.h"
-
-class VectorTimestampEditor;
-class TimestampEditor;
-class QDynamicText;
-class QStandardItemModel;
-class Replacement;
-class BoostSerialization;
-class QVBoxLayout;
-
-typedef SharedPtr< QDynamicText, BoostSerializationNormal > QDynamicTextPointer;
-typedef SharedPtr<TimestampEditor> TimestampEditorPointer;
-typedef SharedPtr< Replacement, BoostSerializationNormal > ReplacementPointer;
-
-
-class TimestampEditor : public QObject, public Shared, public SafeLogger {
- Q_OBJECT
- public:
- TimestampEditor( Teamwork::LoggerPointer logger, VectorTimestampEditor* parent, uint index );
-
- void update();
- private slots:
- void tail();
- void none();
- void enableAll();
- void stampChanged();
- void dateChanged( const QDateTime& );
- void enableChanged( bool );
- private:
- void fillWidgets();
-
- bool trySeekTo( Timestamp s );
-
- ///This returns the currently edited stamp. It the first one not currently applied to the tree.
- Timestamp stamp();
-
- ///This returns the currently edited replacement, or zero.
- ReplacementPointer replacement();
-
- VectorTimestampEditor* m_parent;
- uint m_index;
- Timestamp m_currentStamp;
- Ui_TimestampWidget m_widgets;
- bool m_block;
-};
-
-class VectorTimestampEditorLogger : public Teamwork::Logger {
- public:
- VectorTimestampEditorLogger( VectorTimestampEditor* ed );
- virtual void log( const std::string& str , Level lv );
- private:
- VectorTimestampEditor* m_editor;
-};
-
-///If the parent is destroyed, VectorTimestampEditor is destroyed too. Also it destroys itself if "finish" is clicked, or the dynamic text is destroyed.
-class VectorTimestampEditor : public QObject, public SafeLogger {
- Q_OBJECT
- public:
- ///If embed is false, a new dialog will be created
- VectorTimestampEditor( Teamwork::LoggerPointer logger, QObject* parent, bool embed, QDynamicTextPointer text, bool editable );
- ~VectorTimestampEditor();
-
- QDynamicTextPointer text();
-
- void log( const QString& str, LogLevel level = Info );
-
- private slots:
- void toTailTimestamp();
- void clearLog();
- void finish();
- void textChanged();
- void textDestroyed();
-
- private:
- void fillWidgets();
-
- friend class TimestampEditor;
-
- QDynamicText* m_text;
- bool m_editable;
- bool m_embed;
- Ui_VectorTimestampWidget m_widgets;
- QList< TimestampEditorPointer > m_timestamps;
- QStandardItemModel* m_logModel;
- QVBoxLayout* m_layout;
- QPointer<KDialog> m_dialog; ///Can be zero
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/vectortimestampeditor.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp (nonexistent)
@@ -1,1871 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-///@todo the whole inclusion-structure needs a big cleanup
-
-
-#include "kdevteamwork.h"
-#include <list>
-
-#include <QtGui/QHeaderView>
-#include <QAction>
-#include <QTimer>
-#include <QCursor>
-#include <kdialog.h>
-#include <QPersistentModelIndex>
-#include <QWidget>
-
-#include <kdebug.h>
-#include <klocale.h>
-#include <ktexteditor/document.h>
-#include <kurl.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-
-#include "lib/network/messagetypeset.h"
-#include "lib/network/multisession.h"
-#include "kdevteamworkplugin.h"
-#include "kdevteamwork_messageshower.h"
-#include "kdevteamwork_user.h"
-#include "kdevteamwork_client.h"
-#include "teamworkfoldermanager.h"
-#include "helpers.h"
-#include "kdevteamwork_helpers.h"
-#include "messageusertab.h"
-#include "messagesendmanager.h"
-#include "conversationmanager.h"
-
-///@todo Make most of these managers independent
-#include "collaborationmanager.h"
-#include "messagemanager.h"
-#include "patchesmanager.h"
-
-#include "ui_kdevteamwork_list.h"
-#include "ui_kdevteamwork_interface.h"
-
-using namespace KDevelop;
-
-///@todo make sure fromUtf8(..) and toUtf8(..) is used everywhere, especially in all the messages
-
-const int messageSendTimeout = 3000;
-
-KDevTeamwork* KDevTeamwork::m_self = 0;
-
-//Q_DECLARE_METATYPE( UserPointer )
-Q_DECLARE_METATYPE( QPersistentModelIndex )
-Q_DECLARE_METATYPE( MessagePointer )
-Q_DECLARE_METATYPE( LocalPatchSourcePointer )
-Q_DECLARE_METATYPE( KDevTeamworkUserPointer )
-
-
-LaterDeleter::LaterDeleter( const KDevTeamworkClientPointer& c ) : m_c( c ) {
- deleteLater();
-}
-
-LaterDeleter::~LaterDeleter() {
-}
-
-std::string stringToAddr( const QString& txt );
-int stringToPort( const QString& txt );
-
-QIcon iconFromLevel( LogLevel level ) {
- switch ( level ) {
- case Error:
- return IconCache::getIconStatic( "remove", KIconLoader::Small );
- break;
- case Info:
- return IconCache::getIconStatic( "ok", KIconLoader::Small );
- break;
- case Warning:
- return IconCache::getIconStatic( "fileclose", KIconLoader::Small );
- break;
- case Debug:
- return IconCache::getIconStatic( "log", KIconLoader::Small );
- break;
- default:
- return IconCache::getIconStatic( "unknown", KIconLoader::Small );
- }
-}
-
-///Get rid of this
-void setValueMessage( QVariant& v, const MessagePointer& msg ) {
- v.setValue( msg );
-}
-
-PatchesManager* KDevTeamwork::patchesManager() {
- return m_patchesManager;
-}
-
-Ui::Teamwork& KDevTeamwork::widgets() {
- return *m_widgets;
-}
-
-
-QWidget* KDevTeamwork::widget() {
- return m_widget;
-}
-
-IconCache& KDevTeamwork::icons() {
- return * m_icons;
-}
-
-
-SafeTeamworkEmitter::SafeTeamworkEmitter( KDevTeamwork* tw ) {
- if ( !tw )
- return ;
- connect( this, SIGNAL( signalUpdateMessageInfo( MessagePointer ) ), tw, SLOT( updateMessageInfo( MessagePointer ) ), Qt::QueuedConnection );
-}
-
-template <class Type, class Helper>
-void forEachInModel( QStandardItemModel* model, Helper& hlp, const QModelIndex& parent = QModelIndex() ) {
- for ( int a = 0; a < model->rowCount(); a++ ) {
- QModelIndex i = model->index( a, 0, parent );
- if ( i.isValid() ) {
- QVariant v = model->data( i, Qt::UserRole );
- if ( v.canConvert<Type>() ) {
- Type t = v.value<Type>();
- if ( !hlp( t, i, model ) )
- return ;
- } else {
- ///Some warning-message
- }
- }
- }
-}
-
-template <class Type>
-struct NormalIdentCompare {
- bool operator() ( const Type& lhs, const Type& rhs ) {
- return lhs == rhs;
- }
-};
-
-template <class Type, class Compare>
-struct FindInHelper {
- QModelIndex found;
- Compare compare;
- const Type& searching;
- FindInHelper( const Type& s ) : searching( s ) {}
-
- bool operator () ( const Type& t, QModelIndex i, QStandardItemModel* /*model*/ ) {
- if ( compare( t, searching ) ) {
- found = i;
- return false;
- }
- return true;
- }
-};
-
-template <class Type, class Compare >
-QModelIndex findInModel( QStandardItemModel* model, const Type& t, const QModelIndex& /*parent*/ = QModelIndex() ) {
-
- FindInHelper<Type, Compare> h( t );
-
- forEachInModel<Type>( model, h );
-
- return h.found;
-}
-
-template <class Type >
-QModelIndex findInModelNormal( QStandardItemModel* model, const Type& t, const QModelIndex& parent = QModelIndex() ) {
- return findInModel<Type, NormalIdentCompare<Type> > ( model, t, parent );
-}
-
-UserPointer KDevTeamwork::localUser() {
- ///@todo care about real local user
- return new User( "local" );
-}
-
-#define ADDFILTERMENUITEM(x) { QAction *action = filterMenu->addAction( #x ); action->setData( x ); action->setCheckable( true ); connect( action, SIGNAL( triggered() ), this, SLOT( uiFilterLog() ) ); action->setChecked( m_currentLogFilter & x ); };
-
-#define ADD_FILTER_MENU_ITEM(filterMenu, x, data, checked, slot) { QAction *action = filterMenu->addAction( #x ); action->setData( data ); action->setCheckable( true ); connect( action, SIGNAL( triggered() ), this, SLOT( slot() ) ); action->setChecked( checked ); };
-
-MessageManager* KDevTeamwork::messageManager() {
- return m_messageManager.data();
-}
-
-
-KDevTeamwork::KDevTeamwork( const KUrl& workspaceDirectory, KDevTeamworkPlugin *plugin, QWidget *parent ) :
-m_folderManager( workspaceDirectory ),
-m_logger( new KDevTeamworkLogger( this ) ),
-m_destroyed( false ),
-m_plugin( plugin ),
-m_active( false ),
-m_serverActive( false ),
-m_patchesManager( this ),
-m_collaborationManager( this ),
-m_messageManager( this ),
-m_messageSendManager( *m_widgets ),
-m_currentLogFilter( ( LogLevel ) ( Error | Warning | Info ) )
-{
- m_self = this;
- m_widget = parent;
-
- m_widgets->setupUi( parent );
-
- m_widgets->logFilter->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
- m_widgets->logFilter->setArrowType( Qt::DownArrow );
- m_widgets->logFilter->setPopupMode( QToolButton::InstantPopup );
-
- QMenu *filterMenu = new QMenu( i18n( "Filter" ), m_widgets->logFilter );
-
- ADDFILTERMENUITEM( Debug );
- ADDFILTERMENUITEM( Info );
- ADDFILTERMENUITEM( Warning );
- ADDFILTERMENUITEM( Error );
-
- m_widgets->logFilter->setMenu( filterMenu );
-
- m_widgets->answeringToButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
- m_widgets->answeringToButton->setArrowType( Qt::DownArrow );
- m_widgets->answeringToButton->setPopupMode( QToolButton::InstantPopup );
-
- /*m_messageFilterMenu = new QMenu( i18n( "Filter" ), m_widgets->messageFilter );
-
- m_widgets->messageFilter->setMenu( m_messageFilterMenu );*/
-
- qRegisterMetaType<QPersistentModelIndex> ( "QPersistentModelIndex" );
- qRegisterMetaType<LocalPatchSourcePointer> ( "LocalPatchSourcePointer" );
- qRegisterMetaType<MessagePointer> ( "MessagePointer" );
- qRegisterMetaType<UserPointer> ( "UserPointer" );
-
-
- m_logModel = new QStandardItemModel( 0, 1, m_widgets->logList );
- m_messagesModel = new QStandardItemModel( 0, 1, m_widgets->messageList );
- m_clientsModel = new QStandardItemModel( 0, 1, m_widgets->connectedClients );
- m_serversModel = new QStandardItemModel( 0, 1, m_widgets->connectedServers );
- m_developersModel = new QStandardItemModel( 0, 1, m_widgets->availableDevelopers );
-
- m_widgets->logList->setModel( m_logModel );
- m_widgets->connectedClients->setModel( m_clientsModel );
- m_widgets->connectedServers->setModel( m_serversModel );
- m_widgets->messageList->setModel( m_messagesModel );
- m_widgets->availableDevelopers->setModel( m_developersModel );
- m_widgets->connectedDevelopers->setModel( m_collaborationManager->developersModel() );
-
- m_widgets->availableDevelopers->setItemsExpandable( true );
-
- m_widgets->availableDevelopers->header() ->hide();
- m_widgets->connectedDevelopers->header() ->hide();
-
- m_updateTimer = new QTimer( this );
- m_updateTimer->setSingleShot( true );
- m_updateAnswerTimer = new QTimer( this );
- m_updateAnswerTimer->setSingleShot( true );
-
- m_replyWaitingTimeout = new QTimer( this );
- m_replyWaitingTimeout->setSingleShot( true );
- connect( m_replyWaitingTimeout, SIGNAL( timeout() ), this, SLOT( messageReplyTimeout() ) );
- connect( m_updateAnswerTimer, SIGNAL( timeout() ), this, SLOT( updateAnswerMenu() ) );
-
- connect( m_widgets->allowIncoming, SIGNAL( stateChanged( int ) ), this, SLOT( allowIncomingChanged( int ) ) );
- connect( m_widgets->enableCollaboration, SIGNAL( stateChanged( int ) ), this, SLOT( enableCollaborationChanged( int ) ) );
- connect( m_widgets->connectServer, SIGNAL( clicked() ), this, SLOT( connectServer() ) );
- connect( m_widgets->connectedServers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( serverClicked( const QModelIndex& ) ) );
- connect( m_widgets->connectedServers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( serverDoubleClicked( const QModelIndex& ) ) );
- connect( m_widgets->availableDevelopers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( developerClicked( const QModelIndex& ) ) );
- connect( m_widgets->availableDevelopers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( developerDoubleClicked( const QModelIndex& ) ) );
- connect( m_widgets->availableDevelopers, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT( developerContextMenu( const QPoint& ) ) );
- connect( m_widgets->connectedClients, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( clientClicked( const QModelIndex& ) ) );
- connect( m_widgets->connectedClients, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( clientDoubleClicked( const QModelIndex& ) ) );
- connect( m_widgets->messageList, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( messageClicked( const QModelIndex& ) ) );
- connect( m_widgets->messageList, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( messageDoubleClicked( const QModelIndex& ) ) );
- connect( m_widgets->sendMessage, SIGNAL( clicked( ) ), this, SLOT( sendMessageButton( ) ) );
- connect( m_widgets->clearLog, SIGNAL( clicked( ) ), this, SLOT( clearLogButton( ) ) );
- connect( m_widgets->saveLog, SIGNAL( clicked( ) ), this, SLOT( saveLogButton( ) ) );
- connect( m_updateTimer, SIGNAL( timeout() ), this, SLOT( updateTimeout( ) ) );
- connect( m_widgets->messageType, SIGNAL( currentIndexChanged ( const int ) ), this, SLOT( messageTypeIndexChanged( const int ) ) );
- connect( m_widgets->clearMessages, SIGNAL( clicked() ), this, SLOT( slotClearMessages() ) );
- connect( m_widgets->messageHistory, SIGNAL( clicked() ), this, SLOT( slotMessageHistory() ) );
- connect( m_widgets->messageTargetUser, SIGNAL( editTextChanged( const QString& ) ), this, SLOT( messageTargetUserChanged() ) );
- connect( m_widgets->messageTargetUser, SIGNAL( currentIndexChanged( const QString& ) ), this, SLOT( messageTargetUserChanged() ) );
- connect( m_widgets->clearMessageButton, SIGNAL( clicked() ), this, SLOT( slotClearMessageText() ) );
- m_widgets->sendMessage->setDefault( true );
-
- m_widgets->messageType->clear();
- m_widgets->messageType->insertItem( 0, "Message" );
- m_widgets->messageType->insertItem( 1, "Source-Message" );
-
- sendMessageToUserAction = new QAction( i18n("Send Message"), this );
- connect( sendMessageToUserAction, SIGNAL( triggered() ), this, SLOT( sendMessageToUser() ) );
- sendMessageToUserAction->setToolTip( i18n("Send a text-message to the selected user.") );
-
- sendAnswerAction = new QAction( i18n("Answer"), this );
- connect( sendAnswerAction, SIGNAL( triggered() ), this, SLOT( sendAnswerMessage() ) );
- sendAnswerAction->setToolTip( i18n("Send an answer to this message.") );
-
- disconnectFromServerAction = new QAction( i18n("Disconnect"), this );
- connect( disconnectFromServerAction, SIGNAL( triggered() ), this, SLOT( disconnectFromServer() ) );
- disconnectFromServerAction ->setToolTip( i18n("Disconnect from the selected server.") );
-
- disconnectAllServersAction = new QAction( i18n("Disconnect All"), this );
- connect( disconnectAllServersAction, SIGNAL( triggered() ), this, SLOT( disconnectAllServers() ) );
- disconnectAllServersAction->setToolTip( i18n("Disconnect from all connected servers.") );
-
- kickClientAction = new QAction( i18n("Kick"), this );
- connect( kickClientAction, SIGNAL( triggered() ), this, SLOT( kickClient() ) );
- kickClientAction->setToolTip( i18n("Kick the selected client.") );
-
- banClientAction = new QAction( i18n("Ban"), this );
- connect( banClientAction, SIGNAL( triggered() ), this, SLOT( banClient() ) );
- banClientAction->setToolTip( i18n("Ban the selected client (stop him from reconnecting).") );
-
- kickAllClientsAction = new QAction( i18n("Disconnect All"), this );
- connect( kickAllClientsAction, SIGNAL( triggered() ), this, SLOT( kickAllClients() ) );
- kickAllClientsAction->setToolTip( i18n("Disconnect all connected clients from the local server.") );
-
- m_userInfoAction = new QAction( i18n("User Info"), this );
- connect( m_userInfoAction, SIGNAL( triggered() ), this, SLOT( uiUserInfo() ) );
- m_userInfoAction->setToolTip( i18n("Show information about the user.") );
-
- showPatchesAction = new QAction( i18n("Show Patches"), this );
- connect( showPatchesAction, SIGNAL( triggered() ), this, SLOT( uiShowPatches() ) );
- showPatchesAction->setToolTip( i18n("Show the available patches published by the selected user.") );
-
- connect( m_messageManager.data(), SIGNAL( messageUpdated( const MessagePointer& ) ), this, SLOT( messageUpdated( const MessagePointer& ) ) );
-
- emit init();
-
- setActive( false );
- m_updateAnswerTimer->start( 1000 );
-}
-
-KDevTeamwork::~KDevTeamwork() {
- emit deInit();
- delete m_updateTimer;
- delete m_updateAnswerTimer;
- delete m_replyWaitingTimeout;
-
- if ( TeamworkClientPointer::Locked l = m_client ) {
-
- l->invalidateTeamwork();
- } else {
- ///error
- kDebug(9500) << "error while destruction of KDevTeamwork: could not lock client-pointer. Client cannot be destroyed.";
- }
-
- m_logger.lock() ->invalidate();
- new LaterDeleter( m_client );
- m_destroyed = true;
-}
-
-KDevTeamworkPlugin *KDevTeamwork::plugin() const {
- return m_plugin;
-}
-
-KDevTeamworkUserPointer KDevTeamwork::currentTabUser() {
- if ( !m_widget )
- return 0;
-
- QWidget* c = m_widgets->messageUsers->currentWidget();
-
- for ( QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.begin(); it != m_userTabs.end(); ++it ) {
- if ( ( *it ) ->widget() == c ) {
- return ( *it ) ->user();
- }
- }
-
- return 0;
-}
-
-void KDevTeamwork::slotClearMessageText() {
- m_widgets->messageText->clear();
-}
-
-void KDevTeamwork::slotClearMessages() {
- KDevTeamworkUserPointer current = currentTabUser();
- if ( !current ) {
- m_messagesModel->clear();
- m_messagesModel->insertColumn( 0 );
- } else {
- m_userTabs.remove( current );
- }
-}
-
-void KDevTeamwork::slotMessageHistory() {
- KDevTeamworkUserPointer current = currentTabUser();
- if ( !current ) {
- m_messageManager->showMessageHistory();
- } else {
- QList<KDevTeamworkUserPointer> lst;
- lst << current;
- m_messageManager->showMessageHistory( lst );
- }
-}
-
-bool KDevTeamwork::setActive( bool active ) {
- cout << globalMessageTypeSet().stats();
- if ( !m_active && active ) {
- log( "GUI: starting collaboration" );
- ///start the client
- m_client = new KDevTeamworkClient( this );
- {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- l->insertUserSet( m_persistentUsers );
- } else {
- log( "could not lock fresh created KDevTeamworkClient", Error );
- }
- }
- m_client.unsafe() ->start();
-
- allowIncomingChanged( m_widgets->allowIncoming->checkState() );
- } else if ( m_client && !active ) {
- ///close the client
- log( "GUI: stopping collaboration" );
- {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- l->getUserSet( m_persistentUsers );
- l->invalidateTeamwork();
- }
- }
- m_client = 0;
- m_serversModel->clear();
- m_serversModel->insertColumn( 0 );
- m_developersModel->clear();
- m_developersModel->insertColumn( 0 );
- m_clientsModel->clear();
- m_clientsModel->insertColumn( 0 );
- m_widgets->messageTargetUser->clear();
- m_actionMessage = 0;
- }
- m_active = active;
-
- emit updateConnection( m_client );
-
- enableActiveGUI( m_active );
- m_updateAnswerTimer->start();
-
- return m_active;
-}
-
-void KDevTeamwork::updateMessageInfo( MessagePointer msg ) {
- if( m_destroyed ) return;
-
- log( "updateMessageInfo", Debug );
- messageManager() ->updateMessage( msg );
-}
-
-bool KDevTeamwork::setServerActive( bool active ) {
- m_serverActive = active;
- return m_serverActive;
-}
-
-void KDevTeamwork::documentActivated( KDevelop::IDocument* file ) {
- Q_UNUSED( file );
-}
-
-void KDevTeamwork::popupContextMenu( const QPoint &pos ) {
- Q_UNUSED( pos );
-}
-
-void KDevTeamwork::allowIncomingChanged( int state ) {
- if ( TeamworkClientPointer::Locked l = m_client ) {
- switch ( state ) {
- case Qt::Checked:
- l->allowIncoming( true );
- break;
- case Qt::Unchecked:
- l->allowIncoming( false );
- break;
- }
- } else {
- err( "cannot lock client" );
- }
-}
-
-void KDevTeamwork::enableCollaborationChanged( int state ) {
- switch ( state ) {
- case Qt::Checked:
- setActive( true );
- break;
- case Qt::Unchecked:
- setActive( false );
- break;
- }
-}
-
-void KDevTeamwork::uiFilterLog() {
- QAction * action = qobject_cast<QAction*>( sender() );
- LogLevel level = ( LogLevel ) action->data().toInt();
-
- if ( action->isChecked() )
- m_currentLogFilter = ( LogLevel ) ( m_currentLogFilter | level );
- else
- m_currentLogFilter = ( LogLevel ) ( m_currentLogFilter ^ level );
-
- filterLog();
-}
-
-void KDevTeamwork::filterLog( int max ) {
- int count = m_logModel->rowCount();
- if ( max != 0 && count > max )
- count = max;
- for ( int a = 0; a < m_logModel->rowCount(); a++ ) {
- QModelIndex i = m_logModel->index( a, 0 );
- if ( i.isValid() ) {
- QVariant v = m_logModel->data( i , Qt::UserRole );
- LogLevel lv = ( LogLevel ) v.toInt();
- m_widgets->logList->setRowHidden( a, !( bool ) ( lv & m_currentLogFilter ) );
- }
- }
-}
-
-void KDevTeamwork::uiShowPatches() {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- return ;
-
- QVariant v = act->data();
- if ( !v.canConvert<UserPointer>() ) {
- err( "uiShowPatches: Cannot convert to UserPointer" );
- return ;
- }
- UserPointer::Locked user = v.value<UserPointer>();
- if ( !user || ! user->online().session() ) {
- err( "failed to lock user in uiShowPatches or user is not online" );
- return ;
- }
-
- globalMessageSendHelper().send<PatchesManagerMessage>( user->online().session().unsafe(), PatchesManagerMessage::GetPatchesList );
-}
-
-void KDevTeamwork::showUserInfo( const UserPointer& user ) {
- try {
- if ( !user )
- throw QString( "no user given" );
-
- UserPointer::Locked l = user;
- if ( !l )
- throw QString( "could not lock user" );
-
- if ( !l.freeCast<KDevTeamworkUser>() )
- throw QString( "bad user-type" );
-
- KDialog* d = new KDialog( m_widget );
- d->setAttribute( Qt::WA_DeleteOnClose, true );
- KDevTeamworkUserInfoShower( l.freeCast<KDevTeamworkUser>(), d->mainWidget(), this );
- d->show();
- } catch ( QString str ) {
- log( "error in showUserInfo:" + str, Error );
- }
-
-}
-
-void KDevTeamwork::uiUserInfo() {
- try {
- UserPointer u = sendingUser();
- if ( !u )
- throw QString( "could not get sending-user" );
-
- showUserInfo( u );
- } catch ( QString str ) {
- log( "error in uiUserInfo:" + str, Error );
- }
-}
-
-void KDevTeamwork::connectionRequest( ConnectionRequestPointer request ) {
- log( "got collaboration-request" );
- addReceivedMessageToList( request );
-}
-
-void KDevTeamwork::connectServer() {
- if ( !m_active )
- return ;
- QString txt = m_widgets->serverBox->currentText();
- if ( !txt.isEmpty() ) {
- log( "UI: connecting to server " + txt );
- if ( m_client ) {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- kDebug(9500) << "connecting to \"" << toQ( stringToAddr( txt ) ) << "\":" << stringToPort( txt );
-
- QString userName = m_widgets->loginName->text();
-
- QString password = m_widgets->loginPassword->text();
-
- UserPointer user;
- if ( !userName.isEmpty() )
- user = new User( userName.toUtf8().data(), password.toUtf8().data(), "a user" );
- else
- user = l->identity();
- if ( user ) {
- l->setIdentity( user );
- l->connectToServer( ServerInformation( stringToAddr( txt ), stringToPort( txt ) ), user );
- } else
- err( "cannot connect to a server without having an identity" );
- } else {
- err( "could not lock client-thread" );
- }
- } else {
- err( "error: client is not running" );
- }
- } else {
- err( "UI: cannot connect to unidentified server" );
- }
-}
-
-UserIdentity KDevTeamwork::currentUserIdentity() {
- TeamworkClientPointer::Locked l = m_client;;
- if( l ) {
- UserPointer u = l->identity();
- if( UserPointer::Locked lu = u ) {
- return lu->identity();
- }
- }
- return UserIdentity();
-}
-
-
-void KDevTeamwork::log( const QString & str, LogLevel level ) {
- ///@todo assign an icon for each log-level, maybe allow filtering by level, and add a "clear-log" button
- if( m_destroyed ) return;
- //if( level == Debug ) return;
- m_logModel->insertRow( 0 );
- QModelIndex i = m_logModel->index( 0, 0 );
- //m_logModel->insertColumn( 0, i );
- QIcon icon;
- ///choose an icon using the level
- icon = iconFromLevel( level );
-
- m_logModel->setData( i, str, Qt::DisplayRole );
-
- QVariant lv( level );
- m_logModel->setData( i, lv, Qt::UserRole );
- m_logModel->setData( i, icon, Qt::DecorationRole );
-
- /*if( ! (level & m_currentLogFilter) )
- m_widgets->logList->setRowHidden( 0 , true );*/
-
- filterLog( 3 );
- //kDebug(9500) << "log: \"" << str << "\" level:" << level;
-}
-
-void KDevTeamwork::err( const QString& str ) {
- if( m_destroyed ) return;
- log( str, Error );
-}
-
-///Starts the update-timer for the developer-lists
-void KDevTeamwork::startUpdateTimer() {
- if( m_destroyed ) return;
- m_updateTimer->start( 300 );
-}
-
-TeamworkClientPointer& KDevTeamwork::client() {
- return m_client;
-}
-PatchesManager* KDevTeamwork::patchesManager();
-
-CollaborationManager* KDevTeamwork::collaborationManager() {
- return m_collaborationManager;
-}
-
-LoggerPointer KDevTeamwork::logger() {
- return m_logger;
-}
-
-void KDevTeamwork::enableActiveGUI( bool active ) {
- m_widgets->connectionTab->setEnabled( active );
- m_widgets->availableLabel->setEnabled( active );
- m_widgets->connectedLabel->setEnabled( active );
- m_widgets->availableDevelopers->setEnabled( active );
- m_widgets->connectedDevelopers->setEnabled( active );
-
- enableMessageGUI( active );
- if ( !active ) {
- ///empty list of connected and available developers
- }
-}
-
-void KDevTeamwork::enableMessageGUI( bool active ) {
- m_widgets->messaging->setEnabled( active );
-}
-
-KDevTeamworkLogger::KDevTeamworkLogger( KDevTeamwork* tw ) : m_teamwork( tw ) {
- // connect( this, SIGNAL( guiLog( QString, int ) ), m_teamwork, SLOT( guiLog( QString, int) ), Qt::QueuedConnection );
-}
-
-void KDevTeamworkLogger::log( const std::string& str , Level lv ) {
- if ( m_teamwork ) {
- LogLevel level;
- switch ( lv ) {
- case Info:
- level = ::Info;
- break;
- case Warning:
- level = ::Warning;
- break;
- case Error:
- level = ::Error;
- break;
- case Debug:
- level = ::Debug;
- break;
- default:
- return ;
- }
-
- kDebug(9500) << "log-level: \"" << ~levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"";
- QMetaObject::invokeMethod( m_teamwork, "guiLog", Qt::QueuedConnection, Q_ARG( QString, toQ( str ) ), Q_ARG( int, level ) );
- } else {
- kDebug(9500) << "log-level: \"" << ~levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"";
- }
-}
-
-void KDevTeamworkLogger::safeErrorLog( const std::string& str, Level lv ) {
-
- cout << levelToString( lv ) << "\" message: \"" << toQ( str ) << "\"" << endl;
-}
-
-void KDevTeamwork::guiUserConnected( Teamwork::UserPointer user ) {
- startUpdateTimer();
-
- UserPointer::Locked l = user;
- if ( !l ) {
- err( "error" );
- return ;
- }
- QString name = toQ( l->name() );
-
- QStandardItemModel* model = m_clientsModel;
- model->insertRow( 0 );
- QModelIndex i = model->index( 0, 0 );
-
- model->setData( i, name, Qt::DisplayRole );
- QVariant v;
- v.setValue( user );
- model->setData( i, v, Qt::UserRole );
-
- addDeveloper( user );
-}
-
-void KDevTeamwork::guiUserDisconnected( Teamwork::UserPointer user ) {
- if( m_destroyed ) return;
- startUpdateTimer();
-
- UserPointer::Locked l = user;
- if ( !l ) {
- err( "failed to lock user-pointer" );
- return ;
- }
-
- QString name = toQ( l->name() );
-
- QStandardItemModel* model = m_clientsModel;
- for ( int a = 0; a < model->rowCount(); a++ ) {
- QModelIndex i = model->index( a, 0 );
- QVariant v = model->data( i, Qt::DisplayRole );
- if ( v.type() == QVariant::String ) {
- if ( v.toString() == name ) {
- model->removeRow( a );
- }
- }
- }
-
- ///remove the user from the target-user-list in the messaging-tab
- QVariant v;
- v.setValue( user );
- int i = m_widgets->messageTargetUser->findData( v );
- if ( i != -1 )
- m_widgets->messageTargetUser->removeItem( i );
-
-
- //kDebug(9500) << "disconnecting user is not in list:" << name;
-}
-
-void KDevTeamwork::guiServerConnected( Teamwork::ClientSessionDesc /*session*/, Teamwork::ServerInformation server ) {
- if( m_destroyed ) return;
- startUpdateTimer();
-
- QString desc = toQ( server.desc() );
-
- QStandardItemModel* model = m_serversModel;
- model->insertRow( 0 );
- QModelIndex i = model->index( 0, 0 );
-
- model->setData( i, desc, Qt::DisplayRole );
- QVariant v;
- v.setValue( server );
- model->setData( i, v, Qt::UserRole );
-}
-
-void KDevTeamwork::guiServerDisconnected( Teamwork::ClientSessionDesc /*session*/, Teamwork::ServerInformation server ) {
- if( m_destroyed ) return;
- startUpdateTimer();
-
- QStandardItemModel* model = m_serversModel;
-
- QString desc = toQ( server.desc() );
-
- for ( int a = 0; a < model->rowCount(); a++ ) {
- QModelIndex i = model->index( a, 0 );
- QVariant v = model->data( i, Qt::DisplayRole );
- if ( v.type() == QVariant::String ) {
- if ( v.toString() == desc ) {
- model->removeRow( a );
- return ;
- }
- }
- }
-
- kDebug(9500) << "disconnecting server is not in list:" << desc;
-}
-
-QIcon KDevTeamwork::iconFromUser( User* user, KIconLoader::Group size ) {
- KDevTeamworkUserPointer::Locked u( dynamic_cast<KDevTeamworkUser*>( user ) );
- if ( !u )
- return m_icons->getIcon( "remove", size );
- return u->icon( size );
-}
-
-
-void KDevTeamwork::updateTimeout() {
- if( m_destroyed ) return;
-
- //log( "update-timer", Debug );
- QStandardItemModel * model = m_developersModel;
-
- for ( int a = model->rowCount() - 1; a >= 0; a-- ) {
- QModelIndex i = model->index( a, 0 );
- QVariant v = model->data( i, Qt::UserRole );
- //QVariant v2 = model->data( i, Qt::DecorationRole );
- QIcon icon;
- /*Ü if( v2.canConvert<QIcon>() )
- icon = v2.value<QIcon>();*/
-
- if ( v.canConvert<UserPointer>( ) ) {
- UserPointer p = v.value<UserPointer>();
- UserPointer::Locked l = p;
- if ( l ) {
- SessionPointer s = l->online().session();
-
- if ( s && s.unsafe() ->isOk() ) {
- icon = iconFromUser( l, KIconLoader::Toolbar );
- } else {
- model->removeRow( a );
- continue;
- }
-
- } else {
- err( "user-pointer contained in developer-list could not be locked" );
- icon = m_icons->getIcon( "filecose", KIconLoader::Toolbar );
- }
- } else {
- err( "wrong data in the developers-list" );
- icon = m_icons->getIcon( "filecose", KIconLoader::Toolbar );
- }
- model->setData( i, icon, Qt::DecorationRole );
- }
-
- QComboBox* cb = m_widgets->messageTargetUser;
-
- for ( int a = cb->count(); a >= 0; a-- ) {
- QVariant v = m_widgets->messageTargetUser->itemData( a );
- if ( v.canConvert<UserPointer>() ) {
- UserPointer::Locked lu = v.value<UserPointer>();
- m_widgets->messageTargetUser->setItemData( a, iconFromUser( lu ), Qt::DecorationRole );
- }
- }
-
- m_collaborationManager->updateList();
-
- m_updateTimer->start( 3000 );
-}
-
-void KDevTeamwork::addDeveloper( const Teamwork::UserPointer& u ) {
- QStandardItemModel * model = m_developersModel;
-
- UserPointer::Locked l = u;
- if ( l ) {
- model->insertRow( 0 );
- QModelIndex i = model->index( 0, 0 );
-
- //log("adding user " + toQ( l->name() ) + " to list" );
- model->setData( i, toQ( l->name() ), Qt::DisplayRole );
-
- QVariant v;
- v.setValue<UserPointer>( u );
- model->setData( i, v, Qt::UserRole );
- model->setData( i, iconFromUser( l ), Qt::DecorationRole );
-
- } else {
- err( "could not lock a user-pointer from a received list" );
- }
-}
-
-void KDevTeamwork::registerPatches( PatchesListMessage* msg, QStandardItemModel* model ) {
- SessionPointer::Locked lsession = msg->info().session();
- log( "handing patches-list", Debug );
-
- try {
- if ( !lsession )
- throw "no session";
- UserPointer::Locked luser = lsession->safeUser();
- if ( !luser )
- throw "could not lock user, or wrong data in session";
-
- QModelIndex i = findInModelNormal( model, ( UserPointer ) luser );
- if ( i.isValid() ) {
- if ( model->columnCount( i ) == 0 )
- model->insertColumns( 0, 1, i );
- else
- model->removeRows( 0, model->rowCount( i ), i );
-
- for ( list<LocalPatchSource>::iterator it = msg->patches.begin(); it != msg->patches.end(); ++it ) {
- LocalPatchSourcePointer source = new LocalPatchSource( *it );
- source.unsafe() ->setUser( luser );
- QModelIndex ind = findInModel<LocalPatchSourcePointer, LocalPatchSourcePointer::ValueIdentCompare>( model, source, i );
- if ( ind.isValid() )
- model->removeRows( ind.row(), 1, i );
-
- model->insertRows( 0, 1, i );
- QModelIndex index = model->index( 0, 0, i );
- model->setData( index, ~( *it ).name );
- model->setData( index, ( *it ).getIcon( *m_icons ), Qt::DecorationRole );
- QVariant v;
- v.setValue<LocalPatchSourcePointer>( source );
- model->setData( index, v, Qt::UserRole );
- }
- } else {
- //throw "could not find the user in the developers-list";
- }
- } catch ( const char * str ) {
- err( QString( "in handlePatchesList: " ) + str );
- }
-}
-
-void KDevTeamwork::handlePatchesList( PatchesListMessage* msg ) {
- registerPatches( msg, m_developersModel );
- registerPatches( msg, m_collaborationManager->developersModel() );
-}
-
-void KDevTeamwork::guiUserList( std::list<UserPointer> users ) {
-
- //log( QString("guiUserList : handling user-list of size %1").arg( users.size() ) );
-
- for ( std::list<UserPointer>::iterator it = users.begin(); it != users.end(); ++it ) {
- addDeveloper( *it );
- }
-}
-
-void KDevTeamwork::fillUserMenu( QMenu* menu, const UserPointer& user ) {
- UserPointer::Locked luser = user;
- if ( luser && luser->online() ) {
- QVariant v;
- v.setValue( user );
-
- sendMessageToUserAction->setData( v );
- menu->addAction( sendMessageToUserAction );
-
- showPatchesAction->setData( v );
- //menu->addAction( showPatchesAction );
- m_collaborationManager->fillUserMenu( menu, user );
- m_userInfoAction->setData( v );
- menu->addAction( m_userInfoAction );
- }
-}
-
-void KDevTeamwork::fillMessageMenu( QMenu* menu, const MessagePointer& msg ) {
- MessagePointer::Locked l = msg;
- if ( l->info().session() && l->info().session().unsafe() ->isOk() && l->info().isIncoming() ) {
- QVariant v;
- v.setValue( msg );
- sendAnswerAction->setData( v );
- menu->addAction( sendAnswerAction );
- }
-}
-
-void KDevTeamwork::sendAnswerMessage() {
- MessagePointer::Locked msg = sendingMessage();
- if ( msg ) {
- guiSendMessageTo( msg->info().user(), msg );
- } else {
- log( "sendAnswerMessage: could not lock message to answer to ", Error );
- }
-}
-
-void KDevTeamwork::sendMessageToUser() {
- if ( sendingUser() )
- QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, sendingUser() ) );
-}
-
-
-void KDevTeamwork::contextMenu( const QPoint& p, const QModelIndex& index ) {
-
- if(!index.isValid() )
- return;
- QMenu menu;
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- fillUserMenu( &menu, v.value<UserPointer>() );
- getPatchesList( v.value<UserPointer>() );
-
- }
-
- if ( v.canConvert<LocalPatchSourcePointer>() ) {
- m_patchesManager->fillDeveloperActions( index, &menu );
- }
-
- menu.exec( p );
-}
-
-void KDevTeamwork::maybeDeveloperContextMenu() {
- if ( m_contextMenuIndex.get() ) {
- contextMenu( QCursor::pos(), *m_contextMenuIndex );
- }
-}
-
-void KDevTeamwork::developerClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
-
- m_contextMenuIndex.reset( new QPersistentModelIndex( index ) );
-
- QTimer::singleShot( 400, this, SLOT( maybeDeveloperContextMenu() ) );
-}
-
-void KDevTeamwork::developerContextMenu( const QPoint& p ) {
-
- QModelIndex index = widgets().availableDevelopers->indexAt( p );
- if ( !index.isValid() )
- return ;
-
- contextMenu( p, index );
-}
-
-void KDevTeamwork::getPatchesList( const UserPointer& user ) {
- QVariant v;
- v.setValue( user );
- showPatchesAction->setData( v );
- showPatchesAction->activate( QAction::Trigger );
-}
-
-void KDevTeamwork::developerDoubleClicked( const QModelIndex& index ) {
- m_contextMenuIndex.reset( 0 );
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() )
- QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, v.value<UserPointer>() ) );
-}
-
-void KDevTeamwork::serverClicked( const QModelIndex& index ) {
- QMenu * menu = new QMenu( m_widget );
-
- if ( !index.isValid() )
- return ;
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<ServerInformation>() ) {
- UserPointer user;
- ServerInformation p = v.value<ServerInformation>();
- MultiSessionPointer sess = l->sessionToServer( p );
-
- if ( sess )
- user = l->findSessionUser( sess );
- else
- log( "no session to the server is open", Warning );
-
- if ( !user )
- log( "the server has no associated user, no message can be sent", Warning );
- else
- fillUserMenu( menu, user );
-
- } else {
- err( "wrong information stored in the list-view" );
- }
- } else {
- err( "could not lock the client-handler" );
- }
-
- menu->addAction( disconnectFromServerAction );
- menu->addSeparator();
- menu->addAction( disconnectAllServersAction );
- menu->exec( QCursor::pos() );
-}
-
-void KDevTeamwork::serverDoubleClicked( const QModelIndex& index ) {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<ServerInformation>() ) {
- UserPointer user;
- ServerInformation p = v.value<ServerInformation>();
- MultiSessionPointer::Locked sess = l->sessionToServer( p );
- if ( sess )
- user = l->findSessionUser( sess.cast<SessionInterface>().data() );
- else
- log( "no session to the server is open", Warning );
-
- if ( !user )
- log( "the server has no associated user, no message can be sent", Warning );
- else
- QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, user ) );
- }
- }
-}
-
-void KDevTeamwork:: messageClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
- QMenu menu( m_widget );
-
- UserPointer user;
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert< MessagePointer >() ) {
- MessagePointer::Locked l = v.value< MessagePointer >();
- m_messageManager->fillMessageMenu( &menu, l );
- } else {
- err( "wrong information stored in the message-list-view" );
- }
-
- menu.exec( QCursor::pos() );
-}
-
-void KDevTeamwork::messageTargetUserChanged() {
- m_updateAnswerTimer->start( 100 );
-}
-
-void KDevTeamwork::updateAnswerMenu() {
- QMenu* menu = m_widgets->answeringToButton->menu();
- if( menu == 0 ) menu = new QMenu( i18n( "Answer To" ), m_widget );
- menu->clear();
- KDevTeamworkUserPointer::Locked user = currentMessageTargetUser().cast<KDevTeamworkUser>();
- if( !user ) return;
-
- UserTabMap::iterator it = m_userTabs.find( user );
- if( it != m_userTabs.end() ) {
- QStandardItemModel* model = (*it)->model();
- int maxSearch = model->rowCount();
- if( maxSearch > 100 ) maxSearch = 100;
- int count = 0;
- for( int a = 0 ; a < maxSearch; a++ ) {
- if( count > 10 ) break;
- QModelIndex i = model->index( a, 0 );
- if( i.isValid() ) {
- MessagePointer::Locked m = model->data( i, Qt::UserRole ).value<MessagePointer>();
- if( m ) {
- KDevTeamworkTextMessage* tm = m.freeCast<KDevTeamworkTextMessage>();
- AbstractGUIMessage* gm = m.freeCast<AbstractGUIMessage>();
- if( gm && tm && m->info().isIncoming() && (!tm->answered() || m.data() == m_answerTo.unsafe() ) ) {
- //gm->messageIcon()
- QAction* a = new QAction( gm->messageText().left( 30 )+"...", menu );
- QVariant v;
- v.setValue<MessagePointer>( m );
- a->setData( v );
- a->setCheckable( true );
- if( m.data() == m_answerTo.unsafe() ) a->setChecked( true );
- menu->addAction( a );
- connect( a, SIGNAL( toggled( bool ) ), this, SLOT( answerMenuToggled( bool ) ) );
- connect( a, SIGNAL( triggered( bool ) ), this, SLOT( answerMenuTriggered( bool ) ) );
- count++;
- }
- }
- }
- }
- m_widgets->answeringToButton->setEnabled( model->rowCount() != 0 );
- } else {
- m_widgets->answeringToButton->setEnabled( false );
- }
- m_widgets->answeringToButton->setMenu( menu );
-}
-
-void KDevTeamwork::answerMenuToggled( bool state ) {
- if( !m_widgets->answeringToButton->menu() ) return;
- QAction* sender = qobject_cast<QAction*>( QObject::sender() );
- QList<QAction*> actions = m_widgets->answeringToButton->menu()->findChildren<QAction*>();
- ///Uncheck all except his one
- for( QList<QAction*>::iterator it = actions.begin(); it != actions.end(); ++it ) {
- if( *it != sender ) {
- (*it)->setChecked( false );
- }
- }
- if( !state ) {
- m_answerTo = 0;
- } else {
- m_answerTo = sender->data().value<MessagePointer>();
- }
-}
-
-void KDevTeamwork::answerMenuTriggered( bool ) {
- MessagePointer m = sendingMessage();
- if( !m ) return;
- m_messageManager->showMessage( m );
-}
-
-void KDevTeamwork::messageDoubleClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
-
- UserPointer user;
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<MessagePointer>() ) {
- MessagePointer::Locked l = v.value< MessagePointer >();
- if ( l && l->info().session() ) {
- UserPointer u = userFromSession( l->info().session() );
- if ( u ) {
- QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, u ) );
- } else
- log( "could not get user from message, or message has no session" );
- } else {
- err( "could not lock text-message from view" );
- }
- } else {
- err( "wrong information stored in the message-list-view" );
- }
-}
-
-void KDevTeamwork:: clientClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
-
- QMenu menu( m_widget );
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- fillUserMenu( &menu, v.value<UserPointer>() );
- } else {
- err( "wrong information stored in the list-view" );
- }
-
- menu.addSeparator();
- menu.addAction( kickClientAction );
- menu.addAction( banClientAction );
- menu.addSeparator();
- menu.addAction( kickAllClientsAction );
- menu.exec( QCursor::pos() );
-}
-
-void KDevTeamwork:: clientDoubleClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- QMetaObject::invokeMethod( this, "guiSendMessageTo", Qt::QueuedConnection, Q_ARG( UserPointer, v.value<UserPointer>() ) );
- } else {
- err( "wrong information stored in the list-view" );
- }
-}
-
-void KDevTeamwork::disconnectFromServer() {
- QModelIndex index = m_widgets->connectedServers->currentIndex();
- if ( !index.isValid() )
- return ;
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<ServerInformation>() ) {
- ServerInformation p = v.value<ServerInformation>();
- l->disconnectFromServer( p );
- } else {
- err( "wrong information stored in the list-view" );
- }
- } else {
- err( "could not lock the client-handler" );
- }
-}
-
-void KDevTeamwork::disconnectAllServers() {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- l->disconnectAllServers();
- } else {
- err( "could not lock the client-handler" );
- }
-}
-
-UserPointer KDevTeamwork::sendingUser() {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- return 0;
-
- QVariant v = act->data();
- if ( !v.canConvert<UserPointer>() ) {
- return 0;
- }
- return v.value<UserPointer>();
-}
-
-MessagePointer KDevTeamwork::sendingMessage() {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- return 0;
-
- QVariant v = act->data();
- if ( !v.canConvert<MessagePointer>() ) {
- return 0;
- }
- return v.value<MessagePointer>();
-}
-
-void KDevTeamwork::messageUpdated( const MessagePointer& msg ) {
- try {
- MessagePointer::Locked l = msg;
- if ( !l )
- throw QString( "could not lock a message to update" );
-
- KDevTeamworkUserPointer user = l->info().user().cast<KDevTeamworkUser>();
-
- if ( user ) {
- UserTabMap::iterator it = m_userTabs.find( user );
- if ( it != m_userTabs.end() ) {
- ( *it ) ->messageUpdated( msg );
- }
- }
-
- AbstractGUIMessage* guiMsg = l.freeCast<AbstractGUIMessage>();
-
- if ( !guiMsg )
- throw QString( "cannot update information for a non-gui-message" );
-
- QPersistentModelIndex pi = guiMsg->data.value<QPersistentModelIndex>();
- QModelIndex i( pi );
-
- if ( !i.isValid() )
- throw QString( "cannot update a message, the model-index is invalid" );
-
- QAbstractItemModel* model = const_cast<QAbstractItemModel*>( i.model() );
- model->setData( i, guiMsg->messageIcon(), Qt::DecorationRole ); ///The text is not updated right now
- } catch ( QString str ) {
- err( "in messageUpdated: " + str );
- }
-}
-
-void KDevTeamwork::kickClient() {
- QModelIndex index = m_widgets->connectedClients->currentIndex();
- if ( !index.isValid() )
- return ;
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- UserPointer p = v.value<UserPointer>();
- UserPointer::Locked lu = p;
- if ( lu ) {
- if ( lu->online() ) {
- l->closeSession( lu->online().session() );
- } else {
- err( "user to kick is not online" );
- }
- } else {
- err( "could not lock user-pointer stored in the list-view" );
- }
- } else {
- err( "wrong information stored in the list-view" );
- }
- } else {
- err( "could not lock the client-handler" );
- }
-}
-
-void KDevTeamwork::banClient() {
- QModelIndex index = m_widgets->connectedClients->currentIndex();
- if ( !index.isValid() )
- return ;
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- UserPointer p = v.value<UserPointer>();
- UserPointer::Locked lu = p;
- if ( lu ) {
- lu->ban( true );
- if ( lu->online() ) {
- l->closeSession( lu->online().session() );
- } else {
- err( "user to kick is not online" );
- }
- } else {
- err( "could not lock user-pointer stored in the list-view" );
- }
- } else {
- err( "wrong information stored in the list-view" );
- }
- } else {
- err( "could not lock the client-handler" );
- }
-}
-
-void KDevTeamwork::kickAllClients() {
- TeamworkClientPointer::Locked l = m_client;
- if ( l ) {
- l->closeAllIncomingSessions();
- } else {
- err( "could not lock the client-handler" );
- }
-}
-
-void KDevTeamwork::clearLogButton() {
- m_logModel->clear();
- m_logModel->insertColumn( 0 );
-}
-
-void KDevTeamwork::messageReplyTimeout() {
- log( "messageReplyTimeout", Debug );
- if( m_waitingForReply ) {
- addMessageToList( new FailureMessage( "got no reply", m_waitingForReply ) );
- unlockMessageGui();
- }
-}
-
-void KDevTeamwork::lockMessageGui( const MessagePointer& msg ) {
- //log( QString("lockMessageGui called, waiting for %1").arg( msg.unsafe() ), Debug );
- m_waitingForReply = msg;
- m_widgets->messageText->setEnabled( false );
- m_widgets->clearMessageButton->setEnabled( false );
- m_widgets->sendMessage->setEnabled( false );
- m_replyWaitingTimeout->start( messageSendTimeout );
-}
-
-void KDevTeamwork::unlockMessageGui() {
- log( "unlockMessageGui called", Debug );
- m_waitingForReply = 0;
- m_widgets->messageText->setEnabled( true );
- m_widgets->clearMessageButton->setEnabled( true );
- m_widgets->sendMessage->setEnabled( true );
- m_replyWaitingTimeout->stop();
-}
-
-void KDevTeamwork::receiveMessage( SafeSharedPtr<KDevSystemMessage> msg ) {
- SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
- MessagePointer::Locked lv = m_waitingForReply;
- if ( l ) {
- if( m_waitingForReply == l->info().replyToMessage() ) {
- if( l->message() == KDevSystemMessage::ActionSuccessful ) {
- m_widgets->messageText->clear();
- } else {
- addMessageToList( new FailureMessage( QString( "could not send message: %1").arg( l->messageAsString() ), m_waitingForReply ) );
- }
- unlockMessageGui();
- LockedSharedPtr<KDevTeamworkTextMessage> la = m_answerTo.cast<KDevTeamworkTextMessage>();
- if( la ) {
- la->setAnswered( true );
- }
- m_answerTo = 0;
- m_updateAnswerTimer->start( 300 );
- }
-
- MessagePointer isReplyTo = l->info().replyToMessage();
- switch ( l->message() ) {
- case KDevSystemMessage::CollaborationAccepted: {
- if ( !isReplyTo ) {
- log( "got collaboration-accepted-message, but it was not requested", Warning );
- break;
- }
- startUpdateTimer();
- SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
- log( "collaboration was accepted, reason: " + l->text() );
- if ( l ) {
- m_collaborationManager->addCollaboratingUser( userFromSession( l->info().session() ) );
- } else {
- log( "could not lock a KDevSystemMessage" );
- }
- break;
- }
- case KDevSystemMessage::CollaborationRefused:
- log( "collaboration was refused, reason: " + l->text() );
- break;
- case KDevSystemMessage::CollaborationClosed: {
- log( "peer stopped collaboration" );
- SafeSharedPtr<KDevSystemMessage>::Locked l = msg;
- if ( l ) {
- m_collaborationManager->removeCollaboratingUser( userFromSession( l->info().session() ) );
- }
- }
- break;
- default:
- break;
- }
- }
-}
-
-void KDevTeamwork::addSentMessageToList( const MessagePointer& smsg ) {
- ///Put the message into the "All Users"-tab
- addSentMessageToList( smsg, m_messagesModel );
-
- ///Also put the message into the user-tab
- MessagePointer::Locked msg = smsg;
- if ( msg ) {
- UserPointer::Locked lu = userFromSession( msg->info().session() );
- if ( lu ) {
- QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.find( lu.freeCast<KDevTeamworkUser>() );
- if ( it != m_userTabs.end() ) {
- addSentMessageToList( smsg, ( *it ) ->model() );
- } else {
- m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] = new MessageUserTab( this, lu.freeCast<KDevTeamworkUser>() );
- addSentMessageToList( smsg, m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] ->model() );
- }
- } else {
- log( "failed to lock user", Error );
- }
- } else {
- log( "failed to lock message", Error );
- }
-}
-
-void KDevTeamwork::addMessageToList( const MessagePointer& smsg ) {
- MessagePointer::Locked l = smsg;
- if( l ) {
- if( l->info().isIncoming() ) {
- addReceivedMessageToList( smsg );
- } else {
- addSentMessageToList( smsg );
- }
- } else {
- err( "addMessageToList: could not lock message" );
- }
-}
-
-void KDevTeamwork::addSentMessageToList( const MessagePointer& smsg, QStandardItemModel* model ) {
- MessagePointer::Locked msg = smsg;
- if ( msg ) {
-
- AbstractGUIMessage * guiMsg = msg.freeCast<AbstractGUIMessage>();
- if ( !guiMsg ) {
- err( "cannot add non-gui-message to list" );
- return ;
- }
- model->insertRow( 0 );
- QModelIndex i = model->index( 0, 0 );
-
- if ( model == m_messagesModel )
- guiMsg->data.setValue( QPersistentModelIndex( i ) );
-
- QString toUser, text = guiMsg->messageText();
-
- UserPointer p = msg->info().user();
- if ( p ) {
- UserPointer::Locked lp = p;
- if ( lp ) {
- toUser = ~lp->name();
- } else {
- toUser = "not-lockable-user";
- }
- } else {
- toUser = "not-connected-user";
- }
-
- if ( model != m_messagesModel ) {
- text = text;
- } else {
- text = toUser + ": \"" + text + "\"";
- }
-
- model->setData( i, text, Qt::DisplayRole );
- model->setData( i, guiMsg->messageIcon() , Qt::DecorationRole );
-
- ///The whole message is stored, including all its information. That may become a problem, since it keeps references to all involved sessions.
-
- QVariant v;
- v.setValue( smsg );
- model->setData( i, v, Qt::UserRole );
-
- } else {
- err( "could not lock incoming kdev-text-message" );
- }
- m_updateAnswerTimer->start( 300 );
-}
-
-void KDevTeamwork::addReceivedMessageToList( const MessagePointer& smsg ) {
- ///Put the message into the "All Users"-tab
- addReceivedMessageToList( smsg, m_messagesModel );
-
- ///Also put the message into the user-tab
- MessagePointer::Locked msg = smsg;
- if ( msg ) {
- UserPointer::Locked lu = userFromSession( msg->info().session() );
- if ( lu ) {
- QMap<KDevTeamworkUserPointer, SharedPtr<MessageUserTab> >::iterator it = m_userTabs.find( lu.freeCast<KDevTeamworkUser>() );
- if ( it != m_userTabs.end() ) {
- addReceivedMessageToList( smsg, ( *it ) ->model() );
- } else {
- m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] = new MessageUserTab( this, lu.freeCast<KDevTeamworkUser>() );
- addReceivedMessageToList( smsg, m_userTabs[ lu.freeCast<KDevTeamworkUser>() ] ->model() );
- }
- } else {
- log( "failed to lock user", Error );
- }
- } else {
- log( "failed to lock message", Error );
- }
-}
-
-void KDevTeamwork::addReceivedMessageToList( const MessagePointer& smsg, QStandardItemModel* model ) {
- MessagePointer::Locked msg = smsg;
- if ( msg ) {
- AbstractGUIMessage * guiMsg = msg.freeCast<AbstractGUIMessage>();
-
- if ( !guiMsg ) {
- err( "cannot add non-gui-message to list" );
- return ;
- }
-
- model->insertRow( 0 );
- QModelIndex i = model->index( 0, 0 );
-
- if ( model == m_messagesModel )
- guiMsg->data.setValue( QPersistentModelIndex( i ) );
-
- QString fromUser, text = guiMsg->messageText();
-
- UserPointer p = msg->info().user();
- if ( p ) {
- UserPointer::Locked lp = p;
- if ( lp ) {
- fromUser = toQ( lp->name() );
- } else {
- fromUser = "not-lockable-user";
- }
- } else {
- fromUser = "missing-user-info";
- }
-
- if ( model != m_messagesModel ) {
- text = text;
- } else {
- text = fromUser + ": \"" + text + "\"";
- }
-
- model->setData( i, text, Qt::DisplayRole );
- model->setData( i, guiMsg->messageIcon() , Qt::DecorationRole );
-
- ///The whole message is stored, including all its information. That may become a problem, since it keeps references to all sessions.
-
- QVariant v;
- v.setValue( smsg );
- model->setData( i, v, Qt::UserRole );
-
- } else {
- err( "could not lock incoming kdev-text-message" );
- }
- m_updateAnswerTimer->start( 300 );
-}
-
-void KDevTeamwork::saveLogButton() {
- ///open a save-dialog and store the content of logModel to a file
- log( "not implemented yet", Warning );
-}
-
-void KDevTeamwork::guiSendMessageTo( const UserPointer& user, const MessagePointer& answerTo ) {
- UserPointer::Locked lu = user;
- if ( lu ) {
- m_answerTo = answerTo;
-
- m_widgets->toolBox->setCurrentWidget( m_widgets->messaging );
- int item = -1;
- QVariant v;
- for ( int a = 0; a < m_widgets->messageTargetUser->count(); a++ ) {
- v = m_widgets->messageTargetUser->itemData( a );
- if ( v.canConvert<UserPointer>() ) {
- if ( v.value<UserPointer>() == user ) {
- item = a;
- break;
- }
- }
- }
- v.setValue( user );
- if ( item == -1 ) {
- m_widgets->messageTargetUser->insertItem( 0, toQ( lu->name() ), v );
- m_widgets->messageTargetUser->setItemData( 0, iconFromUser( lu ), Qt::DecorationRole );
- item = 0;
- } else {}
- m_widgets->messageTargetUser->setCurrentIndex( item );
-
- m_widgets->messageType->setCurrentIndex( NormalMessage );
-
- if ( LockedSharedPtr<InDocumentMessage> l = answerTo.cast<InDocumentMessage>() ) {
- m_widgets->messageType->setCurrentIndex( DocumentMessage );
- m_widgets->context->setText( l->context() );
- m_widgets->reference->clear();
- }
- m_widgets->messageText->clear();
- } else {
- err( "could not lock user-pointer stored in the list-view" );
- }
-
- startUpdateTimer();
-}
-
-void KDevTeamwork::messageTypeIndexChanged( const int index ) {
- if( m_destroyed ) return;
-
- switch ( index ) {
- case Message:
- m_widgets->reference->hide();
- m_widgets->referenceLabel->hide();
- m_widgets->contextLabel->hide();
- m_widgets->context->hide();
- break;
- case SourceMessage:
- m_widgets->reference->show();
- m_widgets->referenceLabel->show();
- m_widgets->contextLabel->show();
- m_widgets->context->show();
- break;
- };
-}
-
-UserPointer KDevTeamwork::currentMessageTargetUser() {
- UserPointer user;
- if ( m_widgets->messageTargetUser->currentIndex() != -1 ) {
- QVariant v = m_widgets->messageTargetUser->itemData( m_widgets->messageTargetUser->currentIndex() );
- if ( v.canConvert<UserPointer>() )
- user = v.value<UserPointer>();
- }
- QString uname = m_widgets->messageTargetUser->currentText();
- if ( ( !user && uname.isEmpty() ) )
- return 0;
- if ( !user ) {
- TeamworkClientPointer::Locked l = m_client;
- if( !l )
- return 0;
- else
- return l->findUser( UserIdentity( uname.toUtf8().data() ) );
- }
-
- return user;
-}
-
-void KDevTeamwork::sendMessageButton() {
- //QString txt = m_widgets->messageText->toHtml();
- QString txt = m_widgets->messageText->toPlainText();
-
- MessagePointer::Locked lmsg = m_answerTo;
-
- //Allow sending empty messages, which is useful for text-references
-
- UserPointer user = currentMessageTargetUser();
- if( !user ) {
- log( "sendMessageButton(): target-user not available", Error );
- }
-
- if ( lmsg ) {
- if ( !( lmsg->info().user() == user ) )
- m_answerTo = 0;
- }
-
- TeamworkClientPointer::Locked l = m_client;
-
- if ( l ) {
- UserPointer::Locked ul = user;
- MessagePointer::Locked msg;
- if ( user && ul && ul->online() ) {
- switch ( m_widgets->messageType->currentIndex() ) {
- case Message: {
- msg = new KDevTeamworkTextMessage( l->messageTypes(), txt );
- break;
- }
- case SourceMessage: {
- QString docText;
- InDocumentReference ref( true, m_widgets->reference->text() );
- InDocumentReference endRef( false, m_widgets->reference->text() );
- KUrl docUrl = TeamworkFolderManager::workspaceAbsolute( ref.document() );
-
- IDocument* doc = KDevTeamworkPlugin::staticCore()->documentController()->documentForUrl( docUrl );
-
- if ( doc && doc->textDocument() ) {
- docText = doc->textDocument() ->text();
- ref.useText( docText );
- if( endRef )
- endRef.useText( docText );
- } else {
- log( "the document " + docUrl.url() + " is not open, weak-reference can not be computed. A simple line- and column-reference is created", Warning );
- }
- log( QString("created reference for: (%1, %2) : (%3, %4)").arg( ref.line() ).arg( ref.col() ).arg( endRef.line() ).arg( endRef.col() ), Debug );
-
- msg = new InDocumentMessage( l->messageTypes(), txt, ref, endRef, m_widgets->context->text() );
- msg.cast<InDocumentMessage>()->setConversation( m_messageManager->conversationManager().getConversation(msg.cast<InDocumentMessage>()) );
-
-
- InDocumentMessage* dmsg = msg.freeCast<InDocumentMessage>();
- if ( dmsg ) {
- msg.freeCast<InDocumentMessage>() ->contextLines() = DocumentContextLines( dmsg->start(), dmsg->end(), docText );
- } else {
- log( "error: could not build InDocumentMessage", Error );
- }
- break;
- }
- }
- if ( msg ) {
- if ( m_answerTo ) {
- MessagePointer::Locked la = m_answerTo;
- if ( la ) {
- msg->info().setReply( la->info().uniqueId() );
- msg->info().setReplyMessage( m_answerTo );
- }
- }
-
- ul->online().session().unsafe() ->send( msg );
- addSentMessageToList( msg );
- switch ( m_widgets->messageType->currentIndex() ) {
- case SourceMessage: {}
- }
-
- lockMessageGui( msg );
- m_messageManager->processMessage( msg.cast<KDevTeamworkTextMessage>() );
- } else {
- err( "could not create the message for sending" );
- }
-
- } else {
- if ( user && !ul )
- err( "could not lock the user" );
- if ( ul && !ul->online() )
- err( "no open session to user " + ~ul->name() );
- if ( !user )
- err( "target-user not existing" );
- err( "sending the message failed" );
- }
- } else {
- err( "could not lock the client-handler while sending message" );
- }
-}
-
-
-void KDevTeamwork::handleTextMessage( SafeSharedPtr<KDevTeamworkTextMessage> smsg ) {
- LockedSharedPtr<KDevTeamworkTextMessage> msg = smsg;
- if ( msg ) {
- if ( !m_messageManager->processMessage( msg ) )
- addReceivedMessageToList( smsg );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful );
- } else {
- err( "could not lock incoming kdev-text-message" );
- }
-}
-
-void KDevTeamwork::restorePartialProjectSession( const QDomElement* el ) {
- m_patchesManager->restorePartialProjectSession( el );
- m_collaborationManager->restorePartialProjectSession( el );
- m_messageManager->restorePartialProjectSession( el );
-}
-
-void KDevTeamwork::savePartialProjectSession( QDomElement* el ) {
- m_patchesManager->savePartialProjectSession( el );
- m_collaborationManager->savePartialProjectSession( el );
- m_messageManager->savePartialProjectSession( el );
-}
-
-KDevTeamwork* KDevTeamwork::self() {
- return m_self;
-}
-
-#include "kdevteamwork.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt (nonexistent)
@@ -1,3 +0,0 @@
-add_subdirectory(dynamictext)
-add_subdirectory(libdiff2)
-add_subdirectory(network)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp (nonexistent)
@@ -1,634 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "basicsession.h"
-#include <boost/archive/archive_exception.hpp>
-
-#include "serialization.h"
-#include "logger.h"
-#include "handler.h"
-#include "messageimpl.h"
-#include "user.h"
-#include "messagetypeset.h"
-#include "helpers.h"
-#define MESSAGEDEBUG
-//#define DISABLETRYCATCH
-#define DISABLEUNIVERSALCATCH
-//#define DEBUGLOG(x) out( Logger::Debug ) << x
-//#define DEBUGLOG(x)
-#define DEBUGLOG( x ) cout << x
-
-namespace Teamwork {
-using namespace std;
-
-void compare( const std::vector<char>& buffer, const std::vector<char>& buffer2 ) {
- std::vector<char> buf1=buffer;
- buf1.push_back(0);
- std::vector<char> buf2=buffer2;
- buf2.push_back(0);
- std::cout << "comparing buffers, first buffer:\n" << &buf1[0] << "\nsecond buffer:\n" << &buf2[0] << "\n";
-}
-
-SessionReplyManager::SessionReplyManager( MutexInterfaceImpl* selfMutex ) : selfMutex_( selfMutex ) {}
-
-void SessionReplyManager::addWaitingMessage( MessageInterface* msg ) {
- waitingMessages_[ msg->uniqueId() ] = MessagePointer( msg );
-}
-
-bool SessionReplyManager::handleMessageWaiting( MessagePointer & msg ) {
- if ( msg ) {
- uint i = msg.unsafe() ->info().isReplyTo();
- if ( i ) {
- WaitingMap::iterator it = waitingMessages_.find( i );
- if ( it != waitingMessages_.end() ) {
- MessageInterface::ReplyResult ret;
- MessagePointer::Locked l = ( *it ).second;
- if ( l ) {
- if ( selfMutex_ )
- selfMutex_->lockCountDown();
- ret = l->gotReply( msg );
- if ( selfMutex_ )
- selfMutex_->lockCountUp();
- if ( !ret.messageHandled )
- msg.unsafe() ->info().setReplyMessage( ( *it ).second );
- } else {
- //err() << "could not lock waiting message";
- }
-
- if ( !ret.awaitingMore )
- waitingMessages_.erase( it );
-
- return ret.messageHandled;
- }
- }
- }
- return false;
-}
-
-void SessionReplyManager::removeAllMessages() {
- for ( WaitingMap::iterator it = waitingMessages_.begin(); it != waitingMessages_.end(); ++it ) {
- MessagePointer::Locked l = ( *it ).second;
- if ( l ) {
- if ( selfMutex_ )
- selfMutex_->lockCountDown();
- l->gotReply( MessagePointer() );
- if ( selfMutex_ )
- selfMutex_->lockCountUp();
- }
- }
-
- waitingMessages_.clear();
-}
-
-SessionReplyManager::~SessionReplyManager() {
- removeAllMessages();
-}
-
-SessionInterface::SessionInterface() {
-}
-
-SessionInterface::~SessionInterface() {
-}
-
-UserPointer SessionInterface::safeUser() const {
- return user_;
-}
-
-void SessionInterface::setUser( const UserPointer& user ) {
- user_ = user;
-}
-
-void SessionInterface::final() {
- /*UserPointer::Locked l = user_;
- if( l )
- l->setSession( this );*/
-}
-
-
-bool SessionInterface::handleMessage( MessagePointer /*msg*/ ) throw() {
- return false;
-}
-
-string toString( std::vector<char>& v ) {
- string ret;
- for ( uint a = 0; a < v.size(); a++ )
- ret += v[ a ];
- return ret;
-}
-
-void BasicTCPSession::initial( void ) {
- running_ = true;
- out() << "connecting";
- ost::TCPSession::initial();
- if ( isConnected() ) {
- out() << "connection successful";
- } else {
- err() << "connection failed";
- }
-
- if ( isActive() ) {}
- else {
- err() << "connection inactive";
- }
-}
-
-bool BasicTCPSession::inputOutput() {
- bool worked = false;
-#ifndef DISABLETRYCATCH
- try {
-#endif
- if ( isPending( pendingInput, 0 ) ) {
- if ( !receivingSize_ ) {
- std::vector<char> sz;
- int cnt = getData( sz, 4 );
- if ( cnt == 4 && sz.size() == 4 ) {
- int s = ( *( int* ) ( &sz[ 0 ] ) );
- if ( s >= 0 && s < MAXMESSAGESIZE ) {
- receivingData_.clear();
- receivingSize_ = s;
- //out() << "receiving message of size " << receivingSize_;
- } else {
- throw StreamError( "message-header-integer is wrong: " + formatInt( s ) );
- }
- } else {
- throw StreamError( "message-header-integer is wrong, count of bytes: " + formatInt( cnt ) + " size of buffer: " + formatInt( sz.size() ) );
- }
- DEBUGLOG( "receiving message of size " << receivingSize_ );
- }
-
- if ( isPending( pendingInput, 0 ) ) {
- receivingSize_ -= getData( receivingData_, receivingSize_ );
-
- if ( receivingSize_ <= 0 ) {
- ///process a complete message
- if ( !receivingData_.empty() ) {
- processIncomingMessage( receivingData_ );
- //out() << "got: " << toString( receivingData_ );
- MessagePointer msg = buildMessageFromBuffer( receivingData_, messages_, this );
- MessagePointer::Locked l = ( MessagePointer ) msg;
- if ( l ) {
- l->info().setSession( this );
- DEBUGLOG( "handling message of size " << receivingData_.size() << " and type " << messages_.identify( l ) );
- } else
- out() << "handling not lockable message";
-
- if ( msg ) {
- if ( !handleMessageWaiting( msg ) )
- handleMessage( msg );
- } else {
- err() << "a received message could not be reconstructed";
- }
- worked = true;
- }
-
- receivingSize_ = 0;
- receivingData_.clear();
- }
- //out() << "received: " << receivingData_.size() << " yet needed: " << receivingSize_;
- }
- }
- if ( sendData_.empty() ) {
- //if( sendingMessage_ )
- sendingResult( true );
- serializeMessage();
- }
- if ( !sendData_.empty() ) {
- //out() << "writing " << sendData_.size();
- uint cnt = writeData( sendData_, sendData_.size() );
- //DEBUGLOG( "wrote " << cnt << " left: " << sendData_.size() );
- //if( sendData_.empty() )
- if ( cnt )
- worked = true;
- }
-
-#ifndef DISABLETRYCATCH
-
- } catch ( const StreamError & err ) {
- failed( std::string( "stream-error in inputOuput: " ) + err.what() );
- }
- catch( const boost::archive::archive_exception& exc ) {
- failed( std::string( "archive-exception while deserializing message: " + std::string( exc.what() ) ) );
- }
-
-#ifndef DISABLEUNIVERSALCATCH
- catch ( std::exception & err ) {
- failed( std::string( "exception occurred in inputOuput: " ) + err.what() );
- } catch ( ... ) {
- failed( std::string( "unknown exception occurred in inputOuput" ) );
- }
-#endif
- #endif
-
- return worked;
-}
-
-
-void BasicTCPSession::serializeMessage() {
- if ( !messagesToSend_.empty() ) {
- MessagePointer::Locked mp = messagesToSend_.front().lock();
- if ( !mp )
- err() << "could not lock message";
- else {
-
-#ifndef DISABLETRYCATCH
- try {
-#endif
- sendingMessage_ = messagesToSend_.front();
- if ( !tcp() )
- throw StreamError( "tcp-stream missing" );
- std::vector<char> buffer;
- serializeMessageToBuffer( buffer, *mp );
-#ifdef MESSAGEDEBUG
-
- MessagePointer clone;
- try {
- clone = buildMessageFromBuffer( buffer, messages_, 0 );
- } catch ( const CannotReserialize& ) {
- clone = 0;
- }
- catch( const boost::archive::archive_exception& e ) {
- err() << "archive-exception while reconstructing message: " << e.what();
- }
- catch ( ... ) {
- err() << "exception while reconstructing the message";
- throw;
- }
- try {
- if ( clone ) {
- std::vector<char> buffer2;
- serializeMessageToBuffer( buffer2, *clone.unsafe() );
- if ( buffer2.size() == buffer.size() ) {
- if ( memcmp( &buffer[ 0 ], &buffer2[ 0 ], buffer.size() ) != 0 )
- err() << "the reconstruction of a message of type \"" << mp->name() << "\" is wrong, the serialized content does not match!" ;
- compare( buffer, buffer2 );
- } else {
- err() << "the reconstruction of a message of type \"" << mp->name() << "\" is wrong!(mismatch in size: " << buffer.size() << " -> " << buffer2.size() << ")" ;
- compare( buffer, buffer2 );
- }
- } else {
- err() << "a message that is being sent could not be reconstructed for debugging: \"" << mp->name() << "\"";
- }
- } catch ( const CannotReserialize& )
- {}
- catch( const boost::archive::archive_exception& e ) {
- err() << "archive-exception while reconstructing message: " << e.what();
- }
-#ifndef DISABLEUNIVERSALCATCH
-
- catch ( ... ) {
- err() << "exception while serializing the reconstructed message";
- throw;
- }
-#endif
-#endif
- processOutgoingMessage( buffer );
- sendData_ = binaryInt( buffer.size() );
- sendData_ += buffer;
- //out() << "sending: " << toString( buffer );
-
- DEBUGLOG( "serialized outgoing message of size " << sendData_.size() << " and type " << messages_.identify( mp ) );
-
-#ifndef DISABLETRYCATCH
-
- } catch ( const NonFatalSerializationError & error ) {
- err() << std::string( "could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( error.what() );
- mp->result( false );
- if ( mp->info().isReplyTo() ) {
- MessageInterface * msg = new SystemMessage( messages_, SystemMessage::SerializationFailed, error.what() );
- msg->info().setReply( mp->info().isReplyTo() );
- messagesToSend_.pop_front();
- messagesToSend_.push_front( msg );
- return ;
- }
- }
- catch( const boost::archive::archive_exception& exc ) {
- err() << "archive-exception while reconstructing message: " << exc.what();
- failed( std::string( "could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( exc.what() ) );
- }
-#ifndef DISABLEUNIVERSALCATCH
- catch ( const std::exception & exc ) {
- failed( std::string( "error: could not serialize message of type \"" ) + mp->name() + "\", reason: " + std::string( exc.what() ) );
- } catch ( ... ) {
- failed( "error: could not serialize message " + mp->name() );
- }
-#endif
-#endif
-
- }
- messagesToSend_.pop_front();
- }
-}
-
-template <class DataType>
-u32 BasicTCPSession::writeData( std::vector<DataType>& from, u32 max ) {
- u32 count = 0;
- if ( isPending( pendingOutput, 0 ) ) {
- while ( isPending( pendingOutput, 0 ) && isOk() && count != max ) {
- int Portion = 1000;
- if ( max ) {
- if ( count + Portion > max ) {
- Portion = max - count;
- }
- }
- u32 write = Socket::writeData( &from[ count ], Portion * sizeof( DataType ) );
- //DEBUGLOG( "wrote portion of size " << write );
- if ( write == 0 || write == 0xffffffff ) {
- if ( isPending( pendingOutput, 0 ) ) {
- throw StreamError( "writeData could not send" );
- }
-
- return count;
- } else {
- u32 units = write / sizeof( DataType );
- if ( write % sizeof( DataType ) != 0 ) {
- throw StreamError( "writeData wrote a wrong unit" );
- }
- count += units;
- }
- }
- }
- if ( count == from.size() ) {
- from.clear();
- } else {
- std::vector<DataType> newVec;
- newVec.resize( from.size() - count );
- memcpy( &newVec[ 0 ], &from[ count ], ( from.size() - count ) * sizeof( DataType ) );
- from = newVec;
- }
-
- return count;
-}
-
-template <class DataType>
-u32 BasicTCPSession::getData( std::vector<DataType>& to, u32 max ) {
- u32 count = 0;
- if ( isPending( pendingInput, 0 ) ) {
- while ( isPending( pendingInput, 0 ) && isOk() && count != max ) {
- u32 osize = to.size();
- int Portion = 1000;
- if ( max ) {
- if ( count + Portion > max ) {
- Portion = max - count;
- }
- }
- to.resize( osize + Portion );
- u32 read = Socket::readData( ( char* ) & to[ osize ], Portion * sizeof( DataType ) );
- if ( read == 0 || read == 0xffffffff ) {
- to.resize( osize );
- if ( isPending( pendingInput, 0 ) ) {
- throw StreamError( "could not get data" );
- }
-
- //DEBUGLOG( "got " << count );
- return count;
- } else {
- u32 units = read / sizeof( DataType );
- count += units;
- to.resize( osize + units );
- if ( read % sizeof( DataType ) != 0 ) {
- throw StreamError( "getData got a wrong unit" );
- }
- }
- }
- }
- //DEBUGLOG( "got " << count );
- return count;
-}
-
-const int BasicTCPSession::ConnectionTimeout = 10000;
-
-
-BasicTCPSession::BasicTCPSession( const ost::InetHostAddress &host, ost::tpport_t port, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : ost::TCPSession( host, port ), SessionReplyManager( this ), myDirection( Outgoing ), exit_( false ), failed_( false ), running_( true ), hadFinal_(false), receivingSize_( 0 ), handler_( handler ), logger_( logger ), messages_( messages ), selfPointer_( this ) {
- initName( namePrefix );
-}
-
-
-BasicTCPSession::BasicTCPSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : ost::TCPSession( server ), SessionReplyManager( this ), myDirection( Incoming ), exit_( false ), failed_( false ), running_( true ), hadFinal_(false), receivingSize_( 0 ), handler_( handler ), logger_( logger ), messages_( messages ), selfPointer_( this ) {
- initName( namePrefix );
-}
-
-void BasicTCPSession::failed( std::string reason ) {
- err() << "failed: " << reason.c_str();
- sendingResult( false );
- failed_ = true;
- exit_ = true;
-}
-
-void BasicTCPSession::sendingResult( bool result ) {
- if ( sendingMessage_ ) {
- MessagePointer::Locked l = sendingMessage_;
- if ( l ) {
- lockCountDown();
- l->result( result );
- lockCountUp();
- if ( result && l->needReply( ) ) {
- addWaitingMessage( l );
- }
- } else {
- err() << "could not lock message for sendingResult!";
- }
- sendingMessage_ = 0;
- }
-}
-
-LoggerPrinter BasicTCPSession::err( int prio ) {
- LoggerPrinter p ( logger_, Logger::Error );
- if ( prio )
- p << prio << ":";
- p << "error in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-LoggerPrinter BasicTCPSession::out( Logger::Level lv ) {
- LoggerPrinter p ( logger_, lv );
- p << "in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-void BasicTCPSession::clearSelfPointer() {
- SafeSharedPtr<BasicTCPSession> s = selfPointer_;
- selfPointer_ = 0;
-}
-
-void BasicTCPSession::initName( const string& namePrefix ) {
- static int currentNum = 1;
- currentNum++;
- ostringstream o;
- o << currentNum;
- setSessionName( namePrefix + o.str() );
-}
-
-bool BasicTCPSession::dataToSend() {
- return !sendData_.empty();
-}
-
-void BasicTCPSession::run() {
- lockCountUp();
- while ( !exit_ ) {
- think();
- if ( !inputOutput() ) {
- lockCountDown();
- if ( !isPending( dataToSend() ? ( ost::Socket::Pending ) ( pendingInput | pendingOutput ) : pendingInput, 20 ) )
- sleep( 10 );
- lockCountUp();
- } else {
- lockCountDown();
- ///window for external mutex-requests
- lockCountUp();
- }
- if ( !isConnected() || !isActive() ) {
- out() << "session is closing because the connection is lost";
- exit_ = true;
- }
-
- if ( _Shared_count() == 1 && selfPointer_ ) { ///The session is only referenced by itself, so it may be deleted
- out() << "session is closing because the external reference-count reached zero";
- exit_ = true;
- }
- }
-
- out() << "session exiting";
- exit();
-}
-
-BasicTCPSession::~BasicTCPSession() {
- stopRunningNow();
- terminate();
- removeAllMessages();
-}
-
-bool BasicTCPSession::isOk() {
- return !exit_ && !failed_;
-}
-
-void BasicTCPSession::startSession() {
- start();
-}
-
-void BasicTCPSession::final( void ) {
- if( hadFinal_ ) return;
- SessionInterface::final();
- hadFinal_ = true;
- DEBUGLOG( "final" );
- removeAllMessages();
- exit_ = true;
- lockCountDown();
- running_ = false;
- endSocket(); /// think about how safe it is to call this
- clearSelfPointer();
-}
-
-bool BasicTCPSession::handleMessage( MessagePointer msg ) throw() {
- if ( handler_ ) {
- lockCountDown();
- bool ret = false;
- {
- HandlerPointer::Locked l = handler_;
- if ( l ) {
- DEBUGLOG( "giving message to handler" );
- l->handleMessage( msg );
- } else {
- out() << "could not lock handler";
- }
- }
- lockCountUp();
- return ret;
- } else {
- out() << "no handler";
- }
- return false;
-}
-
-void BasicTCPSession::removeAllMessages() {
- if ( sendingMessage_ ) {
- MessagePointer::Locked l = sendingMessage_;
- if ( l ) {
- lockCountDown();
- l->result( false );
- lockCountUp();
- }
- sendingMessage_ = 0;
- }
-
- SessionReplyManager::removeAllMessages();
-
- while ( messagesToSend_ ) {
- MessagePointer::Locked l = messagesToSend_.front();
- if ( l ) {
- l->result( false );
- } else {
- err() << "could not lock messages while removing it from send-list";
- }
- messagesToSend_.pop_front();
- }
-}
-
-bool BasicTCPSession::send( MessageInterface* msg ) {
- msg->info().setSession( this );
-
- //The following message indicates that the message's constructor does not correctly fill it's message-info. When this error happens, probably MessageConstructionInfo is not used correctly.
- if( !(msg->info().type() == messages_.idFromName( msg->name() )) )
- err() << "sending message that is flagged with an incorrect type, real type: " << msg->name() << " " << messages_.idFromName( msg->name() ).desc() << " flagged type: " << msg->info().type().desc();
-
- if ( !exit_ && !failed_ ) {
- messagesToSend_ << msg;
- } else {
- msg->result( false );
- return false;
- }
- return true;
-}
-
-void BasicTCPSession::stopRunning() {
- if ( !exit_ )
- out( Logger::Debug ) << "stop running";
- exit_ = true;
-}
-
-///This should get some tolerance in future
-void BasicTCPSession::stopRunningNow() {
- stopRunning();
- if ( !Thread::isThread() && Thread::isRunning() )
- Thread::join();
-}
-
-///Returns whether the thread is running
-bool BasicTCPSession::isRunning() {
- return running_ && Thread::isRunning();
-}
-
-string BasicTCPSession::peerDesc() {
- ostringstream str;
- ost::tpport_t port;
-
- str << getPeer( &port ) << ":" << port;
-
- return str.str();
-}
-
-string BasicTCPSession::localDesc() {
- ostringstream str;
- ost::tpport_t port;
-
- str << getLocal( &port ) << ":" << port;
-
- return str.str();
-}
-
-SessionInterface::SessionDirection BasicTCPSession::sessionDirection() {
- return myDirection;
-}
-
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h (nonexistent)
@@ -1,29 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef INTERFACES_H
-#define INTERFACES_H
-//
-// #include "serialization.h"
-// #include "safesharedptr.h"
-//
-// class SafeShared;
-// struct MessageSerialization;
-//
-// namespace Teamwork {
-// typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
-// }
-//
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/interfaces.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp (nonexistent)
@@ -1,225 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#include "basicserver.h"
-#include "serialization.h"
-
-#include "handler.h"
-#include "messageinterface.h"
-#include "basicsession.h"
-
-
-#define SLEEPTIME 50
-
-//#ifdef CCXX_NAMESPACES
-using namespace std;
-//#endif
-
-typedef char StandardDataType;
-
-
-namespace Teamwork {
-
-BasicTCPSocket::BasicTCPSocket( ost::InetAddress &ia, int port ) : ost::TCPSocket( ia, port ) {}
-
-bool BasicTCPSocket::onAccept( const ost::InetHostAddress &ia, ost::tpport_t port ) {
- setCompletion( false );
- cout << "accepting from: " << ia.getHostname() << ":" << port << endl;
-
- return true;
-}
-
-/**The MessageType holds all information necessary to Identify a Message and build an Object from it.
- The IdList is an inheritance-chain. Messages whose list begins with IDs of other Messages must be specializations of those, and the parent-types should be able to handle those too.
-*/
-
-void BasicServer::buildSocket() {
- closeSocket();
- failed_ = false;
-
- try {
- server_ = new BasicTCPSocket( addr, port_ );
- out() << "server is listening on " << addr << ":" << port_;
- } catch ( ost::Socket * socket ) {
- failed_ = true;
- ost::tpport_t port;
- int erro = socket->getErrorNumber();
- ost::InetAddress saddr = ( ost::InetAddress ) socket->getPeer( &port );
- err() << "socket error " << saddr.getHostname() << ":" << port << " = " << erro;
- if ( erro == ost::Socket::errBindingFailed ) {
- err() << "bind failed; port busy";
- } else {
- err() << "client socket failed";
- }
- if ( server_ )
- delete server_;
- server_ = 0;
- }
-}
-
-void BasicServer::run() {
- lockCountUp();
- out() << "server started";
- bool needMore = false;
- while ( !exit_ ) {
- lockCountDown(); ///leave room time other threads that try to lock this one
- if ( server_ && server_->isPendingConnection( needMore ? 1 : SLEEPTIME ) ) {
- lockCountUp();
- try {
- ost::InetHostAddress next = server_->getRequest();
- if ( !allowIncoming_ ) {
- out() << "refusing session for client " << next;
- server_->reject();
- } else {
- out() << "creating session for client " << next;
- SessionPointer tcp = createSession( server_ );
- if ( tcp ) {
- out() << "session created" ;
- if ( !registerSession( tcp ) ) {
- server_->reject();
- out() << "session rejected";
- } else {
- tcp.unsafe() ->startSession();
- }
- } else {
- out() << "session was rejected";
- server_->reject();
- }
- }
- } catch ( ost::Socket * socket ) {
- ost::tpport_t port;
- int err = socket->getErrorNumber();
- ost::InetAddress saddr = ( ost::InetAddress ) socket->getPeer( &port );
- cerr << "socket error " << saddr.getHostname() << ":" << port << " = " << err << endl;
- if ( err == ost::Socket::errBindingFailed )
- cerr << "bind failed; port busy" << endl;
- else
- cerr << "client socket failed" << endl;
- }
- } else {
- sleep( 10 );
- lockCountUp();
- }
- needMore = think();
-
- if ( _Shared_count() == 1 && selfPointer_ ) { ///The server is only referenced by itself, so it may be deleted
- out() << "server is closing because the external reference-count reached zero";
- exit_ = true;
- }
- }
- closeSocket();
-
- out() << "server exiting";
- stopRunning();
- exit();
-}
-
-void BasicServer::allowIncoming( bool allow ) {
- if ( allow ) {
- out() << "incoming connections activated, opening socket";
- buildSocket();
- } else {
- out() << "incoming connections deactivated, closing socket";
- closeSocket();
- }
- allowIncoming_ = allow;
-}
-
-void BasicServer::closeSocket() {
- if ( server_ )
- delete server_;
- server_ = 0;
-}
-
-/**Should be overridden to create own types derived from BasicTCPSession, can return 0*/
-SessionPointer BasicServer::createSession( BasicTCPSocket* sock ) {
- BasicTCPSession * s = new BasicTCPSession( *sock , new HandlerProxy<BasicServer>( this ), messageTypes_, logger_, "incoming_" );
- return s;
-}
-
-bool BasicServer::handleMessage( MessagePointer msg ) throw() {
- messagesToHandle_ << msg;
- return true;
-}
-
-
-LoggerPrinter BasicServer::err() {
- LoggerPrinter l( logger_, Logger::Error );
- l << "server: ";
- return l;
-}
-
-LoggerPrinter BasicServer::out( Logger::Level level ) {
- LoggerPrinter l( logger_, level );
- l << "server: ";
- return l;
-}
-
-void BasicServer::run();
-
-void BasicServer::initial() {
- Thread::initial();
-}
-
-bool BasicServer::think() {
- //messagesToHandle_.clear();
- return false;
-}
-
-void BasicServer::final( void ) {
- stopRunning();
- lockCountDown();
- clearSelfPointer();
-}
-
-bool BasicServer::registerSession( SessionPointer /*session*/ ) {
- return false;
-}
-
-void BasicServer::clearSelfPointer() {
- SafeSharedPtr<BasicServer> s = selfPointer_;
- selfPointer_ = 0;
-}
-
-LoggerPointer& BasicServer::logger() {
- return logger_;
-}
-
-BasicServer::BasicServer( const char* str, int port, MessageTypeSet& messageTypes, LoggerPointer logger, bool openServer ) : Thread( ), messageTypes_( messageTypes ), logger_( logger ), failed_( false ), exit_( false ), allowIncoming_( openServer ), server_( 0 ), port_( port ), selfPointer_( this ) {
- addr = str;
-
- if( allowIncoming_ )
- buildSocket();
-}
-
-BasicServer::~BasicServer() {
- closeSocket();
-}
-
-bool BasicServer::isOk() {
- return !exit_ && !failed_;
-}
-
-SafeList<MessagePointer>& BasicServer::messages() {
- return messagesToHandle_;
-}
-
-void BasicServer::stopRunning() {
- exit_ = true;
-}
-
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h (nonexistent)
@@ -1,890 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 include-file contains most of the meta-programming code used in this network-library.
- * The biggest part of it is management of simple type-lists(like adding a type, removing a type, finding one, etc.)
- * and building a static tree for message-dispatching. Unfortunately it's a bit hard to overview. :)
- */
-
-#ifndef STATICTREE
-#define STATICTREE
-
-#include "binder.h"
-#include <string>
-#include <cstring>
-
-typedef unsigned char uchar;
-namespace Tree {
-
-template <class Out>
-void printId( Out& out, const uchar* const id ) {
- for ( uint i = 0; i < std::strlen( ( char* ) id ); ++i ) {
- if ( i )
- out << ".";
- out << ( int ) id[ i ];
- }
-}
-
-template < int Condition, class Then, class Else >
-struct If {
- typedef Then Result;
-};
-
-template < class Then, class Else >
-struct If <0, Then, Else> {
- typedef Else Result;
-};
-
-struct Fail {
- enum {
- value = 0
- };
-};
-
-struct Success {
- enum {
- value = 1
- };
-};
-
-template < class Compare1, class Compare2, class Then, class Else >
-struct IfSame {
- typedef Else Result;
-};
-
-template < class Compare, class Then, class Else >
-struct IfSame<Compare, Compare, Then, Else> {
- typedef Then Result;
-};
-
-template <class Chain>
-struct Count {
- enum {
- value = 1
- };
-};
-
-template <>
-struct Count<Empty> {
- enum {
- value = 0
- };
-};
-
-template <int Condition>
-struct Assert {
- typedef Empty OK;
-};
-
-template <>
-struct Assert<0> {}
-;
-
-template <class Side1, class Side2>
-struct Count<Binder<Side1, Side2> > {
- enum {
- value = Count<Side1>::value + Count<Side2>::value
- };
-};
-
-template <int number, class Chain>
-struct GetListItem {
- ///The item does not exist
-};
-
-template <class Side1, class Side2>
-struct GetListItem<0, Binder<Side1, Side2> > {
- typedef typename GetListItem< 0, Side1>::Result Result;
-};
-
-template <class Item>
-struct GetListItem<0, Item> {
- typedef Item Result;
-};
-
-template <int number, class Side1, class Side2>
-struct GetListItem< number, Binder<Side1, Side2> > {
- ///If you get an error here which says that GetListItem<-1, ...> has no type named "Result",
- ///that probably means that the searched Item is not in the list. For the CrossMap it means that
- ///a key-type was used which is not in the list.
- typedef typename If < ( Count<Side1>::value > number ), GetListItem< number, Side1>, GetListItem< number - Count<Side1>::value, Side2 > > ::Result::Result Result;
-};
-
-
-
-
-
-template <class Type, uchar preferredSubId>
-class Entry {}
-;
-
-template <class Stuff, class Item>
-struct GetSlaves {
- typedef Entry<Empty, 0> Result;
-};
-
-template <class Stuff, class Item>
-struct GetParents {
- typedef Entry<Empty, 0> Result;
-};
-
-template <class Item1, class Item2>
-struct AddResults {
- typedef Binder<Item1, Item2> Result;
-};
-
-template <class Item1>
-struct AddResults<Empty, Item1> {
- typedef Item1 Result;
-};
-
-template <class Item1>
-struct AddResults<Item1, Empty> {
- typedef Item1 Result;
-};
-
-template <>
-struct AddResults<Empty, Empty> {
- typedef Empty Result;
-};
-
-template <class Item1, uchar a>
-struct AddResults<Entry<Empty, a>, Item1> {
- typedef Item1 Result;
-};
-
-template <class Item1, uchar a>
-struct AddResults<Item1, Entry<Empty, a> > {
- typedef Item1 Result;
-};
-
-template <uchar a, uchar b>
-struct AddResults<Entry<Empty, a>, Entry<Empty, b> > {
- typedef Entry<Empty, 0> Result;
-};
-
-///TODO!
-template <class Stuff>
-struct SortResultByIndex {
- typedef Stuff Result;
-};
-
-template <class Chain1, class Chain2, class Item>
-struct GetParents< Binder<Chain1, Chain2>, Item > {
- typedef typename AddResults< typename GetParents<Chain1, Item>::Result, typename GetParents<Chain2, Item>::Result >::Result Result;
-};
-
-template <class Chain1, class Chain2, class Item>
-struct GetSlaves< Binder<Chain1, Chain2>, Item > {
- typedef typename AddResults< typename GetSlaves<Chain1, Item>::Result, typename GetSlaves<Chain2, Item>::Result >::Result Result;
-};
-
-template <class Item1, class Item, uchar preferredSubId>
-struct GetSlaves< Chain< Item1, Item, preferredSubId >, Item> {
- typedef Entry<Item1, preferredSubId> Result;
-};
-
-template <class Item1, class Item, uchar preferredSubId>
-struct GetParents< Chain< Item1, Item, preferredSubId >, Item1> {
- typedef Entry<Item, preferredSubId> Result;
-};
-
-template <class Container >
-struct ExtractItem {
- typedef Container Result;
-};
-
-template <class Item, uchar preferredSubId>
-struct ExtractItem< Entry< Item, preferredSubId > > {
- typedef Item Result;
-};
-
-template < class Side1, class Side2 >
-struct ExtractItem < Binder< Side1, Side2 > > {
- typedef typename ExtractItem< Side1 >::Result Result;
-};
-
-template <class Slaves, class Stuff, class EntryTemplate, uchar currentNum >
-struct TreeNodeSlaves {
- enum ID {
- id = 0
- };
- template <class Action>
- inline uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
- return 0;
- }
- template < class Out >
- inline void print( Out& out, std::string prefix ) {
- out << prefix + "deadnode1\n";
- }
-};
-
-template <class Item1, class Item2>
-struct BindTogether {
- typedef Binder<Item1, Item2> Result;
-};
-
-template < class Item >
-struct BindTogether<Empty, Item> {
- typedef Item Result;
-};
-template < class Item >
-struct BindTogether<Item, Empty> {
- typedef Item Result;
-};
-
-template <>
-struct BindTogether<Empty, Empty> {
- typedef Empty Result;
-};
-
-///Action must have a member-template called Action, that has a typedef called Result. Action will be applied to each item, and the result bound together.
-template<class Action, class List>
-struct ForEachInList {
- typedef typename Action::template Action<List>::Result Result;
-};
-
-template<class Action, class List1, class List2>
-struct ForEachInList< Action, Binder<List1, List2> > {
- typedef typename BindTogether< typename ForEachInList< Action, List1 >::Result, typename ForEachInList< Action, List2 >::Result >::Result Result;
-};
-
-template <class Item>
-struct IsEmpty {
- enum {
- result = 0
- };
-};
-
-
-template <>
-struct IsEmpty<Empty> {
- enum {
- result = 1
- };
-};
-
-template <>
-struct IsEmpty<Binder<Empty, Empty> > {
- enum {
- result = 1
- };
-};
-
-template <class Item>
-struct Weight {
- enum {
- Result = 1
- };
-};
-
-template <class Left, class Right>
-struct Weight<Binder<Left, Right> > {
- enum {
- Result = Weight<Left>::Result + Weight<Right>::Result
- };
-};
-
-template <class Item>
-struct Balance {
- enum {
- RightOverweight = 0,
- LeftOverweight = 0
- };
-};
-
-template <class Left, class Right>
-struct Balance<Binder<Left, Right> > {
- enum {
- RightOverweight = Weight<Left>::Result < Weight<Right>::Result - 1 ? 1 : 0,
- LeftOverweight = Weight<Left>::Result > Weight<Right>::Result + 1 ? 1 : 0
- };
-};
-
-
-template <class From>
-struct RemoveOneLeft {
- typedef Empty Result;
-};
-
-template <class Left, class Right>
-struct RemoveOneLeft<Binder<Left, Right> > {
- typedef typename RemoveOneLeft<Left>::Result LeftRemoved;
- typedef typename IfSame<LeftRemoved, Empty, Right, typename BindTogether< LeftRemoved, Right >::Result >::Result Result;
-};
-
-template <class From>
-struct GetOneLeft {
- typedef From Result;
-};
-
-template <class Left, class Right>
-struct GetOneLeft<Binder<Left, Right> > {
- typedef typename GetOneLeft<Left>::Result Result;
-};
-
-template <class From>
-struct RemoveOneRight {
- typedef Empty Result;
-};
-
-template <class Left, class Right>
-struct RemoveOneRight<Binder<Left, Right> > {
- typedef typename RemoveOneRight<Right>::Result RightRemoved;
- typedef typename IfSame<RightRemoved, Empty, Left, typename BindTogether< Left, RightRemoved >::Result >::Result Result;
-};
-
-template <class From>
-struct GetOneRight {
- typedef From Result;
-};
-
-template <class Left, class Right>
-struct GetOneRight<Binder<Left, Right> > {
- typedef typename GetOneRight<Right>::Result Result;
-};
-
-template <class Into, class Item>
-struct InsertOneLeft {
- typedef Binder<Item, Into> Result;
-};
-
-template <class Left, class Right, class Item>
-struct InsertOneLeft< Binder<Left, Right>, Item> {
- typedef Binder<InsertOneLeft<Left, Item>, Right> Result;
-};
-
-template <class Into, class Item>
-struct InsertOneRight {
- typedef Binder<Into, Item> Result;
-};
-
-template <class Left, class Right, class Item>
-struct InsertOneRight< Binder<Left, Right>, Item> {
- typedef Binder<Left, InsertOneRight<Right, Item> > Result;
-};
-
-template <class Left, class Right, int LeftOverweight, int RightOverweight>
-struct BalanceNow {
- typedef Binder<Left, Right> Result;
-};
-
-template <class Left, class Right>
-struct BalanceNow<Left, Right, 1, 0> { ///Take one element from left to right side, and recurse
- typedef typename RemoveOneRight<Left>::Result NewLeft;
- typedef typename InsertOneLeft<Right, GetOneRight<Left> >::Result NewRight;
- typedef typename BalanceNow< NewLeft, NewRight, Balance< Binder<NewLeft, NewRight> >::LeftOverweight, Balance< Binder<NewLeft, NewRight> >::RightOverweight >::Result Result;
-};
-
-template <class Left, class Right>
-struct BalanceNow<Left, Right, 0, 1> { ///Take one element from left to right side, and recurse
- typedef typename InsertOneRight<Left, GetOneLeft<Right> >::Result NewLeft;
- typedef typename RemoveOneLeft<Right>::Result NewRight;
- typedef typename BalanceNow< NewLeft, NewRight, Balance< Binder<NewLeft, NewRight> >::LeftOverweight, Balance< Binder<NewLeft, NewRight> >::RightOverweight >::Result Result;
-};
-
-
-template <class Stuff>
-struct Rebalance {
- typedef Stuff Result;
-};
-
-template <class Left, class Right>
-struct Rebalance<Binder<Left, Right> > {
- typedef typename BalanceNow<Left, Right, Balance< Binder<Left, Right> >::LeftOverweight, Balance< Binder<Left, Right> >::RightOverweight >::Result Result;
-};
-
-template <class Item>
-struct Consider {}
-;
-
-class TreeNodeDataInterface {
- public:
-};
-
-template <class Type, class EntryTemplate>
-class TreeNodeData : public TreeNodeDataInterface, public EntryTemplate::template Entry <Type> {
- public:
- TreeNodeData() {}
-}
-;
-
-template < class Stuff, uchar cnum, uchar preferredSubId , class EntryTemplate>
-struct TreeNodeSlaves<Consider<Entry<Empty, preferredSubId> >, Stuff, EntryTemplate, cnum > {
- enum ID {
- id = 0
- };
- template <class Action>
- inline uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
- return 0;
- }
-
- template < class Out >
- inline void print( Out& /*out*/, std::string /*prefix*/ ) {
- }
-
- inline void buildFullId( const std::string& /*pre*/ ) {
- }
-};
-
-template < class Stuff, uchar cnum, class EntryTemplate >
-struct TreeNodeSlaves<Consider<Empty >, Stuff, EntryTemplate, cnum > {
- enum ID {
- id = 0
- };
- template <class Action>
- uchar find( const uchar /*c*/, const uchar*const /*id*/, Action& /*act*/ ) const {
- return 0;
- }
- template < class Out >
- inline void print( Out& /*out*/, std::string /*prefix*/ ) {
- }
-
- inline void buildFullId( const std::string& /*pre*/ ) {
- }
-};
-
-template <class Stuff>
-struct SortByIndex {
- typedef Stuff Result;
-};
-
-template <class Item>
-struct EntryIndex {
- ///The argument-type is wrong
-};
-
-template <class Type, uchar index>
-struct EntryIndex< Entry<Type, index> > {
- enum Result {
- result = index
- };
-};
-
-template <int w>
-struct StaticAssert {
- typedef Empty Ok;
-};
-
-template <>
-struct StaticAssert<0> {}
-;
-
-
-template <class Left, class Right>
-struct Merge {
- typedef typename GetOneLeft<Left>::Result LeftFirst;
- typedef typename GetOneLeft<Right>::Result RightFirst;
-
- typedef typename RemoveOneLeft<Left>::Result LeftTail;
- typedef typename RemoveOneLeft<Right>::Result RightTail;
-
- typedef typename StaticAssert < ( int ) EntryIndex<LeftFirst>::result != ( int ) EntryIndex<RightFirst>::result > ::Ok notSame;
-
- //typedef typename If<typename IsEmpty<LeftFirst>::Result, Right, typename If<typename IsEmpty<RightFirst>::Result, Left, typename MergeImpl<LeftFirst, RightFirst, LeftTail, RightTail>::Result >::Result>::Result Result;
- typedef typename If < ( int ) EntryIndex<LeftFirst>::result <= ( int ) EntryIndex<RightFirst>::result,
- Binder< LeftFirst, typename Merge< LeftTail, Binder<RightFirst, RightTail> >::Result >,
- Binder< RightFirst, typename Merge< Binder<LeftFirst, LeftTail>, RightTail >::Result > > ::Result Result;
-};
-
-template <class Only>
-struct Merge<Only, Empty> {
- typedef Only Result;
-};
-
-template <class Only>
-struct Merge<Empty, Only> {
- typedef Only Result;
-};
-
-
-template <class Left, class Right>
-struct Merge<Binder<Empty, Left>, Right> {
- typedef typename Merge<Left, Right>::Result Result;
-};
-
-template <class Left, class Right>
-struct Merge<Binder<Empty, Left>, Binder<Empty, Right> > {
- typedef typename Merge<Left, Right>::Result Result;
-};
-
-template <class Left, class Right>
-struct Merge<Left, Binder<Empty, Right> > {
- typedef typename Merge<Left, Right>::Result Result;
-};
-
-template <class Left, class Right>
-struct SortByIndex<Binder<Left, Right> > {
- typedef typename Merge< typename SortByIndex<Left>::Result, typename SortByIndex<Right>::Result >::Result Result;
-};
-
-template <class CurrentType, class Stuff, class EntryTemplate>
-class TreeNode : public TreeNodeData<CurrentType, EntryTemplate> {
- //typedef TreeNode<CurrentType, Stuff> TreeNodeType;
- typedef TreeNodeSlaves< Consider< typename SortByIndex< typename GetSlaves<Stuff, CurrentType>::Result>::Result > , Stuff, EntryTemplate, 1 > Slaves;
-
- Slaves slaves;
-
- ///This walks the tree until it cannot go on, then applies the given Action to the current node(additionally giving the type at the node as template-argument), and gives back the return-type(Action::ReturnType).
- public:
-
- inline void buildFullId( const std::string& pre ) {
- slaves.buildFullId( pre );
- }
-
- template < class Out >
- void print( Out& out, std::string prefix = "" ) {
- //out << prefix + " " << typeid( CurrentType ).name() << "\n";
- out << "no rtti";
- slaves.template print<Out>( out, prefix );
- }
-
- ///Searches the tree. Returns 0 if the action could be applied to no node, 1 if the action was applied but not to the searched leaf, and 2 if it was applied to the exact searched target
- template <class Action>
- inline uchar find( const uchar*const id, Action& act ) const {
- const uchar c = id[ 0 ];
- if ( c ) {
- uchar r = slaves.Slaves::template find<Action>
- ( c, id + 1, act );
- if ( !r ) {
- act.template operator() <CurrentType> ( *this );
- ;
- return 1;
- } else {
- return r;
- }
- } else {
- act.template operator() <CurrentType> ( *this );
- ;
- return 2;
- }
- }
-};
-
-struct StandardEntryTemplate {
- template <class Type>
- class Entry {}
- ;
-};
-
-template < class Class >
-struct GetBase {
- typedef typename Class::Precursor Result;
-};
-
-struct All {}
-;
-
-template <class Stuff>
-struct ExtractChains {
- typedef Chain< Stuff, typename GetBase< Stuff >::Result, Stuff::preferredIndex> Result;
-};
-
-template < class Side1, class Side2 >
-struct ExtractChains< Binder< Side1, Side2 > > {
- typedef typename BindTogether< typename ExtractChains< Side1 >::Result, typename ExtractChains<Side2>::Result >::Result Result;
-};
-
-template < class Side2 >
-struct ExtractChains< Binder< Empty, Side2 > > {
- typedef typename ExtractChains<Side2>::Result Result;
-};
-
-template < class Side2 >
-struct ExtractChains< Binder< Side2, Empty > > {
- typedef typename ExtractChains<Side2>::Result Result;
-};
-
-template <class A, class B, uchar C>
-struct ExtractChains< Chain< A, B, C > > {
- typedef Chain< A, B, C > Result;
-};
-
-
-template < class Item, class Master, class Stuff >
-struct WhatIsMissing {
- typedef typename Item::Template_Error_Wrong_Input_Should_Be_Chain Error;
-};
-
-template <class Stuff, class Item>
-struct Contains {
- enum {
- Result = 0
- };
-};
-
-template < class Item, class Parent, uchar C >
-struct Contains< Chain< Item, Parent, C >, Item > {
- enum {
- Result = 1
- };
-};
-
-template <class Side1, class Side2, class Item>
-struct Contains< Binder< Side1, Side2 >, Item > {
- enum {
- Result = Contains< Side1, Item >::Result | Contains< Side2, Item> :: Result
- };
-};
-
-
-template < class Item, class Parent, uchar C, class Master, class Stuff>
-struct WhatIsMissing< Chain< Item, Parent, C >, Master, Stuff > {
- enum {
- Result = !Contains< Stuff, Parent >::Result
- };
- typedef typename If< Result, Parent, Empty >::Result Items;
-};
-
-template < class Item, uchar C, class Master, class Stuff>
-struct WhatIsMissing< Chain< Item, Master, C >, Master, Stuff > {
- enum {
- Result = 0
- };
- typedef Empty Items;
-};
-
-template < class Side1, class Side2, class Master, class Stuff >
-struct WhatIsMissing< Binder< Side1, Side2 > , Master, Stuff > {
- enum {
- Result = WhatIsMissing<Side1, Master, Stuff>::Result | WhatIsMissing<Side2, Master, Stuff>::Result
- };
-
- ///Only return one by one, because multiple items might be missing the same parent and we don't want them multiple times
- typedef typename If< WhatIsMissing<Side1, Master, Stuff>::Result, typename WhatIsMissing<Side1, Master, Stuff>::Items, typename WhatIsMissing<Side2, Master, Stuff>::Items >::Result Items;
- //typedef BindTogether< typename WhatIsMissing<Side1, Master, Stuff>::Items, WhatIsMissing<Side2, Master, Stuff>::Items >::Items Items;
-};
-
-template <class Stuff, class Master, class Missing = typename WhatIsMissing<Stuff, Master, Stuff>::Items >
-struct MakeCompleteImpl {
- typedef typename MakeCompleteImpl< typename BindTogether< Stuff, typename ExtractChains< Missing >::Result >::Result , Master >::Result Result;
-};
-
-template <class Stuff, class Master >
-struct MakeCompleteImpl< Stuff, Master, Empty > {
- typedef Stuff Result;
-};
-
-///Makes sure that the chains for all necessary parent-nodes are available
-template < class Stuff, class Master >
-struct MakeComplete {
- typedef typename MakeCompleteImpl< Stuff, Master >::Result Result;
-};
-
-/**Stuff is the list of types that define the tree
-in form of multiple Chain<Type, Parent-Type, int preferredIndex>, and EntryTemplate is a class which embeds
-a template-class called "Entry" which will be inherited by every single node, with the current type of the node as template-parameter(See StandardEntryTemplate).
-Instead of using the explicit Chain<...>-notation, just a type can be used, and the chain will be extracted by using the type's Precursor"-Typedef, and it's preferredIndex constant/enum. Every item MUST have an explicit sub-id, the automatic generation of ID's was abandoned to make building partial trees easiert.
-Stuff is a set of "Chain"'s or Types, bound together with "Binder". It can be incomplete, only the important leafs have to be there, and the tree leading to them is extracted automatically.
- */
-template < class Master, class Stuff, class EntryTemplate = StandardEntryTemplate >
-struct TreeMasterNode : public TreeNode < Master, /* typename Rebalance<*/ typename MakeComplete< typename ExtractChains< Stuff >::Result, Master >::Result /*>::Result*/, EntryTemplate > {
- typedef TreeNode < Master, /*typename Rebalance<*/ typename MakeComplete< typename ExtractChains< Stuff >::Result, Master >::Result /*>::Result*/, EntryTemplate > Base;
-
- template < class Out >
- void print( Out& out ) {
- Base::buildFullId( "" );
- Base::print( out );
- }
-
- template <class Action>
- uchar find( const uchar*const id, Action& act ) const {
- return Base::find( id, act );
- }
-
-};
-/*
- template< class Item, class Stuff, class EndItem, int real >
- struct IsOnWay {
- };*/
-
-template <class Type>
-struct GetResultValue {
- enum {
- Result = Type::Result
- };
-};
-
-template <class Item>
-struct BaseItem {
- typedef Empty Result;
-};
-
-template <class Item1, class Item2>
-struct BaseItem< Binder< Item1, Item2 > > {
- typedef typename BaseItem<Item1>::Result Result;
-};
-
-template <class Base, class Parent, uchar preferredSubId>
-struct BaseItem< Chain< Base, Parent, preferredSubId > > {
- typedef Base Result;
-};
-
-
-/* template<class Item>
- struct GetParentHighLevel {
- typedef typename BaseItem<typename GetParents< typename MakeComplete< typename ExtractChains< Stuff >::Result >::Result>::Result>::Result Result;
-};*/
-
-template < class Item, class Stuff, class EndItem >
-struct IsOnWay {
- enum {
- Result = GetResultValue< IsOnWay< Item, Stuff, typename GetParents< Stuff, EndItem >::Result > >::Result
- };
-};
-
-template < class Item, class Stuff >
-struct IsOnWay< Item, Stuff, Item > {
- enum {
- Result = 1
- };
-};
-
-template < class Item, class Stuff >
-struct IsOnWay < Item, Stuff, Empty > {
- enum {
- Result = 0
- };
-};
-
-template < class Item, class Stuff, class Leaf >
-struct IsNecessary {
- enum {
- Result = IsOnWay< Item, Stuff, Leaf>::Result
- };
-};
-
-template < class Item, class Stuff >
-struct IsNecessary<Item, Stuff, All> {
- enum {
- Result = 1
- };
-};
-
-template < class Item, class Stuff, class Side1, class Side2 >
-struct IsNecessary<Item, Stuff, Binder< Side1, Side2 > > {
- enum {
- Result = IsNecessary< Item, Stuff, Side1 >::Result | IsNecessary< Item, Stuff, Side2 >::Result
- };
-};
-
-template <int necessary, class SlaveType, class Stuff, uchar id_, uchar preferredSubId, class EntryTemplate>
-struct TreeSlaveData {
- enum ID {
- id = id_ > preferredSubId ? id_ : preferredSubId
- };
- std::string fullId;
- TreeNode<SlaveType, Stuff, EntryTemplate> slave;
-
- TreeSlaveData() {}
-
- template < class Out >
- inline void print( Out& out, std::string prefix ) {
- prefix += "-";
- out << prefix + " ";
- if ( !fullId.empty() )
- printId( out, ( uchar* ) & fullId[ 0 ] );
- else
- out << "invalid-id";
- out << "\n";
- slave.print( out, prefix );
- }
-
- inline void buildFullId( const std::string& pre ) {
- fullId = pre;
- fullId.push_back( id );
- slave.buildFullId( fullId );
- }
-};
-
-/// It would be useful not to create this type at all, but currently it must be done for numbering-consistency
-template <class SlaveType, class Stuff, uchar id_, uchar preferredSubId, class EntryTemplate>
-struct TreeSlaveData< 0, SlaveType, Stuff, id_, preferredSubId, EntryTemplate> {
- enum {
- id = id_ > preferredSubId ? id_ : preferredSubId
- };
-
- inline void buildFullId( const std::string& pre ) {}
-
- ///dummies:
- struct DummySlave {
- template <class Action>
- inline uchar find( const uchar*const /*id*/, Action& /*act*/ ) const {
- return 0;
- }
- };
- DummySlave slave;
-
- template < class Out >
- inline void print( Out& out, std::string prefix ) {}
-
-}
-;
-
-///IsNecessary<Slave, Stuff, ExtractLeafs>::Result
-template <class Slave, class Stuff, uchar cnum, uchar preferredSubId, class EntryTemplate>
-struct TreeNodeSlaves< Consider<Entry<Slave, preferredSubId> >, Stuff, EntryTemplate, cnum> : public TreeSlaveData<1, Slave, Stuff, cnum, preferredSubId, EntryTemplate> {
- typedef TreeSlaveData<1, Slave, Stuff, cnum, preferredSubId, EntryTemplate> Base;
- inline void buildFullId( const std::string& pre ) {
- Base::buildFullId( pre );
- }
-
- template <class Action>
- inline uchar find( const uchar c, const uchar*const id, Action& act ) const {
- if ( c == Base::id ) {
- return Base::slave.template find<Action>( id, act );
- } else {
- return 0;
- }
- }
-
- template < class Out >
- inline void print( Out& out, std::string prefix ) {
- Base::print( out, prefix );
- }
-};
-
-template <class Slave1, class Slave2, class Stuff, uchar cnum, class EntryTemplate>
-struct TreeNodeSlaves< Consider<Binder<Slave1, Slave2> >, Stuff, EntryTemplate, cnum> : private TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum>, private TreeNodeSlaves < Consider<Slave2>, Stuff, EntryTemplate, TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum>::id + 1 > {
- typedef TreeNodeSlaves<Consider<Slave1>, Stuff, EntryTemplate, cnum> Side1;
- typedef TreeNodeSlaves < Consider<Slave2>, Stuff, EntryTemplate, Side1::id + 1 > Side2;
- enum {
- begin = cnum,
- middle = Side1::id,
- id = Side2::id
- };
-
- inline void buildFullId( const std::string& pre ) {
- Side1::buildFullId( pre );
- Side2::buildFullId( pre );
- };
-
- template <class Action>
- inline uchar find( const uchar c, const uchar*const id, Action& act ) const {
- if ( c > middle ) {
- return Side2::find( c, id, act );
- } else {
- return Side1::find( c, id, act );
- }
- }
- template < class Out >
- inline void print( Out& out, std::string prefix ) {
- Side1::print( out, prefix );
- Side2::print( out, prefix );
- }
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/statictree.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt (nonexistent)
@@ -1,47 +0,0 @@
-################################################################################################
-# This library needs to build without KDE4, please don't add KDE4 specific cmake stuff in here #
-################################################################################################
-
-PROJECT(network)
-
-SET(libfiles
- serverconfig.cpp
- message.cpp
- basicserver.cpp
- basicsession.cpp
- messageimpl.cpp
- helpers.cpp
- teamworkserver.cpp
- multisession.cpp
- user.cpp
- teamworkclient.cpp
- forwardsession.cpp
- logger.cpp
- sessioninterface.cpp
- dynamicmessagedispatcher.cpp
- )
-
-SET(testfiles main.cpp )
-
-#add definitions, compiler switches, etc.
-
-#ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions -finline)
-#ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions -fno-inline)
-ADD_DEFINITIONS(-Wall -ftemplate-depth-50 -D_REENTRANT -fexceptions)
-#list all source files here
-
-###### First Target ##########
-# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
-ADD_LIBRARY( kdevteamwork_network SHARED ${libfiles} )
-TARGET_LINK_LIBRARIES( kdevteamwork_network ${COMMONCPP2_LIBRARIES} ${Boost_SERIALIZATION_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${QT_QTCORE_LIBRARY})
-
-INSTALL(TARGETS kdevteamwork_network ${INSTALL_TARGETS_DEFAULT_ARGS})
-
-###### Next Target ##########
-
-ADD_EXECUTABLE( kdevteamwork_server ${testfiles} )
-TARGET_LINK_LIBRARIES( kdevteamwork_server ${QT_QTCORE_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} kdevteamwork_network ${COMMONCPP2_LIBRARIES} ${ZLIB_LIBRARIES} dl )
-
-INSTALL(TARGETS kdevteamwork_server ${INSTALL_TARGETS_DEFAULT_ARGS})
-
-#ADD_DEPENDENCIES( kdevteamwork_server network )
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h (nonexistent)
@@ -1,171 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGEIMPL_H
-#define MESSAGEIMPL_H
-
-#include "networkfwd.h"
-#include "messageinterface.h"
-#include "binder.h"
-#include "networkexport.h"
-///Since objects must have external linkage to be usable as template-arguments, these must be defined here.
-
-namespace Teamwork {
-
-typedef std::vector<char> DataVector;
-
-/** Example for a custom Message:
-class CustomMessage : public RawMessage {
- DECLARE_MESSAGE( CustomMessage, RawMessage, 83 );
- typedef vector<MyType> MyDataType;
- MyDataType myData;
-
- template<class Arch>
- void serial( Arch& arch ) {
- arch & myData;
-}
- public:
-
- CustomMessage( const MessageConstructionInfo& info, MyDataType& data ) : RawMessage( info(this) ), myData( data ) {
-}
-
- CustomMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {
- serial( arch );
-}
-
- virtual void serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-};
- */
-
- class MessageConstructionInfo;
- /**MessageConstructionInfo is a class used while constructing messages, that makes sure that the name of the most derived message will be passed on to RawMessage.
- *Use it by simply passing the this-pointer of each constructed message while passing it to the parent-message. */
-
- class NETWORK_EXPORT MessageConstructionInfo {
- public:
- //This is the constructor you are supposed to use when creating a message(use the automatic conversion from MessageTypeSet&)
- MessageConstructionInfo( const MessageTypeSet& rhs );
-
- //Use this to pass MessageConstructionInfo up to the parent, giving "this" as argument.
- template<class Message>
- MessageConstructionInfo operator() (Message* ) const {
- return MessageConstructionInfo( name_.empty() ? Message::staticName() : name_, typeSet_ );
- }
-
- const MessageTypeSet& typeSet() const;
-
- const std::string name() const;
-
- MessageInfo messageInfo() const;
-
- //operator () must be used when passing the construction-info to the parent
- MessageConstructionInfo( const MessageConstructionInfo& rhs );
-
- private:
- MessageConstructionInfo( const std::string& name, const MessageTypeSet& typeSet_ );
- MessageConstructionInfo& operator=( const MessageConstructionInfo& );
- std::string name_;
- const MessageTypeSet& typeSet_;
- };
-
- class NETWORK_EXPORT RawMessage : public MessageInterface
- {
- DECLARE_MESSAGE( RawMessage, MessageInterface, 1 );
-
- MessageInfo info_;
- DataVector body_;
-
- public:
-
- RawMessage( const MessageConstructionInfo& messageTypes, const DataVector& data );
-
- ///This should be used to indicate that this message is a reply to the other message(replyTarget)
- void setReply( MessageInterface* replyTarget );
-
- RawMessage( InArchive& from, const MessageInfo& info );
-
- virtual void serialize( OutArchive& target );
-
- virtual const MessageInfo& info() const;
-
- virtual MessageInfo& info();
-
- /**This is called once a message has been tried to be sent, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
- */
- virtual void result( bool success );
-
- /**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
- DataVector& body();
-
- /**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
- const DataVector& body() const;
- };
-
-
- class NETWORK_EXPORT TextMessage : public RawMessage {
- DECLARE_MESSAGE( TextMessage, RawMessage, 3 );
- public:
- explicit TextMessage( const MessageConstructionInfo& messageTypes, const std::string& text = "" );
-
- TextMessage( InArchive& from, const MessageInfo& info );
-
- std::string text() const;
- };
-
- struct NETWORK_EXPORT SystemMessage : public TextMessage
- {
- DECLARE_MESSAGE( SystemMessage, TextMessage, 2 );
- public:
- enum Message {
- NoMessage,
- LoginSuccess,
- LoginFailedUnknown,
- BadAuthentication,
- ServerBusy,
- Kicked,
- BadTarget,
- StoredOnServer,
- AlreadyLoggedIn,
- GetUserList,
- SerializationFailed
- };
- private:
- Message msg_;
-
- template<class Arch>
- void serial( Arch& arch ) {
- arch & msg_;
- }
- public:
- SystemMessage( const MessageConstructionInfo& messageTypes, Message msg, const string& ptext="" );
-
- SystemMessage( InArchive& arch, const MessageInfo& info );
-
- virtual void serialize( OutArchive& arch );
-
- Message message();
-
- string messageAsString();
- };
-
- typedef Binder< RawMessage > ::
- Append< TextMessage >
- ::Result::Append<SystemMessage>::Result StandardMessageTypes;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h (nonexistent)
@@ -1,207 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 is the file you should include when you only want to handle messages
- *
- * */
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "networkexport.h"
-#include <vector>
-#include <string>
-
-#ifndef MESSAGEINTERFACE_H
-#define MESSAGEINTERFACE_H
-
-namespace Teamwork {
-
-///UniqueMessageId represents the identity of a single message
-typedef uint64_t UniqueMessageId;
-
-///MessageType represents the Message-Type
-class NETWORK_EXPORT MessageType {
- public:
- typedef std::vector<unsigned char> IdList;
- private:
- IdList idList_;
- unsigned int fastId_; ///can only be used when the idList has <= 4 entries
- bool useFastId;
- UniqueMessageId uniqueId_; ///This is only filled when the MessageType belongs to a Message(0 means invalid)
- void packFastId();
- public:
- MessageType( IdList IDs = IdList() );
-
- MessageType( InArchive& from );
-
- template<class Archive>
- void serialize( Archive& target, const uint /*version*/ = 0 );
-
- ///Only compares the type-id, not the uniqueId
- bool operator == ( const MessageType& rhs ) const;
-
- bool operator < ( const MessageType& rhs ) const;
-
- bool startsWith( const MessageType& rhs ) const;
-
- ///Returns the length of the id
- int length() const;
-
- MessageType& operator += ( unsigned char append );
-
- MessageType& operator -- ();
-
- operator bool() const;
-
- std::string desc() const;
-
- operator const unsigned char*() const;
-};
-
-///this class holds information about the instance of a message(it's id and an optional pointer to the session/user it was created in/for)
-class NETWORK_EXPORT MessageInfo {
- MessageType id_;
- SessionPointer session_;
- UserPointer user_;
- MessagePointer replyToMessage_;
- UniqueMessageId isReplyTo_;
- UniqueMessageId uniqueId_;
- bool deserialized_;
- public:
-
- //Only for temporary usage
- MessageInfo();
-
- MessageInfo( InArchive& arch );
- MessageInfo( const MessageType& type, UniqueMessageId id );
- MessageInfo( const MessageType& type, UniqueMessageId id, const SessionPointer& session, UniqueMessageId isReplyTo = 0 );
- MessageInfo( const MessageInfo& rhs );
- MessageInfo& operator = ( const MessageInfo& rhs );
- ~MessageInfo();
-
- ///The session this message was received through/has been sent through.(whether received or sent: see isIncoming() )
- SessionPointer session() const;
-
- ///The user this message is related to.
- UserPointer user() const;
-
- ///Sets the session, and invalidates the user. If the session has an associated user, the user is used instead.
- void setSession( const SessionPointer& sess );
-
- ///Sets the user and invalidates the session. All session()-calls will be redirected to the session associated to the user.
- void setUser( const UserPointer& sess );
-
- const MessageType& type() const;
-
- void serialize( OutArchive& arch, const uint version = 0 );
-
- /**The unique id is the identity of a message-instance, not of the message-type */
- UniqueMessageId uniqueId() const;
-
- /**Since the uniqueId is not used for sorting this casts away constness so the id of a MessageType that is used as Key in a Map can be changed */
- void setUniqueId( UniqueMessageId newId ) const;
-
- /** if the message is a reply to another message, this should be the uniqueId of the other message.
- this function is thread-safe.(because after creation, this value should not be changed anymore) */
- UniqueMessageId isReplyTo() const;
-
- /** to make one message a reply to another while sending(to the other side), this is enough. To mark the message for local use, setReplyMessage(...) should be set too.*/
- void setReply( UniqueMessageId replyId );
-
- /** this does not automatically set the reply-id, it just sets a message-pointer. */
- void setReplyMessage( const MessagePointer& msg );
-
- ///If the reply is not handled directly by the message that the reply has gone to, the message this is a reply to is stored here.(The message with the id isReplyTo() ), may be invalid
- const MessagePointer& replyToMessage() const;
-
- void setId( const MessageType& id );
-
- /**Removes all kept references to important objects like sessions(those might keep the sessions alive too long)
- this should be called before a message is stored permanently */
-
- void makePersistent();
-
- ///Returns whether the message was constructed from a stream(if false, it was created locally)
- bool isIncoming() const;
-
- ///This can be used to set the isIncoming()-flag. The application or messages may use the flag as indication whether the message is incoming or outgoing.
- void setIsIncoming( bool b );
-};
-
-/**Since messages can have different IDs in different Message-Sets, the id's cannot be hardcoded and must be given with each creation.
-That is simplified by using MessageTypeSet::create which directly fills the correct id
-To create and use an own message there's three things to do:
-1. Implement a message based on MessageInterface(or simpler based on RawMessage)
-2. Within the class-declaration, use the DECLARE_MESSAGE(name, parent, subindex)-macro to define the inheritance used in the message-tree
-3. Register the message to the used MessageTypeSet, to register it to globalMessageTypeSet() simply use the REGISTER_MESSAGE(Message)-macro(within an implementation-file).
-Now the message can be sent and received. */
-
-class NETWORK_EXPORT MessageInterface : public SafeShared /*, public virtual Serializable*/ {
- public:
-
- virtual void serialize( OutArchive& target ) = 0;
-
- ///this function must be thread-safe(so the message does not need to be locked when it is called)
- virtual MessageInfo& info() = 0;
-
- virtual const MessageInfo& info() const = 0;
-
- /**This is called once a message has been tried to be send, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
- */
- virtual void result( bool success ) = 0;
-
- virtual ~MessageInterface();
-
- ///This function is thread-safe
- virtual const char* name();
-
- ///This function must be implemented for all messages, it is atomatically cared about by the DECLARE_MESSAGE(..) macros etc.
- static const char* staticName();
-
- ///This is just a convenience-function that redirects to info().type()
- const MessageType& type() const;
-
- ///This is just a convenience-function that redirects to info().uniqueId()
- UniqueMessageId uniqueId() const;
-
- ///This should return "true" when the message wants a reply. gotReply will then be called once a reply has been received. The default-implementation returns false.
- virtual bool needReply() const;
-
- struct NETWORK_EXPORT ReplyResult {
- bool messageHandled; ///This should indicate that the message was used locally and should not be handled on by higher instances
- bool awaitingMore; ///whether the message is awaiting more replies.(if this is true, the message will not be deleted and needReply will be called again as soon as another reply arrives)
- ReplyResult( bool messageHandled_ = false, bool awaitingMore_ = false );
- }
- ;
- /** p can be invalid, that means that the reply timed out. It is not guaranteed that this function is called. See the description of ReplyResult. */
- virtual ReplyResult gotReply( const MessagePointer& p );
-};
-}
-
-/**This class is used to derive messages from each other, it automatically creates some necessary entries for building static message-trees
-each message must have an explicit sub-id. You still have to care about
-the correct constructors.
-To create messages even easier and safer, see easymessage.h */
-
-#define DECLARE_MESSAGE( Name, parent, subindex ) \
- public: \
- inline static const char* staticName() { return #Name; } \
- typedef parent Precursor; \
- enum { \
- preferredIndex = subindex \
- }; \
- virtual const char* name() { return staticName(); }; \
- /*This little helper-functions returns true when the type as which the function is called is the real type of the message*/ \
- inline bool isDerived() { return strcmp( #Name, name() ) != 0; } \
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageinterface.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp (nonexistent)
@@ -1,335 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "basicserver.h"
-#include "basicsession.h"
-#include "teamworkserver.h"
-#include "messageimpl.h"
-#include "teamworkclient.h"
-#include "dynamicmessagedispatcher.h"
-#include <assert.h>
-#include <vector>
-#include <list>
-#include "handler.h"
-#include "serverconfig.h"
-#include "defines.h"
-
-using namespace Teamwork;
-#define USE_DYNAMIC_DISPATCHER
-
-#define CHECKARGS(b) if( !(b) ) { cout << "wrong argument-count"; return 3; }
-#define NEXTARG if( argc > 0 ) arg = argv[0]; else arg = ""; --argc;
-
-int changeSettings( int argc, char * argv[] ) {
- /*NEXTARG;
- NEXTARG;*/
- std::string arg = argv[1];
- cout << "\n\n\n\n";
- if( arg == "--help" || arg == "--info" || arg == "?" ) {
- cout << "possible commands configuration-manipulation-commands(everything within the [] is optional): \n";
- cout << "--adduser username [password] | Add the user to the list of known users\n";
- cout << "--serverpassword [password] | Change the server-wide password which is used for users without an own password. If empty, access is made public.\n";
- cout << "--servername name | Change the name of the server\n";
- cout << "--deluser username | delete a user from the list of known users\n";
- cout << "--list | list all registered users\n";
- cout << "--show | show current settings of the server\n";
- cout << "--setrights username [banned][admin][trusted] | change the rights of the user(no argument for normal user-rights)\n";
- cout << "--setport [port] | change the port the server is opened on(if the port is left away the default-port("<<STANDARDPORT<<") is used)\n";
- cout << "--setbind [address] | change the address the server is bound to(if it is left away the default(0.0.0.0) is used)\n";
- cout << "\nAll these commands manipulate the configuration-file created in the run-directory. \nThe settings will then apply for the next start of the server.\n";
- cout << "only one of the commands can be called at one time.\n";
- return 0;
- }
-
- ServerConfiguration conf;
- if( !Teamwork::loadServerConfiguration( conf ) ) {
- cout << "could not load the configuration-file" << endl;
- }
- bool changed = false;
-
- if( arg == "--setport" ) {
- NEXTARG;
- if( argc > 2 ) {
- conf.port = strtol( argv[2], 0, 10 );
- } else {
- conf.port = STANDARDPORT;
- }
- cout << "changed the port to " << conf.port << endl;
- changed = true;
- }
- if( arg == "--setbind" ) {
- if( argc > 2 ) {
- conf.bind = argv[2];
- } else {
- conf.bind = "0.0.0.0";
- }
- cout << "changed the bound address to " << conf.bind << endl;
- changed = true;
- }
-
- if( arg == "--setrights" ) {
- CHECKARGS( argc > 2 );
- std::string username = argv[2];
-
- int rights = User::UserRights;
-
- for( int n = 3; n < argc; n++ ) {
- if( argv[n] == std::string( "admin" ) ) rights |= User::AdminRights;
- if( argv[n] == std::string( "trusted" ) ) rights |= User::TrustedRights;
- }
-
- for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
- //UserPointer::Locked l = *it;
- if( it->name() == username ) {
- User u = *it;
- const_cast<User&>(*it).setRights( rights );
- changed = true;
- cout << "successfully set rights for " << it->name() << ": " << it->rightsAsString() << endl;
- break;
- }
- }
- if( !changed )
- cout << "could not find user \"" << username << "\"" << endl;
- }
-
- if( arg == "--show" ) {
- cout << "server-name: \"" << conf.serverName << "\"\n";
- cout << "server-password: \"" << conf.serverPassword << "\"\n";
- cout << "count of registered users: " << conf.registeredUsers.size() << endl;
- cout << "locally bound to address: " << conf.bind << " on port:" << conf.port << endl;
- }
-
- if( arg == "--list" ) {
- cout << "users:" << endl;
- for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
- //UserPointer::Locked l = *it;
- cout << it->name();
- if( !it->password().empty() )
- cout << " (has password)";
- cout << " rights: " << it->rightsAsString();
- cout << endl;
- }
- }
-
- if( arg == "--adduser" ) {
- CHECKARGS( argc > 2 );
- std::string username = argv[2];
- std::string password;
- if( argc > 3 )
- password = argv[3];
-
- bool passwordChanged = false;
-
- for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
- //UserPointer::Locked l = *it;
- if( it->name() == username ) {
- if( !password.empty() ) {
- const_cast<User&>(*it).setPassword( password );
- passwordChanged = true;
- break;
- } else {
- cout << "the user named \"" << username << "\" already exists" << endl;
- return 1;
- }
- }
- }
-
- if( passwordChanged ) {
- cout << "\"" << username << "\"'s password changed to: \"" << password << "\""<< endl;
- } else {
- cout << "user \"" << username << "\" added, password: \"" << password << "\""<< endl;
- conf.registeredUsers.insert( Teamwork::User( username, password ) );
- }
- changed = true;
- }
-
- if( arg == "--deluser" ) {
- CHECKARGS( argc > 2 );
- std::string username = argv[2];
- std::string password;
- if( argc > 3 )
- password = argv[3];
-
- bool found = false;
- for( std::set<User>::iterator it = conf.registeredUsers.begin(); it != conf.registeredUsers.end(); ++it ) {
- //UserPointer::Locked l = *it;
- if( it->name() == username ) {
- found = true;
- conf.registeredUsers.erase( it );
- break;
- }
- }
-
- if( found ) {
- changed = true;
- cout << "user \"" << username << "\" removed" << endl;
- } else {
- cout << "user \"" << username << "\" is not registered" << endl;
- return 4;
- }
- }
-
- if( arg == "--serverpassword" ) {
- if( argc > 2 ) {
- conf.serverPassword = std::string( argv[2] );
- cout << "server-password changed to \"" << conf.serverPassword << "\"" << endl;
- } else {
- if( conf.serverPassword.empty() ) {
- cout << "server-password already was disabled" << endl;
- } else {
- conf.serverPassword = "";
- cout << "server-password disabled" << endl;
- }
- }
- changed = true;
- }
-
- if( arg == "--servername" ) {
- CHECKARGS( argc > 2 );
- conf.serverName = std::string( argv[2] );
- changed = true;
- cout << "server-name changed to \"" << conf.serverName << "\"" << endl;
- }
-
- if( arg == "--servername" ) {
- CHECKARGS( argc > 2 );
- conf.serverName = std::string( argv[2] );
- changed = true;
- }
-
-
- if( changed ) {
- if( !Teamwork::saveServerConfiguration( conf ) ) {
- cout << "failed to save the configuration-file" << endl;
- return 2;
- }
- } else {
- cout << "bad arguments, see --help" << endl;
- }
-
- return 1;
-}
-
-using namespace Teamwork;
-
-#ifndef USE_DYNAMIC_DISPATCHER
-
-///Version that uses the static message-dispatcher
-class StandaloneServer : public Teamwork::Server {
- typedef Binder< RawMessage > :: Append< TextMessage > :: Result MessagesToDispatch;
- public:
- StandaloneServer( int port, std::string bind ) : Teamwork::Server( ServerInformation( bind, port ), new Logger() ) {
- }
- virtual ~StandaloneServer() {}
-
- int receiveMessage( TextMessage* msg ) {
- out() << "standalone-server got text-message: " << msg->text() << " real message-type: " << msg->name();
- return 1;
- }
-
- int receiveMessage( MessageInterface* msg ) {
- UserPointer::Locked lu = msg->info().user();
- out() << "standalone-server got unknown message: " << msg->name() << " from: " << (lu ? lu->name() : "unknown user" );
- return 1;
- }
-
- virtual bool handleMessage( MessagePointer m ) throw() {
- MessageDispatcher< StandaloneServer, MessagesToDispatch > dispatcher(*this);
- dispatcher( m.lock ().data() );
- return Teamwork::Server::handleMessage( m );
- }
-};
-
-#else
-
-///Version that uses the dynamic message-dispatcher (use these as examples)
-class StandaloneServer : public Teamwork::Server {
- DynamicMessageDispatcher dispatcher_;
- public:
- StandaloneServer( int port, std::string bind ) : Teamwork::Server( ServerInformation( bind, port ), new Logger() ) {
- dispatcher_.registerCallback<TextMessage>( this, &StandaloneServer::receiveTextMessage );
- dispatcher_.registerCallback<MessageInterface>( this, &StandaloneServer::receiveUnknownMessage );
- }
- virtual ~StandaloneServer() {}
-
- int receiveTextMessage( const SafeSharedPtr<TextMessage>& smsg ) {
- LockedSharedPtr<TextMessage> msg = smsg;
- out() << "standalone-server got text-message: " << msg->text() << " real message-type: " << msg->name();
- return 1;
- }
-
- int receiveUnknownMessage( const SafeSharedPtr<MessageInterface>& smsg ) {
- LockedSharedPtr<MessageInterface> msg = smsg;
- UserPointer::Locked lu = msg->info().user();
- out() << "standalone-server got unknown message: " << msg->name() << " from: " << (lu ? lu->name() : "unknown user" );
- return 1;
- }
-
- virtual bool handleMessage( MessagePointer m ) throw() {
- if( dispatcher_( m ) )
- return true;
- return Teamwork::Server::handleMessage( m );
- }
-};
-
-#endif
-
-int server() {
- ServerConfiguration conf;
- if( !Teamwork::loadServerConfiguration( conf ) ) {
- cout << "could not load the configuration-file, using defaults" << endl;
- }
-
- SafeSharedPtr<StandaloneServer> serv = new StandaloneServer( conf.port, conf.bind );
- serv.unsafe()->setConfiguration( conf );
- serv.unsafe() ->start();
- serv.unsafe() ->allowIncoming( true );
- cout << "server running on port " << conf.port << endl;
-
- serv.unsafe() ->join();
- return 0;
-}
-
-
-void test2() {
- globalMessageTypeSet().stats();
- SafeSharedPtr<Client> client1 = new Client( ServerInformation( "0.0.0.0", 8155 ) );
- client1.unsafe() ->allowIncoming( true );
- client1.unsafe() ->start();
- SafeSharedPtr<Client> client2 = new Client( ServerInformation( "0.0.0.0", 8156 ) );
- client2.unsafe() ->allowIncoming( true );
- client2.unsafe() ->start();
- {
- SafeSharedPtr<Client>::Locked l = client1;
- l->connectToServer( ServerInformation( "127.0.0.1", 8156 ), new User( "david", "honk", "I am a user" ) );
- }
-
- client2.unsafe() ->join();
-}
-
-
-int main( int argc, char * argv[] ) {
- if( argc > 1 ) {
- if( strcmp(argv[1], "test") != 0 ) {
- return changeSettings( argc, argv );
- } else {
- test2();
- }
- }
- server();
-
- return EXIT_SUCCESS;
-}
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/main.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h (nonexistent)
@@ -1,399 +0,0 @@
-/* This file is part of the KDE libraries
-Copyright 1999 Waldo Bastian <bastian@kde.org>
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Library General Public
-License version 2 as published by the Free Software Foundation.
-
-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.
-*/
-#ifndef SharedPTR_H
-#define SharedPTR_H
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/split_member.hpp>
-#include "networkexport.h"
-
-/**
- * Warning: Not thread-safe: use SafeShared for thread-safe reference-counting.
- * Reference counting for shared objects. If you derive your object
- * from this class, then you may use it in conjunction with
- * SharedPtr to control the lifetime of your object.
- *
- * Specifically, all classes that derive from Shared have an internal
- * counter keeping track of how many other objects have a reference to
- * their object. If used with SharedPtr, then your object will
- * not be deleted until all references to the object have been
- * released.
- *
- * You should probably not ever use any of the methods in this class
- * directly -- let the SharedPtr take care of that. Just derive
- * your class from Shared and forget about it.
- *
- * @author Waldo Bastian <bastian@kde.org>
- */
-class NETWORK_EXPORT Shared {
- public:
- /**
- * Standard constructor. This will initialize the reference count
- * on this object to 0.
- */
- Shared() : count( 0 ) { }
-
- /**
- * Copy constructor. This will @em not actually copy the objects
- * but it will initialize the reference count on this object to 0.
- */
- Shared( const Shared & ) : count( 0 ) { }
-
- /**
- * Overloaded assignment operator.
- */
- Shared &operator=( const Shared & ) {
- return * this;
- }
-
- /**
- * Increases the reference count by one.
- */
- void _Shared_ref() const {
- count++;
- }
-
- /**
- * Releases a reference (decreases the reference count by one). If
- * the count goes to 0, this object will delete itself.
- */
- void _Shared_unref() const {
- if ( !--count )
- delete this;
- }
-
- /**
- * Return the current number of references held.
- *
- * @return Number of references
- */
- int _Shared_count() const {
- return count;
- }
-
- protected:
- virtual ~Shared() { }
- private:
- mutable int count;
-};
-
-///NormaSerialization serializes the object in a primitive way by just calling the objects serialization-method.
-
-struct NETWORK_EXPORT NormalSerialization {
- template <class Type, class Archive, class Target>
- static void load( Target& t, Archive& arch, int /*version*/ ) {
- bool b = false;
- arch >> b;
- if ( b ) {
- t = new Type();
- t->serialize( arch, 0 );
- } else {
- t = 0;
- }
- }
-
- template <class Type, class Archive, class Target>
- static void save( Target& t, Archive& arch, int /*version*/ ) {
- if ( t ) {
- bool b = true;
- arch << b;
- const_cast<Type&>( *t ).serialize( arch, 0 );
- } else {
- bool b = false;
- arch << b;
- }
- }
-};
-
-
-template <class Type, class Container>
-struct extractItemUnsafe {
- static Type* extract( const Container& cont ) {
- return const_cast<Type*>( cont.unsafe() );
- }
-};
-
-
-/**BoostSerialization relies on boost's pointer-serialization(Which includes tracking, versioning, etc.).
- * Objects serialized this way must be registered to the boost serialization-system.
-*/
-struct NETWORK_EXPORT BoostSerialization {
- template <class Type, class Archive, class Target>
- static void load( Target& t, Archive& arch, int /*version*/ ) {
- bool b = false;
- arch >> b; //boost::serialization::make_nvp("valid",b);
- if ( b ) {
- Type * pnt = 0;
- arch & pnt;
- t = pnt;
- } else {
- t = 0;
- }
- }
-
- template <class Type, class Archive, class Target>
- static void save( Target& t, Archive& arch, int /*version*/ ) {
- if ( t ) {
- bool b = true;
- arch << b; //boost::serialization::make_nvp("valid",b);
- const Type* pnt = extractItemUnsafe<Type, Target>::extract( t );
- arch & pnt;
- } else {
- bool b = false;
- arch << b; //boost::serialization::make_nvp("valid",b);
- }
- }
-};
-
-struct BoostSerializationNormal {
- template <class Type, class Archive, class Target>
- static void load( Target& t, Archive& arch, int /*version*/ ) {
- bool b = false;
- arch >> b; //boost::serialization::make_nvp("valid",b);
- if ( b ) {
- Type * pnt = 0;
- arch & pnt;
- t = pnt;
- } else {
- t = 0;
- }
- }
-
- template <class Type, class Archive, class Target>
- static void save( Target& t, Archive& arch, int /*version*/ ) {
- if ( t ) {
- bool b = true;
- arch << b; //boost::serialization::make_nvp("valid",b);
- const Type* pnt = t.data();
- arch & pnt;
- } else {
- bool b = false;
- arch << b; //boost::serialization::make_nvp("valid",b);
- }
- }
-};
-/**
- * Can be used to control the lifetime of an object that has derived
- * Shared. As long a someone holds a SharedPtr on some Shared
- * object it won't become deleted but is deleted once its reference
- * count is 0. This struct emulates C++ pointers virtually perfectly.
- * So just use it like a simple C++ pointer.
- *
- * Shared and SharedPtr are preferred over QShared / QSharedPtr
- * since they are more safe.
- *
- * WARNING: Please note that this class template provides an implicit
- * conversion to T*. Do *not* change this pointer or the pointee (don't
- * call delete on it, for instance) behind SharedPtr's back.
- *
- * @author Waldo Bastian <bastian@kde.org>
- */
-
-template < class T, class Serialization = NormalSerialization >
-class NETWORK_EXPORT SharedPtr {
- public:
- friend class NormalSerialization;
- /**
- * Creates a null pointer.
- */
- inline SharedPtr()
- : ptr( 0 ) { }
- /**
- * Creates a new pointer.
- * @param t the pointer
- */
- inline SharedPtr( T* t )
- : ptr( t ) {
- if ( ptr )
- ptr->_Shared_ref();
- }
-
- /**
- * Copies a pointer.
- * @param p the pointer to copy
- */
- inline SharedPtr( const SharedPtr& p )
- : ptr( p.ptr ) {
- if ( ptr )
- ptr->_Shared_ref();
- }
-
- /**
- * Unreferences the object that this pointer points to. If it was
- * the last reference, the object will be deleted.
- */
- inline ~SharedPtr() {
- if ( ptr )
- ptr->_Shared_unref();
- }
-
- SharedPtr<T, Serialization>& operator= ( const SharedPtr<T, Serialization>& p ) {
- if ( ptr == p.ptr )
- return * this;
- if ( ptr )
- ptr->_Shared_unref();
- ptr = p.ptr;
- if ( ptr )
- ptr->_Shared_ref();
- return *this;
- }
-
- template <class Serialization2>
- SharedPtr<T, Serialization>& operator= ( const SharedPtr<T, Serialization2>& p ) {
- if ( ptr == p.ptr )
- return * this;
- if ( ptr )
- ptr->_Shared_unref();
- ptr = p.ptr;
- if ( ptr )
- ptr->_Shared_ref();
- return *this;
- }
-
- SharedPtr<T, Serialization>& operator= ( T* p ) {
- if ( ptr == p )
- return * this;
- if ( ptr )
- ptr->_Shared_unref();
- ptr = p;
- if ( ptr )
- ptr->_Shared_ref();
- return *this;
- }
- template <class Serialization2>
- inline bool operator== ( const SharedPtr<T, Serialization2>& p ) const {
- return ( ptr == p.ptr );
- }
- template <class Serialization2>
- inline bool operator!= ( const SharedPtr<T, Serialization2>& p ) const {
- return ( ptr != p.ptr );
- }
- inline bool operator== ( const T* p ) const {
- return ( ptr == p );
- }
- inline bool operator!= ( const T* p ) const {
- return ( ptr != p );
- }
- inline bool operator!() const {
- return ( ptr == 0 );
- }
- inline operator T*() const {
- return ptr;
- }
-
- /**
- * Returns the pointer.
- * @return the pointer
- */
- inline T* data() {
- return ptr;
- }
-
- /**
- * Returns the pointer.
- * @return the pointer
- */
- inline const T* data() const {
- return ptr;
- }
-
- /* inline const T& operator*() const {
- return * ptr;
- }*/
- inline T& operator*() {
- return * ptr;
- }
- inline T& operator*() const {
- return * const_cast<T*>( ptr );
- }
- /*inline const T* operator->() const {
- return ptr;
- }*/
- inline T* operator->() const {
- return const_cast<T*>( ptr ); ///That a reference to a pointer is constant does not mean that the pointed-to object is constant(to me)
- }
-
- template <class Archive>
- void load( Archive& arch, int /*version*/ ) {
- Serialization::template load<T>
- ( *this, arch, 0 );
- }
-
- template <class Archive>
- void save( Archive& arch, int /*version*/ ) const {
- Serialization::template save<T>
- ( *this, arch, 0 );
- }
- /*
- ///pointers without target are sorted as lowest
- template <class OT>
- bool operator < ( const SharedPtr<OT>& rhs ) const {
- if( ptr ) {
- if( rhs.ptr ) {
- return *ptr < *rhs.ptr;
- } else {
- return true;
- }
- } else {
- if( rhs.ptr ) {
- return true;
- } else {
- return false;
- }
- }
- }
-
- template <class OT>
- bool operator < ( const OT& rhs ) const {
- if( ptr ) {
- return *ptr < rhs;
- } else {
- return true;
- }
- }*/
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-
- /**
- * Returns the number of references.
- * @return the number of references
- */
- inline int count() const {
- return ptr->_Shared_count();
- } // for debugging purposes
- private:
- T* ptr;
-};
-
-
-template <class Type, class Serialization>
-struct extractItemUnsafe<Type, SharedPtr<Type, Serialization> > {
- static Type* extract( const SharedPtr<Type, Serialization>& cont ) {
- return const_cast<Type*>( cont.data() );
- }
-};
-
-/*template<class Type, class Serialization>
-Type* extractItemUnsafe( const SharedPtr< Type, Serialization >& cont ) {
-return const_cast<Type*>( cont.data() );
-}*/
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sharedptr.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp (nonexistent)
@@ -1,40 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "vector_stream.h"
-#include <assert.h>
-
-
-int main() {
- std::vector<char> testbuf;
- for( int a = 0; a < 100000; a++ )
- testbuf.push_back( a );
-
- std::vector<char> testbuf2 = testbuf;///lesetest
- std::vector<char> testbuf3;///schreibtest
-
- vector_device readDevice( testbuf2 );
- vector_device writeDevice( testbuf3 );
-
- for( int a = 0; a < 100; a++ ) {
- char buf[1000];
- readDevice.read( buf, 1000 );
- writeDevice.write( buf, 1000 );
- }
-
- for( int a = 0; a < 100000; a++ )
- assert( testbuf[a] == testbuf2[a] && testbuf[a] == testbuf3[a] );
-
- cout << "assert success\n";
-
- return 0;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vectest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp (nonexistent)
@@ -1,90 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "serverconfig.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include "serialization.h"
-#include <boost/archive/polymorphic_xml_oarchive.hpp>
-#include <boost/archive/polymorphic_xml_iarchive.hpp>
-#include <boost/serialization/list.hpp>
-#include <boost/serialization/set.hpp>
-#include <fstream>
-#include "defines.h"
-#include <iostream>
-
-#ifdef USE_POLYMORPHIC_ARCHIVE
-// #include <boost/archive/polymorphic_xml_iarchive.hpp>
-// #include <boost/archive/polymorphic_xml_oarchive.hpp>
-// typedef boost::archive::polymorphic_xml_iarchive InternalIArchive;
-// typedef boost::archive::polymorphic_xml_oarchive InternalOArchive;
-
-typedef boost::archive::polymorphic_text_iarchive InternalIArchive;
-typedef boost::archive::polymorphic_text_oarchive InternalOArchive;
-#else
-typedef Teamwork::InArchive InternalIArchive;
-typedef Teamwork::OutArchive InternalOArchive;
-#endif
-
-namespace Teamwork {
-
-ServerConfiguration::ServerConfiguration() : port( STANDARDPORT ), bind( "0.0.0.0" ) {
-}
-
-bool loadServerConfiguration( ServerConfiguration& conf ) {
- std::ifstream file( "teamwork.config", ios_base::in );
- if( !file.good() ) {
- cout << "could not open config-file" << endl;
- return false;
- }
- InternalIArchive arch( file );
- try {
- } catch( ... ) {
- cout << "error while reading the config-file" << endl;
- return false;
- }
- arch & conf;
- return true;
-}
-
-template<class Archive>
-void ServerConfiguration::serialize( Archive& arch, const unsigned int /*version*/ ) {
- arch & serverName;
- arch & serverPassword;
- arch & port;
- arch & bind;
- arch & registeredUsers;
-}
-
-
-bool saveServerConfiguration( ServerConfiguration& conf ) {
- std::ofstream file( "teamwork.config", ios_base::out );
- if( !file.good() ) {
- cout << "could not open config-file" << endl;
- return false;
- }
- /*boost::archive::polymorphic_text_oarchive*/
- InternalOArchive arch( file );
- try {
- } catch( ... ) {
- cout << "error while loading the config-file" << endl;
- return false;
- }
- arch & conf;
- return true;
-}
-
-INSTANTIATE_SERIALIZATION_FUNCTIONS( ServerConfiguration )
-
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp (nonexistent)
@@ -1,196 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#include "user.h"
-#include "serialization.h"
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/nvp.hpp>
-#include <boost/serialization/string.hpp>
-#include <boost/serialization/export.hpp> //must be included after archive-headers
-
-#include "sessioninterface.h"
-#include "teamworkmessages.h"
-
-namespace Teamwork {
-
-void OnlineInformation::setSession( const SessionPointer& sess ) {
- session_ = sess;
-}
-
-OnlineInformation::OnlineInformation( const OnlineInformation& /*rhs*/ ) {
-}
-
-OnlineInformation& OnlineInformation::operator = ( const OnlineInformation& /*rhs*/ ) {
- return *this;
-}
-
-OnlineInformation::OnlineInformation() {}
-
-OnlineInformation::~OnlineInformation() {
-}
-
-const SessionPointer& OnlineInformation::session() {
- return session_;
-}
-
-OnlineInformation::operator bool() {
- return session_ && session_.unsafe() ->isOk();
-}
-
-User::User( const User* user ) {
- *this = *user;
-}
-
-User::User( const UserIdentity& identity ) : name_ ( identity.name() ), rights_( UserRights ) {}
-
-User::User( string name, string password, string description ) : name_( name ), password_( password ), description_( description ), rights_( UserRights ) {}
-
-User::~User() {}
-
-int User::rights() const {
- return rights_;
-}
-
-std::string User::email() const {
- return email_;
-}
-
-void User::setEmail( const std::string& em ) {
- email_ = em;
-}
-
-std::string User::rightsAsString() const {
- std::string ret;
- if( rights_ & (int)UserRights ) ret += "user, ";
- if( rights_ & (int)TrustedRights ) ret += "trusted, ";
- if( rights_ & (int)AdminRights ) ret += "admin, ";
- if(!ret.empty() ) ret = ret.substr( 0, ret.length() - 2 );
-
- return ret;
-}
-
-void User::setRights( int rights ) {
- rights_ = rights;
-}
-
-bool User::matchRight( int right ) {
- return right & rights_;
-}
-
-OnlineInformation& User::online() {
- return online_;
-}
-
-template<class Archive>
-void User::serialize( Archive& arch, const uint /*version*/ ) {
- arch & boost::serialization::make_nvp( "Name", name_ );
- arch & boost::serialization::make_nvp( "password", password_ );
- arch & boost::serialization::make_nvp( "description", description_ );
- arch & boost::serialization::make_nvp( "rights", rights_ );
- arch & boost::serialization::make_nvp( "email", email_ );
-}
-
-///this function is used for authentication. The given user should be the one trying to connect.
-bool User::match( const User& u ) {
- if ( rights_ & BannedRights )
- return false;
- return ( password_.compare( u.password_ ) == 0 ) && ( name_.compare( u.name_ ) == 0 );
-}
-
-bool User::matchIdentity( const User& u ) {
- return name_ == u.name_;
-}
-
-///this function strips all information that is not necessary for correct authentication/identification at the given target-user
-void User::stripForTarget( const User& /*target*/ ) {
- password_ = "";
- description_ = "";
-}
-
-///strips away all information that should stay private, but leaves things like description etc.
-void User::stripForPublic() {
- password_ = "";
-}
-
-///this function strips all information that is not necessary to generally identify a user(this might strip away more than stripForTarget, and includes passwords and such)
-void User::stripForIdentification() {
- password_ = "";
- description_ = "";
-}
-
-UserIdentity User::identity() {
- return UserIdentity( name_ );
-}
-
-
-string User::description() const {
- return description_;
-}
-
-bool User::operator < ( const User& rhs ) const {
- return name_ < rhs.name_;
-}
-
-bool User::operator < ( const string& rhs ) const {
- return name_ < rhs;
-}
-
-bool User::operator < ( const UserIdentity& rhs ) const {
- return name_ < rhs.name();
-}
-
-string User::safeName() const {
- SafeSharedPtr<User>::Locked l = const_cast<User*>( this );
- if ( l ) {
- return name_;
- } else {
- return "unlockable_user";
- }
-}
-
-void User::setSession( const SessionPointer& sess ) {
- online_.setSession( sess );
-}
-
-const string& User::name() const {
- return name_;
-}
-
-const string& User::password() const {
- return password_;
-}
-
-void User::ban( bool banned ) {
- if( banned )
- rights_ |= BannedRights;
- else if( rights_ & BannedRights )
- rights_ -= BannedRights;
-}
-
-bool User::banned() const {
- return rights_ & BannedRights;
-}
-
-void User::setPassword( const string& password ) {
- password_ = password;
-}
-
-INSTANTIATE_SERIALIZATION_FUNCTIONS( User )
-}
-
-///This should be done for each class derived from User, so it can correctly be serialized from a pointer.
-BOOST_CLASS_EXPORT_GUID( Teamwork::User, "Teamwork::User" )
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp (nonexistent)
@@ -1,82 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#include "dynamicmessagedispatcher.h"
-#include <map>
-#include <list>
-
-
-namespace Teamwork {
-
-DynamicMessageDispatcher::DynamicMessageDispatcher( MessageTypeSet& messageTypes ) : m_messageTypes(messageTypes) {
-
-}
-
-DynamicMessageDispatcher::~DynamicMessageDispatcher() {
- for( DelivererList::iterator it = m_deliverers.begin(); it != m_deliverers.end(); ++it )
- delete *it;
-}
-
-void DynamicMessageDispatcher::addDeliverer( MessageDelivererBase* d ) {
- m_deliverers.push_back( d );
-}
-
-int DynamicMessageDispatcher::dispatch( const MessagePointer& msg ) {
- return operator() ( msg );
-}
-
-
-///@todo optimize this, a search-tree should be used, similar to the static tree.
-int DynamicMessageDispatcher::operator ()( const MessagePointer& msg ) {
-
- //Find the best matching targets:
- typedef std::map<int, std::list<MessageDelivererBase*> > TargetMap;
- TargetMap targets; //sort the targets by the match-depth
- for( DelivererList::iterator it = m_deliverers.begin(); it != m_deliverers.end(); ++it ) {
-
- //Find all targets that match
- //Remove already deleted targets
- while( it != m_deliverers.end() && !(*it)->isOk() ) {
- delete *it;
- it = m_deliverers.erase( it );
- }
- if( it == m_deliverers.end() )
- break;
-
- //If we have a match, put it into the list
- if( msg.unsafe()->type().startsWith( (*it)->type() ) ) {
- int orderPosition = -(*it)->type().length(); //minus so biggest become first
- TargetMap::iterator targetIt = targets.find( orderPosition );
- if( targetIt == targets.end() )
- targetIt = targets.insert( std::make_pair( orderPosition, std::list<MessageDelivererBase*>() ) ).first;
-
- (*targetIt).second.push_front( *it );
- }
- }
-
-
- for( TargetMap::const_iterator it = targets.begin(); it != targets.end(); ++it ) {
- for( std::list<MessageDelivererBase*>::const_iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); ++it2 ) {
- int ret = (*it2)->tryDeliverMessage( msg );
- if( ret != 0 ) {
- return ret; //Message successfully delivered
- }
- }
- }
-
- return 0; //Message could not be delivered, or all fitting targets returned 0
- }
-
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp (nonexistent)
@@ -1,125 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "multisession.h"
-#include "teamworkserver.h"
-#include "forwardsession.h"
-
-namespace Teamwork {
-
-MultiSession::MultiSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger ) : BasicTCPSession( server, handler, messages, logger, "incoming_" ), incoming_( true ) {}
-
-MultiSession::MultiSession( const ServerInformation& server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix ) : BasicTCPSession( server.addr().c_str() , server.port(), handler, messages, logger, namePrefix ), incoming_( false ) {}
-
-void MultiSession::deleteForwardSessions() {
- for ( ForwardSessionMap::iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ++it ) {
- ForwardSessionPointer::Locked l = ( *it ).second;
- if ( l ) {
- l->stopRunningNow();
- l->final();
- } else
- err() << "could not lock a Forward-session for final";
- }
- for ( list<ForwardSessionPointer>::iterator it = garbageSessions_.begin(); it != garbageSessions_.end(); ++it ) {
- ForwardSessionPointer::Locked l = ( *it );
- if ( l ) {
- l->stopRunningNow();
- l->final();
- } else
- err() << "could not lock a garbage Forward-session for final";
- }
- forwardSessions_.clear();
- garbageSessions_.clear();
-}
-
-void MultiSession::final() {
- deleteForwardSessions();
- BasicTCPSession::final();
-}
-
-bool MultiSession::think() {
- bool ret = false;
-
- for ( ForwardSessionMap::iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ) {
- ForwardSessionMap::iterator it2 = it;
- ++it;
- ///This costs very much and should be optimized once it works perfectly
- ForwardSessionPointer::Locked l = ( *it2 ).second;
- if ( l ) {
- if ( !( *it2 ).second.unsafe() ->isRunning() ) {
- l->final();
- forwardSessions_.erase( it2 );
- } else {
- l->think();
- }
- } else
- out() << "could not lock a forward-session for think/final";
- }
-
- for ( list<ForwardSessionPointer>::iterator it = garbageSessions_.begin(); it != garbageSessions_.end(); ) {
- list<ForwardSessionPointer>::iterator it2 = it;
- ++it;
- if ( !( *it2 ).unsafe() ->isRunning() ) {
- ForwardSessionPointer::Locked l = ( *it2 );
- if ( l ) {
- l->final();
- garbageSessions_.erase( it2 );
- } else
- out() << "could not lock a garbage Forward-session for final";
- }
- }
-
- return BasicTCPSession::think() | ret;
-}
-
-template <class Type>
- class FastLockHelper {}
-;
-
-MultiSession::~MultiSession() {
- deleteForwardSessions();
-}
-
-void MultiSession::registerForwardSession( const UserPointer& peer, const ForwardSessionPointer& sess ) {
- if ( forwardSessions_.find( peer ) != forwardSessions_.end() ) { ///finalize some older open session to the same target
- UserPointer::Locked u = peer;
- out() << "closing a duplicated indirect session to " << ( u ? u->name() : "not lockable" );
- forwardSessions_[ peer ].unsafe() ->stopRunning();
- garbageSessions_.push_back( forwardSessions_[ peer ] );
- }
-
- forwardSessions_[ peer ] = sess;
-}
-
-bool MultiSession::handleMessage( MessagePointer msg ) throw() {
- MessagePointer mp = msg;
- SafeSharedPtr<ForwardMessage> forward = mp.cast<ForwardMessage>();
- if ( forward ) {
- SafeSharedPtr<ForwardMessage>::Locked l = forward;
- UserPointer u( new User( l->source() ) );
- ForwardSessionMap::iterator it = forwardSessions_.find( u );
- if ( it != forwardSessions_.end() ) {
- ForwardSessionPointer::Locked l = ( *it ).second;
- if ( l ) {
- return l->handleForwardMessage( forward );
- } else {
- err() << "could not lock a forward-session to process an incoming forward-message";
- }
- }
- }
-
- return BasicTCPSession::handleMessage( msg );
-}
-
-}
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h (nonexistent)
@@ -1,92 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include <boost/iostreams/categories.hpp> // seekable_device_tag
-#include <boost/iostreams/positioning.hpp>
-#include <boost/iostreams/stream.hpp>
-#include <streambuf>
-#include <vector>
-#include <stdio.h>
-#include <iostream>
-#include <memory.h>
-
-#ifndef VECTOR_STREAM_H
-#define VECTOR_STREAM_H
-
-using namespace boost::iostreams;
-using namespace std;
-
-class vector_device {
- public:
- typedef char char_type;
- typedef bidirectional_device_tag category;
-
- vector_device( std::vector<char>& vec ) : v_(vec), readPosition_(0) {
- }
-
- std::streamsize read(char* s, std::streamsize n)
- {
- if( n + readPosition_ > v_.size() )
- n = v_.size() - readPosition_;
-
- memcpy( s, &(v_[readPosition_]), n );
- readPosition_ += n;
-
- return n;
- }
-
- std::streamsize write(const char* s, std::streamsize n)
- {
- uint oldSize = v_.size();
- v_.resize( oldSize + n );
- memcpy( &(v_[oldSize]), s, n );
- return n;
- }
-
- private:
- std::vector<char>& v_;
- uint readPosition_;
-};
-
-class vector_read_device {
- public:
- typedef char char_type;
- typedef bidirectional_device_tag category;
-
- vector_read_device( const std::vector<char>& vec ) : v_(vec), readPosition_(0) {
- }
-
- std::streamsize read(char* s, std::streamsize n)
- {
- if( n + readPosition_ > v_.size() )
- n = v_.size() - readPosition_;
-
- memcpy( s, &(v_[readPosition_]), n );
- readPosition_ += n;
-
- return n;
- }
-
- std::streamsize write(const char* /*s*/, std::streamsize /*n*/)
- {
- return 0;
- }
-
- private:
- const std::vector<char>& v_;
- uint readPosition_;
-};
-
-typedef boost::iostreams::stream<vector_device> vector_stream;
-typedef boost::iostreams::stream<vector_read_device> vector_read_stream;
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/vector_stream.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp (nonexistent)
@@ -1,300 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "teamworkclient.h"
-#include "forwardsession.h"
-#include "user.h"
-#include "teamworkmessages.h"
-#include "teamworkservermessages.h"
-#include "messagesendhelper.h"
-#include "multisession.h"
-
-
-namespace Teamwork {
-
-BIND_LIST_2( TeamworkClientDispatchMessages , ForwardMessage, UserListMessage )
-
-///Takes a list of SafeSharedPtr's, and returns a list of the same LockedSharedPtr's
-template <class Type, class Serialization>
-list< typename SafeSharedPtr<Type, Serialization>::Locked > lockList( const list< SafeSharedPtr<Type, Serialization> >& lst ) {
- list< typename SafeSharedPtr<Type, Serialization>::Locked > ret;
- for ( typename list< SafeSharedPtr<Type, Serialization> >::const_iterator it = lst.begin(); it != lst.end(); ++it ) {
- ret.push_back( *it );
- }
-
- return ret;
-}
-
-void Client::userDisconnected( const Teamwork::UserPointer& /*user*/ ) {
- needUserUpdate_ = true; ///The connected client may have been a client that created a direct connection to us, and which may still be reachable through an indirect connection, so an update is needed
-}
-
-
-///this is called whenever a connection is successfully established to a server
-void Client::connectedToServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ ) {}
-
-///this is called whenever the client disconnects from a connected server in any way
-void Client::disconnectedFromServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ ) {
- needUserUpdate_ = true; ///The connected server may have been a client we created a direct connection to, and which is still reachable through an indirect connection, so an update is needed
-}
-
-
-bool Client::think() {
- for ( ClientSessionMap::iterator it = clientSessions_.begin(); it != clientSessions_.end(); ) {
- if ( !( *it ).second.session.unsafe() ->isRunning() ) {
- out() << "closing outgoing session because it stopped running";
- disconnectedFromServer( ( *it ).second, ( *it ).first );
- ClientSessionMap::iterator itb = it;
- ++it;
- clientSessions_.erase( itb );
- } else {
- if ( needUserUpdate_ ) {
- send<SystemMessage>( ( *it ).second.session.unsafe(), SystemMessage::GetUserList );
- }
- ++it;
- }
- }
-
- needUserUpdate_ = false;
-
- return Server::think();
-}
-
-void Client::connectToServer( const ServerInformation& server, const UserPointer& asUser ) {
- if ( isConnectedToServer( server ) )
- disconnectFromServer( server );
-
- UserPointer p = asUser;
- if ( !p )
- p = identity();
- if ( !p ) {
- err() << "tried to connect to a server without having an identity";
- return ;
- }
-
- SessionInterface* session = new MultiSession( server, new HandlerProxy<BasicServer>( this ), messageTypes(), logger() , server.desc() + "_outgoing_" );
- clientSessions_[ server ] = ClientSessionDesc( p, session );
- session->startSession();
-
- UserPointer::Locked l = p;
- if ( l )
- send<IdentificationMessage>( clientSessions_[ server ].session.unsafe(), *l );
- else
- err() << "could not lock user";
-
- connectedToServer( clientSessions_[ server ], server );
-}
-
-bool Client::isConnectedToServer( const ServerInformation& server ) {
- return clientSessions_.find( server ) != clientSessions_.end();
-}
-
-MultiSessionPointer Client::sessionToServer( const ServerInformation& server ) {
- ClientSessionMap::iterator it = clientSessions_.find( server );
- if ( it == clientSessions_.end() )
- return 0;
- else
- return ( *it ).second.session.cast<MultiSession>();
-}
-
-void Client::disconnectFromServer( const ServerInformation& server ) {
- ClientSessionMap::iterator it = clientSessions_.find( server );
- if ( it != clientSessions_.end() ) {
- disconnectedFromServer( ( *it ).second, ( *it ).first );
- ( *it ).second.session.unsafe() ->stopRunning();
- clientSessions_.erase( it );
- }
-}
-
-void Client::disconnectAllServers () {
- int c = 0;
- while ( !clientSessions_.empty() && ++c < 50000 ) {
- disconnectFromServer( ( *clientSessions_.begin() ).first );
- }
-}
-
-int Client::receiveMessage( UserListMessage* msg ) {
- out( Logger::Debug ) << "handling user-list of size " << msg->users.size();
- std::list<UserPointer> users;
- {
- std::set
- <UserPointer::Locked, UserPointer::Locked::ValueSmallerCompare> allReceivedUsers;
-
- MultiSessionPointer session = msg->info().session().cast<MultiSession>();
-
- if ( !session ) {
- out() << "got a user-list message on an indirect session, ignoring";
- return 0;
- }
-
- MultiSessionPointer::Locked lsession = session;
- if ( !lsession ) {
- err() << "could not lock session while receiving user-list";
- return 0;
- }
-
- UserPointer::Locked sUser = lsession->safeUser();
-
- if ( !sUser )
- out( Logger::Debug ) << "sender of the user-list has no user-identity";
-
- ///compare the user-list received from the server and the slave-sessions registered to the session.
- list<UserPointer::Locked> sessionUsers = lockList( lsession->getUserList() );
-
- for ( list<User>::iterator it = msg->users.begin(); it != msg->users.end(); ++it ) {
- UserPointer::Locked l = getUser( createUser( &( *it ) ) );
- if ( !l ) {
- err() << "could not get/create indirect user " << ( *it ).name();
- continue;
- }
- if ( l->online() )
- continue; ///The user is already online, maybe through a direct connection
-
- ForwardSessionPointer s = lsession->getForwardSession( l );
-
- allReceivedUsers.insert( l );
-
- if ( s ) {
- ///There already is an open session to the user
- } else {
- ///Create a new session to the user
- users.push_back( l );
-
- l->setSession( new ForwardSession( identity(), l, msg->info().session().cast<MultiSession>(), logger(), messageTypes(), new HandlerProxy<BasicServer>( this ) ) );
- registerSessionUser( l ); ///Register the user together with its session, so it's noticed once the session is down.
- }
- }
-
- ///now invalidate all users that the session has a forward-session to but that were not listed by the server, because those probably are offline.
-
- for ( list<UserPointer::Locked>::iterator it = sessionUsers.begin(); it != sessionUsers.end(); ++it ) {
- std::set
- <UserPointer::Locked, UserPointer::Locked::ValueSmallerCompare>::iterator fnd = allReceivedUsers.find( *it );
- if ( fnd == allReceivedUsers.end() ) {
- ForwardSessionPointer p = lsession->getForwardSession( ( *it ).data() );
- if ( p ) {
- p.unsafe() ->stopRunning();
- out( Logger::Debug ) << "closing secondary session because the user went offline";
- }
- }
- }
-
- }
-
- //if( !users.empty() )
- gotUserList( users );
-
- return 1;
-}
-
-int Client::receiveMessage( MessageInterface* /*msg*/ ) {
- return 0;
-}
-
-int Client::receiveMessage( ForwardMessage * msg ) {
- out( Logger::Debug ) << "Client dispatching ForwardMessage";
- if ( !identity() )
- return 0;
- UserPointer::Locked l = identity();
- if ( !l ) {
- err() << "could not identity while processing a forwarded message";
- return 0;
- }
-
- if ( !l->matchIdentity( msg->target() ) )
- return 0; ///the server should forward the message to the correct target
-
- out() << "an indirect message from a not yet known client arrived";
-
- if ( !msg->info().session().cast<MultiSession>() ) {
- out() << "got a forward-message on an indirect session, ignoring";
- return 0;
- }
-
- MessagePointer::Locked cl = msg->deserializeContained( messageTypes() );
- if ( cl ) {
- UserPointer::Locked user = getUser( createUser( &msg->source() ) );
- if ( !user ) {
- err() << "could not get/lock the user for a forward-message";
- return 1;
- }
-
- ForwardSession* f = new ForwardSession( identity(), user, msg->info().session().cast<MultiSession>(), logger(), messageTypes(), new HandlerProxy<BasicServer>( this ) );
- f->setUser( f->target() );
- cl->info().setSession( f );
-
- if ( user->online() ) {
- out( Logger::Warning ) << "got indirect message from directly connected user " << user->name() << ", keeping communication indirect";
- } else {
- user->setSession( f );
- }
-
- processMessage( cl.data() );
- } else {
- out() << "could not handle a forwarded message";
- }
- return 1;
-}
-
-void Client::processMessage( MessageInterface* msg ) {
- MessageDispatcher< Client, TeamworkClientDispatchMessages > dispatcher(*this);
- if ( dispatcher( msg ) ) {
- out( Logger::Debug ) << "handled message in the client-class";
- } else {
- out( Logger::Debug ) << "handing message from client-class to the server-class";
- Server::processMessage( msg );
- }
-}
-
-///Is called whenever a connected server sends its list of connected users
-void Client::gotUserList( const std::list<UserPointer>& /*users*/ ) {
-}
-
-///this could be used to create a custom session deriven from MultiSession
-SessionPointer Client::createSession( BasicTCPSocket* sock ) {
- return Server::createSession( sock );
-}
-
-bool Client::registerSession( SessionPointer session ) {
- if ( ! Server::registerSession( session ) )
- return false;
-
- if ( session.unsafe() ->sessionDirection() != SessionInterface::Incoming )
- return true; ///Only send an identification-message to incoming connections, outgoing ones are sent directly while connecting
-
- if ( identity() ) {
- UserPointer::Locked l = identity();
- if ( l )
- send<IdentificationMessage>( session.unsafe(), *l );
- else
- err() << "could not lock user to send identifaction to a new client";
- } else {
- out() << "this server has no identity";
- }
-
- return true;
-}
-
-Client::Client( ServerInformation serverInfo, LoggerPointer logger ) : Server( serverInfo, logger ), needUserUpdate_( false ) {
- // messageTypes().registerMessageTypes<AllTeamworkClientMessages> ();
- //dispatcher_.print( cout );
- allowIncoming( false );
-}
-
-Client::~Client() {
- disconnectAllServers();
-}
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h (nonexistent)
@@ -1,729 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 file defines a multi-indexed set(called CrossMap) similar to boost's multi-index, but with simpler api, with support for index-lists, and less efficient.
-
-#ifndef CROSSMAP_H
-#define CROSSMAP_H
-
-
-#include "statictree.h"
-#include <map>
-#include <string>
-#include <ext/hash_map>
-#include <iostream>
-#include <list>
-#include "crossmapimpl.h"
-
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/hash_map.hpp>
-#include <boost/serialization/split_member.hpp>
-#include <boost/serialization/utility.hpp>
-#include <boost/serialization/map.hpp>
-
-namespace Utils {
-
-using namespace Meta;
-using namespace Tree;
-using namespace __gnu_cxx;
-using namespace std;
-//#define hash_map map
-
-///This can be specialized to get the keys non-intrusively.
-template <class KeyType, int number, class ItemType>
-KeyType getCrossMapKey( const ItemType& item ) {
- return item.template getKey<KeyType, number>();
-}
-
-/**A similar structure may be given to CrossMap to extract the keys in a different way, or the
- * Extractor-member may be specialized. Advantage: partial specialization is possible. */
-
-struct StandardCrossMapKeyExtractor {
- template <class KeyType, int number, class ItemType>
- struct Extractor {
- static KeyType getKey( const ItemType& item ) {
- return getCrossMapKey<KeyType, number, ItemType>( item );
- }
- };
-};
-
-///For the trivial identity no special extraction has to be specialized if StandardCrossMapKeyExtractor is used.
-template <class Type>
-struct StandardCrossMapKeyExtractor::Extractor< Type, 0, Type > {
- static const Type& getKey( const Type& item ) {
- return item;
- }
-};
-
-/**For very simple cases, specialization of getCrossMapKey can be simplified by using this macro.
- * For writing the expression the value is available as a const reference named "value", and the result
- * of the expression is used as key.
- * Example:
- * CROSSMAP_KEY_EXTRACTOR( MyValueType, MyValueType::Id, 0, value.id() );
- * */
-#define CROSSMAP_KEY_EXTRACTOR( ValueType, KeyType, Number, Expression ) \
-namespace Utils { \
-template <> \
-KeyType getCrossMapKey< KeyType, Number, ValueType>( const ValueType& value ) { \
- return Expression; \
-} \
-} \
-
-
-/**This macro can be used to create small wrapper-types that hold another type,
-
-* to access the type in the crossmap in a unique way
-* @example:
-* NAMED_TYPE( UserId, uint );
-* ...;
-* User v = map.value<UserId>( 5 ); ///Gets the user with user-id 5*/
-
-#define NAMED_TYPE(Name, type) \
-struct Name { type value; operator type&() { return value; }; static const char* name() { return #Name; }; Name( const type& v ) : value(v) {}; /*Name& operator = ( const type& t ) { value = t; };*/ Name() {}; bool operator < ( const Name& rhs ) const { return value < rhs.value; } template<class T> Name( const T& t ) : value( t ) {} template<class T> bool operator == ( const T& rhs ) const { return value == rhs.value; } }
-
-
-/**This may be specialized to define own container-types that should not be used as keys directly, but from which subkeys should be extracted
- * */
-
-#define CROSSMAP_DEFINE_CONTAINER( Cnt ) \
-namespace Utils { \
-template<class Type> \
-struct ExtractKeyType::Action<Cnt<Type> > { \
- typedef Type Result; \
- typedef True isContainer; \
-}; \
-} \
-
-
-template<class KeyList>
-struct RealKeys {
- typedef typename ForEachInList<ExtractKeyType, KeyList>::Result Result;
-};
-
-
-///Not used yet, but should be
-#define SET_HASHABLE(Type) template<> Utils::CrossMapHashTraits<Type> { enum { hashable = 1 } };
-
-///This can be used to mark types that should be managed using a hash_multimap instead of a sorted multimap
-template <class Type>
-struct Hashed {}
-;
-
-class CrossMapId {
- uint id_;
- public:
- CrossMapId() : id_( 0 ) {}
-
- CrossMapId( uint id ) : id_( id ) {}
-
- uint id() {
- return id_;
- }
-
- bool operator == ( const CrossMapId & rhs ) const {
- return id_ == rhs.id_;
- }
-
- CrossMapId& operator = ( const CrossMapId & rhs ) {
- id_ = rhs.id_;
- return *this;
- }
-
- bool operator < ( const CrossMapId & rhs ) const {
- return id_ < rhs.id_;
- }
-
- bool operator <= ( const CrossMapId & rhs ) const {
- return id_ <= rhs.id_;
- }
-
- template <class Archive>
- void serialize( Archive & arch, uint version ) {
- arch & id_;
- }
-
- operator uint() const {
- return id_;
- }
-};
-
-/**This is a kind of in-memory database that allows storing/sorting items by an arbitrary count of keys
- * and key-types. The keys are extracted in
- * the moment an item is inserted. If the keys change, update(..) should be called on the item.
- *
- *
- * It is very similar to the boost multi-index, but the api is a bit easier.
- *
- * Advantage against boost's multi-index: One item can be reachable by many indices in the same category,
- * by using CROSSMAP_DEFINE_CONTAINER(..) and giving such a key-container as to the key-list.
- * Then the item will be searchable by each key in the list.
- * (If the value-type is used as key, it will be filled with the key's value by default and no key-extractor needs to be defined for that case)
- * (Example: multiple filenames may be associated to users, and it is possible to get a list of users for each filename)
- *
- * Disadvantage: Less efficient, bigger binary
- *
- * @param Value The value-type, should be a type with a default-constructor(is used as Dummy for Functions like operator[] if the key cannot be found)
- * @param Keys a meta-list containing all keys(using BIND_LIST or Binder<...,...>
- * @param KeyExtractor (optional) a class that helps extracting the keys from the values
- * @param rebuildAfterLoad whether serialization should only store a list of values, without the additional maps and the cross-link-data etc.(then every key has to be re-extracted after the archive was loaded, and the structure may be different)
- */
-
-template <class Value, class Keys, class KeyExtractor = StandardCrossMapKeyExtractor>
-class CrossMap {
- typedef CrossMap< Value, Keys, KeyExtractor> Self;
- typedef KeyValueChain< Value, Keys, KeyExtractor> KeyValues;
- typedef typename RealKeys<Keys>::Result RealKeys;
- typedef CrossMapId Id;
-
- template <bool cacheKeys>
- struct ValueStore {
- Value value;
- KeyValues keyValues;
- ValueStore( const Value & v ) : value( v ), keyValues( v ) {}
- ValueStore& operator = ( const Value & v ) {
- value = v;
- keyValues = KeyValues( v )
- ;
- return *this;
- }
-
- operator Value& () {
- return value;
- }
- };
-
- typedef ValueStore< true > MyValueStore;
-
- bool rebuildAfterLoad_; ///@todo Not yet used
-
- public:
-
- typedef hash_map< uint, MyValueStore > ValueMap;
-
- /**Special care has to be taken when a ValueEditor-object is copied: When a ValueEditor is copied,
- * the source will not update the map on it's destruction, and all copies of a ValueEditor that does
- * not update the map won't do it neither. So generally it's safer to use a ValueEditor in-place, without copying it around. */
-
- class ValueEditor {
- Id id_;
- Self* map_;
- Value* value_;
- public:
- ValueEditor( Self* map, const Id id, Value* value ) : id_( id ), map_( map ), value_( value ) {}
-
- ValueEditor( const ValueEditor& e ) : id_( e.id_ ), map_( e.map_ ), value_( e.value_ ) {
- const_cast<ValueEditor&>( e ).id_ = 0; ///This is done so the destruction of the other ValueEditor doesn't update the map
- }
-
- ValueEditor& operator = ( const ValueEditor& rhs ) {
- map_ = rhs.map_;
- value_ = rhs.value_;
- id_ = rhs.id_;
- const_cast<ValueEditor&>( rhs ).id_ = 0; ///This is done so the destruction of the other ValueEditor doesn't update the map
- }
-
- ~ValueEditor() {
- if ( id_ )
- map_->update( id_ );
- }
-
- ///It is safe to edit a value through this operator. It is not safe to take the address or reference for further use.
- Value* operator ->() {
- return value_;
- }
- };
-
- ///An iterator represents a list of Items that can be iterated over. It depends on the map that created it.
- class Iterator {
- typedef std::list<uint> IdList;
- public:
- Iterator( Self * map = 0 ) : it_( ids_.begin() ), map_( map ) {}
-
- operator bool() const {
- return map_ && it_ != ids_.end();
- }
-
- Iterator& operator ++ () {
- ++it_;
- return *this;
- }
-
- const Value& operator *() const {
- return map_->valueFromId( *it_ );
- }
-
- const Value* operator ->() const {
- return & map_->valueFromId( *it_ );
- }
-
- /**Returns a ValueEditor-object that can be used to directly edit the values in-place comfortably and automatically update the map.
- * @see ValueEditor::operator -> */
- ValueEditor edit() {
- return ValueEditor( map_, *it_, &map_->valueFromId( *it_ ) );
- }
-
- ///expensive
- uint count() const {
- return ids_.size();
- }
-
- Id id() const {
- return * it_;
- }
-
- ///Must be called after the first ids are added, and can be called any time again to jump back to the beginning
- void restart() {
- it_ = ids_.begin();
- }
-
- operator Id() const {
- return * it_;
- }
-
- ///Compares the current value pointed to
- bool operator == ( const Iterator & rhs ) const {
- bool end1 = it_ == ids_.end();
- bool end2 = rhs.it_ == rhs.ids_.end();
- if ( end1 != end2 )
- return false;
- if ( end1 )
- return true;
- return *it_ == *rhs.it_;
- }
-
- private:
- void addId( uint id ) {
- ids_.push_back( id );
- }
-
-
- IdList::const_iterator it_;
- Self* map_;
- IdList ids_;
- friend class CrossMap< Value, Keys, KeyExtractor>;
- };
-
-
- /**
- * @param rebuildAfterLoad Whether the set should be stored compact(only the values themselves, without all the helper-maps). Not used yet.
- * */
- CrossMap( bool rebuildAfterLoad = true ) : rebuildAfterLoad_( rebuildAfterLoad ), currentId_( 1 ) {}
-
- /**The Functions that directly return a Value-Reference return a default-constructed dummy if the item cannot be found.
- * These are very simple convenience-functions that directly return the first matching item. iterator is much more powerful.
- * */
- template <class KeyType>
- const Value & operator[] ( const KeyType& key ) const {
- return value<0, KeyType>( key );
- }
-
- /**This is an expensive convenience-function. It returns a temporary object that allows access to the value, and once that object is destroyed
- * automatically updated the map. (That allows assignment-operations like mymap[5].name = "Honk").
- * But it is very expensive since every time the temporary object is destroyed, all keys are reevaluated and all maps are updated.
- * */
-
- /*
- template <class KeyType>
- ValueEditor<Value> & operator[] ( const KeyType& key ) {
-
- return value<0, KeyType>( key );
- }*/
-
-
- template <int keyNum, class KeyType>
- const Value& value( const KeyType & key ) const {
- typedef std::multimap<KeyType, uint> Map;
- const Map& map = getMap<keyNum, KeyType>();
- typename Map::const_iterator it = map.find( key );
- if ( it != map.end() ) {
- typename ValueMap::const_iterator itt = values_.find( ( *it ).second );
- if ( itt != values_.end() ) {
- return ( *itt ).second.value;
- }
- }
- return dummy_;
- }
-
- Iterator values() const {
- Iterator ret( const_cast<Self*>( this ) );
- for ( typename ValueMap::const_iterator it = values_.begin(); it != values_.end(); ++it )
- ret.addId( ( *it ).first );
-
- ret.restart();
- return ret;
- };
-
- template <int keyNum, class KeyType>
- Iterator values( const KeyType & key ) const {
- typedef std::multimap<KeyType, uint> Map;
- const Map& map = getMap<keyNum, KeyType>();
- std::pair<typename Map::const_iterator, typename Map::const_iterator> range = map.equal_range( key );
- Iterator ret( const_cast<Self*>
- ( this ) );
-
- while ( range.first != range.second ) {
- ret.addId( ( *range.first ).second )
- ;
- ++range.first;
- }
-
- ret.restart();
- return ret;
- }
-
- template <class KeyType>
- Iterator values( const KeyType & key ) const {
- return values<0> ( key );
- }
-
- ///For none-hashed value-types, this is no additional expense agains unordered retrieval. Returns them ordered by the given key.
- template <int keyNum, class KeyType>
- Iterator orderedValues( const KeyType & key ) const {
- typedef std::multimap<KeyType, uint> Map;
- const Map& map = getMap<keyNum, KeyType>();
- std::pair<typename Map::const_iterator, typename Map::const_iterator> range = map.equal_range( key );
- Iterator ret( const_cast<Self*>
- ( this ) );
-
- while ( range.first != range.second ) {
- ret.addId( ( *range.first ).second )
- ;
- ++range.first;
- }
-
- ret.restart();
- return ret;
- }
-
- ///For none-hashed value-types, this is no additional expense agains unordered retrieval.
- template <class KeyType>
- Iterator orderedValues( const KeyType & key ) const {
- return orderedValues<0> ( key );
- }
-
- template <int keyNum, class KeyType>
- Iterator orderedValues() const {
- Iterator ret( const_cast<Self*>( this ) );
- typedef std::multimap<KeyType, uint> Map;
-
- const Map& m = getMap<keyNum, KeyType>();
- for( typename Map::const_iterator it = m.begin(); it != m.end(); ++it )
- ret.addId( (*it).second );
-
- ret.restart();
- return ret;
- }
-
- template<class KeyType>
- Iterator orderedValues() const {
- return orderedValues<0, KeyType>();
- }
-
-
- const Value& valueFromId( Id id ) const {
- typename ValueMap::const_iterator itt = values_.find( id );
- if ( itt != values_.end()
- )
- return ( *itt ).second.value;
- else
- return dummy_;
- }
-
- template <class KeyType>
- const Value& value( const KeyType & key ) const {
- return value< 0, KeyType >( key );
- }
-
- ///Creates a copy of all key-values which can be used to reference items. This might be used to store a consistent representation of the keys a value was stored under.
- static KeyValues copyKeyValues( const Value & value ) {
- return KeyValues( value );
- }
-
- ///When KeyValues are given from outside, they do not have to be recomputed by using the KeyExtractor.
- Id insert( const KeyValues & keyValues, const Value & value ) {
- uint id = currentId_++;
- values_.insert( make_pair( id, value ) );
- insertToData( keyValues, value, id );
- return id;
- }
-
- Id insert( const Value & value ) {
- KeyValues keys( value );
- return insert( keys, value );
- }
-
- ///Returns the Id of the removed Value, or zero on fail
- Id remove
- ( Id id ) {
- if ( id ) {
- typename ValueMap::iterator it = values_.find( id );
- if ( it == values_.end() )
- return 0;
-
- removeFromData( ( *it ).second.keyValues, id );
- values_.erase( id );
- return id;
- } else {
- return 0;
- }
- }
-
- ///Removes the item the iterator currently points at
- bool remove
- ( const Iterator& it ) {
- if ( !it )
- return false;
- return ( bool ) remove
- ( it.id() );
- }
-
- ///Removes all items the iterator iterates over
- uint removeAll( const Iterator& it ) {
- if ( !it )
- return false;
- Iterator i = it;
- i.restart();
- uint ret = 0;
- while ( i ) {
- if ( remove
- ( i.id() ) ) ret++;
- }
- return ret;
- }
-
- ///Returns the Id of the removed Value, or zero on fail
- Id remove
- ( const KeyValues & keyValues, const Value & value ) {
- Id id = find( keyValues, value );
- return remove
- ( id );
- }
-
- ///Returns the Id of the removed Value, or zero on fail
- Id remove
- ( const Value & value ) {
- KeyValues keys( value );
- return remove
- ( keys, value );
- }
-
- ///@return 0 if the item was not found, else the id of a matching value */
- Id find( const KeyValues & values, const Value & value ) {
- return data_.template find( values, value, *this );
- }
-
- /**Tries to get the internal entry-Id of the Value by extracting the value's keys,
- * searching, and using the identity-test to verify that the found value is the same.
- * If all key-values changed since the item was inserted, or it changed in a way that
- * the identity-test(operator ==) fails, it cannot be found.(For that reason
- * it may be useful to choose an additional key above the really necessary ones,
- * that never changes, as the first key.(For example the address of a pointer).
- * @return 0 if the item was not found, else the id of a matching value */
- Id find( const Value & value ) {
- KeyValues keys( value );
- return find( keys, value );
- }
-
- ///@return 0 if there is no content, 1 if there is content, and 2 if the set is inconsistent(some maps have content, others don't)
- int hasContent() const {
- return !values_.empty() && data_.hasContent();
- }
-
- bool empty() const {
- return !hasContent();
- }
-
- void clear() {
- values_.clear();
- data_.clear();
- }
-
- uint count() const {
- return values_.size();
- }
-
- ///@return if the given id is bound to the specified value
- bool validateId( const Value & value, Id id ) const {
- typename ValueMap::const_iterator it = values_.find( id );
-
- if ( it != values_.end() && ( *it ).second.value == value )
- return true;
- return false;
- }
-
- template <class Archive>
- void load( Archive & arch, uint version ) {
- arch & rebuildAfterLoad_;
- arch & currentId_;
- arch & dummy_;
- if ( rebuildAfterLoad_ ) {
- uint size;
- arch & size;
- values_.clear();
- data_.clear();
- for ( uint a = 0; a < size; a++ ) {
- typename ValueMap::value_type t;
- arch & t;
- values_.insert( t );
- insertToData( t.second.keyValues, t.second.value, t.first );
- }
- } else {
- arch & values_;
- arch & data_;
- }
-
- }
- template <class Archive>
- void save( Archive & arch, uint version ) {
- arch & rebuildAfterLoad_;
- arch & currentId_;
- arch & dummy_;
- if ( rebuildAfterLoad_ ) {
- uint size = values_.size();
- arch & size;
- for ( typename ValueMap::const_iterator it = values_.begin(); it != values_.end(); ++it ) {
- arch & *it;
- }
- } else {
- arch & values_;
- arch & data_;
- }
- }
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-
- /**If the Id is known, that should be used. "operator ==" is used while searching,
- * so if something that affects that operator changed, the item cannot be found and updated.
- * the value has to be findable with at least one of the keys. If all keys changed, it cannot be found.*/
- bool update( const Value& value ) {
- return update( find( value ) );
- }
-
- /**Tries to find oldValue, and replaces it with newValue. If oldValue is not found, the item is not inserted. */
- bool update( const Value& oldValue, const Value& newValue ) {
- Id i = find( value );
- if ( !i )
- return false;
- remove
- ( i );
- insert( newValue );
- }
-
- ///Can be called after some keys changed
- bool update( Id id ) {
- if ( id.id() == 0 )
- return false;
- typename ValueMap::iterator it = values_.find( id )
- ;
- if ( it != values_.end() ) {
- removeFromData( ( *it ).second.keyValues, id );
- ( *it ).second.keyValues = KeyValues( ( *it ).second );
- insertToData( ( *it ).second.keyValues, ( *it ).second, id );
- return true;
- } else {
- return false;
- }
- }
-
- typename ValueMap::iterator begin() {
- return values_.begin();
- }
-
- typename ValueMap::iterator end() {
- return values_.end();
- }
-
- typename ValueMap::const_iterator begin() const {
- return values_.begin();
- }
-
- typename ValueMap::const_iterator end() const {
- return values_.end();
- }
-
- private:
- friend class Iterator;
-
- Value& valueFromId( Id id ) {
- typename ValueMap::iterator itt = values_.find( id );
- if ( itt != values_.end()
- )
- return ( *itt ).second.value;
- else
- return dummy_;
- }
-
-
- void removeFromData( const KeyValues & keyValues, Id id ) {
- data_.template remove
- ( keyValues, id );
- }
-
- void insertToData( const KeyValues & keyValues, const Value & value, Id id ) {
- data_.template insert( keyValues, value, id );
- }
-
- ///These functions allow efficient access to the underlying maps
- template <int keyNum>
- const std::multimap< typename GetListItem< keyNum, RealKeys >::Result, Value > & getMap() const {
- return data_. CrossMapData< Value, typename GetListItem< keyNum, Keys >::Result, keyNum> :: map;
- }
-
- template <class KeyType>
- const std::multimap< KeyType, uint >& getMap() const {
- return data_. CrossMapData< Value, KeyType, FindInList<KeyType, Keys>::value > :: map;
- }
-
- template <int occurrenceNum, class KeyType>
- const std::multimap< KeyType, uint >& getMap() const {
- enum {
- num = FindInList<KeyType, RealKeys, occurrenceNum>::value
- };
- return data_. CrossMapData< Value, typename GetListItem< num, Keys >::Result, num > :: map;
- }
-
- template <int keyNum>
- std::multimap< typename GetListItem< keyNum, RealKeys >::Result, Value >& getMap() {
- return data_. CrossMapData< Value, typename GetListItem< keyNum, Keys >::Result, keyNum> :: map;
- }
-
- template <class KeyType>
- std::multimap< KeyType, uint >& getMap() {
- return data_. CrossMapData< Value, KeyType, FindInList<KeyType, Keys>::value > :: map;
- }
-
- template <int occurrenceNum, class KeyType>
- std::multimap< KeyType, uint >& getMap() {
- enum {
- num = FindInList<KeyType, RealKeys, occurrenceNum>::value
- };
- return data_. CrossMapData< Value, typename GetListItem< num, Keys >::Result, num > :: map;
- }
-
- uint currentId_;
-
- Value dummy_;
-
- ValueMap values_;
-
- CrossMapChain< Value, Keys, 0 > data_;
-};
-
-}
-
-CROSSMAP_DEFINE_CONTAINER( std::list )
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmap.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/binder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/binder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/binder.h (nonexistent)
@@ -1,86 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-/** How typelists work:
- * Typelists are represented by the class Binder. That class is a container for only two types, but if one of
- * those is of type Binder<..,..> itself, the types contained by the binder are interpreted as members of the list.
- * That way lists off arbitrary size can be defined recursively.
- *
- * To make the whole thing look a little nicer, either the Append member of Binder(see below), or the BIND_LIST_X(..) macros can be used(see bottom).
-* */
-
-#ifndef BINDER_H
-#define BINDER_H
-
-#include "binder.h"
-
-
-/** This class is used to group multiple types together. They can be appended in a nicer looking manner
-then recursion, Example:
-Binder<Message1>::Append<Message2>::Append<Message3>::Result
-Would be the same as Binder<Binder<Message1, Message2>, Message3 >
-*/
-
-///In the type-lists, the class Empty is counted as non-existent
-class Empty {}
-;
-template <class Chain1, class Chain2 = Empty>
-struct Binder {
- template <class NChain>
- struct Append {
- typedef Binder< Binder< Chain1, Chain2 >, NChain > Result;
- };
-};
-
-template <class Item1>
-struct Binder<Empty, Item1> {
- typedef Item1 Result;
- template <class NChain>
- struct Append {
- typedef Binder< Item1, NChain > Result;
- };
-};
-
-template <class Item1>
-struct Binder<Item1, Empty> {
- typedef Item1 Result;
- template <class NChain>
- struct Append {
- typedef Binder< Item1, NChain > Result;
- };
-
-};
-
-template <>
-struct Binder<Empty, Empty> {
- typedef Empty Result;
- template <class NChain>
- struct Append {
- typedef Binder< NChain, Empty > Result;
- };
-}
-;
-
-template <class Slave, class Parent = typename Slave::Precursor, unsigned char preferredSubId = Slave::preferredIndex>
-class Chain {};
-
-
-///This macro simplifies the syntax of defining a static type-list. The first parameter is the name of the new type, the other parameters are the types.
-#define BIND_LIST_1( name, x1 ) typedef Binder<x1> name;
-#define BIND_LIST_2( name, x1, x2 ) typedef Binder<x1>::Append<x2>::Result name;
-#define BIND_LIST_3( name, x1, x2, x3 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result name;
-#define BIND_LIST_4( name, x1, x2, x3, x4 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result name;
-#define BIND_LIST_5( name, x1, x2, x3, x4, x5 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result::Append<x5>::Result name;
-#define BIND_LIST_6( name, x1, x2, x3, x4, x5, x6 ) typedef Binder<x1>::Append<x2>::Result::Append<x3>::Result::Append<x4>::Result::Append<x5>::Result::Append<x6>::Result name;
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/binder.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h (nonexistent)
@@ -1,148 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-//#define NO_SEND_HELPER
-
-#ifndef MESSAGESENDHELPER_H
-#define MESSAGESENDHELPER_H
-
-#include "networkfwd.h"
-#include "sessioninterface.h"
-#include "messageinterface.h"
-#include "networkexport.h"
-
-namespace Teamwork {
- class MessageTypeSet;
-
-///A little helper-class that allows creating types with less writing(can be imported into any class by inheritance)
-class NETWORK_EXPORT MessageSendHelper {
- MessageTypeSet& types_;
- public:
- MessageSendHelper( MessageTypeSet& types = globalMessageTypeSet() ) : types_( types ) {}
-
-#ifndef NO_SEND_HELPER
-
- /**The following is a set of little helper-functions that are used to reduce the mass of code.
- * They are used to send message, which includes their construction.
- * */
- template <class MessageType>
- inline bool send( SessionInterface* s ) {
- return s->send( new MessageType( types_ ) );
- }
-
- template <class MessageType, class ParamType1>
- inline bool send( SessionInterface* s, const ParamType1& param ) {
- return s->send( new MessageType( types_, param ) );
- }
- template <class MessageType, class ParamType1, class ParamType2>
- inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2 ) {
- return s->send( new MessageType( types_, param, param2 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2>
- inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2 ) {
- return s->send( new MessageType( types_, param, param2 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
- inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3 ) {
- return s->send( new MessageType( types_, param, param2, param3 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
- inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3 ) {
- return s->send( new MessageType( types_, param, param2, param3 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
- inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4 ) {
- return s->send( new MessageType( types_, param, param2, param3, param4 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
- inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4 ) {
- return s->send( new MessageType( types_, param, param2, param3, param4 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
- inline bool send( SessionInterface* s, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4, const ParamType5& param5 ) {
- return s->send( new MessageType( types_, param, param2, param3, param4, param5 ) );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
- inline bool send( SessionInterface* s, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4, ParamType5& param5 ) {
- return s->send( new MessageType( types_, param, param2, param3, param4, param5 ) );
- }
-
- template <class MessageType>
- inline bool sendReply( MessageInterface* replyTo ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_ ), replyTo );
- }
-
- template <class MessageType, class ParamType1>
- inline bool sendReply( MessageInterface* replyTo, const ParamType1& param ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param ), replyTo );
- }
-
- template <class MessageType, class ParamType1, class ParamType2>
- inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2 ), replyTo );
- }
-
- template <class MessageType, class ParamType1, class ParamType2>
- inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2 ), replyTo );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
- inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2, ParamType3& param3 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3 ), replyTo );
- }
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
- inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2, const ParamType3& param3 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3 ), replyTo );
- }
-
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
- inline bool sendReply( MessageInterface* replyTo, ParamType1& param, ParamType2& param2, ParamType3& param3, ParamType4& param4 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3, param4 ), replyTo );
- }
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
- inline bool sendReply( MessageInterface* replyTo, const ParamType1& param, const ParamType2& param2, const ParamType3& param3, const ParamType4& param4 ) {
- if ( !replyTo->info().session() )
- return false;
- return replyTo->info().session().unsafe()->sendReply( new MessageType( types_, param, param2, param3, param4 ), replyTo );
- }
-#endif
-};
-
-///This can be used to simply send messages using the global message-type-set, @todo remove this
-NETWORK_EXPORT MessageSendHelper& globalMessageSendHelper();
-}
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagesendhelper.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h (nonexistent)
@@ -1,122 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef FORWARDSESSION_H
-#define FORWARDSESSION_H
-
-#include "handler.h"
-#include "sessioninterface.h"
-#include "basicsession.h"
-#include "networkexport.h"
-
-namespace Teamwork {
- class ForwardMessage;
- ///A virtual session that uses another session to forward messages through it to a specified user
- class NETWORK_EXPORT ForwardSession : public SessionInterface, public SessionReplyManager {
- friend class MultiSession;
- MultiSessionPointer session_;
- UserPointer targetUser_;
- UserPointer sourceUser_;
- LoggerPointer logger_;
- bool notRunning_;
- MessageTypeSet& messageTypes_;
- HandlerPointer handler_;
-
-
- virtual LoggerPrinter err( int prio = 0 );
-
- virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
-
- public:
- ForwardSession( const UserPointer& sourceUser, const UserPointer& targetUser, const MultiSessionPointer& session, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler = 0 );
-
- ~ForwardSession();
-
- virtual bool isOk();
-
- virtual bool isRunning();
-
- virtual bool send( MessageInterface* msg );
-
- virtual void stopRunning();
-
- virtual void stopRunningNow();
-
- virtual bool think();
-
- virtual void startSession();
-
- UserPointer target();
-
- virtual SessionDirection sessionDirection();
-
- ///Must only be called from within session_!
- bool handleForwardMessage( const SafeSharedPtr<ForwardMessage>& msg );
-
- ///Must only be called from within session_!
- virtual bool handleMessage( MessagePointer msg ) throw();
-
- virtual SessionType sessionType();
-
- protected:
- virtual void final();
- };
-
- ///This is a class that implements the session-interface, and just stores the messages that should be sent in a list. It can be used for debugging.
- class NETWORK_EXPORT FakeSession : public SessionInterface {
- LoggerPointer logger_;
- MessageTypeSet& messageTypes_;
- HandlerPointer handler_;
- std::list<MessagePointer> receivedMessages_;
-
- virtual LoggerPrinter err( int prio = 0 );
-
- virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
-
- public:
- FakeSession( const UserPointer& targetUser, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler = 0 );
-
- virtual bool isOk();
-
- virtual bool isRunning();
-
- virtual bool send( MessageInterface* msg );
-
- virtual void stopRunning();
-
- virtual void stopRunningNow();
-
- virtual bool think();
-
- virtual void startSession();
-
- virtual SessionDirection sessionDirection();
-
- ///Must only be called from within session_!
- virtual bool handleMessage( MessagePointer msg ) throw();
-
- virtual SessionType sessionType();
-
- std::list<MessagePointer>& sentMessages();
-
-
- /**This takes the first message off the stack of sent messages, serializes and deserializes it, and then returns the deserialized message.
- All exceptions from the serialization- and deserialization-process are passed by, additionally errors are indicated by throwing a const char*.
- */
- MessagePointer::Locked getFirstMessage() throw( const char* );
- };
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h (nonexistent)
@@ -1,108 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SESSIONINTERFACE_H
-#define SESSIONINTERFACE_H
-
-#include <string>
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "networkexport.h"
-
-namespace Teamwork {
- class NETWORK_EXPORT SessionInterface : public /*Weak*/SafeShared {
- public:
- virtual void startSession();
-
- virtual ~SessionInterface();
- /**After this function was called, the thread is going to exit soon.
- once isRunning() returns false, it can be deleted(better call join()).*/
- virtual void stopRunning() = 0;
-
- virtual void stopRunningNow() = 0;
-
- /** Use this to send a message to the other side.
- *
- * This is thread-safe.
- * */
- virtual bool send( MessageInterface* msg ) = 0;
-
- /** Use this to send a message to the other side, that is correctly marked as
- * a reply to the message given by @param replyTo. This is just a convenience-function.
- *
- * @param msg The message to be sent. It will be changed so its info().replyTo() etc. will be filled correctly
- * @param replyTo The message to reply to. It does not need to be locked.
- *
- * This is thread-safe.
- * */
- virtual bool sendReply( MessageInterface* msg, MessageInterface* replyTo );
-
- ///Returns true if no errors occurred and the session was not ended. Must be thread-safe.
- virtual bool isOk() = 0;
-
- ///Returns whether the thread is running. Must be thread-safe.
- virtual bool isRunning() = 0;
-
- virtual std::string sessionName();
-
- virtual void setSessionName( const std::string& name );
-
- virtual std::string peerDesc();
-
- virtual std::string localDesc();
-
- enum SessionType {
- Direct,
- Forwarded
- };
-
- ///this function is thread-safe
- virtual SessionType sessionType();
-
- enum SessionDirection {
- Outgoing,
- Incoming
- };
-
- ///this function is thread-safe
- virtual SessionDirection sessionDirection() = 0;
-
- ///This function is thread-safe. The user is not necessarily filled.
- UserPointer safeUser() const;
-
- ///This must never be called again once it has been set on a session, to make it thread-safe.
- void setUser( const UserPointer& user );
-
- private:
- std::string sessionName_;
- UserPointer user_;
- //UserPointer user_;
- ///override standard-functions
- SessionInterface& operator= ( const SessionInterface& rhs );
- SessionInterface( const SessionInterface& rhs );
-
- protected:
- SessionInterface();
-
- /**This can be overridden to possibly handle messages directly in this object.
- The default-implementation just sends the messages to the handler which created this session.*/
- virtual bool handleMessage( MessagePointer msg ) throw();
-
- ///This can be overridden to do some work on a regular basis. Returns whether more time is needed.
- virtual bool think() = 0;
-
- ///This can be overridden to do some cleanup-work within the session-thread. By default it tries to lock the associated user, and call setSession(this) so the user has a chance to notice the difference.
- virtual void final();
- };
-}
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h (nonexistent)
@@ -1,100 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 file needs to be included into any file where boost-serialization takes place
- * */
-
-#ifndef SERIALIZATION_H
-#define SERIALIZATION_H
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-
-#include "networkfwd.h"
-
-#ifdef USE_TEXT_ARCHIVE
-#include <boost/archive/text_iarchive.hpp>
-#include <boost/archive/text_oarchive.hpp>
-#endif
-
-#ifdef USE_POLYMORPHIC_ARCHIVE
-#include <boost/archive/polymorphic_iarchive.hpp>
-#include <boost/archive/polymorphic_oarchive.hpp>
-#endif
-
-#ifdef USE_BINARY_ARCHIVE
-#include <boost/archive/binary_iarchive.hpp>
-#include <boost/archive/binary_oarchive.hpp>
-#endif
-
-#ifdef USE_XML_ARCHIVE
-#include <boost/archive/xml_iarchive.hpp>
-#include <boost/archive/xml_oarchive.hpp>
-#endif
-
-
-//#include <boost/serialization/base_object.hpp>
-#include <boost/serialization/extended_type_info.hpp>
-//#include <boost/serialization/utility.hpp>
-//#include <boost/serialization/list.hpp>
-//#include <boost/serialization/vector.hpp>
-#include <boost/serialization/level.hpp>
-#include <vector>
-#include "networkexport.h"
-
-namespace Teamwork {
-
- class NETWORK_EXPORT TeamworkError : public std::exception {
- std::string str_;
- public:
- TeamworkError( const std::string& str ) {
- str_ = str;
- }
- virtual ~TeamworkError() throw() {}
-
- virtual const char* what ( ) const throw () {
- return str_.c_str();
- }
- };
-
- ///This error may be thrown while serialization and it will only stop the message from being sent, it will not close the session.
- struct NETWORK_EXPORT NonFatalSerializationError : public TeamworkError {
- NonFatalSerializationError( const std::string& str ) : TeamworkError( "non-fatal serialization-error: " + str ) {}
- }
- ;
-
- /**Normally while debugging, all messages are tested by serializing,
- *then rebuilding, serializing the rebuilt message, and comparing the
- *created streams. If this test fails, the message is not sent. in some
- *cases that behavior is not appropriate. Then this exception can be thrown
- *while reserializing or rebuilding the message, to make clear that the
- *message should be sent anyway. */
- struct NETWORK_EXPORT CannotReserialize : public NonFatalSerializationError {
- CannotReserialize() : NonFatalSerializationError( "the message cannot be serialized after being deserialized" ) {}
- }
- ;
-
- class NETWORK_EXPORT StreamError : public TeamworkError {
- public:
- StreamError( const std::string& str ) : TeamworkError( "Stream-Error: " + str ) {}
- }
- ;
-}
-
-/**Because gcc does not support the export-keyword template-functions that are not in the header need to be explicitly instantiated.
- * This is a convenience-macro to instantiate the two default serialization-functions(for InArchive and OutArchive)
- * */
-#define INSTANTIATE_SERIALIZATION_FUNCTIONS(Class) \
-template void Class::serialize( InArchive& arch, const uint ); \
-template void Class::serialize( OutArchive& arch, const uint );
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serialization.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h (nonexistent)
@@ -1,108 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef NETWORKFWD_H
-#define NETWORKFWD_H
-
-#include "networkexport.h"
-
-//#define USE_POLYMORPHIC_ARCHIVE
-#define USE_TEXT_ARCHIVE
-
-class MessageSerialization;
-class NormalSerialization;
-class BoostSerialization;
-
-#ifndef SAFESHAREDPTR_HAVE_DEFAULT
-#define SAFESHAREDPTR_HAVE_DEFAULT
-template<class Type, class Serialization = NormalSerialization>
-class SafeSharedPtr;
-#endif
-
-#ifndef WEAKSAFESHAREDPTR_HAVE_DEFAULT
-#define WEAKSAFESHAREDPTR_HAVE_DEFAULT
-template<class Type, class Serialization = NormalSerialization>
-class WeakSafeSharedPtr;
-#endif
-
-namespace boost {
- namespace archive {
- class binary_oarchive;
- class binary_iarchive;
-
- class text_oarchive;
- class text_iarchive;
-
- class xml_oarchive;
- class xml_iarchive;
-
- class polymorphic_iarchive;
- class polymorphic_oarchive;
- }
-}
-
-namespace Teamwork {
- class HandlerInterface;
- class BasicTCPSession;
- class SessionInterface;
- class MultiSession;
- class ForwardSession;
- class BasicServer;
- class MessageInterface;
- class User;
- class UserIdentity;
- class Logger;
- class LoggerPrinter;
- class MessageTypeSet;
-
- class ClientSessionDesc;
- class ServerInformation;
- class Server;
-
- typedef SafeSharedPtr<HandlerInterface> HandlerPointer;
- typedef SafeSharedPtr<SessionInterface> SessionPointer;
- typedef SafeSharedPtr<BasicServer> ServerPointer;
- typedef SafeSharedPtr<MessageInterface, MessageSerialization> MessagePointer;
- typedef SafeSharedPtr<User, BoostSerialization> UserPointer;
- typedef SafeSharedPtr<Logger> LoggerPointer;
- typedef SafeSharedPtr<MultiSession> MultiSessionPointer;
- typedef SafeSharedPtr<ForwardSession> ForwardSessionPointer;
-
- typedef WeakSafeSharedPtr<SessionInterface> WeakSessionPointer;
-
- #ifdef USE_BINARY_ARCHIVE
- typedef boost::archive::binary_oarchive OutArchive;
- typedef boost::archive::binary_iarchive InArchive;
- #endif
-
- #ifdef USE_POLYMORPHIC_ARCHIVE
- typedef boost::archive::polymorphic_oarchive OutArchive;
- typedef boost::archive::polymorphic_iarchive InArchive;
- #endif
-
- #ifdef USE_TEXT_ARCHIVE
- typedef boost::archive::text_oarchive OutArchive;
- typedef boost::archive::text_iarchive InArchive;
- #endif
-
- #ifdef USE_XML_ARCHIVE
- typedef boost::archive::xml_iarchive InArchive;
- typedef boost::archive::xml_oarchive OutArchive;
- #endif
-
- NETWORK_EXPORT MessageTypeSet& globalMessageTypeSet();
-}
-
-typedef unsigned int u32;
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkfwd.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.h (nonexistent)
@@ -1,75 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef LOGGER_H
-#define LOGGER_H
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include <string>
-#include <iostream>
-#include <sstream>
-
-#include "networkexport.h"
-
-namespace Teamwork {
-
-///WARNING: The functions in this class will be called from many different threads, but only from one thread at a time(due to mutex-locking)
-struct NETWORK_EXPORT Logger : public SafeShared {
- enum Level {
- Debug = 1,
- Info = 2,
- Warning = 4,
- Error = 8
- };
-
- std::string levelToString( Level lv );
-
- ///This can be overridden for custom logging
- virtual void log( const std::string& str , Level lv );
-
- ///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
- virtual void safeErrorLog( const std::string& str, Level lv );
-};
-
-///this class represents one line of logger-output. On its destruction the line is given to the logger. When it is copied, the copy-source is invalidated.
-class NETWORK_EXPORT LoggerPrinter {
- public:
- explicit LoggerPrinter( const LoggerPointer& logger, Logger::Level level = Logger::Info );
-
- LoggerPrinter( const LoggerPrinter& rhs );
-
- template <class ItemType>
- LoggerPrinter& operator << ( const ItemType& item ) {
- if ( out_ )
- * out_ << item;
- else
- std::cout << item; //"invalidated logger is being used" << endl;*/
-
- return *this;
- }
-
- ~LoggerPrinter();
- private:
- LoggerPointer logger_;
- std::ostringstream* out_;
- Logger::Level level_;
-
- void invalidate();
- LoggerPrinter& operator = ( const LoggerPrinter& /*rhs*/ );
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp (nonexistent)
@@ -1,460 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "teamworkserver.h"
-#include "serialization.h"
-#include "messageimpl.h"
-#include "teamworkmessages.h"
-#include "teamworkservermessages.h"
-#include "forwardsession.h"
-#include "multisession.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-namespace Teamwork {
-using namespace std;
-
-BIND_LIST_4( TeamworkServerDispatchMessages, SystemMessage, ForwardMessage, IdentificationMessage, TextMessage )
-
-template <class From, class To, class Compare>
-list<To> mapValues( map<From, To, Compare> mp ) {
- list<To> ret;
- for ( typename map<From, To, Compare>::iterator it = mp.begin(); it != mp.end(); ++it ) {
- ret.push_back( ( *it ).second );
- }
- return ret;
-}
-
-void Server::setIdentity( const UserPointer& user ) {
- ident_ = user;
-}
-
-UserPointer Server::identity() const {
- return ident_;
-}
-
-Server::Server( const ServerInformation& inf, const LoggerPointer& logger ) : BasicServer( inf.addr().c_str(), inf.port(), globalMessageTypeSet(), logger ), MessageSendHelper( globalMessageTypeSet() ), userListDirty_( false ) {
- //dispatcher_.print( cout );
-}
-
-void Server::getUserSet( UserSet& users ) {
- users = users_;
-}
-
-void Server::insertUserSet( const UserSet& users ) {
- users_.insert( users.begin(), users.end() );
-}
-
-Server::~Server() {
- for ( UserSet::iterator it = users_.begin(); it != users_.end(); ++it ) {
- UserPointer::Locked l = *it;
- if ( l ) {
- l->setSession( 0 );
- } else {
- err() << "could not lock a UserPointer while destruction";
- }
- }
-}
-
-SessionPointer Server::createSession( BasicTCPSocket* sock ) {
- return new MultiSession( *sock, new HandlerProxy<BasicServer>( this ), globalMessageTypeSet(), logger() );
- ///check yet whether this is thread-safe, if not give some kind of safe pointers
-}
-
-bool Server::registerSession( SessionPointer session ) {
- MultiSessionPointer s = session.cast<MultiSession>();
- if ( s ) {
- unknownSessions_.insert( s );
- return true;
- } else {
- return false;
- }
-}
-
-bool Server::registerSessionUser( const UserPointer& user ) {
- UserPointer::Locked l = user;
- if( !l ) return false;
- if( !l->online().session() ) return false;
- sessions_[ l->online().session() ] = user ;
- return true;
-}
-
-void Server::sendUserLists() {
- out( Logger::Debug ) << "broadcasting user-list";
- list<UserPointer> users = mapValues( sessions_ );
- for ( SessionMap::iterator it = sessions_.begin(); it != sessions_.end(); ++it ) {
- send<UserListMessage>( ( *it ).first.unsafe(), users, ( *it ).second );
- }
-}
-
-void Server::initial( void ) {
- return BasicServer::initial();
-}
-
-UserPointer Server::findUser( const UserPointer& user ) {
- UserSet::iterator it = users_.find( user );
- if ( it != users_.end() )
- return * it;
- else
- return 0;
-}
-
-UserPointer Server::findUser( const UserIdentity& user ) {
- UserSet::iterator it = users_.find( new User( user ) );
- if ( it != users_.end() )
- return * it;
- else
- return 0;
-}
-
-bool Server::think() {
- ///identify dead sessions and free pointers to them so they are deleted by reference-counting
- for ( SessionSet::iterator it = unknownSessions_.begin(); it != unknownSessions_.end(); ) {
- if ( !( *it ).unsafe() ->isRunning() ) {
- out() << "deleting unknown incoming session";
- SessionSet::iterator itb = it;
- ++it;
- unknownSessions_.erase( itb );
- } else
- ++it;
- }
-
- for ( SessionMap::iterator it = sessions_.begin(); it != sessions_.end(); ) {
- if ( !( *it ).first.unsafe() ->isRunning() ) {
- SessionMap::iterator itb = it;
- ++it;
- UserPointer::Locked l = ( *itb ).second;
- if ( l ) {
- l->setSession( 0 );
- } else {
- err() << "could not lock user-data, reference to session can not be cleared";
- }
-
- closeSession( ( *itb ).first );
- /*userDisconnected( (*itb).second );
- sessions_.erase( itb );*/
- out() << "deleting incoming session";
- } else
- ++it;
- }
-
- while ( !messages().empty() ) {
- MessagePointer::Locked l = ( MessagePointer ) messages().front();
- if ( l ) {
- processMessage( l.data() );
- } else {
- out() << "a message from the incoming queue could not be locked";
- }
- messages().pop_front();
- }
-
- if ( userListDirty_ ) {
- sendUserLists();
- userListDirty_ = false;
- }
-
- return BasicServer::think();
-}
-
-void Server::final( void ) {
- return BasicServer::final();
-}
-
-void Server::closeAllIncomingSessions() {
- int c = 0;
- while ( !sessions_.empty() && ++c < 50000 ) {
- closeSession( ( *sessions_.begin() ).first );
- }
-}
-
-void Server::closeSession( const SessionPointer& session ) {
- if(!session)
- return;
- bool haveSession = false;
- {
- SessionMap::iterator it = sessions_.find( session );
- if ( it != sessions_.end() ) {
- UserPointer::Locked l = (*it).second;
- haveSession = true;
-
- if ( l && l->online().session() == session ) {
- l->setSession( 0 );
- } else
- out() << "error locking user";
- }
- }
-
- session.unsafe() ->stopRunning();
- if ( haveSession ) {
- userDisconnected( sessions_[ session ] );
- userListDirty_ = true;
- }
- unknownSessions_.erase( session.cast<MultiSession>() ); //do this before the next line, because the session may already be deleted
- sessions_.erase( session );
-}
-
-MessageTypeSet& Server::messageTypes() {
- return globalMessageTypeSet();
-}
-
-UserPointer Server::createUser( IdentificationMessage* msg ) {
- return new User( *msg );
-}
-
-UserPointer Server::createUser( const User* user ) {
- return new User( user );
-}
-
-void Server::addUser( UserPointer user ) {
- out() << "adding new user: \"" << user.unsafe() ->safeName() << "\"";
- users_.insert( user );
-}
-
-UserPointer Server::getUser( const UserPointer& user ) {
- UserPointer ret = findUser( user );
- if ( !ret ) {
- UserPointer::Locked l = user;
- if ( l ) {
- UserPointer u = createUser( l );
- addUser( u );
- return u;
- } else {
- return 0;
- }
- } else {
- return ret;
- }
-}
-
-UserPointer Server::getUser( const UserIdentity& user ) {
- UserPointer ret = findUser( user );
- if ( !ret ) {
- UserPointer u = createUser( LockedSharedPtr<User>( new User( user ) ) );
- addUser( u );
- return u;
- } else {
- return ret;
- }
-}
-
-int Server::receiveMessage( IdentificationMessage* msg ) {
- string username = "unknown user";
- MultiSessionPointer theSession;
- try {
- MultiSessionPointer session = msg->info().session().cast<MultiSession>();
- if ( !session )
- throw TeamworkError( "failed to cast server-session" );
- theSession = session;
-
- MultiSessionPointer::Locked l = session;
- if ( !l )
- throw TeamworkError( "failed to lock source-session" );
-
- UserPointer user = createUser( msg );
- if ( !user )
- throw TeamworkError( "could not create user" );
-
- UserPointer::Locked ul = user;
- if ( !ul )
- throw TeamworkError( "failed to lock user" );
-
- UserSet::iterator it = users_.find( user );
-
- username = ul->name();
-
- UserPointer::Locked id = identity();
- if ( id ) {
- if ( id->matchIdentity( *ul ) ) {
- throw TeamworkError( "a user tried to login with the identity of the local server" );
- }
- }
-
- if ( it == users_.end() ) {
- if( configuration_.serverPassword.empty() || ul->password() == configuration_.serverPassword ) {
- out() << "adding new user: " << ul->name();
- addUser( user );
- } else {
- throw TeamworkError( "server-password mismatched" );
- }
- } else {
- UserPointer::Locked nul = *it;
- if ( !nul )
- throw TeamworkError( "failed to lock user" );
- if ( !nul->match( *ul ) ) {
- ostringstream str;
- str << "authentication failed, names: \"" << nul->name() << "\" \"" << ul->name() << "\", banned: " << nul->banned();
- throw TeamworkError( str.str() );
- }
- ul = nul;
- user = *it;
- }
-
- l->setSessionName( ul->name() + "_" + l->sessionName() );
- l->setUser( user );
-
- if ( ul->online() ) {
- string peerDesc = "unknown peer";
- SessionPointer::Locked ll = ul->online().session();
- if ( ll )
- peerDesc = ll->peerDesc();
- out() << "the user " + ul->name() + " logged in twice, the first one from " << peerDesc << " is disconnected";
- send<SystemMessage>( ul->online().session().unsafe(), SystemMessage::BadAuthentication, "another use with the name " + ul->name() + " logged in" );
- send<SystemMessage>( msg->info().session().unsafe(), SystemMessage::AlreadyLoggedIn, "the user " + ul->name() + " was already logged in" );
- closeSession( ul->online().session() );
- }
-
- ul->setSession( msg->info().session() );
- sessions_[ session.cast<SessionInterface>() ] = user;
- unknownSessions_.erase( session );
- out() << "login successful: \"" << user.unsafe() ->name() << "\"";
- send<SystemMessage>( l, SystemMessage::LoginSuccess, string( "welcome to this teamwork-server" ) );
- userConnected( user );
-
- userListDirty_ = true;
- } catch ( exception & exc ) {
- string addrInfo;
- MultiSessionPointer::Locked l = theSession;
- if ( l )
- addrInfo = "from " + l->peerDesc() + " ";
- ;
-
- if ( theSession )
- unknownSessions_.erase( theSession );
-
- out() << "login of user \"" << username << "\" " << addrInfo << "failed: " << exc.what();
-
- msg->info().session().unsafe()->send( new SystemMessage( messageTypes_ , SystemMessage::LoginFailedUnknown, "reason: " + string( exc.what() ) ) );
-
- }
- return 0;
-}
-
-int Server::receiveMessage( TextMessage* msg ) {
- out() << "got text-message: " << msg->text();
- return 0;
-}
-
-int Server::receiveMessage( MessageInterface* /*msg*/ ) {
- out() << "got unknown message-type";
- return 0;
-}
-
-int Server::receiveMessage( SystemMessage* msg ) {
- out() << "got system-message: " << msg->messageAsString() << ": " << msg->text();
- switch ( msg->message() ) {
- case SystemMessage::GetUserList: {
- //SessionPointer::Locked l = msg->info().session();
- if ( msg->info().session() ) {
- list<UserPointer> users = mapValues( sessions_ );
- if ( identity() )
- users.push_back( identity() );
-
- out() << "sending user-list of size " << users.size();
-
- sendReply<UserListMessage>( msg, users, msg->info().user() );
- }
- };
- break;
- default:
- break;
- }
- return 0;
-}
-
-UserPointer Server::findSessionUser( const SessionPointer& session ) {
- SessionMap::iterator it = sessions_.find( session );
- if ( it == sessions_.end() )
- return UserPointer();
- else
- return ( *it ).second;
-}
-}
-
-int Teamwork::Server::receiveMessage( ForwardMessage * msg ) {
- out( Logger::Debug ) << "forwarding message";
-
- UserPointer u( new User( msg->target() ) );
- UserSet::iterator it = users_.find( u );
-
- MultiSession* sess = msg->info().session().cast<MultiSession>().unsafe();
- if ( !sess ) {
- out() << "got forward-message from unknown session";
- return 0;
- }
-
- try {
- if ( it != users_.end() ) {
- ///@todo check if the given session (user) is authorized to send data to the given target(check for connection), and check whether the source-user-information in the message fits the real source
- UserPointer::Locked l = *it;
- if ( l ) {
- if ( l->online() && l->online().session() ) {
- out( Logger::Debug ) << "forwarding a message from " << msg->source().name() << " to " << msg->target().name();
- l->online().session().unsafe() ->send( msg );
- } else {
- if ( msg->storeOnServer() ) {
- out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << ", storing it on the server";
- sendReply<SystemMessage>( msg, SystemMessage::StoredOnServer, "" );
- } else {
- out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << " because the target is not online";
- sendReply<SystemMessage>( msg, SystemMessage::BadTarget, "" );
- }
- }
- } else {
- err() << "internal error: could not lock user";
- throw string( "internal error" );
- }
- } else {
- throw string( "the target-user does not exist" );
- }
- } catch ( string s ) {
- out( Logger::Debug ) << "failed to forward a message from " << msg->source().name() << " to " << msg->target().name() << " reason: " << s;
- sendReply<SystemMessage>( msg, SystemMessage::BadTarget, s );
- }
-
- return 1;
-}
-
-void Teamwork::Server::setConfiguration( const ServerConfiguration& conf ) {
- configuration_ = conf;
- if( !configuration_.serverName.empty() && !identity() ) {
- setIdentity( new User( conf.serverName ) );
- }
- for( ServerConfiguration::UserSet::iterator it = configuration_.registeredUsers.begin(); it != configuration_.registeredUsers.end(); ++it ) {
- UserPointer::Locked u = new User( *it );
- UserPointer ru = findUser( u );
- if( ru ) {
- ///The user already exists, update it
- UserPointer::Locked rlu = ru;
- if( rlu ) {
- (*rlu) = *it;
- rlu->setSession( rlu->online().session() ); ///Session is used to track the state of the user, so give a hint using that interface that something about the user changed.
- }
- } else {
- addUser( createUser( u ) );
- }
- }
-}
-
-const Teamwork::ServerConfiguration& Teamwork::Server::configuration() const {
- return configuration_;
-}
-
-void Teamwork::Server::processMessage( MessageInterface* msg ) {
- MessageDispatcher< Server, TeamworkServerDispatchMessages > dispatcher(*this);
- dispatcher( msg );
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h (nonexistent)
@@ -1,83 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 file contains the implementation-details of DynamicMessageDeliverer
- * */
-
-#ifndef DYNAMICMESSAGEDISPATCHER_INTERNAL_H
-#define DYNAMICMESSAGEDISPATCHER_INTERNAL_H
-
-#include "weaksafesharedptr.h"
-#include "networkfwd.h"
-#include "messageinterface.h"
-
-namespace Teamwork {
-
- ///Some helper-classes for implementing the dispatcher, see below
-class MessageDelivererBase {
- public:
- virtual int tryDeliverMessage( const MessagePointer& msg ) = 0;
- virtual ~MessageDelivererBase() {
- }
- virtual bool isOk() const = 0;
- virtual const MessageType& type() const = 0;
-};
-
-template<class Message, class Target>
- class MessageDeliverer : public MessageDelivererBase {
- public:
- typedef int (Target::*FunctionType)(const SafeSharedPtr<Message>& );
-
- MessageDeliverer( const WeakSafeSharedPtr<Target>& target, FunctionType function, MessageType type, bool lockBeforeCall = true ) : m_function(function), m_target(target), m_lockBeforeCall( lockBeforeCall ), m_type(type) {
- }
-
- virtual bool isOk() const {
- return m_target.get();
- }
-
- virtual const MessageType& type() const {
- return m_type;
- }
-
- virtual int tryDeliverMessage( const MessagePointer& msg ) {
- SafeSharedPtr<Message> myMsg = msg.cast<Message>();
- if( myMsg ) {
- if( m_lockBeforeCall ) {
- //The message can be casted to the needed type, so it should be delivered.
- LockedSharedPtr<Target> lockedTarget = m_target;
- if( lockedTarget ) {
- //Deliver the message
- return (lockedTarget->*m_function) ( myMsg );
- } else {
- //Problem
- }
- } else {
- //Do not lock the target before calling the callback-function
- SafeSharedPtr<Target> ref = m_target.get(); //Make a normal safe-shared-pointer out of the weak one, so the target can not be deleted while the call
- if( ref )
- return (ref.unsafe()->*m_function) ( myMsg );
- }
- }
- return 0;
- };
- virtual ~MessageDeliverer() {
- }
- private:
- FunctionType m_function;
- WeakSafeSharedPtr<Target> m_target;
- bool m_lockBeforeCall;
- MessageType m_type;
- };
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher_internal.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile (nonexistent)
@@ -1,276 +0,0 @@
-# Doxyfile 1.4.1-KDevelop
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-PROJECT_NAME = network.kdevelop
-PROJECT_NUMBER = $VERSION$
-OUTPUT_DIRECTORY =
-CREATE_SUBDIRS = NO
-OUTPUT_LANGUAGE = English
-USE_WINDOWS_ENCODING = NO
-BRIEF_MEMBER_DESC = YES
-REPEAT_BRIEF = YES
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-ALWAYS_DETAILED_SEC = NO
-INLINE_INHERITED_MEMB = NO
-FULL_PATH_NAMES = YES
-STRIP_FROM_PATH = /home/nolden/projekte/summer-of-code/work/kdevelop-teamwork/network/
-STRIP_FROM_INC_PATH =
-SHORT_NAMES = NO
-JAVADOC_AUTOBRIEF = NO
-MULTILINE_CPP_IS_BRIEF = NO
-DETAILS_AT_TOP = NO
-INHERIT_DOCS = YES
-DISTRIBUTE_GROUP_DOC = NO
-TAB_SIZE = 8
-ALIASES =
-OPTIMIZE_OUTPUT_FOR_C = NO
-OPTIMIZE_OUTPUT_JAVA = NO
-SUBGROUPING = YES
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-EXTRACT_ALL = NO
-EXTRACT_PRIVATE = NO
-EXTRACT_STATIC = NO
-EXTRACT_LOCAL_CLASSES = YES
-EXTRACT_LOCAL_METHODS = NO
-HIDE_UNDOC_MEMBERS = NO
-HIDE_UNDOC_CLASSES = NO
-HIDE_FRIEND_COMPOUNDS = NO
-HIDE_IN_BODY_DOCS = NO
-INTERNAL_DOCS = NO
-CASE_SENSE_NAMES = YES
-HIDE_SCOPE_NAMES = NO
-SHOW_INCLUDE_FILES = YES
-INLINE_INFO = YES
-SORT_MEMBER_DOCS = YES
-SORT_BRIEF_DOCS = NO
-SORT_BY_SCOPE_NAME = NO
-GENERATE_TODOLIST = YES
-GENERATE_TESTLIST = YES
-GENERATE_BUGLIST = YES
-GENERATE_DEPRECATEDLIST= YES
-ENABLED_SECTIONS =
-MAX_INITIALIZER_LINES = 30
-SHOW_USED_FILES = YES
-SHOW_DIRECTORIES = YES
-FILE_VERSION_FILTER =
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-QUIET = NO
-WARNINGS = YES
-WARN_IF_UNDOCUMENTED = YES
-WARN_IF_DOC_ERROR = YES
-WARN_NO_PARAMDOC = NO
-WARN_FORMAT = "$file:$line: $text"
-WARN_LOGFILE =
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-INPUT = /home/nolden/projekte/summer-of-code/work/kdevelop-teamwork/network
-FILE_PATTERNS = *.c \
- *.cc \
- *.cxx \
- *.cpp \
- *.ocl \
- *.c++ \
- *.java \
- *.ii \
- *.ixx \
- *.ipp \
- *.i++ \
- *.inl \
- *.h \
- *.hh \
- *.hxx \
- *.hpp \
- *.h++ \
- *.idl \
- *.odl \
- *.cs \
- *.php \
- *.php3 \
- *.inc \
- *.m \
- *.mm \
- *.dox \
- *.C \
- *.CC \
- *.C++ \
- *.II \
- *.I++ \
- *.H \
- *.HH \
- *.H++ \
- *.CS \
- *.PHP \
- *.PHP3 \
- *.M \
- *.MM \
- *.C \
- *.H \
- *.tlh \
- *.diff \
- *.patch \
- *.moc \
- *.xpm \
- *.dox
-RECURSIVE = yes
-EXCLUDE =
-EXCLUDE_SYMLINKS = NO
-EXCLUDE_PATTERNS =
-EXAMPLE_PATH =
-EXAMPLE_PATTERNS = *
-EXAMPLE_RECURSIVE = NO
-IMAGE_PATH =
-INPUT_FILTER =
-FILTER_PATTERNS =
-FILTER_SOURCE_FILES = NO
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-SOURCE_BROWSER = NO
-INLINE_SOURCES = NO
-STRIP_CODE_COMMENTS = YES
-REFERENCED_BY_RELATION = YES
-REFERENCES_RELATION = YES
-VERBATIM_HEADERS = YES
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-ALPHABETICAL_INDEX = NO
-COLS_IN_ALPHA_INDEX = 5
-IGNORE_PREFIX =
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-GENERATE_HTML = YES
-HTML_OUTPUT = html
-HTML_FILE_EXTENSION = .html
-HTML_HEADER =
-HTML_FOOTER =
-HTML_STYLESHEET =
-HTML_ALIGN_MEMBERS = YES
-GENERATE_HTMLHELP = NO
-CHM_FILE =
-HHC_LOCATION =
-GENERATE_CHI = NO
-BINARY_TOC = NO
-TOC_EXPAND = NO
-DISABLE_INDEX = NO
-ENUM_VALUES_PER_LINE = 4
-GENERATE_TREEVIEW = NO
-TREEVIEW_WIDTH = 250
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-GENERATE_LATEX = YES
-LATEX_OUTPUT = latex
-LATEX_CMD_NAME = latex
-MAKEINDEX_CMD_NAME = makeindex
-COMPACT_LATEX = NO
-PAPER_TYPE = a4wide
-EXTRA_PACKAGES =
-LATEX_HEADER =
-PDF_HYPERLINKS = NO
-USE_PDFLATEX = NO
-LATEX_BATCHMODE = NO
-LATEX_HIDE_INDICES = NO
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-GENERATE_RTF = NO
-RTF_OUTPUT = rtf
-COMPACT_RTF = NO
-RTF_HYPERLINKS = NO
-RTF_STYLESHEET_FILE =
-RTF_EXTENSIONS_FILE =
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-GENERATE_MAN = NO
-MAN_OUTPUT = man
-MAN_EXTENSION = .3
-MAN_LINKS = NO
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-GENERATE_XML = yes
-XML_OUTPUT = xml
-XML_SCHEMA =
-XML_DTD =
-XML_PROGRAMLISTING = YES
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-GENERATE_AUTOGEN_DEF = NO
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-GENERATE_PERLMOD = NO
-PERLMOD_LATEX = NO
-PERLMOD_PRETTY = YES
-PERLMOD_MAKEVAR_PREFIX =
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-ENABLE_PREPROCESSING = YES
-MACRO_EXPANSION = NO
-EXPAND_ONLY_PREDEF = NO
-SEARCH_INCLUDES = YES
-INCLUDE_PATH =
-INCLUDE_FILE_PATTERNS =
-PREDEFINED =
-EXPAND_AS_DEFINED =
-SKIP_FUNCTION_MACROS = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-TAGFILES =
-GENERATE_TAGFILE = network.tag
-ALLEXTERNALS = NO
-EXTERNAL_GROUPS = YES
-PERL_PATH = /usr/bin/perl
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-CLASS_DIAGRAMS = YES
-HIDE_UNDOC_RELATIONS = YES
-HAVE_DOT = NO
-CLASS_GRAPH = YES
-COLLABORATION_GRAPH = YES
-GROUP_GRAPHS = YES
-UML_LOOK = NO
-TEMPLATE_RELATIONS = NO
-INCLUDE_GRAPH = YES
-INCLUDED_BY_GRAPH = YES
-CALL_GRAPH = NO
-GRAPHICAL_HIERARCHY = YES
-DIRECTORY_GRAPH = YES
-DOT_IMAGE_FORMAT = png
-DOT_PATH =
-DOTFILE_DIRS =
-MAX_DOT_GRAPH_WIDTH = 1024
-MAX_DOT_GRAPH_HEIGHT = 1024
-MAX_DOT_GRAPH_DEPTH = 1000
-DOT_TRANSPARENT = NO
-DOT_MULTI_TARGETS = NO
-GENERATE_LEGEND = YES
-DOT_CLEANUP = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to the search engine
-#---------------------------------------------------------------------------
-SEARCHENGINE = NO
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/Doxyfile
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp (nonexistent)
@@ -1,318 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "serialization.h"
-#include "messagetypeset.h"
-#include "basicsession.h"
-#include "user.h"
-
-namespace Teamwork {
-
-MessageInfo::MessageInfo() : isReplyTo_( 0 ), uniqueId_( 0 ), deserialized_( false ) {
-}
-
-MessageInfo::MessageInfo( const MessageType& id, UniqueMessageId uniqueId ) : isReplyTo_( 0 ), uniqueId_( uniqueId ), deserialized_( false ) {
- id_ = id;
- // cout << "creating message-info normally";
-}
-
-MessageInfo::MessageInfo( const MessageType& id, UniqueMessageId uniqueId, const SessionPointer& session, UniqueMessageId isReplyTo ) : isReplyTo_( isReplyTo ), uniqueId_( uniqueId ), deserialized_( false ) {
- id_ = id;
- session_ = session;
- // cout << "creating message-info normally";
-}
-
-MessageInfo::~MessageInfo() {
-}
-
-void MessageInfo::setReplyMessage( const MessagePointer& msg ) {
- replyToMessage_ = msg;
-}
-
-const MessagePointer& MessageInfo::replyToMessage() const {
- return replyToMessage_;
-}
-
-SessionPointer MessageInfo::session() const {
- if ( !session_ ) {
- UserPointer::Locked l = user_;
- if ( l ) {
- return l->online().session();
- } else {
- return 0;
- }
- } else {
- return session_;
- }
-}
-
-UserPointer MessageInfo::user() const {
- if ( session_ ) {
- return session_.unsafe() ->safeUser();
- } else {
- return user_;
- }
-}
-
-void MessageInfo::setSession( const SessionPointer& sess ) {
- if ( !sess ) {
- session_ = 0;
- user_ = 0;
- return ;
- }
- if ( UserPointer p = sess.unsafe() ->safeUser() ) {
- setUser( p );
- } else {
- session_ = sess;
- user_ = 0;
- }
-}
-
-void MessageInfo::setUser( const UserPointer& user ) {
- user_ = user;
- session_ = 0;
-}
-
-MessageFactoryInterface* MessageTypeSet::findFactory( MessageType& id ) const {
- while ( id ) { ///walk up the tree until a matching maybe inherited message-type is found
- TypeMap::const_iterator it = types_.find( id );
- if ( it != types_.end() ) {
- return ( *it ).second;
- }
- --id;
- }
- return 0;
-}
-
-MessagePointer MessageTypeSet::buildMessage( InArchive& from, const MessageInfo& inf ) const {
- MessageType id = inf.type();
-
- MessageFactoryInterface* i = findFactory( id );
- if ( i ) {
- MessageInfo info( inf );
- info.setId( id );
- return MessagePointer( i->buildMessage( from, info ) );
- }
-
- cout << "could not build message with id " << id.desc() << endl;
- return MessagePointer();
-}
-
-void MessageType::packFastId() {
- //return;
- fastId_ = 0;
- if ( idList_.size() > 4 ) {
- useFastId = false;
- } else {
- useFastId = true;
- int shift = 24;
- for ( IdList::iterator it = idList_.begin(); it != idList_.end(); ++it ) {
- fastId_ += *it << shift;
- shift -= 8;
- }
- }
-}
-
-MessageType::MessageType( IdList IDs ) : idList_( IDs ), useFastId( false ) {
- packFastId();
-}
-
-MessageType::MessageType( InArchive& from ) : useFastId( false ) {
- serialize( from );
-}
-
-bool MessageType::operator == ( const MessageType& rhs ) const {
- if ( useFastId && rhs.useFastId )
- return fastId_ == rhs.fastId_;
- int s1 = idList_.size();
- int s2 = rhs.idList_.size();
- if ( s1 != s2 )
- return false;
- for ( int a = 0; a < s1; a++ ) {
- if ( idList_[ a ] != rhs.idList_[ a ] )
- return false;
- }
-
- return true;
-}
-
-bool MessageType::operator < ( const MessageType& rhs ) const {
- if ( useFastId && rhs.useFastId )
- return fastId_ < rhs.fastId_;
- int s1 = idList_.size();
- int s2 = rhs.idList_.size();
- int ms = s2 > s1 ? s1 : s2;
- for ( int a = 0; a < ms; a++ ) {
- if ( idList_[ a ] < rhs.idList_[ a ] ) {
- return true;
- }
- if ( idList_[ a ] > rhs.idList_[ a ] ) {
- return false;
- }
- }
- if ( s1 < s2 ) {
- return true;
- }
- if ( s1 > s2 ) {
- return false;
- }
-
- return false;
-}
-
-int MessageType::length() const {
- return idList_.size();
-}
-
-
-bool MessageType::startsWith( const MessageType& rhs ) const {
- int s1 = idList_.size();
- int s2 = rhs.idList_.size();
- if ( s1 < s2 )
- return false;
-
- for ( int a = 0; a < s1; a++ ) {
- if ( idList_[ a ] != rhs.idList_[ a ] )
- return false;
- }
-
- return true;
-}
-
-MessageType& MessageType::operator += ( unsigned char append ) {
- if ( !idList_.empty() )
- idList_.pop_back();
- idList_.push_back( append );
- idList_.push_back( 0 );
- packFastId();
- return *this;
-}
-
-MessageType& MessageType::operator -- () {
- if ( !idList_.empty() ) {
- idList_.pop_back();
- idList_.pop_back();
- idList_.push_back( 0 );
- }
- packFastId();
- return *this;
-}
-
-MessageType::operator bool() const {
- return !idList_.empty();
-}
-
-std::string MessageType::desc() const {
- if ( idList_.empty() )
- return "'invalid id'";
- std::ostringstream ret;
- IdList::const_iterator end = idList_.end();
- if ( end != idList_.begin() )
- --end;
- for ( IdList::const_iterator it = idList_.begin(); it != end; ++it )
- ret << ( int ) * it << "-";
- return ret.str();
-}
-
-MessageType::operator const unsigned char*() const {
- if ( idList_.empty() ) {
- return ( const uchar* ) "";
- } else {
- return ( const uchar* ) & ( idList_[ 0 ] );
- }
-}
-
-UniqueMessageId MessageInfo::uniqueId() const {
- return uniqueId_;
-}
-
-/**Since the uniqueId is not used for sorting this casts away constness so the id of a MessageType that is used as Key in a Map can be changed */
-void MessageInfo::setUniqueId( UniqueMessageId newId ) const {
- const_cast<MessageInfo*>( this ) ->uniqueId_ = newId;
-}
-
-MessageTypeSet::TypeMap::iterator MessageTypeSet::search( const MessageType& id ) {
- return types_.find( id );
-}
-
-MessageType MessageTypeSet::allocateSubId( const MessageType& id, int preferredSubId ) {
- MessageType tempId = id;
- if ( preferredSubId == 0 )
- preferredSubId = 1;
- for ( int a = preferredSubId; a < 255; a++ ) {
- tempId += a;
- if ( types_.find( tempId ) == types_.end() ) {
- return tempId;
- }
- --tempId;
- }
-
- cout << "problem while allocating sub-id for " << id.desc() << ", all sub-id's seem to be taken" << endl;
- ///This should not happen, but anyway try to allocate some id
- if ( tempId ) {
- return allocateSubId( allocateSubId( --tempId ), preferredSubId );
- }
-
- return MessageType();
-}
-MessageTypeSet::MessageTypeSet() {
- srand( time( NULL ) );
- currentUniqueMessageId_ = rand();
- currentUniqueMessageId_ *= rand();
- currentUniqueMessageId_ *= rand();
- currentUniqueMessageId_ *= rand();
-}
-
-MessagePointer MessageTypeSet::buildMessage( InArchive& from, const MessageInfo& inf ) const;
-
-MessageTypeSet::~MessageTypeSet() {
- for ( TypeMap::iterator it = types_.begin(); it != types_.end(); ++it ) {
- delete ( *it ).second;
- }
- types_.clear();
-}
-
-const MessageType& MessageTypeSet::idFromName( const std::string& name ) const {
- TypeNameMap::const_iterator it = ids_.find( name );
- if ( it != ids_.end() ) {
- return ( *it ).second;
- } else if( name == "MessageInterface" ) {
- return const_cast<TypeNameMap&>(ids_)[name]; //Automatically register MessageInterface with the zero-id
- } else {
- cout << "could not assign an ID to a message called \"" << name << "\", it seems not to be registered in the message-type-set" << endl;
- return const_cast<TypeNameMap&>(ids_)[ name ];
- }
-}
-
-std::string MessageTypeSet::stats() const {
- ostringstream ret;
- ret << "count of message-types: " << types_.size() << endl;
- for ( TypeNameMap::const_iterator it = ids_.begin(); it != ids_.end(); ++it ) {
- ret << "type: " << ( *it ).first << " id: " << ( *it ).second.desc() << endl;
- }
- return ret.str();
-}
-
-///returns the class-name of the message(the most specialized one registered in this type-set)
-std::string MessageTypeSet::identify( MessageInterface* msg ) const {
- MessageType id = msg->info().type();
- MessageFactoryInterface* i = findFactory( id );
- if ( i ) {
- return i->identify();
- } else {
- return "could not identify";
- }
-}
-
-}
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/message.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h (nonexistent)
@@ -1,189 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef EASYMESSAGE
-#define EASYMESSAGE
-#include "messagetypeset.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/base_object.hpp>
-
-/**
-This header offers by far the easiest way of declaring a message.
-The Macro
-EASY_DECLARE_MESSAGE( Name, Parent, index, Data, paramSplitPosition )
-Declares a complete Message named "Name", derived from "Parent", and also derived on a custom data-structure called "Data".
-That Data-structure should implement a classic boost "template<class Archive> void serialize( Archive& arch )"-function,
-and should have a default-constructor to create the structure while loading.
-Also it can have a normal constructor with arbitrary count of arguments. That Argument-count must be given in the last
-macro-parameter called "paramSplitPosition". Then, all parameters given to the function-constructor up to the specified count will
-be given to the Data-constructor, and all other parameters to the Parent.
-Unlike the rest of the messaging-system, the Data-structure may use the standard boost-serialization versioning-system.
-
-EASY_IMPLEMENT_MESSAGE(MessageName) must be used in a source-file to implement the message.
-EASY_IMPLEMENT_MESSAGE also calls REGISTER_MESSAGE, so that doesn't have to be done separately when this system is used.
-
-The constructors can be specialized to fit special needs(see EASY_CONSTRUCTOR_...)
-
-If you want to override virtual functions or want to access protected members, use
-EASY_DECLARE_MESSAGE_BEGIN(...)
-override your functions here(this is inside of the classes body)
-END()
-
-
-*/
-
-//These are class-initialization-declarations for with different redirections to Data / Parent
-//First: Total count of parameters, second: how many of them go into Data
-#define PARAMETER_SPLIT_0_0(Data, Parent) Data(), Parent( info(this) )
-#define PARAMETER_SPLIT_0_1(Data, Parent) Data(), Parent( info(this) )
-#define PARAMETER_SPLIT_0_2(Data, Parent) Data(), Parent( info(this) )
-#define PARAMETER_SPLIT_0_3(Data, Parent) Data(), Parent( info(this) )
-#define PARAMETER_SPLIT_0_4(Data, Parent) Data(), Parent( info(this) )
-#define PARAMETER_SPLIT_0_5(Data, Parent) Data(), Parent( info(this) )
-
-#define PARAMETER_SPLIT_1_0(Data, Parent) Data(), Parent( info(this), p1 )
-#define PARAMETER_SPLIT_1_1(Data, Parent) Data( p1 ), Parent( info(this) )
-#define PARAMETER_SPLIT_1_2(Data, Parent) Data( p1 ), Parent( info(this) )
-#define PARAMETER_SPLIT_1_3(Data, Parent) Data( p1 ), Parent( info(this) )
-#define PARAMETER_SPLIT_1_4(Data, Parent) Data( p1 ), Parent( info(this) )
-#define PARAMETER_SPLIT_1_5(Data, Parent) Data( p1 ), Parent( info(this) )
-
-#define PARAMETER_SPLIT_2_0(Data, Parent) Data(), Parent( info(this), p1, p2 )
-#define PARAMETER_SPLIT_2_1(Data, Parent) Data(p1), Parent( info(this), p2 )
-#define PARAMETER_SPLIT_2_2(Data, Parent) Data(p1, p2), Parent( info(this) )
-#define PARAMETER_SPLIT_2_3(Data, Parent) Data(p1, p2), Parent( info(this) )
-#define PARAMETER_SPLIT_2_4(Data, Parent) Data(p1, p2), Parent( info(this) )
-#define PARAMETER_SPLIT_2_5(Data, Parent) Data(p1, p2), Parent( info(this) )
-
-#define PARAMETER_SPLIT_3_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3 )
-#define PARAMETER_SPLIT_3_1(Data, Parent) Data(p1), Parent( info(this), p2, p3 )
-#define PARAMETER_SPLIT_3_2(Data, Parent) Data(p1, p2), Parent( info(this), p3 )
-#define PARAMETER_SPLIT_3_3(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
-#define PARAMETER_SPLIT_3_4(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
-#define PARAMETER_SPLIT_3_5(Data, Parent) Data(p1, p2, p3), Parent( info(this) )
-
-#define PARAMETER_SPLIT_4_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3, p4 )
-#define PARAMETER_SPLIT_4_1(Data, Parent) Data(p1), Parent( info(this), p2, p3, p4 )
-#define PARAMETER_SPLIT_4_2(Data, Parent) Data(p1, p2), Parent( info(this), p3, p4 )
-#define PARAMETER_SPLIT_4_3(Data, Parent) Data(p1, p2, p3), Parent( info(this), p4 )
-#define PARAMETER_SPLIT_4_4(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this) )
-#define PARAMETER_SPLIT_4_5(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this) )
-
-#define PARAMETER_SPLIT_5_0(Data, Parent) Data(), Parent( info(this), p1, p2, p3, p4, p5 )
-#define PARAMETER_SPLIT_5_1(Data, Parent) Data(p1), Parent( info(this), p2, p3, p4, p5 )
-#define PARAMETER_SPLIT_5_2(Data, Parent) Data(p1, p2), Parent( info(this), p3, p4, p5 )
-#define PARAMETER_SPLIT_5_3(Data, Parent) Data(p1, p2, p3), Parent( info(this), p4, p5 )
-#define PARAMETER_SPLIT_5_4(Data, Parent) Data(p1, p2, p3, p4), Parent( info(this), p5 )
-#define PARAMETER_SPLIT_5_5(Data, Parent) Data(p1, p2, p3, p4, p5), Parent( info(this) )
-
-#define EASY_CONSTRUCTOR(Name, Parent, index, Data, SplitPosition) \
-inline Name( const Teamwork::MessageConstructionInfo& info ) : Data(), Parent( info(this) ) { \
-} \
-template<class Param1> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1 ) : PARAMETER_SPLIT_ ## 1 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1> \
-Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1 ) : PARAMETER_SPLIT_ ## 1 ## _ ## SplitPosition (Data,Parent) { \
-} \
-\
-template<class Param1, class Param2> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2> \
-Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, const Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2> \
-Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, const Param2& p2 ) : PARAMETER_SPLIT_ ## 2 ## _ ## SplitPosition (Data,Parent) { \
-} \
-\
-template<class Param1, class Param2, class Param3> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3> \
-Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, const Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3> \
-Name( const Teamwork::MessageConstructionInfo& info, const Param1& p1, Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, const Param2& p2, const Param3& p3 ) : PARAMETER_SPLIT_ ## 3 ## _ ## SplitPosition (Data,Parent) { \
-} \
-\
-template<class Param1, class Param2, class Param3, class Param4> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3, Param4& p4 ) : PARAMETER_SPLIT_ ## 4 ## _ ## SplitPosition (Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3, class Param4> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, const Param3& p3, const Param4& p4 ) : PARAMETER_SPLIT_ ## 4 ## _ ## SplitPosition(Data,Parent) { \
-} \
-template<class Param1, class Param2, class Param3, class Param4, class Param5> \
-Name( const Teamwork::MessageConstructionInfo& info, Param1& p1, Param2& p2, Param3& p3, Param4& p4, Param5& p5 ) : PARAMETER_SPLIT_ ## 5 ## _ ## SplitPosition(Data,Parent) { \
-} \
-/**/
-
-
-//The first 4 lines of the following macros are used to store the values for the implementation, so they must not be given to the implementation again
-#define EASY_DECLARE_MESSAGE_BEGIN( Name, Parent, index, Data, paramSplitPosition ) \
-class Name : public Data, public Parent { \
-DECLARE_MESSAGE( Name, Parent, index ); \
-typedef Data DataType; \
- public: \
- \
-EASY_CONSTRUCTOR ( Name, Parent, index, Data, paramSplitPosition ) \
-virtual void serialize( OutArchive& arch ); \
-Name( InArchive& arch, const Teamwork::MessageInfo& info ); \
-/**/
-
-#define EASY_IMPLEMENT_MESSAGE(Name) \
- void Name :: serialize( OutArchive& arch ) { \
- Precursor::serialize( arch ); \
- /*static_cast<DataType&>(*this).serialize( arch, 0 );*/ \
- arch & boost::serialization::base_object<DataType>(*this); \
-} \
-Name :: Name ( InArchive& arch, const Teamwork::MessageInfo& info ) : Precursor( arch, info ) { \
- /*static_cast<DataType&>(*this).serialize( arch, 0 );*/ \
- arch & boost::serialization::base_object<DataType>(*this); \
-} \
-REGISTER_MESSAGE(Name) \
-/**/
-
-
-#define END() \
-}
-
-#define EASY_DECLARE_MESSAGE( Name, Parent, index, Data, paramSplitPosition ) \
-EASY_DECLARE_MESSAGE_BEGIN( Name, Parent, index, Data, paramSplitPosition ) \
-END()
-
-///Can be used as a dummy for EASY_DECLARE_MESSAGE, if no data is wished
-struct NoData {
- template <class Archive>
- void serialize( Archive& /*arch*/, unsigned int /*version*/ ) {}
-}
-;
-
-template <class T = int>
-struct NoDataB {
- template <class Archive>
- void serialize( Archive& /*arch*/, unsigned int /*version*/ ) {}
-}
-;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/easymessage.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp (nonexistent)
@@ -1,356 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "messageimpl.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include "serialization.h"
-#include "messagetypeset.h"
-#include "helpers.h"
-#include "basicsession.h"
-#include "teamworkmessages.h"
-#include "teamworkservermessages.h"
-#include "messagesendhelper.h"
-#include <boost/serialization/vector.hpp>
-#include <boost/serialization/list.hpp>
-
-
-
-
-namespace Teamwork {
-
- MessageConstructionInfo::MessageConstructionInfo( const std::string& name, const MessageTypeSet& typeSet ) : name_(name), typeSet_(typeSet) {
- }
-
- MessageConstructionInfo::MessageConstructionInfo( const MessageTypeSet& rhs ) : typeSet_( rhs ) {
- }
-
- const MessageTypeSet& MessageConstructionInfo::typeSet() const {
- return typeSet_;
- }
-
- const std::string MessageConstructionInfo::name() const {
- return name_;
- }
-
- MessageInfo MessageConstructionInfo::messageInfo() const {
- return typeSet_.messageInfo( name_.c_str() );
- }
-
- MessageConstructionInfo::MessageConstructionInfo( const MessageConstructionInfo& rhs ) : name_( rhs.name_ ), typeSet_( rhs.typeSet_ ) {
- }
-
- MessageConstructionInfo& MessageConstructionInfo::operator=( const MessageConstructionInfo& ) {
- return *this;
- }
-
- template<class Archive>
- void MessageType::serialize( Archive& target, const uint /*version*/ ) {
- target & idList_;
- packFastId();
- }
-
- MessageInfo::MessageInfo( const MessageInfo& rhs ) {
- operator=( rhs );
- }
-
- MessageInfo& MessageInfo::operator = ( const MessageInfo& rhs ) {
- id_ = rhs.id_;
- uniqueId_ = rhs.uniqueId_;
- session_ = rhs.session_;
- user_ = rhs.user_;
- replyToMessage_ = rhs.replyToMessage_;
- isReplyTo_ = rhs.isReplyTo_;
- deserialized_ = rhs.deserialized_;
- return *this;
- }
-
-
- MessageInfo::MessageInfo( InArchive& arch ) : id_( arch ), deserialized_( true ) {
- //cout << "deserializing message-info";
- arch & isReplyTo_;
- arch & uniqueId_;
- }
-
- const MessageType& MessageInfo::type() const {
- return id_;
- }
-
- void MessageInfo::serialize( OutArchive& arch, const uint version ) {
- id_.serialize( arch, version );
- arch & isReplyTo_;
- arch & uniqueId_;
- }
-
- UniqueMessageId MessageInfo::isReplyTo() const {
- return isReplyTo_;
- }
-
- void MessageInfo::setReply( UniqueMessageId replyId ) {
- isReplyTo_ = replyId;
- }
-
- void MessageInfo::setId( const MessageType& id ) {
- id_ = id;
- }
-
- void MessageInfo::makePersistent() {
- setSession( 0 );
- }
-
- bool MessageInfo::isIncoming() const {
- return deserialized_;
- }
-
- void MessageInfo::setIsIncoming( bool b ) {
- deserialized_ = b;
- }
-
- MessageInterface::~MessageInterface() {}
-
- const char* MessageInterface::name() {
- return staticName();
- }
-
- const char* MessageInterface::staticName() {
- return "MessageInterface";
- }
-
- const MessageType& MessageInterface::type() const {
- return info().type();
- }
-
- UniqueMessageId MessageInterface::uniqueId() const {
- return info().uniqueId();
- }
-
-
- bool MessageInterface::needReply() const {
- return false;
- }
-
- MessageInterface::ReplyResult::ReplyResult( bool messageHandled_ , bool awaitingMore_ ) : messageHandled( messageHandled_ ), awaitingMore( awaitingMore_ ) {}
-
- MessageInterface::ReplyResult MessageInterface::gotReply( const MessagePointer& /*p*/ ) {
- return false;
- }
-
-
-//By making this a static function, it is sure that the object is initialized when first used
-MessageTypeSet& globalMessageTypeSet() {
- static MessageTypeSet allMessages;
- return allMessages;
-}
-
-MessageSendHelper& globalMessageSendHelper() {
- static MessageSendHelper globalSendHelper;
- return globalSendHelper;
-}
-
-void registerDefaultMessages( MessageTypeSet& target ) {
- target.registerMessageType<RawMessage, MessageInterface>( );
- target.registerMessageType<TextMessage, RawMessage>( );
-}
-
-
-RawMessage::RawMessage( const MessageConstructionInfo& info, const DataVector& data ) : body_( data ) {
- info_ = info.messageInfo();
-}
-
-///This should be used to indicate that this message is a reply to the other message(replyTarget)
-void RawMessage::setReply( MessageInterface* replyTarget ) {
- info_.setReply( replyTarget->info().uniqueId() );
-}
-
-RawMessage::RawMessage( InArchive& from, const MessageInfo& info ) : info_( info ) {
- from & body_;
-}
-
-void RawMessage::serialize( OutArchive& target ) {
- target & body_;
-}
-
-const MessageInfo& RawMessage::info() const {
- return info_;
-}
-
-MessageInfo& RawMessage::info() {
- return info_;
-}
-
-/**This is called once a message has been tried to be sent, with the appropriate result, and can be used by the message to give some feedback to the sender. The Session used to send the message is still locked.
- */
-void RawMessage::result( bool /*success*/ ) {
-}
-
-/**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
-DataVector& RawMessage::body() {
- return body_;
-}
-
-/**Returns a reference to the data-store of this raw message. It does not include data serialized to inherited messages. */
-const DataVector& RawMessage::body() const {
- return body_;
-}
-
-
-TextMessage::TextMessage( const MessageConstructionInfo& info, const std::string& text ) : RawMessage( info(this), DataVector() ) {
- if ( text.length() == 0 )
- return ;
- body().resize( text.length() + 1 );
-
- memcpy( ( char* ) & ( body() [ 0 ] ), text.c_str(), text.length() + 1 );
-}
-
-TextMessage::TextMessage( InArchive& from, const MessageInfo& info ) : RawMessage( from, info ) {}
-
-std::string TextMessage::text() const {
- if ( body().size() == 0 )
- return std::string();
- return std::string( &( body() [ 0 ] ) );
-}
-
-SystemMessage::SystemMessage( const MessageConstructionInfo& info, Message msg, const string& ptext ) : TextMessage( info(this), ptext ), msg_( msg ) {}
-
-SystemMessage::SystemMessage( InArchive& arch, const MessageInfo& info ) : TextMessage( arch, info ) {
- serial( arch );
-}
-
-void SystemMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-
-SystemMessage::Message SystemMessage::message() {
- return msg_;
-}
-
-string SystemMessage::messageAsString() {
- switch ( msg_ ) {
- case LoginSuccess:
- return "LoginSuccess";
- case LoginFailedUnknown:
- return "LoginFailedUnknown";
- case BadAuthentication:
- return "BadAuthentication";
- case ServerBusy:
- return "SeverBusy";
- case Kicked:
- return "Kicked";
- case BadTarget:
- return "BadTarget";
- case StoredOnServer:
- return "StoredOnServer";
- case AlreadyLoggedIn:
- return "AlreadyLoggedIn";
- case GetUserList:
- return "GetUserList";
- case NoMessage:
- return "NoMessage";
- case SerializationFailed:
- return "SerializationFailed";
- };
- return "";
-}
-
-
-TeamworkMessage::TeamworkMessage( const MessageConstructionInfo& info ) : RawMessage( info(this), DataVector() ) {}
-TeamworkMessage::TeamworkMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {}
-
-IdentificationMessage::IdentificationMessage( const MessageConstructionInfo& info, const User& user ) : TeamworkMessage( info(this) ), user_( user ) {}
-
-IdentificationMessage::IdentificationMessage( InArchive& arch, const MessageInfo& info ) : TeamworkMessage( arch, info ) {
- serial( arch );
-}
-
-IdentificationMessage::operator User() {
- return user_;
-}
-
-void IdentificationMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-
-
-ForwardMessage::ForwardMessage( const MessageConstructionInfo& info, MessageInterface* messageToForward, const User& source, const User& targ ) : RawMessage( info(this), DataVector( ) ), source_( source ), target_( targ ) {
- serializeMessageToBuffer( body(), *messageToForward );
- source_.stripForTarget( target_ );
- target_.stripForIdentification();
-}
-
-ForwardMessage::ForwardMessage( InArchive& arch, const MessageInfo& info ) : RawMessage( arch, info ) {
- serial( arch );
-}
-
-void ForwardMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch ) ;
- serial( arch );
-}
-
-User& ForwardMessage::source() {
- return source_;
-}
-
-User& ForwardMessage::target() {
- return target_;
-}
-
-MessagePointer ForwardMessage::deserializeContained( MessageTypeSet& messageTypes ) {
- try {
- return buildMessageFromBuffer( body(), messageTypes, info().session() );
- } catch ( ... ) {
- return MessagePointer();
- }
-}
-
-bool ForwardMessage::storeOnServer() {
- return false;
-}
-
-UserListMessage::UserListMessage( const MessageConstructionInfo& info, list<UserPointer> inUsers, const UserPointer& targetUser ) : TeamworkMessage( info(this) ) {
- for ( list<UserPointer>::iterator it = inUsers.begin(); it != inUsers.end(); ++it ) {
- if ( *it == targetUser )
- continue;
-
- UserPointer::Locked l = *it;
- if ( l ) {
- if( !l->online() ) continue;
- users.push_back( *l );
- users.back().stripForPublic();
- } else {
- cout << "could not lock a user-pointer";
- }
- }
-}
-
-UserListMessage::UserListMessage( InArchive& arch, const MessageInfo& info ) : TeamworkMessage( arch, info ) {
- serial( arch );
-}
-
-void UserListMessage::serialize( OutArchive& arch ) {
- Precursor::serialize( arch );
- serial( arch );
-}
-
-INSTANTIATE_SERIALIZATION_FUNCTIONS( MessageType )
-
-REGISTER_MESSAGE( RawMessage )
-REGISTER_MESSAGE( TextMessage )
-REGISTER_MESSAGE( TeamworkMessage )
-REGISTER_MESSAGE( IdentificationMessage )
-REGISTER_MESSAGE( ForwardMessage )
-REGISTER_MESSAGE( SystemMessage )
-REGISTER_MESSAGE( UserListMessage )
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageimpl.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/plan
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/plan (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/plan (nonexistent)
@@ -1,27 +0,0 @@
-A client-server-system is needed, which will be implemented as a static C++-library.
-
-The library will provide classes and functions to:
-- run a client in a seperate thread.
-- run a server in a seperate thread.
-
-The final link between the program using the library and the library will be established by virtual member-functions.
-
-The library will then be used by kdevelop to connect to a server, or to open an own server. The whole library will only depend on STL and common-c++.
-Additionally a standalone server-program will be developed that opens a server using the library, independent from kdevelop.
-
-Objects that have the same number will share one implementation
-
-What the server implemented in the library has to do:
-- keep a list of (user, password, additional authentication-date, additional user-information, user-log) tuples
-- [2] store, manage, and use some options like whether anonymous users are allowed using a storage-class that allows simple changing, storing and restoring of the settings(the storage is done by the program that implements the server)
-- [3] provide a unified message-class for messages to either the server, or to other clients(the clients can communicate through the server or directly, but always moderated by the server). It will allow the clients sending each other messages of types the server does not know and would not understand.
-- provide a set of administrative messages for communications with clients.
-- store messages that are flagged to be safely delivered until the target-client comes online and gives a reply that it got the message
-
-What the client implemented in the library has to do:
-- keep a log of all interesting communication communication
-- keep and manage list of connected users
-- care about most of the implementation-details, and offer the client-program a simple interface to just override interesting high-level functions
-- [2] store, manage, etc. settings
-- [3] provide additional derived message-classes to communicate with other clients through the server
-- implementation of the client will be finished together with the kdevelop-plugin
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/plan
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h (nonexistent)
@@ -1,265 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGE_H
-#define MESSAGE_H
-
-#include "networkfwd.h"
-#include <map>
-#include <string>
-#include <iostream>
-#include "messagetypesetinternal.h"
-
-#include "messageinterface.h"
-#include "networkexport.h"
-
-#define MAXMESSAGESIZE 50000000
-#define DISABLEWARNINGS
-
-#define USE_RTTI
-
-template <class Message>
-const char* staticMessageName() {
- return Message::staticName();
-}
-
-namespace Teamwork {
-
-using namespace Tree;
-
-/**This allows multiple differing dispatch-targets(like the server + the thread). */
-class NETWORK_EXPORT MessageTypeSet {
- //protected:
- ///this should be optimized, and all the no more necessary template dispatch-code above removed
- typedef std::map<MessageType, MessageFactoryInterface* > TypeMap;
- typedef std::map<std::string, MessageType> TypeNameMap;
- TypeMap types_; ///would be more efficient to build a tree from the Chains and walk through that
- TypeNameMap ids_;
-
- ///this should walk through the messages upwards until it finds the best match
- TypeMap::iterator search( const MessageType& id );
-
- MessageType allocateSubId( const MessageType& id, int preferredSubId = 0 );
-
- mutable UniqueMessageId currentUniqueMessageId_;
-
- ///Changes the given id to the matching one
- MessageFactoryInterface* findFactory( MessageType& id ) const;
- public:
- MessageTypeSet();
-
- MessagePointer buildMessage( InArchive& from, const MessageInfo& inf ) const;
-
- ~MessageTypeSet();
-
- //Returns the message-type mapped to a message-name. A message-name in rtti (typeid(Message).name()) format is also accepted for messages derived from MessageInterface
- const MessageType& idFromName( const std::string& name ) const;
-
- std::string stats() const;
-
- ///returns the class-name of the message(the most specialized one registered in this type-set)
- std::string identify( MessageInterface* msg ) const;
-
- ///Register a static list of message-types to this type-set. Not yet registered parent-messages are automatically registered too.
- template < class Types >
- void registerMessageTypes() {
- RegisterAllTypes< typename Tree::MakeComplete< typename Tree::ExtractChains< Types >::Result, MessageInterface > ::Result, MessageTypeSet >::reg ( *this );
- }
-
- /** registers a type as slave of another given type, for simlicity registerMessageTypes should be used instead, together with a whole list of types */
- template <class Message, class ParentMessage>
- MessageType registerMessageType( int preferredSubId = 0 ) {
- if ( ids_.find( staticMessageName<Message>() ) != ids_.end() )
- return ids_[ staticMessageName<Message>() ];
-
- MessageType parentId = type<ParentMessage>();
- MessageType myId = allocateSubId( parentId, preferredSubId );
- if ( !parentId && typeid( ParentMessage ) != typeid( MessageInterface ) )
- std::cout << "while registering \"" << staticMessageName<Message>() << "\" the id of \"" << staticMessageName<ParentMessage>() << "\" could not be allocated!" << endl;
- if ( myId ) {
- //std::cout << "registering message-type " << staticMessageName<Message>() << " with id " << myId.desc() << endl;
- ids_[ staticMessageName<Message>() ] = myId;
- ids_[ typeid(Message).name() ] = myId;
- if ( types_.find( myId ) != types_.end() )
- delete types_[ myId ];
- types_[ myId ] = new MessageFactory<Message>();
- } else {
- std::cout << "could not allocate id for message-type " << staticMessageName<Message>() << endl;
- ///No ID could be allocated
- }
- return myId;
- }
-
- template <class Type>
- inline const MessageType& type() {
- return idFromName( staticMessageName<Type>() );
- }
-
-// MessageInterface* changeUniqueId( MessageInterface* msg ) {
-// msg->info().setUniqueId( currentUniqueMessageId_++ );
-// return msg;
-// }
-
- /** Returns a new correctly filled MessageInfo-structure, that also contains a vald UniqueId.
- * */
- template<class Message>
- MessageInfo messageInfo() const {
- return MessageInfo( idFromName( staticMessageName<MessageType>() ), currentUniqueMessageId_++ );
- }
-
- /**Returns a new correctly filled MessageInfo-structure, that also contains a vald UniqueId,
- * by the name as which the message is registered, or by the message's rtti-name.
- * */
- MessageInfo messageInfo(const char* name) const {
- return MessageInfo( idFromName( name ), currentUniqueMessageId_++ );
- }
- /*
- //For now the following is disabled to test whether it can be conveniently replaced with something that isn't that bad for executable-size
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType>
- inline MessageType* create() {
- return (MessageType*) changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ) ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1>
- inline MessageType* create( ParamType1 param ) {
- return (MessageType*) changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1, class ParamType2>
- inline MessageType* create( ParamType1 param, ParamType2 param2 ) {
- return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2 ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3>
- inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3 ) {
- return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3 ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4>
- inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4 ) {
- return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4 ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5>
- inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5 ) {
- return (MessageType*)changeUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4, param5 ) );
- }
- ///Conveniently create a new message with the correct Message-Id and unique-Id filled. All parameters are passed to the constructor of the created message.
- template <class MessageType, class ParamType1, class ParamType2, class ParamType3, class ParamType4, class ParamType5, class ParamType6>
- inline MessageType* create( ParamType1 param, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5, ParamType6 param6 ) {
- return (MessageType*)setUniqueId( new MessageType( idFromName( staticMessageName<MessageType>() ), param, param2, param3, param4, param5, param6 ) );
- }
- */
-};
-
-/**This is a message-type-set dedicated only to dispatching a chosen set of message-types
-to a chosen dispatch-target. It delivers the given message as the most special type the message
-is based on, by calling "TargetType::receiveMessage( MessageType* )".
- * @param TargetType must be the type the messages should be delivered to
- * @param Messages must be the list of messages(without any inheritance-info)*/
-template <class TargetType, class Messages>
-class NETWORK_EXPORT MessageDispatcher {
- TargetType& targ_;
-
- struct EntryTemplate {
- template <class MessageType>
- struct Entry {
- int dispatch( TargetType& targ, MessageInterface* msg ) const {
- //std::cout << "dispatching as " << staticMessageName<MessageType>() << endl;
- ///Do the dispatch from the MessageDispatcher, so it can be declared friend and the dispatch-functions can be private.
- return MessageDispatcher<TargetType, Messages>::template dispatch<MessageType>
- ( targ, msg );
- }
- };
- };
-
- struct Action {
- TargetType& targ;
- MessageInterface* msg;
- int ret;
-
- Action( TargetType& target, MessageInterface* mesg ) : targ( target ), msg( mesg ), ret( 0 ) {}
- template <class Type, class Node>
- void operator () ( const Node& node ) {
- ret = node.dispatch( targ, msg );
- }
- };
-
- typedef Tree::TreeMasterNode< MessageInterface, Messages, EntryTemplate > Nodes;
- Nodes nodes_;
- public:
- MessageDispatcher( TargetType& targ ) : targ_( targ ) {}
-
- ///dispatches the message to the target that was given while construction
- int operator () ( MessageInterface* msg ) {
- Action act( targ_, msg );
- nodes_.find( msg->type(), act );
- return act.ret;
- }
-
- template <class Out>
- void print( Out& out ) {
-#ifdef USE_RTTI
- out << "Full Tree of " << typeid( *this ).name() << "\n";
- nodes_.print( out );
-#else
- out << "cannot print Message-Tree because RTTI is disabled" << "\n";
-#endif
- }
-
- template < class MessageType >
- static int dispatch( TargetType& targ, MessageInterface* msg ) {
- if ( dynamic_cast<MessageType*>( msg ) ) //this is just a security-check, which should hopefully never trigger
- return targ.receiveMessage( ( MessageType* ) msg );
- else
- cerr << "serious error in the message-type-system!";
- return 0;
- }
-};
-
-
-///This message-type-set contains all messages that were registered by a call to REGISTER_MESSAGE, and may be used instead of the local type-sets, for simplicity. That way messages can be serialized/deserialized without the core-parts being aware that they exist.
-MessageTypeSet& NETWORK_EXPORT globalMessageTypeSet();
-
-template <class MessageType>
-class NETWORK_EXPORT RegisterMessageTypeInternal {
- public:
- RegisterMessageTypeInternal() {
- globalMessageTypeSet().registerMessageTypes<MessageType>();
- }
-};
-
-/**This should be used directly from outside to globally register new message-types.
-The messages should have used the DECLARE_MESSAGE(...)-macro.
-*/
-#define REGISTER_MESSAGE(TYPE) \
-struct registerType##TYPE { \
- RegisterMessageTypeInternal<TYPE> msgReg;\
- registerType##TYPE() : msgReg() {} \
-}; \
-registerType##TYPE register##TYPE; \
-
-}
-
-#ifndef USE_RTTI
-
-BOOST_CLASS_IMPLEMENTATION( Teamwork::MessageInfo, boost::serialization::object_serializable );
-
-#endif
-
-#endif
-
-#include "user.h"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypeset.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h (nonexistent)
@@ -1,120 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef SAFELIST_H
-#define SAFELIST_H
-
-#include <list>
-#include <cc++/thread.h>
-#include "safesharedptr.h"
-
-namespace Teamwork {
- template <class Type>
- class SafeList {
- class MutexLocker {
- ost::Mutex& m_;
- MutexLocker& operator=( const MutexLocker& /*rhs*/ ) {
- return *this;
- };
-
- public:
- MutexLocker( ost::Mutex& mutex ) : m_( mutex ) {
- m_.enterMutex();
- }
-
- MutexLocker( MutexLocker& rhs ) : m_( rhs.m_ ) {
- m_.enterMutex();
- }
-
- ~MutexLocker() {
- m_.leaveMutex();
- }
- };
- std::list<Type> list_;
- mutable ost::Mutex m_;
- public:
- SafeList() {
- }
-
- void push_back( const Type& t ) {
- MutexLocker l( m_ );
- list_.push_back( t );
- }
-
- void push_front( const Type& t ) {
- MutexLocker l( m_ );
- list_.push_front( t );
- }
-
- void pop_back() {
- MutexLocker l( m_ );
- list_.pop_back();
- }
-
- void pop_front() {
- MutexLocker l( m_ );
- list_.pop_front();
- }
-
- Type& front() {
- MutexLocker l( m_ );
- return list_.front();
- }
-
- Type& back() {
- MutexLocker l( m_ );
- return list_.back();
- }
-
- const Type& front() const {
- MutexLocker l( m_ );
- return list_.front();
- }
-
- const Type& back() const {
- MutexLocker l( m_ );
- return list_.back();
- }
-
- SafeList& operator << ( const Type& item ) {
- MutexLocker l( m_ );
- push_back( item );
- return *this;
- }
-
- bool empty() const {
- MutexLocker l( m_ );
- return list_.empty();
- }
-
- void clear() {
- MutexLocker l( m_ );
- list_.clear();
- }
-
- bool empty() {
- MutexLocker l( m_ );
- return list_.empty();
- }
-
- operator bool() const {
- return !empty();
- }
-
- int size() const {
- MutexLocker l( m_ );
- return list_.size();
- }
- };
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safelist.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h (nonexistent)
@@ -1,75 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef MESSAGETYPESETINTERNAL_H
-#define MESSAGETYPESETINTERNAL_H
-
-#include "statictree.h"
-#include "messageinterface.h"
-#include <string>
-#include "networkexport.h"
-
-#define DISABLEWARNINGS
-
-namespace Teamwork {
-using namespace Tree;
-class MessageInfo;
-struct NETWORK_EXPORT MessageFactoryInterface {
- virtual MessagePointer buildMessage( InArchive& from , const MessageInfo& inf ) = 0;
- virtual std::string identify() = 0;
-#ifdef DISABLEWARNINGS
- virtual ~MessageFactoryInterface() {}
-#endif
-}
-;
-
-template <class MessageType>
-struct NETWORK_EXPORT MessageFactory : public MessageFactoryInterface {
- virtual MessagePointer buildMessage( InArchive& from, const MessageInfo& inf ) {
- return MessagePointer( new MessageType( from, inf ) );
- }
- virtual std::string identify() {
- return MessageType::staticName();
- }
-
-#ifdef DISABLEWARNINGS
- virtual ~MessageFactory() {}
-#endif
-}
-;
-
-template < class Type, class Target >
-struct NETWORK_EXPORT RegisterAllTypes {
- static void reg( Target& targ ) {
- targ.Error_Bad_Type_List();
- };
-};
-
-template < class Type, class Parent, uchar preferredSubId, class Target >
-struct NETWORK_EXPORT RegisterAllTypes< Chain< Type, Parent, preferredSubId >, Target > {
- static void reg( Target& targ ) {
- targ.template registerMessageType< Type, Parent > ( preferredSubId );
- };
-};
-
-template < class Side1, class Side2, class Target >
-struct NETWORK_EXPORT RegisterAllTypes< Binder< Side1, Side2 >, Target > {
- static void reg( Target& targ ) {
- RegisterAllTypes< Side2, Target >::reg( targ );
- RegisterAllTypes< Side1, Target >::reg( targ );
- };
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messagetypesetinternal.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h (nonexistent)
@@ -1,102 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef TEAMWORKMESSAGES_H
-#define TEAMWORKMESSAGES_H
-
-#include "networkfwd.h"
-#include "user.h"
-#include "messageimpl.h"
-#include "binder.h"
-#include "networkexport.h"
-
-namespace Teamwork {
-
-/*
-vector<char> messageToData( MessageInterface* msg ) {
- vector<char> vec;
- serializeToBuffer( vec, *msg );
- return vec;
-}*/
-
-/** Abstract message for all messages that have to do with the teamwork-stuff */
-
-class NETWORK_EXPORT TeamworkMessage : public RawMessage {
- DECLARE_MESSAGE( TeamworkMessage, RawMessage, 1 );
- public:
- TeamworkMessage( const MessageConstructionInfo& messageTypes );
- TeamworkMessage( InArchive& arch, const MessageInfo& info );
-};
-
-class NETWORK_EXPORT IdentificationMessage : public TeamworkMessage {
- DECLARE_MESSAGE( IdentificationMessage, TeamworkMessage, 1 );
- User user_;
-
- template <class Arch>
- void serial( Arch& arch ) {
- arch & user_;
- }
-
- public:
-
- IdentificationMessage( const MessageConstructionInfo& messageTypes, const User& user );
-
- IdentificationMessage( InArchive& arch, const MessageInfo& info );
-
- operator User();
-
- virtual void serialize( OutArchive& arch );
-};
-
-typedef TextMessage MaintenanceMessage;
-typedef Chain< MaintenanceMessage, TextMessage, 15> MaintenanceMessageChain;
-
-
-class NETWORK_EXPORT ForwardMessage : public RawMessage {
- DECLARE_MESSAGE( ForwardMessage, RawMessage, 2 );
- User source_;
- User target_;
- public:
- ForwardMessage( const MessageConstructionInfo& messageTypes, MessageInterface* messageToForward, const User& source, const User& targ );
-
- ForwardMessage( InArchive& arch, const MessageInfo& info );
-
- template <class Arch>
- void serial( Arch& arch ) {
- arch & source_;
- arch & target_;
- }
-
- virtual void serialize( OutArchive& arch );
-
- User& source();
-
- User& target();
-
- MessagePointer deserializeContained( MessageTypeSet& messageTypes );
-
- ///Through this variable, messages should state that they should be stored on the server until the target-user is online if it cannot be reached
- virtual bool storeOnServer();
-};
-
-
-typedef Binder< TeamworkMessage >
-::Append< IdentificationMessage >::Result
-//::Append< MaintenanceMessageChain >::Result
-::Append< ForwardMessage >::Result
-TeamworkMessages;
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkmessages.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h (nonexistent)
@@ -1,52 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef TEAMWORK_HELPERS
-#define TEAMWORK_HELPERS
-
-#include "networkfwd.h"
-#include <vector>
-#include <string>
-#include <cstdlib>
-#include "networkexport.h"
-
-namespace Teamwork {
-
- class BasicTCPSession;
-
- NETWORK_EXPORT MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages, SessionPointer sess );
-
- ///May throw several exceptions
- NETWORK_EXPORT void serializeMessageToArchive( OutArchive& arch, MessageInterface& message );
-
- ///May throw several exceptions
- NETWORK_EXPORT void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message );
- NETWORK_EXPORT MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages, SessionPointer sess );
- NETWORK_EXPORT MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages);
-}
-
-template <class VecType, class Vec2Type>
-std::vector<VecType>& operator += ( std::vector<VecType>& lhs, const std::vector<Vec2Type>& rhs ) {
- uint osize = lhs.size();
- lhs.resize( lhs.size() + ( (rhs.size() * sizeof( Vec2Type )) / sizeof(VecType)) );
- memcpy( &lhs[osize], &rhs[0], sizeof(Vec2Type) * rhs.size() );
- return lhs;
-}
-
-std::string formatInt( int i );
-
-std::vector<char> binaryInt( int num );
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h (nonexistent)
@@ -1,36 +0,0 @@
-/*
- This file is part of the KDevelop platform
- Copyright 2006 Matt Rogers <mattr@kde.org>
- Copyright 2004 Jarosław Staniek <staniek@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef NETWORKEXPORT_H
-#define NETWORKEXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-#ifndef NETWORK_XPORT
-# ifdef MAKE_NETWORK_LIB
-# define NETWORK_EXPORT KDE_EXPORT
-# else
-# define NETWORK_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif /* NETWORKEXPORT_H*/
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/networkexport.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/defines.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/defines.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/defines.h (nonexistent)
@@ -1,21 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef DEFINES_H
-#define DEFINES_H
-
-#define STANDARDPORT 8161
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/defines.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h (nonexistent)
@@ -1,123 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef BASICSERVER_H
-#define BASICSERVER_H
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "weaksafesharedptr.h"
-#include "safelist.h"
-#include "logger.h"
-#include "networkexport.h"
-
-#include <cc++/socket.h>
-
-namespace Teamwork {
-template <class Target>
-struct HandlerProxy;
-
-class NETWORK_EXPORT BasicTCPSocket : public ost::TCPSocket {
- protected:
- bool onAccept( const ost::InetHostAddress &ia, ost::tpport_t port );
-
- public:
- BasicTCPSocket( ost::InetAddress &ia, int port );
-};
-
-/**This class runs the server as the run()-method is called in the same ost::Thread.
-This class never deletes itself, it can be deleted from outside once isRunning() returns false or the threads are joined, or it can be deleted through a SharedPtr/SafeSharedPtr.
-For each client that connects, it creates a session derived from BasicSession, which can also be
-created by a derived class.
- */
-class NETWORK_EXPORT BasicServer : protected ost::Thread, public WeakSafeShared {
- public:
- BasicServer( const char* str, int port, MessageTypeSet& messageTypes, LoggerPointer logger, bool openServer = true );
-
- virtual ~BasicServer();
-
- virtual bool isOk();
-
- ///returns the reference to a synchronized list of messages that are waiting for being processed. Processed messages should be removed from that list.
- SafeList<MessagePointer>& messages();
-
- /**After this function was called, the ost::Thread is going to exit soon.
- once isRunning() returns false, it can be deleted.*/
- void stopRunning();
-
- ///Returns whether the ost::Thread is running
- using ost::Thread::isRunning;
-
- ///Starts the ost::Thread, should be called after the ost::Thread was constructed
- using ost::Thread::start;
-
- using ost::Thread::join;
-
- ///This can be used to allow/disallow incoming connections. Already connected clients are not kicked on deactivation.
- void allowIncoming( bool allow );
-
- protected:
-
- ///this one is called from within another Thread, so it is more useful to override processMessage(...) in the teamwork-server than this one
- virtual bool handleMessage( MessagePointer msg ) throw();
-
- virtual LoggerPrinter err();
-
- virtual LoggerPrinter out( Logger::Level level = Logger::Info );
-
- virtual void run();
-
- /**This is called once at the beginning of the Thread*/
- virtual void initial();
-
- /**Gets called regularly from within the server-Thread
- should be overridden, can return whether it needs more cpu-time*/
- virtual bool think();
-
- /**This is called once at end of the Thread*/
- virtual void final( void );
-
- /**In this function, the derived class should take the ownership of the session. If it refuses the ownership, it can return false.
- once it has the ownership, it also has to care about proper
- Must be ovverridden. */
- virtual bool registerSession( SessionPointer /*session*/ );
-
- ///Returns a logger object that allows logging to the correct places
- LoggerPointer& logger();
- protected:
- MessageTypeSet& messageTypes_;
- private:
- ///This object is possible deleted during this call
- void clearSelfPointer();
-
- friend class HandlerProxy<BasicServer>;
- ost::BroadcastAddress addr;
- LoggerPointer logger_;
- bool failed_, exit_, allowIncoming_;
- BasicTCPSocket* server_;
- int port_;
- SafeList<MessagePointer> messagesToHandle_;
- SafeSharedPtr< BasicServer > selfPointer_;
-
- void buildSocket();
-
- void closeSocket();
-
- /**can be overridden to create own types derived from BasicTCPSession, can return 0(reject connection). Not called for forwarded sessions.*/
- virtual SessionPointer createSession( BasicTCPSocket* sock );
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicserver.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h (nonexistent)
@@ -1,57 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef MUTEXINTERFACE_H
-#define MUTEXINTERFACE_H
-
-#include <QMutex>
-#include "networkexport.h"
-
-class NETWORK_EXPORT MutexInterfaceImpl {
- mutable QMutex m_;
- public:
- MutexInterfaceImpl( const MutexInterfaceImpl& /*rhs*/ ) : m_(QMutex::Recursive) {
- }
-
- const MutexInterfaceImpl& operator=( const MutexInterfaceImpl& /*rhs*/ ) {
- return *this;
- }
-
- MutexInterfaceImpl() {}
-
- void lockCountUp() const {
- m_.lock();
- }
-
- bool tryLockCountUp() const {
- return m_.tryLock();
- }
-
- ///timeout in nanoseconds, may have a significant delay, so it shouldn't be used too much
- bool tryLockCountUp( int timeout ) const {
- if(timeout) {
- timeout /= 1000000; //nanoseconds -> milliseconds
- if(timeout)
- timeout = 1;
- }
- return m_.tryLock( timeout );
- }
-
- void lockCountDown() const {
- m_.lock();
- };
-
- ~MutexInterfaceImpl() {}
-};
-
-typedef MutexInterfaceImpl MutexInterface;
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/mutexinterface.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/COPYING
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/COPYING (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/COPYING (nonexistent)
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/COPYING
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp (nonexistent)
@@ -1,53 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "sessioninterface.h"
-#include "user.h"
-#include "messageinterface.h"
-
-namespace Teamwork {
- SessionInterface& SessionInterface::operator= ( const SessionInterface& /*rhs*/ ) {
- return *this;
- }
-
- SessionInterface::SessionInterface( const SessionInterface& /*rhs*/ ) : SafeShared() {
- }
-
- void SessionInterface::startSession() {}
-
- std::string SessionInterface::sessionName() {
- return sessionName_;
- }
-
- bool SessionInterface::sendReply( MessageInterface* msg, MessageInterface* replyTo ) {
- msg->info().setReply( replyTo->info().uniqueId() );
- msg->info().setReplyMessage( replyTo );
- return send( msg );
- }
-
- void SessionInterface::setSessionName( const std::string& name ) {
- sessionName_ = name;
- }
-
- std::string SessionInterface::peerDesc() {
- return std::string();
- }
-
- std::string SessionInterface::localDesc() {
- return std::string();
- }
-
- SessionInterface::SessionType SessionInterface::sessionType() {
- return Direct;
- }
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/sessioninterface.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h (nonexistent)
@@ -1,91 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef METAHELPERS_H
-#define METAHELPERS_H
-
-#include "statictree.h"
-
-namespace Meta {
-using namespace Tree;
-
-///If the same type is in the list multiple times, wantOccurrences can be the index within the list of those types
-template <class Type, class List, int wantOccurrences = 0, int previousCount = 0, int hadOccurrences = 0>
-struct FindInList {
- enum {
- value = -1,
- occurrences = hadOccurrences
- };
-};
-
-template <class Type, int wantOccurrences, int previousCount, int hadOccurrences>
-struct FindInList< Type, Type, wantOccurrences, previousCount, hadOccurrences> {
- enum {
- value = previousCount,
- occurrences = hadOccurrences + 1
- };
-};
-
-template <class Type, class Side1, class Side2, int wantOccurrences, int previousCount, int hadOccurrences>
-struct FindInList< Type, Binder<Side1, Side2>, wantOccurrences, previousCount, hadOccurrences> {
- typedef FindInList<Type, Side1, wantOccurrences, previousCount, hadOccurrences> Side1Find;
- typedef typename If < Side1Find::value != -1 && Side1Find::occurrences - 1 == wantOccurrences, Side1Find, FindInList < Type, Side2, wantOccurrences, Count<Side1>::value + previousCount, hadOccurrences + Side1Find::occurrences > > ::Result EndFind;
- enum {
- value = EndFind::value,
- occurrences = EndFind::occurrences
- };
-};
-
-
-///Takes the absolute index of a type in the list, and converts it to an occurrence-index(only counting the same types)
-template <class Type, class List, int wantNumber = 0, int previousCount = 0, int hadOccurrences = 0>
-struct FindRelativeInList {
- enum {
- value = -1,
- occurrences = hadOccurrences,
- relativeIndex = occurrences - 1
- };
-};
-
-template <class Type, int wantNumber, int previousCount, int hadOccurrences>
-struct FindRelativeInList< Type, Type, wantNumber, previousCount, hadOccurrences> {
- enum {
- value = previousCount,
- occurrences = hadOccurrences + 1,
- relativeIndex = occurrences - 1
- };
-};
-
-template <class Type, class Side1, class Side2, int wantNumber, int previousCount, int hadOccurrences>
-struct FindRelativeInList< Type, Binder<Side1, Side2>, wantNumber, previousCount, hadOccurrences> {
- typedef FindRelativeInList<Type, Side1, wantNumber, previousCount, hadOccurrences> Side1Find;
- typedef typename If < Side1Find::value == wantNumber, Side1Find, FindRelativeInList < Type, Side2, wantNumber, Count<Side1>::value + previousCount, hadOccurrences + Side1Find::occurrences > > ::Result EndFind;
- enum {
- value = EndFind::value,
- occurrences = EndFind::occurrences,
- relativeIndex = occurrences - 1
- };
-};
-
-template <int a, int b>
-struct AssertSame {
- typedef typename Assert < a == b > ::OK OK;
-};
-
-struct True {};
-struct False{};
-
-}
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/metahelpers.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/handler.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/handler.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/handler.h (nonexistent)
@@ -1,48 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef HANDLER_H
-#define HANDLER_H
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "networkexport.h"
-
-namespace Teamwork {
-class NETWORK_EXPORT HandlerInterface : public SafeShared {
- public:
- virtual ~HandlerInterface() {}
- /**When the handler is multithreaded, this function must be thread-safe by just queueing the Message to a secure list and processing later.
- No locking must be done within this function, since it may cause deadlocks as the handler itself tries to lock the message-sender */
- virtual bool handleMessage( MessagePointer msg ) = 0;
-};
-
-template <class Target>
-struct NETWORK_EXPORT HandlerProxy : public HandlerInterface {
- WeakSafeSharedPtr<Target> handler_;
- HandlerProxy( const SafeSharedPtr<Target>& targ ) : handler_( targ ) {}
-
- virtual bool handleMessage( MessagePointer msg ) {
- SafeSharedPtr<Target> targ = handler_.get();
- if ( targ )
- return targ.unsafe() ->handleMessage( msg );
- else
- return false;
- }
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/handler.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h (nonexistent)
@@ -1,568 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef POINTER_H
-#define POINTER_H
-
-//Needed for AtomicCounter
-#include <cc++/thread.h>
-
-#include "sharedptr.h"
-#include "mutexinterface.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/nvp.hpp>
-#include "networkexport.h"
-
-#define MILLI_TO_NANO 1000000
-#define SEC_TO_NANO 1000000000
-
-using namespace std;
-
-#ifndef SAFESHAREDPTR_HAVE_DEFAULT
-#define SAFESHAREDPTR_HAVE_DEFAULT
-template<class Type, class Serialization = NormalSerialization>
-class SafeSharedPtr;
-#endif
-
-/** Derive your classes from SafeShared if you want to use thread-safe reference-counting.
- * It can either be used with SafeSharedPtr to also control access to the function, or with SharedPtr
- * to only do thread-safe reference-counting.
- * */
-class NETWORK_EXPORT SafeShared : public MutexInterfaceImpl {
- public:
- /**
- * Standard constructor. This will initialize the reference count
- * on this object to 0.
- */
- inline SafeShared() : count( 0 ) { }
-
- /**
- * Copy constructor. This will @em not actually copy the objects
- * but it will initialize the reference count on this object to 0.
- */
- inline SafeShared( const SafeShared & ) : MutexInterfaceImpl(), count( 0 ) { }
-
- /**
- * Overloaded assignment operator.
- */
- inline SafeShared &operator=( const SafeShared & ) {
- return * this;
- }
-
- /**
- * Increases the reference count by one.
- */
- void _Shared_ref() const {
- ++count;
- }
-
- /**
- * Releases a reference (decreases the reference count by one). If
- * the count goes to 0, this object will delete itself.
- */
- void _Shared_unref() const {
- if ( !--count ) {
- const_cast<SafeShared*>( this ) ->prepareDeletion();
- if ( !count )
- delete this;
- }
- }
-
- /**
- * Return the current number of references held.
- *
- * @return Number of references
- */
- inline int _Shared_count() const {
- return count;
- }
-
- protected:
- virtual ~SafeShared() { }
- private:
- mutable ost::AtomicCounter count;
- ///This little additional effort is necessary to support weak pointers.
- virtual void prepareDeletion() {}
-};
-
-
-/**A shared pointer that is locked. The mutex will not be freed until this object is deleted.
- As long as this object exists, the data pointed to can be used exclusively. The data may also be 0 (invalid)! */
-#ifndef USE_NEW_LOCKED
-template <class Item>
-class NETWORK_EXPORT LockedSharedPtr : protected SharedPtr<Item> {
- private:
- void release() {
- if ( *this )
- this->data() ->lockCountDown();
- *( ( SharedPtr<Item>* ) this ) = 0;
- }
-
- void inc() {
- if ( *this )
- this->data() ->lockCountUp();
- }
-
- ///tries to increase the lock-count with a given timeout in nanoseconds, if ti fails sets itself to zero.
- void inc( uint64 timeout ) {
- if ( *this )
- if ( !this->data() ->tryLockCountUp( timeout ) )
- SharedPtr<Item>::operator=( 0 );
- }
-
- public:
- inline LockedSharedPtr() : SharedPtr<Item>() {
- inc();
- }
-
- template <class Serialization>
- inline LockedSharedPtr( const SharedPtr<Item, Serialization>& item ) : SharedPtr<Item>( item ) {
- inc();
- }
-
- inline LockedSharedPtr( Item* item ) : SharedPtr<Item>( item ) {
- inc();
- }
-
- ///timeout in nanoseconds
- template <class Serialization>
- inline LockedSharedPtr( const SharedPtr<Item, Serialization>& item, uint64 timeout ) : SharedPtr<Item>( item ) {
- inc( timeout );
- }
-
- inline LockedSharedPtr( const LockedSharedPtr<Item>& rhs ) : SharedPtr<Item>( rhs ) {
- inc();
- }
-
- template <class Target>
- inline LockedSharedPtr<Target> cast() {
- return LockedSharedPtr<Target>( dynamic_cast<Target*>( this->data() ) );
- }
-
- template <class Target>
- inline Target* freeCast() {
- return dynamic_cast<Target*>( this->data() );
- }
-
-
- LockedSharedPtr<Item>& operator = ( const LockedSharedPtr<Item>& rhs ) {
- if ( rhs.data() == this->data() )
- return * this;
- release();
- SharedPtr<Item>::operator=( rhs );
- inc();
- return *this;
- }
-
- inline ~LockedSharedPtr() {
- release();
- }
-
- using SharedPtr<Item>::operator->;
- using SharedPtr<Item>::operator*;
-
- inline bool operator ! () const {
- return !( bool ) * ( ( SharedPtr<Item>* ) this );
- }
-
- inline operator bool () const {
- return ( bool ) * ( ( SharedPtr<Item>* ) this );
- }
-
- inline operator const Item* () const {
- return data();
- }
-
- inline operator Item* () {
- return data();
- }
-
- template <class Item2>
- bool valueSmaller( const LockedSharedPtr<Item2>& rhs ) const {
- if ( this->data() ) {
- if ( rhs.data() ) {
- return ( this->data() ) ->operator<( *( rhs.data() ) );
- } else {
- return true;
- }
- } else {
- if ( rhs.data() ) {
- return true;
- } else {
- return false;
- }
- }
- }
-
- struct ValueSmallerCompare {
- inline bool operator() ( const LockedSharedPtr<Item>& lhs, const LockedSharedPtr<Item>& rhs ) const {
- return lhs.valueSmaller( rhs );
- }
- };
-
- using SharedPtr<Item>::data;
-};
-#else
-template <class Item>
-class NETWORK_EXPORT LockedSharedPtr : protected SharedPtr<Item> {
- private:
- void release() {
- if ( *this )
- this->data() ->lockCountDown();
- *( ( SharedPtr<Item>* ) this ) = 0;
- }
-
- void inc() {
- if ( *this )
- this->data() ->lockCountUp();
- }
-
- ///tries to increase the lock-count with a given timeout in nanoseconds, if ti fails sets itself to zero.
- void inc( uint64 timeout ) {
- if ( *this )
- if ( !this->data() ->tryLockCountUp( timeout ) )
- SharedPtr<Item, Serialization>::operator=( 0 );
- }
-
- using SharedPtr<Item, Serialization>::serialize;
-
- public:
- inline LockedSharedPtr() : SharedPtr<Item, Serialization>() {
- inc();
- };
-
- template <class Serialization2>
- inline LockedSharedPtr( const SharedPtr<Item, Serialization2>& item ) : SharedPtr<Item, Serialization>( const_cast<Item*>( item.data() ) ) {
- inc();
- };
-
- inline LockedSharedPtr( Item* item ) : SharedPtr<Item, Serialization>( item ) {
- inc();
- };
-
- ///timeout in nanoseconds
- template <class Serialization2>
- inline LockedSharedPtr( const SharedPtr<Item, Serialization2>& item, uint64 timeout ) : SharedPtr<Item, Serialization>( const_cast<Item*>( item.data() ) ) {
- inc( timeout );
- };
-
- template <class Serialization2>
- inline LockedSharedPtr( const LockedSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( const_cast<Item*>( rhs.data() ) ) {
- inc();
- }
-
- template <class Target>
- inline LockedSharedPtr<Target> cast() {
- return LockedSharedPtr<Target>( dynamic_cast<Target*>( this->data() ) );
- }
-
- template <class Target>
- inline Target* freeCast() {
- return dynamic_cast<Target*>( this->data() );
- }
-
-
- LockedSharedPtr<Item, Serialization>& operator = ( const LockedSharedPtr<Item, Serialization>& rhs ) {
- release();
- SharedPtr<Item, Serialization>::operator=( rhs );
- inc();
- return *this;
- }
-
- inline ~LockedSharedPtr() {
- release();
- }
-
- using SharedPtr<Item, Serialization>::operator->;
- using SharedPtr<Item, Serialization>::operator*;
-
- inline bool operator ! () const {
- return !( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
- }
-
- inline operator bool () const {
- return ( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
- }
-
- inline operator const Item* () const {
- return data();
- }
-
- inline operator Item* () {
- return data();
- }
-
- template <class Item2, class Serialization2>
- bool valueSmaller( const LockedSharedPtr<Item2, Serialization2>& rhs ) const {
- if ( this->data() ) {
- if ( rhs.data() ) {
- return ( this->data() ) ->operator<( *( rhs.data() ) );
- } else {
- return true;
- }
- } else {
- if ( rhs.data() ) {
- return true;
- } else {
- return false;
- }
- }
- }
-
-
- struct ValueSmallerCompare {
- inline bool operator() ( const LockedSharedPtr<Item, Serialization>& lhs, const LockedSharedPtr<Item, Serialization>& rhs ) const {
- return lhs.valueSmaller( rhs );
- }
- };
-
- using SharedPtr<Item, Serialization>::data;
-};
-#endif
-
-///five seconds of default-timeout
-const uint64 SafeSharedLockTimeout = (uint64) SEC_TO_NANO * (uint64) 5;
-
-template <class Item, class Serialization>
-class NETWORK_EXPORT SafeSharedPtr : protected SharedPtr<Item, Serialization> {
- public:
- typedef SharedPtr<Item, Serialization> Precursor;
-
- typedef LockedSharedPtr<Item> Locked;
-
- template <class Serialization2>
- inline SafeSharedPtr( const SharedPtr<Item, Serialization2>& i ) : SharedPtr<Item, Serialization>( i ) {}
-
- inline SafeSharedPtr() : SharedPtr<Item, Serialization>() {
- };
-
- inline SafeSharedPtr( Item* i ) : SharedPtr<Item, Serialization>( i ) {}
-
- inline SafeSharedPtr( const SafeSharedPtr<Item, Serialization>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
-
- template <class Item2, class Serialization2>
- inline SafeSharedPtr( const SafeSharedPtr<Item2, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
-
- template <class Serialization2>
- inline SafeSharedPtr( SafeSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.unsafe() ) {}
-#ifndef USE_NEW_LOCKED
-
- inline SafeSharedPtr( LockedSharedPtr<Item>& rhs ) : SharedPtr<Item, Serialization>( rhs.data() ) {}
-#else
- /*template<class Serialization2>
- inline SafeSharedPtr( LockedSharedPtr<Item, Serialization2>& rhs ) : SharedPtr<Item, Serialization>( rhs.data() ) {
- }*/
-#endif
-
- ///This function returns the locked pointer. This type of locking never returns zero, except the value of this pointer is zero..
- inline Locked lock ()
- const throw() {
- return Locked( *( Precursor* ) this );
- }
-
- ///The locking may fail, the result may be zero. @param timeout the locking-timeout in nanoseconds
- inline Locked tryLock( uint64 timeout = 0 ) const throw() {
- return Locked( *( Precursor* ) this, timeout );
- }
-
- template <class Type>
- inline operator SafeSharedPtr<Type, Serialization>() {
- return SafeSharedPtr<Type, Serialization>( static_cast<Type*>( this->data() ) );
- }
-
- /// tries to lock with the default-timeout defined by SafeSharedLockTimeout
- inline operator Locked() const {
- //if( SafeSharedLockTimeout ) {
- return Locked( *( Precursor* ) this, SafeSharedLockTimeout );
- /*} else {
- return Locked( *(Precursor*)this );
- }*/
- }
-
- template <class TargetType>
- inline SafeSharedPtr<TargetType, Serialization> cast() const {
- return SafeSharedPtr<TargetType, Serialization>( dynamic_cast<TargetType*>( const_cast<Item*>( this->data() ) ) );
- }
-
- ///This omits locking the mutex, and must only be used to call functions that are thread-safe
- inline Item* unsafe() const {
- return const_cast<Item*>( this->data() );
- }
-
-
- inline SafeSharedPtr<Item, Serialization>& operator = ( const SafeSharedPtr<Item, Serialization>& rhs ) {
- SharedPtr<Item, Serialization>::operator=( const_cast<Item*>( rhs.unsafe() ) );
- return *this;
- };
-
- template <class Item2, class Serialization2>
- inline SafeSharedPtr<Item, Serialization>& operator = ( const SafeSharedPtr<Item2, Serialization2>& rhs ) {
- SharedPtr<Item, Serialization>::operator=( const_cast<Item2*>( rhs.unsafe() ) );
- return *this;
- }
-
- inline operator bool () const {
- return ( bool ) * ( ( SharedPtr<Item, Serialization>* ) this );
- }
-
- inline bool operator !() const {
- return !( ( bool ) * this );
- }
-
- template <class Archive>
- void load( Archive& arch, uint /*version*/ ) {
- *this = 0;
- Serialization::template load<Item>
- ( *this, arch, 0 );
- }
-
- template <class Archive>
- void save( Archive& arch, uint /*version*/ ) const {
- Locked l = lock ()
- ;
- Serialization::template save<Item>
- ( *this, arch, 0 );
- }
-
- template <class Serialization2>
- inline bool operator == ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
- return this->data() == rhs.data();
- }
-
- template <class Serialization2>
- inline bool operator < ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
- return this->data() < rhs.data();
- }
-
- /**This uses non-timed locks, so there is a deadlock-danger. */
- template <class Item2, class Serialization2>
- bool valueSmaller( const SafeSharedPtr<Item2, Serialization2>& rhs ) const {
- if ( this->data() ) {
- if ( rhs.data() ) {
- Locked l = lock ()
- ;
- typename SafeSharedPtr<Item2, Serialization2>::Locked lr = rhs.lock();
- return ( this->data() ) ->operator<( *( rhs.data() ) );
- } else {
- return true;
- }
- } else {
- if ( rhs.data() ) {
- return true;
- } else {
- return false;
- }
- }
- }
- template <class Item2, class Serialization2>
- bool valueSame( const SafeSharedPtr<Item2, Serialization2>& rhs ) const {
- bool a = !this->data(), b = !rhs.data();
-
- if ( a && b )
- return true;
- else if ( a || b )
- return false;
-
- if ( this->data() ) {
- if ( rhs.data() ) {
- Locked l = lock ()
- ;
- typename SafeSharedPtr<Item2, Serialization2>::Locked lr = rhs.lock();
- return ( this->data() ) ->operator==( *( rhs.data() ) );
- } else {
- return true;
- }
- }
- return false;
- }
- /*
- template <class OT>
- bool operator < ( const SafeSharedPtr<OT>& rhs ) const {
- if( this->data() ) {
- if( rhs.data() ) {
- Locked l = lock();
- typename SafeSharedPtr<OT>::Locked lr = rhs.lock();
- return (this->data())->operator<(*(rhs.data()) );
- } else {
- return true;
- }
- } else {
- if( rhs.data() ) {
- return true;
- } else {
- return false;
- }
- }
- }
-
- template <class OT>
- bool operator < ( const SharedPtr<OT>& rhs ) const {
- if( this->data() ) {
- if( rhs.data() ) {
- Locked l = lock();
- return (this->data())->operator<(*(rhs.data()) );
- } else {
- return true;
- }
- } else {
- if( rhs.data() ) {
- return true;
- } else {
- return false;
- }
- }
- }
-
- template <class OT>
- bool operator < ( const OT& rhs ) const {
- if( this->data() ) {
- Locked l = lock();
- return (this->data())->operator<(rhs);
- } else {
- return true;
- }
- }*/
-
- struct ValueSmallerCompare {
- inline bool operator() ( const SafeSharedPtr<Item, Serialization>& lhs, const SafeSharedPtr<Item, Serialization>& rhs ) const {
- return lhs.valueSmaller( rhs );
- }
- };
-
- struct ValueIdentCompare {
- inline bool operator() ( const SafeSharedPtr<Item, Serialization>& lhs, const SafeSharedPtr<Item, Serialization>& rhs ) const {
- return lhs.valueSame( rhs );
- }
- };
-
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-};
-
-namespace boost {
-namespace serialization {
-template <class T, class B >
-struct implementation_level< SafeSharedPtr<T, B> > {
- typedef mpl::integral_c_tag tag;
- typedef mpl::int_< boost::serialization::object_serializable > type;
- BOOST_STATIC_CONSTANT(
- int,
- value = implementation_level::type::value
- );
-};
-}
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/safesharedptr.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h (nonexistent)
@@ -1,164 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef BASICSESSION
-#define BASICSESSION
-
-#include <cc++/socket.h>
-#include <vector>
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "safelist.h"
-#include "logger.h"
-#include "sessioninterface.h"
-#include <map>
-#include "networkexport.h"
-
-namespace Teamwork {
-
- class NETWORK_EXPORT SessionReplyManager {
- typedef std::map<uint, MessagePointer> WaitingMap;
- MutexInterfaceImpl* selfMutex_;
- WaitingMap waitingMessages_; ///here, all messages that wait for a reply are stored, mapped to their unique-ids.
- protected:
- SessionReplyManager( MutexInterfaceImpl* selfMutex );
-
- void addWaitingMessage( MessageInterface* msg );
-
- bool handleMessageWaiting( MessagePointer & msg );
-
- void removeAllMessages();
-
- virtual ~SessionReplyManager();
-};
-
-class NETWORK_EXPORT BasicTCPSession : protected ost::TCPSession, /*public virtual SafeShared,*/ public SessionInterface, public SessionReplyManager {
- public:
- using Thread::setName;
- using Thread::getName;
-
- ///Used by the server to construct a session
- BasicTCPSession( ost::TCPSocket &server, HandlerPointer handler_, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
-
- ///Used by the client to connect to a server
- BasicTCPSession( const ost::InetHostAddress &host, ost::tpport_t port, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
-
- virtual ~BasicTCPSession();
-
- virtual bool isOk();
-
- virtual void startSession();
-
- /**After this function was called, the thread is going to exit soon.
- once isRunning() returns false, it can be deleted(better call join()).*/
- virtual void stopRunning();
-
- ///This should get some tolerance in future
- virtual void stopRunningNow();
-
- ///THREAD-SAFE
- virtual bool send( MessageInterface* msg );
-
- ///Returns whether the thread is running
- virtual bool isRunning();
-
- ///Starts the thread, should be called after the thread was constructed
- using Thread::start;
-
- using Thread::join;
-
- using Socket::isPending;
-
- virtual string peerDesc();
-
- virtual string localDesc();
-
- virtual SessionDirection sessionDirection();
-
- protected:
-
- virtual LoggerPrinter err( int prio = 0 );
-
- virtual LoggerPrinter out( Logger::Level lv = Logger::Info );
-
- /**This can be reimplemented to decompress/decrypt the message.*/
- virtual void processIncomingMessage( std::vector<char>& /*data*/ ) {}
- ;
-
- /**This can be reimplemented to add compression or encryption. The data can be changed however desired.
- It is called just before the message is sent. */
- virtual void processOutgoingMessage( std::vector<char>& /*data*/ ) {}
- ;
-
- /**This can be overridden to possibly handle messages directly in this object.
- The default-implementation just sends the messages to the handler which created this session.*/
- virtual bool handleMessage( MessagePointer msg ) throw() ;
-
- ///This can be overridden to do some work on a regular basis. Returns whether more time is needed.
- virtual bool think() {
- return false;
- }
-
- ///This can be overridden to do final cleanup, store settings/state etc.
- virtual void final( void );
-
- virtual void initial();
-
- ///After this is called, the object may well be deleted
- void clearSelfPointer();
-
- virtual void initName( const string& namePrefix );
-
- private:
- virtual void run();
-
- void removeAllMessages();
-
- bool inputOutput();
-
- void serializeMessage();
-
- ///Takes all Data that was written away from the std::vector, throws StreamError
- template <class DataType>
- u32 writeData( std::vector<DataType>& from, u32 max );
-
- ///Appends the data to the given std::vector, throws StreamError
- template <class DataType>
- u32 getData( std::vector<DataType>& to, u32 max );
-
- void failed( std::string reason = "" );
-
- void sendingResult( bool result );
-
- bool dataToSend();
-
- SessionDirection myDirection;
- static const int ConnectionTimeout;
- bool exit_, failed_, running_, hadFinal_;
- uint receivingSize_;
- HandlerPointer handler_;
- LoggerPointer logger_;
- MessageTypeSet& messages_;
- std::vector<char> lookBack_;
- SafeList<MessagePointer> messagesToSend_;
- std::vector<char> sendData_;
- MessagePointer sendingMessage_; ///when sendData_ is not empty, this holds the message that is currently sent.
- std::vector<char> receivingData_;
- SafeSharedPtr<BasicTCPSession> selfPointer_; ///This is necessary to avoid deletion of the object before the thread has completed running
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/basicsession.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h (nonexistent)
@@ -1,98 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef TEAMWORK_CLIENT_H
-#define TEAMWORK_CLIENT_H
-
-#include <list>
-#include <map>
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "teamworkserver.h"
-#include "user.h"
-#include "networkexport.h"
-
-namespace Teamwork {
-
-class ClientSessionHandler;
-class UserListMessage;
-
-struct NETWORK_EXPORT ClientSessionDesc {
- UserPointer loginUser; ///user as which we are logged in
- SessionPointer session;
- ClientSessionDesc( const UserPointer& asUser = UserPointer(), const SessionPointer& _session = SessionPointer() ) {
- loginUser = asUser;
- session = _session;
- }
-};
-/* typedef Binder< AllTeamworkServerMessages >::Append< UserListMessage >::Result
- AllTeamworkClientMessages;*/
-
-struct NETWORK_EXPORT SessionPointerCompare {
-public:
- bool operator () ( const SessionPointer& s1, const SessionPointer& s2 ) const {
- return s1.unsafe() < s2.unsafe();
- }
-};
-
-/// A teamwork-client generally is the same as a teamwork-server, except it not only supports incoming connections, but also outgoing ones and connections forwarded through a server, and may be associated with a user-identity.
-class NETWORK_EXPORT Client : public Server {
- typedef map< ServerInformation, ClientSessionDesc > ClientSessionMap;
- ClientSessionMap clientSessions_;
- friend class ClientSessionHandler;
- bool needUserUpdate_;
-
- protected:
- virtual bool think();
-
- ///Is called whenever a connected server sends its list of connected users
- virtual void gotUserList( const std::list<UserPointer>& /*users*/ );
-
- ///this could be used to create a custom session deriven from MultiSession
- virtual SessionPointer createSession( BasicTCPSocket* sock );
-
- virtual bool registerSession( SessionPointer session );
-
- virtual void userDisconnected( const Teamwork::UserPointer& user );
-
- ///this is called whenever a connection is successfully established to a server
- virtual void connectedToServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ );
- ///this is called whenever the client disconnects from a connected server in any way
- virtual void disconnectedFromServer( const ClientSessionDesc& /*session*/, const ServerInformation& /*server*/ );
-
- virtual void processMessage( MessageInterface* msg );
-
- public:
- explicit Client( ServerInformation serverInfo, LoggerPointer logger = new Logger() );
-
- virtual ~Client();
-
- ///when no user is given, the identity-user is used. If that is not set, the connect fails.
- void connectToServer( const ServerInformation& server, const UserPointer& asUser = UserPointer() ) ;
- void disconnectFromServer( const ServerInformation& server ) ;
- void disconnectAllServers () ;
-
- bool isConnectedToServer( const ServerInformation& server ) ;
- ///may return invalid pointer when connectedToServer(...) == false
- MultiSessionPointer sessionToServer( const ServerInformation& server ) ;
-
- //int receiveMessage( IdentificationMessage* msg );
- int receiveMessage( ForwardMessage* msg );
- int receiveMessage( MessageInterface* msg ) ;
- int receiveMessage( UserListMessage* msg );
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkclient.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h (nonexistent)
@@ -1,256 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef CROSSMAPIMPL_H
-#define CROSSMAPIMPL_H
-
-#include "metahelpers.h"
-
-namespace Utils {
-using namespace Meta;
-
-template <class Value, class Key, class KeyExtractor, int num, int relativeNum>
-struct KeyValue {
- KeyValue( const Value& value ) : val( KeyExtractor::template Extractor<Key, relativeNum, Value>::getKey( value ) ) {}
- Key val;
-};
-
-struct DummyChainEle {
- template <class Type>
- DummyChainEle( const Type& /*t*/ ) {}
-}
-;
-
-///KeyValueChain stores a copy of all key-values in the given list(and can extract them during the constructor from the Value-type)
-template <class Value, class Keys, class KeyExtractor, int num = 0, class AllKeys = Keys>
-struct KeyValueChain : public If < ( Count< Keys >::value > 1 ), KeyValueChain < Value, typename RemoveOneLeft<Keys>::Result, KeyExtractor, num + 1, AllKeys>, DummyChainEle>::Result, public KeyValue< Value, typename GetOneLeft<Keys>::Result, KeyExtractor, num, FindRelativeInList<typename GetOneLeft<Keys>::Result, AllKeys, num>::relativeIndex > {
- typedef typename If< ( Count< Keys >::value > 1 ), KeyValueChain < Value, typename RemoveOneLeft<Keys>::Result, KeyExtractor, num + 1, AllKeys > , DummyChainEle > ::Result NextChain;
- typedef KeyValue< Value, typename GetOneLeft<Keys>::Result, KeyExtractor, num, FindRelativeInList<typename GetOneLeft<Keys>::Result, AllKeys, num>::relativeIndex > KeyValueItem;
-
- KeyValueChain( const Value& value ) : NextChain( value ), KeyValueItem( value ) {}
- KeyValueChain() {}
-
- ///Sets the value of the n'th key
- template<int n>
- void setValue( typename GetListItem< n, AllKeys >::Result& val ) {
- typedef typename GetListItem< n, AllKeys >::Result KeyType;
- static_cast<KeyValue< Value, KeyType, KeyExtractor, n, FindRelativeInList<KeyType, AllKeys, n>::relativeIndex >*>( this )->val = val;
- }
-
- ///Returns the value of the num'th key
- template<int n>
- typename GetListItem< n, AllKeys >::Result& getValue() {
- typedef typename GetListItem< n, AllKeys >::Result KeyType;
- return static_cast<KeyValue< Value, KeyType, KeyExtractor, n, FindRelativeInList<KeyType, AllKeys, n>::relativeIndex >*>( this )->val;
- }
-};
-
-struct ExtractKeyType {
- template<class Type>
- struct Action {
- typedef Type Result;
- typedef False isContainer;
- };
-};
-
-
-template <class Value, class Key, int num>
-struct CrossMapData {
- enum {
- number = num
- };
-
- typedef typename ExtractKeyType::template Action< Key >::Result RealKey;
- typedef std::multimap< RealKey, uint > MapType;
- typedef typename ExtractKeyType::template Action< Key >::isContainer IsContainer;
-
- MapType map;
-
- template<class KeyExtractor, int relativeNum>
- void insert( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, const Value & /*value*/, const uint id ) {
- insertInternal( keyVal.val, id, IsContainer() );
- }
-
- ///Not yet ported to the container-stuff
- template <class KeyExtractor, int relativeNum, class Validator>
- uint find( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, const Value & value, const Validator & validator ) {
- return findInternal( keyVal.val, value, validator, IsContainer() );
- }
-
- template <class KeyExtractor, int relativeNum>
- void remove( const KeyValue< Value, Key, KeyExtractor, num, relativeNum>& keyVal, uint id ) {
- removeInternal( keyVal.val, id, IsContainer() );
- }
-
- void clear() {
- map.clear();
- }
-
- bool hasContent() const {
- return !map.empty();
- }
-
- template <class Archive>
- void serialize( Archive & arch, uint /*version*/ ) {
- arch & map;
- }
-
- private:
-
- template<class Validator>
- uint findInternal( const Key& key, const Value & value, const Validator & validator, const True ) {
- for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it ) {
- uint ret = findInternal( *it, value, validator, False() );
- if( ret ) return ret;
- }
- return 0;
- }
-
- template<class Validator>
- uint findInternal( const RealKey& key, const Value & value, const Validator & validator, const False ) {
- std::pair<typename MapType::iterator, typename MapType::iterator>
- range = map.equal_range( key );
-
- while ( range.first != range.second ) {
- if ( validator.validateId( value, ( *range.first ).second ) )
- return ( *range.first ).second;
-
- ++range.first;
- }
-
- return 0;
- }
-
-
- void insertInternal( const Key& key, const uint id, const True ) {
- for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it )
- insertInternal( *it, id, False() );
- }
-
- void insertInternal( const RealKey& key, const uint id, const False ) {
- map.insert( make_pair( key, id ) );
- }
-
- void removeInternal( const Key& key, const uint id, const True ) {
- for( typename Key::const_iterator it = key.begin(); it != key.end(); ++it )
- removeInternal( *it, id, False() );
- }
-
- void removeInternal( const RealKey& key, const uint id, const False ) {
- std::pair<typename MapType::iterator, typename MapType::iterator>
- range = map.equal_range( key );
-
-
- while ( range.first != range.second ) {
- if ( id == ( *range.first ).second ) {
- map.erase( range.first );
- return ;
- }
-
- ++range.first;
- }
- }
-};
-
-struct CrossMapChainDummy {
-
- template<class C, class D, class V>
- uint find( const C&, const D&, const V& ) {
- return 0;
- }
-
- template<class C>
- void remove( const C&, uint ) {}
-
- template<class C, class D>
- void insert( const C&, const D&, uint ) {}
-
- void clear() {}
-
- bool hasContent() const {
- return false;
- }
- template<class Archive>
- void serialize( Archive & /*arch*/, uint /*version*/ ) {}
-};
-
-template<class Value, class Keys, int num>
-struct CrossMapChain : public If<( Count<Keys>::value > 1 ), CrossMapChain< Value, typename RemoveOneLeft<Keys>::Result, num + 1>, CrossMapChainDummy>::Result, public CrossMapData< Value, typename GetOneLeft<Keys>::Result, num >
-{
- typedef typename If<( Count<Keys>::value > 1 ), CrossMapChain< Value, typename RemoveOneLeft<Keys>::Result, num + 1>, CrossMapChainDummy>::Result Next;
- typedef CrossMapData< Value, typename GetOneLeft<Keys>::Result, num > Data;
-
- template<class KeyExtractor, class AllKeys>
- void insert( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys >& values, const Value & value, uint valueId ) {
- Next::template insert( values, value, valueId )
- ;
- Data::template insert( values, value, valueId )
- ;
- }
- template <class KeyExtractor, class AllKeys>
- void remove( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys>& values, uint id ) {
- Next::template remove( values, id )
- ;
- Data::template remove( values, id )
- ;
- }
-
- template <class KeyExtractor, class AllKeys, class Validator>
- uint find( const KeyValueChain< Value, Keys, KeyExtractor, num, AllKeys>& values, const Value & value, const Validator & validator ) {
- uint ret = Data::template find( values, value, validator )
- ;
- if ( ret )
- return ret;
-
- return Next::template find( values, value, validator )
- ;
- }
-
- int hasContent() const {
- bool a = Next::hasContent()
- ;
- bool b = Data::hasContent()
- ;
- if ( a != b && Count<Keys>::value >
- 1 )
- return 2;
- else if ( a && b )
- return 1;
- else
- return 0;
- }
-
- void clear() {
- Next::clear();
- Data::clear();
- }
-
- template <class Archive>
- void serialize( Archive & arch, uint /*version*/ ) {
- Data::serialize( arch, 0 );
- Next::serialize( arch, 0 );
- }
-};
-
-template <class Type>
-class CrossMapHashTraits {
- enum {
- hashable = 0
- };
-};
-
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/crossmapimpl.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h (nonexistent)
@@ -1,347 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef WEAKPOINTER_H
-#define WEAKPOINTER_H
-
-#include "safesharedptr.h"
-#include "networkexport.h"
-
-class WeakSafeShared;
-class WeakShared;
-
-#ifndef WEAKSAFESHAREDPTR_HAVE_DEFAULT
-#define WEAKSAFESHAREDPTR_HAVE_DEFAULT
-template<class Type, class Serialization = NormalSerialization>
-class WeakSafeSharedPtr;
-#endif
-
-
-class NETWORK_EXPORT WeakReference : public SafeShared {
- WeakSafeShared* pointer_;
- friend class WeakSafeShared;
-
- void invalidate() {
- pointer_ = 0;
- };
- public:
- WeakReference( WeakSafeShared* pointer ) : pointer_( pointer ) {}
- WeakSafeShared* pointer() {
- return pointer_;
- }
-};
-
-class NETWORK_EXPORT WeakSafeShared : protected SafeShared {
- SafeSharedPtr<WeakReference> ref_;
-
- virtual void prepareDeletion() {
- LockedSharedPtr<WeakReference> l = ref_.lock();
- if ( l )
- l->invalidate();
- }
-
- public:
- WeakSafeShared() : ref_( new WeakReference( this ) ) {}
-
- inline WeakSafeShared &operator=( const WeakSafeShared & ) {
- return * this;
- }
-
- const SafeSharedPtr<WeakReference>& _WeakSafeShared_getRef() const {
- return ref_;
- }
-
- using SafeShared::lockCountUp;
-
- using SafeShared::tryLockCountUp;
-
- using SafeShared::lockCountDown;
-
- using SafeShared::_Shared_count;
-
- using SafeShared::_Shared_ref;
-
- using SafeShared::_Shared_unref;
-};
-
-/** This header gives an additional type of pointer with a higher level. It's functionality is similar to that of QPointer.
- Holding a pointer of type WeakSafeShared, does not increase the reference-count of the pointed object. If the object is deleted,
- the pointer is set to zero. This comes with additional cost. The pointed object must be based on WeakSafeShared, and for each creation of
- that type one additional allocation of an internal SafeShared-object(especially a mutex) is done.
-
- WeakSafeSharedPtr itself does not consume more memory than SafeSharedPtr, but locking-operations are more costly, because two locks are done instead of one.
- */
-
-template <class Item, class Serialization>
-class NETWORK_EXPORT WeakSafeSharedPtr {
- SafeSharedPtr<WeakReference> ref_;
- public:
- WeakSafeSharedPtr() {}
-
- template <class Input>
- WeakSafeSharedPtr( const Input& ptr ) {
- set
- ( ptr );
- }
-
- SafeSharedPtr<Item, Serialization> get
- () const {
- typename SafeSharedPtr<WeakReference>::Locked l = ref_;
- if ( !l )
- return 0;
- return SafeSharedPtr<Item, Serialization>( dynamic_cast<Item*>( l->pointer() ) );
- }
-
- template <class Item2, class Serialization2>
- void set
- ( const SafeSharedPtr<Item2, Serialization2>& item ) {
- typename SafeSharedPtr<Item2, Serialization2>::Locked l = item;
- if ( !l ) {
- ref_ = 0;
- return ;
- } else {
- ref_ = static_cast<Item*>( l.data() ) ->_WeakSafeShared_getRef(); ///The item must be compatible
- }
- }
-
- void set
- ( const Item* item ) {
- if ( !item )
- ref_ = 0;
- else
- ref_ = item->_WeakSafeShared_getRef();
- }
-
- WeakSafeSharedPtr<Item, Serialization> operator = ( const Item* item ) {
- set
- ( item );
- return *this;
- }
-
- template <class Item2, class Serialization2>
- WeakSafeSharedPtr<Item, Serialization> operator = ( const SafeSharedPtr<Item2, Serialization2> item ) {
- set
- ( item );
- return *this;
- }
-
- ///Using this is same as locking a SafeSharedPtr, it uses the default-timeout.
- operator LockedSharedPtr<Item> () const {
- Item * p;
- {
- LockedSharedPtr<WeakReference> l = ref_;
- if ( !l )
- return 0;
- p = reinterpret_cast<Item*>( l->pointer() );
- }
- return LockedSharedPtr<Item>( SharedPtr<Item>( p ), SafeSharedLockTimeout );
- }
-
- template <class Serialization2>
- inline bool operator == ( const SafeSharedPtr<Item, Serialization2>& rhs ) const {
- if ( !rhs && !ref_ )
- return true;
- typename SafeSharedPtr<WeakReference>::Locked l = ref_;
- if ( !l )
- return false;
-
- return l->pointer() == ( WeakSafeShared* ) rhs.unsafe();
- }
-
- inline bool operator == ( const LockedSharedPtr<Item>& rhs ) const {
- if ( !rhs && !ref_ )
- return true;
- LockedSharedPtr<WeakReference> l = ref_;
- if ( !l )
- return false;
-
- return l->pointer() == ( WeakSafeShared* ) rhs.unsafe();
- }
-
- template <class Serialization2>
- inline bool operator == ( const SharedPtr<Item, Serialization2>& rhs ) const {
- if ( !rhs && !ref_ )
- return true;
- LockedSharedPtr<WeakReference> l = ref_;
- if ( !l )
- return false;
-
- return l->pointer() == ( WeakSafeShared* ) rhs.data();
- }
-
- inline bool operator == ( const Item* rhs ) const {
- if ( !rhs && !ref_ )
- return true;
- LockedSharedPtr<WeakReference> l = ref_;
- if ( !l )
- return false;
-
- return l->pointer() == ( WeakSafeShared* ) rhs;
- }
-};
-
-class NETWORK_EXPORT NormalWeakReference : public Shared {
- WeakShared* pointer_;
- friend class WeakShared;
-
- void invalidate() {
- pointer_ = 0;
- };
- public:
- NormalWeakReference( WeakShared* pointer ) : pointer_( pointer ) {}
- WeakShared* pointer() {
- return pointer_;
- }
- const WeakShared* pointer() const {
- return pointer_;
- }
-};
-
-/** To use WeakSharedPtr on an object, that object must be based this type.
- */
-
-class NETWORK_EXPORT WeakShared : private Shared {
- SharedPtr<NormalWeakReference> ref_;
-
- virtual void prepareDeletion() {
- ref_->invalidate();
- }
-
- public:
- WeakShared() : ref_( new NormalWeakReference( this ) ) {}
-
- inline WeakShared &operator=( const WeakShared & ) {
- return * this;
- }
-
- const SharedPtr<NormalWeakReference>& _WeakShared_getRef() const {
- return ref_;
- }
-
- using Shared::_Shared_count;
-
- using Shared::_Shared_ref;
-
- using Shared::_Shared_unref;
-};
-
-template <class Item, class Serialization = NormalSerialization>
-class NETWORK_EXPORT WeakSharedPtr {
- SharedPtr<NormalWeakReference> ref_;
- public:
- WeakSharedPtr() {}
-
- template <class Input>
- WeakSharedPtr( const Input& ptr ) {
- set
- ( ptr );
- }
-
- Item* get
- () {
- if ( !ref_ )
- return 0;
- return ( Item* ) ref_->pointer();
- }
-
- Item* get
- () const {
- if ( !ref_ )
- return 0;
- return ( Item* ) const_cast<WeakShared*>( ref_->pointer() );
- }
-
- void set
- ( const Item* item ) {
- if ( !item )
- ref_ = 0;
- else
- ref_ = item->_WeakShared_getRef();
- }
-
- /*WeakSharedPtr<Item, Serialization> operator = ( const Item* item ) {
- set
- ( item );
- return *this;
- }*/
-
- WeakSharedPtr<Item, Serialization> operator = ( const WeakSharedPtr<Item, Serialization>& item ) {
- set
- ( item );
- return *this;
- }
-
- /*operator SharedPtr<Item>() const {
- return get();
- }*/
-
- operator Item*() {
- return get
- ();
- }
-
- operator Item*() const {
- return const_cast<Item*>( get
- () );
- }
-
- Item* operator ->() {
- return get
- ();
- }
-
- ///This leads to another order than sorting equivalent normal pointers
- bool operator < ( const WeakSharedPtr<Item, Serialization>& rhs ) const {
- return ref_ < rhs.ref_;
- }
-
- operator bool() const {
- return ( bool ) get
- ();
- }
-
- const Item* operator ->() const {
- return get
- ();
- }
-
- operator SharedPtr<Item, Serialization>() const {
- return SharedPtr<Item, Serialization>( get() );
- }
-
- bool operator == ( const Item* rhs ) const {
- if ( !rhs && !ref_ )
- return true;
- if ( !ref_ )
- return false;
-
- return ref_->pointer() == ( WeakShared* ) rhs;
- }
-
- bool operator == ( const WeakSharedPtr<Item, Serialization>& rhs ) const {
- return ref_ == rhs.ref_;
- }
-
- template <class Archive>
- void serialize( Archive& arch, int /*version*/ ) {
- SharedPtr<Item, Serialization> it( get
- () );
- arch & it;
- set
- ( it );
- }
-};
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/weaksafesharedptr.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp (nonexistent)
@@ -1,272 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "forwardsession.h"
-#include "multisession.h"
-#include "helpers.h"
-
-namespace Teamwork {
-
-LoggerPrinter ForwardSession::err( int prio ) {
- LoggerPrinter p ( logger_, Logger::Error );
- if ( prio )
- p << prio << ":";
- p << "error in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-LoggerPrinter ForwardSession::out( Logger::Level lv ) {
- LoggerPrinter p ( logger_, lv );
- p << "in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-ForwardSession::ForwardSession( const UserPointer& sourceUser, const UserPointer& targetUser, const MultiSessionPointer& session, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler ) : SessionReplyManager( session.unsafe() ), session_( session ), targetUser_( targetUser ), sourceUser_( sourceUser ), logger_( logger ), notRunning_( false ), messageTypes_( messageTypes ), handler_( handler ) {
- MultiSessionPointer::Locked l = session_;
- if ( l ) {
- l->registerForwardSession( targetUser_, this );
- } else {
- ///error
- }
- setUser( targetUser );
- UserPointer::Locked lu = targetUser;
- if ( lu ) {
- setSessionName( "forward_" + lu->name() );
- SessionPointer::Locked ls = lu->online().session();
- if ( ls && ls->isRunning() ) {
- out( Logger::Warning ) << "creating an indirect session to " << lu->name() << ", but there already is a direct session";
- } else {
- lu->setSession( this );
- }
-
- } else {
- err() << "could not lock target-user of a forward-session";
- }
-}
-
-ForwardSession::~ForwardSession() {
-}
-
-bool ForwardSession::isOk() {
- MultiSessionPointer p = session_/*.get()*/;
- if ( !notRunning_ && p )
- return p.unsafe() ->isOk();
- return false;
-}
-bool ForwardSession::isRunning() {
- MultiSessionPointer p = session_/*.get()*/;
- if ( !notRunning_ && p )
- return p.unsafe() ->isRunning();
- return false;
-}
-
-
-bool ForwardSession::send( MessageInterface* msg ) {
- if ( !isRunning() )
- return false;
- MultiSessionPointer p = session_/*.get()*/;
- if( !p ) return false;
-
- msg->info().setSession( this );
-
- UserPointer::Locked source = sourceUser_;
- UserPointer::Locked target = targetUser_;
-
- if ( msg && source && target ) {
- if ( msg->needReply() )
- addWaitingMessage( msg );
- return p.unsafe() ->send( new ForwardMessage( messageTypes_, msg, *source, *target ) );
- } else {
- err() << "failed to do the necessary locks for sending a message(message and users)";
- return false;
- }
-}
-
-void ForwardSession::stopRunning() {
- out( Logger::Debug ) << "forwardsession: stopRunning";
- notRunning_ = true;
- session_ = 0;
-}
-
-void ForwardSession::stopRunningNow() {
- out( Logger::Debug ) << "forwardsession: stopRunningNow";
- notRunning_ = true;
- session_ = 0;
-}
-
-bool ForwardSession::think() {
- return false;
-}
-
-void ForwardSession::startSession() {}
-
-UserPointer ForwardSession::target() {
- return targetUser_;
-}
-
-SessionInterface::SessionDirection ForwardSession::sessionDirection() {
- MultiSessionPointer::Locked l = session_;
- if ( !l )
- return Incoming;
- return l->sessionDirection();
-}
-
-///Must only be called from within session_!
-bool ForwardSession::handleForwardMessage( const SafeSharedPtr<ForwardMessage>& msg ) {
- out( Logger::Debug ) << "handling forward-message";
- SafeSharedPtr<ForwardMessage>::Locked l = msg;
- UserPointer::Locked lu = sourceUser_;
-
- if ( l && lu ) {
- if ( lu->match( l->target() ) ) {
- MessagePointer message = l->deserializeContained( messageTypes_ );
- MessagePointer::Locked lmessage = message;
- if ( lmessage ) {
- lmessage->info().setSession( this );
- } else
- err() << "ForwardSession: could not lock a deserialized message";
-
- handleMessage( message );
- return true;
- }
- } else {
- out() << "could not lock forward-message or local user";
- }
-
- return false;
-}
-
-///Must only be called from within session_!
-bool ForwardSession::handleMessage( MessagePointer msg ) throw() {
- if ( handleMessageWaiting( msg ) )
- return true;
- if ( handler_ )
- return handler_.unsafe() ->handleMessage( msg );
- return false;
-}
-
-SessionInterface::SessionType ForwardSession::sessionType() {
- return Forwarded;
-}
-
-void ForwardSession::final() {
- SessionInterface::final();
-}
-
-
-LoggerPrinter FakeSession::err( int prio ) {
- LoggerPrinter p ( logger_, Logger::Error );
- if ( prio )
- p << prio << ":";
- p << "error in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-LoggerPrinter FakeSession::out( Logger::Level lv ) {
- LoggerPrinter p ( logger_, lv );
- p << "in session " << "(" << sessionName() << "): ";
- return p;
-}
-
-FakeSession::FakeSession( const UserPointer& targetUser, const LoggerPointer& logger, MessageTypeSet& messageTypes, HandlerPointer handler ) : logger_( logger ), messageTypes_( messageTypes ), handler_( handler ) {
- setUser( targetUser );
- UserPointer::Locked lu = targetUser;
- if ( lu ) {
- setSessionName( "session_fake_" + lu->name() );
- } else {
- setSessionName( "session_fake" );
- err() << "FakeSession: could not lock target-user of a fake-session";
- }
-}
-
-bool FakeSession::isOk() {
- return true;
-}
-
-bool FakeSession::isRunning() {
- return true;
-}
-
-bool FakeSession::send( MessageInterface* msg ) {
- SafeSharedPtr<FakeSession>::Locked l( this );
- if ( l ) {
- msg->info().setSession( this );
-
- ///Simulate sending the message by serializing and deserializing it within a local buffer
- vector<char> vec;
- serializeMessageToBuffer( vec, *msg );
- MessagePointer nmsg = buildMessageFromBuffer( vec, globalMessageTypeSet(), 0 );
- if ( !nmsg ) {
- err() << "FakeSession: could not build message from buffer";
- return false;
- }
- MessagePointer::Locked l = nmsg;
- if ( !l ) {
- err() << "FakeSession: could not lock created message";
- return false;
- }
- l->info().setReplyMessage( msg->info().replyToMessage() );
-
- receivedMessages_.push_back( nmsg );
- return true;
- } else {
- err() << "FakeSession: lock-error";
- }
- return true;
-}
-
-void FakeSession::stopRunning() {
- out( Logger::Debug ) << "FakeSession: stopRunning";
-}
-
-void FakeSession::stopRunningNow() {
- out( Logger::Debug ) << "FakeSession: stopRunningNow";
-}
-
-bool FakeSession::think() {
- return false;
-}
-
-void FakeSession::startSession() {}
-
-SessionInterface::SessionDirection FakeSession::sessionDirection() {
- return Outgoing;
-}
-
-///Must only be called from within session_!
-bool FakeSession::handleMessage( MessagePointer msg ) throw() {
- if ( handler_ )
- return handler_.unsafe() ->handleMessage( msg );
- return false;
-}
-
-SessionInterface::SessionType FakeSession::sessionType() {
- return Direct;
-}
-
-std::list<MessagePointer>& FakeSession::sentMessages() {
- return receivedMessages_;
-}
-
-
-/**This takes the first message off the stack of sent messages, serializes and deserializes it, and then returns the deserialized message.
- All exceptions from the serialization- and deserialization-process are passed by, additionally errors are indicated by throwing a const char*.
-*/
-MessagePointer::Locked FakeSession::getFirstMessage() throw( const char* ) {
- if ( receivedMessages_.empty() )
- throw "FakeSession: no messages available";
- return receivedMessages_.front();
-}
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/forwardsession.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp (nonexistent)
@@ -1,26 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include <boost/iostreams/stream.hpp>
-#include "mem_iostream.h"
-
-int main() {
-cout << "testing" << "\n";
-std::vector<char> v;
- stream<vector_device> io(v);
- char tv[4] = {0, 0, 0, 0};
- io.write( (char*)tv, 4 );
- io.flush();
- cout << v.size() << endl;
-
- return 1;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/buftest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h (nonexistent)
@@ -1,46 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SERVERCONFIG_H
-#define SERVERCONFIG_H
-
-#include "user.h"
-#include <string>
-#include <set>
-#include "networkexport.h"
-
-namespace Teamwork {
-struct NETWORK_EXPORT ServerConfiguration {
- std::string serverName;
- std::string serverPassword; ///A password that is used for users that don't have an own password set
-
- int port;
- std::string bind;
-
- typedef std::set<User> UserSet;
-
- ServerConfiguration();
-
- std::set<User> registeredUsers;
-
- template<class Archive>
- void serialize( Archive& arch, const unsigned int /*version*/ );
-};
-
-NETWORK_EXPORT bool loadServerConfiguration( ServerConfiguration& conf );
-NETWORK_EXPORT bool saveServerConfiguration( ServerConfiguration& conf );
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/serverconfig.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h (nonexistent)
@@ -1,44 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef TEAMWORKSERVERMESSAGES_H
-#define TEAMWORKSERVERMESSAGES_H
-
-#include "teamworkmessages.h"
-#include "user.h"
-#include "networkexport.h"
-#include <list>
-
-namespace Teamwork {
-
-struct NETWORK_EXPORT UserListMessage : public TeamworkMessage {
- DECLARE_MESSAGE( UserListMessage, TeamworkMessage, 2 );
- std::list<User> users;
-
- UserListMessage( const MessageConstructionInfo& messageTypes, std::list<UserPointer> inUsers, const UserPointer& targetUser );
-
- UserListMessage( InArchive& arch, const MessageInfo& info );
-
- template <class Arch>
- void serial( Arch& arch ) {
- arch & users;
- }
-
- virtual void serialize( OutArchive& arch );
-};
-
-typedef UserListMessage TeamworkServerMessages;
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkservermessages.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp (nonexistent)
@@ -1,78 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "logger.h"
-#include <iostream>
-
-namespace Teamwork {
-
-std::string Logger::levelToString( Level lv ) {
- switch ( lv ) {
- case Debug:
- return "debug";
- case Info:
- return "info";
- case Warning:
- return "warning";
- case Error:
- return "error";
- }
- return "unknown level";
-}
-
-///This can be overridden for custom logging
-void Logger::log( const std::string& str , Level lv ) {
- std::cout << "log-level: \"" << levelToString( lv ) << "\" message: \"" << str << "\"" << endl;
-}
-
-///This function is used when an error occurred while locking the Logger, or in other dangerous error-cases. It must be thread-safe.
-void Logger::safeErrorLog( const std::string& str, Level lv ) {
- std::cout << "problem while logging, statically logging: \"" << "log-level: \"" << levelToString( lv ) << "\" message: \"" << str << "\"" << endl;
-}
-
-void LoggerPrinter::invalidate() {
- out_ = 0;
- logger_ = 0;
-}
-LoggerPrinter& LoggerPrinter::operator = ( const LoggerPrinter& /*rhs*/ ) {
- return * this;
-}
-LoggerPrinter::LoggerPrinter( const LoggerPointer& logger, Logger::Level level ) : logger_( logger ), out_( 0 ), level_( level ) {
- /*if( logger_ )*/ out_ = new std::ostringstream();
-}
-
-LoggerPrinter::LoggerPrinter( const LoggerPrinter& rhs ) : logger_( rhs.logger_ ), out_( rhs.out_ ), level_ ( rhs.level_ ) {
- ( const_cast<LoggerPrinter&>( rhs ) ).invalidate();
-}
-
-LoggerPrinter::~LoggerPrinter() {
- if ( !out_ )
- return ; ///the logger has been copied and thereby invalidated
- std::string s = out_->str();
- if ( s.length() ) {
- if ( LoggerPointer::Locked l = logger_ ) {
- l->log( s, level_ );
- } else {
- if ( logger_ ) {
- logger_.unsafe() ->safeErrorLog( s, level_ );
- } else {
- cerr << "(bad logger): " << s << endl;
- }
- }
- }
- delete out_;
-}
-
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/logger.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt (nonexistent)
@@ -1,13 +0,0 @@
-To build, this project needs:
-- Common C++
-- Boost iostream library
-- Boost serialization library
-
-Under Debian/Ubuntu, found below their respective package names:
-- libcommoncpp2-dev
-- libboost-iostreams-dev
-- libboost-serialization-dev
-
-Although this is located within the kdevelop-tree,
-kdevelop is no dependency of this code.
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dependencies.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h (nonexistent)
@@ -1,86 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef MESSAGESERIALIZATION_H
-#define MESSAGESERIALIZATION_H
-
-///This header defines a serialization-class that can be used as template-parameter to SafeSharedPtr so it uses the message-serialization-system and the MessageTypeSet to serialize and deserialize messages(it stores and loads the messages as vectors). It automatically uses the global message-set stored in globalMessageTypeSet(). A hard lock is done while saving. Warning: May throw exceptions on errors
-
-#include "serialization.h"
-#include "messagetypeset.h"
-#include "helpers.h"
-#include <vector>
-
-#define USE_BUFFER_SERIALIZATION
-
-struct NETWORK_EXPORT MessageSerialization {
- template <class Type, class Archive, class Target>
- static void load( Target& t, Archive& arch, int /*version*/ ) {
- bool b = false;
- arch >> boost::serialization::make_nvp( "valid", b );
- if ( b ) {
-#ifdef USE_BUFFER_SERIALIZATION
-#ifdef USE_TEXT_ARCHIVE
- std::string s;
- arch & boost::serialization::make_nvp( "data", s );
- std::vector<char> v;
- v.resize( s.length() + 1 );
- memcpy( &v[ 0 ], s.c_str(), s.length() + 1 );
-#else
- std::vector<char> v;
- arch & boost::serialization::make_nvp( "data", v );
-#endif
-
- t = ( ( Teamwork::MessagePointer ) Teamwork::buildMessageFromBuffer( v, Teamwork::globalMessageTypeSet(), 0 ) ).cast<Type>();
-#else
- t = ( ( ( Teamwork::MessagePointer ) Teamwork::buildMessageFromArchive( arch, Teamwork::globalMessageTypeSet(), 0 ) ).cast<Type>();
-#endif
- }
- else {
- t = 0;
- }
- }
-
- template <class Type, class Archive, class Target>
- static void save( Target& t, Archive& arch, int /*version*/ ) {
- if ( t ) {
- bool b = true;
-#ifdef USE_BUFFER_SERIALIZATION
-
- arch << boost::serialization::make_nvp( "valid", b );
- std::vector<char> v;
- Teamwork::serializeMessageToBuffer( v, *t.unsafe() );
-
-#ifdef USE_TEXT_ARCHIVE
-
- std::string s;
- if ( v.size() )
- s = &v[ 0 ];
-
- arch & boost::serialization::make_nvp( "data", s );
-#else
- arch & boost::serialization::make_nvp( "data", v );
-#endif
-
-#else
- Teamwork::serializeMessageToArchive( arch, *t.unsafe() );
-#endif
- } else {
- bool b = false;
- arch << boost::serialization::make_nvp( "valid", b );
- }
- }
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/messageserialization.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h (nonexistent)
@@ -1,180 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-/** @Todo hide all this behind an interface
- * */
-
-#ifndef TEAMWORKSERVER_H
-#define TEAMWORKSERVER_H
-
-#include <string>
-#include <map>
-#include <set>
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "sessioninterface.h"
-#include "messageinterface.h"
-#include "basicserver.h"
-#include "user.h"
-#include "messagesendhelper.h"
-#include "serverconfig.h"
-#include "networkexport.h"
-
-namespace Teamwork {
-class Server;
-class IdentificationMessage;
-class ServerInformation;
-
-class SystemMessage;
-class ForwardMessage;
-class IdentificationMessage;
-class TextMessage;
-
-class ForwardSession;
-typedef SafeSharedPtr<ForwardSession> ForwardSessionPointer;
-
-class MultiSession;
-typedef SafeSharedPtr<MultiSession> MultiSessionPointer;
-typedef WeakSafeSharedPtr<MultiSession> WeakMultiSessionPointer;
-
-class NETWORK_EXPORT Server : public BasicServer, public MessageSendHelper {
- typedef std::map< SessionPointer, UserPointer > SessionMap;
- typedef std::set< MultiSessionPointer > SessionSet;
-
- UserPointer ident_;
-
- public:
- typedef std::set< UserPointer, UserPointer::ValueSmallerCompare > UserSet;
-
- Server( const ServerInformation& inf, const LoggerPointer& logger );
- ~Server();
-
- ///If the server-name in the configuration is not empty, and there currently is no local identity std::set, the local identity is std::set to that name.
- void setConfiguration( const ServerConfiguration& conf );
-
- const ServerConfiguration& configuration() const;
-
-
- ///The following two functions can be used to make UserPointers consistent through a longer session where the server may be closed/opened multiple times:
- void getUserSet( UserSet& users );
-
- ///Insert the given user-std::set into the server's own.
- void insertUserSet( const UserSet& users );
-
-
- ///If the user is not registered yet, the user is either created, copied and returned, or zero is returned.
- virtual UserPointer getUser( const UserPointer& user );
-
- ///Creates and registers a user with that identity if it does not already exist. May return zero on conflict.
- virtual UserPointer getUser( const UserIdentity& user );
-
- MessageTypeSet& messageTypes();
-
- ///These two should be overridden to use derived user-classes.
- virtual UserPointer createUser( IdentificationMessage* msg );
- virtual UserPointer createUser( const User* user );
-
-
- int receiveMessage( SystemMessage* msg );
- int receiveMessage( ForwardMessage* msg );
- int receiveMessage( IdentificationMessage* msg );
- int receiveMessage( TextMessage* msg );
- int receiveMessage( MessageInterface* msg );
-
- ///Tries to find the user(together with appropriately filled online-information) among connected users, servers, and users available through another connected server
- UserPointer findUser( const UserPointer& user );
-
- UserPointer findUser( const UserIdentity& user );
-
- ///Returns the user associated with the given session, may return invalid pointer.
- virtual UserPointer findSessionUser( const SessionPointer& session );
-
- virtual void closeSession( const SessionPointer& session );
-
- virtual void closeAllIncomingSessions();
-
- /**Associate this client with a user-identity. May be invalid( is initialized as such ).
- Without this identity correctly std::set, forwarded messages can not be dispatched. The identity will also be broadcasted to new clients that connect to the server, but not to already connected ones */
- void setIdentity( const UserPointer& user );
- ///Returns the user-identity currently associated with this client. May be invalid.
- virtual UserPointer identity() const;
-
- protected:
-
- virtual SessionPointer createSession( BasicTCPSocket* sock );
-
- virtual bool registerSession( SessionPointer session );
-
- ///Internally maps the given user to his session. Fails if the user already has a session
- virtual bool registerSessionUser( const UserPointer& user );
-
- virtual void initial( void );
-
- virtual bool think();
-
- virtual void final( void );
-
- virtual void processMessage( MessageInterface* msg );
-
- ///this is called whenever a new user successfully logged into the server, or when a connected server has sent an identification-message
- virtual void userConnected( const UserPointer& /*user*/ ) {}
-
- ///called whenever a user leaves the server(or connection to a server that had an identification is lost)
- virtual void userDisconnected( const UserPointer& /*user*/ ) {}
-
- private:
- SessionMap sessions_;
- SessionSet unknownSessions_;
- UserSet users_;
-
- ServerConfiguration configuration_;
-
- bool userListDirty_;
-
- void sendUserLists();
-
- void addUser( UserPointer user );
-};
-
-///Encapsulates information about a server to connect to
-class NETWORK_EXPORT ServerInformation {
- std::string addr_;
- int port_;
- public:
- explicit ServerInformation( const std::string& addr = "", int port = 0 ) {
- addr_ = addr;
- port_ = port;
- }
- bool operator < ( const ServerInformation& rhs ) const {
- return addr_ < rhs.addr_ || ( addr_ == rhs.addr_ && port_ < rhs.port_ );
- }
-
- const std::string& addr() const {
- return addr_;
- }
- int port() const {
- return port_;
- }
-
- std::string desc() const {
- std::stringstream s;
- s << addr_ << ":" << port_;
- return s.str();
- }
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/teamworkserver.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.h (nonexistent)
@@ -1,172 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef TEAMWORK_USER_H
-#define TEAMWORK_USER_H
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/nvp.hpp>
-#include <string>
-
-#include "networkfwd.h"
-#include "safesharedptr.h"
-#include "weaksafesharedptr.h"
-#include "networkexport.h"
-
-namespace Teamwork {
-///when a user is flagged as online that means that there is a session to that user. It does not mean that that session is really functional.
-class NETWORK_EXPORT OnlineInformation {
- friend class User;
- SafeSharedPtr<SessionInterface> session_;
- //SessionPointer session_;
-
- void setSession( const SessionPointer& sess );
-
- OnlineInformation( const OnlineInformation& rhs );
- OnlineInformation& operator = ( const OnlineInformation& rhs );
- public:
- OnlineInformation();
- ~OnlineInformation();
-
- ///When a user is reported as online, it is guaranteed that the session is valid.
- operator bool();
-
- const SessionPointer& session();
-};
-
-///This represents the identity of a user, it can be used to store it persistently.
-class NETWORK_EXPORT UserIdentity {
- std::string name_;
- friend class User;
-
- public:
- UserIdentity( const std::string& name ) {
- name_ = name;
- }
- UserIdentity() {}
-
- const std::string& name() const {
- return name_;
- }
-
- template<class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & boost::serialization::make_nvp( "name", name_ );
- }
-
- bool operator == ( const UserIdentity& rhs ) const {
- return name_ == rhs.name_;
- }
-
- bool operator < ( const UserIdentity& rhs ) const {
- return name_ < rhs.name_;
- }
-
- operator bool() const {
- return !name_.empty();
- }
- bool operator !() const {
- return name_.empty();
- }
-};
-
-
-class NETWORK_EXPORT User : public WeakSafeShared {
- std::string name_;
- std::string password_;
- std::string description_;
- std::string email_;
- int rights_;
- OnlineInformation online_;
- public:
- enum Rights {
- UserRights = 1,
- TrustedRights = 2,
- AdminRights = 4,
- BannedRights = 8
- };
-
- User( const UserIdentity& identity );
-
- User( const User* user );
-
- explicit User( std::string name = "", std::string password = "", std::string description = "" );
-
- virtual ~User();
-
- template<class Archive>
- void serialize( Archive& arch, const uint /*version*/ );
-
- bool matchRight( int right );
-
- ///this function is used for authentication. The given user should be the one trying to connect.
- virtual bool match( const User& u );
-
- virtual bool matchIdentity( const User& u );
-
- ///this function strips all information that is not necessary for correct authentication/identification at the given target-user
- virtual void stripForTarget( const User& /*target*/ );
-
- ///strips away all information that should stay private, but leaves things like description etc.
- virtual void stripForPublic();
-
- ///this function strips all information that is not necessary to generally identify a user(this might strip away more than stripForTarget, and removes passwords and such). It should not be called on derived classes, because the User-class is enough for simple Identification.
- void stripForIdentification();
-
- ///the structure can be changed through this.
- OnlineInformation& online();
-
- ///To set the user offline, this should be called with a zero-pointer
- virtual void setSession( const SessionPointer& sess );
-
- virtual std::string description() const;
-
- bool operator < ( const User& rhs ) const;
-
- bool operator < ( const std::string& rhs ) const;
-
- bool operator < ( const UserIdentity& rhs ) const;
-
- const std::string& name() const;
-
- int rights() const;
-
- void setRights( int rights );
-
- std::string rightsAsString() const;
-
- std::string email() const;
-
- void setEmail( const std::string& );
-
- ///This function is thread-safe(no locking must be done before calling it)
- std::string safeName() const;
-
- const std::string& password() const;
-
- void ban( bool banned );
-
- bool banned() const;
-
- void setPassword( const std::string& password );
-
- ///Creates a lightweigth-structure for identification which may be used for persistent storage.
- UserIdentity identity();
-};
-
-typedef SafeSharedPtr<User, BoostSerialization> UserPointer;
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/user.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h (nonexistent)
@@ -1,105 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-///WARNING: This is not tested yet
-
-/** This class works similar to MessageDispatcher, except that it is not static.
- * Callback-functions can be registered at runtime, and
- * there is less dynamically generated code.
- *
- * The target-classes must be based on WeakSafeShared.
- * That way nobody has to care about unregistering targets, because DynamicMessageDispatcher will disconnect
- * destroyed targets automatically..
- *
- * Also the target must be kept alive by a SafeSharedPtr.
- * (else they would get destructed as soon as the reference-count gets increased and decreased once)
- *
- *
- * The downside is that it's slower, the callback-functions need to be registered on runtime,
- * it's probably more error-prone, and what's happening is not absolutely clear on compile-time.
- *
- * It should be preferred over MessageDispatcher either when the message-delivery should be more
- * flexible, or when several(maybe unknown) targets should be allowed to register callback-functions on their own, like plugins.
- *
- * This class is not suitable for handling many(above 50) dispatch-target.
- *
- * The order of message-delivery:
- * When receiveMessage(...) is called, the order of message-delivery is defined this way:
- * 1. Deliver first to the best specialized targets
- * 2. Among targets that match equally well, the last registered targets will get the message first.
- *
- * Once any delivery-function returns a nonzero return-value, the message-deliverey will be stopped and the
- * return-value returned by the receiveMessage(...) -function.
-**/
-
-#ifndef DYNAMICMESSAGEDISPATCHER_H
-#define DYNAMICMESSAGEDISPATCHER_H
-
-#include <vector>
-#include "networkexport.h"
-#include "dynamicmessagedispatcher_internal.h"
-#include "messagetypeset.h" //needed so the message-type-description can be extracted while registering
-
-namespace Teamwork {
-
- ///The message-dispatcher:
-class NETWORK_EXPORT DynamicMessageDispatcher {
- public:
- DynamicMessageDispatcher( MessageTypeSet& messageTypes = globalMessageTypeSet() );
- ~DynamicMessageDispatcher();
-
- /**
- * Use this to register your class for receiving all messages based on a given one.
- *
- * When a callback is registered using this function, the target will be locked before the target-function is called.
- *
- * @param Message(template-param 1) The message-type your class should receive
- * @param target a weak-pointer to the target the message should be delivered to(the weak pointer makes it safe to register and later delete the object without notification)
- * @param function pointer to a member-function of the taget-class, that must have the signature "int function( const SafeSharedPtr<Message>& )"
- *
- * For an example see main.cpp, there's a version of StandaloneServer that uses this.
- * */
- template<class Message, class TargetClass>
- void registerCallback( TargetClass* target, int (TargetClass::*function) (const SafeSharedPtr<Message>&) ) {
- addDeliverer( new MessageDeliverer<Message, TargetClass> ( target, function, m_messageTypes.type<Message>(), true ) );
- }
-
- /**
- * Same as above, except that the target will not be locked before the callback is called
- * */
- template<class Message, class TargetClass, class Serialization>
- void registerUnsafeCallback( TargetClass* target, typename MessageDeliverer<Message, TargetClass>::FunctionType function ) {
- addDeliverer( new MessageDeliverer<Message, TargetClass> ( target, function, m_messageTypes.type<Message>(), false ) );
- }
-
- /** Call this to dispatch the message to the registered targets
- * @return 0 if there is no fitting target, or the value returned by the target's dispatch-function
- */
- int operator() ( const MessagePointer& msg );
-
- protected:
- /** Call this to dispatch the message to the registered targets. It is the same as operator(), but looks cleaner when called from an inherited class.
- * @return 0 if there is no fitting target, or the value returned by the target's dispatch-function
- */
- int dispatch( const MessagePointer& msg );
-
- void addDeliverer( MessageDelivererBase* );
-
- private:
- typedef std::vector<MessageDelivererBase*> DelivererList;
- DelivererList m_deliverers;
- MessageTypeSet& m_messageTypes;
-};
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/dynamicmessagedispatcher.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h (nonexistent)
@@ -1,97 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MULTISESSION_H
-#define MULTISESSION_H
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "serialization.h"
-#include "messagetypeset.h"
-#include "safesharedptr.h"
-#include "basicserver.h"
-#include "basicsession.h"
-#include <string>
-#include <list>
-#include <map>
-#include <set>
-#include "sharedptr.h"
-#include "teamworkmessages.h"
-#include "teamworkservermessages.h"
-#include "user.h"
-#include "messagesendhelper.h"
-//#include "forwardsession.h"
-#include "serverconfig.h"
-
-
-namespace Teamwork {
-class ServerInformation;
-/** MultiSession extends BasicTCPSession with the ability to manage virtual sub-sessions to users reachable through a forwarding server.
- * It is created by Teamwork::Server and Teamwork::Client
-* */
-
-class NETWORK_EXPORT MultiSession : public BasicTCPSession {
- bool incoming_;
- typedef std::map<UserPointer, ForwardSessionPointer, UserPointer::ValueSmallerCompare> ForwardSessionMap;
- ForwardSessionMap forwardSessions_;
- std::list<ForwardSessionPointer> garbageSessions_;
-
- protected:
-
- void deleteForwardSessions();
-
- virtual void final();
-
- public:
- MultiSession( ost::TCPSocket &server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger );
-
- MultiSession( const ServerInformation& server, HandlerPointer handler, MessageTypeSet& messages, const LoggerPointer& logger, const string& namePrefix = "" );
-
- bool operator < ( const MultiSession& rhs ) const {
- return this < ( &rhs );
- }
-
- ///true if the session is an incoming one(connected to the local server), else returns false
- bool incoming() {
- return incoming_;
- }
-
- virtual bool think();
-
- virtual ~MultiSession();
-
- void registerForwardSession( const UserPointer& peer, const ForwardSessionPointer& sess );
-
- virtual bool handleMessage( MessagePointer msg ) throw();
-
- ForwardSessionPointer getForwardSession( const UserPointer& user ) {
- ForwardSessionMap::const_iterator it = forwardSessions_.find( user );
- if ( it != forwardSessions_.end() )
- return ( *it ).second;
- else
- return 0;
- }
-
- list<UserPointer> getUserList() {
- list<UserPointer> ret;
- for ( ForwardSessionMap::const_iterator it = forwardSessions_.begin(); it != forwardSessions_.end(); ++it ) {
- ret.push_back( ( *it ).first );
- }
- return ret;
- }
-};
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/multisession.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp (nonexistent)
@@ -1,110 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "helpers.h"
-#include "serialization.h"
-#include "messagetypeset.h"
-#include "basicsession.h"
-#include "vector_stream.h"
-
-///We can choose an archive-type of our own
-#ifdef USE_POLYMORPHIC_ARCHIVE
-// #include <boost/archive/polymorphic_xml_iarchive.hpp>
-// #include <boost/archive/polymorphic_xml_oarchive.hpp>
-// typedef boost::archive::polymorphic_xml_iarchive InternalIArchive;
-// typedef boost::archive::polymorphic_xml_oarchive InternalOArchive;
-
-#include <boost/archive/polymorphic_text_iarchive.hpp>
-#include <boost/archive/polymorphic_text_oarchive.hpp>
-typedef boost::archive::polymorphic_text_iarchive InternalIArchive;
-typedef boost::archive::polymorphic_text_oarchive InternalOArchive;
-#else
-typedef Teamwork::InArchive InternalIArchive;
-typedef Teamwork::OutArchive InternalOArchive;
-#endif
-
-std::string formatInt( int i ) {
- ostringstream o;
- o << i;
- return o.str();
-}
-
-std::vector<char> binaryInt( int num ) {
- std::vector<char> ret;
- ret.resize( 4 );
- ( *( int* ) ( &ret[ 0 ] ) ) = num;
- return ret;
-}
-
-namespace Teamwork {
- MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages ) {
- return buildMessageFromArchive( arch, messages, 0 );
- }
- MessagePointer buildMessageFromArchive( InArchive& arch, MessageTypeSet& messages, SessionPointer sess ) {
- MessageInfo inf( arch );
- inf.setSession( sess );
-
- return messages.buildMessage( arch, inf );
- }
-
- void serializeMessageToArchive( OutArchive& arch, MessageInterface& message ) {
- message.info().serialize( arch );
-
- message.serialize( arch ); ///it must be called like this, because the serialization would add type-information we don't want
- }
-
- MessagePointer buildMessageFromBuffer( const std::vector<char>& buf, MessageTypeSet& messages, SessionPointer sess ) {
- vector_read_stream str( buf );
- InternalIArchive arch( str );
-
- return buildMessageFromArchive( arch, messages, sess );
- }
-
- void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message ) {
- vector_stream str( buf );
- InternalOArchive arch( str );
-
- serializeMessageToArchive( arch, message );
- }
-
- /*
- MessagePointer buildMessageFromBuffer( std::vector<char> buf, MessageTypeSet& messages, SessionPointer sess )
- {
- buf.push_back( 0 );
- BinaryStreamBuf b( buf );
- std::ifstream str;
-
- str.rdbuf( &b );
-
- InArchive arch( str );
-
- MessageInfo inf( arch );
- inf.setSession( sess );
-
- return messages.buildMessage( arch, inf );
- }
-
- void serializeMessageToBuffer( std::vector<char>& buf, MessageInterface& message ) {
- BinaryStreamBuf b (buf );
- std::ofstream str;
- str.rdbuf( &b );
- OutArchive arch( str );
-
- message.info().serialize( arch );
-
- message.serialize( arch ); ///it must be called like this, because the serialization would add type-information we don't want
- }
- */
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/network/helpers.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp (nonexistent)
@@ -1,268 +0,0 @@
-/***************************************************************************
- kompareprocess.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "kompareprocess.h"
-#include <qdir.h>
-#include <qstringlist.h>
-#include <qtextcodec.h>
-//Added by qt3to4:
-#include <Q3ValueList>
-#include <Q3CString>
-
-#include <kcharsets.h>
-#include <kdebug.h>
-#include <kglobal.h>
-
-#include "diffsettings.h"
-
-
-KompareProcess::KompareProcess( DiffSettings* diffSettings, enum Kompare::DiffMode mode, const QString& source, const QString& destination, const QString& dir )
- : m_diffSettings( diffSettings ),
- m_mode( mode ),
- m_textDecoder( 0 ),
- m_proc(new QProcess)
-{
-
- // connect the stdout and stderr signals
- connect( m_proc, SIGNAL( readyReadStandardOutput() ),
- SLOT ( slotReceivedStdout( ) ) );
- connect( this, SIGNAL( readyReadStandardError() ),
- SLOT ( slotReceivedStderr( ) ) );
-
- // connect the signal that indicates that the proces has exited
- connect( this, SIGNAL( finished( int, QProcess::ExitStatus ) ),
- SLOT ( slotProcessExited( int, QProcess::ExitStatus ) ) );
-
- m_env << "LANG=C";
-
- // Write command and options
- if( m_mode == Kompare::Default )
- {
- writeDefaultCommandLine();
- }
- else
- {
- writeCommandLine();
- }
-
- if( !dir.isEmpty() ) {
- m_proc->setWorkingDirectory( dir );
- }
-
- // Write file names
- m_args << "--";
- m_args << constructRelativePath( dir, source );
- m_args << constructRelativePath( dir, destination );
-}
-
-void KompareProcess::writeDefaultCommandLine()
-{
- if ( !m_diffSettings || m_diffSettings->m_diffProgram.isEmpty() )
- {
- m_prog = "diff";
- m_args << "-dr";
- }
- else
- {
- m_prog = m_diffSettings->m_diffProgram;
- m_args << "-dr";
- }
-
- m_args << "-U" << QString::number( m_diffSettings->m_linesOfContext );
-}
-
-void KompareProcess::writeCommandLine()
-{
- // load the executable into the K3Process
- if ( m_diffSettings->m_diffProgram.isEmpty() )
- {
- kDebug(8101) << "Using the first diff in the path...";
- m_prog = "diff";
- }
- else
- {
- kDebug(8101) << "Using a user specified diff, namely:" << m_diffSettings->m_diffProgram;
- m_prog = m_diffSettings->m_diffProgram;
- }
-
- switch( m_diffSettings->m_format ) {
- case Kompare::Unified :
- m_args << "-U" << QString::number( m_diffSettings->m_linesOfContext );
- break;
- case Kompare::Context :
- m_args << "-C" << QString::number( m_diffSettings->m_linesOfContext );
- break;
- case Kompare::RCS :
- m_args << "-n";
- break;
- case Kompare::Ed :
- m_args << "-e";
- break;
- case Kompare::SideBySide:
- m_args << "-y";
- break;
- case Kompare::Normal :
- case Kompare::UnknownFormat :
- default:
- break;
- }
-
- if ( m_diffSettings->m_largeFiles
-// default diff does not have -H on OpenBSD
-// so don't pass this option unless the user overrode the default program
-#if defined(__OpenBSD__) //krazy:exclude=cpp
- && !m_diffSettings->m_diffProgram.isEmpty()
-#endif
- )
- {
- m_args << "-H";
- }
-
- if ( m_diffSettings->m_ignoreWhiteSpace )
- {
- m_args << "-b";
- }
-
- if ( m_diffSettings->m_ignoreAllWhiteSpace )
- {
- m_args << "-w";
- }
-
- if ( m_diffSettings->m_ignoreEmptyLines )
- {
- m_args << "-B";
- }
-
- if ( m_diffSettings->m_ignoreChangesDueToTabExpansion )
- {
- m_args << "-E";
- }
-
- if ( m_diffSettings->m_createSmallerDiff )
- {
- m_args << "-d";
- }
-
- if ( m_diffSettings->m_ignoreChangesInCase )
- {
- m_args << "-i";
- }
-
- if ( m_diffSettings->m_ignoreRegExp && !m_diffSettings->m_ignoreRegExpText.isEmpty() )
- {
- m_args << "-I" << m_diffSettings->m_ignoreRegExpText;
- }
-
- if ( m_diffSettings->m_showCFunctionChange )
- {
- m_args << "-p";
- }
-
- if ( m_diffSettings->m_convertTabsToSpaces )
- {
- m_args << "-t";
- }
-
- if ( m_diffSettings->m_recursive )
- {
- m_args << "-r";
- }
-
- if ( m_diffSettings->m_newFiles )
- {
- m_args << "-N";
- }
-
-// This option is more trouble than it is worth... please do not ever enable it unless you want really weird crashes
-// if ( m_diffSettings->m_allText )
-// {
-// *this << "-a";
-// }
-
- if ( m_diffSettings->m_excludeFilePattern )
- {
- QStringList::ConstIterator it = m_diffSettings->m_excludeFilePatternList.begin();
- QStringList::ConstIterator end = m_diffSettings->m_excludeFilePatternList.end();
- for ( ; it != end; ++it )
- {
- m_args << "-x" << *it ;
- }
- }
-
- if ( m_diffSettings->m_excludeFilesFile && !m_diffSettings->m_excludeFilesFileURL.isEmpty() )
- {
- m_args << "-X" << m_diffSettings->m_excludeFilesFileURL;
- }
-}
-
-KompareProcess::~KompareProcess()
-{
- delete m_proc;
-}
-
-void KompareProcess::setEncoding( const QString& encoding )
-{
- QTextCodec* textCodec = KGlobal::charsets()->codecForName( encoding.toLatin1() );
- if ( textCodec )
- m_textDecoder = textCodec->makeDecoder();
- else
- {
- kDebug(8101) << "Using locale codec as backup...";
- textCodec = QTextCodec::codecForLocale();
- m_textDecoder = textCodec->makeDecoder();
- }
-}
-
-void KompareProcess::slotReceivedStdout( )
-{
- m_stdout += m_proc->readAllStandardOutput();
-}
-
-void KompareProcess::slotReceivedStderr( )
-{
- m_stderr += m_proc->readAllStandardError();
-}
-
-void KompareProcess::start()
-{
-#ifndef NDEBUG
- QString cmdLine;
- QStringList::ConstIterator it = m_args.begin();
- for (; it != m_args.end(); ++it )
- cmdLine += "\"" + (*it) + "\" ";
- kDebug(8101) << cmdLine;
-#endif
- m_proc->setEnvironment(m_env);
- m_proc->start(m_prog, m_args);
-}
-
-QProcess* KompareProcess::process()
-{
- return m_proc;
-}
-
-void KompareProcess::slotProcessExited( int code, QProcess::ExitStatus status )
-{
- // exit status of 0: no differences
- // 1: some differences
- // 2: error but there may be differences !
- kDebug(8101) << "Exited with exit status :" << status;
- emit diffHasFinished( code == 0 && status != QProcess::CrashExit );
-}
-
-#include "kompareprocess.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt (nonexistent)
@@ -1,27 +0,0 @@
-#@todo: this file needs to be worked over
-
-########### next target ###############
-
-set(diff2_PART_SRCS
- kompareprocess.cpp
- komparemodellist.cpp
- diffmodellist.cpp
- diffmodel.cpp
- difference.cpp
- diffhunk.cpp
- levenshteintable.cpp
- parser.cpp
- parserbase.cpp
- cvsdiffparser.cpp
- diffparser.cpp
- perforceparser.cpp
- diffsettings.cpp
- settingsbase.cpp )
-
-
-# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
-kde4_add_library(kdevteamwork_diff2 SHARED ${diff2_PART_SRCS})
-
-target_link_libraries(kdevteamwork_diff2 ${KDE4_KDEUI_LIBS} ${KDE4_KDE3SUPPORT_LIBS} )
-
-install(TARGETS kdevteamwork_diff2 ${INSTALL_TARGETS_DEFAULT_ARGS})
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp (nonexistent)
@@ -1,138 +0,0 @@
-/**************************************************************************
-** parser.cpp
-** -------------------
-** begin : Sun Aug 4 15:05:35 2002
-** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "parser.h"
-#include <kdebug.h>
-
-#include "cvsdiffparser.h"
-#include "diffparser.h"
-#include "perforceparser.h"
-#include "diffmodel.h"
-
-using namespace Diff2;
-
-Parser::Parser( const KompareModelList* list ) :
- m_list( list )
-{
-}
-
-Parser::~Parser()
-{
-}
-
-int Parser::cleanUpCrap( QStringList& diffLines )
-{
- QStringList::Iterator it = diffLines.begin();
-
- int nol = 0;
-
- QString noNewLine( "\\ No newline" );
-
- for ( ; it != diffLines.end(); ++it )
- {
- if ( (*it).startsWith( noNewLine ) )
- {
- it = diffLines.erase( it );
- // correcting the advance of the iterator because of the remove
- --it;
- QString temp( *it );
- temp.truncate( temp.indexOf( '\n' ) );
- *it = temp;
- ++nol;
- }
- }
-
- return nol;
-}
-
-DiffModelList* Parser::parse( QStringList& diffLines )
-{
- /* Basically determine the generator then call the parse method */
- ParserBase* parser;
-
- m_generator = determineGenerator( diffLines );
-
- int nol = cleanUpCrap( diffLines );
- kDebug(8101) << "Cleaned up" << nol << "line(s) of crap from the diff...";
-
- switch( m_generator )
- {
- case Kompare::CVSDiff :
- kDebug(8101) << "It is a CVS generated diff...";
- parser = new CVSDiffParser( m_list, diffLines );
- break;
- case Kompare::Diff :
- kDebug(8101) << "It is a diff generated diff...";
- parser = new DiffParser( m_list, diffLines );
- break;
- case Kompare::Perforce :
- kDebug(8101) << "It is a Perforce generated diff...";
- parser = new PerforceParser( m_list, diffLines );
- break;
- default:
- // Nothing to delete, just leave...
- return 0L;
- }
-
- m_format = parser->format();
- DiffModelList* modelList = parser->parse();
- if ( modelList )
- {
- kDebug(8101) << "Modelcount:" << modelList->count();
- DiffModelListIterator modelIt = modelList->begin();
- DiffModelListIterator mEnd = modelList->end();
- for ( ; modelIt != mEnd; ++modelIt )
- {
- kDebug(8101) << "Hunkcount:" << (*modelIt)->hunkCount();
- kDebug(8101) << "Diffcount:" << (*modelIt)->differenceCount();
- }
- }
-
- delete parser;
-
- return modelList;
-}
-
-enum Kompare::Generator Parser::determineGenerator( const QStringList& diffLines )
-{
- // Shit have to duplicate some code with this method and the ParserBase derived classes
- QString cvsDiff ( "Index: " );
- QString perforceDiff( "==== " );
-
- QStringList::ConstIterator it = diffLines.begin();
- QStringList::ConstIterator linesEnd = diffLines.end();
-
- while ( it != linesEnd )
- {
- if ( ( *it ).startsWith( cvsDiff ) )
- {
- kDebug(8101) << "Diff is a CVSDiff";
- return Kompare::CVSDiff;
- }
- else if ( ( *it ).startsWith( perforceDiff ) )
- {
- kDebug(8101) << "Diff is a Perforce Diff";
- return Kompare::Perforce;
- }
- ++it;
- }
-
- kDebug(8101) << "We'll assume it is a diff Diff";
-
- // For now we'll assume it is a diff file diff, later we might
- // try to really determine if it is a diff file diff.
- return Kompare::Diff;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp (nonexistent)
@@ -1,159 +0,0 @@
-/**************************************************************************
-** cvsdiffparser.cpp
-** -----------------
-** begin : Sun Aug 4 15:05:35 2002
-** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-#include "cvsdiffparser.h"
-#include <qregexp.h>
-
-#include <kdebug.h>
-
-
-#include "komparemodellist.h"
-
-
-using namespace Diff2;
-
-CVSDiffParser::CVSDiffParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
-{
- // The regexps needed for context cvs diff parsing, the rest is the same as in parserbase.cpp
- // third capture in header1 is non optional for cvs diff, it is the revision
- m_contextDiffHeader1.setPattern( "\\*\\*\\* ([^\\t]+)\\t([^\\t]+)\\t(.*)\\n" );
- m_contextDiffHeader2.setPattern( "--- ([^\\t]+)\\t([^\\t]+)(|\\t(.*))\\n" );
-
- m_normalDiffHeader.setPattern( "Index: (.*)\\n" );
-}
-
-CVSDiffParser::~CVSDiffParser()
-{
-}
-
-enum Kompare::Format CVSDiffParser::determineFormat()
-{
-// kDebug(8101) << "Determining the format of the CVSDiff";
-
- QRegExp normalRE ( "[0-9]+[0-9,]*[acd][0-9]+[0-9,]*" );
- QRegExp unifiedRE( "^--- [^\\t]+\\t" );
- QRegExp contextRE( "^\\*\\*\\* [^\\t]+\\t" );
- QRegExp rcsRE ( "^[acd][0-9]+ [0-9]+" );
- QRegExp edRE ( "^[0-9]+[0-9,]*[acd]" );
-
- QStringList::ConstIterator it = m_diffLines.begin();
-
- while( it != m_diffLines.end() )
- {
- if( (*it).indexOf( normalRE, 0 ) == 0 )
- {
-// kDebug(8101) << "Difflines are from a Normal diff...";
- return Kompare::Normal;
- }
- else if( (*it).indexOf( unifiedRE, 0 ) == 0 )
- {
-// kDebug(8101) << "Difflines are from a Unified diff...";
- return Kompare::Unified;
- }
- else if( (*it).indexOf( contextRE, 0 ) == 0 )
- {
-// kDebug(8101) << "Difflines are from a Context diff...";
- return Kompare::Context;
- }
- else if( (*it).indexOf( rcsRE, 0 ) == 0 )
- {
-// kDebug(8101) << "Difflines are from a RCS diff...";
- return Kompare::RCS;
- }
- else if( (*it).indexOf( edRE, 0 ) == 0 )
- {
-// kDebug(8101) << "Difflines are from an ED diff...";
- return Kompare::Ed;
- }
- ++it;
- }
-// kDebug(8101) << "Difflines are from an unknown diff...";
- return Kompare::UnknownFormat;
-}
-
-bool CVSDiffParser::parseNormalDiffHeader()
-{
- kDebug(8101) << "CVSDiffParser::parseNormalDiffHeader()";
- bool result = false;
-
- QStringList::ConstIterator diffEnd = m_diffLines.end();
-
- while ( m_diffIterator != diffEnd )
- {
- if ( m_normalDiffHeader.exactMatch( *m_diffIterator ) )
- {
- kDebug(8101) << "Matched length Header =" << m_normalDiffHeader.matchedLength();
- kDebug(8101) << "Matched string Header =" << m_normalDiffHeader.cap( 0 );
-
- m_currentModel = new DiffModel();
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_currentModel->setSourceFile ( m_normalDiffHeader.cap( 1 ) );
- m_currentModel->setDestinationFile ( m_normalDiffHeader.cap( 1 ) );
-
- result = true;
-
- ++m_diffIterator;
- break;
- }
- else
- {
- kDebug(8101) << "No match for:" << ( *m_diffIterator );
- }
- ++m_diffIterator;
- }
-
- if ( result == false )
- {
- // Set this to the first line again and hope it is a single file diff
- m_diffIterator = m_diffLines.begin();
- m_currentModel = new DiffModel();
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_singleFileDiff = true;
- }
-
- return result;
-}
-
-
-bool CVSDiffParser::parseEdDiffHeader()
-{
- return false;
-}
-
-bool CVSDiffParser::parseRCSDiffHeader()
-{
- return false;
-}
-
-bool CVSDiffParser::parseEdHunkHeader()
-{
- return false;
-}
-
-bool CVSDiffParser::parseRCSHunkHeader()
-{
- return false;
-}
-
-bool CVSDiffParser::parseEdHunkBody()
-{
- return false;
-}
-
-bool CVSDiffParser::parseRCSHunkBody()
-{
- return false;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp (nonexistent)
@@ -1,107 +0,0 @@
-/***************************************************************************
- diffsettings.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-****************************************************************************/
-
-#include "diffsettings.h"
-#include <kconfig.h>
-
-
-DiffSettings::DiffSettings( QWidget* parent )
- : SettingsBase( parent ),
- m_linesOfContext( 0 ),
- m_format( Kompare::Unified ),
- m_largeFiles( false ),
- m_ignoreWhiteSpace( false ),
- m_ignoreAllWhiteSpace( false ),
- m_ignoreEmptyLines( false ),
- m_ignoreChangesDueToTabExpansion( false ),
- m_createSmallerDiff( false ),
- m_ignoreChangesInCase( false ),
- m_showCFunctionChange( false ),
- m_convertTabsToSpaces( false ),
- m_ignoreRegExp( false ),
- m_recursive( false ),
- m_newFiles( false ),
- m_excludeFilePattern( false ),
- m_excludeFilesFile( false )
-{
-}
-
-DiffSettings::~DiffSettings()
-{
-}
-
-void DiffSettings::loadSettings( KConfig* config )
-{/*
- KConfigGroup group( config, "Diff Options" );
- m_diffProgram = group.readEntry ( "DiffProgram", "" );
- m_linesOfContext = group.readEntry( "LinesOfContext", QVariant(3) ).asInt();
- m_largeFiles = group.readBoolEntry( "LargeFiles", true );
- m_ignoreWhiteSpace = group.readBoolEntry( "IgnoreWhiteSpace", false );
- m_ignoreAllWhiteSpace = group.readBoolEntry( "IgnoreAllWhiteSpace", false );
- m_ignoreEmptyLines = group.readBoolEntry( "IgnoreEmptyLines", false );
- m_ignoreChangesDueToTabExpansion = group.readBoolEntry( "IgnoreChangesDueToTabExpansion", false );
- m_ignoreChangesInCase = group.readBoolEntry( "IgnoreChangesInCase", false );
- m_ignoreRegExp = group.readBoolEntry( "IgnoreRegExp", false );
- m_ignoreRegExpText = group.readEntry ( "IgnoreRegExpText", "" );
- m_ignoreRegExpTextHistory = group.readListEntry( "IgnoreRegExpTextHistory" );
- m_createSmallerDiff = group.readBoolEntry( "CreateSmallerDiff", true );
- m_convertTabsToSpaces = group.readBoolEntry( "ConvertTabsToSpaces", false );
- m_showCFunctionChange = group.readBoolEntry( "ShowCFunctionChange", false );
- m_recursive = group.readBoolEntry( "CompareRecursively", true );
- m_newFiles = group.readBoolEntry( "NewFiles", true );
-
- m_format = static_cast<Kompare::Format>( group.readNumEntry( "Format", Kompare::Unified ) );
-
- KConfigGroup group2 ( config, "Exclude File Options" );
- m_excludeFilePattern = group2.readBoolEntry( "Pattern", false );
- m_excludeFilePatternList = group2.readListEntry( "PatternList" );
- m_excludeFilesFile = group2.readBoolEntry( "File", false );
- m_excludeFilesFileURL = group2.readEntry ( "FileURL", "" );
- m_excludeFilesFileHistoryList = group2.readListEntry( "FileHistoryList" );*/
-}
-
-void DiffSettings::saveSettings( KConfig* config )
-{/*
- KConfigGroup group( config, "Diff Options" );
- group.writeEntry( "DiffProgram", m_diffProgram );
- group.writeEntry( "LinesOfContext", m_linesOfContext );
- group.writeEntry( "Format", QString(m_format) );
- group.writeEntry( "LargeFiles", m_largeFiles );
- group.writeEntry( "IgnoreWhiteSpace", m_ignoreWhiteSpace );
- group.writeEntry( "IgnoreAllWhiteSpace", m_ignoreAllWhiteSpace );
- group.writeEntry( "IgnoreEmptyLines", m_ignoreEmptyLines );
- group.writeEntry( "IgnoreChangesInCase", m_ignoreChangesInCase );
- group.writeEntry( "IgnoreChangesDueToTabExpansion", m_ignoreChangesDueToTabExpansion );
- group.writeEntry( "IgnoreRegExp", m_ignoreRegExp );
- group.writeEntry( "IgnoreRegExpText", m_ignoreRegExpText );
- group.writeEntry( "IgnoreRegExpTextHistory", m_ignoreRegExpTextHistory );
- group.writeEntry( "CreateSmallerDiff", m_createSmallerDiff );
- group.writeEntry( "ConvertTabsToSpaces", m_convertTabsToSpaces );
- group.writeEntry( "ShowCFunctionChange", m_showCFunctionChange );
- group.writeEntry( "CompareRecursively", m_recursive );
- group.writeEntry( "NewFiles", m_newFiles );
- group.setDirty( true );
-
- KConfigGroup group2( config, "Exclude File Options" );
- group2.writeEntry( "Pattern", m_excludeFilePattern );
- group2.writeEntry( "PatternList", m_excludeFilePatternList );
- group2.writeEntry( "File", m_excludeFilesFile );
- group2.writeEntry( "FileURL", m_excludeFilesFileURL );
- group2.writeEntry( "FileHistoryList", m_excludeFilesFileHistoryList );
- group2.setDirty( true );*/
-}
-
-#include "diffsettings.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp (nonexistent)
@@ -1,141 +0,0 @@
-/***************************************************************************
- difference.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "difference.h"
-#include "levenshteintable.h"
-
-using namespace Diff2;
-
-Difference::Difference( int sourceLineNo, int destinationLineNo, int type ) :
- m_type( type ),
- m_sourceLineNo( sourceLineNo ),
- m_destinationLineNo( destinationLineNo ),
- m_applied( false ),
- m_table( new LevenshteinTable() )
-{
-}
-
-Difference::~Difference()
-{
- delete m_table;
-}
-
-void Difference::addSourceLine( const QString& line )
-{
- m_sourceLines.append( new DifferenceString( line ) );
-}
-
-void Difference::addDestinationLine( const QString& line )
-{
- m_destinationLines.append( new DifferenceString( line ) );
-}
-
-int Difference::sourceLineCount() const
-{
- return m_sourceLines.count();
-}
-
-int Difference::destinationLineCount() const
-{
- return m_destinationLines.count();
-}
-
-void Difference::apply( bool apply )
-{
- m_applied = apply;
-}
-
-void Difference::determineInlineDifferences()
-{
- if ( m_type != Difference::Change )
- return;
-
- // Do nothing for now when the slc != dlc
- // One could try to find the closest matching destination string for any
- // of the source strings but this is compute intensive
- if ( sourceLineCount() != destinationLineCount() )
- return;
-
- int slc = sourceLineCount();
-
- for ( int i = 0; i < slc; ++i )
- {
- DifferenceString* sl = sourceLineAt( i );
- DifferenceString* dl = destinationLineAt( i );
-
- // FIXME: If the table cant be created do not do the rest
- m_table->createTable( sl, dl );
-
- m_table->createListsOfMarkers();
- }
-
- // No longer needed, if we ever need to recalculate the inline differences we should
- // simply recreate the table
- delete m_table;
- m_table = 0;
-}
-
-QString Difference::recreateDifference() const
-{
- QString difference;
-
- // source
- DifferenceStringListConstIterator stringIt = m_sourceLines.begin();
- DifferenceStringListConstIterator sEnd = m_sourceLines.end();
-
- for ( ; stringIt != sEnd; ++stringIt )
- {
- switch ( m_type )
- {
- case Change:
- case Delete:
- difference += '-';
- break;
- default:
- // Insert but this is not possible in source
- // Unchanged will be handled in destination
- // since they are the same
-// kDebug( 8101 ) << "Go away, nothing to do for you in source...";
- continue;
- }
- difference += (*stringIt)->string();
- }
-
- //destination
- stringIt = m_destinationLines.begin();
- sEnd = m_destinationLines.end();
-
- for ( ; stringIt != sEnd; ++stringIt )
- {
- switch ( m_type )
- {
- case Change:
- case Insert:
- difference += '+';
- break;
- case Unchanged:
- difference += ' ';
- break;
- default: // Delete but this is not possible in destination
-// kDebug( 8101 ) << "Go away, nothing to do for you in destination...";
- continue;
- }
- difference += (*stringIt)->string();
- }
-
- return difference;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h (nonexistent)
@@ -1,132 +0,0 @@
-/**************************************************************************
-** parserbase.h
-** -------------------
-** begin : Tue Jul 30 23:53:52 2002
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef _DIFF2_PARSERBASE_H
-#define _DIFF2_PARSERBASE_H
-
-#include <qregexp.h>
-
-#include "kompare.h"
-#include "difference.h"
-#include "diffmodellist.h"
-
-class QStringList;
-class QString;
-
-namespace Diff2
-{
-
-class KompareModelList;
-
-class ParserBase
-{
-public:
- ParserBase( const KompareModelList* list, const QStringList& diff );
- virtual ~ParserBase();
-
-public:
- enum Kompare::Format format() { return determineFormat(); };
- DiffModelList* parse();
-
-protected:
- virtual bool parseContextDiffHeader();
- virtual bool parseEdDiffHeader();
- virtual bool parseNormalDiffHeader();
- virtual bool parseRCSDiffHeader();
- virtual bool parseUnifiedDiffHeader();
-
- virtual bool parseContextHunkHeader();
- virtual bool parseEdHunkHeader();
- virtual bool parseNormalHunkHeader();
- virtual bool parseRCSHunkHeader();
- virtual bool parseUnifiedHunkHeader();
-
- virtual bool parseContextHunkBody();
- virtual bool parseEdHunkBody();
- virtual bool parseNormalHunkBody();
- virtual bool parseRCSHunkBody();
- virtual bool parseUnifiedHunkBody();
-
- virtual DiffModelList* parseContext();
- virtual DiffModelList* parseEd();
- virtual DiffModelList* parseNormal();
- virtual DiffModelList* parseRCS();
- virtual DiffModelList* parseUnified();
-
-protected: // Helper methods to speed things up
- bool matchesUnifiedHunkLine( QString line ) const;
-
-protected:
- /** What is format of the diff */
- virtual enum Kompare::Format determineFormat();
-
-protected:
- // Regexps for context parsing
- QRegExp m_contextDiffHeader1;
- QRegExp m_contextDiffHeader2;
-
- QRegExp m_contextHunkHeader1;
- QRegExp m_contextHunkHeader2;
- QRegExp m_contextHunkHeader3;
-
- QRegExp m_contextHunkBodyRemoved;
- QRegExp m_contextHunkBodyAdded;
- QRegExp m_contextHunkBodyChanged;
- QRegExp m_contextHunkBodyContext;
- QRegExp m_contextHunkBodyLine; // Added for convenience
-
- // Regexps for normal parsing
- QRegExp m_normalDiffHeader;
-
- QRegExp m_normalHunkHeaderAdded;
- QRegExp m_normalHunkHeaderRemoved;
- QRegExp m_normalHunkHeaderChanged;
-
- QRegExp m_normalHunkBodyRemoved;
- QRegExp m_normalHunkBodyAdded;
- QRegExp m_normalHunkBodyDivider;
-
- enum Difference::Type m_normalDiffType;
-
- // RegExps for rcs parsing
- QRegExp m_rcsDiffHeader;
-
- // Regexps for unified parsing
- QRegExp m_unifiedDiffHeader1;
- QRegExp m_unifiedDiffHeader2;
-
- QRegExp m_unifiedHunkHeader;
-
- QRegExp m_unifiedHunkBodyAdded;
- QRegExp m_unifiedHunkBodyRemoved;
- QRegExp m_unifiedHunkBodyContext;
- QRegExp m_unifiedHunkBodyLine; // Added for convenience
-
-protected:
- const QStringList& m_diffLines;
- DiffModel* m_currentModel;
- DiffModelList* m_models;
- QStringList::ConstIterator m_diffIterator;
-
- bool m_singleFileDiff;
-
-protected:
- const KompareModelList* m_list;
-};
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp (nonexistent)
@@ -1,40 +0,0 @@
-/***************************************************************************
- settingsbase.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "settingsbase.h"
-#include <qwidget.h>
-
-
-SettingsBase::SettingsBase( QWidget* parent ) : QObject( parent )
-{
-
-}
-
-SettingsBase::~SettingsBase()
-{
-
-}
-
-void SettingsBase::loadSettings( KConfig* /* config */ )
-{
-}
-
-void SettingsBase::saveSettings( KConfig* /* config */ )
-{
-}
-
-#include "settingsbase.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp (nonexistent)
@@ -1,28 +0,0 @@
-/*******************************************************************************
-**
-** Filename : diffmodellist.cpp
-** Created on : 26 march, 2004
-** Copyright : (c) 2004 Otto Bruggeman <bruggie@home.nl>
-**
-*******************************************************************************/
-
-/*******************************************************************************
-**
-** 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.
-**
-*******************************************************************************/
-
-#include "diffmodellist.h"
-#include <kdebug.h>
-#include <q3tl.h>
-
-using namespace Diff2;
-
-void DiffModelList::sort()
-{
- qHeapSort(*this);
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h (nonexistent)
@@ -1,69 +0,0 @@
-/***************************************************************************
- diffhunk.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef DIFFHUNK_H
-#define DIFFHUNK_H
-
-#include "difference.h"
-//Added by qt3to4:
-#include <Q3ValueList>
-
-namespace Diff2
-{
-
-class Difference;
-
-class DiffHunk
-{
-public:
- enum Type { Normal, AddedByBlend };
-
-public:
- DiffHunk( int sourceLine, int destinationLine, const QString& function = QString(), Type type = Normal );
- ~DiffHunk();
-
- const DifferenceList& differences() const { return m_differences; };
- const QString& function() const { return m_function; };
-
- int sourceLineNumber() const { return m_sourceLine; };
- int destinationLineNumber() const { return m_destinationLine; };
-
- int sourceLineCount() const;
- int destinationLineCount() const;
-
- const Type type() const { return m_type; }
- void setType( Type type ) { m_type = type; }
-
- void add( Difference* diff );
-
- QString recreateHunk() const;
-
-private:
- int m_sourceLine;
- int m_destinationLine;
- DifferenceList m_differences;
- QString m_function;
- Type m_type;
-};
-
-typedef Q3ValueList<DiffHunk*> DiffHunkList;
-typedef Q3ValueList<DiffHunk*>::iterator DiffHunkListIterator;
-typedef Q3ValueList<DiffHunk*>::const_iterator DiffHunkListConstIterator;
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp (nonexistent)
@@ -1,222 +0,0 @@
-/**************************************************************************
-** perforceparser.cpp
-** ------------------
-** begin : Sun Aug 4 15:05:35 2002
-** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "perforceparser.h"
-#include <qregexp.h>
-
-#include <kdebug.h>
-
-
-using namespace Diff2;
-
-PerforceParser::PerforceParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
-{
- m_contextDiffHeader1.setPattern( "==== (.*) - (.*) ====\\n" );
- m_contextDiffHeader1.setMinimal( true );
- m_normalDiffHeader.setPattern ( "==== (.*) - (.*) ====\\n" );
- m_normalDiffHeader.setMinimal ( true );
- m_rcsDiffHeader.setPattern ( "==== (.*) - (.*) ====\\n" );
- m_rcsDiffHeader.setMinimal ( true );
- m_unifiedDiffHeader1.setPattern( "==== (.*) - (.*) ====\\n" );
- m_unifiedDiffHeader1.setMinimal( true );
-}
-
-PerforceParser::~PerforceParser()
-{
-}
-
-enum Kompare::Format PerforceParser::determineFormat()
-{
- kDebug(8101) << "Determining the format of the Perforce Diff";
-
- QRegExp unifiedRE( "^@@" );
- QRegExp contextRE( "^\\*{15}" );
- QRegExp normalRE ( "^\\d+(|,\\d+)[acd]\\d+(|,\\d+)" );
- QRegExp rcsRE ( "^[acd]\\d+ \\d+" );
- // Summary is not supported since it gives no useful parsable info
-
- QStringList::ConstIterator it = m_diffLines.begin();
-
- while( it != m_diffLines.end() )
- {
- if( (*it).indexOf( unifiedRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Unified diff...";
- return Kompare::Unified;
- }
- else if( (*it).indexOf( contextRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Context diff...";
- return Kompare::Context;
- }
- else if( (*it).indexOf( normalRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Normal diff...";
- return Kompare::Normal;
- }
- else if( (*it).indexOf( rcsRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a RCS diff...";
- return Kompare::RCS;
- }
- ++it;
- }
- kDebug(8101) << "Difflines are from an unknown diff...";
- return Kompare::UnknownFormat;
-}
-
-bool PerforceParser::parseContextDiffHeader()
-{
-// kDebug(8101) << "ParserBase::parseContextDiffHeader()";
- bool result = false;
-
- QStringList::ConstIterator itEnd = m_diffLines.end();
-
- QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
- QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
-
- while ( m_diffIterator != itEnd )
- {
- if ( m_contextDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
- {
-// kDebug(8101) << "Matched length Header1 =" << m_contextDiffHeader1.matchedLength();
-// kDebug(8101) << "Matched string Header1 =" << m_contextDiffHeader1.cap( 0 );
-// kDebug(8101) << "First capture Header1 =" << m_contextDiffHeader1.cap( 1 );
-// kDebug(8101) << "Second capture Header1 =" << m_contextDiffHeader1.cap( 2 );
-
- m_currentModel = new DiffModel();
- sourceFileRE.exactMatch( m_contextDiffHeader1.cap( 1 ) );
- destinationFileRE.exactMatch( m_contextDiffHeader1.cap( 2 ) );
- kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
- kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
- kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
- kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
- kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
- kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
- m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
- m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
-
- result = true;
-
- break;
- }
- else
- {
- kDebug(8101) << "Matched length =" << m_contextDiffHeader1.matchedLength();
- kDebug(8101) << "Captured texts =" << m_contextDiffHeader1.capturedTexts();
- }
- }
-
- return result;
-}
-
-bool PerforceParser::parseNormalDiffHeader()
-{
- bool result = false;
-
- QStringList::ConstIterator itEnd = m_diffLines.end();
-
- QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
- QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
-
- while ( m_diffIterator != itEnd )
- {
- kDebug(8101) << "Line =" << *m_diffIterator;
- kDebug(8101) << "String length =" << (*m_diffIterator).length();
- if ( m_normalDiffHeader.exactMatch( *(m_diffIterator)++ ) )
- {
- kDebug(8101) << "Matched length Header1 =" << m_normalDiffHeader.matchedLength();
- kDebug(8101) << "Matched string Header1 =" << m_normalDiffHeader.cap( 0 );
- kDebug(8101) << "First capture Header1 = \"" << m_normalDiffHeader.cap( 1 ) << "\"";
- kDebug(8101) << "Second capture Header1 = \"" << m_normalDiffHeader.cap( 2 ) << "\"";
-
- m_currentModel = new DiffModel();
- sourceFileRE.exactMatch( m_normalDiffHeader.cap( 1 ) );
- destinationFileRE.exactMatch( m_normalDiffHeader.cap( 2 ) );
- kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
- kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
- kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
- kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
- kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
- kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
- m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
- m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
-
- result = true;
-
- break;
- }
- else
- {
- kDebug(8101) << "Matched length =" << m_normalDiffHeader.matchedLength();
- kDebug(8101) << "Captured texts =" << m_normalDiffHeader.capturedTexts();
- }
- }
-
- return result;
-}
-
-bool PerforceParser::parseRCSDiffHeader()
-{
- return false;
-}
-
-bool PerforceParser::parseUnifiedDiffHeader()
-{
- bool result = false;
-
- QStringList::ConstIterator itEnd = m_diffLines.end();
-
- QRegExp sourceFileRE ( "([^\\#]+)#(\\d+)" );
- QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );
-
- while ( m_diffIterator != itEnd )
- {
-// kDebug(8101) << "Line =" << *m_diffIterator;
-// kDebug(8101) << "String length =" << (*m_diffIterator).length();
- if ( m_unifiedDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
- {
-// kDebug(8101) << "Matched length Header1 =" << m_unifiedDiffHeader1.matchedLength();
-// kDebug(8101) << "Matched string Header1 =" << m_unifiedDiffHeader1.cap( 0 );
-// kDebug(8101) << "First capture Header1 = \"" << m_unifiedDiffHeader1.cap( 1 ) << "\"";
-// kDebug(8101) << "Second capture Header1 = \"" << m_unifiedDiffHeader1.cap( 2 ) << "\"";
-
- m_currentModel = new DiffModel();
- sourceFileRE.exactMatch( m_unifiedDiffHeader1.cap( 1 ) );
- destinationFileRE.exactMatch( m_unifiedDiffHeader1.cap( 2 ) );
-// kDebug(8101) << "Matched length =" << sourceFileRE.matchedLength();
-// kDebug(8101) << "Matched length =" << destinationFileRE.matchedLength();
-// kDebug(8101) << "Captured texts =" << sourceFileRE.capturedTexts();
-// kDebug(8101) << "Captured texts =" << destinationFileRE.capturedTexts();
-// kDebug(8101) << "Source File :" << sourceFileRE.cap( 1 );
-// kDebug(8101) << "Destination File :" << destinationFileRE.cap( 1 );
- m_currentModel->setSourceFile ( sourceFileRE.cap( 1 ) );
- m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );
-
- result = true;
-
- break;
- }
- else
- {
-// kDebug(8101) << "Matched length =" << m_unifiedDiffHeader1.matchedLength();
-// kDebug(8101) << "Captured texts =" << m_unifiedDiffHeader1.capturedTexts();
- }
- }
-
- return result;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h (nonexistent)
@@ -1,213 +0,0 @@
-/***************************************************************************
- komparemodellist.h - description
- -------------------
- begin : Tue Jun 26 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
- ***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef KOMPAREMODELLIST_H
-#define KOMPAREMODELLIST_H
-
-#include <qobject.h>
-
-#include "diffmodel.h"
-#include "diffmodellist.h"
-#include "kompare.h"
-
-#include "diffexport.h"
-
-class QFile;
-
-class KAction;
-class KDirWatch;
-class K3TempFile;
-
-class DiffSettings;
-class KompareProcess;
-
-namespace Diff2
-{
-
-class DIFF2_EXPORT KompareModelList : public QObject
-{
- Q_OBJECT
-public:
- KompareModelList( DiffSettings* diffSettings, struct Kompare::Info& info, QObject* parent = 0, const char* name = 0 );
- ~KompareModelList();
-
-public:
- // Swap source with destination and show differences
- void swap();
-
- /* Comparing methods */
- bool compare( const QString& source, const QString& destination );
-
- bool compareFiles( const QString& source, const QString& destination );
- bool compareDirs( const QString& source, const QString& destination );
-
- bool openDiff( const QString& diff );
-
- bool openFileAndDiff( const QString& file, const QString& diff );
- bool openDirAndDiff( const QString& dir, const QString& diff );
-
- bool saveDiff( const QString& url, const QString& directory, DiffSettings* diffSettings );
- bool saveAll();
-
- bool saveDestination( DiffModel* model );
-
- void setEncoding( const QString& encoding );
-
- QString recreateDiff() const;
-
- // This parses the difflines and creates new models
- int parseDiffOutput( const QString& diff );
-
- // Call this to emit the signals to the rest of the "world" to show the diff
- void show();
-
- // This will blend the original URL (dir or file) into the diffmodel,
- // this is like patching but with a twist
- bool blendOriginalIntoModelList( const QString& localURL );
-
- enum Kompare::Mode mode() const { return m_info.mode; };
- const DiffModelList* models() const { return m_models; };
-
- int modelCount() const;
- int differenceCount() const;
- int appliedCount() const;
-
- const DiffModel* modelAt( int i ) const { return *( m_models->at( i ) ); };
- int findModel( DiffModel* model ) const { return findItem( model, m_models ); };
-
- bool isModified() const;
-
- int currentModel() const { return findItem( m_selectedModel, m_models ); };
- int currentDifference() const { return m_selectedModel ? m_selectedModel->findDifference( m_selectedDifference ) : -1; };
-
- const DiffModel* selectedModel() const { return m_selectedModel; };
- const Difference* selectedDifference() const { return m_selectedDifference; };
-
- void clear();
-
-private:
- Diff2::DiffModel* firstModel();
- Diff2::DiffModel* lastModel();
- Diff2::DiffModel* prevModel();
- Diff2::DiffModel* nextModel();
-
- bool setSelectedModel( Diff2::DiffModel* model );
-
- void updateModelListActions();
-
-protected:
- bool blendFile( DiffModel* model, const QString& lines );
-
-signals:
- void status( Kompare::Status status );
- void setStatusBarModelInfo( int modelIndex, int differenceIndex, int modelCount, int differenceCount, int appliedCount );
- void error( QString error );
- void modelsChanged( const Diff2::DiffModelList* models );
- void setSelection( const Diff2::DiffModel* model, const Diff2::Difference* diff );
- void setSelection( const Diff2::Difference* diff );
- void applyDifference( bool apply );
- void applyAllDifferences( bool apply );
- void applyDifference( const Diff2::Difference* diff, bool apply );
-
- // Emits true when m_noOfModified > 0, false when m_noOfModified == 0
- void setModified( bool modified );
-
-public slots:
- void slotSelectionChanged( const Diff2::DiffModel* model, const Diff2::Difference* diff );
- void slotSelectionChanged( const Diff2::Difference* diff );
-
- void slotApplyDifference( bool apply );
- void slotApplyAllDifferences( bool apply );
- void slotPreviousModel();
- void slotNextModel();
- void slotPreviousDifference();
- void slotNextDifference();
-
- // This slot is called by the diffmodels whenever their status changes to modified or unmodified
- void slotSetModified( bool modified );
-
-protected slots:
- void slotDiffProcessFinished( bool success );
- void slotWriteDiffOutput( bool success );
-
- void slotActionApplyDifference();
- void slotActionUnApplyDifference();
- void slotActionApplyAllDifferences();
- void slotActionUnapplyAllDifferences();
-
- /** Save the currently selected destination in a multi-file diff,
- or the single destination if a single file diff. */
- void slotSaveDestination();
-
-private slots:
- void slotDirectoryChanged( const QString& );
- void slotFileChanged( const QString& );
-
-private: // Helper methods
- bool isDirectory( const QString& url ) const;
- bool isDiff( const QString& mimetype ) const;
- QString readFile( const QString& fileName );
-
- bool hasPrevModel() const;
- bool hasNextModel() const;
- bool hasPrevDiff() const;
- bool hasNextDiff() const;
-
- QStringList split( const QString& diff );
-
-private:
- K3TempFile* m_diffTemp;
- QString m_diffURL;
-
- KompareProcess* m_diffProcess;
-
- DiffSettings* m_diffSettings;
-
- DiffModelList* m_models;
-
- QString m_source;
- QString m_destination;
-
- DiffModel* m_selectedModel;
- Difference* m_selectedDifference;
-
- KDirWatch* m_dirWatch;
- KDirWatch* m_fileWatch;
-
- int m_noOfModified;
- unsigned int m_modelIndex;
-
- struct Kompare::Info& m_info;
-
- KAction* m_applyDifference;
- KAction* m_unApplyDifference;
- KAction* m_applyAll;
- KAction* m_unapplyAll;
- KAction* m_previousFile;
- KAction* m_nextFile;
- KAction* m_previousDifference;
- KAction* m_nextDifference;
-
- KAction* m_save;
-
- QString m_encoding;
- QTextCodec* m_textCodec;
-};
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h (nonexistent)
@@ -1,68 +0,0 @@
-/*******************************************************************************
-**
-** Filename : levenshteintable.h
-** Created on : 08 november, 2003
-** Copyright : (c) 2003 Otto Bruggeman <bruggie@home.nl>
-**
-*******************************************************************************/
-
-/*******************************************************************************
-**
-** 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.
-**
-*******************************************************************************/
-
-#ifndef _LEVENSHTEIN_H
-#define _LEVENSHTEIN_H
-
-#include "difference.h"
-
-class QString;
-
-namespace Diff2 {
-
-class Marker;
-
-class LevenshteinTable
-{
-public:
- LevenshteinTable();
- LevenshteinTable( unsigned int width, unsigned int height );
- ~LevenshteinTable();
-
-public:
- int getContent( unsigned int posX, unsigned int posY ) const;
- int setContent( unsigned int posX, unsigned int posY, int value );
- bool setSize ( unsigned int width, unsigned int height );
-
- unsigned int width() const { return m_width; };
- unsigned int height() const { return m_height; };
-
- /** Debug method to check if the table is properly filled */
- void dumpLevenshteinTable( void );
-
- /** This will calculate the levenshtein distance of 2 strings */
- unsigned int createTable( DifferenceString* s, DifferenceString* d );
-
- void createListsOfMarkers( void );
- int chooseRoute( int c1, int c2, int c3 );
-
-protected:
- LevenshteinTable( const LevenshteinTable& table );
- const LevenshteinTable& operator = ( const LevenshteinTable& table );
-
-private:
- unsigned int m_width;
- unsigned int m_height;
- unsigned int m_size;
- unsigned int* m_table;
- DifferenceString* m_source;
- DifferenceString* m_destination;
-};
-
-} // namespace Diff2
-
-#endif // _LEVENSHTEIN_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h (nonexistent)
@@ -1,60 +0,0 @@
-/**************************************************************************
-** cvsdiffparser.h
-** -----------------
-** begin : Sun Aug 4 15:05:35 2002
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef _CVSDIFF_PARSER_H
-#define _CVSDIFF_PARSER_H
-
-#include <qregexp.h>
-
-#include "parserbase.h"
-
-namespace Diff2
-{
-
-class KompareModelList;
-
-class CVSDiffParser : public ParserBase
-{
-public:
- CVSDiffParser( const KompareModelList* list, const QStringList& diff );
- virtual ~CVSDiffParser();
-
-protected:
- virtual enum Kompare::Format determineFormat();
-
-protected:
-// virtual bool parseContextDiffHeader();
- virtual bool parseEdDiffHeader();
- virtual bool parseNormalDiffHeader();
- virtual bool parseRCSDiffHeader();
-// virtual bool parseUnifiedDiffHeader();
-
-// virtual bool parseContextHunkHeader();
- virtual bool parseEdHunkHeader();
-// virtual bool parseNormalHunkHeader();
- virtual bool parseRCSHunkHeader();
-// virtual bool parseUnifiedHunkHeader();
-
-// virtual bool parseContextHunkBody();
- virtual bool parseEdHunkBody();
-// virtual bool parseNormalHunkBody();
- virtual bool parseRCSHunkBody();
-// virtual bool parseUnifiedHunkBody();
-};
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/cvsdiffparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp (nonexistent)
@@ -1,80 +0,0 @@
-/**************************************************************************
-** diffparser.cpp
-** --------------
-** begin : Sun Aug 4 15:05:35 2002
-** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "diffparser.h"
-#include <qregexp.h>
-
-#include <kdebug.h>
-
-
-using namespace Diff2;
-
-DiffParser::DiffParser( const KompareModelList* list, const QStringList& diff ) : ParserBase( list, diff )
-{
- // The regexps needed for context diff parsing, the rest is the same as in parserbase.cpp
- m_contextDiffHeader1.setPattern( "\\*\\*\\* ([^\\t]+)\\t([^\\t]+)\\n" );
- m_contextDiffHeader2.setPattern( "--- ([^\\t]+)\\t([^\\t]+)\\n" );
-}
-
-DiffParser::~DiffParser()
-{
-}
-
-enum Kompare::Format DiffParser::determineFormat()
-{
- kDebug(8101) << "Determining the format of the diff Diff";
-
- QRegExp normalRE ( "[0-9]+[0-9,]*[acd][0-9]+[0-9,]*" );
- QRegExp unifiedRE( "^--- " );
- QRegExp contextRE( "^\\*\\*\\* " );
- QRegExp rcsRE ( "^[acd][0-9]+ [0-9]+" );
- QRegExp edRE ( "^[0-9]+[0-9,]*[acd]" );
-
- QStringList::ConstIterator it = m_diffLines.begin();
-
- while( it != m_diffLines.end() )
- {
- kDebug(8101) << (*it);
- if( (*it).indexOf( normalRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Normal diff...";
- return Kompare::Normal;
- }
- else if( (*it).indexOf( unifiedRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Unified diff...";
- return Kompare::Unified;
- }
- else if( (*it).indexOf( contextRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from a Context diff...";
- return Kompare::Context;
- }
- else if( (*it).indexOf( rcsRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from an RCS diff...";
- return Kompare::RCS;
- }
- else if( (*it).indexOf( edRE, 0 ) == 0 )
- {
- kDebug(8101) << "Difflines are from an ED diff...";
- return Kompare::Ed;
- }
- ++it;
- }
- kDebug(8101) << "Difflines are from an unknown diff...";
- return Kompare::UnknownFormat;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h (nonexistent)
@@ -1,141 +0,0 @@
-/***************************************************************************
- kompare.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef KOMPARE_H
-#define KOMPARE_H
-
-#include <kurl.h>
-
-namespace Kompare
-{
- enum Format {
- Context = 0,
- Ed = 1,
- Normal = 2,
- RCS = 3,
- Unified = 4,
- SideBySide = 5,
- UnknownFormat = -1
- };
-
- enum Generator {
- CVSDiff = 0,
- Diff = 1,
- Perforce = 2,
- SubVersion = 3,
- Reserved2 = 4,
- Reserved3 = 5,
- Reserved4 = 6,
- Reserved5 = 7,
- Reserved6 = 8,
- Reserved7 = 9,
- UnknownGenerator = -1
- };
-
- enum Mode {
- ComparingFiles, // compareFiles
- ComparingDirs, // compareDirs
- ShowingDiff, // openDiff
- BlendingDir, // openDirAnfDiff
- BlendingFile, // openFileAndDiff
- UnknownMode // Used to initialize the Infoi struct
- };
-
- enum DiffMode {
- Default,
- Custom,
- UnknownDiffMode // Use to initialize the Info struct
- };
-
- enum Status {
- RunningDiff,
- Parsing,
- FinishedParsing,
- FinishedWritingDiff,
- ReRunningDiff // When a change has been detected after diff has run
- };
-
- enum Target {
- Source,
- Destination
- };
-
- struct Info {
- Info (
- enum Mode _mode = UnknownMode,
- enum DiffMode _diffMode = UnknownDiffMode,
- enum Format _format = UnknownFormat,
- enum Generator _generator = UnknownGenerator,
- KUrl _source = KUrl(),
- KUrl _destination = KUrl(),
- QString _localSource = "",
- QString _localDestination = ""
- )
- {
- mode = _mode;
- diffMode = _diffMode;
- format = _format;
- generator = _generator;
- source = _source;
- destination = _destination;
- localSource = _localSource;
- localDestination = _localDestination;
- }
- enum Mode mode;
- enum DiffMode diffMode;
- enum Format format;
- enum Generator generator;
- KUrl source;
- KUrl destination;
- QString localSource;
- QString localDestination;
- };
-} // End of namespace Kompare
-
-/*
-** This should be removed and put somewhere else
-*/
-class KompareFunctions
-{
-public:
- static QString constructRelativePath( const QString& from, const QString& to )
- {
- KUrl fromURL( from );
- KUrl toURL( to );
- KUrl root;
- int upLevels = 0;
-
- // Find a common root.
- root = from;
- while( root.isValid() && !root.isParentOf( toURL ) ) {
- root = root.upUrl();
- upLevels++;
- }
-
- if( !root.isValid() ) return to;
-
- QString relative;
- for( ; upLevels > 0; upLevels-- ) {
- relative += "../";
- }
-
- relative += QString( to ).replace( 0, root.path( KUrl::LeaveTrailingSlash ).length(), "" );
- return relative;
- }
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompare.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp (nonexistent)
@@ -1,113 +0,0 @@
-/***************************************************************************
- diffhunk.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-
-#include "diffhunk.h"
-#include "difference.h"
-
-using namespace Diff2;
-
-DiffHunk::DiffHunk( int sourceLine, int destinationLine, const QString& function, Type type ) :
- m_sourceLine( sourceLine ),
- m_destinationLine( destinationLine ),
- m_function( function ),
- m_type( type )
-{
-}
-
-DiffHunk::~DiffHunk()
-{
-}
-
-void DiffHunk::add( Difference* diff )
-{
- m_differences.append( diff );
-}
-
-int DiffHunk::sourceLineCount() const
-{
- DifferenceListConstIterator diffIt = m_differences.begin();
- DifferenceListConstIterator dEnd = m_differences.end();
-
- int lineCount = 0;
-
- for ( ; diffIt != dEnd; ++diffIt )
- lineCount += (*diffIt)->sourceLineCount();
-
- return lineCount;
-}
-
-int DiffHunk::destinationLineCount() const
-{
- DifferenceListConstIterator diffIt = m_differences.begin();
- DifferenceListConstIterator dEnd = m_differences.end();
-
- int lineCount = 0;
-
- for ( ; diffIt != dEnd; ++diffIt )
- lineCount += (*diffIt)->destinationLineCount();
-
- return lineCount;
-}
-
-QString DiffHunk::recreateHunk() const
-{
- QString hunk;
- QString differences;
-
- // recreate body
- DifferenceListConstIterator diffIt = m_differences.begin();
- DifferenceListConstIterator dEnd = m_differences.end();
-
- int slc = 0; // source line count
- int dlc = 0; // destination line count
- for ( ; diffIt != dEnd; ++diffIt )
- {
- switch ( (*diffIt)->type() )
- {
- case Difference::Unchanged:
- case Difference::Change:
- slc += (*diffIt)->sourceLineCount();
- dlc += (*diffIt)->destinationLineCount();
- break;
- case Difference::Insert:
- dlc += (*diffIt)->destinationLineCount();
- break;
- case Difference::Delete:
- slc += (*diffIt)->sourceLineCount();
- break;
- }
- differences += (*diffIt)->recreateDifference();
- }
-
- // recreate header
- hunk += QString::fromLatin1( "@@ -%1,%3 +%2,%4 @@" )
- .arg( m_sourceLine )
- .arg( m_destinationLine )
- .arg( slc )
- .arg( dlc );
-
- if ( !m_function.isEmpty() )
- hunk += ' ' + m_function;
-
- hunk += QString::fromLatin1( "\n" );
-
- hunk += differences;
-
- kDebug( 8101 ) << hunk;
- return hunk;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffhunk.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h (nonexistent)
@@ -1,48 +0,0 @@
-/*******************************************************************************
-**
-** Filename : diffmodellist.h
-** Created on : 24 januari, 2004
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-*******************************************************************************/
-
-/*******************************************************************************
-**
-** 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.
-**
-*******************************************************************************/
-
-#ifndef DIFFMODELLIST_H
-#define DIFFMODELLIST_H
-
-#include <q3valuelist.h> // include for the base class
-
-#include "diffmodel.h"
-
-namespace Diff2
-{
-
-typedef Q3ValueListIterator<DiffModel*> DiffModelListIterator;
-typedef Q3ValueListConstIterator<DiffModel*> DiffModelListConstIterator;
-
-class DiffModelList : public Q3ValueList<DiffModel*>
-{
-public:
- DiffModelList() {}
- DiffModelList( const DiffModelList &list ) : Q3ValueList<DiffModel*>( list ) {}
- virtual ~DiffModelList()
- {
- clear();
- }
-
-public:
- virtual void sort();
-
-}; // End of class DiffModelList
-
-} // End of Namespace Diff2
-
-#endif // DIFFMODELLIST_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodellist.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp (nonexistent)
@@ -1,1424 +0,0 @@
-/***************************************************************************
- komparemodellist.cpp - description
- -------------------
- begin : Tue Jun 26 2001
- copyright : (C) 2001-2004 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
- ***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "komparemodellist.h"
-#include <qfile.h>
-#include <qdir.h>
-#include <qregexp.h>
-#include <qtextcodec.h>
-#include <q3valuelist.h>
-#include <QTextStream>
-
-#include <kaction.h>
-#include <kcharsets.h>
-#include <kdebug.h>
-#include <kdirwatch.h>
-#include <kio/netaccess.h>
-#include <klocale.h>
-#include <kmimetype.h>
-#include <k3tempfile.h>
-#include <kstdaction.h>
-
-#include "difference.h"
-#include "diffhunk.h"
-#include "diffmodel.h"
-#include "diffmodellist.h"
-#include "kompareprocess.h"
-#include "parser.h"
-#include <assert.h>
-
-//#include "kompareplugin.h"
-
-using namespace Diff2;
-
-KompareModelList::KompareModelList( DiffSettings* diffSettings, struct Kompare::Info& info, QObject* parent, const char* name )
- : QObject( parent ),
- m_diffProcess( 0 ),
- m_diffSettings( diffSettings ),
- m_models( 0 ),
- m_selectedModel( 0 ),
- m_selectedDifference( 0 ),
- m_noOfModified( 0 ),
- m_modelIndex( 0 ),
- m_info( info ),
- m_textCodec( 0 )
-{
- m_applyDifference = m_unApplyDifference = m_applyAll = m_unapplyAll = m_previousFile = m_nextFile = m_previousDifference = m_nextDifference = m_save = 0;
-/* m_applyDifference = new KAction( i18n("&Apply Difference"), "1rightarrow", Qt::Key_Space,
- this, SLOT(slotActionApplyDifference()),
- (( KomparePart* )parent)->actionCollection(), "difference_apply" );
- m_unApplyDifference = new KAction( i18n("Un&apply Difference"), "1leftarrow", Qt::Key_Backspace,
- this, SLOT(slotActionUnApplyDifference()),
- (( KomparePart* )parent)->actionCollection(), "difference_unapply" );
- m_applyAll = new KAction( i18n("App&ly All"), "2rightarrow", Qt::CTRL + Qt::Key_A,
- this, SLOT(slotActionApplyAllDifferences()),
- (( KomparePart* )parent)->actionCollection(), "difference_applyall" );
- m_unapplyAll = new KAction( i18n("&Unapply All"), "2leftarrow", Qt::CTRL + Qt::Key_U,
- this, SLOT(slotActionUnapplyAllDifferences()),
- (( KomparePart* )parent)->actionCollection(), "difference_unapplyall" );
- m_previousFile = new KAction( i18n("P&revious File"), "2uparrow", Qt::CTRL + Qt::Key_PageUp,
- this, SLOT(slotPreviousModel()),
- (( KomparePart* )parent)->actionCollection(), "difference_previousfile" );
- m_nextFile = new KAction( i18n("N&ext File"), "2downarrow", Qt::CTRL + Qt::Key_PageDown,
- this, SLOT(slotNextModel()),
- (( KomparePart* )parent)->actionCollection(), "difference_nextfile" );
- m_previousDifference = new KAction( i18n("&Previous Difference"), "1uparrow", Qt::CTRL + Qt::Key_Up,
- this, SLOT(slotPreviousDifference()),
- (( KomparePart* )parent)->actionCollection(), "difference_previous" );
- m_nextDifference = new KAction( i18n("&Next Difference"), "1downarrow", Qt::CTRL + Qt::Key_Down,
- this, SLOT(slotNextDifference()),
- (( KomparePart* )parent)->actionCollection(), "difference_next" );
- m_previousDifference->setEnabled( false );
- m_nextDifference->setEnabled( false );*/
-
-/* m_save = KStdAction::save( this, SLOT(slotSaveDestination()), ((KomparePart*)parent)->actionCollection() );
- m_save->setEnabled( false );*/
-
- updateModelListActions();
-}
-
-KompareModelList::~KompareModelList()
-{
-}
-
-bool KompareModelList::isDirectory( const QString& url ) const
-{
- QFileInfo fi( url );
- if ( fi.isDir() )
- return true;
- else
- return false;
-}
-
-bool KompareModelList::isDiff( const QString& mimeType ) const
-{
- if ( mimeType == "text/x-diff" )
- return true;
- else
- return false;
-}
-
-bool KompareModelList::compare( const QString& source, const QString& destination )
-{
- bool result = false;
-
- bool sourceIsDirectory = isDirectory( source );
- bool destinationIsDirectory = isDirectory( source );
-
- if ( sourceIsDirectory && destinationIsDirectory )
- {
- m_info.mode = Kompare::ComparingDirs;
- result = compareDirs( source, destination );
- }
- else if ( !sourceIsDirectory && !destinationIsDirectory )
- {
- QFile sourceFile( source );
- sourceFile.open( QIODevice::ReadOnly );
- QString sourceMimeType = ( KMimeType::findByContent( sourceFile.readAll() ) )->name();
- sourceFile.close();
- kDebug(8101) << "Mimetype source :" << sourceMimeType;
-
- QFile destinationFile( destination );
- destinationFile.open( QIODevice::ReadOnly );
- QString destinationMimeType = ( KMimeType::findByContent( destinationFile.readAll() ) )->name();
- destinationFile.close();
- kDebug(8101) << "Mimetype destination:" << destinationMimeType;
-
- // Not checking if it is a text file/something diff can even compare, we'll let diff handle that
- if ( !isDiff( sourceMimeType ) && isDiff( destinationMimeType ) )
- {
- kDebug(8101) << "Blending destination into source...";
- m_info.mode = Kompare::BlendingFile;
- result = openFileAndDiff( source, destination );
- }
- else if ( isDiff( sourceMimeType ) && !isDiff( destinationMimeType ) )
- {
- kDebug(8101) << "Blending source into destination...";
- m_info.mode = Kompare::BlendingFile;
- result = openFileAndDiff( destination, source );
- }
- else
- {
- kDebug(8101) << "Comparing source with destination";
- m_info.mode = Kompare::ComparingFiles;
- result = compareFiles( source, destination );
- }
- }
- else if ( sourceIsDirectory && !destinationIsDirectory )
- {
- m_info.mode = Kompare::BlendingDir;
- result = openDirAndDiff( source, destination );
- }
- else
- {
- m_info.mode = Kompare::BlendingDir;
- result = openDirAndDiff( destination, source );
- }
-
- return result;
-}
-
-bool KompareModelList::compareFiles( const QString& source, const QString& destination )
-{
- m_source = source;
- m_destination = destination;
-
- clear(); // Destroy the old models...
-
-// m_fileWatch = new KDirWatch( this, "filewatch" );
-// m_fileWatch->addFile( m_source );
-// m_fileWatch->addFile( m_destination );
-
-// connect( m_fileWatch, SIGNAL( dirty( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
-// connect( m_fileWatch, SIGNAL( created( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
-// connect( m_fileWatch, SIGNAL( deleted( const QString& ) ), this, SLOT( slotFileChanged( const QString& ) ) );
-
-// m_fileWatch->startScan();
- m_diffProcess = new KompareProcess( m_diffSettings, Kompare::Custom, m_source, m_destination );
- m_diffProcess->setEncoding( m_encoding );
-
- connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
- this, SLOT(slotDiffProcessFinished( bool )) );
-
- emit status( Kompare::RunningDiff );
- m_diffProcess->start();
-
- return true;
-}
-
-bool KompareModelList::compareDirs( const QString& source, const QString& destination )
-{
- m_source = source;
- m_destination = destination;
-
- clear(); // Destroy the old models...
-
-// m_dirWatch = new KDirWatch( this, "dirwatch" );
- // Watch files in the dirs and watch the dirs recursively
-// m_dirWatch->addDir( m_source, true, true );
-// m_dirWatch->addDir( m_destination, true, true );
-
-// connect( m_dirWatch, SIGNAL( dirty ( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
-// connect( m_dirWatch, SIGNAL( created( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
-// connect( m_dirWatch, SIGNAL( deleted( const QString& ) ), this, SLOT( slotDirectoryChanged( const QString& ) ) );
-
-// m_dirWatch->startScan();
- m_diffProcess = new KompareProcess( m_diffSettings, Kompare::Custom, m_source, m_destination );
- m_diffProcess->setEncoding( m_encoding );
-
- connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
- this, SLOT(slotDiffProcessFinished( bool )) );
-
- emit status( Kompare::RunningDiff );
- m_diffProcess->start();
-
- return true;
-}
-
-bool KompareModelList::openFileAndDiff( const QString& file, const QString& diff )
-{
- clear();
-
- if ( parseDiffOutput( readFile( diff ) ) != 0 )
- {
- emit error( i18n( "<qt>No models or no differences, this file: <b>%1</b>, is not a valid diff file.</qt>", diff ) );
- return false;
- }
-
- // Do our thing :)
- if ( !blendOriginalIntoModelList( file ) )
- {
- kDebug(8101) << "Oops cant blend original file into modellist :" << file;
- emit( i18n( "<qt>There were problems applying the diff <b>%1</b> to the file <b>%2</b>.</qt>", diff, file ) );
- return false;
- }
-
- updateModelListActions();
- show();
-
- return true;
-}
-
-bool KompareModelList::openDirAndDiff( const QString& dir, const QString& diff )
-{
- clear();
-
- if ( parseDiffOutput( readFile( diff ) ) != 0 )
- {
- emit error( i18n( "<qt>No models or no differences, this file: <b>%1</b>, is not a valid diff file.</qt>", diff ) );
- return false;
- }
-
- // Do our thing :)
- if ( !blendOriginalIntoModelList( dir ) )
- {
- // Trouble blending the original into the model
- kDebug(8101) << "Oops cant blend original dir into modellist :" << dir;
- emit error( i18n( "<qt>There were problems applying the diff <b>%1</b> to the folder <b>%2</b>.</qt>", diff, dir ) );
- return false;
- }
-
- updateModelListActions();
- show();
-
- return true;
-}
-
-void KompareModelList::slotSaveDestination()
-{
- if ( m_selectedModel )
- {
- saveDestination( m_selectedModel );
- }
-}
-
-bool KompareModelList::saveDestination( DiffModel* model )
-{
- kDebug(9500) << "KompareModelList::saveDestination:";
-
- if( !model->isModified() )
- return true;
-
- K3TempFile* temp = new K3TempFile();
-
- if( temp->status() != 0 ) {
- emit error( i18n( "Could not open a temporary file." ) );
- temp->unlink();
- delete temp;
- return false;
- }
-
- QTextStream* stream = temp->textStream();
- QStringList list;
-
- DiffHunkListConstIterator hunkIt = model->hunks()->begin();
- DiffHunkListConstIterator hEnd = model->hunks()->end();
-
- for( ; hunkIt != hEnd; ++hunkIt )
- {
- DiffHunk* hunk = *hunkIt;
-
- DifferenceListConstIterator diffIt = hunk->differences().begin();
- DifferenceListConstIterator dEnd = hunk->differences().end();
-
- Difference* diff;
- for( ; diffIt != dEnd; ++diffIt )
- {
- diff = *diffIt;
- if( !diff->applied() )
- {
- DifferenceStringListConstIterator stringIt = diff->destinationLines().begin();
- DifferenceStringListConstIterator sEnd = diff->destinationLines().end();
- for ( ; stringIt != sEnd; ++stringIt )
- {
- list.append( ( *stringIt )->string() );
- }
- }
- else
- {
- DifferenceStringListConstIterator stringIt = diff->sourceLines().begin();
- DifferenceStringListConstIterator sEnd = diff->sourceLines().end();
- for ( ; stringIt != sEnd; ++stringIt )
- {
- list.append( ( *stringIt )->string() );
- }
- }
- }
- }
-
- // kDebug( 8101 ) << "Everything:"<< list.join( "\n" );
-
- if( list.count() > 0 )
- *stream << list.join( "" );
-
- temp->close();
- if( temp->status() != 0 ) {
- emit error( i18n( "<qt>Could not write to the temporary file <b>%1</b>, deleting it.</qt>", temp->name() ) );
- temp->unlink();
- delete temp;
- return false;
- }
-
- bool result = false;
-
- if ( m_info.mode == Kompare::ComparingDirs )
- {
- QString destination = model->destinationPath() + model->destinationFile();
- kDebug(8101) << "Tempfilename :" << temp->name();
- kDebug(8101) << "DestinationURL :" << destination;
- KIO::UDSEntry entry;
- if ( !KIO::NetAccess::stat( KUrl( destination ).toLocalFile(), entry, (QWidget*)parent() ) )
- {
- if ( !KIO::NetAccess::mkdir( KUrl( destination ).toLocalFile(), (QWidget*)parent() ) )
- {
- emit error( i18n( "<qt>Could not create destination directory <b>%1</b>.\nThe file has not been saved.</qt>", destination ) );
- return false;
- }
- }
- result = KIO::NetAccess::upload( temp->name(), KUrl( destination ), (QWidget*)parent() );
- }
- else
- {
- kDebug(8101) << "Tempfilename :" << temp->name();
- kDebug(8101) << "DestinationURL :" << m_destination;
- result = KIO::NetAccess::upload( temp->name(), KUrl( m_destination ), (QWidget*)parent() );
- }
-
- if ( !result )
- {
- emit error( i18n( "<qt>Could not upload the temporary file to the destination location <b>%1</b>. The temporary file is still available under: <b>%2</b>. You can manually copy it to the right place.</qt>", m_destination, temp->name() ) );
- }
- else
- {
- //model->slotSetModified( false );
- temp->unlink();
- delete temp;
- }
-
- return true;
-}
-
-bool KompareModelList::saveAll()
-{
- if ( !m_models )
- return false;
-
- DiffModelListIterator it = m_models->begin();
- DiffModelListIterator end = m_models->end();
- for ( ; it != end; ++it )
- {
- if( !saveDestination( *it ) )
- return false;
- }
- return true;
-}
-
-void KompareModelList::setEncoding( const QString& encoding )
-{
- m_encoding = encoding;
- kDebug(9500) << "Encoding :" << encoding;
- m_textCodec = KGlobal::charsets()->codecForName( encoding.toLatin1() );
- kDebug(9500) << "TextCodec:" << m_textCodec;
- if ( !m_textCodec )
- m_textCodec = QTextCodec::codecForLocale();
- kDebug(9500) << "TextCodec:" << m_textCodec;
-}
-
-void KompareModelList::slotDiffProcessFinished( bool success )
-{
- if ( success )
- {
- emit status( Kompare::Parsing );
- if ( parseDiffOutput( m_diffProcess->diffOutput() ) != 0 )
- {
- emit error( i18n( "Could not parse diff output." ) );
- }
- else
- {
- if ( m_info.mode != Kompare::ShowingDiff )
- {
- kDebug(9500) << "Blend this crap please and do not gimme any conflicts...";
- blendOriginalIntoModelList( m_info.localSource );
- }
- updateModelListActions();
- show();
- }
- emit status( Kompare::FinishedParsing );
- }
- else if ( m_diffProcess->process()->exitStatus() == QProcess::NormalExit )
- {
- emit error( i18n( "The files are identical." ) );
- }
- else
- {
- emit error( m_diffProcess->stdErr() );
- }
-
- delete m_diffProcess;
- m_diffProcess = 0;
-}
-
-void KompareModelList::slotDirectoryChanged( const QString& /*dir*/ )
-{
- // some debug output to see if watching works properly
- kDebug(8101) << "Yippie directories are being watched !!! :)";
- if ( m_diffProcess )
- {
- emit status( Kompare::ReRunningDiff );
- m_diffProcess->start();
- }
-}
-
-void KompareModelList::slotFileChanged( const QString& /*file*/ )
-{
- // some debug output to see if watching works properly
- kDebug(8101) << "Yippie files are being watched !!! :)";
- if ( m_diffProcess )
- {
- emit status( Kompare::ReRunningDiff );
- m_diffProcess->start();
- }
-}
-
-QStringList KompareModelList::split( const QString& fileContents )
-{
- QString contents = fileContents;
- QStringList list;
-
- int pos = 0;
- unsigned int oldpos = 0;
- // split that does not strip the split char
-#ifdef QT_OS_MAC
- const char split = '\r';
-#else
- const char split = '\n';
-#endif
- while ( ( pos = contents.indexOf( split, oldpos ) ) >= 0 )
- {
- list.append( contents.mid( oldpos, pos - oldpos + 1 ) );
- oldpos = pos + 1;
- }
-
- if ( contents.length() > oldpos )
- {
- list.append( contents.right( contents.length() - oldpos ) );
- }
-
- return list;
-}
-
-QString KompareModelList::readFile( const QString& fileName )
-{
- QStringList list;
-
- QFile file( fileName );
- file.open( QIODevice::ReadOnly );
-
- QTextStream stream( &file );
- kDebug(9500) << "Codec =" << m_textCodec;
-
- if ( !m_textCodec )
- m_textCodec = QTextCodec::codecForLocale();
-
- stream.setCodec( m_textCodec );
-
- QString contents = stream.readAll();
-
- file.close();
-
- return contents;
-}
-
-bool KompareModelList::openDiff( const QString& diffFile )
-{
- kDebug(8101) << "Stupid :) Url =" << diffFile;
-
- if ( diffFile.isEmpty() )
- return false;
-
- QString diff = readFile( diffFile );
-
- clear(); // Clear the current models
-
- emit status( Kompare::Parsing );
-
- if ( parseDiffOutput( diff ) != 0 )
- {
- emit error( i18n( "Could not parse diff output." ) );
- return false;
- }
-
- updateModelListActions();
- show();
-
- emit status( Kompare::FinishedParsing );
-
- return true;
-}
-
-QString KompareModelList::recreateDiff() const
-{
- QString diff;
-
- DiffModelListConstIterator modelIt = m_models->begin();
- DiffModelListConstIterator mEnd = m_models->end();
-
- for ( ; modelIt != mEnd; ++modelIt )
- {
- diff += (*modelIt)->recreateDiff();
- }
- return diff;
-}
-
-bool KompareModelList::saveDiff( const QString& url, const QString& directory, DiffSettings* diffSettings )
-{
- kDebug(9500) << "KompareModelList::saveDiff:";
-
- m_diffTemp = new K3TempFile();
- m_diffURL = url;
-
- if( m_diffTemp->status() != 0 ) {
- emit error( i18n( "Could not open a temporary file." ) );
- m_diffTemp->unlink();
- delete m_diffTemp;
- m_diffTemp = 0;
- return false;
- }
-
- m_diffProcess = new KompareProcess( diffSettings, Kompare::Custom, m_source, m_destination, directory );
- m_diffProcess->setEncoding( m_encoding );
-
- connect( m_diffProcess, SIGNAL(diffHasFinished( bool )),
- this, SLOT(slotWriteDiffOutput( bool )) );
-
- emit status( Kompare::RunningDiff );
- m_diffProcess->start();
- return m_diffProcess->process()->waitForStarted();
-}
-
-void KompareModelList::slotWriteDiffOutput( bool success )
-{
- kDebug(8101) << "Success =" << success;
-
- if( success )
- {
- QTextStream* stream = m_diffTemp->textStream();
-
- *stream << m_diffProcess->diffOutput();
-
- m_diffTemp->close();
-
- if( m_diffTemp->status() != 0 )
- {
- emit error( i18n( "Could not write to the temporary file." ) );
- }
-
- KIO::NetAccess::upload( m_diffTemp->name(), KUrl( m_diffURL ), (QWidget*)parent() );
-
- emit status( Kompare::FinishedWritingDiff );
- }
-
- m_diffURL.truncate( 0 );
- m_diffTemp->unlink();
-
- delete m_diffTemp;
- m_diffTemp = 0;
-
- delete m_diffProcess;
- m_diffProcess = 0;
-}
-
-void KompareModelList::slotSelectionChanged( const Diff2::DiffModel* model, const Diff2::Difference* diff )
-{
-// This method will signal all the other objects about a change in selection,
-// it will emit setSelection( const DiffModel*, const Difference* ) to all who are connected
- kDebug(8101) << "KompareModelList::slotSelectionChanged(" << model << "," << diff << ")";
-// kDebug(8101) << "Sender is :" << sender()->className();
-// kDebug(8101) << kBacktrace();
-
- m_selectedModel = const_cast<DiffModel*>(model);
- m_modelIndex = findItem( m_selectedModel, m_models );
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
- m_selectedDifference = const_cast<Difference*>(diff);
-
- m_selectedModel->setSelectedDifference( m_selectedDifference );
-
- // setSelected* search for the argument in the lists and return false if not found
- // if found they return true and set the m_selected*
- if ( !setSelectedModel( m_selectedModel ) )
- {
- // Backup plan
- m_selectedModel = firstModel();
- m_selectedDifference = m_selectedModel->firstDifference();
- }
- else if ( !m_selectedModel->setSelectedDifference( m_selectedDifference ) )
- {
- // Another backup plan
- m_selectedDifference = m_selectedModel->firstDifference();
- }
-
- emit setSelection( model, diff );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
-
- updateModelListActions();
-}
-
-void KompareModelList::slotSelectionChanged( const Diff2::Difference* diff )
-{
-// This method will emit setSelection( const Difference* ) to whomever is listening
-// when for instance in kompareview the selection has changed
- kDebug(8101) << "KompareModelList::slotSelectionChanged(" << diff << ")";
-// kDebug(8101) << "Sender is :" << sender()->className();
-
- m_selectedDifference = const_cast<Difference*>(diff);
-
- if ( !m_selectedModel->setSelectedDifference( m_selectedDifference ) )
- {
- // Backup plan
- m_selectedDifference = m_selectedModel->firstDifference();
- }
-
- emit setSelection( diff );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
-
- updateModelListActions();
-}
-
-void KompareModelList::slotPreviousModel()
-{
- if ( ( m_selectedModel = prevModel() ) != 0 )
- {
- m_selectedDifference = m_selectedModel->firstDifference();
- }
- else
- {
- m_selectedModel = firstModel();
- m_selectedDifference = m_selectedModel->firstDifference();
- }
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
-}
-
-void KompareModelList::slotNextModel()
-{
- if ( ( m_selectedModel = nextModel() ) != 0 )
- {
- m_selectedDifference = m_selectedModel->firstDifference();
- }
- else
- {
- m_selectedModel = lastModel();
- m_selectedDifference = m_selectedModel->firstDifference();
- }
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
-}
-
-DiffModel* KompareModelList::firstModel()
-{
- kDebug( 8101 ) << "KompareModelList::firstModel()";
- m_modelIndex = 0;
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
-
- m_selectedModel = m_models->first();
-
- return m_selectedModel;
-}
-
-DiffModel* KompareModelList::lastModel()
-{
- kDebug( 8101 ) << "KompareModelList::lastModel()";
- m_modelIndex = m_models->count() - 1;
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
-
- m_selectedModel = m_models->last();
-
- return m_selectedModel;
-}
-
-DiffModel* KompareModelList::prevModel()
-{
- kDebug( 8101 ) << "KompareModelList::prevModel()";
- if ( --m_modelIndex < m_models->count() )
- {
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
- m_selectedModel = (*m_models)[ m_modelIndex ];
- }
- else
- {
- m_selectedModel = 0;
- m_modelIndex = 0;
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
- }
-
- return m_selectedModel;
-}
-
-DiffModel* KompareModelList::nextModel()
-{
- kDebug( 8101 ) << "KompareModelList::nextModel()";
- if ( ++m_modelIndex < m_models->count() )
- {
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
- m_selectedModel = (*m_models)[ m_modelIndex ];
- }
- else
- {
- m_selectedModel = 0;
- m_modelIndex = 0;
- kDebug( 8101 ) << "m_modelIndex =" << m_modelIndex;
- }
-
- return m_selectedModel;
-}
-
-void KompareModelList::slotPreviousDifference()
-{
- kDebug(8101) << "slotPreviousDifference called";
- if ( ( m_selectedDifference = m_selectedModel->prevDifference() ) != 0 )
- {
- emit setSelection( m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
- return;
- }
-
- kDebug(8101) << "**** no previous difference... ok lets find the previous model...";
-
- if ( ( m_selectedModel = prevModel() ) != 0 )
- {
- m_selectedDifference = m_selectedModel->lastDifference();
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
- return;
- }
-
-
- kDebug(8101) << "**** !!! No previous model, ok backup plan activated...";
-
- // Backup plan
- m_selectedModel = firstModel();
- m_selectedDifference = m_selectedModel->firstDifference();
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
-}
-
-void KompareModelList::slotNextDifference()
-{
- kDebug(8101) << "slotNextDifference called";
- if ( ( m_selectedDifference = m_selectedModel->nextDifference() ) != 0 )
- {
- emit setSelection( m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
- return;
- }
-
- kDebug(8101) << "**** no next difference... ok lets find the next model...";
-
- if ( ( m_selectedModel = nextModel() ) != 0 )
- {
- m_selectedDifference = m_selectedModel->firstDifference();
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
- return;
- }
-
- kDebug(8101) << "**** !!! No next model, ok backup plan activated...";
-
- // Backup plan
- m_selectedModel = lastModel();
- m_selectedDifference = m_selectedModel->lastDifference();
-
- emit setSelection( m_selectedModel, m_selectedDifference );
- emit setStatusBarModelInfo( findModel( m_selectedModel ), m_selectedModel->findDifference( m_selectedDifference ), modelCount(), differenceCount(), m_selectedModel->appliedCount() );
- updateModelListActions();
-}
-
-void KompareModelList::slotApplyDifference( bool apply )
-{
- m_selectedModel->applyDifference( apply );
- emit applyDifference( apply );
-}
-
-void KompareModelList::slotApplyAllDifferences( bool apply )
-{
- m_selectedModel->applyAllDifferences( apply );
- emit applyAllDifferences( apply );
-}
-
-int KompareModelList::parseDiffOutput( const QString& diff )
-{
- kDebug(8101) << "KompareModelList::parseDiffOutput";
-
- QStringList diffLines = split( diff );
-
- Parser* parser = new Parser( this );
- m_models = parser->parse( diffLines );
-
- m_info.generator = parser->generator();
- m_info.format = parser->format();
-
- delete parser;
-
- if ( m_models )
- {
- m_selectedModel = firstModel();
- kDebug(8101) << "Ok there are differences...";
- m_selectedDifference = m_selectedModel->firstDifference();
- emit setStatusBarModelInfo( 0, 0, modelCount(), differenceCount(), 0);
- }
- else
- {
- // Wow trouble, no models, so no differences...
- kDebug(8101) << "Now i'll be damned, there should be models here !!!";
- return -1;
- }
-
- return 0;
-}
-
-bool KompareModelList::blendOriginalIntoModelList( const QString& localURL )
-{
- kDebug(9500) << "Hurrah we are blending...";
- QFileInfo fi( localURL );
-
- bool result = false;
- DiffModel* model;
-
- QString fileContents;
-
- if ( fi.isDir() )
- { // is a dir
- kDebug(9500) << "Blend Dir";
-// QDir dir( localURL, QString(), QDir::Name|QDir::DirsFirst, QDir::TypeMask );
- DiffModelListIterator modelIt = m_models->begin();
- DiffModelListIterator mEnd = m_models->end();
- for ( ; modelIt != mEnd; ++modelIt )
- {
- model = *modelIt;
- kDebug(8101) << "Model :" << model;
- QString filename = model->sourcePath() + model->sourceFile();
- if ( !filename.startsWith( localURL ) ) {
- KUrl u( localURL );
- u.addPath( filename );
- filename = u.toLocalFile();
- }
- QFileInfo fi2( filename );
- if ( fi2.exists() )
- {
- kDebug(8101) << "Reading from:" << filename;
- fileContents = readFile( filename );
- result = blendFile( model, fileContents );
- }
- else
- {
- kDebug(8101) << "File" << filename << "does not exist !";
- kDebug(8101) << "Assume empty file !";
- fileContents.truncate( 0 );
- result = blendFile( model, fileContents );
- }
- }
- kDebug(9500) << "End of Blend Dir";
- }
- else if ( fi.isFile() )
- { // is a file
- kDebug(9500) << "Blend File";
- kDebug(8101) << "Reading from:" << localURL;
- fileContents = readFile( localURL );
-
- result = blendFile( (*m_models)[ 0 ], fileContents );
- kDebug(9500) << "End of Blend File";
- }
-
- return result;
-}
-
-bool KompareModelList::blendFile( DiffModel* model, const QString& fileContents )
-{
- if ( !model )
- {
- kDebug(9500) << "**** model is null :(";
- return false;
- }
-
- model->setBlended( true );
-
- int srcLineNo = 1, destLineNo = 1;
-
- QStringList lines = split( fileContents );
-
- QStringList::ConstIterator linesIt = lines.begin();
- QStringList::ConstIterator lEnd = lines.end();
-
- DiffHunkList* hunks = model->hunks();
- kDebug(8101) << "Hunks in hunklist:" << hunks->count();
- DiffHunkListIterator hunkIt = hunks->begin();
-
- DiffHunk* newHunk = 0;
- Difference* newDiff = 0;
-
- // FIXME: this approach is not very good, we should first check if the hunk applies cleanly
- // and without offset and if not use that new linenumber with offset to compare against
- // This will only work for files we just diffed with kompare but not for blending where
- // file(s) to patch has/have potentially changed
-
- for ( ; hunkIt != hunks->end(); ++hunkIt )
- {
- // Do we need to insert a new hunk before this one ?
- DiffHunk* hunk = *hunkIt;
- if ( srcLineNo < hunk->sourceLineNumber() )
- {
- newHunk = new DiffHunk( srcLineNo, destLineNo, "", DiffHunk::AddedByBlend );
-
- hunks->insert( hunkIt, newHunk );
-
- newDiff = new Difference( srcLineNo, destLineNo,
- Difference::Unchanged );
-
- newHunk->add( newDiff );
-
- while ( srcLineNo < hunk->sourceLineNumber() && linesIt != lEnd )
- {
- newDiff->addSourceLine( *linesIt );
- newDiff->addDestinationLine( *linesIt );
- srcLineNo++;
- destLineNo++;
- ++linesIt;
- }
- }
-
- // Now we add the linecount difference for the hunk that follows
- int size = hunk->sourceLineCount();
-
- for ( int i = 0; i < size; ++i )
- {
- if( linesIt == lEnd ) {
- kDebug(9500) << "kompare error";
- return false;
- }
- ++linesIt;
- }
-
- srcLineNo += size;
- destLineNo += (*hunkIt)->destinationLineCount();
- }
-
- if ( linesIt != lEnd )
- {
- newHunk = new DiffHunk( srcLineNo, destLineNo, "", DiffHunk::AddedByBlend );
-
- model->addHunk( newHunk );
-
- newDiff = new Difference( srcLineNo, destLineNo, Difference::Unchanged );
-
- newHunk->add( newDiff );
-
- while ( linesIt != lEnd )
- {
- newDiff->addSourceLine( *linesIt );
- newDiff->addDestinationLine( *linesIt );
- ++linesIt;
- }
- }
-#if 0
- DifferenceList hunkDiffList = (*hunkIt)->differences();
- DifferenceListIterator diffIt = hunkDiffList.begin();
- DifferenceListIterator dEnd = hunkDiffList.end();
- kDebug(9500) << "Number of differences in hunkDiffList =" << diffList.count();
-
- DifferenceListIterator tempIt;
- Difference* diff;
-
- for ( ; diffIt != dEnd; ++diffIt )
- {
- diff = *diffIt;
- kDebug(9500) << "*(Diff it) =" << diff;
- // Check if there are lines in the original file before the difference
- // that are not yet in the diff. If so create new Unchanged diff
- if ( srcLineNo < diff->sourceLineNumber() )
- {
- newDiff = new Difference( srcLineNo, destLineNo,
- Difference::Unchanged | Difference::AddedByBlend );
- newHunk->add( newDiff );
- while ( srcLineNo < diff->sourceLineNumber() && linesIt != lEnd )
- {
-// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *linesIt;
- newDiff->addSourceLine( *linesIt );
- newDiff->addDestinationLine( *linesIt );
- srcLineNo++;
- destLineNo++;
- ++linesIt;
- }
- }
- // Now i've got to add that diff
- switch ( diff->type() )
- {
- case Difference::Unchanged:
- kDebug(8101) << "Unchanged";
- for ( int i = 0; i < diff->sourceLineCount(); i++ )
- {
- if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
- {
- kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
- kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
-
- // Do conflict resolution (well sort of)
- diff->sourceLineAt( i )->setConflictString( *linesIt );
- diff->setConflict( true );
- }
-// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *linesIt;
-// kDebug(8101) << "DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
- srcLineNo++;
- destLineNo++;
- ++linesIt;
- }
-
- tempIt = diffIt;
- --diffIt;
- diffList.remove( tempIt );
- newHunk->add( diff );
-
- break;
- case Difference::Change:
- kDebug(8101) << "Change";
-
- //QStringListConstIterator saveIt = linesIt;
-
- for ( int i = 0; i < diff->sourceLineCount(); i++ )
- {
- if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
- {
- kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
- kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
-
- // Do conflict resolution (well sort of)
- diff->sourceLineAt( i )->setConflictString( *linesIt );
- diff->setConflict( true );
- }
- srcLineNo++;
- destLineNo++;
- ++linesIt;
- }
-
- destLineNo += diff->destinationLineCount();
-
- tempIt = diffIt;
- --diffIt;
- diffList.remove( tempIt );
- newHunk->add( diff );
- newModel->addDiff( diff );
-
- break;
- case Difference::Insert:
- kDebug(8101) << "Insert";
- destLineNo += diff->destinationLineCount();
- tempIt = diffIt;
- --diffIt;
- diffList.remove( tempIt );
- newHunk->add( diff );
- newModel->addDiff( diff );
- break;
- case Difference::Delete:
- kDebug(8101) << "Delete";
- kDebug(8101) << "Number of lines in Delete:" << diff->sourceLineCount();
- for ( int i = 0; i < diff->sourceLineCount(); i++ )
- {
- if ( linesIt != lEnd && *linesIt != diff->sourceLineAt( i )->string() )
- {
- kDebug(8101) << "Conflict: SourceLine =" << srcLineNo << ":" << *linesIt;
- kDebug(8101) << "Conflict: DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
-
- // Do conflict resolution (well sort of)
- diff->sourceLineAt( i )->setConflictString( *linesIt );
- diff->setConflict( true );
- }
-
-// kDebug(8101) << "SourceLine =" << srcLineNo << ":" << *it;
-// kDebug(8101) << "DiffLine =" << diff->sourceLineNumber() + i << ":" << diff->sourceLineAt( i )->string();
- srcLineNo++;
- ++linesIt;
- }
-
- tempIt = diffIt;
- --diffIt;
- diffList.remove( tempIt );
- newHunk->add( diff );
- newModel->addDiff( diff );
- break;
- default:
- kDebug(8101) << "****, some diff type we do not know about ???";
- }
- }
- }
-#endif
-
-/*
- diffList = newModel->differences();
-
- diff = diffList.first();
- kDebug(8101) << "Count =" << diffList.count();
- for ( diff = diffList.first(); diff; diff = diffList.next() )
- {
- kDebug(8101) << "sourcelinenumber =" << diff->sourceLineNumber();
- }
-*/
-
- m_selectedModel = firstModel();
-
- m_selectedDifference = m_selectedModel->firstDifference();
-
- return true;
-}
-
-void KompareModelList::show()
-{
- kDebug(9500) << "KompareModelList::Show Number of models =" << m_models->count();
- emit modelsChanged( m_models );
- emit setSelection( m_selectedModel, m_selectedDifference );
-}
-
-void KompareModelList::clear()
-{
- if ( m_models )
- m_models->clear();
-
- emit modelsChanged( m_models );
-}
-
-void KompareModelList::swap()
-{
- QString source = m_source;
- QString destination = m_destination;
- if ( m_info.mode == Kompare::ComparingFiles )
- compareFiles( destination, source );
- else if ( m_info.mode == Kompare::ComparingDirs )
- compareDirs( destination, source );
-}
-
-bool KompareModelList::isModified() const
-{
- if ( m_noOfModified > 0 )
- return true;
- return false;
-}
-
-int KompareModelList::modelCount() const
-{
- return m_models ? m_models->count() : 0;
-}
-
-int KompareModelList::differenceCount() const
-{
- return m_selectedModel ? m_selectedModel->differenceCount() : -1;
-}
-
-int KompareModelList::appliedCount() const
-{
- return m_selectedModel ? m_selectedModel->appliedCount() : -1;
-}
-
-void KompareModelList::slotSetModified( bool modified )
-{
- kDebug(8101) << "KompareModelList::slotSetModified(" << modified << ");";
- kDebug(8101) << "Before: m_noOfModified =" << m_noOfModified;
-
- // If selectedModel emits its signal setModified it does not set the model
- // internal m_modified bool yet, it only does that after the emit.
- if ( modified && !m_selectedModel->isModified() )
- m_noOfModified++;
- else if ( !modified && m_selectedModel->isModified() )
- m_noOfModified--;
-
- kDebug(8101) << "After : m_noOfModified =" << m_noOfModified;
-
- if ( m_noOfModified < 0 )
- {
- kDebug(8101) << "Wow something is ****ed up...";
- }
- else if ( m_noOfModified == 0 )
- {
- emit setModified( false );
- }
- else // > 0 :-)
- {
- emit setModified( true );
- }
-}
-
-bool KompareModelList::setSelectedModel( DiffModel* model )
-{
- kDebug(8101) << "KompareModelList::setSelectedModel(" << model << ")";
-
- if ( model != m_selectedModel )
- {
- if ( findItem( model , m_models ) == -1 )
- return false;
- kDebug(8101) << "m_selectedModel (was) =" << m_selectedModel;
- m_modelIndex = findItem( model , m_models );
- kDebug(8101) << "m_selectedModel (is) =" << m_selectedModel;
- m_selectedModel = model;
- }
-
- updateModelListActions();
-
- return true;
-}
-
-void KompareModelList::updateModelListActions()
-{/*
- if ( m_models && m_selectedModel && m_selectedDifference )
- {
- if ( ( ( KomparePart* )parent() )->isReadWrite() )
- {
- if ( m_selectedModel->appliedCount() != m_selectedModel->differenceCount() )
- m_applyAll->setEnabled( true );
- else
- m_applyAll->setEnabled( false );
-
- if ( m_selectedModel->appliedCount() != 0 )
- m_unapplyAll->setEnabled( true );
- else
- m_unapplyAll->setEnabled( false );
-
- m_applyDifference->setEnabled( true );
- m_unApplyDifference->setEnabled( true );
- m_save->setEnabled( m_selectedModel->isModified() );
- }
- else
- {
- m_applyDifference->setEnabled ( false );
- m_unApplyDifference->setEnabled( false );
- m_applyAll->setEnabled ( false );
- m_unapplyAll->setEnabled ( false );
- m_save->setEnabled ( false );
- }
-
- m_previousFile->setEnabled ( hasPrevModel() );
- m_nextFile->setEnabled ( hasNextModel() );
- m_previousDifference->setEnabled( hasPrevDiff() );
- m_nextDifference->setEnabled ( hasNextDiff() );
- }
- else
- {
- m_applyDifference->setEnabled ( false );
- m_unApplyDifference->setEnabled ( false );
- m_applyAll->setEnabled ( false );
- m_unapplyAll->setEnabled ( false );
-
- m_previousFile->setEnabled ( false );
- m_nextFile->setEnabled ( false );
- m_previousDifference->setEnabled( false );
- m_nextDifference->setEnabled ( false );
- m_save->setEnabled ( false );
- }*/
-}
-
-bool KompareModelList::hasPrevModel() const
-{
- kDebug(8101) << "KompareModelList::hasPrevModel()";
-
- if ( m_modelIndex > 0 )
- {
-// kDebug(8101) << "has prev model";
- return true;
- }
-
-// kDebug(8101) << "doesn't have a prev model, this is the first one...";
-
- return false;
-}
-
-bool KompareModelList::hasNextModel() const
-{
- kDebug(8101) << "KompareModelList::hasNextModel()";
-
- if ( ( unsigned int )m_modelIndex < ( m_models->count() - 1 ) )
- {
-// kDebug(8101) << "has next model";
- return true;
- }
-
-// kDebug(8101) << "doesn't have a next model, this is the last one...";
- return false;
-}
-
-bool KompareModelList::hasPrevDiff() const
-{
-// kDebug(8101) << "KompareModelList::hasPrevDiff()";
- int index = m_selectedModel->diffIndex();
-
- if ( index > 0 )
- {
-// kDebug(8101) << "has prev difference in same model";
- return true;
- }
-
- if ( hasPrevModel() )
- {
-// kDebug(8101) << "has prev difference but in prev model";
- return true;
- }
-
-// kDebug(8101) << "doesn't have a prev difference, not even in the previous model because there is no previous model";
-
- return false;
-}
-
-bool KompareModelList::hasNextDiff() const
-{
-// kDebug(8101) << "KompareModelList::hasNextDiff()";
- int index = m_selectedModel->diffIndex();
-
- if ( index < ( m_selectedModel->differenceCount() - 1 ) )
- {
-// kDebug(8101) << "has next difference in same model";
- return true;
- }
-
- if ( hasNextModel() )
- {
-// kDebug(8101) << "has next difference but in next model";
- return true;
- }
-
-// kDebug(8101) << "doesn't have a next difference, not even in next model because there is no next model";
-
- return false;
-}
-
-void KompareModelList::slotActionApplyDifference()
-{
- if ( !m_selectedDifference->applied() )
- slotApplyDifference( true );
- slotNextDifference();
- updateModelListActions();
-}
-
-void KompareModelList::slotActionUnApplyDifference()
-{
- if ( m_selectedDifference->applied() )
- slotApplyDifference( false );
- slotPreviousDifference();
- updateModelListActions();
-}
-
-void KompareModelList::slotActionApplyAllDifferences()
-{
- slotApplyAllDifferences( true );
- updateModelListActions();
-}
-
-void KompareModelList::slotActionUnapplyAllDifferences()
-{
- slotApplyAllDifferences( false );
- updateModelListActions();
-}
-
-#include "komparemodellist.moc"
-
-/* vim: set ts=4 sw=4 noet: */
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/komparemodellist.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h (nonexistent)
@@ -1,72 +0,0 @@
-/***************************************************************************
- kompareprocess.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef KOMPAREPROCESS_H
-#define KOMPAREPROCESS_H
-
-#include "kompare.h"
-#include <QtCore/QProcess>
-
-class QTextCodec;
-class QTextDecoder;
-class QProcess;
-
-class DiffSettings;
-
-class KompareProcess : public QObject, public KompareFunctions
-{
- Q_OBJECT
-
-public:
- KompareProcess( DiffSettings* diffSettings, enum Kompare::DiffMode mode, const QString& source, const QString& destination, const QString& directory = QString() );
- ~KompareProcess();
-
- void start();
-
- QProcess* process();
-
- QString diffOutput() { return m_stdout; }
- QString stdOut() { return m_stdout; }
- QString stdErr() { return m_stderr; }
-
- void setEncoding( const QString& encoding );
-
-signals:
- void diffHasFinished( bool finishedNormally );
-
-protected:
- void writeDefaultCommandLine();
- void writeCommandLine();
-
-protected slots:
- void slotReceivedStdout( );
- void slotReceivedStderr( );
- void slotProcessExited( int, QProcess::ExitStatus );
-
-private:
- DiffSettings* m_diffSettings;
- enum Kompare::DiffMode m_mode;
- QString m_stdout;
- QString m_stderr;
- QTextDecoder* m_textDecoder;
- QProcess* m_proc;
- QStringList m_env;
- QStringList m_args;
- QString m_prog;
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/kompareprocess.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp (nonexistent)
@@ -1,331 +0,0 @@
-/*******************************************************************************
-**
-** Filename : levenshteintable.cpp
-** Created on : 08 november, 2003
-** Copyright : (c) 2003 Otto Bruggeman <bruggie@home.nl>
-**
-*******************************************************************************/
-
-/*******************************************************************************
-**
-** 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.
-**
-*******************************************************************************/
-
-#include "levenshteintable.h"
-#include <iostream>
-
-#include <qstring.h>
-
-#include <kdebug.h>
-#include <kglobal.h>
-
-
-#include "difference.h"
-
-using namespace Diff2;
-
-LevenshteinTable::LevenshteinTable()
- : m_width( 256 ),
- m_height( 256 ),
- m_size( m_height * m_width ),
- m_table( new unsigned int[ m_size ] ),
- m_source( 0 ),
- m_destination( 0 )
-{
-}
-
-LevenshteinTable::LevenshteinTable( unsigned int width, unsigned int height )
- : m_width( width ),
- m_height( height ),
- m_size( m_width * m_height ),
- m_table( new unsigned int[ m_size ] ),
- m_source( 0 ),
- m_destination( 0 )
-{
-}
-
-LevenshteinTable::~LevenshteinTable()
-{
- delete[] m_table;
- m_source = 0;
- m_destination = 0;
-}
-
-int LevenshteinTable::getContent( unsigned int posX, unsigned int posY ) const
-{
-// kDebug(8101) << "Width =" << m_width << ", height =" << m_height << ", posX =" << posX << ", posY =" << posY;
- return m_table[ posY * m_width + posX ];
-}
-
-int LevenshteinTable::setContent( unsigned int posX, unsigned int posY, int value )
-{
- m_table[ posY * m_width + posX ] = value;
-
- return 0;
-}
-
-bool LevenshteinTable::setSize( unsigned int width, unsigned int height )
-{
- // Set a limit of 16.7 million entries, will be about 64 MB of ram, that should be plenty
- if ( ( ( width ) * ( height ) ) > ( 256 * 256 * 256 ) )
- return false;
-
- if ( ( ( width ) * ( height ) ) > m_size )
- {
- delete[] m_table;
-
- m_size = width * height;
- m_table = new unsigned int[ m_size ];
- }
-
- m_width = width;
- m_height = height;
-
- return true;
-}
-
-void LevenshteinTable::dumpLevenshteinTable()
-{
- for ( unsigned int i = 0; i < m_height; ++i )
- {
- for ( unsigned int j = 0; j < m_width; ++j )
- {
- std::cout.width( 3 );
- std::cout << getContent( j, i );
- }
- std::cout << std::endl;
- }
-}
-
-unsigned int LevenshteinTable::createTable( DifferenceString* source, DifferenceString* destination )
-{
- m_source = source;
- m_destination = destination;
-
- QString s = ' ' + source->string(); // Optimization, so i do not have to subtract 1 from the indexes every
- QString d = ' ' + destination->string(); // single time and add 1 to the width and height of the table
-
- unsigned int m = s.length();
- unsigned int n = d.length();
-
- const QChar* sq = s.unicode();
- const QChar* dq = d.unicode();
-
- if ( m == 1 )
- return --n;
-
- if ( n == 1 )
- return --m;
-
- if ( !setSize( m, n ) )
- return 0;
-
- unsigned int i;
- unsigned int j;
-
- // initialize first row
- for ( i = 0; i < m; ++i )
- setContent( i, 0, i );
- // initialize first column
- for ( j = 0; j < n; ++j )
- setContent( 0, j, j );
-
- int cost = 0, north = 0, west = 0, northwest = 0;
-
- ushort si, dj;
- // Optimization, calculate row wise instead of column wise, wont trash the cache so much with large strings
- for ( j = 1; j < n; ++j )
- {
- dj = QString(dq[ j ]).toInt();
-
- for ( i = 1; i < m; ++i )
- {
- si = QString(sq[ i ]).toInt();
- if ( si == dj )
- cost = 0;
- else
- cost = 1;
-
- north = getContent( i, j-1 ) + 1;
- west = getContent( i-1, j ) + 1;
- northwest = getContent( i-1, j-1 ) + cost;
-
- setContent( i, j, qMin( north, qMin( west, northwest ) ) );
- }
- }
-
- return getContent( m-1, n-1 );
-}
-
-int LevenshteinTable::chooseRoute( int c1, int c2, int c3 )
-{
-// kDebug(8101) << "c1 =" << c1 << ", c2 =" << c2 << ", c3 =" << c3;
- // preference order: c2, c3, c1, hopefully this will work out for me
- if ( c2 <= c1 && c2 <= c3 )
- return 1;
-
- if ( c3 <= c2 && c3 <= c1 )
- return 2;
-
- return 0;
-}
-
-void LevenshteinTable::createListsOfMarkers()
-{
-// std::cout << source.latin1() << std::endl;
-// std::cout << destination.latin1() << std::endl;
-// dumpLevenshteinTable();
-
- unsigned int x = m_width-1;
- unsigned int y = m_height-1;
-
- Marker* c = 0;
-
- int n, nw, w, direction, currentValue;
- while ( x > 0 && y > 0 )
- {
- currentValue = getContent( x, y );
-
- nw = getContent( x - 1, y - 1 );
- n = getContent( x, y - 1 );
- w = getContent( x - 1, y );
-
- direction = chooseRoute( n, nw, w );
-
- switch ( direction )
- {
- case 0: // north
-// kDebug(8101) << "Picking north";
-// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
-
- if ( !m_destination->markerList().isEmpty() )
- c = m_destination->markerList().first();
- else
- c = 0;
-
- if ( c && c->type() == Marker::End )
- {
-// kDebug(8101) << "CurrentValue:" << currentValue;
- if ( n == currentValue )
- m_destination->prepend( new Marker( Marker::Start, y ) );
- // else: the change continues, do not do anything
- }
- else
- {
-// kDebug(8101) << "CurrentValue:" << currentValue;
- if ( n < currentValue )
- m_destination->prepend( new Marker( Marker::End, y ) );
- }
-
- --y;
- break;
- case 1: // northwest
-// kDebug(8101) << "Picking northwest";
-// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
-
- if ( !m_destination->markerList().isEmpty() )
- c = m_destination->markerList().first();
- else
- c = 0;
-
- if ( c && c->type() == Marker::End )
- {
-// kDebug(8101) << "End found: CurrentValue:" << currentValue;
- if ( nw == currentValue )
- m_destination->prepend( new Marker( Marker::Start, y ) );
- // else: the change continues, do not do anything
- }
- else
- {
-// kDebug(8101) << "CurrentValue:" << currentValue;
- if ( nw < currentValue )
- m_destination->prepend( new Marker( Marker::End, y ) );
- }
-
- if ( !m_source->markerList().isEmpty() )
- c = m_source->markerList().first();
- else
- c = 0;
-
- if ( c && c->type() == Marker::End )
- {
-// kDebug(8101) << "End found: CurrentValue:" << currentValue;
- if ( nw == currentValue )
- m_source->prepend( new Marker( Marker::Start, x ) );
- // else: the change continues, do not do anything
- }
- else
- {
-// kDebug(8101) << "CurrentValue:" << currentValue;
- if ( nw < currentValue )
- m_source->prepend( new Marker( Marker::End, x ) );
- }
-
- --y;
- --x;
- break;
- case 2: // west
-// kDebug(8101) << "Picking west";
-// kDebug(8101) << "Source[" << ( x - 1 ) << "] =" << QString( source[ x-1 ] ) << ", destination[" << ( y - 1 ) << "] =" << QString( destination[ y-1 ] );
-
- if ( !m_source->markerList().isEmpty() )
- c = m_source->markerList().first();
- else
- c = 0;
-
- if ( c && c->type() == Marker::End )
- {
-// kDebug(8101) << "End found: CurrentValue:" << currentValue;
- if ( w == currentValue )
- m_source->prepend( new Marker( Marker::Start, x ) );
- // else: the change continues, do not do anything
- }
- else
- {
-// kDebug(8101) << "CurrentValue:" << currentValue;
- if ( w < currentValue )
- m_source->prepend( new Marker( Marker::End, x ) );
- }
-
- --x;
- break;
- }
- }
-
-// kDebug(8101) << "Source string:" << m_source->string();
-// c = m_source->markerList()->first();
-// QStringList list;
-// unsigned int prevValue = 0;
-// for ( ; c; c = m_source->markerList()->next() )
-// {
-// kDebug(8101) << "Source Marker Entry : Type:" << c->type() << ", Offset:" << c->offset();
-// list.append( m_source->string().mid( prevValue, c->offset() - prevValue ) );
-// prevValue = c->offset();
-// }
-// if ( prevValue < m_source->string().length() - 1 )
-// {
-// list.append( m_source->string().mid( prevValue, m_source->string().length() - prevValue ) );
-// }
-// kDebug(8101) << "Source Resulting stringlist :" << list.join("\n");
-
-// list.clear();
-// prevValue = 0;
-
-// kDebug(8101) << "Destination string:" << m_destination->string();
-// for ( ; c; c = m_destination->markerList()->next() )
-// {
-// kDebug(8101) << "Destination Marker Entry : Type:" << c->type() << ", Offset:" << c->offset();
-// list.append( m_destination->string().mid( prevValue, c->offset() - prevValue ) );
-// prevValue = c->offset();
-// }
-// if ( prevValue < m_destination->string().length() - 1 )
-// {
-// list.append( m_destination->string().mid( prevValue, m_destination->string().length() - prevValue ) );
-// }
-// kDebug(8101) << "Destination Resulting string :" << list.join("\n");
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/levenshteintable.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp (nonexistent)
@@ -1,407 +0,0 @@
-/***************************************************************************
- diffmodel.cpp - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "diffmodel.h"
-#include <qregexp.h>
-#include <q3valuelist.h>
-
-#include <kdebug.h>
-#include <klocale.h>
-
-#include "difference.h"
-#include "diffhunk.h"
-
-using namespace Diff2;
-
-/** */
-DiffModel::DiffModel( const QString& source, const QString& destination ) :
- m_source( source ),
- m_destination( destination ),
- m_sourcePath( "" ),
- m_destinationPath( "" ),
- m_sourceFile( "" ),
- m_destinationFile( "" ),
- m_sourceTimestamp( "" ),
- m_destinationTimestamp( "" ),
- m_sourceRevision( "" ),
- m_destinationRevision( "" ),
- m_appliedCount( 0 ),
- m_modified( false ),
- m_diffIndex( 0 ),
- m_selectedDifference( 0 ),
- m_blended( false )
-{
- splitSourceInPathAndFileName();
- splitDestinationInPathAndFileName();
-}
-
-DiffModel::DiffModel() :
- m_source( "" ),
- m_destination( "" ),
- m_sourcePath( "" ),
- m_destinationPath( "" ),
- m_sourceFile( "" ),
- m_destinationFile( "" ),
- m_sourceTimestamp( "" ),
- m_destinationTimestamp( "" ),
- m_sourceRevision( "" ),
- m_destinationRevision( "" ),
- m_appliedCount( 0 ),
- m_modified( false ),
- m_diffIndex( 0 ),
- m_selectedDifference( 0 ),
- m_blended( false )
-{
-}
-
-/** */
-DiffModel::~DiffModel()
-{
-}
-
-void DiffModel::splitSourceInPathAndFileName()
-{
- int pos;
-
- if( ( pos = m_source.lastIndexOf( "/" ) ) >= 0 )
- m_sourcePath = m_source.mid( 0, pos+1 );
-
- if( ( pos = m_source.lastIndexOf( "/" ) ) >= 0 )
- m_sourceFile = m_source.mid( pos+1, m_source.length() - pos );
- else
- m_sourceFile = m_source;
-
- kDebug(8101) << m_source << "was split into" << m_sourcePath << "and" << m_sourceFile;
-}
-
-void DiffModel::splitDestinationInPathAndFileName()
-{
- int pos;
-
- if( ( pos = m_destination.lastIndexOf( "/" ) )>= 0 )
- m_destinationPath = m_destination.mid( 0, pos+1 );
-
- if( ( pos = m_destination.lastIndexOf( "/" ) ) >= 0 )
- m_destinationFile = m_destination.mid( pos+1, m_destination.length() - pos );
- else
- m_destinationFile = m_source;
-
- kDebug(8101) << m_destination << "was split into" << m_destinationPath << "and" << m_destinationFile;
-}
-
-DiffModel& DiffModel::operator=( const DiffModel& model )
-{
- if ( &model != this ) // Guard from self-assignment
- {
- m_source = model.m_source;
- m_destination = model.m_destination;
- m_sourcePath = model.m_sourcePath;
- m_sourceFile = model.m_sourceFile;
- m_sourceTimestamp = model.m_sourceTimestamp;
- m_sourceRevision = model.m_sourceRevision;
- m_destinationPath = model.m_destinationPath;
- m_destinationFile = model.m_destinationFile;
- m_destinationTimestamp = model.m_destinationTimestamp;
- m_destinationRevision = model.m_destinationRevision;
- m_appliedCount = model.m_appliedCount;
- m_modified = model.m_modified;
-
- m_diffIndex = model.m_diffIndex;
- m_selectedDifference = model.m_selectedDifference;
- }
-
- return *this;
-}
-
-bool DiffModel::operator<( const DiffModel& model )
-{
- if ( localeAwareCompareSource( model ) < 0 )
- return true;
- return false;
-}
-
-int DiffModel::localeAwareCompareSource( const DiffModel& model )
-{
- int result = m_sourcePath.localeAwareCompare( model.m_sourcePath );
-
- if ( result == 0 )
- return m_sourceFile.localeAwareCompare( model.m_sourceFile );
-
- return result;
-}
-
-QString DiffModel::recreateDiff() const
-{
- // For now we'll always return a diff in the diff format
- QString diff;
-
- // recreate header
- QString tab = QString::fromLatin1( "\t" );
- QString nl = QString::fromLatin1( "\n" );
- diff += QString::fromLatin1( "--- %1\t%2" ).arg( m_source ).arg( m_sourceTimestamp );
- if ( !m_sourceRevision.isEmpty() )
- diff += tab + m_sourceRevision;
- diff += nl;
- diff += QString::fromLatin1( "+++ %1\t%2" ).arg( m_destination ).arg( m_destinationTimestamp );
- if ( !m_destinationRevision.isEmpty() )
- diff += tab + m_destinationRevision;
- diff += nl;
-
- // recreate body by iterating over the hunks
- DiffHunkListConstIterator hunkIt = m_hunks.begin();
- DiffHunkListConstIterator hEnd = m_hunks.end();
-
- for ( ; hunkIt != hEnd; ++hunkIt )
- {
- if ((*hunkIt)->type() != DiffHunk::AddedByBlend)
- diff += (*hunkIt)->recreateHunk();
- }
-
- return diff;
-}
-
-DifferenceList* DiffModel::allDifferences()
-{
- if ( m_hunks.count() != 0 )
- {
- DiffHunkListConstIterator hunkIt = m_hunks.begin();
- DiffHunkListConstIterator hEnd = m_hunks.end();
-
- for ( ; hunkIt != hEnd; ++hunkIt )
- {
- DiffHunk* hunk = *hunkIt;
-
- DifferenceListConstIterator diffIt = hunk->differences().begin();
- DifferenceListConstIterator dEnd = hunk->differences().end();
-
- for ( ; diffIt != dEnd; ++diffIt )
- {
- m_allDifferences.append( *diffIt );
- }
- }
- return &m_allDifferences;
- }
- else
- {
- DifferenceList *diffList = new DifferenceList;
- return diffList;
- }
-}
-
-Difference* DiffModel::firstDifference()
-{
- kDebug( 8101 ) << "DiffModel::firstDifference()";
- m_diffIndex = 0;
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
-
- m_selectedDifference = m_differences[ m_diffIndex ];
-
- return m_selectedDifference;
-}
-
-Difference* DiffModel::lastDifference()
-{
- kDebug( 8101 ) << "DiffModel::lastDifference()";
- m_diffIndex = m_differences.count() - 1;
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
-
- m_selectedDifference = m_differences[ m_diffIndex ];
-
- return m_selectedDifference;
-}
-
-Difference* DiffModel::prevDifference()
-{
- kDebug( 8101 ) << "DiffModel::prevDifference()";
- if ( --m_diffIndex < m_differences.count() )
- {
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
- m_selectedDifference = m_differences[ m_diffIndex ];
- }
- else
- {
- m_selectedDifference = 0;
- m_diffIndex = 0;
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
- }
-
- return m_selectedDifference;
-}
-
-Difference* DiffModel::nextDifference()
-{
- kDebug( 8101 ) << "DiffModel::nextDifference()";
- if ( ++m_diffIndex < m_differences.count() )
- {
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
- m_selectedDifference = m_differences[ m_diffIndex ];
- }
- else
- {
- m_selectedDifference = 0;
- m_diffIndex = 0; // just for safety...
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
- }
-
- return m_selectedDifference;
-}
-
-const QString DiffModel::sourceFile() const
-{
- return m_sourceFile;
-}
-
-const QString DiffModel::destinationFile() const
-{
- return m_destinationFile;
-}
-
-const QString DiffModel::sourcePath() const
-{
- return m_sourcePath;
-}
-
-const QString DiffModel::destinationPath() const
-{
- return m_destinationPath;
-}
-
-void DiffModel::setSourceFile( const QString& path )
-{
- m_source = path;
- splitSourceInPathAndFileName();
-}
-
-void DiffModel::setDestinationFile( const QString& path )
-{
- m_destination = path;
- splitDestinationInPathAndFileName();
-}
-
-void DiffModel::setSourceTimestamp( const QString& timestamp )
-{
- m_sourceTimestamp = timestamp;
-}
-
-void DiffModel::setDestinationTimestamp( const QString& timestamp )
-{
- m_destinationTimestamp = timestamp;
-}
-
-void DiffModel::setSourceRevision( const QString& revision )
-{
- m_destinationRevision = revision;
-}
-
-void DiffModel::setDestinationRevision( const QString& revision )
-{
- m_destinationRevision = revision;
-}
-
-void DiffModel::addHunk( DiffHunk* hunk )
-{
- m_hunks.append( hunk );
-}
-
-void DiffModel::addDiff( Difference* diff )
-{
- m_differences.append( diff );
-}
-
-void DiffModel::applyDifference( bool apply )
-{
- if ( apply && !m_selectedDifference->applied() )
- m_appliedCount++;
- else if ( !apply && m_selectedDifference->applied() )
- m_appliedCount--;
-
- bool modified;
-
- // Not setting the m_modified yet so i can still query the current
- // modified status from the slot that is connected to the signal
- if ( m_appliedCount == 0 )
- modified = false;
- else
- modified = true;
-
- emit setModified( modified );
-
- m_modified = modified;
-
- m_selectedDifference->apply( apply );
-}
-
-void DiffModel::applyAllDifferences( bool apply )
-{
- bool modified;
-
- // Not setting the m_modified yet so i can still query the current
- // modified status from the slot that is connected to the signal
- if ( apply )
- {
- m_appliedCount = m_differences.count();
- modified = true;
- }
- else
- {
- m_appliedCount = 0;
- modified = false;
- }
-
- emit setModified( modified );
-
- m_modified = modified;
-
- DifferenceListIterator diffIt = m_differences.begin();
- DifferenceListIterator dEnd = m_differences.end();
-
- for ( ; diffIt != dEnd; ++diffIt )
- {
- (*diffIt)->apply( apply );
- }
-}
-
-void DiffModel::slotSetModified( bool modified )
-{
- // Not setting the m_modified yet so i can still query the current
- // modified status from the slot that is connected to the signal
- emit setModified( modified );
-
- m_modified = modified;
-}
-
-bool DiffModel::setSelectedDifference( Difference* diff )
-{
- kDebug(8101) << "diff =" << diff;
- kDebug(8101) << "m_selectedDifference =" << m_selectedDifference;
-
- if ( diff != m_selectedDifference )
- {
- if ( ( findItem( diff, m_differences ) ) == -1 )
- return false;
- // Do not set m_diffIndex if it cant be found
- m_diffIndex = findItem( diff, m_differences );
- kDebug( 8101 ) << "m_diffIndex =" << m_diffIndex;
- m_selectedDifference = diff;
- }
-
- return true;
-}
-
-#include "diffmodel.moc"
-
-/* vim: set ts=4 sw=4 noet: */
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README (nonexistent)
@@ -1 +0,0 @@
-This library is mainly a slightly modified copy from kompare's libdiff2. Maybe both should be merged to one reusable library some time.
\ No newline at end of file
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/README
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h (nonexistent)
@@ -1,57 +0,0 @@
-/**************************************************************************
-** parser.h
-** --------
-** begin : Tue Jul 30 23:53:52 2002
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef _DIFF2_PARSER_H
-#define _DIFF2_PARSER_H
-
-#include "diffmodellist.h"
-#include "kompare.h"
-
-namespace Diff2
-{
-
-class DiffModel;
-class KompareModelList;
-
-class Parser
-{
-public:
- Parser( const KompareModelList* list );
- ~Parser();
-
-public:
- DiffModelList* parse( QStringList& diffLines );
-
- enum Kompare::Generator generator() const { return m_generator; };
- enum Kompare::Format format() const { return m_format; };
-
-private:
- /** Which program was used to generate the output */
- enum Kompare::Generator determineGenerator( const QStringList& diffLines );
-
- int cleanUpCrap( QStringList& diffLines );
-
-private:
- enum Kompare::Generator m_generator;
- enum Kompare::Format m_format;
-
- const KompareModelList* m_list;
-};
-
-} // End of namespace Diff2
-
-#endif
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h (nonexistent)
@@ -1,223 +0,0 @@
-/***************************************************************************
- difference.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef DIFFERENCE_H
-#define DIFFERENCE_H
-
-#include <q3valuelist.h>
-#include <q3valuevector.h>
-
-#include <kdebug.h>
-
-#include "diffexport.h"
-
-class QString;
-
-namespace Diff2
-{
-
-class LevenshteinTable;
-
-class Marker
-{
-public:
- enum Type { Start = 0, End = 1 };
-
-public:
- Marker()
- {
- m_type = Marker::Start;
- m_offset = 0;
- }
- Marker( enum Marker::Type type, unsigned int offset )
- {
- m_type = type;
- m_offset = offset;
- }
- ~Marker() {}
-
-public:
- enum Marker::Type type() const { return m_type; }
- unsigned int offset() const { return m_offset; }
-
- void setType ( enum Marker::Type type ) { m_type = type; }
- void setOffset( unsigned int offset ) { m_offset = offset; }
-
-private:
- enum Marker::Type m_type;
- unsigned int m_offset;
-};
-
-typedef Q3ValueList<Marker*> MarkerList;
-typedef Q3ValueList<Marker*>::iterator MarkerListIterator;
-typedef Q3ValueList<Marker*>::const_iterator MarkerListConstIterator;
-
-class DifferenceString
-{
-public:
- DifferenceString()
- {
-// kDebug(8101) << "DifferenceString::DifferenceString()";
- }
- explicit DifferenceString( const QString& string, const MarkerList& markerList = MarkerList() ) :
- m_string( string ),
- m_markerList( markerList )
- {
-// kDebug(8101) << "DifferenceString::DifferenceString( " << string << ", " << markerList << " )";
- calculateHash();
- }
- DifferenceString( const DifferenceString& ds ) :
- m_string( ds.m_string ),
- m_conflict( ds.m_conflict ),
- m_hash( ds.m_hash ),
- m_markerList( ds.m_markerList )
- {
-// kDebug(8101) << "DifferenceString::DifferenceString( const DifferenceString& " << ds << " )";
- }
- ~DifferenceString() {}
-
-public:
- const QString& string() const
- {
- return m_string;
- }
- const QString& conflictString() const
- {
- return m_conflict;
- }
- const MarkerList& markerList()
- {
- return m_markerList;
- }
- void setString( const QString& string )
- {
- m_string = string;
- calculateHash();
- }
- void setConflictString( const QString& conflict )
- {
- m_conflict = conflict;
- }
- void setMarkerList( const MarkerList& markerList )
- {
- m_markerList = markerList;
- }
- void prepend( Marker* marker )
- {
- m_markerList.prepend( marker );
- }
- bool operator==( const DifferenceString& ks )
- {
- if ( m_hash != ks.m_hash )
- return false;
- return m_string == ks.m_string;
- }
-
-protected:
- void calculateHash()
- {
- unsigned short const* str = reinterpret_cast<unsigned short const*>( m_string.unicode() );
- const unsigned int len = m_string.length();
-
- m_hash = 1315423911;
-
- for ( unsigned int i = 0; i < len; i++ )
- {
- m_hash ^= ( m_hash << 5 ) + str[i] + ( m_hash >> 2 );
- }
- }
-
-private:
- QString m_string;
- QString m_conflict;
- unsigned int m_hash;
- MarkerList m_markerList;
-};
-
-typedef Q3ValueVector<DifferenceString*> DifferenceStringList;
-typedef Q3ValueVector<DifferenceString*>::iterator DifferenceStringListIterator;
-typedef Q3ValueVector<DifferenceString*>::const_iterator DifferenceStringListConstIterator;
-
-class DIFF2_EXPORT Difference
-{
-public:
- enum Type { Change, Insert, Delete, Unchanged };
-
-public:
- Difference( int sourceLineNo, int destinationLineNo, int type = Difference::Unchanged );
- ~Difference();
-
-public:
- int type() const { return m_type; };
-
- int sourceLineNumber() const { return m_sourceLineNo; }
- int destinationLineNumber() const { return m_destinationLineNo; }
-
- int sourceLineCount() const;
- int destinationLineCount() const;
-
- DifferenceString* sourceLineAt( int i ) { return m_sourceLines[ i ]; }
- DifferenceString* destinationLineAt( int i ) { return m_destinationLines[ i ]; }
-
- const DifferenceStringList sourceLines() const { return m_sourceLines; }
- const DifferenceStringList destinationLines() const { return m_destinationLines; }
-
- bool hasConflict() const
- {
- return m_conflicts;
- }
- void setConflict( bool conflicts )
- {
- m_conflicts = conflicts;
- }
-
- void apply( bool apply );
- bool applied() const { return m_applied; }
-
- void setType( int type ) { m_type = type; }
-
- void addSourceLine( const QString& line );
- void addDestinationLine( const QString& line );
-
- /** This method will calculate the differences between the individual strings and store them as Markers */
- void determineInlineDifferences();
-
- QString recreateDifference() const;
-
-private:
- int m_type;
-
- int m_sourceLineNo;
- int m_destinationLineNo;
-
- DifferenceStringList m_sourceLines;
- DifferenceStringList m_destinationLines;
-
- bool m_applied;
- bool m_conflicts;
-
- LevenshteinTable* m_table;
-};
-
-typedef Q3ValueList<Difference*> DifferenceList;
-typedef Q3ValueList<Difference*>::iterator DifferenceListIterator;
-typedef Q3ValueList<Difference*>::const_iterator DifferenceListConstIterator;
-
-} // End of namespace Diff2
-
-#endif
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/difference.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp (nonexistent)
@@ -1,725 +0,0 @@
-/**************************************************************************
-** parserbase.cpp
-** -------------------
-** begin : Sun Aug 4 15:05:35 2002
-** copyright : (C) 2002-2004 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#include "parserbase.h"
-#include <qobject.h>
-
-#include <kdebug.h>
-
-#include "diffmodel.h"
-#include "diffhunk.h"
-#include "difference.h"
-#include "komparemodellist.h"
-
-
-using namespace Diff2;
-
-ParserBase::ParserBase( const KompareModelList* list, const QStringList& diff ) :
- m_diffLines( diff ),
- m_currentModel( 0 ),
- m_models( 0 ),
- m_diffIterator( m_diffLines.begin() ),
- m_singleFileDiff( false ),
- m_list( list )
-{
-// kDebug(8101) << diff;
-// kDebug(8101) << m_diffLines;
- m_models = new DiffModelList();
-
- // used in contexthunkheader
- m_contextHunkHeader1.setPattern( "\\*{15} ?(.*)\\n" ); // capture is for function name
- m_contextHunkHeader2.setPattern( "\\*\\*\\* ([0-9]+),([0-9]+) \\*\\*\\*\\*\\n" );
- // used in contexthunkbody
- m_contextHunkHeader3.setPattern( "--- ([0-9]+),([0-9]+) ----\\n" );
-
- m_contextHunkBodyRemoved.setPattern( "- (.*)" );
- m_contextHunkBodyAdded.setPattern ( "\\+ (.*)" );
- m_contextHunkBodyChanged.setPattern( "! (.*)" );
- m_contextHunkBodyContext.setPattern( " (.*)" );
- m_contextHunkBodyLine.setPattern ( "[-\\+! ] (.*)" );
-
- // This regexp sucks... i'll see what happens
- m_normalDiffHeader.setPattern( "diff (?:(?:-|--)[a-zA-Z0-9=\\\"]+ )*(?:|-- +)(.*) +(.*)\\n" );
-
- m_normalHunkHeaderAdded.setPattern ( "([0-9]+)a([0-9]+)(|,[0-9]+)(.*)\\n" );
- m_normalHunkHeaderRemoved.setPattern( "([0-9]+)(|,[0-9]+)d([0-9]+)(.*)\\n" );
- m_normalHunkHeaderChanged.setPattern( "([0-9]+)(|,[0-9]+)c([0-9]+)(|,[0-9]+)(.*)\\n" );
-
- m_normalHunkBodyRemoved.setPattern ( "< (.*)" );
- m_normalHunkBodyAdded.setPattern ( "> (.*)" );
- m_normalHunkBodyDivider.setPattern ( "---" );
-
- m_unifiedDiffHeader1.setPattern ( "--- ([^\\t]+)\\t([^\\t]+)(?:\\t?)(.*)\\n" );
- m_unifiedDiffHeader2.setPattern ( "\\+\\+\\+ ([^\\t]+)\\t([^\\t]+)(?:\\t?)(.*)\\n" );
- m_unifiedHunkHeader.setPattern ( "@@ -([0-9]+)(|,([0-9]+)) \\+([0-9]+)(|,([0-9]+)) @@(?: ?)(.*)\\n" );
- m_unifiedHunkBodyAdded.setPattern ( "\\+(.*)" );
- m_unifiedHunkBodyRemoved.setPattern( "-(.*)" );
- m_unifiedHunkBodyContext.setPattern( " (.*)" );
- m_unifiedHunkBodyLine.setPattern ( "([-+ ])(.*)" );
-}
-
-ParserBase::~ParserBase()
-{
- if ( m_models )
- m_models = 0; // do not delete this, i pass it around...
-}
-
-enum Kompare::Format ParserBase::determineFormat()
-{
- // Write your own format detection routine damn it :)
- return Kompare::UnknownFormat;
-}
-
-DiffModelList* ParserBase::parse()
-{
- switch( determineFormat() )
- {
- case Kompare::Context :
- return parseContext();
- case Kompare::Ed :
- return parseEd();
- case Kompare::Normal :
- return parseNormal();
- case Kompare::RCS :
- return parseRCS();
- case Kompare::Unified :
- return parseUnified();
- default: // Unknown and SideBySide for now
- return 0L;
- }
-}
-
-bool ParserBase::parseContextDiffHeader()
-{
-// kDebug(8101) << "ParserBase::parseContextDiffHeader()";
- bool result = false;
-
- while ( m_diffIterator != m_diffLines.end() )
- {
- if ( !m_contextDiffHeader1.exactMatch( *(m_diffIterator)++ ) )
- {
- continue;
- }
-// kDebug(8101) << "Matched length Header1 =" << m_contextDiffHeader1.matchedLength();
-// kDebug(8101) << "Matched string Header1 =" << m_contextDiffHeader1.cap( 0 );
- if ( m_diffIterator != m_diffLines.end() && m_contextDiffHeader2.exactMatch( *m_diffIterator ) )
- {
-// kDebug(8101) << "Matched length Header2 =" << m_contextDiffHeader2.matchedLength();
-// kDebug(8101) << "Matched string Header2 =" << m_contextDiffHeader2.cap( 0 );
-
- m_currentModel = new DiffModel( m_contextDiffHeader1.cap( 1 ), m_contextDiffHeader2.cap( 1 ) );
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_currentModel->setSourceTimestamp ( m_contextDiffHeader1.cap( 2 ) );
- m_currentModel->setSourceRevision ( m_contextDiffHeader1.cap( 4 ) );
- m_currentModel->setDestinationTimestamp( m_contextDiffHeader2.cap( 2 ) );
- m_currentModel->setDestinationRevision ( m_contextDiffHeader2.cap( 4 ) );
-
- ++m_diffIterator;
- result = true;
-
- break;
- }
- else
- {
- // We're screwed, second line does not match or is not there...
- break;
- }
- // Do not inc the Iterator because the second line might be the first line of
- // the context header and the first hit was a fluke (impossible imo)
- // maybe we should return false here because the diff is broken ?
- }
-
- return result;
-}
-
-bool ParserBase::parseEdDiffHeader()
-{
- return false;
-}
-
-bool ParserBase::parseNormalDiffHeader()
-{
-// kDebug(8101) << "ParserBase::parseNormalDiffHeader()";
- bool result = false;
-
- while ( m_diffIterator != m_diffLines.end() )
- {
- if ( m_normalDiffHeader.exactMatch( *m_diffIterator ) )
- {
-// kDebug(8101) << "Matched length Header =" << m_normalDiffHeader.matchedLength();
-// kDebug(8101) << "Matched string Header =" << m_normalDiffHeader.cap( 0 );
-
- m_currentModel = new DiffModel();
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_currentModel->setSourceFile ( m_normalDiffHeader.cap( 1 ) );
- m_currentModel->setDestinationFile ( m_normalDiffHeader.cap( 2 ) );
-
- result = true;
-
- ++m_diffIterator;
- break;
- }
- else
- {
- kDebug(8101) << "No match for:" << ( *m_diffIterator );
- }
- ++m_diffIterator;
- }
-
- if ( result == false )
- {
- // Set this to the first line again and hope it is a single file diff
- m_diffIterator = m_diffLines.begin();
- m_currentModel = new DiffModel();
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_singleFileDiff = true;
- }
-
- return result;
-}
-
-bool ParserBase::parseRCSDiffHeader()
-{
- return false;
-}
-
-bool ParserBase::parseUnifiedDiffHeader()
-{
-// kDebug(8101) << "ParserBase::parseUnifiedDiffHeader()";
- bool result = false;
-
- while ( m_diffIterator != m_diffLines.end() ) // do not assume we start with the diffheader1 line
- {
- if ( !m_unifiedDiffHeader1.exactMatch( *m_diffIterator ) )
- {
- ++m_diffIterator;
- continue;
- }
-// kDebug(8101) << "Matched length Header1 =" << m_unifiedDiffHeader1.matchedLength();
-// kDebug(8101) << "Matched string Header1 =" << m_unifiedDiffHeader1.cap( 0 );
- ++m_diffIterator;
- if ( m_diffIterator != m_diffLines.end() && m_unifiedDiffHeader2.exactMatch( *m_diffIterator ) )
- {
- m_currentModel = new DiffModel( m_unifiedDiffHeader1.cap( 1 ), m_unifiedDiffHeader2.cap( 1 ) );
- QObject::connect( m_currentModel, SIGNAL( setModified( bool ) ), m_list, SLOT( slotSetModified( bool ) ) );
- m_currentModel->setSourceTimestamp( m_unifiedDiffHeader1.cap( 2 ) );
- m_currentModel->setSourceRevision( m_unifiedDiffHeader1.cap( 4 ) );
- m_currentModel->setDestinationTimestamp( m_unifiedDiffHeader2.cap( 2 ) );
- m_currentModel->setDestinationRevision( m_unifiedDiffHeader2.cap( 4 ) );
-
- ++m_diffIterator;
- result = true;
-
- break;
- }
- else
- {
- // We're screwed, second line does not match or is not there...
- break;
- }
- }
-
- return result;
-}
-
-bool ParserBase::parseContextHunkHeader()
-{
-// kDebug(8101) << "ParserBase::parseContextHunkHeader()";
-
- if ( m_diffIterator == m_diffLines.end() )
- return false;
-
- if ( !m_contextHunkHeader1.exactMatch( *(m_diffIterator) ) )
- return false; // big fat trouble, aborting...
-
- ++m_diffIterator;
-
- if ( m_diffIterator == m_diffLines.end() )
- return false;
-
- if ( !m_contextHunkHeader2.exactMatch( *(m_diffIterator) ) )
- return false; // big fat trouble, aborting...
-
- ++m_diffIterator;
-
- return true;
-}
-
-bool ParserBase::parseEdHunkHeader()
-{
- return false;
-}
-
-bool ParserBase::parseNormalHunkHeader()
-{
-// kDebug(8101) << "ParserBase::parseNormalHunkHeader()";
- if ( m_diffIterator != m_diffLines.end() )
- {
-// kDebug(8101) << "Header =" << *m_diffIterator;
- if ( m_normalHunkHeaderAdded.exactMatch( *m_diffIterator ) )
- {
- m_normalDiffType = Difference::Insert;
- }
- else if ( m_normalHunkHeaderRemoved.exactMatch( *m_diffIterator ) )
- {
- m_normalDiffType = Difference::Delete;
- }
- else if ( m_normalHunkHeaderChanged.exactMatch( *m_diffIterator ) )
- {
- m_normalDiffType = Difference::Change;
- }
- else
- return false;
-
- ++m_diffIterator;
- return true;
- }
-
- return false;
-}
-
-bool ParserBase::parseRCSHunkHeader()
-{
- return false;
-}
-
-bool ParserBase::parseUnifiedHunkHeader()
-{
-// kDebug(8101) << "ParserBase::parseUnifiedHunkHeader()";
- if( m_diffIterator == m_diffLines.end() ) return false;
-
- if ( m_unifiedHunkHeader.exactMatch( *m_diffIterator ) )
- {
- ++m_diffIterator;
- return true;
- }
- else
- {
-// kDebug(8101) << "This is not a unified hunk header :" << (*m_diffIterator);
- return false;
- }
-
-}
-
-bool ParserBase::parseContextHunkBody()
-{
-// kDebug(8101) << "ParserBase::parseContextHunkBody()";
-
- // Storing the src part of the hunk for later use
- QStringList oldLines;
- for( ; m_diffIterator != m_diffLines.end() && m_contextHunkBodyLine.exactMatch( *m_diffIterator ); ++m_diffIterator ) {
-// kDebug(8101) << "Added old line:" << *m_diffIterator;
- oldLines.append( *m_diffIterator );
- }
-
- if( !m_contextHunkHeader3.exactMatch( *m_diffIterator ) )
- return false;
-
- ++m_diffIterator;
-
- // Storing the dest part of the hunk for later use
- QStringList newLines;
- for( ; m_diffIterator != m_diffLines.end() && m_contextHunkBodyLine.exactMatch( *m_diffIterator ); ++m_diffIterator ) {
-// kDebug(8101) << "Added new line:" << *m_diffIterator;
- newLines.append( *m_diffIterator );
- }
-
- QString function = m_contextHunkHeader1.cap( 1 );
-// kDebug(8101) << "Captured function:" << function;
- int linenoA = m_contextHunkHeader2.cap( 1 ).toInt();
-// kDebug(8101) << "Source line number:" << linenoA;
- int linenoB = m_contextHunkHeader3.cap( 1 ).toInt();
-// kDebug(8101) << "Dest line number:" << linenoB;
-
- DiffHunk* hunk = new DiffHunk( linenoA, linenoB, function );
-
- m_currentModel->addHunk( hunk );
-
- QStringList::Iterator oldIt = oldLines.begin();
- QStringList::Iterator newIt = newLines.begin();
-
- Difference* diff;
- while( oldIt != oldLines.end() || newIt != newLines.end() )
- {
- if( oldIt != oldLines.end() && m_contextHunkBodyRemoved.exactMatch( *oldIt ) )
- {
-// kDebug(8101) << "Delete:";
- diff = new Difference( linenoA, linenoB );
- diff->setType( Difference::Delete );
- m_currentModel->addDiff( diff );
-// kDebug(8101) << "Difference added";
- hunk->add( diff );
- for( ; oldIt != oldLines.end() && m_contextHunkBodyRemoved.exactMatch( *oldIt ); ++oldIt )
- {
-// kDebug(8101) << "" << m_contextHunkBodyRemoved.cap( 1 );
- diff->addSourceLine( m_contextHunkBodyRemoved.cap( 1 ) );
- linenoA++;
- }
- }
- else if( newIt != newLines.end() && m_contextHunkBodyAdded.exactMatch( *newIt ) )
- {
-// kDebug(8101) << "Insert:";
- diff = new Difference( linenoA, linenoB );
- diff->setType( Difference::Insert );
- m_currentModel->addDiff( diff );
-// kDebug(8101) << "Difference added";
- hunk->add( diff );
- for( ; newIt != newLines.end() && m_contextHunkBodyAdded.exactMatch( *newIt ); ++newIt )
- {
-// kDebug(8101) << "" << m_contextHunkBodyAdded.cap( 1 );
- diff->addDestinationLine( m_contextHunkBodyAdded.cap( 1 ) );
- linenoB++;
- }
- }
- else if( ( oldIt == oldLines.end() || m_contextHunkBodyContext.exactMatch( *oldIt ) ) &&
- ( newIt == newLines.end() || m_contextHunkBodyContext.exactMatch( *newIt ) ) )
- {
-// kDebug(8101) << "Unchanged:";
- diff = new Difference( linenoA, linenoB );
- // Do not add this diff with addDiff to the model... no unchanged differences allowed in there...
- diff->setType( Difference::Unchanged );
- hunk->add( diff );
- while( ( oldIt == oldLines.end() || m_contextHunkBodyContext.exactMatch( *oldIt ) ) &&
- ( newIt == newLines.end() || m_contextHunkBodyContext.exactMatch( *newIt ) ) &&
- ( oldIt != oldLines.end() || newIt != newLines.end() ) )
- {
- QString l;
- if( oldIt != oldLines.end() )
- {
- l = m_contextHunkBodyContext.cap( 1 );
-// kDebug(8101) << "old:" << l;
- ++oldIt;
- }
- if( newIt != newLines.end() )
- {
- l = m_contextHunkBodyContext.cap( 1 );
-// kDebug(8101) << "new:" << l;
- ++newIt;
- }
- diff->addSourceLine( l );
- diff->addDestinationLine( l );
- linenoA++;
- linenoB++;
- }
- }
- else if( ( oldIt != oldLines.end() && m_contextHunkBodyChanged.exactMatch( *oldIt ) ) ||
- ( newIt != newLines.end() && m_contextHunkBodyChanged.exactMatch( *newIt ) ) )
- {
-// kDebug(8101) << "Changed:";
- diff = new Difference( linenoA, linenoB );
- diff->setType( Difference::Change );
- m_currentModel->addDiff( diff );
-// kDebug(8101) << "Difference added";
- hunk->add( diff );
- while( oldIt != oldLines.end() && m_contextHunkBodyChanged.exactMatch( *oldIt ) )
- {
-// kDebug(8101) << "" << m_contextHunkBodyChanged.cap( 1 );
- diff->addSourceLine( m_contextHunkBodyChanged.cap( 1 ) );
- linenoA++;
- ++oldIt;
- }
- while( newIt != newLines.end() && m_contextHunkBodyChanged.exactMatch( *newIt ) )
- {
-// kDebug(8101) << "" << m_contextHunkBodyChanged.cap( 1 );
- diff->addDestinationLine( m_contextHunkBodyChanged.cap( 1 ) );
- linenoB++;
- ++newIt;
- }
- }
- else
- return false;
- diff->determineInlineDifferences();
- }
-
- return true;
-}
-
-bool ParserBase::parseEdHunkBody()
-{
- return false;
-}
-
-bool ParserBase::parseNormalHunkBody()
-{
-// kDebug(8101) << "ParserBase::parseNormalHunkBody";
-
- QString type;
-
- int linenoA = 0, linenoB = 0;
-
- if ( m_normalDiffType == Difference::Insert )
- {
- linenoA = m_normalHunkHeaderAdded.cap( 1 ).toInt();
- linenoB = m_normalHunkHeaderAdded.cap( 2 ).toInt();
- }
- else if ( m_normalDiffType == Difference::Delete )
- {
- linenoA = m_normalHunkHeaderRemoved.cap( 1 ).toInt();
- linenoB = m_normalHunkHeaderRemoved.cap( 3 ).toInt();
- }
- else if ( m_normalDiffType == Difference::Change )
- {
- linenoA = m_normalHunkHeaderChanged.cap( 1 ).toInt();
- linenoB = m_normalHunkHeaderChanged.cap( 3 ).toInt();
- }
-
- DiffHunk* hunk = new DiffHunk( linenoA, linenoB );
- m_currentModel->addHunk( hunk );
- Difference* diff = new Difference( linenoA, linenoB );
- hunk->add( diff );
- m_currentModel->addDiff( diff );
-
- diff->setType( m_normalDiffType );
-
- if ( m_normalDiffType == Difference::Change || m_normalDiffType == Difference::Delete )
- for( ; m_diffIterator != m_diffLines.end() && m_normalHunkBodyRemoved.exactMatch( *m_diffIterator ); ++m_diffIterator )
- {
-// kDebug(8101) << "Line =" << *m_diffIterator;
- diff->addSourceLine( m_normalHunkBodyRemoved.cap( 1 ) );
- }
- if ( m_normalDiffType == Difference::Change )
- if( m_diffIterator != m_diffLines.end() && m_normalHunkBodyDivider.exactMatch( *m_diffIterator ) )
- {
-// kDebug(8101) << "Line =" << *m_diffIterator;
- ++m_diffIterator;
- }
- else
- return false;
- if ( m_normalDiffType == Difference::Insert || m_normalDiffType == Difference::Change )
- for( ; m_diffIterator != m_diffLines.end() && m_normalHunkBodyAdded.exactMatch( *m_diffIterator ); ++m_diffIterator )
- {
-// kDebug(8101) << "Line =" << *m_diffIterator;
- diff->addDestinationLine( m_normalHunkBodyAdded.cap( 1 ) );
- }
-
- return true;
-}
-
-bool ParserBase::parseRCSHunkBody()
-{
- return false;
-}
-
-bool ParserBase::matchesUnifiedHunkLine( QString line ) const
-{
- static const QChar context( ' ' );
- static const QChar added ( '+' );
- static const QChar removed( '-' );
-
- QChar first = line[0];
-
- return ( first == context || first == added || first == removed );
-}
-
-bool ParserBase::parseUnifiedHunkBody()
-{
-// kDebug(8101) << "ParserBase::parseUnifiedHunkBody";
-
- int linenoA = 0, linenoB = 0;
-
- // Fetching the stuff we need from the hunkheader regexp that was parsed in parseUnifiedHunkHeader();
- linenoA = m_unifiedHunkHeader.cap( 1 ).toInt();
- linenoB = m_unifiedHunkHeader.cap( 4 ).toInt();
- QString function = m_unifiedHunkHeader.cap( 7 );
- for ( int i = 0; i < 9; i++ )
- {
-// kDebug(8101) << "Capture" << i << ":" << m_unifiedHunkHeader.cap( i );
- }
-
- DiffHunk* hunk = new DiffHunk( linenoA, linenoB, function );
- m_currentModel->addHunk( hunk );
-
- const QStringList::ConstIterator m_diffLinesEnd = m_diffLines.end();
-
- const QString context = QString( " " );
- const QString added = QString( "+" );
- const QString removed = QString( "-" );
-
- while( m_diffIterator != m_diffLinesEnd && matchesUnifiedHunkLine( *m_diffIterator ) )
- {
- Difference* diff = new Difference( linenoA, linenoB );
- hunk->add( diff );
-
- if( (*m_diffIterator).startsWith( context ) )
- { // context
- for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( context ); ++m_diffIterator )
- {
- diff->addSourceLine( QString( *m_diffIterator ).remove( 0, 1 ) );
- diff->addDestinationLine( QString( *m_diffIterator ).remove( 0, 1 ) );
- linenoA++;
- linenoB++;
- }
- }
- else
- { // This is a real difference, not context
- for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( removed ); ++m_diffIterator )
- {
- diff->addSourceLine( QString( *m_diffIterator ).remove( 0, 1 ) );
- linenoA++;
- }
- for( ; m_diffIterator != m_diffLinesEnd && (*m_diffIterator).startsWith( added ); ++m_diffIterator )
- {
- diff->addDestinationLine( QString( *m_diffIterator ).remove( 0, 1 ) );
- linenoB++;
- }
- if ( diff->sourceLineCount() == 0 )
- {
- diff->setType( Difference::Insert );
-// kDebug(8101) << "Insert difference";
- }
- else if ( diff->destinationLineCount() == 0 )
- {
- diff->setType( Difference::Delete );
-// kDebug(8101) << "Delete difference";
- }
- else
- {
- diff->setType( Difference::Change );
-// kDebug(8101) << "Change difference";
- }
- diff->determineInlineDifferences();
- m_currentModel->addDiff( diff );
- }
- }
-
- return true;
-}
-
-DiffModelList* ParserBase::parseContext()
-{
- while ( parseContextDiffHeader() )
- {
- while ( parseContextHunkHeader() )
- parseContextHunkBody();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- m_models->sort();
-
- if ( m_models->count() > 0 )
- {
- return m_models;
- }
- else
- {
- delete m_models;
- return 0L;
- }
-}
-
-DiffModelList* ParserBase::parseEd()
-{
- while ( parseEdDiffHeader() )
- {
- while ( parseEdHunkHeader() )
- parseEdHunkBody();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- m_models->sort();
-
- if ( m_models->count() > 0 )
- {
- return m_models;
- }
- else
- {
- delete m_models;
- return 0L;
- }
-}
-
-DiffModelList* ParserBase::parseNormal()
-{
- while ( parseNormalDiffHeader() )
- {
- while ( parseNormalHunkHeader() )
- parseNormalHunkBody();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- if ( m_singleFileDiff )
- {
- while ( parseNormalHunkHeader() )
- parseNormalHunkBody();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- m_models->sort();
-
- if ( m_models->count() > 0 )
- {
- return m_models;
- }
- else
- {
- delete m_models;
- return 0L;
- }
-}
-
-DiffModelList* ParserBase::parseRCS()
-{
- while ( parseRCSDiffHeader() )
- {
- while ( parseRCSHunkHeader() )
- parseRCSHunkBody();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- m_models->sort();
-
- if ( m_models->count() > 0 )
- {
- return m_models;
- }
- else
- {
- delete m_models;
- return 0L;
- }
-}
-
-DiffModelList* ParserBase::parseUnified()
-{
- while ( parseUnifiedDiffHeader() )
- {
- while ( parseUnifiedHunkHeader() )
- parseUnifiedHunkBody();
-// kDebug(8101) << "New model ready to be analyzed...";
-// kDebug(8101) << "differenceCount() ==" << m_currentModel->differenceCount();
- if ( m_currentModel->differenceCount() > 0 )
- m_models->append( m_currentModel );
- }
-
- m_models->sort();
-
- if ( m_models->count() > 0 )
- {
- return m_models;
- }
- else
- {
- delete m_models;
- return 0L;
- }
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/parserbase.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h (nonexistent)
@@ -1,43 +0,0 @@
-/**************************************************************************
-** perforceparser.h
-** -------------------
-** begin : Sun Sep 8 20:58:59 2002
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef _PERFORCE_PARSER_H
-#define _PERFORCE_PARSER_H
-
-#include "parserbase.h"
-
-namespace Diff2
-{
-
-class PerforceParser : public ParserBase
-{
-public:
- PerforceParser( const KompareModelList* list, const QStringList& diff );
- virtual ~PerforceParser();
-
-protected:
- virtual bool parseContextDiffHeader();
- virtual bool parseNormalDiffHeader();
- virtual bool parseRCSDiffHeader();
- virtual bool parseUnifiedDiffHeader();
-
-protected:
- virtual enum Kompare::Format determineFormat();
-};
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/perforceparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h (nonexistent)
@@ -1,66 +0,0 @@
-/***************************************************************************
- diffsettings.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef DIFFSETTINGS_H
-#define DIFFSETTINGS_H
-
-#include <qstringlist.h>
-#include <qwidget.h>
-
-#include "kompare.h"
-#include "settingsbase.h"
-
-#include "diffexport.h"
-
-class DIFF2_EXPORT DiffSettings : public SettingsBase
-{
-Q_OBJECT
-public:
- DiffSettings( QWidget* parent );
- virtual ~DiffSettings();
-public:
- // some virtual functions that will be overloaded from the base class
- virtual void loadSettings( KConfig* config );
- virtual void saveSettings( KConfig* config );
-
-public:
- QString m_diffProgram;
- int m_linesOfContext;
- Kompare::Format m_format;
- bool m_largeFiles; // -H
- bool m_ignoreWhiteSpace; // -b
- bool m_ignoreAllWhiteSpace; // -w
- bool m_ignoreEmptyLines; // -B
- bool m_ignoreChangesDueToTabExpansion; // -E
- bool m_createSmallerDiff; // -d
- bool m_ignoreChangesInCase; // -i
- bool m_showCFunctionChange; // -p
- bool m_convertTabsToSpaces; // -t
- bool m_ignoreRegExp; // -I
- QString m_ignoreRegExpText; // the RE for -I
- QStringList m_ignoreRegExpTextHistory;
- bool m_recursive; // -r
- bool m_newFiles; // -N
-// bool m_allText; // -a
- bool m_excludeFilePattern; // -x
- QStringList m_excludeFilePatternList; // The list of patterns for -x
- bool m_excludeFilesFile; // -X
- QString m_excludeFilesFileURL; // The filename to -X
- QStringList m_excludeFilesFileHistoryList; // The history list of filenames
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffsettings.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h (nonexistent)
@@ -1,175 +0,0 @@
-/***************************************************************************
- diffmodel.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef DIFFMODEL_H
-#define DIFFMODEL_H
-
-#include <qobject.h>
-#include <qstringlist.h>
-
-#include "diffhunk.h"
-#include "kompare.h"
-
-#include "diffexport.h"
-
-namespace Diff2
-{
-
- template<class Container, class Item>
- int findItem( const Item& item, const Container* container ) {
- int i = 0;
- foreach( Item it, *container ) {
- if( it == item )
- return i;
- i++;
- }
- return -1;
- }
-
-template<class Pointer>
-int findItem( const Pointer* item, const DifferenceList& container ) {
- int i = 0;
- foreach( Difference* it, container ) {
- if( it == item )
- return i;
- i++;
- }
- return -1;
-}
-
-class DiffHunk;
-class Difference;
-
-class DIFF2_EXPORT DiffModel : public QObject
-{
-Q_OBJECT
-public:
-
- DiffModel( const QString& srcBaseURL, const QString& destBaseURL );
- DiffModel();
- DiffModel( const DiffModel& ) : QObject() {};
- ~DiffModel();
-
- int parseDiff( enum Kompare::Format format, const QStringList& list );
-
- QString recreateDiff() const;
-
- int hunkCount() const { return m_hunks.count(); }
- int differenceCount() const { return m_differences.count(); }
- int appliedCount() const { return m_appliedCount; }
-
- DiffHunk* hunkAt( int i ) { return *( m_hunks.at( i ) ); }
- const Difference* differenceAt( int i ) { return *( m_differences.at( i ) ); }
-
- DiffHunkList* hunks() { return &m_hunks; }
- const DiffHunkList* hunks() const { return &m_hunks; }
- DifferenceList* differences() { return &m_differences; }
- const DifferenceList* differences() const { return &m_differences; }
-
- DifferenceList* allDifferences();
-
- int findDifference( Difference* diff ) const {
- return findItem( diff, m_differences );
- }
- //return m_differences.( diff ); }
-
- Difference* firstDifference();
- Difference* lastDifference();
- Difference* prevDifference();
- Difference* nextDifference();
-
- const QString source() const { return m_source; }
- const QString destination() const { return m_destination; }
- const QString sourceFile() const;
- const QString destinationFile() const;
- const QString sourcePath() const;
- const QString destinationPath() const;
- const QString sourceTimestamp() const { return m_sourceTimestamp; }
- const QString destinationTimestamp() const { return m_destinationTimestamp; }
- const QString sourceRevision() const { return m_sourceRevision; }
- const QString destinationRevision() const { return m_destinationRevision; }
-
- void setSourceFile( const QString& path );
- void setDestinationFile( const QString& path );
- void setSourceTimestamp( const QString& timestamp );
- void setDestinationTimestamp( const QString& timestamp );
- void setSourceRevision( const QString& revision );
- void setDestinationRevision( const QString& revision );
-
- void addHunk( DiffHunk* hunk );
- void addDiff( Difference* diff );
- bool isModified() const { return m_modified; }
-
- const int diffIndex( void ) const { return m_diffIndex; }
- void setDiffIndex( int diffIndex ) { m_diffIndex = diffIndex; }
-
- void applyDifference( bool apply );
- void applyAllDifferences( bool apply );
-
- bool setSelectedDifference( Difference* diff );
-
- DiffModel& operator=( const DiffModel& model );
- bool operator<( const DiffModel& model );
-
- int localeAwareCompareSource( const DiffModel& model );
-
- bool isBlended() const { return m_blended; }
- void setBlended( bool blended ) { m_blended = blended; }
-
-signals:
- void setModified( bool modified );
-
-public slots:
- void slotSetModified( bool modified );
-
-private:
- void splitSourceInPathAndFileName();
- void splitDestinationInPathAndFileName();
-
-private:
- QString m_source;
- QString m_destination;
-
- QString m_sourcePath;
- QString m_destinationPath;
-
- QString m_sourceFile;
- QString m_destinationFile;
-
- QString m_sourceTimestamp;
- QString m_destinationTimestamp;
-
- QString m_sourceRevision;
- QString m_destinationRevision;
-
- DiffHunkList m_hunks;
- DifferenceList m_differences;
- DifferenceList m_allDifferences;
-
- int m_appliedCount;
- bool m_modified;
-
- unsigned int m_diffIndex;
- Difference* m_selectedDifference;
-
- bool m_blended;
-};
-
-} // End of namespace Diff2
-
-#endif
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h (nonexistent)
@@ -1,40 +0,0 @@
-/***************************************************************************
- settingsbase.h - description
- -------------------
- begin : Sun Mar 4 2001
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
- copyright : (C) 2001-2003 John Firebaugh <jfirebaugh@kde.org>
-****************************************************************************/
-
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef SETTINGSBASE_H
-#define SETTINGSBASE_H
-
-#include <qobject.h>
-
-#include "kompare.h"
-
-class QWidget;
-class KConfig;
-
-class SettingsBase : public QObject
-{
-Q_OBJECT
-public:
- SettingsBase( QWidget* parent );
- ~SettingsBase();
-
-public:
- virtual void loadSettings( KConfig* config );
- virtual void saveSettings( KConfig* config );
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/settingsbase.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h (nonexistent)
@@ -1,37 +0,0 @@
-/**************************************************************************
-** diffparser.h
-** -----------------
-** begin : Sun Aug 4 15:05:35 2002
- copyright : (C) 2001-2003 Otto Bruggeman <otto.bruggeman@home.nl>
-**
-***************************************************************************/
-/***************************************************************************
-**
-** 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.
-**
-***************************************************************************/
-
-#ifndef _DIFF_PARSER_H
-#define _DIFF_PARSER_H
-
-#include "parserbase.h"
-
-namespace Diff2
-{
-
-class DiffParser : public ParserBase
-{
-public:
- DiffParser( const KompareModelList* list, const QStringList& diff );
- virtual ~DiffParser();
-
-protected:
- virtual enum Kompare::Format determineFormat();
-};
-
-} // End of namespace Diff2
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2/diffexport.h (nonexistent)
@@ -1,37 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef DIFFEXPORT_H
-#define DIFFEXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-#ifndef DIFF2_EXPORT
-# ifdef MAKE_DIFF2_LIB
-# define DIFF2_EXPORT KDE_EXPORT
-# else
-# define DIFF2_EXPORT KDE_IMPORT
-# endif
-#endif
-
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2 (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2 (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/libdiff2
___________________________________________________________________
Deleted: svn:ignore
## -1,8 +0,0 ##
-*.moc
-.libs
-CMakeFiles
-DartTestfile.txt
-Makefile
-Makefile.in
-cmake_install.cmake
-install_icons.cmake
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h (nonexistent)
@@ -1,223 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef DYNAMICTEXT_H
-#define DYNAMICTEXT_H
-#include <string>
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/split_member.hpp>
-
-typedef std::string String;
-
-#include "../network/crossmap.h"
-#include "../network/safesharedptr.h"
-#include "../network/weaksafesharedptr.h"
-#include "vectortimestamp.h"
-#include "offsetutils.h"
-
-#include "dynamictextexport.h"
-#include "dynamictexthelpers.h"
-#include "flexibletext.h"
-using namespace Tree;
-
-#define INVALID_POSITION -1000000
-
-struct DYNAMICTEXT_EXPORT OffsetRequest {
- VectorTimestamp from;
- VectorTimestamp to;
- OffsetRequest( const VectorTimestamp& f, const VectorTimestamp& t ) : from(f), to(t) {
- }
- bool operator == ( const OffsetRequest& rhs ) const {
- return from == rhs.from && to == rhs.to;
- }
-};
-
-namespace __gnu_cxx {
-template<>
-struct hash<OffsetRequest> {
- size_t operator () ( const OffsetRequest& req ) const {
- return req.from.hash() + 3*req.to.hash();
- }
-};
-}
-
-/** DynamicText is a class that manages a dynamic document that is
- * created by an arbitrary count of parallel sources by timestamped replacements.
- *
- * It allows to create any state that is possible without conflicts(allows for example
- * to undo all changes done by one user, or even only specific changes by disabling them
- * one for one.)
- *
- * currently, every function may throw DynamicTextError on problems
- * */
-class DYNAMICTEXT_EXPORT DynamicText : public SafeShared {
-
- public:
- typedef std::string String;
-
- typedef SumTree::FlexibleText<String> Text;
-
- /**
- * @param initialState the state which will be used as zero-state.
- * */
- explicit DynamicText( const VectorTimestamp& initialState = VectorTimestamp(), const String& initialText = String() );
-
- /**Does the replacement precisely, considering the timestamp. Jumps back to the current state after inserting.
- * @param stamp The timestamp in whose context the replacement has to be done
- * @param replacement The replacement to do in the given timestamp. It will be stored.. */
- bool insert( const VectorTimestamp& stamp, const SimpleReplacement& replacement );
-
- /**Inserts the replacement in the current context, using the given index, and returning the resulting identifying timestamp.
- * */
- VectorTimestamp insert( uint index, const SimpleReplacement& replacement );
-
- /**The current state the text is in
- * */
- VectorTimestamp state() const;
-
- /**The highest state possible
- * */
- VectorTimestamp tailState() const;
-
- VectorTimestamp initialState() const;
-
- const Text& text() const;
-
- const String& initialText() const;
- /**
- * @param state The state which the text should have after the change. The default-parameter changes to the current state.
- * If force is enabled, conflicts will be ignored instead of stopping.(The resulting text may be damaged)
- */
- bool changeState( const VectorTimestamp& state = VectorTimestamp(), bool force = false );
-
- /**
- * Removes everything above the current state.
- * */
- void cut();
-
- /**rewinds to a position that is smaller/same than state in every index
- * @param state the state of the document will be smaller than that state
- * */
- bool rewind( const VectorTimestamp& state );
- ///The given state must be bigger/same than the current state in every stamp
- bool advance( const VectorTimestamp& state );
-
- void dump() const;
-
- /** @return the first replacement with the given primary index, or zero */
- ReplacementPointer first( uint index ) const;
-
- /** @return the first replacement with the given primary index, that is currently not applied to the text(its primary stamp is higher than the current state's stamp on that index), or zero */
- ReplacementPointer firstUnapplied( uint index ) const;
-
- /** @return the last replacement with the given primary index, or zero */
- ReplacementPointer last( uint index ) const;
-
- /** @return the last replacement with the given primary index, that is currently applied to the text(its primary stamp is same as the current state's stamp on that index), or zero */
- ReplacementPointer lastApplied( uint index ) const;
-
- /**
- * @return the highest stamp with that index
- * */
- Timestamp highestStamp( uint index ) const;
-
- /**Returns the internal replacement-objects that can be used for example to disable
- * a single replacement. This is dangerous, they should not be altered.
- * @param primaryIndex index(user?)
- * @param stamp timestamp for that index
- * */
- ReplacementPointer replacement( uint primaryIndex, Timestamp stamp );
-
- template<class Archive>
- void load( Archive& arch, const uint version ) {
- standardSerialize( arch, version );
- m_allReplacements.clear();
- for( uint a = 0; a < m_applied.size(); a++ ) {
- ReplacementPointer p = m_applied[0].first;
- if( p == 0 ) p = m_unApplied[0].first;
- while( p != 0 ) {
- hashReplacement( p );
- p = p->next();
- }
- }
- }
-
- template<class Archive>
- void save( Archive& arch, const uint version ) const {
- const_cast<DynamicText*>( this ) ->standardSerialize( arch, version );
- }
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-
- private:
- template<class Archive>
- void standardSerialize( Archive& arch, const uint ) {
- arch & m_text;
- arch & m_state;
- arch & m_initialState;
- arch & m_currentOffset;
- arch & m_dummy;
- arch & m_applied;
- arch & m_unApplied;
- arch & m_initialText;
- }
-
- VectorTimestamp insertInternal( uint index, const SimpleReplacement& replacement );
-
- bool changeStateInternal( const VectorTimestamp& state = VectorTimestamp(), bool force = false );
-
- bool rewindInternal( const VectorTimestamp& state );
- ///The given state must be bigger/same than the current state in every stamp
- bool advanceInternal( const VectorTimestamp& state );
-
- ///The following are notification-functions that can be overridden by derived classes
- ///To get notified about exact string-changes you can register a notifier to the FlexibleText returned by text().
- virtual void notifyInserted( const ReplacementPointer& rep );
- virtual void notifyStateChanged();
-
- ///@todo check which keys are really necessary
- BIND_LIST_3( ReplacementKeys, WeakReplacementPointer, VectorTimestamp, ReplacementId )
- typedef Utils::CrossMap< WeakReplacementPointer, ReplacementKeys > ReplacementSet;
- ReplacementSet m_allReplacements;
- friend class Advancer;
-
- ///This contains the chains from the beginning until(including) the last item that is applied.
- std::vector<ReplacementChain> m_applied;
- ///This contains the chains that were temporarily unapplied
- std::vector<ReplacementChain> m_unApplied;
-
- typedef __gnu_cxx::hash_map< OffsetRequest, OffsetMap > OffsetCache;
- OffsetCache m_offsetCache;
-
- Text m_text;
- String m_initialText;
- VectorTimestamp m_state;
- VectorTimestamp m_initialState;
- OffsetMap m_currentOffset; ///This offset-map represents all replacements that should have been applied(according to m_state), but are not.
-
- void hashReplacement( const ReplacementPointer& rep );
- void unHashReplacement( const ReplacementPointer& rep );
-
- ///Returns the offset from the 'from' position to the 'to' one. If position is set, all replacements that are behind that position(given in from-space) will be excluded while computation.
- OffsetMap offset( VectorTimestamp from, VectorTimestamp to, int position = INVALID_POSITION );
-
- ReplacementPointer m_dummy;
-
- ///Changes the state to the newest one available
- bool toTail();
-};
-
-typedef SharedPtr<DynamicText, BoostSerialization> DynamicTextPointer;
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp (nonexistent)
@@ -1,707 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "sumtree.h"
-#include <string>
-#include <sstream>
-#include <algorithm>
-#include "verify.h"
-#include <limits.h>
-
-///Must be less than SPLIT_NODES_THRESHOLD and more than JOIN_NODES_THRESHOLD
-#define PREFERRED_NODES 4
-
-#define SPLIT_NODES_THRESHOLD 8
-
-///Must be less than PREFERRED_NODES
-#define JOIN_NODES_THRESHOLD 2
-
-namespace SumTree {
-
-void mult( ostream& os, int count, const char* c ) {
- for ( int a = 0; a < count; a++ )
- os << c;
-}
-
-Node::Node( bool isLeaf, Node* parent ) : parent_( parent ), nodeCount_( 0 ), sum_( 0 ), indexCount_( 0 ), isLeaf_( isLeaf ) {}
-
-Node* Node::makeOwn( Node* parent ) {
- //Node * myParent = parent_ get();
- if ( _Shared_count() == 1 ) {
- parent_ = parent;
- return this;
- }
-
- return ( new Node( *this ) ) ->setParent( parent );
-}
-
-Node* Node::setParent( Node* parent ) {
- //DYN_VERIFY_SAME( parent, 0 ); //reactive if WeakSharedPtr is used again
-
- parent_ = parent;
- return this;
-}
-
-int Map::sum( int index ) const {
- return tree_->sum( index );
-}
-
-int Map::sum() const {
- return tree_->sum();
-}
-
-bool Map::hasIndex( int index ) const {
- return tree_->hasIndex( index );
-}
-
-void Map::indexAndSum( int sum, IndexAndSum& targ ) const {
- targ.index = 0;
- targ.sum = 0;
- tree_->indexAndSum( sum, targ );
-}
-
-int Map::index( int sum ) const {
- return tree_->index( sum );
-}
-
-Map::Map( const SumVector& summands ) {
- tree_ = new Node( false, 0 );
- int cnt = build( summands.begin(), summands.end(), tree_ );
- DYN_VERIFY_SAME( (int)cnt, (int)summands.size() );
-}
-
-Map::~Map() {}
-
-Map::Map( const Map& rhs ) : WeakShared(), tree_ ( new Node( *rhs.tree_ ) ) {}
-
-Map& Map::operator = ( const Map& rhs ) {
- tree_ = new Node( *rhs.tree_ );
- return *this;
-}
-
-void Node::addNode( Node* node ) {
- nodes_.push_back( node );
- ++nodeCount_;
-}
-
-bool Node::hasIndex( int indicesNeeded ) const {
- ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it != nodes_.end() ) {
- ///Ask the next one for the summ
- return ( *it ) ->hasIndex( indicesNeeded );
- }
-
- if( !isRange() )
- if( indicesNeeded == 0 ) return true;
- else
- if( indicesNeeded < indexCount_ ) return true;
-
- return false;
-}
-
-int Node::indexValue( int indicesNeeded ) const {
- ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it != nodes_.end() ) {
- ///Ask the next one for the summ
- return ( *it ) ->indexValue( indicesNeeded );
- }
-
- if( !isRange() ) {
- DYN_VERIFY_SAME( indicesNeeded, 0 );
- return sum_;
- } else {
- DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
- return sum_ / indexCount_;
- }
-}
-
-int Node::setIndexValue( int indicesNeeded, int value ) {
- ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it != nodes_.end() ) {
- ///Ask the next one for the summ
- ( *it ) = ( *it ) ->makeOwn( this );
- return ( *it ) ->setIndexValue( indicesNeeded, value );
- }
-
- if( !isRange() ) {
- DYN_VERIFY_SAME( indicesNeeded, 0 );
- DYN_VERIFY( isLeaf_ );
-
- int ret = sum_;
- update( value - ret, 0 );
- return ret;
- } else {
- DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
- ///It is a Range, split it up into two new ranges and one normal value-node which we can change.
- int eachValue = sum_ / indexCount_;
- if( eachValue == value ) return value; ///No need to split up
- Node * n = new Node( true, this );
- update( -eachValue, -1 );
- splitRange( indicesNeeded, n );
- n->update( value, 1 );
- updateStructure();
- return eachValue;
- }
-}
-
-int Node::changeIndexValue( int indicesNeeded, int value ) {
- ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- ListType::iterator end = nodes_.end();
-
- for ( ; it != end && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it != end ) {
- NodePointer& n( *it );
- ///Ask the next one for the summ
- n = n->makeOwn( this );
- return n->changeIndexValue( indicesNeeded, value );
- }
-
- if( !isRange() ) {
- DYN_VERIFY_SAME( indicesNeeded, 0 );
- DYN_VERIFY( isLeaf_ );
-
- update( value, 0 );
- return sum_;
- } else {
- DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
- ///It is a Range, split it into two new ranges and one normal value-node which we can change.
- int eachValue = sum_ / indexCount_;
- Node * n = new Node( true, this );
- update( -eachValue, -1 );
- splitRange( indicesNeeded, n );
- n->update( value + eachValue, 1 );
- updateStructure();
- return value + eachValue;
- }
-}
-
-void Node::updateStructure() {
- if ( isLeaf_ )
- return ;
- DYN_VERIFY_SAME( (int)nodes_.size(), (int)nodeCount_ );
-
- int dif = nodeCount_ - PREFERRED_NODES;
- if ( dif > 0 ) {
- ///split sub-nodes into a usable count of parts
- int splitAway = dif + 1;
- ///Algorithm: find the "splitAway" nodes with the lowest index-count-sum, and export them to a container-node
-
- int cnt = 0; ///The count of nodes that are summed to "indices"
- int indices = 0; ///Their count of indices
- ListType::iterator first = nodes_.begin(); ///The last node of the group that sums to "indices"
-
- ListType::iterator best = nodes_.end();
- ListType::iterator bestLast;
- int bestIndices = INT_MAX;
-
- ListType::iterator it;
- for ( it = nodes_.begin(); it != nodes_.end(); ++it ) {
- if ( cnt == splitAway ) {
- if ( indices < bestIndices ) {
- best = first;
- bestLast = it;
- bestIndices = indices;
- }
- indices -= ( *first ) ->indexCount();
- ++first;
- } else {
- cnt++;
- }
- indices += ( *it ) ->indexCount();
- }
- if ( indices < bestIndices ) {
- best = first;
- bestLast = it;
- bestIndices = indices;
- }
-
- ///now create an own group for (best -> bestLast)
- if ( best != nodes_.end() ) {
- NodePointer branch = new Node( false, this );
- branch->nodes_.insert( branch->nodes_.begin(), best, bestLast );
- DYN_VERIFY_SAME( (int)branch->nodes_.size(), (int)cnt );
- branch->nodeCount_ = cnt;
-
- it = best;
- while ( it != bestLast ) {
- //(*best)->setParent( branch );
- branch->sum_ += ( *it ) ->sum_;
- branch->indexCount_ += ( *it ) ->indexCount_;
- ++it;
- }
-
- nodeCount_ += 1;
- nodes_.insert( best, branch );
- DYN_VERIFY_SAME( (int)nodeCount_, (int)nodes_.size() );
-
- nodeCount_ -= cnt;
- nodes_.erase( best, bestLast );
- DYN_VERIFY_SAME( (int)nodeCount_, (int)nodes_.size() );
-
- } else {
- DYN_VERIFY( 0 );
- }
-
- } else if ( nodeCount_ <= JOIN_NODES_THRESHOLD ) {
- if ( parent_ ) {
- ///Remove empty non-leaf-nodes
- if ( nodeCount_ == 0 ) {
- if( indexCount_ == 0 ) {
- parent_->removeChild( this );
- } else {
- ///It is a range, leave it alone.
- }
- } else {
- ///Move all own children to the parent
- for ( ListType::iterator it = parent_->nodes_.begin(); it != parent_->nodes_.end(); ++it ) {
- if ( it->data() == this ) {
- parent_->nodes_.insert( it, nodes_.begin(), nodes_.end() );
- parent_->nodeCount_ += nodeCount_;
- NodePointer n = this; ///To prevent too early deletion
- parent_->removeChild( this );
- parent_->updateStructure();
- nodeCount_ = 0;
- break;
- }
- }
- }
- ///Move child-nodes up to the parent
- } else {}
- }
-}
-
-void Node::insertIndex( int indicesNeeded, int value ) {
- ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it == nodes_.end() || ( *it ) ->isLeaf() ) {
-
- bool range = isRange();
-
- if ( indicesNeeded <= 1 || range ) {
- Node * n = new Node( true, this );
- if( range ) {
- splitRange( indicesNeeded, n );
- } else {
- ///We have reached the end, insert the index
- nodes_.insert( it, NodePointer( n ) );
- ++nodeCount_;
- }
- n->update( value, 1 );
- } else {
- ///There are still indices missing, they could be filled with zeroes by using insertRange
- DYN_VERIFY( 0 );
- }
- } else {
- ( *it ) = ( *it ) ->makeOwn( this );
- ( *it ) ->insertIndex( indicesNeeded, value );
- }
- updateStructure();
-}
-
-void Node::splitRange( int indicesNeeded, Node* insertNode ) {
- DYN_VERIFY_SMALLERSAME( indicesNeeded, indexCount_ );
- int eachValue = sum_ / indexCount_;
- DYN_VERIFY_SAME( eachValue*indexCount_, sum_ );
- int r1Size = indicesNeeded;
- int r2Size = indexCount_ - indicesNeeded;
-
- update( -sum_, -indexCount_ ); /*This should be done more efficiently with only one single update*/
- DYN_VERIFY_SAME( sum_, 0 );
- DYN_VERIFY_SAME( indexCount_, 0 );
- ///This makes this range-node a normal node.
-
- Node * n;
-// Add the first split-range
- if( r1Size ) {
- n = new Node( false, this );
- nodes_.insert( nodes_.end(), NodePointer( n ) );
- ++nodeCount_;
- n->update( eachValue * r1Size, r1Size );
- }
-
- nodes_.insert( nodes_.end(), NodePointer( insertNode ) );
- ++nodeCount_;
-
- ///Add the second split-range
- if( r2Size ) {
- n = new Node( false, this );
- nodes_.insert( nodes_.end(), NodePointer( n ) );
- ++nodeCount_;
- n->update( eachValue * r2Size, r2Size );
- }
-
- DYN_VERIFY( !isRange() );
-}
-
-void Node::insertRange( int indicesNeeded, int size, int value ) {
- ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if ( it == nodes_.end() || ( *it ) ->isLeaf() ) {
- bool range = isRange();
- if ( indicesNeeded <= 1 || range ) {
- Node * n = new Node( false, this );
-
- if( range ) {
- /**This is a range, and needs to be made a normal inner node with a split up slave-range. */
- DYN_VERIFY( it == nodes_.end() );
- splitRange( indicesNeeded, n );
- } else {
- /**We have reached the end, insert the range*/
- nodes_.insert( it, NodePointer( n ) );
- ++nodeCount_;
- }
-
- n->update( value*size, size );
- } else {
- ///There are still indices missing, they could be filled with zeroes
- DYN_VERIFY( 0 );
- }
- } else {
- ( *it ) = ( *it ) ->makeOwn( this );
- ( *it ) ->insertRange( indicesNeeded, size, value );
- }
- updateStructure();
-}
-
-void Node::removeChild( Node* n ) {
- for ( ListType::iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
- if ( ( *it ).data() == n ) {
- nodes_.erase( it );
- --nodeCount_;
- return ;
- }
- }
-}
-
-int Node::removeIndex( int indicesNeeded ) {
- ListType::iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- for ( ; it != nodes_.end() && indicesNeeded >= 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if( it != nodes_.end() && indicesNeeded == 0 && ( *it ) ->isLeaf() ) {
- ///Remove the leaf-node
- int ret = ( *it ) ->sum();
- nodes_.erase( it );
- --nodeCount_;
- update( -ret, -1 );
-
- updateStructure();
- return ret;
- } else if( isRange() ) {
- DYN_VERIFY_SMALLER( indicesNeeded, indexCount_ );
- int ret = sum_ / indexCount_;
- update( -ret, -1 );
- updateStructure();
- return ret;
- } else {
- DYN_VERIFY( it != nodes_.end() );
- ( *it ) = ( *it ) ->makeOwn( this );
- return ( *it ) ->removeIndex( indicesNeeded );
- }
-}
-
-int Map::setIndexValue( int index, int value ) {
- return tree_->setIndexValue( index, value );
-}
-
-int Map::changeIndexValue( int index, int diff ) {
- return tree_->changeIndexValue( index, diff );
-}
-
-int Map::indexValue( int indicesNeeded ) const {
- return tree_->indexValue( indicesNeeded );
-}
-
-void Map::insertRange( int position, int size, int value ) {
- tree_->insertRange( position, size, value );
-}
-
-///Inserts an index at position "index" with the value "value"
-void Map::insertIndex( int index, int value ) {
- tree_->insertIndex( index, value );
-}
-
-int Map::removeIndex( int index ) {
- return tree_->removeIndex( index );
-}
-
-int Map::indexCount() const {
- return tree_->indexCount();
-}
-
-int Node::sum( int index ) const {
- if ( index == 0 )
- return 0;
- int summ = 0;
- int indicesNeeded = index;
-
- ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- ListType::const_iterator end = nodes_.end();
- for ( ; it != end && indicesNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->indexCount();
- if ( itCount <= indicesNeeded ) {
- summ += ( *it ) ->sum();
- indicesNeeded -= itCount;
- } else {
- break;
- }
- }
-
- if( indicesNeeded > 0 ) {
- if ( it != end ) {
- ///Ask the next one for the summ
- summ += ( *it ) ->sum( indicesNeeded );
- } else if( isRange() ) {
- int eachValue = sum_ / indexCount_;
- int cnt = indicesNeeded;
- if( cnt > indexCount_ ) cnt = indexCount_;
- summ += cnt * eachValue;
- }
- }
-
- return summ;
-}
-/*
-int Node::index( int sum ) const {
- ListType::const_iterator end = nodes_.end();
- int index = 0;
- for( ListType::const_iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
- int cnt = (*it)->sum();
- if( cnt <= sum ) {
- index -= cnt;
- } else {
- return index + (*it)->index( sum );
- }
- }
- return index;
- if( isLeaf_ && sum == 0 ) {
- return 0;
- } else {
- cout << nodes_.size() << endl;
-
- DYN_VERIFY( isLeaf_ && sum == 0 );
- }
-}*/
-
-int Node::index( int sum ) const {
- if ( isLeaf_ )
- return 0;
- int ind = 0;
- int sumNeeded = sum;
-
- ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as index(they are completely in)
- ListType::const_iterator end = nodes_.end();
- for ( ; it != end && sumNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->sum();
- if ( itCount <= sumNeeded ) {
- ind += ( *it ) ->indexCount();
- sumNeeded -= itCount;
- } else {
- break;
- }
- }
- if ( it != end ) {
- if ( sumNeeded > 0 ) {
- ///Ask the next one for the summ
- ind += ( *it ) ->index( sumNeeded );
- } else {
- ///Jump over all indices that have a size of zero, because those
- ///might steal the map from the index behind(it should not be possible to map to them).
- while ( it != end && ( *it ) ->sum() == 0 ) {
- ind += ( *it ) ->indexCount();
-
- ++it;
- }
- }
- } else if( sumNeeded > 0 && isRange() ) {
- int eachValue = sum_ / indexCount_;
- ind += ( sumNeeded / eachValue );
- }
-
- return ind;
-}
-
-void Node::indexAndSum( int sum, IndexAndSum& targ ) const {
- if ( isLeaf_ )
- return;
- int sumNeeded = sum;
-
- ListType::const_iterator it = nodes_.begin(); ///Add all nodes whose upper bound is lower/same as targ.indexex(they are completely in)
- ListType::const_iterator end = nodes_.end();
- for ( ; it != end && sumNeeded > 0 ; ++it ) {
- int itCount = ( *it ) ->sum();
- if ( itCount <= sumNeeded ) {
- targ.index += ( *it ) ->indexCount();
- targ.sum += itCount;
- sumNeeded -= itCount;
- } else {
- break;
- }
- }
- if ( it != end ) {
- if ( sumNeeded > 0 ) {
- ///Ask the next one for the summ
- ( *it ) ->indexAndSum( sumNeeded, targ );
- } else {
- ///Jump over all targ.indexices that have a size of zero, because those
- ///might steal the map from the targ.indexex behtarg.index(it should not be possible to map to them).
- while ( it != end && ( *it ) ->sum() == 0 ) {
- targ.index += ( *it ) ->indexCount();
-
- ++it;
- }
- }
- } else if( sumNeeded > 0 && isRange() ) {
- int eachValue = sum_ / indexCount_;
- int cnt = ( sumNeeded / eachValue );
- targ.index += cnt;
- targ.sum += cnt * eachValue;
- }
-}
-
-int Map::build( const SumVector::const_iterator& begin, const SumVector::const_iterator& end, Node* parent ) {
- if ( begin == end )
- return 0;
-
- SumVector::const_iterator it = begin;
- ++it;
- if ( it == end ) {
- ///It is the only item
- NodePointer ret = new Node( true, parent );
-
- ret->update( *begin, 1 );
- parent->addNode( ret );
- return 1;
- }
- it = begin;
- int count = 0;
- for ( SumVector::const_iterator i = begin; i != end; ++i )
- ++count;
-
- int threshold = count / PREFERRED_NODES;
- if ( threshold == 0 )
- threshold = 1;
-
- SumVector::const_iterator currentItem = begin;
- it = begin;
- count = 0;
- int totalCount = 0;
- NodePointer branch = new Node( false, parent );
- parent->addNode( branch );
-
- while ( 1 ) {
- if ( it == end || ( count >= threshold && it != currentItem ) ) {
- totalCount += build( currentItem, it, branch );
- currentItem = it;
- count = 0;
-
- if ( it == end )
- break;
- }
- ++count;
-
- ++it;
- }
- return totalCount;
-}
-/*
-Map Map::rebuild() {
- std::vector<int> vecs;
- tree_->fillValues( vecs );
- return Map( vecs );
-}*/
-
-std::string Node::dump( int indexOffset, int depth ) const {
- std::ostringstream os;
- mult( os, depth, " " );
- os << "depth: " << depth << ( isLeaf_ ? " leaf " : " helper " ) << "sum: " << sum_ << " ";
-
- if ( !isLeaf_ ) {
- os << "index-count " << indexCount_ << " (nodes: " << nodes_.size() << ")\n";
- for ( ListType::const_iterator it = nodes_.begin(); it != nodes_.end(); ++it ) {
- os << ( *it ) ->dump( indexOffset, depth + 1 );
- indexOffset += ( *it ) ->indexCount();
- }
- } else {
- os << "index: " << indexOffset << "\n";
- }
-
- return os.str();
-}
-
-std::string Map::dump() const {
- return tree_->dump( 0, 0 );
-}
-
-
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h (nonexistent)
@@ -1,36 +0,0 @@
-/*
- This file is part of the KDevelop platform
- Copyright 2006 Matt Rogers <mattr@kde.org>
- Copyright 2004 Jarosław Staniek <staniek@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef DYNAMICTEXTEXPORT_H
-#define DYNAMICTEXTEXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-#ifndef DYNAMICTEXT_XPORT
-# ifdef MAKE_DYNAMICTEXT_LIB
-# define DYNAMICTEXT_EXPORT KDE_EXPORT
-# else
-# define DYNAMICTEXT_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif /* DYNAMICTEXTEXPORT_H*/
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictextexport.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp (nonexistent)
@@ -1,204 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "vectortimestamp.h"
-#include <iostream>
-#include <ext/hash_map>
-#include <sstream>
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-std::ostream& operator << ( std::ostream& str, const VectorTimestamp& timestamp ) {
- str << timestamp.print();
- return str;
-}
-
-namespace __gnu_cxx {
-template <>
-struct hash<VectorTimestamp> {
- size_t operator() ( const VectorTimestamp& x ) {
- return x.hash();
- }
-};
-}
-
-///Maximizes every stamp with the other side
-void VectorTimestamp::maximize( const VectorTimestamp& rhs ) {
- if ( rhs.m_state.size() > m_state.size() )
- m_state.resize( rhs.m_state.size(), 0 );
- for ( uint a = 0; a < rhs.m_state.size(); a++ ) {
- if ( rhs.m_state[ a ] > m_state[ a ] )
- m_state[ a ] = rhs.m_state[ a ];
- }
-}
-
-bool VectorTimestamp::isZero() const {
- for ( uint a = 0; a < m_state.size(); a++ )
- if ( m_state[ a ] != 0 )
- return false;
- return true;
-}
-
-
-
-///copies the timestamp and increases on the given index by one
-VectorTimestamp::VectorTimestamp( int primaryIndex, const VectorTimestamp& rhs ) : m_state( rhs.m_state ), m_primaryIndex( 0 ) {
- setPrimaryIndex( primaryIndex );
- increase();
-}
-
-Timestamp VectorTimestamp::primaryStamp() const {
- if ( m_state.size() <= m_primaryIndex )
- return 0;
- return ( *this ) [ m_primaryIndex ];
-}
-/**
- * @return whether every timestamp is smaller than the according index of rhs
-* */
-bool VectorTimestamp::smaller( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- if ( sz == 0 )
- return false;
-
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 < s2 )
- continue;
- else
- return false;
- }
- return true;
-}
-
-/**
- * @return whether every timestamp is smaller than or same as the according index of rhs
-* */
-bool VectorTimestamp::smallerOrSame( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 <= s2 )
- continue;
- else
- return false;
- }
- return true;
-}
-
-bool VectorTimestamp::isOneBigger( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 > s2 )
- return true;
- }
- return false;
-}
-
-bool VectorTimestamp::isOneSmaller( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 < s2 )
- return true;
- }
- return false;
-}
-
-size_t VectorTimestamp::hash() const {
- size_t s = 0;
- uint sz = m_state.size();
- for ( uint a = 0; a < sz; a++ ) {
- s += ( a * 17 ) * m_state[ a ];
- }
- return s;
-}
-
-bool VectorTimestamp::operator == ( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- if ( ( *this ) [ a ] != rhs[ a ] )
- return false;
- }
- return true;
-}
-
-///The following two are useful for sorting in a map
-///Very inefficient
-bool VectorTimestamp::operator < ( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 < s2 )
- return true;
- else if ( s1 > s2 )
- return false;
- }
- return false;
-}
-
-///Very inefficient
-bool VectorTimestamp::operator <= ( const VectorTimestamp& rhs ) const {
- uint sz = size();
- if ( rhs.size() > sz )
- sz = rhs.size();
- for ( uint a = 0; a < sz; a++ ) {
- Timestamp s1 = ( *this ) [ a ];
- Timestamp s2 = rhs[ a ];
- if ( s1 < s2 )
- return true;
- else if ( s1 > s2 )
- return false;
- }
- return true;
-}
-
-void VectorTimestamp::setPrimaryIndex( const uint index ) {
- m_primaryIndex = index;
- if ( m_state.size() < index + 1 )
- m_state.resize( index + 1, 0 );
-}
-
-std::string VectorTimestamp::print() const {
- std::string ret = "[";
- for ( std::vector<Timestamp>::const_iterator it = m_state.begin(); it != m_state.end(); ++it ) {
- if ( it != m_state.begin() )
- ret += ", ";
- std::ostringstream o;
- o << *it;
- ret += o.str();
- }
- ret += "]";
-
- return ret;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt (nonexistent)
@@ -1,37 +0,0 @@
-################################################################################################
-# This library needs to build without KDE4, please don't add KDE4 specific cmake stuff in here #
-################################################################################################
-
-PROJECT( dynamictext )
-
-#if you don't want the full compiler output, remove the following line
-#SET(CMAKE_VERBOSE_MAKEFILE ON)
-
-SET( dynamictext_SRCS
- dynamictext.cpp
- vectortimestamp.cpp
- offsetutils.cpp
- sumtree.cpp
-)
-
-#add definitions, compiler switches, etc.
-#ADD_DEFINITIONS(-Wall -g -fno-inline -fexceptions)
-#ADD_DEFINITIONS(-Wall -os -finline -fexceptions)
-#ADD_DEFINITIONS(-Wall -o3 -g -fexceptions)
-
-ADD_DEFINITIONS(-Wall ${KDE4_ENABLE_EXCEPTIONS})
-
-#list all source files here
-
-######## next target ########
-
-# This library only exists as a convenience library for the teamwork plugin, thus it is not SOVERSION'ed
-ADD_LIBRARY( kdevteamwork_dynamictext SHARED ${dynamictext_SRCS} )
-TARGET_LINK_LIBRARIES( kdevteamwork_dynamictext ${COMMONCPP2_LIBRARIES} ${Boost_THREAD_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} ${QT_QTCORE_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
-install(TARGETS kdevteamwork_dynamictext ${INSTALL_TARGETS_DEFAULT_ARGS})
-
-ADD_EXECUTABLE( testexec main.cpp)
-TARGET_LINK_LIBRARIES( testexec kdevteamwork_dynamictext ${Boost_THREAD_LIBRARY} ${Boost_SERIALIZATION_LIBRARY} dl ${ZLIB_LIBRARIES} )
-
-#ADD_DEPENDENCIES( testexec, dynamictext )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h (nonexistent)
@@ -1,188 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef SUMTREE_H
-#define SUMTREE_H
-
-#include <list>
-#include <vector>
-
-#include "../network/safesharedptr.h"
-#include "../network/weaksafesharedptr.h"
-
-#include "verify.h"
-#include "dynamictextexport.h"
-
-namespace SumTree {
-class Node;
-class EndIndexCompare;
-typedef SharedPtr<Node> NodePointer;
-typedef WeakSharedPtr<Node> WeakNodePointer;
-
-
-///A pair that contains an index and the sum of all values before that index
-struct DYNAMICTEXT_EXPORT IndexAndSum {
- int index;
- int sum;
-};
-
-///Everything may throw DynamicTextError. Every pointer to Nodes, except those from parent-node to slave-node, must be weak-pointers.(because the ref-count is important for ownership-stuff)
-class DYNAMICTEXT_EXPORT Node : public Shared {
- typedef std::list<NodePointer> ListType;
- public:
- Node( bool isLeaf, Node* parent );
-
- ///If this node is already owned by parent, returns this. Else creates a copy owned by parent.
- inline Node* makeOwn( Node* parent );
- Node* setParent( Node* parent );
-
- ///Can be used to add/subtract a value from the sum(should only be directly called on end-items without children, and the index-range is only expanded, never shrinked.)
- inline void update( const int sumDif, const int indexCountDif ) {
- sum_ += sumDif;
- indexCount_ += indexCountDif;
-
- // DYN_VERIFY_SMALLER( sum_, 1000000 );
- Node* parent = parent_/*.get()*/;
- if( parent && (sumDif != 0 || indexCountDif != 0 ) )
- parent_->update( sumDif, indexCountDif );
- }
-
- void addNode( Node* node );
-
- ///The sum is counted until that index, not including it.
- int sum( int index ) const;
-
- int index( int sum ) const;
-
- int sum() const {
- return sum_;
- }
- int indexCount() const {
- return indexCount_;
- }
-
- void indexAndSum( int sum, IndexAndSum& targ ) const;
-
- std::string dump( int offset,int depth ) const;
-
- template<class Container>
- void fillValues( Container& c ) {
- if( isLeaf_ ) {
- c.push_back( sum_ );
- }else {
- for( ListType::iterator it = nodes_.begin(); it != nodes_.end(); ++it )
- (*it)->fillValues( c );
- }
- }
-
- bool hasIndex( int index ) const;
-
- int indexValue( int index ) const;
-
- int setIndexValue( int index, int value );
-
- int changeIndexValue( int index, int diff );
-
- void insertIndex( int index, int value );
-
- void insertRange( int position, int size, int value );
-
- int removeIndex( int index );
-
- bool isLeaf() const {
- return isLeaf_;
- }
-
- bool isRange() const {
- return !isLeaf_ && nodeCount_ == 0 && indexCount_ != 0;
- }
-
- void updateStructure();
-
- private:
- void splitRange( int splitPosition, Node* insertNode );
-
- void removeChild( Node* n );
-
- friend class EndIndexCompare;
- /*WeakNodePointer*/Node* parent_; ///if this is zero, the node is available for taking, else it must be copied.
- ListType nodes_;
- int nodeCount_; ///Cache for nodes_.size()
- int sum_; ///Sum over all sub-elements
- int indexCount_; ///The count of indices this node and all subnodes cover
- bool isLeaf_;
-};
-
-///This object can be copied around and changed at will, no other instances of it will be affected, while still staying efficient(Because of implicit node-sharing)
-class DYNAMICTEXT_EXPORT Map : public WeakShared {
- public:
- typedef std::vector< int > SumVector; ///Pairs of (index, sum-value). Muss dicht sein.
- ///preferredOrder says how many slave-nodes one node should ideally have. Higher values -> faster manipulation, lower values -> faster lookup
- Map( const SumVector& summands = SumVector() );
- Map( const Map& rhs );
- ~Map();
-
- Map& operator = ( const Map& rhs );
-
- ///Returns the sum over all indices
- int sum() const;
- ///Returns the values of all indices up to(not including) index summed together
- int sum( int index ) const;
-
- ///Returns the index that the given sum falls into. Warning: indices that have a value of zero cannot be mapped back with this function.
- int index( int sum ) const;
-
- void indexAndSum( int sum, IndexAndSum& targ ) const;
-
- bool hasIndex( int index ) const;
- // Map rebuild();
-
- ///Complexity: O(1)
- int indexCount()const ;
-
- ///Returns the value of that specified index
- int indexValue( int index ) const;
-
- ///Returns the previous value of that index. The value must not be zero, because that would not allow consistent mapping back(exception is thrown)
- int setIndexValue( int index, int value );
-
- ///Returns the new value of that index. If the value becomes zero, the index cannot be mapped back through index(..) anymore.
- int changeIndexValue( int index, int diff );
-
- ///Inserts an index at position "index" with the value "value"
- void insertIndex( int index, int value = 0 ) ;
-
- /**Efficiently inserts a range of indices with
- * same value(may be zero) into the tree.
- * @param position Starting-position of the range
- * @param size Count of indices the range will occupy
- * @param value The value each index of the range will get(the whole range will have the sum size*range)
- * $
- */
- void insertRange( int position, int size, int eachValue = 0 );
-
- ///Removes one index at position index, returns the personal sum that index had associated
- int removeIndex( int index );
-
- std::string dump() const;
-
- private:
- int build( const SumVector::const_iterator& begin, const SumVector::const_iterator& end, Node* parent );
- NodePointer tree_;
-};
-
-}
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/sumtree.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp (nonexistent)
@@ -1,250 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "offsetutils.h"
-#include <iostream>
-#include <sstream>
-#include "verify.h"
-
-OffsetMapError::OffsetMapError( Type type ) : t( type ) {}
-
-const char* OffsetMapError::asText() const {
- switch ( t ) {
- case Inconsistent:
- return "the map is inconsistent";
- default:
- return "unknown";
- }
-}
-
-void OffsetMap::clear() {
- m_offsets.clear();
-}
-
-OffsetMap::OffsetMap( OffsetPosition position, int offset ) {
- addOffset( position, offset );
-}
-
-OffsetMap::OffsetMap() {}
-
-/**Returns true if the given map can be inserted without making the map inconsistent
- * */
-bool OffsetMap::isCompatible( const OffsetMap& rhs ) const {
- OffsetMap rhsInv = ~rhs;
-
- if ( m_offsets.empty() )
- return true;
-
- for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
- OffsetPosition i = rhsInv( ( *it ).first );
- if ( rhs( i ) != ( *it ).first )
- return false;
- }
-
- for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it ) {
- int endPos = ( *it ).first + ( *it ).second;
- if ( endPos < 0 )
- return false;
-
- std::map< OffsetPosition, int >::const_iterator it2 = m_offsets.lower_bound( ( OffsetPosition ) endPos );
-
- if ( it2 != m_offsets.begin() ) {
- --it2;
- if ( ( *it2 ).second + ( *it2 ).first > endPos )
- return false;
- }
- }
- return true;
-}
-
-OffsetMap OffsetMap::operator %( const OffsetMap& rhs ) const {
- OffsetMap ret;
- OffsetMap rhsInv = ~rhs;
-
- for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
- OffsetPosition i = rhsInv( ( *it ).first ); // - rhs.getOffset( ( *it ).first );
- ret.m_offsets[ i ] = ( *it ).second;
- }
-
- for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it )
- ret.addOffset( ( *it ).first, ( *it ).second );
- return ret;
-}
-
-OffsetMap& OffsetMap::operator %=( const OffsetMap& rhs ) {
- OffsetMap rhsInv = ~rhs;
- std::map<OffsetPosition, int> oldOffsets;
- oldOffsets.swap( m_offsets );
-
- for ( std::map<OffsetPosition, int>::const_iterator it = oldOffsets.begin(); it != oldOffsets.end(); ++it ) {
- OffsetPosition i = rhsInv( ( *it ).first );
- DYN_VERIFY_SAME( rhs( i ), ( *it ).first );
- m_offsets[ i ] = ( *it ).second;
- }
-
- for ( std::map<OffsetPosition, int>::const_reverse_iterator it = rhs.m_offsets.rbegin(); it != rhs.m_offsets.rend(); ++it )
- addOffset( ( *it ).first, ( *it ).second );
- return *this;
-}
-
-/**Inverts the offset-map(like the mathematical inversion of a function)
- * */
-OffsetMap OffsetMap::operator ~() const {
- OffsetMap ret;
- std::map<OffsetPosition, int>& newMap( ret.m_offsets );
- for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
- if( (*it).second > 0 ) {
- for( int a = 1; a <= (*it).second; ++a ) {
- int npos = ( *it ).first + a;
- std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
- if ( it2 == newMap.end() ) {
- newMap[ npos ] = -1;
- } else {
- ( *it2 ).second -= 1;
- }
- }
- } else {
- for( int a = -1; a >= (*it).second; --a ) {
- int npos = ( *it ).first + a;
- std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
- if ( it2 == newMap.end() ) {
- newMap[ npos ] = -a;
- } else {
- ( *it2 ).second -= a;
- }
- }
- }
-
- /*int npos = ( *it ).first + ( *it ).second;
- std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
- if ( it2 == newMap.end() ) {
- newMap[ npos ] = -( *it ).second;
- } else {
- ( *it2 ).second -= ( *it ).second;
- }*/
- }
-
- //cout << "inverting. old map size: " << newMap.size() << " new map size: " << m_offsets.size() << endl;
- return ret;
-}
-
-OffsetMap OffsetMap::engInvert() const {
- OffsetMap ret;
- std::map<OffsetPosition, int>& newMap( ret.m_offsets );
- for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it ) {
-
- int npos = ( *it ).first;
- if( ( *it ).second < 0 )
- --npos;
- else if( ( *it ).second > 0 )
- ++npos;
-
- std::map<OffsetPosition, int>::iterator it2 = newMap.find( npos );
- if ( it2 == newMap.end() ) {
- newMap[ npos ] = -( *it ).second;
- } else {
- ( *it2 ).second -= ( *it ).second;
- }
- }
-
- //cout << "inverting. old map size: " << newMap.size() << " new map size: " << m_offsets.size() << endl;
- return ret;
-}
-
-void OffsetMap::printMap() const {
- cout << "offsets: " << print() << endl;
-}
-
-std::string OffsetMap::print() const {
- ostringstream o;
- for ( std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin(); it != m_offsets.end(); ++it )
- o << "(" << ( *it ).first << ": " << ( *it ).second << ") ";
- return o.str();
-}
-
-int OffsetMap::getOffset( OffsetPosition position ) const {
-
- std::map<OffsetPosition, int>::const_iterator it = m_offsets.begin();
-
- int ret = 0;
- while ( it != m_offsets.end() && ( *it ).first <= position ) {
- ret += ( *it ).second;
- ++it;
- }
- return ret;
-}
-
-int OffsetMap::operator () ( const OffsetPosition position ) const {
- return getOffset( position ) + position;
-}
-
-void OffsetMap::addOffset( OffsetPosition position, int offset ) {
- /*if ( ( offset + int( position ) ) < 0 || offset == 0 )
- return ;*/
- //cout << "inserting offset " << offset << " at position " << position << endl;
- OffsetInternalMap::iterator it = m_offsets.find( position );
- if ( it == m_offsets.end() ) {
- it = m_offsets.insert( OffsetInternalMap::value_type( position, offset ) ).first;
- } else {
- (*it).second += offset;
- if ( (*it).second == 0 )
- m_offsets.erase( it );
- }
-}
-
-void OffsetMap::mergeOffset( OffsetPosition position, int offset ) {
- OffsetInternalMap::iterator it = m_offsets.find( ( OffsetPosition ) position );
- if( it != m_offsets.end() ) {
- (*it).second += offset;
- makeConsistent( it );
- } else {
- makeConsistent( m_offsets.insert( OffsetInternalMap::value_type( position, offset ) ).first );
- }
-}
-
-void OffsetMap::makeConsistent( OffsetInternalMap::iterator position ) {
- std::map< OffsetPosition, int >::iterator it = position;
- bool forward = (*position).second > 0;
-
- OffsetPosition until = (*position).first + (*position).second;
-
- if( forward ) {
- ///seek forwards and include all overlapped offets into this one
- ++it;
- while( it != m_offsets.end() && (*it).first <= until ) {
- (*position).second += (*it).second;
- m_offsets.erase( it++ );
- }
- } else {
- ///seek backwards and include this one into any overlapped offset, deleting this one.
-
- if( it != m_offsets.begin() ) {
- --it;
- while( (*it).first >= until ) {
- (*it).second += (*position).second;
- m_offsets.erase( position );
- position = it;
- if( it != m_offsets.begin() )
- --it;
- else
- break;
- }
- }
- }
-
- if( (*position).second == 0 )
- m_offsets.erase( position );
-}
-
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp (nonexistent)
@@ -1,842 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "offsetutils.h"
-#include <assert.h>
-#include "sumtree.h"
-
-#define CNT 500
-#define SMALLCNT 50
-#define CYCLES 1
-
-#define private public
-#include "dynamictext.h"
-#include "flexibletext.h"
-#include <time.h>
-#include <sstream>
-
-typedef std::list<std::string> StringList;
-
-std::list<std::string> splitString( const std::string& text ) {
- std::list<std::string> ret;
- uint len = text.length();
- int currentStart = 0;
-
- for ( uint a = 0; a < len; a++ ) {
- if ( text[ a ] == '\n' ) {
- ret.push_back( std::string( text.substr( currentStart, a - currentStart ) ) );
- currentStart = a + 1;
- }
- }
- //if ( currentStart != len )
- ret.push_back( std::string( text.substr( currentStart, len - currentStart ) ) );
-
- return ret;
-}
-
-
-std::string compareText( const std::string& str1, const std::string& str2 ) {
- std::ostringstream os;
- StringList l1 = splitString( str1 );
- StringList l2 = splitString( str2 );
- uint size = l1.size();
- if ( l2.size() > size )
- size = l2.size();
-
- StringList::iterator it1 = l1.begin();
- StringList::iterator it2 = l2.begin();
- int cnt1 = 0;
- int cnt2 = 0;
- os << "total length: " << str1.length() << " " << str2.length() << endl;
-
- for ( uint a = 0; a < size; a++ ) {
- std::string text1 = "empty";
- std::string text2 = "empty";
-
- if ( it1 != l1.end() )
- text1 = "\"" + *it1 + "\"";
-
- if ( it2 != l2.end() )
- text2 = "\"" + *it2 + "\"";
-
- os << a << "(total counts " << cnt1 << ":" << cnt2 << "): " << text1 << " : " << text2 << "(length " << ( text1 == "empty" ? 0 : it1->length() ) << ":" << ( text2 == "empty" ? 0 : it2->length() ) << ") " << ( text1 == text2 ? "match" : "MISMATCH" ) << "\n" ;
-
- if ( it1 != l1.end() ) {
- cnt1 += it1->length() + 1;
- ++it1;
- }
- if ( it2 != l2.end() ) {
- cnt2 += it2->length() + 1;
- ++it2;
- }
- }
- return os.str();
- //": \nflexText:\"" << flexText.text() << "\"\nstring: \n\"" << string << "\"" << endl
-}
-
-struct doubleText {
- SumTree::FlexibleText<std::string> flexText;
- std::string string;
- clock_t flexClock;
- clock_t stringClock;
- doubleText( const std::string& str ) : flexText( str ), string( str ), flexClock( 0 ), stringClock( 0 ) {}
- int lastActionType;
- int lastPosition;
- std::string lastText;
- int lastLength;
-
- void insert( int position, std::string text ) {
- lastActionType = 0;
- lastPosition = position;
- lastText = text;
-
- //flexText.rebuildTree();
- clock_t c = clock();
- flexText.insert( position, text );
- flexClock += clock() - c;
- c = clock();
- string.insert( position, text );
- stringClock += clock() - c;
- //compare();
- }
- void remove
- ( int position, int length ) {
- lastActionType = 1;
- lastPosition = position;
- lastLength = length;
-
- clock_t c = clock();
- flexText.erase( position, length );
- flexClock += clock() - c;
- c = clock();
- string.erase( position, length );
- stringClock += clock() - c;
- //compare();
- }
- void compare() {
- bool fail = false;
-
-
- if ( flexText.text().length() != string.length() )
- fail = true;
-
- if( flexText.length() < 10000 ) {
- //As long as the text is not big, check for line/column conversion consistency
- int len = flexText.length();
- for( int a = 0; a < len; a++ ) {
- int line, column;
- flexText.linearToLineColumn( a, line, column );
- if( flexText.lineColumnToLinear( line, column ) != a ) {
- cout << "linear to line/column-check: back-conversion failed at position " << a << endl;
- fail = false;
- }
- }
- }
-
- if( fail ){
- cout << "error, last action: " << ( lastActionType ? "removal " : "insertion " ) << " of \"";
- if ( lastActionType )
- cout << lastLength;
- else
- cout << lastText;
- cout << "\" at " << lastPosition << " comparing flexText(left) to string(right): \n" << compareText( flexText.text(), string );
- }
-
- DYN_VERIFY_SAME( flexText.text().length(), string.length() );
- //cout << "length: " << flexText.text().length() << " " << string.length() << endl;
- DYN_VERIFY_SAME( flexText.text(), string );
- }
- void showClock() {
- cout << "\\flexible: " << float( flexClock ) / float( CLOCKS_PER_SEC ) << endl << "\\string: " << float( stringClock ) / float( CLOCKS_PER_SEC ) << endl;
- }
-};
-
-typedef SumTree::FlexibleText<std::string> Text;
-void verifyFlexibleText() {
- std::list<std::string> bla;
- bla.push_back( "hallo" );
- bla.push_back( "Ich bin der David" );
-
- {
- /*Text:
-a (length 2, total 2)
-b (length 3, total 5)
-ccc (length 4, total 9)
- (length 1, total 10)
-dddd (length 5, total 15)
-
- */
- Text text( "a\nbb\nccc\n\ndddd\n" );
- int line, column;
- text.linearToLineColumn( 0, line, column );
- DYN_VERIFY_SAME( line, 0 ); DYN_VERIFY_SAME( column, 0 );
-
- text.linearToLineColumn( 1, line, column );
- DYN_VERIFY_SAME( line, 0 ); DYN_VERIFY_SAME( column, 1 );
-
- text.linearToLineColumn( 2, line, column );
- DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 0 );
-
- text.linearToLineColumn( 4, line, column );
- DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 2 );
-
- text.linearToLineColumn( 5, line, column );
- DYN_VERIFY_SAME( line, 2 ); DYN_VERIFY_SAME( column, 0 );
-
- text.remove( 3, 1 );
- text.linearToLineColumn( 3, line, column );
- DYN_VERIFY_SAME( line, 1 ); DYN_VERIFY_SAME( column, 1 );
-
- text.linearToLineColumn( 4, line, column );
- DYN_VERIFY_SAME( line, 2 ); DYN_VERIFY_SAME( column, 0 );
- cout << "Line-wrap tested ok" << endl;
- };
-
- Text text( "hallo\nIch bin der David" );
- cout << text.text() << endl;
- text.erase( 1, 1, 2 );
- text.erase( 0, 6 );
- text.insert( text.length() - 1, "ende!\naber" );
- text.insert( text.length() - 1, "\n" );
- cout << text.text() << endl;
-
- char inputs[ 44 ] = {'a', 'b', 'c', 'd', ' ', 'f', 'g', 'h', 'i', 'j', '\n', 'a', 'b', ' ', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'q', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'q'};
-
- std::string input;
-
- for ( int a = 0; a < rand() % 1000 + 50; a++ ) {
- input += inputs[ rand() % 44 ];
- }
-
- doubleText d( input );
- int cnt = 0;
-
- for ( int b = 0; b < 100000; b++ ) {
- ///remove a random small range
- if ( d.string.size() != 0 ) {
- uint remSize = rand() % 5;
- uint remPos = rand() % d.string.size();
- if ( remPos + remSize > d.string.size() )
- remSize = d.string.size() - remPos;
- d.remove( remPos, remSize );
- }
-
- uint addSize = rand() % 10;
- uint addPos = rand() % ( d.string.size() + 1 );
- std::string input;
- for ( uint a = 0; a < addSize; a++ ) {
- input += inputs[ rand() % 44 ];
- }
- d.insert( addPos, input );
- ++cnt;
- if ( cnt == 1000 ) {
- cnt = 0;
- d.showClock();
- cout << "size: " << d.string.size() << endl;
- d.compare();
- }
-
- ///Copy the text and remove some part, to make sure that the tree stays consistent
- Text f( d.flexText );
- if ( d.string.size() != 0 ) {
- uint remSize = rand() % 5;
- uint remPos = rand() % d.string.size();
- if ( remPos + remSize > d.string.size() )
- remSize = d.string.size() - remPos;
- f.remove( remPos, remSize );
- }
- //d.compare();
- }
- //cout << "\n" << d.flexText.dumpTree() << "\n";
-
-}
-
-void verifySumTree() {
-
- try {
- SumTree::Map tree;
- tree.insertRange( 0, 10, 1 );
- for( int a = 0; a < 10; a++ ) {
- DYN_VERIFY_SAME( tree.indexValue( 0 ), 1 );
- DYN_VERIFY_SAME( tree.index( a ), a );
- SumTree::IndexAndSum r;
- tree.indexAndSum( a, r );
- DYN_VERIFY_SAME( r.index, a );
- DYN_VERIFY_SAME( r.sum, a );
- cout << a << ": " << tree.indexValue( a ) << " "<< tree.sum( a ) << endl;
- }
- DYN_VERIFY_SAME( tree.sum( 10 ), 10 );
- DYN_VERIFY_SAME( tree.sum( 11 ), 10 );
- tree.setIndexValue( 1, 0 );
- for( int a = 0; a < 10; a++ )
- cout << a << ": " << tree.indexValue( a ) << " " << tree.sum( a ) << endl;
- DYN_VERIFY_SAME( tree.sum( 10 ), 9 );
- DYN_VERIFY_SAME( tree.sum( 11 ), 9 );
- DYN_VERIFY_SAME( tree.indexValue( 1 ), 0 );
- DYN_VERIFY_SAME( tree.indexValue( 2 ), 1 );
- tree.changeIndexValue( 1, 1 );
- DYN_VERIFY_SAME( tree.indexValue( 1 ), 1 );
- DYN_VERIFY_SAME( tree.indexValue( 2 ), 1 );
- tree.insertIndex( 3, 0 );
- DYN_VERIFY_SAME( tree.indexValue( 3 ), 0 );
- DYN_VERIFY_SAME( tree.sum( 5 ), 4 );
- tree.removeIndex( 0 );
- tree.removeIndex( 0 );
- tree.removeIndex( 0 );
- DYN_VERIFY_SAME( tree.indexValue( 0 ), 0 );
-
- } catch ( DynamicTextError err ) {
- cout << "remove-index-test failed: " << err.what() << endl;
- terminate();
- }
-
- int cycles = 3;
- for ( int a = 0; a < cycles; a++ ) {
- cout << "testing cycle " << a + 1 << endl;
- std::vector<int > summands;
- //srand ( time(NULL) );
- int count = rand() % 20000;
- summands.resize( count );
-
- for ( int a = 0; a < count; a++ ) {
- summands[ a ] = rand() % 2000 + 1;
- }
-
- try {
- SumTree::Map tree( summands );
- int sum = tree.sum( 5 );
-/* int nsum = tree.sum( 6 );*/
- DYN_VERIFY_SAME( tree.index( sum ), 5 );
- tree.setIndexValue( 5, 0 );
- // DYN_VERIFY_SAME( tree.index( sum ), 6 ); ///Reactivate in time!
- } catch ( DynamicTextError err ) {
- cout << "custom test failed: " << err.what() << endl;
- terminate();
- }
-
- //uint t = timeGetTime();
- try {
- SumTree::Map tree( summands );
- DYN_VERIFY_SAME( tree.indexCount(), count );
- } catch ( DynamicTextError err ) {
- cout << "count-invariance failed: " << err.what() << endl;
- terminate();
- }
- //cout << "count-invariance elapsed time: " << timeGetTime() - t << endl;
-
- int a = 0;
- try {
- SumTree::Map tree( summands );
- int sum = 0;
- for ( a = 0; a < count; a++ ) {
- int s = tree.sum( a );
- DYN_VERIFY_SAME( s, sum );
- sum += summands[ a ];
- int ind = tree.index( s );
- DYN_VERIFY_SAME( ind, a );
- }
-
- } catch ( DynamicTextError err ) {
- cout << "sum-test failed: " << err.what() << endl;
- terminate();
- }
-
- //cout << "sum-test elapsed time: " << time(NULL) - t << endl;
-
- try {
- SumTree::Map tree( summands );
-/* int sum = 0;*/
- for ( int a = 0; a < count; a++ ) {
- int s = tree.indexValue( a );
- DYN_VERIFY_SAME( s, summands[ a ] );
- }
-
- } catch ( DynamicTextError err ) {
- cout << "index-value failed: " << err.what() << endl;
- terminate();
- }
-
- try {
- SumTree::Map tree( summands );
- for ( int a = 0; a < count; a++ ) {
- tree.setIndexValue( a, a );
- DYN_VERIFY_SAME( a, tree.indexValue( a ) );
- }
-
- } catch ( DynamicTextError err ) {
- cout << "set-index-value failed: " << err.what() << endl;
- terminate();
- }
-
- try {
- SumTree::Map tree( summands );
- for ( int a = 0; a < count; a++ ) {
- int v = tree.indexValue( a );
- DYN_VERIFY_SAME( v + a, tree.changeIndexValue( a, a ) );
- }
-
- } catch ( DynamicTextError err ) {
- cout << "change-index-value failed: " << err.what() << endl;
- terminate();
- }
-
- try {
- SumTree::Map tree( summands );
- for ( int a = 0; a < count; a += 2 ) {
- int v = tree.indexValue( a );
- tree.insertIndex( a, a );
- DYN_VERIFY_SAME( tree.indexValue( a ), a );
- DYN_VERIFY_SAME( tree.indexValue( a + 1 ), v );
- }
- } catch ( DynamicTextError err ) {
- cout << "insert-index-test failed: " << err.what() << endl;
- terminate();
- }
- try {
- SumTree::Map tree( summands );
- for ( int a = count / 10; a >= 0; a-- ) {
- int r = tree.removeIndex( a * 9 );
- DYN_VERIFY_SAME( r, summands[ a * 9 ] );
- }
- } catch ( DynamicTextError err ) {
- cout << "remove-index-test failed: " << err.what() << endl;
- terminate();
- }
- }
-
-
-}
-
-///@todo create so automatic testing-algorithm that tests the system more intensively
-
-void verifyDynamicText() {
- cout << "testing replacement-system" << endl;
-
- try {
- DynamicText t;
- cout << "test 0.1: \n";
- VectorTimestamp a5 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
- VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 1, "a", "" ) );
- VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 2, "b", "" ) );
- VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 3, "a", "" ) );
-
- cout << t.state().print() << "text: " << t.text() << endl;
-
- VectorTimestamp v( t.state() );
- v.setStamp( 0, 0 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
- DYN_VERIFY_SAME( t.text().text(), "b" );
-
- v.setStamp( 0, 1 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
- DYN_VERIFY_SAME( t.text().text(), "ab" );
-
- v.setStamp( 0, 2 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
- DYN_VERIFY_SAME( t.text().text(), "aab" );
-
- v.setStamp( 0, 3 );
- t.changeState( v );
- DYN_VERIFY_SAME( t.text().text(), "aaba" );
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- terminate();
- }
-
- try {
- DynamicText t;
- cout << "test 4: \n";
- VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "i", "" ) );
- VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 0, "d", "" ) );
- VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 0, "v", "" ) ); ///!
- VectorTimestamp b2 = t.insert( 1, SimpleReplacement( 0, "d", "" ) );
- VectorTimestamp a3 = t.insert( 0, SimpleReplacement( t.text().length(), "r", "" ) );
- //VectorTimestamp a4 = t.insert( 0, SimpleReplacement( 0, " ", "" ) );
- VectorTimestamp a5 = t.insert( 0, SimpleReplacement( 0, "q", "" ) ); ///!
- VectorTimestamp a6 = t.insert( 0, SimpleReplacement( 1, "v", "" ) );
-
- cout << t.state().print() << "text: " << t.text() << endl;
- VectorTimestamp v( t.state() );
- v.setStamp( 1, 0 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
-
- v = t.state();
- v.setStamp( 0, 1 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- terminate();
- }
-
- try {
- DynamicText t;
- cout << "test 2: \n";
- VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
- VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 1, "b", "" ) );
- VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 2, "c", "" ) );
- VectorTimestamp b2 = t.insert( 1, SimpleReplacement( 3, "d", "" ) );
- VectorTimestamp a3 = t.insert( 0, SimpleReplacement( 4, "e", "" ) );
-
- cout << t.state().print() << "text: " << t.text() << endl;
- VectorTimestamp v( t.state() );
- v.setStamp( 1, 1 );
- t.changeState( v );
- cout << t.state().print() << "text: " << t.text() << endl;
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- terminate();
- }
-
- try {
- DynamicText t;
- cout << "test 1.1: \n";
- t.insert( 0, SimpleReplacement( 0, "a", "" ) );
- t.insert( 0, SimpleReplacement( 1, "b", "" ) );
- t.insert( 1, SimpleReplacement( 1, "q", "" ) );
- t.insert( 1, SimpleReplacement( 2, "q", "" ) );
-
- cout << t.state().print() << "text: " << t.text() << endl;
- VectorTimestamp v( t.state() );
- v.setStamp( 0, 1 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
- /*
- v = t.state();
- v.setStamp( 0, 1 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;*/
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- terminate();
- }
-
- try {
- cout << "test:\n";
- DynamicText t;
- VectorTimestamp start = t.insert( 0, SimpleReplacement( 0, "HalloichbinderDavid", "" ) );
- VectorTimestamp u0r1 = t.insert( 0, SimpleReplacement( 0, "Ahoiiiiii", "Hallo" ) );
- VectorTimestamp u1r1( 1, start );
- t.insert( u1r1, SimpleReplacement( 5, "ja", "ich" ) );
- VectorTimestamp u2r1( 2, start );
- t.insert( u2r1, SimpleReplacement( 8, "jsem", "bin" ) );
- t.changeState();
- cout << t.state().print() << "text: " << t.text() << endl;
- VectorTimestamp u1r2( 1, t.state() );
- t.insert( u1r2, SimpleReplacement( 18, "Davidek", "David" ) );
- t.changeState();
- VectorTimestamp mix = t.state();
- mix.setStamp( 0, 1 );
- t.changeState( mix );
- cout << t.state().print() << " text: " << t.text() << endl;
- t.changeState( u1r1 );
- cout << t.state().print() << "text: " << t.text() << endl;
- t.changeState( start );
- ReplacementPointer r = t.replacement( 0, 2 );
- assert( r );
- r->setEnabled( false );
- r = t.replacement( 2, 1 );
- assert( r );
- r->setEnabled( false );
- t.changeState();
-
- cout << t.state().print() << ", some disabled, text: " << t.text() << endl;
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- }
-
- {
- cout << "test:\n";
- std::string text = "hallo";
- std::string text2 = text;
- OffsetMap om;
- ReplacementPointer r = new Replacement( VectorTimestamp(), SimpleReplacement( 1, "BLA", "al" ) );
- ReplacementPointer r2 = new Replacement( VectorTimestamp(), SimpleReplacement( 4, "HeHe", "lo" ) );
- ReplacementPointer r3 = new Replacement( VectorTimestamp(), SimpleReplacement( 2, "Ne nee neee", "LAHe" ) );
- //r->setEnabled( false );
- r->apply( text2, OffsetMap(), om );
- r2->apply( text2, OffsetMap(), om );
- r3->apply( text2, OffsetMap(), om );
-
- std::string text3 = text2;
- om.printMap();
- cout << endl;
-
- r3->unApply( text3, OffsetMap(), om );
- r2->unApply( text3, OffsetMap(), om );
- r->unApply( text3, OffsetMap(), om );
- cout << "before apply: \"" << text << "\", after: \"" << text2 << "\" after unapply: \"" << text3 << "\"" << endl;
- cout << "offset-map: ";
- om.printMap();
- cout << endl;
- }
-
- cout << "testing document-manager" << endl;
- VectorTimestamp ts( 0, VectorTimestamp() );
-
- try {
- DynamicText t;
- cout << "test 1.2: \n";
- VectorTimestamp a1 = t.insert( 0, SimpleReplacement( 0, "a", "" ) );
- VectorTimestamp c1 = t.insert( 2, SimpleReplacement( 0, "w", "" ) );
- VectorTimestamp a2 = t.insert( 0, SimpleReplacement( 1, "b", "" ) );
- VectorTimestamp b1 = t.insert( 1, SimpleReplacement( 1, "q", "" ) );
-
-#define VERIFY_OFFSET( index, from, to ) \
- { OffsetMap om = t.offset( to, from ); \
- cout << "verifying offset from " << from.print() << " to " << to.print() << " at index " << index << " map is: " << om.print() << cout; \
- t.changeState( from ); \
- cout << "text in state " << from.print() << ": " << t.text() << endl; \
- char c = t.text()[index]; \
- t.changeState( to ); \
- cout << "text in state " << to.print() << ": " << t.text() << endl; \
- cout << "index: " << index << " mapped index: " << om(index) << " values: " << c << " " << t.text()[ om( index ) ] << endl; \
- DYN_VERIFY_SAME( c, t.text()[ om( index ) ] ); \
- OffsetMap om2 = t.offset( from, to ); DYN_VERIFY_SAME( om2( om( index ) ), index ); \
- } \
-
- VERIFY_OFFSET( 2, a2, a1 );
-
- VERIFY_OFFSET( 2, b1, a2 );
-
- t.changeState();
- cout << t.state().print() << "text: " << t.text() << endl;
- VectorTimestamp v( t.state() );
- v.setStamp( 2, 0 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
-
- v.setStamp( 0, 1 );
- t.changeState( v );
- cout << t.state().print() << v << " text: " << t.text() << endl;
-
- } catch ( DynamicTextError err ) {
- cout << "error: " << err.what();
- terminate();
- }
-
- DynamicText t;
-
- t.insert( ts, SimpleReplacement( 0, "aabb", "" ) );
- t.changeState( ts );
-
-
- VectorTimestamp ts1( 1, ts );
- VectorTimestamp ts2( 0, ts );
- t.insert( ts1, SimpleReplacement( 1, "a_b", "ab" ) );
- t.insert( ts2, SimpleReplacement( 3, "cc", "b" ) );
- VectorTimestamp v( 1, ts1 );
- v.maximize( ts2 );
-
- t.insert( v, SimpleReplacement( 0, "dd", "a" ) );
- t.changeState();
-
-
- cout << "text: " << t.text() << endl;
- VectorTimestamp ss( 0 );
- ss.setStamp( 0, 1 );
- ss.setStamp( 1, 2 );
- t.changeState( ss );
- cout << "text on 1,2: " << t.text() << endl;
-
- t.changeState();
- /*VectorTimestamp nv( 0, t.state() );
- t.insert( nv, SimpleReplacement( 0, "ey", "dda" ) );
- t.changeState();*/
-
- cout << "end text: " << t.text() << endl;
-
- VectorTimestamp ns( 0, t.state() );
- t.insert( ns, SimpleReplacement( 5, "hihi", "c" ) );
- t.changeState();
-
- cout << "whole end text: " << t.text() << endl;
- /*
- ns.setStamp( 1, 0 );
-
- t.changeState( ns );*/
-
- cout << "text edited by 1: " << t.text() << endl;
-
- ss.setStamp( 1, 0 );
-
- cout << "ready" << endl;
-}
-
-
-void verifyOffsets() {
- {
- //srand ( time( NULL ) );
- OffsetMap o;
- o %= OffsetMap( 3, 1 );
- o %= OffsetMap( 6, 2 );
- assert( o( 0 ) == 0 );
- assert( o( 1 ) == 1 );
- assert( o( 2 ) == 2 );
- assert( o( 3 ) == 4 );
- assert( o( 6 ) == 9 );
- assert( o( 7 ) == 10 );
-
-
- cout << "verifying offset-map\\m";
-
- for ( int b = 0; b < 1000; b++ ) {
- try {
- {
- int pos1 = rand() % 10;
- int off1 = rand() % 10;
- if( off1 < -pos1 ) off1 = pos1;
-
- int pos2 = rand() % 10;
- int off2 = rand() % 10;
- if( off2 < -pos2 ) off2 = pos2;
-
- OffsetMap om( pos1, off1);
- OffsetMap om2( pos2, off2 );
- OffsetMap om3 = om2 % om;
- OffsetMap om3Inv = ~om3;
- for ( int a = 0; a < 10; a++ ) {
- DYN_VERIFY_SAME( om2( om( a ) ), om3( a ) );
- /*int om3A = om3(a);
- int om3Invom3A = om3Inv( om3A );
- int result = om3( om3Invom3A );
- DYN_VERIFY_SAME( result, om3A );*/
- }
- }
- } catch ( const DynamicTextError & error ) {
- cout << "verifyOffsets error: " << error.what() << endl;
- terminate();
- }
- }
- cout << "success\n";
- }
-
-
- cout << "building map 1" << endl;
- OffsetMap o;
- OffsetMap o2;
- for ( int a = 0; a < SMALLCNT; a++ ) {
- float f = ( float( rand() ) / RAND_MAX ) * CNT;
- int of = (int)( ( float( rand() ) / RAND_MAX ) * 100 ) - 50;
- if ( of ) {
- OffsetMap in( ( uint ) f, of );
- if ( o.isCompatible( in ) )
- o %= in;
- }
- }
- cout << "ready" << endl;
-
- cout << "building map 2" << endl;
- for ( int a = 0; a < SMALLCNT; a++ ) {
- float f = ( float( rand() ) / RAND_MAX ) * CNT;
- int of = (int)( ( float( rand() ) / RAND_MAX ) * 100 ) - 50;
- if ( of ) {
- OffsetMap in( ( uint ) f, of );
- if ( o.isCompatible( in ) )
- o %= in;
- /* else
- cout << "incompatible: " << (uint)f << " " << of << endl;*/
- }
- }
- cout << "ready" << endl;
- /*
- o %= OffsetMap( 3, 1 );
- o %= OffsetMap( 5, 1 );
- o %= OffsetMap( 10, -2 );
- o %= OffsetMap( 15, 3 );
-
- o2 %= OffsetMap( 1, 1 );
- o2 %= OffsetMap( 8, -2 );
-// o2 % OffsetMap( 5, 1 );
-// o2 % OffsetMap( 10, -2 );
-// o2 % OffsetMap( 15, 3 );
-
- //cout << "map 1: ";
- o.printMap();
- //cout << "map 2: ";
- o2.printMap();
- if ( !o.isCompatible( o2 ) ) {
- cout << "map 2 is not compatible" << endl;
- return ;
- }*/
- OffsetMap o3 = o % o2;
- //cout << "combined: ";
- o3.printMap();
-
- /* cout << "inversion-test: ";
- OffsetMap oInv(o);
- ~oInv;
- oInv.printMap();
- cout << endl;
- for( int a = 5; a < CNT; a++ ) {
- int oa = o(a);
- cout << a << " == " << oInv( oa );
- cout << " (" << oa << ")" << endl;
- assert( oInv( o(a) ) == a );
- }
- cout << "success "<< endl;*/
-
-
- cout << "testing o(o2(x)) == o3(x) ( with o3 = o % o2 )" << endl;
- for ( int a = 0; a < CNT; a++ ) {
- if ( o2( a ) < 0 || o( a ) < 0 )
- continue;
- if ( !o( o2( a ) ) == o3( a ) )
- cout << "error for a " << a << ": " << o( a ) << " " << o2( a ) << " : " << o( o2( a ) ) << " != " << o3( a ) << endl;
- assert( o( o2( a ) ) == o3( a ) );
- }
- cout << "success" << endl;
-
- o3 = o3 % ( ~o2 );
-
- cout << "testing (o % o2) % (~o2) == o2" << endl;
- for ( int a = 0; a < CNT; a++ ) {
- if ( o2( a ) < 0 || o( a ) < 0 )
- continue;
- int val1 = o3( a );
- int val2 = o( a );
- if ( val1 != val2 )
- cout << "error for a " << a << ": " << o( a ) << " " << o3( a ) << " : " << val1 << " != " << val2 << endl;
- assert( val1 == val2 );
- }
- cout << "success" << endl;
-
-}
-
-
-int main( int /* argc */, char** /*argv*/ ) {
- verifyDynamicText();
- verifySumTree();
- verifyFlexibleText();
- verifyOffsets();
-
- //printf("testing\n");
- // for( int q = 0; q < CYCLES; q++ ) {
- // }
-
-
- return EXIT_SUCCESS;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/main.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h (nonexistent)
@@ -1,125 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef VECTORTIMESTAMP_H
-#define VECTORTIMESTAMP_H
-
-#include <vector>
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/level.hpp>
-#include <iosfwd>
-#include "dynamictextexport.h"
-
-typedef int Timestamp;
-
-class DYNAMICTEXT_EXPORT VectorTimestamp {
- std::vector<Timestamp> m_state;
- uint m_primaryIndex;
- public:
- VectorTimestamp( int primaryIndex = 0 ) : m_primaryIndex( 0 ) {
- setPrimaryIndex( primaryIndex );
- }
-
- ///copies the timestamp and increases on the given index by one
- VectorTimestamp( int primaryIndex, const VectorTimestamp& rhs );
-
- Timestamp primaryStamp() const;
-
- Timestamp operator[] ( const uint index ) const {
- if ( index < m_state.size() ) {
- return m_state[ index ];
- } else {
- return 0;
- }
- }
-
- void setStamp( uint index, int value ) {
- if ( index >= m_state.size() ) {
- m_state.resize( index + 1, 0 );
- }
-
- m_state[ index ] = value;
- }
-
- ///Maximizes every stamp with the other side
- void maximize( const VectorTimestamp& rhs );
-
- bool isZero() const;
-
- template <class Archive>
- void serialize( Archive& arch, const uint /*version*/ ) {
- arch & m_state;
- arch & m_primaryIndex;
- }
-
- /**
- * @return whether every timestamp is smaller than the according index of rhs
- * */
- bool smaller( const VectorTimestamp& rhs ) const ;
-
- /**
- * @return whether every timestamp is smaller than or same as the according index of rhs
- * */
- bool smallerOrSame( const VectorTimestamp& rhs ) const ;
-
- bool isOneBigger( const VectorTimestamp& rhs ) const ;
-
- bool isOneSmaller( const VectorTimestamp& rhs ) const ;
-
- size_t hash() const ;
-
- bool operator == ( const VectorTimestamp& rhs ) const ;
-
- inline bool operator != ( const VectorTimestamp& rhs ) const {
- return ! operator==( rhs );
- }
-
- ///The following two are useful for sorting in a map
- ///Very inefficient
- bool operator < ( const VectorTimestamp& rhs ) const ;
-
- ///Very inefficient
- bool operator <= ( const VectorTimestamp& rhs ) const ;
-
- void setPrimaryIndex( const uint index );
-
- uint primaryIndex() const {
- return m_primaryIndex;
- }
-
- void decrease() {
- --m_state[ m_primaryIndex ];
- }
-
- void increase() {
- ++m_state[ m_primaryIndex ];
- }
-
- void resize( uint sz ) {
- m_state.resize( sz, 0 );
- }
-
- uint size() const {
- return m_state.size();
- }
-
- std::string print() const;
-};
-
-DYNAMICTEXT_EXPORT std::ostream& operator << ( std::ostream& str, const VectorTimestamp& timestamp );
-
-BOOST_CLASS_IMPLEMENTATION(VectorTimestamp, object_serializable)
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/vectortimestamp.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp (nonexistent)
@@ -1,929 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#define NOCATCH
-
-#include "dynamictext.h"
-#include "../network/serialization.h"
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/export.hpp>
-#include <ostream>
-#include "verify.h"
-
-#ifndef NOCATCH
-typedef DynamicTextError CatchedDynamicTextError;
-#else
-typedef DynamicTextErrorDummy CatchedDynamicTextError;
-#endif
-
-std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs ) {
- o << "( at " << rhs.m_position << ": '" << rhs.m_oldText << "' -> '" << rhs.m_newText << "' )";
- return o;
-}
-
-CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, WeakReplacementPointer, 0, value )
-CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, VectorTimestamp, 0, value->vectorStamp() )
-CROSSMAP_KEY_EXTRACTOR( WeakReplacementPointer, ReplacementId, 0, ReplacementId( value->primaryIndex(), value->primaryStamp() ) )
-
-namespace __gnu_cxx {
-template <>
-struct hash<ReplacementId> {
- size_t operator() ( const ReplacementId& x ) {
- return x.primaryIndex * 17 + x.stamp;
- }
-};
-}
-
-DynamicTextError::DynamicTextError( const String& fun, int l, const String& f, const String& exp, const String& realExp ) : function( fun ), line( l ), file( f ), expression( exp ), realExpression( realExp ) {
- cout << what() << endl;
-}
-String DynamicTextError::what() const {
- std::ostringstream os;
- os << "DynamicTextError in " << function << ", " << file << ":" << line;
- if ( !expression.empty() )
- os << ", expression \"" << expression << "\" failed";
- if ( !realExpression.empty() )
- os << ", values: " << realExpression;
- return os.str();
-}
-
-OffsetMap Replacement::offset( const OffsetMap& ofs ) {
- return OffsetMap( ofs( m_replacement.m_position ), int( m_replacement.m_newText.length() ) - int( m_replacement.m_oldText.length() ) );
-}
-
-void Replacement::setEnabled( bool e ) {
- m_enabled = e;
-}
-
-
-template <class TextType>
-bool Replacement::apply( TextType& text, const OffsetMap& outerOffset, OffsetMap& staticOffset ) {
- if ( m_enabled ) {
- std::cout << "applying replacement " << replacement() << "\noffset: " << outerOffset.print() << "\nstaticOffset: " << staticOffset.print() << endl;
- int pos = outerOffset( staticOffset( m_replacement.m_position ) );
- DYN_VERIFY_SMALLERSAME( 0, pos );
- DYN_VERIFY_SMALLERSAME( (int)pos, (int)text.length() );
- DYN_VERIFY_SAME( text.substr( pos, m_replacement.m_oldText.length() ), m_replacement.m_oldText );
-
- text.replace( pos, m_replacement.m_oldText.length(), m_replacement.m_newText );
- } else {
- staticOffset %= ~offset( outerOffset );
- }
-
- return true;
-}
-
-template <class TextType>
-bool Replacement::unApply( TextType& text, const OffsetMap& outerOffset, OffsetMap& staticOffset ) {
- if ( m_enabled ) {
- int pos = outerOffset( staticOffset( m_replacement.m_position ) );
- DYN_VERIFY_SMALLERSAME( 0, pos );
- DYN_VERIFY_SMALLERSAME( (int)pos, (int)text.length() );
- DYN_VERIFY_SAME( text.substr( pos, m_replacement.m_newText.length() ), m_replacement.m_newText );
-
- text.replace( pos, m_replacement.m_newText.length(), m_replacement.m_oldText );
- } else {
- staticOffset %= offset( outerOffset );
- }
-
- return true;
-}
-
-void Replacement::setNext( ReplacementPointer next ) {
- m_next = next;
- /* if ( m_next ) {
- m_next->m_prev = next;
- DYN_VERIFY( !next->m_next );
- next->m_next = m_next;
- }
- m_next = next;
- m_next->m_prev = this;*/
-}
-
-void Replacement::setPrev( ReplacementPointer prev ) {
- m_prev = prev;
- /* if ( m_prev ) {
- m_prev->m_next = prev;
- }
- m_prev = prev;
- m_prev->m_next = this;*/
-}
-
-bool Replacement::operator < ( const Replacement& rhs ) const throw( DynamicTextError ) {
- DYN_VERIFY_SAME( rhs.primaryIndex(), primaryIndex() );
- return primaryStamp() < rhs.primaryStamp();
-}
-
-bool Replacement::operator <= ( const Replacement& rhs ) const throw( DynamicTextError ) {
- DYN_VERIFY_SAME( rhs.primaryIndex(), primaryIndex() );
- return primaryStamp() <= rhs.primaryStamp();
-}
-
-uint Replacement::primaryIndex() const {
- return m_state.primaryIndex();
-}
-
-const VectorTimestamp& Replacement::vectorStamp() const {
- return m_state;
-}
-
-Timestamp Replacement::primaryStamp() const {
- return m_state.primaryStamp();
-}
-
-ReplacementPointer Replacement::next() const {
- return m_next;
-}
-
-ReplacementPointer Replacement::prev() const {
- return m_prev;
-}
-
-bool Replacement::enabled() const {
- return m_enabled;
-}
-
-#ifdef USE_LINKS
-void Replacement::updateLink( uint index, ReplacementPointer link ) {
- if ( m_links.size() <= index )
- m_links.resize( index + 1 );
- if ( !m_links[ index ] || m_links[ index ] ->primaryStamp() > link->primaryStamp() )
- m_links[ index ] = link;
-}
-#endif
-
-const DynamicText::Text& DynamicText::text() const {
- return m_text;
-}
-
-const String& DynamicText::initialText() const {
- return m_initialText;
-}
-
-bool DynamicText::insert( const VectorTimestamp& stamp, const SimpleReplacement& replacement ) {
- DYN_VERIFY( !m_allReplacements.values( stamp ) ); ///Make sure a same stamp has not been inserted already
- DYN_VERIFY( !stamp.isZero() );
-
- VectorTimestamp currentState = m_state;
- VectorTimestamp s = stamp;
- s.decrease();
-
- if ( s.size() > m_state.size() ) {
- m_state.resize( s.size() );
- m_unApplied.resize( s.size() );
- m_applied.resize( s.size() );
- }
-
- {
- ///Make sure that all wished pre-stamps are available
- for ( uint a = 0; a < stamp.size(); a++ ) {
- if ( stamp[ a ] != 0 ) {
- Timestamp max = highestStamp( a );
- if ( a == stamp.primaryIndex() ) {
- DYN_VERIFY_SAME( s[ a ], max ); ///Make sure no higher entries exist
- } else {
- DYN_VERIFY_SMALLERSAME( s[ a ], max ); ///Make sure that no non-existent states are referenced
- }
-
- }
- }
- }
-
- try {
- DYN_VERIFY( changeStateInternal( s ) );
-
- insertInternal( stamp.primaryIndex(), replacement );
-
- DYN_VERIFY( changeStateInternal( currentState ) );
- } catch ( const CatchedDynamicTextError & err ) {
- if ( m_state != currentState )
- notifyStateChanged();
- throw;
- }
-
- return true;
-}
-
-ReplacementPointer DynamicText::first( uint index ) const {
- if ( m_applied.size() > index && m_applied[ index ].first )
- return m_applied[ index ].first;
-
- if ( m_unApplied.size() > index && m_unApplied[ index ].first )
- return m_unApplied[ index ].first;
-
- return 0;
-}
-
-ReplacementPointer DynamicText::firstUnapplied( uint index ) const {
- if ( m_unApplied.size() > index && m_unApplied[ index ].first )
- return m_unApplied[ index ].first;
-
- return 0;
-}
-
-ReplacementPointer DynamicText::last( uint index ) const {
- if ( m_unApplied.size() > index && m_unApplied[ index ].last )
- return m_unApplied[ index ].last;
-
- if ( m_applied.size() > index && m_applied[ index ].last )
- return m_applied[ index ].last;
- return 0;
-}
-
-ReplacementPointer DynamicText::lastApplied( uint index ) const {
- if ( m_applied.size() > index && m_applied[ index ].last )
- return m_applied[ index ].last;
- return 0;
-}
-
-Timestamp DynamicText::highestStamp( uint a ) const {
- Timestamp max = 0;
-
- if ( m_unApplied.size() > a && m_unApplied[ a ].last )
- max = m_unApplied[ a ].last->primaryStamp();
- else if ( m_applied.size() > a && m_applied[ a ].last )
- max = m_applied[ a ].last->primaryStamp();
-
- if ( m_initialState[ a ] > max )
- max = m_initialState[ a ];
-
- return max;
-}
-
-VectorTimestamp DynamicText::insert( uint index, const SimpleReplacement& replacement ) {
- VectorTimestamp state = m_state;
- VectorTimestamp ret;
- try {
- ret = insertInternal( index, replacement );
- } catch ( const CatchedDynamicTextError & err ) {
- if ( state != m_state )
- notifyStateChanged();
- throw;
- }
-
- if ( state != m_state )
- notifyStateChanged();
- return ret;
-}
-
-VectorTimestamp DynamicText::insertInternal( uint index, const SimpleReplacement& replacement ) {
- VectorTimestamp stamp( index, m_state );
- DYN_VERIFY( !m_allReplacements.values( stamp ) ); ///Make sure a same stamp has not been inserted already
- DYN_VERIFY( !stamp.isZero() );
-
- VectorTimestamp s = stamp;
- s.decrease();
-
- DYN_VERIFY_SAME( s, m_state );
-
- if ( stamp.size() > m_state.size() || stamp.size() > m_unApplied.size() ) {
- m_state.resize( stamp.size() );
- m_unApplied.resize( stamp.size() );
- m_applied.resize( stamp.size() );
- }
-
- DYN_VERIFY_SAME( m_unApplied[ index ].first, 0 /*Make sure there isn't already a replacement with that primary index*/ );
-
- ReplacementPointer rep = new Replacement( stamp, replacement );
-
- DYN_VERIFY( rep->apply( m_text, OffsetMap(), m_currentOffset ) );
-
- if ( s.primaryStamp() != 0 ) {
- ReplacementPointer prev = this->replacement( s.primaryIndex(), s.primaryStamp() );
- if ( prev ) { ///Since the collaboration can start in any state, we don't have to insist on this
- DYN_VERIFY_SAME( prev, m_applied[ s.primaryIndex() ].last );
- prev->setNext( rep );
- rep->setPrev( prev );
- }
- }
- if ( m_applied.size() <= s.primaryIndex() )
- m_applied.resize( s.primaryIndex() + 1 );
- m_applied[ s.primaryIndex() ].last = rep;
- if ( m_applied[ s.primaryIndex() ].first == 0 )
- m_applied[ s.primaryIndex() ].first = rep;
-
-#ifdef USE_LINKS
- ///Set the m_links-member of all previous-stamped items
- for ( int a = 0; a < m_applied.size(); a++ ) {
- if ( a != stamp.primaryIndex() ) {
- if ( s[ a ] != 0 ) {
- ReplacementPointer p = this->replacement( a, s[ a ] );
- DYN_VERIFY( p );
-
- p->updateLink( stamp.primaryIndex(), rep );
- }
- }
- }
-#endif
-
- m_state.setPrimaryIndex( stamp.primaryIndex() );
- m_state.increase();
-
-
- DYN_VERIFY_SAME( stamp, m_state );
-
- hashReplacement( rep );
-
- notifyInserted( rep );
-
- return stamp;
-}
-
-void DynamicText::dump() const {}
-
-VectorTimestamp DynamicText::state() const {
- return m_state;
-}
-
-VectorTimestamp DynamicText::initialState() const {
- return m_initialState;
-}
-
-struct SafetyCounter {
- uint m_cnt;
- uint m_maxCnt;
-public:
-
- SafetyCounter( uint max = 10000 ) : m_cnt( 0 ), m_maxCnt( max ) {}
-
- operator bool() {
- ++m_cnt;
- return m_cnt < m_maxCnt;
- }
-};
-
-VectorTimestamp DynamicText::tailState() const {
- VectorTimestamp target( m_state );
- for ( uint a = 0; a < m_unApplied.size(); a++ ) {
- if ( m_unApplied[ a ].last )
- target.maximize( m_unApplied[ a ].last->vectorStamp() );
- }
-
- return target;
-}
-
-///Changes the state to the newest one available
-bool DynamicText::toTail() {
- VectorTimestamp target( m_state );
- for ( uint a = 0; a < m_unApplied.size(); a++ ) {
- if ( m_unApplied[ a ].last )
- target.maximize( m_unApplied[ a ].last->vectorStamp() );
- }
-
- if ( !target.isZero() )
- changeStateInternal( target );
- return true;
-}
-
-OffsetMap DynamicText::offset( VectorTimestamp from, VectorTimestamp to, int position ) {
- if ( from == to )
- return OffsetMap();
-
- OffsetRequest request( from, to );
-
-// OffsetCache::iterator it = m_offsetCache.find( request );
-//
-// if ( it != m_offsetCache.end() ) {
-// return ( *it ).second;
-// }
-
- uint sz = m_applied.size();
-
- DYN_VERIFY_SMALLERSAME( to.size(), sz );
- DYN_VERIFY_SMALLERSAME( from.size(), sz );
-
- std::vector<ReplacementPointer> chains( sz );
- std::vector<ReplacementPointer> next( sz ); ///Contains the next replacement into the direction from -> to
- for ( uint a = 0; a < sz; a++ ) {
- chains[ a ] = replacement( a, from[ a ] );
- if ( chains[ a ] ) {
- DYN_VERIFY_SAME( chains[ a ] ->primaryStamp(), from[ a ] );
- }
- if ( to[ a ] < from[ a ] )
- next[ a ] = replacement( a, from[ a ] - 1 );
- else if ( to[ a ] > from[ a ] )
- next[ a ] = replacement( a, from[ a ] + 1 );
- }
-
- //VectorTimestamp currentState = from;
-
- SafetyCounter s( 10000 );
-
- bool waited = false;
- bool first = true;
-
- while ( waited || first ) {
- DYN_VERIFY( s );
- first = false;
-
- bool force = false;
- if ( waited ) { ///If there is an inheritance-chain, break it by just applying the first one.
- force = true;
- waited = false;
- }
-
- for ( uint a = 0; a < chains.size(); a++ ) {
- if ( from[ a ] != to[ a ] ) {
- bool unapply = from[ a ] > to[ a ];
- if ( !force ) {
- ///Find out if there's another one that can be unapplied, and that should be unapplied before this one. If there is one, wait.
- bool wait = false;
- for ( uint b = 0; b < chains.size(); b++ ) {
- if ( b == a )
- continue;
-
- if ( !chains[ b ] )
- continue;
-
- const VectorTimestamp& s2( chains[ b ] ->vectorStamp() );
- if ( from[ b ] >= s2[ b ] && s2[ b ] > to[ b ] ) {
- DYN_VERIFY( chains[ a ] );
- ///The other replacement has to be unapplied
- if ( unapply ) {
- ///Should the replacement b be unapplied before a is unapplied?
- if ( chains[ a ] ->vectorStamp() [ b ] < s2[ b ] || s2[ a ] >= from[ a ] ) {
- ///a expects b not to be applied || b expects a to be applied
- wait = true;
- break;
- }
- } else {
- ///Should the replacement b be unapplied before a is applied?
- DYN_VERIFY( next[ a ] );
- if ( next[ a ] ->vectorStamp() [ b ] < s2[ b ] || s2[ a ] < from[ a ] + 1 ) {
- ///next a expects b not to be applied || b expects next a not to be applied
- wait = true;
- break;
- }
- }
- }
-
- if ( from[ b ] < s2[ b ] && s2[ b ] <= to[ b ] ) {
- DYN_VERIFY( next[ b ] );
-
- if ( unapply ) {
- ///Should the replacement b be applied before a is unapplied?
- if ( chains[ a ] ->vectorStamp() [ b ] >= next[ b ] ->primaryStamp() || next[ b ] ->vectorStamp() [ a ] >= from[ a ] ) {
- ///a expects next b to be applied || next b expects a to be applied
- wait = true;
- break;
- }
- } else {
- ///Should the replacement b be applied before a is applied?
- DYN_VERIFY( next[ a ] );
- if ( next[ a ] ->vectorStamp() [ b ] > next[ b ] ->primaryStamp() || next[ b ] ->vectorStamp() [ a ] < from[ a ] + 1 ) {
- ///next a expects next b to be applied || next b expects next a not to be applied
- wait = true;
- break;
- }
- }
- }
- }
-
- if ( wait ) {
- waited = true;
- continue;
- }
- } else {
- force = false;
- }
-
- VectorTimestamp preNextStamp;
- VectorTimestamp nextStamp;
- VectorTimestamp intermediate;
- OffsetMap ret;
-
- if ( to[ a ] < from[ a ] ) {
- VectorTimestamp n = from;
- n.setPrimaryIndex( a );
- n.decrease(); ///n = the intermediate state we are stepping to
-
- VectorTimestamp prev = chains[a]->vectorStamp();
- prev.decrease(); ///prev = the state the replacement in chains[a] was applied to
-
- ///The position-checking needs to be done to avoid endless recursion
- OffsetMap innerOffset = ~offset( prev, n, chains[a]->replacement().m_position );
- ret = offset( n, to );
- if( position != INVALID_POSITION && position < innerOffset( chains[a]->replacement().m_position ) )
- return ret;
- ret = chains[a]->offset( innerOffset ) % ret;
- } else {
- VectorTimestamp n = from;
- n.setPrimaryIndex( a );
- n.increase();
- VectorTimestamp prev = next[a]->vectorStamp();
- prev.decrease();
- OffsetMap innerOffset = ~offset( prev, from, next[a]->replacement().m_position );
- ret = offset( n, to );
- if( position != INVALID_POSITION && position < innerOffset( next[a]->replacement().m_position ) )
- return ret;
- ret = ~next[a]->offset( innerOffset ) % ret;
- }
-
- /// Now: ret = offset( preNextStamp, nextStamp )
-
- /**chains[a]->offset() = of( v( chains[a].state ) -> chains[a].state )
- * with v(chains[a].state) = pre-state of chains[a].state (stamp at position primaryStamp decrease by one)
- *
- * Simple case: of( from -> to )(x) = of( next -> to )( ( of( from -> next )(x) )
- *
- * Problem: What if the current state does not exactly match the state created by the item to remove?
- * of( chains[a].prevStamp -> chains[a].stamp ) = chains[a]->offset()
- * of[ from -> to ](x) = of[chains[a].stamp -> to ]( of[ chains[a].prevStamp -> chains[a].stamp ] ( of[ from -> chains[a].prevStamp ](x) ) )
- **/
-
- m_offsetCache.insert( OffsetCache::value_type( request, ret ) );
- return ret;
- }
- }
- }
-
- DYN_VERIFY( 0 );
-}
-
-bool DynamicText::rewindInternal( const VectorTimestamp& state ) {
- SafetyCounter s( 10000 );
-
- bool applied = true;
- bool waited = false;
-
- while ( applied || waited ) {
- DYN_VERIFY( s );
-
- bool force = false;
- if ( waited && !applied ) { ///If there is an inheritance-chain, break it by just applying the first one.
- force = true;
- waited = false;
- }
- applied = false;
- waited = false;
-
-
- for ( uint a = 0; a < m_applied.size(); a++ ) {
- if ( state[ a ] > m_state[ a ] )
- continue;
- ReplacementChain& r( m_applied[ a ] );
- if ( !r.first && !r.last )
- continue;
- DYN_VERIFY( r.last );
- const VectorTimestamp& s( r.last->vectorStamp() );
-
- if ( s.primaryStamp() > state[ s.primaryIndex() ] ) {
-
- if ( !force ) {
- ///Find out if there's another one that can be unapplied, and that should be unapplied before this one. If there is one, wait.
- bool wait = false;
- for ( uint b = 0; b < m_applied.size(); b++ ) {
- if ( b == a )
- continue;
-
- ReplacementChain& r2( m_applied[ b ] );
- if ( !r2.first && !r2.last )
- continue;
- const VectorTimestamp& s2( r2.last->vectorStamp() );
-
- if ( s2.primaryStamp() > state[ s2.primaryIndex() ] && m_state[ s2.primaryIndex() ] >= s2.primaryStamp() ) {
- ///The other replacement has to be unapplied
- if ( s[ b ] < s2.primaryStamp() || s2[ a ] >= s.primaryStamp() ) {
- ///The other replacement should be unapplied before this one
- wait = true;
- break;
- }
- }
- }
-
- if ( wait ) {
- waited = true;
- continue;
- }
- } else {
- force = false;
- }
-
- //It can be unapplied now
- /*VectorTimestamp prev( s );
- prev.decrease();*/
-
-
- VectorTimestamp prevCurrent = m_state;
- prevCurrent.setPrimaryIndex( a );
- DYN_VERIFY_NOTSAME( prevCurrent.primaryStamp(), 0 );
-
- //prevCurrent.decrease();
-
- VectorTimestamp prev( s );
- //prev.decrease();
- OffsetMap offset;
- offset = ~this->offset( prev, prevCurrent, r.first->replacement().m_position - 1 ); ///@todo -1 or not?
-
- DYN_VERIFY( r.last->unApply( m_text, offset, m_currentOffset ) );
-
- m_state.setPrimaryIndex( s.primaryIndex() );
- m_state.decrease();
-
- applied = true;
-
- if ( m_unApplied.size() <= a )
- m_unApplied.resize( a + 1 );
-
- if ( m_unApplied[ a ].first ) {
- DYN_VERIFY_SAME( r.last, m_unApplied[ a ].first->prev() );
- m_unApplied[ a ].first = r.last;
- } else {
- m_unApplied[ a ].first = m_unApplied[ a ].last = r.last;
- }
- if ( r.last->prev() ) {
- r.last = r.last->prev();
- } else {
- r.first = r.last = 0;
- }
- }
- }
- }
-
- DYN_VERIFY( m_state.smallerOrSame( state ) );
-
- return true;
-}
-/*
-// ReplacementPointer DynamicText::findBound( const VectorTimestamp& stamp ) {
-// }
-
-OffsetMap DynamicText::backwardsOffset( const VectorTimestamp& to ) {
-DYN_VERIFY( to.smallerOrSame( m_state ) );
-DYN_VERIFY( m_allReplacements.iterator( to ) );
-
-bool applied = true;
-
-int sz = m_applied.size();
-
-DYN_VERIFY_SMALLERSAME( to.size(), sz );
-DYN_VERIFY_SMALLERSAME( m_state.size(), sz );
-//DYN_VERIFY( sz >= to.size() && sz >= m_state.size() );
-
-std::vector<ReplacementPointer> chains( sz );
-for ( int a = 0; a < sz; a++ ) {
- chains[ a ] = m_applied[ a ].last;
- if ( chains[ a ] )
- DYN_VERIFY( chains[ a ] ->primaryIndex() == a );
-}
-
-OffsetMap offset = m_currentOffset;
-VectorTimestamp currentState = m_state;
-
-SafetyCounter s( 10000 );
-
-while ( applied ) {
- DYN_VERIFY( s );
- applied = false;
- for ( int a = 0; a < sz; a++ ) {
- if ( !chains[ a ] )
- continue;
- DYN_VERIFY ( to[ a ] <= currentState[ a ] );
- DYN_VERIFY( chains[ a ] );
-
- VectorTimestamp s = chains[ a ] ->vectorStamp();
- //s.decrease();
-
- if ( !( currentState == to ) && s == currentState ) {
- offset = offset % ( ~chains[ a ] ->offset() );
- applied = true;
- chains[ a ] = chains[ a ] ->prev();
- s.decrease();
- currentState = s;
- }
- }
-}
-
-DYN_VERIFY( currentState == to );
-return offset;
-}*/
-
-bool DynamicText::advanceInternal( const VectorTimestamp& state ) {
- DYN_VERIFY( m_state.smallerOrSame( state ) );
- if ( state.isZero() )
- return true;
-
- uint sz = m_applied.size();
- /*
- DYN_VERIFY_SMALLERSAME( sz, state.size() );
- DYN_VERIFY_SMALLERSAME( sz, m_state.size() );*/
-
- if ( m_unApplied.size() < m_applied.size() )
- m_unApplied.resize( m_applied.size() );
-
- bool applied = true;
- bool waited = false;
-
- SafetyCounter s( 10000 );
-
- while ( applied || waited ) {
- DYN_VERIFY( s );
-
- bool force = false;
- if ( waited && !applied ) { ///If there is an inheritance-chain, break it by just applying the first one.
- force = true;
- waited = false;
- }
- applied = false;
- waited = false;
-
- //Apply all replacements that can be applied to the current state, and need to be applied.
- for ( uint a = 0; a < sz; a++ ) {
- DYN_VERIFY_SMALLERSAME ( m_state[ a ], state[ a ] );
- ReplacementChain& r( m_unApplied[ a ] );
- if ( !r.first && !r.last )
- continue;
- DYN_VERIFY( r.first );
- const VectorTimestamp& s( r.first->vectorStamp() );
-
- if ( s.primaryStamp() <= state[ s.primaryIndex() ] ) {
-
- if ( !force ) {
- ///Find out if there's another one that can be applied, and that should be applied before this one. If there is one, wait.
- bool wait = false;
- for ( uint b = 0; b < sz; b++ ) {
- if ( b == a )
- continue;
-
- ReplacementChain& r2( m_unApplied[ b ] );
- if ( !r2.first && !r2.last )
- continue;
- const VectorTimestamp& s2( r2.first->vectorStamp() );
-
- if ( s2.primaryStamp() <= state[ s2.primaryIndex() ] && m_state[ s2.primaryIndex() ] < s2.primaryStamp() ) {
- ///The other replacement has to be applied
- if ( s[ b ] >= s2.primaryStamp() || s2[ a ] < s.primaryStamp() ) {
- ///The other replacement should be applied before this one
- wait = true;
- break;
- }
- }
- }
-
- if ( wait ) {
- waited = true;
- continue;
- }
- } else {
- force = false;
- }
-
- //It can be applied now
- VectorTimestamp prev( s );
- prev.decrease();
- OffsetMap offset;
- offset = ~this->offset( prev, m_state, r.first->replacement().m_position-1 );
-
- DYN_VERIFY( r.first->apply( m_text, offset, m_currentOffset ) );
-
- m_state.setPrimaryIndex( s.primaryIndex() );
- m_state.increase();
-
- applied = true;
- if ( m_applied[ a ].last ) {
- DYN_VERIFY_SAME( m_applied[ a ].last, r.first->prev() );
- m_applied[ a ].last = r.first;
- } else {
- m_applied[ a ].last = m_applied[ a ].first = r.first;
- }
- if ( r.first->next() ) {
- r.first = r.first->next();
- } else {
- r.last = r.first = 0;
- }
- }
- }
- }
-
- DYN_VERIFY_SAME( m_state, state );
- return m_state == state;
-}
-
-bool DynamicText::rewind( const VectorTimestamp& state ) {
- VectorTimestamp v = m_state;
- try {
- rewindInternal( state );
- } catch ( const CatchedDynamicTextError & err ) {
- if ( v != m_state )
- notifyStateChanged();
- throw;
- }
-
-
- if ( v != m_state )
- notifyStateChanged();
- return true;
-}
-
-///The given state must be bigger/same than the current state in every stamp
-bool DynamicText::advance( const VectorTimestamp& state ) {
- VectorTimestamp v = m_state;
- try {
- advanceInternal( state );
- } catch ( const CatchedDynamicTextError & err ) {
-
- if ( v != m_state )
- notifyStateChanged();
- throw;
- }
-
- if ( v != m_state )
- notifyStateChanged();
- return true;
-}
-
-bool DynamicText::changeState( const VectorTimestamp& state, bool force ) {
- VectorTimestamp v = m_state;
- bool ret;
- try {
- ret = changeStateInternal( state, force );
- } catch ( const CatchedDynamicTextError & err ) {
- if ( v != m_state )
- notifyStateChanged();
- throw;
- }
-
- if ( v != m_state )
- notifyStateChanged();
- return ret;
-}
-
-bool DynamicText::changeStateInternal( const VectorTimestamp& state, bool /*force*/ ) {
- if ( state.isZero() )
- return toTail();
- if ( state == m_state )
- return true;
- ///First some verification
-
- for ( uint a = 0; a < m_applied.size(); a++ ) {
- if ( m_applied[ a ].last == 0 )
- continue;
- DYN_VERIFY_SAME( m_applied[ a ].last->primaryIndex(), a );
- DYN_VERIFY_SAME( m_applied[ a ].last->primaryStamp(), m_state[ a ] );
- }
-
- DYN_VERIFY( rewindInternal( state ) );
-
- DYN_VERIFY( advanceInternal( state ) );
-
-
- return true;
-}
-
-void DynamicText::cut() {
- for ( uint a = 0; a < m_applied.size(); a++ ) {
- if ( m_applied[ a ].last )
- m_applied[ a ].last->setNext( 0 );
- }
- for ( uint a = 0; a < m_unApplied.size(); a++ ) {
- m_unApplied[ a ].first = 0;
- m_unApplied[ a ].last = 0;
- }
-}
-
-DynamicText::DynamicText( const VectorTimestamp& initialState, const String& initialText ) : m_text( initialText ), m_initialText( initialText ), m_state( initialState ), m_initialState( initialState ) {
- m_dummy = new Replacement();
-}
-
-ReplacementPointer DynamicText::replacement( uint primaryIndex, Timestamp stamp ) {
- ReplacementSet::Iterator it = m_allReplacements.values( ReplacementId( primaryIndex, stamp ) );
- if ( it && *it ) {
- return ( *it ).get();
- } else {
- return 0;
- }
-}
-
-void DynamicText::hashReplacement( const ReplacementPointer& rep ) {
- DYN_VERIFY( !m_allReplacements.find( rep ) );
- m_allReplacements.insert( rep );
-}
-
-void DynamicText::unHashReplacement( const ReplacementPointer& rep ) {
- m_allReplacements.remove( rep );
-}
-
-void DynamicText::notifyInserted( const ReplacementPointer& /*rep*/ ) {}
-
-void DynamicText::notifyStateChanged() {}
-
-//BOOST_CLASS_EXPORT_GUID( DynamicText, "DynamicText" )
-
-template bool Replacement::unApply( DynamicText::Text& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
-template bool Replacement::apply( DynamicText::Text& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
-
-///For testing
-template bool Replacement::unApply( std::string& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
-template bool Replacement::apply( std::string& text, const OffsetMap& outerOffset, OffsetMap& contextOffset );
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictext.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h (nonexistent)
@@ -1,99 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef OFFSETUTILS_H
-#define OFFSETUTILS_H
-
-#include <map>
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/map.hpp>
-#include <string>
-#include <iosfwd>
-#include "dynamictextexport.h"
-
-typedef int OffsetPosition;
-
-using namespace std;
-
-///Can be thrown by OffsetMap.
-struct OffsetMapError {
- enum Type {
- Inconsistent
- };
- Type t;
-
- OffsetMapError( Type type );
-
- const char* asText() const;
-};
-
-///@todo there's a lot of room for optimizations in this.. but first make sure everything works correctly. Everything may throw DynamicTextError
-
-class DYNAMICTEXT_EXPORT OffsetMap {
- public:
- void clear();
-
- OffsetMap( OffsetPosition position, int offset );
-
- OffsetMap();
-
- /**Returns true if the given map can be inserted without making the map inconsistent
- * */
- bool isCompatible( const OffsetMap& rhs ) const;
-
- /**Insert the given offset-map into this one(while transforming it through this one).
- * corresponds to the mathematical function-operator o (like g o f).
- * Let the function for the current map be f(x), the inserted be g(x), and the resulting map be h(x).
- * Then h(x) = f(g(x))
- *
- * This function may throw OffsetMapError if the insertion would make the map inconsistent.
- *
- * */
- OffsetMap operator %( const OffsetMap& rhs ) const;
-
- OffsetMap& operator %=( const OffsetMap& rhs );
-
- /**Inverts the offset-map(like the mathematical inversion of a function)
- * */
- OffsetMap operator ~() const;
-
- OffsetMap engInvert() const;
-
- void printMap() const;
-
- std::string print() const;
-
- ///Applies the function defined by this offset-map to the given parameter
- int operator () ( const OffsetPosition position ) const;
-
- template <class Archive>
- void serialize( Archive& arch, const OffsetPosition ) {
- arch & m_offsets;
- }
- private:
- typedef std::map<OffsetPosition, int> OffsetInternalMap;
-
- ///Iterator may get deleted
- void makeConsistent( OffsetInternalMap::iterator position );
-
- int getOffset( OffsetPosition position ) const;
-
- void addOffset( OffsetPosition position, int offset );
- void mergeOffset( OffsetPosition position, int offset );
-
- OffsetInternalMap m_offsets;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/offsetutils.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h (nonexistent)
@@ -1,56 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef DYNAMICTEXT_VERIFY_H
-#define DYNAMICTEXT_VERIFY_H
-
-#include <string>
-#include <sstream>
-#include "dynamictextexport.h"
-
-struct DynamicTextErrorDummy {
- std::string what() const {
- return "";
- }
-};
-
-struct DYNAMICTEXT_EXPORT DynamicTextError {
- std::string function;
- int line;
- std::string file;
- std::string expression;
- std::string realExpression;
- DynamicTextError( const std::string& fun, int l = 0, const std::string& f = "", const std::string& exp = "", const std::string& realExp = "" );
- std::string what() const;
-};
-
-#define DYN_VERIFY( x ) if( x ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #x ); }
-#define DYN_VERIFY_SAME( a, b ) if( a == b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" == " ) + #b, "\"" + toText( a ) + std::string( "\" == \"" ) + toText( b ) + "\"" ); }
-#define DYN_VERIFY_SMALLER( a, b ) if( a < b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" < " ) + #b, "\"" + toText( a ) + std::string( "\" < \"" ) + toText( b ) + "\"" ); }
-#define DYN_VERIFY_SMALLERSAME( a, b ) if( a <= b ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" <= " ) + #b, "\"" + toText( a ) + std::string( "\" <= \"" ) + toText( b ) + "\"" ); }
-#define DYN_VERIFY_NOTSAME( a, b ) if( !(a == b) ){}else{ throw DynamicTextError( __FUNCTION__, __LINE__, __FILE__, #a + std::string(" != " ) + #b, "\"" + toText( a ) + std::string( "\" != \"" ) + toText( b ) + "\"" ); }
-
-
-
-#ifndef HAVE_TOTEXT
-#define HAVE_TOTEXT
-template <class Item>
-std::string toText( const Item& it ) {
- ostringstream os;
- os << it;
- return os.str();
-}
-#endif
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/verify.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h (nonexistent)
@@ -1,495 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef FLEXIBLETEXT_H
-#define FLEXIBLETEXT_H
-
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/split_member.hpp>
-#include <boost/serialization/deque.hpp>
-#include <boost/serialization/string.hpp>
-#include <iostream>
-#include <list>
-#include <sstream>
-#include <deque>
-
-#include "sumtree.h"
-#include "flexibletextnotifier.h"
-#include "dynamictextexport.h"
-
-namespace SumTree {
-
-template<class Tp>
-class DYNAMICTEXT_EXPORT TemporaryExchange {
- public:
- TemporaryExchange( Tp& target, Tp newValue ) : target_(target), oldValue_(target) {
- target_ = newValue;
- }
- ~TemporaryExchange() {
- target_ = oldValue_;
- }
- private:
- Tp& target_;
- Tp oldValue_;
-};
-///This is just a little helper that autmatically deleted unremoved members of a string-list on exceptions etc.
-///If they should be used on elsewhere, they must be removed from this list.
-template <class StringList>
-struct DYNAMICTEXT_EXPORT ManagedStringList {
- ManagedStringList( const StringList& rhs ) : list( rhs ) {}
-
- void delete_front() {
- delete list.front();
- list.pop_front();
- }
-
- ~ManagedStringList() {
- for ( typename StringList::iterator it = list.begin(); it != list.end(); ++it ) {
- delete *it;
- }
- }
-
- StringList* operator -> () {
- return & list;
- }
- StringList list;
-};
-
-/**This is a class that simulates a normal string, but is much more flexible and allows access using line/column- and index-information.
- * For big documents that are edited it is much more efficient than a string, because much less allocation has to be done, since the
- * document is internally stored within smaller units(divided into lines).
- *
- * Any function in this class may throw DynamicTextError on error!
- * */
-
-template <class String, class Char = char, Char lineBreak = '\n'>
-class DYNAMICTEXT_EXPORT FlexibleText {
- typedef std::deque<String*> StringVector;
- public:
- typedef std::list<String*> StringList;
-
- FlexibleText( const String& text = "" ) : notify_(0) {
- build( text );
- }
-
- ~FlexibleText() {
- deleteText();
- }
-
-// template <class StringListType>
-// FlexibleText( const StringListType& text ) {
-// build( text );
-// }
-
- FlexibleText( const FlexibleText& rhs ) : notify_(0) {
- operator=( rhs );
- }
-
- FlexibleText& operator = ( const FlexibleText& rhs ) {
- deleteText();
- for( typename StringVector::const_iterator it = rhs.text_.begin(); it != rhs.text_.end(); ++it ) {
- text_.push_back( new String( **it ) );
- }
- lineColMap_ = rhs.lineColMap_;
- return *this;
- }
-
- void linearToLineColumn( int position, int& line, int& column ) const {
- SumTree::IndexAndSum s;
- lineColMap_.indexAndSum( position, s );
- line = s.index;
- column = position - s.sum;
- }
-
- int lineColumnToLinear( int line, int column ) const {
- return lineColMap_.sum( line ) + column;
- }
-
- String substr( int position, int count ) const {
- SumTree::IndexAndSum s;
- lineColMap_.indexAndSum( position, s );
- return substr( s.index, position - s.sum, count );
- }
-
-
- void replace( int position, int length, const String& replacement )
- {
- ///Maybe implement this more efficiently as a single action
- if( notify_ )
- notify_->notifyFlexibleTextReplace( position, length, replacement );
- TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
-
- SumTree::IndexAndSum s;
- lineColMap_.indexAndSum( position, s );
- int column = position - s.sum;
- erase( s.index, column, length );
- insert( s.index, column, replacement );
- }
-
- void insert( int position, const String& text )
- {
- if( notify_ )
- notify_->notifyFlexibleTextInsert( position, text );
- TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
-
- SumTree::IndexAndSum s;
- lineColMap_.indexAndSum( position, s );
- insert( s.index, position - s.sum, text );
- }
-
- ///Remove 'length' charateres at position 'position'. remove and erase do the same, they are provided for compatibility with Qt and STL.
- void remove( int position, int length ) {
- return erase( position, length );
- }
-
- ///Remove 'length' charateres at position 'position'. remove and erase do the same, they are provided for compatibility with Qt and STL.
- void erase( int position, int length )
- {
- if( notify_ )
- notify_->notifyFlexibleTextErase( position, length );
- TemporaryExchange< FlexibleTextNotifier<String>* > hideNotify( notify_, 0 );
-
- SumTree::IndexAndSum s;
- lineColMap_.indexAndSum( position, s );
- erase ( s.index, position - s.sum, length );
- }
-
- String substr( int line, int column, int count ) const {
- String ret;
- int currentColumn = column;
- int currentLine = line;
- uint size = text_.size();
- while ( count > 0 ) {
- if ( currentLine >= (int)size )
- return ret;
- int get
- = min( text_[ currentLine ] ->length() - column, count );
- ret += text_[ currentLine ] ->substr( column, get
- );
- count -= get
- ;
- if ( count != 0 ) {
- ret.append( "\n" );
- count -= 1;
- }
- currentLine++;
- currentColumn = 0;
- }
- return ret;
- }
-
- int length() const {
- int s = lineColMap_.sum();
- DYN_VERIFY_SMALLER( 0, s );
- return s - 1;
- }
-
- ///SHould be called time by time(for efficiency), especially if many insertions have been done.
- void rebuildTree() {
- //lineColMap_ = lineColMap_.rebuild();
- }
-
- void checkConsistency() {
-#ifdef EXTREMEDEBUG
- int sum = 0;
- int num = 0;
- int sz = text_.size();
- for ( typename StringVector::iterator it = text_.begin(); it != text_.end(); ++it ) {
- int lineColSum = lineColMap_.sum( num );
- if( lineColMap_.indexValue( num ) != (*it)->length() + 1 || sum != lineColSum ) {
- cout << "consistency-fail: at line " << num << " text: \n" << dump() << "offsets-tree: " << lineColMap_.dump() << endl;
- }
-
- DYN_VERIFY_SAME( lineColMap_.indexValue( num ), (*it)->length() + 1 );
- DYN_VERIFY_SAME( sum, lineColSum );
- num++;
- sum += ( *it ) ->length() + 1;
- }
-#endif
- };
-
- ///Returns the whole text as the normal string-representation
- String text() const {
- return substr( 0, 0, length() );
- }
-
- /*operator String() const {
- return substr( 0, 0, length() );
- }*/
-
- std::string dump() const {
- String ret;
- int line = 0;
- for( typename StringVector::const_iterator it = text_.begin(); it != text_.end(); ++it ) {
- std::ostringstream os; os << "line " << line << "(len " << (*it)->length() << "): \"" << **it << "\"\n";
- ret += os.str();
- line++;
- }
- return ret;
- }
-
- std::string dumpTree() const {
- return lineColMap_.dump();
- }
-
- template<class Archive>
- void save( Archive& arch, const uint ) const {
- int lines = text_.size();
- arch << lines;
- for( typename StringVector::const_iterator it = text_.begin(); it != text_.end(); ++it ) {
- arch << **it;
- }
- }
-
- template<class Archive>
- void load( Archive& arch, const uint ) {
- deleteText();
-
- int lines;
- arch >> lines;
-
- for( int a = 0; a < lines; a++ ) {
- String* s = new String();
- arch >> *s;
- text_.push_back( s );
- }
- rebuildTree();
- }
-
- ///Very inefficient, ranges should be used whenever possible
- Char operator [] ( uint offset ) const {
- IndexAndSum s;
- lineColMap_.indexAndSum( offset, s );
- return (*text_[s.index])[offset - s.sum];
- }
-
- /** Register a notifier that will be notified with ANY change to the text, exactly before the change is applied */
- void registerNotifier( FlexibleTextNotifier<String>* notifier ) const {
- notify_ = notifier;
- };
-
- /** unregister a previously registered notifier */
- void unregisterNotifier() const {
- notify_ = 0;
- }
-
- BOOST_SERIALIZATION_SPLIT_MEMBER()
- private:
-
- ///Erase and insert could be public, the only problem is that the change-notification would become more complicated(currently notification is done in linear measure)
-
- void insert( int line, int column, const String& text ) {
-#ifdef EXTREMDEBUG
- cout << "insertion at " << line << ":" << column << " length " << text.length() << " of \"" << text << "\"" << endl;
- checkConsistency();
-#endif
- uint len = text.length();
- if( len == 0 ) return;
- int currentStart = 0;
- bool nobreak = true;
- String endAppend; ///Needs to be appended to the last line inserted
- int l = line + 1;
-
- for ( uint a = 0; a < len; a++ ) {
- if ( text[ a ] == lineBreak ) {
- if( nobreak ) {
- ///It is the first line, put it into the insertion-line and break.
- int insertLength = a - currentStart;
- String& curLine( *text_[line] );
- int removeLength = curLine.length() - column;
- DYN_VERIFY_SMALLERSAME( 0, removeLength );
- ///Copy the last part of the line it is inserted to, and append it to the last line inserted.
- endAppend = curLine.substr( column, removeLength );
-
- ///Replace the removed part of the inserted-to line with the first inserted line
- lineColMap_.changeIndexValue( line, insertLength - removeLength );
- text_[ line ] ->replace( column, removeLength, text, currentStart, insertLength );
- } else {
- ///Now insert all other lines behind "line"
- text_.insert( text_.begin() + l, new String( text, currentStart, a - currentStart ) );
- lineColMap_.insertIndex( l, a - currentStart + 1 );
- l++;
- }
-
- currentStart = a + 1;
- nobreak = false;
- }
- }
-
- if( nobreak ) {
- text_[ line ] ->insert( column, text );
- lineColMap_.changeIndexValue( line, len );
-#ifdef EXTREMDEBUG
- checkConsistency();
-#endif
- } else {
- ///insert the last part
- String* s = new String( text, currentStart, len - currentStart );
- s->append( endAppend );
- text_.insert( text_.begin() + l, s );
- lineColMap_.insertIndex( l, s->length() + 1 );
- }
-
-#ifdef EXTREMEDEBUG
- cout << "text after: \n" << dump() << "offsets after: " << lineColMap_.dump() << endl;
- checkConsistency();
-#endif
- }
-
- ///Remove 'length' characters in line 'line', starting at column 'column'. If the length is longer than the rest of the line, this will continue deleting in the next line.
- void erase( int line, int column, int length ) {
-#ifdef EXTREMEDEBUG
- cout << "erasing " << line << ":" << column << " length " << length << endl;
- cout << "text before: \n" << dump() << "offsets before: " << lineColMap_.dump() << endl;
- checkConsistency();
-#endif
-
- if ( length == 0 )
- return ;
-
-#ifdef EXTREMEDEBUG
- DYN_VERIFY_SMALLERSAME( 0, removeLength );
- DYN_VERIFY_SAME( text_[ line ] ->length() + 1, lineColMap_.indexValue( line ) );
- DYN_VERIFY_SMALLER( 0, lineColMap_.indexValue( line ) );
-#endif
- int removeLength = min( length, text_[ line ] ->length() - column );
- int lengthLeft = length - removeLength;
- lineColMap_.changeIndexValue( line, -removeLength );
- text_[ line ] ->erase( column, removeLength );
- bool broken = true;
-
- if ( lengthLeft )
- lengthLeft -= 1; ///Count one character for the linebreak, because it is removed and the next line pushed up
- else
- return ;
-
- ///First find out what exactly has to be removed
- int currentLine = line;
-
- while ( lengthLeft > 0 ) {
- currentLine++;
- lengthLeft -= text_[ currentLine ] ->length();
- if ( lengthLeft > 0 ) {
- broken = true;
- lengthLeft -= 1; ///If the whole line is removed, also count the linebreak.
- } else {
- broken = false;
- }
- }
-
- ///Add the rest of the line that caused the stop to the beginning line
- if ( lengthLeft != 0 ) {
- ///Add the last -lengthLeft characters to text_[line]
- text_[ line ] ->append( text_[ currentLine ] ->substr( text_[ currentLine ] ->length() + lengthLeft, -lengthLeft ) );
- lineColMap_.changeIndexValue( line, -lengthLeft );
- } else if ( broken ) {
- ///Move the next unaffected line up
- if ( (int)text_.size() > currentLine + 1 ) {
- currentLine++;
- uint len = text_[ currentLine ] ->length();
- text_[ line ] ->append( *text_[ currentLine ] );
- lineColMap_.changeIndexValue( line, len );
- }
- }
-
- ///Remove all unneeded lines
- for ( int a = line + 1; a <= currentLine; a++ ) {
- delete text_[ a ];
- lineColMap_.removeIndex( line + 1 );
- }
-
- text_.erase( text_.begin() + line + 1, text_.begin() + currentLine + 1 );
-
-#ifdef EXTREMDEBUG
- checkConsistency();
-#endif
- }
-
- void deleteText() {
- for( typename StringVector::iterator it = text_.begin(); it != text_.end(); ++it ) {
- delete *it;
- }
- text_.clear();
- }
- StringList split( const String& text ) {
- StringList ret;
- uint len = text.length();
- int currentStart = 0;
-
- for ( uint a = 0; a < len; a++ ) {
- if ( text[ a ] == lineBreak ) {
- ret.push_back( new String( text.substr( currentStart, a - currentStart ) ) );
- currentStart = a + 1;
- }
- }
- //if ( currentStart != len )
- ret.push_back( new String( text.substr( currentStart, len - currentStart ) ) );
-
- return ret;
- }
- template <class StringListType>
- void build( const StringListType& lines ) {
- std::vector<int> length;
- int size = lines.size();
- length.resize( size );
-
- int a = 0;
- for ( typename StringListType::const_iterator i = lines.begin(); i != lines.end(); i++ ) {
- length[ a ] = i->length() + 1; ///Plus one for the next-line character
- text_.push_back( new String( *i ) );
- a++;
- }
-
- //length[ size - 1 ] -= 1; ///The last line should not get the linebreak.
- lineColMap_ = SumTree::Map( length );
- }
-
- void build( const String& text ) {
- std::vector<int> length;
- ManagedStringList<StringList> lines( split( text ) );
- int size = lines->size();
- length.resize( size );
-
- int a = 0;
- while( !lines->empty() ) {
- length[ a ] = lines->front()->length() + 1; ///Plus one for the next-line character
- text_.push_back( lines->front() );
- lines->pop_front();
- a++;
- }
-
- //length[ size - 1 ] -= 1; ///The last line should not get the linebreak.
- lineColMap_ = SumTree::Map( length );
- }
-
- inline static int min( int a, int b ) {
- return a < b ? a : b;
- }
-
- mutable FlexibleTextNotifier<String>* notify_;
- StringVector text_; ///Not the most intelligent solution(some combination of maps and offset-maps would be perfect)
- SumTree::Map lineColMap_;
-};
-}
-
-template <class String, class Char, Char lineBreak>
-std::ostream& operator << ( std::ostream& o, const SumTree::FlexibleText<String, Char, lineBreak>& rhs ) {
- o << rhs.text();
- return o;
-}
-
-
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletext.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h (nonexistent)
@@ -1,32 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#ifndef FLEXIBLETEXT_NOTIFIER
-#define FLEXIBLETEXT_NOTIFIER
-
-namespace SumTree {
-
- ///Override this so you are able to register your class to be notified of changes in a FlexibleText
- ///All of these functions are called by FlexibleText immediately BEFORE the replacement is done
- ///Only one of those notifications is called, even though a replacement may internally be implemented by erasing and inserting.
- ///These are allowed to throw DynamicTextError
- template<class StringType>
- class FlexibleTextNotifier {
- public:
- virtual void notifyFlexibleTextErase( int position, int length ) = 0;
- virtual void notifyFlexibleTextInsert( int position, const StringType& text ) = 0;
- virtual void notifyFlexibleTextReplace( int position, int length, const StringType& replacement ) = 0;
- virtual ~FlexibleTextNotifier(){};
- };
-}
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/flexibletextnotifier.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h (nonexistent)
@@ -1,145 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#define private public
-
-#ifndef DYNAMICTEXT_HELPERS
-#define DYNAMICTEXT_HELPERS
-
-#include <iosfwd>
-
-#include "offsetutils.h"
-#include "verify.h"
-#include "../network/sharedptr.h"
-#include "../network/weaksafesharedptr.h"
-#include "vectortimestamp.h"
-#include "dynamictextexport.h"
-
-///Check whether these are useful for something or should be completely removed
-//#define USELINKS
-
-class DynamicText;
-class Replacement;
-class Advancer;
-typedef SharedPtr<Replacement, BoostSerializationNormal> ReplacementPointer;
-typedef WeakSharedPtr<Replacement, BoostSerializationNormal> WeakReplacementPointer;
-
-struct DYNAMICTEXT_EXPORT SimpleReplacement {
- uint m_position;
- std::string m_oldText;
- std::string m_newText;
- SimpleReplacement() : m_position( 0 ) {
- }
- SimpleReplacement( uint position, const std::string& newText, const std::string& oldText ) : m_position( position ), m_oldText( oldText ), m_newText( newText ) {}
-
- operator bool() const {
- return m_oldText.length() != 0 || m_newText.length() != 0;
- }
- template<class Archive>
- void serialize( Archive& arch, const uint ) {
- arch & m_position & m_oldText & m_newText;
- }
-};
-
-DYNAMICTEXT_EXPORT std::ostream& operator << ( std::ostream& o, const SimpleReplacement& rhs );
-
-class DYNAMICTEXT_EXPORT Replacement : public WeakShared {
- public:
-
- Replacement( const VectorTimestamp& state, const SimpleReplacement& repl ) : m_state( state ), m_replacement( repl ), m_enabled(true) {}
- Replacement() : m_enabled(true) {}
-
- ///Returns a map that simulates applying the replacement. of( x -> y ) with x pre-state of this state, and y state of this.
- OffsetMap offset( const OffsetMap& ofs = OffsetMap() );
-
- ReplacementPointer next() const;
- ReplacementPointer prev() const;
-
- bool enabled() const;
-
- ///These only compare the primary stamp
- bool operator < ( const Replacement& rhs ) const throw(DynamicTextError);
- bool operator <= ( const Replacement& rhs ) const throw(DynamicTextError);
-
- uint primaryIndex() const;
- Timestamp primaryStamp() const;
-
- const VectorTimestamp& vectorStamp() const;
-
- template<class Archive>
- void serialize( Archive& arch, const uint ) {
- arch & m_state & m_replacement & m_next & m_prev & m_enabled;
- }
-
- const SimpleReplacement& replacement() const {
- return m_replacement;
- }
-
- ///This must only be changed in an unapplied state. Else it will lead to corruption of the document.
- void setEnabled( bool e );
-
- private:
- void setNext( ReplacementPointer next );
- void setPrev( ReplacementPointer prev );
-
- template<class TextType>
- bool apply( TextType& text, const OffsetMap& offset, OffsetMap& staticOffset );
- template<class TextType>
- bool unApply( TextType& text, const OffsetMap& offset, OffsetMap& staticOffset );
-
-#ifdef USE_LINKS
- ///Checks whether "link" should be put into the "links"-map. If it should
- void updateLink( uint index, ReplacementPointer link );
-#endif
-
- friend class DynamicText;
- VectorTimestamp m_state; ///Each Replacement has a unique primary stamp, m_next has the same plus 1, m_prev the same minus one.
-
- SimpleReplacement m_replacement;
-
- ///One is weak one is not, so a chain of replacements cannot keep itself alive. Once the first is lost, all are lost.
- ReplacementPointer m_next;
- WeakReplacementPointer m_prev;
-
-#ifdef USELINKS
- std::vector<WeakReplacementPointer> m_links; ///This maps the index-numbers of other Collaborators to their first replacement that uses the timestamp of this Replacement.
-#endif
-
- bool m_enabled;
-};
-
-struct DYNAMICTEXT_EXPORT ReplacementChain {
- ReplacementPointer first, last;
- template<class Archive>
- void serialize( Archive& arch, const uint ) {
- arch & first & last;
- }
-};
-
-struct DYNAMICTEXT_EXPORT ReplacementId {
- uint primaryIndex;
- Timestamp stamp;
- ReplacementId( uint i = 0, Timestamp st = 0 ) : primaryIndex( i ), stamp( st ) {}
- ReplacementId( ReplacementPointer p ) : primaryIndex( p->primaryIndex() ), stamp( p->primaryStamp() ) {}
- bool operator < ( const ReplacementId& rhs ) const {
- return primaryIndex < rhs.primaryIndex || ( primaryIndex == rhs.primaryIndex && stamp < rhs.stamp );
- }
- template<class Archive>
- void serialize( Archive& arch, const uint version ) {
- arch & primaryIndex & stamp;
- }
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/lib/dynamictext/dynamictexthelpers.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake (nonexistent)
@@ -1,59 +0,0 @@
-# - Try to find libcommoncpp2
-#
-# COMMONCPP2_FOUND - system has libcommoncpp2
-# COMMONCPP2_INCLUDE_DIRS - the commoncpp2 include directory
-# COMMONCPP2_LIBRARIES - The libraries needed to use commoncpp2
-
-
-IF(COMMONCPP2_INCLUDE_DIRS AND COMMONCPP2_LIBRARIES)
- # Already in cache, be silent
- SET(Commoncpp_FIND_QUIETLY TRUE)
-ENDIF(COMMONCPP2_INCLUDE_DIRS AND COMMONCPP2_LIBRARIES)
-
-IF( NOT WIN32 )
- INCLUDE(UsePkgConfig)
- PKGCONFIG(libccgnu2 _Libccgnu2IncDir _Libccgnu2LinkDir _Libccgnu2LinkFlags _Libccgnu2Cflags)
- SET(LIBCCGNU2_DEFINITIONS ${_Libccgnu2Cflags})
- PKGCONFIG(libccext2 _Libccext2IncDir _Libccext2LinkDir _Libccext2LinkFlags _Libccext2Cflags)
- SET(LIBCCEXT2_DEFINITIONS ${_Libccext2Cflags})
- SET(COMMONCPP2_DEFINTIONS ${LIBCCGNU2_DEFINITIONS} ${LIBCCEXT2_DEFINITIONS})
-ENDIF( NOT WIN32 )
-
-FIND_PATH(COMMONCPP2_INCLUDE_DIRS cc++/network.h
- PATHS
- ${_Libccgnu2IncDir}
- PATH_SUFFIX cc++
-)
-
-FIND_LIBRARY(LIBCCGNU2_LIBRARY NAMES ccgnu2 libccgnu2
- PATHS
- ${_Libccext2LinkDir}
-)
-
-FIND_LIBRARY(LIBCCEXT2_LIBRARY NAMES ccext2 libccext2
- PATHS
- ${_Libccext2LinkDir}
-)
-
-IF(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
- SET(COMMONCPP2_FOUND TRUE)
- SET(COMMONCPP2_LIBRARIES ${LIBCCGNU2_LIBRARY} ${LIBCCEXT2_LIBRARY})
-ELSE(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
- SET(COMMONCPP2_FOUND FALSE)
-ENDIF(COMMONCPP2_INCLUDE_DIRS AND LIBCCGNU2_LIBRARY AND LIBCCEXT2_LIBRARY)
-
-IF(COMMONCPP2_FOUND)
- IF(NOT Commoncpp_FIND_QUIETLY)
- MESSAGE(STATUS "Found libccgnu2 and libccext2 ${COMMONCPP2_LIBRARIES}")
- ENDIF(NOT Commoncpp_FIND_QUIETLY)
-ELSE(COMMONCPP2_FOUND)
- IF(Commoncpp_FIND_REQUIRED)
- MESSAGE(FATAL_ERROR "Could not find libccgnu2 or libccext2")
- ELSE(Commoncpp_FIND_REQUIRED)
- MESSAGE(STATUS "Could not find libccgnu2 or libccext2, teamwork plugin disabled")
- ENDIF(Commoncpp_FIND_REQUIRED)
-ENDIF(COMMONCPP2_FOUND)
-
-SET(COMMONCPP2_LIBRARIES ${COMMONCPP2_LIBRARIES} CACHE String "All libraries of Common C++")
-
-MARK_AS_ADVANCED( COMMONCPP2_INCLUDE_DIRS LIBCCGNU2_LIBRARY LIBCCEXT2_LIBRARY COMMONCPP2_LIBRARIES )
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindCommoncpp.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.h (nonexistent)
@@ -1,188 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef PATCHESMANAGER_H
-#define PATCHESMANAGER_H
-//#include <boost/serialization/list.hpp>
-#include <list>
-#include <string>
-#include <QObject>
-#include <QMetaType>
-#include <QStandardItemModel>
-#include <QPointer>
-
-#include "lib/network/serialization.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/easymessage.h"
-
-#include "ui_kdevteamwork_managepatches.h"
-#include "kdevteamwork_messages.h"
-#include "patchmessage.h"
-
-#include "utils.h"
-
-
-using namespace std;
-using namespace Teamwork;
-
-class EditPatch;
-class QDomElement;
-class IconCache;
-class KDevTeamwork;
-class KDevTeamworkClient;
-class PatchesManager;
-typedef SafeSharedPtr<KDevTeamworkClient> TeamworkClientPointer;
-typedef SharedPtr<EditPatch> EditPatchPointer;
-
-
-struct PatchesManagerConfig {
- std::list<LocalPatchSourcePointer> patchSources;
-
- template <class Archive>
- void serializePatches( Archive& arch, const uint /*version*/ ) {
- arch & NVP( patchSources );
- }
-
- template <class Archive>
- void serialize( Archive& arch, const uint version ) {
- serializePatches( arch, version );
- }
-
- bool hasPatch( const LocalPatchSourcePointer& patch ) {
- for ( std::list<LocalPatchSourcePointer>::iterator it = patchSources.begin(); it != patchSources.end(); ++it ) {
- if ( *it == patch )
- return true;
- }
- return false;
- }
-
- void addPatch( const LocalPatchSourcePointer& patch ) {
- patchSources.push_back( patch );
- }
-};
-
-BIND_LIST_4( PatchesManagerMessages, PatchesManagerMessage, PatchesListMessage, PatchRequestMessage, PatchMessage )
-
-class PatchesManager : public QObject {
- Q_OBJECT
- public:
- PatchesManager( KDevTeamwork* tw );
- ~PatchesManager();
-
- void showPatchInfo( const LocalPatchSourcePointer& patch , bool local = true );
-
- void restorePartialProjectSession( const QDomElement* el );
-
- void savePartialProjectSession( QDomElement* el );
-
- void fillDeveloperActions( const QModelIndex& index, QMenu* menu );
-
- void addPatch( const LocalPatchSourcePointer& patch );
- bool hasPatch( const LocalPatchSourcePointer& patch );
-
- ///Tries to find out whether the patch is applied by using the patch-command in dry-run mode. Only works with patch-files(not commands). Fills the result into the given patch
- LocalPatchSource::State determineState( const LocalPatchSourcePointer& patch );
-
- ///Tries to merge the patches to one. If it fails, returns zero.
- LocalPatchSourcePointer merge( const QString& name, const QList<LocalPatchSourcePointer>& patches );
-
- KDevTeamwork* teamwork();
-
- public slots:
- void processMessage( PatchesManagerMessagePointer );
- private slots:
- void save();
- void load();
- void editDialogClosed( EditPatch* );
- void editStateChanged( EditPatch* );
-
- void guiUpdatePatchesList();
-
- void init();
- void slotManagePatches();
- void slotUpdateConnection( TeamworkClientPointer newClient );
-
- ///The patches-management-menu:
- void slotEditPatch();
- void slotAddPatch();
- void slotRemovePatch();
- void slotCloseManagement();
- void slotManagementFinished( int result );
-
- ///The developer/patch context-menu:
- void slotShowPatch();
- void slotShowPatchInfo();
- void slotApplyPatch();
- void slotDownloadPatch();
-
- ///The patch-message context-menu
- void slotShowRequestedPatch();
- void slotDenyPatch();
- void slotAllowPatch();
-
- private:
- EditPatchPointer showEditDialog( const LocalPatchSourcePointer& patch, bool local );
- ///Actions for the developer/patch-menu:
- QAction* m_showPatchAction;
- QAction* m_showPatchInfoAction;
- QAction* m_downloadPatchAction;
- QAction* m_applyPatchAction;
-
- LocalPatchSourcePointer::Locked patchFromIdentity( const LocalPatchSource::Identity& identity );
-
- void log( const QString& str, LogLevel level = Info );
-
- LocalPatchSourcePointer selectedPatch();
-
- ///The edit-dialog:
- LocalPatchSourcePointer patchFromEdit(); ///may return invalid pointer
- void fillEditFromPatch( LocalPatchSourcePointer patch , bool local = true );
-
- KDevTeamwork* m_teamwork;
- PatchesManagerConfig m_config;
-
- friend class MessageDispatcher< PatchesManager, PatchesManagerMessages >;
- friend class EditPatch;
-
- MessageDispatcher< PatchesManager, PatchesManagerMessages > dispatcher_;
-
- Ui_ManagePatches m_managePatches;
- QPointer<KDialog> m_manageDlg;
-
- QStandardItemModel* m_patchesModel;
-
- LocalPatchSourcePointer m_editingPatch;
-
- void applyPatch( LocalPatchSourcePointer::Locked patch, bool reverse = false );
-
- int receiveMessage( MessageInterface* msg );
- int receiveMessage( PatchesManagerMessage* msg );
- int receiveMessage( PatchesListMessage* msg );
- int receiveMessage( PatchRequestMessage* msg );
- int receiveMessage( PatchMessage* msg );
-
- QList<EditPatchPointer> m_editing;
-
- ///Actions for the PatchRequestMessage-menu:
- QAction* m_denyPatchAction;
- QAction* m_allowPatchAction;
- QAction* m_showRequestedPatchAction;
-
- QTimer* m_updateTimer;
- friend class PatchRequestData;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/patchesmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp (nonexistent)
@@ -1,42 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "qdynamictext.h"
-#include "lib/network/serialization.h"
-#include <boost/serialization/export.hpp>
-
-QDynamicText::QDynamicText( const VectorTimestamp& initialState, const std::string& initialText ) : DynamicText( initialState, initialText ) {
-}
-
-void QDynamicText::notifyInserted( const ReplacementPointer& rep ) {
- emit inserted( rep, *this );
-}
-
-void QDynamicText::notifyStateChanged() {
- emit stateChanged( *this );
-}
-
-QDynamicText::QDynamicText( const QDynamicText& rhs ) : QObject(), DynamicText( rhs ) {
-}
-
-QDynamicText& QDynamicText::operator = ( const QDynamicText& rhs ) {
- DynamicText::operator=( rhs );
- return *this;
-}
-
-//BOOST_CLASS_EXPORT_GUID(QDynamicText, "QDynamicText")
-
-
-#include "qdynamictext.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/qdynamictext.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui (nonexistent)
@@ -1,321 +0,0 @@
-<ui version="4.0" >
- <class>UserInfo</class>
- <widget class="QWidget" name="UserInfo" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>419</width>
- <height>202</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="2" column="0" >
- <widget class="QFrame" name="frame" >
- <property name="frameShape" >
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>1</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="menuButton" >
- <property name="text" >
- <string>Menu</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <property name="orientation" >
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" >
- <size>
- <width>121</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="historyButton" >
- <property name="text" >
- <string>History</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item row="1" column="0" >
- <widget class="QGroupBox" name="groupBox" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>5</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font" >
- <font>
- <family>Sans Serif</family>
- <pointsize>9</pointsize>
- <weight>75</weight>
- <italic>false</italic>
- <bold>true</bold>
- <underline>false</underline>
- <strikeout>false</strikeout>
- </font>
- </property>
- <property name="title" >
- <string>Description</string>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QLabel" name="description" >
- <property name="font" >
- <font>
- <family>Sans Serif</family>
- <pointsize>9</pointsize>
- <weight>50</weight>
- <italic>false</italic>
- <bold>false</bold>
- <underline>false</underline>
- <strikeout>false</strikeout>
- </font>
- </property>
- <property name="text" >
- <string comment="KDE::DoNotExtract" >TextLabel</string>
- </property>
- <property name="wordWrap" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0" >
- <widget class="QFrame" name="frame_2" >
- <property name="frameShape" >
- <enum>QFrame::StyledPanel</enum>
- </property>
- <property name="frameShadow" >
- <enum>QFrame::Raised</enum>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="icon" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string/>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="name_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Name&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="name" >
- <property name="text" >
- <string>Name</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="email_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">E-Mail&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="email" >
- <property name="text" >
- <string>E-Mail</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0" >
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QLabel" name="state_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">State&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item row="0" column="3" >
- <widget class="QLabel" name="ipadress" >
- <property name="text" >
- <string>IP-Address</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1" >
- <widget class="QLabel" name="state" >
- <property name="text" >
- <string>State</string>
- </property>
- </widget>
- </item>
- <item row="0" column="2" >
- <widget class="QLabel" name="ipadress_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">IP-Adress&lt;/span>:&lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QLabel" name="rights_2" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>&lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css">
-p, li { white-space: pre-wrap; }
-&lt;/style>&lt;/head>&lt;body style=" font-family:Sans Serif; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;">
-&lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;span style=" font-weight:600;">Rights&lt;/span>: &lt;/p>&lt;/body>&lt;/html></string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="rights" >
- <property name="text" >
- <string>Rights</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_userinfo.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui (nonexistent)
@@ -1,30 +0,0 @@
-<ui version="4.0" >
- <class>InDocumentButtons</class>
- <widget class="QWidget" name="InDocumentButtons" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>333</width>
- <height>51</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>9</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QPushButton" name="jumpToPosition" >
- <property name="text" >
- <string>Jump to Position</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_indocumentmessagebuttons.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp (nonexistent)
@@ -1,425 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "collaborationmanager.h"
-#include "lib/network/messagesendhelper.h"
-#include <QPersistentModelIndex>
-#include <QMenu>
-#include <QMetaType>
-#include "filecollaborationmanager.h"
-#include "messagemanager.h"
-#include "kdevteamwork_user.h"
-#include "kdevteamwork_client.h"
-#include <QModelIndex>
-#include <QPoint>
-#include <QTimer>
-#include "ui_kdevteamwork_interface.h"
-#include <QStandardItemModel>
-
-Q_DECLARE_METATYPE( MessagePointer )
-using namespace std;
-typedef QPointer<FileCollaborationSession> QFileCollaborationSessionPointer;
-Q_DECLARE_METATYPE( QPersistentModelIndex )
-Q_DECLARE_METATYPE( QFileCollaborationSessionPointer )
-
-CollaborationManager::CollaborationManager( KDevTeamwork* tw ) : SafeLogger( tw->logger() ), m_teamwork( tw ), m_fileCollaboration( this ), m_ignoreClick( false ) {
-
- m_contextMenuTimer = new QTimer( this );
- m_contextMenuTimer->setSingleShot( true );
-
- connect( m_contextMenuTimer, SIGNAL( timeout() ), this, SLOT( maybeContextMenu() ) );
-
- m_closeCollaborationAction = new QAction( i18n("Stop Collaboration"), this );
- connect( m_closeCollaborationAction, SIGNAL( triggered() ), this, SLOT( uiCloseCollaboration() ) );
-
- m_developersModel = new QStandardItemModel( 0, 1, this );
-
- qRegisterMetaType<MessagePointer>( "MessagePointer" );
- qRegisterMetaType<QFileCollaborationSessionPointer>( "QFileCollaborationSessionPointer" );
-
- m_acceptConnectionAction = new QAction( i18n("Accept Collaboration"), this );
- connect( m_acceptConnectionAction, SIGNAL( triggered() ), this, SLOT( uiAcceptCollaboration() ) );
- m_acceptConnectionAction->setToolTip( i18n("Start a collaboration-session with the user.") );
-
- m_denyConnectionAction = new QAction( i18n("Refuse Collaboration"), this );
- connect( m_denyConnectionAction, SIGNAL( triggered() ), this, SLOT( uiDenyCollaboration() ) );
- m_denyConnectionAction->setToolTip( i18n("Refuse collaborating with the user.") );
-
- m_requestCollaborationAction = new QAction( i18n("Request Collaboration"), this );
- connect( m_requestCollaborationAction, SIGNAL( triggered() ), this, SLOT( uiRequestCollaboration() ) );
- m_requestCollaborationAction->setToolTip( i18n("Request a collaboration-session to the selected user.") );
-
- connect( m_teamwork, SIGNAL(init()), this, SLOT(init() ) );
-}
-
-void CollaborationManager::init() {
- connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( collaboratingDeveloperClicked( const QModelIndex& ) ) );
- connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( collaboratingDeveloperDoubleClicked( const QModelIndex& ) ) );
-
- connect( m_teamwork->widgets().connectedDevelopers, SIGNAL( customContextMenuRequested( const QPoint& ) ), this, SLOT(collaboratingDeveloperContextMenu( const QPoint& ) ) );
-
- connect( m_teamwork, SIGNAL( updateConnection(TeamworkClientPointer) ), this, SLOT( updateConnection(const TeamworkClientPointer&) ) );
- m_closeCollaborationAction->setToolTip( i18n("Stop collaborating with the selected developer.") );
-}
-
-CollaborationManager::~CollaborationManager() {
-}
-
-void CollaborationManager::addCollaboratingUser( const UserPointer& u ) {
- if ( u )
- m_collaboratingUsers.insert( u );
- m_teamwork->startUpdateTimer();
-}
-
-void CollaborationManager::removeCollaboratingUser( const UserPointer& user ) {
- m_collaboratingUsers.erase( user );
- m_teamwork->startUpdateTimer();
-}
-
-bool CollaborationManager::isCollaborating( const UserPointer& user ) {
- return m_collaboratingUsers.find( user ) != m_collaboratingUsers.end();
-}
-
-void CollaborationManager::sessionStateChanged( const FileCollaborationSessionPointer& /*session*/ ) {
- updateList();
-}
-
-void CollaborationManager::updateList() {
- QStandardItemModel* model = m_developersModel;
- /*model->clear();
- model->insertColumn( 0 );*/
-
- ///find all users and sessions, and where they are stored in the tree-view
- QMap< UserPointer, QPersistentModelIndex > users;
-
- for( int r = 0; r < model->rowCount(); ++r ) {
- QModelIndex i = model->index( r, 0 );
- if( !i.isValid() ) continue;
- QVariant v = i.data( Qt::UserRole );
-
- if( v.canConvert<UserPointer>() ) {
- users[ v.value<UserPointer>() ] = QPersistentModelIndex( i );
- } else {
- for( int r2 = 0; r2 < model->rowCount( i ); ++r2 ) {
- QModelIndex i2 = model->index( r2, 0, i );
- if( !i2.isValid() ) continue;
-
- QVariant v = i.data( Qt::UserRole );
-
- if( v.canConvert<UserPointer>() )
- users[ v.value<UserPointer>() ] = QPersistentModelIndex( i2 );
- }
- }
- }
-
- ///Now remove all users that are not collaborating anymore
- for( QMap< UserPointer, QPersistentModelIndex >::iterator it = users.begin(); it != users.end(); ++it ) {
- if( m_collaboratingUsers.find( it.key() ) == m_collaboratingUsers.end() )
- model->removeRows( it->row(), 1, it->parent() );
- }
-
- ///Now add/update all users
- for ( UserSet::reverse_iterator it = m_collaboratingUsers.rbegin(); it != m_collaboratingUsers.rend(); ++it ) {
- //FileCollaborationSessionPointer session = m_fileCollaboration->sessions().value( (*it).cast<KDevTeamworkUser>() );
-
- KDevTeamworkUserPointer::Locked l = (*it).cast<KDevTeamworkUser>();
-
- QModelIndex iparent;//( sessions[session] );
- ///Insert the user
- QModelIndex i;
- if( users.contains( l.data() ) ) {
- i = users[l.data()];
- } else {
- model->insertRow( 0, iparent );
- i = model->index( 0, 0, iparent );
- }
-
- ///Update user-data
- if ( l ) {
- QIcon icon = l->icon();
- model->setData( i, ~l->User::name(), Qt::DisplayRole );
- model->setData( i, icon, Qt::DecorationRole );
- } else {
- model->setData( i, QString( "not lockable" ), Qt::DisplayRole );
- }
- QVariant lv;
- lv.setValue( *it );
-
- model->setData( i, lv, Qt::UserRole );
- }
-
- emit updateModel( model );
-}
-
-void CollaborationManager::maybeContextMenu() {
- if( !m_ignoreClick && m_contextMenuIndex.get() && m_contextMenuIndex->isValid() ) {
- QModelIndex i = *m_contextMenuIndex;
- QPoint p = QCursor::pos();
- contextMenu( p, i );
- }
-
- m_ignoreClick = false;
- m_contextMenuIndex.reset( 0 );
-}
-
-void CollaborationManager::collaboratingDeveloperDoubleClicked( const QModelIndex& index ) {
- m_ignoreClick = true;
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- m_teamwork->guiSendMessageTo( v.value<UserPointer>() );
- } else if( v.canConvert<CollaborationTreeActionPointer>() ) {
- CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
- if( p ) {
- p->doubleClicked();
- }
- }
-}
-
-
-
-void CollaborationManager::collaboratingDeveloperClicked( const QModelIndex& index ) {
- if ( !index.isValid() )
- return ;
- QVariant v = index.model() ->data( index, Qt::UserRole );
- //if ( v.canConvert<UserPointer>() ) {
- m_contextMenuIndex.reset( new QPersistentModelIndex( index ) );
- m_contextMenuTimer->start( 250 );
- /*} else if( v.canConvert<CollaborationTreeActionPointer>() ) {
- CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
- if( p ) {
- p->clicked();
- }
- }*/
-
-}
-
-void CollaborationManager::contextMenu( const QPoint& p, const QModelIndex& index ) {
-
- if(!index.isValid() )
- return;
- QMenu menu;
-
- QVariant v = index.model() ->data( index, Qt::UserRole );
- if ( v.canConvert<UserPointer>() ) {
- m_teamwork->fillUserMenu( &menu, v.value<UserPointer>() );
- m_teamwork->getPatchesList( v.value<UserPointer>() );
-
- if( isCollaborating( v.value<UserPointer>() ) )
- emit fillCollaboratingUserMenu( &menu, v.value<UserPointer>() );
-
- m_closeCollaborationAction->setData( v );
- menu.addAction( m_closeCollaborationAction );
- } else if( v.canConvert<CollaborationTreeActionPointer>() ) {
- CollaborationTreeActionPointer p = v.value<CollaborationTreeActionPointer>();
- if( p ) {
- p->fillContextMenu( &menu );
- }
- }
-
- if( !menu.isEmpty() )
- menu.exec( p );
-}
-
-void CollaborationManager::collaboratingDeveloperContextMenu( const QPoint& p ) {
-
- QModelIndex index = m_teamwork->widgets().connectedDevelopers->indexAt( p );
-
- contextMenu( p, index );
-}
-
-void CollaborationManager::uiCloseCollaboration() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<UserPointer>() )
- throw "cannot convert model-index";
-
- UserPointer::Locked lUser = v.value<UserPointer>();
- if( !lUser ) throw "failed to lock user";
-
- removeCollaboratingUser( lUser );
-
- m_teamwork->startUpdateTimer();
- if ( !m_teamwork->client() || !lUser->online().session() )
- throw "no physical collaboration";
-
- globalMessageSendHelper().send<KDevSystemMessage>( lUser->online().session().unsafe(), KDevSystemMessage::CollaborationClosed, "stopping collaboration" );
- }
- catch ( QString & str ) {
- err() << "in uiCloseCollaboration:" << str;
- } catch ( const char * str ) {
- err() << "in uiCloseCollaboration:" << str;
- }
-}
-
-void CollaborationManager::fillUserMenu( QMenu* menu, const UserPointer& user ) {
- if ( !isCollaborating( user ) ) {
- UserPointer::Locked l = user;
- if ( l && l->online() ) {
- QVariant v;
- v.setValue( user );
- m_requestCollaborationAction->setData( v );
- menu->addAction( m_requestCollaborationAction );
- }
- }
- //emit fillCollaboratingUserMenu( menu, user );
-}
-
-void CollaborationManager::updateConnection( const TeamworkClientPointer& cl ) {
- if( cl ) {
- connect( cl.unsafe(), SIGNAL(signalDispatchMessage(CollaborationMessagePointer)), this, SLOT(processMessage(const CollaborationMessagePointer&)) );
- } else {
- m_developersModel->clear();
- m_developersModel->insertColumn( 0 );
- }
-}
-
-void CollaborationManager::processMessage( const CollaborationMessagePointer& msg ) {
- if( msg.cast< FileCollaborationMessage >() ) ///Here a dispatcher is not necessary yet
- m_fileCollaboration->processMessage( msg.cast< FileCollaborationMessage >() );
-}
-
-void CollaborationManager::restorePartialProjectSession( const QDomElement* /*el*/ ) {}
-
-void CollaborationManager::savePartialProjectSession( QDomElement* /*el*/ ) {}
-
-void setValueMessage( QVariant& v, const MessagePointer& msg );
-
-void ConnectionRequest::fillContextMenu( QMenu* menu, KDevTeamwork* teamwork ) {
- if ( m_state == Waiting ) {
- QVariant v;
- setValueMessage( v, MessagePointer( this ) );
- teamwork->collaborationManager()->m_acceptConnectionAction->setData( v );
- menu->addAction( teamwork->collaborationManager()->m_acceptConnectionAction );
- teamwork->collaborationManager()->m_denyConnectionAction->setData( v );
- menu->addAction( teamwork->collaborationManager()->m_denyConnectionAction );
- menu->addSeparator();
- }
-}
-
-KDevTeamwork * CollaborationManager::teamwork() {
- return m_teamwork;
-}
-
-FileCollaborationManager& CollaborationManager::fileCollaborationManager() {
- return *m_fileCollaboration;
-}
-
-QStandardItemModel * CollaborationManager::developersModel( )
-{
- return m_developersModel;
-}
-
-void CollaborationManager::uiAcceptCollaboration() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "error";
-
- QVariant v = act->data();
-
- if ( !v.canConvert<MessagePointer>() )
- throw "cannot convert data";
-
- MessagePointer::Locked lMessage = v.value<MessagePointer>();
-
- if ( lMessage && lMessage.cast<ConnectionRequest>() ) {
- if ( lMessage->info().session() ) {
- lMessage.cast<ConnectionRequest>() ->setState( ConnectionRequest::Accepted );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( lMessage, KDevSystemMessage::CollaborationAccepted, "collaboration accepted" );
- if ( lMessage->info().user() )
- addCollaboratingUser( lMessage->info().user() );
- m_teamwork->messageManager()->updateMessage( lMessage );
-
- m_teamwork->startUpdateTimer();
- }
- } else {
- throw "could not lock message-info or client-class";
- }
- } catch ( const char * str ) {
- err() << "in uiAcceptCollaboration:" << str;
- }
-}
-
-void CollaborationManager::uiDenyCollaboration() {
- try {
- if ( !m_teamwork->client() )
- throw "client not running";
-
- QAction* act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "error";
-
- QVariant v = act->data();
-
- if ( !v.canConvert<MessagePointer>() )
- throw "cannot convert data";
-
- MessagePointer::Locked lMessage = v.value<MessagePointer>();
-
- if ( lMessage && lMessage.cast<ConnectionRequest>() ) {
- if ( lMessage->info().session() ) {
- lMessage.cast<ConnectionRequest>() ->setState( ConnectionRequest::Accepted );
- globalMessageSendHelper().sendReply<KDevSystemMessage>( lMessage, KDevSystemMessage::CollaborationRefused, "collaboration denied" );
- m_teamwork->messageManager()->updateMessage( lMessage );
- }
- } else {
- throw "could not lock message-info or client-class";
- }
- } catch ( const char * str ) {
- err() << "in uiDenyCollaboration: " << str;
- }
-}
-
-void CollaborationManager::uiRequestCollaboration() {
- TeamworkClientPointer::Locked l = m_teamwork->client();
-
- try {
- if ( !l )
- throw "could not client while requesting connection" ;
- QAction* act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "error in uiDenyCollaboration";
-
- QVariant v = act->data();
-
- if ( !v.canConvert<UserPointer>() )
- throw "error in uiDenyCollaboration, cannot convert data";
-
- UserPointer::Locked user = v.value<UserPointer>();
- UserPointer::Locked ident = l->identity();
- if ( user && ident ) {
- if ( user->online().session() ) {
- ConnectionRequest * msg = new ConnectionRequest( l->messageTypes(), ident, user, "please let me connect", m_teamwork );
- user->online().session().unsafe() ->send( msg );
- m_teamwork->addMessageToList( msg );
- } else {
- throw "no open session to the target-user";
- }
- } else {
- throw "could not lock target-user or local user";
- }
- } catch ( const char * str ) {
- err() << "uiRequestCollaboration:" << str;
- }
-}
-
-
-#include "collaborationmanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/collaborationmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp (nonexistent)
@@ -1,223 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "indocumentreference.h"
-#include "utils.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-QString InDocumentReference::createReference( const QString& file, int startLine, int startCol, int endLine, int endCol ) {
- QString ret = file;
- if( startLine != -1 ) ret.append( QString( ":%1" ).arg( startLine ) );
- if( startCol != -1 ) ret.append( QString( ":%1" ).arg( startCol ) );
- if( endLine != -1 ) ret.append( QString( ":%1" ).arg( endLine ) );
- if( endCol != -1 ) ret.append( QString( ":%1" ).arg( endCol ) );
- return ret;
-}
-
-void InDocumentReference::parseReference( const QString& ref, QString& file, int& startLine, int& startCol, int& endLine, int& endCol ) {
- file = "";
- startLine = endLine = startCol = endCol = -1;
- if ( ref.indexOf( ':' ) != -1 ) {
- file = ref.left( ref.indexOf( ':' ) );
-
- QString tail = ref.mid( file.length()+1 );
-
- int refs[4] = {-1, -1, -1, -1};
- for( int a = 0; a < 4; a++ ) {
- if( tail.isEmpty() ) break;
- int nextPos = tail.indexOf( ':' );
- if( nextPos == -1 ) nextPos = tail.length();
- refs[a] = tail.left( nextPos ).toInt();
- tail = tail.mid( nextPos+1 );
- if( tail.isEmpty() ) break;
- }
-
- startLine = refs[0];
- startCol = refs[1];
- endLine = refs[2];
- endCol = refs[3];
- }
-}
-
-///This creates a reference that refers to a position, but not intelligently.
-InDocumentReference::InDocumentReference( bool start, const QString& ref ) : m_line( -1 ), m_col( -1 ) {
- int d1, d2;
- QString doc;
- if( start )
- parseReference( ref, doc, m_line, m_col, d1, d2 );
- else
- parseReference( ref, doc, d1, d2, m_line, m_col );
- m_document = ~doc;
-}
-
-InDocumentReference::InDocumentReference( const QString& document, int line, int col, const QString& text ) {
- m_line = line;
- m_document = ~document;
- m_col = col;
- if ( !text.isEmpty() )
- useText( text );
-}
-
-void InDocumentReference::useText( const QString& text ) {
- if ( m_line == -1 )
- return ;
- int index = lineColToIndex( text, m_line, m_col == -1 ? 0 : m_col );
- if ( index != -1 ) {
- SumSearch<10> search( ~text );
- m_position = search.getReference( index );
- }
-}
-
-QString InDocumentReference::document() const {
- return ~m_document;
-}
-
-struct InDocumentReference::TextSearchInstance::Private : public Shared {
- SumSearch<10> search;
- QString text;
-
- Private( const QString& txt ) : search( ~txt ), text( txt ) {
-
- }
-};
-
-
-InDocumentReference::TextSearchInstance::TextSearchInstance( const TextSearchInstance& rhs ) {
- *this = rhs;
-}
-
-InDocumentReference::TextSearchInstance::TextSearchInstance( const QString& txt ) {
- m_data = new Private( txt );
-}
-
-InDocumentReference::TextSearchInstance::TextSearchInstance() {
-}
-
-QString InDocumentReference::TextSearchInstance::text() const {
- if( !m_data ) return "";
- else
- return m_data->text;
-}
-
-InDocumentReference::TextSearchInstance::~TextSearchInstance() {
-}
-
-InDocumentReference::TextSearchInstance& InDocumentReference::TextSearchInstance::operator = ( const TextSearchInstance& rhs ) {
- m_data = rhs.m_data;
- return *this;
-}
-
-InDocumentReference::TextSearchInstance::operator bool() const {
- return (bool)m_data;
-}
-
-///Finds the reference-position dynamically within the given text. If the search fails, puts -1 -1.
-void InDocumentReference::findInText( const TextSearchInstance& text, int& line, int& col ) const {
- if ( !isValid() || !text ) {
- line = -1;
- col = -1;
- return ;
- }
- int pos = text.m_data->search.findReference( m_position );
-
- if ( pos == -1 ) {
- line = -1;
- col = -1;
- return ;
- /*
- ///Fall bock to returning the fixed line- and column-numbers
- line = m_line;
- if( m_col != -1 )
- col = m_col;
- else
- col = 0; */
- } else {
- indexToLineCol( pos, text.m_data->text, line, col );
- }
-}
-
-bool InDocumentReference::isValid() const {
- return ( m_line != -1 ) && !m_document.empty();
-}
-
-bool InDocumentReference::isDynamic() const {
- return m_position.isValid();
-}
-
-InDocumentReference::operator bool() const {
- return isValid();
-}
-
-///findInText(..) should be preferred, because it can find the correct position even if the text changed.
-int InDocumentReference::line() const {
- return m_line;
-}
-
-QString InDocumentReference::asText() const {
- QString ret = QString( "%1" ).arg( m_line );
- if ( m_col != 0 && m_col != -1 )
- ret += QString( ":%1" ).arg( m_col );
- if ( m_position.isValid() )
- ret = "~" + ret;
- return ret;
-}
-
-int InDocumentReference::col() const {
- if ( m_col != -1 )
- return m_col;
- else
- return 0;
-}
-
-DocumentContextLines::DocumentContextLines() : m_lineOffset( 0 ) {}
-
-DocumentContextLines::DocumentContextLines( const InDocumentReference& beginRef, const InDocumentReference& endRef, const QString& text, int /*contextSize*/ ) : m_lineOffset( 0 ) {
- int startLine = beginRef.line();
- int endLine = endRef.line();
- if ( startLine == -1 )
- return ;
- m_lineOffset = startLine - 5;
- if ( endLine == -1 )
- endLine = startLine;
- int end = endLine + 5;
- if ( m_lineOffset < 0 )
- m_lineOffset = 0;
- if ( end < m_lineOffset )
- end = m_lineOffset + 1;
-
- int i = lineColToIndex( text, m_lineOffset, 0 );
- if ( i == -1 ) {
- m_lineOffset = 0;
- return ;
- }
- int endI = lineColToIndex( text, end, 0 );
- if ( endI == -1 )
- endI = text.size();
-
- m_lines = ~text.mid( i, endI - i );
-}
-
-DocumentContextLines::operator bool() const {
- return !m_lines.empty();
-}
-
-QString DocumentContextLines::text() const {
- return ~m_lines;
-}
-
-int DocumentContextLines::lineOffset() const {
- return m_lineOffset;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/indocumentreference.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.h (nonexistent)
@@ -1,60 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGESENDMANAGER_H
-#define MESSAGESENDMANAGER_H
-
-#include <QObject>
-#include <QPointer>
-#include "ui_kdevteamwork_interface.h"
-#include <ktexteditor/range.h>
-
-namespace KDevelop {
-class IDocument;
-}
-
-namespace KTextEditor {
- class View;
- class Document;
-}
-
-/**This cares about the "send message"-tab in the kdevteamwork user-interface by updating it, according to the current selection in the current document.
- * */
-class MessageSendManager : public QObject {
- Q_OBJECT
- public:
- MessageSendManager( Ui::Teamwork& widgets );
-
- private slots:
- void documentActivated( KDevelop::IDocument* document );
- void documentClosed( KDevelop::IDocument* document );
- void documentDestroyed( QObject* obj );
- void selectionChanged( KTextEditor::View* );
- void viewCreated( KTextEditor::Document* , KTextEditor::View* );
- private:
- void connectView( KTextEditor::View* view );
- void connectDocument( KDevelop::IDocument* );
- void disconnectDocument();
- Ui::Teamwork& m_widgets;
- KDevelop::IDocument* m_lastDocument;
-
- KTextEditor::View* view();
-
- KUrl m_currentFile; ///Currently edited file
- KTextEditor::Range m_currentSelection; ///Current selection within that file
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.h (nonexistent)
@@ -1,74 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef MESSAGEUSERTAB_H
-#define MESSAGEUSERTAB_H
-
-#include <QObject>
-#include <QPointer>
-#include "autoconstructpointer.h"
-
-#include "ui_kdevteamwork_list.h"
-#include "lib/network/safesharedptr.h"
-
-class QWidget;
-class QListView;
-class QStandardItemModel;
-class KDevTeamworkUser;
-class MessageSerialization;
-typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
-
-namespace Teamwork {
- class MessageInterface;
- typedef SafeSharedPtr< MessageInterface, MessageSerialization > MessagePointer;
-}
-
-class KDevTeamwork;
-
-class MessageUserTab : public QObject, public Shared {
- Q_OBJECT
- QPointer<QWidget> m_widget;
- QStandardItemModel* m_model;
- QListView* m_view;
- KDevTeamworkUserPointer m_user;
- KDevTeamwork* m_teamwork;
-
- /*MessageUserTab( const MessageUserTab& rhs );*/
-
- MessageUserTab& operator = ( const MessageUserTab& rhs );
-
- AutoConstructPointer<Ui_List> m_list;
-
- public:
- MessageUserTab( KDevTeamwork* tw, KDevTeamworkUserPointer user );
-
- ~MessageUserTab();
-
- bool operator < ( const MessageUserTab& rhs );
-
- QStandardItemModel* model();
-
- QListView* view() ;
-
- KDevTeamworkUserPointer user();
-
- QWidget* widget();
-
- void messageUpdated( const Teamwork::MessagePointer& msg );
-
- public slots:
- void userStateChanged( KDevTeamworkUserPointer );
-};
-
-#endif
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.cpp (nonexistent)
@@ -1,123 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "utils.h"
-#include <QDomDocument>
-#include <QDomNode>
-#include <QTextStream>
-#include <sstream>
-#include <iostream>
-//#include <ostringstream>
-#include <QList>
-#include <QByteArray>
-#include <boost/serialization/extended_type_info_typeid.hpp>
-#include <boost/serialization/split_free.hpp>
-#include <boost/serialization/level.hpp>
-#include <boost/serialization/traits.hpp>
-#include <boost/serialization/level_enum.hpp>
-
-
-QString toQ( const std::string& str ) {
- return QString::fromUtf8( str.c_str() );
- //return QString::fromStdString( str );
-}
-
-std::string fromQ( const QString& str ) {
- return str.toUtf8().data();
- //return QString::toStdString( str );
-}
-
-std::string operator ~ ( const QString& rhs ) {
- return fromQ( rhs );
-}
-
-QString operator ~ ( const std::string& rhs ) {
- return toQ(rhs );
-}
-
-std::ostream& operator << ( std::ostream& stream, const QString& str ) {
- stream << str.toUtf8().data();
- return stream;
-}
-
-void indexToLineCol( int position, const QString& text, int& line, int& col ) {
- line = 0;
- col = 0;
- int tlen = (int)text.length();
- for( int a = 0; a < tlen; a++ )
- {
- if( a == position ) return;
- if( text[a] == '\n' ) {
- line++;
- col = 0;
- } else {
- col++;
- }
- }
- return;
-}
-
-int lineColToIndex( const QString& text, int sline, int scol ) {
- int line = 0;
- int col = 0;
- int tlen = (int)text.length();
- for( int a = 0; a < tlen; a++ )
- {
- if( line == sline && col == scol ) return a;
- if( text[a] == '\n' ) {
- line++;
- col = 0;
- } else {
- col++;
- }
- }
- if( line == sline && col == scol ) return tlen; ///Include the last bounding index
- return -1;
-}
-
-void indexToLineCol( int position, const std::string& text, int& line, int& col ) {
- line = 0;
- col = 0;
- int tlen = (int)text.length();
- for( int a = 0; a < tlen; a++ )
- {
- if( a == position ) return;
- if( text[a] == '\n' ) {
- line++;
- col = 0;
- } else {
- col++;
- }
- }
- return;
-}
-
-int lineColToIndex( const std::string& text, int sline, int scol ) {
- int line = 0;
- int col = 0;
- int tlen = (int)text.length();
- for( int a = 0; a < tlen; a++ )
- {
- if( line == sline && col == scol ) return a;
- if( text[a] == '\n' ) {
- line++;
- col = 0;
- } else {
- col++;
- }
- }
- if( line == sline && col == scol ) return tlen; ///Include the last bounding index
- return -1;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/utils.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui (nonexistent)
@@ -1,64 +0,0 @@
-<ui version="4.0" >
- <class>NewFileCollaborationSession</class>
- <widget class="QWidget" name="NewFileCollaborationSession" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>386</width>
- <height>214</height>
- </rect>
- </property>
- <property name="windowTitle" >
- <string>Dialog</string>
- </property>
- <layout class="QGridLayout" >
- <item row="0" column="0" colspan="2" >
- <widget class="QCheckBox" name="allowSentDocuments" >
- <property name="text" >
- <string>Allow collaborators to add own documents</string>
- </property>
- <property name="checked" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="1" column="0" colspan="2" >
- <widget class="QLabel" name="files" >
- <property name="text" >
- <string>Files:
-File 1
-File 2</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0" >
- <widget class="QLabel" name="users" >
- <property name="text" >
- <string>Invite users:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0" >
- <widget class="QLabel" name="label" >
- <property name="text" >
- <string>Session-Name:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1" >
- <widget class="KLineEdit" name="sessionName" />
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KLineEdit</class>
- <extends>QLineEdit</extends>
- <header>klineedit.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections>
- </connections>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_filecollaborationsession.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.cpp (nonexistent)
@@ -1,62 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "safelogger.h"
-
-LogSuffix& LogSuffix::operator = ( const LogSuffix& /*rhs */ ) {
- return * this;
-}
-LogSuffix::LogSuffix( const LogSuffix& /*rhs */ ) {}
-
-LogSuffix::LogSuffix( const char* txt, SafeLogger* logger ) : m_logger( logger ) {
- m_logger->m_logSuffix.push_back( txt );
-}
-
-LogSuffix::~LogSuffix() {
- if ( !m_logger->m_logSuffix.empty() )
- m_logger->m_logSuffix.pop_back();
- else
- m_logger->err() << "error in SafeLogger::LogSuffix: tried to pop more than pushed";
-}
-
-SafeLogger::SafeLogger( Teamwork::LoggerPointer logger, std::string logPrefix ) : m_logger( logger ), m_logPrefix( logPrefix ) {}
-
-SafeLogger::~SafeLogger() {}
-
-Teamwork::LoggerPrinter SafeLogger::out( Teamwork::Logger::Level level ) {
- Teamwork::LoggerPrinter ret( m_logger, level );
- ret << logPrefix();
- uint sz = m_logSuffix.size();
- for ( uint a = 0; a < sz; a++ )
- ret << m_logSuffix[ a ];
- return ret;
-}
-
-Teamwork::LoggerPointer SafeLogger::logger() const {
- return m_logger;
-}
-
-Teamwork::LoggerPrinter SafeLogger::err() {
- Teamwork::LoggerPrinter ret( m_logger, Teamwork::Logger::Error );
- ret << logPrefix();
- uint sz = m_logSuffix.size();
- for ( uint a = 0; a < sz; a++ )
- ret << m_logSuffix[ a ];
- return ret;
-}
-
-std::string SafeLogger::logPrefix() {
- return m_logPrefix;
-}
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/safelogger.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevteamwork.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/dotest
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/dotest (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/dotest (nonexistent)
@@ -1,2 +0,0 @@
-#!/bin/sh
-colorgcc test.cpp test -lstdc++ -I../../ -ftemplate-depth-30 && ./test
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/dotest
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.h (nonexistent)
@@ -1,131 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef FILECOLLABORATION_H
-#define FILECOLLABORATION_H
-
-#include <QStringList>
-#include <QList>
-#include <QIcon>
-
-#include "lib/network/messagetypeset.h"
-#include "lib/network/safesharedptr.h"
-#include "lib/network/weaksafesharedptr.h"
-
-#include "filecollaborationmessages.h"
-#include "collaborationmanager.h"
-#include "lib/network/crossmap.h"
-#include "safelogger.h"
-#include "verify.h"
-
-namespace KTextEditor {
-class Document;
-}
-
-class FileCollaborationManager;
-class KDevTeamworkUser;
-class CollaborationManager;
-
-class FileCollaborationManager;
-class FileCollaborationSession;
-class QAction;
-class DocumentWrapper;
-class QModelIndex;
-class QStandardItemModel;
-
-typedef SafeSharedPtr<KDevTeamworkUser, BoostSerialization> KDevTeamworkUserPointer;
-typedef SharedPtr<FileCollaborationSession> FileCollaborationSessionPointer;
-typedef SharedPtr<DocumentWrapper> DocumentWrapperPointer;
-
-// BIND_LIST_2( FileCollaborationDirectMessages, FileCollaborationRequest, FileCollaborationMessage )
-
-class FileCollaborationUserTreeAction;
-
-class FileCollaboration : public QObject, public Shared, public SafeLogger {
- Q_OBJECT
- public:
-
- ///May throw QString
- FileCollaboration( KDevTeamworkUserPointer user, FileCollaborationSession* session, const FileCollaborationRequestPointer& request = 0 );
-
- KDevTeamworkUserPointer user() const;
-
- FileCollaborationSessionPointer session() const;
-
- ///This collaboration's index in the vector-timestamps
- uint primaryIndex() const;
-
- ///Returns whether the other side was invited to join the session by this side
- bool invited() const;
-
- ///@return whether the connection is active
- bool connectionActive() const;
-
- void close( const QString& reason );
-
- QIcon icon() const;
-
- signals:
- void connectionResult( FileCollaboration*, bool ); ///If true, connection was successful. If false, connection failed.
-
- public slots:
- void slotFillCollaboratingUserMenu( QMenu* menu, const UserPointer& user );
- void processMessage( const MessagePointer& msg );
- void slotConnectionResult( bool );
- void userStateChanged();
-
- private:
- void updateTree( QModelIndex& i, QStandardItemModel* model );
-
- void invite( const FileCollaborationRequestPointer& request, bool automatic ) throw(QString);
- void doubleClicked();
- void fillContextMenu( int i, QMenu* menu );
-
- friend class FileCollaborationUserTreeAction;
- friend class FileCollaborationSession;
-
-// int receiveMessage( MessageInterface* msg );
-// int receiveMessage( FileSynchronize* msg );
-// int receiveMessage( FileCollaborationRequest* msg );
-// int receiveMessage( FileCollaborationMessage* msg );
-
- KDevTeamworkUserPointer m_user;
- FileCollaborationSessionPointer m_session;
- FileCollaborationRequestPointer m_request;
-
- QString m_userName;
- uint m_index; ///The index of the other side this collaboration-object is a bridge to
-
- bool m_connectionActive;
- bool m_userConnected;
- bool m_invited;
-
- virtual std::string logPrefix();
-
-/* friend class MessageDispatcher< FileCollaboration, FileCollaborationDirectMessages >;
- MessageDispatcher< FileCollaboration, FileCollaborationDirectMessages > m_dispatcher;*/
-};
-
-typedef SharedPtr<FileCollaboration> FileCollaborationPointer;
-
-struct FileCollaborationUserTreeAction : public StandardCollaborationTreeAction<FileCollaboration> {
- FileCollaborationUserTreeAction( FileCollaboration* w ) : StandardCollaborationTreeAction<FileCollaboration>( w ) {}
- virtual void doubleClicked();
-
- virtual void fillContextMenu( QMenu* menu );
-}
-;
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaboration.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp (nonexistent)
@@ -1,735 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "documentwrapper.h"
-#include "kdevteamwork_messages.h"
-#include "kdevteamworkplugin.h"
-#include <QStandardItemModel>
-#include <QModelIndex>
-#include <QMenu>
-#include <QVariant>
-#include <QFileInfo>
-#include <QFile>
-#include <kmessagebox.h>
-#include <klocalizedstring.h>
-#include <k3process.h>
-#include <ktexteditor/document.h>
-#include <ktexteditor/range.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-#include "lib/dynamictext/dynamictext.h"
-#include "kdevteamwork_helpers.h"
-#include "collaborationmanager.h"
-#include "filecollaborationmessages.h"
-#include "lib/network/basicsession.h"
-#include "utils.h"
-#include "lib/dynamictext/verify.h"
-#include "filesynchronizemessage.h"
-#include "qdynamictext.h"
-#include "vectortimestampeditor.h"
-#include "kdevteamwork.h"
-#include "patchesmanager.h"
-#include "teamworkfoldermanager.h"
-#include "filecollaborationsession.h"
-#include "patchmessage.h"
-#include "filecollaborationmanager.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/messagesendhelper.h"
-#include <interfaces/iuicontroller.h> /* defines [function] activeMainWindow */
-#include <interfaces/icore.h> /* defines [function] uiController */
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-using namespace KDevelop;
-
-#define IFDEBUG( x ) /**/
-//#define IFDEBUG( x ) x
-
-struct DocumentWrapperTreeAction : public StandardCollaborationTreeAction<DocumentWrapper> {
- DocumentWrapperTreeAction( DocumentWrapper* w ) : StandardCollaborationTreeAction<DocumentWrapper>( w ) {}
- virtual void doubleClicked() {
- if ( target ) {
- target->openDocument( true );
- }
- }
- virtual void clicked() {}
- virtual void fillContextMenu( QMenu* menu ) {
- if ( target )
- target->fillContextMenu( 0, menu );
- }
-}
-;
-
-bool DocumentWrapper::hadError() const {
- return m_hadError;
-}
-
-uint DocumentWrapper::id() const {
- return m_id;
-}
-
-DocumentWrapper::DocumentWrapper( uint id, const LoggerPointer& logger, QString fileName, uint ownIndex, bool readFile_, FileCollaborationSession* session, bool fromBuffer ) :
- SafeLogger( logger, ~( "document-wrapper \"" + fileName + "\": " ) ),
- m_text( new QDynamicText() ),
- m_block( false ),
- m_realFile( readFile_ ),
- m_fileName( fileName ),
- m_document( 0 ),
- m_session( session ),
- m_ownIndex( ownIndex ),
- m_id( id ),
- m_hadError( false ),
- m_disabled( false ),
- m_dead( false ),
- m_dispatcher( *this ){
- //openDocument();
- out( Logger::Debug ) << "DocumentWrapper for" << fileName << "created:" << ownIndex << "" << readFile_;
- if ( m_realFile )
- readFile( fromBuffer );
-
- connect( m_text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( stateChanged() ) );
-}
-
-QIcon DocumentWrapper::icon() const {
- if ( m_dead )
- return IconCache::getIconStatic( "collaboration_file_dead" );
- if ( !m_disabled )
- return IconCache::getIconStatic( "collaboration_file" );
- else
- return IconCache::getIconStatic( "collaboration_file_disabled" );
-}
-
-void DocumentWrapper::updateTree( QModelIndex& i, QStandardItemModel* model ) {
- model->setData( i, fileName(), Qt::DisplayRole );
- model->setData( i, icon(), Qt::DecorationRole );
- QVariant v;
- v.setValue<CollaborationTreeActionPointer>( new DocumentWrapperTreeAction( this ) );
- model->setData( i, v, Qt::UserRole );
-}
-
-void DocumentWrapper::fillContextMenu( int /*var*/, QMenu* menu ) {
- QMenu * m = new QMenu( menu );
- m->setTitle( "Save Visible State" );
- m->addAction( "As Patch", this, SLOT( saveAsPatch() ) );
- //m->addAction( "To New Buffer", this, SLOT( saveNewBuffer() ) );
- //m->addSeparator();
- m->addAction( QString( "As %1" ).arg( m_fileName ), this, SLOT( saveAsBufferFile() ) );
- menu->addMenu( m );
-
-
- if ( m_disabled )
- menu->addAction( "Enable Editing", this, SLOT( toggleEnabled() ) );
- else if ( m_session->isMasterSession() )
- menu->addAction( "Disable Editing", this, SLOT( toggleEnabled() ) );
-
- if ( m_session->isMasterSession() || m_dead ) {
- menu->addSeparator();
- menu->addAction( "Remove", this, SLOT( remove
- () ) );
- }
-
- menu->addSeparator();
- menu->addAction( "Manage Dynamic Text", this, SLOT( manageDynamicText() ) );
-}
-
-QString DocumentWrapper::text() const {
- return ~m_text->text().text();
-}
-
-VectorTimestamp DocumentWrapper::state() const {
- return m_text->state();
-}
-
-const QDynamicText& DocumentWrapper::dynamicText() const {
- return * m_text;
-}
-
-bool DocumentWrapper::checkDocumentSync() const {
- if ( m_document && m_document->textDocument() ) {
- return m_document->textDocument() ->text() == ~m_text->text().text();
- } else {
- return true;
- }
-}
-
-void DocumentWrapper::remove
-() {}
-
-
-void DocumentWrapper::toggleEnabled() {
- m_disabled = !m_disabled;
- out( Logger::Debug ) << "Editing is now" << ( m_disabled ? "disabled" : "enabled");
-}
-
-void DocumentWrapper::saveAsBufferFile() {
- KUrl u = TeamworkFolderManager::workspaceAbsolute( m_fileName );
-
- IDocument* doc = KDevTeamworkPlugin::staticDocumentController() ->openDocument( u, KTextEditor::Cursor() );
-
- if ( doc && doc->textDocument() ) {
- if ( doc->state() == IDocument::Modified || doc->state() == IDocument::DirtyAndModified ) {
- int answer = KMessageBox::warningYesNo( KDevTeamworkPlugin::staticCore()->uiController()->activeMainWindow()->window(), i18n( "The buffer of %1 is modified, should the content be replaced?" , m_fileName ) );
- if ( answer != KMessageBox::Yes )
- return ;
- }
- doc->textDocument() ->setText( ~m_text->text().text() );
-
- } else {
- err() << "saveAsBufferFile(): could not open document for" << u.toLocalFile();
- }
-}
-
-OutputFileWriter::OutputFileWriter( const QString& file ) : m_file( file ), m_failed( false ) {
- if ( !m_file.open( QIODevice::WriteOnly ) )
- throw QString( "could not open file %1" ).arg( file );
-}
-
-bool OutputFileWriter::failed() const {
- return m_failed;
-}
-
-void OutputFileWriter::receivedStdout( K3Process */*proc*/, char *buffer, int buflen ) {
- if ( m_file.write( buffer, buflen ) != buflen ) {
- m_failed = true;
- }
-}
-
-LocalPatchSourcePointer DocumentWrapper::saveAsPatch( bool addToList, bool edit ) {
- try {
- KDevTeamwork * tw = KDevTeamwork::self();
-
- PatchesManager* pm = tw->patchesManager();
-
- QString peer = m_session->firstPeerName();
- if ( m_session->isMasterSession() )
- peer = "local";
-
- LocalPatchSourcePointer::Locked l = new LocalPatchSource();
- l->name = ~( m_session->name() + "@" + peer + "_" + QDateTime::currentDateTime().toString( Qt::ISODate ) );
- l->type = "text/x-diff";
- l->applyCommand = "-p0";
- l->unApplyCommand = "-p0 -R";
- l->userIdentity = m_session->manager() ->teamwork() ->currentUserIdentity();
-
- KUrl u = TeamworkFolderManager::createUniqueFile( "patches", "diff", ~l->name, "collab_", "" );
-
- l->filename = ~TeamworkFolderManager::teamworkRelative( u, "patches" );
-
- KUrl workingDir = TeamworkFolderManager::createUniqueDirectory( "temp", m_session->name(), "diff_" );
- KUrl subFolder( TeamworkFolderManager::teamworkRelative( workingDir ) );
- subFolder.addPath( QFileInfo( m_fileName ).path() );
-
- KUrl tempCurrent = TeamworkFolderManager::createUniqueFile( subFolder.toLocalFile(), m_fileName );
- KUrl tempBase = TeamworkFolderManager::createUniqueFile( subFolder.toLocalFile(), m_fileName, "base_" );
-
- TeamworkFolderManager::self() ->registerTempItem( tempCurrent );
- TeamworkFolderManager::self() ->registerTempItem( tempBase );
-
- {
- QByteArray path = tempCurrent.toLocalFile().toUtf8();
- std::ofstream fCurrent( path.data(), ios_base::out );
- if ( !fCurrent.is_open() )
- throw "could not open file for writing: " + tempCurrent.toLocalFile();
- fCurrent << m_text->text().text();
- }
- {
- QByteArray path = tempBase.toLocalFile().toUtf8();
- std::ofstream fBase( path.data(), ios_base::out );
- if ( !fBase.is_open() )
- throw "could not open file for writing: " + tempBase.toLocalFile();
- fBase << m_text->initialText();
- }
- K3Process proc;
- ///@todo make this work with remote files
- OutputFileWriter ow( u.toLocalFile() );
- proc.setWorkingDirectory( workingDir.toLocalFile() );
- QString cmdLine = + + " " + tempCurrent.toLocalFile() + " > " + u.toLocalFile();
- proc.setPriority( K3Process::PrioLowest );
- proc << "diff";
- proc << "--unified=4";
- proc << tempBase.toLocalFile();
- proc << tempCurrent.toLocalFile();
-
- connect( &proc, SIGNAL( receivedStdout ( K3Process *, char *, int ) ), &ow, SLOT( receivedStdout( K3Process*, char*, int ) ) );
-
- if ( ow.failed() )
- throw QString( "writing to %1 failed" ).arg( u.prettyUrl() );
-
- out( Logger::Debug ) << "saveAsPatch(..) executing \"diff --unified=4 " + tempBase.toLocalFile() + " " + tempCurrent.toLocalFile() + "\"";
-
- proc.start( K3Process::Block, K3Process::Stdout );
- if ( addToList )
- pm->addPatch( l );
- if ( edit )
- pm->showPatchInfo( l, true );
-
- return l;
- } catch ( const QString & str ) {
- err() << "saveAsPatch():" << str;
- } catch ( const char * str ) {
- err() << "saveAsPatch():" << str;
- }
- return 0;
-}
-
-void DocumentWrapper::saveNewBuffer() {
- ///It would be nice to create a nameless buffer here and insert the text
-}
-
-void DocumentWrapper::manageDynamicText() {
- new VectorTimestampEditor( logger(), this, false, m_text, true );
-}
-
-void DocumentWrapper::stateChanged() {
- if ( m_block )
- return ;
- fillDocumentText();
-}
-
-bool DocumentWrapper::synchronize( const UserPointer& user ) {
- if ( m_dead )
- return false;
-
- out( Logger::Debug ) << "synchronizing with" << user.unsafe()->safeName();
-
- UserPointer::Locked l = user;
- if ( l && l->online().session() ) {
- return globalMessageSendHelper().send<FileSynchronize>( l->online().session().unsafe(), fileName(), *m_text, true, id(), m_session->id() );
- } else {
- err() << "cannot send synchronization-message because the user cannot be locked, or is not online";
- return false;
- }
-}
-
-int DocumentWrapper::receiveMessage( FileEditRejectMessage* msg ) {
- if ( m_session->isMasterSession() ) {
- out( Logger::Warning ) << "got a reject-message from a client, sending complete synchronization";
- synchronize( msg->info().user() );
- return 0;
- }
-
- ///A reject-message contains a new state that should be applied
- VectorTimestamp v = msg->timeStamp();
- try {
- m_text->changeState( v );
- m_text->cut();
- } catch ( const DynamicTextError & err ) {
- ///There is no other way than resynchronizing the whole file
- out() << "error while handling a reject, resynchronizing. Error:" << err.what();
- globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, VectorTimestamp(), id(), m_session->id() );
- }
- return 1;
-}
-
-int DocumentWrapper::receiveMessage( MessageInterface* msg ) {
- out( Logger::Warning ) << "got unknown message of type" << msg->name();
- return 0;
-}
-
-int DocumentWrapper::receiveMessage( FileEditMessage* msg ) {
- try {
- if ( ( m_disabled || m_dead ) && m_session->isMasterSession() ) {
- globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, m_text->tailState(), id(), m_session->id() );
- return 0;
- }
- FileEditMessage * emsg = dynamic_cast<FileEditMessage*>( msg );
- {
- Block b( m_block );
- bool wasTail = m_text->state() == m_text->tailState();
- m_text->insert( emsg->timeStamp(), emsg->replacement() );
-
- if ( wasTail ) {
- m_text->text().registerNotifier( this );
- m_text->changeState();
- m_text->text().unregisterNotifier();
- }
- }
-
- } catch ( const DynamicTextError & error ) {
- ///@todo error-handling
- err() << "receiveMessage( FileEditMessage" << msg->timeStamp() << "" << msg->replacement() << "):" << error.what();
- globalMessageSendHelper().sendReply<FileEditRejectMessage>( msg, m_text->tailState(), id(), m_session->id() );
- m_text->text().unregisterNotifier(); //@todo use a little wrapper-class for this
- }
- return 1;
-}
-
-void DocumentWrapper::notifyFlexibleTextErase( int position, int length ) {
- if ( m_document && m_document->textDocument() ) {
- Block b( m_block );
- int line, column;
-
- m_text->text().linearToLineColumn( position, line, column );
- if ( line == -1 || column == -1 )
- throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
-
- KTextEditor::Cursor start( line, column );
-
-
- m_text->text().linearToLineColumn( position + length, line, column );
-
- if ( line == -1 || column == -1 )
- throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
-
- KTextEditor::Cursor end( line, column );
-
-
- m_document->textDocument() ->replaceText( KTextEditor::Range( start, end ), "" );
- }
-}
-
-void DocumentWrapper::notifyFlexibleTextInsert( int position, const std::string& text ) {
- if ( m_document && m_document->textDocument() ) {
- Block b( m_block );
- int line, column;
-
- m_text->text().linearToLineColumn( position, line, column );
- if ( line == -1 || column == -1 )
- throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
-
- KTextEditor::Cursor start( line, column );
-
- m_document->textDocument() ->replaceText( KTextEditor::Range( start, start ), toQ( text.c_str() ) );
- }
-}
-
-void DocumentWrapper::notifyFlexibleTextReplace( int position, int length, const std::string& replacement ) {
- if ( m_document && m_document->textDocument() ) {
- Block b( m_block );
- int line, column;
-
- m_text->text().linearToLineColumn( position, line, column );
- if ( line == -1 || column == -1 )
- throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
-
- KTextEditor::Cursor start( line, column );
-
-
- m_text->text().linearToLineColumn( position + length, line, column );
-
- if ( line == -1 || column == -1 )
- throw DynamicTextError( "receiveMessage( FileEditMessage ): could not convert index to cursor" );
-
- KTextEditor::Cursor end( line, column );
-
-
- m_document->textDocument() ->replaceText( KTextEditor::Range( start, end ), toQ( replacement.c_str() ) );
- }
-}
-
-void DocumentWrapper::processMessage( DocumentWrapperMessage* msg ) {
-
- /*if ( !checkDocumentSync() ) {
- if ( m_document && m_document->textDocument() ) {
- out( Logger::Warning ) << "processMessage(begin): document and dynamictext got out of sync! Resynchronizing";
- fillDocumentText();
- }
- }*/
-
- IFDEBUG( out( Logger::Debug ) << "processMessage(..) processing" << msg->name() );
-
- m_dispatcher( msg );
- /*
- if ( !checkDocumentSync() ) {
- if ( m_document && m_document->textDocument() ) {
- out( Logger::Warning ) << "processMessage(end): document and dynamictext got out of sync! Resynchronizing";
- fillDocumentText();
- }
- }*/
-}
-
-void DocumentWrapper::documentDestroyed() {
- m_document = 0;
-}
-
-QString DocumentWrapper::fileName() const {
- return m_fileName;
-}
-
-IDocument* DocumentWrapper::document() {
- return m_document;
-}
-
-void DocumentWrapper::fillDocumentText() {
- Block b( m_block );
- if ( m_document && m_document->textDocument() ) {
- m_document->textDocument() ->setText( ~m_text->text().text() );
- } else {
- err() << "cannot update document-text: no document available";
- }
-}
-
-void DocumentWrapper::openDocument( bool toForeground ) {
- try {
- if ( m_document ) {
- if( toForeground )
- KDevTeamworkPlugin::staticDocumentController() ->activateDocument( m_document );
- return ;
- }
-
- out( Logger::Debug ) << "openDocument()" << fileName() << "" << toForeground;
-
- if ( m_tempFile.isEmpty() ) {
- KUrl subfolder( QString( "filecollaboration" ) );
- subfolder.addPath( m_session->name() + "_" + QString( "%1").arg(m_session->id() ) );
-
- QString location;
- if ( m_session->isMasterSession() ) {
- location = "local";
- } else {
- location = m_session->firstPeerName();
- }
-
- ///@todo make this work work remote files
- m_tempFile = TeamworkFolderManager::createUniqueFile( subfolder.toLocalFile(), m_fileName, "", "@" + m_session->name() ).toLocalFile();
- }
-
- out( Logger::Debug ) << "temporary file for" << fileName() << "is" << m_tempFile;
-
- m_document = KDevTeamworkPlugin::staticDocumentController() ->openDocument( m_tempFile, KTextEditor::Cursor(), toForeground == true ? KDevelop::IDocumentController::DefaultMode : KDevelop::IDocumentController::DoNotActivate );
-
- if ( m_document ) {
- KTextEditor::Document * doc = m_document->textDocument();
- if ( !doc ) {
- m_document = 0;
- throw "could not open as text-document";
- }
- fillDocumentText();
-
- /*connect( m_document, SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );*/
- connect( m_document->textDocument(), SIGNAL( destroyed( QObject* ) ), this, SLOT( documentDestroyed() ) );
- connect( doc, SIGNAL( textInserted ( KTextEditor::Document *,
- const KTextEditor::Range & ) ), this, SLOT( textInserted ( KTextEditor::Document *,
- const KTextEditor::Range & ) ) );
- connect( doc, SIGNAL( textRemoved ( KTextEditor::Document *,
- const KTextEditor::Range & ) ), this, SLOT( textRemoved ( KTextEditor::Document *,
- const KTextEditor::Range & ) ) );
- connect( doc, SIGNAL( textChanged ( KTextEditor::Document *,
- const KTextEditor::Range &,
- const KTextEditor::Range & ) ), this, SLOT( textChanged ( KTextEditor::Document *,
- const KTextEditor::Range &,
- const KTextEditor::Range & ) ) );
- } else {
- throw "could not open document";
- }
- } catch ( const QString & str ) {
- err() << "openDocument():" << str;
- } catch ( const char * str ) {
- err() << "openDocument():" << str;
- }
-}
-
-uint getPositionInDocument( KTextEditor::Document * doc, const KTextEditor::Cursor& cursor ) {
- QString str = doc->text( KTextEditor::Range( KTextEditor::Cursor( 0, 0 ), cursor ) );
- return str.length();
-}
-
-void DocumentWrapper::textChanged ( KTextEditor::Document * document, const KTextEditor::Range & oldRange, const KTextEditor::Range & newRange ) {
- if ( m_block )
- return ;
- out( Logger::Debug ) << "textChanged";
-
- VectorTimestamp v( m_text->state() );
- v.setPrimaryIndex( m_ownIndex );
- v.increase();
-
- int start = m_text->text().lineColumnToLinear( oldRange.start().line(), oldRange.start().column() );
- int end = m_text->text().lineColumnToLinear( oldRange.end().line(), oldRange.end().column() );
-
- if ( start == -1 || end == -1 || start == end ) {
- err() << "textRemoved(..): DynamicText and Document seem to be out of sync";
-
- fillDocumentText();
- return ;
- }
-
- std::string oldText = m_text->text().substr( start, end - start );
- QString newText = document->text( newRange );
-
- if ( oldRange.end().line() == oldRange.start().line() && newRange.end().line() == newRange.start().line() ) {
- out( Logger::Debug ) << "textChanged at" << start << ":" << oldText << "->" << newText;
- } else {
- out( Logger::Debug ) << "textChanged at" << start;
- }
-
- ///It might be better to model the edit by one removal and one insertion, because that allows better resolution of conflicts.(Think about if it should be like that)
- SimpleReplacement r( start, ~newText, oldText );
-
- try {
- DYN_VERIFY( !m_disabled );
- DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
- Block b( m_block );
- m_text->insert( v, r );
- } catch ( const DynamicTextError & error ) {
- err() << "error in textRemoved(..):" << error.what();
- fillDocumentText();
- return ;
- }
-
- if ( !m_dead )
- emit publishEdit( v, r, this );
-}
-
-///All the line/column to/from linear conversion is very slow and should be done different
-void DocumentWrapper::textRemoved ( KTextEditor::Document * /*document*/, const KTextEditor::Range & range ) {
- if ( m_block )
- return ;
- int start = m_text->text().lineColumnToLinear( range.start().line(), range.start().column() );
- int end = m_text->text().lineColumnToLinear( range.end().line(), range.end().column() );
-
- if ( start == -1 || end == -1 ) {
- err() << "textRemoved(..): DynamicText and Document seem to be out of sync";
- fillDocumentText();
- return ;
- }
-
- std::string oldText = m_text->text().substr( start, end - start );
-
- if ( range.end().line() == range.start().line() ) {
- IFDEBUG( out( Logger::Debug ) << "textRemoved at" << start << ":" << document->text( range ) );
- } else {
- IFDEBUG( out( Logger::Debug ) << "textRemoved at" << start );
- }
-
- SimpleReplacement r( start, "", oldText );
-
- VectorTimestamp v;
- try {
- DYN_VERIFY( !m_disabled );
- DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
- Block b( m_block );
- v = m_text->insert( m_ownIndex, r );
- } catch ( const DynamicTextError & error ) {
- err() << "error in textRemoved(..):" << error.what();
- fillDocumentText();
- return ;
- }
-
- if ( !m_dead )
- emit publishEdit( v, r, this );
-}
-
-void DocumentWrapper::textInserted ( KTextEditor::Document * document, const KTextEditor::Range & range ) {
- if ( m_block )
- return ;
- VectorTimestamp v;
-
- QString newText = document->text( range );
- uint pos = m_text->text().lineColumnToLinear( range.start().line(), range.start().column() );
-
- if ( range.end().line() == range.start().line() ) {
- IFDEBUG( out( Logger::Debug ) << "textInserted at" << pos << ":" << document->text( range ) );
- } else {
- IFDEBUG( out( Logger::Debug ) << "textInserted at" << pos );
- }
-
- SimpleReplacement r = SimpleReplacement( pos, ~newText, "" );
-
- try {
- DYN_VERIFY_SAME( m_text->state(), m_text->tailState() );
- DYN_VERIFY( !m_disabled );
- Block b( m_block );
- v = m_text->insert( m_ownIndex, r );
- } catch ( const DynamicTextError & error ) {
- err() << "error in textInserted(..):" << error.what();
- fillDocumentText();
- return ;
- }
-
- if ( !m_dead )
- emit publishEdit( v, r, this );
-}
-
-std::string DocumentWrapper::logPrefix() {
- return "DocumentWrapper for " + ~fileName() + ": ";
-}
-
-int DocumentWrapper::receiveMessage( FileSynchronize* msg ) {
- ///@todo merge synchronizations from different clients when self was crashed
- /*if ( !m_text->state().isZero() ) {
- err() << "got synchronization although timestamp already is" << m_text->state().print();
- return ;
- }*/
- out( Logger::Debug ) << "got synchronization - current Timestamp:" << m_text->state().print() << "new:" << msg->state().print();
-
- try {
- m_text = msg->createDynamicText();
- connect( m_text.data(), SIGNAL( stateChanged( QDynamicText& ) ), this, SLOT( stateChanged() ) );
- fillDocumentText();
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionSuccessful );
- } catch ( const DynamicTextError & error ) {
- err() << "error while synchronization:" << error.what();
- globalMessageSendHelper().sendReply<KDevSystemMessage>( msg, KDevSystemMessage::ActionFailed );
- }
-
- return 1;
-}
-
-bool DocumentWrapper::dead() const {
- return m_dead;
-}
-
-bool DocumentWrapper::disabled() const {
- return m_disabled;
-}
-
-void DocumentWrapper::setDisabled( bool disabled ) {
- m_disabled = disabled;
-}
-
-void DocumentWrapper::setDead( bool dead ) {
- m_dead = dead;
-}
-
-void DocumentWrapper::readFile( bool fromBuffer ) throw ( QString ) {
- KUrl u = TeamworkFolderManager::workspaceAbsolute( m_fileName );
-
- if ( !m_text->state().isZero() ) {
- out( Logger::Warning ) << "readFile called although state already is" << m_text->state().print();
- }
-
- QString txt;
-
- if ( fromBuffer ) {
- IDocument * doc = KDevTeamworkPlugin::staticDocumentController() ->documentForUrl( u );
- if ( doc && doc->textDocument() ) {
- txt = doc->textDocument() ->text();
- }
- }
-
- if ( txt.isEmpty() ) {
- if ( !u.isLocalFile() )
- throw QString( "file is not local" );
- if ( !QFileInfo( u.toLocalFile() ).exists() )
- throw QString( "file does not exist" );
-
- QFile f( u.toLocalFile() );
- if ( !f.open( QIODevice::ReadOnly ) )
- throw QString( "could not open file" );
-
- ///@todo What about encoding etc. ?
- QByteArray b = f.readAll();
- Block bl( m_block );
- m_text = new QDynamicText( VectorTimestamp( m_ownIndex, VectorTimestamp() ), b.data() );
- } else {
- m_text = new QDynamicText( VectorTimestamp( m_ownIndex, VectorTimestamp() ), txt.toUtf8().data() );
- }
- /*m_text->changeState();
- m_text->insert( m_ownIndex, SimpleReplacement( 0, b.data(), m_text->text() ) );*/
-}
-
-#include "documentwrapper.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/documentwrapper.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui (nonexistent)
@@ -1,173 +0,0 @@
-<ui version="4.0" >
- <class>TimestampWidget</class>
- <widget class="QWidget" name="TimestampWidget" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>950</width>
- <height>29</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QHBoxLayout" >
- <property name="margin" >
- <number>0</number>
- </property>
- <property name="spacing" >
- <number>6</number>
- </property>
- <item>
- <widget class="QPushButton" name="tail" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Tail</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="none" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>None</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="enableAll" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Enable All(x)</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="KIntNumInput" name="stamp" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>120</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="minimum" >
- <number>0</number>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="stampCount" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>(last stamp)</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDateTimeEdit" name="date" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="lastDate" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>5</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>(last date)</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QCheckBox" name="enableBox" >
- <property name="sizePolicy" >
- <sizepolicy>
- <hsizetype>4</hsizetype>
- <vsizetype>0</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Enable</string>
- </property>
- <property name="tristate" >
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="replacementText" >
- <property name="text" >
- <string>replacement-text</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KIntNumInput</class>
- <extends>QWidget</extends>
- <header>knuminput.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_timestampwidget.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.h (nonexistent)
@@ -1,283 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef CONVERSATIONMANAGER_H
-#define CONVERSATIONMANAGER_H
-
-#include <QObject>
-#include <QtCore/QPointer>
-#include <QTime>
-#include <ktexteditor/document.h>
-#include <ktexteditor/smartcursor.h>
-#include <ktexteditor/smartinterface.h>
-#include "teamworkfwd.h"
-#include "indocumentreference.h"
-#include "messagehistorymanager.h"
-#include "lib/network/crossmap.h"
-#include "safelogger.h"
-#include "ui_kdevteamwork_internalmessage.h"
-#
-
-class QStandardItemModel;
-class TemporaryConversationConnector;
-class KDevTeamworkClient;
-class QTimer;
-class InDocumentMessage;
-
-namespace KDevelop {
- class IDocument;
-}
-
-typedef SafeSharedPtr<InDocumentMessage, MessageSerialization> InDocumentMessagePointer;
-
-///This is a class that helps detecting when the document is deleted and then deleting the smartcursor, also it automatically creates the cursor. @todo replace with QOwnedPointer
-class SmartCursorContainer {
- QPointer<KTextEditor::Document> m_document;
- KTextEditor::SmartCursor* m_smartCursor;
- public:
- SmartCursorContainer( KTextEditor::Document* doc = 0 ) : m_document( doc ), m_smartCursor( 0 ) {
- if ( m_document ) {
- KTextEditor::SmartInterface * smart =
- qobject_cast<KTextEditor::SmartInterface*>( doc );
-
- if ( smart )
- m_smartCursor = smart->newSmartCursor();
- }
- }
- KTextEditor::SmartCursor* operator -> () {
- return m_smartCursor;
- }
- ~SmartCursorContainer() {
- if ( m_smartCursor )
- delete m_smartCursor;
- m_smartCursor = 0;
- }
- KTextEditor::SmartCursor& operator *() {
- return * m_smartCursor;
- }
- SmartCursorContainer( const SmartCursorContainer& rhs ) {
- if ( &rhs == this )
- return ;
- if ( m_smartCursor && m_document )
- delete m_smartCursor;
- m_document = rhs.m_document;
- m_smartCursor = rhs.m_smartCursor;
- const_cast<SmartCursorContainer&>( rhs ).m_smartCursor = 0;
- }
- SmartCursorContainer& operator = ( const SmartCursorContainer& rhs ) {
- if ( &rhs == this )
- return * this;
- if ( m_smartCursor && m_document )
- delete m_smartCursor;
- m_document = rhs.m_document;
- m_smartCursor = rhs.m_smartCursor;
- const_cast<SmartCursorContainer&>( rhs ).m_smartCursor = 0;
- return *this;
- }
-
- operator bool() {
- return m_document && m_smartCursor && m_smartCursor->isValid();
- }
-};
-
-namespace KTextEditor {
-class View;
-class Cursor;
-class SmartCursor;
-}
-class InDocumentMessage;
-enum LogLevel;
-class ConversationManager;
-class QWidget;
-class SmartCursor;
-
-CROSSMAP_DEFINE_CONTAINER( QList )
-
-struct OrderedDocumentMessage {
- int position;
- InDocumentMessagePointer message;
- OrderedDocumentMessage( uint pos, const InDocumentMessagePointer& msg ) : position( pos ), message( msg ) {}
- OrderedDocumentMessage() : position( 0 ), message( 0 ) {}
-
- operator bool() const {
- return ( bool ) message;
- }
- /*template<class Archive>
- void serialize( Archive& arch, const uint version ) {
- arch & position & message;
- }*/
-};
-
-class InDocumentConversation : public QObject, public Shared, public SafeLogger {
- Q_OBJECT
- ///Order, message, file
- BIND_LIST_3( Keys, InDocumentMessagePointer, int, QString )
- typedef Utils::CrossMap< OrderedDocumentMessage, Keys > MessageSet;
- public:
- InDocumentConversation( InDocumentMessage* msg = 0 );
- ~InDocumentConversation();
-
- void addMessage( InDocumentMessage* msg );
-
- template <class ArchType>
- void load( ArchType& arch, unsigned int version );
-
- template <class ArchType>
- void save( ArchType& arch, unsigned int version ) const;
-
- ConversationManager* manager() const;
-
- void fillContextMenu( QMenu* menu, KDevTeamwork* teamwork, MessagePointer msg );
-
- ///Returns true if the message belongs to this conversation
- bool match( InDocumentMessage* msg ) const;
-
- void setActive( bool );
-
- UserPointer primaryUser();
-
- public slots:
- void userStateChanged( KDevTeamworkUserPointer );
- void documentActivated( KDevelop::IDocument* document );
- void verticalScrollPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos );
- void cursorPositionChanged ( KTextEditor::View *view, const KTextEditor::Cursor& newPos );
- void horizontalScrollPositionChanged ( KTextEditor::View *view );
- void jumpTo();
- void hide();
- void sendMessage();
- void gotReply( MessagePointer msg );
-
- void messageClicked( const QModelIndex& );
- void messageContextMenu ( const QPoint & );
- void selectMessage( InDocumentMessagePointer msg );
-
- void userInfo();
- void log( const QString& str, LogLevel level = Info ) const;
- void selectNearestMessage();
- private slots:
- void textChanged ( KTextEditor::Document * document, const KTextEditor::Range & oldRange, const KTextEditor::Range & newRange );
- void textRemoved ( KTextEditor::Document * document, const KTextEditor::Range & range );
- void textInserted ( KTextEditor::Document * document, const KTextEditor::Range & range );
-
- void rangeDeleted();
- private:
- virtual std::string logPrefix();
-
- InDocumentMessagePointer selectedMessage();
-
- void documentActivated( KDevelop::IDocument* document, const InDocumentMessagePointer& msg );
-
- void messageSelected( const MessagePointer& msg );
- template <class ArchType>
- void serial( ArchType& arch, unsigned int /*version*/ ) {
- arch & m_documentName;
- arch & m_line;
- arch & m_active;
- }
- void pushMessage( const InDocumentMessagePointer& msg );
-
- KTextEditor::Cursor currentDocCursor() const;
-
- QString context() const;
- void messageSendReady( bool success );
- void addListItem( const QString& txt, const QString& icon = "error" );
- SessionPointer session();
- void fillUserBox();
- void fillMessageModel();
- void fillMessageToModel( const LockedSharedPtr<InDocumentMessage>& );
- void setupWidget( QWidget* parent );
- void embedInView( KTextEditor::View* view, KDevelop::IDocument* document, KTextEditor::Cursor position );
- KTextEditor::Cursor findPositionInDocument( InDocumentMessagePointer::Locked l, KTextEditor::Cursor* endTarget = 0 );
- void placeWidget( KTextEditor::View* view, const KTextEditor::Cursor* awayFrom = 0, bool forceShow = false );
-
- string m_documentName;
- int m_line;
- int m_conversationId;
- bool m_active;
- uint m_messageCount;
-
- //list<InDocumentMessagePointer> m_messages;
- MessageSet m_messages;
-
- QPointer<QWidget> m_widget;
- Ui_InternalMessage m_widgets;
- SmartCursorContainer m_smartCursor;
- QAction* m_jumpToAction;
- QAction* m_hideAction;
- QAction* m_userInfoAction;
- QStandardItemModel* m_messagesModel;
- InDocumentMessagePointer m_sendingMessage;
- SharedPtr<TemporaryConversationConnector> m_userConnector;
- bool m_block;
-
- QTimer* m_selectNearestMessageTimer;
-
- QPointer<KTextEditor::Document> m_currentConnectedDocument;
-
- KTextEditor::SmartRange* m_currentRange;
-
- InDocumentReference::TextSearchInstance m_currentSearchInstance;
-
- QTime m_lastSendTime;
- public:
- BOOST_SERIALIZATION_SPLIT_MEMBER()
-};
-
-typedef SharedPtr<InDocumentConversation> InDocumentConversationPointer;
-
-class ConversationManager : public QObject {
- Q_OBJECT
- public:
-
- ConversationManager( MessageManager* mng );
- ~ConversationManager();
-
- int processMessage( InDocumentMessage* msg );
-
- static ConversationManager* instance() {
- return m_instance;
- }
-
- void log( const QString& str, LogLevel level );
-
- /* template <class ArchType>
- void serialize( ArchType& arch, unsigned int ) {
- arch & m_conversations;
- }*/
-
- MessageManager* manager() const {
- return const_cast<MessageManager*>( m_manager );
- }
-
- ///Returns zero if the conversation does not exist.
- InDocumentConversationPointer findConversation( const QString& context );
-
- ///If the conversation does not exist, it is created.
- InDocumentConversationPointer getConversation( InDocumentMessage* );
-
- public slots:
- void load();
- void save();
- void documentActivated( KDevelop::IDocument* document );
-
- private:
- static ConversationManager* m_instance;
- typedef map<string, InDocumentConversationPointer> ConversationSet;
- ConversationSet m_conversations; ///maps conversation-ids to conversations
- MessageManager* m_manager;
- static ConversationManager* globalManager;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/conversationmanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui (nonexistent)
@@ -1,293 +0,0 @@
-<ui version="4.0" >
- <class>MessageHistory</class>
- <widget class="QWidget" name="MessageHistory" >
- <property name="geometry" >
- <rect>
- <x>0</x>
- <y>0</y>
- <width>712</width>
- <height>616</height>
- </rect>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QGroupBox" name="groupBox_2" >
- <property name="title" >
- <string>Messages</string>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="label_3" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>From:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDateEdit" name="fromDate" />
- </item>
- <item>
- <widget class="QLabel" name="label_2" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Until:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDateEdit" name="untilDate" >
- <property name="currentSection" >
- <enum>QDateTimeEdit::DaySection</enum>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="allMessagesButton" >
- <property name="text" >
- <string>All</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QTreeView" name="messages" />
- </item>
- <item>
- <widget class="QDockWidget" name="messageFrame" >
- <property name="contextMenuPolicy" >
- <enum>Qt::NoContextMenu</enum>
- </property>
- <property name="features" >
- <set>QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable|QDockWidget::NoDockWidgetFeatures</set>
- </property>
- <widget class="QWidget" name="dockWidgetContents" />
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="label" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Type:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="typeFilter" />
- </item>
- <item>
- <widget class="QLabel" name="label_4" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text" >
- <string>Context:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="contextFilter" />
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item row="0" column="1" >
- <layout class="QVBoxLayout" >
- <property name="spacing" >
- <number>6</number>
- </property>
- <property name="leftMargin" >
- <number>0</number>
- </property>
- <property name="topMargin" >
- <number>0</number>
- </property>
- <property name="rightMargin" >
- <number>0</number>
- </property>
- <property name="bottomMargin" >
- <number>0</number>
- </property>
- <item>
- <widget class="QGroupBox" name="groupBox" >
- <property name="sizePolicy" >
- <sizepolicy vsizetype="Preferred" hsizetype="Maximum" >
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize" >
- <size>
- <width>140</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="title" >
- <string>Developers</string>
- </property>
- <layout class="QGridLayout" >
- <property name="leftMargin" >
- <number>9</number>
- </property>
- <property name="topMargin" >
- <number>9</number>
- </property>
- <property name="rightMargin" >
- <number>9</number>
- </property>
- <property name="bottomMargin" >
- <number>9</number>
- </property>
- <property name="horizontalSpacing" >
- <number>6</number>
- </property>
- <property name="verticalSpacing" >
- <number>6</number>
- </property>
- <item row="0" column="0" >
- <widget class="QListView" name="developers" />
- </item>
- <item row="1" column="0" >
- <widget class="QPushButton" name="allDevelopersButton" >
- <property name="text" >
- <string>All</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections>
- <connection>
- <sender>allDevelopersButton</sender>
- <signal>clicked()</signal>
- <receiver>developers</receiver>
- <slot>clearSelection()</slot>
- <hints>
- <hint type="sourcelabel" >
- <x>54</x>
- <y>517</y>
- </hint>
- <hint type="destinationlabel" >
- <x>52</x>
- <y>415</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork_messagehistory.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop (nonexistent)
@@ -1,77 +0,0 @@
-[Desktop Entry]
-Type=Service
-Exec=blubb
-Comment=This plugin allows collaboration
-Comment[bs]=Ovaj dodatak omogućava sarađivanje
-Comment[ca]=Aquest connector permet la col·laboració
-Comment[ca@valencia]=Aquest connector permet la col·laboració
-Comment[de]=Dieses Modul ermöglicht die Zusammenarbeit
-Comment[en_GB]=This plugin allows collaboration
-Comment[es]=Este complemento permite colaboración
-Comment[et]=See plugin võimaldab koostööd
-Comment[fr]=Ce module externe permet de travailler en collaboration
-Comment[gl]=Este complemento permite traballar colaborativamente.
-Comment[hu]=Ez a bővítmény lehetővé teszi az együttműködést
-Comment[it]=Questa estensione consente la collaborazione
-Comment[nl]=Deze plugin maakt samenwerken mogelijk
-Comment[pl]=Wtyczka ta pozwala na kolaborację
-Comment[pt]=Este 'plugin' permite a colaboração
-Comment[pt_BR]=Este plugin permite a colaboração
-Comment[sv]=Insticksprogrammet tillhandahåller stöd för samarbete
-Comment[uk]=За допомогою цього додатка можна здійснювати співпрацю
-Comment[x-test]=xxThis plugin allows collaborationxx
-Name=Teamwork
-Name[bs]=Timski rad
-Name[ca]=Treball en equip
-Name[ca@valencia]=Treball en equip
-Name[de]=Zusammenarbeit
-Name[en_GB]=Teamwork
-Name[es]=Trabajo en equipo
-Name[et]=Meeskonnatöö
-Name[fr]=Équipe de travail
-Name[ga]=Cur Le Chéile
-Name[gl]=Traballo en equipo
-Name[hu]=Csapatmunka
-Name[it]=Lavoro di squadra
-Name[nl]=Teamwork
-Name[pl]=Teamwork
-Name[pt]=Trabalho em Equipa
-Name[pt_BR]=Trabalho em equipe
-Name[sk]=Tímová práca
-Name[sv]=Lagarbete
-Name[ug]=ھەمكارلىشىپ ئىشلەش
-Name[uk]=Командна робота
-Name[x-test]=xxTeamworkxx
-GenericName=Teamwork
-GenericName[bs]=Timski rad
-GenericName[ca]=Treball d'equip
-GenericName[ca@valencia]=Treball d'equip
-GenericName[de]=Zusammenarbeit
-GenericName[en_GB]=Teamwork
-GenericName[es]=Trabajo en equipo
-GenericName[et]=Meeskonnatöö
-GenericName[fr]=L'équipe de travail
-GenericName[ga]=Cur Le Chéile
-GenericName[gl]=Equipo de traballo
-GenericName[hu]=Csapatmunka
-GenericName[it]=Lavoro di squadra
-GenericName[nds]=Koppelarbeit
-GenericName[nl]=Teamwork
-GenericName[pl]=Teamwork
-GenericName[pt]=Trabalho em equipa
-GenericName[pt_BR]=Trabalho em equipe
-GenericName[sk]=Tímová práca
-GenericName[sv]=Lagarbete
-GenericName[tr]=Takım çalışması
-GenericName[ug]=ھەمكارلىشىپ ئىشلەش
-GenericName[uk]=Командна робота
-GenericName[x-test]=xxTeamworkxx
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevteamwork
-X-KDE-PluginInfo-Name=kdevteamwork
-X-KDE-PluginInfo-Author=David Nolden
-X-KDE-PluginInfo-Version=0.15
-X-KDE-PluginInfo-License=GPL
-X-KDevelop-Version=7
-X-KDevelop-Category=Global
-X-KDevelop-Mode=GUI
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/kdevteamwork.desktop
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h (nonexistent)
@@ -1,99 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#ifndef TEAMWORKFOLDERMANAGER_H
-#define TEAMWORKFOLDERMANAGER_H
-
-#include <kurl.h>
-#include <QString>
-#include <QMap>
-
-/**Since KDevelop now is no single-project application any more,
- * a notion of a workspace is necessary so teamwork is possible across multiple projects.
- * The workspace-directory is the directory where the .teamwork-subfolder with all the teamwork-data
- * will be created, and file-collaboration is possible on subfolders of that workspace.
- * Of course the workspace-directory could be a simple project-directory.
- * This class manages the .teamwork-subfolder of the workspace.
- * */
-class TeamworkFolderManager {
- public:
- TeamworkFolderManager( const KUrl& directory );
- ~TeamworkFolderManager();
- /**
- * This function creates an empty file.
- * This function throws QString on errors.
- * @param subFolder can be a whole sub-tree which will be created if it doesn't exist.
- * @param extension the extension of the file to create, without dot(example "cpp")
- * @param name name of the file. If a file with that name already exists, it will be prefixed to be unique.
- * @return the absolute URL of the file
- * */
- static KUrl createUniqueFile( const QString& subFolder, const QString& extension, const QString& name, const QString& namePrefix, const QString& nameSuffix ) throw(QString);
-
- static KUrl createUniqueDirectory( const QString& subFolder, const QString& name, const QString& namePrefix = "", const QString& nameSuffix = "" ) throw(QString);
-
- /** This takes a complete reference-filename which may include folders(those will be created), and from which extension and name will be extracted.(see function above)
- * */
- static KUrl createUniqueFile( const QString& subFolder, const QString& fileName, const QString& namePrefix = "", const QString& nameSuffix = "" ) throw(QString);
-
- /**
- * This may be called with a file/folder. On destruction of the class(close of the workspace), that folder will automatically be deleted.
- * @param url Complete url of the file/folder to be deleted on destruction. It must be a subfolder of the .teamwork-folder.
- * */
- static void registerTempItem( const KUrl& file );
-
- /**
- * @param subfolder a subfolder of .teamwork that the url will be relative to
- * @return the URL relative to the .teamwork-directory
- * */
- static QString teamworkRelative( const KUrl& url, const QString& subfolder = QString() );
-
- /**
- * @param subfolder a subfolder of workspace-dir that the url will be relative to
- * @return the URL relative to the workspace-directory
- * */
- static QString workspaceRelative( const KUrl& url, const QString& subfolder = QString() );
-
- /**
- * @param subFolder an additional subFolder of workspace-dir that the sub-url is in
- * @return the absolute directory of the given sub-directory
- * */
- static KUrl workspaceAbsolute( const QString& subPath, const QString& subFolder = QString() );
-
- /**
- * @param subFolder an additional subFolder of .teamwork that the sub-url is in
- * @return the absolute directory of the given sub-directory of the .teamwork-folder
- * */
- static KUrl teamworkAbsolute( const QString& subPath, const QString& subFolder = QString() );
-
- static KUrl workspaceDirectory();
-
- static TeamworkFolderManager* self();
-
- /**
- * Creates the .teamwork folder if it does not exist yet.
- **/
- static void createTeamworkFolder() throw(QString);
-
- private:
- static bool createFile( const KUrl& url );
- static TeamworkFolderManager* m_self;
-
- KUrl m_teamworkDir;
- KUrl m_workspaceDir;
-
- QMap<QString, bool> m_tempItems;
-};
-
-#endif
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/teamworkfoldermanager.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp (nonexistent)
@@ -1,369 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "filecollaborationmanager.h"
-#include <QAction>
-#include <QMenu>
-#include <QTimer>
-#include <QFileInfo>
-#include <QModelIndex>
-#include <QStandardItemModel>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/cursor.h>
-
-#include <interfaces/idocumentcontroller.h>
-
-#include "lib/network/messagesendhelper.h"
-#include "lib/network/messagetypeset.h"
-#include "lib/network/sessioninterface.h"
-
-#include "lib/dynamictext/verify.h"
-
-#include "teamworkfwd.h"
-#include "patchesmanager.h"
-#include "kdevteamwork_user.h"
-#include "kdevutils.h"
-#include "documentwrapper.h"
-#include "kdevteamwork_helpers.h"
-#include "ui_kdevteamwork_filecollaborationsession.h"
-
-/* Exclude this file from doublequote_chars check as krazy doesn't understand
-std::string*/
-//krazy:excludeall=doublequote_chars
-
-using namespace Teamwork;
-
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, QList<QString>, 0, value->plainFileNames() )
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, QList<KDevTeamworkUserPointer>, 0, value->users() )
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, SessionName, 0, value->name() )
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, FileCollaborationSessionPointer, 0, value )
-CROSSMAP_KEY_EXTRACTOR( FileCollaborationSessionPointer, CollabSessionId, 0, value->id() )
-
-/**How file-collaboration should work:
- * Host:
- * - Once developer starts a collaboration-session on an arbitrary set of files, he can invite an arbitrary count of collaborating developers to join it.
- * - He can only host one collaboration-session at a time.
- * - Once the session is closed, he is asked whether he'd like to store the changes of the session as a patch to the patches-list(that way he may also unapply the changes if he saved them).
- * Client:
- * - A client gets an invitation and can accept it.
- * - The client can only be part of one collaboration-session at a time.
- * - Once the session is closed, he is asked whether the result of the session should be stored as a diff-file to the patches-list.(that way it may be applied to the local tree)
- *
- * Implementation: See DynamicText
- *
- * */
-
-/**Algorithm for the FileCollaboration:
- * - Each FileCollaboration-message that is sent gets a personal sequence-number(which is like a timestamp, the "count of locally happened events")
- * that can be used to see which state of the communication it was sent in(and can be used to resolve causalities)
- * - Each FileCollaboration-session has a vector containing all current sequence-numbers
- * - Each FileCollaboration-message is sent together with that vector, so conflicts may be resolved.
- * - Whenever the master-session sends a FileResynchronize-message, the local version of the slave-session is totally updated
- * */
-
-
-Q_DECLARE_METATYPE( Teamwork::UserPointer )
-
-
-
-FileCollaborationManager::FileCollaborationManager( CollaborationManager* manager ) :
- SafeLogger( manager->teamwork() ->logger(),
- "FileCollaborationManager: " ),
- m_manager( manager ),
-m_dispatcher( *this ) {
- connect( m_manager, SIGNAL( fillCollaboratingUserMenu( QMenu*, const UserPointer& ) ), this, SLOT( slotFillCollaboratingUserMenu( QMenu*, const UserPointer& ) ) );
- m_startCollaborationSessionAction = new QAction( i18n("Start File-Collaboration"), this );
- connect( m_startCollaborationSessionAction, SIGNAL( triggered() ), this, SLOT( slotStartCollaborationSession() ) );
- connect( manager, SIGNAL( updateModel( QStandardItemModel* ) ), this, SLOT( updateCollaborationModel( QStandardItemModel* ) ) );
-
-}
-
-KDevTeamwork* FileCollaborationManager::teamwork() {
- return m_manager->teamwork();
-}
-
-const FileCollaborationManager::SessionSet& FileCollaborationManager::sessions() {
- return m_sessions;
-}
-
-FileCollaborationSession * FileCollaborationManager::startSession( const QString& name, CollabFileList files, uint primaryIndex, CollabSessionId id ) {
- FileCollaborationSessionPointer s = new FileCollaborationSession( name, files, this, primaryIndex, id );
- m_sessions.insert( s );
-
- connect( s.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), this, SLOT( slotSessionStateChanged( const FileCollaborationSessionPointer& ) ) );
-
- return s;
-}
-
-void FileCollaborationManager::updateCollaborationModel( QStandardItemModel* model ) {
-
- ///Add/update sessions
- QMap< FileCollaborationSessionPointer, QPersistentModelIndex > sessions;
-
- for ( int r = model->rowCount() - 1; r >= 0 ; --r ) {
- QModelIndex i = model->index( r, 0 );
- if ( !i.isValid() )
- continue;
- QVariant v = i.data( Qt::UserRole );
- if ( v.canConvert<CollaborationTreeActionPointer>() ) {
- CollaborationTreeActionPointer action = v.value<CollaborationTreeActionPointer>();
- StandardCollaborationTreeAction<FileCollaborationSession> *session = dynamic_cast< StandardCollaborationTreeAction<FileCollaborationSession>* >( action.data() );
- if( session ) {
- if ( !session->target ) {
- model->removeRow( r );
- } else {
- sessions[ (FileCollaborationSession*)session->target ] = i;
- }
- }
- }
- }
-
- SessionSet::ValueMap::const_iterator it = m_sessions.begin();
- for ( ; it != m_sessions.end(); ++it ) {
- FileCollaborationSessionPointer session = ( *it ).second.value;
- QModelIndex i;
- if ( sessions.contains( session ) ) {
- i = sessions[ session ];
- } else {
- model->insertRow( 0 );
- i = model->index( 0, 0 );
- sessions[ session ] = QPersistentModelIndex( i );
- disconnect( session.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), m_manager, SLOT( sessionStateChanged( const FileCollaborationSessionPointer& ) ) );
- connect( session.data(), SIGNAL( stateChanged( const FileCollaborationSessionPointer& ) ), m_manager, SLOT( sessionStateChanged( const FileCollaborationSessionPointer& ) ) );
- }
-
- QIcon icon = session->icon();
- model->setData( i, session->name(), Qt::DisplayRole );
- model->setData( i, icon, Qt::DecorationRole );
-
- /*QVariant
- model->setData( i, icon, Qt::DecorationRole );*/
- QVariant v;
- v.setValue<CollaborationTreeActionPointer>( new StandardCollaborationTreeAction<FileCollaborationSession>( session ) );
- model->setData( i, v, Qt::UserRole );
-
- session->updateTree( i, model );
- }
-}
-
-void FileCollaborationManager::slotFillCollaboratingUserMenu( QMenu * menu, const UserPointer & user ) {
- if ( m_sessions.empty() ) {
- QVariant v;
- v.setValue( user );
- m_startCollaborationSessionAction->setData( v );
-
- menu->addAction( m_startCollaborationSessionAction );
- }
-
- emit fillCollaboratingUserMenu( menu, user );
-}
-
-
-
-void FileCollaborationManager::slotStartCollaborationSession() {
- try {
- QAction * act = qobject_cast<QAction*>( sender() );
- if ( !act )
- throw "no action";
-
- QVariant v = act->data();
- if ( !v.canConvert<UserPointer>() )
- throw "wrong data";
-
- UserPointer::Locked lu = v.value<UserPointer>();
- if ( !lu )
- throw "could not lock user";
-
- CollabFileList files;
-
- files.push_back(CollabFile(0, currentDocumentPath() ) );
-
- Ui_NewFileCollaborationSession s;
- KDialog d;
- d.setButtons( KDialog::Ok | KDialog::Cancel );
- s.setupUi( d.mainWidget() );
- s.sessionName->setText( "Collaborate_on_" + QFileInfo( files.front().file ).baseName() );
- QString filesText = "Files:";
- for( CollabFileList::iterator it = files.begin(); it != files.end(); ++it ) {
- filesText += "\n" + it->file;
- }
- s.files->setText( filesText );
-
- QString usersText = "Invite users:";
- usersText += "\n" + ~lu->name();
- s.users->setText( usersText );
-
- if( d.exec() == QDialog::Accepted ) {
- QString name = s.sessionName->text();
- FileCollaborationSessionPointer p = startSession( name, files );
-
- p->setAllowSentDocuments( s.allowSentDocuments->isChecked() );
- p->inviteUser( lu.freeCast<KDevTeamworkUser>() );
- }
- } catch ( const char * str ) {
- err() << QString( "Error in slotStartCollaborationSession(): " ) + str;
- } catch ( QString str ) {
- err() << QString( "Error in slotStartCollaborationSession(): " ) + str;
- };
-}
-
-void FileCollaborationManager::processMessage( FileCollaborationMessagePointer msg ) {
- FileCollaborationMessagePointer::Locked l = msg;
- if ( l ) {
- if ( l->sessionId() == 0 || msg.cast<FileCollaborationRequest>() ) {
- m_dispatcher( l );
- } else {
- FileCollaborationSessionPointer s = m_sessions.value<CollabSessionId>( l->sessionId() );
- if ( s ) {
- s->processMessage( l.data() );
- } else {
- err() << "got message for unknown file-collaboration-session with id ~" << l->sessionId() <<", type:" << msg.unsafe()->name();
- }
- }
- } else {
- err() << "could not lock a FileCollaborationMessage";
- }
-}
-
-int FileCollaborationManager::receiveMessage( MessageInterface* msg ) {
- out( Logger::Warning ) << "got unknown message-type" << msg->name();
- return 0;
-}
-
-int FileCollaborationManager::receiveMessage( FileCollaborationRequest* msg ) {
- ///Since it is an AbstractGUIMessage, it can plug itself into the GUI and wait for an answer by the user.
- m_manager->teamwork() ->addMessageToList( msg );
- return 1;
-}
-
-int FileCollaborationManager::receiveMessage( FileCollaborationMessage* msg ) {
- SessionSet::Iterator it = m_sessions.values<CollabSessionId>( msg->sessionId() );
- if( it ) {
- return const_cast<FileCollaborationSession*>((*it).data())->processMessage( msg );
- } else {
- out( Logger::Warning ) << "got a FileCollaborationMessage of type" << msg->name() << "for a non-existent session:" << (uint)msg->sessionId();
- return 0;
- }
-}
-
-void FileCollaborationManager::slotSessionStateChanged( const FileCollaborationSessionPointer & session ) {
- m_sessions.update( session );
-}
-
-void FileCollaborationManager::denyCollaboration( const FileCollaborationRequestPointer& msg ) {
- FileCollaborationRequestPointer::Locked l = msg;
- if ( !l ) {
- err() << "denyCollaboration(): could not lock message";
- return;
- }
-
- std::pair< RequestMap::const_iterator, RequestMap::const_iterator > range = m_requests.equal_range( l->sessionId() );
-
- ///Deny all other requests for the same session
- bool ready = false;
- while( !ready ) {
- ready = true;
- std::pair< RequestMap::iterator, RequestMap::iterator > range = m_requests.equal_range( l->sessionId() );
-
- while( range.first != range.second ) {
- if( (*range.first).second == msg ) {
- m_requests.erase( range.first++ );
- continue;
- }
- FileCollaborationRequestPointer::Locked lm = (*range.first).second;
- if( lm ) {
- int cnt = m_requests.size();
- lm->denyCollaboration();
- if( m_requests.size() != (uint)cnt ) {
- ready = false;
- break;
- }
- }
- ++range.first;
- }
- }
-}
-
-bool FileCollaborationManager::acceptCollaboration( const FileCollaborationRequestPointer& msg ) {
- try {
- FileCollaborationRequestPointer::Locked l = msg;
- if ( !l )
- throw "could not lock message";
-
- //Q_VERIFY( l->index() != 0 );
-
- FileCollaborationSessionPointer session;
- if( m_sessions.values( l->sessionId() ) ) {
- session = m_sessions[ l->sessionId() ];
- } else {
- QString name = l->FileCollaborationRequestData::name();
- if( name.isEmpty() ) {
- name = "anonymous session";
- if( l->info().user() )
- name += "@" + ~l->info().user().unsafe()->safeName();
- }
- session = startSession( name, l->files(), l->index(), l->sessionId() );
- if ( !session )
- throw "could not create FileCollaborationSession";
- }
-
- session->acceptMessage( msg );
-
- ///Now pull in all other requests waiting for this session
- bool ready = false;
- while( !ready ) {
- ready = true;
- std::pair< RequestMap::iterator, RequestMap::iterator > range = m_requests.equal_range( l->sessionId() );
-
- while( range.first != range.second ) {
- if( (*range.first).second == msg ) {
- m_requests.erase( range.first++ );
- continue;
- }
- FileCollaborationRequestPointer::Locked lm = (*range.first).second;
- if( lm ) {
- int cnt = m_requests.size();
- lm->denyCollaboration();
- if( m_requests.size() != (uint)cnt ) {
- ready = false;
- break;
- }
- }
- ++range.first;
- }
- }
-
- out( Logger::Debug ) << "collaboration accepted";
- m_requests.erase( l->sessionId() );
- return true;
- } catch ( const QString & str ) {
- err() << "error in acceptCollaboration:" << str;
- return false;
- } catch ( const char * str ) {
- err() << "error in acceptCollaboration:" << str;
- return false;
- }
-}
-
-void FileCollaborationManager::closeSession( const FileCollaborationSessionPointer& session ) {
- session->aboutToClose();
- m_sessions.remove( session );
-}
-
-
-#include "filecollaborationmanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filecollaborationmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp (nonexistent)
@@ -1,39 +0,0 @@
-/***************************************************************************
- Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-#include "filesynchronizemessage.h"
-#include "lib/dynamictext/dynamictext.h"
-#include "utils.h"
-#include "qtserialization.h"
-#include <boost/serialization/vector.hpp>
-
-FileSynchronizeData::FileSynchronizeData( const QString& fileName, const QDynamicText& text, bool sendDynamic ) {
- if( sendDynamic ) {
- m_fileText = ~text.text().text();
- } else {
- m_text = new QDynamicText( text );
- }
- m_state = text.state();
- m_fileName = fileName;
-}
-
-QDynamicTextPointer FileSynchronizeData::createDynamicText() {
- if( m_text )
- return m_text;
- else
- return new QDynamicText( m_state, ~m_fileText );
-}
-
-EASY_IMPLEMENT_MESSAGE( FileSynchronize )
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/filesynchronizemessage.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp (nonexistent)
@@ -1,105 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-
-
-#include "messagesendmanager.h"
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-#include <interfaces/icore.h>
-#include <interfaces/idocument.h>
-#include <interfaces/idocumentcontroller.h>
-#include <indocumentreference.h>
-
-#include "kdevteamworkplugin.h"
-#include "teamworkfoldermanager.h"
-
-MessageSendManager::MessageSendManager( Ui::Teamwork& widgets ) : m_widgets( widgets ), m_lastDocument(0) {
- connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentActivated( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentLoaded( KDevelop::IDocument* ) ), this, SLOT( documentActivated( KDevelop::IDocument* ) ) );
- connect( KDevTeamworkPlugin::staticDocumentController(), SIGNAL( documentClosed( KDevelop::IDocument* ) ), this, SLOT( documentClosed( KDevelop::IDocument* ) ) );
- if( KDevTeamworkPlugin::staticDocumentController()->activeDocument() )
- documentActivated( KDevTeamworkPlugin::staticDocumentController()->activeDocument() );
-}
-
-void MessageSendManager::documentActivated( KDevelop::IDocument* document ) {
- if( document == m_lastDocument ) return;
- disconnectDocument();
- connectDocument( document );
-}
-
-void MessageSendManager::documentClosed( KDevelop::IDocument* document ) {
- if( document == m_lastDocument )
- disconnectDocument();
-}
-
-void MessageSendManager::connectDocument( KDevelop::IDocument* document ) {
- m_lastDocument = document;
- if( !document->textDocument() ) return;
- connect( document->textDocument(), SIGNAL(destroyed( QObject* )), this, SLOT( documentDestroyed( QObject* ) ) );
- connect( document->textDocument(), SIGNAL( viewCreated( KTextEditor::Document* , KTextEditor::View* ) ), this, SLOT( viewCreated( KTextEditor::Document*, KTextEditor::View* ) ) );
-
- KTextEditor::View* v = view();
- if( !v ) return;
- connectView( v );
-}
-
-void MessageSendManager::connectView( KTextEditor::View* v ) {
- disconnect( v, SIGNAL( selectionChanged( KTextEditor::View* ) ), this, SLOT( selectionChanged( KTextEditor::View* ) ) ); ///Just to make sure that multiple connections don't happen
- connect( v, SIGNAL( selectionChanged( KTextEditor::View* ) ), this, SLOT( selectionChanged( KTextEditor::View* ) ) );
-}
-
-KTextEditor::View* MessageSendManager::view() {
- if( !m_lastDocument ) return 0;
- if( !m_lastDocument->textDocument() ) return 0;
- return m_lastDocument->textDocument()->activeView();
-}
-
-void MessageSendManager::disconnectDocument() {
- KDevelop::IDocument* document = m_lastDocument;
- if( !document ) return;
- if( !document->textDocument() ) return;
- disconnect( document->textDocument(), SIGNAL(destroyed( QObject* )), this, SLOT( documentDestroyed( QObject* ) ) );
- disconnect( document->textDocument(), SIGNAL( viewCreated( KTextEditor::Document* , KTextEditor::View* ) ), this, SLOT( viewCreated( KTextEditor::Document*, KTextEditor::View* ) ) );
-
- m_lastDocument = 0;
-}
-
-void MessageSendManager::documentDestroyed( QObject* /*obj*/ ) {
- m_lastDocument = 0;
-}
-
-void MessageSendManager::viewCreated( KTextEditor::Document* , KTextEditor::View* ) {
-}
-
-void MessageSendManager::selectionChanged( KTextEditor::View* view ) {
-
- m_currentSelection = view->selectionRange();
- KTextEditor::Document* doc = view->document();
- m_currentFile = "";
- if( doc )
- m_currentFile = TeamworkFolderManager::workspaceRelative( doc->url() );
-
- ///Now check if the message-send-widget is visible
- if( m_widgets.toolBox->currentWidget() == m_widgets.messaging && !m_currentFile.isEmpty() ) {
- if( m_currentSelection.isEmpty() ) {
- ///Remove the selection
- } else {
- m_widgets.reference->setText( InDocumentReference::createReference( m_currentFile.pathOrUrl(), m_currentSelection.start().line(), m_currentSelection.start().column(), m_currentSelection.end().line(), m_currentSelection.end().column() ) );
- }
- }
-}
-
-#include "messagesendmanager.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messagesendmanager.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.cpp (nonexistent)
@@ -1,109 +0,0 @@
-/***************************************************************************
-Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
-***************************************************************************/
-
-/***************************************************************************
- * *
- * 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. *
- * *
- ***************************************************************************/
-#include "messageusertab.h"
-
-#include <QWidget>
-#include<QListView>
-#include<QStandardItemModel>
-
-#include "kdevteamwork.h"
-#include "kdevteamwork_user.h"
-#include <QMetaType>
-#include "ui_kdevteamwork_interface.h"
-#include "utils.h"
-#include "kdevteamwork_messages.h"
-
-Q_DECLARE_METATYPE( MessagePointer )
-
-
-MessageUserTab& MessageUserTab::operator = ( const MessageUserTab& /*rhs*/ ) {
- return * this;
-}
-
-MessageUserTab::~MessageUserTab() {
- delete m_widget;
-}
-
-bool MessageUserTab::operator < ( const MessageUserTab& rhs ) {
- return m_user < rhs.m_user;
-}
-
-MessageUserTab::MessageUserTab( KDevTeamwork* tw, KDevTeamworkUserPointer user ) : m_user( user ), m_teamwork( tw ) {
- m_widget = new QWidget;
- m_list->setupUi( m_widget );
- qRegisterMetaType<KDevTeamworkUserPointer>( "KDevTeamworkUserPointer" );
- m_view = m_list->list;
- m_model = new QStandardItemModel( 0, 1, m_widget );
- m_view->setModel( m_model );
- KDevTeamworkUserPointer::Locked l = user;
- if ( l ) {
- tw->m_widgets->messageUsers->addTab( m_widget, l->icon(), ~l->safeName() );
- connect( l.data(), SIGNAL( userStateChanged( KDevTeamworkUserPointer ) ), this, SLOT( userStateChanged( KDevTeamworkUserPointer ) ), Qt::QueuedConnection );
- }
- connect( m_view, SIGNAL( clicked( const QModelIndex& ) ), tw, SLOT( messageClicked( const QModelIndex& ) ) );
-
- userStateChanged( m_user );
-}
-
-void MessageUserTab::userStateChanged( KDevTeamworkUserPointer ) {
- if ( !m_teamwork->m_widget )
- return ;
- int i = m_teamwork->m_widgets->messageUsers->indexOf( m_widget );
- if ( i != -1 ) {
- KDevTeamworkUserPointer::Locked l = m_user;
- if ( l ) {
- m_teamwork->m_widgets->messageUsers->setTabIcon( i, l->icon() );
- }
- }
-}
-
-void MessageUserTab::messageUpdated( const Teamwork::MessagePointer& msg ) {
- for ( int a = 0; a < m_model->rowCount(); ++a ) {
- QModelIndex i = m_model->index( a, 0 );
- if ( i.isValid() ) {
- QVariant v = m_model->data( i, Qt::UserRole );
- if ( v.canConvert<MessagePointer>() ) {
- if ( v.value<MessagePointer>() == msg ) {
- MessagePointer::Locked l = msg;
- if ( l ) {
- AbstractGUIMessage * guiMsg = l.freeCast<AbstractGUIMessage>();
- if ( guiMsg ) {
- m_model->setData( i, guiMsg->messageIcon(), Qt::DecorationRole );
- }
- }
- }
- }
- }
- }
-}
-
-QStandardItemModel* MessageUserTab::model() {
- return m_model;
-}
-
-QListView* MessageUserTab::view() {
- return m_view;
-}
-
-KDevTeamworkUserPointer MessageUserTab::user() {
- return m_user;
-}
-
-QWidget* MessageUserTab::widget() {
- return m_widget;
-}
-
-#include "messageusertab.moc"
-
-// kate: space-indent on; indent-width 2; tab-width 2; replace-tabs on
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/teamwork/messageusertab.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharp.g
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharp.g (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharp.g (nonexistent)
@@ -1,3015 +0,0 @@
------------------------------------------------------------------------------
--- Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
---
--- This grammar 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 grammar 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
--- Lesser 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.
------------------------------------------------------------------------------
-
-
------------------------------------------------------------------------------
--- Grammar for C# 2.0
--- Modelled after the reference grammar of the C# 2.0 language specification
--- (ECMA-334, Third Edition from June 2005, available at
--- http://www.ecma-international.org/publications/standards/Ecma-334.htm),
--- and the BSD-licensed ANTLR C# 1.0 grammar "kcsparse" at
--- http://antlr.org/grammar/list (version from December 01, 2005)
------------------------------------------------------------------------------
-
-
--- 16 first/follow conflicts:
--- - The EXTERN conflicts in compilationUnit. They would be gone if
--- typeDeclaration used OptionalTypeModifiers instead of
--- broader optionalModifiers, but we stick with the latter one in order
--- to improve the AST. As the externAliasDirective comes first, it
--- rightfully gets selected, and so the conflict is harmless.
--- (done right by default, 2 conflicts)
--- - The LBRACKET conflict in compilationUnit,
--- and the following EXTERN, LBRACKET conflict there.
--- LBRACKET is resolved, EXTERN is just the above harmless conflict again.
--- (manually resolved, 2 conflicts)
--- - The COMMA conflict in attributeArguments: greedy is ok.
--- (done right by default, 1 conflict)
--- - The COMMA conflict in enumBody, also similar to the above.
--- (manually resolved, 1 conflict)
--- - The COMMA conflict in typeArguments:
--- the approach for catching ">" signs works this way, and the conflict
--- is resolved by the trailing condition at the end of the rule.
--- (manually resolved, 1 conflict)
--- - The COMMA conflict in arrayInitializer, another one of those.
--- (manually resolved, 1 conflict)
--- - The BIT_AND conflict in bitAndExpression,
--- the PLUS, MINUS conflict in additiveExpression,
--- the STAR conflict in multiplicativeExpression, and
--- the LPAREN, INCREMENT, DECREMENT conflict in primaryExpression.
--- They originate in the rather hackish solution to make expressions like
--- "a is SomeType ? ifExp : elseExp" work (see conditionalExpression)
--- and can be ignored, because the condition does the necessary check.
--- (manually resolved, 4 conflicts)
--- - The LBRACKET conflict in arrayCreationExpressionRest, for which
--- newExpression with its arrayCreationExpression part is to blame.
--- Caused by the fact that arrayCreationExpression can't be seperated
--- from primaryAtom and put into primaryExpression instead.
--- (manually resolved, 1 conflict)
--- - The LBRACKET, STAR conflict in unmanagedType, similar to the one
--- in arrayCreationExpression, only that it's triggered by the
--- rank specifiers instead. The LBRACKET conflict is caused by the fact
--- that arrayCreationExpression can't be seperated.
--- As a consequence, all rank specifiers are checked for safety, always.
--- The star conflict is caused by the may-end-with-epsilon typeArguments.
--- It doesn't apply at all, only kdevelop-pg thinks it does. Code segments...
--- (manually resolved, 1 conflict)
--- - The DOT conflict in namespaceOrTypeName:
--- Caused by the may-end-with-epsilon typeArguments. It doesn't apply
--- at all, only kdevelop-pg thinks it does. Code segments...
--- (done right by default, 1 conflict)
--- - The DOT conflict in namespaceOrTypeNameSafe,
--- which actually stems from indexerDeclaration.
--- (manually resolved, 1 conflict)
-
--- 14 first/first conflicts:
--- - The ADD, ALIAS, etc. (identifier) conflict in usingDirective.
--- (manually resolved, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflicts in attributeArguments,
--- two similar ones.
--- (manually resolved, 2 conflicts)
--- - The PARTIAL conflict in classOrStructMemberDeclaration,
--- between typeDeclarationRest and identifier.
--- (manually resolved, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflict
--- in classOrStructMemberDeclaration, between constructorDeclaration
--- and the (Type ...) part of the rule.
--- (manually resolved, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflict
--- in classOrStructMemberDeclaration (another one), between
--- the field declaration and the (typeNameSafe ...) part of the subrule.
--- (manually resolved, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflict in eventDeclaration,
--- between variableDeclarator and typeName.
--- (manually resolved, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflict
--- in typeParametersConstraints, caused by the similarity of
--- primaryOrSecondaryConstraint (with ClassType) and
--- secondaryConstraints (with typeName). Not resolved, instead,
--- primaryOrSecondaryConstraint may be both, as indicated by the name.
--- (done right by default, 1 conflict)
--- - The ADD, ALIAS, etc. (identifier) conflict in blockStatement
--- between all three statement Types. labeledStatement vs. the other two
--- is resolved easily, whereas localVariableDeclarationStatement
--- vs. embeddedStatement needs arbitrary-length LL(k), and is solved
--- with a try/rollback() block.
--- (manually resolved, 1 conflict)
--- - The CHECKED, UNCHECKED, YIELD conflict in embeddedStatement.
--- For "checked" and "unchecked", this is because there are both blocks
--- and expression statements starting with "(un)checked". For "Yield",
--- this is because "Yield" is not only the start of yieldStatement,
--- but also a non-keyword identifier, and as such needs special treatment.
--- Seperate LA(2) comparisons for all three of them.
--- (manually resolved, 1 conflict)
--- - The CATCH conflict in catchClauses.
--- (manually resolved, 1 conflict)
--- - The VOID conflict in TypeofExpression.
--- (manually resolved, 1 conflict)
--- - The BOOL, BYTE, CHAR, etc. conflict in TypeofExpression.
--- That conflict is only naturally, because there's the same "Type" rule
--- in two branches of an alternative item. One for C# 2.0 or higher,
--- and another one for C# 1.0. So, this is an artificial conflict.
--- (manually resolved, 1 conflict)
--- - The VOID conflict in returnType.
--- (manually resolved, 1 conflict)
-
--- Total amount of conflicts: 30
-
-
-
-------------------------------------------------------------
--- Global declarations
-------------------------------------------------------------
-
-[:
-#include <QtCore/QString>
-#include <QtCore/QSet>
-
-namespace KDevelop
-{
-class DUContext;
-}
-
-namespace CSharpPP
-{
-class HandlerVisitor;
-}
-
-namespace CSharp
-{
-class ParseSession;
-}
-
-#define yy_block_errors 0
-
-:]
-
-%export_macro "KDEVCSHARPPARSER_EXPORT"
-%export_macro_header "csharpparserexport.h"
-
-
-------------------------------------------------------------
--- Ast Node class members
-------------------------------------------------------------
-%ast_extra_members
-[:
- KDevelop::DUContext* ducontext;
-:]
-
-------------------------------------------------------------
--- Parser class members
-------------------------------------------------------------
-
-%parserclass (public declaration)
-[:
- /**
- * Transform the raw input into tokens.
- * When this method returns, the parser's token stream has been filled
- * and any parse*() method can be called.
- */
- void tokenize( ParseSession* session );
-
- /**
- * The compatibilityMode status variable tells which version of C#
- * should be checked against.
- */
- enum CSharpCompatibilityMode {
- CSharp10Compatibility = 100,
- CSharp20Compatibility = 200
- };
- Parser::CSharpCompatibilityMode compatibilityMode();
- void setCompatibilityMode( Parser::CSharpCompatibilityMode Mode );
-
- void ppDefineSymbol( QString symbolName );
-
- enum ProblemType {
- error,
- warning,
- info
- };
- void reportProblem( Parser::ProblemType type, const char* message );
- void reportProblem( Parser::ProblemType type, QString message );
-:]
-
-%parserclass (protected declaration)
-[:
- friend class ::CSharpPP::HandlerVisitor; // calls the pp_*() methods
-
- /** Called when an #error or #warning directive has been found.
- * @param type Either Parser::Error or Parser::Warning.
- * @param label The error/warning text.
- */
- virtual void ppDiagnostic( Parser::ProblemType /*type*/, QString /*message*/ ) {}
- virtual void ppDiagnostic( Parser::ProblemType /*type*/ ) {}
-:]
-
-%parserclass (private declaration)
-[:
- void ppUndefineSymbol( QString symbolName );
- bool ppIsSymbolDefined( QString symbolName );
-
- Parser::CSharpCompatibilityMode m_compatibilityMode;
- QSet<QString> m_ppDefinedSymbols;
-
- struct ParserState {
- // ltCounter stores the amount of currently open type arguments rules,
- // all of which are beginning with a less than ("<") character.
- // This way, also RSHIFT (">>") can be used to close type arguments rules,
- // in addition to GREATER_THAN (">").
- int ltCounter;
- };
- ParserState m_state;
-
- // Rather hackish solution for recognizing expressions like
- // "a is SomeType ? ifExp : elseExp", see conditionalExpression.
- bool isNullableType( TypeAst *type );
- void unsetNullableType( TypeAst *type );
- TypeAst *lastRelationalExpressionRestType(
- NullCoalescingExpressionAst *nullCoalescingExpression );
-:]
-
-%parserclass (constructor)
-[:
- m_compatibilityMode = CSharp20Compatibility;
-:]
-
-
-
-------------------------------------------------------------
--- Enumeration Types for additional AST members
-------------------------------------------------------------
-
-%namespace
-[:
-namespace AccessPolicy
-{
- enum AccessPolicyEnum {
- AccessPrivate = 0, // default value: memory pool initializes everything with zeros
- AccessProtected,
- AccessProtectedInternal,
- AccessInternal,
- AccessPublic
- };
-}
-
-namespace Modifiers
-{
- enum ModifierEnum {
- ModNew = 1,
- ModAbstract = 1 << 1,
- ModSealed = 1 << 2,
- ModStatic = 1 << 3,
- ModReadonly = 1 << 4,
- ModVolatile = 1 << 5,
- ModVirtual = 1 << 6,
- ModOverride = 1 << 7,
- ModExtern = 1 << 8,
- ModUnsafe = 1 << 9,
- ModFixed = 1 << 10
- };
-}
-
-namespace ConversionOperatorDeclaration
-{
- enum ConversionTypeEnum {
- ConversionImplicit,
- ConversionExplicit
- };
-}
-
-namespace ConstructorInitializer
-{
- enum ConstructorInitializerTypeEnum {
- TypeBase,
- TypeThis
- };
-}
-
-namespace OverloadableOperator
-{
- enum UnaryOrBinaryEnum {
- TypeUnary,
- TypeBinary
- };
-
- enum OverloadableOperatorEnum
- {
- // Overloadable Unary operators:
- OpBang,
- OpTilde,
- OpIncrement,
- OpDecrement,
- OpTrue,
- OpFalse,
- // Overloadable Unary or binary operators:
- OpPlus,
- OpMinus,
- // Overloadable binary operators:
- OpStar,
- OpSlash,
- OpRemainder,
- OpBitAnd,
- OpBitOr,
- OpBitXor,
- OpLShift,
- OpRShift,
- OpEqual,
- OpNotEqual,
- OpGreaterThan,
- OpLessThan,
- OpGreaterEqual,
- OpLessEqual
- };
-}
-
-namespace AccessorDeclarations
-{
- enum AccessorTypeEnum {
- TypeGet,
- TypeSet,
- TypeNone // only possible for the second, optional Accessor
- };
-}
-
-namespace PrimaryOrSecondaryConstraint
-{
- enum PrimaryOrSecondaryConstraintEnum {
- TypeType,
- TypeClass,
- TypeStruct
- };
-}
-
-namespace Argument
-{
- enum ArgumentTypeEnum {
- TypeValueParameter,
- TypeReferenceParameter,
- TypeOutputParameter
- };
-}
-
-namespace GotoStatement
-{
- enum GotoStatementEnum {
- TypeLabeledStatement,
- TypeSwitchCase,
- TypeSwitchDefault
- };
-}
-
-namespace YieldStatement
-{
- enum YieldStatementEnum {
- TypeYieldReturn,
- TypeYieldBreak
- };
-}
-
-namespace SwitchLabel
-{
- enum BranchTypeEnum {
- CaseBranch,
- DefaultBranch
- };
-}
-
-namespace Expression
-{
- enum AssignmentOperatorEnum {
- NoAssignment,
- OpAssign,
- OpPlusAssign,
- OpMinusAssign,
- OpStarAssign,
- OpSlashAssign,
- OpRemainderAssign,
- OpBitAndAssign,
- OpBitOrAssign,
- OpBitXorAssign,
- OpLShiftAssign,
- OpRShiftAssign
- };
-}
-
-namespace EqualityExpressionRest
-{
- enum EqualityOperatorEnum {
- OpEqual,
- OpNotEqual
- };
-}
-
-namespace RelationalExpressionRest
-{
- enum RelationalOperatorEnum {
- OpLessThan,
- OpGreaterThan,
- OpLessEqual,
- OpGreaterEqual,
- OpIs,
- OpAs
- };
-}
-
-namespace ShiftExpressionRest
-{
- enum ShiftOperatorEnum {
- OpLShift,
- OpRShift
- };
-}
-
-namespace AdditiveExpressionRest
-{
- enum AdditiveOperatorEnum {
- OpPlus,
- OpMinus
- };
-}
-
-namespace MultiplicativeExpressionRest
-{
- enum MultiplicativeOperatorEnum {
- OpStar,
- OpSlash,
- OpRemainder
- };
-}
-
-namespace UnaryExpression
-{
- enum UnaryExpressionEnum {
- TypeIncrementedExpression,
- TypeDecrementedExpression,
- TypeUnaryMinusExpression,
- TypeUnaryPlusExpression,
- TypeBitwiseNotExpression,
- TypeLogicalNotExpression,
- TypeCastExpression,
- TypeprimaryExpression,
- TypePointerIndirectionExpression,
- TypeAddressofExpression
- };
-}
-
-namespace PrimarySuffix
-{
- enum PrimarySuffixEnum {
- TypeMemberAccess,
- TypePointerMemberAccess,
- TypeInvocation,
- TypeElementAccess,
- TypeIncrement,
- TypeDecrement
- };
-}
-
-namespace PrimaryAtom
-{
- enum PrimaryAtomEnum {
- TypeLiteral,
- TypeParenthesizedExpression,
- TypeMemberAccess,
- TypeThisAccess,
- TypeBaseAccess,
- TypeNewExpression,
- TypeTypeofExpression,
- TypeCheckedExpression,
- TypeUncheckedExpression,
- TypeDefaultValueExpression,
- TypeAnonymousMethodExpression,
- TypeSizeofExpression
- };
-}
-
-namespace PredefinedType
-{
- enum PredefinedTypeEnum {
- TypeBool,
- TypeByte,
- TypeChar,
- TypeDecimal,
- TypeDouble,
- TypeFloat,
- TypeInt,
- TypeLong,
- TypeObject,
- TypeSbyte,
- TypeShort,
- TypeString,
- TypeUint,
- TypeUlong,
- TypeUshort
- };
-}
-
-namespace BaseAccess
-{
- enum BaseAccessEnum {
- TypeBaseMemberAccess,
- TypeBaseIndexerAccess
- };
-}
-
-namespace TypeofExpression
-{
- enum TypeofExpressionEnum {
- TypeVoid,
- TypeUnboundTypeName,
- TypeType
- };
-}
-
-namespace ReturnType
-{
- enum ReturnTypeEnum {
- TypeRegular,
- TypeVoid
- };
-}
-
-namespace PointerType
-{
- enum PointerTypeEnum {
- TypeRegular,
- TypeVoidStar
- };
-}
-
-namespace UnmanagedTypeSuffix
-{
- enum SuffixType {
- TypeStar,
- TypeRankSpecifier
- };
-}
-
-namespace BuiltinClassType
-{
- enum BuiltinClassTypeEnum {
- TypeObject,
- TypeString
- };
-}
-
-namespace SimpleType
-{
- enum SimpleTypeEnum {
- TypeNumeric,
- TypeBool
- };
-}
-
-namespace NumericType
-{
- enum NumericTypeEnum {
- TypeIntegral,
- TypeFloatingPoint,
- TypeDecimal
- };
-}
-
-namespace IntegralTypes
-{
- enum IntegralTypeEnum {
- TypeSbyte,
- TypeByte,
- TypeShort,
- TypeUshort,
- TypeInt,
- TypeUint,
- TypeLong,
- TypeUlong,
- TypeChar
- };
-}
-
-namespace FloatingPointType
-{
- enum FloatingPointTypeEnum {
- TypeFloat,
- TypeDouble
- };
-}
-
-namespace Parameter
-{
- enum ParameterTypeEnum {
- ValueParameter,
- ReferenceParameter,
- OutputParameter
- };
-}
-
-namespace Literal
-{
- enum LiteralTypeEnum {
- TypeTrue,
- TypeFalse,
- TypeNull,
- TypeInteger,
- TypeReal,
- TypeCharacter,
- TypeString
- };
-}
-:]
-
-
-
-------------------------------------------------------------
--- List of defined tokens
-------------------------------------------------------------
-
--- keywords:
-%token ABSTRACT ("abstract"), AS ("as"), BASE ("base"), BOOL ("bool"),
- BREAK ("break"), BYTE ("byte"), CASE ("case"), CATCH ("catch"),
- CHAR ("char"), CHECKED ("checked"), CLASS ("class"), CONST ("const"),
- CONTINUE ("continue"), DECIMAL ("decimal"), DEFAULT ("default"),
- DELEGATE ("delegate"), DO ("do"), DOUBLE ("double"), ELSE ("else"),
- ENUM ("enum"), EVENT ("event"), EXPLICIT ("explicit"),
- EXTERN ("extern"), FINALLY ("finally"), FIXED ("fixed"),
- FLOAT ("float"), FOREACH ("foreach"), FOR ("for"), GOTO ("goto"),
- IF ("if"), IMPLICIT ("implicit"), IN ("in"), INT ("int"),
- INTERFACE ("interface"), INTERNAL ("internal"), IS ("is"),
- LOCK ("lock"), LONG ("long"), NAMESPACE ("namespace"), NEW ("new"),
- OBJECT ("object"), OPERATOR ("operator"), OUT ("out"),
- OVERRIDE ("override"), PARAMS ("params"), PRIVATE ("private"),
- PROTECTED ("protected"), PUBLIC ("public"), READONLY ("readonly"),
- REF ("ref"), RETURN ("return"), SBYTE ("sbyte"), SEALED ("sealed"),
- SHORT ("short"), SIZEOF ("sizeof"), STACKALLOC ("stackalloc"),
- STATIC ("static"), STRING ("string"), STRUCT ("struct"),
- SWITCH ("switch"), THIS ("this"), THROW ("throw"), TRY ("try"),
- TYPEOF ("typeof"), UINT ("uint"), ULONG ("ulong"),
- UNCHECKED ("unchecked"), UNSAFE ("unsafe"), USHORT ("ushort"),
- USING ("using"), VIRTUAL ("virtual"), VOID ("void"),
- VOLATILE ("volatile"), WHILE ("while") ;;
-
--- non-keyword identifiers with special meaning in the grammar:
-%token ADD ("add"), ALIAS("alias"), GET ("get"), GLOBAL ("global"),
- PARTIAL ("partial"), REMOVE ("remove"), SET ("set"), VALUE ("value"),
- WHERE ("where"), YIELD ("yield"), ASSEMBLY ("assembly") ;;
-
--- seperators:
-%token LPAREN ("("), RPAREN (")"), LBRACE ("{"), RBRACE ("}"), LBRACKET ("["),
- RBRACKET ("]"), COMMA (","), SEMICOLON (";"), DOT (".") ;;
-
--- operators:
-%token COLON (":"), SCOPE ("::"), QUESTION ("?"), QUESTIONQUESTION ("??"),
- BANG ("!"), TILDE ("~"), EQUAL ("=="), LESS_THAN ("<"),
- LESS_EQUAL ("<="), GREATER_THAN (">"), GREATER_EQUAL (">="),
- NOT_EQUAL ("!="), LOG_AND ("&&"), LOG_OR ("||"), ARROW_RIGHT ("->"),
- INCREMENT ("++"), DECREMENT ("--"), ASSIGN ("="), PLUS ("+"),
- PLUS_ASSIGN ("+="), MINUS ("-"), MINUS_ASSIGN ("-="), STAR ("*"),
- STAR_ASSIGN ("*="), SLASH ("/"), SLASH_ASSIGN ("/="), BIT_AND ("&"),
- BIT_AND_ASSIGN ("&="), BIT_OR ("|"), BIT_OR_ASSIGN ("|="),
- BIT_XOR ("^"), BIT_XOR_ASSIGN ("^="), REMAINDER ("%"),
- REMAINDER_ASSIGN ("%="), LSHIFT ("<<"), LSHIFT_ASSIGN ("<<="),
- RSHIFT (">>"), RSHIFT_ASSIGN (">>=") ;;
-
--- literals and identifiers:
-%token TRUE ("true"), FALSE ("false"), NULL ("null"),
- INTEGER_LITERAL ("integer literal"), REAL_LITERAL ("real literal"),
- CHARACTER_LITERAL ("character literal"),
- STRING_LITERAL ("string literal"), IDENTIFIER ("identifier") ;;
-
--- token that makes the parser fail in any case:
-%token INVALID ("invalid token") ;;
-
-
-
-
-------------------------------------------------------------
--- Start of the actual grammar
-------------------------------------------------------------
-
-
- 0 [: m_state.ltCounter = 0; :]
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#externAlias=externAliasDirective)+
- | 0
- )
- try/recover(#using=usingDirective)*
- try/recover(
- 0 [: if (LA(2).kind != Token_ASSEMBLY) break; :] -- exit the "star loop"
- #globalAttribute=globalAttributeSection
- )*
- try/recover(#namespace=namespaceMemberDeclaration)*
--> compilationUnit ;;
-
-
- EXTERN ALIAS identifier=identifier SEMICOLON
--> externAliasDirective ;;
-
- USING
- ( ?[: LA(2).kind == Token_ASSIGN :] -- "using alias" directive
- alias:identifier ASSIGN namespaceOrTypeName:namespaceOrTypeName
- usingAliasDirective=usingAliasDirectiveData[alias, namespaceOrTypeName]
- |
- namespaceName:namespaceName -- "using namespace" directive
- usingNamespaceDirective=usingNamespaceDirectiveData[namespaceName]
- )
- SEMICOLON
--> usingDirective ;;
-
- 0
--> usingAliasDirectiveData [
- argument member node alias: identifier;
- argument member node namespaceOrTypeName: namespaceOrTypeName;
-] ;;
-
- 0
--> usingNamespaceDirectiveData [
- argument member node namespaceName: namespaceName;
-] ;;
-
-
-
-
--- ATTRIBUTE sections, global and standard ones. They have a slight similarity
--- with Java's annotations in that they are used as advanced Type Modifiers.
-
--- Strictly seen, the ASSEMBLY here should just be attributeTarget.
--- But for the sake of avoiding an LL(k)-ambiguous conflict
--- (in compilationUnit), we just allow "assembly".
-
- LBRACKET ASSEMBLY COLON
- #attribute=attribute
- ( COMMA [: if (yytoken == Token_RBRACKET) { break; } :]
- #attribute=attribute
- )*
- RBRACKET
--> globalAttributeSection ;;
-
- try/recover(#attribute=attributeSection)*
--> optionalAttributeSections ;;
-
- LBRACKET
- ( ?[: LA(2).kind == Token_COLON :] target=attributeTarget COLON
- | 0
- )
- #attribute=attribute
- ( COMMA [: if (yytoken == Token_RBRACKET) { break; } :]
- #attribute=attribute
- )*
- RBRACKET
--> attributeSection ;;
-
- identifier=identifier | keyword=keyword
--> attributeTarget ;;
-
- name=typeName (arguments=attributeArguments | 0)
--> attribute ;;
-
- LPAREN
- (
- -- empty argument list:
- RPAREN
- |
- -- argument list only containing named arguments:
- ?[: LA(2).kind == Token_ASSIGN :]
- #namedArgument=namedArgument @ COMMA
- RPAREN
- |
- -- argument list with positional arguments and
- -- optionally appended named arguments:
- #positionalArgument=positionalArgument
- ( COMMA
- ( ?[: LA(2).kind == Token_ASSIGN :]
- (#namedArgument=namedArgument @ COMMA)
- [: break; :] -- go directly to the closing parenthesis
- |
- #positionalArgument=positionalArgument
- )
- )*
- RPAREN
- )
--> attributeArguments ;;
-
- attributeArgumentExpression=expression
--> positionalArgument ;;
-
- argumentName=identifier ASSIGN attributeArgumentExpression=expression
--> namedArgument ;;
-
-
-
-
--- NAMESPACES can be nested arbitrarily and contain stuff
--- like classes, interfaces, or other declarations.
-
- namespaceDeclaration=namespaceDeclaration
- | typeDeclaration=typeDeclaration
--> namespaceMemberDeclaration ;;
-
- NAMESPACE name=qualifiedIdentifier body=namespaceBody (SEMICOLON | 0)
--> namespaceDeclaration ;;
-
- LBRACE
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#externAlias=externAliasDirective)+
- | 0
- )
- try/recover(#using=usingDirective)*
- try/recover(#namespace=namespaceMemberDeclaration)*
- RBRACE
--> namespaceBody ;;
-
- attributes:optionalAttributeSections
- modifiers:optionalModifiers
- rest=typeDeclarationRest[ attributes, modifiers ]
--> typeDeclaration ;;
-
--- C# 2.0 or higher allows partial classes, structs and interfaces.
--- We don't need to introduce an additional check here, because the lexer only
--- returns the PARTIAL token for C# versions >= 2.0, and IDENTIFIER otherwise.
--- TODO: after parsing, check if the modifiers are allowed for the specific
--- kind of type declaration.
-
- (
- PARTIAL
- ( classDeclaration=classDeclaration[ attributes, modifiers, true ]
- | structDeclaration=structDeclaration[ attributes, modifiers, true ]
- | interfaceDeclaration=interfaceDeclaration[ attributes, modifiers, true ]
- )
- |
- ( classDeclaration=classDeclaration[ attributes, modifiers, false ]
- | structDeclaration=structDeclaration[ attributes, modifiers, false ]
- | interfaceDeclaration=interfaceDeclaration[ attributes, modifiers, false ]
- | enumDeclaration=enumDeclaration[ attributes, modifiers ]
- | delegateDeclaration=delegateDeclaration[ attributes, modifiers ]
- )
- )
--> typeDeclarationRest [
- argument temporary node attributes: optionalAttributeSections;
- argument temporary node modifiers: optionalModifiers;
-] ;;
-
-
-
--- Definition of a C# CLASS
-
- CLASS className=identifier
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- (classBase=classBase | 0)
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- body=classBody
- (SEMICOLON | 0)
--> classDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member variable partial: bool;
-] ;;
-
-
--- Definition of a C# STRUCT
-
- STRUCT structName=identifier
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- (structInterfaces=interfaceBase | 0)
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- body=structBody
- (SEMICOLON | 0)
--> structDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member variable partial: bool;
-] ;;
-
-
--- Definition of a C# INTERFACE
-
- INTERFACE interfaceName=identifier
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- (interfaceBase=interfaceBase | 0)
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- body=interfaceBody
- (SEMICOLON | 0)
--> interfaceDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member variable partial: bool;
-] ;;
-
-
--- Definition of a C# ENUM
-
- ENUM enumName=identifier
- (enumBase=enumBase | 0)
- body=enumBody
- (SEMICOLON | 0)
--> enumDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
-] ;;
-
-
--- Definition of a C# DELEGATE
-
- DELEGATE returnType=returnType delegateName=identifier
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- LPAREN (formalParameters=formalParameterList | 0) RPAREN
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- SEMICOLON
--> delegateDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
-] ;;
-
-
--- BASE CLASSES and INTERFACES
--- which can be implemented by the Types above
-
--- For classBase, the first type in the list of Base types May_ be a class.
--- (But it can also be an interface.) In order to avoid ambiguities, only the
--- first part of the rule has the exact seperation. If the second part of the
--- rule is chosen, then the first element of baseTypeSequence can be
--- the Base class.
-
- COLON
- ( builtinClassType=builtinClassType
- (COMMA (#interfaceType=typeName @ COMMA) | 0)
- |
- #baseType=typeName @ COMMA
- )
--> classBase ;;
-
- COLON #interfaceType=typeName @ COMMA
--> interfaceBase ;;
-
- COLON integralType=integralType
--> enumBase ;;
-
-
-
--- BODIES of classes, interfaces, and the likes.
-
- LBRACE try/recover(#memberDeclaration=classMemberDeclaration)* RBRACE
--> classBody ;;
-
- LBRACE try/recover(#memberDeclaration=structMemberDeclaration)* RBRACE
--> structBody ;;
-
- LBRACE try/recover(#memberDeclaration=interfaceMemberDeclaration)* RBRACE
--> interfaceBody ;;
-
- LBRACE
- try/recover(
- #memberDeclaration=enumMemberDeclaration
- ( 0 [: if (LA(2).kind == Token_RBRACE) break; :] -- exit the "star loop"
- COMMA #memberDeclaration=enumMemberDeclaration
- )*
- (COMMA | 0)
- |
- 0
- )
- RBRACE
--> enumBody ;;
-
- attributes=optionalAttributeSections
- memberName=identifier
- (ASSIGN value=constantExpression | 0)
--> enumMemberDeclaration ;;
-
-
-
-
--- Now on to what happens inside the class, interface, etc. bodies:
-
-
--- The CLASS MEMBER DECLARATION is one of the most complex rules in here,
--- and covers everything that can occur inside a class body.
-
- attributes:optionalAttributeSections
- modifiers:optionalModifiers
- ( finalizerDeclaration=finalizerDeclaration[ attributes, modifiers ]
- | otherDeclaration=classOrStructMemberDeclaration[ attributes, modifiers ]
- )
--> classMemberDeclaration ;;
-
- attributes:optionalAttributeSections
- modifiers:optionalModifiers
- declaration=classOrStructMemberDeclaration[ attributes, modifiers ]
--> structMemberDeclaration ;;
-
--- The first few declarations start with a specific token and don't need
--- to be refactored. The other declarations must be split to avoid conflicts.
-
- (
- constantDeclaration=constantDeclaration[ attributes, modifiers ]
- | eventDeclaration=eventDeclaration[ attributes, modifiers ]
- |
- -- The OPERATOR DECLARATION, part one: Conversion operator overloading.
- conversionOperatorDeclaration=conversionOperatorDeclaration[ attributes, modifiers ]
- |
- -- A normal or static CONSTRUCTOR DECLARATION.
- ?[: LA(2).kind == Token_LPAREN :]
- constructorDeclaration=constructorDeclaration[ attributes, modifiers ]
- |
- -- The TYPE DECLARATION, buried under lookahead conditions ;)
- ?[: (yytoken != Token_PARTIAL) || (LA(2).kind == Token_CLASS
- || LA(2).kind == Token_INTERFACE || LA(2).kind == Token_ENUM
- || LA(2).kind == Token_STRUCT || LA(2).kind == Token_DELEGATE) :]
- typeDeclarationRest=typeDeclarationRest[ attributes, modifiers ]
- |
- -- Many of the declarations start with a type, and method declarations
- -- start with a return type which is therefore the least common denominator.
- MemberType:returnType
- (
- -- The OPERATOR DECLARATION rest, part two: overloading of real operators
- ?[: MemberType->type == ReturnType::TypeRegular :]
- unaryOrBinaryOperatorDeclaration=unaryOrBinaryOperatorDeclaration[
- attributes, modifiers, MemberType->regularType
- ]
- |
- -- The INDEXER DECLARATION rest, part one.
- ?[: MemberType->type == ReturnType::TypeRegular :]
- indexerDeclaration=indexerDeclaration[
- attributes, modifiers, MemberType->regularType, 0 /* no interface Type */
- ]
- |
- -- The FIELD DECLARATION rest. Declares member variables.
- ?[: ( LA(2).kind == Token_SEMICOLON || LA(2).kind == Token_ASSIGN
- || LA(2).kind == Token_COMMA || LA(2).kind == Token_LBRACKET
- ) && (MemberType->type == ReturnType::TypeRegular) :]
- (#variableDeclarator:variableDeclarator[
- ((modifiers->modifiers & Modifiers::ModFixed) != 0) /* is a fixed size buffer? */
- ] @ COMMA)
- SEMICOLON
- fieldDeclaration=variableDeclarationData[
- attributes, modifiers,
- MemberType->regularType, variableDeclaratorSequence
- ]
- |
- -- and this is for rules that are still not split up sufficiently:
- MemberNameOrInterfaceType:typeNameSafe
- -- (interfaceType for the indexer declaration, memberName otherwise)
- (
- -- The INDEXER DECLARATION rest, part two.
- ?[: MemberType->type == ReturnType::TypeRegular :]
- DOT
- indexerDeclaration=indexerDeclaration[
- attributes, modifiers,
- MemberType->regularType, MemberNameOrInterfaceType
- ]
- |
- -- The PROPERTY DECLARATION rest.
- ?[: MemberType->type == ReturnType::TypeRegular :]
- propertyDeclaration=propertyDeclaration[
- attributes, modifiers, MemberType->regularType, MemberNameOrInterfaceType
- ]
- |
- -- The METHOD DECLARATION rest.
- methodDeclaration=methodDeclaration[
- attributes, modifiers, MemberType, MemberNameOrInterfaceType
- ]
- )
- )
- )
--> classOrStructMemberDeclaration [
- argument temporary node attributes: optionalAttributeSections;
- argument temporary node modifiers: optionalModifiers;
-] ;;
-
-
-
--- Having summarized the possible class/struct members, we now specify
--- what they look like.
-
-
--- The FINALIZER is what other languages know as deConstructor.
--- Only allowed inside classes.
-
- TILDE className=identifier LPAREN RPAREN
- (body=block | SEMICOLON)
--> finalizerDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
-] ;;
-
-
-
--- The CONSTRUCTOR DECLARATION. Naturally quite similar to the method one.
--- Will also be folded into the memberDeclaration.
-
- className=identifier
- LPAREN (formalParameters=formalParameterList | 0) RPAREN
- (constructorInitializer=constructorInitializer | 0)
- (body=block | SEMICOLON)
--> constructorDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
-] ;;
-
- COLON
- ( BASE [: (*yynode)->initializerType = ConstructorInitializer::TypeBase; :]
- | THIS [: (*yynode)->initializerType = ConstructorInitializer::TypeThis; :]
- )
- LPAREN arguments=optionalArgumentList RPAREN
--> constructorInitializer [
- member variable initializerType: ConstructorInitializer::ConstructorInitializerTypeEnum;
-] ;;
-
--- There is also a STATIC CONSTRUCTOR DECLARATION which is only used if
--- the Modifiers contain "static" (and optionally "extern", and nothing else).
--- Apart from the "static" Modifier, the static Constructor declaration
--- is a subset of the generic one. In order to keep the parser simple,
--- we don't check on the Modifiers here and thus only use
--- constructorDeclaration. On the whole, Modifier checking should be done
--- in the visitor, later on... but we could make an exception here.
-
--- className=identifier LPAREN RPAREN
--- (body=block | SEMICOLON)
--- -> staticConstructorDeclaration ;;
-
-
-
--- The EVENT DECLARATION.
-
- EVENT type=type
- (
- -- this condition avoids the LL(k) conflict here:
- ?[: (LA(2).kind == Token_COMMA) || (LA(2).kind == Token_ASSIGN)
- || (LA(2).kind == Token_SEMICOLON)
- :]
- (#variableDeclarator=variableDeclarator[false] @ COMMA) SEMICOLON
- |
- eventName=typeName
- LBRACE eventaccessorDeclarations=eventaccessorDeclarations RBRACE
- )
--> eventDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
-] ;;
-
--- EVENT ACCESSOR DECLARATIONS appear inside an event declaration.
-
- accessor1Attributes:optionalAttributeSections
- (
- ADD accessor1Body:block
- addAccessorDeclaration=eventAccessorDeclaration[
- accessor1Attributes, accessor1Body
- ]
- accessor2Attributes:optionalAttributeSections
- REMOVE accessor2Body:block
- removeAccessorDeclaration=eventAccessorDeclaration[
- accessor2Attributes, accessor2Body
- ]
- |
- REMOVE accessor1Body:block
- removeAccessorDeclaration=eventAccessorDeclaration[
- accessor1Attributes, accessor1Body
- ]
- accessor2Attributes:optionalAttributeSections
- ADD accessor2Body:block
- addAccessorDeclaration=eventAccessorDeclaration[
- accessor2Attributes, accessor2Body
- ]
- )
--> eventaccessorDeclarations ;;
-
- 0
--> eventAccessorDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node body: block;
-] ;;
-
-
-
--- The different forms of the OPERATOR DECLARATION which overloads operators:
--- Conversion, Unary and binary operator declarations.
-
- ( IMPLICIT [: (*yynode)->conversion = ConversionOperatorDeclaration::ConversionImplicit; :]
- | EXPLICIT [: (*yynode)->conversion = ConversionOperatorDeclaration::ConversionExplicit; :]
- )
- OPERATOR targetType=type
- LPAREN sourceParameter=operatorDeclarationParameter RPAREN
- (body=block | SEMICOLON)
--> conversionOperatorDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- member variable conversion: ConversionOperatorDeclaration::ConversionTypeEnum;
-] ;;
-
- OPERATOR
- ( UnaryOp:overloadableUnaryOnlyOperator[&(*yynode)->overloadableOperatorType]
- LPAREN sourceParameter1=operatorDeclarationParameter RPAREN
- [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeUnary;
- (*yynode)->overloadableOperatorToken = UnaryOp->token; :]
- |
- binaryOp:overloadableBinaryOnlyOperator[&(*yynode)->overloadableOperatorType]
- LPAREN sourceParameter1=operatorDeclarationParameter
- COMMA sourceParameter2=operatorDeclarationParameter RPAREN
- [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeBinary;
- (*yynode)->overloadableOperatorToken = binaryOp->token; :]
- |
- UnaryOrBinaryOp:overloadableUnaryOrBinaryOperator[&(*yynode)->overloadableOperatorType]
- LPAREN sourceParameter1=operatorDeclarationParameter
- (
- COMMA sourceParameter2=operatorDeclarationParameter
- [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeBinary;
- (*yynode)->overloadableOperatorToken = UnaryOrBinaryOp->token; :]
- |
- 0 [: (*yynode)->unaryOrBinary = OverloadableOperator::TypeUnary;
- (*yynode)->overloadableOperatorToken = UnaryOrBinaryOp->token; :]
- )
- RPAREN
- )
- (body=block | SEMICOLON)
--> unaryOrBinaryOperatorDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member node returnType: type;
- member variable unaryOrBinary: OverloadableOperator::UnaryOrBinaryEnum;
- member variable overloadableOperatorType: OverloadableOperator::OverloadableOperatorEnum;
- member token overloadableOperatorToken;
-] ;;
-
- type=type name=identifier
--> operatorDeclarationParameter ;;
-
-
--- OVERLOADABLE OPERATORS for operator declarations.
-
- (
- token=BANG [: *op = OverloadableOperator::OpBang; :]
- | token=TILDE [: *op = OverloadableOperator::OpTilde; :]
- | token=INCREMENT [: *op = OverloadableOperator::OpIncrement; :]
- | token=DECREMENT [: *op = OverloadableOperator::OpDecrement; :]
- | token=TRUE [: *op = OverloadableOperator::OpTrue; :]
- | token=FALSE [: *op = OverloadableOperator::OpFalse; :]
- )
--> overloadableUnaryOnlyOperator [
- argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
-] ;;
-
- (
- token=STAR [: *op = OverloadableOperator::OpStar; :]
- | token=SLASH [: *op = OverloadableOperator::OpSlash; :]
- | token=REMAINDER [: *op = OverloadableOperator::OpRemainder; :]
- | token=BIT_AND [: *op = OverloadableOperator::OpBitAnd; :]
- | token=BIT_OR [: *op = OverloadableOperator::OpBitOr; :]
- | token=BIT_XOR [: *op = OverloadableOperator::OpBitXor; :]
- | token=LSHIFT [: *op = OverloadableOperator::OpLShift; :]
- | token=RSHIFT [: *op = OverloadableOperator::OpRShift; :]
- | token=EQUAL [: *op = OverloadableOperator::OpEqual; :]
- | token=NOT_EQUAL [: *op = OverloadableOperator::OpNotEqual; :]
- | token=GREATER_THAN [: *op = OverloadableOperator::OpGreaterThan; :]
- | token=LESS_THAN [: *op = OverloadableOperator::OpLessThan; :]
- | token=GREATER_EQUAL [: *op = OverloadableOperator::OpGreaterEqual; :]
- | token=LESS_EQUAL [: *op = OverloadableOperator::OpLessEqual; :]
- )
--> overloadableBinaryOnlyOperator [
- argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
-] ;;
-
- (
- token=PLUS [: *op = OverloadableOperator::OpPlus; :]
- | token=MINUS [: *op = OverloadableOperator::OpMinus; :]
- )
--> overloadableUnaryOrBinaryOperator [
- argument temporary variable op: OverloadableOperator::OverloadableOperatorEnum*;
-] ;;
-
-
-
--- The INDEXER DECLARATION rest.
-
- THIS LBRACKET formalParameters=formalParameterList RBRACKET
- LBRACE accessorDeclarations=accessorDeclarations RBRACE
--> indexerDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member node type: type;
- argument member node interfaceType: typeNameSafe;
-] ;;
-
-
-
--- The PROPERTY DECLARATION rest.
-
- LBRACE accessorDeclarations=accessorDeclarations RBRACE
--> propertyDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member node type: type;
- argument member node propertyName: typeNameSafe;
-] ;;
-
--- ACCESSOR DECLARATIONS appear inside a property declaration.
-
- accessor1Attributes=optionalAttributeSections
- (accessor1Modifier=accessorModifier | 0)
- (
- GET (accessor1Body=block | SEMICOLON)
- [: (*yynode)->accessor1Type = AccessorDeclarations::TypeGet; :]
- (
- accessor2Attributes=optionalAttributeSections
- (accessor2Modifier=accessorModifier | 0)
- SET (accessor2Body=block | SEMICOLON)
- [: (*yynode)->accessor2Type = AccessorDeclarations::TypeSet; :]
- | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
- )
- |
- SET (accessor1Body=block | SEMICOLON)
- [: (*yynode)->accessor1Type = AccessorDeclarations::TypeSet; :]
- (
- accessor2Attributes=optionalAttributeSections
- (accessor2Modifier=accessorModifier | 0)
- GET (accessor2Body=block | SEMICOLON)
- [: (*yynode)->accessor2Type = AccessorDeclarations::TypeGet; :]
- | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
- )
- )
--> accessorDeclarations [
- member variable accessor1Type: AccessorDeclarations::AccessorTypeEnum;
- member variable accessor2Type: AccessorDeclarations::AccessorTypeEnum;
-] ;;
-
- (
- PROTECTED [: (*yynode)->accessPolicy = AccessPolicy::AccessProtected; :]
- ( INTERNAL [: (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal; :]
- | 0
- )
- | INTERNAL [: (*yynode)->accessPolicy = AccessPolicy::AccessInternal; :]
- ( PROTECTED [: (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal; :]
- | 0
- )
- | PRIVATE [: (*yynode)->accessPolicy = AccessPolicy::AccessPrivate; :]
- )
--> accessorModifier [
- member variable accessPolicy: AccessPolicy::AccessPolicyEnum;
-] ;;
-
-
-
--- The METHOD DECLARATION rest.
-
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- LPAREN (formalParameters=formalParameterList | 0) RPAREN
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- (body=block | SEMICOLON)
--> methodDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member node modifiers: optionalModifiers;
- argument member node returnType: returnType;
- argument member node methodName: typeNameSafe;
-] ;;
-
-
-
-
--- Interfaces have their own specific INTERFACE MEMBER DECLARATIONS.
--- Resembling the classOrStructMemberDeclaration, but less complex.
-
- attributes:optionalAttributeSections
- ( NEW [: declNew = true; :]
- | 0 [: declNew = false; :]
- )
- (
- eventDeclaration=interfaceEventDeclaration[
- attributes, declNew
- ]
- |
- -- Many of the declarations start with a type, and method declarations
- -- start with a return type which is therefore the least common denominator.
- MemberType:returnType
- (
- -- The INDEXER DECLARATION rest.
- ?[: MemberType->type == ReturnType::TypeRegular :]
- indexerDeclaration=interfaceIndexerDeclaration[
- attributes, declNew, MemberType->regularType
- ]
- |
- -- The method and property declarations need to be split further.
- memberName:identifier
- (
- -- The INTERFACE PROPERTY DECLARATION rest.
- ?[: MemberType->type == ReturnType::TypeRegular :]
- interfacePropertyDeclaration=interfacePropertyDeclaration[
- attributes, declNew,
- MemberType->regularType, memberName
- ]
- |
- -- The INTERFACE METHOD DECLARATION rest.
- interfaceMethodDeclaration=interfaceMethodDeclaration[
- attributes, declNew, MemberType, memberName
- ]
- )
- )
- )
--> interfaceMemberDeclaration [
- temporary variable declNew: bool; -- specifies if the "new" keyword prepends the declaration
-] ;;
-
-
--- Here are the detailed interface member declaration rules. Basically,
--- all of them are just simplified versions of the class/struct ones.
-
--- The INTERFACE EVENT DECLARATION.
-
- EVENT EventType=type eventName=identifier SEMICOLON
--> interfaceEventDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member variable declNew: bool;
-] ;;
-
--- The INTERFACE INDEXER DECLARATION.
-
- THIS LBRACKET formalParameters=formalParameterList RBRACKET
- LBRACE interfaceAccessors=interfaceAccessors RBRACE
--> interfaceIndexerDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member variable declNew: bool;
- argument member node type: type;
-] ;;
-
--- The INTERFACE PROPERTY DECLARATION.
-
- LBRACE interfaceAccessors=interfaceAccessors RBRACE
--> interfacePropertyDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member variable declNew: bool;
- argument member node type: type;
- argument member node propertyName: identifier;
-] ;;
-
--- And last but not least, the INTERFACE METHOD DECLARATION.
-
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(typeParameters=typeParameters)
- | 0
- )
- LPAREN (formalParameters=formalParameterList | 0) RPAREN
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/recover(#typeParametersConstraints=typeParametersConstraintsClause)+
- | 0
- )
- SEMICOLON
--> interfaceMethodDeclaration [
- argument member node attributes: optionalAttributeSections;
- argument member variable declNew: bool;
- argument member node returnType: returnType;
- argument member node methodName: identifier;
-] ;;
-
-
-
--- An INTERFACE ACCESSOR looks like "[attributes] get;" or "[attributes] set;"
--- and is used by interfaceIndexerDeclaration and interfacePropertyDeclaration.
-
- accessor1Attributes=optionalAttributeSections
- (
- GET SEMICOLON
- [: (*yynode)->accessor1Type = AccessorDeclarations::TypeGet; :]
- (
- accessor2Attributes=optionalAttributeSections SET SEMICOLON
- [: (*yynode)->accessor2Type = AccessorDeclarations::TypeSet; :]
- | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
- )
- |
- SET SEMICOLON
- [: (*yynode)->accessor1Type = AccessorDeclarations::TypeSet; :]
- (
- accessor2Attributes=optionalAttributeSections GET SEMICOLON
- [: (*yynode)->accessor2Type = AccessorDeclarations::TypeGet; :]
- | 0 [: (*yynode)->accessor2Type = AccessorDeclarations::TypeNone; :]
- )
- )
--> interfaceAccessors [
- member variable accessor1Type: AccessorDeclarations::AccessorTypeEnum;
- member variable accessor2Type: AccessorDeclarations::AccessorTypeEnum;
-] ;;
-
-
-
-
--- A FORMAL PARAMETER LIST is part of a method header and contains one or more
--- Parameters, optionally ending with a variable-length "Parameter array".
--- It's not as hackish as it used to be, nevertheless it could still be nicer.
-
- 0 [: bool parameterArrayOccurred = false; :]
- (
- try/recover(
- #formalParameter=formalParameter[&parameterArrayOccurred]
- ( 0 [: if( parameterArrayOccurred == true ) { break; } :]
- -- Don't proceed after the Parameter array. If there's a cleaner way
- -- to exit the loop when m_parameterArrayOccurred == true,
- -- please use that instead of this construct.
- COMMA #formalParameter=formalParameter[&parameterArrayOccurred]
- )*
- )
- | 0
- )
--> formalParameterList ;;
-
--- How it _should_ look:
---
--- 0 [: bool parameterArrayOccurred = false; :]
--- (
--- try/recover(
--- #formalParameter=formalParameter[&parameterArrayOccurred]
--- ( ?[: parameterArrayOccurred == false :] -- kdev-pg dismisses this condition!
--- COMMA #formalParameter=formalParameter[&parameterArrayOccurred]
--- )*
--- )
--- | 0
--- )
--- -> formalParameterList ;;
-
- attributes=optionalAttributeSections
- (
- PARAMS paramsType=arrayType variableName=identifier
- [: *parameterArrayOccurred = true; :]
- |
- modifier=optionalParameterModifier type=type variableName=identifier
- )
--> formalParameter [
- argument temporary variable parameterArrayOccurred: bool*;
-] ;;
-
-
--- An OPTIONAL ARGUMENT LIST is used when calling methods
--- (not for declaring them, that's what formal Parameter lists are for).
-
- try/recover(#argument=argument @ COMMA) | 0
--> optionalArgumentList ;;
-
- (
- expression=expression
- [: (*yynode)->argumentType = Argument::TypeValueParameter; :]
- | REF expression=expression
- [: (*yynode)->argumentType = Argument::TypeReferenceParameter; :]
- | OUT expression=expression
- [: (*yynode)->argumentType = Argument::TypeOutputParameter; :]
- )
--> argument [
- member variable argumentType: Argument::ArgumentTypeEnum;
-] ;;
-
-
-
-
--- type Parameters, type arguments, and constraints clauses form C#'s support
--- for generics and are responsible for the greater-than special casing.
-
--- TYPE PARAMETERS are used in class, interface etc. declarations to
--- determine the generic types allowed as type argument.
-
- LESS_THAN [: int currentLtLevel = m_state.ltCounter; m_state.ltCounter++; :]
- #typeParameters=typeParameters @ COMMA
- (
- typeArgumentsOrParametersEnd
- | 0 -- they can also be changed by typeParameters or TypeArgument
- )
- -- make sure we have gobbled up enough '>' characters
- -- if we are at the "top level" of nested typeParameters productions
- [: if (currentLtLevel == 0 && m_state.ltCounter != currentLtLevel ) {
- if (!yy_block_errors) {
- reportProblem(error, "The amount of closing ``>'' characters is incorrect");
- }
- return false;
- }
- :]
--> typeParameters ;;
-
- attributes=optionalAttributeSections parameterName=identifier
--> typeParameters ;;
-
-
--- TYPE ARGUMENTS are used in initializers, invocations, etc. to
--- specify the exact types for this generic class/method instance.
-
- LESS_THAN [: int currentLtLevel = m_state.ltCounter; m_state.ltCounter++; :]
- #typeArgument=type @ COMMA
- (
- typeArgumentsOrParametersEnd
- | 0 -- they can also be changed by typeParameters or TypeArgument
- )
- -- make sure we have gobbled up enough '>' characters
- -- if we are at the "top level" of nested typeArguments productions
- [: if (currentLtLevel == 0 && m_state.ltCounter != currentLtLevel ) {
- if (!yy_block_errors) {
- reportProblem(error, "The amount of closing ``>'' characters is incorrect");
- }
- return false;
- }
- :]
--> typeArguments ;;
-
-
- GREATER_THAN [: m_state.ltCounter -= 1; :] -- ">"
- | RSHIFT [: m_state.ltCounter -= 2; :] -- ">>"
--> typeArgumentsOrParametersEnd ;;
-
-
--- type Parameter CONSTRAINTS CLAUSES also belong to C#'s generics,
--- and can narrow down the allowed types given as type arguments.
-
- WHERE typeParameters=identifier COLON constraints=typeParametersConstraints
--> typeParametersConstraintsClause ;;
-
- (
- primaryOrSecondaryConstraint=primaryOrSecondaryConstraint
- ( COMMA
- ( #secondaryConstraint=secondaryConstraint
- (COMMA ( #secondaryConstraint=secondaryConstraint
- | ConstructorConstraint=ConstructorConstraint
- [: break; :] -- it's the last item: exit the "star loop"
- )
- )*
- |
- ConstructorConstraint=ConstructorConstraint
- )
- | 0
- )
- |
- #secondaryConstraint=secondaryConstraint
- (COMMA ( #secondaryConstraint=secondaryConstraint
- | ConstructorConstraint=ConstructorConstraint
- [: break; :] -- it's the last item: exit the "star loop"
- )
- )*
- |
- ConstructorConstraint=ConstructorConstraint
- )
--> typeParametersConstraints ;;
-
- (
- classTypeOrSecondaryConstraint=classType
- [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeType; :]
- | CLASS [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeClass; :]
- | STRUCT [: (*yynode)->constraintType = PrimaryOrSecondaryConstraint::TypeStruct; :]
- )
--> primaryOrSecondaryConstraint [
- member variable constraintType: PrimaryOrSecondaryConstraint::PrimaryOrSecondaryConstraintEnum;
-] ;;
-
- #interfaceTypeOrTypeParameters=typeName
--> secondaryConstraint ;;
-
- NEW LPAREN RPAREN
--> ConstructorConstraint ;;
-
-
-
-
-
--- And now for the good stuff: statements, expressions and the likes. Yay!
-
--- This is a BLOCK, a list of statements. It is used in many contexts:
--- - As the body of a method, Constructor, overloaded operator, ...
--- - As the body of an Accessor
--- - As a completely independent braced block of code inside a method,
--- starting a new scope for variable definitions
-
- LBRACE try/recover(#statement=blockStatement)* RBRACE
--> block ;;
-
--- A BLOCK STATEMENT is either an embedded statement or a variable declaration.
-
- (
- ?[: LA(2).kind == Token_COLON :]
- labeledStatement=labeledStatement
- |
- localConstantDeclarationStatement=localConstantDeclaration SEMICOLON
- |
- -- Local variable declarations, as well as expression statements, can start
- -- with class1<xxx>.bla or similar. This is only solvable with LL(k), so
- -- what's needed here is the following hack lookahead function, until
- -- backtracking or real LL(k) is implemented.
- try/rollback (
- localVariableDeclarationStatement=localVariableDeclarationStatement
- ) catch (
- statement=embeddedStatement
- )
- )
--> blockStatement ;;
-
- label=identifier COLON blockStatement
--> labeledStatement ;;
-
-
-
--- VARIABLE DECLARATIONS, initializers, etc.
-
--- The LOCAL VARIABLE DECLARATION does not allow attributes or Modifiers,
--- this is only allowed in field declarations. Both store their data with
--- the variableDeclarationData rule, using rule arguments.
-
- declaration=localVariableDeclaration SEMICOLON
--> localVariableDeclarationStatement ;;
-
- type:type (#declarator:variableDeclarator[false] @ COMMA)
- data=variableDeclarationData[
- 0 /* no attributes */, 0 /* no Modifiers */, type, declaratorSequence
- ]
--> localVariableDeclaration ;;
-
- 0
--> variableDeclarationData [
- argument member node attributes: optionalAttributeSections; -- not used in local
- argument member node modifiers: optionalModifiers; -- variable declarations
- argument member node type: type;
- argument member node #variableDeclarator: variableDeclarator;
-] ;;
-
--- The VARIABLE DECLARATOR is the part after the type specification for a
--- variable declaration. There can be more declarators, seperated by commas.
-
- variableName=identifier
- (
- -- Fixed size buffers are a C# 2.0 feature. Not in the
- -- ECMA specification, but used by both Microsoft and Mono compilers.
- ?[: fixedSizeBuffer :]
- LBRACKET arraySize=expression RBRACKET
- |
- ?[: !fixedSizeBuffer :]
- ASSIGN variableInitializer=variableInitializer
- |
- ?[: !fixedSizeBuffer :]
- 0
- )
--> variableDeclarator [
- argument temporary variable fixedSizeBuffer: bool;
-] ;;
-
-
--- The CONSTANT DECLARATION. Declares "const" values.
--- Analog to variable declarations, attributes and Modifiers are not allowed
--- in local constant declarations, only in class-wide ones.
-
- CONST type:type (#declarator:constantDeclarator @ COMMA)
- data=constantDeclarationData[
- 0 /* no attributes */, 0 /* no Modifiers */, type, declaratorSequence
- ]
--> localConstantDeclaration ;;
-
- CONST type:type (#declarator:constantDeclarator @ COMMA) SEMICOLON
- data=constantDeclarationData[
- attributes, modifiers, type, declaratorSequence
- ]
--> constantDeclaration [
- argument temporary node attributes: optionalAttributeSections;
- argument temporary node modifiers: optionalModifiers;
-] ;;
-
- 0
--> constantDeclarationData [
- argument member node attributes: optionalAttributeSections; -- not used in local
- argument member node modifiers: optionalModifiers; -- constant declarations
- argument member node type: type;
- argument member node #constantDeclarator: constantDeclarator;
-] ;;
-
- constantName=identifier ASSIGN expression=constantExpression
--> constantDeclarator ;;
-
-
--- The INITIALIZERS provide the actual values for the variable declarators.
-
- expression=expression
- | arrayInitializer=arrayInitializer
- -- unsafe grammar extension: stackalloc initializer
- | stackallocInitializer=stackallocInitializer
--> variableInitializer ;;
-
- LBRACE
- try/recover(
- #variableInitializer=variableInitializer
- ( 0 [: if (LA(2).kind == Token_RBRACE) { break; } :]
- COMMA #variableInitializer=variableInitializer
- )*
- ( COMMA | 0 )
- |
- 0
- )
- RBRACE
--> arrayInitializer ;;
-
--- unsafe grammar extension: stackalloc initializer
- STACKALLOC unmanagedType LBRACKET expression=expression RBRACKET
--> stackallocInitializer ;;
-
-
-
-
--- The (embedded) STATEMENT is a central point of the grammar,
--- even if delegating most of the work to its children.
-
- (
- block=block -- more blockStatements within {} braces
- -- selection statements:
- | ifStatement=ifStatement
- | switchStatement=switchStatement
- -- iteration statements:
- | whileStatement=whileStatement
- | doWhileStatement=doWhileStatement
- | forStatement=forStatement
- | foreachStatement=foreachStatement
- -- jump statements:
- | breakStatement=breakStatement
- | continueStatement=continueStatement
- | gotoStatement=gotoStatement
- | returnStatement=returnStatement
- | throwStatement=throwStatement
- -- other statements:
- | tryStatement=tryStatement
- | lockStatement=lockStatement
- | usingStatement=usingStatement
- | SEMICOLON -- the specification calls it emptyStatement
- |
- -- CHECKED and UNCHECKED can also be the start of an expression.
- -- So, manual checking if the second token is the start of a block.
- ?[: LA(2).kind == Token_LBRACE :]
- checkedStatement=checkedStatement
- |
- ?[: LA(2).kind == Token_LBRACE :]
- uncheckedStatement=uncheckedStatement
- |
- -- Iterators with Yield have been introduced by C# 2.0, and for C# 1.0
- -- the lexer returns the IDENTIFIER token instead of YIELD, so we don't
- -- need to do a specific version check here.
- -- YIELD is a non-keyword identifier, so it clashes with expressions:
- ?[: LA(2).kind == Token_RETURN || LA(2).kind == Token_BREAK :]
- yieldStatement=yieldStatement
- |
- -- method call, Assignment, etc.:
- expressionStatement=statementExpression SEMICOLON
- |
- -- unsafe grammar extension: "unsafe" statement
- unsafeStatement=unsafeStatement
- |
- -- unsafe grammar extension: "fixed" statement
- fixedStatement=fixedStatement
- )
--> embeddedStatement ;;
-
-
--- Simple one-rule statements:
-
- IF LPAREN condition=booleanExpression RPAREN ifBody=embeddedStatement
- (ELSE elseBody=embeddedStatement | 0)
- -- the traditional "dangling-else" conflict:
- -- kdevelop-pg generates proper code here, matching as soon as possible.
--> ifStatement ;;
-
- WHILE LPAREN condition=booleanExpression RPAREN body=embeddedStatement
--> whileStatement ;;
-
- DO body=embeddedStatement
- WHILE LPAREN condition=booleanExpression RPAREN SEMICOLON
--> doWhileStatement ;;
-
- FOREACH LPAREN
- variableType=type variableName=identifier IN collection=expression
- RPAREN
- body=embeddedStatement
--> foreachStatement ;;
-
- BREAK SEMICOLON
--> breakStatement ;;
-
- CONTINUE SEMICOLON
--> continueStatement ;;
-
- GOTO
- ( label=identifier
- [: (*yynode)->gotoType = GotoStatement::TypeLabeledStatement; :]
- | CASE constantExpression=constantExpression
- [: (*yynode)->gotoType = GotoStatement::TypeSwitchCase; :]
- | DEFAULT
- [: (*yynode)->gotoType = GotoStatement::TypeSwitchDefault; :]
- )
- SEMICOLON
--> gotoStatement [
- member variable gotoType: GotoStatement::GotoStatementEnum;
-] ;;
-
- RETURN (returnExpression=expression | 0) SEMICOLON
--> returnStatement ;;
-
- THROW (exception=expression | 0) SEMICOLON
--> throwStatement ;;
-
- CHECKED body=block
--> checkedStatement ;;
-
- UNCHECKED body=block
--> uncheckedStatement ;;
-
- LOCK LPAREN lockExpression=expression RPAREN body=embeddedStatement
--> lockStatement ;;
-
- YIELD
- ( RETURN returnExpression=expression
- [: (*yynode)->yieldType = YieldStatement::TypeYieldReturn; :]
- | BREAK
- [: (*yynode)->yieldType = YieldStatement::TypeYieldBreak; :]
- )
- SEMICOLON
--> yieldStatement [
- member variable yieldType: YieldStatement::YieldStatementEnum;
-] ;;
-
-
--- unsafe grammar extension: "unsafe" and "fixed" statements
-
- UNSAFE body=block
--> unsafeStatement ;;
-
- FIXED LPAREN
- pointerType=pointerType
- (fixedPointerDeclarator=fixedPointerDeclarator @ COMMA)
- RPAREN
- body=embeddedStatement
--> fixedStatement ;;
-
- pointerName=identifier ASSIGN initializer=expression
--> fixedPointerDeclarator ;;
-
-
--- The SWITCH STATEMENT, consisting of a header and multiple
--- "case x:" or "default:" Switch statement groups.
-
- SWITCH LPAREN switchExpression=expression RPAREN
- LBRACE try/recover(#switchSection=switchSection)* RBRACE
--> switchStatement ;;
-
- (#label=switchLabel)+
- ( 0 [: if (yytoken == Token_DEFAULT && LA(2).kind != Token_LPAREN)
- { break; } // don't give in to defaultValueExpression
- :]
- #statement=blockStatement
- )+
--> switchSection ;;
-
- ( CASE caseExpression=constantExpression
- [: (*yynode)->branchType = SwitchLabel::CaseBranch; :]
- | DEFAULT
- [: (*yynode)->branchType = SwitchLabel::DefaultBranch; :]
- ) COLON
--> switchLabel [
- member variable branchType: SwitchLabel::BranchTypeEnum;
-] ;;
-
-
--- The TRY STATEMENT, also known as try/catch/finally block.
-
- TRY tryBody=block
- ( catchClauses=catchClauses (FINALLY finallyBody=block | 0)
- | FINALLY finallyBody=block
- )
--> tryStatement ;;
-
- (
- ?[: LA(2).kind != Token_LPAREN :]
- generalCatchClause=generalCatchClause
- |
- ( -- also let general catch clauses get through:
- 0 [: if (LA(2).kind != Token_LPAREN) { break; } :]
- #specificCatchClause=specificCatchClause
- )+
- ( generalCatchClause=generalCatchClause | 0 )
- )
--> catchClauses ;;
-
- CATCH LPAREN
- exceptionType=classType (exceptionName=identifier | 0)
- RPAREN
- body=block
--> specificCatchClause ;;
-
- CATCH body=block
--> generalCatchClause ;;
-
-
--- The USING STATEMENT, acquiring and afterwards disposing a System.Disposable.
-
- USING LPAREN resourceAcquisition=resourceAcquisition RPAREN
- body=embeddedStatement
--> usingStatement ;;
-
--- Hm, we know that LL(k) conflict from somewhere, don't we?
--- Right, it's the same one as in blockStatement and the upcoming forControl.
-
- try/rollback( localVariableDeclaration=localVariableDeclaration )
- catch( expression=expression )
--> resourceAcquisition ;;
-
-
--- The FOR STATEMENT, including its problematic child forControl.
-
- FOR LPAREN forControl=forControl RPAREN forBody=embeddedStatement
--> forStatement ;;
-
--- The FOR CONTROL is the three statements inside the for(...) parentheses,
--- or the alternative foreach specifier. It has the same problematic conflict
--- between localVariableDeclaration and expression that blockStatement also
--- has and which is only solvable with LL(k). Until backtracking or real LL(k)
--- is implemented, we have to workaround with a lookahead hack function.
-
- (
- try/rollback (
- localVariableDeclaration=localVariableDeclaration -- "int i = 0"
- ) catch (
- #statementExpression=statementExpression @ COMMA
- )
- |
- 0
- )
- SEMICOLON
- (forCondition=booleanExpression | 0) SEMICOLON -- "i < size;"
- (#forIterator=statementExpression @ COMMA | 0) -- "i++"
--> forControl ;;
-
-
-
-
--- EXPRESSIONS
--- Note that most of these expressions follow the pattern
--- thisLevelExpression :
--- nextHigherPrecedenceExpression @ OPERATOR
---
--- The operators in C# have the following precedences:
--- lowest (14) Assignment = *= /= %= += -= <<= >>= &= ^= |=
--- (13) Conditional ?:
--- (12) Conditional OR ||
--- (11) Conditional AND &&
--- (10) Logical OR |
--- ( 9) Logical XOR ^
--- ( 8) Logical AND &
--- ( 7) Equality == !=
--- ( 6) Relational and type-testing < > <= >= is as
--- ( 5) Shift << >>
--- ( 4) Additive +(binary) -(binary)
--- ( 3) Multiplicative * / %
--- ( 2) Unary +(Unary) -(Unary) ! ~ ++x --x (type)x
--- highest ( 1) Primary x.y f(x) a[x] x++ x-- new
-
-
--- Both BOOLEAN and CONSTANT EXPRESSIONS ought to return a certain kind of
--- value, but it's not possible for any parser to check those restrictions.
-
- expression=expression
--> constantExpression ;;
-
- expression=expression
--> booleanExpression ;;
-
--- A STATEMENT EXPRESSION may not contain certain subsets of expression,
--- but it's just not feasible for LL(k) parsers to filter them out.
-
- expression=expression
--> statementExpression ;;
-
-
--- So this is the actual EXPRESSION, also known as Assignment expression.
-
- conditionalExpression=conditionalExpression
- (
- ( ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpAssign; :]
- | PLUS_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpPlusAssign; :]
- | MINUS_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpMinusAssign; :]
- | STAR_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpStarAssign; :]
- | SLASH_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpSlashAssign; :]
- | REMAINDER_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpRemainderAssign; :]
- | BIT_AND_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpBitAndAssign; :]
- | BIT_OR_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpBitOrAssign; :]
- | BIT_XOR_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpBitXorAssign; :]
- | LSHIFT_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpLShiftAssign; :]
- | RSHIFT_ASSIGN
- [: (*yynode)->assignmentOperator = Expression::OpRShiftAssign; :]
- )
- assignmentExpression=expression
- |
- 0 [: (*yynode)->assignmentOperator = Expression::NoAssignment; :]
- )
--> expression [
- member variable assignmentOperator: Expression::AssignmentOperatorEnum;
-] ;;
-
-
- nullCoalescingExpression=nullCoalescingExpression
- (
- QUESTION ifExpression=expression COLON elseExpression=expression
- |
- -- this rather hackish solution prevents false errors for expressions
- -- like "a is SomeType ? ifExp : elseExp", where NullableType steals
- -- the question mark from conditionalExpression.
- ?[: (compatibilityMode() >= CSharp20Compatibility)
- && isNullableType(lastRelationalExpressionRestType((*yynode)->nullCoalescingExpression)) :]
- 0 [: unsetNullableType(lastRelationalExpressionRestType((*yynode)->nullCoalescingExpression)); :]
- ifExpression=expression COLON elseExpression=expression
- |
- 0
- )
--> conditionalExpression ;;
-
--- The NULL COALESCING EXPRESSION is new in C# 2.0 and provides fallback values
--- for nullable variables. If a is non-null, (a ?? b) returns a,
--- but if a is null, (a ?? b) returns b.
--- Version checking is already done by the lexer and not needed here.
-
- #expression=logicalOrExpression @ QUESTIONQUESTION
--> nullCoalescingExpression ;;
-
- #expression=logicalAndExpression @ LOG_OR
--> logicalOrExpression ;;
-
- #expression=bitOrExpression @ LOG_AND
--> logicalAndExpression ;;
-
- #expression=bitXorExpression @ BIT_OR
--> bitOrExpression ;;
-
- #expression=bitAndExpression @ BIT_XOR
--> bitXorExpression ;;
-
- #expression=equalityExpression @ BIT_AND
--> bitAndExpression ;;
-
- expression=relationalExpression
- (#additionalExpression=equalityExpressionRest)*
--> equalityExpression ;;
-
- ( EQUAL [: (*yynode)->equalityOperator = EqualityExpressionRest::OpEqual; :]
- | NOT_EQUAL [: (*yynode)->equalityOperator = EqualityExpressionRest::OpNotEqual; :]
- )
- expression=relationalExpression
--> equalityExpressionRest [
- member variable equalityOperator: EqualityExpressionRest::EqualityOperatorEnum;
-] ;;
-
- expression=shiftExpression
- (#additionalExpression=relationalExpressionRest)*
--> relationalExpression ;;
-
- (
- ( LESS_THAN [: (*yynode)->relationalOperator = RelationalExpressionRest::OpLessThan; :]
- | GREATER_THAN [: (*yynode)->relationalOperator = RelationalExpressionRest::OpGreaterThan; :]
- | LESS_EQUAL [: (*yynode)->relationalOperator = RelationalExpressionRest::OpLessEqual; :]
- | GREATER_EQUAL [: (*yynode)->relationalOperator = RelationalExpressionRest::OpGreaterEqual; :]
- )
- expression=shiftExpression
- |
- ( IS [: (*yynode)->relationalOperator = RelationalExpressionRest::OpIs; :]
- | AS [: (*yynode)->relationalOperator = RelationalExpressionRest::OpAs; :]
- )
- type=type
- )
--> relationalExpressionRest [
- member variable relationalOperator: RelationalExpressionRest::RelationalOperatorEnum;
-] ;;
-
- expression=additiveExpression
- (#additionalExpression=shiftExpressionRest)*
--> shiftExpression ;;
-
- ( LSHIFT [: (*yynode)->shiftOperator = ShiftExpressionRest::OpLShift; :]
- | RSHIFT [: (*yynode)->shiftOperator = ShiftExpressionRest::OpRShift; :]
- )
- expression=additiveExpression
--> shiftExpressionRest [
- member variable shiftOperator: ShiftExpressionRest::ShiftOperatorEnum;
-] ;;
-
- expression=multiplicativeExpression
- (#additionalExpression=additiveExpressionRest)*
--> additiveExpression ;;
-
- ( PLUS [: (*yynode)->additiveOperator = AdditiveExpressionRest::OpPlus; :]
- | MINUS [: (*yynode)->additiveOperator = AdditiveExpressionRest::OpMinus; :]
- )
- expression=multiplicativeExpression
--> additiveExpressionRest [
- member variable additiveOperator: AdditiveExpressionRest::AdditiveOperatorEnum;
-] ;;
-
- expression=unaryExpression
- (#additionalExpression=multiplicativeExpressionRest)*
--> multiplicativeExpression ;;
-
- ( STAR [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpStar; :]
- | SLASH [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpSlash; :]
- | REMAINDER [: (*yynode)->multiplicativeOperator = MultiplicativeExpressionRest::OpRemainder; :]
- )
- expression=unaryExpression
--> multiplicativeExpressionRest [
- member variable multiplicativeOperator: MultiplicativeExpressionRest::MultiplicativeOperatorEnum;
-] ;;
-
-
-
--- So, up till now this was the easy stuff. Here comes another sincere
--- conflict in the grammar that can only be solved with LL(k).
--- The conflict in this rule is the ambiguity between type casts (which
--- can be arbitrary class names within parentheses) and primaryExpressions,
--- which can also look that way from an LL(1) perspective.
--- Until real LL(k) or backtracking is implemented in kdev-pg, this problem
--- is solved with another lookahead hack function.
-
- (
- INCREMENT unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeIncrementedExpression; :]
- | DECREMENT unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeDecrementedExpression; :]
- | MINUS unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeUnaryMinusExpression; :]
- | PLUS unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeUnaryPlusExpression; :]
- | TILDE unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeBitwiseNotExpression; :]
- | BANG unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeLogicalNotExpression; :]
- |
- try/rollback (
- castExpression=castExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeCastExpression; :]
- )
- catch (
- primaryExpression=primaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeprimaryExpression; :]
- )
- |
- -- unsafe grammar extension: pointer indirection expression
- STAR unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypePointerIndirectionExpression; :]
- |
- -- unsafe grammar extension: addressof expression
- BIT_AND unaryExpression=unaryExpression
- [: (*yynode)->ruleType = UnaryExpression::TypeAddressofExpression; :]
- )
--> unaryExpression [
- member variable ruleType: UnaryExpression::UnaryExpressionEnum;
-] ;;
-
- LPAREN type=type RPAREN castedExpression=unaryExpression
--> castExpression ;;
-
-
--- PRIMARY EXPRESSIONs: qualified names, array expressions,
--- method invocation, post increment/decrement, etc.
-
- primaryAtom=primaryAtom (#primarySuffix=primarySuffix)*
--> primaryExpression ;;
-
- (
- -- this is the part of memberAccess that's not in primaryAtom
- DOT memberName=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
- [: (*yynode)->suffixType = PrimarySuffix::TypeMemberAccess; :]
- |
- -- the suffix part of invocationExpression
- LPAREN arguments=optionalArgumentList RPAREN
- [: (*yynode)->suffixType = PrimarySuffix::TypeInvocation; :]
- |
- -- elementAccess (also known as array Access)
- LBRACKET (#expression=expression @ COMMA) RBRACKET
- [: (*yynode)->suffixType = PrimarySuffix::TypeElementAccess; :]
- |
- INCREMENT
- [: (*yynode)->suffixType = PrimarySuffix::TypeIncrement; :]
- |
- DECREMENT
- [: (*yynode)->suffixType = PrimarySuffix::TypeDecrement; :]
- |
- -- unsafe grammar extension: pointer Access
- ARROW_RIGHT memberName=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
- [: (*yynode)->suffixType = PrimarySuffix::TypePointerMemberAccess; :]
- )
--> primarySuffix [
- member variable suffixType: PrimarySuffix::PrimarySuffixEnum;
-] ;;
-
-
--- PRIMARY ATOM: the basic element of a Primary expression,
--- and expressions in general
-
- (
- literal=literal
- [: (*yynode)->ruleType = PrimaryAtom::TypeLiteral; :]
- |
- LPAREN expression=expression RPAREN
- [: (*yynode)->ruleType = PrimaryAtom::TypeParenthesizedExpression; :]
- |
- simpleNameOrMemberAccess=simpleNameOrMemberAccess
- [: (*yynode)->ruleType = PrimaryAtom::TypeMemberAccess; :]
- |
- THIS
- [: (*yynode)->ruleType = PrimaryAtom::TypeThisAccess; :]
- |
- baseAccess=baseAccess
- [: (*yynode)->ruleType = PrimaryAtom::TypeBaseAccess; :]
- |
- newExpression=newExpression
- [: (*yynode)->ruleType = PrimaryAtom::TypeNewExpression; :]
- |
- TypeofExpression=TypeofExpression
- [: (*yynode)->ruleType = PrimaryAtom::TypeTypeofExpression; :]
- |
- CHECKED LPAREN expression=expression RPAREN
- [: (*yynode)->ruleType = PrimaryAtom::TypeCheckedExpression; :]
- |
- UNCHECKED LPAREN expression=expression RPAREN
- [: (*yynode)->ruleType = PrimaryAtom::TypeUncheckedExpression; :]
- |
- DEFAULT LPAREN type=type RPAREN
- [: (*yynode)->ruleType = PrimaryAtom::TypeDefaultValueExpression; :]
- |
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- anonymousMethodExpression=anonymousMethodExpression
- [: (*yynode)->ruleType = PrimaryAtom::TypeAnonymousMethodExpression; :]
- |
- -- unsafe grammar extension: sizeof(type)
- SIZEOF LPAREN unmanagedType=unmanagedType RPAREN
- [: (*yynode)->ruleType = PrimaryAtom::TypeSizeofExpression; :]
- )
--> primaryAtom [
- member variable ruleType: PrimaryAtom::PrimaryAtomEnum;
-] ;;
-
-
--- Here come the more complex parts of primaryAtom that have been split out.
-
--- This rule covers two rules from the specification, the SIMPLE NAME and
--- most of MEMBER ACCESS.
-
- (
- ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
- | 0
- )
- memberName=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
- |
- predefinedType=predefinedType DOT memberName=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
- )
--> simpleNameOrMemberAccess ;;
-
- (
- BOOL [: (*yynode)->type = PredefinedType::TypeBool; :]
- | BYTE [: (*yynode)->type = PredefinedType::TypeByte; :]
- | CHAR [: (*yynode)->type = PredefinedType::TypeChar; :]
- | DECIMAL [: (*yynode)->type = PredefinedType::TypeDecimal; :]
- | DOUBLE [: (*yynode)->type = PredefinedType::TypeDouble; :]
- | FLOAT [: (*yynode)->type = PredefinedType::TypeFloat; :]
- | INT [: (*yynode)->type = PredefinedType::TypeInt; :]
- | LONG [: (*yynode)->type = PredefinedType::TypeLong; :]
- | OBJECT [: (*yynode)->type = PredefinedType::TypeObject; :]
- | SBYTE [: (*yynode)->type = PredefinedType::TypeSbyte; :]
- | SHORT [: (*yynode)->type = PredefinedType::TypeShort; :]
- | STRING [: (*yynode)->type = PredefinedType::TypeString; :]
- | UINT [: (*yynode)->type = PredefinedType::TypeUint; :]
- | ULONG [: (*yynode)->type = PredefinedType::TypeUlong; :]
- | USHORT [: (*yynode)->type = PredefinedType::TypeUshort; :]
- )
--> predefinedType [
- member variable type: PredefinedType::PredefinedTypeEnum;
-] ;;
-
-
- BASE
- ( DOT identifier=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
- [: (*yynode)->accessType = BaseAccess::TypeBaseMemberAccess; :]
- |
- LBRACKET (#expression=expression @ COMMA) RBRACKET
- [: (*yynode)->accessType = BaseAccess::TypeBaseIndexerAccess; :]
- )
--> baseAccess [
- member variable accessType: BaseAccess::BaseAccessEnum;
-] ;;
-
-
- DELEGATE (anonymousMethodSignature=anonymousMethodSignature | 0)
- body=block
--> anonymousMethodExpression ;;
-
- LPAREN
- ( (#anonymousMethodParameter=anonymousMethodParameter @ COMMA) | 0 )
- RPAREN
--> anonymousMethodSignature ;;
-
- modifier=optionalParameterModifier type=type variableName=identifier
--> anonymousMethodParameter ;;
-
-
--- NEW EXPRESSION is actually three rules in one: arrayCreationExpression,
--- objectCreationExpression and delegateCreationExpression.
--- But as they all contain a "type" rule in the same place, it's not
--- a good idea to try to tell them apart. Also, object creation and
--- delegate creation can derive the exact same token sequence.
-
- NEW type:type
- ( arrayCreationExpression=arrayCreationExpressionRest[type]
- | objectOrDelegateCreationExpression=objectOrDelegateCreationExpressionRest[type]
- )
--> newExpression ;;
-
--- The rest of object/delegate or array creation expressions.
-
- LPAREN argumentListOrExpression=optionalArgumentList RPAREN
--> objectOrDelegateCreationExpressionRest [
- argument member node type: type;
-] ;;
-
- (
- arrayInitializer=arrayInitializer
- |
- LBRACKET (#expression=expression @ COMMA) RBRACKET
- ( 0 [: if (LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
- { break; }
- :] -- avoids swallowing the LBRACKETs in
- -- primarySuffix's element Access part.
- #rankSpecifier=rankSpecifier
- )*
- (arrayInitializer=arrayInitializer | 0)
- )
--> arrayCreationExpressionRest [
- argument member node type: type;
-] ;;
-
-
--- The TYPEOF EXPRESSION is nasty, because it either needs LL(k) lookahead
--- or a very ugly duplication of the type system. And when I say Very_ ugly,
--- I mean it. I tried it, and decided to go with the cleaner lookahead hack.
-
- TYPEOF LPAREN
- (
- ?[: LA(2).kind == Token_RPAREN :]
- VOID
- [: (*yynode)->typeofType = TypeofExpression::TypeVoid; :]
- |
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- try/rollback(
- unboundTypeName=unboundTypeName
- [: (*yynode)->typeofType = TypeofExpression::TypeUnboundTypeName; :]
- )
- catch(
- otherType=type
- [: (*yynode)->typeofType = TypeofExpression::TypeType; :]
- )
- |
- otherType=type
- [: (*yynode)->typeofType = TypeofExpression::TypeType; :]
- )
- RPAREN
--> TypeofExpression [
- member variable typeofType: TypeofExpression::TypeofExpressionEnum;
-] ;;
-
- ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
- | 0
- )
- #namePart=unboundTypeNamePart @ DOT
--> unboundTypeName ;;
-
- identifier=identifier
- genericDimensionSpecifier=genericDimensionSpecifier
--> unboundTypeNamePart ;;
-
- LESS_THAN [: (*yynode)->commaCount = 0; :]
- ( COMMA [: (*yynode)->commaCount++; :] )*
- GREATER_THAN
--> genericDimensionSpecifier [
- member variable commaCount: int;
-] ;;
-
-
-
-
-
---
--- All kinds of rules for types here.
---
-
--- The RETURN TYPE can only be used as return value, not in a declaration.
-
- (
- ?[: LA(2).kind != Token_STAR :] -- "void*" is a regular type in unsafe code
- VOID [: (*yynode)->type = ReturnType::TypeVoid; :]
- |
- regularType=type [: (*yynode)->type = ReturnType::TypeRegular; :]
- )
--> returnType [
- member variable type: ReturnType::ReturnTypeEnum;
-] ;;
-
--- The regular TYPE recognizes the same set of tokens as the one in the C#
--- specification, but had to be refactored quite a bit. Looks different here.
-
- unmanagedType=unmanagedType -- it's too cumbersome to track "unsafe",
- -- | managedType=managedType -- so have it on by default
--> type ;;
-
- -- unsafe grammar extension: unmanaged type (includes all of the managed one)
- ( regularType=nonArrayType
- [: (*yynode)->type = PointerType::TypeRegular; :]
- | VOID STAR
- [: (*yynode)->type = PointerType::TypeVoidStar; :]
- )
- ( 0 [: if (yytoken == Token_LBRACKET &&
- LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
- { break; }
- :] -- prevents rankSpecifier from swallowing the LBRACKETs in
- -- newExpression/arrayCreationExpression.
- #unmanagedTypeSuffix=unmanagedTypeSuffix
- )*
--> unmanagedType [
- member variable type: PointerType::PointerTypeEnum;
-] ;;
-
- -- unsafe grammar extension: pointer type
- ( regularType=nonArrayType
- #unmanagedTypeSuffix=unmanagedTypeSuffix
- [: (*yynode)->type = PointerType::TypeRegular; :]
- | VOID STAR
- [: (*yynode)->type = PointerType::TypeVoidStar; :]
- )
- ( 0 [: if (yytoken == Token_LBRACKET &&
- LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
- { break; }
- :] -- prevents rankSpecifier from swallowing the LBRACKETs in
- -- newExpression/arrayCreationExpression.
- #unmanagedTypeSuffix=unmanagedTypeSuffix
- )*
--> pointerType [
- member variable type: PointerType::PointerTypeEnum;
- member variable starCount: int;
-] ;;
-
- STAR [: (*yynode)->type = UnmanagedTypeSuffix::TypeStar; :]
- | rankSpecifier=rankSpecifier [: (*yynode)->type = UnmanagedTypeSuffix::TypeRankSpecifier; :]
--> unmanagedTypeSuffix [
- member variable type: UnmanagedTypeSuffix::SuffixType;
-] ;;
-
- nonArrayType=nonArrayType
- ( 0 [: if (LA(2).kind != Token_COMMA && LA(2).kind != Token_RBRACKET)
- { break; }
- :] -- avoids swallowing the LBRACKETs in
- -- newExpression/arrayCreationExpression.
- #rankSpecifier=rankSpecifier
- )*
--> managedType ;;
-
- nonArrayType=nonArrayType (#rankSpecifier=rankSpecifier)+
--> arrayType ;;
-
- LBRACKET [: (*yynode)->dimensionSeperatorCount = 0; :]
- ( COMMA [: (*yynode)->dimensionSeperatorCount++; :] )*
- RBRACKET
--> rankSpecifier [
- member variable dimensionSeperatorCount: int;
-] ;;
-
- builtinClassType=builtinClassType
- | optionallyNullableType=optionallyNullableType
--> nonArrayType ;;
-
- typeName=typeName
- | builtinClassType=builtinClassType
--> classType ;;
-
- OBJECT [: (*yynode)->type = BuiltinClassType::TypeObject; :]
- | STRING [: (*yynode)->type = BuiltinClassType::TypeString; :]
--> builtinClassType [
- member variable type: BuiltinClassType::BuiltinClassTypeEnum;
-] ;;
-
--- NULLABLE TYPES are new in C# 2.0 and need to be expressed a little bit
--- differently than in LALR grammars like in the C# specification.
-
- nonNullableType=nonNullableType
- ( ?[: compatibilityMode() >= CSharp20Compatibility :]
- QUESTION [: (*yynode)->nullable = true; :]
- |
- 0 [: (*yynode)->nullable = false; :]
- )
--> optionallyNullableType [
- member variable nullable: bool;
-] ;;
-
- typeName=typeName
- | simpleType=simpleType
--> nonNullableType ;;
-
-
--- Now for SIMPLE TYPES, this is easier ;)
-
- (
- numericType=numericType
- [: (*yynode)->type = SimpleType::TypeNumeric; :]
- | BOOL
- [: (*yynode)->type = SimpleType::TypeBool; :]
- )
--> simpleType [
- member variable type: SimpleType::SimpleTypeEnum;
-] ;;
-
-
--- NUMERIC TYPES include INTEGRAL TYPES, FLOATING POINT TYPES, and DECIMAL.
-
- (
- intType=integralType
- [: (*yynode)->type = NumericType::TypeIntegral; :]
- | floatType=floatingPointType
- [: (*yynode)->type = NumericType::TypeFloatingPoint; :]
- | DECIMAL
- [: (*yynode)->type = NumericType::TypeDecimal; :]
- )
--> numericType [
- member variable type: NumericType::NumericTypeEnum;
-] ;;
-
- (
- SBYTE [: (*yynode)->type = IntegralTypes::TypeSbyte; :]
- | BYTE [: (*yynode)->type = IntegralTypes::TypeByte; :]
- | SHORT [: (*yynode)->type = IntegralTypes::TypeShort; :]
- | USHORT [: (*yynode)->type = IntegralTypes::TypeUshort; :]
- | INT [: (*yynode)->type = IntegralTypes::TypeInt; :]
- | UINT [: (*yynode)->type = IntegralTypes::TypeUint; :]
- | LONG [: (*yynode)->type = IntegralTypes::TypeLong; :]
- | ULONG [: (*yynode)->type = IntegralTypes::TypeUlong; :]
- | CHAR [: (*yynode)->type = IntegralTypes::TypeChar; :]
- )
--> integralType [
- member variable type: IntegralTypes::IntegralTypeEnum;
-] ;;
-
- (
- FLOAT [: (*yynode)->type = FloatingPointType::TypeFloat; :]
- | DOUBLE [: (*yynode)->type = FloatingPointType::TypeDouble; :]
- )
--> floatingPointType [
- member variable type: FloatingPointType::FloatingPointTypeEnum;
-] ;;
-
-
--- TYPE NAMES and NAMESPACE NAMES are the same thing,
--- essentially qualified identifiers with optional type arguments.
-
- namespaceName=namespaceOrTypeName
--> namespaceName ;;
-
- typeName=namespaceOrTypeName
--> typeName ;;
-
- ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
- | 0
- )
- #namePart=namespaceOrTypeNamePart @ DOT
--> namespaceOrTypeName ;;
-
- identifier=identifier
- try/rollback(
- ?[: compatibilityMode() >= CSharp20Compatibility :]
- typeArguments=typeArguments
- | 0
- ) catch(0)
--> namespaceOrTypeNamePart ;;
-
- typeName=namespaceOrTypeNameSafe
--> typeNameSafe ;;
-
- ( ?[: LA(2).kind == Token_SCOPE :] qualifiedAliasLabel=identifier SCOPE
- | 0
- )
- #namePart=namespaceOrTypeNamePart
- ( 0 [: if (LA(2).kind != Token_IDENTIFIER) break; :] -- exit the "star loop"
- DOT #namePart=namespaceOrTypeNamePart
- )*
--> namespaceOrTypeNameSafe ;;
-
-
--- QUALIFIED IDENTIFIERs are either qualified ones or raw identifiers.
--- In the C# grammar, they're only used as namespace Names.
-
- #name=identifier @ DOT
--> qualifiedIdentifier ;;
-
-
-
-
---
--- MODIFIERS, KEYWORDS, LITERALS, and the IDENTIFIER wrapper
---
-
- (
- REF [: (*yynode)->parameterType = Parameter::ReferenceParameter; :]
- | OUT [: (*yynode)->parameterType = Parameter::OutputParameter; :]
- | 0 [: (*yynode)->parameterType = Parameter::ValueParameter; :]
- )
--> optionalParameterModifier [
- member variable parameterType: Parameter::ParameterTypeEnum;
-] ;;
-
--- These are all the Modifiers that can occur in front of type and type member
--- declarations. They are not valid in every combination, this has to be
--- checked seperately after parsing this rule.
-
- (
- PUBLIC [: (*yynode)->accessPolicy = AccessPolicy::AccessPublic; :]
- | PRIVATE [: (*yynode)->accessPolicy = AccessPolicy::AccessPrivate; :]
- | PROTECTED
- [: if ((*yynode)->accessPolicy == AccessPolicy::AccessInternal)
- (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal;
- else
- (*yynode)->accessPolicy = AccessPolicy::AccessProtected;
- :]
- | INTERNAL
- [: if ((*yynode)->accessPolicy == AccessPolicy::AccessProtected)
- (*yynode)->accessPolicy = AccessPolicy::AccessProtectedInternal;
- else
- (*yynode)->accessPolicy = AccessPolicy::AccessInternal;
- :]
- | NEW [: (*yynode)->modifiers |= Modifiers::ModNew; :]
- | ABSTRACT [: (*yynode)->modifiers |= Modifiers::ModAbstract; :]
- | SEALED [: (*yynode)->modifiers |= Modifiers::ModSealed; :]
- | STATIC [: (*yynode)->modifiers |= Modifiers::ModStatic; :]
- | READONLY [: (*yynode)->modifiers |= Modifiers::ModReadonly; :]
- | VOLATILE [: (*yynode)->modifiers |= Modifiers::ModVolatile; :]
- | VIRTUAL [: (*yynode)->modifiers |= Modifiers::ModVirtual; :]
- | OVERRIDE [: (*yynode)->modifiers |= Modifiers::ModOverride; :]
- | EXTERN [: (*yynode)->modifiers |= Modifiers::ModExtern; :]
- -- unsafe grammar extension: "unsafe" keyword
- | UNSAFE [: (*yynode)->modifiers |= Modifiers::ModUnsafe; :]
- -- unspecified unsafe Modifier, but used by MS and Mono, so accept it here as well:
- | ?[: compatibilityMode() >= CSharp20Compatibility :]
- FIXED [: (*yynode)->modifiers |= Modifiers::ModFixed; :]
- )*
--> optionalModifiers [
- member variable modifiers: unsigned int; -- using the ModifierEnum values
- member variable accessPolicy: AccessPolicy::AccessPolicyEnum;
-] ;;
-
- (
- keyword=ABSTRACT | keyword=AS | keyword=BASE | keyword=BOOL
- | keyword=BREAK | keyword=BYTE | keyword=CASE | keyword=CATCH | keyword=CHAR
- | keyword=CHECKED | keyword=CLASS | keyword=CONST | keyword=CONTINUE
- | keyword=DECIMAL | keyword=DEFAULT | keyword=DELEGATE | keyword=DO
- | keyword=DOUBLE | keyword=ELSE | keyword=ENUM | keyword=EVENT
- | keyword=EXPLICIT | keyword=EXTERN | keyword=FINALLY | keyword=FIXED
- | keyword=FLOAT | keyword=FOREACH | keyword=FOR | keyword=GOTO | keyword=IF
- | keyword=IMPLICIT | keyword=IN | keyword=INT | keyword=INTERFACE
- | keyword=INTERNAL | keyword=IS | keyword=LOCK | keyword=LONG
- | keyword=NAMESPACE | keyword=NEW | keyword=OBJECT | keyword=OPERATOR
- | keyword=OUT | keyword=OVERRIDE | keyword=PARAMS | keyword=PRIVATE
- | keyword=PROTECTED | keyword=PUBLIC | keyword=READONLY | keyword=REF
- | keyword=RETURN | keyword=SBYTE | keyword=SEALED | keyword=SHORT
- | keyword=SIZEOF | keyword=STACKALLOC | keyword=STATIC | keyword=STRING
- | keyword=STRUCT | keyword=SWITCH | keyword=THIS | keyword=THROW | keyword=TRY
- | keyword=TYPEOF | keyword=UINT | keyword=ULONG | keyword=UNCHECKED
- | keyword=UNSAFE | keyword=USHORT | keyword=USING | keyword=VIRTUAL
- | keyword=VOID | keyword=VOLATILE | keyword=WHILE
- )
--> keyword ;;
-
- (
- ident=IDENTIFIER
- | ident=ADD
- | ident=ALIAS
- | ident=GET
- | ident=GLOBAL
- | ident=PARTIAL
- | ident=REMOVE
- | ident=SET
- | ident=VALUE
- | ident=WHERE
- | ident=YIELD
- | ident=ASSEMBLY
- )
--> identifier ;;
-
- (
- TRUE [: (*yynode)->literalType = Literal::TypeTrue; :]
- | FALSE [: (*yynode)->literalType = Literal::TypeFalse; :]
- | NULL [: (*yynode)->literalType = Literal::TypeNull; :]
- |
- integerLiteral=INTEGER_LITERAL
- [: (*yynode)->literalType = Literal::TypeInteger; :]
- |
- floatingPointLiteral=REAL_LITERAL
- [: (*yynode)->literalType = Literal::TypeReal; :]
- |
- characterLiteral=CHARACTER_LITERAL
- [: (*yynode)->literalType = Literal::TypeCharacter; :]
- |
- stringLiteral=STRING_LITERAL
- [: (*yynode)->literalType = Literal::TypeString; :]
- )
--> literal [
- member variable literalType: Literal::LiteralTypeEnum;
-] ;;
-
-
-
-
-
-
------------------------------------------------------------------
--- Code segments copied to the implementation (.cpp) file.
--- If existent, kdevelop-pg's current syntax requires this block
--- to occur at the end of the file.
------------------------------------------------------------------
-
-[:
-#include "csharplexer.h"
-
-
-namespace CSharp
-{
-
-void Parser::tokenize( ParseSession* session )
-{
- Lexer lexer( this, session );
-
- int kind = Parser::Token_EOF;
- do
- {
- kind = lexer.yylex();
- //std::Cerr << lexer.YYText() << std::Endl; //" "; // debug output
-
- if ( !kind ) // when the lexer returns 0, the end of file is reached
- kind = Parser::Token_EOF;
-
- Parser::Token &t = this->tokenStream->next();
- t.kind = kind;
- t.begin = lexer.tokenBegin();
- t.end = lexer.tokenEnd();
- }
- while (kind != Parser::Token_EOF);
-
- this->yylex(); // produce the look ahead token
-}
-
-
-Parser::CSharpCompatibilityMode Parser::compatibilityMode()
-{
- return m_compatibilityMode;
-}
-void Parser::setCompatibilityMode( Parser::CSharpCompatibilityMode Mode )
-{
- m_compatibilityMode = Mode;
-}
-
-void Parser::ppDefineSymbol( QString symbolName )
-{
- m_ppDefinedSymbols.insert( symbolName );
-}
-
-void Parser::ppUndefineSymbol( QString symbolName )
-{
- m_ppDefinedSymbols.remove( symbolName );
-}
-
-bool Parser::ppIsSymbolDefined( QString symbolName )
-{
- return (m_ppDefinedSymbols.find(symbolName) != m_ppDefinedSymbols.end());
-}
-
-
-// Rather hackish solution for recognizing expressions like
-// "a is SomeType ? ifExp : elseExp", see conditionalExpression.
-// Needs three methods to fix parsing for about 0.2% of all C# source files.
-
-bool Parser::isNullableType( TypeAst *type )
-{
- if ( !type )
- return false;
- else if ( !type->unmanagedType )
- return false;
- else if ( !type->unmanagedType->regularType || type->unmanagedType->unmanagedTypeSuffixSequence )
- return false;
- else if ( !type->unmanagedType->regularType->optionallyNullableType )
- return false;
- else if ( type->unmanagedType->regularType->optionallyNullableType->nullable == false )
- return false;
- else // if ( type->optionallyNullableType->nullable == true )
- return true;
-}
-
-// This method is only to be called after isNullableType(Type) returns true,
-// and therefore expects all the appropriate members not to be 0.
-void Parser::unsetNullableType( TypeAst *type )
-{
- type->unmanagedType->regularType->optionallyNullableType->nullable = false;
-}
-
-// This method expects nullCoalescingExpression to be fully parsed and valid.
-// (Otherwise, this method is not called at all.
-TypeAst *Parser::lastRelationalExpressionRestType(
- NullCoalescingExpressionAst *nullCoalescingExpression )
-{
- RelationalExpressionAst *relexp =
- nullCoalescingExpression
- ->expressionSequence->back()->element // gets a logicalOrExpression
- ->expressionSequence->back()->element // gets a logicalAndExpression
- ->expressionSequence->back()->element // gets a bitOrExpression
- ->expressionSequence->back()->element // gets a bitXorExpression
- ->expressionSequence->back()->element // gets a bitAndExpression
- ->expressionSequence->back()->element // gets an equalityExpression
- ->expression // gets a RelationalExpression
- ;
-
- if ( relexp->additionalExpressionSequence != 0 )
- return relexp->additionalExpressionSequence->back()->element->type;
- else
- return 0;
-}
-
-
-Parser::ParserState *Parser::copyCurrentState()
-{
- ParserState *state = new ParserState();
- state->ltCounter = m_state.ltCounter;
- return state;
-}
-
-void Parser::restoreState( Parser::ParserState *state )
-{
- m_state.ltCounter = state->ltCounter;
-}
-
-} // end of namespace CSharp
-
-:]
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.cpp (nonexistent)
@@ -1,77 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright (C) 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "parsesession.h"
-
-#include "kdev-pg-memory-pool.h"
-#include "kdev-pg-token-stream.h"
-
-namespace CSharp
-{
-
-ParseSession::ParseSession()
- : memoryPool( new Parser::memoryPoolType )
- , tokenStream( new KDevPG::TokenStream )
- , compatibilityMode( Parser::CSharp20Compatibility )
-{
-}
-
-ParseSession::~ParseSession()
-{
- delete memoryPool;
- delete tokenStream;
-}
-
-KDevelop::SimpleCursor ParseSession::positionAt( qint64 offset ) const
-{
- qint64 line, column;
- tokenStream->locationTable()->positionAt( offset, &line, &column );
- return KDevelop::SimpleCursor(line, column);
-}
-
-qint64 ParseSession::size() const
-{
- return m_contents.size();
-}
-
-const char *ParseSession::contents() const
-{
- return m_contents.constData();
-}
-
-void ParseSession::setContents( const QByteArray & contents )
-{
- m_contents = contents;
-}
-
-QString ParseSession::symbol( qint64 token ) const
-{
- const KDevPG::TokenStream::Token& tok = tokenStream->token( token );
- return QString::fromUtf8(m_contents.constData() + tok.begin, tok.end - tok.begin);
-}
-
-KDevelop::IndexedString ParseSession::indexedSymbol( qint64 token ) const
-{
- const KDevPG::TokenStream::Token& tok = tokenStream->token( token );
- return KDevelop::IndexedString(m_contents.constData() + tok.begin, tok.end - tok.begin);
-}
-
-} // end of namespace CSharp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/parsesession.h (nonexistent)
@@ -1,76 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright (C) 2006 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef CSHARP_PARSESESSION_H
-#define CSHARP_PARSESESSION_H
-
-#include <QtCore/QByteArray>
-
-#include <csharpparser.h>
-#include <language/editor/simplecursor.h>
-#include <language/duchain/indexedstring.h>
-#include <language/duchain/ducontext.h>
-
-namespace CSharp
-{
-
-typedef QPair<KDevelop::DUContextPointer, KDevelop::SimpleRange> SimpleUse;
-
-/// Contains everything needed to keep an AST useful once the rest of the parser
-/// has gone away.
-class KDEVCSHARPPARSER_EXPORT ParseSession
-{
-public:
- ParseSession();
- ~ParseSession();
-
- /**
- * Return the position (\a line%, \a column%) of the \a offset in the file.
- *
- * \note the line starts from 0.
- */
- KDevelop::SimpleCursor positionAt( qint64 offset ) const;
-
- void setContents( const QByteArray& contents );
-
- const char *contents() const;
- qint64 size() const;
- Parser::memoryPoolType *memoryPool;
- KDevPG::TokenStream *tokenStream;
- Parser::CSharpCompatibilityMode compatibilityMode;
-
- KDevelop::IndexedString indexedSymbol(qint64 token) const;
- QString symbol(qint64 token) const;
-
- /// @TODO implement this
- void mapAstUse(AstNode* node, const SimpleUse& use)
- {
- Q_UNUSED(node);
- Q_UNUSED(use);
- }
-
-private:
- QByteArray m_contents;
-};
-
-} // end of namespace CSharp
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.cpp (nonexistent)
@@ -1,139 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-#include "csharpppscope.h"
-
-
-namespace CSharpPP
-{
-
-Scope::Scope( CSharp::Parser* parser )
- : m_type(Scope::TypeRoot), m_parser(parser), m_child(0), m_parent(0)
-{
- m_isActive = true;
- m_waitingForActiveSection = true;
-}
-
-Scope::Scope( Scope::ScopeType Type, CSharp::Parser* Parser, bool active )
- : m_type(Type), m_parser(Parser), m_child(0)
-{
- if (active == true)
- {
- m_waitingForActiveSection = true;
- m_isActive = true;
- }
- else
- {
- m_waitingForActiveSection = false;
- m_isActive = false;
- }
-}
-
-Scope::~Scope()
-{
- if (m_child != 0)
- delete m_child;
- if (m_parent != 0)
- m_parent->m_child = 0;
-}
-
-Scope* Scope::currentScope()
-{
- if (m_child == 0)
- return this;
- else
- return m_child->currentScope();
-}
-
-Scope::ScopeType Scope::type()
-{
- return m_type;
-}
-
-bool Scope::isActive()
-{
- return m_isActive;
-}
-
-bool Scope::isWaitingForActiveSection()
-{
- return m_waitingForActiveSection;
-}
-
-void Scope::setActivated( bool active )
-{
- if (m_type != Scope::TypeIf)
- return;
- else if (m_waitingForActiveSection == false)
- m_isActive = false;
- else
- {
- m_isActive = active;
-
- if (active == true)
- m_waitingForActiveSection = false;
- }
-}
-
-bool Scope::pushScope( Scope::ScopeType type, Scope** newCurrent )
-{
- if (m_child != 0) {
- *newCurrent = m_child->currentScope();
- return false; // only the deepest nested Scope shall create children
- }
-
- m_child = new Scope(type, m_parser, m_isActive);
- m_child->setParent(this);
- *newCurrent = m_child;
- return true;
-}
-
-bool Scope::popScope( Scope::ScopeType type, Scope** newCurrent )
-{
- if (m_parent == 0 || type != m_type) {
- *newCurrent = this->currentScope();
- return false;
- }
-
- *newCurrent = m_parent;
- delete this;
- return true;
-}
-
-void Scope::setCSharpParser( ::CSharp::Parser* parser )
-{
- m_parser = parser;
-}
-
-::CSharp::Parser* Scope::csharpParser()
-{
- return m_parser;
-}
-
-void Scope::setParent( Scope* parent )
-{
- m_parent = parent;
-}
-
-Scope* Scope::parent()
-{
- return m_parent;
-}
-
-} // end of namespace CSharpPP
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/CMakeLists.txt (nonexistent)
@@ -1,139 +0,0 @@
-
-include_directories(
- ${KDE4_INCLUDES}
- ${KDE4_INCLUDE_DIR}/kdevelop-pg-qt
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDEVPLATFORM_INCLUDE_DIR}/interfaces
- ${KDEVPLATFORM_INCLUDE_DIR}/editor
- ${KDEVPLATFORM_INCLUDE_DIR}/project
- ${KDEVPLATFORM_INCLUDE_DIR}/project/interfaces
- ${KDEVPLATFORM_INCLUDE_DIR}/language
- ${KDEVPLATFORM_INCLUDE_DIR}/language/interfaces
- ${KDEVPLATFORM_INCLUDE_DIR}/language/backgroundparser
- ${KDEVPLATFORM_INCLUDE_DIR}/language/duchain
- ${KDEVPLATFORM_INCLUDE_DIR}/language/duchain/viewer
-)
-
-find_package(KDevelop-PG-Qt)
-
-########### next target ###############
-
-# autogenerate the lexer and the parser
-kdevpgqt_generate(_kdevpgList csharp NAMESPACE CSharp DEBUG_VISITOR
- "${CMAKE_CURRENT_SOURCE_DIR}/csharp.g"
- "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.h"
-)
-
-kdevpgqt_generate(_kdevpgList2 csharppp NAMESPACE CSharpPP DEBUG_VISITOR
- "${CMAKE_CURRENT_SOURCE_DIR}/csharppp.g"
- "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.h"
-)
-
-set(kdevcsharpparser_STAT_SRCS
- csharpio.cpp
- csharpppscope.cpp
- csharppphandlervisitor.cpp
- parsesession.cpp
- ${_kdevpgList}
- ${_kdevpgList2}
-)
-
-find_package(Flex)
-
-if(FLEX_FOUND)
- # Copy csharplexer.ll to the builddir, so that flex doesn't write out
- # absolute paths in the generated file when we pass them as arguments.
- # In short, I don't want stuff like
- # '#line 2 "/home/kde/build/.../csharplexer.cpp" in SVN.
- add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
- MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.ll"
- COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
- "${CMAKE_CURRENT_SOURCE_DIR}/csharplexer.ll"
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
- )
- set_source_files_properties(
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
- GENERATED
- )
- # Add command to generate the lexer.
- add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
- MAIN_DEPENDENCY "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.ll"
- DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
- COMMAND ${FLEX_EXECUTABLE}
- ARGS -o"csharplexer.cpp"
- "csharplexer.ll"
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
- )
-else(FLEX_FOUND)
- # If flex is not available, copy the pre-generated lexer from SVN.
- add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
- DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
- COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
- COMMENT "flex is not installed, using the pre-generated lexer from SVN."
- )
-endif(FLEX_FOUND)
-
-set(kdevcsharpparser_STAT_SRCS
- ${kdevcsharpparser_STAT_SRCS}
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
-)
-set_source_files_properties(
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
- GENERATED
-)
-
-
-
-# Note: This library doesn't follow API/ABI/BC rules and shouldn't have a SOVERSION
-# Its only purpose is to support the plugin without needing to add all source files
-# to the plugin target
-kde4_add_library(kdev4csharpparser SHARED ${kdevcsharpparser_STAT_SRCS})
-target_link_libraries(kdev4csharpparser ${KDE4_KDECORE_LIBS} ${KDE4_KTEXTEDITOR_LIBS} ${KDEVPLATFORM_LANGUAGE_LIBRARIES})
-install(TARGETS kdev4csharpparser ${INSTALL_TARGETS_DEFAULT_ARGS} )
-
-
-add_custom_target( copy-generated
-
-# 1. copy the kdev-pg generated files for the csharp parser
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpast.h"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpast.h"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpparser.h"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.cpp"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpparser.cpp"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.h"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpvisitor.h"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.cpp"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpvisitor.cpp"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.h"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpdefaultvisitor.h"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.cpp"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharpdefaultvisitor.cpp"
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
- "${CMAKE_CURRENT_SOURCE_DIR}/generated/csharplexer.cpp"
-
-# 2. depend on the files being copied
- DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/csharpast.h"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.h"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpparser.cpp"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.h"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpvisitor.cpp"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.h"
- "${CMAKE_CURRENT_BINARY_DIR}/csharpdefaultvisitor.cpp"
- "${CMAKE_CURRENT_BINARY_DIR}/csharplexer.cpp"
-)
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpio.cpp (nonexistent)
@@ -1,76 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-// This file is meant to be specific to the framework in which the parser
-// operates, and is likely to be adapted for different environments.
-// Specifically, the error output might not always go to std::cerr,
-// but will rather be placed as items inside some listbox.
-
-
-#include "csharpparser.h"
-#include "csharplexer.h"
-
-#include <QString>
-
-#include <KDebug>
-
-// void print_token_environment(CSharp::parser* parser);
-
-
-namespace CSharp
-{
-
-void Parser::reportProblem( Parser::ProblemType type, QString message )
-{
- if (type == error)
- kDebug() << "** ERROR: " << message;
- else if (type == warning)
- kDebug() << "** WARNING: " << message;
- else if (type == info)
- kDebug() << "** Info: " << message;
-}
-
-void Parser::reportProblem( Parser::ProblemType type, const char* message )
-{
- reportProblem(type, QString::fromUtf8(message));
-}
-
-
-// custom error recovery
-void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
-{
- // print_token_environment(this);
- reportProblem(
- Parser::error,
- QString("Expected token ``%1''").arg(name)
- //+ "'' instead of ``" + current_token_text
- );
-}
-
-void Parser::expectedSymbol(int /*expected_symbol*/, const QString& name)
-{
- // print_token_environment(this);
- reportProblem(
- Parser::error,
- QString("Expected symbol ``%1''").arg(name)
- //+ "'' instead of ``" + current_token_text
- );
-}
-
-} // end of namespace CSharp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/resources/source-locations.txt (nonexistent)
@@ -1,77 +0,0 @@
-Where I got the specifications, grammars and stuff.
-
-
-Different versions of the Language specification:
-
-ECMA-334 (C# Language specification), 3rd edition (June 2005):
-http://www.ecma-international.org/publications/standards/Ecma-334.htm
-...covers C# 2.0.
-
-ISO/IEC 23270:2003 (C# Language specification, 2nd edition, April 2004):
-http://isotc.iso.org/livelink/livelink/fetch/2000/2489/Ittf_Home/PubliclyAvailableStandards.htm
-...covers C# 1.0.
-
-HTML version of the ECMA-334 (2rd edition / C# 1.0, it seems) standard:
-http://www.jaggersoft.com/csharp_standard/index.htm
-
-For more information and more links, check out the page from the Mono project:
-http://www.mono-project.com/ECMA
-
-
-Grammars:
-
-- Every specification contains an example grammar, yay!
-
-Mono's C# 2.0 grammar (.jay format, very bison-like):
-http://svn.myrealbox.com/viewcvs/trunk/mcs/gmcs/cs-parser.jay?rev=60352&view=auto
-
-Mono's C# 1.0 grammar (.jay format, very bison-like):
-http://svn.myrealbox.com/viewcvs/trunk/mcs/mcs/cs-parser.jay?rev=60352&view=auto
-
-James Power's flex/bison C# parser:
-http://www.cs.nuim.ie/~jpower/Research/csharp/
-http://www.cs.may.ie/~jpower/
-
-ANTLR contains a C# parser in examples/csharp/csharp_v1/, which appears to be
-an approximate copy (or rather the origin) of kcsparse.
-
-From http://antlr.org/grammar/list:
-
-- kcsparse: parses C# 1.0 files
-Kunle Odutola Thu Dec 8, 2005 06:37
-"Yet Another C# Grammar For ANTLR implemented in C#. It is probably more
-complete and includes both an ANTLR and a C# Flex lexer. With kcsparse, you can
-(a) Parse C# 1.x source code including some with C# preprocessing directives,
-(b)Build and display an AST from C# source and,
-(c) Unparse the AST (i.e. pretty prints the AST)."
-
-- C# Grammar with minimal lookaheads
-Todd King Mon Sep 26, 2005 00:48
-"This C# antlr grammar implements most of the C# spec except for a few of the
-unsafe elements. I designed this grammar for speed so I avoided using arbitrary
-lookaheads where I could. I got it down to just 7 lookaheads. This grammar can
-parse large files very fast because it doesnýt waste time spinning in arbitrary
-lookaheads. (It can parse the entire NAnt project in 5 seconds, that is
-90986 LOC)"
-
-- C# grammar (based on ecma-334 spec)
-Robin Debreuil Fri Mar 5, 2004 11:50
-"A (mostly) complete cs parser. It parses into a tree structure loosely based
-on the CodeDom. Does not yet do #if preprocessor segments, and no unsafe code
-(as of yet). You can test by downloading the CSharp.zip file and dragging
-cs files into CSharp.exe. The zip includes the grammar file, as well as the
-cs token classes (the grammar uses a heterogeneous tree, though that should
-be simple to turn off). permalink: http://www.debreuil.com/CSharp. TJP: copied
-src, exe to antlr.org and changed link as debreuil's links are dead."
-
-- C# Grammar File
-Rajendra Kumar Komandur Wed Oct 29, 2003 20:07
-"Grammar file for cSharp language which supports most part of the cSharp
-language spec."
-
-
-Other resources:
-
-A Comparison Of Microsoft'S C# Programming Language
-To Sun Microsystems' Java Programming Language (by Dare Obasanjo)
-http://www.25hoursaday.com/CsharpVsJava.html
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppp.g
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppp.g (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppp.g (nonexistent)
@@ -1,437 +0,0 @@
------------------------------------------------------------------------------
--- Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
---
--- This grammar 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 grammar 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
--- Lesser 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.
------------------------------------------------------------------------------
-
-
------------------------------------------------------------------------------
--- Grammar for the pre-processor part of C# 2.0
--- Modelled after the reference grammar of the C# 2.0 language specification
--- (ECMA-334, Third Edition from June 2005, available at
--- http://www.ecma-international.org/publications/standards/Ecma-334.htm).
------------------------------------------------------------------------------
-
-
-------------------------------------------------------------
--- Global declarations
-------------------------------------------------------------
-
-[:
-#include <QtCore/QString>
-namespace KDevelop
-{
-class DUContext;
-}
-
-namespace CSharp
-{
-class Lexer;
-class ParseSession;
-}
-
-:]
-
-%export_macro "KDEVCSHARPPARSER_EXPORT"
-%export_macro_header "csharpparserexport.h"
-
-
-------------------------------------------------------------
--- Parser class members
-------------------------------------------------------------
-
-%parserclass (public declaration)
-[:
- enum PPParseResult {
- ResultOk,
- ResultInvalid,
- ResultEof
- };
-
- /**
- * Process a pre-processor line.
- * This method occupies the lexer until a PP_NEW_LINE token is found,
- * and carries out the appropriate action. For example, when processing
- * a #define statement it stores the defined symbol, or when processing
- * an #if statement it evaluates the expression and sets the correct value
- * for the ppIsSectionSkipped() method.
- *
- * @param firstToken The first token of the pre-processor line.
- * @param Scope The currently active pre-processor state, stored as a Scope.
- * @param lexer The lexer object which is currently processing the source file.
- * @return CSharpPP::Parser::ResultOk if the line was processed correctly,
- * CSharpPP::Parser::ResultInvalid if there was a parsing error,
- * or CSharpPP::Parser::ResultEof if the end of file was found (unexpectedly).
- */
- Parser::PPParseResult ppParseLine(
- Parser::TokenType firstToken, Scope *Scope, CSharp::Lexer *lexer, CSharp::ParseSession* session );
-:]
-
-%parserclass (private declaration)
-[:
- Scope *m_scope;
- CSharp::Lexer *m_lexer;
-
- /**
- * Transform the raw input into tokens.
- * When this method returns, the parser's token stream has been filled
- * and any parse_*() method can be called. Alternatively, the end of file
- * has been reached and we have to issue an error.
- */
- void tokenize(bool &encounteredEof);
-
- /**
- * Add the currently lexed token into the token stream, using the
- * given token kind. Used by the pre-processor that has to bypass
- * the normal tokenizing process.
- */
- void addToken(Parser::TokenType tokenKind);
-
- KDevPG::TokenStream m_tokenStream;
- KDevPG::MemoryPool m_memoryPool;
-:]
-
-%parserclass (constructor)
-[:
- setTokenStream(&m_tokenStream);
- setMemoryPool(&m_memoryPool);
-:]
-
-
-
-------------------------------------------------------------
--- Enumeration Types for additional AST members
-------------------------------------------------------------
-
-%namespace
-[:
-class Scope;
-
-namespace PPEqualityExpressionRest
-{
- enum PPEqualityOperatorEnum {
- opEqual,
- opNotEqual
- };
-}
-
-namespace PPPrimaryExpression
-{
- enum PPPrimaryExpressionTypeEnum {
- TypeTrue,
- TypeFalse,
- TypeConditionalSymbol,
- TypeParenthesisExpression
- };
-}
-
-namespace PPDeclaration
-{
- enum PPDeclarationTypeEnum {
- TypeDefine,
- TypeUndef
- };
-}
-
-namespace PPDiagnostic
-{
- enum PPDiagnosticTypeEnum {
- TypeError,
- TypeWarning
- };
-}
-
-namespace PPRegion
-{
- enum PPRegionTypeEnum {
- TypeRegion,
- TypeEndregion
- };
-}
-:]
-
-
-
-
-------------------------------------------------------------
--- List of defined tokens
-------------------------------------------------------------
-
--- start tokens:
-%token PP_DEFINE ("#define"), PP_UNDEF ("#undef"), PP_IF ("#if"),
- PP_ELIF ("#elif"), PP_ELSE ("#else"), PP_ENDIF ("#endif"),
- PP_LINE ("#line"), PP_ERROR ("#error"), PP_WARNING ("#warning"),
- PP_REGION ("#region"), PP_ENDREGION ("#endregion"),
- PP_PRAGMA ("#pragma") ;;
-
--- value tokens and the line break:
-%token PP_CONDITIONAL_SYMBOL ("pre-processor symbol"),
- PP_NEW_LINE ("line break"), PP_LINE_NUMBER ("line number"),
- PP_FILE_NAME ("file name (in double quotes)"),
- PP_IDENTIFIER_OR_KEYWORD ("identifier or keyword"),
- PP_MESSAGE ("single-line text"), PP_PRAGMA_TEXT ("pragma text") ;;
-
--- operators and keywords:
-%token PP_EQUAL ("=="), PP_NOT_EQUAL ("!="), PP_LOG_AND ("&&"),
- PP_LOG_OR ("||"), PP_BANG ("!"), PP_LPAREN ("("), PP_RPAREN (")"),
- PP_TRUE ("true"), PP_FALSE ("false"), PP_DEFAULT ("default") ;;
-
--- token that makes the parser fail in any case:
-%token PP_INVALID ("invalid token") ;;
-
-
-
-
-------------------------------------------------------------
--- Start of the actual grammar
-------------------------------------------------------------
-
---
--- Preprocessor rules. Those are handled before the grammar is
--- actually processed, as part of the lexing (called from within the lexer).
---
-
- ( declaration=PPDeclaration
- | ifClause=PPIfClause
- | elifClause=PPElifClause
- | elseClause=PPElseClause
- | endifClause=PPEndifClause
- | diagnostic=PPDiagnostic
- | region=PPRegion
- | line=PPLine
- | pragma=PPPragma
- )
- PP_NEW_LINE
--> PPDirective ;;
-
- ( PP_DEFINE [: (*yynode)->type = PPDeclaration::TypeDefine; :]
- | PP_UNDEF [: (*yynode)->type = PPDeclaration::TypeUndef; :]
- )
- conditionalSymbol=PP_CONDITIONAL_SYMBOL
--> PPDeclaration [
- member variable type: PPDeclaration::PPDeclarationTypeEnum;
-] ;;
-
- PP_IF expression=PPExpression
--> PPIfClause ;;
-
- PP_ELIF expression=PPExpression
--> PPElifClause ;;
-
- PP_ELSE
--> PPElseClause ;;
-
- PP_ENDIF
--> PPEndifClause ;;
-
- ( PP_ERROR [: (*yynode)->type = PPDiagnostic::TypeError; :]
- | PP_WARNING [: (*yynode)->type = PPDiagnostic::TypeWarning; :]
- )
- (message=PP_MESSAGE | 0)
--> PPDiagnostic [
- member variable type: PPDiagnostic::PPDiagnosticTypeEnum;
-] ;;
-
- ( PP_REGION [: (*yynode)->type = PPRegion::TypeRegion; :]
- | PP_ENDREGION [: (*yynode)->type = PPRegion::TypeEndregion; :]
- )
- (label=PP_MESSAGE | 0)
--> PPRegion [
- member variable type: PPRegion::PPRegionTypeEnum;
-] ;;
-
- PP_LINE
- ( lineNumber=PP_LINE_NUMBER (fileName=PP_FILE_NAME | 0)
- | tokenDefault=PP_DEFAULT
- | identifierOrKeyword=PP_IDENTIFIER_OR_KEYWORD
- )
--> PPLine ;;
-
- PP_PRAGMA (pragmaText=PP_PRAGMA_TEXT | 0)
--> PPPragma ;;
-
-
-
--- Expressions used in #if and #elif
-
- #expression=PPAndExpression @ PP_LOG_OR
--> PPExpression ;;
-
- #expression=PPEqualityExpression @ PP_LOG_AND
--> PPAndExpression ;;
-
- expression=PPUnaryExpression
- (#additionalExpression=PPEqualityExpressionRest)*
--> PPEqualityExpression ;;
-
- ( PP_EQUAL [: (*yynode)->equalityOperator = PPEqualityExpressionRest::opEqual; :]
- | PP_NOT_EQUAL [: (*yynode)->equalityOperator = PPEqualityExpressionRest::opNotEqual; :]
- )
- expression=PPUnaryExpression
--> PPEqualityExpressionRest [
- member variable equalityOperator: PPEqualityExpressionRest::PPEqualityOperatorEnum;
-] ;;
-
- ( PP_BANG expression=PPPrimaryExpression [: (*yynode)->negated = true; :]
- | expression=PPPrimaryExpression [: (*yynode)->negated = false; :]
- )
--> PPUnaryExpression [
- member variable negated: bool;
-] ;;
-
- (
- PP_TRUE [: (*yynode)->type = PPPrimaryExpression::TypeTrue; :]
- | PP_FALSE [: (*yynode)->type = PPPrimaryExpression::TypeFalse; :]
- | conditionalSymbol=PP_CONDITIONAL_SYMBOL
- [: (*yynode)->type = PPPrimaryExpression::TypeConditionalSymbol; :]
- | PP_LPAREN parenthesisExpression=PPExpression PP_RPAREN
- [: (*yynode)->type = PPPrimaryExpression::TypeParenthesisExpression; :]
- )
--> PPPrimaryExpression [
- member variable type: PPPrimaryExpression::PPPrimaryExpressionTypeEnum;
-] ;;
-
-
-
-
-
------------------------------------------------------------------
--- Code segments copied to the implementation (.cpp) file.
--- If existent, kdevelop-pg's current syntax requires this block
--- to occur at the end of the file.
------------------------------------------------------------------
-
-[:
-#include "csharpparser.h"
-#include "csharplexer.h"
-#include "csharppphandlervisitor.h"
-#include "csharpppscope.h"
-
-#include <QString>
-
-
-namespace CSharpPP
-{
-
-void Parser::tokenize(bool &encounteredEof)
-{
- encounteredEof = false;
- int kind = Parser::Token_EOF;
- do
- {
- kind = m_lexer->yylex();
- //std::cerr << "pp: " << lexer.YYText() << std::endl; //" "; // debug output
-
- Parser::Token &t = this->tokenStream->next();
- t.kind = kind;
- t.begin = m_lexer->tokenBegin();
- t.end = m_lexer->tokenEnd();
-
- if (kind == Parser::Token_EOF)
- {
- t.kind = Parser::Token_PP_NEW_LINE;
- encounteredEof = true;
- break;
- }
- }
- while (kind != Parser::Token_PP_NEW_LINE);
-
- Parser::Token &t = this->tokenStream->next();
- t.kind = Parser::Token_EOF;
- t.begin = m_lexer->tokenBegin();
- t.end = m_lexer->tokenEnd();
-
- this->yylex(); // produce the look ahead token
-}
-
-void Parser::addToken(Parser::TokenType tokenKind)
-{
- //std::cerr << "pp: " << lexer.YYText() << std::endl; //" "; // debug output
- Parser::Token &t = this->tokenStream->next();
- t.kind = tokenKind;
- t.begin = m_lexer->tokenBegin();
- t.end = m_lexer->tokenEnd();
-}
-
-
-Parser::PPParseResult Parser::ppParseLine(
- Parser::TokenType firstToken, Scope* Scope, CSharp::Lexer *lexer, CSharp::ParseSession* session )
-{
- // 0) setup
- if (Scope == 0)
- return Parser::ResultInvalid;
-
- m_scope = Scope;
- bool encounteredEof;
-
- // 1) tokenize
- m_lexer = lexer;
- addToken(firstToken);
- tokenize(encounteredEof);
-
- // 2) parse
- PPDirectiveAst* PPDirectiveNode = 0;
- bool matched = parsePPDirective(&PPDirectiveNode);
-
- if (matched)
- {
- HandlerVisitor v(session);
- v.setScope(m_scope);
- v.visitNode(PPDirectiveNode);
- }
- else
- {
- expectedSymbol(AstNode::PPDirectiveKind, "PPDirective"); // ### remove me
- return Parser::ResultInvalid;
- }
-
- if (encounteredEof)
- return Parser::ResultEof;
- else
- return Parser::ResultOk;
-}
-
-
-// custom error recovery
-void Parser::expectedToken(int /*expected*/, qint64 /*where*/, const QString& name)
-{
- //printTokenEnvironment(this);
- if (m_scope->csharpParser() != 0)
- {
- m_scope->csharpParser()->reportProblem(
- CSharp::Parser::error,
- QString("Invalid pre-processor directive: Expected token ``%1''").arg(name)
- //+ "'' instead of ``" + currentTokenText
- );
- }
-}
-
-void Parser::expectedSymbol(int /*expectedSymbol*/, const QString& name)
-{
- //printTokenEnvironment(this);
- if (m_scope->csharpParser() != 0)
- {
- m_scope->csharpParser()->reportProblem(
- CSharp::Parser::error,
- QString("Invalid pre-processor directive: Expected symbol ``%1''").arg(name)
- //+ "'' instead of ``" + currentTokenText
- );
- }
-}
-
-} // end of namespace CSharpPP
-
-:]
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpppscope.h (nonexistent)
@@ -1,138 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-#ifndef CSHARP_PP_SCOPE_H
-#define CSHARP_PP_SCOPE_H
-
-namespace CSharp
-{
- class Parser;
-}
-
-namespace CSharpPP
-{
-
-/**
- * Pre-processor Scopes are managed by the pre-processor parser
- * and contain information about the current state of how the
- * pre-processor directives are nested at the moment, and most importantly,
- * if the current code segment is to be included or excluded by the lexer.
- *
- * After each pre-processor directive, the lexer checks the current Scope
- * in order to to know if the upcoming text is to be treated as tokens
- * or like #ifdef'd out.
- */
-class Scope
-{
-public:
- enum ScopeType {
- TypeRoot,
- TypeIf,
- TypeRegion
- };
-
- Scope( CSharp::Parser* parser );
- ~Scope();
-
- /**
- * Retrieves the last child of the Scope hierarchy. That child contains
- * the state at the current code position and should be used for getting
- * info.
- */
- Scope* currentScope();
-
- Scope::ScopeType type();
-
- /**
- * Returns @true if the code at the current position is included into
- * the parser's token stream, or @false if it's a skipped section.
- * This is called by the lexer after each pre-processor line, and
- * makes him treat the upcoming text either as tokens or like #ifdef'd out.
- */
- bool isActive();
-
- /**
- * Returns @true if the Scope corresponds to an #if/#elif/#else condition
- * and has not yet seen a code segment that is included
- * (as in: not skipped), and @false otherwise.
- */
- bool isWaitingForActiveSection();
-
- /**
- * Set the current state of the Scope to "active" or "not active".
- * To be called for #if and #elif conditions with the expression value
- * as argument.
- */
- void setActivated( bool active );
-
- /**
- * Creates a new child Scope inside this one, inheriting its state.
- *
- * @param type Determines the type of the new Scope.
- * @param newCurrent The new current Scope, given as a return value.
- * @return @true if the Scope has been created, or @false if this Scope
- * already possesses a child (in this case, nothing is done).
- */
- bool pushScope( Scope::ScopeType type, Scope** newCurrent = 0 );
-
- /**
- * Destroys this Scope so that its parent is the current Scope again.
- * If this one is already the root Scope, it is not destroyed and stays
- * the currently active Scope.
- *
- * @param type The type of the Scope that should be closed.
- * If it doesn't match with this Scope's type,
- * it's semantically wrong and the Scope is not destroyed.
- * @param newCurrent The new current Scope, given as a return value.
- * @return @true if the Scope has been destroyed,
- * @false if it is already the root Scope.
- */
- bool popScope( Scope::ScopeType type, Scope** newCurrent = 0 );
-
- /**
- * Sets the actual parser class - the one not handling the pre-processor.
- */
- void setCSharpParser( ::CSharp::Parser* parser );
- ::CSharp::Parser* csharpParser();
-
-private:
- Scope( Scope::ScopeType type, CSharp::Parser* parser, bool active );
-
- void setParent( Scope* parent );
- Scope* parent();
-
- ScopeType m_type;
- CSharp::Parser* m_parser;
-
- /** Child Scope of the current one. (May be recursive.) */
- Scope* m_child;
-
- /** Parent Scope of the current one. */
- Scope* m_parent;
-
- bool m_isActive;
-
- /** This flag is initially set true, and becomes false when an #if or
- * #elif expression is found that evaluates to true. */
- bool m_waitingForActiveSection;
-};
-
-} // end of namespace CSharpPP
-
-#endif // CSHARP_PP_SCOPE_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/FlexLexer.h (nonexistent)
@@ -1,208 +0,0 @@
-
-// -*-C++-*-
-// FlexLexer.h -- define interfaces for lexical analyzer classes generated
-// by flex
-
-// Copyright (c) 1993 The Regents of the University of California.
-// All rights reserved.
-//
-// This code is derived from software contributed to Berkeley by
-// Kent Williams and Tom Epperly.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions
-// are met:
-
-// 1. Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-
-// Neither the name of the University nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-
-// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
-// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-// PURPOSE.
-
-// This file defines FlexLexer, an abstract class which specifies the
-// external interface provided to flex C++ lexer objects, and yyFlexLexer,
-// which defines a particular lexer class.
-//
-// If you want to create multiple lexer classes, you use the -P flag
-// to rename each yyFlexLexer to some other xxFlexLexer. You then
-// include <FlexLexer.h> in your other sources once per lexer class:
-//
-// #undef yyFlexLexer
-// #define yyFlexLexer xxFlexLexer
-// #include <FlexLexer.h>
-//
-// #undef yyFlexLexer
-// #define yyFlexLexer zzFlexLexer
-// #include <FlexLexer.h>
-// ...
-
-#ifndef __FLEX_LEXER_H
-// Never included before - need to define base class.
-#define __FLEX_LEXER_H
-
-#include <iostream>
-# ifndef FLEX_STD
-# define FLEX_STD std::
-# endif
-
-extern "C++" {
-
-struct yy_buffer_state;
-typedef int yy_state_type;
-
-class FlexLexer {
-public:
- virtual ~FlexLexer() { }
-
- const char* YYText() const { return yytext; }
- int YYLeng() const { return yyleng; }
-
- virtual void
- yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0;
- virtual struct yy_buffer_state*
- yy_create_buffer( FLEX_STD istream* s, int size ) = 0;
- virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0;
- virtual void yyrestart( FLEX_STD istream* s ) = 0;
-
- virtual int yylex() = 0;
-
- // Call yylex with new input/output sources.
- int yylex( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0 )
- {
- switch_streams( new_in, new_out );
- return yylex();
- }
-
- // Switch to new input/output streams. A nil stream pointer
- // indicates "keep the current one".
- virtual void switch_streams( FLEX_STD istream* new_in = 0,
- FLEX_STD ostream* new_out = 0 ) = 0;
-
- int lineno() const { return yylineno; }
-
- int debug() const { return yy_flex_debug; }
- void set_debug( int flag ) { yy_flex_debug = flag; }
-
-protected:
- char* yytext;
- int yyleng;
- int yylineno; // only maintained if you use %option yylineno
- int yy_flex_debug; // only has effect with -d or "%option debug"
-};
-
-}
-#endif
-
-#if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce)
-// Either this is the first time through (yyFlexLexerOnce not defined),
-// or this is a repeated include to define a different flavor of
-// yyFlexLexer, as discussed in the flex man page.
-#define yyFlexLexerOnce
-
-extern "C++" {
-
-class yyFlexLexer : public FlexLexer {
-public:
- // arg_yyin and arg_yyout default to the cin and cout, but we
- // only make that assignment when initializing in yylex().
- yyFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 );
-
- virtual ~yyFlexLexer();
-
- void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
- struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size );
- void yy_delete_buffer( struct yy_buffer_state* b );
- void yyrestart( FLEX_STD istream* s );
-
- void yypush_buffer_state( struct yy_buffer_state* new_buffer );
- void yypop_buffer_state(void);
-
-#ifndef yywrap
- int yywrap();
-#endif
- virtual int yylex();
- virtual void switch_streams( FLEX_STD istream* new_in, FLEX_STD ostream* new_out );
-
-protected:
- virtual int LexerInput( char* buf, int max_size );
- virtual void LexerOutput( const char* buf, int size );
- virtual void LexerError( const char* msg );
-
- void yyunput( int c, char* buf_ptr );
- int yyinput();
-
- void yy_load_buffer_state();
- void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream* s );
- void yy_flush_buffer( struct yy_buffer_state* b );
-
- int yy_start_stack_ptr;
- int yy_start_stack_depth;
- int* yy_start_stack;
-
- void yy_push_state( int new_state );
- void yy_pop_state();
- int yy_top_state();
-
- yy_state_type yy_get_previous_state();
- yy_state_type yy_try_NUL_trans( yy_state_type current_state );
- int yy_get_next_buffer();
-
- FLEX_STD istream* yyin; // input source for default LexerInput
- FLEX_STD ostream* yyout; // output sink for default LexerOutput
-
- // yy_hold_char holds the character lost when yytext is formed.
- char yy_hold_char;
-
- // Number of characters read into yy_ch_buf.
- int yy_n_chars;
-
- // Points to current character in buffer.
- char* yy_c_buf_p;
-
- int yy_init; // whether we need to initialize
- int yy_start; // start state number
-
- // Flag which is used to allow yywrap()'s to do buffer switches
- // instead of setting up a fresh yyin. A bit of a hack ...
- int yy_did_buffer_switch_on_eof;
-
-
- size_t yy_buffer_stack_top; /**< index of top of stack. */
- size_t yy_buffer_stack_max; /**< capacity of stack. */
- struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */
- void yyensure_buffer_stack(void);
-
- // The following are not always needed, but may be depending
- // on use of certain flex features (like REJECT or yymore()).
-
- yy_state_type yy_last_accepting_state;
- char* yy_last_accepting_cpos;
-
- yy_state_type* yy_state_buf;
- yy_state_type* yy_state_ptr;
-
- char* yy_full_match;
- int* yy_full_state;
- int yy_full_lp;
-
- int yy_lp;
- int yy_looking_for_trail_begin;
-
- int yy_more_flag;
- int yy_more_len;
- int yy_more_offset;
- int yy_prev_more_offset;
-};
-
-}
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.h (nonexistent)
@@ -1,77 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-#include "csharpparser.h"
-#include "csharpppparser.h"
-
-#include <iostream>
-
-#ifndef DONT_INCLUDE_FLEXLEXER
-#include "FlexLexer.h"
-#endif
-
-// The YY_USER_ACTION macro is called whenever a token is found by Flex
-#define YY_USER_ACTION \
-m_tokenBegin = m_tokenEnd; \
-m_tokenEnd += yyleng;
-
-
-namespace CSharp
-{
-
-class Lexer : public yyFlexLexer
-{
-public:
- Lexer( CSharp::Parser *parser, ParseSession* session );
- void restart( CSharp::Parser *parser, ParseSession* session );
-
- virtual ~Lexer() { cleanup(); }
-
- int yylex();
- const char *contents() const;
- qint64 tokenBegin() { return m_tokenBegin; }
- qint64 tokenEnd() { return m_tokenEnd; }
-
-private:
- // Takes care of handling and destroying unclosed Scopes.
- void cleanup();
-
- // retrieves the upper-most pre-processor Scope
- CSharpPP::Scope* ppCurrentScope();
-
-protected:
- // custom input, replacing the Flex default input stdin
- virtual int LexerInput( char *buf, int max_size );
-
- // dismisses any lexer output (which should not happen anyways)
- virtual void LexerOutput( const char * /*buf*/, int /*max_size*/ ) { return; }
- virtual void LexerError( const char */*msg*/ ) { return; }
-
-private:
- CSharp::Parser* m_parser;
- ParseSession *m_session;
- qint64 m_tokenBegin, m_tokenEnd;
- qint64 m_currentOffset;
- CSharpPP::Scope* m_ppRootScope;
- KDevPG::LocationTable *m_locationTable;
-};
-
-} // end of namespace CSharp
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharplexer.ll (nonexistent)
@@ -1,628 +0,0 @@
-%{
-/*****************************************************************************
- * Copyright (c) 2005, 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-%}
-
-%option c++
-%option yyclass="CSharp::Lexer"
-%option noyywrap
-
-
-%{
-
-#define DONT_INCLUDE_FLEXLEXER
-#include "csharplexer.h"
-#include "csharpppscope.h"
-#include "parsesession.h"
-
-
-// This is meant to be called with the first token in a pre-processor line.
-// Pre-processing completely bypasses the normal tokenizing process.
-#define PP_PROCESS_TOKEN(t) \
-{ \
- CSharpPP::Parser ppParser; \
- CSharpPP::Parser::PPParseResult Result = \
- ppParser.ppParseLine( CSharpPP::Parser::Token_##t, ppCurrentScope(), this, m_session ); \
- \
- if ( Result == CSharpPP::Parser::ResultEof ) \
- { \
- BEGIN(INITIAL); \
- return 0; /* end of file */ \
- } \
- else if ( Result == CSharpPP::Parser::ResultInvalid ) \
- { \
- BEGIN(INITIAL); \
- return Parser::Token_INVALID; \
- } \
- else if ( Result == CSharpPP::Parser::ResultOk ) \
- { \
- if (ppCurrentScope()->isActive()) \
- BEGIN(INITIAL); \
- else \
- BEGIN(PP_SKIPPED_SECTION_PART); \
- } \
-}
-
-%}
-
-
- /* UTF-8 sequences, generated with the Unicode.hs script from
- * http://lists.gnu.org/archive/html/help-flex/2005-01/msg00043.html */
-
- /* 0x0041-0x005a, 0x005f, 0x0061-0x007a: one byte in UTF-8 */
-Letter1 [A-Za-z_]
- /* 0x00c0-0x00d6, 0x00d8-0x00f6, 0x00f8-0x00ff */
-Letter2 [\xC3]([\x80-\x96]|[\x98-\xB6]|[\xB8-\xBF])
- /* 0x0100-0x1fff */
-Letter3 [\xC4-\xDF][\x80-\xBF]|([\xE0][\xA0-\xBF]|[\xE1][\x80-\xBF])[\x80-\xBF]
- /* 0x3040-0x318f */
-Letter4 [\xE3]([\x86][\x80-\x8F]|[\x81-\x85][\x80-\xBF])
- /* 0x3300-0x337f */
-Letter5 [\xE3][\x8C-\x8D][\x80-\xBF]
- /* 0x3400-0x3d2d */
-Letter6 [\xE3](\xB4[\x80-\xAD]|[\x90-\xB3][\x80-\xBF])
- /* 0x4e00-0x9fff */
-Letter7 ([\xE4][\xB8-\xBF]|[\xE5-\xE9][\x80-\xBF])[\x80-\xBF]
- /* 0xf900-0xfaff */
-Letter8 [\xEF][\xA4-\xAB][\x80-\xBF]
-
-Letter {Letter1}|{Letter2}|{Letter3}|{Letter4}|{Letter5}|{Letter6}|{Letter7}|{Letter8}
-
-
- /* 0x0080-0xffff */
-Multibyte1 ([\xC2-\xDF]|[\xE0][\xA0-\xBF]|[\xE1-\xEF][\x80-\xBF])[\x80-\xBF]
- /* 0x10000-0x10ffff */
-Multibyte2 (\xF0[\x90-\xBF]|\xF4[\x80-\x8F]|[\xF1-\xF3][\x80-\xBF])[\x80-\xBF][\x80-\xBF]
- /* Unicode characters above 0x10ffff are not supported by C#. */
- /* Any multi-byte Unicode character. Single-byte ones are just . in lex. */
-Multibyte {Multibyte1}|{Multibyte2}
-
-
- /* 0x2028 and 0x2029, currently unused in this lexer
- for performance and convenience reasons. */
-UnicodeNewLine [\xE2][\x80][\xA8-\xA9]
-
-
- /* non-Unicode stuff */
-
-Whitespace [ \t\v\f]+
-LineComment "//"[^\n]*
-
-DecimalDigit [0-9]
-HexDigit [0-9a-fA-F]
-
-ShortUnicodeEscape [\\][u]{HexDigit}{HexDigit}{HexDigit}{HexDigit}
-LongUnicodeEscape [\\][U]{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}{HexDigit}
-UnicodeEscape {ShortUnicodeEscape}|{LongUnicodeEscape}
-HexEscape [\\][x]{HexDigit}{HexDigit}?{HexDigit}?{HexDigit}?
-SimpleEscape [\\]([']|["]|[\\]|[0abfnrtv])
-Escape ({SimpleEscape}|{UnicodeEscape}|{HexEscape})
-
-IntegerSuffix (([Ll][Uu]?)|([Uu][Ll]?))
-DecimalLiteral {DecimalDigit}+{IntegerSuffix}?
-HexLiteral [0][xX]{HexDigit}+{IntegerSuffix}?
-IntegerLiteral ({DecimalLiteral}|{HexLiteral})
-
-Sign [+-]
-RealSuffix ([fF]|[dD]|[m_m])
-Exponent [eE]{Sign}?{DecimalDigit}+
-Real1 {DecimalDigit}+[\.]{DecimalDigit}+{Exponent}?{RealSuffix}?
-Real2 [\.]{DecimalDigit}+{Exponent}?{RealSuffix}?
-Real3 {DecimalDigit}+{Exponent}{RealSuffix}?
-Real4 {DecimalDigit}+{RealSuffix}
-RealLiteral ({Real1}|{Real2}|{Real3}|{Real4})
-InvalidReal {DecimalDigit}+[\.]{Exponent}?{RealSuffix}?
-
-AvailableIdentifier {Letter}({Letter}|{DecimalDigit})*
-Verbatim_identifier [@]{Letter}({Letter}|{DecimalDigit})*
-Identifier ({AvailableIdentifier}|{Verbatim_identifier})
-
-ppPrefix ^{Whitespace}?[#]{Whitespace}?
-ppNewLine {Whitespace}?{LineComment}?[\n]
-
-
-%x IN_BLOCKCOMMENT
-%x PP_EXPECT_NEW_LINE
-%x PP_DECLARATION
-%x PP_IF_CLAUSE
-%x PP_LINE
-%x PP_MESSAGE
-%x PP_PRAGMA
-%x PP_SKIPPED_SECTION_PART
-
-%%
-
- /* whitespace, newlines and comments */
-
-{Whitespace} /* skip */ ;
-[\n] /* skip */ ;
-
-{LineComment} /* line comments, skip */ ;
-
-"/*" BEGIN(IN_BLOCKCOMMENT);
-<IN_BLOCKCOMMENT>{
-[^*\n]* /* eat anything that's not a '*' */ ;
-"*"+[^*/\n]* /* eat up '*'s that are not followed by slashes or newlines */;
-[\n] /* skip */ ;
-"*"+"/" BEGIN(INITIAL);
-<<EOF>> {
- m_parser->reportProblem( Parser::error,
- "Encountered end of file in an unclosed block comment" );
- cleanup();
- return Parser::Token_EOF;
-}
-}
-
-
- /* seperators */
-
-"(" return Parser::Token_LPAREN;
-")" return Parser::Token_RPAREN;
-"{" return Parser::Token_LBRACE;
-"}" return Parser::Token_RBRACE;
-"[" return Parser::Token_LBRACKET;
-"]" return Parser::Token_RBRACKET;
-"," return Parser::Token_COMMA;
-";" return Parser::Token_SEMICOLON;
-"." return Parser::Token_DOT;
-
-
- /* operators */
-
-":" return Parser::Token_COLON;
-"::" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
- return Parser::Token_SCOPE;
- }
- else {
- m_parser->reportProblem( Parser::error,
- "Global alias access (with \"::\") is not supported by C# 1.0" );
- return Parser::Token_INVALID;
- }
-}
-"?" return Parser::Token_QUESTION;
-"??" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
- return Parser::Token_QUESTIONQUESTION;
- }
- else {
- m_parser->reportProblem( Parser::error,
- "Null coalescing expressions (with \"??\") are not supported by C# 1.0" );
- return Parser::Token_INVALID;
- }
-}
-"!" return Parser::Token_BANG;
-"~" return Parser::Token_TILDE;
-"==" return Parser::Token_EQUAL;
-"<" return Parser::Token_LESS_THAN;
-"<=" return Parser::Token_LESS_EQUAL;
-">" return Parser::Token_GREATER_THAN;
-">=" return Parser::Token_GREATER_EQUAL;
-"!=" return Parser::Token_NOT_EQUAL;
-"&&" return Parser::Token_LOG_AND;
-"||" return Parser::Token_LOG_OR;
-"->" return Parser::Token_ARROW_RIGHT; // TODO: new in 2.0 or not?
-"++" return Parser::Token_INCREMENT;
-"--" return Parser::Token_DECREMENT;
-"=" return Parser::Token_ASSIGN;
-"+" return Parser::Token_PLUS;
-"+=" return Parser::Token_PLUS_ASSIGN;
-"-" return Parser::Token_MINUS;
-"-=" return Parser::Token_MINUS_ASSIGN;
-"*" return Parser::Token_STAR;
-"*=" return Parser::Token_STAR_ASSIGN;
-"/" return Parser::Token_SLASH;
-"/=" return Parser::Token_SLASH_ASSIGN;
-"&" return Parser::Token_BIT_AND;
-"&=" return Parser::Token_BIT_AND_ASSIGN;
-"|" return Parser::Token_BIT_OR;
-"|=" return Parser::Token_BIT_OR_ASSIGN;
-"^" return Parser::Token_BIT_XOR;
-"^=" return Parser::Token_BIT_XOR_ASSIGN;
-"%" return Parser::Token_REMAINDER;
-"%=" return Parser::Token_REMAINDER_ASSIGN;
-"<<" return Parser::Token_LSHIFT;
-"<<=" return Parser::Token_LSHIFT_ASSIGN;
-">>" return Parser::Token_RSHIFT;
-">>=" return Parser::Token_RSHIFT_ASSIGN;
-
-
- /* reserved words */
-
-"abstract" return Parser::Token_ABSTRACT;
-"as" return Parser::Token_AS;
-"base" return Parser::Token_BASE;
-"bool" return Parser::Token_BOOL;
-"break" return Parser::Token_BREAK;
-"byte" return Parser::Token_BYTE;
-"case" return Parser::Token_CASE;
-"catch" return Parser::Token_CATCH;
-"char" return Parser::Token_CHAR;
-"checked" return Parser::Token_CHECKED;
-"class" return Parser::Token_CLASS;
-"const" return Parser::Token_CONST;
-"continue" return Parser::Token_CONTINUE;
-"decimal" return Parser::Token_DECIMAL;
-"default" return Parser::Token_DEFAULT;
-"delegate" return Parser::Token_DELEGATE;
-"do" return Parser::Token_DO;
-"double" return Parser::Token_DOUBLE;
-"else" return Parser::Token_ELSE;
-"enum" return Parser::Token_ENUM;
-"event" return Parser::Token_EVENT;
-"explicit" return Parser::Token_EXPLICIT;
-"extern" return Parser::Token_EXTERN;
-"false" return Parser::Token_FALSE;
-"finally" return Parser::Token_FINALLY;
-"fixed" return Parser::Token_FIXED;
-"float" return Parser::Token_FLOAT;
-"for" return Parser::Token_FOR;
-"foreach" return Parser::Token_FOREACH;
-"goto" return Parser::Token_GOTO;
-"if" return Parser::Token_IF;
-"implicit" return Parser::Token_IMPLICIT;
-"in" return Parser::Token_IN;
-"int" return Parser::Token_INT;
-"interface" return Parser::Token_INTERFACE;
-"internal" return Parser::Token_INTERNAL;
-"is" return Parser::Token_IS;
-"lock" return Parser::Token_LOCK;
-"long" return Parser::Token_LONG;
-"namespace" return Parser::Token_NAMESPACE;
-"new" return Parser::Token_NEW;
-"null" return Parser::Token_NULL;
-"object" return Parser::Token_OBJECT;
-"operator" return Parser::Token_OPERATOR;
-"out" return Parser::Token_OUT;
-"override" return Parser::Token_OVERRIDE;
-"params" return Parser::Token_PARAMS;
-"private" return Parser::Token_PRIVATE;
-"protected" return Parser::Token_PROTECTED;
-"public" return Parser::Token_PUBLIC;
-"readonly" return Parser::Token_READONLY;
-"ref" return Parser::Token_REF;
-"return" return Parser::Token_RETURN;
-"sbyte" return Parser::Token_SBYTE;
-"sealed" return Parser::Token_SEALED;
-"short" return Parser::Token_SHORT;
-"sizeof" return Parser::Token_SIZEOF;
-"stackalloc" return Parser::Token_STACKALLOC;
-"static" return Parser::Token_STATIC;
-"string" return Parser::Token_STRING;
-"struct" return Parser::Token_STRUCT;
-"switch" return Parser::Token_SWITCH;
-"this" return Parser::Token_THIS;
-"throw" return Parser::Token_THROW;
-"true" return Parser::Token_TRUE;
-"try" return Parser::Token_TRY;
-"typeof" return Parser::Token_TYPEOF;
-"uint" return Parser::Token_UINT;
-"ulong" return Parser::Token_ULONG;
-"unchecked" return Parser::Token_UNCHECKED;
-"unsafe" return Parser::Token_UNSAFE;
-"ushort" return Parser::Token_USHORT;
-"using" return Parser::Token_USING;
-"virtual" return Parser::Token_VIRTUAL;
-"void" return Parser::Token_VOID;
-"volatile" return Parser::Token_VOLATILE;
-"while" return Parser::Token_WHILE;
-
-
- /* Non-keyword identifiers. They only have special meaning in
- * specific contexts and are treated as identifiers otherwise.
- * Many of those have been introduced by C# 2.0. */
-
-"add" return Parser::Token_ADD;
-"alias" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
- return Parser::Token_ALIAS;
- else
- return Parser::Token_IDENTIFIER;
-}
-"get" return Parser::Token_GET;
-"global" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
- return Parser::Token_GLOBAL;
- else
- return Parser::Token_IDENTIFIER;
-}
-"partial" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
- return Parser::Token_PARTIAL;
- else
- return Parser::Token_IDENTIFIER;
-}
-"remove" return Parser::Token_REMOVE;
-"set" return Parser::Token_SET;
-"value" return Parser::Token_VALUE;
-"where" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
- return Parser::Token_WHERE;
- else
- return Parser::Token_IDENTIFIER;
-}
-"yield" {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility )
- return Parser::Token_YIELD;
- else
- return Parser::Token_IDENTIFIER;
-}
-
- /* A non-keyword identifier that is not marked as such by the specification,
- * for global attributes: */
-"assembly" return Parser::Token_ASSEMBLY;
-
-
- /* characters and strings */
-
-[']({Escape}|{Multibyte}|[^\\\n\'])['] return Parser::Token_CHARACTER_LITERAL;
-[']({Escape}|{Multibyte}|[\\][^\\\n\']|[^\\\n\'])*(([\\]?[\n])|[']) {
- m_parser->reportProblem( Parser::error,
- QString("Invalid character literal: %1").arg(yytext) );
- return Parser::Token_CHARACTER_LITERAL;
-}
-
-["]({Escape}|{Multibyte}|[^\\\n\"])*["] return Parser::Token_STRING_LITERAL;
-["]({Escape}|{Multibyte}|[\\][^\\\n\"]|[^\\\n\"])*(([\\]?[\n])|["]) {
- m_parser->reportProblem( Parser::error,
- QString("Invalid string literal: %1").arg(yytext) );
- return Parser::Token_STRING_LITERAL;
-}
- /* verbatim strings: */
-[@]["](["]["]|[^"])*["] return Parser::Token_STRING_LITERAL;
-
-
-
- /* the pre-processor */
-
-<INITIAL,PP_SKIPPED_SECTION_PART>{
-{ppPrefix}"define" BEGIN(PP_DECLARATION); PP_PROCESS_TOKEN(PP_DEFINE);
-{ppPrefix}"undef" BEGIN(PP_DECLARATION); PP_PROCESS_TOKEN(PP_UNDEF);
-{ppPrefix}"if" BEGIN(PP_IF_CLAUSE); PP_PROCESS_TOKEN(PP_IF);
-{ppPrefix}"elif" BEGIN(PP_IF_CLAUSE); PP_PROCESS_TOKEN(PP_ELIF);
-{ppPrefix}"else" BEGIN(PP_EXPECT_NEW_LINE); PP_PROCESS_TOKEN(PP_ELSE);
-{ppPrefix}"endif" BEGIN(PP_EXPECT_NEW_LINE); PP_PROCESS_TOKEN(PP_ENDIF);
-{ppPrefix}"line" BEGIN(PP_LINE); PP_PROCESS_TOKEN(PP_LINE);
-{ppPrefix}"error"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_ERROR);
-{ppPrefix}"warning"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_WARNING);
-{ppPrefix}"region"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_REGION);
-{ppPrefix}"endregion"{Whitespace}? BEGIN(PP_MESSAGE); PP_PROCESS_TOKEN(PP_ENDREGION);
-{ppPrefix}"pragma"{Whitespace}? {
- if( m_parser->compatibilityMode() >= Parser::CSharp20Compatibility ) {
- BEGIN(PP_PRAGMA); PP_PROCESS_TOKEN(PP_PRAGMA);
- }
- else {
- BEGIN(INITIAL);
- m_parser->reportProblem( Parser::error,
- "#pragma directives are not supported by C# 1.0" );
- return Parser::Token_INVALID;
- }
-}
-{ppPrefix}{Identifier} {
- m_parser->reportProblem( Parser::error,
- QString("Invalid pre-processor directive: ``%1").arg(yytext) + "''" );
- return Parser::Token_INVALID;
-}
-}
-
-<PP_EXPECT_NEW_LINE,PP_DECLARATION,PP_IF_CLAUSE,PP_LINE,PP_MESSAGE,PP_PRAGMA>{
-<<EOF>> {
- m_parser->reportProblem( Parser::warning,
- "No newline at the end of the file" );
- return CSharpPP::Parser::Token_EOF;
-}
-}
-
-<PP_EXPECT_NEW_LINE,PP_DECLARATION,PP_IF_CLAUSE,PP_LINE>{
-{Whitespace} /* skip */ ;
-{LineComment} /* before an unexpected EOF, skip */ ;
-}
-
-
-<PP_EXPECT_NEW_LINE>{
-{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
-. return CSharpPP::Parser::Token_PP_INVALID;
-}
-
-<PP_DECLARATION>{
-"true"|"false" {
- m_parser->reportProblem( Parser::error,
- "You may not define ``true'' or ``false'' with #define or #undef" );
- return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL; // we could do Token_INVALID here,
- // but this way the error is shown and the parser continues, I prefer this.
-}
-{Identifier} return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL; // ...including keywords
-{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
-. return CSharpPP::Parser::Token_PP_INVALID;
-}
-
-<PP_IF_CLAUSE>{
-"==" return CSharpPP::Parser::Token_PP_EQUAL;
-"!=" return CSharpPP::Parser::Token_PP_NOT_EQUAL;
-"&&" return CSharpPP::Parser::Token_PP_LOG_AND;
-"||" return CSharpPP::Parser::Token_PP_LOG_OR;
-"!" return CSharpPP::Parser::Token_PP_BANG;
-"true" return CSharpPP::Parser::Token_PP_TRUE;
-"false" return CSharpPP::Parser::Token_PP_FALSE;
-"(" return CSharpPP::Parser::Token_PP_LPAREN;
-")" return CSharpPP::Parser::Token_PP_RPAREN;
-{Identifier} return CSharpPP::Parser::Token_PP_CONDITIONAL_SYMBOL;
-{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
-. return CSharpPP::Parser::Token_PP_INVALID;
-}
-
-<PP_SKIPPED_SECTION_PART>{
- /* splitting the line at "#" keeps the token shorter than real directives, */
- /* so that those are recognized and not taken as skipped text as well. */
-[^#\n]* /* skip */ ;
-[#] /* skip */ ;
-[\n] /* skip */ ;
-}
-
-<PP_LINE>{
-{ppNewLine} return CSharpPP::Parser::Token_PP_NEW_LINE;
-{DecimalDigit}+ return CSharpPP::Parser::Token_PP_LINE_NUMBER;
-["][^\"\n]+["] return CSharpPP::Parser::Token_PP_FILE_NAME;
-"default" return CSharpPP::Parser::Token_PP_DEFAULT;
-{Identifier} return CSharpPP::Parser::Token_PP_IDENTIFIER_OR_KEYWORD;
-. return CSharpPP::Parser::Token_PP_INVALID;
-}
-
-<PP_MESSAGE>{
-[^\n]+ return CSharpPP::Parser::Token_PP_MESSAGE;
-[\n] return CSharpPP::Parser::Token_PP_NEW_LINE;
-}
-
-<PP_PRAGMA>{
-[^\n]+ return CSharpPP::Parser::Token_PP_PRAGMA_TEXT;
-[\n] return CSharpPP::Parser::Token_PP_NEW_LINE;
-}
-
-
- /* identifiers and number literals */
-
-{Identifier} return Parser::Token_IDENTIFIER;
-
-{IntegerLiteral} return Parser::Token_INTEGER_LITERAL;
-{RealLiteral} return Parser::Token_REAL_LITERAL;
-
-
- /* everything else is not a valid lexeme */
-
-. return Parser::Token_INVALID;
-
-
- /* some additional checking for unclosed #ifs and #regions at the EOF */
-
-<INITIAL,PP_SKIPPED_SECTION_PART>{
-<<EOF>> {
- cleanup();
- return Parser::Token_EOF;
-}
-}
-
-%%
-
-namespace CSharp
-{
-
-Lexer::Lexer( Parser *parser, ParseSession* session ) : m_ppRootScope(0)
-{
- restart( parser, session );
-}
-
-void Lexer::restart( Parser *parser, ParseSession* session )
-{
- cleanup();
-
- m_parser = parser;
- m_locationTable = parser->tokenStream->locationTable();
- m_session = session;
- m_ppRootScope = 0;
- m_tokenBegin = m_tokenEnd = 0;
- m_currentOffset = 0;
-
- // check for and ignore the UTF-8 byte order mark
- const unsigned char *ucontents = (const unsigned char *) contents();
- if ( ucontents[0] == 0xEF && ucontents[1] == 0xBB && ucontents[2] == 0xBF )
- {
- m_tokenBegin = m_tokenEnd = 3;
- m_currentOffset = 3;
- }
-
- yyrestart(NULL);
- BEGIN(INITIAL); // is not set automatically by yyrestart()
-}
-
-// reads a character, and returns 1 as the number of characters read
-// (or 0 when the end of the string is reached)
-int Lexer::LexerInput( char *buf, int /*maxSize*/ )
-{
- int c = contents()[ m_currentOffset++ ];
-
- switch(c)
- {
- case '\r':
- c = '\n'; // only have one single line break character: '\n'
- if ( contents()[m_currentOffset + 1] == '\n' )
- {
- m_currentOffset++;
- m_tokenEnd++;
- }
-
- // fall through
- case '\n':
- m_locationTable->newline( m_currentOffset );
- break;
-
- default:
- break;
- }
-
- return (c == 0) ? 0 : (buf[0] = c, 1);
-}
-
-CSharpPP::Scope* Lexer::ppCurrentScope()
-{
- if ( m_ppRootScope == 0 )
- {
- m_ppRootScope = new CSharpPP::Scope( m_parser );
- }
- return m_ppRootScope->currentScope();
-}
-
-void Lexer::cleanup()
-{
- // check for open Scopes, and pop them / report errors as needed
- if (m_ppRootScope != 0)
- {
- CSharpPP::Scope* currentScope = ppCurrentScope();
- CSharpPP::Scope::ScopeType ScopeType = currentScope->type();
-
- while ( ScopeType != CSharpPP::Scope::TypeRoot )
- {
- if ( ScopeType == CSharpPP::Scope::TypeIf )
- {
- m_parser->reportProblem( Parser::error,
- "Encountered end of file in an unclosed #if/#elif/#else section" );
- }
- else if ( ScopeType == CSharpPP::Scope::TypeRegion )
- {
- m_parser->reportProblem( Parser::error,
- "Encountered end of file in an unclosed #region section" );
- }
-
- if ( !currentScope->popScope(ScopeType, &currentScope) )
- break;
-
- ScopeType = currentScope->type();
- }
-
- delete m_ppRootScope;
- m_ppRootScope = 0;
- }
-}
-
-const char *Lexer::contents() const
-{
- return m_session->contents();
-}
-
-} // end of namespace CSharp
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.cpp (nonexistent)
@@ -1,265 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-#include "csharppphandlervisitor.h"
-#include "csharpppparser.h"
-#include "csharpppscope.h"
-#include "parsesession.h"
-
-#include <QString>
-
-
-namespace CSharpPP
-{
-
-HandlerVisitor::HandlerVisitor(CSharp::ParseSession* session)
- : DefaultVisitor(), m_session(session), m_scope(0)
-{
-}
-
-HandlerVisitor::~HandlerVisitor()
-{
-}
-
-void HandlerVisitor::setScope(Scope* currentScope)
-{
- m_scope = currentScope;
-}
-
-
-
-void HandlerVisitor::visitPPDeclaration(PPDeclarationAst* node)
-{
- if (m_scope == 0 || m_session == 0)
- return;
- else if (m_scope->isActive() == false)
- return; // don't do anything if the current section is #if'd out.
-
- QString symbolName = m_session->symbol(node->conditionalSymbol);
-
- if (node->type == PPDeclaration::TypeDefine)
- m_scope->csharpParser()->ppDefineSymbol(symbolName);
- else if (node->type == PPDeclaration::TypeUndef)
- m_scope->csharpParser()->ppUndefineSymbol(symbolName);
-}
-
-void HandlerVisitor::visitPPIfClause(PPIfClauseAst* node)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- m_scope->pushScope(Scope::TypeIf, &m_scope);
-
- if (m_scope->isActive() == false)
- return;
- else if (m_scope->isWaitingForActiveSection())
- {
- visitNode(node->expression);
- m_scope->setActivated(m_expressionBool);
- }
- else
- m_scope->setActivated(false);
-}
-
-void HandlerVisitor::visitPPElifClause(PPElifClauseAst* node)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- if (m_scope->type() != Scope::TypeIf)
- {
- m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
- "#elif is unexpected here");
- }
-
- if (m_scope->isWaitingForActiveSection())
- {
- visitNode(node->expression);
- m_scope->setActivated(m_expressionBool);
- }
- else
- m_scope->setActivated(false);
-}
-
-void HandlerVisitor::visitPPElseClause(PPElseClauseAst*)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- if (m_scope->type() != Scope::TypeIf)
- {
- m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
- "#else is unexpected here");
- }
-
- if (m_scope->isWaitingForActiveSection())
- m_scope->setActivated(true);
- else
- m_scope->setActivated(false);
-}
-
-void HandlerVisitor::visitPPEndifClause(PPEndifClauseAst*)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- bool successful = m_scope->popScope( Scope::TypeIf, &m_scope );
- if (!successful && m_scope->csharpParser() != 0)
- {
- m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
- "#endif is unexpected here");
- }
-}
-
-void HandlerVisitor::visitPPDiagnostic(PPDiagnosticAst* node)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- if (!m_scope->csharpParser() != 0)
- {
- ::CSharp::Parser::ProblemType diagnosticType;
- if (node->type == PPDiagnostic::TypeError)
- diagnosticType = ::CSharp::Parser::error;
- else // if (node->type == PPDiagnostic::TypeWarning)
- diagnosticType = ::CSharp::Parser::warning;
-
- if (node->message)
- {
- m_scope->csharpParser()->ppDiagnostic( diagnosticType, m_session->symbol(node->message) );
- }
- else
- m_scope->csharpParser()->ppDiagnostic( diagnosticType );
- }
-}
-
-void HandlerVisitor::visitPPRegion(PPRegionAst* node)
-{
- if (m_scope == 0 || m_session == 0)
- return;
-
- if (node->type == PPRegion::TypeRegion)
- {
- m_scope->pushScope( Scope::TypeRegion, &m_scope );
- }
- if (node->type == PPRegion::TypeEndregion)
- {
- bool successful = m_scope->popScope( Scope::TypeRegion, &m_scope );
- if (!successful && m_scope->csharpParser() != 0)
- {
- m_scope->csharpParser()->reportProblem( ::CSharp::Parser::error,
- "#endregion is unexpected here");
- }
- }
-}
-
-void HandlerVisitor::visitPPLine(PPLineAst* node)
-{
- DefaultVisitor::visitPPLine(node);
-}
-
-void HandlerVisitor::visitPPPragma(PPPragmaAst* node)
-{
- DefaultVisitor::visitPPPragma(node);
-}
-
-
-void HandlerVisitor::visitPPExpression(PPExpressionAst* node)
-{
- bool result = false;
- const KDevPG::ListNode<PPAndExpressionAst*> *_It =
- node->expressionSequence->front(), *_End = _It;
-
- do
- {
- visitNode(_It->element);
- _It = _It->next;
-
- result = result || m_expressionBool;
- // PPExpression is actually PPOrExpression
- }
- while (_It != _End && result == false);
-
- m_expressionBool = result;
-}
-
-void HandlerVisitor::visitPPAndExpression(PPAndExpressionAst* node)
-{
- bool result = true;
- const KDevPG::ListNode<PPEqualityExpressionAst*> *_It =
- node->expressionSequence->front(), *_End = _It;
-
- do
- {
- visitNode(_It->element);
- _It = _It->next;
-
- result = result && m_expressionBool;
- }
- while (_It != _End && result == true);
-
- m_expressionBool = result;
-}
-
-void HandlerVisitor::visitPPEqualityExpression(PPEqualityExpressionAst* node)
-{
- DefaultVisitor::visitPPEqualityExpression(node);
- // the child visit_*() methods assign the right value to m_expressionBool
-}
-
-void HandlerVisitor::visitPPEqualityExpressionRest(PPEqualityExpressionRestAst* node)
-{
- bool previous = m_expressionBool;
- visitNode(node->expression);
- if (node->equalityOperator == PPEqualityExpressionRest::opEqual)
- m_expressionBool = (previous == m_expressionBool);
- else // opNotEqual
- m_expressionBool = (previous != m_expressionBool);
-}
-
-void HandlerVisitor::visitPPUnaryExpression(PPUnaryExpressionAst* node)
-{
- DefaultVisitor::visitPPUnaryExpression(node);
-
- if (node->negated == true)
- m_expressionBool = !m_expressionBool;
-}
-
-void HandlerVisitor::visitPPPrimaryExpression(PPPrimaryExpressionAst* node)
-{
- switch (node->type)
- {
- case PPPrimaryExpression::TypeTrue:
- m_expressionBool = true;
- break;
- case PPPrimaryExpression::TypeFalse:
- m_expressionBool = false;
- break;
- case PPPrimaryExpression::TypeConditionalSymbol:
- {
- m_expressionBool = m_scope->csharpParser()->ppIsSymbolDefined(m_session->symbol(node->conditionalSymbol));
- }
- break;
- case PPPrimaryExpression::TypeParenthesisExpression:
- DefaultVisitor::visitNode(node->parenthesisExpression);
- break;
- }
-}
-
-} // end of namespace CSharpPP
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharppphandlervisitor.h (nonexistent)
@@ -1,71 +0,0 @@
-/*****************************************************************************
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at> *
- * *
- * This program 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 grammar 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 *
- * Lesser 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. *
- *****************************************************************************/
-
-#ifndef CSHARP_PP_HANDLER_VISITOR_H
-#define CSHARP_PP_HANDLER_VISITOR_H
-
-#include "csharpppdefaultvisitor.h"
-
-namespace CSharp
-{
-class ParseSession;
-}
-
-namespace CSharpPP
-{
-
-class Scope;
-
-
-class HandlerVisitor : public DefaultVisitor
-{
-public:
- HandlerVisitor( CSharp::ParseSession* session );
- ~HandlerVisitor();
-
- void setScope( Scope* currentScope );
-
- virtual void visitPPDeclaration(PPDeclarationAst* node);
- virtual void visitPPIfClause(PPIfClauseAst* node);
- virtual void visitPPElifClause(PPElifClauseAst* node);
- virtual void visitPPElseClause(PPElseClauseAst* node);
- virtual void visitPPEndifClause(PPEndifClauseAst* node);
- virtual void visitPPDiagnostic(PPDiagnosticAst* node);
- virtual void visitPPRegion(PPRegionAst* node);
- virtual void visitPPLine(PPLineAst* node);
- virtual void visitPPPragma(PPPragmaAst* node);
-
- virtual void visitPPExpression(PPExpressionAst* node);
- virtual void visitPPAndExpression(PPAndExpressionAst* node);
- virtual void visitPPEqualityExpression(PPEqualityExpressionAst* node);
- virtual void visitPPEqualityExpressionRest(PPEqualityExpressionRestAst* node);
- virtual void visitPPUnaryExpression(PPUnaryExpressionAst* node);
- virtual void visitPPPrimaryExpression(PPPrimaryExpressionAst* node);
-
-private:
- CSharp::ParseSession* m_session;
- Scope* m_scope;
-
- /** Temporary variable for evaluating #if and #elif conditions. */
- bool m_expressionBool;
-};
-
-} // end of namespace CSharp_PP
-
-#endif // CSHARP_PP_HANDLER_VISITOR_H
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parser/csharpparserexport.h (nonexistent)
@@ -1,36 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef CSHARPPARSEREXPORT_H
-#define CSHARPPARSEREXPORT_H
-
-/* needed for KDE_EXPORT macros */
-#include <kdemacros.h>
-
-#ifndef KDEVCSHARPPARSER_EXPORT
-# ifdef MAKE_KDEVCSHARPPARSER_LIB
-# define KDEVCSHARPPARSER_EXPORT KDE_EXPORT
-# else
-# define KDEVCSHARPPARSER_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/Messages.sh (nonexistent)
@@ -1,7 +0,0 @@
-#!/bin/sh
-files=`find . -name \*.rc -o -name \*.ui`
-if [ "x$files" != "x" ]; then
- $EXTRACTRC $files >> rc.cpp
-fi
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevcsharp.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/CMakeLists.txt (nonexistent)
@@ -1,60 +0,0 @@
-project(csharp)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${csharp_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-include (KDE4Defaults)
-include (MacroLibrary)
-include (MacroOptionalAddSubdirectory)
-
-find_package(KDevPlatform REQUIRED)
-
-add_subdirectory(parser)
-
-include_directories(
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_SOURCE_DIR}/parser
- ${CMAKE_CURRENT_BINARY_DIR}/parser
- ${KDE4_INCLUDE_DIR}/threadweaver
- ${KDE4_INCLUDE_DIR}/kdevelop-pg-qt
- ${KDEVPLATFORM_INCLUDE_DIR}
-)
-
-
-########### next target ###############
-
-add_definitions( ${QT_DEFINITIONS} ${KDE4_DEFINITIONS} -DKDE_DEFAULT_DEBUG_AREA=9044 )
-
-set(kdevcsharplanguagesupport_PART_SRCS
- csharplanguagesupport.cpp
- parsejob.cpp
-
- duchain/editorintegrator.cpp
- duchain/identifiercompiler.cpp
- duchain/contextbuilder.cpp
- duchain/declarationbuilder.cpp
- duchain/usebuilder.cpp
- duchain/dumpchain.cpp
- duchain/typebuilder.cpp
-)
-
-kde4_add_plugin(kdevcsharplanguagesupport ${kdevcsharplanguagesupport_PART_SRCS})
-target_link_libraries(kdevcsharplanguagesupport
- ${QT_QTDESIGNER_LIBRARY}
- ${KDE4_KTEXTEDITOR_LIBS}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDEVPLATFORM_PROJECT_LIBRARIES}
- ${KDE4_THREADWEAVER_LIBRARIES}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
- ${KDE4_KDEUI_LIBS}
- kdev4csharpparser
-)
-
-install(TARGETS kdevcsharplanguagesupport DESTINATION ${PLUGIN_INSTALL_DIR})
-
-
-########### install files ###############
-
-install(FILES kdevcsharpsupport.desktop DESTINATION ${SERVICES_INSTALL_DIR})
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.cpp (nonexistent)
@@ -1,96 +0,0 @@
-/* This file is part of KDevelop
-Copyright (C) 2006 Adam Treat <treat@kde.org>
-Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
-
-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.
-*/
-
-#include "csharplanguagesupport.h"
-
-#include <kdebug.h>
-#include <kcomponentdata.h>
-#include <kstandarddirs.h>
-#include <kgenericfactory.h>
-
-#include <QExtensionFactory>
-
-#include <interfaces/icore.h>
-#include <interfaces/ilanguagecontroller.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/iprojectcontroller.h>
-#include <language/backgroundparser/backgroundparser.h>
-#include <interfaces/iproject.h>
-
-#include "parsejob.h"
-
-K_PLUGIN_FACTORY(KDevCSharpSupportFactory, registerPlugin<CSharpLanguageSupport>(); )
-K_EXPORT_PLUGIN(KDevCSharpSupportFactory("kdevcsharpsupport"))
-
-using namespace CSharp;
-
-CSharpLanguageSupport::CSharpLanguageSupport( QObject* parent, const QVariantList& /*args*/ )
- : KDevelop::IPlugin( KDevCSharpSupportFactory::componentData(), parent )
- , KDevelop::ILanguageSupport()
-{
- KDEV_USE_EXTENSION_INTERFACE( KDevelop::ILanguageSupport )
-
- connect( core()->projectController(),
- SIGNAL( projectOpened(KDevelop::IProject*) ),
- this, SLOT( projectOpened(KDevelop::IProject*) ) );
- connect( core()->projectController(),
- SIGNAL( projectClosed() ),
- this, SLOT( projectClosed() ) );
-
- kDebug() << "CSharp support loaded";
-}
-
-CSharpLanguageSupport::~CSharpLanguageSupport()
-{}
-
-KDevelop::ParseJob *CSharpLanguageSupport::createParseJob( const KUrl &url )
-{
- return new ParseJob( url, this );
-}
-
-void CSharpLanguageSupport::projectOpened(KDevelop::IProject *project)
-{
- foreach(KDevelop::IDocument* doc, core()->documentController()->openDocuments()) {
- if (project->inProject(doc->url())) {
- QString path = doc->url().path();
-
- core()->languageController()->backgroundParser()->addDocument(doc->url());
- }
- }
-}
-
-void CSharpLanguageSupport::projectClosed()
-{
- // FIXME This should remove the project files from the backgroundparser
-}
-
-KDevelop::ILanguage * CSharpLanguageSupport::language()
-{
- return core()->languageController()->language(name());
-}
-
-QString CSharpLanguageSupport::name() const
-{
- return "C#";
-}
-
-#include "csharplanguagesupport.moc"
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/csharplanguagesupport.h (nonexistent)
@@ -1,54 +0,0 @@
-/* This file is part of KDevelop
-Copyright (C) 2006 Adam Treat <treat@kde.org>
-Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
-
-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.
-*/
-
-#ifndef KDEVCSHARPLANGUAGESUPPORT_H
-#define KDEVCSHARPLANGUAGESUPPORT_H
-
-#include <interfaces/iplugin.h>
-#include <language/interfaces/ilanguagesupport.h>
-
-namespace KDevelop {
-class IDocument;
-class IProject;
-}
-
-class CSharpLanguageSupport : public KDevelop::IPlugin, public KDevelop::ILanguageSupport
-{
-Q_OBJECT
-Q_INTERFACES( KDevelop::ILanguageSupport )
-public:
- CSharpLanguageSupport( QObject *parent, const QVariantList& args = QVariantList() );
- virtual ~CSharpLanguageSupport();
-
- virtual QString name() const;
-
- virtual KDevelop::ParseJob *createParseJob(const KUrl &url);
- virtual KDevelop::ILanguage *language();
-
-private slots:
- void projectOpened(KDevelop::IProject *project);
- void projectClosed();
-
-private:
-};
-
-#endif
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/kdevcsharpsupport.desktop (nonexistent)
@@ -1,85 +0,0 @@
-[Desktop Entry]
-Encoding=UTF-8
-Type=Service
-Exec=blubb
-Comment=CSharp Language Support
-Comment[bs]=CSharp jezička podrška
-Comment[ca]=Implementació del llenguatge CSharp
-Comment[ca@valencia]=Implementació del llenguatge CSharp
-Comment[de]=Sprachunterstützung für CSharp
-Comment[el]=Υποστήριξη γλώσσας CSharp
-Comment[en_GB]=CSharp Language Support
-Comment[es]=Implementación del lenguaje CSharp
-Comment[et]=CSharpi keele toetus
-Comment[fr]=Prise en charge du langage C#
-Comment[ga]=Tacaíocht C#
-Comment[gl]=Compatibilidade coa linguaxe CSharp
-Comment[hne]=सी# भाखा समर्थन
-Comment[it]=Supporto per il linguaggio CSharp
-Comment[ja]=CSharp 言語のサポート
-Comment[nds]=Ünnerstütten för C-Sharp
-Comment[nl]=Ondersteuning voor de taal CSharp
-Comment[pl]=Obsługa języka CSharp
-Comment[pt]=Suporte à Linguagem C#
-Comment[pt_BR]=Suporte à linguagem CSharp
-Comment[sv]=Stöd för språket C#
-Comment[tr]=CSharp Dil Desteği
-Comment[uk]=Підтримка мови C#
-Comment[x-test]=xxCSharp Language Supportxx
-Name=CSharp Support
-Name[bs]=CSharp podrška
-Name[ca]=Implementació de CSharp
-Name[ca@valencia]=Implementació de CSharp
-Name[de]=Unterstützung für CSharp
-Name[en_GB]=CSharp Support
-Name[es]=Implementación de CSharp
-Name[et]=CSharpi toetus
-Name[fr]=Prise en charge de CSharp
-Name[ga]=Tacaíocht C#
-Name[gl]=Compatibilidade con CSharp
-Name[hu]=CSharp támogatás
-Name[it]=Supporto per CSharp
-Name[nl]=Ondersteuning voor CSharp
-Name[pl]=Obsługa CSharp
-Name[pt]=Suporte a C#
-Name[pt_BR]=Suporte a CSharp
-Name[sv]=C#-stöd
-Name[ug]=CSharp قوللىشى
-Name[uk]=Підтримка CSharp
-Name[x-test]=xxCSharp Supportxx
-GenericName=CSharp Support
-GenericName[bs]=CSharp podrška
-GenericName[ca]=Implementació de CSharp
-GenericName[ca@valencia]=Implementació de CSharp
-GenericName[de]=Unterstützung für CSharp
-GenericName[el]=Υποστήριξη CSharp
-GenericName[en_GB]=CSharp Support
-GenericName[es]=Implementación de CSharp
-GenericName[et]=CSharpi toetus
-GenericName[fr]=Prise en charge du langage C#
-GenericName[ga]=Tacaíocht C#
-GenericName[gl]=Compatibilidade con CSharp
-GenericName[hne]=केडेवसीसार्पसपोर्ट
-GenericName[hu]=CSharp támogatás
-GenericName[it]=Supporto per CSharp
-GenericName[ja]=CSharp サポート
-GenericName[nds]=C-Sharp-Ünnerstütten
-GenericName[nl]=Ondersteuning voor CSharp
-GenericName[pl]=Obsługa CSharp
-GenericName[pt]=Suporte a C#
-GenericName[pt_BR]=Suporte a CSharp
-GenericName[sv]=C#-stöd
-GenericName[tr]=CSharp Desteği
-GenericName[ug]=CSharp قوللىشى
-GenericName[uk]=Підтримка CSharp
-GenericName[x-test]=xxCSharp Supportxx
-ServiceTypes=KDevelop/Plugin
-Icon=source
-X-KDE-Library=kdevcsharplanguagesupport
-X-KDE-PluginInfo-Name=kdevcsharplanguagesupport
-X-KDevelop-Version=7
-X-KDevelop-Language=C#
-X-KDevelop-Args=C#
-X-KDevelop-Interfaces=ILanguageSupport
-X-KDevelop-SupportedMimeTypes=text/x-csharp
-X-KDevelop-Mode=NoGUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.cpp (nonexistent)
@@ -1,222 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright (c) 2006 Adam Treat <treat@kde.org>
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
- * Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "parsejob.h"
-
-#include <cassert>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-
-#include "Thread.h"
-
-#include <QFile>
-#include <QFileInfo>
-#include <QByteArray>
-#include <QReadLocker>
-
-#include <kdebug.h>
-#include <klocale.h>
-
-#include <KTextEditor/SmartInterface>
-
-#include <interfaces/ilanguage.h>
-#include <language/interfaces/icodehighlighting.h>
-
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-
-// from the parser subdirectory
-#include <parsesession.h>
-#include <csharpparser.h>
-
-#include "csharplanguagesupport.h"
-#include "csharpdebugvisitor.h"
-
-#include "duchain/declarationbuilder.h"
-#include "duchain/usebuilder.h"
-#include "duchain/editorintegrator.h"
-#include "duchain/dumpchain.h"
-
-namespace CSharp
-{
-
-ParseJob::ParseJob( const KUrl &url, CSharpLanguageSupport *parent )
- : KDevelop::ParseJob( url, parent )
- , m_session( new ParseSession )
- , m_AST( 0 )
- , m_readFromDisk( false )
-{}
-
-#if 0
-ParseJob::ParseJob( KDevelop::Document *document, CSharpLanguageSupport *parent )
- : KDevelop::ParseJob( document, parent )
- , m_session( new ParseSession )
- , m_AST( 0 )
- , m_readFromDisk( false )
-{}
-#endif
-
-ParseJob::~ParseJob()
-{}
-
-CSharpLanguageSupport* ParseJob::csharp() const
-{
- return static_cast<CSharpLanguageSupport*>(const_cast<QObject*>(parent()));
-}
-
-CSharp::AstNode *ParseJob::AST() const
-{
- Q_ASSERT ( isFinished () && m_AST );
- return m_AST;
-}
-
-ParseSession *ParseJob::parseSession() const
-{
- return m_session;
-}
-
-bool ParseJob::wasReadFromDisk() const
-{
- return m_readFromDisk;
-}
-
-void ParseJob::run()
-{
- if ( abortRequested())
- return abortJob();
-
- QReadLocker lock(csharp()->language()->parseLock());
-
- m_readFromDisk = !contentsAvailableFromEditor();
-
- QString localFile(KUrl(document().str()).toLocalFile());
-
- QFileInfo fileInfo( localFile );
-
- if ( m_readFromDisk )
- {
- QFile file( localFile );
- if ( !file.open( QIODevice::ReadOnly ) )
- {
- KDevelop::ProblemPointer p(new KDevelop::Problem());
- p->setSource(KDevelop::ProblemData::Disk);
- p->setDescription(i18n( "Could not open file '%1'", localFile ));
- switch (file.error()) {
- case QFile::ReadError:
- p->setExplanation(i18n("File could not be read from."));
- break;
- case QFile::OpenError:
- p->setExplanation(i18n("File could not be opened."));
- break;
- case QFile::PermissionsError:
- p->setExplanation(i18n("File permissions prevent opening for read."));
- break;
- default:
- break;
- }
- p->setFinalLocation(KDevelop::DocumentRange(document().str(), KTextEditor::Cursor(0,0), KTextEditor::Cursor(0,0)));
- // TODO addProblem(p);
- kWarning( ) << "Could not open file " << document().str() << " (path " << fileInfo.filePath() << ")";
- return ;
- }
-
- m_session->setContents( file.readAll() );
- Q_ASSERT ( m_session->size() > 0 );
- file.close();
- }
- else
- {
- m_session->setContents( contentsFromEditor().toAscii() );
- }
-
- kDebug() << "===-- PARSING --===> "
- << document().str()
- << " <== readFromDisk: " << m_readFromDisk
- << " size: " << m_session->size()
- << endl;
-
- if ( abortRequested() )
- return abortJob();
-
- // 0) setup
- Parser csharpParser;
- csharpParser.setCompatibilityMode( m_session->compatibilityMode );
- csharpParser.setTokenStream( m_session->tokenStream );
- csharpParser.setMemoryPool( m_session->memoryPool );
-
- // 1) tokenize
- csharpParser.tokenize( m_session );
-
- if ( abortRequested() )
- return abortJob();
-
- // 2) parse
- csharpParser.parseCompilationUnit( &m_AST );
-
- if ( abortRequested() )
- return abortJob();
-
- DebugVisitor debug(m_session->tokenStream, QString::fromUtf8(m_session->contents()));
- debug.visitNode(m_AST);
-
- if ( abortRequested() )
- return abortJob();
-
- // 3) Form definition-use chain
- CSharp::EditorIntegrator editor(parseSession());
- editor.setCurrentUrl(document());
-
- //kDebug( ) << (contentContext ? "updating" : "building") << "duchain for" << parentJob()->document().str();
-
- DeclarationBuilder builder(&editor);
- KDevelop::TopDUContext* chain = builder.build(document(), m_AST);
- setDuChain(chain);
-
- if ( abortRequested() )
- return abortJob();
-
- UseBuilder useBuilder(&editor);
- useBuilder.buildUses(m_AST);
-
- /*if (!abortRequested() && editor.smart()) {
- editor.smart()->clearRevision();
-
- if ( csharp()->codeHighlighting() )
- {
- QMutexLocker lock(editor.smart()->smartMutex());
- csharp()->codeHighlighting()->highlightDUChain( chain );
- }
- }*/
-
- KDevelop::DUChainReadLocker duchainlock(KDevelop::DUChain::lock());
-
- DumpChain dump;
- dump.dump(chain);
-}
-
-} // end of namespace CSharp
-
-#include "parsejob.moc"
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/parsejob.h (nonexistent)
@@ -1,74 +0,0 @@
-/*
- * This file is part of KDevelop
- *
- * Copyright (c) 2006 Adam Treat <treat@kde.org>
- * Copyright (c) 2006 Jakob Petsovits <jpetso@gmx.at>
- * Copyright (C) 2008 Hamish Rodda <rodda@kde.org>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef CSHARP_PARSEJOB_H
-#define CSHARP_PARSEJOB_H
-
-#include <kurl.h>
-#include <language/backgroundparser/parsejob.h>
-
-namespace KDevelop {
-class Document;
-}
-
-class CSharpLanguageSupport;
-
-namespace CSharp
-{
-
-class ParseSession;
-class CompilationUnitAst;
-class AstNode;
-
-class ParseJob : public KDevelop::ParseJob
-{
- Q_OBJECT
-
-public:
- ParseJob( const KUrl &url, CSharpLanguageSupport* parent );
- //ParseJob( KDevelop::Document* document, CSharpLanguageSupport* parent );
-
- virtual ~ParseJob();
-
- CSharpLanguageSupport* csharp() const;
-
- ParseSession* parseSession() const;
-
- bool wasReadFromDisk() const;
-
- virtual AstNode *AST() const;
-
-protected:
- virtual void run();
-
-private:
- ParseSession *m_session;
- CompilationUnitAst *m_AST;
- bool m_readFromDisk;
-};
-
-} // end of namespace CSharp
-
-#endif
-
-// kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.cpp (nonexistent)
@@ -1,285 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "contextbuilder.h"
-
-#include <language/duchain/duchain.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/duchainlock.h>
-
-#include "parsesession.h"
-#include "editorintegrator.h"
-#include "identifiercompiler.h"
-
-using namespace KTextEditor;
-using namespace KDevelop;
-
-namespace CSharp {
-
-ContextBuilder::ContextBuilder()
- : m_identifierCompiler(0), m_mapAst(false)
-{
-}
-
-void ContextBuilder::setEditor(EditorIntegrator* editor)
-{
- m_identifierCompiler = new IdentifierCompiler(editor->parseSession());
- ContextBuilderBase::setEditor(editor, false);
-}
-
-void ContextBuilder::setEditor(ParseSession* session)
-{
- EditorIntegrator* e = new EditorIntegrator(session);
- m_identifierCompiler = new IdentifierCompiler(e->parseSession());
- ContextBuilderBase::setEditor(e, false);
-}
-
-ContextBuilder::~ContextBuilder ()
-{
- delete m_identifierCompiler;
-}
-
-void ContextBuilder::startVisiting( AstNode* node )
-{
- visitNode(node);
-}
-
-void ContextBuilder::setContextOnNode( AstNode* node, KDevelop::DUContext* ctx )
-{
- node->ducontext = ctx;
-}
-
-KDevelop::DUContext* ContextBuilder::contextFromNode( AstNode* node )
-{
- return node->ducontext;
-}
-
-EditorIntegrator* ContextBuilder::editor() const
-{
- return static_cast<EditorIntegrator*>(ContextBuilderBase::editor());
-}
-
-KTextEditor::Range ContextBuilder::editorFindRange( AstNode* fromRange, AstNode* toRange )
-{
- return editor()->findRange(fromRange, toRange).textRange();
-}
-
-QualifiedIdentifier ContextBuilder::identifierForNode(AstNode* id)
-{
- if( !id )
- return QualifiedIdentifier();
-
- m_identifierCompiler->run(id);
-
- return m_identifierCompiler->identifier();
-}
-
-void ContextBuilder::visitClassDeclaration(ClassDeclarationAst * node)
-{
- visitNode(node->attributes);
- visitNode(node->modifiers);
-
- //visitNode(node->className);
- QualifiedIdentifier id = identifierForNode(node->className);
-
- visitNode(node->typeParameters);
- visitNode(node->classBase);
-
- if (node->typeParametersConstraintsSequence)
- {
- const KDevPG::ListNode<TypeParametersConstraintsClauseAst*> *__it = node->typeParametersConstraintsSequence->front(), *__end = __it;
- do
- {
- visitNode(__it->element);
- __it = __it->next;
- }
- while (__it != __end);
- }
-
- if (node->body) {
- openContext(node->body, DUContext::Class, id);
-
- visitNode(node->body);
-
- closeContext();
- }
-}
-
-void ContextBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
-{
- visitNode(node->attributes);
- visitNode(node->modifiers);
- visitNode(node->returnType);
-
- QualifiedIdentifier id = identifierForNode(node->methodName);
-
- visitNode(node->typeParameters);
-
- DUContext* parameters = 0;
- if (node->formalParameters) {
- parameters = openContext(node->formalParameters, DUContext::Other, id);
- id = currentContext()->localScopeIdentifier();
- visitNode(node->formalParameters);
- closeContext();
- }
-
- if (node->typeParametersConstraintsSequence)
- {
- const KDevPG::ListNode<TypeParametersConstraintsClauseAst*> *__it = node->typeParametersConstraintsSequence->front(), *__end = __it;
- do
- {
- visitNode(__it->element);
- __it = __it->next;
- }
- while (__it != __end);
- }
-
- DUContext* body = openContext(node->body, DUContext::Function, id);
- if (parameters) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(parameters);
- }
-
- visitNode(node->body);
-
- closeContext();
-}
-
-void ContextBuilder::visitForStatement(ForStatementAst *node)
-{
- DUContext* control = 0;
- if (node->forControl) {
- control = openContext(node->forControl, DUContext::Other, 0);
- visitNode(node->forControl);
- closeContext();
- }
-
- if (node->forBody) {
- DUContext* body = openContext(node->forBody, DUContext::Other, 0);
- if (control) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(control);
- }
- visitNode(node->forBody);
- closeContext();
- }
-}
-
-void ContextBuilder::visitForeachStatement(ForeachStatementAst *node)
-{
- DUContext* control = 0;
- if (node->variableType) {
- AstNode* last = node->collection;
- if (!last) {
- last = node->variableName;
- if (!last)
- last = node->variableType;
- }
- control = openContext(node->variableType, last, DUContext::Other, 0);
-
- visitNode(node->variableType);
- visitNode(node->variableName);
- visitNode(node->collection);
-
- closeContext();
- }
-
- if (node->body) {
- DUContext* body = openContext(node->body, DUContext::Other, 0);
- if (control) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(control);
- }
- visitNode(node->body);
- closeContext();
- }
-}
-
-void ContextBuilder::visitIfStatement(IfStatementAst * node)
-{
- DUContext* condition = 0;
- if (node->condition) {
- condition = openContext(node->condition, DUContext::Other, 0);
- visitNode(node->condition);
- closeContext();
- }
-
- if (node->ifBody) {
- DUContext* body = openContext(node->ifBody, DUContext::Other, 0);
-
- if (condition) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(condition);
- }
-
- visitNode(node->ifBody);
- closeContext();
- }
-
- if (node->elseBody) {
- DUContext* body = openContext(node->elseBody, DUContext::Other, 0);
-
- if (condition) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(condition);
- }
-
- visitNode(node->elseBody);
- closeContext();
- }
-}
-
-void ContextBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
-{
- visitNode(node->attributes);
- visitNode(node->modifiers);
- //visitNode(node->className);
-
- QualifiedIdentifier id;
-
- DUContext* parameters = 0;
- if (node->formalParameters) {
- parameters = openContext(node->formalParameters, DUContext::Other, node->className);
- id = currentContext()->localScopeIdentifier();
- visitNode(node->formalParameters);
- closeContext();
- }
-
- if (node->constructorInitializer) {
- DUContext* body = openContext(node->constructorInitializer, node->body ? static_cast<AstNode*>(node->body) : static_cast<AstNode*>(node->constructorInitializer), DUContext::Other, id);
- if (parameters) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(parameters);
- }
- visitNode(node->constructorInitializer);
- visitNode(node->body);
- closeContext();
-
- } else if (node->body) {
- DUContext* body = openContext(node->body, DUContext::Class, id);
- if (parameters) {
- DUChainWriteLocker lock(DUChain::lock());
- body->addImportedParentContext(parameters);
- }
- visitNode(node->body);
- closeContext();
- }
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/contextbuilder.h (nonexistent)
@@ -1,81 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef CONTEXTBUILDER_H
-#define CONTEXTBUILDER_H
-
-#include "csharpdefaultvisitor.h"
-
-#include <language/duchain/builders/abstractcontextbuilder.h>
-
-namespace CSharp {
-
-class EditorIntegrator;
-class IdentifierCompiler;
-class ParseSession;
-
-typedef KDevelop::AbstractContextBuilder<AstNode, AstNode> ContextBuilderBase;
-
-/**
- * A class which iterates the AST to identify contexts.
- */
-class ContextBuilder: public ContextBuilderBase, protected DefaultVisitor
-{
-public:
- ContextBuilder();
- virtual ~ContextBuilder ();
-
- void setEditor(EditorIntegrator* editor);
- void setEditor(ParseSession* session);
-
-protected:
- EditorIntegrator* editor() const;
-
- virtual void startVisiting( AstNode* node );
- virtual void setContextOnNode( AstNode* node, KDevelop::DUContext* ctx );
- virtual KDevelop::DUContext* contextFromNode( AstNode* node );
- virtual KTextEditor::Range editorFindRange( AstNode* fromRange, AstNode* toRange );
-
- /**
- * Compile an identifier for the specified AstNode \a id.
- *
- * \note this reference will only be valid until the next time the function
- * is called, so you need to create a copy (store as non-reference).
- * @param typeSpecifier a pointer that will eventually be filled with a type-specifier that can be found in the name(for example the return-type of a cast-operator)
- */
- virtual KDevelop::QualifiedIdentifier identifierForNode(AstNode* id);
-
- // Visitors
- virtual void visitForStatement(ForStatementAst *node);
- virtual void visitForeachStatement(ForeachStatementAst *node);
- virtual void visitIfStatement(IfStatementAst *node);
- virtual void visitClassDeclaration(ClassDeclarationAst *node);
- virtual void visitMethodDeclaration(MethodDeclarationAst *node);
- virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
-
-protected:
- // Variables
- IdentifierCompiler* m_identifierCompiler;
- bool m_mapAst;
-};
-
-}
-
-#endif // CONTEXTBUILDER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.h (nonexistent)
@@ -1,58 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef DUMPCHAIN_H
-#define DUMPCHAIN_H
-
-
-#include "csharpdefaultvisitor.h"
-
-namespace KDevelop
-{
-class DUContext;
-}
-
-namespace CSharp {
-
-class ParseSession;
-
-class DumpChain: protected DefaultVisitor
-{
-public:
- DumpChain();
- virtual ~DumpChain();
-
- void dump(AstNode *node, ParseSession* session = 0);
-
- void dump(KDevelop::DUContext* context, bool imported = false);
-
-
-protected:
- virtual void visitNode(CSharp::AstNode *node);
-
-private:
- class EditorIntegrator* m_editor;
- ParseSession* m_session;
- int indent;
-};
-
-}
-
-#endif // DUMPCHAIN_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.cpp (nonexistent)
@@ -1,83 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "editorintegrator.h"
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/smartrange.h>
-#include <ktexteditor/smartinterface.h>
-
-#include <language/editor/documentrange.h>
-#include <language/editor/documentrangeobject.h>
-
-#include "csharpast.h"
-#include "parsesession.h"
-
-using namespace KTextEditor;
-using namespace CSharp;
-
-EditorIntegrator::EditorIntegrator( ParseSession* session )
- : m_session(session)
-{
-}
-
-KDevelop::SimpleCursor EditorIntegrator::findPosition( qint64 token, Edge edge ) const
-{
- const KDevPG::TokenStream::Token& t = m_session->tokenStream->token(token);
- return findPosition(t, edge);
-}
-
-KDevelop::SimpleCursor EditorIntegrator::findPosition( const KDevPG::TokenStream::Token & token, Edge edge ) const
-{
- if(edge == BackEdge)
- return m_session->positionAt(token.end + 1);
- else
- return m_session->positionAt(token.begin + 1);
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange( AstNode * node, RangeEdge edge )
-{
- Q_UNUSED(edge);
- return KDevelop::SimpleRange(findPosition(node->startToken, FrontEdge), findPosition(node->endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange( qint64 startToken, qint64 endToken )
-{
- return KDevelop::SimpleRange(findPosition(startToken, FrontEdge), findPosition(endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange(AstNode* from, AstNode* to)
-{
- return KDevelop::SimpleRange(findPosition(from->startToken, FrontEdge), findPosition(to->endToken, BackEdge));
-}
-
-KDevelop::SimpleRange EditorIntegrator::findRange( const KDevPG::TokenStream::Token & token )
-{
- return KDevelop::SimpleRange(findPosition(token, FrontEdge), findPosition(token, BackEdge));
-}
-
-QString EditorIntegrator::tokenToString(qint64 token) const
-{
- return m_session->symbol(token);
-}
-
-ParseSession * EditorIntegrator::parseSession() const
-{
- return m_session;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/editorintegrator.h (nonexistent)
@@ -1,115 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef CSHARPEDITORINTEGRATOR_H
-#define CSHARPEDITORINTEGRATOR_H
-
-#include <language/editor/editorintegrator.h>
-#include <language/editor/simplerange.h>
-
-#include "kdev-pg-token-stream.h"
-
-namespace CSharp {
-
-class ParseSession;
-class AstNode;
-
-class EditorIntegrator : public KDevelop::EditorIntegrator
-{
-public:
- EditorIntegrator(ParseSession* session);
-
- ParseSession* parseSession() const;
-
- /**
- * Finds the location and \a file where the given \a token was parsed from. This function
- * does not change any of the EditorIntegrator's state.
- *
- * \param token token to locate
- * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
- *
- * \returns the requested cursor relating to the start or end of the given token.
- */
- KDevelop::SimpleCursor findPosition(const KDevPG::TokenStream::Token& token, Edge edge = BackEdge) const;
-
- /**
- * Finds the location and \a file where the given \a token was parsed from.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \param token token to locate
- * \param edge set to FrontEdge to return the start position of the token, BackEdge to return the end position.
- *
- * \returns the requested cursor relating to the start or end of the given token.
- */
- KDevelop::SimpleCursor findPosition(qint64 token, Edge edge = BackEdge) const;
-
- using KDevelop::EditorIntegrator::createRange;
-
- /**
- * Create a range encompassing the given AstNode \a node.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(AstNode* node, RangeEdge = OuterEdge);
-
- /**
- * Create a range encompassing the given AstNode \a nodes.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(AstNode* from, AstNode* to);
-
- /**
- * Create a range encompassing the given AstNode \a token.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(const KDevPG::TokenStream::Token& token);
-
- /**
- * Create a range encompassing the given AstNode \a token.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(qint64 token);
-
- /**
- * Create a range encompassing the given AstNode \a tokens.
- * This function does not change any of the EditorIntegrator's state.
- *
- * \overload
- */
- KDevelop::SimpleRange findRange(qint64 start_token, qint64 end_token);
-
- /**
- * Retrieve the string represented by a token.
- */
- QString tokenToString(qint64 token) const;
-
-private:
- ParseSession* m_session;
-};
-
-}
-
-#endif // CSHARPEDITORINTEGRATOR_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp (nonexistent)
@@ -1,338 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "typebuilder.h"
-
-#include <ktexteditor/smartrange.h>
-
-#include "editorintegrator.h"
-#include "parsesession.h"
-#include "declarationbuilder.h"
-//#define DEBUG
-
-#ifdef DEBUG
-#define ifDebug(x) x;
-#else
-#define ifDebug(x)
-#endif
-
-using namespace KDevelop;
-
-namespace CSharp {
-
-StructureType* TypeBuilder::openClass(bool interface, bool /*parameters*/)
-{
- Q_UNUSED(interface);
-
- StructureType* classType = /*parameters ? new ParameterizedType() :*/ new StructureType();
-
- //classType->setClassType(interface ? StructureType::Interface : StructureType::Class);
-
- return classType;
-}
-
-void TypeBuilder::visitIntegralType(IntegralTypeAst *node)
-{
- bool openedType = false;
-
- if (node) {
- uint type = IntegralType::TypeNone;
- uint modifiers = AbstractType::NoModifiers;
-
- switch (node->type) {
- case PredefinedType::TypeBool:
- type = IntegralType::TypeBoolean;
- break;
- case PredefinedType::TypeByte:
- type = IntegralType::TypeByte;
- break;
- case PredefinedType::TypeChar:
- type = IntegralType::TypeChar;
- break;
- case PredefinedType::TypeDecimal:
- type = CustomIntegrals::TypeDecimal;
- break;
- case PredefinedType::TypeDouble:
- type = IntegralType::TypeDouble;
- break;
- case PredefinedType::TypeFloat:
- type = IntegralType::TypeFloat;
- break;
- case PredefinedType::TypeInt:
- type = IntegralType::TypeInt;
- break;
- case PredefinedType::TypeLong:
- type = IntegralType::TypeLong;
- break;
- case PredefinedType::TypeObject:
- type = CustomIntegrals::TypeObject;
- break;
- case PredefinedType::TypeSbyte:
- type = IntegralType::TypeSbyte;
- break;
- case PredefinedType::TypeShort:
- type = IntegralType::TypeShort;
- break;
- case PredefinedType::TypeString:
- type = IntegralType::TypeString;
- break;
- case PredefinedType::TypeUint:
- type = IntegralType::TypeInt;
- modifiers |= AbstractType::UnsignedModifier;
- break;
- case PredefinedType::TypeUlong:
- type = IntegralType::TypeLong;
- modifiers |= AbstractType::UnsignedModifier;
- break;
- case PredefinedType::TypeUshort:
- type = IntegralType::TypeShort;
- modifiers |= AbstractType::UnsignedModifier;
- break;
- default:
- break;
- }
-
- IntegralType::Ptr integral(new IntegralType(type));
- integral->setModifiers( modifiers );
-
- openedType = true;
- openType(integral);
- }
-
- TypeBuilderBase::visitIntegralType(node);
-
- if (openedType)
- closeType();
-}
-
-void TypeBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
-{
- visitNode(node->returnType);
-
- FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType());
- functionType->setModifiers( parseModifiers(node->modifiers) );
-
- if (lastType())
- functionType->setReturnType(lastType());
-
- openType(functionType);
-
- TypeBuilderBase::visitMethodDeclaration(node);
-
- closeType();
-}
-
-void TypeBuilder::visitTypeName(TypeNameAst *node)
-{
- TypeBuilderBase::visitTypeName(node);
-
- if (openTypeFromName(identifierForNode(node->typeName), node, true))
- closeType();
-}
-
-#if 0
-void TypeBuilder::visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node)
-{
- visitNode(node->returnType);
-
- FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType(parseModifiers(node->modifiers)));
-
- if (lastType())
- functionType->setReturnType(lastType());
-
- openType(functionType);
-
- TypeBuilderBase::visitInterfaceMethodDeclaration(node);
-
- closeType();
-}
-#endif
-
-void TypeBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
-{
- // TODO set constructor type
-
- FunctionType::Ptr functionType = FunctionType::Ptr(new FunctionType());
- functionType->setModifiers( parseModifiers(node->modifiers) );
-
- if (lastType())
- functionType->setReturnType(lastType());
-
- openType(functionType);
-
- TypeBuilderBase::visitConstructorDeclaration(node);
-
- closeType();
-}
-
-void TypeBuilder::visitClassDeclaration(ClassDeclarationAst *node)
-{
- StructureType::Ptr classType = StructureType::Ptr(openClass(false, node->typeParameters));
-
- openType(classType);
-
- classTypeOpened( currentAbstractType() ); //This callback is needed, because the type of the class-declaration needs to be set early so the class can be referenced from within itself
-
- TypeBuilderBase::visitClassDeclaration(node);
-
- closeType();
-}
-
-#if 0
-void TypeBuilder::visitInterfaceDeclaration(InterfaceDeclarationAst * node)
-{
- StructureType::Ptr classType = StructureType::Ptr(openClass(true, node->typeParameters));
-
- openType(classType);
-
- classTypeOpened( TypeRepository::self()->registerType(currentAbstractType()) ); //This callback is needed, because the type of the class-declaration needs to be set early so the class can be referenced from within itself
-
- TypeBuilderBase::visitInterfaceDeclaration(node);
-
- // Prevent additional elements being added if this becomes the current type again
- classType->close();
-
- closeType();
-}
-
-bool TypeBuilder::nodeValid(AstNode* node) const
-{
- return node && node->startToken <= node->endToken;
-}
-
-void TypeBuilder::visitOptionalArrayBuiltInType(OptionalArrayBuiltInTypeAst * node)
-{
- visitNode(node->type);
-
- if (nodeValid(node->declaratorBrackets)) {
- ArrayType::Ptr array(new ArrayType());
-
- array->setElementType(lastType());
-
- if( node->declaratorBrackets ) {
- array->setDimension(node->declaratorBrackets->bracketCount);
- } else {
- array->setDimension(0);
- }
-
- injectType(array);
- }
-}
-
-void TypeBuilder::visitTypeArgument(TypeArgumentAst * node)
-{
- //node->
-
- TypeBuilderBase::visitTypeArgument(node);
-}
-#endif
-
-uint TypeBuilder::parseModifiers(OptionalModifiersAst * node) const
-{
- uint modifiers = AbstractType::NoModifiers;
-
- if (node->modifiers & Modifiers::ModNew)
- modifiers |= AbstractType::NewModifier;
- if (node->modifiers & Modifiers::ModSealed)
- modifiers |= AbstractType::SealedModifier;
- // TODO
- //if (node->modifiers & Modifiers::ModVirtual)
- //modifiers |= AbstractType::
- if (node->modifiers & Modifiers::ModVolatile)
- modifiers |= AbstractType::VolatileModifier;
- // TODO
- //if (node->modifiers & Modifiers::ModExtern)
- //modifiers |= AbstractType::;
- if (node->modifiers & Modifiers::ModUnsafe)
- modifiers |= AbstractType::UnsafeModifier;
- if (node->modifiers & Modifiers::ModFixed)
- modifiers |= AbstractType::FixedModifier;
-
- // TODO Move to Declaration Builder
- //if (node->modifiers & Modifiers::ModAbstract)
- //modifiers |= AbstractType::AbstractModifier;
- //if (node->modifiers & Modifiers::ModStatic)
- //modifiers |= AbstractType::StaticModifier;
- //if (node->modifiers & Modifiers::ModOverride)
- //modifiers |= AbstractType::OverrideModifier;
- //if (node->modifiers & Modifiers::ModReadonly)
- //modifiers |= AbstractType::ReadonlyModifier;
-
- return modifiers;
-}
-
-#if 0
-void TypeBuilder::visitClassExtendsClause(ClassExtendsClauseAst * node)
-{
- m_rememberClassNames.clear();
-
- TypeBuilderBase::visitClassExtendsClause(node);
-
- StructureType* klass = dynamic_cast<StructureType*>(currentAbstractType().data());
-
- foreach (const StructureType::Ptr& extends, m_rememberClassNames) {
- // TODO read locking required??
- if (extends->classType() == StructureType::Interface) {
- DUChainWriteLocker lock(DUChain::lock());
- klass->addExtendsClass(extends);
- } else {
- // TODO problem reporter
- kDebug() << "Tried to extend rather than implement an interface";
- }
- }
-}
-
-void TypeBuilder::visitClassOrInterfaceTypeName(ClassOrInterfaceTypeNameAst * node)
-{
- m_currentIdentifier.clear();
-
- TypeBuilderBase::visitClassOrInterfaceTypeName(node);
-
- if (openTypeFromName(m_currentIdentifier, node, true))
- closeType();
-}
-
-void TypeBuilder::visitClassOrInterfaceTypeNamePart(ClassOrInterfaceTypeNamePartAst * node)
-{
- m_currentIdentifier.push(identifierForNode(node->identifier));
-
- TypeBuilderBase::visitClassOrInterfaceTypeNamePart(node);
-}
-
-void TypeBuilder::visitImplementsClause(ImplementsClauseAst * node)
-{
- /*m_rememberClassNames.clear();
-
- TypeBuilderBase::visitImplements_clause(node);
-
- StructureType* klass = dynamic_cast<StructureType*>(m_typeStack.top().data());
-
- foreach (const StructureType::Ptr& interface, m_rememberClassNames) {
- // TODO read locking required??
- if (interface->classType() == StructureType::Interface) {
- DUChainWriteLocker lock(DUChain::lock());
- klass->addImplementsInterface(interface);
- } else {
- // TODO problem reporter
- kDebug() << "Tried to implement a class rather than an interface";
- }
- }*/
-}
-#endif
-
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.cpp (nonexistent)
@@ -1,55 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2007 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-//krazy:excludeall=cpp
-
-#include "identifiercompiler.h"
-#include "csharpast.h"
-#include "csharpparser.h"
-#include "parsesession.h"
-
-using namespace KDevelop;
-using namespace CSharp;
-
-IdentifierCompiler::IdentifierCompiler(ParseSession* session)
- : m_session(session)
-{
-}
-
-void IdentifierCompiler::run(AstNode *node)
-{
- m_name.clear();
- visitNode(node);
-}
-
-void IdentifierCompiler::visitIdentifier(IdentifierAst *node)
-{
- IndexedString id;
-
- if (node->ident)
- id = m_session->indexedSymbol(node->ident);
-
- m_name.push(Identifier(id));
-}
-
-const QualifiedIdentifier& IdentifierCompiler::identifier() const
-{
- return m_name;
-}
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/identifiercompiler.h (nonexistent)
@@ -1,51 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2007 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef NAME_COMPILER_H
-#define NAME_COMPILER_H
-
-#include "csharpdefaultvisitor.h"
-#include <language/duchain/identifier.h>
-#include <language/duchain/declaration.h>
-
-namespace CSharp {
-
-class ParseSession;
-
-class IdentifierCompiler: protected DefaultVisitor
-{
-public:
- IdentifierCompiler(ParseSession* session);
-
- void run(AstNode *node);
-
- const KDevelop::QualifiedIdentifier& identifier() const;
-
-protected:
- virtual void visitIdentifier(IdentifierAst *node);
-
-private:
- ParseSession* m_session;
- KDevelop::QualifiedIdentifier m_name;
-};
-
-}
-
-#endif // NAME_COMPILER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h (nonexistent)
@@ -1,79 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef TYPEBUILDER_H
-#define TYPEBUILDER_H
-
-#include "contextbuilder.h"
-#include <language/duchain/builders/abstracttypebuilder.h>
-
-#include <language/duchain/declaration.h>
-#include <language/duchain/identifier.h>
-#include <language/duchain/types/alltypes.h>
-
-namespace CSharp {
-
-typedef KDevelop::AbstractTypeBuilder<AstNode, IdentifierAst, CSharp::ContextBuilder> TypeBuilderBase;
-
-namespace CustomIntegrals
-{
- enum {
- TypeDecimal = KDevelop::IntegralType::TypeLanguageSpecific,
- TypeObject
- };
-}
-
-/**
- * Create types from an AstNode tree.
- *
- * \note This builder overrides visitDeclarator, in order to support
- * array types; parent classes will not have
- * their visitDeclarator function called.
- */
-class TypeBuilder: public TypeBuilderBase
-{
-protected:
-#if 0
- virtual void visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node);
- virtual void visitInterfaceDeclaration(InterfaceDeclarationAst *node);
-#endif
-
- virtual void visitClassDeclaration(ClassDeclarationAst *node);
- virtual void visitMethodDeclaration(MethodDeclarationAst *node);
- virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
-
- virtual void visitIntegralType(IntegralTypeAst *node);
- virtual void visitTypeName(TypeNameAst *node);
-
-private:
- bool nodeValid(AstNode* node) const;
-
- /// @TODO Do we need the argument \e parameters or not?
- KDevelop::StructureType* openClass(bool interface, bool parameters);
- KDevelop::FunctionType* openFunction();
-
- uint parseModifiers(OptionalModifiersAst* node) const;
-
- QList<KDevelop::StructureType::Ptr> m_rememberClassNames;
- KDevelop::QualifiedIdentifier m_currentIdentifier;
-};
-
-}
-
-#endif // TYPEBUILDER_H
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/typebuilder.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/dumpchain.cpp (nonexistent)
@@ -1,320 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2002-2005 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "dumpchain.h"
-
-#include <QtCore/QString>
-#include <QTextStream>
-
-#include <kdebug.h>
-#include <ktexteditor/range.h>
-
-#include <language/duchain/types/identifiedtype.h>
-#include "editorintegrator.h"
-#include <language/duchain/ducontext.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainpointer.h>
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/identifier.h>
-#include <language/duchain/use.h>
-#include "parser/parsesession.h"
-
-using namespace KDevelop;
-using namespace CSharp;
-
-static char const * const names[] = {
- "BaseAccess",
- "ConstructorConstraint",
- "PointerType",
- "PredefinedType",
- "PrimarySuffix",
- "RelationalExpression",
- "ReturnType",
- "TypeofExpression",
- "UnboundtypeName",
- "UnboundtypeNamePart",
- "AccessorDeclarations",
- "AccessorModifier",
- "AdditiveExpression",
- "AdditiveExpressionRest",
- "AnonymousMethodExpression",
- "AnonymousMethodParameter",
- "AnonymousMethodSignature",
- "Argument",
- "ArrayCreationExpressionRest",
- "ArrayInitializer",
- "ArrayType",
- "Attribute",
- "AttributeArguments",
- "AttributeSection",
- "AttributeTarget",
- "BitAndExpression",
- "BitOrExpression",
- "BitXorExpression",
- "Block",
- "BlockStatement",
- "BooleanExpression",
- "BreakStatement",
- "BuiltinClassType",
- "CastExpression",
- "CatchClauses",
- "CheckedStatement",
- "ClassBase",
- "ClassBody",
- "ClassDeclaration",
- "ClassMemberDeclaration",
- "ClassOrStructMemberDeclaration",
- "ClassType",
- "CompilationUnit",
- "ConditionalExpression",
- "ConstantDeclaration",
- "ConstantDeclarationData",
- "ConstantDeclarator",
- "ConstantExpression",
- "ConstructorDeclaration",
- "ConstructorInitializer",
- "ContinueStatement",
- "ConversionOperatorDeclaration",
- "DelegateDeclaration",
- "DoWhileStatement",
- "EmbeddedStatement",
- "EnumBase",
- "EnumBody",
- "EnumDeclaration",
- "EnumMemberDeclaration",
- "EqualityExpression",
- "EqualityExpressionRest",
- "EventAccessorDeclaration",
- "EventDeclaration",
- "EventaccessorDeclarations",
- "Expression",
- "ExternAliasDirective",
- "FinalizerDeclaration",
- "FixedPointerDeclarator",
- "FixedStatement",
- "FloatingPointType",
- "ForControl",
- "ForStatement",
- "ForeachStatement",
- "FormalParameter",
- "FormalParameterList",
- "GeneralCatchClause",
- "GenericDimensionSpecifier",
- "GlobalAttributeSection",
- "GotoStatement",
- "Identifier",
- "IfStatement",
- "IndexerDeclaration",
- "IntegralType",
- "InterfaceAccessors",
- "InterfaceBase",
- "InterfaceBody",
- "InterfaceDeclaration",
- "InterfaceEventDeclaration",
- "InterfaceIndexerDeclaration",
- "InterfaceMemberDeclaration",
- "InterfaceMethodDeclaration",
- "InterfacePropertyDeclaration",
- "Keyword",
- "LabeledStatement",
- "Literal",
- "LocalConstantDeclaration",
- "LocalVariableDeclaration",
- "LocalVariableDeclarationStatement",
- "LockStatement",
- "LogicalAndExpression",
- "LogicalOrExpression",
- "ManagedType",
- "MethodDeclaration",
- "MultiplicativeExpression",
- "MultiplicativeExpressionRest",
- "NamedArgument",
- "NamespaceBody",
- "NamespaceDeclaration",
- "NamespaceMemberDeclaration",
- "NamespaceName",
- "NamespaceOrtypeName",
- "NamespaceOrtypeNamePart",
- "NamespaceOrtypeNameSafe",
- "NewExpression",
- "NonArrayType",
- "NonNullableType",
- "NullCoalescingExpression",
- "NumericType",
- "ObjectOrDelegateCreationExpressionRest",
- "OperatorDeclarationParameter",
- "OptionalArgumentList",
- "OptionalAttributeSections",
- "OptionalModifiers",
- "OptionalParameterModifier",
- "OptionallyNullableType",
- "OverloadableBinaryOnlyOperator",
- "OverloadableUnaryOnlyOperator",
- "OverloadableUnaryOrBinaryOperator",
- "PositionalArgument",
- "PrimaryAtom",
- "PrimaryExpression",
- "PrimaryOrSecondaryConstraint",
- "PropertyDeclaration",
- "QualifiedIdentifier",
- "RankSpecifier",
- "RelationalExpressionRest",
- "ResourceAcquisition",
- "ReturnStatement",
- "SecondaryConstraint",
- "ShiftExpression",
- "ShiftExpressionRest",
- "SimpleNameOrMemberAccess",
- "SimpleType",
- "SpecificCatchClause",
- "StackallocInitializer",
- "StatementExpression",
- "StructBody",
- "StructDeclaration",
- "StructMemberDeclaration",
- "SwitchLabel",
- "SwitchSection",
- "SwitchStatement",
- "ThrowStatement",
- "TryStatement",
- "Type",
- "TypeArguments",
- "TypeArgumentsOrParametersEnd",
- "TypeDeclaration",
- "TypeDeclarationRest",
- "TypeName",
- "TypeNameSafe",
- "TypeParameters",
- "TypeParametersConstraints",
- "TypeParametersConstraintsClause",
- "UnaryExpression",
- "UnaryOrBinaryOperatorDeclaration",
- "UncheckedStatement",
- "UnmanagedType",
- "UnmanagedTypeSuffix",
- "UnsafeStatement",
- "UsingAliasDirectiveData",
- "UsingDirective",
- "UsingNamespaceDirectiveData",
- "UsingStatement",
- "VariableDeclarationData",
- "VariableDeclarator",
- "VariableInitializer",
- "WhileStatement",
- "YieldStatement"
-};
-
-DumpChain::DumpChain()
- : m_editor(0)
- , indent(0)
-{
-}
-
-void DumpChain::dump( AstNode * node, ParseSession* session)
-{
- delete m_editor;
- m_editor = 0;
-
- Q_ASSERT(session);
- m_session = session;
- m_editor = new EditorIntegrator(session);
-
- visitNode(node);
-}
-
-void DumpChain::visitNode(AstNode *node)
-{
- QString indentation;
- for( int a = 0; a < indent; a++ )
- indentation += "| ";
-
- if (node) {
- if (m_editor) {
- QString nodeText;
- for( qint64 a = node->startToken; a <= node->endToken; a++ ) {
- if( !nodeText.isEmpty() )
- nodeText += ' ';
- nodeText += m_session->symbol(a);
- }
- if( !nodeText.isEmpty() ) nodeText = "\"" + nodeText + "\"";
-
-
- kDebug() << indentation << "\\" << names[node->kind - 1000]
- << "[" << node->startToken << m_editor->findPosition(node->startToken, EditorIntegrator::FrontEdge).textCursor() << ", "
- << node->endToken << m_editor->findPosition(node->endToken, EditorIntegrator::BackEdge).textCursor() << "]" << nodeText << endl;
- } else {
- kDebug() << indentation << "\\" << names[node->kind - 1000]
- << "[" << node->startToken << "," << node->endToken << "]" << endl;
- }
- }
-
- ++indent;
- DefaultVisitor::visitNode(node);
- --indent;
-
- if (node) {
- if (m_editor) {
- kDebug() << indentation << "/" << names[node->kind - 1000]
- << "[(" << node->endToken << ") "/*<< m_editor->findPosition(node->startToken, EditorIntegrator::FrontEdge) << ", "*/
- << m_editor->findPosition(node->endToken, EditorIntegrator::FrontEdge).textCursor() << "]" << endl;
- } else {
- kDebug() << indentation << "/" << names[node->kind - 1000]
- << "[" << node->startToken << "," << node->endToken << ']' << endl;
- }
- }
-}
-
-DumpChain::~ DumpChain( )
-{
- delete m_editor;
-}
-
-void DumpChain::dump( DUContext * context, bool imported )
-{
- kDebug() << QString(indent * 2, ' ') << (imported ? "==import==> Context " : "New Context ") << context << "\"" << context->localScopeIdentifier() << "\" [" << context->scopeIdentifier() << "]" << context->range().textRange() << " " << (dynamic_cast<TopDUContext*>(context) ? "top-context" : "");
- if( !context )
- return;
- if (!imported) {
- foreach (Declaration* dec, context->localDeclarations()) {
-
- kDebug() << QString((indent+1) * 2, ' ') << "Declaration: " << dec->toString() << /*(idType ? (" (type-identity: " + idType->identifier().toString() + ")") : QString()) <<*/ " [" << dec->qualifiedIdentifier() << "]" << dec << "(internal ctx" << dec->internalContext() << ")" << dec->range().textRange() << "," << (dec->isDefinition() ? "definition, " : "not a definition, ") << dec->uses().count() << "use(s).";
- QMap<IndexedString, QList<SimpleRange> > uses = dec->uses();
- for(QMap<IndexedString, QList<SimpleRange> >::const_iterator it = uses.begin(); it != uses.end(); ++it) {
- kDebug() << QString((indent+2) * 2, ' ') << "File:" << it.key().str();
- foreach (const SimpleRange& range, *it)
- kDebug() << QString((indent+2) * 2+1, ' ') << "Use:" << range.textRange();
- }
- }
- }
-
- ++indent;
- if (!imported) {
- ///@todo Think whether this is used for top-contexts, and if it is, prevent endless recursion due to loops
- foreach (const KDevelop::DUContext::Import& parent, context->importedParentContexts()) {
- dump(parent.context(context->topContext()), true);
- }
-
- foreach (DUContext* child, context->childContexts())
- dump(child);
- }
- --indent;
-}
-
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.cpp (nonexistent)
@@ -1,140 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "declarationbuilder.h"
-
-#include <QByteArray>
-
-#include <ktexteditor/smartrange.h>
-#include <ktexteditor/smartinterface.h>
-
-#include "editorintegrator.h"
-#include "identifiercompiler.h"
-#include <language/duchain/functiondeclaration.h>
-#include "csharpast.h"
-#include "parsesession.h"
-
-using namespace KTextEditor;
-using namespace KDevelop;
-
-namespace CSharp {
-
-DeclarationBuilder::DeclarationBuilder (ParseSession* session)
-{
- setEditor(session);
-}
-
-DeclarationBuilder::DeclarationBuilder (EditorIntegrator* editor)
-{
- setEditor(editor);
-}
-
-void DeclarationBuilder::closeDeclaration()
-{
- if (currentDeclaration()) {
- DUChainWriteLocker lock(DUChain::lock());
-
- currentDeclaration()->setType(lastType());
- }
-
- eventuallyAssignInternalContext();
-
- //kDebug() << "Mangled declaration:" << currentDeclaration()->mangledIdentifier();
-
- DeclarationBuilderBase::closeDeclaration();
-}
-
-void DeclarationBuilder::visitClassDeclaration(ClassDeclarationAst * node)
-{
- // TODO csharp-specific class declaration
- openDefinition<Declaration>(node->className, node);
-
- currentDeclaration()->setKind(Declaration::Type);
-
- DeclarationBuilderBase::visitClassDeclaration(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitInterfaceDeclaration(InterfaceDeclarationAst * node)
-{
- // TODO csharp-specific class declaration
- openDefinition<Declaration>(node->interfaceName, node);
-
- currentDeclaration()->setKind(Declaration::Type);
-
- DeclarationBuilderBase::visitInterfaceDeclaration(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst * node)
-{
- openDefinition<ClassFunctionDeclaration>(node->methodName, node);
-
- currentDeclaration()->setKind(Declaration::Type);
-
- DeclarationBuilderBase::visitInterfaceMethodDeclaration(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitConstructorDeclaration(ConstructorDeclarationAst * node)
-{
- openDefinition<ClassFunctionDeclaration>(node->className, node);
-
- currentDeclaration()->setKind(Declaration::Type);
-
- DeclarationBuilderBase::visitConstructorDeclaration(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitMethodDeclaration(MethodDeclarationAst * node)
-{
- openDefinition<ClassFunctionDeclaration>(node->methodName, node);
-
- currentDeclaration()->setKind(Declaration::Type);
-
- DeclarationBuilderBase::visitMethodDeclaration(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitVariableDeclarator(VariableDeclaratorAst * node)
-{
- if (currentContext()->type() == DUContext::Class)
- openDefinition<ClassMemberDeclaration>(node->variableName, node);
- else
- openDefinition<Declaration>(node->variableName, node);
-
- DeclarationBuilderBase::visitVariableDeclarator(node);
-
- closeDeclaration();
-}
-
-void DeclarationBuilder::visitFormalParameter(FormalParameterAst *node)
-{
- openDefinition<Declaration>(node->variableName, node);
-
- DeclarationBuilderBase::visitFormalParameter(node);
-
- closeDeclaration();
-}
-
-}
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/declarationbuilder.h (nonexistent)
@@ -1,56 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef DECLARATIONBUILDER_H
-#define DECLARATIONBUILDER_H
-
-#include "typebuilder.h"
-#include <language/duchain/builders/abstractdeclarationbuilder.h>
-
-namespace CSharp {
-
-class ParseSession;
-
-typedef KDevelop::AbstractDeclarationBuilder<AstNode, AstNode, CSharp::TypeBuilder> DeclarationBuilderBase;
-
-/**
- * A class which iterates the AST to extract definitions of types.
- */
-class DeclarationBuilder: public DeclarationBuilderBase
-{
-public:
- DeclarationBuilder(ParseSession* session);
- DeclarationBuilder(EditorIntegrator* editor);
-
-protected:
- virtual void closeDeclaration();
-
- virtual void visitClassDeclaration(ClassDeclarationAst *node);
- virtual void visitMethodDeclaration(MethodDeclarationAst *node);
- virtual void visitInterfaceMethodDeclaration(InterfaceMethodDeclarationAst *node);
- virtual void visitConstructorDeclaration(ConstructorDeclarationAst *node);
- virtual void visitInterfaceDeclaration(InterfaceDeclarationAst *node);
- //virtual void visitVariableDeclaration(VariableDeclarationAst *node);
- virtual void visitVariableDeclarator(VariableDeclaratorAst *node);
- virtual void visitFormalParameter(FormalParameterAst *node);
-};
-
-}
-
-#endif // DECLARATIONBUILDER_H
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp (nonexistent)
@@ -1,46 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#include "usebuilder.h"
-
-#include "editorintegrator.h"
-#include "parsesession.h"
-
-using namespace KTextEditor;
-using namespace KDevelop;
-
-namespace CSharp {
-
-UseBuilder::UseBuilder (ParseSession* session)
-{
- setEditor(session);
-}
-
-UseBuilder::UseBuilder (EditorIntegrator* editor)
-{
- setEditor(editor);
-}
-
-void UseBuilder::visitSimpleNameOrMemberAccess(SimpleNameOrMemberAccessAst *node)
-{
- newUse(node->memberName);
-
- UseBuilderBase::visitSimpleNameOrMemberAccess(node);
-}
-
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h (nonexistent)
@@ -1,48 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2006-2008 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- 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.
-*/
-
-#ifndef USEBUILDER_H
-#define USEBUILDER_H
-
-#include "contextbuilder.h"
-
-#include <language/duchain/builders/abstractusebuilder.h>
-
-namespace CSharp {
-
-class ParseSession;
-
-typedef KDevelop::AbstractUseBuilder<AstNode, AstNode, CSharp::ContextBuilder> UseBuilderBase;
-
-/**
- * A class which iterates the AST to extract uses of definitions.
- */
-class UseBuilder: public UseBuilderBase
-{
-public:
- UseBuilder(ParseSession* session);
- UseBuilder(EditorIntegrator* editor);
-
-protected:
- virtual void visitSimpleNameOrMemberAccess(SimpleNameOrMemberAccessAst *node);
-};
-
-}
-
-#endif // USEBUILDER_H
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/csharp/duchain/usebuilder.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.h (nonexistent)
@@ -1,81 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITASCPP_UUTCONSTRUCTOR_H
-#define VERITASCPP_UUTCONSTRUCTOR_H
-
-#include "veritascppexport.h"
-#include "classskeleton.h"
-#include "methodskeleton.h"
-#include <language/editor/simplecursor.h>
-
-namespace KDevelop { class Declaration; class Use; class DUContext; class SimpleCursor; }
-
-namespace Veritas
-{
-
-class DocumentAccess;
-/*!
-Generate a skeleton for unit under test from its implementation
-in a test. Fetches all method uses and construct method skeletons
-for those.
-
-input:
-@code
-void MyTest::test() {
- MyUnitUnderTest uut;
- uut.rockOn();
-}
-@endcode
-=>
-output:
-@code
-class MyUnitUnderTest {
-public:
- void rockOn();
-};
-@endcode
-@unittest Veritas::Test::UUTCreationTest
-*/
-class VERITASCPP_EXPORT UUTConstructor
-{
-public:
- /*! Generate a class for an unresolved variable and all it's Use's */
- virtual ClassSkeleton morph(KDevelop::Declaration* variable);
-
- UUTConstructor();
- virtual ~UUTConstructor();
- virtual void setDocumentAccess(DocumentAccess*);
-
-private:
- /*! Create a method skeleton from a @param use of @param clazz
- eg: Foo f; f.bar(); => method Foo::bar() */
- MethodSkeleton createMethod(KDevelop::Declaration* clazz, const KDevelop::Use* use, KDevelop::DUContext*);
- QString enoughText(const KUrl& url, const KDevelop::SimpleCursor&) const;
- void printUseInfo(int useId, const KDevelop::Use* use, KDevelop::DUContext* ctx);
- void constructMethodsFor(KDevelop::DUContext* ctx, KDevelop::Declaration* variable, ClassSkeleton& cs);
-
-private:
- DocumentAccess* m_docAccess;
-};
-
-}
-
-#endif // VERITASCPP_UUTCONSTRUCTOR_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp (nonexistent)
@@ -1,291 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "uutconstructor.h"
-#include "documentaccess.h"
-
-// kdevplatform
-#include <language/duchain/declaration.h>
-#include <language/editor/simplecursor.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/use.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/types/delayedtype.h>
-
-#include "../cppduchain/expressionparser.h"
-#include "../cppduchain/expressionevaluationresult.h"
-
-#include <ktexteditor/smartrange.h>
-
-using Veritas::UUTConstructor;
-using Veritas::ClassSkeleton;
-using Veritas::MethodSkeleton;
-using KTextEditor::SmartRange;
-using namespace KDevelop;
-using Cpp::ExpressionParser;
-using Cpp::ExpressionEvaluationResult;
-
-namespace
-{
-
-/*! Debugger helper for types */
-void printTypeInfoFor(Declaration* decl)
-{
- AbstractType::Ptr atype = decl->type<AbstractType>();
- if (atype) {
- kDebug() << "Not an Unresolved type [" << atype->toString()
- << " " << decl->toString() << "]";
- } else {
- kDebug() << "Failed to fetch type for " << decl->toString();
- }
-}
-
-/*! Serialize @param type to string. Remove any prefixes. */
-QString cleanTypeNameFor(DelayedType::Ptr type)
-{
- QString strType = type->toString();
- if (strType.startsWith("<unresolved> ")) {
- strType = strType.split(' ').last();
- }
- return strType;
-}
-
-/*! Fetch the declaration associated with @param use */
-Declaration* declarationForUse(const Use* use, DUContext* ctx)
-{
- TopDUContext* top = ctx->topContext();
- int declarationId = use->m_declarationIndex;
- return top->usedDeclarationForIndex(declarationId);
-}
-
-DelayedType::Ptr isUnresolvedType(Declaration* variable)
-{
- DelayedType::Ptr type = variable->type<DelayedType>();
- if (!type || type->kind() != DelayedType::Unresolved) {
- printTypeInfoFor(variable);
- type = 0;
- }
- return type;
-}
-
-void printAllDeclarations(DUContext* ctx)
-{
- kDebug() << "";
- foreach(Declaration* dcl, ctx->localDeclarations()) {
- kDebug() << dcl->toString();
- }
- kDebug() << "";
-}
-
-} // end anonymous namespace
-
-void UUTConstructor::printUseInfo(int useId, const Use* use, DUContext* ctx)
-{
- Q_UNUSED(useId);
- Declaration* decl = declarationForUse(use,ctx);
- if (!decl) return;
- kDebug() << "decl " << decl->toString();
- KUrl url(decl->url().str());
- kDebug() << "useTxt " << m_docAccess->text(url, use->m_range);
-}
-
-ClassSkeleton UUTConstructor::morph(Declaration* variable)
-{
- Q_ASSERT(variable); Q_ASSERT(m_docAccess);
- DUChainReadLocker lock(DUChain::lock());
-
- ClassSkeleton cs;
- DelayedType::Ptr varType = isUnresolvedType(variable);
- if (!varType) return cs;
- cs.setName(cleanTypeNameFor(varType));
-
- DUContext* ctx = variable->context();
- printAllDeclarations(ctx);
- constructMethodsFor(ctx, variable, cs);
- return cs;
-}
-
-void UUTConstructor::constructMethodsFor(DUContext* ctx, Declaration* classToMorph, ClassSkeleton& cs)
-{
- const Use* uses = ctx->uses();
- for(int i=0; i<ctx->usesCount(); i++, uses++) {
- Declaration* decl = declarationForUse(uses, ctx);
- printUseInfo(i, uses, ctx);
- if (decl == classToMorph) {
- MethodSkeleton ms = createMethod(decl, uses, ctx);
- if (!ms.isEmpty()) {
- cs.addMethod(ms);
- }
- }
- }
- foreach(DUContext* child, ctx->childContexts()) {
- constructMethodsFor(child, classToMorph, cs);
- }
-}
-
-
-UUTConstructor::UUTConstructor()
- : m_docAccess(0)
-{}
-
-UUTConstructor::~UUTConstructor()
-{}
-
-void UUTConstructor::setDocumentAccess(Veritas::DocumentAccess* docAccess)
-{
- Q_ASSERT(!m_docAccess);
- m_docAccess = docAccess;
- Q_ASSERT(m_docAccess);
-}
-
-
-QString UUTConstructor::enoughText(const KUrl& url, const KDevelop::SimpleCursor& cursor) const
-{
- SimpleCursor ahead(cursor.line+4, 0); // though luck if you smear a use over more than 3 lines.
- //SimpleCursor ahead(cursor.line, cursor.column+10);
- SimpleRange farEnough(cursor, ahead);
- QString txt = m_docAccess->text(url, farEnough);
- kDebug() << txt;
- return txt;
-}
-
-namespace
-{
-/*! remove spaces, newlines and stuff after the first semicolon.
- Also get rid of first '.' or '->' */
-void normalize(QString& text)
-{
- kDebug() << QString("before ``%1''").arg(text);
- text.remove(QRegExp("[ \r\n\t]"));
- int pos = text.indexOf(";");
- if (pos == -1) {
- text.clear();
- kDebug() << QString("after ``%1''").arg(text);
- return;
- }
- text = text.left(pos);
- if (text.startsWith('.')) {
- text = text.mid(1, -1);
- } else if (text.startsWith("->")) {
- text = text.mid(2, -1);
- } else {
- text.clear();
- }
- kDebug() << QString("after ``%1''").arg(text);
-}
-
-QString extractMethodName(QString& text)
-{
- kDebug() << text;
- int firstBrace = text.indexOf("(");
- QString methodName = text.left(firstBrace);
- text = text.mid(firstBrace);
- return methodName;
-}
-
-QList<int> topLevelCommaPositions(const QString& text)
-{
- QStack<bool> braces;
- QList<int> result;
- if (!text.contains(',')) return result;
- QString text_ = text.mid(1, text.count()-1);
- for (int i=0; i<text_.count(); i++) {
- QChar c = text_[i];
- if (c == ',') {
- if (braces.isEmpty()) result << i;
- } else if (c == '(') {
- braces.push(true);
- } else if (c == ')' && !braces.isEmpty()) {
- braces.pop();
- }
- }
- return result;
-}
-
-QString serializeTypeFromExpression(const QString& expr, DUContext* ctx)
-{
- ExpressionParser* ep = new ExpressionParser;
- DUContextPointer p(ctx);
- TopDUContext* top = ctx->topContext();
- ExpressionEvaluationResult er = ep->evaluateType(expr.toLatin1(), p, top);
- delete ep;
- if (!er.type) {
- kDebug() << "failed to grab arguments";
- return QString();
- }
- if (er.type.abstractType()->whichType() == AbstractType::TypeFunction) {
- TypePtr<FunctionType> f = er.type.type<FunctionType>();
- Q_ASSERT(f); Q_ASSERT(f->returnType());
- return f->returnType()->toString();
- } else {
- return er.type.abstractType()->toString();
- }
-}
-
-QString extractArguments(QString& text, DUContext* ctx)
-{
- kDebug() << text;
- QList<int> commas = topLevelCommaPositions(text);
- kDebug() << "COMMAS " << commas;
- if (commas.isEmpty()) {
- int lastBrace = text.indexOf(')');
- QString type = serializeTypeFromExpression(text.mid(1, lastBrace), ctx);
- if (type.isEmpty()) return QString();
- return QString("(%1)").arg(type);
- } else {
- QString args("(");
- int prev = 1;
- foreach(int i, commas) {
- i = i+1;
- QString expr = text.mid(prev, i);
- args += serializeTypeFromExpression(expr, ctx) + ", ";
- prev = i+1;
- }
- int lastBrace = text.indexOf(')');
- args += serializeTypeFromExpression(text.mid(prev, lastBrace), ctx);
- args += ')';
- return args;
- }
-}
-
-} // end anonymous namespace
-
-MethodSkeleton UUTConstructor::createMethod(Declaration* clazz, const Use* use, DUContext* ctx)
-{
- KUrl doc(clazz->url().str());
- MethodSkeleton ms;
- QString text = enoughText(doc, use->m_range.end);
- normalize(text);
- if (text.isEmpty()) {
- kDebug() << "Failed to parser\n" << enoughText(doc, use->m_range.end);
- return ms;
- }
- if (text.contains("(") && text.contains(")")) { // function member use
- ms.setName(extractMethodName(text));
- if (!text.startsWith("()")) {
- ms.setArguments(extractArguments(text, ctx));
- }
- ms.setBody("// GENERATED");
- } else { // data member use. do nothing for now.
- }
- return ms;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutconstructor.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp (nonexistent)
@@ -1,335 +0,0 @@
-/*
- * KDevelop xUnit test support
- * Copyright 2008 Manuel Breugelmans
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "stubcreationtest.h"
-
-#include "kdevtest.h"
-
-#include "../stubconstructor.h"
-#include "../classskeleton.h"
-#include "../constructorskeleton.h"
-#include "../methodskeleton.h"
-
-#include "classdeclarationfactory.h"
-
-#include <language/duchain/classdeclaration.h>
-#include <language/editor/simplecursor.h>
-
-
-using Veritas::StubConstructor;
-using Veritas::ClassSkeleton;
-using Veritas::ConstructorSkeleton;
-using Veritas::MethodSkeleton;
-using Veritas::Test::StubCreationTest;
-using Veritas::Test::DeclarationFactory;
-
-using namespace KDevelop;
-
-/////////////////////////// fixture //////////////////////////////////////////
-
-void StubCreationTest::init()
-{
- m_factory = new DeclarationFactory;
- m_constructor = new StubConstructor;
-}
-
-void StubCreationTest::cleanup()
-{
- if (m_factory) {
- //m_factory->release();
- delete m_factory;
- }
- if (m_constructor) delete m_constructor;
-}
-
-/////////////////////////// commands /////////////////////////////////////////
-
-void StubCreationTest::appendStubToClassName()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{};\n");
-
- KVERIFY(!actual.isEmpty());
- ClassSkeleton expected;
- expected.setName("IFooStub");
- KOMPARE("IFoo", actual.super());
- KOMPARE(expected.name(), actual.name());
-}
-
-void StubCreationTest::basicConstructor()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{ public: IFoo(); virtual ~IFoo(); };\n");
-
- ConstructorSkeleton cs = actual.constructor();
- KVERIFY(!cs.isEmpty());
- KOMPARE("IFooStub", cs.name());
-}
-
-void StubCreationTest::basicDestructor()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{ public: IFoo(); virtual ~IFoo(); };\n");
-
- MethodSkeleton d = actual.destructor();
- KOMPARE("~IFooStub", d.name());
-}
-
-void StubCreationTest::basicInterface()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual void foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- MethodSkeleton ms;
- ms.setName("foo");
- ms.setReturnType("void");
- ms.setBody("");
- KOMPARE("IFooStub", actual.name());
- KOMPARE("IFoo", actual.super());
- KOMPARE(1, actual.methods().count());
- kompareMethods(ms, actual.methods()[0]);
-
- KVERIFY(!actual.hasMembers());
- KOMPARE(0, actual.memberCount());
-}
-
-void StubCreationTest::nonVoidReturnType()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual int foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- MethodSkeleton ms;
- ms.setName("foo");
- ms.setReturnType("int");
- ms.setBody("return m_foo;");
- KOMPARE("IFooStub", actual.name());
- KOMPARE(1, actual.methods().count());
- kompareMethods(ms, actual.methods()[0]);
- KOMPARE(1, actual.memberCount());
- KOMPARE("int m_foo", actual.member(0));
-}
-
-void StubCreationTest::nonVirtualMethod()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " int foo();\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- KVERIFY(actual.methods().isEmpty());
-}
-
-void StubCreationTest::privateMethod()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "private: virtual bool bar();\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- KVERIFY(actual.methods().isEmpty());
-}
-
-void StubCreationTest::signal()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "signals: void foo();\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- KVERIFY(actual.methods().isEmpty());
-}
-
-void StubCreationTest::signalWithEmptyPublic()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- "signals: void foo();\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- KVERIFY(actual.methods().isEmpty());
-}
-
-void StubCreationTest::prependNamespace()
-{
- ClassSkeleton actual = createStubClassFrom(
- "namespace Zoo { class IFoo {}; }\n");
-
- KVERIFY(!actual.isEmpty());
- KOMPARE("Zoo::IFooStub", actual.name());
-}
-
-void StubCreationTest::prependNestedNamespace()
-{
- ClassSkeleton actual = createStubClassFrom(
- "namespace Zoo { namespace Loo { class IFoo {}; } }\n");
-
- KVERIFY(!actual.isEmpty());
- KOMPARE("Zoo::Loo::IFooStub", actual.name());
-}
-
-void StubCreationTest::constMethod()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual void foo() const = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- MethodSkeleton expectedMtd;
- expectedMtd.setName("foo");
- expectedMtd.setReturnType("void");
- expectedMtd.setBody("");
- expectedMtd.setConst(true);
- KOMPARE(1, actual.methods().count());
- kompareMethods(expectedMtd, actual.methods()[0]);
-}
-
-void StubCreationTest::dropMemberConstness()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual const int foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- KOMPARE(1, actual.memberCount());
- KOMPARE("int m_foo", actual.member(0));
-}
-
-void StubCreationTest::pointerConstructorInitializer()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual IFoo* foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- ConstructorSkeleton cs = actual.constructor();
- KOMPARE(1, cs.initializerList().size());
- KOMPARE("m_foo(0)", cs.initializerList()[0]);
-}
-
-void StubCreationTest::boolConstructorInitializer()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual bool foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- ConstructorSkeleton cs = actual.constructor();
- KOMPARE(1, cs.initializerList().size());
- KOMPARE("m_foo(false)", cs.initializerList()[0]);
-}
-
-void StubCreationTest::intConstructorInitializer()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual int foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- ConstructorSkeleton cs = actual.constructor();
- KOMPARE(1, cs.initializerList().size());
- KOMPARE("m_foo(0)", cs.initializerList()[0]);
-}
-
-void StubCreationTest::noInitializerRegularClass()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual IFoo foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- ConstructorSkeleton cs = actual.constructor();
- KOMPARE(0, cs.initializerList().size());
-}
-
-void StubCreationTest::noInitializerVoidReturn()
-{
- ClassSkeleton actual = createStubClassFrom(
- "class IFoo\n"
- "{\n"
- "public:\n"
- " virtual void foo() = 0;\n"
- "};\n");
-
- KVERIFY(!actual.isEmpty());
- ConstructorSkeleton cs = actual.constructor();
- KOMPARE(0, cs.initializerList().size());
-}
-
-/////////////////////////// helpers //////////////////////////////////////////
-
-void StubCreationTest::kompareMethods(const MethodSkeleton& expected, const MethodSkeleton& actual)
-{
- KOMPARE(expected.name(), actual.name());
- KOMPARE(expected.returnType(), actual.returnType());
- KOMPARE(expected.arguments(), actual.arguments());
- KOMPARE(expected.body(), actual.body());
- KOMPARE(expected.isConst(), actual.isConst());
-}
-
-ClassSkeleton StubCreationTest::createStubClassFrom(const QByteArray& text)
-{
- ClassDeclaration* clazz = m_factory->classFromText(text);
- kDebug() << clazz;
- return m_constructor->morph(clazz);
-}
-
-QTEST_KDEMAIN( StubCreationTest, NoGUI )
-#include "stubcreationtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h (nonexistent)
@@ -1,28 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KDEVELOP_KDEVTEST_H_INCLUDED
-#define KDEVELOP_KDEVTEST_H_INCLUDED
-
-#include <qtest_kde.h>
-#include <QtTest/QTest>
-#include "xtest/kasserts.h"
-
-#endif // KDEVELOP_KDEVTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/kdevtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt (nonexistent)
@@ -1,24 +0,0 @@
-set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR})
-
-include_directories(${KDEVPlATFORM_INCLUDES})
-
-macro(kdev_add_test test_EXEC test_SRCS)
- qt4_automoc( ${test_SRCS} )
- kde4_add_unit_test(veritas-${test_EXEC} ${test_SRCS})
- target_link_libraries(veritas-${test_EXEC}
- veritascpp
- ${QT_QTTEST_LIBRARY}
- ${QT_QTXML_LIBRARY}
- ${KDE4_KDECORE_LIBS}
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
- ${KDE4_KTEXTEDITOR_LIBRARY})
-endmacro(kdev_add_test)
-
-kdev_add_test(unit-classskeleton classskeletontest.cpp)
-kdev_add_test(unit-stubcreation stubcreationtest.cpp)
-kdev_add_test(unit-constructorskeleton constructorskeletontest.cpp)
-kdev_add_test(unit-methodskeleton methodskeletontest.cpp)
-kdev_add_test(unit-classwriter classwritertest.cpp)
-kdev_add_test(unit-uutcreation uutcreationtest.cpp)
-kdev_add_test(unit-ktextdocumentstub ktextdocumentstubtest.cpp)
-kdev_add_test(unit-includewriter includewritertest.cpp)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp (nonexistent)
@@ -1,50 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include "constructorskeletontest.h"
-#include "kdevtest.h"
-#include "../constructorskeleton.h"
-
-using Veritas::Test::ConstructorSkeletonTest;
-using Veritas::ConstructorSkeleton;
-
-void ConstructorSkeletonTest::init()
-{
-}
-
-void ConstructorSkeletonTest::cleanup()
-{
-}
-
-void ConstructorSkeletonTest::instantiate()
-{
- ConstructorSkeleton cs;
- KVERIFY(cs.isEmpty());
- cs.setName("Foo");
- cs.setBody("int i=0;");
- cs.addInitializer("m_i(0)");
- cs.addInitializer("m_j(1)");
- KOMPARE("Foo", cs.name());
- KOMPARE("int i=0;", cs.body());
- KOMPARE(QStringList() << "m_i(0)" << "m_j(1)", cs.initializerList());
-}
-
-QTEST_MAIN( ConstructorSkeletonTest )
-#include "constructorskeletontest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h (nonexistent)
@@ -1,61 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#ifndef VERITAS_DOCUMENTACCESSSTUB_H
-#define VERITAS_DOCUMENTACCESSSTUB_H
-
-#include "../documentaccess.h"
-#include <QList>
-
-namespace Veritas { namespace Test {
-
-class DocumentAccessStub : public Veritas::DocumentAccess
-{
-public:
- DocumentAccessStub() { m_count = 0; }
- virtual ~DocumentAccessStub() {}
- virtual QString text(const KUrl&, const KDevelop::SimpleRange& range) const {
- m_ranges << range;
- QStringList lines;
- foreach(QString line, m_text.split("\n")) lines.append(line+"\n");
- if (lines.isEmpty()) return "";
- for (int i=lines.count(); i>range.end.line+1 && !lines.isEmpty(); i--)
- lines.removeLast();
- for (int i=0; i<range.start.line && !lines.isEmpty(); i++)
- lines.removeFirst();
- if (lines.isEmpty()) return "";
- lines[0] = lines[0].mid(range.start.column);
- if (range.start.line == range.end.line) {
- lines[0] = lines[0].left(range.end.column - range.start.column);
- } else if (m_text.split("\n").count() > range.end.line) {
- lines[lines.count()-1] = lines[lines.count()-1].left(range.end.column);
- }
- return lines.join("");
- }
- QString text(const KUrl& ) const { return m_text; }
- QString m_text;
- int m_count;
- mutable QList<KDevelop::SimpleRange> m_ranges;
-};
-
-}}
-
-#endif // VERITAS_DOCUMENTACCESSTUB_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/documentaccessstub.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp (nonexistent)
@@ -1,112 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#include "includewritertest.h"
-#include "kdevtest.h"
-#include "../includewriter.h"
-
-using Veritas::Test::IncludeWriterTest;
-using Veritas::IncludeSerializer;
-using Veritas::IncludeGuardSerializer;
-
-QString IncludeWriterTest::construct(const QString included, const QString includer)
-{
- QBuffer buff;
- IncludeSerializer is;
- is.write(included, includer, &buff);
- return QString(buff.data());
-}
-
-void IncludeWriterTest::sameDir()
-{
- QString included("/path/to/foo.h");
- QString includer("/path/to/bar.h");
-
- QString actual = construct(included, includer);
- QString expected = "#include \"foo.h\"";
-
- assertAlike(expected, actual);
-}
-
-void IncludeWriterTest::oneDirUp()
-{
- QString included("/path/to/foo.h");
- QString includer("/path/to/more/bar.h");
-
- QString actual = construct(included, includer);
- QString expected = "#include \"../foo.h\"";
-
- assertAlike(expected, actual);
-}
-
-void IncludeWriterTest::oneDirDown()
-{
- QString included("/path/to/more/foo.h");
- QString includer("/path/to/bar.h");
-
- QString actual = construct(included, includer);
- QString expected = "#include \"more/foo.h\"";
-
- assertAlike(expected, actual);
-}
-
-void IncludeWriterTest::guards()
-{
- QBuffer buff;
- IncludeGuardSerializer igs;
- QString filename("/path/to/foo.h");
-
- igs.writeOpen(filename, &buff);
- QString actual = QString(buff.data());
- QString expected("#ifndef PATH_TO_FOO_H_INCLUDED\n#define PATH_TO_FOO_H_INCLUDED");
-
- assertAlike(expected, actual);
-
- QBuffer buff2;
- igs.writeClose(filename, &buff2);
- actual = QString(buff2.data());
- expected = QString("#endif // PATH_TO_FOO_H_INCLUDED");
-
- assertAlike(expected, actual);
-}
-
-////////////////////// Helpers ///////////////////////////////////////////////
-
-/*! Construct a regular expression that is tolerant on
-spaces, newlines tabs etc */
-QRegExp IncludeWriterTest::whiteSpaceRegex(const QString& text)
-{
- QString ws("[\\s\\n\\r\\t]*");
- QString escaped = QRegExp::escape(text);
- return QRegExp(ws + escaped + ws);
-}
-
-// custom assertion
-void IncludeWriterTest::assertAlike(const QString& expected, const QString& actual)
-{
- QRegExp pattern = whiteSpaceRegex(expected);
- KVERIFY_MSG(pattern.isValid(), pattern.errorString() + " " +pattern.pattern());
- QString failMsg = QString("\nExpected:\n%1\nActual:\n%2").arg(expected).arg(actual);
- KVERIFY_MSG(pattern.exactMatch(actual), failMsg);
-}
-
-QTEST_MAIN( IncludeWriterTest )
-#include "includewritertest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp (nonexistent)
@@ -1,157 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#include "ktextdocumentstubtest.h"
-
-#include "kdevtest.h"
-
-#include "documentaccessstub.h"
-#include <language/editor/simplerange.h>
-#include <ktexteditor/range.h>
-#include <ktexteditor/cursor.h>
-
-using Veritas::Test::DocumentAccessStubTest;
-using Veritas::Test::DocumentAccessStub;
-using KTextEditor::Range;
-using KTextEditor::Cursor;
-using KDevelop::SimpleRange;
-
-Q_DECLARE_METATYPE(KTextEditor::Range)
-Q_DECLARE_METATYPE(KTextEditor::Cursor)
-
-void DocumentAccessStubTest::init()
-{
- qRegisterMetaType<Range>();
- qRegisterMetaType<Cursor>();
-}
-
-void DocumentAccessStubTest::cleanup()
-{
-}
-
-void DocumentAccessStubTest::text()
-{
- KUrl f;
- DocumentAccessStub* stub = new DocumentAccessStub;
- stub->m_text = QString("boo");
- KOMPARE("boo", stub->text(f));
-
- stub = new DocumentAccessStub();
- stub->m_text = "boo\nhoo";
- KOMPARE("boo\nhoo", stub->text(f));
-}
-
-void DocumentAccessStubTest::textRange_data()
-{
- QTest::addColumn<QString>("input");
- QTest::addColumn<Range>("range");
- QTest::addColumn<QString>("expected");
-
- QString in("boo\nho\nzoop");
- QTest::newRow("01") << in << Range(0,0,0,1) << "b";
- QTest::newRow("02") << in << Range(0,1,0,2) << "o";
- QTest::newRow("03") << in << Range(0,0,0,3) << "boo";
- QTest::newRow("04") << in << Range(0,0,1,0) << "boo\n";
- QTest::newRow("05") << in << Range(1,0,1,2) << "ho";
- QTest::newRow("06") << in << Range(2,0,2,3) << "zoo";
- QTest::newRow("07") << in << Range(0,0,1,2) << "boo\nho";
- QTest::newRow("08") << in << Range(1,1,2,1) << "o\nz";
- QTest::newRow("09") << in << Range(0,0,2,4) << "boo\nho\nzoop";
- QTest::newRow("10") << in << Range(2,3,2,4) << "p";
- QTest::newRow("11") << in << Range(1,2,2,0) << "\n";
- QTest::newRow("12") << in << Range(0,0,4,0) << in + "\n"; // dont care about trailing newlines
-}
-
-void DocumentAccessStubTest::textRange()
-{
- QFETCH(QString, expected);
- DocumentAccessStub* stub = new DocumentAccessStub;
- QFETCH(QString, input);
- stub->m_text = input;
- QFETCH(Range, range);
- KUrl url;
- SimpleRange sr(range);
- QString actual = stub->text(url,sr);
- KOMPARE(expected, actual);
-}
-
-// void DocumentAccessStubTest::textRangeLines()
-// {
-// DocumentAccessStub* stub = new DocumentAccessStub;
-// stub->m_text = "foo\nbar\nbaz\n";
-// Range range(1,0,1,3);
-// QStringList actual = stub->textLines(range);
-// KOMPARE(QStringList() << "bar", actual);
-// }
-//
-// void DocumentAccessStubTest::character_data()
-// {
-// QTest::addColumn<QString>("input");
-// QTest::addColumn<Cursor>("cursor");
-// QTest::addColumn<QChar>("expected");
-//
-// QString in("boo\nho\nzoap");
-// QTest::newRow("01") << in << Cursor(0,0) << QChar('b');
-// QTest::newRow("02") << in << Cursor(0,1) << QChar('o');
-// QTest::newRow("03") << in << Cursor(0,3) << QChar('\n');
-// QTest::newRow("04") << in << Cursor(1,0) << QChar('h');
-// QTest::newRow("05") << in << Cursor(2,2) << QChar('a');
-// QTest::newRow("06") << in << Cursor(2,3) << QChar('p');
-// }
-//
-// void DocumentAccessStubTest::character()
-// {
-// DocumentAccessStub* stub = new DocumentAccessStub;
-// QFETCH(QString, input);
-// stub->m_text = input;
-// QFETCH(Cursor, cursor);
-// QChar actual = stub->character(cursor);
-// QFETCH(QChar, expected);
-// KOMPARE(expected, actual);
-// }
-//
-// void DocumentAccessStubTest::line_data()
-// {
-// QTest::addColumn<QString>("input");
-// QTest::addColumn<int>("line");
-// QTest::addColumn<QString>("expected");
-//
-// QString in("boo\nho\nzoap\n\n");
-// QTest::newRow("01") << in << 0 << "boo\n";
-// QTest::newRow("02") << in << 1 << "ho\n";
-// QTest::newRow("03") << in << 2 << "zoap\n";
-// QTest::newRow("04") << in << 3 << "\n";
-// }
-//
-// void DocumentAccessStubTest::line()
-// {
-// DocumentAccessStub* stub = new DocumentAccessStub;
-// QFETCH(QString, input);
-// stub->m_text = input;
-// QFETCH(int, line);
-// QString actual = stub->line(line);
-// QFETCH(QString, expected);
-// KOMPARE(expected, actual);
-// }
-
-
-QTEST_MAIN( DocumentAccessStubTest )
-#include "ktextdocumentstubtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h (nonexistent)
@@ -1,41 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
-#define QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas { namespace Test {
-
-/*! Might want to remove it, testing basic value classes is not so useful */
-class ConstructorSkeletonTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void instantiate();
-};
-
-}}
-
-#endif // QTEST_CONSTRUCTORSKELETONTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/constructorskeletontest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h (nonexistent)
@@ -1,41 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef QTEST_STUBCLASSTEST_H_INCLUDED
-#define QTEST_STUBCLASSTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas { namespace Test {
-
-/*! Does not deserve it's own testcase */
-class ClassSkeletonTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void construct();
-};
-
-}}
-
-#endif // QTEST_STUBCLASSTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp (nonexistent)
@@ -1,183 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include "classdeclarationfactory.h"
-
-// kdevplatform
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/duchainlock.h>
-
-// kdevelop
-#include <language/duchain/classdeclaration.h>
-#include "../cppduchain/declarationbuilder.h"
-#include "../cppduchain/environmentmanager.h"
-#include "../cppduchain/usebuilder.h"
-#include "../parser/parser.h"
-#include "../parser/parsesession.h"
-#include "../parser/rpp/preprocessor.h"
-#include "../parser/rpp/pp-engine.h"
-
-using Veritas::Test::DeclarationFactory;
-using namespace KDevelop;
-using namespace Cpp;
-
-int DeclarationFactory::m_count = 0;
-
-DeclarationFactory::DeclarationFactory()
-{
- m_lock = new DUChainWriteLocker(DUChain::lock());
- m_lock->unlock();
-}
-
-DeclarationFactory::~DeclarationFactory()
-{
- if (m_lock && m_lock->locked()) {
- m_lock->unlock();
- delete m_lock;
- }
-}
-
-namespace
-{
-ClassDeclaration* classDeclarationIn(DUContext* ctx)
-{
- Q_ASSERT(ctx->localDeclarations().count() !=0 );
- Declaration* dcl = ctx->localDeclarations().first();
- Q_ASSERT(dcl);
- ClassDeclaration* clazz = dynamic_cast<ClassDeclaration*>(dcl);
- Q_ASSERT(clazz);
- return clazz;
-}
-}
-
-ClassDeclaration* DeclarationFactory::classFromText(const QByteArray& text)
-{
- if (m_lock->locked()) m_lock->unlock();
- TopDUContext* top = parseText(text);
- Q_ASSERT(top);
- m_tops << top;
- if (!m_lock->locked()) m_lock->lock();
- DUContext* context = top;
-
- if (context->localDeclarations().count() == 0) {
- // see if we'r in a namespace. if so extract the class from there
- QVector<DUContext*> children = context->childContexts();
- Q_ASSERT(!children.isEmpty());
- Q_ASSERT(children[0]->type() == DUContext::Namespace);
- context = children[0];
- if (context->localDeclarations().count() == 0) {
- // still no classdeclaration, try one more
- QVector<DUContext*> children = context->childContexts();
- Q_ASSERT(!children.isEmpty());
- Q_ASSERT(children[0]->type() == DUContext::Namespace);
- context = children[0];
- }
- }
-
- ClassDeclaration* clazz = classDeclarationIn(context);
- if (m_lock->locked()) m_lock->unlock();
- return clazz;
-}
-
-QList<Declaration*> DeclarationFactory::variablesFromText(const QByteArray& text)
-{
- if (m_lock->locked()) m_lock->unlock();
- TopDUContext* top = parseText(text);
- Q_ASSERT(top);
- m_tops << top;
- if (!m_lock->locked()) m_lock->lock();
- Q_ASSERT(top->localDeclarations().count() !=0 );
- QList<Declaration*> ret;
- foreach(Declaration* dcl, top->localDeclarations()) {
- if (dcl && (dcl->kind() == Declaration::Instance) && (dcl->isDefinition())) {
- ret << dcl;
- }
- }
- if (m_lock->locked()) m_lock->unlock();
- return ret;
-}
-
-QList<Declaration*> dcls(DUContext* ctx)
-{
- QList<Declaration*> ret;
- foreach(Declaration* dcl, ctx->localDeclarations()) {
- if ((dcl->kind() == Declaration::Instance) && (dcl->isDefinition())) {
- DelayedType::Ptr type = dcl->type<DelayedType>();
- if (!type || type->kind() != DelayedType::Unresolved) {
- kDebug() << "Is a resolved type, or delayed.";
- } else {
- ret << dcl;
- }
- }
- }
- foreach(DUContext* cctx, ctx->childContexts()) {
- ret += dcls(cctx);
- }
- return ret;
-}
-
-QList<Declaration*> DeclarationFactory::unresolvedVariablesFromText(const QByteArray& text)
-{
- if (m_lock->locked()) m_lock->unlock();
- TopDUContext* top = parseText(text);
- Q_ASSERT(top);
- m_tops << top;
- if (!m_lock->locked()) m_lock->lock();
- Q_ASSERT(top->localDeclarations().count() !=0 );
- QList<Declaration*> ret = dcls(top);
- if (m_lock->locked()) m_lock->unlock();
- return ret;
-}
-
-void DeclarationFactory::release()
-{
- foreach(TopDUContext* top, m_tops) {
- if (top) {
- TopDUContextPointer tp(top);
- DUChain::self()->removeDocumentChain(static_cast<TopDUContext*>(top));
- Q_ASSERT(!tp);
- }
- }
- m_lock->unlock();
-}
-
-TopDUContext* DeclarationFactory::parseText(const QByteArray& text)
-{
- ParseSession* session = new ParseSession();
- rpp::Preprocessor preprocessor;
- rpp::pp pp(&preprocessor);
- session->setContentsAndGenerateLocationTable(
- pp.processFile("anonymous", text));
-
- Parser parser(&m_control);
- TranslationUnitAST* ast = parser.parse(session);
- ast->session = session;
-
- IndexedString url(QString("/internal/%1").arg(m_count));
- DeclarationBuilder definitionBuilder(session);
- Cpp::EnvironmentFilePointer file(new Cpp::EnvironmentFile(url,0));
- TopDUContext* top = definitionBuilder.buildDeclarations(file, ast);
-
- UseBuilder useBuilder(session);
- useBuilder.buildUses(ast);
-
- delete session;
- return top;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp (nonexistent)
@@ -1,151 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include "classwritertest.h"
-#include "../classwriter.h"
-#include "../classskeleton.h"
-#include "kdevtest.h"
-#include <KDebug>
-#include <QRegExp>
-
-using Veritas::Test::ClassWriterTest;
-using Veritas::ClassSerializer;
-using Veritas::ClassSkeleton;
-
-/////////////////////////// test commands ////////////////////////////////////
-
-void ClassWriterTest::noMethods()
-{
- ClassSkeleton cs;
- cs.setName("Foo");
-
- QString actual = serialize(cs);
- QString expected("class Foo { };");
-
- assertAlike(expected, actual);
-}
-
-void ClassWriterTest::method()
-{
- ClassSkeleton cs;
- cs.setName("Foo");
- MethodSkeleton ms;
- ms.setName("foo");
- ms.setVirtual();
- cs.addMethod(ms);
-
- QString expected("class Foo { public: virtual void foo() { } };");
- QString actual = serialize(cs);
-
- assertAlike(expected, actual);
-}
-
-void ClassWriterTest::constructor()
-{
- ClassSkeleton cs;
- cs.setName("Foo");
- ConstructorSkeleton ctr;
- ctr.setName("Foo");
- ctr.addInitializer("m_foo(0)");
- ctr.setAccess(Veritas::Public);
- cs.setConstructor(ctr);
-
- QString actual = serialize(cs);
- QString expected =
- "class Foo { public: Foo() : m_foo(0) { } }; ";
-
- assertAlike(expected, actual);
-}
-
-void ClassWriterTest::constMethod()
-{
- ClassSkeleton cs;
- cs.setName("Foo");
- MethodSkeleton ms;
- ms.setName( "foo" );
- ms.setConst( true );
- ms.setReturnType( "void" );
- cs.addMethod( ms );
-
- QString actual = serialize(cs);
- QVERIFY(actual.contains( " const" ));
-}
-
-void ClassWriterTest::singleNamespace()
-{
- ClassSkeleton cs;
- cs.setName("FooSpace::Foo");
-
- QString actual = serialize(cs);
- QString expected =
- "namespace FooSpace { "
- "class Foo { }; } ";
-
- assertAlike(expected, actual);
-}
-
-void ClassWriterTest::nestedNamespace()
-{
- ClassSkeleton cs;
- cs.setName("FooSpace::BarSpace::Foo");
-
- QString actual = serialize(cs);
- QString expected =
- "namespace FooSpace { namespace BarSpace { "
- "class Foo { }; }} ";
-
- assertAlike(expected, actual);
-}
-
-
-////////////////////////// helpers ///////////////////////////////////////////
-
-/*! Construct a regular expression that is tolerant on
-spaces, newlines tabs etc */
-QRegExp ClassWriterTest::whiteSpaceRegex(const QString& text)
-{
- QString ws("[\\s\\n\\r\\t]*");
- QString escaped = QRegExp::escape(text);
- QStringList r = escaped.split(" ");
- r.push_front(ws);
- r.push_back(ws);
- return QRegExp(r.join(ws));
-}
-
-// helper
-QString ClassWriterTest::serialize(const ClassSkeleton& cs)
-{
- QBuffer buff;
- ClassSerializer cw;
- cw.write(cs, &buff);
- return QString(buff.data());
-}
-
-// custom assertion
-void ClassWriterTest::assertAlike(const QString& expected, const QString& actual)
-{
- QRegExp pattern = whiteSpaceRegex(expected);
- KVERIFY_MSG(pattern.isValid(), pattern.errorString() + " " +pattern.pattern());
- QString failMsg = QString("\nExpected:\n%1\nActual:\n%2").arg(expected).arg(actual);
- KVERIFY_MSG(pattern.exactMatch(actual), failMsg);
-}
-
-QTEST_MAIN( ClassWriterTest )
-#include "classwritertest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h (nonexistent)
@@ -1,72 +0,0 @@
-/*
- * KDevelop xUnit test support
- * Copyright 2008 Manuel Breugelmans
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef QTEST_STUBCREATIONTEST_H_INCLUDED
-#define QTEST_STUBCREATIONTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include "../classskeleton.h"
-
-
-namespace Veritas
-{
-class StubConstructor;
-namespace Test
-{
-
-class DeclarationFactory;
-class StubCreationTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void appendStubToClassName();
- void basicConstructor();
- void basicDestructor();
- void basicInterface();
- void nonVoidReturnType();
- void nonVirtualMethod();
- void privateMethod();
- void signal();
- void signalWithEmptyPublic();
- void prependNamespace();
- void prependNestedNamespace();
- void constMethod();
- void dropMemberConstness();
- void pointerConstructorInitializer();
- void intConstructorInitializer();
- void boolConstructorInitializer();
- void noInitializerRegularClass();
- void noInitializerVoidReturn();
-
-private:
- ClassSkeleton createStubClassFrom(const QByteArray&);
- void kompareMethods(const MethodSkeleton& expected, const MethodSkeleton& actual);
-
-private:
- DeclarationFactory* m_factory;
- StubConstructor* m_constructor;
-};
-
-}}
-
-#endif // QTEST_STUBCREATIONTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/stubcreationtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h (nonexistent)
@@ -1,62 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#ifndef VERITAS_CPP_CLASSDECLARATIONFACTORY
-#define VERITAS_CPP_CLASSDECLARATIONFACTORY
-
-#include <QList>
-#include "../veritascppexport.h"
-#include "../parser/control.h"
-
-namespace KDevelop { class ClassDeclaration; class TopDUContext; class DUChainWriteLocker; class Declaration;}
-
-namespace Veritas { namespace Test {
-
-class VERITASCPP_EXPORT DeclarationFactory
-{
-public:
- DeclarationFactory();
- virtual ~DeclarationFactory();
-
- /*! Extract a classdeclaration from a piece of code in @p text.
- * Try the first declaration, and the first declaration in namespaces.
- * This method is rather conservative, ie loads of Q_ASSERT's */
- KDevelop::ClassDeclaration* classFromText(const QByteArray& text);
-
- QList<KDevelop::Declaration*> variablesFromText(const QByteArray& text);
- QList<KDevelop::Declaration*> unresolvedVariablesFromText(const QByteArray& text);
-
- /*! Call this after you are done with a declaration.
- Cleanup of created topducontexts. */
- void release();
-
- KDevelop::DUChainWriteLocker* m_lock;
-
-private:
- KDevelop::TopDUContext* parseText(const QByteArray& text);
- static int m_count;
- Control m_control;
- QList<KDevelop::TopDUContext*> m_tops;
-};
-
-}}
-
-#endif // VERITAS_CPP_CLASSDECLARATIONFACTORY
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classdeclarationfactory.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp (nonexistent)
@@ -1,325 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "uutcreationtest.h"
-#include "kdevtest.h"
-#include "classdeclarationfactory.h"
-#include "../uutconstructor.h"
-#include "../classskeleton.h"
-#include "documentaccessstub.h"
-#include <language/duchain/use.h>
-
-using Veritas::Test::UUTCreationTest;
-using Veritas::Test::DeclarationFactory;
-using Veritas::Test::DocumentAccessStub;
-using Veritas::UUTConstructor;
-using Veritas::ClassSkeleton;
-using Veritas::MethodSkeleton;
-
-using namespace KDevelop;
-
-void UUTCreationTest::init()
-{
- m_factory = new DeclarationFactory;
- m_document = new DocumentAccessStub;
- m_constructor = new UUTConstructor;
- m_constructor->setDocumentAccess(m_document);
-}
-
-void UUTCreationTest::cleanup()
-{
- if (m_factory) delete m_factory;
- if (m_document) delete m_document;
- if (m_constructor) delete m_constructor;
-}
-
-void UUTCreationTest::unresolvedVariable()
-{
- QList<Declaration*> variables = m_factory->unresolvedVariablesFromText("Foo f;");
- Q_ASSERT(variables.count() == 1);
- ClassSkeleton cs = m_constructor->morph(variables[0]);
-
- KVERIFY(!cs.isEmpty());
- KOMPARE("Foo", cs.name());
- KVERIFY(cs.methods().isEmpty());
- KOMPARE(0, cs.memberCount());
-}
-
-void UUTCreationTest::resolvedVariables()
-{
- QList<Declaration*> variables = m_factory->variablesFromText(
- "class Foo {}; int i; Foo f;");
- Q_ASSERT(variables.count() == 2);
-
- KVERIFY(m_constructor->morph(variables[0]).isEmpty());
- KVERIFY(m_constructor->morph(variables[1]).isEmpty());
-}
-
-// helper to construct a class from it's implementation
-ClassSkeleton UUTCreationTest::classFromImplementation(const QByteArray& text)
-{
- QList<Declaration*> variables =
- m_factory->unresolvedVariablesFromText(text);
- m_document->m_text = QString(text);
- if (!variables.count()) return ClassSkeleton();
- return m_constructor->morph(variables[0]);
-}
-
-void UUTCreationTest::singleUse()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo moo; moo.foo(); } ");
-
- assertNamed("Foo", cs);
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::tdd_nonVoidReturn()
-{
- TDD_TODO;
-
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; int i = f.foo(); } ");
-
- assertNamed("Foo", cs);
- KOMPARE(1, cs.methods().count());
-
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("int", ms.returnType());
- assertNoArguments(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::singleArgument()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; int i; f.foo(i); } ");
-
- assertNamed("Foo", cs);
- KOMPARE(1, cs.methods().count());
-
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("(int)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::tdd_pointerUse()
-{
- TDD_TODO;
-
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo *f; f->foo(); } ");
- assertNamed("Foo", cs);
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::multipleUses()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f.foo(); f.foo1(); } ");
-
- assertNamed("Foo", cs);
- KOMPARE(2, cs.methods().count());
-
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- assertNoArguments(ms);
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-
- MethodSkeleton ms2 = cs.methods()[1];
- assertNamed("foo1", ms2);
- assertNoArguments(ms2);
- assertReturnsVoid(ms2);
- assertDefaultBody(ms2);
-}
-
-void UUTCreationTest::useInIfConstruct()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; if (true) { f.foo(); } } ");
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::assertSimpleFooMethod(const ClassSkeleton& cs)
-{
- KOMPARE(1, cs.methods().count());
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- assertNoArguments(ms);
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::spacesBeforeDot()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f .foo(); } ");
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::spacesAfterDot()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f. foo(); } ");
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::methodOnNextLine()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f.\nfoo(); } ");
- assertSimpleFooMethod(cs);
-}
-
-void UUTCreationTest::dataMemberUse()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f.m_foo; } ");
- KOMPARE(0, cs.methods().count());
-}
-
-void UUTCreationTest::multipleParameters()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; int i; char c; f.foo(i,c); } ");
-
- KOMPARE(1, cs.methods().count());
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("(int, char)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::classParameter()
-{
- ClassSkeleton cs = classFromImplementation(
- "class Bar; void fun() { Foo f; Bar b; f.foo(b); } ");
-
- KOMPARE(1, cs.methods().count());
- MethodSkeleton ms = cs.methods()[0];
- KOMPARE("(Bar)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::threeParameters()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; int i; char c; bool b; f.foo(i,c,b); } ");
-
- KOMPARE(1, cs.methods().count());
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("(int, char, bool)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::functionUseWithIdenticalName()
-{
- ClassSkeleton cs = classFromImplementation(
- "void f() {} void fun() { Foo f; f.foo(); f(); } ");
- assertSimpleFooMethod(cs);
-}
-
-
-void UUTCreationTest::multipleParametersSmearedOverMultipleLines()
-{
- kDebug() << 4;
- ClassSkeleton cs = classFromImplementation(
- "void fun() {\n"
- " Foo f; int i; char c;\n"
- " f.foo(\n"
- " i,\n"
- " c);\n"
- "}\n");
-
- KOMPARE(1, cs.methods().count());
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("(int, char)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::nestedBraces()
-{
- ClassSkeleton cs = classFromImplementation(
- "int fn() {\n"
- " return 0;\n"
- "}\n"
- "void fun() {\n"
- " Foo f;\n"
- " int i;\n"
- " f.foo(fn());\n"
- "}\n");
- MethodSkeleton ms = cs.methods()[0];
- assertNamed("foo", ms);
- KOMPARE("(int)", ms.arguments());
- assertReturnsVoid(ms);
- assertDefaultBody(ms);
-}
-
-void UUTCreationTest::noSemicolon()
-{
- ClassSkeleton cs = classFromImplementation(
- "void fun() { Foo f; f.foo() } ");
- assertNamed("Foo", cs);
- KOMPARE(0, cs.methods().count());
-}
-
-//////////////////// Custom assertions ///////////////////////////////////////
-
-void UUTCreationTest::assertReturnsVoid(const MethodSkeleton& ms)
-{
- QString failMsg = QString("Was expecting void return type but got: %1").arg(ms.returnType());
- KOMPARE_MSG("void", ms.returnType(), failMsg);
-}
-
-void UUTCreationTest::assertNoArguments(const MethodSkeleton& ms)
-{
- QString failMsg = QString("Was expecting no arguments but got: %1").arg(ms.returnType());
- KOMPARE_MSG("()", ms.arguments(), failMsg);
-}
-
-void UUTCreationTest::assertNamed(const QString& name, const ClassSkeleton& t)
-{
- QString failMsg = QString("Wrong name. Expected : ``%1'' but got ``%2''").arg(name).arg(t.name());
- KOMPARE_MSG(name, t.name(), failMsg);
-}
-
-void UUTCreationTest::assertNamed(const QString& name, const MethodSkeleton& t)
-{
- QString failMsg = QString("Wrong name. Expected : ``%1'' but got ``%2''").arg(name).arg(t.name());
- KOMPARE_MSG(name, t.name(), failMsg);
-}
-
-void UUTCreationTest::assertDefaultBody(const MethodSkeleton& ms)
-{
- KOMPARE("// GENERATED", ms.body());
-}
-
-QTEST_MAIN( UUTCreationTest )
-#include "uutcreationtest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h (nonexistent)
@@ -1,55 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef QTEST_CLASSWRITERTEST_H_INCLUDED
-#define QTEST_CLASSWRITERTEST_H_INCLUDED
-
-#include <QObject>
-#include <QString>
-#include <QRegExp>
-
-namespace Veritas
-{
-class ClassSkeleton;
-
-namespace Test
-{
-
-/*! @unitundertest Veritas::ClassSerializer */
-class ClassWriterTest : public QObject
-{
-Q_OBJECT
-private slots:
- void noMethods();
- void method();
- void constructor();
- void constMethod();
- void singleNamespace();
- void nestedNamespace();
-
-private:
- QRegExp whiteSpaceRegex(const QString& text);
- QString serialize(const ClassSkeleton& cs);
- void assertAlike(const QString& expected, const QString& actual);
-};
-
-}}
-
-#endif // QTEST_CLASSWRITERTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classwritertest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp (nonexistent)
@@ -1,48 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include "classskeletontest.h"
-#include "kdevtest.h"
-#include "../classskeleton.h"
-
-using Veritas::ClassSkeleton;
-using Veritas::Test::ClassSkeletonTest;
-
-void ClassSkeletonTest::init()
-{
-}
-
-void ClassSkeletonTest::cleanup()
-{
-}
-
-void ClassSkeletonTest::construct()
-{
- ClassSkeleton sc;
- KVERIFY(sc.isEmpty());
- KVERIFY(sc.name().isEmpty());
- KVERIFY(sc.methods().isEmpty());
- sc.setName("Foo");
- KOMPARE("Foo", sc.name());
- KVERIFY(!sc.isEmpty());
-}
-
-QTEST_MAIN( ClassSkeletonTest )
-#include "classskeletontest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/classskeletontest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h (nonexistent)
@@ -1,84 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef QTEST_UUTCREATIONTEST_H_INCLUDED
-#define QTEST_UUTCREATIONTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas
-{
-class UUTConstructor;
-class MethodSkeleton;
-class ClassSkeleton;
-
-namespace Test
-{
-
-class DocumentAccessStub;
-class DeclarationFactory;
-
-/*! @unitundertest Veritas::UUTConstructor */
-class UUTCreationTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void unresolvedVariable();
- void resolvedVariables();
- void singleUse();
- void tdd_nonVoidReturn();
- void singleArgument();
- void tdd_pointerUse();
- void multipleUses();
- void useInIfConstruct();
- void spacesBeforeDot();
- void spacesAfterDot();
- void methodOnNextLine();
- void dataMemberUse();
- void multipleParameters();
- void classParameter();
- void threeParameters();
- void functionUseWithIdenticalName();
- void multipleParametersSmearedOverMultipleLines();
- void nestedBraces();
- void noSemicolon();
-
-private:
- void assertReturnsVoid(const MethodSkeleton& ms);
- void assertNoArguments(const MethodSkeleton& ms);
- void assertNamed(const QString& name, const MethodSkeleton&);
- void assertNamed(const QString& name, const ClassSkeleton&);
- void assertDefaultBody(const MethodSkeleton&);
- ClassSkeleton classFromImplementation(const QByteArray& text);
- void assertSimpleFooMethod(const ClassSkeleton& cs);
-
-private:
- DeclarationFactory* m_factory;
- DocumentAccessStub* m_document;
- UUTConstructor* m_constructor;
-};
-
-}}
-
-
-#endif // QTEST_UUTCREATIONTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/uutcreationtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp (nonexistent)
@@ -1,52 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include "methodskeletontest.h"
-#include "kdevtest.h"
-#include "../methodskeleton.h"
-
-using Veritas::Test::MethodSkeletonTest;
-using Veritas::MethodSkeleton;
-
-void MethodSkeletonTest::init()
-{
-}
-
-void MethodSkeletonTest::cleanup()
-{
-}
-
-void MethodSkeletonTest::construct()
-{
- MethodSkeleton ms;
- KVERIFY(ms.isEmpty());
- ms.setName("foo");
- ms.setBody("int i=0;");
- ms.setArguments("(int j)");
- ms.setReturnType("int");
- KVERIFY(!ms.isEmpty());
- KOMPARE("foo", ms.name());
- KOMPARE("int i=0;", ms.body());
- KOMPARE("(int j)", ms.arguments());
- KOMPARE("int", ms.returnType());
-}
-
-QTEST_MAIN( MethodSkeletonTest )
-#include "methodskeletontest.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h (nonexistent)
@@ -1,41 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef QTEST_METHODSKELETONTEST_H_INCLUDED
-#define QTEST_METHODSKELETONTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-
-namespace Veritas { namespace Test {
-
-/*! A bit redundant */
-class MethodSkeletonTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void construct();
-};
-
-}}
-
-#endif // QTEST_METHODSKELETONTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/methodskeletontest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h (nonexistent)
@@ -1,52 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#ifndef QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
-#define QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include <KUrl>
-
-namespace Veritas { namespace Test {
-
-class DocumentAccessStubTest : public QObject
-{
-Q_OBJECT
-private slots:
- void init();
- void cleanup();
-
- void text();
- void textRange();
- void textRange_data();
-// void textRangeLines();
-// void character();
-// void character_data();
-// void line();
-// void line_data();
-
-private:
- KUrl m_someUrl;
-};
-
-}}
-
-#endif // QTEST_KTEXTDOCUMENTSTUBTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/ktextdocumentstubtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h (nonexistent)
@@ -1,48 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef QTEST_INCLUDEWRITERTEST_H_INCLUDED
-#define QTEST_INCLUDEWRITERTEST_H_INCLUDED
-
-#include <QtCore/QObject>
-#include <QString>
-#include <QRegExp>
-
-namespace Veritas { namespace Test {
-
-/*! @unitundertest Veritas::IncludeSerializer */
-class IncludeWriterTest : public QObject
-{
-Q_OBJECT
-private slots:
- void sameDir();
- void oneDirUp();
- void oneDirDown();
- void guards();
-
-private:
- QRegExp whiteSpaceRegex(const QString& text);
- void assertAlike(const QString& expected, const QString& actual);
- QString construct(const QString included, const QString includer);
-};
-
-}}
-
-#endif // QTEST_INCLUDEWRITERTEST_H_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/tests/includewritertest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h (nonexistent)
@@ -1,64 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#ifndef VERITASCPP_UUTCONTEXTACTION_INCLUDED
-#define VERITASCPP_UUTCONTEXTACTION_INCLUDED
-
-#include "veritascppexport.h"
-#include <QObject>
-
-class KAction;
-namespace KDevelop { class Context; class ContextMenuExtension; class Declaration; }
-
-namespace Veritas
-{
-class UUTConstructor;
-
-/*! Context menu action to create a unit under test skeleton based
- on it's implementation.
- @see Veritas::UUTConstructor */
-class VERITASCPP_EXPORT UUTContextAction : public QObject
-{
-Q_OBJECT
-public:
- UUTContextAction(QObject* parent=0);
- ~UUTContextAction();
-
- /*! initialization */
- void setup();
-
- /*! Checks if @param context should get an uut action and adds it to
- @param menu if so. Otherwise nothing happens. */
- void appendTo(KDevelop::ContextMenuExtension& menu, KDevelop::Context* context);
-
-private slots:
- void createImplementation();
-
-private:
- KDevelop::Declaration* m_clazz;
- KAction* m_createImplementation;
- UUTConstructor* m_constructor;
-};
-
-}
-
-#endif // VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h (nonexistent)
@@ -1,63 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#ifndef VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
-#define VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
-
-#include "veritascppexport.h"
-#include <QObject>
-
-class KAction;
-namespace KDevelop { class Context; class ContextMenuExtension; }
-namespace KDevelop { class ClassDeclaration; }
-
-namespace Veritas
-{
-
-/*! Provides a context menu action on class declarations which
- allows for stub code generation.
- @see Veritas::StubConstructor */
-class VERITASCPP_EXPORT StubContextAction : public QObject
-{
-Q_OBJECT
-public:
- StubContextAction(QObject* parent=0);
- ~StubContextAction();
-
- /*! initialization */
- void setup();
-
- /*! Checks if @param context should get an uut action and adds it to
- @param menu if so. Otherwise nothing happens. */
- void appendTo(KDevelop::ContextMenuExtension& menu, KDevelop::Context* context);
-
-private slots:
- void constructStub();
-
-private:
- KDevelop::ClassDeclaration* m_clazz;
- KAction* m_constructStub;
-};
-
-}
-
-#endif // VERITAS_CPP_STUBCONTEXTACTION_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt (nonexistent)
@@ -1,39 +0,0 @@
-remove_definitions( -DKDE_DEFAULT_DEBUG_AREA=9007 )
-add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9003 )
-
-include_directories(
- ${cpp_SOURCE_DIR}
- ${cpp_BINARY_DIR})
-
-#add_subdirectory(tests)
-
-########### next target ###############
-
-set(veritascppsupport_LIB_SRCS
- testswitch.cpp
- classskeleton.cpp
- constructorskeleton.cpp
- methodskeleton.cpp
- stubconstructor.cpp
- classwriter.cpp
- stubcontextaction.cpp
- uutconstructor.cpp
- documentaccess.cpp
- uutcontextaction.cpp
- tests/classdeclarationfactory.cpp
-)
-
-# Note: This library doesn't follow API/ABI/BC rules and shouldn't have a SOVERSION
-# Its only purpose is to support the plugin without needing to add all source files
-# to the plugin target
-
-kde4_add_library(veritascpp SHARED ${veritascppsupport_LIB_SRCS})
-target_link_libraries(veritascpp
- kdev4cppduchain
- kdev4cppparser
- kdev4cpprpp
- ${KDEVPLATFORM_LANGUAGE_LIBRARIES}
- ${KDEVPLATFORM_INTERFACES_LIBRARIES}
- ${KDE4_KTEXTEDITOR_LIBS})
-install(TARGETS veritascpp ${INSTALL_TARGETS_DEFAULT_ARGS})
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp (nonexistent)
@@ -1,40 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include "constructorskeleton.h"
-
-using Veritas::ConstructorSkeleton;
-
-ConstructorSkeleton::ConstructorSkeleton()
-{}
-
-
-ConstructorSkeleton::~ConstructorSkeleton()
-{}
-
-void ConstructorSkeleton::addInitializer(const QString& initializer)
-{
- m_initializerList << initializer;
-}
-
-QStringList ConstructorSkeleton::initializerList() const
-{
- return m_initializerList;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.h (nonexistent)
@@ -1,76 +0,0 @@
-/*
- * KDevelop xUnit test support
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef VERITAS_CLASSSKELETON_INCLUDED_H
-#define VERITAS_CLASSSKELETON_INCLUDED_H
-
-#include <QtCore/QString>
-#include "veritascppexport.h"
-#include "constructorskeleton.h"
-#include "methodskeleton.h"
-
-namespace Veritas
-{
-
-/*! Lightweight struct which stores C++ Class information (simple AST)
- * It is intended to be used for code generation. */
-class VERITASCPP_EXPORT ClassSkeleton
-{
-public:
- ClassSkeleton();
- virtual ~ClassSkeleton();
-
- bool isEmpty() const;
-
- QString name() const;
- QString super() const;
- ConstructorSkeleton constructor() const;
- MethodSkeleton destructor() const;
- QList<MethodSkeleton> methods() const;
-
- void addSuper(const QString&);
- void setName(const QString&);
- void setConstructor(const ConstructorSkeleton&);
- void setDestructor(const MethodSkeleton&);
- void addMethod(const MethodSkeleton&);
-
- int memberCount() const;
- QString member(int i) const;
- void addMember(const QString&);
-
- bool hasMethods() const;
- bool hasMembers() const;
- bool hasConstructor() const;
- bool hasDestructor() const;
- bool hasSomething() const;
-
-private:
- QString m_name;
- QList<MethodSkeleton> m_methods;
- bool m_empty;
- ConstructorSkeleton m_constructor;
- MethodSkeleton m_destructor;
- QList<QString> m_members;
- QString m_super;
-};
-
-}
-
-#endif // VERITAS_CLASSSKELETON_INCLUDED_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp (nonexistent)
@@ -1,132 +0,0 @@
-/*
- * KDevelop xUnit test support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "stubconstructor.h"
-
-// kdevplatform
-#include <interfaces/idocument.h>
-#include <language/duchain/duchainutils.h>
-#include <language/duchain/duchain.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/ducontext.h>
-#include <language/duchain/classfunctiondeclaration.h>
-
-// kdevelop
-#include <language/duchain/classdeclaration.h>
-
-using Veritas::ClassSkeleton;
-using Veritas::MethodSkeleton;
-using Veritas::ConstructorSkeleton;
-using Veritas::StubConstructor;
-using namespace KDevelop;
-
-namespace
-{
-
-/*! Returns true if @param decl is a member function with the following properties:
- - no constructor nor destructor
- - virtual
- - not private
- - not a Qt meta function */
-QStringList blackList(QString("metaObject,qt_metacast,qt_metacall").split(','));
-ClassFunctionDeclaration* filterMemberFunction(Declaration* decl)
-{
- ClassFunctionDeclaration* fdcl = dynamic_cast<ClassFunctionDeclaration*>(decl);
- if (fdcl) {
- if (fdcl->isDestructor() || fdcl->isConstructor() ||
- !fdcl->isVirtual() || fdcl->accessPolicy() == Declaration::Private ||
- blackList.contains(fdcl->identifier().toString())) {
- return 0;
- }
- }
- return fdcl;
-}
-
-MethodSkeleton fillMethod(ClassFunctionDeclaration* function)
-{
- MethodSkeleton ms;
- FunctionType::Ptr type = function->type<FunctionType>();
- if (!type) { kDebug() << "Erm type == 0"; return ms; }
- ms.setName(function->identifier().toString());
- ms.setFunctionType(type);
- ms.setConst(type->modifiers() & AbstractType::ConstModifier);
- return ms;
-}
-
-QString stubNameFor(ClassDeclaration* clazz)
-{
- return clazz->qualifiedIdentifier().toString() + "Stub";
-}
-
-/*! add a data member to the class and return this in method ms.
- eg: class FooStub { int m_foo; int foo() { return m_foo; } }; */
-void insertFakeMember(const QString& member, MethodSkeleton& ms, ClassSkeleton& cs, ConstructorSkeleton& constr)
-{
- ms.setBody("return " + member + ';');
- QString type = ms.returnType();
- if (type.startsWith("const ")) {
- type = type.mid(6, -1);
- }
- cs.addMember(type + ' ' + member);
- if (type == "bool") {
- constr.addInitializer(member + "(false)");
- } else if (type == "int" || type.contains("*")) {
- constr.addInitializer(member + "(0)");
- }
-}
-
-} // end anonymous namespace
-
-StubConstructor::StubConstructor()
-{}
-
-StubConstructor::~StubConstructor()
-{}
-
-ClassSkeleton StubConstructor::morph(ClassDeclaration* clazz)
-{
- Q_ASSERT(clazz);
- DUChainReadLocker lock(DUChain::lock());
-
- QString stubName = stubNameFor(clazz);
- ClassSkeleton cs; cs.setName(stubName);
- cs.addSuper(clazz->identifier().toString());
- ConstructorSkeleton constr; constr.setName(stubName);
- MethodSkeleton destr; destr.setName('~' + stubName);
-
- ClassFunctionDeclaration* function;
- foreach(Declaration* dcl, clazz->internalContext()->localDeclarations()) {
- function = filterMemberFunction(dcl);
- if (function) { // construct and add method to the stub
- MethodSkeleton ms = fillMethod(function);
- if (ms.returnType() != "void") {
- QString member = "m_" + ms.name();
- insertFakeMember(member, ms, cs, constr);
- }
- cs.addMethod(ms);
- }
- }
-
- cs.setConstructor(constr);
- cs.setDestructor(destr);
- return cs;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h (nonexistent)
@@ -1,48 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef VERITASCPP_CONSTRUCTORSKELETON_INCLUDED
-#define VERITASCPP_CONSTRUCTORSKELETON_INCLUDED
-
-#include "veritascppexport.h"
-#include <QStringList>
-#include "methodskeleton.h"
-
-namespace Veritas
-{
-
-/*! Value class which stores a simplified AST for constructors methods */
-class VERITASCPP_EXPORT ConstructorSkeleton : public MethodSkeleton
-{
-public:
- ConstructorSkeleton();
- virtual ~ConstructorSkeleton();
-
- void addInitializer(const QString&);
- QStringList initializerList() const;
-
-private:
- QStringList m_initializerList;
-};
-
-}
-
-#endif // VERITASCPP_METHODSKELETON_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/constructorskeleton.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.h (nonexistent)
@@ -1,62 +0,0 @@
-/*
- * KDevelop xUnit test support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef VERITAS_STUBCONSTRUCTOR_INCLUDED_H
-#define VERITAS_STUBCONSTRUCTOR_INCLUDED_H
-
-#include "veritascppexport.h"
-#include "classskeleton.h"
-
-namespace KDevelop { class ClassDeclaration; }
-
-namespace Veritas
-{
-
-/*!
-Constructs a test fake sub class implementation for a given class.
-
-input:
-@code
-class Foo {
-public:
- virtual int foo();
-};
-@endcode
-
-=> output:
-@code
-class FooStub {
-public:
- int m_foo;
- virtual int foo() { return m_foo; };
-};
-@endcode */
-class VERITASCPP_EXPORT StubConstructor
-{
-public:
- StubConstructor();
- virtual ~StubConstructor();
- ClassSkeleton morph(KDevelop::ClassDeclaration*);
-};
-
-}
-
-#endif // VERITAS_STUBCONSTRUCTOR_INCLUDED_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubconstructor.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp (nonexistent)
@@ -1,159 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "stubcontextaction.h"
-#include "stubconstructor.h"
-#include "classwriter.h"
-#include "includewriter.h"
-#include "classskeleton.h"
-
-#include <KAction>
-#include <KDebug>
-#include <KLocale>
-#include <QFile>
-#include <QDir>
-#include <QInputDialog>
-#include <QFileInfo>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-// kdevplatform
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/context.h>
-#include <interfaces/contextmenuextension.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainutils.h>
-#include <language/editor/simplecursor.h>
-#include <language/interfaces/editorcontext.h>
-#include <language/duchain/duchainlock.h>
-
-// kdevelop
-#include <language/duchain/classdeclaration.h>
-
-using Veritas::ClassSkeleton;
-using Veritas::ClassSerializer;
-using Veritas::StubConstructor;
-using Veritas::IncludeSerializer;
-using Veritas::IncludeGuardSerializer;
-using Veritas::StubContextAction;
-using namespace KDevelop;
-
-namespace
-{
-QString activeUrl()
-{
- ICore* core = ICore::self();
- IDocumentController* dc = core->documentController();
- IDocument* doc = dc->activeDocument();
- if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
- return "";
- } else {
- return doc->url().toLocalFile();
- }
-}
-
-QString stubUrl()
-{
- ICore* core = ICore::self();
- IDocumentController* dc = core->documentController();
- IDocument* doc = dc->activeDocument();
- if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
- return "";
- } else {
- QFileInfo fi(doc->url().toLocalFile());
- return fi.absolutePath() + QDir::separator() + fi.baseName() + "stub." + fi.completeSuffix();
- }
-}
-
-} // end anonymous namespace
-
-StubContextAction::StubContextAction(QObject* parent)
- : QObject(parent), m_clazz(0), m_constructStub(0)
-{
-}
-
-/*! initialization */
-void StubContextAction::setup()
-{
- Q_ASSERT(m_clazz == 0); Q_ASSERT(m_constructStub == 0);
- m_constructStub = new KAction(this);
- m_constructStub->setText(i18n("Generate Stub Class"));
- connect(m_constructStub, SIGNAL(triggered()), this, SLOT(constructStub()));
- Q_ASSERT(m_constructStub);
-}
-
-void StubContextAction::constructStub()
-{
- Q_ASSERT(m_constructStub);
- if (!m_clazz) return;
-
- bool owk;
- QString url;
- QString current = activeUrl();
- url = QInputDialog::getText(
- 0, i18n("Generate Stub"),
- i18n("Save to "), QLineEdit::Normal,
- stubUrl(), &owk);
- if (!owk || url.isEmpty() || QFile::exists(url)) return;
-
- QFile target(url);
- IncludeGuardSerializer().writeOpen(url, &target);
- IncludeSerializer().write(current, url, &target);
- ClassSkeleton cs = StubConstructor().morph(m_clazz);
- ClassSerializer().write(cs, &target);
- IncludeGuardSerializer().writeClose(url, &target);
-
- ICore::self()->documentController()->openDocument(KUrl(url));
-}
-
-StubContextAction::~StubContextAction()
-{}
-
-#define STOP_IF(X) \
- if (X) { m_clazz = 0; return; }\
- else (void)0
-
-void StubContextAction::appendTo(ContextMenuExtension& menu, Context* context)
-{
- KDevelop::ContextMenuExtension cm;
- STOP_IF(context->type() != Context::EditorContext);
-
- EditorContext* ec = dynamic_cast<EditorContext*>(context);
- STOP_IF(!ec);
-
- DUChainWriteLocker lock(DUChain::lock());
- ///@todo this isn't neede any more, the context contains the information
- SimpleCursor sc(ec->position());
- Declaration* dcl = DUChainUtils::itemUnderCursor(ec->url(), sc);
- STOP_IF(!dcl);
- STOP_IF(dcl->kind() != Declaration::Type);
-
- ClassDeclaration* clazz = dynamic_cast<ClassDeclaration*>(dcl);
- STOP_IF(!clazz);
-
- m_clazz = clazz;
- menu.addAction(ContextMenuExtension::ExtensionGroup, m_constructStub);
- Q_ASSERT(m_clazz);
-}
-
-#include "stubcontextaction.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/stubcontextaction.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp (nonexistent)
@@ -1,100 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-#include "methodskeleton.h"
-#include <language/duchain/types/functiontype.h>
-
-using Veritas::MethodSkeleton;
-using KDevelop::FunctionType;
-
-MethodSkeleton::MethodSkeleton()
- : m_empty(true), m_arguments("()"), m_isConst(false)
-{}
-
-MethodSkeleton::~MethodSkeleton()
-{}
-
-void MethodSkeleton::setFunctionType(FunctionType::Ptr fn)
-{
- m_arguments = fn->partToString(FunctionType::SignatureArguments);
- m_returnType = fn->partToString(FunctionType::SignatureReturn);
-}
-
-bool MethodSkeleton::isEmpty() const
-{
- return m_empty;
-}
-
-void MethodSkeleton::setName(const QString& name)
-{
- m_empty = false;
- m_name = name;
-}
-
-void MethodSkeleton::setBody(const QString& body)
-{
- m_body = body;
-}
-
-void MethodSkeleton::setReturnType(const QString& rt)
-{
- m_returnType = rt;
-}
-
-#include <KDebug>
-
-void MethodSkeleton::setArguments(const QString& sig)
-{
- m_arguments = sig;
-}
-
-QString MethodSkeleton::name() const
-{
- return m_name;
-}
-
-QString MethodSkeleton::body() const
-{
- return m_body;
-}
-
-QString MethodSkeleton::returnType() const
-{
- if (!isEmpty() && m_returnType.isEmpty()) return "void";
- return m_returnType;
-}
-
-QString MethodSkeleton::arguments() const
-{
- if (m_arguments.isEmpty()) {
- return "()";
- }
- return m_arguments;
-}
-
-void MethodSkeleton::setConst(bool isConst)
-{
- m_isConst = isConst;
-}
-
-bool MethodSkeleton::isConst() const
-{
- return m_isConst;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.h (nonexistent)
@@ -1,67 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef VERITASCPP_METHODSKELETON_INCLUDED
-#define VERITASCPP_METHODSKELETON_INCLUDED
-
-#include "veritascppexport.h"
-#include <QtCore/QString>
-#include <language/duchain/types/functiontype.h>
-
-namespace Veritas
-{
-enum Access { Public, Protected, Private };
-
-/*! Value class which stores a simplified AST for member functions */
-class VERITASCPP_EXPORT MethodSkeleton
-{
-public:
- MethodSkeleton();
- virtual ~MethodSkeleton();
- bool isEmpty() const;
-
- void setFunctionType(KDevelop::FunctionType::Ptr);
- void setName(const QString&);
- void setArguments(const QString&);
- void setReturnType(const QString&);
- void setBody(const QString&);
- void setAccess(Access) {}
- void setVirtual() {}
- void setConst(bool);
-
- QString name() const;
- QString arguments() const;
- QString body() const;
- QString returnType() const;
- bool isConst() const;
-
-private:
- bool m_empty;
- QString m_name;
- QString m_body;
- QString m_returnType;
- QString m_arguments;
- bool m_isConst;
-};
-
-}
-
-#endif // VERITASCPP_METHODSKELETON_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/methodskeleton.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.h (nonexistent)
@@ -1,62 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef VERITAS_TESTSWITCH_H
-#define VERITAS_TESTSWITCH_H
-
-#include "veritascppexport.h"
-#include "../cppduchain/environmentmanager.h"
-#include <QtCore/QObject>
-
-class KActionCollection;
-class KUrl;
-namespace KDevelop { class TopDUContext; }
-
-namespace Veritas
-{
-
-/*! Adds an action which allows for swapping between a test and its unit
- under test. */
-class VERITASCPP_EXPORT TestSwitch : public QObject
-{
-Q_OBJECT
-public:
- TestSwitch(QObject* parent);
- virtual ~TestSwitch();
-
- /*! Creates and connects the QAction. Invoke this once. */
- void connectAction(KActionCollection*);
- void setStandardMacros(Cpp::ReferenceCountedMacroSet*);
-
-private slots:
- /*! Connected to the action's triggered() signal */
- void swapTest_UnitUnderTest();
-
-private:
- KDevelop::TopDUContext* documentContextFor(const KUrl& url);
- bool m_actionConnected;
- Cpp::ReferenceCountedMacroSet* m_standardMacros;
- bool m_buzzySwitching;
-};
-
-}
-
-#endif // VERITAS_TESTSWITCH_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.cpp (nonexistent)
@@ -1,374 +0,0 @@
-/*
- * KDevelop xUnit test support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "testswitch.h"
-
-#include <KAction>
-#include <KActionCollection>
-#include <KLocale>
-#include <QFileInfo>
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-// kdevplatform includes
-#include <interfaces/icore.h>
-#include <interfaces/idocument.h>
-#include <interfaces/idocumentcontroller.h>
-#include <language/backgroundparser/backgroundparser.h>
-#include <language/duchain/duchainlock.h>
-#include <language/duchain/topducontext.h>
-#include <language/duchain/ducontext.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/indexedstring.h>
-#include <language/duchain/use.h>
-#include <language/duchain/duchain.h>
-#include <language/editor/simplecursor.h>
-#include <language/duchain/parsingenvironment.h>
-#include <language/duchain/persistentsymboltable.h>
-
-// kdevelop includes
-#include "../cpputils.h"
-#include "../cppduchain/cppduchain.h"
-#include "../cppduchain/environmentmanager.h"
-#include "../cppduchain/cpppreprocessenvironment.h"
-
-using Veritas::TestSwitch;
-using namespace KDevelop;
-
-namespace
-{
-
-IDocument* activeDocument()
-{
- ICore* core = ICore::self();
- IDocumentController* dc = core->documentController();
- IDocument* doc = dc->activeDocument();
- if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
- return 0;
- } else {
- return doc;
- }
-}
-
-QStringList headerExtensions(QString("h,H,hh,hxx,hpp,tlh,h++").split(','));
-bool isHeader(const KUrl& url)
-{
- QFileInfo fi(url.toLocalFile());
- return headerExtensions.contains(fi.suffix());
-}
-
-/*! check if ctx contains a qExec() call */
-bool hasQExecInvocation(DUContext* ctx, TopDUContext* top)
-{
- const Use* u = ctx->uses();
- Declaration* d;
- Identifier qExec("qExec");
- for(int i=0; i<ctx->usesCount(); i++, u++) {
- d = top->usedDeclarationForIndex(u->m_declarationIndex);
- if (!d || !d->isFunctionDeclaration()) continue;
- if (d->identifier() == qExec) return true;
- }
- return false;
-}
-
-/*! find a main() declaration */
-DUContext* findMainContext(TopDUContext* ctx)
-{
- Identifier main("main");
- QList<Declaration*> dcls = ctx->findDeclarations(main);
- Declaration* d = 0;
- foreach(Declaration* d2, dcls) {
- if (d2->isFunctionDeclaration() && d2->isDefinition()) {
- d = d2;
- break;
- } else {
- }
- }
- if(d)
- return d->internalContext();
- else
- return 0;
-}
-
-/*! return true if ctx contains a QTest main function (expanded QTEST_MAIN macro) */
-bool hasQTestMainFunction(TopDUContext* ctx)
-{
- DUContext* mainCtx = findMainContext(ctx);
- if (!mainCtx) return false; // no main() present
- return hasQExecInvocation(mainCtx, ctx);
-}
-
-Declaration* mostFrequentClass(const QMap<Declaration*, int>& classes)
-{
- int maxCount = -1;
- Declaration* max = 0;
- QMapIterator<Declaration*, int> it(classes);
- while (it.hasNext()) {
- it.next();
- if (it.value() > maxCount) {
- maxCount = it.value();
- max = it.key();
- }
- }
- return max;
-}
-
-/*! Try to fetch the owner class declaration for a member function */
-Declaration* isMemberFunctionDefinition(Declaration* decl)
-{
- if (!decl->isFunctionDeclaration() || !decl->isDefinition()) {
- return 0; // not a member defintion
- }
- return Cpp::localClassFromCodeContext(decl->internalContext());
-}
-
-/*! Increment the class count for @param clazz */
-void updateClassCount(Declaration* clazz, QMap<Declaration*,int>& classes)
-{
- if (!classes.contains(clazz)) {
- classes[clazz] = 0;
- }
- classes[clazz] += 1;
- kDebug() << "Incremented member definition count for " << clazz->toString();
-}
-
-/*! Calculates the class with the highest number of member function
- implementations in context ctx */
-Declaration* dominantClassInCpp(TopDUContext* ctx)
-{
- kDebug() << "";
- QMap<Declaration*, int> classes;
- foreach(Declaration* d, ctx->localDeclarations()) {
- if (Declaration* const clazz = isMemberFunctionDefinition(d)) {
- updateClassCount(clazz, classes);
- }
- }
- return mostFrequentClass(classes);
-}
-
-/*! Increment the class count for the owner class of context @param ctx */
-void updateClassMemberCountFor(DUContext* ctx, QMap<Declaration*,int>& classes)
-{
- Declaration* clazz = ctx->owner();
- if (!classes.contains(clazz)) classes[clazz] = 0;
- int& count = classes[clazz];
- foreach(Declaration* d, ctx->localDeclarations()) {
- if (d->isFunctionDeclaration()) {
- count += 1;
- }
- }
-}
-
-/*! recursive functions which traverses ctx for classes and updates the
- member counts in the classes map */
-void computeClassMemberCount(DUContext* parent, QMap<Declaration*,int>& classes)
-{
- foreach(DUContext* child, parent->childContexts()){
- switch(child->type()) {
- case DUContext::Class: {
- updateClassMemberCountFor(child, classes); break;
- } case DUContext::Namespace: {
- computeClassMemberCount(child, classes); break;
- } default: {}
- }
- }
-}
-
-/*! Calculates the class with the highest number of member function
- declarations in context ctx */
-Declaration* dominantClassInHeader(TopDUContext* ctx)
-{
- kDebug() << "";
- QMap<Declaration*, int> classes;
- computeClassMemberCount(ctx, classes);
- kDebug() << "classes_" << classes;
- return mostFrequentClass(classes);
-}
-
-bool isTest(Declaration* clazz)
-{
- QualifiedIdentifier qid = clazz->qualifiedIdentifier();
- return qid.toString().endsWith("Test"); //|| hasQTestMainFunction(docCtx);
-}
-
-QualifiedIdentifier getUnitUnderTestIdFor(Declaration* testClass)
-{
- QString qidStr(testClass->qualifiedIdentifier().toString());
- qidStr.chop(4); // truncate 'Test'
- QualifiedIdentifier uutQid(qidStr);
- return uutQid;
-}
-
-QualifiedIdentifier getTestIdFor(Declaration* uutClass)
-{
- QString qidStr(uutClass->qualifiedIdentifier().toString());
- QualifiedIdentifier testQid(qidStr + "Test");
- return testQid;
-}
-
-KUrl findTargetLocation(QualifiedIdentifier target)
-{
- kDebug() << "Querying persistent symbol table for " << target.toString();
- PersistentSymbolTable& pst = PersistentSymbolTable::self();
- const IndexedDeclaration* matches;
- uint count;
- pst.declarations(target, count, matches);
- KUrl url;
-/* if (count > 0) {
- url = KUrl(matches->declaration()->url().str());
- }*/
- for(uint i=0; i<count; ++i, ++matches) {
- Declaration* matched = matches->declaration();
- if (!matched || matched->url().isEmpty()) continue;
- kDebug() << "matched " << matched->toString() << " " << matched->url().str();
- if (!matched->isForwardDeclaration()) {
- url = KUrl(matches->declaration()->url().str());
- }
- }
- return url;
-}
-
-/*! Parse doc string @p comment for @p key and extract it's argument.
- Return default string if not found. */
-QString extractArgumentFromDocs(const QString& key, const QString& comment)
-{
- kDebug() << key;
- int i = comment.indexOf(key);
- if (i==-1) return QString();
- QString rest = comment.mid(i + 1 + QString(key).count()); // +1 is for space
- QStringList spl = rest.split(' ', QString::SkipEmptyParts);
- rest = spl[0];
- if (rest.contains("\n") || rest.contains("*")) {
- return QString();
- } else {
- return rest;
- }
-}
-
-KUrl resolveTargetUrl(QualifiedIdentifier& target)
-{
- KUrl targetUrl = findTargetLocation(target);
- if (targetUrl.isEmpty() && target.count() > 1) {
- // try without namespaces
- QualifiedIdentifier qid(target.last().toString());
- targetUrl = findTargetLocation(qid);
- }
- if (targetUrl.isEmpty() && target.count() > 2) {
- // given foo::baz::Bar try foo::Bar
- QualifiedIdentifier qid(target.first().toString());
- qid += QualifiedIdentifier(target.last().toString());
- targetUrl = findTargetLocation(qid);
- }
- return targetUrl;
-}
-
-} // end anonymous namespace
-
-TestSwitch::TestSwitch(QObject* parent)
- : QObject(parent), m_actionConnected(false), m_standardMacros(0), m_buzzySwitching(false)
-{}
-
-TestSwitch::~TestSwitch()
-{}
-
-void TestSwitch::connectAction(KActionCollection* col)
-{
- if (m_actionConnected) return;
- KAction* a = col->addAction("switch_test_unitundertest");
- a->setText( i18n("&Switch Test/Unit Under Test") );
- a->setShortcut( Qt::CTRL | Qt::SHIFT | Qt::Key_R );
- connect(a, SIGNAL(triggered()),
- this, SLOT(swapTest_UnitUnderTest()));
- m_actionConnected = true;
-}
-
-
-void TestSwitch::setStandardMacros(Cpp::ReferenceCountedMacroSet* macros)
-{
- m_standardMacros = macros;
-}
-
-TopDUContext* TestSwitch::documentContextFor(const KUrl& url)
-{
- CppPreprocessEnvironment* env = new CppPreprocessEnvironment(0, Cpp::EnvironmentFilePointer());
- if (m_standardMacros) env->merge(*m_standardMacros);
- DUChain* chainStore = DUChain::self();
- TopDUContext* docCtx = chainStore->chainForDocument(url, env);
- delete env;
- if(docCtx && docCtx->parsingEnvironmentFile() && docCtx->parsingEnvironmentFile()->isProxyContext()) {
- if(!docCtx->importedParentContexts().isEmpty()) {
- docCtx = dynamic_cast<TopDUContext*>(docCtx->importedParentContexts().first().context(0));
- }
- }
- return docCtx;
-}
-
-#define STOP_IF(X, MSG) \
- if (X) { kDebug() << MSG; m_buzzySwitching = false; return; }
-
-void TestSwitch::swapTest_UnitUnderTest()
-{
- if (m_buzzySwitching) return;
- m_buzzySwitching = true;
- kDebug() << "Switching between test and unit under test";
- IDocument* doc = activeDocument();
- STOP_IF(!doc, "Can't switch, no active document.")
-
- DUChainReadLocker lock(DUChain::lock());
- TopDUContext* docCtx = documentContextFor(doc->url());
- STOP_IF(!docCtx, QString("Failed to get chain for %1").arg(doc->url().toLocalFile()))
-
- Declaration* clazz = (isHeader(doc->url())) ?
- dominantClassInHeader(docCtx) :
- dominantClassInCpp(docCtx);
- STOP_IF(!clazz, "No dominant class found.")
- kDebug() << "Dominant Class >> " << clazz->toString();
-
- QString dox = clazz->comment(), docTarget;
- kDebug() << "DOX\n" << dox;
- if (dox.contains("@unitundertest")) {
- docTarget = extractArgumentFromDocs("@unitundertest", dox);
- } else if (dox.contains("@unittest")) {
- docTarget = extractArgumentFromDocs("@unittest", dox);
- }
-
- QualifiedIdentifier target; // the class to load
- if (!docTarget.isEmpty()) {
- target = QualifiedIdentifier(docTarget);
- } else { // resort to naming conventions
- target = (isTest(clazz)) ?
- getUnitUnderTestIdFor(clazz) :
- getTestIdFor(clazz);
- }
- KUrl targetUrl = resolveTargetUrl(target);
- lock.unlock();
-
- if (!targetUrl.isEmpty()) {
- kDebug() << "Found test/uut in " << targetUrl;
- IDocumentController* dc = ICore::self()->documentController();
- dc->openDocument(targetUrl);
- } else {
- kDebug() << "Failed to find switch candidate for " << doc->url();
- }
- m_buzzySwitching = false;
-}
-
-#include "testswitch.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/testswitch.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:mergeinfo
## -0,0 +0,0 ##
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.cpp (nonexistent)
@@ -1,110 +0,0 @@
-/*
- * KDevelop xUnit testing support
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "classwriter.h"
-#include "classskeleton.h"
-#include "constructorskeleton.h"
-#include "methodskeleton.h"
-#include <QIODevice>
-#include <QTextStream>
-
-using Veritas::ClassSerializer;
-using Veritas::ClassSkeleton;
-using Veritas::ConstructorSkeleton;
-using Veritas::MethodSkeleton;
-
-namespace
-{
-
-const QString INDENT = " ";
-QString indent() { return INDENT; }
-
-void intro(const ClassSkeleton& source, QTextStream& str)
-{
- QStringList qualifiedName = source.name().split("::");
- Q_ASSERT(qualifiedName.size()>=1);
- for (int i=0; i<qualifiedName.size()-1;i++) {
- str << "\nnamespace " << qualifiedName[i] << " {";
- }
- str << "\nclass " << qualifiedName.last();
- if (!source.super().isEmpty()) {
- str << " : public " << source.super();
- }
- str << "\n" << "{\n";
-}
-
-void writeConstructor(const ConstructorSkeleton& ctr, QTextStream& str)
-{
- if(ctr.isEmpty()) return;
- str << indent() << ctr.name() << "() ";
- QStringList inits = ctr.initializerList();
- if (inits.count()!=0) str << ": ";
- for(int i=0; i<inits.count(); i++) {
- str << inits[i];
- if (i!=inits.count()-1) str << ", ";
- }
- str << " {}\n";
-}
-
-void writeDestructor(const MethodSkeleton& destr, QTextStream& str)
-{
- if (!destr.isEmpty()) {
- str << indent() << "virtual " << destr.name() << "() {}\n";
- }
-}
-
-void writeMethod(const MethodSkeleton& mtd, QTextStream& str)
-{
- QString const_ = mtd.isConst() ? " const " : "";
- str << indent() << "virtual " << mtd.returnType()
- << " " << mtd.name() << mtd.arguments() << const_ << " {\n";
- foreach(const QString& line, mtd.body().split('\n', QString::SkipEmptyParts)) {
- str << indent() << indent() << line << "\n";
- }
- str << indent() << "}\n";
-}
-
-} // end anonymous namespace
-
-void ClassSerializer::write(const ClassSkeleton& source, QIODevice* target)
-{
- target->open(QIODevice::Append);
- QTextStream str(target);
- intro(source, str);
- if (source.hasSomething()) {
- str << "public:\n";
- writeConstructor(source.constructor(), str);
- writeDestructor(source.destructor(), str);
- foreach(const MethodSkeleton &ms, source.methods()) {
- writeMethod(ms, str);
- }
- for(int i=0; i<source.memberCount(); i++) {
- str << INDENT << source.member(i) << ";\n";
- }
- }
- str << "};\n";
- int nrofNamespaces = source.name().split("::").size()-1;
- for (int i=0; i<nrofNamespaces; i++) {
- str << "}";
- }
- if (nrofNamespaces!=0) str << "\n";
- target->close();
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp (nonexistent)
@@ -1,129 +0,0 @@
-/*
- * KDevelop xUnit test support
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "classskeleton.h"
-
-using Veritas::ClassSkeleton;
-using Veritas::ConstructorSkeleton;
-using Veritas::MethodSkeleton;
-
-ClassSkeleton::ClassSkeleton()
- : m_empty(true)
-{}
-
-ClassSkeleton::~ClassSkeleton()
-{}
-
-bool ClassSkeleton::isEmpty() const
-{
- return m_empty;
-}
-
-QString ClassSkeleton::name() const
-{
- return m_name;
-}
-
-void ClassSkeleton::setName(const QString& name)
-{
- m_empty = false;
- m_name = name;
-}
-
-void ClassSkeleton::addMethod(const MethodSkeleton& mtd)
-{
- m_methods << mtd;
-}
-
-ConstructorSkeleton ClassSkeleton::constructor() const
-{
- return m_constructor;
-}
-
-MethodSkeleton ClassSkeleton::destructor() const
-{
- return m_destructor;
-}
-
-QList<MethodSkeleton> ClassSkeleton::methods() const
-{
- return m_methods;
-}
-
-void ClassSkeleton::setConstructor(const ConstructorSkeleton& ctr)
-{
- m_constructor = ctr;
-}
-
-void ClassSkeleton::setDestructor(const MethodSkeleton& dtr)
-{
- m_destructor = dtr;
-}
-
-int ClassSkeleton::memberCount() const
-{
- return m_members.count();
-}
-
-QString ClassSkeleton::member(int i) const
-{
- return m_members.value(i);
-}
-
-void ClassSkeleton::addMember(const QString& member)
-{
- m_members << member;
-}
-
-bool ClassSkeleton::hasMethods() const
-{
- return m_methods.count()!=0;
-}
-
-bool ClassSkeleton::hasMembers() const
-{
- return memberCount()!=0;
-}
-
-bool ClassSkeleton::hasConstructor() const
-{
- return !constructor().isEmpty();
-}
-
-bool ClassSkeleton::hasDestructor() const
-{
- return !destructor().isEmpty();
-}
-
-bool ClassSkeleton::hasSomething() const
-{
- return hasMembers() || hasMethods() || hasConstructor() || hasDestructor();
-}
-
-void ClassSkeleton::addSuper(const QString& super)
-{
- m_super = super;
-}
-
-QString ClassSkeleton::super() const
-{
- return m_super;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classskeleton.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp (nonexistent)
@@ -1,160 +0,0 @@
-/*
- * KDevelop xUnit testing support
- *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
- *
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "uutcontextaction.h"
-#include "uutconstructor.h"
-#include "classwriter.h"
-#include "includewriter.h"
-#include "classskeleton.h"
-#include "documentaccess.h"
-
-#include <KAction>
-#include <KDebug>
-#include <KLocale>
-#include <QFile>
-#include <QDir>
-#include <QInputDialog>
-#include <QFileInfo>
-
-#include <ktexteditor/document.h>
-#include <ktexteditor/view.h>
-
-// kdevplatform
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/context.h>
-#include <interfaces/contextmenuextension.h>
-#include <language/duchain/declaration.h>
-#include <language/duchain/duchainutils.h>
-#include <language/editor/simplecursor.h>
-#include <language/duchain/duchainlock.h>
-#include <language/interfaces/editorcontext.h>
-
-// kdevelop
-#include <language/duchain/classdeclaration.h>
-
-using Veritas::ClassSkeleton;
-using Veritas::ClassSerializer;
-using Veritas::IncludeGuardSerializer;
-using Veritas::UUTConstructor;
-using Veritas::UUTContextAction;
-using Veritas::DocumentAccess;
-using namespace KDevelop;
-
-namespace
-{
-QString activeUrl()
-{
- ICore* core = ICore::self();
- IDocumentController* dc = core->documentController();
- IDocument* doc = dc->activeDocument();
- if (!doc || !doc->textDocument() || !doc->textDocument()->activeView()) {
- return "";
- } else {
- QFileInfo fi(doc->url().toLocalFile());
- return fi.absolutePath() + QDir::separator() + fi.baseName() + "gen." + fi.completeSuffix();
- }
-}
-} // end anonymous namespace
-
-UUTContextAction::UUTContextAction(QObject* parent)
- : QObject(parent), m_clazz(0), m_createImplementation(0), m_constructor(0)
-{}
-
-void UUTContextAction::setup()
-{
- Q_ASSERT(m_clazz == 0); Q_ASSERT(m_createImplementation == 0); Q_ASSERT(m_constructor == 0);
- m_createImplementation = new KAction(this);
- m_createImplementation->setText(i18n("Generate Unit Under Test"));
- connect(m_createImplementation, SIGNAL(triggered()),
- this, SLOT(createImplementation()));
- DocumentAccess* docAccess = new DocumentAccess(this);
- m_constructor = new UUTConstructor;
- m_constructor->setDocumentAccess(docAccess);
- Q_ASSERT(m_createImplementation && m_constructor);
-}
-
-void UUTContextAction::createImplementation()
-{
- Q_ASSERT(m_createImplementation); Q_ASSERT(m_constructor);
- if (!m_clazz) return;
-
- bool owk;
- QString url;
- url = QInputDialog::getText(
- 0, i18n("Generate Unit Under Test"),
- i18n("Save to "), QLineEdit::Normal,
- activeUrl(), &owk);
- if (!owk || url.isEmpty() || QFile::exists(url)) return;
-
- QFile target(url);
- IncludeGuardSerializer().writeOpen(url, &target);
- ClassSkeleton cs = m_constructor->morph(m_clazz);
- ClassSerializer().write(cs, &target);
- IncludeGuardSerializer().writeClose(url, &target);
-
- ICore::self()->documentController()->openDocument(KUrl(url));
-}
-
-UUTContextAction::~UUTContextAction()
-{
- if (m_createImplementation) delete m_createImplementation;
- if (m_constructor) delete m_constructor;
-}
-
-#define STOP_IF(X) \
-if (X) { m_clazz = 0; return; } \
-else (void)(0)
-
-#define STOP_IF_(X, MSG) \
-if (X) {\
- m_clazz = 0;\
- kDebug() << "Not appending UUT action because " << MSG;\
- return;\
-} else (void)(0)
-
-
-void UUTContextAction::appendTo(ContextMenuExtension& menu, Context* context)
-{
- Q_ASSERT(m_createImplementation); Q_ASSERT(m_constructor);
- STOP_IF(context->type() != Context::EditorContext);
- EditorContext* ec = dynamic_cast<EditorContext*>(context);
- STOP_IF(!ec);
-
- DUChainWriteLocker lock(DUChain::lock());
- SimpleCursor sc(ec->position());
- ///@todo not needed any more, just take the data out of the context(DeclarationContext)
- Declaration* decl = DUChainUtils::itemUnderCursor(ec->url(), sc);
- STOP_IF_(!decl, "no declaration under cursor.");
- STOP_IF_(decl->kind() != Declaration::Instance, "Not an instance declaration.");
- STOP_IF_(!decl->isDefinition(), "Not a definition");
-
- DelayedType::Ptr type = decl->type<DelayedType>();
- STOP_IF_(!type, "Not a delayed/unresolved type (null)");
- STOP_IF_(type->kind() != DelayedType::Unresolved, "Not an unresolved type [but delayed]");
-
- m_clazz = decl;
- menu.addAction(ContextMenuExtension::ExtensionGroup, m_createImplementation);
- Q_ASSERT(m_clazz);
-}
-
-#include "uutcontextaction.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/uutcontextaction.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.h (nonexistent)
@@ -1,42 +0,0 @@
-/*
-* KDevelop xUnit testing support
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-
-#ifndef VERITAS_CPP_CLASSWRITER_INCLUDED
-#define VERITAS_CPP_CLASSWRITER_INCLUDED
-
-class QIODevice;
-#include "veritascppexport.h"
-
-namespace Veritas
-{
-class ClassSkeleton;
-
-/*! @unittest Veritas::Test::ClassWriterTest */
-class VERITASCPP_EXPORT ClassSerializer
-{
-public:
- void write(const ClassSkeleton& source, QIODevice* target);
-
-};
-
-}
-
-#endif // VERITAS_CPP_CLASSWRITER_INCLUDED
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/classwriter.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/includewriter.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/includewriter.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/includewriter.h (nonexistent)
@@ -1,92 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITAS_CPP_INCLUDEWRITER_H
-#define VERITAS_CPP_INCLUDEWRITER_H
-
-#include <KUrl>
-#include <QTextStream>
-#include <QDir>
-
-namespace Veritas
-{
-
-/*! @unittest Veritas::Test::IncludeWriterTest */
-class IncludeSerializer
-{
-public:
- void write(const QString& included, const QString& includer, QIODevice* target) {
- KUrl includedUrl(included);
- KUrl includerUrl(includer);
- target->open(QIODevice::Append);
- QTextStream str(target);
- if (includedUrl.upUrl() == includerUrl.upUrl()) {
- str << "#include \"" << includedUrl.fileName() << "\"\n";
- } else if (includedUrl.upUrl() == includerUrl.upUrl().upUrl()) {
- str << "#include \"../" << includedUrl.fileName() << "\"\n";
- } else if (includedUrl.upUrl().upUrl() == includerUrl.upUrl()) {
- str << "#include \"" << includedUrl.upUrl().fileName() << QDir::separator() << includedUrl.fileName() << "\"\n";
- } else {
- int common = 0;
- while ( common < included.count() && common < includer.count() ) {
- if (included[common] != includer[common]) {
- break;
- }
- common++;
- }
- str << "#include \"" << included.mid(common) << "\"\n";
- }
- target->close();
- }
-};
-
-/*! @unittest Veritas::Test::IncludeWriterTest */
-class IncludeGuardSerializer
-{
-public:
- void writeOpen(const QString& headerFile, QIODevice* target) {
- target->open(QIODevice::Append);
- QTextStream str(target);
- str << "\n#ifndef " << guard(headerFile)
- << "\n#define " << guard(headerFile) << "\n\n";
- target->close();
- }
-
- void writeClose(const QString& headerFile, QIODevice* target) {
- target->open(QIODevice::Append);
- QTextStream str(target);
- str << "\n#endif // " << guard(headerFile) << "\n";
- target->close();
- }
-
-private:
- QString guard(const QString& headerFile) {
- KUrl url(headerFile);
- QString upUp = url.upUrl().upUrl().fileName().toUpper();
- QString up = url.upUrl().fileName().toUpper();
- QString fn = url.fileName().toUpper();
- fn = fn.replace(".", "_");
- return upUp + "_" + up + "_" + fn + "_INCLUDED";
- }
-};
-
-}
-
-#endif // VERITAS_CPP_INCLUDEWRITER_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/includewriter.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.h (nonexistent)
@@ -1,47 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#ifndef VERITASCPP_DOCUMENT_ACCESS
-#define VERITASCPP_DOCUMENT_ACCESS
-
-#include <KUrl>
-#include <QtCore/QObject>
-#include <language/editor/simplerange.h>
-#include "veritascppexport.h"
-
-namespace Veritas
-{
-
-/*! Extra layer of indirection to get around ICore, IDocumentController, IDocument and KT::Document
- dependencies in tests. (and put the shiny new stub generator to good use :> ) */
-class VERITASCPP_EXPORT DocumentAccess : public QObject
-{
-Q_OBJECT
-public:
- DocumentAccess(QObject* parent=0);
- virtual ~DocumentAccess();
- /*! Fetch the text contained in a @param range for a @param url */
- virtual QString text(const KUrl& url, const KDevelop::SimpleRange& range) const;
- virtual QString text(const KUrl&) const;
-};
-
-}
-
-#endif // VERITASCPP_DOCUMENT_ACCESS
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp (nonexistent)
@@ -1,62 +0,0 @@
-/*
-* KDevelop xUnit integration
-* Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com>
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
-* 02110-1301, USA.
-*/
-
-#include "documentaccess.h"
-#include <interfaces/icore.h>
-#include <interfaces/idocumentcontroller.h>
-#include <interfaces/idocument.h>
-#include <ktexteditor/document.h>
-
-using Veritas::DocumentAccess;
-using namespace KDevelop;
-
-DocumentAccess::DocumentAccess(QObject* parent)
- : QObject(parent)
-{}
-
-DocumentAccess::~DocumentAccess()
-{}
-
-KTextEditor::Document* documentForUrl(const KUrl& url)
-{
- ICore* c = ICore::self();
- IDocumentController* dc = c->documentController();
- IDocument* doc = dc->documentForUrl(url);
- if (!doc || !doc->isTextDocument() ) return 0;
- KTextEditor::Document* tdoc = doc->textDocument();
- return tdoc;
-}
-
-QString DocumentAccess::text(const KUrl& url, const KDevelop::SimpleRange& range) const
-{
- KTextEditor::Document* tdoc = documentForUrl(url);
- if (!tdoc) return QString();
- return tdoc->text(range.textRange());
-}
-
-QString DocumentAccess::text(const KUrl& url) const
-{
- KTextEditor::Document* tdoc = documentForUrl(url);
- if (!tdoc) return QString();
- return tdoc->text();
-}
-
-#include "documentaccess.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/documentaccess.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switch.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switch.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switch.h (nonexistent)
@@ -1,38 +0,0 @@
-/*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-/*! Test - Unit Under Test code navigation example
-
-Purpose is to navigate quickly from a test to it's unit.
-
-KDevelop4 will read the switch target from the class'
-documentation string. If this is not present a heuristic
-based on naming conventions will try to resolve a switch
-candidate.
-
-First open both switch.h and switchtest.h in KDevelop4 to make
-sure the symbols are parsed. Next configure the switch shortcut
-in Settings -> Configure Shortcuts -> Switch Test/Unit Under Test.
-Hit this key combination to jump between switch.h and switchtest.h
-*/
-
-/*! @unittest SwitchExampleTest */
-class SwitchExample
-{
-public:
- void foo();
-};
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switch.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/clean.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/clean.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/clean.sh (nonexistent)
@@ -1,6 +0,0 @@
-#!/bin/bash
-
-KEEPERS="(^stubgeneration.h$|^uutgeneration.h$|^switch.h$|^switchtest.h$|^clean.sh$)"
-GARBAGE=$(ls | grep -Ev $KEEPERS)
-echo "Removing $GARBAGE"
-rm -i $GARBAGE
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/clean.sh
___________________________________________________________________
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h (nonexistent)
@@ -1,64 +0,0 @@
-/*
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-/*! Examples and howto for stub code generation */
-
-/*!
-This is your everyday interface. Now we want to construct
-a stub class skeleton for the virtual methods.
-
-Steps:
- 1/ Point your mouse cursor to the first 'Foo'
- 2/ Notice the neat code highlighting
- 3/ Right click to spawn a context menu
- 4/ Choose ``Generate Stub Class''
- 5/ A dialog box will appear. Provide a filename
- This file will contain the generated code
- 6/ Hit ok.
- 7/ Stub is generated and focused.
-*/
-class Foo
-{
-public:
- Foo();
- virtual ~Foo();
- virtual int foo(char);
-};
-
-/*! Only virtual methods are stubbed. No code is generated
- * for non-virtual, signals nor for private methods. */
-class Bar
-{
-public:
- void bar();
-signals:
- void barr();
-private:
- void barrr();
-};
-
-namespace Zoo
-{
-class Loo
-{
-public:
- virtual void moo();
- virtual void boo() const;
-};
-}
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/stubgeneration.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h (nonexistent)
@@ -1,39 +0,0 @@
-/*
-* This program 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 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.,
-* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-/*! Test - Unit Under Test code navigation example
-
-Purpose is to navigate quickly from a test to it's unit.
-
-KDevelop4 will read the switch target from the class'
-documentation string. If this is not present a heuristic
-based on naming conventions will try to resolve a switch
-candidate.
-
-First open both switch.h and switchtest.h in KDevelop4 to make
-sure the symbols are parsed. Next configure the switch shortcut
-in Settings -> Configure Shortcuts -> Switch Test/Unit Under Test.
-Hit this key combination to jump between switch.h and switchtest.h
-*/
-
-/*! @unitundertest SwitchExample */
-class SwitchExampleTest : public QObject
-{
-Q_OBJECT
-private slots:
- void testFoo();
-};
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/switchtest.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h (nonexistent)
@@ -1,45 +0,0 @@
-/*
- * This program 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 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.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-/*! Examples and howto for unit under test generation from a test-driven
- implementation. */
-
-/*!
-This is your everyday test first test command. You have
-coded the Baz class by intention and now want to generate
-a skeleton implementation.
-
-Steps:
- 1/ Move your cursor to baz
- 2/ Notice the neat code highlighting
- 3/ Right click to spawn a context menu
- 4/ Choose ``Generate Unit Under Test''
- 5/ A dialog box will appear. Provide a filename
- This file will contain the generated code
- 6/ Hit ok.
- 7/ Unit Under Test skeleton is generated
-
-*/
-class Foo;
-class Bar;
-void FooTest::foo()
-{
- Baz baz;
- baz.moo();
- baz.zoo(Foo(), Bar());
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/examples/uutgeneration.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/veritascppexport.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/veritascppexport.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/veritascppexport.h (nonexistent)
@@ -1,37 +0,0 @@
-/***************************************************************************
- * This file is part of KDevelop *
- * Copyright 2008 Manuel Breugelmans <mbr.nxi@gmail.com> *
- * Copyright 2007 Andreas Pakulat <apaku@gmx.de> *
- * Copyright 2006 Matt Rogers <mattr@kde.org> *
- * Copyright 2004 Jaroslaw Staniek <js@iidea.pl> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef LANGUAGES_CPP_VERITASCPP_EXPORT_H
-#define LANGUAGES_CPP_VERITASCPP_EXPORT_H
-
-#include <kdemacros.h>
-
-#ifndef VERITASCPP_EXPORT
-# ifdef MAKE_VERITASCPP_LIB
-# define VERITASCPP_EXPORT KDE_EXPORT
-# else
-# define VERITASCPP_EXPORT KDE_IMPORT
-# endif
-#endif
-
-#endif // LANGUAGES_CPP_VERITASCPP_EXPORT_H
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/veritascpp/veritascppexport.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewerbase.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewerbase.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewerbase.ui (nonexistent)
@@ -1,220 +0,0 @@
-<!DOCTYPE UI><UI version="3.2" stdsetdef="1">
-<class>ViewerBase</class>
-<widget class="QWidget">
- <property name="name">
- <cstring>ViewerBase</cstring>
- </property>
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>600</width>
- <height>480</height>
- </rect>
- </property>
- <property name="caption">
- <string>Viewer</string>
- </property>
- <grid>
- <property name="name">
- <cstring>unnamed</cstring>
- </property>
- <widget class="QLayoutWidget" row="0" column="1" rowspan="4" colspan="1">
- <property name="name">
- <cstring>layout2</cstring>
- </property>
- <vbox>
- <property name="name">
- <cstring>unnamed</cstring>
- </property>
- <widget class="QTextEdit">
- <property name="name">
- <cstring>source</cstring>
- </property>
- <property name="sizePolicy">
- <sizepolicy>
- <hsizetype>7</hsizetype>
- <vsizetype>7</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>1</verstretch>
- </sizepolicy>
- </property>
- </widget>
- <widget class="QTabWidget">
- <property name="name">
- <cstring>tabWidget2</cstring>
- </property>
- <property name="sizePolicy">
- <sizepolicy>
- <hsizetype>7</hsizetype>
- <vsizetype>7</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>2</verstretch>
- </sizepolicy>
- </property>
- <widget class="QWidget">
- <property name="name">
- <cstring>tab</cstring>
- </property>
- <attribute name="title">
- <string>Parse Tree</string>
- </attribute>
- <grid>
- <property name="name">
- <cstring>unnamed</cstring>
- </property>
- <widget class="QListView" row="0" column="0">
- <column>
- <property name="text">
- <string>Name</string>
- </property>
- <property name="clickable">
- <bool>true</bool>
- </property>
- <property name="resizable">
- <bool>true</bool>
- </property>
- </column>
- <column>
- <property name="text">
- <string>Value 1</string>
- </property>
- <property name="clickable">
- <bool>true</bool>
- </property>
- <property name="resizable">
- <bool>true</bool>
- </property>
- </column>
- <column>
- <property name="text">
- <string>Value 2</string>
- </property>
- <property name="clickable">
- <bool>true</bool>
- </property>
- <property name="resizable">
- <bool>true</bool>
- </property>
- </column>
- <property name="name">
- <cstring>ast</cstring>
- </property>
- </widget>
- </grid>
- </widget>
- <widget class="QWidget">
- <property name="name">
- <cstring>tab</cstring>
- </property>
- <attribute name="title">
- <string>Source to Be Written Back</string>
- </attribute>
- <grid>
- <property name="name">
- <cstring>unnamed</cstring>
- </property>
- <widget class="QTextEdit" row="0" column="0">
- <property name="name">
- <cstring>writeBack</cstring>
- </property>
- </widget>
- </grid>
- </widget>
- </widget>
- </vbox>
- </widget>
- <widget class="QLineEdit" row="0" column="0">
- <property name="name">
- <cstring>allLocation</cstring>
- </property>
- <property name="maximumSize">
- <size>
- <width>150</width>
- <height>32767</height>
- </size>
- </property>
- </widget>
- <widget class="QPushButton" row="1" column="0">
- <property name="name">
- <cstring>addAll</cstring>
- </property>
- <property name="maximumSize">
- <size>
- <width>150</width>
- <height>32767</height>
- </size>
- </property>
- <property name="text">
- <string>Add All From Directory</string>
- </property>
- </widget>
- <widget class="QPushButton" row="2" column="0">
- <property name="name">
- <cstring>choose</cstring>
- </property>
- <property name="maximumSize">
- <size>
- <width>150</width>
- <height>32767</height>
- </size>
- </property>
- <property name="text">
- <string>Choose File to Add...</string>
- </property>
- </widget>
- <widget class="QListBox" row="3" column="0">
- <property name="name">
- <cstring>files</cstring>
- </property>
- <property name="sizePolicy">
- <sizepolicy>
- <hsizetype>7</hsizetype>
- <vsizetype>7</vsizetype>
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="maximumSize">
- <size>
- <width>150</width>
- <height>32767</height>
- </size>
- </property>
- </widget>
- </grid>
-</widget>
-<connections>
- <connection>
- <sender>addAll</sender>
- <signal>clicked()</signal>
- <receiver>ViewerBase</receiver>
- <slot>addAll_clicked()</slot>
- </connection>
- <connection>
- <sender>choose</sender>
- <signal>clicked()</signal>
- <receiver>ViewerBase</receiver>
- <slot>choose_clicked()</slot>
- </connection>
- <connection>
- <sender>files</sender>
- <signal>currentChanged(Q3ListBoxItem*)</signal>
- <receiver>ViewerBase</receiver>
- <slot>files_currentChanged(Q3ListBoxItem*)</slot>
- </connection>
- <connection>
- <sender>tabWidget2</sender>
- <signal>selected(const QString&amp;)</signal>
- <receiver>ViewerBase</receiver>
- <slot>tabWidget2_selected(const QString&amp;)</slot>
- </connection>
-</connections>
-<slots>
- <slot>addAll_clicked()</slot>
- <slot>choose_clicked()</slot>
- <slot>files_currentChanged(Q3ListBoxItem*)</slot>
- <slot>tabWidget2_selected(const QString&amp;)</slot>
-</slots>
-<layoutdefaults spacing="6" margin="11"/>
-</UI>
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewerbase.ui
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-designer
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt (nonexistent)
@@ -1,54 +0,0 @@
-set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} )
-
-add_definitions ( -DQT3_SUPPORT -DQT3_SUPPORT_WARNINGS)
-
-#if(false)
-
-include_directories(
- ${CMAKE_CURRENT_BINARY_DIR}
- ${AutomakeManager_SOURCE_DIR}
- ${KDE4_INCLUDES}
-)
-
-########### next target ###############
-
-set(runner_SRCS
- runner.cpp
-)
-
-kde4_add_executable(runner TEST ${runner_SRCS})
-target_link_libraries(runner ${KDE4_KDECORE_LIBS} ${KDE4_KIO_LIBS})
-
-
-
-########### next target ###############
-set(viewer_SRCS
- viewer.cpp
- viewer_main.cpp
-)
-
-set(viewer_UI
- viewerbase.ui
-)
-
-kde4_add_ui3_files(viewer_SRCS ${viewer_UI})
-kde4_add_executable(viewer TEST ${viewer_SRCS})
-target_link_libraries(viewer ${KDE4_KDECORE_LIBS} ${KDE4_KIO_LIBS})
-
-
-########### next target ###############
-
-set(testinterface_SRCS
- ../automakeast.cpp
- ../automakedriver.cpp
- ../automakeparser.cpp
- ../makefileinterface.cpp
- testinterface.cpp
-)
-
-kde4_add_unit_test(kdevautomake-test ${testinterface_SRCS})
-target_link_libraries(kdevautomake-test ${KDE4_KDECORE_LIBS} ${QT_QTTEST_LIBRARY} ${KDE4_KIO_LIBS})
-
-#endif(false)
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.cpp (nonexistent)
@@ -1,164 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include "viewer.h"
-
-#include <QDir>
-#include <QLineEdit>
-#include <q3listbox.h>
-#include <q3filedialog.h>
-#include <q3textedit.h>
-#include <QFile>
-#include <qtextstream.h>
-#include <q3listview.h>
-#include <qtabwidget.h>
-//Added by qt3to4:
-#include <Q3ValueList>
-
-#include <automakeast.h>
-#include <automakedriver.h>
-
-using namespace AutoMake;
-
-Viewer::Viewer(QWidget *parent)
- : QWidget(parent), Ui::ViewerBase()
-{
- setupUi(this);
- if (QFile::exists(QDir::currentDirPath() + '/' + "qtlist"))
- {
- QFile f(QDir::currentDirPath() + '/' + "qtlist");
- f.open(QIODevice::ReadOnly);
- QTextStream str(&f);
- while (!str.atEnd())
- files->insertItem(str.readLine());
- }
- ast->setSorting(-1);
- parentProject.push((Q3ListViewItem*)0);
-}
-
-void Viewer::on_addAll_clicked()
-{
- if (allLocation->text().isEmpty())
- return;
- QDir d(allLocation->text());
- QStringList l = d.entryList("*.am");
- for (QStringList::iterator it = l.begin(); it != l.end(); ++it)
- (*it) = QDir::cleanDirPath(allLocation->text() + '/' + (*it));
- files->insertStringList(l);
-}
-
-void Viewer::on_choose_clicked()
-{
- QString fileName = Q3FileDialog::getOpenFileName(QDir::currentDirPath(), "*.am", this);
- if (!fileName.isEmpty())
- files->insertItem(fileName);
-}
-
-void Viewer::on_files_currentChanged(Q3ListBoxItem* item)
-{
- ast->clear();
-
- QFile f(item->text());
- f.open(QIODevice::ReadOnly);
- QTextStream str(&f);
- source->setText(str.read());
- f.close();
-
- int result = Driver::parseFile(item->text().ascii(), &projectAST);
- if (projectAST && (result == 0))
- {
- processAST(projectAST);
- }
- if (tabWidget2->currentPageIndex() == 1)
- tabWidget2_selected("Source to be written back");
-}
-
-void Viewer::tabWidget2_selected(const QString& text)
-{
- if ((text == "Source to be written back") && projectAST)
- {
- QString buffer;
- projectAST->writeBack(buffer);
- writeBack->setText(buffer);
- }
-}
-
-void Viewer::processAST(ProjectAST *projectAST, Q3ListViewItem *globAfter)
-{
- Q3ListViewItem *projectIt;
- if (!parentProject.top())
- projectIt = new Q3ListViewItem(ast, "Project");
- else
- {
- if ( projectAST->isConditionalScope() || projectAST->isRule() )
- projectIt = new Q3ListViewItem(parentProject.top(), globAfter, projectAST->scopedID);
- }
- projectIt->setOpen(true);
-
- Q3ListViewItem *after = 0;
- for (QList<AST*>::const_iterator it = projectAST->statements.constBegin();
- it != projectAST->statements.constEnd(); ++it)
- {
- AST *ast = *it;
- if (ast == 0)
- continue;
- switch (ast->nodeType()) {
- case AST::AssignmentAST: {
- AssignmentAST *assignmentAST = static_cast<AssignmentAST*>(ast);
- Q3ListViewItem *item = new Q3ListViewItem(projectIt, after,
- assignmentAST->scopedID, assignmentAST->op, assignmentAST->values.join(""));
- item->setMultiLinesEnabled(true);
- after = item; }
- break;
-
- case AST::TargetAST:
- {
- AutomakeTargetAST* ata = static_cast<AutomakeTargetAST*>(ast);
- Q3ListViewItem* item = new Q3ListViewItem(projectIt, after,
- ata->target, QString(), ata->deps.join(""));
- after = item;
- }
- break;
-
- case AST::NewLineAST:
-// after = new QListViewItem(projectIt, after, "<newline>");
- break;
-
- case AST::CommentAST:
-// after = new QListViewItem(projectIt, after, "<comment>");
- break;
-
- case AST::MakefileConditionalAST:
- {
- ConditionAST* ata = static_cast<ConditionAST*>(ast);
- Q3ListViewItem* item = new Q3ListViewItem(projectIt, after,
- ata->type, ata->conditionName, QString() );
- after = item;
- }
- case AST::ProjectAST: {
- ProjectAST *projectAST = static_cast<ProjectAST*>(ast);
- parentProject.push(projectIt);
- processAST(projectAST, after);
- parentProject.pop(); }
- break;
- }
- }
-}
-
-#include "viewer.moc"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.h (nonexistent)
@@ -1,46 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef VIEWER_H
-#define VIEWER_H
-
-#include <QStack>
-
-#include "viewerbase.h"
-
-namespace AutoMake { class ProjectAST; }
-
-class Q3ListViewItem;
-
-class Viewer: public QWidget, private Ui::ViewerBase
-{
-Q_OBJECT
-public:
- Viewer(QWidget *parent = 0);
- void processAST(AutoMake::ProjectAST *projectAST, Q3ListViewItem *globAfter = 0);
-public slots:
- virtual void tabWidget2_selected(const QString&);
- virtual void on_files_currentChanged(Q3ListBoxItem*);
- virtual void on_choose_clicked();
- virtual void on_addAll_clicked();
-private:
- AutoMake::ProjectAST *projectAST;
- QStack<Q3ListViewItem *> parentProject;
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-chdr
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/runner.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/runner.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/runner.cpp (nonexistent)
@@ -1,32 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include <automakeast.h>
-#include <automakedriver.h>
-
-using namespace AutoMake;
-
-int main(int argc, char *argv[])
-{
- ProjectAST *projectAST;
- if (argc > 1)
- return Driver::parseFile(argv[1], &projectAST);
- else
- return 0;
-}
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/runner.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp (nonexistent)
@@ -1,33 +0,0 @@
-/***************************************************************************
- * Copyright 2005 Alexander Dymo <adymo@kdevelop.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include <qapplication.h>
-#include "viewer.h"
-
-int main(int argc, char **argv)
-{
- QApplication app(argc, argv);
-
- Viewer viewer;
- app.setMainWidget(&viewer);
- viewer.show();
- viewer.resize(800, 600);
- //viewer.setWindowState(viewer.windowState() | Qt::WindowMaximized);
-
- return app.exec();
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/viewer_main.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Deleted: svn:keywords
## -1 +0,0 ##
-Author Date Id Revision
\ No newline at end of property
Deleted: svn:mime-type
## -1 +0,0 ##
-text/x-c++src
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.cpp (nonexistent)
@@ -1,64 +0,0 @@
-/***************************************************************************
- * KDevelop Automake Support Tests *
- * Copyright 2005 Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "testinterface.h"
-#include <QtTest/QtTest>
-#include "makefileinterface.h"
-
-QTEST_MAIN(TestInterface)
-
-void TestInterface::testIsVariable()
-{
- QFETCH(QString, variable);
- QFETCH(bool, result);
-
- QCOMPARE( MakefileInterface::isVariable( variable ), result );
-}
-
-void TestInterface::testIsVariable_data()
-{
- QTest::addColumn<QString>("variable");
- QTest::addColumn<bool>("result");
-
- QTest::newRow("v1") << "$(top_srcdir1)" << true;
- QTest::newRow("v2") << "$(!DFDFDDFFD)" << false;
- QTest::newRow("v3") << "@MY_1VARIABLE@" << true;
- QTest::newRow("v4") << "@%#$ASDFSDF#@" << false;
- QTest::newRow("v5") << "bin_PROGRAMS" << false;
-}
-
-void TestInterface::testCanonicalize()
-{
- QFETCH(QString, target);
- QFETCH(QString, result);
-
- QCOMPARE( MakefileInterface::canonicalize( target ), result );
-}
-
-void TestInterface::testCanonicalize_data()
-{
- QTest::addColumn<QString>("target");
- QTest::addColumn<QString>("result");
- QTest::newRow("v1") << "libfoo.la" << "libfoo_la";
- QTest::newRow("v2") << "libbar++.la" << "libbar___la";
- QTest::newRow("v3") << "lib123!#$%^.la" << "lib123______la";
-}
-
-#include "testinterface.moc"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.h (nonexistent)
@@ -1,38 +0,0 @@
-/***************************************************************************
- * KDevelop Automake Support Tests *
- * Copyright 2005 Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#ifndef TESTINTERFACE_H
-#define TESTINTERFACE_H
-
-#include <QtCore/QObject>
-
-class TestInterface : public QObject
-{
-Q_OBJECT
-private slots:
- void testIsVariable();
- void testIsVariable_data();
-
- void testCanonicalize();
- void testCanonicalize_data();
-
-};
-
-#endif
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests/testinterface.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/tests
___________________________________________________________________
Deleted: svn:ignore
## -1,3 +0,0 ##
-Makefile
-Makefile.in
-qtlist
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.h (nonexistent)
@@ -1,267 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef AUTOMAKEAST_H
-#define AUTOMAKEAST_H
-
-#include <QList>
-#include <QStringList>
-
-/**
-@file autotools.h
-Abstract Syntax Tree (AST) class declarations.
-*/
-
-namespace AutoMake
-{
-
-/**
- * AST node.
- * This is the base class. Objects of this type are not created by the parser.
- *
- * Each AST node holds the list of its children which are always deleted in the
- * destructor. This way, it's possible call delete for only root AST node and
- * others will be deleted automatically.
- *
- * Each AST node also knows how to write the information back into .pro file.
- */
-class AST
-{
-public:
- /**Type of AST node.*/
- enum NodeType {
- ProjectAST, ///< Project, scope or function scope.
- AssignmentAST, ///< Variable assignment.
- TargetAST, ///< Automake target
- MakefileConditionalAST, ///< Makefile.am conditional
- NewLineAST, ///< Line feed.
- CommentAST ///< Comment.
- };
-
- /** Constructs AST with given node type.*/
- AST(NodeType nodeType): m_nodeType(nodeType), m_depth(0) {}
- virtual ~AST();
-
- /**
- * Adds child AST node to this node. Despite this function is virtual,
- * reimplementations should call it to make automatic destruction of
- * AST tree possible.*/
- virtual void addChildAST(AST *node);
-
- /**
- * Writes information stored in the AST into the @p buffer.
- * This is a default implementation which iterates over child nodes
- * and calls writeBack for each child node.
- */
- virtual void writeBack(QString &buffer);
-
- /** @return The type of the node.*/
- virtual NodeType nodeType() const { return m_nodeType; }
-
- /** Sets the depth of the node in AST.*/
- void setDepth(int depth) { m_depth = depth; }
-
- /** @return The depth of the node in AST.*/
- int depth() const { return m_depth; }
-
- /** @return The indentation string based on node depth.*/
- virtual QString indentation();
-
- //! \return true if this AST has children
- bool hasChildren() const;
-
- /**
- * Get the children of this ast
- * \return the list of this ast's children
- */
- QList<AST*> children() const;
-
-
-
-protected:
- NodeType m_nodeType;
- QList<AST*> m_children;
-
-private:
- int m_depth;
-
-};
-
-
-/**
- * Project AST node.
- * Represents complete projects, scopes and function scopes.
- * Examples:
- * @code
- * scopename{
- * var=value
- * }
- * function(args){
- * var=value
- * }
- * @endcode
- */
-class ProjectAST: public AST
-{
-public:
- /**The kind of a project node.*/
- enum Kind
- {
- Project, ///< Project
- Target, ///< Custom Automake Target
- ConditionalScope, ///< Automake Conditional
- Rule, ///< Automake Rule
- Empty ///< Project does not exist. the AST is empty
- };
-
- /** Constructs a project node of given @p kind. */
- ProjectAST(Kind kind = Project): AST(AST::ProjectAST), m_kind(kind) {}
-
- virtual void writeBack(QString &buffer);
- virtual void addChildAST(AST *node);
-
- /** @return true if this node is a project.*/
- bool isProject() const { return m_kind == Project; }
-
- bool isRule() const { return m_kind == Rule; }
-
- /** @return true if this node is an automake conditional */
- bool isConditionalScope() const { return m_kind == ConditionalScope; }
-
- /** @return true if this node is empty.*/
- bool isEmpty() const { return m_kind == Empty; }
-
- /**Scoped identifier (scope name or rule).*/
- QString scopedID;
-
- /**Function arguments. Empty for other kinds of projects.*/
- QString args;
-
- /** The automake conditional has an else attached */
- bool hasElse;
-
- /**List of statements.*/
- QList<AutoMake::AST*> statements;
-
-private:
- Kind m_kind;
-
-};
-
-
-/**
- * Assignment AST node.
- * Represents assignments, for example:
- * \code
- * var=value
- * \endcode
- *
- * Values can be specified on several lines and
- * each line is stored as a string in the list of values.@n
- * For example, if we have in .pro:
- * \code
- * SOURCES=a.cpp \
- * b.cpp c.cpp
- * \endcode
- * then values will be stored as a two elements list:
- * \code
- * a.cpp
- * b.cpp c.cpp
- * \endcode
- */
-class AssignmentAST: public AST
-{
-public:
- AssignmentAST(): AST(AST::AssignmentAST) {}
-
- virtual void writeBack(QString &buffer);
-
- /**Scoped name of the variable.*/
- QString scopedID;
-
- /**Operator.*/
- QString op;
-
- /**List of values.*/
- QStringList values;
-};
-
-class AutomakeTargetAST : public AST
-{
-public:
- AutomakeTargetAST() : AST(AST::TargetAST) {}
-
- virtual void writeBack( QString& buffer );
-
- /// The name of the target
- QString target;
-
- /// The dependencies for the target, if any
- QStringList deps;
-};
-
-class ConditionAST : public AST
-{
-public:
- ConditionAST() : AST( AST::MakefileConditionalAST ) {}
-
- virtual void writeBack( QString& buffer );
-
- /// The keyword for the condition (if, else, endif)
- QString type;
-
- /// The name of the condition
- QString conditionName;
-};
-
-/**
- * New line AST node.
- * Represents line feeds in files.
- */
-class NewLineAST: public AST
-{
-public:
- NewLineAST(): AST(AST::NewLineAST) {}
-
- virtual void writeBack(QString &buffer);
-};
-
-
-/**
- * Comment AST node.
- * Represents comments.
- */
-class CommentAST: public AST
-{
-public:
- CommentAST(): AST(AST::CommentAST) {}
-
- virtual void writeBack(QString &buffer);
-
- /**Comment text.*/
- QString comment;
-
-};
-
-}
-
-#endif
-
-// kate: indent-mode csands; space-indent off; tab-width 4; auto-insert-doxygen on;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop (nonexistent)
@@ -1,53 +0,0 @@
-[Desktop Entry]
-Type=Service
-Name=Autotools Importer
-Name[bs]=Autotools uvoz
-Name[ca]=Importador Autotools
-Name[ca@valencia]=Importador Autotools
-Name[de]=Autotools-Import
-Name[en_GB]=Autotools Importer
-Name[es]=Importador Autotools
-Name[et]=Autotoolsi importija
-Name[fr]=Importateur Autools
-Name[ga]=Iompórtálaí Autotools
-Name[gl]=Importador de Autotools
-Name[it]=Importatore per Autotools
-Name[nl]=Import van Autotools
-Name[pl]=Importowanie Autotools
-Name[pt]=Importação das Autotools
-Name[pt_BR]=Importação das Autotools
-Name[sv]=Import av Autotools
-Name[uk]=Імпортування з Autotools
-Name[x-test]=xxAutotools Importerxx
-Comment=Allows to manage projects using a GNU-based build system
-Comment[bs]=Dozvoljava upravljanje projektima korištenjem GNU-baziranog build sistema
-Comment[ca]=Permet gestionar projectes que usen un sistema de construcció basat en GNU
-Comment[ca@valencia]=Permet gestionar projectes que usen un sistema de construcció basat en GNU
-Comment[de]=Ermöglicht die Verwaltung von Projekten mit einem GNU-basierten Erstellungssystem
-Comment[en_GB]=Allows to manage projects using a GNU-based build system
-Comment[es]=Permite gestionar proyectos que usan un sistema de construcción basado en GNU
-Comment[et]=Võimaldab hallata projekte GNU-põhise ehitussüsteemi alusel
-Comment[fr]=Permet de gérer des projets à l'aide d'un système de construction fondé sur GNU
-Comment[gl]=Permite xestionar proxectos usando un sistema de compilación baseado en GNU.
-Comment[it]=Consente di gestire progetti utilizzando un sistema di creazione basato su GNU
-Comment[nl]=Geeft de mogelijkheid tot het beheren van projecten met een GNU-gebaseerd bouw systeem
-Comment[pl]=Pozwala na zarządzanie projektami przy użyciu systemu budowania opartego o GNU
-Comment[pt]=Permite ao KDevelop gerir projectos com um sistema de compilações baseado na GNU
-Comment[pt_BR]=Permite gerenciar projetos com um sistema de compilações baseado na GNU
-Comment[sv]=Gör det möjligt att hantera projekt som använder ett GNU-baserat byggsystem
-Comment[uk]=Надає змогу керувати проектами за допомогою заснованої на GNU системи збирання
-Comment[x-test]=xxAllows to manage projects using a GNU-based build systemxx
-Icon=gear
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevautomakeimporter
-X-KDE-PluginInfo-Author=Matt Rogers
-X-KDE-PluginInfo-Email=mattr@kde.org
-X-KDE-PluginInfo-Version=0.1
-X-KDE-PluginInfo-Name=KDevAutotoolsImporter
-X-KDE-PluginInfo-Category=Project Management
-X-KDevelop-FileManager=GNU Autotools
-X-KDevelop-Version=12
-X-KDevelop-Interfaces=org.kdevelop.IBuildSystemManager,org.kdevelop.IProjectFileManager
-X-KDevelop-Mode=NoGUI
-X-KDevelop-ProjectFilesFilter=*.am
-X-KDevelop-ProjectFilesFilterDescription=Automake Project Files
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/kdevautomakeimporter.desktop
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.h (nonexistent)
@@ -1,101 +0,0 @@
-/* A Bison parser, made by GNU Bison 2.1. */
-
-/* Skeleton parser for Yacc-like parsing with Bison,
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
-
- 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, 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., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA. */
-
-/* As a special exception, when this file is copied by Bison into a
- Bison output file, you may use that output file without restriction.
- This special exception was added by the Free Software Foundation
- in version 1.24 of Bison. */
-
-/* Tokens. */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
- /* Put the tokens into the symbol table, so that GDB and other debuggers
- know about them. */
- enum yytokentype {
- ID_SIMPLE = 258,
- ID_LIST = 259,
- LBRACE = 260,
- EQ = 261,
- PLUSEQ = 262,
- MINUSQE = 263,
- STAREQ = 264,
- TILDEEQ = 265,
- RBRACE = 266,
- COLON = 267,
- NUMSIGN = 268,
- NEWLINE = 269,
- NUMBER = 270,
- COMMENT = 271,
- CONT = 272,
- DOT = 273,
- RCURLY = 274,
- LCURLY = 275,
- ID_ARGS = 276,
- LIST_COMMENT = 277,
- ID_LIST_SINGLE = 278,
- IF_KEYWORD = 279,
- ELSE_KEYWORD = 280,
- ENDIF_KEYWORD = 281,
- KEYWORD = 282,
- RULE = 283
- };
-#endif
-/* Tokens. */
-#define ID_SIMPLE 258
-#define ID_LIST 259
-#define LBRACE 260
-#define EQ 261
-#define PLUSEQ 262
-#define MINUSQE 263
-#define STAREQ 264
-#define TILDEEQ 265
-#define RBRACE 266
-#define COLON 267
-#define NUMSIGN 268
-#define NEWLINE 269
-#define NUMBER 270
-#define COMMENT 271
-#define CONT 272
-#define DOT 273
-#define RCURLY 274
-#define LCURLY 275
-#define ID_ARGS 276
-#define LIST_COMMENT 277
-#define ID_LIST_SINGLE 278
-#define IF_KEYWORD 279
-#define ELSE_KEYWORD 280
-#define ENDIF_KEYWORD 281
-#define KEYWORD 282
-#define RULE 283
-
-
-
-
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-typedef int YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
-#endif
-
-extern YYSTYPE yylval;
-
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.cpp (nonexistent)
@@ -1,1786 +0,0 @@
-/* A Bison parser, made by GNU Bison 2.1. */
-
-/* Skeleton parser for Yacc-like parsing with Bison,
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
-
- 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, 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., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA. */
-
-/* As a special exception, when this file is copied by Bison into a
- Bison output file, you may use that output file without restriction.
- This special exception was added by the Free Software Foundation
- in version 1.24 of Bison. */
-
-/* Written by Richard Stallman by simplifying the original so called
- ``semantic'' parser. */
-
-/* All symbols defined below should begin with yy or YY, to avoid
- infringing on user name space. This should be done even for local
- variables, as they might otherwise be expanded by user macros.
- There are some unavoidable exceptions within include files to
- define necessary library symbols; they are noted "INFRINGES ON
- USER NAME SPACE" below. */
-
-/* Identify Bison output. */
-#define YYBISON 1
-
-/* Bison version. */
-#define YYBISON_VERSION "2.1"
-
-/* Skeleton name. */
-#define YYSKELETON_NAME "yacc.c"
-
-/* Pure parsers. */
-#define YYPURE 0
-
-/* Using locations. */
-#define YYLSP_NEEDED 0
-
-
-
-/* Tokens. */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
- /* Put the tokens into the symbol table, so that GDB and other debuggers
- know about them. */
- enum yytokentype {
- ID_SIMPLE = 258,
- ID_LIST = 259,
- LBRACE = 260,
- EQ = 261,
- PLUSEQ = 262,
- MINUSQE = 263,
- STAREQ = 264,
- TILDEEQ = 265,
- RBRACE = 266,
- COLON = 267,
- NUMSIGN = 268,
- NEWLINE = 269,
- NUMBER = 270,
- COMMENT = 271,
- CONT = 272,
- DOT = 273,
- RCURLY = 274,
- LCURLY = 275,
- ID_ARGS = 276,
- LIST_COMMENT = 277,
- ID_LIST_SINGLE = 278,
- IF_KEYWORD = 279,
- ELSE_KEYWORD = 280,
- ENDIF_KEYWORD = 281,
- KEYWORD = 282,
- RULE = 283
- };
-#endif
-/* Tokens. */
-#define ID_SIMPLE 258
-#define ID_LIST 259
-#define LBRACE 260
-#define EQ 261
-#define PLUSEQ 262
-#define MINUSQE 263
-#define STAREQ 264
-#define TILDEEQ 265
-#define RBRACE 266
-#define COLON 267
-#define NUMSIGN 268
-#define NEWLINE 269
-#define NUMBER 270
-#define COMMENT 271
-#define CONT 272
-#define DOT 273
-#define RCURLY 274
-#define LCURLY 275
-#define ID_ARGS 276
-#define LIST_COMMENT 277
-#define ID_LIST_SINGLE 278
-#define IF_KEYWORD 279
-#define ELSE_KEYWORD 280
-#define ENDIF_KEYWORD 281
-#define KEYWORD 282
-#define RULE 283
-
-
-
-
-/* Copy the first part of user declarations. */
-#line 1 "autotools.yy"
-
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-/**
-@file autotools.yy
-Autotools Parser
-
-Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
-
-@todo Recognize comments after statements like:
-noinst_HEADERS = foo.h #regognize me
-
-@fixme Parser fails on files that do not end with a newline
-@fixme 1 shift/reduce conflict in "line_body" rule
-*/
-
-
-#include <qstack.h>
-#include "automakeast.h"
-
-#define YYSTYPE_IS_DECLARED
-
-using namespace AutoMake;
-
-/**
-The yylval type.
-*/
-typedef struct Result {
- Result(): node(0) {}
-
- /**Type of semantic value for simple grammar rules.*/
- QString value;
- /**Type of semantic value for grammar rules which are parts of AST.*/
- AST *node;
- /**Type of semantic value for "multiline_values" grammar rule.
- Each line of multiline value is stored as a string in the list.
-
- For example we have in Makefile.am file:
- @code
- foo_SOURCES = foo1.cpp \
- foo2.cpp \
- foo3.cpp foo4.cpp
- @endcode
- The string list will be populated with three strings:
- <pre>
- foo1.cpp
- foo2.cpp
- foo3.cpp foo4.cpp
- </pre>
- */
- QStringList values;
-} YYSTYPE;
-
-
-void yyerror(const char *str) {
- qWarning("bison error: %s\n", str);
-}
-
-int yylex();
-
-/**
-The stack to store ProjectAST pointers when a new child
-ProjectAST is created and filled with statements.
-
-Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
-adding statements. Each statement is added as a child StatementAST to the ProjectAST
-currently on the top in the stack.
-
-When a scope or function scope statement is parsed, the child ProjectAST is created
-and pushed onto the stack. Therefore all statements which belong to the scope
-or function scope are added as childs to their direct parent (scope or function scope).
-*/
-QStack<ProjectAST*> projects;
-
-/**
-The current depth of AST node is stored here.
-AST depth is important to know because automatic indentation can
-be easily implemented (the parser itself looses all information
-about indentation).
-*/
-int depth = 0;
-
-/*
-To debug this parser, put the line below into the next bison file section.
-Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
-%debug
-*/
-
-
-/* Enabling traces. */
-#ifndef YYDEBUG
-# define YYDEBUG 1
-#endif
-
-/* Enabling verbose error messages. */
-#ifdef YYERROR_VERBOSE
-# undef YYERROR_VERBOSE
-# define YYERROR_VERBOSE 1
-#else
-# define YYERROR_VERBOSE 0
-#endif
-
-/* Enabling the token table. */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
-#endif
-
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-typedef int YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
-#endif
-
-
-
-/* Copy the second part of user declarations. */
-
-
-/* Line 219 of yacc.c. */
-#line 262 "autotools_yacc.cpp"
-
-#if ! defined (YYSIZE_T) && defined (__SIZE_TYPE__)
-# define YYSIZE_T __SIZE_TYPE__
-#endif
-#if ! defined (YYSIZE_T) && defined (size_t)
-# define YYSIZE_T size_t
-#endif
-#if ! defined (YYSIZE_T) && (defined (__STDC__) || defined (__cplusplus))
-# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
-# define YYSIZE_T size_t
-#endif
-#if ! defined (YYSIZE_T)
-# define YYSIZE_T unsigned int
-#endif
-
-#ifndef YY_
-# if YYENABLE_NLS
-# if ENABLE_NLS
-# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-# define YY_(msgid) dgettext ("bison-runtime", msgid)
-# endif
-# endif
-# ifndef YY_
-# define YY_(msgid) msgid
-# endif
-#endif
-
-#if ! defined (yyoverflow) || YYERROR_VERBOSE
-
-/* The parser invokes alloca or malloc; define the necessary symbols. */
-
-# ifdef YYSTACK_USE_ALLOCA
-# if YYSTACK_USE_ALLOCA
-# ifdef __GNUC__
-# define YYSTACK_ALLOC __builtin_alloca
-# else
-# define YYSTACK_ALLOC alloca
-# if defined (__STDC__) || defined (__cplusplus)
-# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-# define YYINCLUDED_STDLIB_H
-# endif
-# endif
-# endif
-# endif
-
-# ifdef YYSTACK_ALLOC
- /* Pacify GCC's `empty if-body' warning. */
-# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
-# ifndef YYSTACK_ALLOC_MAXIMUM
- /* The OS might guarantee only one guard page at the bottom of the stack,
- and a page size can be as small as 4096 bytes. So we cannot safely
- invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
- to allow for a few compiler-allocated temporary stack slots. */
-# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2005 */
-# endif
-# else
-# define YYSTACK_ALLOC YYMALLOC
-# define YYSTACK_FREE YYFREE
-# ifndef YYSTACK_ALLOC_MAXIMUM
-# define YYSTACK_ALLOC_MAXIMUM ((YYSIZE_T) -1)
-# endif
-# ifdef __cplusplus
-extern "C" {
-# endif
-# ifndef YYMALLOC
-# define YYMALLOC malloc
-# if (! defined (malloc) && ! defined (YYINCLUDED_STDLIB_H) \
- && (defined (__STDC__) || defined (__cplusplus)))
-void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
-# endif
-# endif
-# ifndef YYFREE
-# define YYFREE free
-# if (! defined (free) && ! defined (YYINCLUDED_STDLIB_H) \
- && (defined (__STDC__) || defined (__cplusplus)))
-void free (void *); /* INFRINGES ON USER NAME SPACE */
-# endif
-# endif
-# ifdef __cplusplus
-}
-# endif
-# endif
-#endif /* ! defined (yyoverflow) || YYERROR_VERBOSE */
-
-
-#if (! defined (yyoverflow) \
- && (! defined (__cplusplus) \
- || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))
-
-/* A type that is properly aligned for any stack member. */
-union yyalloc
-{
- short int yyss;
- YYSTYPE yyvs;
- };
-
-/* The size of the maximum gap between one aligned stack and the next. */
-# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
-
-/* The size of an array large to enough to hold all stacks, each with
- N elements. */
-# define YYSTACK_BYTES(N) \
- ((N) * (sizeof (short int) + sizeof (YYSTYPE)) \
- + YYSTACK_GAP_MAXIMUM)
-
-/* Copy COUNT objects from FROM to TO. The source and destination do
- not overlap. */
-# ifndef YYCOPY
-# if defined (__GNUC__) && 1 < __GNUC__
-# define YYCOPY(To, From, Count) \
- __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-# else
-# define YYCOPY(To, From, Count) \
- do \
- { \
- YYSIZE_T yyi; \
- for (yyi = 0; yyi < (Count); yyi++) \
- (To)[yyi] = (From)[yyi]; \
- } \
- while (0)
-# endif
-# endif
-
-/* Relocate STACK from its old location to the new one. The
- local variables YYSIZE and YYSTACKSIZE give the old and new number of
- elements in the stack, and YYPTR gives the new location of the
- stack. Advance YYPTR to a properly aligned location for the next
- stack. */
-# define YYSTACK_RELOCATE(Stack) \
- do \
- { \
- YYSIZE_T yynewbytes; \
- YYCOPY (&yyptr->Stack, Stack, yysize); \
- Stack = &yyptr->Stack; \
- yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
- yyptr += yynewbytes / sizeof (*yyptr); \
- } \
- while (0)
-
-#endif
-
-#if defined (__STDC__) || defined (__cplusplus)
- typedef signed char yysigned_char;
-#else
- typedef short int yysigned_char;
-#endif
-
-/* YYFINAL -- State number of the termination state. */
-#define YYFINAL 3
-/* YYLAST -- Last index in YYTABLE. */
-#define YYLAST 33
-
-/* YYNTOKENS -- Number of terminals. */
-#define YYNTOKENS 29
-/* YYNNTS -- Number of nonterminals. */
-#define YYNNTS 18
-/* YYNRULES -- Number of rules. */
-#define YYNRULES 35
-/* YYNRULES -- Number of states. */
-#define YYNSTATES 43
-
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
-#define YYUNDEFTOK 2
-#define YYMAXUTOK 283
-
-#define YYTRANSLATE(YYX) \
- ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
-
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
-static const unsigned char yytranslate[] =
-{
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
- 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 26, 27, 28
-};
-
-#if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
- YYRHS. */
-static const unsigned char yyprhs[] =
-{
- 0, 0, 3, 4, 7, 10, 11, 13, 15, 17,
- 19, 21, 23, 25, 27, 29, 32, 34, 37, 39,
- 42, 46, 49, 51, 54, 55, 58, 61, 63, 65,
- 69, 71, 74, 76, 78, 81
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS. */
-static const yysigned_char yyrhs[] =
-{
- 30, 0, -1, -1, 31, 32, -1, 32, 33, -1,
- -1, 37, -1, 34, -1, 36, -1, 35, -1, 41,
- -1, 42, -1, 43, -1, 45, -1, 46, -1, 24,
- 38, -1, 26, -1, 26, 38, -1, 25, -1, 25,
- 38, -1, 38, 44, 39, -1, 3, 38, -1, 3,
- -1, 39, 40, -1, -1, 4, 17, -1, 23, 14,
- -1, 17, -1, 22, -1, 38, 12, 39, -1, 28,
- -1, 27, 38, -1, 6, -1, 7, -1, 16, 14,
- -1, 14, -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
-static const unsigned short int yyrline[] =
-{
- 0, 142, 142, 142, 149, 175, 178, 182, 186, 190,
- 194, 198, 202, 206, 210, 216, 224, 230, 239, 245,
- 254, 264, 266, 269, 274, 277, 278, 279, 280, 283,
- 292, 300, 309, 309, 312, 320
-};
-#endif
-
-#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
-/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
- First, the terminals, then, starting at YYNTOKENS, nonterminals. */
-static const char *const yytname[] =
-{
- "$end", "error", "$undefined", "ID_SIMPLE", "ID_LIST", "LBRACE", "EQ",
- "PLUSEQ", "MINUSQE", "STAREQ", "TILDEEQ", "RBRACE", "COLON", "NUMSIGN",
- "NEWLINE", "NUMBER", "COMMENT", "CONT", "DOT", "RCURLY", "LCURLY",
- "ID_ARGS", "LIST_COMMENT", "ID_LIST_SINGLE", "IF_KEYWORD",
- "ELSE_KEYWORD", "ENDIF_KEYWORD", "KEYWORD", "RULE", "$accept", "project",
- "@1", "statements", "statement", "automake_if", "endif_statement",
- "else_statement", "variable_assignment", "scoped_identifier",
- "multiline_values", "line_body", "target", "am_rule",
- "include_directive", "operator", "comment", "emptyline", 0
-};
-#endif
-
-# ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
- token YYLEX-NUM. */
-static const unsigned short int yytoknum[] =
-{
- 0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
- 265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
- 275, 276, 277, 278, 279, 280, 281, 282, 283
-};
-# endif
-
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
-static const unsigned char yyr1[] =
-{
- 0, 29, 31, 30, 32, 32, 33, 33, 33, 33,
- 33, 33, 33, 33, 33, 34, 35, 35, 36, 36,
- 37, 38, 38, 39, 39, 40, 40, 40, 40, 41,
- 42, 43, 44, 44, 45, 46
-};
-
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
-static const unsigned char yyr2[] =
-{
- 0, 2, 0, 2, 2, 0, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 2, 1, 2, 1, 2,
- 3, 2, 1, 2, 0, 2, 2, 1, 1, 3,
- 1, 2, 1, 1, 2, 1
-};
-
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
- STATE-NUM when YYTABLE doesn't specify something else to do. Zero
- means the default is an error. */
-static const unsigned char yydefact[] =
-{
- 2, 0, 5, 1, 3, 22, 35, 0, 0, 18,
- 16, 0, 30, 4, 7, 9, 8, 6, 0, 10,
- 11, 12, 13, 14, 21, 34, 15, 19, 17, 31,
- 32, 33, 24, 24, 29, 20, 0, 27, 28, 0,
- 23, 25, 26
-};
-
-/* YYDEFGOTO[NTERM-NUM]. */
-static const yysigned_char yydefgoto[] =
-{
- -1, 1, 2, 4, 13, 14, 15, 16, 17, 18,
- 34, 40, 19, 20, 21, 33, 22, 23
-};
-
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
- STATE-NUM. */
-#define YYPACT_NINF -18
-static const yysigned_char yypact[] =
-{
- -18, 2, -18, -18, -3, 0, -18, -6, 0, 0,
- 0, 0, -18, -18, -18, -18, -18, -18, 3, -18,
- -18, -18, -18, -18, -18, -18, -18, -18, -18, -18,
- -18, -18, -18, -18, 10, 10, -5, -18, -18, 4,
- -18, -18, -18
-};
-
-/* YYPGOTO[NTERM-NUM]. */
-static const yysigned_char yypgoto[] =
-{
- -18, -18, -18, -18, -18, -18, -18, -18, -18, -4,
- -17, -18, -18, -18, -18, -18, -18, -18
-};
-
-/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
- positive, shift that token. If negative, reduce the rule which
- number is the opposite. If zero, do what YYDEFACT says.
- If YYTABLE_NINF, syntax error. */
-#define YYTABLE_NINF -1
-static const unsigned char yytable[] =
-{
- 5, 24, 3, 5, 26, 27, 28, 29, 25, 30,
- 31, 6, 41, 7, 36, 32, 35, 0, 42, 0,
- 0, 8, 9, 10, 11, 12, 0, 37, 0, 0,
- 0, 0, 38, 39
-};
-
-static const yysigned_char yycheck[] =
-{
- 3, 5, 0, 3, 8, 9, 10, 11, 14, 6,
- 7, 14, 17, 16, 4, 12, 33, -1, 14, -1,
- -1, 24, 25, 26, 27, 28, -1, 17, -1, -1,
- -1, -1, 22, 23
-};
-
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
- symbol of state STATE-NUM. */
-static const unsigned char yystos[] =
-{
- 0, 30, 31, 0, 32, 3, 14, 16, 24, 25,
- 26, 27, 28, 33, 34, 35, 36, 37, 38, 41,
- 42, 43, 45, 46, 38, 14, 38, 38, 38, 38,
- 6, 7, 12, 44, 39, 39, 4, 17, 22, 23,
- 40, 17, 14
-};
-
-#define yyerrok (yyerrstatus = 0)
-#define yyclearin (yychar = YYEMPTY)
-#define YYEMPTY (-2)
-#define YYEOF 0
-
-#define YYACCEPT goto yyacceptlab
-#define YYABORT goto yyabortlab
-#define YYERROR goto yyerrorlab
-
-
-/* Like YYERROR except do call yyerror. This remains here temporarily
- to ease the transition to the new meaning of YYERROR, for GCC.
- Once GCC version 2 has supplanted version 1, this can go. */
-
-#define YYFAIL goto yyerrlab
-
-#define YYRECOVERING() (!!yyerrstatus)
-
-#define YYBACKUP(Token, Value) \
-do \
- if (yychar == YYEMPTY && yylen == 1) \
- { \
- yychar = (Token); \
- yylval = (Value); \
- yytoken = YYTRANSLATE (yychar); \
- YYPOPSTACK; \
- goto yybackup; \
- } \
- else \
- { \
- yyerror (YY_("syntax error: cannot back up")); \
- YYERROR; \
- } \
-while (0)
-
-
-#define YYTERROR 1
-#define YYERRCODE 256
-
-
-/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
- If N is 0, then set CURRENT to the empty location which ends
- the previous symbol: RHS[0] (always defined). */
-
-#define YYRHSLOC(Rhs, K) ((Rhs)[K])
-#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N) \
- do \
- if (N) \
- { \
- (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
- (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
- (Current).last_line = YYRHSLOC (Rhs, N).last_line; \
- (Current).last_column = YYRHSLOC (Rhs, N).last_column; \
- } \
- else \
- { \
- (Current).first_line = (Current).last_line = \
- YYRHSLOC (Rhs, 0).last_line; \
- (Current).first_column = (Current).last_column = \
- YYRHSLOC (Rhs, 0).last_column; \
- } \
- while (0)
-#endif
-
-
-/* YY_LOCATION_PRINT -- Print the location on the stream.
- This macro was not mandated originally: define only if we know
- we won't break user code: when these are the locations we know. */
-
-#ifndef YY_LOCATION_PRINT
-# if YYLTYPE_IS_TRIVIAL
-# define YY_LOCATION_PRINT(File, Loc) \
- fprintf (File, "%d.%d-%d.%d", \
- (Loc).first_line, (Loc).first_column, \
- (Loc).last_line, (Loc).last_column)
-# else
-# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-# endif
-#endif
-
-
-/* YYLEX -- calling `yylex' with the right arguments. */
-
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (YYLEX_PARAM)
-#else
-# define YYLEX yylex ()
-#endif
-
-/* Enable debugging if requested. */
-#if YYDEBUG
-
-# ifndef YYFPRINTF
-# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
-# define YYFPRINTF fprintf
-# endif
-
-# define YYDPRINTF(Args) \
-do { \
- if (yydebug) \
- YYFPRINTF Args; \
-} while (0)
-
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
-do { \
- if (yydebug) \
- { \
- YYFPRINTF (stderr, "%s ", Title); \
- yysymprint (stderr, \
- Type, Value); \
- YYFPRINTF (stderr, "\n"); \
- } \
-} while (0)
-
-/*------------------------------------------------------------------.
-| yy_stack_print -- Print the state stack from its BOTTOM up to its |
-| TOP (included). |
-`------------------------------------------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yy_stack_print (short int *bottom, short int *top)
-#else
-static void
-yy_stack_print (bottom, top)
- short int *bottom;
- short int *top;
-#endif
-{
- YYFPRINTF (stderr, "Stack now");
- for (/* Nothing. */; bottom <= top; ++bottom)
- YYFPRINTF (stderr, " %d", *bottom);
- YYFPRINTF (stderr, "\n");
-}
-
-# define YY_STACK_PRINT(Bottom, Top) \
-do { \
- if (yydebug) \
- yy_stack_print ((Bottom), (Top)); \
-} while (0)
-
-
-/*------------------------------------------------.
-| Report that the YYRULE is going to be reduced. |
-`------------------------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yy_reduce_print (int yyrule)
-#else
-static void
-yy_reduce_print (yyrule)
- int yyrule;
-#endif
-{
- int yyi;
- unsigned long int yylno = yyrline[yyrule];
- YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu), ",
- yyrule - 1, yylno);
- /* Print the symbols being reduced, and their result. */
- for (yyi = yyprhs[yyrule]; 0 <= yyrhs[yyi]; yyi++)
- YYFPRINTF (stderr, "%s ", yytname[yyrhs[yyi]]);
- YYFPRINTF (stderr, "-> %s\n", yytname[yyr1[yyrule]]);
-}
-
-# define YY_REDUCE_PRINT(Rule) \
-do { \
- if (yydebug) \
- yy_reduce_print (Rule); \
-} while (0)
-
-/* Nonzero means print parse trace. It is left uninitialized so that
- multiple parsers can coexist. */
-int yydebug;
-#else /* !YYDEBUG */
-# define YYDPRINTF(Args)
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
-# define YY_STACK_PRINT(Bottom, Top)
-# define YY_REDUCE_PRINT(Rule)
-#endif /* !YYDEBUG */
-
-
-/* YYINITDEPTH -- initial size of the parser's stacks. */
-#ifndef YYINITDEPTH
-# define YYINITDEPTH 200
-#endif
-
-/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
- if the built-in stack extension method is used).
-
- Do not make this value too large; the results are undefined if
- YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
- evaluated with infinite-precision integer arithmetic. */
-
-#ifndef YYMAXDEPTH
-# define YYMAXDEPTH 10000
-#endif
-
-
-
-#if YYERROR_VERBOSE
-
-# ifndef yystrlen
-# if defined (__GLIBC__) && defined (_STRING_H)
-# define yystrlen strlen
-# else
-/* Return the length of YYSTR. */
-static YYSIZE_T
-# if defined (__STDC__) || defined (__cplusplus)
-yystrlen (const char *yystr)
-# else
-yystrlen (yystr)
- const char *yystr;
-# endif
-{
- const char *yys = yystr;
-
- while (*yys++ != '\0')
- continue;
-
- return yys - yystr - 1;
-}
-# endif
-# endif
-
-# ifndef yystpcpy
-# if defined (__GLIBC__) && defined (_STRING_H) && defined (_GNU_SOURCE)
-# define yystpcpy stpcpy
-# else
-/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
- YYDEST. */
-static char *
-# if defined (__STDC__) || defined (__cplusplus)
-yystpcpy (char *yydest, const char *yysrc)
-# else
-yystpcpy (yydest, yysrc)
- char *yydest;
- const char *yysrc;
-# endif
-{
- char *yyd = yydest;
- const char *yys = yysrc;
-
- while ((*yyd++ = *yys++) != '\0')
- continue;
-
- return yyd - 1;
-}
-# endif
-# endif
-
-# ifndef yytnamerr
-/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
- quotes and backslashes, so that it's suitable for yyerror. The
- heuristic is that double-quoting is unnecessary unless the string
- contains an apostrophe, a comma, or backslash (other than
- backslash-backslash). YYSTR is taken from yytname. If YYRES is
- null, do not copy; instead, return the length of what the result
- would have been. */
-static YYSIZE_T
-yytnamerr (char *yyres, const char *yystr)
-{
- if (*yystr == '"')
- {
- size_t yyn = 0;
- char const *yyp = yystr;
-
- for (;;)
- switch (*++yyp)
- {
- case '\'':
- case ',':
- goto do_not_strip_quotes;
-
- case '\\':
- if (*++yyp != '\\')
- goto do_not_strip_quotes;
- /* Fall through. */
- default:
- if (yyres)
- yyres[yyn] = *yyp;
- yyn++;
- break;
-
- case '"':
- if (yyres)
- yyres[yyn] = '\0';
- return yyn;
- }
- do_not_strip_quotes: ;
- }
-
- if (! yyres)
- return yystrlen (yystr);
-
- return yystpcpy (yyres, yystr) - yyres;
-}
-# endif
-
-#endif /* YYERROR_VERBOSE */
-
-
-
-#if YYDEBUG
-/*--------------------------------.
-| Print this symbol on YYOUTPUT. |
-`--------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yysymprint (FILE *yyoutput, int yytype, YYSTYPE *yyvaluep)
-#else
-static void
-yysymprint (yyoutput, yytype, yyvaluep)
- FILE *yyoutput;
- int yytype;
- YYSTYPE *yyvaluep;
-#endif
-{
- /* Pacify ``unused variable'' warnings. */
- (void) yyvaluep;
-
- if (yytype < YYNTOKENS)
- YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
- else
- YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
-
-
-# ifdef YYPRINT
- if (yytype < YYNTOKENS)
- YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# endif
- switch (yytype)
- {
- default:
- break;
- }
- YYFPRINTF (yyoutput, ")");
-}
-
-#endif /* ! YYDEBUG */
-/*-----------------------------------------------.
-| Release the memory associated to this symbol. |
-`-----------------------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
-#else
-static void
-yydestruct (yymsg, yytype, yyvaluep)
- const char *yymsg;
- int yytype;
- YYSTYPE *yyvaluep;
-#endif
-{
- /* Pacify ``unused variable'' warnings. */
- (void) yyvaluep;
-
- if (!yymsg)
- yymsg = "Deleting";
- YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
-
- switch (yytype)
- {
-
- default:
- break;
- }
-}
-
-
-/* Prevent warnings from -Wmissing-prototypes. */
-
-#ifdef YYPARSE_PARAM
-# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM);
-# else
-int yyparse ();
-# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
-
-
-
-/* The look-ahead symbol. */
-int yychar;
-
-/* The semantic value of the look-ahead symbol. */
-YYSTYPE yylval;
-
-/* Number of syntax errors so far. */
-int yynerrs;
-
-
-
-/*----------.
-| yyparse. |
-`----------*/
-
-#ifdef YYPARSE_PARAM
-# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM)
-# else
-int yyparse (YYPARSE_PARAM)
- void *YYPARSE_PARAM;
-# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
-int
-yyparse (void)
-#else
-int
-yyparse ()
- ;
-#endif
-#endif
-{
-
- int yystate;
- int yyn;
- int yyresult;
- /* Number of tokens to shift before error messages enabled. */
- int yyerrstatus;
- /* Look-ahead token as an internal (translated) token number. */
- int yytoken = 0;
-
- /* Three stacks and their tools:
- `yyss': related to states,
- `yyvs': related to semantic values,
- `yyls': related to locations.
-
- Refer to the stacks thru separate pointers, to allow yyoverflow
- to reallocate them elsewhere. */
-
- /* The state stack. */
- short int yyssa[YYINITDEPTH];
- short int *yyss = yyssa;
- short int *yyssp;
-
- /* The semantic value stack. */
- YYSTYPE yyvsa[YYINITDEPTH];
- YYSTYPE *yyvs = yyvsa;
- YYSTYPE *yyvsp;
-
-
-
-#define YYPOPSTACK (yyvsp--, yyssp--)
-
- YYSIZE_T yystacksize = YYINITDEPTH;
-
- /* The variables used to return semantic value and location from the
- action routines. */
- YYSTYPE yyval;
-
-
- /* When reducing, the number of symbols on the RHS of the reduced
- rule. */
- int yylen;
-
- YYDPRINTF ((stderr, "Starting parse\n"));
-
- yystate = 0;
- yyerrstatus = 0;
- yynerrs = 0;
- yychar = YYEMPTY; /* Cause a token to be read. */
-
- /* Initialize stack pointers.
- Waste one element of value and location stack
- so that they stay on the same level as the state stack.
- The wasted elements are never initialized. */
-
- yyssp = yyss;
- yyvsp = yyvs;
-
- goto yysetstate;
-
-/*------------------------------------------------------------.
-| yynewstate -- Push a new state, which is found in yystate. |
-`------------------------------------------------------------*/
- yynewstate:
- /* In all cases, when you get here, the value and location stacks
- have just been pushed. so pushing a state here evens the stacks.
- */
- yyssp++;
-
- yysetstate:
- *yyssp = yystate;
-
- if (yyss + yystacksize - 1 <= yyssp)
- {
- /* Get the current used size of the three stacks, in elements. */
- YYSIZE_T yysize = yyssp - yyss + 1;
-
-#ifdef yyoverflow
- {
- /* Give user a chance to reallocate the stack. Use copies of
- these so that the &'s don't force the real ones into
- memory. */
- YYSTYPE *yyvs1 = yyvs;
- short int *yyss1 = yyss;
-
-
- /* Each stack pointer address is followed by the size of the
- data in use in that stack, in bytes. This used to be a
- conditional around just the two extra args, but that might
- be undefined if yyoverflow is a macro. */
- yyoverflow (YY_("memory exhausted"),
- &yyss1, yysize * sizeof (*yyssp),
- &yyvs1, yysize * sizeof (*yyvsp),
-
- &yystacksize);
-
- yyss = yyss1;
- yyvs = yyvs1;
- }
-#else /* no yyoverflow */
-# ifndef YYSTACK_RELOCATE
- goto yyexhaustedlab;
-# else
- /* Extend the stack our own way. */
- if (YYMAXDEPTH <= yystacksize)
- goto yyexhaustedlab;
- yystacksize *= 2;
- if (YYMAXDEPTH < yystacksize)
- yystacksize = YYMAXDEPTH;
-
- {
- short int *yyss1 = yyss;
- union yyalloc *yyptr =
- (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
- if (! yyptr)
- goto yyexhaustedlab;
- YYSTACK_RELOCATE (yyss);
- YYSTACK_RELOCATE (yyvs);
-
-# undef YYSTACK_RELOCATE
- if (yyss1 != yyssa)
- YYSTACK_FREE (yyss1);
- }
-# endif
-#endif /* no yyoverflow */
-
- yyssp = yyss + yysize - 1;
- yyvsp = yyvs + yysize - 1;
-
-
- YYDPRINTF ((stderr, "Stack size increased to %lu\n",
- (unsigned long int) yystacksize));
-
- if (yyss + yystacksize - 1 <= yyssp)
- YYABORT;
- }
-
- YYDPRINTF ((stderr, "Entering state %d\n", yystate));
-
- goto yybackup;
-
-/*-----------.
-| yybackup. |
-`-----------*/
-yybackup:
-
-/* Do appropriate processing given the current state. */
-/* Read a look-ahead token if we need one and don't already have one. */
-/* yyresume: */
-
- /* First try to decide what to do without reference to look-ahead token. */
-
- yyn = yypact[yystate];
- if (yyn == YYPACT_NINF)
- goto yydefault;
-
- /* Not known => get a look-ahead token if don't already have one. */
-
- /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */
- if (yychar == YYEMPTY)
- {
- YYDPRINTF ((stderr, "Reading a token: "));
- yychar = YYLEX;
- }
-
- if (yychar <= YYEOF)
- {
- yychar = yytoken = YYEOF;
- YYDPRINTF ((stderr, "Now at end of input.\n"));
- }
- else
- {
- yytoken = YYTRANSLATE (yychar);
- YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
- }
-
- /* If the proper action on seeing token YYTOKEN is to reduce or to
- detect an error, take that action. */
- yyn += yytoken;
- if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
- goto yydefault;
- yyn = yytable[yyn];
- if (yyn <= 0)
- {
- if (yyn == 0 || yyn == YYTABLE_NINF)
- goto yyerrlab;
- yyn = -yyn;
- goto yyreduce;
- }
-
- if (yyn == YYFINAL)
- YYACCEPT;
-
- /* Shift the look-ahead token. */
- YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
-
- /* Discard the token being shifted unless it is eof. */
- if (yychar != YYEOF)
- yychar = YYEMPTY;
-
- *++yyvsp = yylval;
-
-
- /* Count tokens shifted since error; after three, turn off error
- status. */
- if (yyerrstatus)
- yyerrstatus--;
-
- yystate = yyn;
- goto yynewstate;
-
-
-/*-----------------------------------------------------------.
-| yydefault -- do the default action for the current state. |
-`-----------------------------------------------------------*/
-yydefault:
- yyn = yydefact[yystate];
- if (yyn == 0)
- goto yyerrlab;
- goto yyreduce;
-
-
-/*-----------------------------.
-| yyreduce -- Do a reduction. |
-`-----------------------------*/
-yyreduce:
- /* yyn is the number of a rule to reduce with. */
- yylen = yyr2[yyn];
-
- /* If YYLEN is nonzero, implement the default value of the action:
- `$$ = $1'.
-
- Otherwise, the following line sets YYVAL to garbage.
- This behavior is undocumented and Bison
- users should not rely upon it. Assigning to YYVAL
- unconditionally makes the parser a bit smaller, and it avoids a
- GCC warning that YYVAL may be used uninitialized. */
- yyval = yyvsp[1-yylen];
-
-
- YY_REDUCE_PRINT (yyn);
- switch (yyn)
- {
- case 2:
-#line 142 "autotools.yy"
- {
- ProjectAST *projectAST = new ProjectAST();
- projects.push(projectAST);
-;}
- break;
-
- case 4:
-#line 150 "autotools.yy"
- {
- projects.top()->addChildAST((yyvsp[0].node));
-
- if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "if" )
- {
- (yyvsp[0].node)->setDepth(depth);
- depth++;
- }
- else if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "else" )
- {
- --depth;
- (yyvsp[0].node)->setDepth(depth);
- ++depth;
- }
- else if ( (yyvsp[0].node)->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( (yyvsp[0].node) )->scopedID == "endif" )
- {
- --depth;
- (yyvsp[0].node)->setDepth(depth);
- }
- else
- (yyvsp[0].node)->setDepth(depth);
-;}
- break;
-
- case 6:
-#line 179 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 7:
-#line 183 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 8:
-#line 187 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 9:
-#line 191 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 10:
-#line 195 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 11:
-#line 199 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 12:
-#line 203 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 13:
-#line 207 "autotools.yy"
- {
- (yyval.node) = (yyvsp[0].node);
-;}
- break;
-
- case 14:
-#line 211 "autotools.yy"
- {
- (yyval.node) = new NewLineAST();
-;}
- break;
-
- case 15:
-#line 217 "autotools.yy"
- {
- ConditionAST* projectAST = new ConditionAST();
- projectAST->type = "if";
- projectAST->conditionName = (yyvsp[0].value);
- (yyval.node) = projectAST;
-;}
- break;
-
- case 16:
-#line 225 "autotools.yy"
- {
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- (yyval.node) = past;
-;}
- break;
-
- case 17:
-#line 231 "autotools.yy"
- {
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- past->conditionName = (yyvsp[0].value);
- (yyval.node) = past;
-;}
- break;
-
- case 18:
-#line 240 "autotools.yy"
- {
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- (yyval.node) = past;
-;}
- break;
-
- case 19:
-#line 246 "autotools.yy"
- {
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- past->conditionName = (yyvsp[0].value);
- (yyval.node) = past;
-;}
- break;
-
- case 20:
-#line 255 "autotools.yy"
- {
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = (yyvsp[-2].value);
- node->op = (yyvsp[-1].value);
- node->values = (yyvsp[0].values);
- (yyval.node) = node;
-;}
- break;
-
- case 21:
-#line 265 "autotools.yy"
- { (yyval.value) = (yyvsp[-1].value) + (yyvsp[0].value); ;}
- break;
-
- case 23:
-#line 270 "autotools.yy"
- {
- QStringList list = (yyvsp[0].value).split(QRegExp("\\s+"), QString::SkipEmptyParts);
- (yyval.values) = (yyval.values) + list; //.append($<value>2);
-;}
- break;
-
- case 24:
-#line 274 "autotools.yy"
- { (yyval.values).clear(); ;}
- break;
-
- case 25:
-#line 277 "autotools.yy"
- { (yyval.value) = (yyvsp[-1].value) + " \\\n"; ;}
- break;
-
- case 26:
-#line 278 "autotools.yy"
- { (yyval.value) = (yyvsp[-1].value) + "\n"; ;}
- break;
-
- case 27:
-#line 279 "autotools.yy"
- { (yyval.value) = "\\\n"; ;}
- break;
-
- case 29:
-#line 284 "autotools.yy"
- {
- AutomakeTargetAST *node = new AutomakeTargetAST();
- node->target = (yyvsp[-2].value);
- node->deps = (yyvsp[0].values);
- (yyval.node) = node;
-;}
- break;
-
- case 30:
-#line 293 "autotools.yy"
- {
- ProjectAST* node = new ProjectAST(ProjectAST::Rule);
- node->scopedID = (yyvsp[0].value);
- (yyval.node) = node;
-;}
- break;
-
- case 31:
-#line 301 "autotools.yy"
- {
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = (yyvsp[-1].value);
- node->values = QStringList((yyvsp[0].value));
- (yyval.node) = node;
-;}
- break;
-
- case 34:
-#line 313 "autotools.yy"
- {
- CommentAST *node = new CommentAST();
- node->comment = (yyvsp[-1].value) + "\n";
- (yyval.node) = node;
-;}
- break;
-
-
- default: break;
- }
-
-/* Line 1126 of yacc.c. */
-#line 1517 "autotools_yacc.cpp"
-
- yyvsp -= yylen;
- yyssp -= yylen;
-
-
- YY_STACK_PRINT (yyss, yyssp);
-
- *++yyvsp = yyval;
-
-
- /* Now `shift' the result of the reduction. Determine what state
- that goes to, based on the state we popped back to and the rule
- number reduced by. */
-
- yyn = yyr1[yyn];
-
- yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
- if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
- yystate = yytable[yystate];
- else
- yystate = yydefgoto[yyn - YYNTOKENS];
-
- goto yynewstate;
-
-
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
-yyerrlab:
- /* If not already recovering from an error, report this error. */
- if (!yyerrstatus)
- {
- ++yynerrs;
-#if YYERROR_VERBOSE
- yyn = yypact[yystate];
-
- if (YYPACT_NINF < yyn && yyn < YYLAST)
- {
- int yytype = YYTRANSLATE (yychar);
- YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
- YYSIZE_T yysize = yysize0;
- YYSIZE_T yysize1;
- int yysize_overflow = 0;
- char *yymsg = 0;
-# define YYERROR_VERBOSE_ARGS_MAXIMUM 5
- char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
- int yyx;
-
-#if 0
- /* This is so xgettext sees the translatable formats that are
- constructed on the fly. */
- YY_("syntax error, unexpected %s");
- YY_("syntax error, unexpected %s, expecting %s");
- YY_("syntax error, unexpected %s, expecting %s or %s");
- YY_("syntax error, unexpected %s, expecting %s or %s or %s");
- YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
-#endif
- char *yyfmt;
- char const *yyf;
- static char const yyunexpected[] = "syntax error, unexpected %s";
- static char const yyexpecting[] = ", expecting %s";
- static char const yyor[] = " or %s";
- char yyformat[sizeof yyunexpected
- + sizeof yyexpecting - 1
- + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
- * (sizeof yyor - 1))];
- char const *yyprefix = yyexpecting;
-
- /* Start YYX at -YYN if negative to avoid negative indexes in
- YYCHECK. */
- int yyxbegin = yyn < 0 ? -yyn : 0;
-
- /* Stay within bounds of both yycheck and yytname. */
- int yychecklim = YYLAST - yyn;
- int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
- int yycount = 1;
-
- yyarg[0] = yytname[yytype];
- yyfmt = yystpcpy (yyformat, yyunexpected);
-
- for (yyx = yyxbegin; yyx < yyxend; ++yyx)
- if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
- {
- if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
- {
- yycount = 1;
- yysize = yysize0;
- yyformat[sizeof yyunexpected - 1] = '\0';
- break;
- }
- yyarg[yycount++] = yytname[yyx];
- yysize1 = yysize + yytnamerr (0, yytname[yyx]);
- yysize_overflow |= yysize1 < yysize;
- yysize = yysize1;
- yyfmt = yystpcpy (yyfmt, yyprefix);
- yyprefix = yyor;
- }
-
- yyf = YY_(yyformat);
- yysize1 = yysize + yystrlen (yyf);
- yysize_overflow |= yysize1 < yysize;
- yysize = yysize1;
-
- if (!yysize_overflow && yysize <= YYSTACK_ALLOC_MAXIMUM)
- yymsg = (char *) YYSTACK_ALLOC (yysize);
- if (yymsg)
- {
- /* Avoid sprintf, as that infringes on the user's name space.
- Don't have undefined behavior even if the translation
- produced a string with the wrong number of "%s"s. */
- char *yyp = yymsg;
- int yyi = 0;
- while ((*yyp = *yyf))
- {
- if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
- {
- yyp += yytnamerr (yyp, yyarg[yyi++]);
- yyf += 2;
- }
- else
- {
- yyp++;
- yyf++;
- }
- }
- yyerror (yymsg);
- YYSTACK_FREE (yymsg);
- }
- else
- {
- yyerror (YY_("syntax error"));
- goto yyexhaustedlab;
- }
- }
- else
-#endif /* YYERROR_VERBOSE */
- yyerror (YY_("syntax error"));
- }
-
-
-
- if (yyerrstatus == 3)
- {
- /* If just tried and failed to reuse look-ahead token after an
- error, discard it. */
-
- if (yychar <= YYEOF)
- {
- /* Return failure if at end of input. */
- if (yychar == YYEOF)
- YYABORT;
- }
- else
- {
- yydestruct ("Error: discarding", yytoken, &yylval);
- yychar = YYEMPTY;
- }
- }
-
- /* Else will try to reuse look-ahead token after shifting the error
- token. */
- goto yyerrlab1;
-
-
-/*---------------------------------------------------.
-| yyerrorlab -- error raised explicitly by YYERROR. |
-`---------------------------------------------------*/
-yyerrorlab:
-
- /* Pacify compilers like GCC when the user code never invokes
- YYERROR and the label yyerrorlab therefore never appears in user
- code. */
- if (0)
- goto yyerrorlab;
-
-yyvsp -= yylen;
- yyssp -= yylen;
- yystate = *yyssp;
- goto yyerrlab1;
-
-
-/*-------------------------------------------------------------.
-| yyerrlab1 -- common code for both syntax error and YYERROR. |
-`-------------------------------------------------------------*/
-yyerrlab1:
- yyerrstatus = 3; /* Each real token shifted decrements this. */
-
- for (;;)
- {
- yyn = yypact[yystate];
- if (yyn != YYPACT_NINF)
- {
- yyn += YYTERROR;
- if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
- {
- yyn = yytable[yyn];
- if (0 < yyn)
- break;
- }
- }
-
- /* Pop the current state because it cannot handle the error token. */
- if (yyssp == yyss)
- YYABORT;
-
-
- yydestruct ("Error: popping", yystos[yystate], yyvsp);
- YYPOPSTACK;
- yystate = *yyssp;
- YY_STACK_PRINT (yyss, yyssp);
- }
-
- if (yyn == YYFINAL)
- YYACCEPT;
-
- *++yyvsp = yylval;
-
-
- /* Shift the error token. */
- YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
-
- yystate = yyn;
- goto yynewstate;
-
-
-/*-------------------------------------.
-| yyacceptlab -- YYACCEPT comes here. |
-`-------------------------------------*/
-yyacceptlab:
- yyresult = 0;
- goto yyreturn;
-
-/*-----------------------------------.
-| yyabortlab -- YYABORT comes here. |
-`-----------------------------------*/
-yyabortlab:
- yyresult = 1;
- goto yyreturn;
-
-#ifndef yyoverflow
-/*-------------------------------------------------.
-| yyexhaustedlab -- memory exhaustion comes here. |
-`-------------------------------------------------*/
-yyexhaustedlab:
- yyerror (YY_("memory exhausted"));
- yyresult = 2;
- /* Fall through. */
-#endif
-
-yyreturn:
- if (yychar != YYEOF && yychar != YYEMPTY)
- yydestruct ("Cleanup: discarding lookahead",
- yytoken, &yylval);
- while (yyssp != yyss)
- {
- yydestruct ("Cleanup: popping",
- yystos[*yyssp], yyvsp);
- YYPOPSTACK;
- }
-#ifndef yyoverflow
- if (yyss != yyssa)
- YYSTACK_FREE (yyss);
-#endif
- return yyresult;
-}
-
-
-#line 322 "autotools.yy"
-
-
-#include "automake_lex.cpp"
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeparser.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc -o -name \*.ui | grep -v '/tests/'` >> rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h | grep -v '/tests/'` -o $podir/kdevautomake.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/CMakeLists.txt (nonexistent)
@@ -1,57 +0,0 @@
-project(AutomakeManager)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${AutomakeManager_SOURCE_DIR}/cmake)
-
-find_package(KDE4 REQUIRED)
-find_package(KDevPlatform REQUIRED)
-find_package(KDevelop REQUIRED)
-
-#add_definitions( -DKDE_DEFAULT_DEBUG_AREA=9020 )
-add_subdirectory(tests)
-add_subdirectory(automakebuilder)
-
-include_directories(
- ${AutomakeBuilder_SOURCE_DIR}
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDEVELOP_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-########### next target ###############
-
-set(kdevautomakeimporter_SRCS
- automakeast.cpp
- automakedriver.cpp
- automakeparser.cpp
- makefileinterface.cpp
- automakeprojectmodel.cpp
- automakeimporter.cpp
-)
-
-
-set( automakesettings_SRCS
- settings/automakepreferences.cpp
-)
-
-set( automakesettings_UI
- settings/automakebuildsettings.ui
-)
-
-
-kde4_add_plugin(kdevautomakeimporter ${kdevautomakeimporter_SRCS})
-target_link_libraries(kdevautomakeimporter ${KDE4_KDECORE_LIBS} ${KDEVPLATFORM_LANGUAGE_LIBRARIES} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES} )
-
-kde4_add_kcfg_files( automakesettings_SRCS automakeconfig.kcfgc )
-kde4_add_ui_files( automakesettings_SRCS ${automakesettings_UI} )
-kde4_add_plugin( kcm_kdevautomake_settings ${automakesettings_SRCS} )
-target_link_libraries( kcm_kdevautomake_settings ${KDE4_KDEUI_LIBS} ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES})
-
-
-install(TARGETS kdevautomakeimporter DESTINATION ${PLUGIN_INSTALL_DIR} )
-install(TARGETS kcm_kdevautomake_settings DESTINATION ${PLUGIN_INSTALL_DIR} )
-install(FILES kcm_kdevautomake_settings.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install(FILES kdevautomakeimporter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/CMakeLists.txt
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.ll
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.ll (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.ll (nonexistent)
@@ -1,137 +0,0 @@
-%{
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "autotools_yacc.h"
-
-/**
-@file autotools.ll
-Autotools Lexer
-
-There are 3 types of identifiers recognized by this lexer:
--id_simple: examples of such identifiers are qmake variables and scoped variables
-at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
--id_list: those are "value list identifiers" at the right side in assignments
-(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
--id_args: function arguments recognized as one identifier
-(example: ""${QMAKE_FILE} is intended only for Windows!""
-in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
-.
-
-To recognize those identifiers two additional start conditions are used: list and funcargs.
-
-@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
-the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
-so no indentation is preserved by this lexer (and parser).
-
-To debug this lexer, put the line below into the next flex file section.
-%option debug
-*/
-%}
-%option noyywrap
-%x list
-%x funcargs
-%x conditional
-
-delim [ \t]
-ws {delim}+
-letter [A-Za-z]
-digit [0-9]
-id_simple ({digit}|{letter}|\!|-|_|\*|\$|@)({letter}|{digit}|\||\!|-|_|\*|\$|\(|\.|\+|\-|\)|\/)*
-id_list [^\n#]*\\{ws}*
-id_args [^\n]*\)
-number {digit}+
-comment #.*
-comment_cont {ws}#.*\n
-id_list_single [^\n]*
-cont \\{ws}*\n
-keywords (if|else|endif|include)
-rule [\t]+[^\n]*
-
-%%
-
-<list,INITIAL>{ws} {}
-<list,INITIAL>{cont} { BEGIN(list); return CONT; }
-{keywords} {
- yylval.value = yytext;
- if ( yylval.value == "if" )
- return IF_KEYWORD;
-
- if ( yylval.value == "else" )
- return ELSE_KEYWORD;
-
- if ( yylval.value == "endif" )
- return ENDIF_KEYWORD;
-
- return KEYWORD;
-}
-
-
-{id_simple} { yylval.value = yytext; return (ID_SIMPLE); }
-
-<INITIAL>{rule} {
- yylval.value = yytext;
- return RULE;
-}
-
-<list>{id_list} {
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
- unput('\\');
- BEGIN(INITIAL);
- return (ID_LIST);
- }
-
-<list>{comment_cont} {
- yylval.value = yytext;
- BEGIN(list);
- return (LIST_COMMENT);
- }
-
-<list>{comment} {
- yylval.value = yytext;
- return LIST_COMMENT;
- }
-
-<list>{id_list_single} {
- yylval.value = yytext;
- BEGIN(INITIAL);
- return (ID_LIST_SINGLE);
- }
-
-<funcargs>{id_args} {
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.length()-1);
- unput(')');
- BEGIN(INITIAL);
- return (ID_ARGS);
- }
-
-"=" { BEGIN(list); yylval.value = yytext; return EQ; }
-"+=" { BEGIN(list); yylval.value = yytext; return PLUSEQ; }
-"{" { return LCURLY; }
-"}" { return RCURLY; }
-":" { BEGIN(list); yylval.value = yytext; return COLON; }
-<list,INITIAL>"\n" { BEGIN(INITIAL); return NEWLINE; }
-{comment} { yylval.value = yytext; return (COMMENT); }
-
-%%
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.ll
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfg
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfg (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfg (nonexistent)
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE kcfg SYSTEM "http://www.kde.org/standards/kcfg/1.0/kcfg.dtd">
-<kcfg>
- <kcfgfile arg="true"/>
- <group name="Automake">
- <entry name="currentBuildDir" key="CurrentBuildDir" type="Url" />
- </group>
-</kcfg>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.cpp (nonexistent)
@@ -1,239 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2005 Matt Rogers <mattr@kde.org>
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "automakeimporter.h"
-
-#include <kdebug.h>
-
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-
-#include <interfaces/iplugincontroller.h>
-#include <interfaces/icore.h>
-#include <interfaces/iproject.h>
-
-#include "automakeprojectmodel.h"
-#include "makefileinterface.h"
-#include "iautomakebuilder.h"
-
-K_PLUGIN_FACTORY(AutotoolsSupportFactory, registerPlugin<AutoMakeImporter>(); )
-K_EXPORT_PLUGIN(AutotoolsSupportFactory("kdevautomakeimporter"))
-
-AutoMakeImporter::AutoMakeImporter( QObject* parent,
- const QVariantList& )
-: KDevelop::IPlugin( AutotoolsSupportFactory::componentData(), parent ), m_rootItem(0L)
-{
-KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBuildSystemManager )
-KDEV_USE_EXTENSION_INTERFACE( KDevelop::IProjectFileManager )
- m_interface = new MakefileInterface( this );
-
- IPlugin* i = core()->pluginController()->pluginForExtension( "org.kdevelop.IAutomakeBuilder" );
- Q_ASSERT(i);
- m_builder = i->extension<IAutomakeBuilder>();
- Q_ASSERT(m_builder);
-}
-
-AutoMakeImporter::~AutoMakeImporter()
-{
- //delete m_rootItem;
-}
-
-KUrl AutoMakeImporter::buildDirectory(KDevelop::ProjectBaseItem* item) const
-{
- kDebug() << "Looking up buildDirectory for item "<< item->text();
-
- KUrl out;
-
- // First we'll need to find the folder in the source directory tree
- if( item->folder() ) {
- kDebug() << item->text()<< "is a folder-item";
- out = item->folder()->url();
- } else if( item->parent() ) {
- kDebug() << item->text()<< "must be either a target-item or member of a target-item";
- KDevelop::ProjectBaseItem* base = static_cast<KDevelop::ProjectBaseItem*>(item->parent());
- if( base->type() == KDevelop::ProjectBaseItem::Target )
- {
- out = static_cast<KDevelop::ProjectFolderItem*>(base->parent())->url();
- } else {
- out = static_cast<KDevelop::ProjectFolderItem*>(base)->url();
- }
- }
-
- KConfigGroup automakeGrp = item->project()->projectConfiguration()->group("Automake");
- KUrl buildDir = automakeGrp.readEntry( "CurrentBuildDir", KUrl() );
-
- if (buildDir.isValid()) {
- // If a separat buildDir is defined we need to locate the directory that
- // matches the upper found directory from the source directory tree
- kDebug() << "We need to build in a separat build directory";
-
- KUrl projectPath = m_projectRoot[item->project()];
- QString relUrl = KUrl::relativeUrl( projectPath, out );
-
- kDebug() << "Separat buildDir: "<< buildDir;
- kDebug() << "Relative URL: "<< relUrl;
-
- buildDir.addPath(relUrl);
- out = buildDir;
- }
-
- out.cleanPath();
- kDebug() << "BuildDirectory for "<<item->text()<< "is:"<<out;
-
- return out;
-}
-
-KDevelop::IProjectBuilder* AutoMakeImporter::builder(KDevelop::ProjectFolderItem*) const
-{
- Q_ASSERT(m_builder);
- return m_builder;
-}
-
-QList<KDevelop::ProjectFolderItem*> AutoMakeImporter::parse( KDevelop::ProjectFolderItem* item )
-{
- kDebug() << "Got parse request for"<<item->text()<<"-"<<item->url();
-
- // create all subdirs and repot them back to the caller
- QList<KDevelop::ProjectFolderItem*> folder;
- const QStringList subdirs = m_interface->subdirsFor( item->url() );
- foreach( const QString& dir, subdirs ) {
- QString fullPath = item->url().toLocalFile() + QDir::separator() + dir;
- folder.append( new AutoMakeDirItem(item->project(), fullPath, item) );
- }
-
- // fill up this folder with all targets and files
- createFolderItems( item );
-
- return folder;
-}
-
-KDevelop::ProjectFolderItem* AutoMakeImporter::import( KDevelop::IProject* project)
-{
- kDebug() << "Got import request for" << project->folder();
-
- KUrl folderUrl = project->folder();
- if (!folderUrl.isLocalFile()) {
- kDebug() << project->folder() << "is not a local path";
- return 0;
- }
-
- m_interface->setProjectRoot( folderUrl );
- bool parsedCorrectly = m_interface->parse( folderUrl );
- if (!parsedCorrectly) {
- kDebug() << "something went wrong during the parse of "<<folderUrl;
- return 0;
- }
-
- m_projectRoot[project] = folderUrl;
-
- m_rootItem = new AutoMakeDirItem( project, folderUrl.url(), 0 );
-// m_rootItem->setProjectRoot(true);
- return m_rootItem;
-}
-
-KUrl AutoMakeImporter::findMakefile( KDevelop::ProjectFolderItem* dom ) const
-{
- Q_UNUSED( dom );
- return KUrl();
-}
-
-KUrl::List AutoMakeImporter::findMakefiles( KDevelop::ProjectFolderItem* dom ) const
-{
- Q_UNUSED( dom );
- return KUrl::List();
-}
-
-void AutoMakeImporter::createFolderItems( KDevelop::ProjectFolderItem* item )
-{
- kDebug() << "createProjectItems for"<<item->text()<<"-"<<item->url();
-
- // check if we got an automake dir
- AutoMakeDirItem* folderItem = dynamic_cast<AutoMakeDirItem*>(item);
- if (!folderItem) {
- kDebug() << item->text()<<"is not an AutoMakeDirItem";
- return;
- }
-
- //now run through all targets for this folder and create the needed items
- QList<TargetInfo> targets = m_interface->targetsForFolder( folderItem->url() );
- KDevelop::ProjectBaseItem* dataTarget = 0;
- KDevelop::ProjectBaseItem* notInstalledHeaders = 0;
- KDevelop::ProjectBaseItem* installedHeaders = 0;
-
- foreach( TargetInfo target, targets )
- {
- switch( target.type )
- {
- case AutoMake::Data:
- {
- if ( dataTarget == 0 )
- dataTarget = new AutoMakeBaseItem( item->project(), "Data", folderItem );
- QFileInfo rcInfo( target.url.path(), target.name );
- new AutoMakeFileItem( item->project(), KUrl(rcInfo.absoluteFilePath()), dataTarget );
- }
- break;
- case AutoMake::Headers:
- if ( target.location != AutoMake::None )
- {
- if ( installedHeaders == 0 )
- installedHeaders = new AutoMakeBaseItem( item->project(), "Installed headers", folderItem );
- QFileInfo headerInfo( target.url.path(), target.name );
- new AutoMakeFileItem( item->project(), KUrl(headerInfo.absoluteFilePath()), installedHeaders );
- }
- else
- {
- if ( notInstalledHeaders == 0 )
- notInstalledHeaders = new AutoMakeBaseItem( item->project(), "Not Installed headers", folderItem );
- QFileInfo headerInfo( target.url.path(), target.name );
- new AutoMakeFileItem( item->project(), KUrl(headerInfo.absoluteFilePath()), notInstalledHeaders );
- }
- break;
- case AutoMake::Program:
- case AutoMake::Library:
- case AutoMake::LibtoolLibrary:
- default:
- AutoMakeTargetItem* targetItem = new AutoMakeTargetItem( item->project(), target, folderItem );
- QList<QFileInfo> targetFiles = m_interface->filesForTarget( target );
- foreach( const QFileInfo& fi, targetFiles ) {
- new AutoMakeFileItem( item->project(), KUrl(fi.absoluteFilePath()), targetItem );
- }
- break;
- };
- }
-
- // add Makefile.am and other common files that are not mentioned inside Makefile.am
- // but should nevertheless be added to the projectmodel
- QFileInfo makefile(folderItem->url().toLocalFile(), "Makefile.am");
- if (makefile.exists()) {
- kDebug() << "Adding "<<makefile.absoluteFilePath();
- new KDevelop::ProjectFileItem( item->project(), makefile.absoluteFilePath(), folderItem );
- }
-}
-
-QList<KDevelop::ProjectTargetItem*> AutoMakeImporter::targets() const
-{
- return QList<KDevelop::ProjectTargetItem*>();
-}
-
-QList< KDevelop::ProjectTargetItem * > AutoMakeImporter::targets(KDevelop::ProjectFolderItem * folder) const
-{
- return folder->targetList();
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakebuildsettings.ui (nonexistent)
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>AutomakeBuildSettings</class>
- <widget class="QWidget" name="AutomakeBuildSettings">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>605</width>
- <height>36</height>
- </rect>
- </property>
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Build Directory</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="KUrlRequester" name="kcfg_currentBuildDir"/>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>KUrlRequester</class>
- <extends>QFrame</extends>
- <header>kurlrequester.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.cpp (nonexistent)
@@ -1,49 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "automakepreferences.h"
-
-#include <KPluginFactory>
-#include <KUrl>
-
-#include "automakeconfig.h"
-#include "ui_automakebuildsettings.h"
-
-K_PLUGIN_FACTORY(AutomakePreferencesFactory, registerPlugin<AutomakePreferences>(); )
-K_EXPORT_PLUGIN(AutomakePreferencesFactory("kcm_kdevautomake_settings"))
-
-AutomakePreferences::AutomakePreferences(QWidget* parent, const QVariantList& args)
- : ProjectKCModule<AutomakeSettings>(AutomakePreferencesFactory::componentData(), parent, args)
-{
- QVBoxLayout* l = new QVBoxLayout( this );
- QWidget* w = new QWidget;
- m_prefsUi = new Ui::AutomakeBuildSettings;
- m_prefsUi->setupUi( w );
- m_prefsUi->kcfg_currentBuildDir->setMode(KFile::Directory|KFile::ExistingOnly);
- l->addWidget( w );
-
- addConfig( AutomakeSettings::self(), w );
- load();
-}
-
-AutomakePreferences::~AutomakePreferences()
-{}
-
-#include "automakepreferences.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/settings/automakepreferences.h (nonexistent)
@@ -1,44 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef AUTOMAKEPREFERENCES_H
-#define AUTOMAKEPREFERENCES_H
-
-#include <project/projectkcmodule.h>
-
-class AutomakeSettings;
-
-namespace Ui { class AutomakeBuildSettings; }
-
-/**
- * @author Robert Gruber <rgruber@users.sourceforge.net>
- */
-class AutomakePreferences : public ProjectKCModule<AutomakeSettings>
-{
- Q_OBJECT
- public:
- explicit AutomakePreferences(QWidget* parent = 0, const QVariantList& args = QVariantList());
- ~AutomakePreferences();
-
- private:
- Ui::AutomakeBuildSettings* m_prefsUi;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.cpp (nonexistent)
@@ -1,483 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright (C) 2005 Matt Rogers <mattr@kde.org>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "makefileinterface.h"
-
-#include <QtAlgorithms>
-#include <QFileInfo>
-#include <QList>
-#include <QHash>
-
-#include <kdebug.h>
-
-#include "automakeast.h"
-#include "automakedriver.h"
-
-
-uint qHash( const QFileInfo& key )
-{
- return qHash( key.absolutePath() );
-}
-
-namespace AutoMake
-{
- TargetType convertToType( const QString& type )
- {
- if ( type == "PROGRAMS" )
- return Program;
- else if ( type == "LIBRARIES" )
- return Library;
- else if ( type == "LTLIBRARIES" )
- return LibtoolLibrary;
- else if ( type == "LISP" )
- return Lisp;
- else if ( type == "PYTHON" )
- return Python;
- else if ( type == "JAVA" )
- return Java;
- else if ( type == "SCRIPTS" )
- return Scripts;
- else if ( type == "DATA" )
- return Data;
- else if ( type == "HEADERS" )
- return Headers;
- else if ( type == "MANS" )
- return ManPages;
- else if ( type == "TEXINFOS" )
- return Texinfo;
- else
- return Unknown;
- }
-
- InstallLocation convertToLocation( const QString& location )
- {
- if ( location == "bin" )
- return Bin;
- else if ( location == "lib" )
- return Lib;
- else if ( location == "libexec" )
- return Libexec;
- else if ( location == "noinst" )
- return None;
- else if ( location == "check" )
- return Check;
- else if ( location == "info" )
- return Info;
- else if ( location.contains( "^man" ) )
- return Man;
- else if ( location == "kde_module" )
- return Lib;
- else if ( location == "EXTRA" )
- return None;
- else
- return Custom;
- }
-}
-
-
-using namespace AutoMake;
-
-class MakefileInterface::Private
-{
-public:
- AutoMakeASTHash projects;
- QStringList filesToParse;
- KUrl topLevelParseDir;
-};
-
-MakefileInterface::MakefileInterface( QObject* parent )
-: QObject( parent )
-{
- d = new MakefileInterface::Private;
- d->filesToParse.append("Makefile.am.in");
- d->filesToParse.append("Makefile.am");
- d->filesToParse.append("Makefile.in");
-}
-
-MakefileInterface::~MakefileInterface()
-{
- qDeleteAll( d->projects );
- delete d;
-}
-
-QString MakefileInterface::canonicalize( const QString& target )
-{
- QString result;
- for ( int i = 0; i < target.length(); ++i )
- {
- QChar addition = target.at( i );
- if ( !addition.isLetterOrNumber() && addition != '@' && addition != '_' )
- addition = QChar( '_' );
-
- result += addition;
- }
-
- kDebug(9020) << "'" << target << "' has been normalized to '"
- << result << "'" << endl;
-
- return result;
-}
-
-bool MakefileInterface::parse( const KUrl& dir, ParserRecursion recursive )
-{
- kDebug(9020) << "directory to parse is:" << dir.path();
- int ret = -1;
- AutoMake::ProjectAST* ast = 0L;
-
- QFileInfo parsingFile;
- QStringList::const_iterator it, itEnd = d->filesToParse.constEnd();
- for ( it = d->filesToParse.constBegin(); it != itEnd; ++it )
- {
- parsingFile.setFile( dir.path(), (*it) );
- if ( parsingFile.exists() )
- {
- using namespace AutoMake;
- ret = Driver::parseFile( parsingFile.absoluteFilePath(), &ast );
- if ( ret != -1 )
- break;
- }
- }
-
- if ( !ast || ret == -1 )
- {
- kWarning(9020) << "parsing" << dir.path()
- << "not successful! Fix your Makefile!" << endl;
- return false;
- }
-
- d->projects[parsingFile] = ast;
-
- if ( recursive == NonRecursive || ( ast && !ast->hasChildren() ) )
- return ( ret != -1 );
-
-
- QStringList subdirs = subdirsFor( dir );
- foreach( const QString& sd, subdirs )
- {
- kDebug(9020) << "Beginning parsing of '" << sd << "'";
- parse( dir.path() + '/' + sd, recursive );
- }
-
- return (ret != -1);
-}
-
-void MakefileInterface::setProjectRoot( const KUrl& dir )
-{
- d->topLevelParseDir = dir;
-}
-
-QString MakefileInterface::projectRoot() const
-{
- return d->topLevelParseDir.path();
-}
-
-QStringList MakefileInterface::topSubDirs() const
-{
- return subdirsFor( d->topLevelParseDir );
-}
-
-AutoMake::ProjectAST* MakefileInterface::astForFolder( const KUrl& folder ) const
-{
- ProjectAST* ast = 0;
- QFileInfo parsingFile;
- QStringList::const_iterator it, itEnd = d->filesToParse.constEnd();
- for ( it = d->filesToParse.constBegin(); it != itEnd; ++it )
- {
- parsingFile.setFile( folder.path(), (*it) );
- if ( parsingFile.exists() )
- ast = d->projects[parsingFile];
-
- if ( ast != 0 )
- break;
-
- }
-
- return ast;
-}
-
-bool MakefileInterface::isVariable( const QString& item )
-{
- if ( item.contains( QRegExp( "(\\$\\([a-zA-Z0-9_-]*\\)|@[a-zA-Z0-9_-]*@)" ) ) )
- return true;
- else
- return false;
-}
-
-QString MakefileInterface::resolveVariable( const QString& variable, AutoMake::ProjectAST* ast ) const
-{
- if ( !ast )
- return variable;
-
- kDebug(9020) << "attempting to resolve '" << variable << "'";
- QList<AST*> childList = ast->children();
- QList<AST*>::iterator it( childList.begin() ), clEnd( childList.end() );
-
- for ( ; it != clEnd; ++it )
- {
- if ( ( *it )->nodeType() == AST::AssignmentAST )
- {
- AssignmentAST* assignment = static_cast<AssignmentAST*>( ( *it ) );
- if ( variable.indexOf( assignment->scopedID ) != -1 )
- {
- QString resolution = assignment->values.join( " " ).trimmed();
- kDebug(9020) << "Resolving variable '" << variable << "' to '"
- << resolution << "'" << endl;
- return resolution;
- }
- }
- }
-
- return variable;
-}
-
-QStringList MakefileInterface::subdirsFor( const KUrl& folder ) const
-{
- AutoMake::ProjectAST* ast = astForFolder( folder );
- if ( !ast )
- {
- kWarning(9020) << "Couldn't find AST for "
- << folder.path() << endl;
- return QStringList();
- }
-
- QStringList subdirs = subdirsFor( ast );
- // check for and deal with KDE hacks (TOPSUBDIRS and AUTODIRS)
- foreach (QString subdir, subdirs) {
- if (subdir.contains("$(TOPSUBDIRS)")) {
- kDebug() << "Found special subdir variable"<<subdir;
- QFile subdirsFile(folder.toLocalFile()+QDir::separator()+"subdirs");
- if ( subdirsFile.exists() ) {
- if ( subdirsFile.open(QIODevice::ReadOnly) ) {
- QTextStream in(&subdirsFile);
- while (!in.atEnd()) {
- subdirs.append( in.readLine() );
- }
- subdirs.removeAll( subdir );
- }
- } else {
- // fallback -> act like AUTODIRS in case subdirs file is not present
- subdir = "$(AUTODIRS)";
- }
- }
- if (subdir.contains("$(AUTODIRS)")) {
- kDebug() << "Found special subdir variable"<<subdir;
- QDir dirHelper(folder.toLocalFile());
- QStringList autodirs = dirHelper.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
- subdirs.removeAll(subdir); // remove the TOPSUBDIRS entry...
- subdirs.append(autodirs); // ... and insert all found subdirs instead
- }
- }
-
- return subdirs;
-}
-
-QList<TargetInfo> MakefileInterface::targetsForFolder( const KUrl& folder ) const
-{
- kDebug(9020) << folder.path();
-
- QList<TargetInfo> targetList;
- AutoMake::ProjectAST* ast = astForFolder( folder );
-
- if ( !ast )
- {
- kWarning(9020) << "Unable to get AST for "
- << folder.path() << endl;
- return targetList;
- }
-
- QList<AST*> childList = ast->children();
- QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
- for ( cit = childList.constBegin(); cit != citEnd; ++cit )
- {
- if ( (*cit)->nodeType() == AST::AssignmentAST )
- {
- AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
- if ( assignment->scopedID.contains( AutoMake::targetPrimaries ) )
- {
- foreach( const QString& target, assignment->values )
- {
- if ( target == "#" || target == "\\" )
- continue;
-
- QStringList targetSplit = assignment->scopedID.split( '_' );
- QString primary = targetSplit.takeLast();
- QString location = targetSplit.join( "_" );
-
- kDebug( 9020 ) << "primary:" << primary
- << "location:" << location << endl;
-
- TargetInfo info;
- info.type = AutoMake::convertToType( primary );
- info.location = AutoMake::convertToLocation( location );
- info.name = target;
- info.url = folder;
- kDebug( 9020 ) << "target name:" << target;
- targetList.append( info );
- }
- }
- }
- }
-
- return targetList;
-}
-
-QStringList MakefileInterface::subdirsFor( AutoMake::ProjectAST* ast ) const
-{
- QList<AST*> childList = ast->children();
- QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
- for ( cit = childList.constBegin(); cit != citEnd; ++cit )
- {
- if ( (*cit)->nodeType() == AST::AssignmentAST )
- {
- AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
- if ( assignment->scopedID == "SUBDIRS" )
- {
- QStringList subdirList = assignment->values;
- subdirList.removeAll(".");
- subdirList.removeAll("..");
- subdirList.removeAll("\\");
- subdirList.removeAll("#");
-
- QStringList::const_iterator vit = subdirList.constBegin();
- for ( ; vit != subdirList.constEnd(); ++vit )
- {
- QString dirFromList = ( *vit );
- QString realDir = dirFromList;
- if ( realDir.startsWith( "\\" ) )
- realDir.remove( 0, 1 );
-
- realDir = realDir.trimmed();
- if ( !realDir.isEmpty() )
- {
- if ( isVariable( realDir ) )
- {
- kDebug(9020) << "'" << realDir << "' is a variable";
- realDir = resolveVariable( realDir, ast );
- }
-
- subdirList.replace( subdirList.indexOf( dirFromList ),
- realDir );
- }
- }
- kDebug(9020) << "subdirs is '"
- << assignment->values << "'" << endl;
- return subdirList;
- }
- }
- }
-
- return QStringList();
-}
-
-QList<QFileInfo> MakefileInterface::filesForTarget( const TargetInfo& target ) const
-{
- QList<QFileInfo> fileInfoList;
- QString targetId;
- AutoMake::ProjectAST* ast = astForFolder( target.url );
- if ( !ast )
- return QList<QFileInfo>();
-
- if ( isVariable( target.name ) )
- targetId = resolveVariable( target.name, ast );
- else
- targetId = canonicalize( target.name );
-
-
- switch ( target.type )
- {
- case Program:
- case Library:
- case LibtoolLibrary:
- targetId += QLatin1String( "_SOURCES" );
- break;
- case Lisp:
- targetId += QLatin1String( "_LISP" );
- break;
- case Texinfo:
- targetId += QLatin1String( "_TEXINFOS" );
- break;
- case Scripts:
- targetId += QLatin1String( "_SCRIPTS" );
- break;
- case Java:
- targetId += QLatin1String( "_JAVA" );
- break;
- case Python:
- targetId += QLatin1String( "_PYTHON" );
- break;
- case Data:
- targetId += QLatin1String( "_DATA" );
- break;
- case Headers:
- targetId += QLatin1String( "_HEADERS" );
- break;
- case ManPages:
- targetId += QLatin1String( "_MANS" );
- break;
- default:
- break;
- };
-
-
- QStringList valuesList = valuesForId( targetId, ast );
- foreach( const QString& value, valuesList )
- {
- if ( value == QLatin1String( "\\" ) )
- continue;
-
- QFileInfo fi( target.url.path(), value );
- fileInfoList.append( fi );
- }
-
- return fileInfoList;
-}
-
-QStringList MakefileInterface::valuesForId( const QString& id, AutoMake::ProjectAST* ast ) const
-{
- kDebug(9020) << "looking for '" << id << "'";
-
- QStringList valuesList;
- QList<AST*> childList = ast->children();
- QList<AST*>::const_iterator cit, citEnd = childList.constEnd();
- for ( cit = childList.constBegin(); cit != citEnd; ++cit )
- {
- if ( (*cit)->nodeType() == AST::AssignmentAST )
- {
- AssignmentAST* assignment = static_cast<AssignmentAST*>( (*cit) );
- if ( assignment->scopedID == id )
- {
- kDebug(9020) << "found" << id;
- QStringList valuesList = assignment->values;
- valuesList.removeAll( QLatin1String( "\\" ) );
-
- kDebug(9020) << "providing list '"
- << assignment->values << "' for id" << id << endl;
- return valuesList;
- }
- }
- }
-
- return valuesList;
-
-}
-#include "makefileinterface.moc"
-
-
-//kate: hl c++;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp (nonexistent)
@@ -1,66 +0,0 @@
-/*
- * KDevelop Automake Support
- * Copyright 2005 Matt Rogers <mattr@kde.org>
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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.
- */
-
-#include "automakeprojectmodel.h"
-
-AutoMakeDirItem::AutoMakeDirItem( KDevelop::IProject* p, const KUrl& url, KDevelop::ProjectBaseItem* parent )
- : KDevelop::ProjectBuildFolderItem( p, url, parent )
-{
-}
-
-AutoMakeDirItem::~AutoMakeDirItem()
-{
-}
-
-
-AutoMakeFileItem::AutoMakeFileItem( KDevelop::IProject* p, const KUrl& url, KDevelop::ProjectBaseItem* parent )
- : KDevelop::ProjectFileItem( p, url, parent )
-{
-}
-
-AutoMakeFileItem::~AutoMakeFileItem()
-{
-}
-
-AutoMakeTargetItem::AutoMakeTargetItem( KDevelop::IProject* p, const TargetInfo& target, KDevelop::ProjectBaseItem* parent )
- : KDevelop::ProjectTargetItem( p, target.url.pathOrUrl(), parent )
-{
- m_target = target;
- setText( target.name );
-}
-
-AutoMakeTargetItem::~AutoMakeTargetItem()
-{
-}
-
-AutoMakeBaseItem::AutoMakeBaseItem( KDevelop::IProject* p, const QString& target, KDevelop::ProjectBaseItem* parent )
- : KDevelop::ProjectBaseItem( p, target, parent )
-{
-}
-
-AutoMakeBaseItem::~AutoMakeBaseItem()
-{
-}
-
-int AutoMakeBaseItem::type() const
-{
- return ProjectBaseItem::Target;
-}
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeconfig.kcfgc (nonexistent)
@@ -1,5 +0,0 @@
-File=automakeconfig.kcfg
-ClassName=AutomakeSettings
-Singleton=true
-Inherits=KDevelop::ProjectConfigSkeleton
-IncludeFiles=project/projectconfigskeleton.h
\ No newline at end of file
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/Messages.sh (nonexistent)
@@ -1,4 +0,0 @@
-#!/bin/sh
-$EXTRACTRC `find . -name \*.rc` `find . -name \*.ui` >>rc.cpp
-$XGETTEXT `find . -name \*.cc -o -name \*.cpp -o -name \*.h` -o $podir/kdevautomakebuilder.pot
-rm -f rc.cpp
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/CMakeLists.txt (nonexistent)
@@ -1,26 +0,0 @@
-project(AutomakeBuilder)
-
-include_directories(
- ${KDEVPLATFORM_INCLUDE_DIR}
- ${KDEVELOP_INCLUDE_DIR}
- ${KDE4_INCLUDES}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_SOURCE_DIR}
-)
-
-########### next target ###############
-
-set(automakebuilder_LIB_SRCS
- automakebuilder.cpp
- configurejob.cpp
-)
-
-
-kde4_add_plugin( kdevautomakebuilder ${automakebuilder_LIB_SRCS} )
-target_link_libraries( kdevautomakebuilder ${KDEVPLATFORM_INTERFACES_LIBRARIES} ${KDEVPLATFORM_PROJECT_LIBRARIES} ${KDEVPLATFORM_OUTPUTVIEW_LIBRARIES} ${KDEVPLATFORM_UTIL_LIBRARIES} )
-
-install( TARGETS kdevautomakebuilder DESTINATION ${PLUGIN_INSTALL_DIR} )
-
-########### install files ###############
-install( FILES kdevautomakebuilder.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES iautomakebuilder.h DESTINATION ${INCLUDE_INSTALL_DIR}/kdevelop/automake COMPONENT Devel)
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.cpp (nonexistent)
@@ -1,136 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "automakebuilder.h"
-#include <make/imakebuilder.h>
-
-#include <project/projectmodel.h>
-
-#include <interfaces/iproject.h>
-#include <interfaces/icore.h>
-#include <interfaces/iplugincontroller.h>
-
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-#include <kaboutdata.h>
-#include <kdebug.h>
-
-#include "configurejob.h"
-
-K_PLUGIN_FACTORY(AutomakeBuilderFactory, registerPlugin<AutomakeBuilder>(); )
-K_EXPORT_PLUGIN(AutomakeBuilderFactory(KAboutData("kdevautomakebuilder","kdevautomakebuilder", ki18n("Automake Builder"), "0.1", ki18n("Support for building Automake projects"), KAboutData::License_GPL)))
-
-AutomakeBuilder::AutomakeBuilder(QObject *parent, const QVariantList &)
- : KDevelop::IPlugin(AutomakeBuilderFactory::componentData(), parent)
-{
- KDEV_USE_EXTENSION_INTERFACE( KDevelop::IProjectBuilder )
- KDEV_USE_EXTENSION_INTERFACE( IAutomakeBuilder )
-
- m_makeBuilder = core()->pluginController()->pluginForExtension("org.kdevelop.IMakeBuilder");
- if( m_makeBuilder )
- {
- IMakeBuilder* mbuilder = m_makeBuilder->extension<IMakeBuilder>();
- if( mbuilder )
- {
- connect( m_makeBuilder, SIGNAL( built( KDevelop::ProjectBaseItem* ) ),
- this, SIGNAL( built( KDevelop::ProjectBaseItem* ) ) );
- connect( m_makeBuilder, SIGNAL( cleaned( KDevelop::ProjectBaseItem* ) ),
- this, SIGNAL( cleaned( KDevelop::ProjectBaseItem* ) ) );
- connect( m_makeBuilder, SIGNAL( installed( KDevelop::ProjectBaseItem* ) ),
- this, SIGNAL( installed( KDevelop::ProjectBaseItem* ) ) );
- connect( m_makeBuilder, SIGNAL( failed( KDevelop::ProjectBaseItem* ) ),
- this, SIGNAL( failed( KDevelop::ProjectBaseItem* ) ) );
- connect( m_makeBuilder, SIGNAL( makeTargetBuilt( KDevelop::ProjectBaseItem*, const QString& ) ),
- this, SIGNAL( pruned( KDevelop::ProjectBaseItem* ) ) );
- }
- }
-}
-
-AutomakeBuilder::~AutomakeBuilder()
-{
-}
-
-KJob* AutomakeBuilder::prune( KDevelop::IProject* project )
-{
- kDebug() << "Distcleaning";
- if( m_makeBuilder )
- {
- IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
- if( builder )
- {
- kDebug() << "Distcleaning with make";
- return builder->executeMakeTarget(project->projectItem(), "distclean");
- }
- }
- return 0;
-}
-
-KJob* AutomakeBuilder::build(KDevelop::ProjectBaseItem *dom)
-{
- kDebug() << "Building";
- if( m_makeBuilder )
- {
- IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
- if( builder )
- {
- kDebug() << "Building with make";
- return builder->build(dom);
- }
- }
- return 0;
-}
-
-KJob* AutomakeBuilder::configure( KDevelop::IProject* project )
-{
- ConfigureJob* job = new ConfigureJob(project, this);
- return job;
-}
-
-KJob* AutomakeBuilder::clean(KDevelop::ProjectBaseItem *dom)
-{
- kDebug() << "Cleaning";
- if( m_makeBuilder )
- {
- IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
- if( builder )
- {
- kDebug() << "Cleaning with make";
- return builder->clean(dom);
- }
- }
- return 0;
-}
-
-KJob* AutomakeBuilder::install(KDevelop::ProjectBaseItem *dom)
-{
- kDebug() << "Installing";
- if( m_makeBuilder )
- {
- IMakeBuilder* builder = m_makeBuilder->extension<IMakeBuilder>();
- if( builder )
- {
- kDebug() << "Installing with make";
- return builder->install(dom);
- }
- }
- return 0;
-}
-
-#include "automakebuilder.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/iautomakebuilder.h (nonexistent)
@@ -1,45 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef IAUTOMAKEBUILDER_H
-#define IAUTOMAKEBUILDER_H
-
-#include <project/interfaces/iprojectbuilder.h>
-#include <interfaces/iplugin.h>
-
-
-class IProject;
-class ProjectItem;
-
-/**
-@author Robert Gruber
-*/
-
-class IAutomakeBuilder : public KDevelop::IProjectBuilder
-{
-public:
- virtual ~IAutomakeBuilder() {}
-
-};
-
-//KDEV_DECLARE_EXTENSION_INTERFACE( IAutomakeBuilder, "org.kdevelop.IAutomakeBuilder" )
-Q_DECLARE_INTERFACE( IAutomakeBuilder, "org.kdevelop.IAutomakeBuilder" )
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/automakebuilder.h (nonexistent)
@@ -1,70 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef AUTOMAKEBUILDER_H
-#define AUTOMAKEBUILDER_H
-
-#include <interfaces/iplugin.h>
-#include "iautomakebuilder.h"
-#include <QtCore/QList>
-#include <QtCore/QPair>
-#include <QtCore/QVariant>
-
-class QStringList;
-class QSignalMapper;
-class KDialog;
-namespace KDevelop{
- class ProjectBaseItem;
- class CommandExecutor;
- class OutputModel;
-}
-
-/**
-@author Robert Gruber
-*/
-class AutomakeBuilder : public KDevelop::IPlugin, public IAutomakeBuilder
-{
- Q_OBJECT
- Q_INTERFACES( IAutomakeBuilder )
- Q_INTERFACES( KDevelop::IProjectBuilder )
-
-public:
- explicit AutomakeBuilder(QObject *parent = 0, const QVariantList &args = QVariantList());
- virtual ~AutomakeBuilder();
-
- virtual KJob* build(KDevelop::ProjectBaseItem *dom);
- virtual KJob* clean(KDevelop::ProjectBaseItem *dom);
- virtual KJob* install(KDevelop::ProjectBaseItem *dom);
- virtual KJob* configure(KDevelop::IProject *dom);
- virtual KJob* prune(KDevelop::IProject *dom);
-
-Q_SIGNALS:
- void built(KDevelop::ProjectBaseItem*);
- void failed(KDevelop::ProjectBaseItem*);
- void installed(KDevelop::ProjectBaseItem*);
- void cleaned(KDevelop::ProjectBaseItem*);
- void configured(KDevelop::ProjectBaseItem*);
- void pruned(KDevelop::ProjectBaseItem*);
-
-private:
- KDevelop::IPlugin* m_makeBuilder;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/kdevautomakebuilder.desktop (nonexistent)
@@ -1,55 +0,0 @@
-[Desktop Entry]
-Type=Service
-Name=Automake Project Builder
-Name[bs]=Automatsko stvaranje projekta
-Name[ca]=Constructor de projecte Automake
-Name[ca@valencia]=Constructor de projecte Automake
-Name[de]=Automake-Projekterstellung
-Name[en_GB]=Automake Project Builder
-Name[es]=Constructor de proyectos Automake
-Name[et]=Automake'i projekti ehitaja
-Name[fr]=Constructeur de projets Automake
-Name[gl]=Construtor de proxectos Automake
-Name[it]=Creatore di progetti per Automake
-Name[ms]=Pembina Projek Automake
-Name[nds]=Automake-Projektbuumoduul
-Name[nl]=Automake projecten Builder
-Name[pl]=Budowanie projektu Automake
-Name[pt]=Construtor de Projectos do Automake
-Name[pt_BR]=Construtor de projetos do Automake
-Name[sv]=Bygg Automake-projekt
-Name[tr]=Automake Proje Oluşturucu
-Name[uk]=Інструмент збирання проектів Automake
-Name[x-test]=xxAutomake Project Builderxx
-Comment=Builds Automake Projects
-Comment[bs]=Izgraditelj Automake projekata
-Comment[ca]=Construeix projectes d'Automake
-Comment[ca@valencia]=Construeix projectes d'Automake
-Comment[de]=Erstellt Automake-Projekte
-Comment[en_GB]=Builds Automake Projects
-Comment[es]=Construye proyectos de Automake
-Comment[et]=Automake'i projektide ehitamine
-Comment[fr]=Construit des projets Automake
-Comment[gl]=Constrúe proxectos de Automake
-Comment[it]=Crea progetti Automake
-Comment[ms]=Bina Projek Automake
-Comment[nds]=Buut Automake-Projekten
-Comment[nl]=Creëert Automake projecten
-Comment[pl]=Buduje projekty Automake
-Comment[pt]=Compila projectos do Automake
-Comment[pt_BR]=Compila projetos do Automake
-Comment[sv]=Bygger Automake-projekt
-Comment[tr]=Automake Projelerini İnşa Eder
-Comment[uk]=Збирає проекти Automake
-Comment[x-test]=xxBuilds Automake Projectsxx
-Icon=gear
-ServiceTypes=KDevelop/Plugin
-X-KDE-Library=kdevautomakebuilder
-X-KDE-PluginInfo-Name=KDevAutomakeBuilder
-X-KDE-PluginInfo-Category=Project Management
-X-KDevelop-ProjectBuilder=Automake
-X-KDevelop-Version=12
-X-KDevelop-Category=Project
-X-KDevelop-Interfaces=org.kdevelop.IAutomakeBuilder
-X-KDevelop-IRequired=org.kdevelop.IMakeBuilder
-X-KDevelop-Mode=NoGUI
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.cpp (nonexistent)
@@ -1,95 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#include "configurejob.h"
-
-#include <QDir>
-
-#include <make/imakebuilder.h>
-
-#include <project/projectmodel.h>
-#include <interfaces/iproject.h>
-#include <interfaces/icore.h>
-#include <interfaces/iplugincontroller.h>
-#include <outputview/ioutputview.h>
-#include <outputview/outputmodel.h>
-#include <util/commandexecutor.h>
-
-#include <kpluginfactory.h>
-#include <kpluginloader.h>
-#include <kdebug.h>
-
-ConfigureJob::ConfigureJob(KDevelop::IProject* project, QObject *parent)
- : OutputJob(parent),
- m_project(project), m_killed(false)
-{
- setCapabilities(Killable);
-}
-
-void ConfigureJob::start()
-{
- if( !m_project ) {
- setError(NoProjectError);
- setErrorText(i18n("No project specified."));
- return emitResult();
- }
-
- setStandardToolView(KDevelop::IOutputView::BuildView);
- setBehaviours(KDevelop::IOutputView::AllowUserClose | KDevelop::IOutputView::AutoScroll);
- setModel(new KDevelop::OutputModel(this), KDevelop::IOutputView::TakeOwnership);
- startOutput();
-
- KConfigGroup automakeGrp = m_project->projectConfiguration()->group("Automake");
- KUrl buildDir = automakeGrp.readEntry( "CurrentBuildDir", KUrl() );
-
- QString configure = buildConfigureCall();
-
- /// @todo add additional configure args here (e.g. --prefix=<dir>)
-
- KDevelop::CommandExecutor* cmd = new KDevelop::CommandExecutor(configure, this);
- connect(cmd, SIGNAL(receivedStandardError(const QStringList&)),
- model(), SLOT(appendLines(const QStringList&) ) );
- connect(cmd, SIGNAL(receivedStandardOutput(const QStringList&)),
- model(), SLOT(appendLines(const QStringList&) ) );
- cmd->setWorkingDirectory( (buildDir.isValid())?buildDir.toLocalFile():m_project->folder().toLocalFile() );
- connect( cmd, SIGNAL( failed() ), this, SLOT( slotFailed() ) );
- connect( cmd, SIGNAL( completed() ), this, SLOT( slotCompleted() ) );
- cmd->start();
-}
-
-QString ConfigureJob::buildConfigureCall()
-{
- // always call the configure script from the project's directory
- return m_project->folder().toLocalFile() + QDir::separator() + "configure";
-}
-
-void ConfigureJob::slotFailed()
-{
- setError(ConfigureError);
- setErrorText(i18n("Configure failed"));
- emitResult();
-}
-
-void ConfigureJob::slotCompleted()
-{
- emitResult();
-}
-
-#include "configurejob.moc"
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakebuilder/configurejob.h (nonexistent)
@@ -1,59 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef CONFIGUREJOB_H
-#define CONFIGUREJOB_H
-
-#include <outputview/outputjob.h>
-
-namespace KDevelop{
- class IProject;
-}
-
-/**
-@author Robert Gruber
-*/
-class ConfigureJob : public KDevelop::OutputJob
-{
- Q_OBJECT
-
-public:
- ConfigureJob(KDevelop::IProject* project, QObject *parent = 0);
-
- enum ErrorTypes {
- NoProjectError = UserDefinedError,
- ConfigureError
- };
-
- virtual void start();
-
-private Q_SLOTS:
- void slotFailed();
- void slotCompleted();
-
-private:
- QString buildConfigureCall();
-
- KDevelop::IProject* m_project;
-
- bool m_killed;
-};
-
-#endif
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.h (nonexistent)
@@ -1,59 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef AUTOMAKEDRIVER_H
-#define AUTOMAKEDRIVER_H
-
-#include <qlist.h>
-#include <kurl.h>
-
-namespace AutoMake {
-
-/**
-@file autotoolsdriver.h
-Driver for a automake parser.
-*/
-
-class ProjectAST;
-
-/**
- * Driver.
- * Use methods of this class to lauch parsing and build the AST.
- */
-class Driver
-{
-public:
- /**
- * Parses the file @p fileName and stores the resulting ProjectAST root
- * into @p ast. @p ast should not be initialized before. Driver will
- * initialize it on its own.
- * @return The result of parsing. Result is 0 on success and <> 0 on failure.
- */
- static int parseFile(const char *fileName, ProjectAST **ast);
- static int parseFile(const QString& fileName, ProjectAST **ast);
- static int parseFile(const KUrl & fileName, ProjectAST **ast);
-
-};
-
-}
-
-#endif
-
-// kate: indent-mode csands; tab-width 4; space-indent off; auto-insert-doxygen on;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.cpp (nonexistent)
@@ -1,68 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include "automakedriver.h"
-#include "automakeast.h"
-
-#include <stdio.h>
-#include <qstack.h>
-#include <kio/netaccess.h>
-
-extern FILE *yyin, *yyout;
-extern int yyparse();
-extern int yydebug;
-extern QStack<AutoMake::ProjectAST *> projects;
-
-namespace AutoMake {
-
-int Driver::parseFile(const char *fileName, ProjectAST **ast)
-{
-// yydebug = 1;
- yyin = fopen(fileName, "r");
- if (yyin == 0)
- {
- ast = 0;
- return 1;
- }
- int ret = yyparse();
- *ast = projects.top();
- fclose(yyin);
- return ret;
-}
-
-int Driver::parseFile(const QString& fileName, ProjectAST **ast)
-{
- return parseFile(fileName.toAscii().constData(), ast);
-}
-
-int Driver::parseFile(const KUrl& fileName, ProjectAST **ast)
-{
- QString tmpFile;
- int ret = 0;
- if (KIO::NetAccess::download(fileName, tmpFile, 0))
- ret = parseFile(tmpFile, ast);
- KIO::NetAccess::removeTempFile(tmpFile);
- return ret;
-}
-
-}
-
-//kate: indent-mode csands; space-indent off; tab-width 4;
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakedriver.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake_lex.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake_lex.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake_lex.cpp (nonexistent)
@@ -1,1896 +0,0 @@
-#line 2 "autotools_lex.cpp"
-
-#line 4 "autotools_lex.cpp"
-
-#define YY_INT_ALIGNED short int
-
-/* A lexical scanner generated by flex */
-
-#define FLEX_SCANNER
-#define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 31
-#if YY_FLEX_SUBMINOR_VERSION > 0
-#define FLEX_BETA
-#endif
-
-/* First, we deal with platform-specific or compiler-specific issues. */
-
-/* begin standard C headers. */
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-/* end standard C headers. */
-
-/* flex integer type definitions */
-
-#ifndef FLEXINT_H
-#define FLEXINT_H
-
-/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
-
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
-#include <inttypes.h>
-typedef int8_t flex_int8_t;
-typedef uint8_t flex_uint8_t;
-typedef int16_t flex_int16_t;
-typedef uint16_t flex_uint16_t;
-typedef int32_t flex_int32_t;
-typedef uint32_t flex_uint32_t;
-#else
-typedef signed char flex_int8_t;
-typedef short int flex_int16_t;
-typedef int flex_int32_t;
-typedef unsigned char flex_uint8_t;
-typedef unsigned short int flex_uint16_t;
-typedef unsigned int flex_uint32_t;
-#endif /* ! C99 */
-
-/* Limits of integral types. */
-#ifndef INT8_MIN
-#define INT8_MIN (-128)
-#endif
-#ifndef INT16_MIN
-#define INT16_MIN (-32767-1)
-#endif
-#ifndef INT32_MIN
-#define INT32_MIN (-2147483647-1)
-#endif
-#ifndef INT8_MAX
-#define INT8_MAX (127)
-#endif
-#ifndef INT16_MAX
-#define INT16_MAX (32767)
-#endif
-#ifndef INT32_MAX
-#define INT32_MAX (2147483647)
-#endif
-#ifndef UINT8_MAX
-#define UINT8_MAX (255U)
-#endif
-#ifndef UINT16_MAX
-#define UINT16_MAX (65535U)
-#endif
-#ifndef UINT32_MAX
-#define UINT32_MAX (4294967295U)
-#endif
-
-#endif /* ! FLEXINT_H */
-
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else /* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_CONST
-
-#endif /* __STDC__ */
-#endif /* ! __cplusplus */
-
-#ifdef YY_USE_CONST
-#define yyconst const
-#else
-#define yyconst
-#endif
-
-/* Returned upon end-of-file. */
-#define YY_NULL 0
-
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
- */
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
-
-/* Enter a start condition. This macro really ought to take a parameter,
- * but we do it the disgusting crufty way forced on us by the ()-less
- * definition of BEGIN.
- */
-#define BEGIN (yy_start) = 1 + 2 *
-
-/* Translate the current start state into a value that can be later handed
- * to BEGIN to return to the state. The YYSTATE alias is for lex
- * compatibility.
- */
-#define YY_START (((yy_start) - 1) / 2)
-#define YYSTATE YY_START
-
-/* Action number for EOF rule of a given start state. */
-#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
-/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE yyrestart(yyin )
-
-#define YY_END_OF_BUFFER_CHAR 0
-
-/* Size of default input buffer. */
-#ifndef YY_BUF_SIZE
-#define YY_BUF_SIZE 16384
-#endif
-
-#ifndef YY_TYPEDEF_YY_BUFFER_STATE
-#define YY_TYPEDEF_YY_BUFFER_STATE
-typedef struct yy_buffer_state *YY_BUFFER_STATE;
-#endif
-
-extern int yyleng;
-
-extern FILE *yyin, *yyout;
-
-#define EOB_ACT_CONTINUE_SCAN 0
-#define EOB_ACT_END_OF_FILE 1
-#define EOB_ACT_LAST_MATCH 2
-
- #define YY_LESS_LINENO(n)
-
-/* Return all but the first "n" matched characters back to the input stream. */
-#define yyless(n) \
- do \
- { \
- /* Undo effects of setting up yytext. */ \
- int yyless_macro_arg = (n); \
- YY_LESS_LINENO(yyless_macro_arg);\
- *yy_cp = (yy_hold_char); \
- YY_RESTORE_YY_MORE_OFFSET \
- (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
- YY_DO_BEFORE_ACTION; /* set up yytext again */ \
- } \
- while ( 0 )
-
-#define unput(c) yyunput( c, (yytext_ptr) )
-
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
-
-#ifndef YY_STRUCT_YY_BUFFER_STATE
-#define YY_STRUCT_YY_BUFFER_STATE
-struct yy_buffer_state
- {
- FILE *yy_input_file;
-
- char *yy_ch_buf; /* input buffer */
- char *yy_buf_pos; /* current position in input buffer */
-
- /* Size of input buffer in bytes, not including room for EOB
- * characters.
- */
- yy_size_t yy_buf_size;
-
- /* Number of characters read into yy_ch_buf, not including EOB
- * characters.
- */
- int yy_n_chars;
-
- /* Whether we "own" the buffer - i.e., we know we created it,
- * and can realloc() it to grow it, and should free() it to
- * delete it.
- */
- int yy_is_our_buffer;
-
- /* Whether this is an "interactive" input source; if so, and
- * if we're using stdio for input, then we want to use getc()
- * instead of fread(), to make sure we stop fetching input after
- * each newline.
- */
- int yy_is_interactive;
-
- /* Whether we're considered to be at the beginning of a line.
- * If so, '^' rules will be active on the next match, otherwise
- * not.
- */
- int yy_at_bol;
-
- int yy_bs_lineno; /**< The line count. */
- int yy_bs_column; /**< The column count. */
-
- /* Whether to try to fill the input buffer when we reach the
- * end of it.
- */
- int yy_fill_buffer;
-
- int yy_buffer_status;
-
-#define YY_BUFFER_NEW 0
-#define YY_BUFFER_NORMAL 1
- /* When an EOF's been seen but there's still some text to process
- * then we mark the buffer as YY_EOF_PENDING, to indicate that we
- * shouldn't try reading from the input source any more. We might
- * still have a bunch of tokens to match, though, because of
- * possible backing-up.
- *
- * When we actually see the EOF, we change the status to "new"
- * (via yyrestart()), so that the user can continue scanning by
- * just pointing yyin at a new input file.
- */
-#define YY_BUFFER_EOF_PENDING 2
-
- };
-#endif /* !YY_STRUCT_YY_BUFFER_STATE */
-
-/* Stack of input buffers. */
-static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
-static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
-static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
-
-/* We provide macros for accessing buffer states in case in the
- * future we want to put the buffer states in a more general
- * "scanner state".
- *
- * Returns the top of the stack, or NULL.
- */
-#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
- ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
- : NULL)
-
-/* Same as previous macro, but useful when we know that the buffer stack is not
- * NULL or when we need an lvalue. For internal use only.
- */
-#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
-
-/* yy_hold_char holds the character lost when yytext is formed. */
-static char yy_hold_char;
-static int yy_n_chars; /* number of characters read into yy_ch_buf */
-int yyleng;
-
-/* Points to current character in buffer. */
-static char *yy_c_buf_p = (char *) 0;
-static int yy_init = 1; /* whether we need to initialize */
-static int yy_start = 0; /* start state number */
-
-/* Flag which is used to allow yywrap()'s to do buffer switches
- * instead of setting up a fresh yyin. A bit of a hack ...
- */
-static int yy_did_buffer_switch_on_eof;
-
-void yyrestart (FILE *input_file );
-void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
-YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
-void yy_delete_buffer (YY_BUFFER_STATE b );
-void yy_flush_buffer (YY_BUFFER_STATE b );
-void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
-void yypop_buffer_state (void );
-
-static void yyensure_buffer_stack (void );
-static void yy_load_buffer_state (void );
-static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file );
-
-#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
-
-YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
-YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
-YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len );
-
-void *yyalloc (yy_size_t );
-void *yyrealloc (void *,yy_size_t );
-void yyfree (void * );
-
-#define yy_new_buffer yy_create_buffer
-
-#define yy_set_interactive(is_interactive) \
- { \
- if ( ! YY_CURRENT_BUFFER ){ \
- yyensure_buffer_stack (); \
- YY_CURRENT_BUFFER_LVALUE = \
- yy_create_buffer(yyin,YY_BUF_SIZE ); \
- } \
- YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
- }
-
-#define yy_set_bol(at_bol) \
- { \
- if ( ! YY_CURRENT_BUFFER ){\
- yyensure_buffer_stack (); \
- YY_CURRENT_BUFFER_LVALUE = \
- yy_create_buffer(yyin,YY_BUF_SIZE ); \
- } \
- YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
- }
-
-#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
-
-/* Begin user sect3 */
-
-#define yywrap(n) 1
-#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
-
-FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
-
-typedef int yy_state_type;
-
-extern int yylineno;
-
-int yylineno = 1;
-
-extern char *yytext;
-#define yytext_ptr yytext
-
-static yy_state_type yy_get_previous_state (void );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
-static int yy_get_next_buffer (void );
-static void yy_fatal_error (yyconst char msg[] );
-
-/* Done after the current pattern has been matched and before the
- * corresponding action - sets up yytext.
- */
-#define YY_DO_BEFORE_ACTION \
- (yytext_ptr) = yy_bp; \
- yyleng = (size_t) (yy_cp - yy_bp); \
- (yy_hold_char) = *yy_cp; \
- *yy_cp = '\0'; \
- (yy_c_buf_p) = yy_cp;
-
-#define YY_NUM_RULES 18
-#define YY_END_OF_BUFFER 19
-/* This struct is not used in this scanner,
- but its presence is necessary. */
-struct yy_trans_info
- {
- flex_int32_t yy_verify;
- flex_int32_t yy_nxt;
- };
-static yyconst flex_int16_t yy_accept[64] =
- { 0,
- 0, 0, 9, 9, 0, 0, 0, 0, 19, 18,
- 1, 16, 1, 4, 17, 18, 15, 11, 18, 4,
- 4, 13, 14, 9, 1, 8, 6, 18, 10, 5,
- 1, 1, 1, 4, 4, 17, 12, 0, 2, 4,
- 4, 3, 4, 9, 9, 6, 1, 9, 8, 6,
- 0, 10, 4, 4, 4, 6, 9, 7, 4, 4,
- 4, 4, 0
- } ;
-
-static yyconst flex_int32_t yy_ec[256] =
- { 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 4, 5, 1, 6, 7, 1, 1, 1, 8,
- 9, 10, 11, 1, 12, 13, 14, 15, 15, 15,
- 15, 15, 15, 15, 15, 15, 15, 16, 1, 1,
- 17, 1, 1, 18, 19, 19, 19, 19, 19, 19,
- 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
- 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
- 1, 20, 1, 1, 21, 1, 19, 19, 22, 23,
-
- 24, 25, 19, 19, 26, 19, 19, 27, 19, 28,
- 19, 19, 19, 19, 29, 19, 30, 19, 19, 19,
- 19, 19, 31, 32, 33, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1
- } ;
-
-static yyconst flex_int32_t yy_meta[34] =
- { 0,
- 1, 1, 2, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1
- } ;
-
-static yyconst flex_int16_t yy_base[74] =
- { 0,
- 0, 0, 32, 51, 34, 36, 0, 0, 142, 155,
- 38, 155, 42, 67, 0, 124, 155, 155, 45, 23,
- 31, 155, 155, 63, 64, 0, 98, 131, 130, 0,
- 56, 59, 60, 0, 0, 0, 155, 103, 155, 109,
- 114, 0, 114, 67, 0, 106, 107, 132, 0, 126,
- 125, 122, 101, 98, 96, 113, 119, 155, 96, 90,
- 93, 90, 155, 146, 148, 150, 102, 97, 84, 66,
- 64, 40, 152
- } ;
-
-static yyconst flex_int16_t yy_def[74] =
- { 0,
- 63, 1, 64, 64, 65, 65, 66, 66, 63, 63,
- 67, 63, 63, 63, 68, 63, 63, 63, 63, 14,
- 14, 63, 63, 69, 69, 70, 69, 71, 71, 67,
- 67, 67, 63, 14, 14, 68, 63, 63, 63, 14,
- 14, 14, 14, 69, 72, 69, 69, 73, 70, 69,
- 71, 71, 14, 14, 14, 69, 73, 63, 14, 14,
- 14, 14, 0, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63
- } ;
-
-static yyconst flex_int16_t yy_nxt[189] =
- { 0,
- 10, 11, 12, 13, 14, 15, 14, 10, 10, 14,
- 16, 14, 10, 10, 14, 17, 18, 14, 14, 19,
- 14, 14, 14, 20, 14, 21, 14, 14, 14, 14,
- 22, 10, 23, 25, 12, 25, 10, 26, 10, 31,
- 45, 32, 29, 33, 29, 33, 38, 39, 38, 40,
- 41, 27, 25, 12, 25, 42, 26, 31, 43, 32,
- 32, 33, 32, 33, 51, 47, 49, 47, 45, 48,
- 27, 34, 45, 34, 34, 34, 34, 34, 35, 34,
- 34, 34, 46, 46, 44, 34, 46, 34, 34, 34,
- 34, 34, 34, 34, 34, 34, 34, 36, 34, 50,
-
- 39, 50, 30, 45, 38, 39, 38, 56, 47, 56,
- 47, 45, 48, 42, 56, 62, 56, 46, 45, 61,
- 42, 58, 60, 59, 42, 46, 46, 50, 39, 50,
- 52, 45, 46, 52, 58, 55, 54, 53, 52, 52,
- 37, 63, 63, 63, 63, 46, 24, 24, 28, 28,
- 10, 10, 57, 57, 9, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63
- } ;
-
-static yyconst flex_int16_t yy_chk[189] =
- { 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 3, 3, 3, 5, 3, 6, 11,
- 72, 11, 5, 13, 6, 13, 19, 19, 19, 20,
- 20, 3, 4, 4, 4, 21, 4, 31, 21, 31,
- 32, 33, 32, 33, 71, 25, 70, 25, 24, 25,
- 4, 14, 44, 14, 14, 14, 14, 14, 14, 14,
- 14, 14, 24, 25, 69, 14, 44, 14, 14, 14,
- 14, 14, 14, 14, 14, 14, 14, 68, 14, 27,
-
- 27, 27, 67, 27, 38, 38, 38, 46, 47, 46,
- 47, 46, 47, 62, 56, 61, 56, 27, 56, 60,
- 59, 57, 55, 54, 53, 46, 47, 50, 50, 50,
- 52, 50, 56, 51, 48, 43, 41, 40, 29, 28,
- 16, 9, 0, 0, 0, 50, 64, 64, 65, 65,
- 66, 66, 73, 73, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
- 63, 63, 63, 63, 63, 63, 63, 63
- } ;
-
-static yy_state_type yy_last_accepting_state;
-static char *yy_last_accepting_cpos;
-
-extern int yy_flex_debug;
-int yy_flex_debug = 0;
-
-/* The intent behind this definition is that it'll catch
- * any uses of REJECT which flex missed.
- */
-#define REJECT reject_used_but_not_detected
-#define yymore() yymore_used_but_not_detected
-#define YY_MORE_ADJ 0
-#define YY_RESTORE_YY_MORE_OFFSET
-char *yytext;
-#line 1 "autotools.ll"
-#line 2 "autotools.ll"
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "automakeparser.h"
-#include <stdlib.h>
-
-/**
-@file autotools.ll
-Autotools Lexer
-
-There are 3 types of identifiers recognized by this lexer:
--id_simple: examples of such identifiers are qmake variables and scoped variables
-at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
--id_list: those are "value list identifiers" at the right side in assignments
-(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
--id_args: function arguments recognized as one identifier
-(example: ""${QMAKE_FILE} is intended only for Windows!""
-in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
-.
-
-To recognize those identifiers two additional start conditions are used: list and funcargs.
-
-@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
-the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
-so no indentation is preserved by this lexer (and parser).
-
-To debug this lexer, put the line below into the next flex file section.
-%option debug
-*/
-
-
-
-#line 559 "autotools_lex.cpp"
-
-#define INITIAL 0
-#define list 1
-#define funcargs 2
-#define conditional 3
-
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-
-#ifndef YY_EXTRA_TYPE
-#define YY_EXTRA_TYPE void *
-#endif
-
-/* Macros after this point can all be overridden by user definitions in
- * section 1.
- */
-
-#ifndef YY_SKIP_YYWRAP
-#ifdef __cplusplus
-extern "C" int yywrap (void );
-#else
-extern int yywrap (void );
-#endif
-#endif
-
- static void yyunput (int c,char *buf_ptr );
-
-#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int );
-#endif
-
-#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * );
-#endif
-
-#ifndef YY_NO_INPUT
-
-#ifdef __cplusplus
-static int yyinput (void );
-#else
-static int input (void );
-#endif
-
-#endif
-
-/* Amount of stuff to slurp up with each read. */
-#ifndef YY_READ_BUF_SIZE
-#define YY_READ_BUF_SIZE 8192
-#endif
-
-/* Copy whatever the last rule matched to the standard output. */
-#ifndef ECHO
-/* This used to be an fputs(), but since the string might contain NUL's,
- * we now use fwrite().
- */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
-#endif
-
-/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
- * is returned in "result".
- */
-#ifndef YY_INPUT
-#define YY_INPUT(buf,result,max_size) \
- if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
- { \
- int c = '*'; \
- size_t n; \
- for ( n = 0; n < max_size && \
- (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
- buf[n] = (char) c; \
- if ( c == '\n' ) \
- buf[n++] = (char) c; \
- if ( c == EOF && ferror( yyin ) ) \
- YY_FATAL_ERROR( "input in flex scanner failed" ); \
- result = n; \
- } \
- else \
- { \
- errno=0; \
- while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
- { \
- if( errno != EINTR) \
- { \
- YY_FATAL_ERROR( "input in flex scanner failed" ); \
- break; \
- } \
- errno=0; \
- clearerr(yyin); \
- } \
- }\
-\
-
-#endif
-
-/* No semi-colon after return; correct usage is to write "yyterminate();" -
- * we don't want an extra ';' after the "return" because that will cause
- * some compilers to complain about unreachable statements.
- */
-#ifndef yyterminate
-#define yyterminate() return YY_NULL
-#endif
-
-/* Number of entries by which start-condition stack grows. */
-#ifndef YY_START_STACK_INCR
-#define YY_START_STACK_INCR 25
-#endif
-
-/* Report a fatal error. */
-#ifndef YY_FATAL_ERROR
-#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
-#endif
-
-/* end tables serialization structures and prototypes */
-
-/* Default declaration of generated scanner - a define so the user can
- * easily add parameters.
- */
-#ifndef YY_DECL
-#define YY_DECL_IS_OURS 1
-
-extern int yylex (void);
-
-#define YY_DECL int yylex (void)
-#endif /* !YY_DECL */
-
-/* Code executed at the beginning of each rule, after yytext and yyleng
- * have been set up.
- */
-#ifndef YY_USER_ACTION
-#define YY_USER_ACTION
-#endif
-
-/* Code executed at the end of each rule. */
-#ifndef YY_BREAK
-#define YY_BREAK break;
-#endif
-
-#define YY_RULE_SETUP \
- YY_USER_ACTION
-
-/** The main scanner function which does all the work.
- */
-YY_DECL
-{
- register yy_state_type yy_current_state;
- register char *yy_cp, *yy_bp;
- register int yy_act;
-
-#line 72 "autotools.ll"
-
-
-#line 714 "autotools_lex.cpp"
-
- if ( (yy_init) )
- {
- (yy_init) = 0;
-
-#ifdef YY_USER_INIT
- YY_USER_INIT;
-#endif
-
- if ( ! (yy_start) )
- (yy_start) = 1; /* first start state */
-
- if ( ! yyin )
- yyin = stdin;
-
- if ( ! yyout )
- yyout = stdout;
-
- if ( ! YY_CURRENT_BUFFER ) {
- yyensure_buffer_stack ();
- YY_CURRENT_BUFFER_LVALUE =
- yy_create_buffer(yyin,YY_BUF_SIZE );
- }
-
- yy_load_buffer_state( );
- }
-
- while ( 1 ) /* loops until end-of-file is reached */
- {
- yy_cp = (yy_c_buf_p);
-
- /* Support of yytext. */
- *yy_cp = (yy_hold_char);
-
- /* yy_bp points to the position in yy_ch_buf of the start of
- * the current run.
- */
- yy_bp = yy_cp;
-
- yy_current_state = (yy_start);
-yy_match:
- do
- {
- register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
- if ( yy_accept[yy_current_state] )
- {
- (yy_last_accepting_state) = yy_current_state;
- (yy_last_accepting_cpos) = yy_cp;
- }
- while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
- {
- yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 64 )
- yy_c = yy_meta[(unsigned int) yy_c];
- }
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
- ++yy_cp;
- }
- while ( yy_base[yy_current_state] != 155 );
-
-yy_find_action:
- yy_act = yy_accept[yy_current_state];
- if ( yy_act == 0 )
- { /* have to back up */
- yy_cp = (yy_last_accepting_cpos);
- yy_current_state = (yy_last_accepting_state);
- yy_act = yy_accept[yy_current_state];
- }
-
- YY_DO_BEFORE_ACTION;
-
-do_action: /* This label is used only to access EOF actions. */
-
- switch ( yy_act )
- { /* beginning of action switch */
- case 0: /* must back up */
- /* undo the effects of YY_DO_BEFORE_ACTION */
- *yy_cp = (yy_hold_char);
- yy_cp = (yy_last_accepting_cpos);
- yy_current_state = (yy_last_accepting_state);
- goto yy_find_action;
-
-case 1:
-YY_RULE_SETUP
-#line 74 "autotools.ll"
-{}
- YY_BREAK
-case 2:
-/* rule 2 can match eol */
-YY_RULE_SETUP
-#line 75 "autotools.ll"
-{ BEGIN(list); return CONT; }
- YY_BREAK
-case 3:
-YY_RULE_SETUP
-#line 76 "autotools.ll"
-{
- yylval.value = yytext;
- if ( yylval.value == "if" )
- return IF_KEYWORD;
-
- if ( yylval.value == "else" )
- return ELSE_KEYWORD;
-
- if ( yylval.value == "endif" )
- return ENDIF_KEYWORD;
-
- return KEYWORD;
-}
- YY_BREAK
-case 4:
-YY_RULE_SETUP
-#line 91 "autotools.ll"
-{ yylval.value = yytext; return (ID_SIMPLE); }
- YY_BREAK
-case 5:
-YY_RULE_SETUP
-#line 93 "autotools.ll"
-{
- yylval.value = yytext;
- return RULE;
-}
- YY_BREAK
-case 6:
-YY_RULE_SETUP
-#line 98 "autotools.ll"
-{
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
- unput('\\');
- BEGIN(INITIAL);
- return (ID_LIST);
- }
- YY_BREAK
-case 7:
-/* rule 7 can match eol */
-YY_RULE_SETUP
-#line 106 "autotools.ll"
-{
- yylval.value = yytext;
- BEGIN(list);
- return (LIST_COMMENT);
- }
- YY_BREAK
-case 8:
-YY_RULE_SETUP
-#line 112 "autotools.ll"
-{
- yylval.value = yytext;
- return LIST_COMMENT;
- }
- YY_BREAK
-case 9:
-YY_RULE_SETUP
-#line 117 "autotools.ll"
-{
- yylval.value = yytext;
- BEGIN(INITIAL);
- return (ID_LIST_SINGLE);
- }
- YY_BREAK
-case 10:
-YY_RULE_SETUP
-#line 123 "autotools.ll"
-{
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.length()-1);
- unput(')');
- BEGIN(INITIAL);
- return (ID_ARGS);
- }
- YY_BREAK
-case 11:
-YY_RULE_SETUP
-#line 131 "autotools.ll"
-{ BEGIN(list); yylval.value = yytext; return EQ; }
- YY_BREAK
-case 12:
-YY_RULE_SETUP
-#line 132 "autotools.ll"
-{ BEGIN(list); yylval.value = yytext; return PLUSEQ; }
- YY_BREAK
-case 13:
-YY_RULE_SETUP
-#line 133 "autotools.ll"
-{ return LCURLY; }
- YY_BREAK
-case 14:
-YY_RULE_SETUP
-#line 134 "autotools.ll"
-{ return RCURLY; }
- YY_BREAK
-case 15:
-YY_RULE_SETUP
-#line 135 "autotools.ll"
-{ BEGIN(list); yylval.value = yytext; return COLON; }
- YY_BREAK
-case 16:
-/* rule 16 can match eol */
-YY_RULE_SETUP
-#line 136 "autotools.ll"
-{ BEGIN(INITIAL); return NEWLINE; }
- YY_BREAK
-case 17:
-YY_RULE_SETUP
-#line 137 "autotools.ll"
-{ yylval.value = yytext; return (COMMENT); }
- YY_BREAK
-case 18:
-YY_RULE_SETUP
-#line 139 "autotools.ll"
-ECHO;
- YY_BREAK
-#line 928 "autotools_lex.cpp"
-case YY_STATE_EOF(INITIAL):
-case YY_STATE_EOF(list):
-case YY_STATE_EOF(funcargs):
-case YY_STATE_EOF(conditional):
- yyterminate();
-
- case YY_END_OF_BUFFER:
- {
- /* Amount of text matched not including the EOB char. */
- int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
-
- /* Undo the effects of YY_DO_BEFORE_ACTION. */
- *yy_cp = (yy_hold_char);
- YY_RESTORE_YY_MORE_OFFSET
-
- if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
- {
- /* We're scanning a new file or input source. It's
- * possible that this happened because the user
- * just pointed yyin at a new source and called
- * yylex(). If so, then we have to assure
- * consistency between YY_CURRENT_BUFFER and our
- * globals. Here is the right place to do so, because
- * this is the first action (other than possibly a
- * back-up) that will match for the new input source.
- */
- (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
- YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
- YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
- }
-
- /* Note that here we test for yy_c_buf_p "<=" to the position
- * of the first EOB in the buffer, since yy_c_buf_p will
- * already have been incremented past the NUL character
- * (since all states make transitions on EOB to the
- * end-of-buffer state). Contrast this with the test
- * in input().
- */
- if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
- { /* This was really a NUL. */
- yy_state_type yy_next_state;
-
- (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
-
- yy_current_state = yy_get_previous_state( );
-
- /* Okay, we're now positioned to make the NUL
- * transition. We couldn't have
- * yy_get_previous_state() go ahead and do it
- * for us because it doesn't know how to deal
- * with the possibility of jamming (and we don't
- * want to build jamming into it because then it
- * will run more slowly).
- */
-
- yy_next_state = yy_try_NUL_trans( yy_current_state );
-
- yy_bp = (yytext_ptr) + YY_MORE_ADJ;
-
- if ( yy_next_state )
- {
- /* Consume the NUL. */
- yy_cp = ++(yy_c_buf_p);
- yy_current_state = yy_next_state;
- goto yy_match;
- }
-
- else
- {
- yy_cp = (yy_c_buf_p);
- goto yy_find_action;
- }
- }
-
- else switch ( yy_get_next_buffer( ) )
- {
- case EOB_ACT_END_OF_FILE:
- {
- (yy_did_buffer_switch_on_eof) = 0;
-
- if ( yywrap( ) )
- {
- /* Note: because we've taken care in
- * yy_get_next_buffer() to have set up
- * yytext, we can now set up
- * yy_c_buf_p so that if some total
- * hoser (like flex itself) wants to
- * call the scanner after we return the
- * YY_NULL, it'll still work - another
- * YY_NULL will get returned.
- */
- (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
-
- yy_act = YY_STATE_EOF(YY_START);
- goto do_action;
- }
-
- else
- {
- if ( ! (yy_did_buffer_switch_on_eof) )
- YY_NEW_FILE;
- }
- break;
- }
-
- case EOB_ACT_CONTINUE_SCAN:
- (yy_c_buf_p) =
- (yytext_ptr) + yy_amount_of_matched_text;
-
- yy_current_state = yy_get_previous_state( );
-
- yy_cp = (yy_c_buf_p);
- yy_bp = (yytext_ptr) + YY_MORE_ADJ;
- goto yy_match;
-
- case EOB_ACT_LAST_MATCH:
- (yy_c_buf_p) =
- &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
-
- yy_current_state = yy_get_previous_state( );
-
- yy_cp = (yy_c_buf_p);
- yy_bp = (yytext_ptr) + YY_MORE_ADJ;
- goto yy_find_action;
- }
- break;
- }
-
- default:
- YY_FATAL_ERROR(
- "fatal flex scanner internal error--no action found" );
- } /* end of action switch */
- } /* end of scanning one token */
-} /* end of yylex */
-
-/* yy_get_next_buffer - try to read in a new buffer
- *
- * Returns a code representing an action:
- * EOB_ACT_LAST_MATCH -
- * EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- * EOB_ACT_END_OF_FILE - end of file
- */
-static int yy_get_next_buffer (void)
-{
- register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
- register char *source = (yytext_ptr);
- register int number_to_move, i;
- int ret_val;
-
- if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
- YY_FATAL_ERROR(
- "fatal flex scanner internal error--end of buffer missed" );
-
- if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
- { /* Don't try to fill the buffer, so this is an EOF. */
- if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
- {
- /* We matched a single character, the EOB, so
- * treat this as a final EOF.
- */
- return EOB_ACT_END_OF_FILE;
- }
-
- else
- {
- /* We matched some text prior to the EOB, first
- * process it.
- */
- return EOB_ACT_LAST_MATCH;
- }
- }
-
- /* Try to read more data. */
-
- /* First move last chars to start of buffer. */
- number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
-
- for ( i = 0; i < number_to_move; ++i )
- *(dest++) = *(source++);
-
- if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
- /* don't do the read, it's not guaranteed to return an EOF,
- * just force an EOF
- */
- YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
-
- else
- {
- size_t num_to_read =
- YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
-
- while ( num_to_read <= 0 )
- { /* Not enough room in the buffer - grow it. */
-
- /* just a shorter name for the current buffer */
- YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
-
- int yy_c_buf_p_offset =
- (int) ((yy_c_buf_p) - b->yy_ch_buf);
-
- if ( b->yy_is_our_buffer )
- {
- int new_size = b->yy_buf_size * 2;
-
- if ( new_size <= 0 )
- b->yy_buf_size += b->yy_buf_size / 8;
- else
- b->yy_buf_size *= 2;
-
- b->yy_ch_buf = (char *)
- /* Include room in for 2 EOB chars. */
- yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
- }
- else
- /* Can't grow it, we don't own it. */
- b->yy_ch_buf = 0;
-
- if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR(
- "fatal error - scanner input buffer overflow" );
-
- (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
-
- num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
- number_to_move - 1;
-
- }
-
- if ( num_to_read > YY_READ_BUF_SIZE )
- num_to_read = YY_READ_BUF_SIZE;
-
- /* Read in more data. */
- YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
- (yy_n_chars), num_to_read );
-
- YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
- }
-
- if ( (yy_n_chars) == 0 )
- {
- if ( number_to_move == YY_MORE_ADJ )
- {
- ret_val = EOB_ACT_END_OF_FILE;
- yyrestart(yyin );
- }
-
- else
- {
- ret_val = EOB_ACT_LAST_MATCH;
- YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
- YY_BUFFER_EOF_PENDING;
- }
- }
-
- else
- ret_val = EOB_ACT_CONTINUE_SCAN;
-
- (yy_n_chars) += number_to_move;
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
-
- (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
-
- return ret_val;
-}
-
-/* yy_get_previous_state - get the state just before the EOB char was reached */
-
- static yy_state_type yy_get_previous_state (void)
-{
- register yy_state_type yy_current_state;
- register char *yy_cp;
-
- yy_current_state = (yy_start);
-
- for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
- {
- register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
- if ( yy_accept[yy_current_state] )
- {
- (yy_last_accepting_state) = yy_current_state;
- (yy_last_accepting_cpos) = yy_cp;
- }
- while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
- {
- yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 64 )
- yy_c = yy_meta[(unsigned int) yy_c];
- }
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
- }
-
- return yy_current_state;
-}
-
-/* yy_try_NUL_trans - try to make a transition on the NUL character
- *
- * synopsis
- * next_state = yy_try_NUL_trans( current_state );
- */
- static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
-{
- register int yy_is_jam;
- register char *yy_cp = (yy_c_buf_p);
-
- register YY_CHAR yy_c = 1;
- if ( yy_accept[yy_current_state] )
- {
- (yy_last_accepting_state) = yy_current_state;
- (yy_last_accepting_cpos) = yy_cp;
- }
- while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
- {
- yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 64 )
- yy_c = yy_meta[(unsigned int) yy_c];
- }
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
- yy_is_jam = (yy_current_state == 63);
-
- return yy_is_jam ? 0 : yy_current_state;
-}
-
- static void yyunput (int c, register char * yy_bp )
-{
- register char *yy_cp;
-
- yy_cp = (yy_c_buf_p);
-
- /* undo effects of setting up yytext */
- *yy_cp = (yy_hold_char);
-
- if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
- { /* need to shift things up to make room */
- /* +2 for EOB chars. */
- register int number_to_move = (yy_n_chars) + 2;
- register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
- YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
- register char *source =
- &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
-
- while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
- *--dest = *--source;
-
- yy_cp += (int) (dest - source);
- yy_bp += (int) (dest - source);
- YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
- (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
-
- if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
- YY_FATAL_ERROR( "flex scanner push-back overflow" );
- }
-
- *--yy_cp = (char) c;
-
- (yytext_ptr) = yy_bp;
- (yy_hold_char) = *yy_cp;
- (yy_c_buf_p) = yy_cp;
-}
-
-#ifndef YY_NO_INPUT
-#ifdef __cplusplus
- static int yyinput (void)
-#else
- static int input (void)
-#endif
-
-{
- int c;
-
- *(yy_c_buf_p) = (yy_hold_char);
-
- if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
- {
- /* yy_c_buf_p now points to the character we want to return.
- * If this occurs *before* the EOB characters, then it's a
- * valid NUL; if not, then we've hit the end of the buffer.
- */
- if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
- /* This was really a NUL. */
- *(yy_c_buf_p) = '\0';
-
- else
- { /* need more input */
- int offset = (yy_c_buf_p) - (yytext_ptr);
- ++(yy_c_buf_p);
-
- switch ( yy_get_next_buffer( ) )
- {
- case EOB_ACT_LAST_MATCH:
- /* This happens because yy_g_n_b()
- * sees that we've accumulated a
- * token and flags that we need to
- * try matching the token before
- * proceeding. But for input(),
- * there's no matching to consider.
- * So convert the EOB_ACT_LAST_MATCH
- * to EOB_ACT_END_OF_FILE.
- */
-
- /* Reset buffer status. */
- yyrestart(yyin );
-
- /*FALLTHROUGH*/
-
- case EOB_ACT_END_OF_FILE:
- {
- if ( yywrap( ) )
- return EOF;
-
- if ( ! (yy_did_buffer_switch_on_eof) )
- YY_NEW_FILE;
-#ifdef __cplusplus
- return yyinput();
-#else
- return input();
-#endif
- }
-
- case EOB_ACT_CONTINUE_SCAN:
- (yy_c_buf_p) = (yytext_ptr) + offset;
- break;
- }
- }
- }
-
- c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
- *(yy_c_buf_p) = '\0'; /* preserve yytext */
- (yy_hold_char) = *++(yy_c_buf_p);
-
- return c;
-}
-#endif /* ifndef YY_NO_INPUT */
-
-/** Immediately switch to a different input stream.
- * @param input_file A readable stream.
- *
- * @note This function does not reset the start condition to @c INITIAL .
- */
- void yyrestart (FILE * input_file )
-{
-
- if ( ! YY_CURRENT_BUFFER ){
- yyensure_buffer_stack ();
- YY_CURRENT_BUFFER_LVALUE =
- yy_create_buffer(yyin,YY_BUF_SIZE );
- }
-
- yy_init_buffer(YY_CURRENT_BUFFER,input_file );
- yy_load_buffer_state( );
-}
-
-/** Switch to a different input buffer.
- * @param new_buffer The new input buffer.
- *
- */
- void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer )
-{
-
- /* TODO. We should be able to replace this entire function body
- * with
- * yypop_buffer_state();
- * yypush_buffer_state(new_buffer);
- */
- yyensure_buffer_stack ();
- if ( YY_CURRENT_BUFFER == new_buffer )
- return;
-
- if ( YY_CURRENT_BUFFER )
- {
- /* Flush out information for old buffer. */
- *(yy_c_buf_p) = (yy_hold_char);
- YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
- YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
- }
-
- YY_CURRENT_BUFFER_LVALUE = new_buffer;
- yy_load_buffer_state( );
-
- /* We don't actually know whether we did this switch during
- * EOF (yywrap()) processing, but the only time this flag
- * is looked at is after yywrap() is called, so it's safe
- * to go ahead and always set it.
- */
- (yy_did_buffer_switch_on_eof) = 1;
-}
-
-static void yy_load_buffer_state (void)
-{
- (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
- (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
- yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
- (yy_hold_char) = *(yy_c_buf_p);
-}
-
-/** Allocate and initialize an input buffer state.
- * @param file A readable stream.
- * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
- *
- * @return the allocated buffer state.
- */
- YY_BUFFER_STATE yy_create_buffer (FILE * file, int size )
-{
- YY_BUFFER_STATE b;
-
- b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
- if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
-
- b->yy_buf_size = size;
-
- /* yy_ch_buf has to be 2 characters longer than the size given because
- * we need to put in 2 end-of-buffer characters.
- */
- b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 );
- if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
-
- b->yy_is_our_buffer = 1;
-
- yy_init_buffer(b,file );
-
- return b;
-}
-
-/** Destroy the buffer.
- * @param b a buffer created with yy_create_buffer()
- *
- */
- void yy_delete_buffer (YY_BUFFER_STATE b )
-{
-
- if ( ! b )
- return;
-
- if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
- YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
-
- if ( b->yy_is_our_buffer )
- yyfree((void *) b->yy_ch_buf );
-
- yyfree((void *) b );
-}
-
-#ifndef __cplusplus
-extern int isatty (int );
-#endif /* __cplusplus */
-
-/* Initializes or reinitializes a buffer.
- * This function is sometimes called more than once on the same buffer,
- * such as during a yyrestart() or at EOF.
- */
- static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file )
-
-{
- int oerrno = errno;
-
- yy_flush_buffer(b );
-
- b->yy_input_file = file;
- b->yy_fill_buffer = 1;
-
- /* If b is the current buffer, then yy_init_buffer was _probably_
- * called from yyrestart() or through yy_get_next_buffer.
- * In that case, we don't want to reset the lineno or column.
- */
- if (b != YY_CURRENT_BUFFER){
- b->yy_bs_lineno = 1;
- b->yy_bs_column = 0;
- }
-
- b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
-
- errno = oerrno;
-}
-
-/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
- * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
- *
- */
- void yy_flush_buffer (YY_BUFFER_STATE b )
-{
- if ( ! b )
- return;
-
- b->yy_n_chars = 0;
-
- /* We always need two end-of-buffer characters. The first causes
- * a transition to the end-of-buffer state. The second causes
- * a jam in that state.
- */
- b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
- b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
-
- b->yy_buf_pos = &b->yy_ch_buf[0];
-
- b->yy_at_bol = 1;
- b->yy_buffer_status = YY_BUFFER_NEW;
-
- if ( b == YY_CURRENT_BUFFER )
- yy_load_buffer_state( );
-}
-
-/** Pushes the new state onto the stack. The new state becomes
- * the current state. This function will allocate the stack
- * if necessary.
- * @param new_buffer The new state.
- *
- */
-void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
-{
- if (new_buffer == NULL)
- return;
-
- yyensure_buffer_stack();
-
- /* This block is copied from yy_switch_to_buffer. */
- if ( YY_CURRENT_BUFFER )
- {
- /* Flush out information for old buffer. */
- *(yy_c_buf_p) = (yy_hold_char);
- YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
- YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
- }
-
- /* Only push if top exists. Otherwise, replace top. */
- if (YY_CURRENT_BUFFER)
- (yy_buffer_stack_top)++;
- YY_CURRENT_BUFFER_LVALUE = new_buffer;
-
- /* copied from yy_switch_to_buffer. */
- yy_load_buffer_state( );
- (yy_did_buffer_switch_on_eof) = 1;
-}
-
-/** Removes and deletes the top of the stack, if present.
- * The next element becomes the new top.
- *
- */
-void yypop_buffer_state (void)
-{
- if (!YY_CURRENT_BUFFER)
- return;
-
- yy_delete_buffer(YY_CURRENT_BUFFER );
- YY_CURRENT_BUFFER_LVALUE = NULL;
- if ((yy_buffer_stack_top) > 0)
- --(yy_buffer_stack_top);
-
- if (YY_CURRENT_BUFFER) {
- yy_load_buffer_state( );
- (yy_did_buffer_switch_on_eof) = 1;
- }
-}
-
-/* Allocates the stack if it does not exist.
- * Guarantees space for at least one push.
- */
-static void yyensure_buffer_stack (void)
-{
- int num_to_alloc;
-
- if (!(yy_buffer_stack)) {
-
- /* First allocation is just for 2 elements, since we don't know if this
- * scanner will even need a stack. We use 2 instead of 1 to avoid an
- * immediate realloc on the next call.
- */
- num_to_alloc = 1;
- (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
- (num_to_alloc * sizeof(struct yy_buffer_state*)
- );
-
- memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
-
- (yy_buffer_stack_max) = num_to_alloc;
- (yy_buffer_stack_top) = 0;
- return;
- }
-
- if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
-
- /* Increase the buffer to prepare for a possible push. */
- int grow_size = 8 /* arbitrary grow size */;
-
- num_to_alloc = (yy_buffer_stack_max) + grow_size;
- (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
- ((yy_buffer_stack),
- num_to_alloc * sizeof(struct yy_buffer_state*)
- );
-
- /* zero only the new slots.*/
- memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
- (yy_buffer_stack_max) = num_to_alloc;
- }
-}
-
-/** Setup the input buffer state to scan directly from a user-specified character buffer.
- * @param base the character buffer
- * @param size the size in bytes of the character buffer
- *
- * @return the newly allocated buffer state object.
- */
-YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size )
-{
- YY_BUFFER_STATE b;
-
- if ( size < 2 ||
- base[size-2] != YY_END_OF_BUFFER_CHAR ||
- base[size-1] != YY_END_OF_BUFFER_CHAR )
- /* They forgot to leave room for the EOB's. */
- return 0;
-
- b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) );
- if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
-
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
- b->yy_buf_pos = b->yy_ch_buf = base;
- b->yy_is_our_buffer = 0;
- b->yy_input_file = 0;
- b->yy_n_chars = b->yy_buf_size;
- b->yy_is_interactive = 0;
- b->yy_at_bol = 1;
- b->yy_fill_buffer = 0;
- b->yy_buffer_status = YY_BUFFER_NEW;
-
- yy_switch_to_buffer(b );
-
- return b;
-}
-
-/** Setup the input buffer state to scan a string. The next call to yylex() will
- * scan from a @e copy of @a str.
- * @param str a NUL-terminated string to scan
- *
- * @return the newly allocated buffer state object.
- * @note If you want to scan bytes that may contain NUL values, then use
- * yy_scan_bytes() instead.
- */
-YY_BUFFER_STATE yy_scan_string (yyconst char * str )
-{
-
- return yy_scan_bytes(str,strlen(str) );
-}
-
-/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
- * scan from a @e copy of @a bytes.
- * @param bytes the byte buffer to scan
- * @param len the number of bytes in the buffer pointed to by @a bytes.
- *
- * @return the newly allocated buffer state object.
- */
-YY_BUFFER_STATE yy_scan_bytes (yyconst char * bytes, int len )
-{
- YY_BUFFER_STATE b;
- char *buf;
- yy_size_t n;
- int i;
-
- /* Get memory for full buffer, including space for trailing EOB's. */
- n = len + 2;
- buf = (char *) yyalloc(n );
- if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
-
- for ( i = 0; i < len; ++i )
- buf[i] = bytes[i];
-
- buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
-
- b = yy_scan_buffer(buf,n );
- if ( ! b )
- YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
-
- /* It's okay to grow etc. this buffer, and we should throw it
- * away when we're done.
- */
- b->yy_is_our_buffer = 1;
-
- return b;
-}
-
-#ifndef YY_EXIT_FAILURE
-#define YY_EXIT_FAILURE 2
-#endif
-
-static void yy_fatal_error (yyconst char* msg )
-{
- (void) fprintf( stderr, "%s\n", msg );
- exit( YY_EXIT_FAILURE );
-}
-
-/* Redefine yyless() so it works in section 3 code. */
-
-#undef yyless
-#define yyless(n) \
- do \
- { \
- /* Undo effects of setting up yytext. */ \
- int yyless_macro_arg = (n); \
- YY_LESS_LINENO(yyless_macro_arg);\
- yytext[yyleng] = (yy_hold_char); \
- (yy_c_buf_p) = yytext + yyless_macro_arg; \
- (yy_hold_char) = *(yy_c_buf_p); \
- *(yy_c_buf_p) = '\0'; \
- yyleng = yyless_macro_arg; \
- } \
- while ( 0 )
-
-/* Accessor methods (get/set functions) to struct members. */
-
-/** Get the current line number.
- *
- */
-int yyget_lineno (void)
-{
-
- return yylineno;
-}
-
-/** Get the input stream.
- *
- */
-FILE *yyget_in (void)
-{
- return yyin;
-}
-
-/** Get the output stream.
- *
- */
-FILE *yyget_out (void)
-{
- return yyout;
-}
-
-/** Get the length of the current token.
- *
- */
-int yyget_leng (void)
-{
- return yyleng;
-}
-
-/** Get the current token.
- *
- */
-
-char *yyget_text (void)
-{
- return yytext;
-}
-
-/** Set the current line number.
- * @param line_number
- *
- */
-void yyset_lineno (int line_number )
-{
-
- yylineno = line_number;
-}
-
-/** Set the input stream. This does not discard the current
- * input buffer.
- * @param in_str A readable stream.
- *
- * @see yy_switch_to_buffer
- */
-void yyset_in (FILE * in_str )
-{
- yyin = in_str ;
-}
-
-void yyset_out (FILE * out_str )
-{
- yyout = out_str ;
-}
-
-int yyget_debug (void)
-{
- return yy_flex_debug;
-}
-
-void yyset_debug (int bdebug )
-{
- yy_flex_debug = bdebug ;
-}
-
-/* yylex_destroy is for both reentrant and non-reentrant scanners. */
-int yylex_destroy (void)
-{
-
- /* Pop the buffer stack, destroying each element. */
- while(YY_CURRENT_BUFFER){
- yy_delete_buffer(YY_CURRENT_BUFFER );
- YY_CURRENT_BUFFER_LVALUE = NULL;
- yypop_buffer_state();
- }
-
- /* Destroy the stack itself. */
- yyfree((yy_buffer_stack) );
- (yy_buffer_stack) = NULL;
-
- return 0;
-}
-
-/*
- * Internal utility routines.
- */
-
-#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
-{
- register int i;
- for ( i = 0; i < n; ++i )
- s1[i] = s2[i];
-}
-#endif
-
-#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s )
-{
- register int n;
- for ( n = 0; s[n]; ++n )
- ;
-
- return n;
-}
-#endif
-
-void *yyalloc (yy_size_t size )
-{
- return (void *) malloc( size );
-}
-
-void *yyrealloc (void * ptr, yy_size_t size )
-{
- /* The cast to (char *) in the following accommodates both
- * implementations that use char* generic pointers, and those
- * that use void* generic pointers. It works with the latter
- * because both ANSI C and C++ allow castless assignment from
- * any pointer type to void*, and deal with argument conversions
- * as though doing an assignment.
- */
- return (void *) realloc( (char *) ptr, size );
-}
-
-void yyfree (void * ptr )
-{
- free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
-}
-
-#define YYTABLES_NAME "yytables"
-
-#undef YY_NEW_FILE
-#undef YY_FLUSH_BUFFER
-#undef yy_set_bol
-#undef yy_new_buffer
-#undef yy_set_interactive
-#undef YY_DO_BEFORE_ACTION
-
-#ifdef YY_DECL_IS_OURS
-#undef YY_DECL_IS_OURS
-#undef YY_DECL
-#endif
-#line 139 "autotools.ll"
-
-
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake_lex.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.yy
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.yy (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.yy (nonexistent)
@@ -1,322 +0,0 @@
-%{
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-/**
-@file autotools.yy
-Autotools Parser
-
-Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
-
-@todo Recognize comments after statements like:
-noinst_HEADERS = foo.h #regognize me
-
-@fixme Parser fails on files that do not end with a newline
-@fixme 1 shift/reduce conflict in "line_body" rule
-*/
-
-
-#include <qstack.h>
-#include "automakeast.h"
-
-#define YYSTYPE_IS_DECLARED
-
-using namespace AutoMake;
-
-/**
-The yylval type.
-*/
-typedef struct Result {
- Result(): node(0) {}
-
- /**Type of semantic value for simple grammar rules.*/
- QString value;
- /**Type of semantic value for grammar rules which are parts of AST.*/
- AST *node;
- /**Type of semantic value for "multiline_values" grammar rule.
- Each line of multiline value is stored as a string in the list.
-
- For example we have in Makefile.am file:
- @code
- foo_SOURCES = foo1.cpp \
- foo2.cpp \
- foo3.cpp foo4.cpp
- @endcode
- The string list will be populated with three strings:
- <pre>
- foo1.cpp
- foo2.cpp
- foo3.cpp foo4.cpp
- </pre>
- */
- QStringList values;
-} YYSTYPE;
-
-
-void yyerror(const char *str) {
- qWarning("bison error: %s\n", str);
-}
-
-int yylex();
-
-/**
-The stack to store ProjectAST pointers when a new child
-ProjectAST is created and filled with statements.
-
-Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
-adding statements. Each statement is added as a child StatementAST to the ProjectAST
-currently on the top in the stack.
-
-When a scope or function scope statement is parsed, the child ProjectAST is created
-and pushed onto the stack. Therefore all statements which belong to the scope
-or function scope are added as childs to their direct parent (scope or function scope).
-*/
-QStack<ProjectAST*> projects;
-
-/**
-The current depth of AST node is stored here.
-AST depth is important to know because automatic indentation can
-be easily implemented (the parser itself looses all information
-about indentation).
-*/
-int depth = 0;
-
-/*
-To debug this parser, put the line below into the next bison file section.
-Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
-%debug
-*/
-%}
-%debug
-%token ID_SIMPLE
-%token ID_LIST
-%token LBRACE
-%token EQ
-%token PLUSEQ
-%token MINUSQE
-%token STAREQ
-%token TILDEEQ
-%token LBRACE
-%token RBRACE
-%token COLON
-%token NUMSIGN
-%token NEWLINE
-%token NUMBER
-%token COMMENT
-%token CONT
-%token DOT
-%token RCURLY
-%token LCURLY
-%token ID_ARGS
-%token LIST_COMMENT
-%token ID_LIST_SINGLE
-%token IF_KEYWORD
-%token ELSE_KEYWORD
-%token ENDIF_KEYWORD
-%token KEYWORD
-%token RULE
-
-%%
-
-project :
-{
- ProjectAST *projectAST = new ProjectAST();
- projects.push(projectAST);
-}
-statements
-;
-
-statements : statements statement
-{
- projects.top()->addChildAST($<node>2);
-
- if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "if" )
- {
- $<node>2->setDepth(depth);
- depth++;
- }
- else if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "else" )
- {
- --depth;
- $<node>2->setDepth(depth);
- ++depth;
- }
- else if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "endif" )
- {
- --depth;
- $<node>2->setDepth(depth);
- }
- else
- $<node>2->setDepth(depth);
-}
-|
-;
-
-statement : variable_assignment
-{
- $<node>$ = $<node>1;
-}
-| automake_if
-{
- $<node>$ = $<node>1;
-}
-| else_statement
-{
- $<node>$ = $<node>1;
-}
-| endif_statement
-{
- $<node>$ = $<node>1;
-}
-| target
-{
- $<node>$ = $<node>1;
-}
-| am_rule
-{
- $<node>$ = $<node>1;
-}
-| include_directive
-{
- $<node>$ = $<node>1;
-}
-| comment
-{
- $<node>$ = $<node>1;
-}
-| emptyline
-{
- $<node>$ = new NewLineAST();
-}
-;
-
-automake_if: IF_KEYWORD scoped_identifier
-{
- ConditionAST* projectAST = new ConditionAST();
- projectAST->type = "if";
- projectAST->conditionName = $<value>2;
- $<node>$ = projectAST;
-};
-
-endif_statement: ENDIF_KEYWORD
-{
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- $<node>$ = past;
-}
-| ENDIF_KEYWORD scoped_identifier
-{
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- past->conditionName = $<value>2;
- $<node>$ = past;
-}
-;
-
-else_statement: ELSE_KEYWORD
-{
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- $<node>$ = past;
-}
-| ELSE_KEYWORD scoped_identifier
-{
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- past->conditionName = $<value>2;
- $<node>$ = past;
-}
-;
-
-variable_assignment : scoped_identifier operator multiline_values
-{
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = $<value>1;
- node->op = $<value>2;
- node->values = $<values>3;
- $<node>$ = node;
-}
-;
-
-scoped_identifier : ID_SIMPLE scoped_identifier
-{ $<value>$ = $<value>1 + $<value>2; }
-| ID_SIMPLE
-;
-
-multiline_values : multiline_values line_body
-{
- QStringList list = $<value>2.split(QRegExp("\\s+"), QString::SkipEmptyParts);
- $<values>$ = $<values>$ + list; //.append($<value>2);
-}
-| { $<values>$.clear(); }
- ;
-
-line_body : ID_LIST CONT { $<value>$ = $<value>1 + " \\\n"; }
- | ID_LIST_SINGLE NEWLINE { $<value>$ = $<value>1 + "\n"; }
- | CONT { $<value>$ = "\\\n"; }
- | LIST_COMMENT
- ;
-
-target: scoped_identifier COLON multiline_values
-{
- AutomakeTargetAST *node = new AutomakeTargetAST();
- node->target = $<value>1;
- node->deps = $<values>3;
- $<node>$ = node;
-}
-;
-
-am_rule: RULE
-{
- ProjectAST* node = new ProjectAST(ProjectAST::Rule);
- node->scopedID = $<value>1;
- $<node>$ = node;
-}
-;
-
-include_directive: KEYWORD scoped_identifier
-{
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = $<value>1;
- node->values = QStringList($<value>2);
- $<node>$ = node;
-}
-;
-
-operator : EQ | PLUSEQ
-;
-
-comment : COMMENT NEWLINE
-{
- CommentAST *node = new CommentAST();
- node->comment = $<value>1 + "\n";
- $<node>$ = node;
-}
-;
-
-emptyline : NEWLINE
-;
-%%
-
-#include "automake_lex.cpp"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.yy
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.h (nonexistent)
@@ -1,120 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright 2005 Matt Rogers <mattr@kde.org>
- * Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef AUTOMAKEIMPORTER_H
-#define AUTOMAKEIMPORTER_H
-
-#include <QList>
-#include <QString>
-#include <QtCore/QVariant>
-#include <kdevplatform/project/interfaces/ibuildsystemmanager.h>
-#include <interfaces/iplugin.h>
-
-class QObject;
-
-class AutoMakeItem;
-class MakefileInterface;
-class QDir;
-class IAutomakeBuilder;
-
-namespace KDevelop
-{
- class IProject;
- class IProjectBuilder;
- class ProjectBaseItem;
- class ProjectFileItem;
- class ProjectFolderItem;
- class ProjectTargetItem;
-}
-
-
-class AutoMakeImporter : public KDevelop::IPlugin, public KDevelop::IBuildSystemManager
-{
-Q_OBJECT
-Q_INTERFACES( KDevelop::IBuildSystemManager )
-Q_INTERFACES( KDevelop::IProjectFileManager )
-
-public:
-
- virtual Features features() const { return Features(Folders | Targets | Files); }
-
- explicit AutoMakeImporter( QObject* parent = 0, const QVariantList& args = QVariantList() );
- virtual ~AutoMakeImporter();
-
- virtual KDevelop::IProjectBuilder* builder(KDevelop::ProjectFolderItem*) const;
- virtual KUrl buildDirectory(KDevelop::ProjectBaseItem*) const;
- virtual KUrl::List includeDirectories(KDevelop::ProjectBaseItem*) const { return KUrl::List(); }
-// virtual KUrl::List preprocessorDefines() const { return KUrl::List(); }
-
- virtual KDevelop::ProjectFolderItem* addFolder( const KUrl&, KDevelop::ProjectFolderItem* ) { return 0; }
-
- virtual QHash< QString, QString > defines(KDevelop::ProjectBaseItem *) const { return QHash<QString, QString>(); }
- virtual QHash<QString, QString> environment(KDevelop::ProjectBaseItem*) const { return QHash<QString,QString>(); }
-
- virtual KDevelop::ProjectTargetItem* createTarget( const QString&,
- KDevelop::ProjectFolderItem* ) { return false; }
-
- virtual KDevelop::ProjectFileItem* addFile( const KUrl&,
- KDevelop::ProjectFolderItem* ) { return false; }
-
- virtual bool addFileToTarget( KDevelop::ProjectFileItem*, KDevelop::ProjectTargetItem* ) { return false; }
-
- virtual bool removeFolder( KDevelop::ProjectFolderItem* ) { return false; }
-
- virtual bool removeTarget( KDevelop::ProjectTargetItem* ) { return false; }
-
- virtual bool removeFile( KDevelop::ProjectFileItem* ) { return false; }
- virtual bool removeFileFromTarget( KDevelop::ProjectFileItem*,
- KDevelop::ProjectTargetItem* ) { return false; }
-
- virtual bool removeFilesAndFolders(QList<KDevelop::ProjectBaseItem*>){return false;}
- virtual bool removeFilesFromTargets(QList<QPair<KDevelop::ProjectTargetItem*, KDevelop::ProjectFileItem*> >){return false;}
-
- virtual bool renameFile(KDevelop::ProjectFileItem*, const KUrl&) { return false; }
- virtual bool renameFolder(KDevelop::ProjectFolderItem*, const KUrl&) { return false; }
-
-
- virtual QList<KDevelop::ProjectTargetItem*> targets() const;
- virtual QList<KDevelop::ProjectTargetItem*> targets(KDevelop::ProjectFolderItem* folder) const;
-
- virtual QList<KDevelop::ProjectFolderItem*> parse( KDevelop::ProjectFolderItem* dom );
- virtual KDevelop::ProjectFolderItem* import( KDevelop::IProject* project);
-
-
- virtual bool reload(KDevelop::ProjectFolderItem*) { return false; }
- virtual KUrl findMakefile( KDevelop::ProjectFolderItem* dom ) const;
- virtual KUrl::List findMakefiles( KDevelop::ProjectFolderItem* dom ) const;
-
-private:
- void createFolderItems( KDevelop::ProjectFolderItem* );
-
-
- KDevelop::ProjectFolderItem* m_rootItem;
- MakefileInterface* m_interface;
-
- IAutomakeBuilder* m_builder;
-
- QMap<KDevelop::IProject*, KUrl> m_projectRoot;
-};
-
-#endif
-// kate: indent-mode cstyle; space-indent off; tab-width 4; auto-insert-doxygen on;
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeimporter.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake (nonexistent)
@@ -1,46 +0,0 @@
-#
-# Find the KDevelop Platform modules and sets various variables accordingly
-#
-# Example usage of this module:
-# find_package(KDevPlatform 1.0.0 REQUIRED)
-#
-# The version number and REQUIRED flag are optional. You can set CMAKE_PREFIX_PATH
-# variable to help it find the required files and directories
-
-# KDEVPLATFORM_FOUND - set to TRUE if the platform was found and the version is compatible FALSE otherwise
-#
-# KDEVPLATFORM_VERSION - The version number of kdevplatform
-# KDEVPLATFORM_VERSION_MAJOR - The major version number of kdevplatform
-# KDEVPLATFORM_VERSION_MINOR - The minor version number of kdevplatform
-# KDEVPLATFORM_VERSION_PATCH - The patch version number of kdevplatform
-# KDEVPLATFORM_INCLUDE_DIR - include dir of the platform, for example /usr/include/kdevplatform
-# KDEVPLATFORM_INTERFACES_LIBRARIES - interfaces module library
-# KDEVPLATFORM_LANGUAGE_LIBRARIES - language module library
-# KDEVPLATFORM_OUTPUTVIEW_LIBRARIES - outputview module library
-# KDEVPLATFORM_PROJECT_LIBRARIES - project module library
-# KDEVPLATFORM_SUBLIME_LIBRARIES - sublime module library
-# KDEVPLATFORM_SHELL_LIBRARIES - shell module library
-# KDEVPLATFORM_TESTS_LIBRARIES - library to write tests for plugins,
-# contains some useful tools and a way to replace parts of Core
-# classes with custom implementations
-# KDEVPLATFORM_UTIL_LIBRARIES - util module library
-# KDEVPLATFORM_VCS_LIBRARIES - vcs module library
-# KDEVPLATFORM_SOURCEFORMATTER_LIBRARIES - source formatter library
-# KDEVPLATFORM_DEBUGGER_LIBRARIES - debugger module library
-#
-# The following macros are added (from KDevPlatformMacros.cmake):
-#
-# KDEVPLATFORM_ADD_APP_TEMPLATES( template1 ... templateN )
-# Use this to get packaged template archives for the given templates.
-# Parameters should be the directories containing the templates.
-#
-# Copyright 2007 Andreas Pakulat <apaku@gmx.de>
-# Redistribution and use is allowed according to the terms of the BSD license.
-
-set(_KDevPlatform_FIND_QUIETLY ${KDevPlatform_FIND_QUIETLY})
-find_package( KDevPlatform ${KDevPlatform_FIND_VERSION} NO_MODULE )
-set(KDevPlatform_FIND_QUIETLY ${_KDevPlatform_FIND_QUIETLY})
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(KDevPlatform DEFAULT_MSG KDevPlatform_CONFIG )
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/cmake/FindKDevPlatform.cmake
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/kcm_kdevautomake_settings.desktop (nonexistent)
@@ -1,62 +0,0 @@
-[Desktop Entry]
-Icon=kdevelop
-Type=Service
-ServiceTypes=KCModule
-
-X-KDE-ModuleType=Library
-X-KDE-Library=kcm_kdevautomake_settings
-X-KDE-FactoryName=kcm_kdevautomake_settings
-X-KDE-ParentApp=kdevplatformproject
-X-KDE-ParentComponents=KDevAutotoolsImporter
-X-KDE-CfgDlgHierarchy=BUILDTOOL
-
-Name=Automake
-Name[bs]=Automake
-Name[ca]=Automake
-Name[ca@valencia]=Automake
-Name[de]=Automake
-Name[en_GB]=Automake
-Name[eo]=Automake
-Name[es]=Automake
-Name[et]=Automake
-Name[fr]=Automake
-Name[ga]=Automake
-Name[gl]=Automake
-Name[hu]=Automake
-Name[it]=Automake
-Name[ms]=Automake
-Name[nds]=Automake
-Name[nl]=Automake
-Name[pl]=Automake
-Name[pt]=Automake
-Name[pt_BR]=Automake
-Name[sk]=Automake
-Name[sv]=Automake
-Name[tr]=Automake
-Name[ug]=Automake
-Name[uk]=Automake
-Name[x-test]=xxAutomakexx
-Comment=Configure Automake settings
-Comment[bs]=Konfiguracija Automake postavki
-Comment[ca]=Configura els arranjaments d'Automake
-Comment[ca@valencia]=Configura els arranjaments d'Automake
-Comment[de]=Automake-Einstellungen festlegen
-Comment[en_GB]=Configure Automake settings
-Comment[es]=Configurar preferencias de Automake
-Comment[et]=Automake'i seadistamine
-Comment[fr]=Configure les paramètres Automake
-Comment[ga]=Cumraigh socruithe Automake
-Comment[gl]=Configurar as opcións de Automake
-Comment[hu]=Automake beállítások módosítása
-Comment[it]=Configura le impostazioni di Automake
-Comment[ms]=Konfigur Tetapan Automake
-Comment[nds]=Automake instellen
-Comment[nl]=Configureert Automake instellingen
-Comment[pl]=Ustawienia Automake
-Comment[pt]=Configurar as opções do Automake
-Comment[pt_BR]=Configurar as opções do Automake
-Comment[sv]=Anpassa Automake-inställningar
-Comment[tr]=Automake ayarlarını yapılandır
-Comment[uk]=Налаштувати параметри Automake
-Comment[x-test]=xxConfigure Automake settingsxx
-
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.h (nonexistent)
@@ -1,92 +0,0 @@
-/* This file is part of KDevelop
- Copyright 2004 Roberto Raggi <roberto@kdevelop.org>
- Copyright 2009 Robert Gruber <rgruber@users.sourceforge.net>
-
- 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.
-*/
-#ifndef AUTOMAKEPROJECTMODEL_H
-#define AUTOMAKEPROJECTMODEL_H
-
-#include <QList>
-#include <QIcon>
-#include <kdevplatform/project/projectmodel.h>
-#include "makefileinterface.h"
-
-namespace AutoTools { class ProjectAST; }
-
-class AutoMakeDirItem : public KDevelop::ProjectBuildFolderItem
-{
-public:
- explicit AutoMakeDirItem( KDevelop::IProject*, const KUrl& url, KDevelop::ProjectBaseItem* parent = 0 );
- virtual ~AutoMakeDirItem();
-
- virtual KDevelop::ProjectFolderItem* folder() const
- {
- return const_cast<AutoMakeDirItem*>( this );
- }
-
- void parseInfoFromAst( AutoTools::ProjectAST* ) {}
-
-};
-
-class AutoMakeFileItem : public KDevelop::ProjectFileItem
-{
-public:
- explicit AutoMakeFileItem( KDevelop::IProject*, const KUrl& url, KDevelop::ProjectBaseItem* parent = 0 );
- virtual ~AutoMakeFileItem();
-
- virtual KDevelop::ProjectFileItem* file() const
- {
- return const_cast<AutoMakeFileItem*>( this );
- }
-};
-
-class AutoMakeTargetItem : public KDevelop::ProjectTargetItem
-{
-public:
- explicit AutoMakeTargetItem( KDevelop::IProject*, const TargetInfo& target, KDevelop::ProjectBaseItem* parent = 0 );
-
- virtual ~AutoMakeTargetItem();
-
- virtual KDevelop::ProjectTargetItem* target() const
- {
- return const_cast<AutoMakeTargetItem*>( this );
- }
-
- virtual const KUrl::List& includeDirectories() const { return m_includes; }
- virtual const QHash<QString, QString>& environment() const { return m_environment; }
- virtual const QList<QPair<QString, QString> >& defines() const { return m_defines; }
- void parseInfoFromAst( AutoTools::ProjectAST* ) {}
-
-
-private:
- TargetInfo m_target;
- KUrl::List m_includes;
- QHash<QString, QString> m_environment;
- QList<QPair<QString, QString> > m_defines;
-};
-
-class AutoMakeBaseItem : public KDevelop::ProjectBaseItem
-{
-public:
- explicit AutoMakeBaseItem( KDevelop::IProject*, const QString& target, KDevelop::ProjectBaseItem* parent = 0 );
- virtual ~AutoMakeBaseItem();
-
- virtual int type() const;
-};
-
-#endif // AUTOMAKEPROJECTMODEL_H
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeprojectmodel.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.cpp
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.cpp (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.cpp (nonexistent)
@@ -1,109 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#include "automakeast.h"
-
-namespace AutoMake {
-
-//AST
-
-AST::~AST()
-{
- qDeleteAll( m_children );
-}
-
-void AST::addChildAST(AST *node)
-{
- m_children.append(node);
-}
-
-void AST::writeBack(QString &buffer)
-{
- foreach( AST* a, m_children )
- {
- a->writeBack(buffer);
- }
-}
-
-QString AST::indentation()
-{
- QString result;
- for (int i = 0; i < depth(); i++)
- result += '\t';
- return result;
-}
-
-bool AST::hasChildren() const
-{
- return !m_children.isEmpty();
-}
-
-QList<AST*> AST::children() const
-{
- return m_children;
-}
-
-//ProjectAST
-
-void ProjectAST::writeBack(QString &buffer)
-{
- if ( isRule() )
- buffer += scopedID;
- else
- buffer += indentation();
-
- AST::writeBack(buffer);
-
-}
-
-void ProjectAST::addChildAST(AST *node)
-{
- statements.append(node);
- AST::addChildAST(node);
-}
-
-void AssignmentAST::writeBack(QString &buffer)
-{
- buffer += indentation() + scopedID + ' ' + op + ' ' + values.join(" ");
-}
-
-void AutomakeTargetAST::writeBack( QString& buffer )
-{
- buffer += target + ':' + deps.join("");
-}
-
-void ConditionAST::writeBack( QString& buffer )
-{
- buffer += indentation() + type + ' ' + conditionName;
-}
-
-void NewLineAST::writeBack(QString &buffer)
-{
- buffer += '\n';
-}
-
-void CommentAST::writeBack(QString &buffer)
-{
- buffer += indentation() + comment;
-}
-
-}
-
-// kate: indent-mode csands; tab-width 4; space-indent off;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automakeast.cpp
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.ll
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.ll (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.ll (nonexistent)
@@ -1,136 +0,0 @@
-%{
-/***************************************************************************
- * Copyright 2006 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-#include "autoconfparser.h"
-#include <stdlib.h>
-
-/**
-@file autoconf.ll
-Autoconf Lexer
-
-There are 3 types of identifiers recognized by this lexer:
--id_simple: examples of such identifiers are qmake variables and scoped variables
-at the left of the operator in assignments (like "SOURCES" in "SOURCES+=foo.cpp goo.cpp");
--id_list: those are "value list identifiers" at the right side in assignments
-(like "foo.cpp goo.cpp" in "SOURCES+=foo.cpp goo.cpp");
--id_args: function arguments recognized as one identifier
-(example: ""${QMAKE_FILE} is intended only for Windows!""
-in "!win32-*:!wince-*:error("${QMAKE_FILE} is intended only for Windows!")" statements).
-.
-
-To recognize those identifiers two additional start conditions are used: list and funcargs.
-
-@note "Not" operator (!) is recognized as a part of an identifier. Linefeeds passed to
-the parser as NEWLINE tokens to preserve file structure but whitespaces are stripped
-so no indentation is preserved by this lexer (and parser).
-
-To debug this lexer, put the line below into the next flex file section.
-%option debug
-*/
-%}
-%option noyywrap
-%x list
-%x funcargs
-%x conditional
-
-delim [ \t]
-ws {delim}+
-letter [A-Za-z]
-digit [0-9]
-id_simple ({digit}|{letter}|\!|-|_|\*|\$|@)({letter}|{digit}|\||\!|-|_|\*|\$|\(|\.|\+|\-|\)|\/)*
-id_list [^\n#]*\\{ws}*
-id_args [^\n]*\)
-number {digit}+
-comment #.*
-comment_cont {ws}#.*\n
-id_list_single [^\n]*
-cont \\{ws}*\n
-keywords (if|else|endif|include)
-rule [\t]+[^\n]*
-
-%%
-
-<list,INITIAL>{ws} {}
-<list,INITIAL>{cont} { BEGIN(list); return CONT; }
-{keywords} {
- yylval.value = yytext;
- if ( yylval.value == "if" )
- return IF_KEYWORD;
-
- if ( yylval.value == "else" )
- return ELSE_KEYWORD;
-
- if ( yylval.value == "endif" )
- return ENDIF_KEYWORD;
-
- return KEYWORD;
-}
-
-
-{id_simple} { yylval.value = yytext; return (ID_SIMPLE); }
-
-<INITIAL>{rule} {
- yylval.value = yytext;
- return RULE;
-}
-
-<list>{id_list} {
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.lastIndexOf("\\"));
- unput('\\');
- BEGIN(INITIAL);
- return (ID_LIST);
- }
-
-<list>{comment_cont} {
- yylval.value = yytext;
- BEGIN(list);
- return (LIST_COMMENT);
- }
-
-<list>{comment} {
- yylval.value = yytext;
- return LIST_COMMENT;
- }
-
-<list>{id_list_single} {
- yylval.value = yytext;
- BEGIN(INITIAL);
- return (ID_LIST_SINGLE);
- }
-
-<funcargs>{id_args} {
- yylval.value = yytext;
- yylval.value = yylval.value.mid(0, yylval.value.length()-1);
- unput(')');
- BEGIN(INITIAL);
- return (ID_ARGS);
- }
-
-"=" { BEGIN(list); yylval.value = yytext; return EQ; }
-"+=" { BEGIN(list); yylval.value = yytext; return PLUSEQ; }
-"{" { return LCURLY; }
-"}" { return RCURLY; }
-":" { BEGIN(list); yylval.value = yytext; return COLON; }
-<list,INITIAL>"\n" { BEGIN(INITIAL); return NEWLINE; }
-{comment} { yylval.value = yytext; return (COMMENT); }
-
-%%
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autoconf.ll
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.yy
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.yy (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.yy (nonexistent)
@@ -1,322 +0,0 @@
-%{
-/***************************************************************************
- * Copyright (C) 2005 by Alexander Dymo <adymo@kdevelop.org> *
- * *
- * Copyright (c) 2005 by Matt Rogers <mattr@kde.org> *
- * *
- * This program 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 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 Library General Public *
- * License along with this program; if not, write to the *
- * Free Software Foundation, Inc., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-/**
-@file autotools.yy
-Autotools Parser
-
-Simple LALR parser which builds the syntax tree (see @ref Autotools::AST).
-
-@todo Recognize comments after statements like:
-noinst_HEADERS = foo.h #regognize me
-
-@fixme Parser fails on files that do not end with a newline
-@fixme 1 shift/reduce conflict in "line_body" rule
-*/
-
-
-#include <qstack.h>
-#include "automakeast.h"
-
-#define YYSTYPE_IS_DECLARED
-
-using namespace AutoMake;
-
-/**
-The yylval type.
-*/
-typedef struct Result {
- Result(): node(0) {}
-
- /**Type of semantic value for simple grammar rules.*/
- QString value;
- /**Type of semantic value for grammar rules which are parts of AST.*/
- AST *node;
- /**Type of semantic value for "multiline_values" grammar rule.
- Each line of multiline value is stored as a string in the list.
-
- For example we have in Makefile.am file:
- @code
- foo_SOURCES = foo1.cpp \
- foo2.cpp \
- foo3.cpp foo4.cpp
- @endcode
- The string list will be populated with three strings:
- <pre>
- foo1.cpp
- foo2.cpp
- foo3.cpp foo4.cpp
- </pre>
- */
- QStringList values;
-} YYSTYPE;
-
-
-void yyerror(const char *str) {
- qWarning("bison error: %s\n", str);
-}
-
-int yylex();
-
-/**
-The stack to store ProjectAST pointers when a new child
-ProjectAST is created and filled with statements.
-
-Parser creates root ProjectAST for a .pro file, pushes it onto the stack and starts
-adding statements. Each statement is added as a child StatementAST to the ProjectAST
-currently on the top in the stack.
-
-When a scope or function scope statement is parsed, the child ProjectAST is created
-and pushed onto the stack. Therefore all statements which belong to the scope
-or function scope are added as childs to their direct parent (scope or function scope).
-*/
-QStack<ProjectAST*> projects;
-
-/**
-The current depth of AST node is stored here.
-AST depth is important to know because automatic indentation can
-be easily implemented (the parser itself looses all information
-about indentation).
-*/
-int depth = 0;
-
-/*
-To debug this parser, put the line below into the next bison file section.
-Don't forget to uncomment "yydebug = 1" line in autotoolsdriver.cpp.
-%debug
-*/
-%}
-%debug
-%token ID_SIMPLE
-%token ID_LIST
-%token LBRACE
-%token EQ
-%token PLUSEQ
-%token MINUSQE
-%token STAREQ
-%token TILDEEQ
-%token LBRACE
-%token RBRACE
-%token COLON
-%token NUMSIGN
-%token NEWLINE
-%token NUMBER
-%token COMMENT
-%token CONT
-%token DOT
-%token RCURLY
-%token LCURLY
-%token ID_ARGS
-%token LIST_COMMENT
-%token ID_LIST_SINGLE
-%token IF_KEYWORD
-%token ELSE_KEYWORD
-%token ENDIF_KEYWORD
-%token KEYWORD
-%token RULE
-
-%%
-
-project :
-{
- ProjectAST *projectAST = new ProjectAST();
- projects.push(projectAST);
-}
-statements
-;
-
-statements : statements statement
-{
- projects.top()->addChildAST($<node>2);
-
- if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "if" )
- {
- $<node>2->setDepth(depth);
- depth++;
- }
- else if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "else" )
- {
- --depth;
- $<node>2->setDepth(depth);
- ++depth;
- }
- else if ( $<node>2->nodeType() == AST::ProjectAST &&
- static_cast<ProjectAST*>( $<node>2 )->scopedID == "endif" )
- {
- --depth;
- $<node>2->setDepth(depth);
- }
- else
- $<node>2->setDepth(depth);
-}
-|
-;
-
-statement : variable_assignment
-{
- $<node>$ = $<node>1;
-}
-| automake_if
-{
- $<node>$ = $<node>1;
-}
-| else_statement
-{
- $<node>$ = $<node>1;
-}
-| endif_statement
-{
- $<node>$ = $<node>1;
-}
-| target
-{
- $<node>$ = $<node>1;
-}
-| am_rule
-{
- $<node>$ = $<node>1;
-}
-| include_directive
-{
- $<node>$ = $<node>1;
-}
-| comment
-{
- $<node>$ = $<node>1;
-}
-| emptyline
-{
- $<node>$ = new NewLineAST();
-}
-;
-
-automake_if: IF_KEYWORD scoped_identifier
-{
- ConditionAST* projectAST = new ConditionAST();
- projectAST->type = "if";
- projectAST->conditionName = $<value>2;
- $<node>$ = projectAST;
-};
-
-endif_statement: ENDIF_KEYWORD
-{
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- $<node>$ = past;
-}
-| ENDIF_KEYWORD scoped_identifier
-{
- ConditionAST* past = new ConditionAST();
- past->type= "endif";
- past->conditionName = $<value>2;
- $<node>$ = past;
-}
-;
-
-else_statement: ELSE_KEYWORD
-{
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- $<node>$ = past;
-}
-| ELSE_KEYWORD scoped_identifier
-{
- ConditionAST* past = new ConditionAST();
- past->type = "else";
- past->conditionName = $<value>2;
- $<node>$ = past;
-}
-;
-
-variable_assignment : scoped_identifier operator multiline_values
-{
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = $<value>1;
- node->op = $<value>2;
- node->values = $<values>3;
- $<node>$ = node;
-}
-;
-
-scoped_identifier : ID_SIMPLE scoped_identifier
-{ $<value>$ = $<value>1 + $<value>2; }
-| ID_SIMPLE
-;
-
-multiline_values : multiline_values line_body
-{
- QStringList list = $<value>2.split(QRegExp("\\s+"), QString::SkipEmptyParts);
- $<values>$ = $<values>$ + list; //.append($<value>2);
-}
-| { $<values>$.clear(); }
- ;
-
-line_body : ID_LIST CONT { $<value>$ = $<value>1 + " \\\n"; }
- | ID_LIST_SINGLE NEWLINE { $<value>$ = $<value>1 + "\n"; }
- | CONT { $<value>$ = "\\\n"; }
- | LIST_COMMENT
- ;
-
-target: scoped_identifier COLON multiline_values
-{
- AutomakeTargetAST *node = new AutomakeTargetAST();
- node->target = $<value>1;
- node->deps = $<values>3;
- $<node>$ = node;
-}
-;
-
-am_rule: RULE
-{
- ProjectAST* node = new ProjectAST(ProjectAST::Rule);
- node->scopedID = $<value>1;
- $<node>$ = node;
-}
-;
-
-include_directive: KEYWORD scoped_identifier
-{
- AssignmentAST *node = new AssignmentAST();
- node->scopedID = $<value>1;
- node->values = QStringList($<value>2);
- $<node>$ = node;
-}
-;
-
-operator : EQ | PLUSEQ
-;
-
-comment : COMMENT NEWLINE
-{
- CommentAST *node = new CommentAST();
- node->comment = $<value>1 + "\n";
- $<node>$ = node;
-}
-;
-
-emptyline : NEWLINE
-;
-%%
-
-#include "automake_lex.cpp"
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/automake.yy
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autotoolsparser.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/autotoolsparser.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/autotoolsparser.h (nonexistent)
@@ -1,101 +0,0 @@
-/* A Bison parser, made by GNU Bison 2.1. */
-
-/* Skeleton parser for Yacc-like parsing with Bison,
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
-
- 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, 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., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA. */
-
-/* As a special exception, when this file is copied by Bison into a
- Bison output file, you may use that output file without restriction.
- This special exception was added by the Free Software Foundation
- in version 1.24 of Bison. */
-
-/* Tokens. */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
- /* Put the tokens into the symbol table, so that GDB and other debuggers
- know about them. */
- enum yytokentype {
- ID_SIMPLE = 258,
- ID_LIST = 259,
- LBRACE = 260,
- EQ = 261,
- PLUSEQ = 262,
- MINUSQE = 263,
- STAREQ = 264,
- TILDEEQ = 265,
- RBRACE = 266,
- COLON = 267,
- NUMSIGN = 268,
- NEWLINE = 269,
- NUMBER = 270,
- COMMENT = 271,
- CONT = 272,
- DOT = 273,
- RCURLY = 274,
- LCURLY = 275,
- ID_ARGS = 276,
- LIST_COMMENT = 277,
- ID_LIST_SINGLE = 278,
- IF_KEYWORD = 279,
- ELSE_KEYWORD = 280,
- ENDIF_KEYWORD = 281,
- KEYWORD = 282,
- RULE = 283
- };
-#endif
-/* Tokens. */
-#define ID_SIMPLE 258
-#define ID_LIST 259
-#define LBRACE 260
-#define EQ 261
-#define PLUSEQ 262
-#define MINUSQE 263
-#define STAREQ 264
-#define TILDEEQ 265
-#define RBRACE 266
-#define COLON 267
-#define NUMSIGN 268
-#define NEWLINE 269
-#define NUMBER 270
-#define COMMENT 271
-#define CONT 272
-#define DOT 273
-#define RCURLY 274
-#define LCURLY 275
-#define ID_ARGS 276
-#define LIST_COMMENT 277
-#define ID_LIST_SINGLE 278
-#define IF_KEYWORD 279
-#define ELSE_KEYWORD 280
-#define ENDIF_KEYWORD 281
-#define KEYWORD 282
-#define RULE 283
-
-
-
-
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-typedef int YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
-#endif
-
-extern YYSTYPE yylval;
-
-
-
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/autotoolsparser.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.h
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.h (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.h (nonexistent)
@@ -1,102 +0,0 @@
-/* KDevelop Automake Support
- *
- * Copyright (C) 2005 Matt Rogers <mattr@kde.org>
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301, USA.
- */
-
-#ifndef MAKEFILEINTERFACE_H
-#define MAKEFILEINTERFACE_H
-
-#include <QObject>
-#include <QRegExp>
-#include <QDir>
-#include <kurl.h>
-
-class QFileInfo;
-
-namespace AutoMake
-{
- class ProjectAST;
- enum TargetType { Program, Library, LibtoolLibrary, Lisp, Python, Java,
- Scripts, Data, Headers, ManPages, Texinfo, Unknown };
- enum InstallLocation { Bin, Libexec, Lib, None, Check, Info, Man, Custom };
-
- const QRegExp targetPrimaries = QRegExp( "_(PROGRAMS|LIBRARIES|LISP|PYTHON|JAVA|SCRIPTS|DATA|HEADERS|MANS|TEXINFOS|LTLIBRARIES)" );
-
- TargetType convertToType( const QString& );
- InstallLocation convertToLocation( const QString& );
-
-}
-
-template <typename T> class QList;
-template <typename T1, typename T2> class QMap;
-template <typename T1, typename T2> class QHash;
-
-typedef QHash<QFileInfo, AutoMake::ProjectAST*> AutoMakeASTHash;
-typedef QMap<QFileInfo, AutoMake::ProjectAST*> AutoMakeASTMap;
-typedef QList<AutoMake::ProjectAST*> AutoMakeASTList;
-
-struct TargetInfo
-{
- AutoMake::TargetType type;
- AutoMake::InstallLocation location;
- QString name;
- KUrl url;
- QString display;
-};
-
-class MakefileInterface : public QObject
-{
- Q_OBJECT
-public:
- enum ParserRecursion { Recursive, NonRecursive };
- enum TargetType { Program, Library, LibtoolLibrary, Lisp, Python, Java,
- Scripts, Data, Headers, ManPages, Texinfo };
- enum InstallLocations { Bin, Libexec, Lib, None, Check, Info, Man, Extra };
-
- MakefileInterface( QObject* parent );
- ~MakefileInterface();
-
- static QString canonicalize( const QString& target );
- static bool isVariable( const QString& item );
-
- QString resolveVariable( const QString& variable, AutoMake::ProjectAST* ast ) const;
-
- bool parse( const KUrl& dir, ParserRecursion recursive = Recursive );
-
- QString projectRoot() const;
- void setProjectRoot( const KUrl& dir );
- QStringList topSubDirs() const;
- QStringList subdirsFor( const KUrl& dir ) const;
-
- QList<TargetInfo> targetsForFolder( const KUrl& dir ) const;
- QList<QFileInfo> filesForTarget( const TargetInfo& ) const;
-
-private:
- QStringList subdirsFor( AutoMake::ProjectAST* ) const;
- AutoMake::ProjectAST* astForFolder( const KUrl& dir ) const;
- QStringList valuesForId( const QString&, AutoMake::ProjectAST* ) const;
-
-private:
- class Private;
- Private* d;
-
-};
-
-#endif
-
-//kate: hl c++;
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake/makefileinterface.h
___________________________________________________________________
Deleted: svn:eol-style
## -1 +0,0 ##
-native
\ No newline at end of property
Index: trunk/playground/devtools/kdevelop4-extra-plugins/automake
===================================================================
--- trunk/playground/devtools/kdevelop4-extra-plugins/automake (revision 1522569)
+++ trunk/playground/devtools/kdevelop4-extra-plugins/automake (nonexistent)
Property changes on: trunk/playground/devtools/kdevelop4-extra-plugins/automake
___________________________________________________________________
Deleted: svn:ignore
## -1,4 +0,0 ##
-.libs
-Makefile
-Makefile.in
-*.moc