diff --git a/libs/widgets/KoCsvImportDialog.cpp b/libs/widgets/KoCsvImportDialog.cpp index 0ffdcf62a70..cdca006dc62 100644 --- a/libs/widgets/KoCsvImportDialog.cpp +++ b/libs/widgets/KoCsvImportDialog.cpp @@ -1,786 +1,787 @@ /* This file is part of the KDE project Copyright (C) 1999 David Faure Copyright (C) 2004 Nicolas GOUTTE 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 "KoCsvImportDialog.h" // Qt +#include #include #include #include #include // KF5 #include #include #include #include #include #include #include "ui_KoCsvImportDialog.h" class KoCsvImportWidget : public QWidget, public Ui::KoCsvImportWidget { Q_OBJECT public: explicit KoCsvImportWidget(QWidget* parent) : QWidget(parent) { setupUi(this); } }; class Q_DECL_HIDDEN KoCsvImportDialog::Private { public: KoCsvImportDialog* q; KoCsvImportWidget* dialog; bool rowsAdjusted; bool columnsAdjusted; int startRow; int startCol; int endRow; int endCol; QChar textQuote; QString delimiter; QString commentSymbol; bool ignoreDuplicates; QByteArray data; QTextCodec* codec; QStringList formatList; ///< List of the column formats explicit Private(KoCsvImportDialog* qq) : q(qq) {} void loadSettings(); void saveSettings(); void fillTable(); void setText(int row, int col, const QString& text); void adjustRows(int iRows); void adjustCols(int iCols); bool checkUpdateRange(); QTextCodec* updateCodec() const; }; KoCsvImportDialog::KoCsvImportDialog(QWidget* parent) : KoDialog(parent) , d(new Private(this)) { d->dialog = new KoCsvImportWidget(this); d->rowsAdjusted = false; d->columnsAdjusted = false; d->startRow = 0; d->startCol = 0; d->endRow = -1; d->endCol = -1; d->textQuote = QChar('"'); d->delimiter = QString(','); d->commentSymbol = QString('#'); d->ignoreDuplicates = false; d->codec = QTextCodec::codecForName("UTF-8"); setButtons( KoDialog::Ok|KoDialog::Cancel ); setCaption( i18n( "Import Data" ) ); QStringList encodings; encodings << i18nc( "Descriptive encoding name", "Recommended ( %1 )" ,"UTF-8" ); encodings << i18nc( "Descriptive encoding name", "Locale ( %1 )" ,QString(QTextCodec::codecForLocale()->name() )); encodings += KCharsets::charsets()->descriptiveEncodingNames(); // Add a few non-standard encodings, which might be useful for text files const QString description(i18nc("Descriptive encoding name","Other ( %1 )")); encodings << description.arg("Apple Roman"); // Apple encodings << description.arg("IBM 850") << description.arg("IBM 866"); // MS DOS encodings << description.arg("CP 1258"); // Windows d->dialog->comboBoxEncoding->insertItems( 0, encodings ); setDataTypes(Generic|Text|Date|None); // XXX: Qt3->Q4 //d->dialog->m_sheet->setReadOnly( true ); d->loadSettings(); //resize(sizeHint()); resize( 600, 400 ); // Try to show as much as possible of the table view setMainWidget(d->dialog); d->dialog->m_sheet->setSelectionMode( QAbstractItemView::MultiSelection ); QButtonGroup* buttonGroup = new QButtonGroup( this ); buttonGroup->addButton(d->dialog->m_radioComma, 0); buttonGroup->addButton(d->dialog->m_radioSemicolon, 1); buttonGroup->addButton(d->dialog->m_radioSpace, 2); buttonGroup->addButton(d->dialog->m_radioTab, 3); buttonGroup->addButton(d->dialog->m_radioOther, 4); connect(d->dialog->m_formatComboBox, SIGNAL(activated(QString)), this, SLOT(formatChanged(QString))); connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(delimiterClicked(int))); connect(d->dialog->m_delimiterEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed())); connect(d->dialog->m_delimiterEdit, SIGNAL(textChanged(QString)), this, SLOT(genericDelimiterChanged(QString))); connect(d->dialog->m_comboQuote, SIGNAL(activated(QString)), this, SLOT(textquoteSelected(QString))); connect(d->dialog->m_sheet, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(currentCellChanged(int,int))); connect(d->dialog->m_ignoreDuplicates, SIGNAL(stateChanged(int)), this, SLOT(ignoreDuplicatesChanged(int))); connect(d->dialog->m_updateButton, SIGNAL(clicked()), this, SLOT(updateClicked())); connect(d->dialog->comboBoxEncoding, SIGNAL(textChanged(QString)), this, SLOT(encodingChanged(QString))); } KoCsvImportDialog::~KoCsvImportDialog() { d->saveSettings(); delete d; } // ---------------------------------------------------------------- // public methods void KoCsvImportDialog::setData( const QByteArray& data ) { d->data = data; d->fillTable(); } bool KoCsvImportDialog::firstRowContainHeaders() const { return d->dialog->m_firstRowHeader->isChecked(); } bool KoCsvImportDialog::firstColContainHeaders() const { return d->dialog->m_firstColHeader->isChecked(); } int KoCsvImportDialog::rows() const { int rows = d->dialog->m_sheet->rowCount(); if ( d->endRow >= 0 ) rows = d->endRow - d->startRow + 1; return rows; } int KoCsvImportDialog::cols() const { int cols = d->dialog->m_sheet->columnCount(); if ( d->endCol >= 0 ) cols = d->endCol - d->startCol + 1; return cols; } QString KoCsvImportDialog::text(int row, int col) const { // Check for overflow. if ( row >= rows() || col >= cols()) return QString(); QTableWidgetItem* item = d->dialog->m_sheet->item( row - d->startRow, col - d->startCol ); if ( !item ) return QString(); return item->text(); } void KoCsvImportDialog::setDataTypes(DataTypes dataTypes) { d->formatList.clear(); if (dataTypes & Generic) d->formatList << i18n("Generic"); if (dataTypes & Text) d->formatList << i18n("Text"); if (dataTypes & Date) d->formatList << i18n("Date"); if (dataTypes & Currency) d->formatList << i18n("Currency"); if (dataTypes & None) d->formatList << i18n("None"); d->dialog->m_formatComboBox->insertItems(0, d->formatList); } void KoCsvImportDialog::setDataWidgetEnabled(bool enable) { d->dialog->m_tabWidget->setTabEnabled(0, enable); } QString KoCsvImportDialog::decimalSymbol() const { return d->dialog->m_decimalSymbol->text(); } void KoCsvImportDialog::setDecimalSymbol(const QString& symbol) { d->dialog->m_decimalSymbol->setText(symbol); } QString KoCsvImportDialog::thousandsSeparator() const { return d->dialog->m_thousandsSeparator->text(); } void KoCsvImportDialog::setThousandsSeparator(const QString& separator) { d->dialog->m_thousandsSeparator->setText(separator); } QString KoCsvImportDialog::delimiter() const { return d->delimiter; } void KoCsvImportDialog::setDelimiter(const QString& delimit) { d->delimiter = delimit; if (delimit == ",") d->dialog->m_radioComma->setChecked(true); else if (delimit == "\t") d->dialog->m_radioTab->setChecked(true); else if (delimit == " ") d->dialog->m_radioSpace->setChecked(true); else if (delimit == ";") d->dialog->m_radioSemicolon->setChecked(true); else { d->dialog->m_radioOther->setChecked(true); d->dialog->m_delimiterEdit->setText(delimit); } } // ---------------------------------------------------------------- void KoCsvImportDialog::Private::loadSettings() { KConfigGroup configGroup = KSharedConfig::openConfig()->group("CSVDialog Settings"); textQuote = configGroup.readEntry("textQuote", "\"").at(0); delimiter = configGroup.readEntry("delimiter", ","); ignoreDuplicates = configGroup.readEntry("ignoreDups", false); const QString codecText = configGroup.readEntry("codec", ""); // update widgets if (!codecText.isEmpty()) { dialog->comboBoxEncoding->setCurrentIndex(dialog->comboBoxEncoding->findText(codecText)); codec = updateCodec(); } q->setDelimiter(delimiter); dialog->m_ignoreDuplicates->setChecked(ignoreDuplicates); dialog->m_comboQuote->setCurrentIndex(textQuote == '\'' ? 1 : textQuote == '"' ? 0 : 2); } void KoCsvImportDialog::Private::saveSettings() { KConfigGroup configGroup = KSharedConfig::openConfig()->group("CSVDialog Settings"); configGroup.writeEntry("textQuote", QString(textQuote)); configGroup.writeEntry("delimiter", delimiter); configGroup.writeEntry("ignoreDups", ignoreDuplicates); configGroup.writeEntry("codec", dialog->comboBoxEncoding->currentText()); configGroup.sync(); } void KoCsvImportDialog::Private::fillTable() { int row, column; bool lastCharDelimiter = false; enum { Start, InQuotedField, MaybeQuotedFieldEnd, QuotedFieldEnd, MaybeInNormalField, InNormalField } state = Start; QChar x; QString field; QApplication::setOverrideCursor(Qt::WaitCursor); dialog->m_sheet->setRowCount(0); dialog->m_sheet->setColumnCount(0); int maxColumn = 1; row = column = 1; QTextStream inputStream(data, QIODevice::ReadOnly); debugWidgets <<"Encoding:" << codec->name(); inputStream.setCodec( codec ); int delimiterIndex = 0; const int delimiterLength = delimiter.size(); bool lastCharWasCr = false; // Last character was a Carriage Return while (!inputStream.atEnd()) { inputStream >> x; // read one char // ### TODO: we should perhaps skip all other control characters if ( x == '\r' ) { // We have a Carriage Return, assume that its role is the one of a LineFeed lastCharWasCr = true; x = '\n'; // Replace by Line Feed } else if ( x == '\n' && lastCharWasCr ) { // The end of line was already handled by the Carriage Return, so do nothing for this character lastCharWasCr = false; continue; } else if ( x == QChar( 0xc ) ) { // We have a FormFeed, skip it lastCharWasCr = false; continue; } else { lastCharWasCr = false; } if ( column > maxColumn ) maxColumn = column; switch (state) { case Start : if (x == textQuote) { state = InQuotedField; } else if (delimiterIndex < delimiterLength && x == delimiter.at(delimiterIndex)) { field += x; delimiterIndex++; if (field.right(delimiterIndex) == delimiter) { if ((ignoreDuplicates == false) || (lastCharDelimiter == false)) column += delimiterLength; lastCharDelimiter = true; field.clear(); delimiterIndex = 0; state = Start; } else if (delimiterIndex >= delimiterLength) delimiterIndex = 0; } else if (x == '\n') { ++row; column = 1; if ( row > ( endRow - startRow ) && endRow >= 0 ) break; } else { field += x; state = MaybeInNormalField; } break; case InQuotedField : if (x == textQuote) { state = MaybeQuotedFieldEnd; } else if (x == '\n') { setText(row - startRow, column - startCol, field); field.clear(); ++row; column = 1; if ( row > ( endRow - startRow ) && endRow >= 0 ) break; state = Start; } else { field += x; } break; case MaybeQuotedFieldEnd : if (x == textQuote) { field += x; state = InQuotedField; } else if (x == '\n') { setText(row - startRow, column - startCol, field); field.clear(); ++row; column = 1; if ( row > ( endRow - startRow ) && endRow >= 0 ) break; state = Start; } else if (delimiterIndex < delimiterLength && x == delimiter.at(delimiterIndex)) { field += x; delimiterIndex++; if (field.right(delimiterIndex) == delimiter) { setText(row - startRow, column - startCol, field.left(field.count()-delimiterIndex)); field.clear(); if ((ignoreDuplicates == false) || (lastCharDelimiter == false)) column += delimiterLength; lastCharDelimiter = true; field.clear(); delimiterIndex = 0; } else if (delimiterIndex >= delimiterLength) delimiterIndex = 0; state = Start; } else { state = QuotedFieldEnd; } break; case QuotedFieldEnd : if (x == '\n') { setText(row - startRow, column - startCol, field); field.clear(); ++row; column = 1; if ( row > ( endRow - startRow ) && endRow >= 0 ) break; state = Start; } else if (delimiterIndex < delimiterLength && x == delimiter.at(delimiterIndex)) { field += x; delimiterIndex++; if (field.right(delimiterIndex) == delimiter) { setText(row - startRow, column - startCol, field.left(field.count()-delimiterIndex)); field.clear(); if ((ignoreDuplicates == false) || (lastCharDelimiter == false)) column += delimiterLength; lastCharDelimiter = true; field.clear(); delimiterIndex = 0; } else if (delimiterIndex >= delimiterLength) delimiterIndex = 0; state = Start; } else { state = QuotedFieldEnd; } break; case MaybeInNormalField : if (x == textQuote) { field.clear(); state = InQuotedField; break; } state = InNormalField; case InNormalField : if (x == '\n') { setText(row - startRow, column - startCol, field); field.clear(); ++row; column = 1; if ( row > ( endRow - startRow ) && endRow >= 0 ) break; state = Start; } else if (delimiterIndex < delimiterLength && x == delimiter.at(delimiterIndex)) { field += x; delimiterIndex++; if (field.right(delimiterIndex) == delimiter) { setText(row - startRow, column - startCol, field.left(field.count()-delimiterIndex)); field.clear(); if ((ignoreDuplicates == false) || (lastCharDelimiter == false)) column += delimiterLength; lastCharDelimiter = true; field.clear(); delimiterIndex = 0; } else if (delimiterIndex >= delimiterLength) delimiterIndex = 0; state = Start; } else { field += x; } } if (delimiter.isEmpty() || x != delimiter.at(0)) lastCharDelimiter = false; } if ( !field.isEmpty() ) { // the last line of the file had not any line end setText(row - startRow, column - startCol, field); ++row; field.clear(); } if (row) row--; // row is higher by 1, so reduce it columnsAdjusted = true; adjustRows( row - startRow ); adjustCols( maxColumn - startCol ); for (column = 0; column < dialog->m_sheet->columnCount(); ++column) { const QTableWidgetItem* headerItem = dialog->m_sheet->horizontalHeaderItem(column); if (!headerItem || !formatList.contains(headerItem->text())) { dialog->m_sheet->setHorizontalHeaderItem(column, new QTableWidgetItem(i18n("Generic"))); } } dialog->m_rowStart->setMinimum(1); dialog->m_colStart->setMinimum(1); dialog->m_rowStart->setMaximum(row); dialog->m_colStart->setMaximum(maxColumn); dialog->m_rowEnd->setMinimum(1); dialog->m_colEnd->setMinimum(1); dialog->m_rowEnd->setMaximum(row); dialog->m_colEnd->setMaximum(maxColumn); dialog->m_rowEnd->setValue(endRow == -1 ? row : endRow); dialog->m_colEnd->setValue(endCol == -1 ? maxColumn : endCol); QApplication::restoreOverrideCursor(); } KoCsvImportDialog::DataType KoCsvImportDialog::dataType(int col) const { const QString header = d->dialog->m_sheet->model()->headerData(col, Qt::Horizontal).toString(); if (header == i18n("Generic")) return Generic; else if (header == i18n("Text")) return Text; else if (header == i18n("Date")) return Date; else if (header == i18n("Currency")) return Currency; else if (header == i18n("None")) return None; return Generic; } void KoCsvImportDialog::Private::setText(int row, int col, const QString& text) { if (row < 1 || col < 1) // skipped by the user return; if ((row > (endRow - startRow) && endRow > 0) || (col > (endCol - startCol) && endCol > 0)) return; if (dialog->m_sheet->rowCount() < row) { dialog->m_sheet->setRowCount(row + 5000); /* We add 5000 at a time to limit recalculations */ rowsAdjusted = true; } if (dialog->m_sheet->columnCount() < col) { dialog->m_sheet->setColumnCount(col); columnsAdjusted = true; } QTableWidgetItem* item = dialog->m_sheet->item(row - 1, col - 1); if (!item) { item = new QTableWidgetItem(); dialog->m_sheet->setItem(row - 1, col - 1, item); } item->setText(text); } /* * Called after the first fillTable() when number of rows are unknown. */ void KoCsvImportDialog::Private::adjustRows(int iRows) { if (rowsAdjusted) { dialog->m_sheet->setRowCount(iRows); rowsAdjusted = false; } } void KoCsvImportDialog::Private::adjustCols(int iCols) { if (columnsAdjusted) { dialog->m_sheet->setColumnCount(iCols); columnsAdjusted = false; if (endCol == -1) { if (iCols > (endCol - startCol)) iCols = endCol - startCol; dialog->m_sheet->setColumnCount(iCols); } } } void KoCsvImportDialog::returnPressed() { if (d->dialog->m_radioOther->isChecked()) return; d->delimiter = d->dialog->m_delimiterEdit->text(); d->fillTable(); } void KoCsvImportDialog::genericDelimiterChanged( const QString & ) { d->dialog->m_radioOther->setChecked ( true ); delimiterClicked(d->dialog->m_radioOther->group()->id(d->dialog->m_radioOther)); // other } void KoCsvImportDialog::formatChanged( const QString& newValue ) { QList selectionRanges = d->dialog->m_sheet->selectedRanges(); foreach (const QTableWidgetSelectionRange &selectionRange, selectionRanges) { for (int j = selectionRange.leftColumn(); j <= selectionRange.rightColumn(); ++j) { d->dialog->m_sheet->horizontalHeaderItem(j)->setText(newValue); } } } void KoCsvImportDialog::delimiterClicked(int id) { const QButtonGroup* group = d->dialog->m_radioComma->group(); if (id == group->id(d->dialog->m_radioComma) ) d->delimiter = ','; else if (id == group->id(d->dialog->m_radioOther)) d->delimiter = d->dialog->m_delimiterEdit->text(); else if (id == group->id(d->dialog->m_radioTab)) d->delimiter = '\t'; else if (id == group->id(d->dialog->m_radioSpace)) d->delimiter = ' '; else if (id == group->id(d->dialog->m_radioSemicolon)) d->delimiter = ';'; debugWidgets << "Delimiter" << d->delimiter << "selected."; d->fillTable(); } void KoCsvImportDialog::textquoteSelected(const QString& mark) { if (mark == i18n("None")) d->textQuote = 0; else d->textQuote = mark[0]; d->fillTable(); } void KoCsvImportDialog::updateClicked() { if ( !d->checkUpdateRange() ) return; d->startRow = d->dialog->m_rowStart->value() - 1; d->endRow = d->dialog->m_rowEnd->value(); d->startCol = d->dialog->m_colStart->value() - 1; d->endCol = d->dialog->m_colEnd->value(); d->fillTable(); } bool KoCsvImportDialog::Private::checkUpdateRange() { if ((dialog->m_rowStart->value() > dialog->m_rowEnd->value()) || (dialog->m_colStart->value() > dialog->m_colEnd->value())) { KMessageBox::error(0, i18n("Please check the ranges you specified. The start value must be lower than the end value.")); return false; } return true; } void KoCsvImportDialog::currentCellChanged(int, int col) { const QString header = d->dialog->m_sheet->model()->headerData(col, Qt::Horizontal).toString(); const int index = d->dialog->m_formatComboBox->findText(header); d->dialog->m_formatComboBox->setCurrentIndex(index > -1 ? index : 0); } void KoCsvImportDialog::ignoreDuplicatesChanged(int) { if (d->dialog->m_ignoreDuplicates->isChecked()) d->ignoreDuplicates = true; else d->ignoreDuplicates = false; d->fillTable(); } QTextCodec* KoCsvImportDialog::Private::updateCodec() const { const QString strCodec( KCharsets::charsets()->encodingForName( dialog->comboBoxEncoding->currentText() ) ); debugWidgets <<"Encoding:" << strCodec; bool ok = false; QTextCodec* codec = QTextCodec::codecForName( strCodec.toUtf8() ); // If QTextCodec has not found a valid encoding, so try with KCharsets. if ( codec ) { ok = true; } else { codec = KCharsets::charsets()->codecForName( strCodec, ok ); } // Still nothing? if ( !codec || !ok ) { // Default: UTF-8 warnWidgets << "Cannot find encoding:" << strCodec; // ### TODO: what parent to use? KMessageBox::error( 0, i18n("Cannot find encoding: %1", strCodec ) ); return 0; } return codec; } void KoCsvImportDialog::encodingChanged(const QString &) { QTextCodec* codec = d->updateCodec(); if ( codec ) { d->codec = codec; d->fillTable(); } } #include "KoCsvImportDialog.moc" diff --git a/libs/widgets/KoPageLayoutWidget.cpp b/libs/widgets/KoPageLayoutWidget.cpp index f91555ca262..a3816f96d8a 100644 --- a/libs/widgets/KoPageLayoutWidget.cpp +++ b/libs/widgets/KoPageLayoutWidget.cpp @@ -1,348 +1,350 @@ /* This file is part of the KDE project * Copyright (C) 2007, 2010 Thomas Zander * * 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 "KoPageLayoutWidget.h" #include #include +#include + class Q_DECL_HIDDEN KoPageLayoutWidget::Private { public: Ui::KoPageLayoutWidget widget; KoPageLayout pageLayout; KoUnit unit; QButtonGroup *orientationGroup; bool marginsEnabled; bool allowSignals; }; KoPageLayoutWidget::KoPageLayoutWidget(QWidget *parent, const KoPageLayout &layout) : QWidget(parent) , d(new Private) { d->widget.setupUi(this); d->pageLayout = layout; d->marginsEnabled = true; d->allowSignals = true; d->orientationGroup = new QButtonGroup(this); d->orientationGroup->addButton(d->widget.portrait, KoPageFormat::Portrait); d->orientationGroup->addButton(d->widget.landscape, KoPageFormat::Landscape); QButtonGroup *group2 = new QButtonGroup(this); group2->addButton(d->widget.singleSided); group2->addButton(d->widget.facingPages); // the two sets of labels we use might have different lengths; make sure this does not create a 'jumping' ui d->widget.facingPages->setChecked(true); facingPagesChanged(); int width = qMax(d->widget.leftLabel->width(), d->widget.rightLabel->width()); d->widget.singleSided->setChecked(true); facingPagesChanged(); width = qMax(width, qMax(d->widget.leftLabel->width(), d->widget.rightLabel->width())); d->widget.leftLabel->setMinimumSize(QSize(width, 5)); d->widget.units->addItems(KoUnit::listOfUnitNameForUi(KoUnit::HidePixel)); d->widget.sizes->addItems(KoPageFormat::localizedPageFormatNames()); setPageSpread(false); connect(d->widget.sizes, SIGNAL(currentIndexChanged(int)), this, SLOT(sizeChanged(int))); connect(d->widget.units, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); connect(group2, SIGNAL(buttonClicked(int)), this, SLOT(facingPagesChanged())); connect(d->orientationGroup, SIGNAL(buttonClicked(int)), this, SLOT(orientationChanged())); connect(d->widget.width, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.height, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.topMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.bottomMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.bindingEdgeMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.pageEdgeMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.width, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.height, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); setUnit(KoUnit(KoUnit::Millimeter)); setPageLayout(layout); if (layout.format == 0) // make sure we always call this during startup, even if the A3 (index=0) was chosen sizeChanged(layout.format); showTextDirection(false); /* disable advanced page layout features by default */ d->widget.facingPageLabel->setVisible(false); d->widget.facingPages->setVisible(false); d->widget.singleSided->setVisible(false); d->widget.stylesLabel->setVisible(false); d->widget.pageStyle->setVisible(false); } KoPageLayoutWidget::~KoPageLayoutWidget() { delete d; } KoPageLayout KoPageLayoutWidget::pageLayout() const { return d->pageLayout; } void KoPageLayoutWidget::sizeChanged(int row) { if (row < 0) return; if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.format = static_cast (row); bool custom = d->pageLayout.format == KoPageFormat::CustomSize; d->widget.width->setEnabled( custom ); d->widget.height->setEnabled( custom ); if ( !custom ) { d->pageLayout.width = MM_TO_POINT( KoPageFormat::width( d->pageLayout.format, d->pageLayout.orientation ) ); d->pageLayout.height = MM_TO_POINT( KoPageFormat::height( d->pageLayout.format, d->pageLayout.orientation ) ); if (d->widget.facingPages->isChecked()) // is pagespread d->pageLayout.width *= 2; } d->widget.width->changeValue( d->pageLayout.width ); d->widget.height->changeValue( d->pageLayout.height ); emit layoutChanged(d->pageLayout); d->allowSignals = true; } void KoPageLayoutWidget::unitChanged(int row) { setUnit(KoUnit::fromListForUi(row, KoUnit::HidePixel)); } void KoPageLayoutWidget::setUnit(const KoUnit &unit) { if (d->unit == unit) return; d->unit = unit; d->widget.width->setUnit(unit); d->widget.height->setUnit(unit); d->widget.topMargin->setUnit(unit); d->widget.bottomMargin->setUnit(unit); d->widget.bindingEdgeMargin->setUnit(unit); d->widget.pageEdgeMargin->setUnit(unit); d->widget.units->setCurrentIndex(unit.indexInListForUi(KoUnit::HidePixel)); emit unitChanged(d->unit); } void KoPageLayoutWidget::setPageLayout(const KoPageLayout &layout) { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout = layout; Q_ASSERT(d->orientationGroup->button( layout.orientation )); d->orientationGroup->button( layout.orientation )->setChecked( true ); if (layout.bindingSide >= 0 && layout.pageEdge >= 0) { d->widget.facingPages->setChecked(true); d->widget.bindingEdgeMargin->changeValue(layout.bindingSide); d->widget.pageEdgeMargin->changeValue(layout.pageEdge); d->pageLayout.leftMargin = -1; d->pageLayout.rightMargin = -1; } else { d->widget.singleSided->setChecked(true); d->widget.bindingEdgeMargin->changeValue(layout.leftMargin); d->widget.pageEdgeMargin->changeValue(layout.rightMargin); d->pageLayout.pageEdge = -1; d->pageLayout.bindingSide = -1; } facingPagesChanged(); d->widget.topMargin->changeValue(layout.topMargin); d->widget.bottomMargin->changeValue(layout.bottomMargin); d->allowSignals = true; d->widget.sizes->setCurrentIndex(layout.format); // calls sizeChanged() } void KoPageLayoutWidget::facingPagesChanged() { if (! d->allowSignals) return; d->allowSignals = false; if (d->widget.singleSided->isChecked()) { d->widget.leftLabel->setText(i18n("Left Edge:")); d->widget.rightLabel->setText(i18n("Right Edge:")); } else { d->widget.leftLabel->setText(i18n("Binding Edge:")); d->widget.rightLabel->setText(i18n("Page Edge:")); } d->allowSignals = true; marginsChanged(); sizeChanged(d->widget.sizes->currentIndex()); } void KoPageLayoutWidget::marginsChanged() { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.leftMargin = -1; d->pageLayout.rightMargin = -1; d->pageLayout.bindingSide = -1; d->pageLayout.pageEdge = -1; d->pageLayout.topMargin = d->marginsEnabled?d->widget.topMargin->value():0; d->pageLayout.bottomMargin = d->marginsEnabled?d->widget.bottomMargin->value():0; qreal left = d->marginsEnabled?d->widget.bindingEdgeMargin->value():0; qreal right = d->marginsEnabled?d->widget.pageEdgeMargin->value():0; if (left + right > d->pageLayout.width - 10) { // make sure the actual text area is never smaller than 10 points. qreal diff = d->pageLayout.width - 10 - left - right; left = qMin(d->pageLayout.width - 10, qMax(qreal(0.0), left - diff / qreal(2.0))); right = qMax(qreal(0.0), right - d->pageLayout.width - 10 - left); } if (d->widget.singleSided->isChecked()) { d->pageLayout.leftMargin = left; d->pageLayout.rightMargin = right; } else { d->pageLayout.bindingSide = left; d->pageLayout.pageEdge = right; } // debugWidgets << " " << d->pageLayout.left <<"|"<< d->pageLayout.bindingSide << "," << // d->pageLayout.right << "|"<< d->pageLayout.pageEdge; emit layoutChanged(d->pageLayout); d->allowSignals = true; } void KoPageLayoutWidget::setTextAreaAvailable(bool available) { d->marginsEnabled = available; d->widget.margins->setEnabled(available); marginsChanged(); } void KoPageLayoutWidget::optionsChanged() { if (! d->allowSignals) return; if (d->widget.sizes->currentIndex() == KoPageFormat::CustomSize) { d->pageLayout.width = d->widget.width->value(); d->pageLayout.height = d->widget.height->value(); } else sizeChanged(d->widget.sizes->currentIndex()); marginsChanged(); } void KoPageLayoutWidget::orientationChanged() { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.orientation = d->widget.landscape->isChecked() ? KoPageFormat::Landscape : KoPageFormat::Portrait; qreal x = d->widget.height->value(); d->widget.height->changeValue( d->widget.width->value() ); d->widget.width->changeValue( x ); d->allowSignals = true; optionsChanged(); } void KoPageLayoutWidget::showUnitchooser(bool on) { d->widget.units->setVisible(on); d->widget.unitsLabel->setVisible(on); } void KoPageLayoutWidget::showPageSpread(bool on) { d->widget.facingPageLabel->setVisible(on); d->widget.singleSided->setVisible(on); d->widget.facingPages->setVisible(on); } void KoPageLayoutWidget::setPageSpread(bool pageSpread) { if (pageSpread) d->widget.facingPages->setChecked(true); else d->widget.singleSided->setChecked(true); } void KoPageLayoutWidget::setApplyToDocument(bool apply) { if (apply) { d->widget.facingPageLabel->setText(i18n("Facing Pages:")); d->widget.facingPages->setText(i18n("Facing pages")); } else { d->widget.facingPageLabel->setText(i18n("Page Layout:")); d->widget.facingPages->setText(i18n("Page spread")); } } void KoPageLayoutWidget::showTextDirection(bool on) { d->widget.directionLabel->setVisible(on); d->widget.textDirection->setVisible(on); } void KoPageLayoutWidget::setTextDirection(KoText::Direction direction ) { int index = 0; switch(direction) { case KoText::LeftRightTopBottom: index = 1; break; case KoText::RightLeftTopBottom: index = 2; break; case KoText::TopBottomRightLeft: // unused for now. case KoText::InheritDirection: case KoText::AutoDirection: index = 0; case KoText::TopBottomLeftRight: ; // unhandled, because it actually doesn't exist in real-world writing systems. // Boustrophedon would be interesting to implement, though } d->widget.textDirection->setCurrentIndex(index); } KoText::Direction KoPageLayoutWidget::textDirection() const { switch(d->widget.textDirection->currentIndex()) { case 1: return KoText::LeftRightTopBottom; case 2: return KoText::RightLeftTopBottom; default: case 0: return KoText::AutoDirection; } } void KoPageLayoutWidget::showPageStyles(bool on) { d->widget.stylesLabel->setVisible(on); d->widget.pageStyle->setVisible(on); } void KoPageLayoutWidget::setPageStyles(const QStringList &styles) { d->widget.pageStyle->clear(); d->widget.pageStyle->addItems(styles); } QString KoPageLayoutWidget::currentPageStyle() const { return d->widget.pageStyle->currentText(); } diff --git a/plan/src/kptview.h b/plan/src/kptview.h index 44d11935e71..a98e55342db 100644 --- a/plan/src/kptview.h +++ b/plan/src/kptview.h @@ -1,451 +1,452 @@ /* This file is part of the KDE project Copyright (C) 1998, 1999, 2000 Torben Weis Copyright (C) 2002 - 2010 Dag Andersen 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 KPTVIEW_H #define KPTVIEW_H #include "kplato_export.h" #include #include "kptcontext.h" #include "kptviewbase.h" +#include #include #include #include #include class QMenu; class QPrintDialog; class QStackedWidget; class QSplitter; class QUrl; class KUndo2Command; class QAction; class KToggleAction; class QLabel; class KConfigSkeleton; class KConfigSkeletonItem; class KoView; namespace KPlato { class View; class ViewBase; class ViewListItem; class ViewListWidget; struct ViewInfo; class AccountsView; class GanttView; class PertEditor; class AccountsEditor; class TaskEditor; class CalendarEditor; class ScheduleEditor; class ScheduleManager; class CalculateScheduleCmd; class ResourceAssignmentView; class TaskStatusView; class Calendar; class MainDocument; class Part; class Node; class Project; class Task; class MainSchedule; class Schedule; class Resource; class ResourceGroup; class Relation; class Context; class ViewAdaptor; class HtmlView; class ReportView; class ReportDesignDialog; class DockWidget; class ConfigDialog : public KConfigDialog { Q_OBJECT public: ConfigDialog( QWidget *parent, const QString &name, KConfigSkeleton *config ); protected Q_SLOTS: /// Return true if any widget has changed virtual bool hasChanged(); /** * Update the settings from the dialog. * Virtual function for custom additions. * * Example use: User clicks Ok or Apply button in a configure dialog. */ virtual void updateSettings(); /** * Update the dialog based on the settings. * Virtual function for custom additions. * * Example use: Initialisation of dialog. * Example use: User clicks Reset button in a configure dialog. */ virtual void updateWidgets(); /** * Update the dialog based on the default settings. * Virtual function for custom additions. * * Example use: User clicks Defaults button in a configure dialog. */ virtual void updateWidgetsDefault(); /** * Returns whether the current state of the dialog is * the same as the default configuration. */ virtual bool isDefault(); private: KConfigSkeleton *m_config; QMap m_signalsmap; QMap m_itemmap; QMap m_propertymap; }; //------------- class KPLATO_EXPORT View : public KoView { Q_OBJECT public: explicit View(KoPart *part, MainDocument *doc, QWidget *parent = 0); ~View(); MainDocument *getPart() const; KoPart *getKoPart() const; Project& getProject() const; QMenu *popupMenu( const QString& name ); virtual bool loadContext(); virtual void saveContext( QDomElement &context ) const; /// Load the workpackage from @p url into @p project. Return true if successful, else false. bool loadWorkPackage( Project &project, const QUrl &url ); QWidget *canvas() const; KoPageLayout pageLayout() const; void setPageLayout(const KoPageLayout &pageLayout); ScheduleManager *currentScheduleManager() const; long activeScheduleId() const; void setActiveSchedule( long id ); /// Returns the default view information like standard name and tooltip for view type @p type ViewInfo defaultViewInfo( const QString &type ) const; /// Returns the default category information like standard name and tooltip for category type @p type ViewInfo defaultCategoryInfo( const QString &type ) const; ViewBase *createTaskEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createResourceEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createAccountsEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createCalendarEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createScheduleHandler( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ScheduleEditor *createScheduleEditor( QWidget *parent ); ViewBase *createScheduleEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createDependencyEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createPertEditor( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createProjectStatusView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createPerformanceStatusView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createTaskStatusView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createTaskView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createTaskWorkPackageView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createGanttView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createMilestoneGanttView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createResourceAppointmentsView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createResourceAppointmentsGanttView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createAccountsView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createResourceAssignmentView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createChartView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createReportView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); ViewBase *createReportsGeneratorView( ViewListItem *cat, const QString &tag, const QString &name = QString(), const QString &tip = QString(), int index = -1 ); KoPrintJob * createPrintJob(); QPrintDialog* createPrintDialog(KoPrintJob*, QWidget*); Q_SIGNALS: void currentScheduleManagerChanged( ScheduleManager *sm ); void taskModulesChanged(const QStringList &modules); public Q_SLOTS: void slotUpdate(); void slotCreateNewProject(); void slotEditResource(); void slotEditResource( Resource *resource ); void slotEditCut(); void slotEditCopy(); void slotEditPaste(); void slotRefreshView(); void slotViewSelector( bool show ); void slotAddTask(); void slotAddSubTask(); void slotAddMilestone(); void slotAddSubMilestone(); void slotProjectEdit(); void slotDefineWBS(); void slotCurrencyConfig(); void slotCreateView(); void slotConfigure(); void slotIntroduction(); void slotAddRelation( Node *par, Node *child ); void slotModifyRelation( Relation *rel ); void slotAddRelation( Node *par, Node *child, int linkType ); void slotModifyRelation( Relation *rel, int linkType ); void slotModifyRelation(); void slotDeleteRelation(); void slotRenameNode( Node *node, const QString& name ); void slotPopupMenu( const QString& menuname, const QPoint &pos ); void slotPopupMenu( const QString& menuname, const QPoint &pos, ViewListItem *item ); void addViewListItem( const ViewListItem *item, const ViewListItem *parent, int index ); void removeViewListItem( const ViewListItem *item ); void slotOpenReportFile(); protected Q_SLOTS: void slotGuiActivated( ViewBase *view, bool ); void slotViewActivated( ViewListItem*, ViewListItem* ); void slotPlugScheduleActions(); void slotViewSchedule( QAction *act ); void slotScheduleChanged( MainSchedule* ); void slotScheduleAdded( const MainSchedule * ); void slotScheduleRemoved( const MainSchedule * ); void slotSelectionChanged( ScheduleManager *sm ); void slotAddScheduleManager( Project *project ); void slotDeleteScheduleManager( Project *project, ScheduleManager *sm ); void slotMoveScheduleManager( ScheduleManager *sm, ScheduleManager *parent, int index ); void slotCalculateSchedule( Project*, ScheduleManager* ); void slotBaselineSchedule( Project *project, ScheduleManager *sm ); void slotProjectWorktime(); void slotOpenNode(); void slotOpenNode( Node *node ); void slotTaskProgress(); void slotTaskDescription(); void slotDeleteTask( QList lst ); void slotDeleteTask( Node *node ); void slotDeleteTask(); void slotIndentTask(); void slotUnindentTask(); void slotMoveTaskUp(); void slotMoveTaskDown(); void slotConnectNode(); void slotDeleteResource( Resource *resource ); void slotDeleteResourceGroup( ResourceGroup *group ); void slotDeleteResourceObjects( QObjectList ); void slotCurrentChanged( int ); void slotSelectDefaultView(); void slotInsertResourcesFile(const QString&, const QUrl &projects); void slotInsertFile(); void slotWorkPackageLoaded(); void slotMailWorkpackage( Node *node, Resource *resource = 0 ); void slotMailWorkpackages( const QList &nodes, Resource *resource = 0 ); void slotOpenUrlRequest( HtmlView *v, const QUrl &url ); void slotProjectCalculated( ScheduleManager *sm ); void slotUpdateViewInfo( ViewListItem *itm ); void createReportView(const QDomDocument &doc); void saveTaskModule( const QUrl &url, Project *project ); void removeTaskModule( const QUrl &url ); void taskModuleFileChanged(const QString &path); protected: virtual void guiActivateEvent( bool activated ); virtual void updateReadWrite( bool readwrite ); QList sortedActionList(); QAction *addScheduleAction( Schedule *sch ); void setLabel( ScheduleManager *sm = 0 ); Task *currentTask() const; Node *currentNode() const; Resource *currentResource(); ResourceGroup *currentResourceGroup(); Calendar *currentCalendar(); void updateView( QWidget *widget ); ViewBase *currentView() const; ViewBase *createIntroductionView(); private Q_SLOTS: void slotActionDestroyed( QObject *o ); void slotViewListItemRemoved( ViewListItem *item ); void slotViewListItemInserted( ViewListItem *item, ViewListItem *parent, int index ); void slotProjectEditFinished( int result ); void slotTaskEditFinished( int result ); void slotSummaryTaskEditFinished( int result ); void slotEditResourceFinished( int result ); void slotProjectWorktimeFinished( int result ); void slotDefineWBSFinished( int result ); void slotCurrencyConfigFinished( int result ); void slotInsertFileFinished( int result ); void slotAddSubTaskFinished( int result ); void slotAddTaskFinished( int result ); void slotAddSubMilestoneFinished( int result ); void slotAddMilestoneFinished( int result ); void slotTaskProgressFinished( int result ); void slotMilestoneProgressFinished( int result ); void slotTaskDescriptionFinished( int result ); void slotAddRelationFinished( int result ); void slotModifyRelationFinished( int result ); void slotReportDesignFinished( int result ); void slotOpenReportFileFinished( int result ); void slotCreateViewFinished( int result ); void slotRemoveCommands(); void hideToolDocker(); void initiateViews(); void slotViewScheduleManager(ScheduleManager *sm); private: void createViews(); ViewBase *createView( ViewListItem *cat, const QString &type, const QString &tag, const QString &name, const QString &tip, int index = -1 ); QString standardTaskStatusReport() const; private: QSplitter *m_sp; QStackedWidget *m_tab; ViewListWidget *m_viewlist; ViewListItem *m_viewlistItem; // requested popupmenu item //QDockWidget *m_toolbox; int m_viewGrp; int m_defaultFontSize; int m_currentEstimateType; bool m_updateAccountsview; bool m_updateResourceAssignmentView; bool m_updatePertEditor; QLabel *m_estlabel; ViewAdaptor* m_dbus; QActionGroup *m_scheduleActionGroup; QMap m_scheduleActions; QMultiMap m_calculationcommands; QList m_undocommands; bool m_readWrite; int m_defaultView; QList m_visitedViews; QList m_dockers; // ------ File QAction *actionCreateTemplate; QAction *actionCreateNewProject; // ------ Edit QAction *actionCut; QAction *actionCopy; QAction *actionPaste; // ------ View KToggleAction *actionViewSelector; // ------ Insert // ------ Project QAction *actionEditMainProject; // ------ Tools QAction *actionEditStandardWorktime; QAction *actionDefineWBS; QAction *actionInsertFile; QAction *actionCurrencyConfig; QAction *actionOpenReportFile; // ------ Settings QAction *actionConfigure; // ------ Help QAction *actionIntroduction; // ------ Popup QAction *actionOpenNode; QAction *actionTaskProgress; QAction *actionTaskDescription; QAction *actionDeleteTask; QAction *actionIndentTask; QAction *actionUnindentTask; QAction *actionMoveTaskUp; QAction *actionMoveTaskDown; QAction *actionEditResource; QAction *actionEditRelation; QAction *actionDeleteRelation; //Test QAction *actNoInformation; QMap m_reportActionMap; KoPart *m_partpart; KDirWatch m_dirwatch; }; } //Kplato namespace #endif diff --git a/plan/src/kptviewlist.cpp b/plan/src/kptviewlist.cpp index f34e702e055..0e6db7b2ffe 100644 --- a/plan/src/kptviewlist.cpp +++ b/plan/src/kptviewlist.cpp @@ -1,869 +1,870 @@ /* This file is part of the KDE project Copyright (C) 2007 -2010 Dag Andersen 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 "kptviewlist.h" #include #include #include #include #include #include +#include #include #include #include #include #include "KoDocument.h" #include "kptviewbase.h" #include "kptmaindocument.h" #include "kptviewlistdialog.h" #include "kptviewlistdocker.h" #include "kptschedulemodel.h" #include "Help.h" #include #include namespace KPlato { // class ViewCategoryDelegate : public QItemDelegate { public: ViewCategoryDelegate( QObject *parent, QTreeView *view ) : QItemDelegate( parent ), m_view( view ) {} QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; virtual void paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; private: QTreeView *m_view; }; QSize ViewCategoryDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const { const QAbstractItemModel * model = index.model(); Q_ASSERT( model ); if ( model->parent( index ).isValid() ) { return QItemDelegate::sizeHint( option, index ); } return QItemDelegate::sizeHint( option, index ).expandedTo( QSize( 0, 16 ) ); } void ViewCategoryDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { const QAbstractItemModel * model = index.model(); Q_ASSERT( model ); if ( !model->parent( index ).isValid() ) { // this is a top-level item. QStyleOptionButton buttonOption; buttonOption.state = option.state; buttonOption.rect = option.rect; buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; m_view->style() ->drawControl( QStyle::CE_PushButton, &buttonOption, painter, m_view ); QStyleOption branchOption; static const int i = 9; // ### hardcoded in qcommonstyle.cpp QRect r = option.rect; branchOption.rect = QRect( r.left() + i / 2, r.top() + ( r.height() - i ) / 2, i, i ); branchOption.palette = option.palette; branchOption.state = QStyle::State_Children; if ( m_view->isExpanded( index ) ) branchOption.state |= QStyle::State_Open; m_view->style() ->drawPrimitive( QStyle::PE_IndicatorBranch, &branchOption, painter, m_view ); // draw text QRect textrect = QRect( r.left() + i * 2, r.top(), r.width() - ( ( 5 * i ) / 2 ), r.height() ); QString text = elidedText( option.fontMetrics, textrect.width(), Qt::ElideMiddle, model->data( index, Qt::DisplayRole ).toString() ); m_view->style() ->drawItemText( painter, textrect, Qt::AlignLeft|Qt::AlignVCenter, option.palette, m_view->isEnabled(), text ); } else { QItemDelegate::paint( painter, option, index ); } } ViewListItem::ViewListItem( const QString &tag, const QStringList &strings, int type ) : QTreeWidgetItem( strings, type ), m_tag( tag ) { } ViewListItem::ViewListItem( QTreeWidget *parent, const QString &tag, const QStringList &strings, int type ) : QTreeWidgetItem( parent, strings, type ), m_tag( tag ) { } ViewListItem::ViewListItem( QTreeWidgetItem *parent, const QString &tag, const QStringList &strings, int type ) : QTreeWidgetItem( parent, strings, type ), m_tag( tag ) { } void ViewListItem::setReadWrite( bool rw ) { if ( type() == ItemType_SubView ) { static_cast( view() )->updateReadWrite( rw ); } } void ViewListItem::setView( ViewBase *view ) { setData( 0, ViewListItem::DataRole_View, qVariantFromValue(static_cast( view ) ) ); } ViewBase *ViewListItem::view() const { if ( data(0, ViewListItem::DataRole_View ).isValid() ) { return static_cast( data(0, ViewListItem::DataRole_View ).value() ); } return 0; } void ViewListItem::setDocument( KoDocument *doc ) { setData( 0, ViewListItem::DataRole_Document, qVariantFromValue(static_cast( doc ) ) ); } KoDocument *ViewListItem::document() const { if ( data(0, ViewListItem::DataRole_Document ).isValid() ) { return static_cast( data(0, ViewListItem::DataRole_Document ).value() ); } return 0; } QString ViewListItem::viewType() const { if ( type() != ItemType_SubView ) { return QString(); } QString name = view()->metaObject()->className(); if ( name.contains( ':' ) ) { name = name.remove( 0, name.lastIndexOf( ':' ) + 1 ); } return name; } void ViewListItem::save( QDomElement &element ) const { element.setAttribute( "itemtype", QString::number(type()) ); element.setAttribute( "tag", tag() ); if ( type() == ItemType_SubView ) { element.setAttribute( "viewtype", viewType() ); element.setAttribute( "name", m_viewinfo.name == text( 0 ) ? "" : text( 0 ) ); element.setAttribute( "tooltip", m_viewinfo.tip == toolTip( 0 ) ? TIP_USE_DEFAULT_TEXT : toolTip( 0 ) ); } else if ( type() == ItemType_Category ) { debugPlan<hide(); setRootIsDecorated( false ); setItemDelegate( new ViewCategoryDelegate( this, this ) ); setItemsExpandable( true ); setSelectionMode( QAbstractItemView::SingleSelection ); setDragDropMode( QAbstractItemView::InternalMove ); //setContextMenuPolicy( Qt::ActionsContextMenu ); connect( this, SIGNAL(itemPressed(QTreeWidgetItem*,int)), SLOT(handleMousePress(QTreeWidgetItem*)) ); } void ViewListTreeWidget::drawRow( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { QTreeWidget::drawRow( painter, option, index ); } void ViewListTreeWidget::handleMousePress( QTreeWidgetItem *item ) { //debugPlan; if ( item == 0 ) return ; if ( item->parent() == 0 ) { setItemExpanded( item, !isItemExpanded( item ) ); return ; } } void ViewListTreeWidget::mousePressEvent ( QMouseEvent *event ) { if ( event->button() == Qt::RightButton ) { QTreeWidgetItem *item = itemAt( event->pos() ); if ( item && item->type() == ViewListItem::ItemType_Category ) { setCurrentItem( item ); emit customContextMenuRequested( event->pos() ); event->accept(); return; } } QTreeWidget::mousePressEvent( event ); } void ViewListTreeWidget::save( QDomElement &element ) const { int cnt = topLevelItemCount(); if ( cnt == 0 ) { return; } QDomElement cs = element.ownerDocument().createElement( "categories" ); element.appendChild( cs ); for ( int i = 0; i < cnt; ++i ) { ViewListItem *itm = static_cast( topLevelItem( i ) ); if ( itm->type() != ViewListItem::ItemType_Category ) { continue; } QDomElement c = cs.ownerDocument().createElement( "category" ); cs.appendChild( c ); emit const_cast( this )->updateViewInfo( itm ); itm->save( c ); for ( int j = 0; j < itm->childCount(); ++j ) { ViewListItem *vi = static_cast( itm->child( j ) ); if ( vi->type() != ViewListItem::ItemType_SubView ) { continue; } QDomElement el = c.ownerDocument().createElement( "view" ); c.appendChild( el ); emit const_cast( this )->updateViewInfo( vi ); vi->save( el ); QDomElement elm = el.ownerDocument().createElement( "settings" ); el.appendChild( elm ); static_cast( vi->view() )->saveContext( elm ); } } } // void ViewListTreeWidget::startDrag( Qt::DropActions supportedActions ) { QModelIndexList indexes = selectedIndexes(); if ( indexes.count() == 1 ) { ViewListItem *item = static_cast( itemFromIndex( indexes.at( 0 ) ) ); Q_ASSERT( item ); QTreeWidgetItem *root = invisibleRootItem(); int count = root->childCount(); if ( item && item->type() == ViewListItem::ItemType_Category ) { root->setFlags( root->flags() | Qt::ItemIsDropEnabled ); for ( int i = 0; i < count; ++i ) { QTreeWidgetItem * ch = root->child( i ); ch->setFlags( ch->flags() & ~Qt::ItemIsDropEnabled ); } } else if ( item ) { root->setFlags( root->flags() & ~Qt::ItemIsDropEnabled ); for ( int i = 0; i < count; ++i ) { QTreeWidgetItem * ch = root->child( i ); ch->setFlags( ch->flags() | Qt::ItemIsDropEnabled ); } } } QTreeWidget::startDrag( supportedActions ); } void ViewListTreeWidget::dropEvent( QDropEvent *event ) { QTreeWidget::dropEvent( event ); if ( event->isAccepted() ) { emit modified(); } } ViewListItem *ViewListTreeWidget::findCategory( const QString &cat ) { QTreeWidgetItem * item; int cnt = topLevelItemCount(); for ( int i = 0; i < cnt; ++i ) { item = topLevelItem( i ); if ( static_cast(item)->tag() == cat ) return static_cast(item); } return 0; } ViewListItem *ViewListTreeWidget::category( const KoView *view ) const { QTreeWidgetItem * item; int cnt = topLevelItemCount(); for ( int i = 0; i < cnt; ++i ) { item = topLevelItem( i ); for ( int c = 0; c < item->childCount(); ++c ) { if ( view == static_cast( item->child( c ) )->view() ) { return static_cast( item ); } } } return 0; } //----------------------- ViewListWidget::ViewListWidget( MainDocument *part, QWidget *parent )//QString name, KXmlGuiWindow *parent ) : QWidget( parent ), m_part( part ), m_prev( 0 ), m_temp( 0 ) { setObjectName("ViewListWidget"); Help::add(this, xi18nc("@info:whatsthis", "View Selector" "This is the list of views and editors." "You can configure the list by using the context menu:" "" "Rename categories or views" "Configure. Move, remove, rename or edit tool tip for categories or views" "Insert categories and views" "" "More..." "", Help::page("Manual/View_Selector"))); m_viewlist = new ViewListTreeWidget( this ); m_viewlist->setEditTriggers( QAbstractItemView::NoEditTriggers ); connect(m_viewlist, SIGNAL(modified()), this, SIGNAL(modified())); m_currentSchedule = new KComboBox( this ); m_model.setFlat( true ); m_sfModel.setFilterKeyColumn ( ScheduleModel::ScheduleScheduled ); m_sfModel.setFilterRole( Qt::EditRole ); m_sfModel.setFilterFixedString( "true" ); m_sfModel.setDynamicSortFilter ( true ); m_sfModel.setSourceModel( &m_model ); m_currentSchedule->setModel( &m_sfModel ); Help::add(m_currentSchedule, xi18nc("@info:whatsthis", "Schedule selector" "" "Selects the schedule to be used when displaying schedule dependent data." "Unscheduled tasks are only shown in editors." "More..." "", Help::page("Manual/Main_Work_Space#Schedule_Selector"))); QVBoxLayout *l = new QVBoxLayout( this ); l->setMargin( 0 ); l->addWidget( m_viewlist ); l->addWidget( m_currentSchedule ); connect( m_viewlist, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(slotActivated(QTreeWidgetItem*,QTreeWidgetItem*)) ); connect( m_viewlist, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(slotItemChanged(QTreeWidgetItem*,int)) ); setupContextMenus(); connect( m_currentSchedule, SIGNAL(activated(int)), SLOT(slotCurrentScheduleChanged(int)) ); connect( &m_model, SIGNAL(scheduleManagerAdded(ScheduleManager*)), SLOT(slotScheduleManagerAdded(ScheduleManager*)) ); connect( m_viewlist, SIGNAL(updateViewInfo(ViewListItem*)), SIGNAL(updateViewInfo(ViewListItem*)) ); } ViewListWidget::~ViewListWidget() { } void ViewListWidget::setReadWrite( bool rw ) { foreach ( ViewListItem *c, categories() ) { for ( int i = 0; i < c->childCount(); ++i ) { static_cast( c->child( i ) )->setReadWrite( rw ); } } } void ViewListWidget::slotItemChanged( QTreeWidgetItem */*item*/, int /*col */) { //debugPlan; } void ViewListWidget::slotActivated( QTreeWidgetItem *item, QTreeWidgetItem *prev ) { if ( m_prev ) { m_prev->setData( 0, Qt::BackgroundRole, QVariant() ); } if ( item && item->type() == ViewListItem::ItemType_Category ) { return ; } emit activated( static_cast( item ), static_cast( prev ) ); if ( item ) { QVariant v = QBrush( QColor( Qt::yellow ) ); item->setData( 0, Qt::BackgroundRole, v ); m_prev = static_cast( item ); } } ViewListItem *ViewListWidget::addCategory( const QString &tag, const QString& name ) { //debugPlan ; ViewListItem *item = m_viewlist->findCategory( tag ); if ( item == 0 ) { item = new ViewListItem( m_viewlist, tag, QStringList( name ), ViewListItem::ItemType_Category ); item->setExpanded( true ); item->setFlags( item->flags() | Qt::ItemIsEditable ); } return item; } QList ViewListWidget::categories() const { QList lst; QTreeWidgetItem *item; int cnt = m_viewlist->topLevelItemCount(); for ( int i = 0; i < cnt; ++i ) { item = m_viewlist->topLevelItem( i ); if ( item->type() == ViewListItem::ItemType_Category ) lst << static_cast( item ); } return lst; } ViewListItem *ViewListWidget::findCategory( const QString &tag ) const { return m_viewlist->findCategory( tag ); } ViewListItem *ViewListWidget::category( const KoView *view ) const { return m_viewlist->category( view ); } QString ViewListWidget::uniqueTag( const QString &seed ) const { QString tag = seed; for ( int i = 1; findItem( tag ); ++i ) { tag = QString("%1-%2").arg( seed ).arg( i ); } return tag; } ViewListItem *ViewListWidget::addView(QTreeWidgetItem *category, const QString &tag, const QString &name, ViewBase *view, KoDocument *doc, const QString &iconName, int index) { ViewListItem * item = new ViewListItem( uniqueTag( tag ), QStringList( name ), ViewListItem::ItemType_SubView ); item->setView( view ); item->setDocument( doc ); if (! iconName.isEmpty()) { item->setData(0, Qt::DecorationRole, QIcon::fromTheme(iconName)); } item->setFlags( ( item->flags() | Qt::ItemIsEditable ) & ~Qt::ItemIsDropEnabled ); insertViewListItem( item, category, index ); connect(view, SIGNAL(optionsModified()), SLOT(setModified())); return item; } void ViewListWidget::setSelected( QTreeWidgetItem *item ) { //debugPlan<currentItem(); if ( item == 0 && m_viewlist->currentItem() ) { m_viewlist->currentItem()->setSelected( false ); if ( m_prev ) { m_prev->setData( 0, Qt::BackgroundRole, QVariant() ); } } m_viewlist->setCurrentItem( item ); //debugPlan<currentItem(); } void ViewListWidget::setCurrentItem( QTreeWidgetItem *item ) { m_viewlist->setCurrentItem( item ); //debugPlan<currentItem(); } ViewListItem *ViewListWidget::currentItem() const { return static_cast( m_viewlist->currentItem() ); } ViewListItem *ViewListWidget::currentCategory() const { ViewListItem *item = static_cast( m_viewlist->currentItem() ); if ( item == 0 ) { return 0; } if ( item->type() == ViewListItem::ItemType_Category ) { return item; } return static_cast( item->parent() ); } KoView *ViewListWidget::findView( const QString &tag ) const { ViewListItem *i = findItem( tag ); if ( i == 0 ) { return 0; } return i->view(); } ViewListItem *ViewListWidget::findItem( const QString &tag ) const { ViewListItem *item = findItem( tag, m_viewlist->invisibleRootItem() ); if ( item == 0 ) { QTreeWidgetItem *parent = m_viewlist->invisibleRootItem(); for (int i = 0; i < parent->childCount(); ++i ) { item = findItem( tag, parent->child( i ) ); if ( item != 0 ) { break; } } } return item; } ViewListItem *ViewListWidget::findItem( const QString &tag, QTreeWidgetItem *parent ) const { if ( parent == 0 ) { return findItem( tag, m_viewlist->invisibleRootItem() ); } for (int i = 0; i < parent->childCount(); ++i ) { ViewListItem * ch = static_cast( parent->child( i ) ); if ( ch->tag() == tag ) { //debugPlan<invisibleRootItem() ); } for (int i = 0; i < parent->childCount(); ++i ) { ViewListItem * ch = static_cast( parent->child( i ) ); if ( ch->view() == view ) { //debugPlan<type() != ViewListItem::ItemType_Category ) { return; } debugPlan<type(); if ( m_contextitem->childCount() > 0 ) { if ( KMessageBox::warningContinueCancel( this, i18n( "Removing this category will also remove all its views." ) ) == KMessageBox::Cancel ) { return; } } // first remove all views in this category while ( m_contextitem->childCount() > 0 ) { ViewListItem *itm = static_cast( m_contextitem->child( 0 ) ); takeViewListItem( itm ); delete itm->view(); delete itm; } takeViewListItem( m_contextitem ); delete m_contextitem; m_contextitem = 0; emit modified(); } void ViewListWidget::slotRemoveView() { if ( m_contextitem ) { takeViewListItem( m_contextitem ); delete m_contextitem->view(); delete m_contextitem; emit modified(); } } void ViewListWidget::slotEditViewTitle() { //QTreeWidgetItem *item = m_viewlist->currentItem(); if ( m_contextitem ) { debugPlan<type(); QString title = m_contextitem->text( 0 ); m_viewlist->editItem( m_contextitem ); if ( title != m_contextitem->text( 0 ) ) { emit modified(); } } } void ViewListWidget::slotConfigureItem() { if ( m_contextitem == 0 ) { return; } KoDialog *dlg = 0; if ( m_contextitem->type() == ViewListItem::ItemType_Category ) { debugPlan<type(); dlg = new ViewListEditCategoryDialog( *this, m_contextitem, this ); } else if ( m_contextitem->type() == ViewListItem::ItemType_SubView ) { dlg = new ViewListEditViewDialog( *this, m_contextitem, this ); } if ( dlg ) { connect(dlg, SIGNAL(finished(int)), SLOT(slotDialogFinished(int))); dlg->show(); dlg->raise(); dlg->activateWindow(); } } void ViewListWidget::slotDialogFinished( int result ) { if ( result == QDialog::Accepted ) { emit modified(); } if ( sender() ) { sender()->deleteLater(); } } void ViewListWidget::slotEditDocumentTitle() { //QTreeWidgetItem *item = m_viewlist->currentItem(); if ( m_contextitem ) { debugPlan<type(); QString title = m_contextitem->text( 0 ); m_viewlist->editItem( m_contextitem ); } } int ViewListWidget::removeViewListItem( ViewListItem *item ) { QTreeWidgetItem *p = item->parent(); if ( p == 0 ) { p = m_viewlist->invisibleRootItem(); } int i = p->indexOfChild( item ); if ( i != -1 ) { p->takeChild( i ); emit modified(); } return i; } void ViewListWidget::addViewListItem( ViewListItem *item, QTreeWidgetItem *parent, int index ) { QTreeWidgetItem *p = parent; if ( p == 0 ) { p = m_viewlist->invisibleRootItem(); } if ( index == -1 ) { index = p->childCount(); } p->insertChild( index, item ); emit modified(); } int ViewListWidget::takeViewListItem( ViewListItem *item ) { while ( item->childCount() > 0 ) { takeViewListItem( static_cast( item->child( 0 ) ) ); } int pos = removeViewListItem( item ); if ( pos != -1 ) { emit viewListItemRemoved( item ); if ( item == m_prev ) { m_prev = 0; } if ( m_prev ) { setCurrentItem( m_prev ); } } return pos; } void ViewListWidget::insertViewListItem( ViewListItem *item, QTreeWidgetItem *parent, int index ) { addViewListItem( item, parent, index ); emit viewListItemInserted( item, static_cast( parent ), index ); } void ViewListWidget::setupContextMenus() { // NOTE: can't use xml file as there may not be a factory() QAction *action; // view actions action = new QAction(koIcon("edit-rename"), xi18nc("@action:inmenu rename view", "Rename"), this); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotEditViewTitle()) ); m_viewactions.append( action ); action = new QAction(koIcon("configure"), xi18nc("@action:inmenu configure view", "Configure..."), this ); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotConfigureItem()) ); m_viewactions.append( action ); action = new QAction(koIcon("list-remove"), xi18nc("@action:inmenu remove view", "Remove"), this); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotRemoveView()) ); m_viewactions.append( action ); action = new QAction( this ); action->setSeparator( true ); m_viewactions.append( action ); // Category actions action = new QAction(koIcon("edit-rename"), xi18nc("@action:inmenu rename view category", "Rename"), this); connect( action, SIGNAL(triggered(bool)), SLOT(renameCategory()) ); m_categoryactions.append( action ); action = new QAction(koIcon("configure"), xi18nc("@action:inmenu configure view category", "Configure..."), this); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotConfigureItem()) ); m_categoryactions.append( action ); action = new QAction(koIcon("list-remove"), xi18nc("@action:inmenu Remove view category", "Remove"),this); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotRemoveCategory()) ); m_categoryactions.append( action ); action = new QAction( this ); action->setSeparator( true ); m_categoryactions.append( action ); // list actions action = new QAction(koIcon("list-add"), xi18nc("@action:inmenu Insert View", "Insert..."), this); connect( action, SIGNAL(triggered(bool)), this, SLOT(slotAddView()) ); m_listactions.append( action ); } void ViewListWidget::renameCategory() { if ( m_contextitem ) { QString title = m_contextitem->text( 0 ); m_viewlist->editItem( m_contextitem, 0 ); } } void ViewListWidget::contextMenuEvent ( QContextMenuEvent *event ) { QMenu menu; QList lst; m_contextitem = static_cast(m_viewlist->itemAt( event->pos() ) ); if ( m_contextitem == 0 ) { lst += m_listactions; } else { if ( m_contextitem->type() == ViewListItem::ItemType_Category ) { lst += m_categoryactions; } else if ( m_contextitem->type() == ViewListItem::ItemType_SubView ) { lst += m_viewactions; ViewBase *v = dynamic_cast( m_contextitem->view() ); if ( v ) { lst += v->viewlistActionList(); } } lst += m_listactions; } if ( ! lst.isEmpty() ) { //menu.addTitle( i18n( "Edit" ) ); foreach ( QAction *a, lst ) { menu.addAction( a ); } } if ( ! menu.actions().isEmpty() ) { menu.exec( event->globalPos() ); } } void ViewListWidget::save( QDomElement &element ) const { m_viewlist->save( element ); } void ViewListWidget::setProject( Project *project ) { debugPlan<currentIndex(), m_currentSchedule->modelColumn() ); debugPlan<setCurrentIndex( idx.row() ); debugPlan< Copyright (C) 2011, 2012 Dag Andersen 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 "kptaccountseditor.h" #include "kptcommand.h" #include "kptcalendar.h" #include "kptduration.h" #include "kptnode.h" #include "kptproject.h" #include "kpttask.h" #include "kptaccount.h" #include "kptdatetime.h" #include "Help.h" #include "kptdebug.h" #include #include #include #include #include #include #include #include +#include #include #include namespace KPlato { AccountseditorConfigDialog::AccountseditorConfigDialog( ViewBase *view, AccountTreeView *treeview, QWidget *p, bool selectPrint) : KPageDialog(p), m_view( view ), m_treeview( treeview ) { setWindowTitle( i18n("Settings") ); QTabWidget *tab = new QTabWidget(); QWidget *w = ViewBase::createPageLayoutWidget( view ); tab->addTab( w, w->windowTitle() ); m_pagelayout = w->findChild(); Q_ASSERT( m_pagelayout ); m_headerfooter = ViewBase::createHeaderFooterWidget( view ); m_headerfooter->setOptions( view->printingOptions() ); tab->addTab( m_headerfooter, m_headerfooter->windowTitle() ); KPageWidgetItem *page = addPage( tab, i18n( "Printing" ) ); page->setHeader( i18n( "Printing Options" ) ); if (selectPrint) { setCurrentPage(page); } connect( this, SIGNAL(accepted()), this, SLOT(slotOk())); } void AccountseditorConfigDialog::slotOk() { debugPlan; m_view->setPageLayout( m_pagelayout->pageLayout() ); m_view->setPrintingOptions( m_headerfooter->options() ); } //-------------------- AccountTreeView::AccountTreeView( QWidget *parent ) : TreeViewBase( parent ) { header()->setContextMenuPolicy( Qt::CustomContextMenu ); setModel( new AccountItemModel( this ) ); setSelectionModel( new QItemSelectionModel( model() ) ); setSelectionMode( QAbstractItemView::SingleSelection ); setSelectionBehavior( QAbstractItemView::SelectRows ); setAcceptDrops( false ); setDropIndicatorShown( false ); connect( header(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(headerContextMenuRequested(QPoint)) ); } void AccountTreeView::headerContextMenuRequested( const QPoint &pos ) { debugPlan<logicalIndexAt(pos)<<" at"<pos()), event->globalPos() ); } void AccountTreeView::selectionChanged( const QItemSelection &sel, const QItemSelection &desel ) { debugPlan<selectedIndexes() ) { debugPlan<selectedIndexes() ); } void AccountTreeView::currentChanged( const QModelIndex & current, const QModelIndex & previous ) { debugPlan; QTreeView::currentChanged( current, previous ); emit currentChanged( current ); // possible bug in qt: in QAbstractItemView::SingleSelection you can select multiple items/rows selectionModel()->select( current, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows ); } Account *AccountTreeView::currentAccount() const { return model()->account( currentIndex() ); } Account *AccountTreeView::selectedAccount() const { QModelIndexList lst = selectionModel()->selectedRows(); if ( lst.count() == 1 ) { return model()->account( lst.first() ); } return 0; } QList AccountTreeView::selectedAccounts() const { QList lst; foreach ( const QModelIndex &i, selectionModel()->selectedRows() ) { Account *a = model()->account( i ); if ( a ) { lst << a; } } return lst; } //----------------------------------- AccountsEditor::AccountsEditor(KoPart *part, KoDocument *doc, QWidget *parent) : ViewBase(part, doc, parent) { setupGui(); QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new AccountTreeView( this ); connect(this, SIGNAL(expandAll()), m_view, SLOT(slotExpand())); connect(this, SIGNAL(collapseAll()), m_view, SLOT(slotCollapse())); l->addWidget( m_view ); m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); connect( model(), SIGNAL(executeCommand(KUndo2Command*)), doc, SLOT(addCommand(KUndo2Command*)) ); connect( m_view, SIGNAL(currentChanged(QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex)) ); connect( m_view, SIGNAL(selectionChanged(QModelIndexList)), this, SLOT(slotSelectionChanged(QModelIndexList)) ); connect( m_view, SIGNAL(contextMenuRequested(QModelIndex,QPoint)), this, SLOT(slotContextMenuRequested(QModelIndex,QPoint)) ); connect( m_view, SIGNAL(headerContextMenuRequested(QPoint)), SLOT(slotHeaderContextMenuRequested(QPoint)) ); Help::add(this, xi18nc("@info:whatsthis", "Cost Breakdown Structure Editor" "" "The Cost Breakdown Structure (CBS) consists of accounts" " organized into a tree structure." " Accounts can be tied to tasks or resources." " Usually there will be two top accounts, one for aggregating costs from tasks" " and one for aggregating costs from resources." "" "This view supports printing using the context menu." "More..." "", Help::page("Manual/Cost_Breakdown_Structure_Editor"))); } void AccountsEditor::updateReadWrite( bool readwrite ) { m_view->setReadWrite( readwrite ); } void AccountsEditor::draw( Project &project ) { m_view->setProject( &project ); } void AccountsEditor::draw() { } void AccountsEditor::setGuiActive( bool activate ) { debugPlan<currentIndex().isValid() ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } slotSelectionChanged( m_view->selectionModel()->selectedRows() ); } } void AccountsEditor::slotContextMenuRequested( const QModelIndex &index, const QPoint& pos ) { debugPlan<setContextMenuIndex(index); slotHeaderContextMenuRequested( pos ); m_view->setContextMenuIndex(QModelIndex()); } void AccountsEditor::slotHeaderContextMenuRequested( const QPoint &pos ) { debugPlan; QList lst = contextActionList(); if ( ! lst.isEmpty() ) { QMenu::exec( lst, pos, lst.first() ); } } Account *AccountsEditor::currentAccount() const { return m_view->currentAccount(); } void AccountsEditor::slotCurrentChanged( const QModelIndex &curr ) { debugPlan< lst = m_view->selectedAccounts(); bool one = lst.count() == 1; bool more = lst.count() > 1; actionAddAccount->setEnabled( on && !more ); actionAddSubAccount->setEnabled( on && one ); bool baselined = project() ? project()->isBaselined() : false; actionDeleteSelection->setEnabled( on && one && ! baselined ); } void AccountsEditor::setupGui() { QString name = "accountseditor_edit_list"; actionAddAccount = new QAction(koIcon("document-new"), i18n("Add Account"), this); actionCollection()->addAction("add_account", actionAddAccount ); actionCollection()->setDefaultShortcut(actionAddAccount, Qt::CTRL + Qt::Key_I); connect( actionAddAccount, SIGNAL(triggered(bool)), SLOT(slotAddAccount()) ); addAction( name, actionAddAccount ); actionAddSubAccount = new QAction(koIcon("document-new"), i18n("Add Subaccount"), this); actionCollection()->addAction("add_subaccount", actionAddSubAccount ); actionCollection()->setDefaultShortcut(actionAddSubAccount, Qt::SHIFT + Qt::CTRL + Qt::Key_I); connect( actionAddSubAccount, SIGNAL(triggered(bool)), SLOT(slotAddSubAccount()) ); addAction( name, actionAddSubAccount ); actionDeleteSelection = new QAction(koIcon("edit-delete"), i18nc("@action", "Delete"), this); actionCollection()->addAction("delete_selection", actionDeleteSelection ); actionCollection()->setDefaultShortcut(actionDeleteSelection, Qt::Key_Delete); connect( actionDeleteSelection, SIGNAL(triggered(bool)), SLOT(slotDeleteSelection()) ); addAction( name, actionDeleteSelection ); createOptionActions(ViewBase::OptionExpand | ViewBase::OptionCollapse | ViewBase::OptionPrint | ViewBase::OptionPrintPreview | ViewBase::OptionPrintPdf | ViewBase::OptionPrintConfig); } void AccountsEditor::slotOptions() { debugPlan; AccountseditorConfigDialog *dlg = new AccountseditorConfigDialog( this, m_view, this ); connect(dlg, SIGNAL(finished(int)), SLOT(slotOptionsFinished(int))); dlg->show(); dlg->raise(); dlg->activateWindow(); } void AccountsEditor::slotAddAccount() { debugPlan; int row = -1; Account *parent = m_view->selectedAccount(); // sibling if ( parent ) { row = parent->parent() ? parent->parent()->indexOf( parent ) : project()->accounts().indexOf( parent ); if ( row >= 0 ) { ++row; } parent = parent->parent(); } insertAccount( new Account(), parent, row ); } void AccountsEditor::slotAddSubAccount() { debugPlan; insertAccount( new Account(), m_view->selectedAccount(), -1 ); } void AccountsEditor::insertAccount( Account *account, Account *parent, int row ) { m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); QModelIndex i = m_view->model()->insertAccount( account, parent, row ); if ( i.isValid() ) { QModelIndex p = m_view->model()->parent( i ); if (parent) debugPlan<<" parent="<name()<<":"<setExpanded( p, true ); } m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); m_view->edit( i ); } } void AccountsEditor::slotDeleteSelection() { debugPlan; m_view->model()->removeAccounts( m_view->selectedAccounts() ); } void AccountsEditor::slotAccountsOk() { debugPlan<<"Account Editor : slotAccountsOk"; //QModelList //QModelIndex i = m_view->model()->insertGroup( g ); } KoPrintJob *AccountsEditor::createPrintJob() { return m_view->createPrintJob( this ); } bool AccountsEditor::loadContext(const KoXmlElement &context) { m_view->loadContext(model()->columnMap(), context); return true; } void AccountsEditor::saveContext(QDomElement &context) const { m_view->saveContext(model()->columnMap(), context); } } // namespace KPlato diff --git a/plan/src/libs/ui/kptdocumentspanel.h b/plan/src/libs/ui/kptdocumentspanel.h index 00ea3af80b2..491cb1ebb86 100644 --- a/plan/src/libs/ui/kptdocumentspanel.h +++ b/plan/src/libs/ui/kptdocumentspanel.h @@ -1,82 +1,83 @@ /* This file is part of the KDE project Copyright (C) 2007 Dag Andersen 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 KPTDOCUMENTSPANEL_H #define KPTDOCUMENTSPANEL_H #include "kplatoui_export.h" #include "ui_kptdocumentspanel.h" #include "kptdocuments.h" +#include #include #include class QModelIndex; namespace KPlato { class Node; class DocumentItemModel; class MacroCommand; class DocumentTreeView; class KPLATOUI_EXPORT DocumentsPanel : public QWidget { Q_OBJECT public: explicit DocumentsPanel( Node &node, QWidget *parent = 0 ); ~DocumentsPanel() {} MacroCommand *buildCommand(); Ui::DocumentsPanel widget; DocumentItemModel* model() const; Document *selectedDocument() const; Q_SIGNALS: void changed(); protected Q_SLOTS: void slotAddUrl(); void slotChangeUrl(); void slotRemoveUrl(); void slotViewUrl(); void dataChanged( const QModelIndex& ); void slotSelectionChanged( const QModelIndexList& ); void currentChanged( const QModelIndex &index ); private: Node &m_node; Documents m_docs; enum State { Unmodified = 1, Modified = 2, Added = 4, Removed = 8 }; QMap m_state; QMap m_orgurl; KUndo2QStack m_cmds; DocumentTreeView *m_view; }; } #endif diff --git a/plan/src/libs/ui/kptitemviewsettup.cpp b/plan/src/libs/ui/kptitemviewsettup.cpp index d1c3b1fc157..7c97a070b9a 100644 --- a/plan/src/libs/ui/kptitemviewsettup.cpp +++ b/plan/src/libs/ui/kptitemviewsettup.cpp @@ -1,290 +1,290 @@ /* This file is part of the KDE project Copyright (C) 2007, 2012 Dag Andersen 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 "kptitemviewsettup.h" #include "kptitemmodelbase.h" #include "kptviewbase.h" #include "kptdebug.h" #include "KoPageLayoutWidget.h" +#include #include - namespace KPlato { ItemViewSettup::Item::Item( int column, const QString &text ) : QListWidgetItem( text ), m_column( column ) { } int ItemViewSettup::Item::column() const { return m_column; } bool ItemViewSettup::Item::operator<( const QListWidgetItem & other ) const { return m_column < static_cast( other ).column(); } //-------------------------- ItemViewSettup::ItemViewSettup( TreeViewBase *view, bool includeColumn0, QWidget *parent ) : QWidget( parent ), m_view( view ), m_includeColumn0( includeColumn0 ) { setupUi( this ); stretchLastSection->setChecked( view->header()->stretchLastSection() ); QAbstractItemModel *model = view->model(); QMap map; int c = includeColumn0 ? 0 : 1; debugPlan<columnCount(); ++c ) { Item *item = new Item( c, model->headerData( c, Qt::Horizontal ).toString() ); item->setToolTip( model->headerData( c, Qt::Horizontal, Qt::ToolTipRole ).toString() ); if ( view->isColumnHidden( c ) ) { selector->availableListWidget()->addItem( item ); } else { map.insert( view->section( c ), item ); } } foreach( Item *i, map ) { selector->selectedListWidget()->addItem( i ); } connect( stretchLastSection, SIGNAL(stateChanged(int)), this, SLOT(slotChanged()) ); connect( selector, SIGNAL(added(QListWidgetItem*)), this, SLOT(slotChanged()) ); connect( selector, SIGNAL(removed(QListWidgetItem*)), this, SLOT(slotChanged()) ); connect( selector, SIGNAL(movedUp(QListWidgetItem*)), this, SLOT(slotChanged()) ); connect( selector, SIGNAL(movedDown(QListWidgetItem*)), this, SLOT(slotChanged()) ); } void ItemViewSettup::slotChanged() { emit enableButtonOk( true ); } void ItemViewSettup::slotOk() { debugPlan; QListWidget *lst = selector->availableListWidget(); for ( int r = 0; r < lst->count(); ++r ) { int c = static_cast( lst->item( r ) )->column(); m_view->hideColumn( c ); } lst = selector->selectedListWidget(); for ( int r = 0; r < lst->count(); ++r ) { int c = static_cast( lst->item( r ) )->column(); m_view->mapToSection( c, r ); m_view->showColumn( c ); } m_view->setStretchLastSection( stretchLastSection->isChecked() ); } void ItemViewSettup::setDefault() { debugPlan; selector->availableListWidget()->clear(); selector->selectedListWidget()->clear(); QAbstractItemModel *model = m_view->model(); int c = m_includeColumn0 ? 0 : 1; QList def = m_view->defaultColumns(); for ( ; c < model->columnCount(); ++c ) { if ( ! def.contains( c ) ) { Item *item = new Item( c, model->headerData( c, Qt::Horizontal ).toString() ); item->setToolTip( model->headerData( c, Qt::Horizontal, Qt::ToolTipRole ).toString() ); selector->availableListWidget()->addItem( item ); } } foreach ( int i, def ) { Item *item = new Item( i, model->headerData( i, Qt::Horizontal ).toString() ); item->setToolTip( model->headerData( i, Qt::Horizontal, Qt::ToolTipRole ).toString() ); selector->selectedListWidget()->addItem( item ); } } //--------------------------- ItemViewSettupDialog::ItemViewSettupDialog( ViewBase *view, TreeViewBase *treeview, bool includeColumn0, QWidget *parent ) : KPageDialog( parent ), m_view( view ), m_treeview( treeview ), m_pagelayout( 0 ), m_headerfooter( 0 ) { setWindowTitle( i18n("View Settings") ); setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); button(QDialogButtonBox::Ok)->setDefault(true); button( QDialogButtonBox::RestoreDefaults )->setEnabled( ! treeview->defaultColumns().isEmpty() ); m_panel = new ItemViewSettup( treeview, includeColumn0 ); KPageWidgetItem *page = new KPageWidgetItem( m_panel, i18n( "Tree View" ) ); page->setHeader( i18n( "Tree View Column Configuration" ) ); addPage( page ); m_pageList.append( page ); connect(this, SIGNAL(accepted()), this, SLOT(slotOk())); connect(this, SIGNAL(accepted()), m_panel, SLOT(slotOk())); connect(button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked(bool)), m_panel, SLOT(setDefault())); } void ItemViewSettupDialog::slotOk() { debugPlan<setPageLayout( m_pagelayout->pageLayout() ); } if ( m_headerfooter ) { m_view->setPrintingOptions( m_headerfooter->options() ); } } KPageWidgetItem *ItemViewSettupDialog::insertWidget( int index, QWidget *widget, const QString &name, const QString &header ) { KPageWidgetItem *before = m_pageList.value( index ); KPageWidgetItem *page = new KPageWidgetItem( widget, name ); page->setHeader( header ); if ( before ) { insertPage( before, page ); m_pageList.insert( index, page ); } else { addPage( page ); m_pageList.append( page ); } return page; } void ItemViewSettupDialog::addPrintingOptions(bool setAsCurrent) { if ( ! m_view ) { return; } QTabWidget *tab = new QTabWidget(); QWidget *w = ViewBase::createPageLayoutWidget( m_view ); tab->addTab( w, w->windowTitle() ); m_pagelayout = w->findChild(); Q_ASSERT( m_pagelayout ); m_headerfooter = ViewBase::createHeaderFooterWidget( m_view ); tab->addTab( m_headerfooter, m_headerfooter->windowTitle() ); KPageWidgetItem *itm = insertWidget( -1, tab, i18n( "Printing" ), i18n( "Printing Options" ) ); if (setAsCurrent) { setCurrentPage(itm); } } //------------------------------- SplitItemViewSettupDialog::SplitItemViewSettupDialog( ViewBase *view, DoubleTreeViewBase *treeview, QWidget *parent ) : KPageDialog( parent ), m_view( view ), m_treeview( treeview ), m_pagelayout( 0 ), m_headerfooter( 0 ) { setWindowTitle( i18n("View Settings") ); setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); button(QDialogButtonBox::Ok)->setDefault(true); bool nodef = treeview->masterView()->defaultColumns().isEmpty() || treeview->slaveView()->defaultColumns().isEmpty(); button( QDialogButtonBox::Ok )->setEnabled( ! nodef ); m_page1 = new ItemViewSettup( treeview->masterView(), true ); KPageWidgetItem *page = new KPageWidgetItem( m_page1, i18n( "Main View" ) ); page->setHeader( i18n( "Main View Column Configuration" ) ); addPage( page ); m_pageList.append( page ); m_page2 = new ItemViewSettup( treeview->slaveView(), true ); page = new KPageWidgetItem( m_page2, i18n( "Auxiliary View" ) ); page->setHeader( i18n( "Auxiliary View Column Configuration" ) ); addPage( page ); m_pageList.append( page ); //connect( m_page1, SIGNAL(enableButtonOk(bool)), this, SLOT(enableButtonOk(bool)) ); //connect( m_page2, SIGNAL(enableButtonOk(bool)), this, SLOT(enableButtonOk(bool)) ); connect( this, SIGNAL(accepted()), this, SLOT(slotOk()) ); connect( this, SIGNAL(accepted()), m_page1, SLOT(slotOk()) ); connect( this, SIGNAL(accepted()), m_page2, SLOT(slotOk()) ); connect( button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked(bool)), m_page1, SLOT(setDefault()) ); connect( button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked(bool)), m_page2, SLOT(setDefault()) ); } void SplitItemViewSettupDialog::slotOk() { debugPlan; if ( ! m_view ) { return; } m_view->setPageLayout( m_pagelayout->pageLayout() ); m_view->setPrintingOptions( m_headerfooter->options() ); } KPageWidgetItem *SplitItemViewSettupDialog::insertWidget( int index, QWidget *widget, const QString &name, const QString &header ) { KPageWidgetItem *before = m_pageList.value( index ); KPageWidgetItem *page = new KPageWidgetItem( widget, name ); page->setHeader( header ); if ( before ) { insertPage( before, page ); m_pageList.insert( index, page ); } else { addPage( page ); m_pageList.append( page ); } return page; } void SplitItemViewSettupDialog::addPrintingOptions(bool setAsCurrent) { if ( ! m_view ) { return; } QTabWidget *tab = new QTabWidget(); QWidget *w = ViewBase::createPageLayoutWidget( m_view ); tab->addTab( w, w->windowTitle() ); m_pagelayout = w->findChild(); Q_ASSERT( m_pagelayout ); m_pagelayout->setPageLayout( m_view->pageLayout() ); m_headerfooter = ViewBase::createHeaderFooterWidget( m_view ); tab->addTab( m_headerfooter, m_headerfooter->windowTitle() ); m_headerfooter->setOptions( m_view->printingOptions() ); KPageWidgetItem *itm = insertWidget( -1, tab, i18n( "Printing" ), i18n( "Printing Options" ) ); if (setAsCurrent) { setCurrentPage(itm); } } } //namespace KPlato diff --git a/plan/src/libs/ui/kpttaskeditor.cpp b/plan/src/libs/ui/kpttaskeditor.cpp index 21546118d33..91db5acbb18 100644 --- a/plan/src/libs/ui/kpttaskeditor.cpp +++ b/plan/src/libs/ui/kpttaskeditor.cpp @@ -1,1710 +1,1711 @@ /* This file is part of the KDE project Copyright (C) 2006 - 2010, 2012 Dag Andersen 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 "kpttaskeditor.h" #include "kptglobal.h" #include "kptcommonstrings.h" #include "kptnodeitemmodel.h" #include "kptcommand.h" #include "kptproject.h" #include "kptitemviewsettup.h" #include "kptworkpackagesenddialog.h" #include "kptworkpackagesendpanel.h" #include "kptdatetime.h" #include "kptdebug.h" #include "kptresourcemodel.h" #include "kptresourceallocationmodel.h" #include "ResourceAllocationView.h" #include "kpttaskdialog.h" #include "TasksEditController.h" #include "Help.h" #include #include #include #include #include #include #include #include +#include #include #include #include #include #include namespace KPlato { //-------------------- TaskEditorItemModel::TaskEditorItemModel( QObject *parent ) : NodeItemModel( parent ) { } Qt::ItemFlags TaskEditorItemModel::flags( const QModelIndex &index ) const { if ( index.column() == NodeModel::NodeType ) { if ( ! m_readWrite || isColumnReadOnly( index.column() ) ) { return QAbstractItemModel::flags( index ); } Node *n = node( index ); bool baselined = n ? n->isBaselined() : false; if ( n && ! baselined && ( n->type() == Node::Type_Task || n->type() == Node::Type_Milestone ) ) { return QAbstractItemModel::flags( index ) | Qt::ItemIsEditable | Qt::ItemIsDropEnabled; } return QAbstractItemModel::flags( index ) | Qt::ItemIsDropEnabled; } return NodeItemModel::flags( index ); } QVariant TaskEditorItemModel::headerData( int section, Qt::Orientation orientation, int role ) const { if ( orientation == Qt::Horizontal && section == NodeModel::NodeType ) { if ( role == Qt::ToolTipRole ) { return xi18nc( "@info:tooltip", "The type of task or the estimate type of the task" ); } else if ( role == Qt::WhatsThisRole ) { return xi18nc( "@info:whatsthis", "

Indicates the type of task or the estimate type of the task.

" "The type can be set to Milestone, Effort or Duration." "If the type is Summary or Project the type is not editable."); } } return NodeItemModel::headerData(section, orientation, role); } QVariant TaskEditorItemModel::data( const QModelIndex &index, int role ) const { if ( role == Qt::TextAlignmentRole ) { return NodeItemModel::data( index, role ); } Node *n = node( index ); if ( n != 0 && index.column() == NodeModel::NodeType ) { return type( n, role ); } return NodeItemModel::data( index, role ); } bool TaskEditorItemModel::setData( const QModelIndex &index, const QVariant &value, int role ) { Node *n = node( index ); if ( n != 0 && role == Qt::EditRole && index.column() == NodeModel::NodeType ) { return setType( n, value, role ); } return NodeItemModel::setData( index, value, role ); } QVariant TaskEditorItemModel::type( const Node *node, int role ) const { switch ( role ) { case Qt::DisplayRole: { if ( node->type() == Node::Type_Task ) { return node->estimate()->typeToString( true ); } return node->typeToString( true ); } case Qt::EditRole: return node->type(); case Qt::TextAlignmentRole: return Qt::AlignCenter; case Qt::ToolTipRole: { if ( node->type() == Node::Type_Task ) { return xi18nc( "@info:tooltip", "Task with estimate type: %1", node->estimate()->typeToString( true ) ); } return xi18nc( "@info:tooltip", "Task type: %1", node->typeToString( true ) ); } case Qt::StatusTipRole: case Qt::WhatsThisRole: return QVariant(); case Role::EnumListValue: { if ( node->type() == Node::Type_Milestone ) { return 0; } if ( node->type() == Node::Type_Task ) { return node->estimate()->type() + 1; } return -1; } case Role::EnumList: { QStringList lst; lst << Node::typeToString( Node::Type_Milestone, true ); lst += Estimate::typeToStringList( true ); return lst; } } return QVariant(); } bool TaskEditorItemModel::setType( Node *node, const QVariant &value, int role ) { switch ( role ) { case Qt::EditRole: { if ( node->type() == Node::Type_Summarytask ) { return false; } int v = value.toInt(); switch ( v ) { case 0: { // Milestone NamedCommand *cmd = 0; if ( node->constraint() == Node::FixedInterval ) { cmd = new NodeModifyConstraintEndTimeCmd( *node, node->constraintStartTime(), kundo2_i18n( "Set type to Milestone" ) ); } else { cmd = new ModifyEstimateCmd( *node, node->estimate()->expectedEstimate(), 0.0, kundo2_i18n( "Set type to Milestone" ) ); } emit executeCommand( cmd ); return true; } default: { // Estimate --v; MacroCommand *m = new MacroCommand( kundo2_i18n( "Set type to %1", Estimate::typeToString( (Estimate::Type)v, true ) ) ); m->addCommand( new ModifyEstimateTypeCmd( *node, node->estimate()->type(), v ) ); if ( node->type() == Node::Type_Milestone ) { if ( node->constraint() == Node::FixedInterval ) { m->addCommand( new NodeModifyConstraintEndTimeCmd( *node, node->constraintStartTime().addDays( 1 ) ) ); } else { m->addCommand( new ModifyEstimateUnitCmd( *node, node->estimate()->unit(), Duration::Unit_d ) ); m->addCommand( new ModifyEstimateCmd( *node, node->estimate()->expectedEstimate(), 1.0 ) ); } } emit executeCommand( m ); return true; } } break; } default: break; } return false; } //-------------------- TaskEditorTreeView::TaskEditorTreeView( QWidget *parent ) : DoubleTreeViewBase( parent ) { TaskEditorItemModel *m = new TaskEditorItemModel( this ); setModel( m ); //setSelectionBehavior( QAbstractItemView::SelectItems ); setSelectionMode( QAbstractItemView::ExtendedSelection ); setSelectionBehavior( QAbstractItemView::SelectRows ); createItemDelegates( m ); setItemDelegateForColumn( NodeModel::NodeType, new EnumDelegate( this ) ); connect( this, SIGNAL(dropAllowed(QModelIndex,int,QDragMoveEvent*)), SLOT(slotDropAllowed(QModelIndex,int,QDragMoveEvent*)) ); } NodeItemModel *TaskEditorTreeView::baseModel() const { NodeSortFilterProxyModel *pr = proxyModel(); if ( pr ) { return static_cast( pr->sourceModel() ); } return static_cast( model() ); } void TaskEditorTreeView::slotDropAllowed( const QModelIndex &index, int dropIndicatorPosition, QDragMoveEvent *event ) { QModelIndex idx = index; NodeSortFilterProxyModel *pr = proxyModel(); if ( pr ) { idx = pr->mapToSource( index ); } event->ignore(); if ( baseModel()->dropAllowed( idx, dropIndicatorPosition, event->mimeData() ) ) { event->accept(); } } //-------------------- NodeTreeView::NodeTreeView( QWidget *parent ) : DoubleTreeViewBase( parent ) { NodeItemModel *m = new NodeItemModel( this ); setModel( m ); //setSelectionBehavior( QAbstractItemView::SelectItems ); setSelectionMode( QAbstractItemView::ExtendedSelection ); setSelectionBehavior( QAbstractItemView::SelectRows ); createItemDelegates( m ); connect( this, SIGNAL(dropAllowed(QModelIndex,int,QDragMoveEvent*)), SLOT(slotDropAllowed(QModelIndex,int,QDragMoveEvent*)) ); } NodeItemModel *NodeTreeView::baseModel() const { NodeSortFilterProxyModel *pr = proxyModel(); if ( pr ) { return static_cast( pr->sourceModel() ); } return static_cast( model() ); } void NodeTreeView::slotDropAllowed( const QModelIndex &index, int dropIndicatorPosition, QDragMoveEvent *event ) { QModelIndex idx = index; NodeSortFilterProxyModel *pr = proxyModel(); if ( pr ) { idx = pr->mapToSource( index ); } event->ignore(); if ( baseModel()->dropAllowed( idx, dropIndicatorPosition, event->mimeData() ) ) { event->accept(); } } //----------------------------------- TaskEditor::TaskEditor(KoPart *part, KoDocument *doc, QWidget *parent) : ViewBase(part, doc, parent ) { debugPlan<<"----------------- Create TaskEditor ----------------------"; QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new TaskEditorTreeView( this ); connect(this, SIGNAL(expandAll()), m_view, SLOT(slotExpand())); connect(this, SIGNAL(collapseAll()), m_view, SLOT(slotCollapse())); l->addWidget( m_view ); debugPlan<actionSplitView(); setupGui(); m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); m_view->setDragDropMode( QAbstractItemView::DragDrop ); m_view->setDropIndicatorShown( true ); m_view->setDragEnabled ( true ); m_view->setAcceptDrops( true ); m_view->setAcceptDropsOnView( true ); QList lst1; lst1 << 1 << -1; // only display column 0 (NodeName) in left view QList show; show << NodeModel::NodeResponsible << NodeModel::NodeAllocation << NodeModel::NodeType << NodeModel::NodeEstimateCalendar << NodeModel::NodeEstimate << NodeModel::NodeOptimisticRatio << NodeModel::NodePessimisticRatio << NodeModel::NodeRisk << NodeModel::NodeConstraint << NodeModel::NodeConstraintStart << NodeModel::NodeConstraintEnd << NodeModel::NodeRunningAccount << NodeModel::NodeStartupAccount << NodeModel::NodeStartupCost << NodeModel::NodeShutdownAccount << NodeModel::NodeShutdownCost << NodeModel::NodeDescription; QList lst2; for ( int i = 0; i < model()->columnCount(); ++i ) { if ( ! show.contains( i ) ) { lst2 << i; } } for ( int i = 0; i < show.count(); ++i ) { int sec = m_view->slaveView()->header()->visualIndex( show[ i ] ); //debugPlan<<"move section:"<slaveView()->header()->moveSection( sec, i ); } } m_view->hideColumns( lst1, lst2 ); m_view->masterView()->setDefaultColumns( QList() << NodeModel::NodeName ); m_view->slaveView()->setDefaultColumns( show ); connect( model(), SIGNAL(executeCommand(KUndo2Command*)), doc, SLOT(addCommand(KUndo2Command*)) ); connect( m_view, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex,QModelIndex)) ); connect( m_view, SIGNAL(selectionChanged(QModelIndexList)), this, SLOT(slotSelectionChanged(QModelIndexList)) ); connect( m_view, SIGNAL(contextMenuRequested(QModelIndex,QPoint,QModelIndexList)), SLOT(slotContextMenuRequested(QModelIndex,QPoint,QModelIndexList)) ); connect( m_view, SIGNAL(headerContextMenuRequested(QPoint)), SLOT(slotHeaderContextMenuRequested(QPoint)) ); connect(baseModel(), SIGNAL(projectShownChanged(bool)), SLOT(slotProjectShown(bool))); connect(model(), SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(slotEnableActions())); Help::add(this, xi18nc("@info:whatsthis", "Task Editor" "" "The Task Editor is used to create, edit, and delete tasks. " "Tasks are organized into a Work Breakdown Structure (WBS) to any depth." "" "This view supports configuration and printing using the context menu." "More..." "", Help::page("Manual/Task_Editor"))); } void TaskEditor::slotProjectShown( bool on ) { debugPlan<rowCount() > 0 ) { idx = proxyModel()->index( 0, 0 ); m_view->selectionModel()->setCurrentIndex( idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows ); } } else if ( baseModel() && baseModel()->rowCount() > 0 ) { idx = baseModel()->index( 0, 0 ); m_view->selectionModel()->setCurrentIndex( idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows ); } if ( on && idx.isValid() ) { m_view->masterView()->expand( idx ); } slotEnableActions(); } void TaskEditor::updateReadWrite( bool rw ) { m_view->setReadWrite( rw ); ViewBase::updateReadWrite( rw ); } void TaskEditor::setProject( Project *project ) { debugPlan<setProject( project ); ViewBase::setProject( project ); } void TaskEditor::createDockers() { // Add dockers DockWidget *ds = 0; { ds = new DockWidget( this, "Allocations", xi18nc( "@title resource allocations", "Allocations" ) ); QTreeView *x = new QTreeView( ds ); AllocatedResourceItemModel *m1 = new AllocatedResourceItemModel( x ); x->setModel( m1 ); m1->setProject( project() ); // x->setHeaderHidden( true ); x->setSelectionBehavior( QAbstractItemView::SelectRows ); x->setSelectionMode( QAbstractItemView::ExtendedSelection ); x->expandAll(); x->resizeColumnToContents( 0 ); x->setDragDropMode( QAbstractItemView::DragOnly ); x->setDragEnabled ( true ); ds->setWidget( x ); connect(this, SIGNAL(projectChanged(Project*)), m1, SLOT(setProject(Project*))); connect(this, SIGNAL(taskSelected(Task*)), m1, SLOT(setTask(Task*))); connect(m1, SIGNAL(expandAll()), x, SLOT(expandAll())); connect(m1, SIGNAL(resizeColumnToContents(int)), x, SLOT(resizeColumnToContents(int))); addDocker( ds ); } { ds = new DockWidget( this, "Resources", xi18nc( "@title", "Resources" ) ); ds->setToolTip( xi18nc( "@info:tooltip", "Drag resources into the Task Editor" " and drop into the allocations- or responsible column" ) ); ResourceAllocationView *e = new ResourceAllocationView(part(), ds ); ResourceItemModel *m = new ResourceItemModel( e ); e->setModel( m ); m->setProject( project() ); m->setReadWrite( isReadWrite() ); QList show; show << ResourceModel::ResourceName; for ( int i = m->columnCount() - 1; i >= 0; --i ) { e->setColumnHidden( i, ! show.contains( i ) ); } e->setHeaderHidden( true ); e->setSelectionBehavior( QAbstractItemView::SelectRows ); e->setSelectionMode( QAbstractItemView::ExtendedSelection ); e->expandAll(); e->resizeColumnToContents( ResourceModel::ResourceName ); e->setDragDropMode( QAbstractItemView::DragOnly ); e->setDragEnabled ( true ); ds->setWidget( e ); connect(m_view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), e, SLOT(setSelectedTasks(const QItemSelection&, const QItemSelection&))); connect(this, SIGNAL(projectChanged(Project*)), m, SLOT(setProject(Project*))); connect(this, SIGNAL(readWriteChanged(bool)), m, SLOT(setReadWrite(bool))); connect(m, SIGNAL(executeCommand(KUndo2Command*)), part(), SLOT(addCommand(KUndo2Command*))); addDocker( ds ); } { ds = new DockWidget( this, "Taskmodules", xi18nc( "@title", "Task Modules" ) ); ds->setToolTip( xi18nc( "@info:tooltip", "Drag a task module into the Task Editor to add it to the project" ) ); ds->setLocation( Qt::LeftDockWidgetArea ); ds->setShown(false); // hide by default QTreeView *e = new QTreeView( ds ); QSortFilterProxyModel *sf = new QSortFilterProxyModel(e); TaskModuleModel *m = new TaskModuleModel(sf); sf->setSourceModel(m); e->setModel(sf); e->sortByColumn(0, Qt::AscendingOrder); e->setSortingEnabled(true); e->setHeaderHidden( true ); e->setRootIsDecorated( false ); e->setSelectionBehavior( QAbstractItemView::SelectRows ); e->setSelectionMode( QAbstractItemView::SingleSelection ); // e->resizeColumnToContents( 0 ); e->setDragDropMode( QAbstractItemView::DragDrop ); e->setAcceptDrops( true ); e->setDragEnabled ( true ); ds->setWidget( e ); connect(e, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(taskModuleDoubleClicked(QModelIndex))); connect(this, SIGNAL(loadTaskModules(QStringList)), m, SLOT(loadTaskModules(QStringList))); connect(m, SIGNAL(saveTaskModule(QUrl,Project*)), this, SIGNAL(saveTaskModule(QUrl,Project*))); connect(m, SIGNAL(removeTaskModule(QUrl)), this, SIGNAL(removeTaskModule(QUrl))); addDocker( ds ); } } void TaskEditor::taskModuleDoubleClicked(QModelIndex idx) { QUrl url = idx.data(Qt::UserRole).toUrl(); if (url.isValid()) { emit openDocument(url); } } void TaskEditor::setTaskModules(const QStringList& files) { emit loadTaskModules( files ); } void TaskEditor::setGuiActive( bool activate ) { debugPlan<selectionModel()->currentIndex().isValid() && m_view->model()->rowCount() > 0 ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } } void TaskEditor::slotCurrentChanged( const QModelIndex &curr, const QModelIndex & ) { debugPlan<( selectedNode() ) ); } QModelIndexList TaskEditor::selectedRows() const { #if 0 // Qt bug? return m_view->selectionModel()->selectedRows(); #else QModelIndexList lst; foreach ( QModelIndex i, m_view->selectionModel()->selectedIndexes() ) { if ( i.column() == 0 ) { lst << i; } } return lst; #endif } int TaskEditor::selectedRowCount() const { return selectedRows().count(); } QList TaskEditor::selectedNodes() const { QList lst; foreach ( const QModelIndex &i, selectedRows() ) { Node * n = m_view->baseModel()->node( i ); if ( n != 0 && n->type() != Node::Type_Project ) { lst.append( n ); } } return lst; } Node *TaskEditor::selectedNode() const { QList lst = selectedNodes(); if ( lst.count() != 1 ) { return 0; } return lst.first(); } Node *TaskEditor::currentNode() const { Node * n = m_view->baseModel()->node( m_view->selectionModel()->currentIndex() ); if ( n == 0 || n->type() == Node::Type_Project ) { return 0; } return n; } void TaskEditor::slotContextMenuRequested( const QModelIndex& index, const QPoint& pos, const QModelIndexList &rows ) { QString name; if (rows.count() > 1) { debugPlan< summarytasks; QList tasks; QList milestones; for (const QModelIndex &idx : rows) { Node *node = m_view->baseModel()->node( idx ); if (node) { switch ( node->type() ) { case Node::Type_Task: tasks << static_cast(node); break; case Node::Type_Milestone: milestones << static_cast(node); break; case Node::Type_Summarytask: summarytasks << static_cast(node); break; default: break; } } } if (!tasks.isEmpty()) { editTasks(tasks, pos); return; } return; } Node *node = m_view->baseModel()->node( index ); if ( node == 0 ) { return; } debugPlan<name()<<" :"<type() ) { case Node::Type_Project: name = "task_edit_popup"; break; case Node::Type_Task: name = node->isScheduled( baseModel()->id() ) ? "task_popup" : "task_edit_popup"; break; case Node::Type_Milestone: name = node->isScheduled( baseModel()->id() ) ? "taskeditor_milestone_popup" : "task_edit_popup"; break; case Node::Type_Summarytask: name = "summarytask_popup"; break; default: name = "node_popup"; break; } m_view->setContextMenuIndex(index); if ( name.isEmpty() ) { slotHeaderContextMenuRequested( pos ); m_view->setContextMenuIndex(QModelIndex()); return; } debugPlan<setContextMenuIndex(QModelIndex()); } void TaskEditor::editTasks(const QList &tasks, const QPoint &pos) { QList lst; QAction tasksEdit(i18n( "Edit..."), nullptr); if (!tasks.isEmpty()) { TasksEditController *ted = new TasksEditController(*project(), tasks, this); connect(&tasksEdit, SIGNAL(triggered(bool)), ted, SLOT(activate())); connect(ted, SIGNAL(addCommand(KUndo2Command*)), koDocument(), SLOT(addCommand(KUndo2Command*))); lst << &tasksEdit; } lst += contextActionList(); if (!lst.isEmpty()) { QMenu::exec( lst, pos, lst.first() ); } } void TaskEditor::setScheduleManager( ScheduleManager *sm ) { if (!sm && scheduleManager()) { // we should only get here if the only schedule manager is scheduled, // or when last schedule manager is deleted m_domdoc.clear(); QDomElement element = m_domdoc.createElement("expanded"); m_domdoc.appendChild(element); m_view->masterView()->saveExpanded(element); } bool tryexpand = sm && !scheduleManager(); QDomDocument doc; bool expand = sm && scheduleManager(); if (expand) { m_view->masterView()->setObjectName("TaskEditor"); QDomElement element = doc.createElement("expanded"); doc.appendChild(element); m_view->masterView()->saveExpanded(element); } ViewBase::setScheduleManager(sm); m_view->baseModel()->setScheduleManager( sm ); if (expand) { m_view->masterView()->doExpand(doc); } else if (tryexpand) { m_view->masterView()->doExpand(m_domdoc); } } void TaskEditor::slotEnableActions() { updateActionsEnabled( isReadWrite() ); } void TaskEditor::updateActionsEnabled( bool on ) { // debugPlan<setEnabled( false ); actionAddTask->setEnabled( false ); actionAddMilestone->setEnabled( false ); menuAddSubTask->setEnabled( false ); actionAddSubtask->setEnabled( false ); actionAddSubMilestone->setEnabled( false ); actionDeleteTask->setEnabled( false ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); return; } int selCount = selectedRowCount(); if ( selCount == 0 ) { if ( currentNode() ) { // there are tasks but none is selected menuAddTask->setEnabled( false ); actionAddTask->setEnabled( false ); actionAddMilestone->setEnabled( false ); menuAddSubTask->setEnabled( false ); actionAddSubtask->setEnabled( false ); actionAddSubMilestone->setEnabled( false ); actionDeleteTask->setEnabled( false ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); } else { // we need to be able to add the first task menuAddTask->setEnabled( true ); actionAddTask->setEnabled( true ); actionAddMilestone->setEnabled( true ); menuAddSubTask->setEnabled( false ); actionAddSubtask->setEnabled( false ); actionAddSubMilestone->setEnabled( false ); actionDeleteTask->setEnabled( false ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); } return; } Node *n = selectedNode(); // 0 if not a single task, summarytask or milestone if ( selCount == 1 && n == 0 ) { // only project selected menuAddTask->setEnabled( true ); actionAddTask->setEnabled( true ); actionAddMilestone->setEnabled( true ); menuAddSubTask->setEnabled( true ); actionAddSubtask->setEnabled( true ); actionAddSubMilestone->setEnabled( true ); actionDeleteTask->setEnabled( false ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); return; } if ( selCount == 1 && n != currentNode() ) { // multi selection in progress menuAddTask->setEnabled( false ); actionAddTask->setEnabled( false ); actionAddMilestone->setEnabled( false ); menuAddSubTask->setEnabled( false ); actionAddSubtask->setEnabled( false ); actionAddSubMilestone->setEnabled( false ); actionDeleteTask->setEnabled( false ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); return; } bool baselined = false; Project *p = m_view->project(); if ( p && p->isBaselined() ) { foreach ( Node *n, selectedNodes() ) { if ( n->isBaselined() ) { baselined = true; break; } } } if ( selCount == 1 ) { menuAddTask->setEnabled( true ); actionAddTask->setEnabled( true ); actionAddMilestone->setEnabled( true ); menuAddSubTask->setEnabled( ! baselined || n->type() == Node::Type_Summarytask ); actionAddSubtask->setEnabled( ! baselined || n->type() == Node::Type_Summarytask ); actionAddSubMilestone->setEnabled( ! baselined || n->type() == Node::Type_Summarytask ); actionDeleteTask->setEnabled( ! baselined ); Node *s = n->siblingBefore(); actionMoveTaskUp->setEnabled( s ); actionMoveTaskDown->setEnabled( n->siblingAfter() ); s = n->siblingBefore(); actionIndentTask->setEnabled( ! baselined && s && ! s->isBaselined() ); actionUnindentTask->setEnabled( ! baselined && n->level() > 1 ); return; } // selCount > 1 menuAddTask->setEnabled( false ); actionAddTask->setEnabled( false ); actionAddMilestone->setEnabled( false ); menuAddSubTask->setEnabled( false ); actionAddSubtask->setEnabled( false ); actionAddSubMilestone->setEnabled( false ); actionDeleteTask->setEnabled( ! baselined ); actionMoveTaskUp->setEnabled( false ); actionMoveTaskDown->setEnabled( false ); actionIndentTask->setEnabled( false ); actionUnindentTask->setEnabled( false ); } void TaskEditor::setupGui() { QString name = "taskeditor_add_list"; menuAddTask = new KActionMenu(koIcon("view-task-add"), i18n("Add Task"), this); actionCollection()->addAction("add_task", menuAddTask ); connect( menuAddTask, SIGNAL(triggered(bool)), SLOT(slotAddTask()) ); addAction( name, menuAddTask ); actionAddTask = new QAction( i18n( "Add Task" ), this); actionAddTask->setShortcut( Qt::CTRL + Qt::Key_I ); connect( actionAddTask, SIGNAL(triggered(bool)), SLOT(slotAddTask()) ); menuAddTask->addAction( actionAddTask ); actionAddMilestone = new QAction( i18n( "Add Milestone" ), this ); actionAddMilestone->setShortcut( Qt::CTRL + Qt::ALT + Qt::Key_I ); connect( actionAddMilestone, SIGNAL(triggered(bool)), SLOT(slotAddMilestone()) ); menuAddTask->addAction( actionAddMilestone ); menuAddSubTask = new KActionMenu(koIcon("view-task-child-add"), i18n("Add Sub-Task"), this); actionCollection()->addAction("add_subtask", menuAddTask ); connect( menuAddSubTask, SIGNAL(triggered(bool)), SLOT(slotAddSubtask()) ); addAction( name, menuAddSubTask ); actionAddSubtask = new QAction( i18n( "Add Sub-Task" ), this ); actionAddSubtask->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ); connect( actionAddSubtask, SIGNAL(triggered(bool)), SLOT(slotAddSubtask()) ); menuAddSubTask->addAction( actionAddSubtask ); actionAddSubMilestone = new QAction( i18n( "Add Sub-Milestone" ), this ); actionAddSubMilestone->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::ALT + Qt::Key_I ); connect( actionAddSubMilestone, SIGNAL(triggered(bool)), SLOT(slotAddSubMilestone()) ); menuAddSubTask->addAction( actionAddSubMilestone ); actionDeleteTask = new QAction(koIcon("edit-delete"), xi18nc("@action", "Delete"), this); actionCollection()->setDefaultShortcut( actionDeleteTask, Qt::Key_Delete ); actionCollection()->addAction("delete_task", actionDeleteTask ); connect( actionDeleteTask, SIGNAL(triggered(bool)), SLOT(slotDeleteTask()) ); addAction( name, actionDeleteTask ); name = "taskeditor_move_list"; actionIndentTask = new QAction(koIcon("format-indent-more"), i18n("Indent Task"), this); actionCollection()->addAction("indent_task", actionIndentTask ); connect(actionIndentTask, SIGNAL(triggered(bool)), SLOT(slotIndentTask())); addAction( name, actionIndentTask ); actionUnindentTask = new QAction(koIcon("format-indent-less"), i18n("Unindent Task"), this); actionCollection()->addAction("unindent_task", actionUnindentTask ); connect(actionUnindentTask, SIGNAL(triggered(bool)), SLOT(slotUnindentTask())); addAction( name, actionUnindentTask ); actionMoveTaskUp = new QAction(koIcon("arrow-up"), i18n("Move Up"), this); actionCollection()->addAction("move_task_up", actionMoveTaskUp ); connect(actionMoveTaskUp, SIGNAL(triggered(bool)), SLOT(slotMoveTaskUp())); addAction( name, actionMoveTaskUp ); actionMoveTaskDown = new QAction(koIcon("arrow-down"), i18n("Move Down"), this); actionCollection()->addAction("move_task_down", actionMoveTaskDown ); connect(actionMoveTaskDown, SIGNAL(triggered(bool)), SLOT(slotMoveTaskDown())); addAction( name, actionMoveTaskDown ); // Add the context menu actions for the view options actionShowProject = new KToggleAction( i18n( "Show Project" ), this ); connect(actionShowProject, SIGNAL(triggered(bool)), baseModel(), SLOT(setShowProject(bool))); addContextAction( actionShowProject ); connect(m_view->actionSplitView(), SIGNAL(triggered(bool)), SLOT(slotSplitView())); addContextAction( m_view->actionSplitView() ); createOptionActions(ViewBase::OptionAll); createDockers(); } void TaskEditor::slotSplitView() { debugPlan; m_view->setViewSplitMode( ! m_view->isViewSplit() ); emit optionsModified(); } void TaskEditor::slotOptions() { debugPlan; SplitItemViewSettupDialog *dlg = new SplitItemViewSettupDialog( this, m_view, this ); dlg->addPrintingOptions(sender()->objectName() == "print options"); connect(dlg, SIGNAL(finished(int)), SLOT(slotOptionsFinished(int))); dlg->show(); dlg->raise(); dlg->activateWindow(); } void TaskEditor::slotAddTask() { debugPlan; if ( selectedRowCount() == 0 || ( selectedRowCount() == 1 && selectedNode() == 0 ) ) { m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask( m_view->project()->taskDefaults() ); QModelIndex idx = m_view->baseModel()->insertSubtask( t, m_view->project() ); Q_ASSERT( idx.isValid() ); edit( idx ); return; } Node *sib = selectedNode(); if ( sib == 0 ) { return; } m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask( m_view->project()->taskDefaults() ); QModelIndex idx = m_view->baseModel()->insertTask( t, sib ); Q_ASSERT( idx.isValid() ); edit( idx ); } void TaskEditor::slotAddMilestone() { debugPlan; if ( selectedRowCount() == 0 || ( selectedRowCount() == 1 && selectedNode() == 0 ) ) { // None selected or only project selected: insert under main project m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask(); t->estimate()->clear(); QModelIndex idx = m_view->baseModel()->insertSubtask( t, m_view->project() ); Q_ASSERT( idx.isValid() ); edit( idx ); return; } Node *sib = selectedNode(); // sibling if ( sib == 0 ) { return; } m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask(); t->estimate()->clear(); QModelIndex idx = m_view->baseModel()->insertTask( t, sib ); Q_ASSERT( idx.isValid() ); edit( idx ); } void TaskEditor::slotAddSubMilestone() { debugPlan; Node *parent = selectedNode(); if ( parent == 0 && selectedRowCount() == 1 ) { // project selected parent = m_view->project(); } if ( parent == 0 ) { return; } m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask( m_view->project()->taskDefaults() ); t->estimate()->clear(); QModelIndex idx = m_view->baseModel()->insertSubtask( t, parent ); Q_ASSERT( idx.isValid() ); edit( idx ); } void TaskEditor::slotAddSubtask() { debugPlan; Node *parent = selectedNode(); if ( parent == 0 && selectedRowCount() == 1 ) { // project selected parent = m_view->project(); } if ( parent == 0 ) { return; } m_view->closePersistentEditor( m_view->selectionModel()->currentIndex() ); Task *t = m_view->project()->createTask( m_view->project()->taskDefaults() ); QModelIndex idx = m_view->baseModel()->insertSubtask( t, parent ); Q_ASSERT( idx.isValid() ); edit( idx ); } void TaskEditor::edit( const QModelIndex &i ) { if ( i.isValid() ) { m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect ); m_view->setParentsExpanded( i, true ); // in case treeview does not have focus m_view->edit( i ); } } void TaskEditor::slotDeleteTask() { //debugPlan; QList lst = selectedNodes(); while ( true ) { // remove children of selected tasks, as parents delete their children Node *ch = 0; foreach ( Node *n1, lst ) { foreach ( Node *n2, lst ) { if ( n2->isChildOf( n1 ) ) { ch = n2; break; } } if ( ch != 0 ) { break; } } if ( ch == 0 ) { break; } lst.removeAt( lst.indexOf( ch ) ); } //foreach ( Node* n, lst ) { debugPlan<name(); } emit deleteTaskList( lst ); QModelIndex i = m_view->selectionModel()->currentIndex(); if ( i.isValid() ) { m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); } } void TaskEditor::slotIndentTask() { debugPlan; Node *n = selectedNode(); if ( n ) { emit indentTask(); QModelIndex i = baseModel()->index( n ); m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); m_view->setParentsExpanded( i, true ); } } void TaskEditor::slotUnindentTask() { debugPlan; Node *n = selectedNode(); if ( n ) { emit unindentTask(); QModelIndex i = baseModel()->index( n ); m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); } } void TaskEditor::slotMoveTaskUp() { debugPlan; Node *n = selectedNode(); if ( n ) { emit moveTaskUp(); QModelIndex i = baseModel()->index( n ); m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); } } void TaskEditor::slotMoveTaskDown() { debugPlan; Node *n = selectedNode(); if ( n ) { emit moveTaskDown(); QModelIndex i = baseModel()->index( n ); m_view->selectionModel()->select( i, QItemSelectionModel::Rows | QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect ); m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); } } bool TaskEditor::loadContext( const KoXmlElement &context ) { ViewBase::loadContext( context ); bool show = (bool)(context.attribute( "show-project", "0" ).toInt() ); actionShowProject->setChecked( show ); baseModel()->setShowProject( show ); // why is this not called by the action? bool res = m_view->loadContext( baseModel()->columnMap(), context ); return res; } void TaskEditor::saveContext( QDomElement &context ) const { ViewBase::saveContext( context ); context.setAttribute( "show-project", QString::number(baseModel()->projectShown()) ); m_view->saveContext( baseModel()->columnMap(), context ); } KoPrintJob *TaskEditor::createPrintJob() { return m_view->createPrintJob( this ); } //----------------------------------- TaskView::TaskView(KoPart *part, KoDocument *doc, QWidget *parent) : ViewBase(part, doc, parent) { QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new NodeTreeView( this ); connect(this, SIGNAL(expandAll()), m_view, SLOT(slotExpand())); connect(this, SIGNAL(collapseAll()), m_view, SLOT(slotCollapse())); NodeSortFilterProxyModel *p = new NodeSortFilterProxyModel( m_view->baseModel(), m_view ); m_view->setModel( p ); l->addWidget( m_view ); setupGui(); //m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); m_view->setDragDropMode( QAbstractItemView::InternalMove ); m_view->setDropIndicatorShown( false ); m_view->setDragEnabled ( true ); m_view->setAcceptDrops( false ); m_view->setAcceptDropsOnView( false ); QList readonly; readonly << NodeModel::NodeName << NodeModel::NodeResponsible << NodeModel::NodeAllocation << NodeModel::NodeEstimateType << NodeModel::NodeEstimateCalendar << NodeModel::NodeEstimate << NodeModel::NodeOptimisticRatio << NodeModel::NodePessimisticRatio << NodeModel::NodeRisk << NodeModel::NodeConstraint << NodeModel::NodeConstraintStart << NodeModel::NodeConstraintEnd << NodeModel::NodeRunningAccount << NodeModel::NodeStartupAccount << NodeModel::NodeStartupCost << NodeModel::NodeShutdownAccount << NodeModel::NodeShutdownCost << NodeModel::NodeDescription; foreach ( int c, readonly ) { m_view->baseModel()->setReadOnly( c, true ); } QList lst1; lst1 << 1 << -1; QList show; show << NodeModel::NodeStatus << NodeModel::NodeCompleted << NodeModel::NodeResponsible << NodeModel::NodeAssignments << NodeModel::NodePerformanceIndex << NodeModel::NodeBCWS << NodeModel::NodeBCWP << NodeModel::NodeACWP << NodeModel::NodeDescription; for ( int s = 0; s < show.count(); ++s ) { m_view->slaveView()->mapToSection( show[s], s ); } QList lst2; for ( int i = 0; i < m_view->model()->columnCount(); ++i ) { if ( ! show.contains( i ) ) { lst2 << i; } } m_view->hideColumns( lst1, lst2 ); m_view->masterView()->setDefaultColumns( QList() << 0 ); m_view->slaveView()->setDefaultColumns( show ); connect( m_view->baseModel(), SIGNAL(executeCommand(KUndo2Command*)), doc, SLOT(addCommand(KUndo2Command*)) ); connect( m_view, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex,QModelIndex)) ); connect( m_view, SIGNAL(selectionChanged(QModelIndexList)), this, SLOT(slotSelectionChanged(QModelIndexList)) ); connect( m_view, SIGNAL(contextMenuRequested(QModelIndex,QPoint,QModelIndexList)), SLOT(slotContextMenuRequested(QModelIndex,QPoint)) ); connect( m_view, SIGNAL(headerContextMenuRequested(QPoint)), SLOT(slotHeaderContextMenuRequested(QPoint)) ); Help::add(this, xi18nc("@info:whatsthis", "Task Execution View" "" "The view is used to edit and inspect task progress during project execution." "" "This view supports configuration and printing using the context menu." "More..." "", Help::page("Manual/Task_Execution_View"))); } void TaskView::updateReadWrite( bool rw ) { m_view->setReadWrite( rw ); ViewBase::updateReadWrite( rw ); } void TaskView::draw( Project &project ) { m_view->setProject( &project ); } void TaskView::draw() { } void TaskView::setGuiActive( bool activate ) { debugPlan<selectionModel()->currentIndex().isValid() && m_view->model()->rowCount() > 0 ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } } void TaskView::slotCurrentChanged( const QModelIndex &curr, const QModelIndex & ) { debugPlan<selectionModel(); return sm->selectedRows().count(); } QList TaskView::selectedNodes() const { QList lst; QItemSelectionModel* sm = m_view->selectionModel(); if ( sm == 0 ) { return lst; } foreach ( const QModelIndex &i, sm->selectedRows() ) { Node * n = m_view->baseModel()->node( proxyModel()->mapToSource( i ) ); if ( n != 0 && n->type() != Node::Type_Project ) { lst.append( n ); } } return lst; } Node *TaskView::selectedNode() const { QList lst = selectedNodes(); if ( lst.count() != 1 ) { return 0; } return lst.first(); } Node *TaskView::currentNode() const { Node * n = m_view->baseModel()->node( proxyModel()->mapToSource( m_view->selectionModel()->currentIndex() ) ); if ( n == 0 || n->type() == Node::Type_Project ) { return 0; } return n; } void TaskView::slotContextMenuRequested( const QModelIndex& index, const QPoint& pos ) { QString name; Node *node = m_view->baseModel()->node( proxyModel()->mapToSource( index ) ); if ( node ) { switch ( node->type() ) { case Node::Type_Task: name = "taskview_popup"; break; case Node::Type_Milestone: name = "taskview_milestone_popup"; break; case Node::Type_Summarytask: name = "taskview_summary_popup"; break; default: break; } } else debugPlan<<"No node: "<setContextMenuIndex(index); emit requestPopupMenu( name, pos ); m_view->setContextMenuIndex(QModelIndex()); } void TaskView::setScheduleManager( ScheduleManager *sm ) { //debugPlan<masterView()->saveExpanded(element); } bool tryexpand = sm && !scheduleManager(); QDomDocument doc; bool expand = sm && scheduleManager() && sm != scheduleManager(); if (expand) { m_view->masterView()->setObjectName("TaskEditor"); QDomElement element = doc.createElement("expanded"); doc.appendChild(element); m_view->masterView()->saveExpanded(element); } ViewBase::setScheduleManager(sm); m_view->baseModel()->setScheduleManager( sm ); if (expand) { m_view->masterView()->doExpand(doc); } else if (tryexpand) { m_view->masterView()->doExpand(m_domdoc); } } void TaskView::slotEnableActions() { updateActionsEnabled( true ); } void TaskView::updateActionsEnabled( bool /*on*/ ) { } void TaskView::setupGui() { // KActionCollection *coll = actionCollection(); // Add the context menu actions for the view options actionShowProject = new KToggleAction( i18n( "Show Project" ), this ); connect(actionShowProject, SIGNAL(triggered(bool)), baseModel(), SLOT(setShowProject(bool))); addContextAction( actionShowProject ); connect(m_view->actionSplitView(), SIGNAL(triggered(bool)), SLOT(slotSplitView())); addContextAction( m_view->actionSplitView() ); createOptionActions(ViewBase::OptionAll); } void TaskView::slotSplitView() { debugPlan; m_view->setViewSplitMode( ! m_view->isViewSplit() ); emit optionsModified(); } void TaskView::slotOptions() { debugPlan; SplitItemViewSettupDialog *dlg = new SplitItemViewSettupDialog( this, m_view, this ); dlg->addPrintingOptions(sender()->objectName() == "print options"); connect(dlg, SIGNAL(finished(int)), SLOT(slotOptionsFinished(int))); dlg->show(); dlg->raise(); dlg->activateWindow(); } bool TaskView::loadContext( const KoXmlElement &context ) { ViewBase::loadContext( context ); bool show = (bool)(context.attribute( "show-project", "0" ).toInt() ); actionShowProject->setChecked( show ); baseModel()->setShowProject( show ); // why is this not called by the action? return m_view->loadContext( m_view->baseModel()->columnMap(), context ); } void TaskView::saveContext( QDomElement &context ) const { ViewBase::saveContext( context ); context.setAttribute( "show-project", QString::number(baseModel()->projectShown()) ); m_view->saveContext( m_view->baseModel()->columnMap(), context ); } KoPrintJob *TaskView::createPrintJob() { return m_view->createPrintJob( this ); } //--------------------------------- WorkPackageTreeView::WorkPackageTreeView( QWidget *parent ) : DoubleTreeViewBase( parent ) { debugPlan<<"----------"<baseModel(); } void WorkPackageTreeView::slotDropAllowed( const QModelIndex &index, int dropIndicatorPosition, QDragMoveEvent *event ) { Q_UNUSED(index); Q_UNUSED(dropIndicatorPosition); Q_UNUSED(event); /* QModelIndex idx = index; NodeSortFilterProxyModel *pr = proxyModel(); if ( pr ) { idx = pr->mapToSource( index ); } event->ignore(); if ( baseModel()->dropAllowed( idx, dropIndicatorPosition, event->mimeData() ) ) { event->accept(); }*/ } //-------------------------------- TaskWorkPackageView::TaskWorkPackageView(KoPart *part, KoDocument *doc, QWidget *parent) : ViewBase(part, doc, parent ), m_cmd( 0 ) { QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new WorkPackageTreeView( this ); connect(this, SIGNAL(expandAll()), m_view, SLOT(slotExpand())); connect(this, SIGNAL(collapseAll()), m_view, SLOT(slotCollapse())); l->addWidget( m_view ); setupGui(); //m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); m_view->setDragDropMode( QAbstractItemView::InternalMove ); m_view->setDropIndicatorShown( false ); m_view->setDragEnabled ( true ); m_view->setAcceptDrops( false ); m_view->setAcceptDropsOnView( false ); QList readonly; readonly << NodeModel::NodeName << NodeModel::NodeResponsible << NodeModel::NodeAllocation << NodeModel::NodeEstimateType << NodeModel::NodeEstimateCalendar << NodeModel::NodeEstimate << NodeModel::NodeOptimisticRatio << NodeModel::NodePessimisticRatio << NodeModel::NodeRisk << NodeModel::NodeConstraint << NodeModel::NodeConstraintStart << NodeModel::NodeConstraintEnd << NodeModel::NodeRunningAccount << NodeModel::NodeStartupAccount << NodeModel::NodeStartupCost << NodeModel::NodeShutdownAccount << NodeModel::NodeShutdownCost << NodeModel::NodeDescription; foreach ( int c, readonly ) { m_view->baseModel()->setReadOnly( c, true ); } QList lst1; lst1 << 1 << -1; QList show; show << NodeModel::NodeStatus << NodeModel::NodeCompleted << NodeModel::NodeResponsible << NodeModel::NodeAssignments << NodeModel::NodeDescription; for ( int s = 0; s < show.count(); ++s ) { m_view->slaveView()->mapToSection( show[s], s ); } QList lst2; for ( int i = 0; i < m_view->model()->columnCount(); ++i ) { if ( ! show.contains( i ) ) { lst2 << i; } } m_view->hideColumns( lst1, lst2 ); m_view->masterView()->setDefaultColumns( QList() << 0 ); m_view->slaveView()->setDefaultColumns( show ); connect( m_view->baseModel(), SIGNAL(executeCommand(KUndo2Command*)), doc, SLOT(addCommand(KUndo2Command*)) ); connect( m_view, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex,QModelIndex)) ); connect( m_view, SIGNAL(selectionChanged(QModelIndexList)), this, SLOT(slotSelectionChanged(QModelIndexList)) ); connect( m_view, SIGNAL(contextMenuRequested(QModelIndex,QPoint,QModelIndexList)), SLOT(slotContextMenuRequested(QModelIndex,QPoint)) ); connect( m_view, SIGNAL(headerContextMenuRequested(QPoint)), SLOT(slotHeaderContextMenuRequested(QPoint)) ); } Project *TaskWorkPackageView::project() const { return m_view->project(); } void TaskWorkPackageView::setProject( Project *project ) { m_view->setProject( project ); } WorkPackageProxyModel *TaskWorkPackageView::proxyModel() const { return m_view->proxyModel(); } void TaskWorkPackageView::updateReadWrite( bool rw ) { m_view->setReadWrite( rw ); ViewBase::updateReadWrite( rw ); } void TaskWorkPackageView::setGuiActive( bool activate ) { debugPlan<selectionModel()->currentIndex().isValid() && m_view->model()->rowCount() > 0 ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } } void TaskWorkPackageView::slotRefreshView() { emit checkForWorkPackages(); } void TaskWorkPackageView::slotCurrentChanged( const QModelIndex &curr, const QModelIndex & ) { debugPlan<selectionModel(); return sm->selectedRows().count(); } QList TaskWorkPackageView::selectedNodes() const { QList lst; QItemSelectionModel* sm = m_view->selectionModel(); if ( sm == 0 ) { return lst; } foreach ( const QModelIndex &i, sm->selectedRows() ) { Node * n = proxyModel()->taskFromIndex( i ); if ( n != 0 && n->type() != Node::Type_Project ) { lst.append( n ); } } return lst; } Node *TaskWorkPackageView::selectedNode() const { QList lst = selectedNodes(); if ( lst.count() != 1 ) { return 0; } return lst.first(); } Node *TaskWorkPackageView::currentNode() const { Node * n = proxyModel()->taskFromIndex( m_view->selectionModel()->currentIndex() ); if ( n == 0 || n->type() == Node::Type_Project ) { return 0; } return n; } void TaskWorkPackageView::slotContextMenuRequested( const QModelIndex& index, const QPoint& pos ) { QString name; Node *node = proxyModel()->taskFromIndex( index ); if ( node ) { switch ( node->type() ) { case Node::Type_Task: name = "workpackage_popup"; break; case Node::Type_Milestone: name = "taskview_milestone_popup"; break; case Node::Type_Summarytask: name = "taskview_summary_popup"; break; default: break; } } else debugPlan<<"No node: "<setContextMenuIndex(index); emit requestPopupMenu( name, pos ); m_view->setContextMenuIndex(QModelIndex()); } void TaskWorkPackageView::setScheduleManager( ScheduleManager *sm ) { //debugPlan<baseModel()->setScheduleManager( sm ); } void TaskWorkPackageView::slotEnableActions() { updateActionsEnabled( true ); } void TaskWorkPackageView::updateActionsEnabled( bool on ) { bool o = ! selectedNodes().isEmpty(); actionMailWorkpackage->setEnabled( o && on ); } void TaskWorkPackageView::setupGui() { // KActionCollection *coll = actionCollection(); QString name = "workpackage_list"; actionMailWorkpackage = new QAction(koIcon("mail-send"), i18n("Send..."), this); actionCollection()->setDefaultShortcut( actionMailWorkpackage, Qt::CTRL + Qt::Key_M ); actionCollection()->addAction("send_workpackage", actionMailWorkpackage ); connect( actionMailWorkpackage, SIGNAL(triggered(bool)), SLOT(slotMailWorkpackage()) ); addAction( name, actionMailWorkpackage ); // Add the context menu actions for the view options connect(m_view->actionSplitView(), SIGNAL(triggered(bool)), SLOT(slotSplitView())); addContextAction( m_view->actionSplitView() ); createOptionActions(ViewBase::OptionAll); } void TaskWorkPackageView::slotMailWorkpackage() { QList lst = selectedNodes(); if ( ! lst.isEmpty() ) { // TODO find a better way to log to avoid undo/redo m_cmd = new MacroCommand( kundo2_i18n( "Log Send Workpackage" ) ); QPointer dlg = new WorkPackageSendDialog( lst, scheduleManager(), this ); connect ( dlg->panel(), SIGNAL(sendWorkpackages(QList,Resource*)), this, SIGNAL(mailWorkpackages(QList,Resource*)) ); connect ( dlg->panel(), SIGNAL(sendWorkpackages(QList,Resource*)), this, SLOT(slotWorkPackageSent(QList,Resource*)) ); dlg->exec(); delete dlg; if ( ! m_cmd->isEmpty() ) { part()->addCommand( m_cmd ); m_cmd = 0; } delete m_cmd; m_cmd = 0; } } void TaskWorkPackageView::slotWorkPackageSent( const QList &nodes, Resource *resource ) { foreach ( Node *n, nodes ) { WorkPackage *wp = new WorkPackage( static_cast( n )->workPackage() ); wp->setOwnerName( resource->name() ); wp->setOwnerId( resource->id() ); wp->setTransmitionTime( DateTime::currentDateTime() ); wp->setTransmitionStatus( WorkPackage::TS_Send ); m_cmd->addCommand( new WorkPackageAddCmd( static_cast( n->projectNode() ), n, wp ) ); } } void TaskWorkPackageView::slotSplitView() { debugPlan; m_view->setViewSplitMode( ! m_view->isViewSplit() ); emit optionsModified(); } void TaskWorkPackageView::slotOptions() { debugPlan; SplitItemViewSettupDialog *dlg = new SplitItemViewSettupDialog( this, m_view, this ); dlg->addPrintingOptions(sender()->objectName() == "print options"); connect(dlg, SIGNAL(finished(int)), SLOT(slotOptionsFinished(int))); dlg->show(); dlg->raise(); dlg->activateWindow(); } bool TaskWorkPackageView::loadContext( const KoXmlElement &context ) { debugPlan; ViewBase::loadContext( context ); return m_view->loadContext( m_view->baseModel()->columnMap(), context ); } void TaskWorkPackageView::saveContext( QDomElement &context ) const { ViewBase::saveContext( context ); m_view->saveContext( m_view->baseModel()->columnMap(), context ); } KoPrintJob *TaskWorkPackageView::createPrintJob() { return m_view->createPrintJob( this ); } } // namespace KPlato diff --git a/plan/src/libs/ui/reportsgenerator/ReportsGeneratorView.cpp b/plan/src/libs/ui/reportsgenerator/ReportsGeneratorView.cpp index 344ebc2b599..9146f06ab8c 100644 --- a/plan/src/libs/ui/reportsgenerator/ReportsGeneratorView.cpp +++ b/plan/src/libs/ui/reportsgenerator/ReportsGeneratorView.cpp @@ -1,538 +1,539 @@ /* This file is part of the KDE project Copyright (C) 2017 Dag Andersen 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 "ReportsGeneratorView.h" #include "reportgenerator/ReportGenerator.h" #include "Help.h" #include "kptdebug.h" #include #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KPlato { #define FULLPATHROLE Qt::UserRole + 123 class TemplateFileDelegate : public QStyledItemDelegate { public: TemplateFileDelegate(QObject *parent); 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; QMap files; }; TemplateFileDelegate::TemplateFileDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget *TemplateFileDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index); qDebug()<(editor); qDebug()<setEditable(true); cb->addItems(files.keys()); QString file = index.data().toString(); cb->setCurrentText(file); } void TemplateFileDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *cb = qobject_cast(editor); qDebug()<currentText(); qDebug()<<"template file:"<setData(index, nfile); if (files.contains(nfile)) { nfile = files[nfile].url(); } model->setData(index, nfile, FULLPATHROLE); } } else qDebug()<<" No combo box editor!!"; } class FileItemDelegate : public QStyledItemDelegate { public: FileItemDelegate(QObject *parent); 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; QMap files; }; FileItemDelegate::FileItemDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget *FileItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option); Q_UNUSED(index); KUrlRequester *u = new KUrlRequester(parent); u->setMode(KFile::File); return u; } void FileItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { KUrlRequester *u = qobject_cast(editor); QString file = index.data().toString(); if (!file.isEmpty()) { u->setUrl(QUrl(file)); } } void FileItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { KUrlRequester *u = qobject_cast(editor); if (u && index.isValid()) { model->setData(index, u->url().url()); } } class FileNameExtensionDelegate : public QStyledItemDelegate { public: FileNameExtensionDelegate(QObject *parent); 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; }; FileNameExtensionDelegate::FileNameExtensionDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget *FileNameExtensionDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option); Q_UNUSED(index); QComboBox *cb = new QComboBox(parent); for (int i = 0; i < ReportsGeneratorView::addOptions().count(); ++i) { cb->addItem(ReportsGeneratorView::addOptions().at(i), ReportsGeneratorView::addTags().value(i)); } return cb; } void FileNameExtensionDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QComboBox *cb = qobject_cast(editor); if (cb) { int idx = ReportsGeneratorView::addTags().indexOf(index.data(Qt::UserRole).toString()); cb->setCurrentIndex(idx < 0 ? 0 : idx); } } void FileNameExtensionDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *cb = qobject_cast(editor); if (cb && index.isValid()) { model->setData(index, cb->currentData(), Qt::UserRole); model->setData(index, cb->currentText()); } } QStringList ReportsGeneratorView::addOptions() { return QStringList() << i18n("Nothing") << i18n("Date") << i18n("Number"); } QStringList ReportsGeneratorView::addTags() { return QStringList() << "Nothing" << "Date" << "Number"; } ReportsGeneratorView::ReportsGeneratorView(KoPart *part, KoDocument *doc, QWidget *parent) : ViewBase(part, doc, parent) { debugPlan<<"----------------- Create ReportsGeneratorView ----------------------"; QVBoxLayout * l = new QVBoxLayout(this); l->setMargin(0); m_view = new QTreeView(this); QStandardItemModel *m = new QStandardItemModel(m_view); m->setHorizontalHeaderLabels(QStringList() << i18n("Name") << i18n("Report Template") << i18n("Report File") << i18n("Add")); m->setHeaderData(0, Qt::Horizontal, xi18nc("@info:tooltip", "Report name"), Qt::ToolTipRole); m->setHeaderData(1, Qt::Horizontal, xi18nc("@info:tooltip", "Report template file name"), Qt::ToolTipRole); m->setHeaderData(2, Qt::Horizontal, xi18nc("@info:tooltip", "Name of the generated report file"), Qt::ToolTipRole); m->setHeaderData(3, Qt::Horizontal, xi18nc("@info:tooltip", "Information added to filename"), Qt::ToolTipRole); m_view->setModel(m); m_view->setContextMenuPolicy(Qt::CustomContextMenu); m_view->setRootIsDecorated(false); m_view->setAlternatingRowColors(true); connect(m_view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(slotContextMenuRequested(const QPoint&))); l->addWidget(m_view); TemplateFileDelegate *del = new TemplateFileDelegate(m_view); QString path = QStandardPaths::locate(QStandardPaths::AppDataLocation, "reports", QStandardPaths::LocateDirectory); qDebug()<<"standardpath:"<files.insert(url.fileName(), url); } } m_view->setItemDelegateForColumn(1, del); m_view->setItemDelegateForColumn(2, new FileItemDelegate(m_view)); m_view->setItemDelegateForColumn(3, new FileNameExtensionDelegate(m_view)); m_view->header()->setSectionResizeMode(3, QHeaderView::Fixed); m_view->header()->resizeSection(3, 12); connect(m_view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(slotSelectionChanged())); setupGui(); Help::add(this, xi18nc("@info:whatsthis", "Add and generate reports" "" "Enables you to add and generate reports based on Open Document (.odf) files." "" "You can create a report template using any Open Document text editor." "More..." "", Help::page("Manual/Reports_Generator_View"))); } void ReportsGeneratorView::setGuiActive(bool activate) { debugPlan<selectionModel()->selectedRows(); } int ReportsGeneratorView::selectedRowCount() const { return selectedRows().count(); } void ReportsGeneratorView::slotContextMenuRequested(const QPoint& pos) { debugPlan; emit requestPopupMenu("reportsgeneratorview_popup", m_view->mapToGlobal(pos)); } void ReportsGeneratorView::slotEnableActions() { updateActionsEnabled(isReadWrite()); } void ReportsGeneratorView::updateActionsEnabled(bool on) { actionAddReport->setEnabled(on); actionRemoveReport->setEnabled(on && selectedRowCount() > 0); actionGenerateReport->setEnabled(on && selectedRowCount() > 0); } void ReportsGeneratorView::setupGui() { // Umpff, adding a specific list name for this view in calligraplan.rc does not work! // But reusing an already existing name works, so... // Not important atm, the whole setup should be refactored anyway. //QString name = "reportsgeneratorview_list"; QString name = "workpackage_list"; KActionCollection *coll = actionCollection(); actionAddReport = new QAction(koIcon("list-add"), i18n("Add Report"), this); coll->addAction("add_report", actionAddReport); coll->setDefaultShortcut(actionAddReport, Qt::CTRL + Qt::Key_I); connect(actionAddReport, SIGNAL(triggered(bool)), SLOT(slotAddReport())); addAction(name, actionAddReport); addContextAction(actionAddReport); actionRemoveReport = new QAction(koIcon("list-remove"), i18n("Remove Report"), this); coll->addAction("remove_report", actionRemoveReport); coll->setDefaultShortcut(actionRemoveReport, Qt::CTRL + Qt::Key_D); connect(actionRemoveReport, SIGNAL(triggered(bool)), SLOT(slotRemoveReport())); addAction(name, actionRemoveReport); addContextAction(actionRemoveReport); actionGenerateReport = new QAction(koIcon("document-export"), i18n("Generate Report"), this); coll->addAction("generate_report", actionGenerateReport); coll->setDefaultShortcut(actionGenerateReport, Qt::CTRL + Qt::Key_G); connect(actionGenerateReport, SIGNAL(triggered(bool)), SLOT(slotGenerateReport())); addAction(name, actionGenerateReport); addContextAction(actionGenerateReport); // createOptionAction(); } void ReportsGeneratorView::slotOptions() { debugPlan; // SplitItemViewSettupDialog *dlg = new SplitItemViewSettupDialog(this, m_view, this); // dlg->addPrintingOptions(); // connect(dlg, SIGNAL(finished(int)), SLOT(slotOptionsFinished(int))); // dlg->show(); // dlg->raise(); // dlg->activateWindow(); } void ReportsGeneratorView::slotAddReport() { debugPlan; QAbstractItemModel *m = m_view->model(); int row = m->rowCount(); m->insertRow(row); QModelIndex idx = m->index(row, 0); m->setData(idx, i18n("New report")); QModelIndex add = m->index(row, 3); m->setData(add, ReportsGeneratorView::addOptions().at(0)); m->setData(add, ReportsGeneratorView::addTags().at(0), Qt::UserRole); m_view->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect); m_view->edit(idx); emit optionsModified(); } void ReportsGeneratorView::slotRemoveReport() { debugPlan<model(); QModelIndexList lst = selectedRows(); if (lst.isEmpty()) { return; } // Assumption: model is flat // We must do this in descending row order QMap map; for (int i = 0; i < lst.count(); ++i) { map.insert(-lst.at(i).row(), lst.at(i)); // sort descending } for (const QModelIndex &idx : map) { Q_ASSERT(!idx.parent().isValid()); // must be flat m->removeRow(idx.row(), idx.parent()); } emit optionsModified(); } void ReportsGeneratorView::slotGenerateReport() { debugPlan; QAbstractItemModel *model = m_view->model(); for (const QModelIndex &idx : selectedRows()) { QString name = model->index(idx.row(), 0).data().toString(); QString tmp = model->index(idx.row(), 1).data(FULLPATHROLE).toString(); QString file = model->index(idx.row(), 2).data().toString(); if (tmp.isEmpty()) { QMessageBox::information(this, xi18nc("@title:window", "Generate Report"), i18n("Failed to generate %1." "\nTemplate file name is empty.", name)); continue; } if (file.isEmpty()) { debugPlan<<"No files for report:"<index(idx.row(), 3).data(Qt::UserRole).toString(); if (addition == "Date") { int dotpos = file.lastIndexOf('.'); QString date = QDate::currentDate().toString(); file = file.insert(dotpos, date.prepend('-')); } else if (addition == "Number") { int dotpos = file.lastIndexOf('.'); QString fn = file; for (int i = 1; QFile::exists(fn); ++i) { fn = file.insert(dotpos, QString::number(i).prepend('-')); } file = fn; } // warn if file exists if (QFile::exists(QUrl(file).path())) { if (QMessageBox::question(this, i18n("Report Generation"), i18n("File exists. Continue?")) == QMessageBox::No) { return; } } generateReport(tmp, file); } } bool ReportsGeneratorView::generateReport(const QString &templateFile, const QString &file) { ReportGenerator rg; rg.setReportType("odt"); // TODO: handle different report types rg.setTemplateFile(templateFile); rg.setReportFile(file); rg.setProject(project()); rg.setScheduleManager(scheduleManager()); if (!rg.open()) { debugPlan<<"Failed to open report generator"; QMessageBox::warning(this, i18n("Failed to open report generator"), rg.lastError()); return false; } if (!rg.createReport()) { QMessageBox::warning(this, i18n("Failed to create report"), rg.lastError()); return false; } QMessageBox::information(this, i18n("Report Generation"), i18n("Report file generated: %1", file)); return true; } bool ReportsGeneratorView::loadContext(const KoXmlElement &context) { debugPlan; m_view->header()->setStretchLastSection((bool)(context.attribute("stretch-last-column", "1").toInt())); KoXmlElement e = context.namedItem("sections").toElement(); if (!e.isNull()) { QHeaderView *h = m_view->header(); QString s("section-%1"); for (int i = 0; i < h->count(); ++i) { if (e.hasAttribute(s.arg(i))) { int index = e.attribute(s.arg(i), "-1").toInt(); if (index >= 0 && index < h->count()) { h->moveSection(h->visualIndex(index), i); } } } } KoXmlElement parent = context.namedItem("data").toElement(); if (!parent.isNull()) { debugPlan<<"Load data"; int row = 0; QAbstractItemModel *model = m_view->model(); forEachElement(e, parent) { if (e.tagName() != "row") { continue; } model->insertRow(row); QString name = e.attribute("name"); QString tmp = e.attribute("template"); QString file = e.attribute("file"); QString add = e.attribute("add"); QModelIndex idx = model->index(row, 0); model->setData(idx, name); idx = model->index(row, 1); model->setData(idx, tmp, FULLPATHROLE); model->setData(idx, QUrl(tmp).fileName()); idx = model->index(row, 2); model->setData(idx, file); idx = model->index(row, 3); model->setData(idx, add, Qt::UserRole); model->setData(idx, ReportsGeneratorView::addOptions().value(ReportsGeneratorView::addTags().indexOf(add))); ++row; } } ViewBase::loadContext(context); for (int c = 0; c < m_view->header()->count(); ++c) { m_view->resizeColumnToContents(c); } return true; } void ReportsGeneratorView::saveContext(QDomElement &context) const { debugPlan; context.setAttribute( "stretch-last-column", QString::number(m_view->header()->stretchLastSection()) ); QDomElement e = context.ownerDocument().createElement("sections"); context.appendChild(e); QHeaderView *h = m_view->header(); for (int i = 0; i < h->count(); ++i) { e.setAttribute(QString("section-%1").arg(i), h->logicalIndex(i)); } QDomElement data = context.ownerDocument().createElement("data"); context.appendChild(data); const QAbstractItemModel *model = m_view->model(); for (int row = 0; row < model->rowCount(); ++row) { e = data.ownerDocument().createElement("row"); data.appendChild(e); QModelIndex idx = model->index(row, 0); e.setAttribute("name", idx.data().toString()); idx = model->index(row, 1); e.setAttribute("template", idx.data(FULLPATHROLE).toString()); idx = model->index(row, 2); e.setAttribute("file", idx.data().toString()); idx = model->index(row, 3); e.setAttribute("add", idx.data(Qt::UserRole).toString()); } ViewBase::saveContext(context); } } // namespace KPlato diff --git a/plan/src/libs/widgets/KoPageLayoutWidget.cpp b/plan/src/libs/widgets/KoPageLayoutWidget.cpp index c9e17b748a9..b67e9848807 100644 --- a/plan/src/libs/widgets/KoPageLayoutWidget.cpp +++ b/plan/src/libs/widgets/KoPageLayoutWidget.cpp @@ -1,348 +1,350 @@ /* This file is part of the KDE project * Copyright (C) 2007, 2010 Thomas Zander * * 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 "KoPageLayoutWidget.h" #include #include +#include + class Q_DECL_HIDDEN KoPageLayoutWidget::Private { public: Ui::KoPageLayoutWidget widget; KoPageLayout pageLayout; KoUnit unit; QButtonGroup *orientationGroup; bool marginsEnabled; bool allowSignals; }; KoPageLayoutWidget::KoPageLayoutWidget(QWidget *parent, const KoPageLayout &layout) : QWidget(parent) , d(new Private) { d->widget.setupUi(this); d->pageLayout = layout; d->marginsEnabled = true; d->allowSignals = true; d->orientationGroup = new QButtonGroup(this); d->orientationGroup->addButton(d->widget.portrait, KoPageFormat::Portrait); d->orientationGroup->addButton(d->widget.landscape, KoPageFormat::Landscape); QButtonGroup *group2 = new QButtonGroup(this); group2->addButton(d->widget.singleSided); group2->addButton(d->widget.facingPages); // the two sets of labels we use might have different lengths; make sure this does not create a 'jumping' ui d->widget.facingPages->setChecked(true); facingPagesChanged(); int width = qMax(d->widget.leftLabel->width(), d->widget.rightLabel->width()); d->widget.singleSided->setChecked(true); facingPagesChanged(); width = qMax(width, qMax(d->widget.leftLabel->width(), d->widget.rightLabel->width())); d->widget.leftLabel->setMinimumSize(QSize(width, 5)); d->widget.units->addItems(KoUnit::listOfUnitNameForUi(KoUnit::HidePixel)); d->widget.sizes->addItems(KoPageFormat::localizedPageFormatNames()); setPageSpread(false); connect(d->widget.sizes, SIGNAL(currentIndexChanged(int)), this, SLOT(sizeChanged(int))); connect(d->widget.units, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); connect(group2, SIGNAL(buttonClicked(int)), this, SLOT(facingPagesChanged())); connect(d->orientationGroup, SIGNAL(buttonClicked(int)), this, SLOT(orientationChanged())); connect(d->widget.width, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.height, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.topMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.bottomMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.bindingEdgeMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.pageEdgeMargin, SIGNAL(valueChangedPt(qreal)), this, SLOT(marginsChanged())); connect(d->widget.width, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); connect(d->widget.height, SIGNAL(valueChangedPt(qreal)), this, SLOT(optionsChanged())); setUnit(KoUnit(KoUnit::Millimeter)); setPageLayout(layout); if (layout.format == 0) // make sure we always call this during startup, even if the A3 (index=0) was chosen sizeChanged(layout.format); showTextDirection(false); /* disable advanced page layout features by default */ d->widget.facingPageLabel->setVisible(false); d->widget.facingPages->setVisible(false); d->widget.singleSided->setVisible(false); d->widget.stylesLabel->setVisible(false); d->widget.pageStyle->setVisible(false); } KoPageLayoutWidget::~KoPageLayoutWidget() { delete d; } KoPageLayout KoPageLayoutWidget::pageLayout() const { return d->pageLayout; } void KoPageLayoutWidget::sizeChanged(int row) { if (row < 0) return; if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.format = static_cast (row); bool custom = d->pageLayout.format == KoPageFormat::CustomSize; d->widget.width->setEnabled( custom ); d->widget.height->setEnabled( custom ); if ( !custom ) { d->pageLayout.width = MM_TO_POINT( KoPageFormat::width( d->pageLayout.format, d->pageLayout.orientation ) ); d->pageLayout.height = MM_TO_POINT( KoPageFormat::height( d->pageLayout.format, d->pageLayout.orientation ) ); if (d->widget.facingPages->isChecked()) // is pagespread d->pageLayout.width *= 2; } d->widget.width->changeValue( d->pageLayout.width ); d->widget.height->changeValue( d->pageLayout.height ); emit layoutChanged(d->pageLayout); d->allowSignals = true; } void KoPageLayoutWidget::unitChanged(int row) { setUnit(KoUnit::fromListForUi(row, KoUnit::HidePixel)); } void KoPageLayoutWidget::setUnit(const KoUnit &unit) { if (d->unit == unit) return; d->unit = unit; d->widget.width->setUnit(unit); d->widget.height->setUnit(unit); d->widget.topMargin->setUnit(unit); d->widget.bottomMargin->setUnit(unit); d->widget.bindingEdgeMargin->setUnit(unit); d->widget.pageEdgeMargin->setUnit(unit); d->widget.units->setCurrentIndex(unit.indexInListForUi(KoUnit::HidePixel)); emit unitChanged(d->unit); } void KoPageLayoutWidget::setPageLayout(const KoPageLayout &layout) { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout = layout; Q_ASSERT(d->orientationGroup->button( layout.orientation )); d->orientationGroup->button( layout.orientation )->setChecked( true ); if (layout.bindingSide >= 0 && layout.pageEdge >= 0) { d->widget.facingPages->setChecked(true); d->widget.bindingEdgeMargin->changeValue(layout.bindingSide); d->widget.pageEdgeMargin->changeValue(layout.pageEdge); d->pageLayout.leftMargin = -1; d->pageLayout.rightMargin = -1; } else { d->widget.singleSided->setChecked(true); d->widget.bindingEdgeMargin->changeValue(layout.leftMargin); d->widget.pageEdgeMargin->changeValue(layout.rightMargin); d->pageLayout.pageEdge = -1; d->pageLayout.bindingSide = -1; } facingPagesChanged(); d->widget.topMargin->changeValue(layout.topMargin); d->widget.bottomMargin->changeValue(layout.bottomMargin); d->allowSignals = true; d->widget.sizes->setCurrentIndex(layout.format); // calls sizeChanged() } void KoPageLayoutWidget::facingPagesChanged() { if (! d->allowSignals) return; d->allowSignals = false; if (d->widget.singleSided->isChecked()) { d->widget.leftLabel->setText(i18n("Left Edge:")); d->widget.rightLabel->setText(i18n("Right Edge:")); } else { d->widget.leftLabel->setText(i18n("Binding Edge:")); d->widget.rightLabel->setText(i18n("Page Edge:")); } d->allowSignals = true; marginsChanged(); sizeChanged(d->widget.sizes->currentIndex()); } void KoPageLayoutWidget::marginsChanged() { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.leftMargin = -1; d->pageLayout.rightMargin = -1; d->pageLayout.bindingSide = -1; d->pageLayout.pageEdge = -1; d->pageLayout.topMargin = d->marginsEnabled?d->widget.topMargin->value():0; d->pageLayout.bottomMargin = d->marginsEnabled?d->widget.bottomMargin->value():0; qreal left = d->marginsEnabled?d->widget.bindingEdgeMargin->value():0; qreal right = d->marginsEnabled?d->widget.pageEdgeMargin->value():0; if (left + right > d->pageLayout.width - 10) { // make sure the actual text area is never smaller than 10 points. qreal diff = d->pageLayout.width - 10 - left - right; left = qMin(d->pageLayout.width - 10, qMax(qreal(0.0), left - diff / qreal(2.0))); right = qMax(qreal(0.0), right - d->pageLayout.width - 10 - left); } if (d->widget.singleSided->isChecked()) { d->pageLayout.leftMargin = left; d->pageLayout.rightMargin = right; } else { d->pageLayout.bindingSide = left; d->pageLayout.pageEdge = right; } // debugWidgets << " " << d->pageLayout.left <<"|"<< d->pageLayout.bindingSide << "," << // d->pageLayout.right << "|"<< d->pageLayout.pageEdge; emit layoutChanged(d->pageLayout); d->allowSignals = true; } void KoPageLayoutWidget::setTextAreaAvailable(bool available) { d->marginsEnabled = available; d->widget.margins->setEnabled(available); marginsChanged(); } void KoPageLayoutWidget::optionsChanged() { if (! d->allowSignals) return; if (d->widget.sizes->currentIndex() == KoPageFormat::CustomSize) { d->pageLayout.width = d->widget.width->value(); d->pageLayout.height = d->widget.height->value(); } else sizeChanged(d->widget.sizes->currentIndex()); marginsChanged(); } void KoPageLayoutWidget::orientationChanged() { if (! d->allowSignals) return; d->allowSignals = false; d->pageLayout.orientation = d->widget.landscape->isChecked() ? KoPageFormat::Landscape : KoPageFormat::Portrait; qreal x = d->widget.height->value(); d->widget.height->changeValue( d->widget.width->value() ); d->widget.width->changeValue( x ); d->allowSignals = true; optionsChanged(); } void KoPageLayoutWidget::showUnitchooser(bool on) { d->widget.units->setVisible(on); d->widget.unitsLabel->setVisible(on); } void KoPageLayoutWidget::showPageSpread(bool on) { d->widget.facingPageLabel->setVisible(on); d->widget.singleSided->setVisible(on); d->widget.facingPages->setVisible(on); } void KoPageLayoutWidget::setPageSpread(bool pageSpread) { if (pageSpread) d->widget.facingPages->setChecked(true); else d->widget.singleSided->setChecked(true); } void KoPageLayoutWidget::setApplyToDocument(bool apply) { if (apply) { d->widget.facingPageLabel->setText(i18n("Facing Pages:")); d->widget.facingPages->setText(i18n("Facing pages")); } else { d->widget.facingPageLabel->setText(i18n("Page Layout:")); d->widget.facingPages->setText(i18n("Page spread")); } } void KoPageLayoutWidget::showTextDirection(bool on) { d->widget.directionLabel->setVisible(on); d->widget.textDirection->setVisible(on); } /* void KoPageLayoutWidget::setTextDirection(KoText::Direction direction ) { int index = 0; switch(direction) { case KoText::LeftRightTopBottom: index = 1; break; case KoText::RightLeftTopBottom: index = 2; break; case KoText::TopBottomRightLeft: // unused for now. case KoText::InheritDirection: case KoText::AutoDirection: index = 0; case KoText::TopBottomLeftRight: ; // unhandled, because it actually doesn't exist in real-world writing systems. // Boustrophedon would be interesting to implement, though } d->widget.textDirection->setCurrentIndex(index); } KoText::Direction KoPageLayoutWidget::textDirection() const { switch(d->widget.textDirection->currentIndex()) { case 1: return KoText::LeftRightTopBottom; case 2: return KoText::RightLeftTopBottom; default: case 0: return KoText::AutoDirection; } } */ void KoPageLayoutWidget::showPageStyles(bool on) { d->widget.stylesLabel->setVisible(on); d->widget.pageStyle->setVisible(on); } void KoPageLayoutWidget::setPageStyles(const QStringList &styles) { d->widget.pageStyle->clear(); d->widget.pageStyle->addItems(styles); } QString KoPageLayoutWidget::currentPageStyle() const { return d->widget.pageStyle->currentText(); } diff --git a/plugins/chartshape/dialogs/TableEditorDialog.cpp b/plugins/chartshape/dialogs/TableEditorDialog.cpp index c0d5136f09e..d2a772e83c2 100644 --- a/plugins/chartshape/dialogs/TableEditorDialog.cpp +++ b/plugins/chartshape/dialogs/TableEditorDialog.cpp @@ -1,266 +1,267 @@ /* This file is part of the KDE project Copyright 2008 Johannes Simon Copyright 2009 Inge Wallin 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. */ // Own #include "TableEditorDialog.h" // Qt #include +#include // Calligra #include // KoChart #include "ChartProxyModel.h" #include "ChartTableView.h" #include "ChartDebug.h" using namespace KoChart; TableEditorDialog::TableEditorDialog() : QDialog( 0 ) , m_tableView( new ChartTableView ) { setupUi( this ); m_proxyModel = 0; init(); } TableEditorDialog::~TableEditorDialog() { delete m_tableView; } void TableEditorDialog::init() { tableViewContainer->addWidget( m_tableView ); const QIcon insertRowIcon = koIcon("edit-table-insert-row-above"); const QIcon deleteRowIcon = koIcon("edit-table-delete-row"); const QIcon insertColIcon = koIcon("edit-table-insert-column-left"); const QIcon deleteColIcon = koIcon("edit-table-delete-column"); // Create actions. m_insertRowsAction = new QAction( insertRowIcon, i18n( "Insert Rows" ), m_tableView ); m_deleteRowsAction = new QAction( deleteRowIcon, i18n( "Delete Rows" ), m_tableView ); m_insertColumnsAction = new QAction( insertColIcon, i18n( "Insert Columns" ), m_tableView ); m_deleteColumnsAction = new QAction( deleteColIcon, i18n( "Delete Columns" ), m_tableView ); // Set icons on buttons(?). insertRow->setIcon( insertRowIcon ); deleteRow->setIcon( deleteRowIcon ); insertColumn->setIcon( insertColIcon ); deleteColumn->setIcon( deleteColIcon ); // Initially, no index is selected. Deletion only works with legal // selections. They will automatically be enabled when an index // is selected. deleteRow->setEnabled( false ); deleteColumn->setEnabled( false ); // Buttons connect( insertRow, SIGNAL(pressed()), this, SLOT(slotInsertRowPressed()) ); connect( insertColumn, SIGNAL(pressed()), this, SLOT(slotInsertColumnPressed()) ); connect( deleteRow, SIGNAL(pressed()), this, SLOT(slotDeleteRowPressed()) ); connect( deleteColumn, SIGNAL(pressed()), this, SLOT(slotDeleteColumnPressed()) ); // Context Menu Actions connect( m_insertRowsAction, SIGNAL(triggered()), this, SLOT(slotInsertRowPressed()) ); connect( m_insertColumnsAction, SIGNAL(triggered()), this, SLOT(slotInsertColumnPressed()) ); connect( m_deleteRowsAction, SIGNAL(triggered()), this, SLOT(slotDeleteRowPressed()) ); connect( m_deleteColumnsAction, SIGNAL(triggered()), this, SLOT(slotDeleteColumnPressed()) ); connect( m_tableView, SIGNAL(currentIndexChanged(QModelIndex)), this, SLOT(slotCurrentIndexChanged(QModelIndex)) ); // We only need to connect one of the data direction buttons, since // they are mutually exclusive. connect( dataSetsInRows, SIGNAL(toggled(bool)), this, SLOT(slotDataSetsInRowsToggled(bool)) ); // FIXME: QAction to create a separator?? QAction *separator = new QAction( m_tableView ); separator->setSeparator( true ); // Add all the actions to the view. m_tableView->addAction( m_deleteRowsAction ); m_tableView->addAction( m_insertRowsAction ); m_tableView->addAction( separator ); m_tableView->addAction( m_deleteColumnsAction ); m_tableView->addAction( m_insertColumnsAction ); m_tableView->setContextMenuPolicy( Qt::ActionsContextMenu ); // Initialize the contents of the controls slotUpdateDialog(); } void TableEditorDialog::setProxyModel( ChartProxyModel* proxyModel ) { if ( m_proxyModel == proxyModel ) return; // Disconnect the old proxy model. m_proxyModel->disconnect( this ); m_proxyModel = proxyModel; // Connect the new proxy model. if ( m_proxyModel ) { connect( m_proxyModel, SIGNAL(modelReset()), this, SLOT(slotUpdateDialog()) ); } slotUpdateDialog(); } void TableEditorDialog::setModel( QAbstractItemModel *model ) { m_tableView->setModel( model ); } void TableEditorDialog::slotUpdateDialog() { if ( !m_proxyModel ) return; switch ( m_proxyModel->dataDirection() ) { case Qt::Horizontal: dataSetsInRows->setChecked( true ); break; case Qt::Vertical: dataSetsInColumns->setChecked( true ); break; default: warnChart << "Unrecognized value for data direction: " << m_proxyModel->dataDirection(); } } // ---------------------------------------------------------------- // slots void TableEditorDialog::slotInsertRowPressed() { Q_ASSERT( m_tableView->model() ); QAbstractItemModel *model = m_tableView->model(); QModelIndex currIndex = m_tableView->currentIndex(); int selectedRow; if ( model->rowCount() == 0 ) // +1 is added below. selectedRow = -1; else if ( currIndex.isValid() ) selectedRow = currIndex.row(); else selectedRow = m_tableView->model()->rowCount() - 1; // Insert the row *after* the selection, thus +1 model->insertRow( selectedRow + 1 ); } void TableEditorDialog::slotInsertColumnPressed() { Q_ASSERT( m_tableView->model() ); QAbstractItemModel *model = m_tableView->model(); QModelIndex currIndex = m_tableView->currentIndex(); int selectedColumn; if ( model->columnCount() == 0 ) // +1 is added below. selectedColumn = -1; if ( currIndex.isValid() ) selectedColumn = currIndex.column(); else selectedColumn = m_tableView->model()->columnCount() - 1; // Insert the column *after* the selection, thus +1 model->insertColumn( selectedColumn + 1 ); } void TableEditorDialog::slotDeleteRowPressed() { deleteSelectedRowsOrColumns( Qt::Horizontal ); } void TableEditorDialog::slotDeleteColumnPressed() { deleteSelectedRowsOrColumns( Qt::Vertical ); } void TableEditorDialog::deleteSelectedRowsOrColumns( Qt::Orientation orientation ) { // Note: In the following, both rows and columns will be referred to // as "row", for ease of reading this code. Q_ASSERT( m_tableView->model() ); const QModelIndexList selectedIndexes = m_tableView->selectionModel()->selectedIndexes(); if ( selectedIndexes.isEmpty() ) return; QList rowsToBeRemoved; // Make sure we don't delete a row twice, as indexes can exist // multiple times for one row foreach( const QModelIndex &index, selectedIndexes ) { const int row = orientation == Qt::Horizontal ? index.row() : index.column(); if ( !rowsToBeRemoved.contains( row ) ) rowsToBeRemoved.append( row ); } // Use qGreater() as comparator to remove rows in reversed order // to not change the indexes of the selected rows qSort( rowsToBeRemoved.begin(), rowsToBeRemoved.end(), qGreater() ); foreach( int row, rowsToBeRemoved ) { Q_ASSERT( row >= 0 ); if ( orientation == Qt::Horizontal ) m_tableView->model()->removeRow( row ); else m_tableView->model()->removeColumn( row ); } // Deselect the deleted rows m_tableView->setCurrentIndex( QModelIndex() ); } void TableEditorDialog::slotCurrentIndexChanged( const QModelIndex &index ) { const bool isValid = index.isValid(); m_deleteRowsAction->setEnabled( isValid ); m_insertRowsAction->setEnabled( isValid ); deleteRow->setEnabled( isValid ); insertRow->setEnabled( isValid ); m_deleteColumnsAction->setEnabled( isValid ); m_insertColumnsAction->setEnabled( isValid ); deleteColumn->setEnabled( isValid ); insertColumn->setEnabled( isValid ); } void TableEditorDialog::slotDataSetsInRowsToggled( bool enabled ) { Q_ASSERT( m_proxyModel ); m_proxyModel->setDataDirection( enabled ? Qt::Horizontal : Qt::Vertical ); } diff --git a/plugins/formulashape/FormulaToolWidget.cpp b/plugins/formulashape/FormulaToolWidget.cpp index ed109192cc5..8f521779617 100644 --- a/plugins/formulashape/FormulaToolWidget.cpp +++ b/plugins/formulashape/FormulaToolWidget.cpp @@ -1,161 +1,162 @@ /* This file is part of the KDE project Copyright (C) 2007 Martin Pfeiffer 2009 Jeremias Epperlein 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 "FormulaToolWidget.h" #include "KoFormulaTool.h" #include "KoFormulaShape.h" #include "ElementFactory.h" #include "BasicElement.h" #include "FormulaCursor.h" #include "FormulaDebug.h" #include #include #include +#include #include FormulaToolWidget::FormulaToolWidget( KoFormulaTool* tool, QWidget* parent ) : QTabWidget( parent ) { m_tool = tool; setupUi( this ); // setup the element insert menus m_fractionMenu.addAction( m_tool->action( "insert_fraction" ) ); m_fractionMenu.addAction( m_tool->action( "insert_bevelled_fraction" ) ); m_fenceMenu.addAction( m_tool->action( "insert_fence" ) ); m_fenceMenu.addAction( m_tool->action( "insert_enclosed" ) ); m_tableMenu.addAction( m_tool->action( "insert_33table" ) ); m_tableMenu.addAction( m_tool->action( "insert_21table" ) ); m_rootMenu.addAction( m_tool->action( "insert_root" ) ); m_rootMenu.addAction( m_tool->action( "insert_sqrt" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_subscript" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_supscript" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_subsupscript" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_underscript" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_overscript" ) ); m_scriptsMenu.addAction( m_tool->action( "insert_underoverscript" ) ); m_alterTableMenu.addAction( m_tool->action( "insert_row") ); m_alterTableMenu.addAction( m_tool->action( "insert_column") ); m_alterTableMenu.addAction( m_tool->action( "remove_row") ); m_alterTableMenu.addAction( m_tool->action( "remove_column") ); // assign menus to toolbuttons buttonFence->setMenu( &m_fenceMenu ); buttonFence->setDefaultAction( m_tool->action( "insert_fence" ) ); buttonRoot->setMenu( &m_rootMenu ); buttonRoot->setDefaultAction( m_tool->action( "insert_sqrt" ) ); buttonFraction->setMenu( &m_fractionMenu ); buttonFraction->setDefaultAction(m_tool->action("insert_fraction")); buttonTable->setMenu( &m_tableMenu ); buttonTable->setDefaultAction(m_tool->action( "insert_33table")); buttonScript->setMenu( &m_scriptsMenu ); buttonScript->setDefaultAction(m_tool->action( "insert_subscript")); buttonAlterTable->setMenu(&m_alterTableMenu); buttonAlterTable->setDefaultAction(m_tool->action("insert_row")); // setup the buttons for symbol insertion buttonArrows->setText(QChar(0x2190)); setupButton(buttonArrows,m_arrowMenu,i18n("Arrows"), symbolsInRange(0x2190,0x21FF)); buttonGreek->setText(QChar(0x03B2)); setupButton(buttonGreek,m_greekMenu,i18n("Greek"), symbolsInRange(0x0391,0x03A1) <setText(QChar(0x2265)); setupButton(buttonRelation,m_relationMenu,i18n("Relations"), symbolsInRange(0x223C,0x2292) <setText(QChar(0x2211)); setupButton(buttonOperators,m_operatorMenu,i18n("Operators"), symbolsInRange(0x220F,0x2219) <setText(QChar(0x211A)); setupButton(buttonMisc,m_miscMenu,i18n("Miscellaneous"), symbolsInRange(0x2200,0x2205) <hide(); connect( buttonLoad, SIGNAL(clicked()), m_tool, SLOT(loadFormula()) ); connect( buttonSave, SIGNAL(clicked()), m_tool, SLOT(saveFormula()) ); connect( buttonAlterTable, SIGNAL(triggered(QAction*)), m_tool, SLOT(changeTable(QAction*))); } FormulaToolWidget::~FormulaToolWidget() {} void FormulaToolWidget::setFormulaTool( KoFormulaTool* tool ) { m_tool = tool; } void FormulaToolWidget::insertSymbol ( QTableWidgetItem* item ) { m_tool->insertSymbol(item->text()); } void FormulaToolWidget::setupButton ( QToolButton* button, QMenu& menu, const QString& text, QList list, int length) { QWidgetAction *widgetaction=new QWidgetAction(button); QTableWidget* table= new QTableWidget(list.length()/length,length,button); for (int i=0; isetFlags(Qt::ItemIsEnabled); table->setItem(i/length,i%length, newItem); } table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table->horizontalHeader()->hide(); table->verticalHeader()->hide(); table->resizeColumnsToContents(); table->resizeRowsToContents(); table->setShowGrid(false); table->setFixedSize(table->horizontalHeader()->length(), table->verticalHeader()->length()); button->setToolTip(text); //TODO: that is a little bit hackish // connect( table,SIGNAL(itemActivated(QTableWidgetItem*)), // table, SIGNAL(itemClicked(QTableWidgetItem*))); connect( table,SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(insertSymbol(QTableWidgetItem*))); connect( table,SIGNAL(itemClicked(QTableWidgetItem*)), &menu, SLOT(hide())); button->setPopupMode(QToolButton::InstantPopup); button->setMenu(&menu); widgetaction->setDefaultWidget(table); menu.addAction(widgetaction); } QList< QString > FormulaToolWidget::symbolsInRange ( int first, int last ) { QList list; for (int i=first;i<=last;++i) { list.append(QChar(i)); } return list; } diff --git a/sheets/dialogs/LayoutDialog.cpp b/sheets/dialogs/LayoutDialog.cpp index a0a9832ddfc..7d7db53823b 100644 --- a/sheets/dialogs/LayoutDialog.cpp +++ b/sheets/dialogs/LayoutDialog.cpp @@ -1,3571 +1,3572 @@ /* This file is part of the KDE project Copyright (C) 2006 Stefan Nikolaus (C) 2004 Tomas Mecir (C) 2002-2004 Ariya Hidayat (C) 2002-2003 Norbert Andres (C) 2001-2003 Philipp Mueller (C) 2002 John Dailey (C) 1999-2002 Laurent Montel (C) 1999-2002 Harri Porten (C) 2000-2001 David Faure (C) 1998-2000 Torben Weis (C) 2000 Werner Trobin (C) 1999 Reginald Stadlbauer (C) 1998-1999 Stephan Kulow 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. */ // Local #include "LayoutDialog.h" #include #include #include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "SheetsDebug.h" #include "CalculationSettings.h" #include "Cell.h" #include "CellStorage.h" #include "Localization.h" #include "Map.h" #include "RowFormatStorage.h" #include "ui/Selection.h" #include "Sheet.h" #include "Style.h" #include "StyleManager.h" #include "StyleStorage.h" #include "ValueFormatter.h" #include "commands/MergeCommand.h" #include "commands/StyleCommand.h" #include "commands/RowColumnManipulators.h" using namespace Calligra::Sheets; /*************************************************************************** * * PatternSelect * ***************************************************************************/ PatternSelect::PatternSelect(QWidget *parent, const char *) : QFrame(parent) { penStyle = Qt::NoPen; penWidth = 1; penColor = palette().text().color(); selected = false; undefined = false; } void PatternSelect::setPattern(const QColor &_color, int _width, Qt::PenStyle _style) { penStyle = _style; penColor = _color; penWidth = _width; repaint(); } void PatternSelect::setUndefined() { undefined = true; } void PatternSelect::paintEvent(QPaintEvent *_ev) { QFrame::paintEvent(_ev); QPainter painter(this); if (!undefined) { QPen pen(penColor, penWidth, penStyle); painter.setPen(pen); painter.drawLine(6, height() / 2, width() - 6, height() / 2); } else { painter.fillRect(2, 2, width() - 4, height() - 4, Qt::BDiagPattern); } } void PatternSelect::mousePressEvent(QMouseEvent *) { slotSelect(); emit clicked(this); } void PatternSelect::slotUnselect() { selected = false; setLineWidth(1); setFrameStyle(QFrame::Panel | QFrame::Sunken); repaint(); } void PatternSelect::slotSelect() { selected = true; setLineWidth(2); setFrameStyle(QFrame::Panel | QFrame::Plain); repaint(); } /*************************************************************************** * * GeneralTab * ***************************************************************************/ GeneralTab::GeneralTab(QWidget* parent, CellFormatDialog * dlg) : QWidget(parent), m_dlg(dlg) { QGridLayout * layout = new QGridLayout(this); QGroupBox * groupBox = new QGroupBox(this); groupBox->setTitle(i18n("Style")); QGridLayout * groupBoxLayout = new QGridLayout(groupBox); groupBoxLayout->setAlignment(Qt::AlignTop); QLabel * label1 = new QLabel(groupBox); label1->setText(i18nc("Name of the style", "Name:")); groupBoxLayout->addWidget(label1, 0, 0); m_nameEdit = new KLineEdit(groupBox); m_nameEdit->setText(m_dlg->styleName); groupBoxLayout->addWidget(m_nameEdit, 0, 1); m_nameStatus = new QLabel(groupBox); m_nameStatus->hide(); groupBoxLayout->addWidget(m_nameStatus, 1, 1); QLabel * label2 = new QLabel(groupBox); label2->setText(i18n("Inherit style:")); groupBoxLayout->addWidget(label2, 2, 0); m_parentBox = new KComboBox(false, groupBox); m_parentBox->clear(); QStringList tmp = m_dlg->getStyleManager()->styleNames(); tmp.removeAll(m_dlg->styleName); // place the default style first tmp.removeAll(i18n("Default")); m_parentBox->insertItem(0, i18n("Default")); m_parentBox->insertItems(1, tmp); if (!m_dlg->getStyle()->parentName().isNull()) m_parentBox->setCurrentIndex(m_parentBox->findText(m_dlg->getStyle()->parentName())); else m_parentBox->setCurrentIndex(m_parentBox->findText(i18n("Default"))); connect(m_parentBox, SIGNAL(activated(QString)), this, SLOT(parentChanged(QString))); connect(m_nameEdit, SIGNAL(textChanged(QString)), this, SLOT(styleNameChanged(QString))); groupBoxLayout->addWidget(m_parentBox, 2, 1); m_parentStatus = new QLabel(groupBox); m_parentStatus->hide(); groupBoxLayout->addWidget(m_parentStatus, 3, 1); QSpacerItem * spacer = new QSpacerItem(20, 260, QSizePolicy::Minimum, QSizePolicy::Expanding); layout->addWidget(groupBox, 0, 0); layout->addItem(spacer, 1, 0); if (m_dlg->getStyle()->type() == Style::BUILTIN) { m_nameEdit->setEnabled(false); m_parentBox->setEnabled(false); } resize(QSize(534, 447).expandedTo(minimumSizeHint())); } GeneralTab::~GeneralTab() { } void GeneralTab::styleNameChanged(const QString& name) { if (!m_dlg->getStyleManager()->validateStyleName(name, m_dlg->getStyle())) { m_nameStatus->setText(i18n("A style with this name already exists.")); m_nameStatus->show(); m_dlg->setOkButtonEnabled(false); } else if (name.isEmpty()) { m_nameStatus->setText(i18n("The style name can not be empty.")); m_nameStatus->show(); m_dlg->setOkButtonEnabled(false); } else { m_nameStatus->hide(); m_dlg->setOkButtonEnabled(true); } } void GeneralTab::parentChanged(const QString& parentName) { if (m_nameEdit->text() == parentName) { m_parentStatus->setText(i18n("A style cannot inherit from itself.")); m_parentStatus->show(); m_dlg->setOkButtonEnabled(false); } else if (!m_dlg->checkCircle(m_nameEdit->text(), parentName)) { m_parentStatus->setText(i18n("The style cannot inherit from '%1' because of recursive references.", m_parentBox->currentText())); m_parentStatus->show(); m_dlg->setOkButtonEnabled(false); } else { m_parentStatus->hide(); m_dlg->setOkButtonEnabled(true); } if (parentName.isEmpty() || parentName == i18n("Default")) m_dlg->getStyle()->clearAttribute(Style::NamedStyleKey); else m_dlg->getStyle()->setParentName(parentName); // Set difference to new parent, set GUI to parent values, add changes made before // m_dlg->initGUI(); } bool GeneralTab::apply(CustomStyle * style) { if (m_nameEdit->isEnabled()) { if (style->type() != Style::BUILTIN) { QString name(style->name()); style->setName(m_nameEdit->text()); if (m_parentBox->isEnabled()) { if (m_parentBox->currentText() == i18n("Default") || m_parentBox->currentText().isEmpty()) style->clearAttribute(Style::NamedStyleKey); else style->setParentName(m_parentBox->currentText()); } m_dlg->getStyleManager()->changeName(name, m_nameEdit->text()); } } if (style->type() == Style::TENTATIVE) style->setType(Style::CUSTOM); return true; } /*************************************************************************** * * CellFormatDialog * ***************************************************************************/ CellFormatDialog::CellFormatDialog(QWidget* parent, Selection* selection) : KPageDialog(parent) , m_sheet(selection->activeSheet()) , m_selection(selection) , m_style(0) , m_styleManager(0) { initMembers(); //We need both conditions quite often, so store the condition here too isRowSelected = m_selection->isRowSelected(); isColumnSelected = m_selection->isColumnSelected(); QRect range = m_selection->lastRange(); left = range.left(); top = range.top(); right = range.right(); bottom = range.bottom(); if (left == right) oneCol = true; else oneCol = false; if (top == bottom) oneRow = true; else oneRow = false; Cell cell = Cell(m_sheet, left, top); oneCell = (left == right && top == bottom && !cell.doesMergeCells()); isMerged = ((cell.doesMergeCells() && left + cell.mergedXCells() >= right && top + cell.mergedYCells() >= bottom)); // Initialize with the upper left object. const Style styleTopLeft = cell.style(); borders[BorderType_Left].style = styleTopLeft.leftBorderPen().style(); borders[BorderType_Left].width = styleTopLeft.leftBorderPen().width(); borders[BorderType_Left].color = styleTopLeft.leftBorderPen().color(); borders[BorderType_Top].style = styleTopLeft.topBorderPen().style(); borders[BorderType_Top].width = styleTopLeft.topBorderPen().width(); borders[BorderType_Top].color = styleTopLeft.topBorderPen().color(); borders[BorderType_FallingDiagonal].style = styleTopLeft.fallDiagonalPen().style(); borders[BorderType_FallingDiagonal].width = styleTopLeft.fallDiagonalPen().width(); borders[BorderType_FallingDiagonal].color = styleTopLeft.fallDiagonalPen().color(); borders[BorderType_RisingDiagonal].style = styleTopLeft.goUpDiagonalPen().style(); borders[BorderType_RisingDiagonal].width = styleTopLeft.goUpDiagonalPen().width(); borders[BorderType_RisingDiagonal].color = styleTopLeft.goUpDiagonalPen().color(); // Look at the upper right one for the right border. const Style styleTopRight = Cell(m_sheet, right, top).style(); borders[BorderType_Right].style = styleTopRight.rightBorderPen().style(); borders[BorderType_Right].width = styleTopRight.rightBorderPen().width(); borders[BorderType_Right].color = styleTopRight.rightBorderPen().color(); // Look at the bottom left cell for the bottom border. const Style styleBottomLeft = Cell(m_sheet, left, bottom).style(); borders[BorderType_Bottom].style = styleBottomLeft.bottomBorderPen().style(); borders[BorderType_Bottom].width = styleBottomLeft.bottomBorderPen().width(); borders[BorderType_Bottom].color = styleBottomLeft.bottomBorderPen().color(); // Just an assumption cell = Cell(m_sheet, right, top); if (cell.isPartOfMerged()) { cell = cell.masterCell(); const Style styleMove1 = Cell(m_sheet, cell.column(), top).style(); borders[BorderType_Vertical].style = styleMove1.leftBorderPen().style(); borders[BorderType_Vertical].width = styleMove1.leftBorderPen().width(); borders[BorderType_Vertical].color = styleMove1.leftBorderPen().color(); const Style styleMove2 = Cell(m_sheet, right, cell.row()).style(); borders[BorderType_Horizontal].style = styleMove2.topBorderPen().style(); borders[BorderType_Horizontal].width = styleMove2.topBorderPen().width(); borders[BorderType_Horizontal].color = styleMove2.topBorderPen().color(); } else { borders[BorderType_Vertical].style = styleTopRight.leftBorderPen().style(); borders[BorderType_Vertical].width = styleTopRight.leftBorderPen().width(); borders[BorderType_Vertical].color = styleTopRight.leftBorderPen().color(); const Style styleBottomRight = Cell(m_sheet, right, bottom).style(); borders[BorderType_Horizontal].style = styleBottomRight.topBorderPen().style(); borders[BorderType_Horizontal].width = styleBottomRight.topBorderPen().width(); borders[BorderType_Horizontal].color = styleBottomRight.topBorderPen().color(); } cell = Cell(m_sheet, left, top); prefix = styleTopLeft.prefix(); postfix = styleTopLeft.postfix(); precision = styleTopLeft.precision(); floatFormat = styleTopLeft.floatFormat(); floatColor = styleTopLeft.floatColor(); alignX = styleTopLeft.halign(); alignY = styleTopLeft.valign(); textColor = styleTopLeft.fontColor(); bgColor = styleTopLeft.backgroundColor(); fontSize = styleTopLeft.fontSize(); fontFamily = styleTopLeft.fontFamily(); fontBold = styleTopLeft.bold(); fontItalic = styleTopLeft.italic(); strike = styleTopLeft.strikeOut(); underline = styleTopLeft.underline(); // Needed to initialize the font correctly ( bug in Qt ) font = styleTopLeft.font(); m_currency = styleTopLeft.currency(); brushColor = styleTopLeft.backgroundBrush().color(); brushStyle = styleTopLeft.backgroundBrush().style(); bMultiRow = styleTopLeft.wrapText(); bVerticalText = styleTopLeft.verticalText(); bShrinkToFit = styleTopLeft.shrinkToFit(); textRotation = styleTopLeft.angle(); formatType = styleTopLeft.formatType(); bDontPrintText = !styleTopLeft.printText(); bHideFormula = styleTopLeft.hideFormula(); bHideAll = styleTopLeft.hideAll(); bIsProtected = !styleTopLeft.notProtected(); indent = styleTopLeft.indentation(); value = cell.value(); const ColumnFormat *cl; widthSize = 0.0; heightSize = 0.0; Selection::ConstIterator end(m_selection->constEnd()); for (Selection::ConstIterator it(m_selection->constBegin()); it != end; ++it) { QRect range = (*it)->rect(); Style style = m_sheet->cellStorage()->style(range); // FIXME merge initParameters(style); // left border range.setWidth(1); checkBorderLeft(m_sheet->cellStorage()->style(range)); // right border range = (*it)->rect(); range.setLeft(range.right()); checkBorderRight(m_sheet->cellStorage()->style(range)); // inner borders range = (*it)->rect(); range = range.adjusted(1, 1, -1, -1); style = m_sheet->cellStorage()->style(range); checkBorderHorizontal(style); checkBorderVertical(style); // top border range = (*it)->rect(); range.setHeight(1); checkBorderTop(style); // bottom border range = (*it)->rect(); range.setBottom(range.top()); checkBorderBottom(m_sheet->cellStorage()->style(range)); } // column width if (!isRowSelected) { for (int x = left; x <= right; x++) { cl = m_sheet->columnFormat(x); widthSize = qMax(cl->width(), widthSize); } } // row height if (!isColumnSelected) { for (int y = top; y <= bottom; y++) { heightSize = qMax(m_sheet->rowFormats()->rowHeight(y), static_cast(heightSize) ); } } if (!bTextRotation) textRotation = 0; init(); } CellFormatDialog::CellFormatDialog(QWidget* parent, Selection* selection, CustomStyle* style, StyleManager* manager) : KPageDialog(parent) , m_sheet(selection->activeSheet()) , m_selection(selection) , m_style(style) , m_styleManager(manager) { initMembers(); initGUI(); init(); } void CellFormatDialog::initGUI() { isRowSelected = false; isColumnSelected = false; styleName = m_style->name(); borders[BorderType_Left].style = m_style->leftBorderPen().style(); borders[BorderType_Left].width = m_style->leftBorderPen().width(); borders[BorderType_Left].color = m_style->leftBorderPen().color(); borders[BorderType_Top].style = m_style->topBorderPen().style(); borders[BorderType_Top].width = m_style->topBorderPen().width(); borders[BorderType_Top].color = m_style->topBorderPen().color(); borders[BorderType_Right].style = m_style->rightBorderPen().style(); borders[BorderType_Right].width = m_style->rightBorderPen().width(); borders[BorderType_Right].color = m_style->rightBorderPen().color(); borders[BorderType_Bottom].style = m_style->bottomBorderPen().style(); borders[BorderType_Bottom].width = m_style->bottomBorderPen().width(); borders[BorderType_Bottom].color = m_style->bottomBorderPen().color(); borders[BorderType_FallingDiagonal].style = m_style->fallDiagonalPen().style(); borders[BorderType_FallingDiagonal].width = m_style->fallDiagonalPen().width(); borders[BorderType_FallingDiagonal].color = m_style->fallDiagonalPen().color(); borders[BorderType_RisingDiagonal].style = m_style->goUpDiagonalPen().style(); borders[BorderType_RisingDiagonal].width = m_style->goUpDiagonalPen().width(); borders[BorderType_RisingDiagonal].color = m_style->goUpDiagonalPen().color(); borders[BorderType_Vertical].style = m_style->leftBorderPen().style(); borders[BorderType_Vertical].width = m_style->leftBorderPen().width(); borders[BorderType_Vertical].color = m_style->leftBorderPen().color(); borders[BorderType_Horizontal].style = m_style->topBorderPen().style(); borders[BorderType_Horizontal].width = m_style->topBorderPen().width(); borders[BorderType_Horizontal].color = m_style->topBorderPen().color(); prefix = m_style->prefix(); postfix = m_style->postfix(); precision = m_style->precision(); floatFormat = m_style->floatFormat(); floatColor = m_style->floatColor(); alignX = m_style->halign(); alignY = m_style->valign(); textColor = m_style->fontColor(); bgColor = m_style->backgroundColor(); fontSize = m_style->fontSize(); fontFamily = m_style->fontFamily(); fontBold = m_style->bold(); fontItalic = m_style->italic(); strike = m_style->strikeOut(); underline = m_style->underline(); // Needed to initialize the font correctly ( bug in Qt ) font = m_style->font(); m_currency = m_style->currency(); brushColor = m_style->backgroundBrush().color(); brushStyle = m_style->backgroundBrush().style(); bMultiRow = m_style->wrapText(); bVerticalText = m_style->verticalText(); bShrinkToFit = m_style->shrinkToFit(); textRotation = m_style->angle(); formatType = m_style->formatType(); indent = m_style->indentation(); bDontPrintText = !m_style->printText(); bHideFormula = m_style->hideFormula(); bHideAll = m_style->hideAll(); bIsProtected = !m_style->notProtected(); widthSize = defaultWidthSize; heightSize = defaultHeightSize; } CellFormatDialog::~CellFormatDialog() { delete formatOnlyNegSignedPixmap; delete formatRedOnlyNegSignedPixmap; delete formatRedNeverSignedPixmap; delete formatAlwaysSignedPixmap; delete formatRedAlwaysSignedPixmap; } void CellFormatDialog::initMembers() { formatOnlyNegSignedPixmap = 0; formatRedOnlyNegSignedPixmap = 0; formatRedNeverSignedPixmap = 0; formatAlwaysSignedPixmap = 0; formatRedAlwaysSignedPixmap = 0; // We assume, that all other objects have the same values for (int i = 0; i < BorderType_END; ++i) { borders[i].bStyle = true; borders[i].bColor = true; } bFloatFormat = true; bFloatColor = true; bTextColor = true; bBgColor = true; bTextFontFamily = true; bTextFontSize = true; bTextFontBold = true; bTextFontItalic = true; bStrike = true; bUnderline = true; bTextRotation = true; bFormatType = true; bCurrency = true; bDontPrintText = false; bHideFormula = false; bHideAll = false; bIsProtected = true; m_currency = Currency(); // locale default Sheet* sheet = m_sheet; defaultWidthSize = sheet ? sheet->map()->defaultColumnFormat()->width() : 0; defaultHeightSize = sheet ? sheet->map()->defaultRowFormat()->height() : 0; } bool CellFormatDialog::checkCircle(QString const & name, QString const & parent) { return m_styleManager->checkCircle(name, parent); } KLocale* CellFormatDialog::locale() const { return m_sheet->map()->calculationSettings()->locale(); } void CellFormatDialog::setOkButtonEnabled(bool enabled) { buttonBox()->button(QDialogButtonBox::Ok)->setEnabled(enabled); } void CellFormatDialog::checkBorderRight(const Style& style) { if (borders[BorderType_Right].style != style.rightBorderPen().style() || borders[BorderType_Right].width != style.rightBorderPen().width()) borders[BorderType_Right].bStyle = false; if (borders[BorderType_Right].color != style.rightBorderPen().color()) borders[BorderType_Right].bColor = false; } void CellFormatDialog::checkBorderLeft(const Style& style) { if (borders[BorderType_Left].style != style.leftBorderPen().style() || borders[BorderType_Left].width != style.leftBorderPen().width()) borders[BorderType_Left].bStyle = false; if (borders[BorderType_Left].color != style.leftBorderPen().color()) borders[BorderType_Left].bColor = false; } void CellFormatDialog::checkBorderTop(const Style& style) { if (borders[BorderType_Top].style != style.topBorderPen().style() || borders[BorderType_Top].width != style.topBorderPen().width()) borders[BorderType_Top].bStyle = false; if (borders[BorderType_Top].color != style.topBorderPen().color()) borders[BorderType_Top].bColor = false; } void CellFormatDialog::checkBorderBottom(const Style& style) { if (borders[BorderType_Bottom].style != style.bottomBorderPen().style() || borders[BorderType_Bottom].width != style.bottomBorderPen().width()) borders[BorderType_Bottom].bStyle = false; if (borders[BorderType_Bottom].color != style.bottomBorderPen().color()) borders[BorderType_Bottom].bColor = false; } void CellFormatDialog::checkBorderVertical(const Style& style) { if (borders[BorderType_Vertical].style != style.leftBorderPen().style() || borders[BorderType_Vertical].width != style.leftBorderPen().width()) borders[BorderType_Vertical].bStyle = false; if (borders[BorderType_Vertical].color != style.leftBorderPen().color()) borders[BorderType_Vertical].bColor = false; } void CellFormatDialog::checkBorderHorizontal(const Style& style) { if (borders[BorderType_Horizontal].style != style.topBorderPen().style() || borders[BorderType_Horizontal].width != style.topBorderPen().width()) borders[BorderType_Horizontal].bStyle = false; if (borders[BorderType_Horizontal].color != style.topBorderPen().color()) borders[BorderType_Horizontal].bColor = false; } void CellFormatDialog::initParameters(const Style& style) { if (borders[BorderType_FallingDiagonal].style != style.fallDiagonalPen().style()) borders[BorderType_FallingDiagonal].bStyle = false; if (borders[BorderType_FallingDiagonal].width != style.fallDiagonalPen().width()) borders[BorderType_FallingDiagonal].bStyle = false; if (borders[BorderType_FallingDiagonal].color != style.fallDiagonalPen().color()) borders[BorderType_FallingDiagonal].bColor = false; if (borders[BorderType_RisingDiagonal].style != style.goUpDiagonalPen().style()) borders[BorderType_RisingDiagonal].bStyle = false; if (borders[BorderType_RisingDiagonal].width != style.goUpDiagonalPen().width()) borders[BorderType_RisingDiagonal].bStyle = false; if (borders[BorderType_RisingDiagonal].color != style.goUpDiagonalPen().color()) borders[BorderType_RisingDiagonal].bColor = false; if (strike != style.strikeOut()) bStrike = false; if (underline != style.underline()) bUnderline = false; if (prefix != style.prefix()) prefix.clear(); if (postfix != style.postfix()) postfix.clear(); if (floatFormat != style.floatFormat()) bFloatFormat = false; if (floatColor != style.floatColor()) bFloatColor = false; if (textColor != style.fontColor()) bTextColor = false; if (fontFamily != style.fontFamily()) bTextFontFamily = false; if (fontSize != style.fontSize()) bTextFontSize = false; if (fontBold != style.bold()) bTextFontBold = false; if (fontItalic != style.italic()) bTextFontItalic = false; if (bgColor != style.backgroundColor()) bBgColor = false; if (textRotation != style.angle()) bTextRotation = false; if (formatType != style.formatType()) bFormatType = false; if (bMultiRow != style.wrapText()) bMultiRow = false; if (bVerticalText != style.verticalText()) bVerticalText = false; if (bShrinkToFit != style.shrinkToFit()) bShrinkToFit = false; if (!bDontPrintText != style.printText()) bDontPrintText = false; Currency currency = style.currency(); if (currency != m_currency) bCurrency = false; } void CellFormatDialog::init() { // Did we initialize the bitmaps ? if (formatOnlyNegSignedPixmap == 0) { formatOnlyNegSignedPixmap = paintFormatPixmap("123.456", Qt::black, "-123.456", Qt::black); formatRedOnlyNegSignedPixmap = paintFormatPixmap("123.456", Qt::black, "-123.456", Qt::red); formatRedNeverSignedPixmap = paintFormatPixmap("123.456", Qt::black, "123.456", Qt::red); formatAlwaysSignedPixmap = paintFormatPixmap("+123.456", Qt::black, "-123.456", Qt::black); formatRedAlwaysSignedPixmap = paintFormatPixmap("+123.456", Qt::black, "-123.456", Qt::red); } setWindowTitle(i18n("Cell Format")); setFaceType(KPageDialog::Tabbed); setMinimumWidth(600); setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); if (m_style) { generalPage = new GeneralTab(this, this); KPageWidgetItem* generalitem = addPage(generalPage, i18n("&General")); //generalitem->setHeader( i18n( "&General" ) ); Q_UNUSED(generalitem); } floatPage = new CellFormatPageFloat(this, this); addPage(floatPage, i18n("&Data Format")); fontPage = new CellFormatPageFont(this, this); addPage(fontPage, i18n("&Font")); // miscPage = new CellFormatPageMisc( tab, this ); // tab->addTab( miscPage, i18n("&Misc") ); positionPage = new CellFormatPagePosition(this, this); addPage(positionPage, i18n("&Position")); borderPage = new CellFormatPageBorder(this, this); addPage(borderPage, i18n("&Border")); patternPage = new CellFormatPagePattern(this, this); addPage(patternPage, i18n("Back&ground")); protectPage = new CellFormatPageProtection(this, this); addPage(protectPage, i18n("&Cell Protection")); connect(this, SIGNAL(accepted()), this, SLOT(slotApply())); } QPixmap * CellFormatDialog::paintFormatPixmap(const char * _string1, const QColor & _color1, const char *_string2, const QColor & _color2) { QPixmap * pixmap = new QPixmap(150, 14); pixmap->fill(Qt::transparent); QPainter painter; painter.begin(pixmap); painter.setPen(_color1); painter.drawText(2, 11, _string1); painter.setPen(_color2); painter.drawText(75, 11, _string2); painter.end(); return pixmap; } void CellFormatDialog::applyStyle() { generalPage->apply(m_style); borderPage->apply(0); floatPage->apply(m_style); // miscPage->apply( m_style ); fontPage->apply(m_style); positionPage->apply(m_style); patternPage->apply(m_style); protectPage->apply(m_style); } void CellFormatDialog::slotApply() { if (m_style) { applyStyle(); return; } // (Tomas) TODO: this will be slow !!! // We need to create a command that would act as macro, // but which would also ensure that updates are not painted until everything // is updated properly ... KUndo2Command* macroCommand = new KUndo2Command(kundo2_i18n("Change Format")); if (isMerged != positionPage->getMergedCellState()) { MergeCommand* command = new MergeCommand(macroCommand); command->setSheet(m_sheet); command->setSelection(m_selection); if (!positionPage->getMergedCellState()) //dissociate cells command->setReverse(true); command->add(*m_selection); } StyleCommand* command = new StyleCommand(macroCommand); command->setSheet(m_sheet); command->add(*m_selection); borderPage->apply(command); floatPage->apply(command); fontPage->apply(command); positionPage->apply(command); patternPage->apply(command); protectPage->apply(command); if (int(positionPage->getSizeHeight()) != int(heightSize)) { ResizeRowManipulator* command = new ResizeRowManipulator(macroCommand); command->setSheet(m_sheet); command->setSize(positionPage->getSizeHeight()); command->add(*m_selection); } if (int(positionPage->getSizeWidth()) != int(widthSize)) { ResizeColumnManipulator* command = new ResizeColumnManipulator(macroCommand); command->setSheet(m_sheet); command->setSize(positionPage->getSizeWidth()); command->add(*m_selection); } m_selection->canvas()->addCommand(macroCommand); } /*************************************************************************** * * CellFormatPageFloat * ***************************************************************************/ CellFormatPageFloat::CellFormatPageFloat(QWidget* parent, CellFormatDialog *_dlg) : QWidget(parent), dlg(_dlg) { QVBoxLayout* layout = new QVBoxLayout(this); QGroupBox *grp = new QGroupBox(i18n("Format"), this); QGridLayout *grid = new QGridLayout(grp); int fHeight = grp->fontMetrics().height(); grid->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title generic = new QRadioButton(i18n("Generic"), grp); generic->setWhatsThis(i18n("This is the default format and Calligra Sheets autodetects the actual data type depending on the current cell data. By default, Calligra Sheets right justifies numbers, dates and times within a cell and left justifies anything else.")); grid->addWidget(generic, 1, 0); number = new QRadioButton(i18n("Number"), grp); number->setWhatsThis(i18n("The number notation uses the notation you globally choose in System Settings -> Common Appearance and Behavior -> Locale -> Country/Region & Language -> Numbers tab. Numbers are right justified by default.")); grid->addWidget(number, 2, 0); percent = new QRadioButton(i18n("Percent"), grp); percent->setWhatsThis(i18n("When you have a number in the current cell and you switch from the dcell format from Generic to Percent, the current cell number will be multiplied by 100%.\nFor example if you enter 12 and set the cell format to Percent, the number will then be 1,200 %. Switching back to Generic cell format will bring it back to 12.\nYou can also use the Percent icon in the Format Toolbar.")); grid->addWidget(percent, 3, 0); money = new QRadioButton(i18n("Money"), grp); money->setWhatsThis(i18n("The Money format converts your number into money notation using the settings globally fixed in System Settings -> Common Appearance and Behavior -> Locale -> Country/Region & Language -> Money. The currency symbol will be displayed and the precision will be the one set in System Settings.\nYou can also use the Currency icon in the Format Toolbar to set the cell formatting to look like your current currency.")); grid->addWidget(money, 4, 0); scientific = new QRadioButton(i18n("Scientific"), grp); scientific->setWhatsThis(i18n("The scientific format changes your number using the scientific notation. For example, 0.0012 will be changed to 1.2E-03. Going back using Generic cell format will display 0.0012 again.")); grid->addWidget(scientific, 5, 0); fraction = new QRadioButton(i18n("Fraction"), grp); fraction->setWhatsThis(i18n("The fraction format changes your number into a fraction. For example, 0.1 can be changed to 1/8, 2/16, 1/10, etc. You define the type of fraction by choosing it in the field on the right. If the exact fraction is not possible in the fraction mode you choose, the nearest closest match is chosen.\n For example: when we have 1.5 as number, we choose Fraction and Sixteenths 1/16 the text displayed into cell is \"1 8/16\" which is an exact fraction. If you have 1.4 as number in your cell and you choose Fraction and Sixteenths 1/16 then the cell will display \"1 6/16\" which is the nearest closest Sixteenth fraction.")); grid->addWidget(fraction, 6, 0); date = new QRadioButton(i18n("Date"), grp); date->setWhatsThis(i18n("To enter a date, you should enter it in one of the formats set in System Settings -> Common Appearance and Behavior -> Locale -> Country/Region & Language -> Time & Dates. There are two formats set here: the date format and the short date format.\nJust like you can drag down numbers you can also drag down dates and the next cells will also get dates.")); grid->addWidget(date, 7, 0); time = new QRadioButton(i18n("Time"), grp); time->setWhatsThis(i18n("This formats your cell content as a time. To enter a time, you should enter it in the Time format set in System Settings -> Common Appearance and Behavior -> Locale -> Country/Region & Language -> Date & Time. In the Cell Format dialog box you can set how the time should be displayed by choosing one of the available time format options. The default format is the system format set in System Settings. When the number in the cell does not make sense as a time, Calligra Sheets will display 00:00 in the global format you have in System Settings.")); grid->addWidget(time, 8, 0); datetime = new QRadioButton(i18n("Date and Time"), grp); datetime->setWhatsThis(i18n("This formats your cell content as date and time. To enter a date and a time, you should enter it in the Time format set in System Settings -> Common Appearance and Behavior -> Locale -> Country/Region & Language -> Time & Dates. In the Cell Format dialog box you can set how the time should be displayed by choosing one of the available date format options. The default format is the system format set in System Settings. When the number in the cell does not make sense as a date and time, Calligra Sheets will display 00:00 in the global format you have in System Settings.")); grid->addWidget(datetime, 9, 0); textFormat = new QRadioButton(i18n("Text"), grp); textFormat->setWhatsThis(i18n("This formats your cell content as text. This can be useful if you want a number treated as text instead as a number, for example for a ZIP code. Setting a number as text format will left justify it. When numbers are formatted as text, they cannot be used in calculations or formulas. It also change the way the cell is justified.")); grid->addWidget(textFormat, 10, 0); customFormat = new QRadioButton(i18n("Custom"), grp); customFormat->setWhatsThis(i18n("The custom format does not work yet. To be enabled in the next release.")); grid->addWidget(customFormat, 11, 0); customFormat->setEnabled(false); QGroupBox *box2 = new QGroupBox(grp); box2->setTitle(i18n("Preview")); QGridLayout *grid3 = new QGridLayout(box2); exampleLabel = new QLabel(box2); exampleLabel->setWhatsThis(i18n("This will display a preview of your choice so you can know what it does before clicking the OK button to validate it.")); grid3->addWidget(exampleLabel, 0, 1); grid->addWidget(box2, 9, 1, 3, 1); customFormatEdit = new KLineEdit(grp); grid->addWidget(customFormatEdit, 0, 1); customFormatEdit->setHidden(true); listFormat = new QListWidget(grp); grid->addWidget(listFormat, 1, 1, 8, 1); listFormat->setWhatsThis(i18n("Displays choices of format for the fraction, date or time formats.")); layout->addWidget(grp); /* *** */ QGroupBox *box = new QGroupBox(this); grid = new QGridLayout(box); postfix = new KLineEdit(box); postfix->setWhatsThis(i18n("You can add here a Postfix such as a $HK symbol to the end of each cell content in the checked format.")); grid->addWidget(postfix, 2, 1); precision = new QSpinBox(box); precision->setValue(dlg->precision); precision->setSpecialValueText(i18n("variable")); precision->setRange(-1, 10); precision->setSingleStep(1); precision->setWhatsThis(i18n("You can control how many digits are displayed after the decimal point for numeric values. This can also be changed using the Increase precision or Decrease precision icons in the Format toolbar. ")); grid->addWidget(precision, 1, 1); prefix = new KLineEdit(box); prefix->setWhatsThis(i18n("You can add here a Prefix such as a $ symbol at the start of each cell content in the checked format.")); grid->addWidget(prefix, 0, 1); format = new KComboBox(box); format->setWhatsThis(i18n("You can choose whether positive values are displayed with a leading + sign and whether negative values are shown in red.")); grid->addWidget(format, 0, 3); QLabel* tmpQLabel; tmpQLabel = new QLabel(box); grid->addWidget(tmpQLabel, 2, 0); tmpQLabel->setText(i18n("Postfix:")); postfix->setText(dlg->postfix); tmpQLabel = new QLabel(box); grid->addWidget(tmpQLabel, 0, 0); tmpQLabel->setText(i18n("Prefix:")); tmpQLabel = new QLabel(box); grid->addWidget(tmpQLabel, 1, 0); tmpQLabel->setText(i18n("Precision:")); prefix->setText(dlg->prefix); format->setIconSize(QSize(150, 14)); format->insertItem(0, *_dlg->formatOnlyNegSignedPixmap, ""); format->insertItem(1, *_dlg->formatRedOnlyNegSignedPixmap, ""); format->insertItem(2, *_dlg->formatRedNeverSignedPixmap, ""); format->insertItem(3, *_dlg->formatAlwaysSignedPixmap, ""); format->insertItem(4, *_dlg->formatRedAlwaysSignedPixmap, ""); tmpQLabel = new QLabel(box); grid->addWidget(tmpQLabel, 0, 2); tmpQLabel->setText(i18n("Format:")); currencyLabel = new QLabel(box); grid->addWidget(currencyLabel, 1, 2); currencyLabel->setText(i18n("Currency:")); currency = new KComboBox(box); grid->addWidget(currency, 1, 3); // fill the currency combo box currency->insertItem(0, i18n("Automatic")); int index = 2; //ignore first two in the list bool ok = true; QString text; while (ok) { text = Currency::chooseString(index, ok); if (ok) currency->insertItem(index - 1, text); else break; ++index; } currency->setCurrentIndex(0); currency->hide(); currencyLabel->hide(); if (!dlg->bFloatFormat || !dlg->bFloatColor) format->setCurrentIndex(5); else if (dlg->floatFormat == Style::OnlyNegSigned && dlg->floatColor == Style::AllBlack) format->setCurrentIndex(0); else if (dlg->floatFormat == Style::OnlyNegSigned && dlg->floatColor == Style::NegRed) format->setCurrentIndex(1); else if (dlg->floatFormat == Style::AlwaysUnsigned && dlg->floatColor == Style::NegRed) format->setCurrentIndex(2); else if (dlg->floatFormat == Style::AlwaysSigned && dlg->floatColor == Style::AllBlack) format->setCurrentIndex(3); else if (dlg->floatFormat == Style::AlwaysSigned && dlg->floatColor == Style::NegRed) format->setCurrentIndex(4); layout->addWidget(box); cellFormatType = dlg->formatType; newFormatType = cellFormatType; if (!cellFormatType) generic->setChecked(true); else { if (cellFormatType == Format::Number) number->setChecked(true); else if (cellFormatType == Format::Percentage) percent->setChecked(true); else if (cellFormatType == Format::Money) { money->setChecked(true); currencyLabel->show(); currency->show(); if (dlg->bCurrency) { QString tmp; if (dlg->m_currency.index() == 1) // custom currency unit tmp = dlg->m_currency.symbol(); else { bool ok = true; tmp = Currency::chooseString(dlg->m_currency.index(), ok); if (!ok) tmp = dlg->m_currency.symbol(); } currency->setCurrentIndex(currency->findText(tmp)); } } else if (cellFormatType == Format::Scientific) scientific->setChecked(true); else if (Format::isDate(cellFormatType)) date->setChecked(true); else if (Format::isTime(cellFormatType)) time->setChecked(true); else if (Format::isFraction(cellFormatType)) fraction->setChecked(true); else if (cellFormatType == Format::Text) textFormat->setChecked(true); else if (cellFormatType == Format::Custom) customFormat->setChecked(true); } connect(generic, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(fraction, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(money, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(date, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(datetime, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(scientific, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(number, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(percent, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(time, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(textFormat, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(customFormat, SIGNAL(clicked()), this, SLOT(slotChangeState())); connect(listFormat, SIGNAL(itemSelectionChanged()), this, SLOT(makeformat())); connect(precision, SIGNAL(valueChanged(int)), this, SLOT(slotChangeValue(int))); connect(prefix, SIGNAL(textChanged(QString)), this, SLOT(makeformat())); connect(postfix, SIGNAL(textChanged(QString)), this, SLOT(makeformat())); connect(currency, SIGNAL(activated(QString)), this, SLOT(currencyChanged(QString))); connect(format, SIGNAL(activated(int)), this, SLOT(formatChanged(int))); connect(format, SIGNAL(activated(int)), this, SLOT(makeformat())); slotChangeState(); m_bFormatColorChanged = false; m_bFormatTypeChanged = false; this->resize(400, 400); } void CellFormatPageFloat::formatChanged(int) { m_bFormatColorChanged = true; } void CellFormatPageFloat::slotChangeValue(int) { makeformat(); } void CellFormatPageFloat::slotChangeState() { QStringList list; listFormat->clear(); currency->hide(); currencyLabel->hide(); // start with enabled, they get disabled when inappropriate further down precision->setEnabled(true); prefix->setEnabled(true); postfix->setEnabled(true); format->setEnabled(true); if (generic->isChecked() || number->isChecked() || percent->isChecked() || scientific->isChecked() || textFormat->isChecked()) listFormat->setEnabled(false); else if (money->isChecked()) { listFormat->setEnabled(false); precision->setValue(2); currency->show(); currencyLabel->show(); } else if (date->isChecked()) { format->setEnabled(false); precision->setEnabled(false); prefix->setEnabled(false); postfix->setEnabled(false); listFormat->setEnabled(true); init(); } else if (datetime->isChecked()) { format->setEnabled(false); precision->setEnabled(false); prefix->setEnabled(false); postfix->setEnabled(false); listFormat->setEnabled(true); datetimeInit(); } else if (fraction->isChecked()) { precision->setEnabled(false); listFormat->setEnabled(true); list += i18n("Halves 1/2"); list += i18n("Quarters 1/4"); list += i18n("Eighths 1/8"); list += i18n("Sixteenths 1/16"); list += i18n("Tenths 1/10"); list += i18n("Hundredths 1/100"); list += i18n("One digit 5/9"); list += i18n("Two digits 15/22"); list += i18n("Three digits 153/652"); listFormat->addItems(list); if (cellFormatType == Format::fraction_half) listFormat->setCurrentRow(0); else if (cellFormatType == Format::fraction_quarter) listFormat->setCurrentRow(1); else if (cellFormatType == Format::fraction_eighth) listFormat->setCurrentRow(2); else if (cellFormatType == Format::fraction_sixteenth) listFormat->setCurrentRow(3); else if (cellFormatType == Format::fraction_tenth) listFormat->setCurrentRow(4); else if (cellFormatType == Format::fraction_hundredth) listFormat->setCurrentRow(5); else if (cellFormatType == Format::fraction_one_digit) listFormat->setCurrentRow(6); else if (cellFormatType == Format::fraction_two_digits) listFormat->setCurrentRow(7); else if (cellFormatType == Format::fraction_three_digits) listFormat->setCurrentRow(8); else listFormat->setCurrentRow(0); } else if (time->isChecked()) { precision->setEnabled(false); prefix->setEnabled(false); postfix->setEnabled(false); format->setEnabled(false); listFormat->setEnabled(true); list += i18n("System: ") + dlg->locale()->formatTime(QTime::currentTime(), false); list += i18n("System: ") + dlg->locale()->formatTime(QTime::currentTime(), true); QDateTime tmpTime(QDate(1, 1, 1900), QTime(10, 35, 25), Qt::UTC); ValueFormatter *fmt = dlg->getSheet()->map()->formatter(); list += fmt->timeFormat(tmpTime, Format::Time1); list += fmt->timeFormat(tmpTime, Format::Time2); list += fmt->timeFormat(tmpTime, Format::Time3); list += fmt->timeFormat(tmpTime, Format::Time4); list += fmt->timeFormat(tmpTime, Format::Time5); list += (fmt->timeFormat(tmpTime, Format::Time6) + i18n(" (=[mm]:ss)")); list += (fmt->timeFormat(tmpTime, Format::Time7) + i18n(" (=[hh]:mm:ss)")); list += (fmt->timeFormat(tmpTime, Format::Time8) + i18n(" (=[hh]:mm)")); listFormat->addItems(list); if (cellFormatType == Format::Time) listFormat->setCurrentRow(0); else if (cellFormatType == Format::SecondeTime) listFormat->setCurrentRow(1); else if (cellFormatType == Format::Time1) listFormat->setCurrentRow(2); else if (cellFormatType == Format::Time2) listFormat->setCurrentRow(3); else if (cellFormatType == Format::Time3) listFormat->setCurrentRow(4); else if (cellFormatType == Format::Time4) listFormat->setCurrentRow(5); else if (cellFormatType == Format::Time5) listFormat->setCurrentRow(6); else if (cellFormatType == Format::Time6) listFormat->setCurrentRow(7); else if (cellFormatType == Format::Time7) listFormat->setCurrentRow(8); else if (cellFormatType == Format::Time8) listFormat->setCurrentRow(9); else listFormat->setCurrentRow(0); } if (customFormat->isChecked()) { customFormatEdit->setHidden(false); precision->setEnabled(false); prefix->setEnabled(false); postfix->setEnabled(false); format->setEnabled(false); listFormat->setEnabled(true); } else customFormatEdit->setHidden(true); m_bFormatTypeChanged = true; makeformat(); } void CellFormatPageFloat::init() { QStringList list; QString tmp; QString tmp2; QDate tmpDate(2000, 2, 18); list += i18n("System: ") + dlg->locale()->formatDate(QDate::currentDate(), KLocale::ShortDate); list += i18n("System: ") + dlg->locale()->formatDate(QDate::currentDate(), KLocale::LongDate); ValueFormatter *fmt = dlg->getSheet()->map()->formatter(); /*18-Feb-00*/ list += fmt->dateFormat(tmpDate, Format::Date1); /*18-Feb-1999*/ list += fmt->dateFormat(tmpDate, Format::Date2); /*18-Feb*/ list += fmt->dateFormat(tmpDate, Format::Date3); /*18-2*/ list += fmt->dateFormat(tmpDate, Format::Date4); /*18/2/00*/ list += fmt->dateFormat(tmpDate, Format::Date5); /*18/5/1999*/ list += fmt->dateFormat(tmpDate, Format::Date6); /*Feb-99*/ list += fmt->dateFormat(tmpDate, Format::Date7); /*February-99*/ list += fmt->dateFormat(tmpDate, Format::Date8); /*February-1999*/ list += fmt->dateFormat(tmpDate, Format::Date9); /*F-99*/ list += fmt->dateFormat(tmpDate, Format::Date10); /*18/Feb*/ list += fmt->dateFormat(tmpDate, Format::Date11); /*18/2*/ list += fmt->dateFormat(tmpDate, Format::Date12); /*18/Feb/1999*/ list += fmt->dateFormat(tmpDate, Format::Date13); /*2000/Feb/18*/ list += fmt->dateFormat(tmpDate, Format::Date14); /*2000-Feb-18*/ list += fmt->dateFormat(tmpDate, Format::Date15); /*2000-2-18*/ list += fmt->dateFormat(tmpDate, Format::Date16); /*2 february 2000*/ list += fmt->dateFormat(tmpDate, Format::Date17); list += fmt->dateFormat(tmpDate, Format::Date18); list += fmt->dateFormat(tmpDate, Format::Date19); list += fmt->dateFormat(tmpDate, Format::Date20); list += fmt->dateFormat(tmpDate, Format::Date21); list += fmt->dateFormat(tmpDate, Format::Date22); list += fmt->dateFormat(tmpDate, Format::Date23); list += fmt->dateFormat(tmpDate, Format::Date24); list += fmt->dateFormat(tmpDate, Format::Date25); list += fmt->dateFormat(tmpDate, Format::Date26); list += fmt->dateFormat(tmpDate, Format::Date27); list += fmt->dateFormat(tmpDate, Format::Date28); list += fmt->dateFormat(tmpDate, Format::Date29); list += fmt->dateFormat(tmpDate, Format::Date30); list += fmt->dateFormat(tmpDate, Format::Date31); list += fmt->dateFormat(tmpDate, Format::Date32); list += fmt->dateFormat(tmpDate, Format::Date33); list += fmt->dateFormat(tmpDate, Format::Date34); list += fmt->dateFormat(tmpDate, Format::Date35); listFormat->addItems(list); if (cellFormatType == Format::ShortDate) listFormat->setCurrentRow(0); else if (cellFormatType == Format::TextDate) listFormat->setCurrentRow(1); else if (cellFormatType == Format::Date1) listFormat->setCurrentRow(2); else if (cellFormatType == Format::Date2) listFormat->setCurrentRow(3); else if (cellFormatType == Format::Date3) listFormat->setCurrentRow(4); else if (cellFormatType == Format::Date4) listFormat->setCurrentRow(5); else if (cellFormatType == Format::Date5) listFormat->setCurrentRow(6); else if (cellFormatType == Format::Date6) listFormat->setCurrentRow(7); else if (cellFormatType == Format::Date7) listFormat->setCurrentRow(8); else if (cellFormatType == Format::Date8) listFormat->setCurrentRow(9); else if (cellFormatType == Format::Date9) listFormat->setCurrentRow(10); else if (cellFormatType == Format::Date10) listFormat->setCurrentRow(11); else if (cellFormatType == Format::Date11) listFormat->setCurrentRow(12); else if (cellFormatType == Format::Date12) listFormat->setCurrentRow(13); else if (cellFormatType == Format::Date13) listFormat->setCurrentRow(14); else if (cellFormatType == Format::Date14) listFormat->setCurrentRow(15); else if (cellFormatType == Format::Date15) listFormat->setCurrentRow(16); else if (cellFormatType == Format::Date16) listFormat->setCurrentRow(17); else if (cellFormatType == Format::Date17) listFormat->setCurrentRow(18); else if (cellFormatType == Format::Date18) listFormat->setCurrentRow(19); else if (cellFormatType == Format::Date19) listFormat->setCurrentRow(20); else if (cellFormatType == Format::Date20) listFormat->setCurrentRow(21); else if (cellFormatType == Format::Date21) listFormat->setCurrentRow(22); else if (cellFormatType == Format::Date22) listFormat->setCurrentRow(23); else if (cellFormatType == Format::Date23) listFormat->setCurrentRow(24); else if (cellFormatType == Format::Date24) listFormat->setCurrentRow(25); else if (cellFormatType == Format::Date25) listFormat->setCurrentRow(26); else if (cellFormatType == Format::Date26) listFormat->setCurrentRow(27); else if (cellFormatType == Format::Date27) listFormat->setCurrentRow(28); else if (cellFormatType == Format::Date28) listFormat->setCurrentRow(29); else if (cellFormatType == Format::Date29) listFormat->setCurrentRow(30); else if (cellFormatType == Format::Date30) listFormat->setCurrentRow(31); else if (cellFormatType == Format::Date31) listFormat->setCurrentRow(32); else if (cellFormatType == Format::Date32) listFormat->setCurrentRow(33); else if (cellFormatType == Format::Date33) listFormat->setCurrentRow(34); else if (cellFormatType == Format::Date34) listFormat->setCurrentRow(35); else if (cellFormatType == Format::Date35) listFormat->setCurrentRow(36); else listFormat->setCurrentRow(0); } void CellFormatPageFloat::datetimeInit() { QStringList list; list += i18n("System: ") + dlg->locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::ShortDate); list += i18n("System: ") + dlg->locale()->formatDateTime(QDateTime::currentDateTime(), KLocale::LongDate); listFormat->addItems(list); } void CellFormatPageFloat::currencyChanged(const QString &) { int index = currency->currentIndex(); if (index > 0) ++index; dlg->m_currency = Currency(index); makeformat(); } void CellFormatPageFloat::updateFormatType() { if (generic->isChecked()) newFormatType = Format::Generic; else if (number->isChecked()) newFormatType = Format::Number; else if (percent->isChecked()) newFormatType = Format::Percentage; else if (date->isChecked()) { newFormatType = Format::ShortDate; switch (listFormat->currentRow()) { case 0: newFormatType = Format::ShortDate; break; case 1: newFormatType = Format::TextDate; break; case 2: newFormatType = Format::Date1; break; /*18-Feb-99*/ case 3: newFormatType = Format::Date2; break; /*18-Feb-1999*/ case 4: newFormatType = Format::Date3; break; /*18-Feb*/ case 5: newFormatType = Format::Date4; break; /*18-05*/ case 6: newFormatType = Format::Date5; break; /*18/05/00*/ case 7: newFormatType = Format::Date6; break; /*18/05/1999*/ case 8: newFormatType = Format::Date7; break;/*Feb-99*/ case 9: newFormatType = Format::Date8; break; /*February-99*/ case 10: newFormatType = Format::Date9; break; /*February-1999*/ case 11: newFormatType = Format::Date10; break; /*F-99*/ case 12: newFormatType = Format::Date11; break; /*18/Feb*/ case 13: newFormatType = Format::Date12; break; /*18/02*/ case 14: newFormatType = Format::Date13; break; /*18/Feb/1999*/ case 15: newFormatType = Format::Date14; break; /*2000/Feb/18*/ case 16: newFormatType = Format::Date15; break;/*2000-Feb-18*/ case 17: newFormatType = Format::Date16; break;/*2000-02-18*/ case 18: newFormatType = Format::Date17; break; /*2000-02-18*/ case 19: newFormatType = Format::Date18; break; case 20: newFormatType = Format::Date19; break; case 21: newFormatType = Format::Date20; break; case 22: newFormatType = Format::Date21; break; case 23: newFormatType = Format::Date22; break; case 24: newFormatType = Format::Date23; break; case 25: newFormatType = Format::Date24; break; case 26: newFormatType = Format::Date25; break; case 27: newFormatType = Format::Date26; break; case 28: newFormatType = Format::Date27; break; case 29: newFormatType = Format::Date28; break; case 30: newFormatType = Format::Date29; break; case 31: newFormatType = Format::Date30; break; case 32: newFormatType = Format::Date31; break; case 33: newFormatType = Format::Date32; break; case 34: newFormatType = Format::Date33; break; case 35: newFormatType = Format::Date34; break; case 36: newFormatType = Format::Date35; break; } } else if (money->isChecked()) newFormatType = Format::Money; else if (scientific->isChecked()) newFormatType = Format::Scientific; else if (fraction->isChecked()) { newFormatType = Format::fraction_half; switch (listFormat->currentRow()) { case 0: newFormatType = Format::fraction_half; break; case 1: newFormatType = Format::fraction_quarter; break; case 2: newFormatType = Format::fraction_eighth; break; case 3: newFormatType = Format::fraction_sixteenth; break; case 4: newFormatType = Format::fraction_tenth; break; case 5: newFormatType = Format::fraction_hundredth; break; case 6: newFormatType = Format::fraction_one_digit; break; case 7: newFormatType = Format::fraction_two_digits; break; case 8: newFormatType = Format::fraction_three_digits; break; } } else if (time->isChecked()) { newFormatType = Format::Time; switch (listFormat->currentRow()) { case 0: newFormatType = Format::Time; break; case 1: newFormatType = Format::SecondeTime; break; case 2: newFormatType = Format::Time1; break; case 3: newFormatType = Format::Time2; break; case 4: newFormatType = Format::Time3; break; case 5: newFormatType = Format::Time4; break; case 6: newFormatType = Format::Time5; break; case 7: newFormatType = Format::Time6; break; case 8: newFormatType = Format::Time7; break; case 9: newFormatType = Format::Time8; break; } } else if (textFormat->isChecked()) newFormatType = Format::Text; else if (customFormat->isChecked()) newFormatType = Format::Custom; } void CellFormatPageFloat::makeformat() { m_bFormatTypeChanged = true; QString tmp; updateFormatType(); QColor color; Style::FloatFormat floatFormat = Style::OnlyNegSigned; switch (format->currentIndex()) { case 0: floatFormat = Style::OnlyNegSigned; color = Qt::black; break; case 1: floatFormat = Style::OnlyNegSigned; color = Qt::red; break; case 2: floatFormat = Style::AlwaysUnsigned; color = Qt::red; break; case 3: floatFormat = Style::AlwaysSigned; color = Qt::black; break; case 4: floatFormat = Style::AlwaysSigned; color = Qt::red; break; } if (!dlg->value.isNumber() || dlg->value.asFloat() >= 0 || !format->isEnabled()) { color = Qt::black; } ValueFormatter *fmt = dlg->getSheet()->map()->formatter(); tmp = fmt->formatText(dlg->value, newFormatType, precision->value(), floatFormat, prefix->isEnabled() ? prefix->text() : QString(), postfix->isEnabled() ? postfix->text() : QString(), newFormatType == Format::Money ? dlg->m_currency.symbol() : QString()).asString(); if (tmp.length() > 50) tmp = tmp.left(50); exampleLabel->setText(tmp.prepend("")); } void CellFormatPageFloat::apply(CustomStyle * style) { if (postfix->text() != dlg->postfix) { if (postfix->isEnabled()) style->setPostfix(postfix->text()); else style->setPostfix(""); } if (prefix->text() != dlg->prefix) { if (prefix->isEnabled()) style->setPrefix(prefix->text()); else style->setPrefix(""); } if (dlg->precision != precision->value()) style->setPrecision(precision->value()); if (m_bFormatColorChanged) { switch (format->currentIndex()) { case 0: style->setFloatFormat(Style::OnlyNegSigned); style->setFloatColor(Style::AllBlack); break; case 1: style->setFloatFormat(Style::OnlyNegSigned); style->setFloatColor(Style::NegRed); break; case 2: style->setFloatFormat(Style::AlwaysUnsigned); style->setFloatColor(Style::NegRed); break; case 3: style->setFloatFormat(Style::AlwaysSigned); style->setFloatColor(Style::AllBlack); break; case 4: style->setFloatFormat(Style::AlwaysSigned); style->setFloatColor(Style::NegRed); break; } } if (m_bFormatTypeChanged) { style->setFormatType(newFormatType); if (money->isChecked()) { Currency currency; int index = this->currency->currentIndex(); if (index == 0) { if (this->currency->currentText() == i18n("Automatic")) currency = Currency(); else currency = Currency(this->currency->currentText()); } else { currency = Currency(++index); } style->setCurrency(currency); } } } void CellFormatPageFloat::apply(StyleCommand* _obj) { if (postfix->text() != dlg->postfix) if (postfix->isEnabled()) { // If we are in here it *never* can be disabled - FIXME (Werner)! if (postfix->isEnabled()) _obj->setPostfix(postfix->text()); else _obj->setPostfix(""); } if (prefix->text() != dlg->prefix) { if (prefix->isEnabled()) _obj->setPrefix(prefix->text()); else _obj->setPrefix(""); } if (dlg->precision != precision->value()) _obj->setPrecision(precision->value()); if (m_bFormatColorChanged) { switch (format->currentIndex()) { case 0: _obj->setFloatFormat(Style::OnlyNegSigned); _obj->setFloatColor(Style::AllBlack); break; case 1: _obj->setFloatFormat(Style::OnlyNegSigned); _obj->setFloatColor(Style::NegRed); break; case 2: _obj->setFloatFormat(Style::AlwaysUnsigned); _obj->setFloatColor(Style::NegRed); break; case 3: _obj->setFloatFormat(Style::AlwaysSigned); _obj->setFloatColor(Style::AllBlack); break; case 4: _obj->setFloatFormat(Style::AlwaysSigned); _obj->setFloatColor(Style::NegRed); break; } } if (m_bFormatTypeChanged) { _obj->setFormatType(newFormatType); if (money->isChecked()) { Currency currency; int index = this->currency->currentIndex(); if (index == 0) { if (this->currency->currentText() == i18n("Automatic")) currency = Currency(); else currency = Currency(this->currency->currentText()); } else { currency = Currency(++index); } _obj->setCurrency(currency); } } if (newFormatType == Format::Scientific) { // FIXME: temprorary fix to at least get precision to work // TODO: Add min-exponent-digits to dialog // Custom format overrides precision, so create a proper one QString format = "0."; if (precision->value() > 0) { for (int i = 0; i < precision->value(); ++i) format.append('0'); } format.append("E+00"); _obj->setCustomFormat(format); } else { // nothing else needs custom format _obj->setCustomFormat(QString()); } } /*************************************************************************** * * CellFormatPageProtection * ***************************************************************************/ CellFormatPageProtection::CellFormatPageProtection(QWidget* parent, CellFormatDialog * _dlg) : QWidget(parent), m_dlg(_dlg) { setupUi(this); connect(m_bHideAll, SIGNAL(toggled(bool)), m_bIsProtected, SLOT(setDisabled(bool))); connect(m_bHideAll, SIGNAL(toggled(bool)), m_bHideFormula, SLOT(setDisabled(bool))); m_bDontPrint->setChecked(m_dlg->bDontPrintText); m_bHideAll->setChecked(m_dlg->bHideAll); m_bHideFormula->setChecked(m_dlg->bHideFormula); m_bIsProtected->setChecked(m_dlg->bIsProtected); } CellFormatPageProtection::~CellFormatPageProtection() { } void CellFormatPageProtection::apply(CustomStyle * style) { if (m_dlg->bDontPrintText != m_bDontPrint->isChecked()) { style->setDontPrintText(m_bDontPrint->isChecked()); } if (m_dlg->bIsProtected != m_bIsProtected->isChecked()) { style->setNotProtected(!m_bIsProtected->isChecked()); } if (m_dlg->bHideAll != m_bHideAll->isChecked()) { style->setHideAll(m_bHideAll->isChecked()); } if (m_dlg->bHideFormula != m_bHideFormula->isChecked()) { style->setHideFormula(m_bHideFormula->isChecked()); } } void CellFormatPageProtection::apply(StyleCommand* _obj) { if (m_dlg->bDontPrintText != m_bDontPrint->isChecked()) _obj->setDontPrintText(m_bDontPrint->isChecked()); if (m_dlg->bIsProtected != m_bIsProtected->isChecked()) _obj->setNotProtected(!m_bIsProtected->isChecked()); if (m_dlg->bHideAll != m_bHideAll->isChecked()) _obj->setHideAll(m_bHideAll->isChecked()); if (m_dlg->bHideFormula != m_bHideFormula->isChecked()) _obj->setHideFormula(m_bHideFormula->isChecked()); } /*************************************************************************** * * CellFormatPageFont * ***************************************************************************/ CellFormatPageFont::CellFormatPageFont(QWidget* parent, CellFormatDialog *_dlg) : QWidget(parent) { setupUi(this); dlg = _dlg; bTextColorUndefined = !dlg->bTextColor; connect(textColorButton, SIGNAL(changed(QColor)), this, SLOT(slotSetTextColor(QColor))); QStringList tmpListFont; QFontDatabase *fontDataBase = new QFontDatabase(); tmpListFont = fontDataBase->families(); delete fontDataBase; family_combo->addItems(tmpListFont); selFont = dlg->font; if (dlg->bTextFontFamily) { selFont.setFamily(dlg->fontFamily); // debugSheets <<"Family =" << dlg->fontFamily; if (family_combo->findItems(dlg->fontFamily, Qt::MatchExactly).size() == 0) { family_combo->insertItem(0, ""); family_combo->setCurrentRow(0); } else family_combo->setCurrentItem(family_combo->findItems(dlg->fontFamily, Qt::MatchExactly)[0]); } else { family_combo->insertItem(0, ""); family_combo->setCurrentRow(0); } connect(family_combo, SIGNAL(currentTextChanged(QString)), SLOT(family_chosen_slot(QString))); QStringList lst; lst.append(""); for (unsigned int i = 1; i < 100; ++i) lst.append(QString("%1").arg(i)); size_combo->insertItems(0, lst); size_combo->setInsertPolicy(KComboBox::NoInsert); connect(size_combo, SIGNAL(activated(QString)), SLOT(size_chosen_slot(QString))); connect(size_combo , SIGNAL(editTextChanged(QString)), this, SLOT(size_chosen_slot(QString))); connect(weight_combo, SIGNAL(activated(QString)), SLOT(weight_chosen_slot(QString))); connect(style_combo, SIGNAL(activated(QString)), SLOT(style_chosen_slot(QString))); strike->setChecked(dlg->strike); connect(strike, SIGNAL(clicked()), SLOT(strike_chosen_slot())); underline->setChecked(dlg->underline); connect(underline, SIGNAL(clicked()), SLOT(underline_chosen_slot())); example_label->setText(i18n("Dolor Ipse")); connect(this, SIGNAL(fontSelected(QFont)), this, SLOT(display_example(QFont))); setCombos(); display_example(selFont); fontChanged = false; this->resize(400, 400); } void CellFormatPageFont::slotSetTextColor(const QColor &_color) { textColor = _color; bTextColorUndefined = false; } void CellFormatPageFont::apply(CustomStyle * style) { if (!bTextColorUndefined && textColor != dlg->textColor) style->setFontColor(textColor); if ((size_combo->currentIndex() != 0) && (dlg->fontSize != selFont.pointSize())) style->setFontSize(selFont.pointSize()); if ((selFont.family() != dlg->fontFamily) && family_combo->currentItem() != 0 && !family_combo->currentItem()->text().isEmpty()) style->setFontFamily(selFont.family()); style->setFontBold(weight_combo->currentIndex() != 0 && selFont.bold()); style->setFontItalic(style_combo->currentIndex() != 0 && selFont.italic()); style->setFontStrikeOut(strike->isChecked()); style->setFontUnderline(underline->isChecked()); } void CellFormatPageFont::apply(StyleCommand* _obj) { if (!bTextColorUndefined && textColor != dlg->textColor) _obj->setFontColor(textColor); if (fontChanged) { if ((size_combo->currentIndex() != 0) && (dlg->fontSize != selFont.pointSize())) _obj->setFontSize(selFont.pointSize()); if ((selFont.family() != dlg->fontFamily) && (family_combo->currentItem() != 0 && !family_combo->currentItem()->text().isEmpty())) _obj->setFontFamily(selFont.family()); if (weight_combo->currentIndex() != 0) _obj->setFontBold(selFont.bold()); if (style_combo->currentIndex() != 0) _obj->setFontItalic(selFont.italic()); _obj->setFontStrike(strike->isChecked()); _obj->setFontUnderline(underline->isChecked()); } } void CellFormatPageFont::underline_chosen_slot() { selFont.setUnderline(underline->isChecked()); emit fontSelected(selFont); } void CellFormatPageFont::strike_chosen_slot() { selFont.setStrikeOut(strike->isChecked()); emit fontSelected(selFont); } void CellFormatPageFont::family_chosen_slot(const QString & family) { selFont.setFamily(family); emit fontSelected(selFont); } void CellFormatPageFont::size_chosen_slot(const QString & size) { QString size_string = size; if (size_string.toInt() > 0) selFont.setPointSize(size_string.toInt()); emit fontSelected(selFont); } void CellFormatPageFont::weight_chosen_slot(const QString & weight) { QString weight_string = weight; if (weight_string == i18n("Normal")) selFont.setBold(false); if (weight_string == i18n("Bold")) selFont.setBold(true); emit fontSelected(selFont); } void CellFormatPageFont::style_chosen_slot(const QString & style) { QString style_string = style; if (style_string == i18n("Roman")) selFont.setItalic(false); if (style_string == i18n("Italic")) selFont.setItalic(true); emit fontSelected(selFont); } void CellFormatPageFont::display_example(const QFont& font) { QString string; fontChanged = true; example_label->setFont(font); example_label->repaint(); } void CellFormatPageFont::setCombos() { QString string; KComboBox* combo; int number_of_entries; if (dlg->bTextColor) textColor = dlg->textColor; else textColor = palette().text().color(); if (!textColor.isValid()) textColor = palette().text().color(); textColorButton->setColor(textColor); combo = size_combo; if (dlg->bTextFontSize) { // debugSheets <<"SIZE=" << dlg->fontSize; selFont.setPointSize(dlg->fontSize); number_of_entries = size_combo->count(); string.setNum(dlg->fontSize); for (int i = 0; i < number_of_entries ; i++) { if (string == (QString) combo->itemText(i)) { combo->setCurrentIndex(i); // debugSheets <<"Found Size" << string.data() <<" setting to item" i; break; } } } else combo->setCurrentIndex(0); if (!dlg->bTextFontBold) weight_combo->setCurrentIndex(0); else if (dlg->fontBold) { selFont.setBold(dlg->fontBold); weight_combo->setCurrentIndex(2); } else { selFont.setBold(dlg->fontBold); weight_combo->setCurrentIndex(1); } if (!dlg->bTextFontItalic) weight_combo->setCurrentIndex(0); else if (dlg->fontItalic) { selFont.setItalic(dlg->fontItalic); style_combo->setCurrentIndex(2); } else { selFont.setItalic(dlg->fontItalic); style_combo->setCurrentIndex(1); } } /*************************************************************************** * * CellFormatPagePosition * ***************************************************************************/ CellFormatPagePosition::CellFormatPagePosition(QWidget* parent, CellFormatDialog *_dlg) : QWidget(parent), dlg(_dlg) { setupUi(this); connect(angleRotation, SIGNAL(valueChanged(int)), spinBox3, SLOT(setValue(int))); connect(spinBox3, SIGNAL(valueChanged(int)), angleRotation, SLOT(setValue(int))); if (dlg->alignX == Style::Left) left->setChecked(true); else if (dlg->alignX == Style::Center) center->setChecked(true); else if (dlg->alignX == Style::Right) right->setChecked(true); else if (dlg->alignX == Style::HAlignUndefined) standard->setChecked(true); QButtonGroup* horizontalGroup = new QButtonGroup(this); horizontalGroup->addButton(left); horizontalGroup->addButton(center); horizontalGroup->addButton(right); horizontalGroup->addButton(standard); connect(horizontalGroup, SIGNAL(buttonClicked(int)), this, SLOT(slotStateChanged(int))); if (dlg->alignY == Style::Top) top->setChecked(true); else if (dlg->alignY == Style::Middle) middle->setChecked(true); else if (dlg->alignY == Style::Bottom) bottom->setChecked(true); multi->setChecked(dlg->bMultiRow); vertical->setChecked(dlg->bVerticalText); shrinkToFit->setChecked(dlg->bShrinkToFit); angleRotation->setValue(-dlg->textRotation);//annma spinBox3->setValue(-dlg->textRotation); if (dlg->textRotation != 0) { multi->setEnabled(false); vertical->setEnabled(false); shrinkToFit->setEnabled(false); } mergeCell->setChecked(dlg->isMerged); mergeCell->setEnabled(!dlg->oneCell && ((!dlg->isRowSelected) && (!dlg->isColumnSelected))); QGridLayout *grid2 = new QGridLayout(indentGroup); grid2->addItem(new QSpacerItem(0, indentGroup->fontMetrics().height() / 8), 0, 0); // groupbox title m_indent = new KoUnitDoubleSpinBox(indentGroup); m_indent->setMinimum(0.0); m_indent->setMaximum(400.0); m_indent->setLineStepPt(10.0); m_indent->setUnit(dlg->selection()->canvas()->unit()); m_indent->changeValue(dlg->indent); grid2->addWidget(m_indent, 0, 0); width = new KoUnitDoubleSpinBox(m_widthPanel); QGridLayout *gridWidth = new QGridLayout(m_widthPanel); gridWidth->setMargin(0); gridWidth->setSpacing(0); gridWidth->addWidget(width, 0, 0); width->setValue(dlg->widthSize); width->setUnit(dlg->selection()->canvas()->unit()); //to ensure, that we don't get rounding problems, we store the displayed value (for later check for changes) dlg->widthSize = width->value(); if (dlg->isRowSelected) width->setEnabled(false); double dw = dlg->selection()->canvas()->unit().toUserValue(dlg->defaultWidthSize); defaultWidth->setText(i18n("Default width (%1 %2)", dw, dlg->selection()->canvas()->unit().symbol())); if (dlg->isRowSelected) defaultWidth->setEnabled(false); height = new KoUnitDoubleSpinBox(m_heightPanel); QGridLayout *gridHeight = new QGridLayout(m_heightPanel); gridHeight->setMargin(0); gridHeight->setSpacing(0); gridHeight->addWidget(height, 0, 0); height->setValue(dlg->heightSize); height->setUnit(dlg->selection()->canvas()->unit()); //to ensure, that we don't get rounding problems, we store the displayed value (for later check for changes) dlg->heightSize = height->value(); if (dlg->isColumnSelected) height->setEnabled(false); double dh = dlg->selection()->canvas()->unit().toUserValue(dlg->defaultHeightSize); defaultHeight->setText(i18n("Default height (%1 %2)", dh, dlg->selection()->canvas()->unit().symbol())); if (dlg->isColumnSelected) defaultHeight->setEnabled(false); // in case we're editing a style, we disable the cell size settings if (dlg->getStyle()) { defaultHeight->setEnabled(false); defaultWidth->setEnabled(false); } connect(defaultWidth , SIGNAL(clicked()), this, SLOT(slotChangeWidthState())); connect(defaultHeight , SIGNAL(clicked()), this, SLOT(slotChangeHeightState())); connect(vertical , SIGNAL(clicked()), this, SLOT(slotChangeVerticalState())); connect(shrinkToFit, SIGNAL(clicked()), this, SLOT(slotChangeShrinkToFitState())); connect(multi , SIGNAL(clicked()), this, SLOT(slotChangeMultiState())); connect(angleRotation, SIGNAL(valueChanged(int)), this, SLOT(slotChangeAngle(int))); slotStateChanged(0); m_bOptionText = false; this->resize(400, 400); } void CellFormatPagePosition::slotChangeMultiState() { m_bOptionText = true; if (vertical->isChecked()) { vertical->setChecked(false); } } void CellFormatPagePosition::slotChangeVerticalState() { m_bOptionText = true; if (multi->isChecked()) { multi->setChecked(false); } if (shrinkToFit->isChecked()) { shrinkToFit->setChecked(false); } } void CellFormatPagePosition::slotChangeShrinkToFitState() { m_bOptionText = true; if (vertical->isChecked()) { vertical->setChecked(false); } if (multi->isChecked()) { multi->setChecked(false); } } void CellFormatPagePosition::slotStateChanged(int) { if (right->isChecked() || center->isChecked()) m_indent->setEnabled(false); else m_indent->setEnabled(true); } bool CellFormatPagePosition::getMergedCellState() const { return mergeCell->isChecked(); } void CellFormatPagePosition::slotChangeWidthState() { if (defaultWidth->isChecked()) width->setEnabled(false); else width->setEnabled(true); } void CellFormatPagePosition::slotChangeHeightState() { if (defaultHeight->isChecked()) height->setEnabled(false); else height->setEnabled(true); } void CellFormatPagePosition::slotChangeAngle(int _angle) { if (_angle == 0) { multi->setEnabled(true); vertical->setEnabled(true); } else { multi->setEnabled(false); vertical->setEnabled(false); } } void CellFormatPagePosition::apply(CustomStyle * style) { if (top->isChecked() && dlg->alignY != Style::Top) style->setVAlign(Style::Top); else if (bottom->isChecked() && dlg->alignY != Style::Bottom) style->setVAlign(Style::Bottom); else if (middle->isChecked() && dlg->alignY != Style::Middle) style->setVAlign(Style::Middle); if (left->isChecked() && dlg->alignX != Style::Left) style->setHAlign(Style::Left); else if (right->isChecked() && dlg->alignX != Style::Right) style->setHAlign(Style::Right); else if (center->isChecked() && dlg->alignX != Style::Center) style->setHAlign(Style::Center); else if (standard->isChecked() && dlg->alignX != Style::HAlignUndefined) style->setHAlign(Style::HAlignUndefined); if (m_bOptionText) { if (multi->isEnabled()) { style->setWrapText(multi->isChecked()); } if (vertical->isEnabled()) { style->setVerticalText(vertical->isChecked()); } if (shrinkToFit->isEnabled()) { style->setShrinkToFit(shrinkToFit->isChecked()); } } if (dlg->textRotation != angleRotation->value()) style->setAngle((-angleRotation->value())); if (m_indent->isEnabled() && dlg->indent != m_indent->value()) style->setIndentation(m_indent->value()); // setting the default column width and row height if (dlg->getStyle()->type() == Style::BUILTIN && dlg->getStyle()->name() == "Default") { if ((int) height->value() != (int) dlg->heightSize) { dlg->getSheet()->map()->setDefaultRowHeight(height->value()); } if ((int) width->value() != (int) dlg->widthSize) { dlg->getSheet()->map()->setDefaultColumnWidth(width->value()); } } } void CellFormatPagePosition::apply(StyleCommand* _obj) { Style::HAlign ax; Style::VAlign ay; if (top->isChecked()) ay = Style::Top; else if (bottom->isChecked()) ay = Style::Bottom; else if (middle->isChecked()) ay = Style::Middle; else ay = Style::Middle; // Default, just in case if (left->isChecked()) ax = Style::Left; else if (right->isChecked()) ax = Style::Right; else if (center->isChecked()) ax = Style::Center; else if (standard->isChecked()) ax = Style::HAlignUndefined; else ax = Style::HAlignUndefined; //Default, just in case if (top->isChecked() && ay != dlg->alignY) _obj->setVerticalAlignment(Style::Top); else if (bottom->isChecked() && ay != dlg->alignY) _obj->setVerticalAlignment(Style::Bottom); else if (middle->isChecked() && ay != dlg->alignY) _obj->setVerticalAlignment(Style::Middle); if (left->isChecked() && ax != dlg->alignX) _obj->setHorizontalAlignment(Style::Left); else if (right->isChecked() && ax != dlg->alignX) _obj->setHorizontalAlignment(Style::Right); else if (center->isChecked() && ax != dlg->alignX) _obj->setHorizontalAlignment(Style::Center); else if (standard->isChecked() && ax != dlg->alignX) _obj->setHorizontalAlignment(Style::HAlignUndefined); if (m_bOptionText) { if (multi->isEnabled()) _obj->setMultiRow(multi->isChecked()); else _obj->setMultiRow(false); } if (m_bOptionText) { if (vertical->isEnabled()) _obj->setVerticalText(vertical->isChecked()); else _obj->setVerticalText(false); } if (m_bOptionText) { if (shrinkToFit->isEnabled()) _obj->setShrinkToFit(shrinkToFit->isChecked()); else _obj->setShrinkToFit(false); } if (dlg->textRotation != angleRotation->value()) _obj->setAngle((-angleRotation->value())); if (m_indent->isEnabled() && dlg->indent != m_indent->value()) _obj->setIndentation(m_indent->value()); } double CellFormatPagePosition::getSizeHeight() const { if (defaultHeight->isChecked()) return dlg->defaultHeightSize; // guess who calls this! else return height->value(); } double CellFormatPagePosition::getSizeWidth() const { if (defaultWidth->isChecked()) return dlg->defaultWidthSize; // guess who calls this! else return width->value(); } /*************************************************************************** * * BorderButton * ***************************************************************************/ BorderButton::BorderButton(QWidget *parent, const char * /*_name*/) : QPushButton(parent) { penStyle = Qt::NoPen; penWidth = 1; penColor = palette().text().color(); setCheckable(true); setChecked(false); setChanged(false); } void BorderButton::mousePressEvent(QMouseEvent *) { this->setChecked(!isChecked()); emit clicked(this); } void BorderButton::setUndefined() { setPenStyle(Qt::SolidLine); setPenWidth(1); setColor(palette().midlight().color()); } void BorderButton::unselect() { setChecked(false); setPenWidth(1); setPenStyle(Qt::NoPen); setColor(palette().text().color()); setChanged(true); } /*************************************************************************** * * Border * ***************************************************************************/ Border::Border(QWidget *parent, const char * /*_name*/, bool _oneCol, bool _oneRow) : QFrame(parent) { setAutoFillBackground(true); oneCol = _oneCol; oneRow = _oneRow; } #define OFFSETX 5 #define OFFSETY 5 void Border::paintEvent(QPaintEvent *_ev) { QFrame::paintEvent(_ev); QPen pen; QPainter painter; painter.begin(this); pen = QPen(palette().midlight(), 2, Qt::SolidLine).color(); painter.setPen(pen); painter.drawLine(OFFSETX - 5, OFFSETY, OFFSETX , OFFSETY); painter.drawLine(OFFSETX, OFFSETY - 5, OFFSETX , OFFSETY); painter.drawLine(width() - OFFSETX, OFFSETY, width() , OFFSETY); painter.drawLine(width() - OFFSETX, OFFSETY - 5, width() - OFFSETX , OFFSETY); painter.drawLine(OFFSETX, height() - OFFSETY, OFFSETX , height()); painter.drawLine(OFFSETX - 5, height() - OFFSETY, OFFSETX , height() - OFFSETY); painter.drawLine(width() - OFFSETX, height() - OFFSETY, width() , height() - OFFSETY); painter.drawLine(width() - OFFSETX, height() - OFFSETY, width() - OFFSETX , height()); if (oneCol == false) { painter.drawLine(width() / 2, OFFSETY - 5, width() / 2 , OFFSETY); painter.drawLine(width() / 2 - 5, OFFSETY, width() / 2 + 5 , OFFSETY); painter.drawLine(width() / 2, height() - OFFSETY, width() / 2 , height()); painter.drawLine(width() / 2 - 5, height() - OFFSETY, width() / 2 + 5 , height() - OFFSETY); } if (oneRow == false) { painter.drawLine(OFFSETX - 5, height() / 2, OFFSETX , height() / 2); painter.drawLine(OFFSETX, height() / 2 - 5, OFFSETX , height() / 2 + 5); painter.drawLine(width() - OFFSETX, height() / 2, width(), height() / 2); painter.drawLine(width() - OFFSETX, height() / 2 - 5, width() - OFFSETX , height() / 2 + 5); } painter.end(); emit redraw(); } void Border::mousePressEvent(QMouseEvent* _ev) { emit choosearea(_ev); } /*************************************************************************** * * CellFormatPageBorder * ***************************************************************************/ CellFormatPageBorder::CellFormatPageBorder(QWidget* parent, CellFormatDialog *_dlg) : QWidget(parent), dlg(_dlg) { sheet = dlg->getSheet(); InitializeGrids(); InitializeBorderButtons(); InitializePatterns(); SetConnections(); preview->slotSelect(); pattern[2]->slotSelect(); style->setEnabled(false); size->setEnabled(false); preview->setPattern(Qt::black , 1, Qt::SolidLine); this->resize(400, 400); } void CellFormatPageBorder::InitializeGrids() { QGridLayout *grid = new QGridLayout(this); QGridLayout *grid2 = 0; QGroupBox* tmpQGroupBox = 0; /***********************/ /* here is the data to initialize all the border buttons with */ const char borderButtonNames[BorderType_END][20] = {"top", "bottom", "left", "right", "vertical", "fall", "go", "horizontal"}; const char shortcutButtonNames[BorderShortcutType_END][20] = {"remove", "all", "outline"}; QString borderButtonIconNames[BorderType_END] = { koIconName("format-border-set-top"), koIconName("format-border-set-bottom"), koIconName("format-border-set-left"), koIconName("format-border-set-right"), koIconName("format-border-set-internal-vertical"), koIconName("format-border-set-internal-horizontal"), koIconName("format-border-set-diagonal-tl-br"), koIconName("format-border-set-diagonal-bl-tr") }; QString shortcutButtonIconNames[BorderShortcutType_END] = { koIconName("format-border-set-none"), QString(), koIconName("format-border-set-external") }; int borderButtonPositions[BorderType_END][2] = {{0, 2}, {4, 2}, {2, 0}, {2, 4}, {4, 4}, {4, 0}, {0, 0}, {0, 4}}; int shortcutButtonPositions[BorderShortcutType_END][2] = { {0, 0}, {0, 1}, {0, 2} }; /***********************/ /* set up a layout box for most of the border setting buttons */ tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Border")); tmpQGroupBox->setAlignment(Qt::AlignLeft); grid2 = new QGridLayout(tmpQGroupBox); int fHeight = tmpQGroupBox->fontMetrics().height(); grid2->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title area = new Border(tmpQGroupBox, "area", dlg->oneCol, dlg->oneRow); grid2->addWidget(area, 2, 1, 3, 3); QPalette palette = area->palette(); palette.setColor(area->backgroundRole(), this->palette().base().color()); area->setPalette(palette); /* initailize the buttons that are in this box */ for (int i = BorderType_Top; i < BorderType_END; i++) { borderButtons[i] = new BorderButton(tmpQGroupBox, borderButtonNames[i]); loadIcon(borderButtonIconNames[i], borderButtons[i]); grid2->addWidget(borderButtons[i], borderButtonPositions[i][0] + 1, borderButtonPositions[i][1]); } grid->addWidget(tmpQGroupBox, 0, 0, 3, 1); /* the remove, all, and outline border buttons are in a second box down below.*/ tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Preselect")); tmpQGroupBox->setAlignment(Qt::AlignLeft); grid2 = new QGridLayout(tmpQGroupBox); /* the "all" button is different depending on what kind of region is currently selected */ if ((dlg->oneRow == true) && (dlg->oneCol == false)) { shortcutButtonIconNames[BorderShortcutType_All] = koIconName("format-border-set-internal-vertical"); } else if ((dlg->oneRow == false) && (dlg->oneCol == true)) { shortcutButtonIconNames[BorderShortcutType_All] = koIconName("format-border-set-internal-horizontal"); } else { shortcutButtonIconNames[BorderShortcutType_All] = koIconName("format-border-set-internal"); } for (int i = BorderShortcutType_Remove; i < BorderShortcutType_END; i++) { shortcutButtons[i] = new BorderButton(tmpQGroupBox, shortcutButtonNames[i]); loadIcon(shortcutButtonIconNames[i], shortcutButtons[i]); grid2->addWidget(shortcutButtons[i], shortcutButtonPositions[i][0], shortcutButtonPositions[i][1]); } if (dlg->oneRow && dlg->oneCol) { shortcutButtons[BorderShortcutType_All]->setEnabled(false); } grid->addWidget(tmpQGroupBox, 3, 0, 2, 1); /* now set up the group box with the pattern selector */ tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Pattern")); tmpQGroupBox->setAlignment(Qt::AlignLeft); grid2 = new QGridLayout(tmpQGroupBox); fHeight = tmpQGroupBox->fontMetrics().height(); grid2->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title char name[] = "PatternXX"; Q_ASSERT(NUM_BORDER_PATTERNS < 100); for (int i = 0; i < NUM_BORDER_PATTERNS; i++) { name[7] = '0' + (i + 1) / 10; name[8] = '0' + (i + 1) % 10; pattern[i] = new PatternSelect(tmpQGroupBox, name); pattern[i]->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(pattern[i], i % 5, i / 5); /* this puts them in the pattern: 1 6 2 7 3 8 4 9 5 10 */ } color = new KColorButton(tmpQGroupBox); grid2->addWidget(color, 8, 1); QLabel *tmpQLabel = new QLabel(tmpQGroupBox); tmpQLabel->setText(i18n("Color:")); grid2->addWidget(tmpQLabel, 8, 0); /* tack on the 'customize' border pattern selector */ customize = new QCheckBox(i18n("Customize"), tmpQGroupBox); grid2->addWidget(customize, 6, 0); connect(customize, SIGNAL(clicked()), SLOT(cutomize_chosen_slot())); size = new KComboBox(tmpQGroupBox); size->setEditable(true); grid2->addWidget(size, 7, 1); size->setValidator(new QIntValidator(size)); QString tmp; for (int i = 0; i < 10; i++) { tmp = tmp.setNum(i); size->insertItem(i, tmp); } size->setCurrentIndex(1); style = new KComboBox(tmpQGroupBox); grid2->addWidget(style, 7, 0); style->setIconSize(QSize(100, 14)); style->insertItem(0, paintFormatPixmap(Qt::DotLine), ""); style->insertItem(1, paintFormatPixmap(Qt::DashLine), ""); style->insertItem(2, paintFormatPixmap(Qt::DashDotLine), ""); style->insertItem(3, paintFormatPixmap(Qt::DashDotDotLine), ""); style->insertItem(4, paintFormatPixmap(Qt::SolidLine), ""); palette = style->palette(); palette.setColor(style->backgroundRole(), this->palette().window().color()); style->setPalette(palette); grid->addWidget(tmpQGroupBox, 0, 1, 4, 1); /* Now the preview box is put together */ tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Preview")); tmpQGroupBox->setAlignment(Qt::AlignLeft); grid2 = new QGridLayout(tmpQGroupBox); fHeight = tmpQGroupBox->fontMetrics().height(); grid2->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title preview = new PatternSelect(tmpQGroupBox, "Pattern_preview"); preview->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(preview, 1, 0); grid->addWidget(tmpQGroupBox, 4, 1); } void CellFormatPageBorder::InitializeBorderButtons() { for (int i = BorderType_Top; i < BorderType_END; i++) { if (dlg->borders[i].style != Qt::NoPen || !dlg->borders[i].bStyle) { /* the horozontil and vertical buttons might be disabled depending on what kind of area is selected so check that first. */ if ((dlg->oneRow == true && i == BorderType_Horizontal) || (dlg->oneCol == true && i == BorderType_Vertical)) { borderButtons[i]->setEnabled(false); } else if (dlg->borders[i].bColor && dlg->borders[i].bStyle) { borderButtons[i]->setPenStyle(dlg->borders[i].style); borderButtons[i]->setPenWidth(dlg->borders[i].width); borderButtons[i]->setColor(dlg->borders[i].color); borderButtons[i]->setChecked(true); } else { borderButtons[i]->setUndefined(); } } } } void CellFormatPageBorder::InitializePatterns() { pattern[0]->setPattern(Qt::black, 1, Qt::DotLine); pattern[1]->setPattern(Qt::black, 1, Qt::DashLine); pattern[2]->setPattern(Qt::black, 1, Qt::SolidLine); pattern[3]->setPattern(Qt::black, 1, Qt::DashDotLine); pattern[4]->setPattern(Qt::black, 1, Qt::DashDotDotLine); pattern[5]->setPattern(Qt::black, 2, Qt::SolidLine); pattern[6]->setPattern(Qt::black, 3, Qt::SolidLine); pattern[7]->setPattern(Qt::black, 4, Qt::SolidLine); pattern[8]->setPattern(Qt::black, 5, Qt::SolidLine); pattern[9]->setPattern(Qt::black, 1, Qt::NoPen); slotSetColorButton(Qt::black); } void CellFormatPageBorder::SetConnections() { connect(color, SIGNAL(changed(QColor)), this, SLOT(slotSetColorButton(QColor))); for (int i = 0; i < NUM_BORDER_PATTERNS; i++) { connect(pattern[i], SIGNAL(clicked(PatternSelect*)), this, SLOT(slotUnselect2(PatternSelect*))); } for (int i = BorderType_Top; i < BorderType_END; i++) { connect(borderButtons[i], SIGNAL(clicked(BorderButton*)), this, SLOT(changeState(BorderButton*))); } for (int i = BorderShortcutType_Remove; i < BorderShortcutType_END; i++) { connect(shortcutButtons[i], SIGNAL(clicked(BorderButton*)), this, SLOT(preselect(BorderButton*))); } connect(area , SIGNAL(redraw()), this, SLOT(draw())); connect(area , SIGNAL(choosearea(QMouseEvent*)), this, SLOT(slotPressEvent(QMouseEvent*))); connect(style, SIGNAL(activated(int)), this, SLOT(slotChangeStyle(int))); connect(size, SIGNAL(editTextChanged(QString)), this, SLOT(slotChangeStyle(QString))); connect(size , SIGNAL(activated(int)), this, SLOT(slotChangeStyle(int))); } void CellFormatPageBorder::cutomize_chosen_slot() { if (customize->isChecked()) { style->setEnabled(true); size->setEnabled(true); slotUnselect2(preview); } else { style->setEnabled(false); size->setEnabled(false); pattern[2]->slotSelect(); preview->setPattern(Qt::black , 1, Qt::SolidLine); } } void CellFormatPageBorder::slotChangeStyle(const QString &) { /* if they try putting text in the size box, then erase the line */ slotChangeStyle(0); } void CellFormatPageBorder::slotChangeStyle(int) { int index = style->currentIndex(); QString tmp; int penSize = size->currentText().toInt(); if (!penSize) { preview->setPattern(preview->getColor(), penSize, Qt::NoPen); } else { switch (index) { case 0: preview->setPattern(preview->getColor(), penSize, Qt::DotLine); break; case 1: preview->setPattern(preview->getColor(), penSize, Qt::DashLine); break; case 2: preview->setPattern(preview->getColor(), penSize, Qt::DashDotLine); break; case 3: preview->setPattern(preview->getColor(), penSize, Qt::DashDotDotLine); break; case 4: preview->setPattern(preview->getColor(), penSize, Qt::SolidLine); break; default: debugSheets << "Error in combobox"; break; } } slotUnselect2(preview); } QPixmap CellFormatPageBorder::paintFormatPixmap(Qt::PenStyle _style) { QPixmap pixmap(100, 14); pixmap.fill(Qt::transparent); QPainter painter; painter.begin(&pixmap); painter.setPen(QPen(palette().text().color(), 5, _style)); painter.drawLine(0, 7, 100, 7); painter.end(); return pixmap; } void CellFormatPageBorder::loadIcon(const QString &iconName, BorderButton *_button) { _button->setIcon(QIcon::fromTheme(iconName)); } void CellFormatPageBorder::apply(StyleCommand* obj) { if (borderButtons[BorderType_Horizontal]->isChanged()) applyHorizontalOutline(obj); if (borderButtons[BorderType_Vertical]->isChanged()) applyVerticalOutline(obj); if (borderButtons[BorderType_Left]->isChanged()) applyLeftOutline(obj); if (borderButtons[BorderType_Right]->isChanged()) applyRightOutline(obj); if (borderButtons[BorderType_Top]->isChanged()) applyTopOutline(obj); if (borderButtons[BorderType_Bottom]->isChanged()) applyBottomOutline(obj); if (borderButtons[BorderType_RisingDiagonal]->isChanged() || borderButtons[BorderType_FallingDiagonal]->isChanged()) applyDiagonalOutline(obj); } void CellFormatPageBorder::applyTopOutline(StyleCommand* obj) { BorderButton * top = borderButtons[BorderType_Top]; QPen tmpPen(top->getColor(), top->getPenWidth(), top->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setTopBorderPen(tmpPen); } else { if (borderButtons[BorderType_Top]->isChanged()) obj->setTopBorderPen(tmpPen); } } void CellFormatPageBorder::applyBottomOutline(StyleCommand* obj) { BorderButton * bottom = borderButtons[BorderType_Bottom]; QPen tmpPen(bottom->getColor(), bottom->getPenWidth(), bottom->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setBottomBorderPen(tmpPen); } else { if (borderButtons[BorderType_Bottom]->isChanged()) obj->setBottomBorderPen(tmpPen); } } void CellFormatPageBorder::applyLeftOutline(StyleCommand* obj) { BorderButton * left = borderButtons[BorderType_Left]; QPen tmpPen(left->getColor(), left->getPenWidth(), left->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setLeftBorderPen(tmpPen); } else { if (borderButtons[BorderType_Left]->isChanged()) obj->setLeftBorderPen(tmpPen); } } void CellFormatPageBorder::applyRightOutline(StyleCommand* obj) { BorderButton* right = borderButtons[BorderType_Right]; QPen tmpPen(right->getColor(), right->getPenWidth(), right->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setRightBorderPen(tmpPen); } else { if (borderButtons[BorderType_Right]->isChanged()) obj->setRightBorderPen(tmpPen); } } void CellFormatPageBorder::applyDiagonalOutline(StyleCommand* obj) { BorderButton * fallDiagonal = borderButtons[BorderType_FallingDiagonal]; BorderButton * goUpDiagonal = borderButtons[BorderType_RisingDiagonal]; QPen tmpPenFall(fallDiagonal->getColor(), fallDiagonal->getPenWidth(), fallDiagonal->getPenStyle()); QPen tmpPenGoUp(goUpDiagonal->getColor(), goUpDiagonal->getPenWidth(), goUpDiagonal->getPenStyle()); if (dlg->getStyle()) { if (fallDiagonal->isChanged()) dlg->getStyle()->setFallDiagonalPen(tmpPenFall); if (goUpDiagonal->isChanged()) dlg->getStyle()->setGoUpDiagonalPen(tmpPenGoUp); } else { if (fallDiagonal->isChanged()) obj->setFallDiagonalPen(tmpPenFall); if (goUpDiagonal->isChanged()) obj->setGoUpDiagonalPen(tmpPenGoUp); } } void CellFormatPageBorder::applyHorizontalOutline(StyleCommand* obj) { QPen tmpPen(borderButtons[BorderType_Horizontal]->getColor(), borderButtons[BorderType_Horizontal]->getPenWidth(), borderButtons[BorderType_Horizontal]->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setTopBorderPen(tmpPen); } else { if (borderButtons[BorderType_Horizontal]->isChanged()) obj->setHorizontalPen(tmpPen); } } void CellFormatPageBorder::applyVerticalOutline(StyleCommand* obj) { BorderButton* vertical = borderButtons[BorderType_Vertical]; QPen tmpPen(vertical->getColor(), vertical->getPenWidth(), vertical->getPenStyle()); if (dlg->getStyle()) { dlg->getStyle()->setLeftBorderPen(tmpPen); } else { if (borderButtons[BorderType_Vertical]->isChanged()) obj->setVerticalPen(tmpPen); } } void CellFormatPageBorder::slotSetColorButton(const QColor &_color) { currentColor = _color; for (int i = 0; i < NUM_BORDER_PATTERNS; ++i) { pattern[i]->setColor(currentColor); } preview->setColor(currentColor); } void CellFormatPageBorder::slotUnselect2(PatternSelect *_p) { for (int i = 0; i < NUM_BORDER_PATTERNS; ++i) { if (pattern[i] != _p) { pattern[i]->slotUnselect(); } } preview->setPattern(_p->getColor(), _p->getPenWidth(), _p->getPenStyle()); } void CellFormatPageBorder::preselect(BorderButton *_p) { BorderButton* top = borderButtons[BorderType_Top]; BorderButton* bottom = borderButtons[BorderType_Bottom]; BorderButton* left = borderButtons[BorderType_Left]; BorderButton* right = borderButtons[BorderType_Right]; BorderButton* vertical = borderButtons[BorderType_Vertical]; BorderButton* horizontal = borderButtons[BorderType_Horizontal]; BorderButton* remove = shortcutButtons[BorderShortcutType_Remove]; BorderButton* outline = shortcutButtons[BorderShortcutType_Outline]; BorderButton* all = shortcutButtons[BorderShortcutType_All]; _p->setChecked(false); if (_p == remove) { for (int i = BorderType_Top; i < BorderType_END; i++) { if (borderButtons[i]->isChecked()) { borderButtons[i]->unselect(); } } } if (_p == outline) { top->setChecked(true); top->setPenWidth(preview->getPenWidth()); top->setPenStyle(preview->getPenStyle()); top->setColor(currentColor); top->setChanged(true); bottom->setChecked(true); bottom->setPenWidth(preview->getPenWidth()); bottom->setPenStyle(preview->getPenStyle()); bottom->setColor(currentColor); bottom->setChanged(true); left->setChecked(true); left->setPenWidth(preview->getPenWidth()); left->setPenStyle(preview->getPenStyle()); left->setColor(currentColor); left->setChanged(true); right->setChecked(true); right->setPenWidth(preview->getPenWidth()); right->setPenStyle(preview->getPenStyle()); right->setColor(currentColor); right->setChanged(true); } if (_p == all) { if (dlg->oneRow == false) { horizontal->setChecked(true); horizontal->setPenWidth(preview->getPenWidth()); horizontal->setPenStyle(preview->getPenStyle()); horizontal->setColor(currentColor); horizontal->setChanged(true); } if (dlg->oneCol == false) { vertical->setChecked(true); vertical->setPenWidth(preview->getPenWidth()); vertical->setPenStyle(preview->getPenStyle()); vertical->setColor(currentColor); vertical->setChanged(true); } } area->repaint(); } void CellFormatPageBorder::changeState(BorderButton *_p) { _p->setChanged(true); if (_p->isChecked()) { _p->setPenWidth(preview->getPenWidth()); _p->setPenStyle(preview->getPenStyle()); _p->setColor(currentColor); } else { _p->setPenWidth(1); _p->setPenStyle(Qt::NoPen); _p->setColor(palette().text().color()); } area->repaint(); } void CellFormatPageBorder::draw() { BorderButton* top = borderButtons[BorderType_Top]; BorderButton* bottom = borderButtons[BorderType_Bottom]; BorderButton* left = borderButtons[BorderType_Left]; BorderButton* right = borderButtons[BorderType_Right]; BorderButton* risingDiagonal = borderButtons[BorderType_RisingDiagonal]; BorderButton* fallingDiagonal = borderButtons[BorderType_FallingDiagonal]; BorderButton* vertical = borderButtons[BorderType_Vertical]; BorderButton* horizontal = borderButtons[BorderType_Horizontal]; QPen pen; QPainter painter; painter.begin(area); if ((bottom->getPenStyle()) != Qt::NoPen) { pen = QPen(bottom->getColor(), bottom->getPenWidth(), bottom->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, area->height() - OFFSETY, area->width() - OFFSETX , area->height() - OFFSETY); } if ((top->getPenStyle()) != Qt::NoPen) { pen = QPen(top->getColor(), top->getPenWidth(), top->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, OFFSETY, area->width() - OFFSETX, OFFSETY); } if ((left->getPenStyle()) != Qt::NoPen) { pen = QPen(left->getColor(), left->getPenWidth(), left->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, OFFSETY, OFFSETX , area->height() - OFFSETY); } if ((right->getPenStyle()) != Qt::NoPen) { pen = QPen(right->getColor(), right->getPenWidth(), right->getPenStyle()); painter.setPen(pen); painter.drawLine(area->width() - OFFSETX, OFFSETY, area->width() - OFFSETX, area->height() - OFFSETY); } if ((fallingDiagonal->getPenStyle()) != Qt::NoPen) { pen = QPen(fallingDiagonal->getColor(), fallingDiagonal->getPenWidth(), fallingDiagonal->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, OFFSETY, area->width() - OFFSETX, area->height() - OFFSETY); if (dlg->oneCol == false && dlg->oneRow == false) { painter.drawLine(area->width() / 2, OFFSETY, area->width() - OFFSETX, area->height() / 2); painter.drawLine(OFFSETX, area->height() / 2 , area->width() / 2, area->height() - OFFSETY); } } if ((risingDiagonal->getPenStyle()) != Qt::NoPen) { pen = QPen(risingDiagonal->getColor(), risingDiagonal->getPenWidth(), risingDiagonal->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, area->height() - OFFSETY , area->width() - OFFSETX , OFFSETY); if (dlg->oneCol == false && dlg->oneRow == false) { painter.drawLine(area->width() / 2, OFFSETY, OFFSETX, area->height() / 2); painter.drawLine(area->width() / 2, area->height() - OFFSETY , area->width() - OFFSETX, area->height() / 2); } } if ((vertical->getPenStyle()) != Qt::NoPen) { pen = QPen(vertical->getColor(), vertical->getPenWidth(), vertical->getPenStyle()); painter.setPen(pen); painter.drawLine(area->width() / 2, 5 , area->width() / 2 , area->height() - 5); } if ((horizontal->getPenStyle()) != Qt::NoPen) { pen = QPen(horizontal->getColor(), horizontal->getPenWidth(), horizontal->getPenStyle()); painter.setPen(pen); painter.drawLine(OFFSETX, area->height() / 2, area->width() - OFFSETX, area->height() / 2); } painter.end(); } void CellFormatPageBorder::invertState(BorderButton *_p) { if (_p->isChecked()) { _p->unselect(); } else { _p->setChecked(true); _p->setPenWidth(preview->getPenWidth()); _p->setPenStyle(preview->getPenStyle()); _p->setColor(currentColor); _p->setChanged(true); } } void CellFormatPageBorder::slotPressEvent(QMouseEvent *_ev) { BorderButton* top = borderButtons[BorderType_Top]; BorderButton* bottom = borderButtons[BorderType_Bottom]; BorderButton* left = borderButtons[BorderType_Left]; BorderButton* right = borderButtons[BorderType_Right]; BorderButton* vertical = borderButtons[BorderType_Vertical]; BorderButton* horizontal = borderButtons[BorderType_Horizontal]; QRect rect(OFFSETX, OFFSETY - 8, area->width() - OFFSETX, OFFSETY + 8); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((top->getPenWidth() != preview->getPenWidth()) || (top->getColor() != currentColor) || (top->getPenStyle() != preview->getPenStyle())) && top->isChecked()) { top->setPenWidth(preview->getPenWidth()); top->setPenStyle(preview->getPenStyle()); top->setColor(currentColor); top->setChanged(true); } else invertState(top); } rect.setCoords(OFFSETX, area->height() - OFFSETY - 8, area->width() - OFFSETX, area->height() - OFFSETY + 8); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((bottom->getPenWidth() != preview->getPenWidth()) || (bottom->getColor() != currentColor) || (bottom->getPenStyle() != preview->getPenStyle())) && bottom->isChecked()) { bottom->setPenWidth(preview->getPenWidth()); bottom->setPenStyle(preview->getPenStyle()); bottom->setColor(currentColor); bottom->setChanged(true); } else invertState(bottom); } rect.setCoords(OFFSETX - 8, OFFSETY, OFFSETX + 8, area->height() - OFFSETY); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((left->getPenWidth() != preview->getPenWidth()) || (left->getColor() != currentColor) || (left->getPenStyle() != preview->getPenStyle())) && left->isChecked()) { left->setPenWidth(preview->getPenWidth()); left->setPenStyle(preview->getPenStyle()); left->setColor(currentColor); left->setChanged(true); } else invertState(left); } rect.setCoords(area->width() - OFFSETX - 8, OFFSETY, area->width() - OFFSETX + 8, area->height() - OFFSETY); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((right->getPenWidth() != preview->getPenWidth()) || (right->getColor() != currentColor) || (right->getPenStyle() != preview->getPenStyle())) && right->isChecked()) { right->setPenWidth(preview->getPenWidth()); right->setPenStyle(preview->getPenStyle()); right->setColor(currentColor); right->setChanged(true); } else invertState(right); } //don't work because I don't know how create a rectangle //for diagonal /*rect.setCoords(OFFSETX,OFFSETY,XLEN-OFFSETX,YHEI-OFFSETY); if (rect.contains(QPoint(_ev->x(),_ev->y()))) { invertState(fallDiagonal); } rect.setCoords(OFFSETX,YHEI-OFFSETY,XLEN-OFFSETX,OFFSETY); if (rect.contains(QPoint(_ev->x(),_ev->y()))) { invertState(goUpDiagonal); } */ if (dlg->oneCol == false) { rect.setCoords(area->width() / 2 - 8, OFFSETY, area->width() / 2 + 8, area->height() - OFFSETY); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((vertical->getPenWidth() != preview->getPenWidth()) || (vertical->getColor() != currentColor) || (vertical->getPenStyle() != preview->getPenStyle())) && vertical->isChecked()) { vertical->setPenWidth(preview->getPenWidth()); vertical->setPenStyle(preview->getPenStyle()); vertical->setColor(currentColor); vertical->setChanged(true); } else invertState(vertical); } } if (dlg->oneRow == false) { rect.setCoords(OFFSETX, area->height() / 2 - 8, area->width() - OFFSETX, area->height() / 2 + 8); if (rect.contains(QPoint(_ev->x(), _ev->y()))) { if (((horizontal->getPenWidth() != preview->getPenWidth()) || (horizontal->getColor() != currentColor) || (horizontal->getPenStyle() != preview->getPenStyle())) && horizontal->isChecked()) { horizontal->setPenWidth(preview->getPenWidth()); horizontal->setPenStyle(preview->getPenStyle()); horizontal->setColor(currentColor); horizontal->setChanged(true); } else invertState(horizontal); } } area->repaint(); } /*************************************************************************** * * BrushSelect * ***************************************************************************/ BrushSelect::BrushSelect(QWidget *parent, const char *) : QFrame(parent) { brushStyle = Qt::NoBrush; brushColor = Qt::red; selected = false; } void BrushSelect::setPattern(const QColor &_color, Qt::BrushStyle _style) { brushStyle = _style; brushColor = _color; repaint(); } void BrushSelect::paintEvent(QPaintEvent *_ev) { QFrame::paintEvent(_ev); QPainter painter; QBrush brush(brushColor, brushStyle); painter.begin(this); painter.setPen(Qt::NoPen); painter.setBrush(brush); painter.drawRect(2, 2, width() - 4, height() - 4); painter.end(); } void BrushSelect::mousePressEvent(QMouseEvent *) { slotSelect(); emit clicked(this); } void BrushSelect::slotUnselect() { selected = false; setLineWidth(1); setFrameStyle(QFrame::Panel | QFrame::Sunken); repaint(); } void BrushSelect::slotSelect() { selected = true; setLineWidth(2); setFrameStyle(QFrame::Panel | QFrame::Plain); repaint(); } /*************************************************************************** * * CellFormatPagePattern * ***************************************************************************/ CellFormatPagePattern::CellFormatPagePattern(QWidget* parent, CellFormatDialog *_dlg) : QWidget(parent) { dlg = _dlg; QGridLayout *grid = new QGridLayout(this); QGroupBox* tmpQGroupBox; tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Pattern")); tmpQGroupBox->setAlignment(Qt::AlignLeft); QGridLayout *grid2 = new QGridLayout(tmpQGroupBox); int fHeight = tmpQGroupBox->fontMetrics().height(); grid2->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title brush1 = new BrushSelect(tmpQGroupBox, "Frame_1"); brush1->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush1, 1, 0); brush2 = new BrushSelect(tmpQGroupBox, "Frame_2"); brush2->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush2, 1, 1); brush3 = new BrushSelect(tmpQGroupBox, "Frame_3"); brush3->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush3, 1, 2); brush4 = new BrushSelect(tmpQGroupBox, "Frame_4"); brush4->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush4, 2, 0); brush5 = new BrushSelect(tmpQGroupBox, "Frame_5"); brush5->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush5, 2, 1); brush6 = new BrushSelect(tmpQGroupBox, "Frame_6"); brush6->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush6, 2, 2); brush7 = new BrushSelect(tmpQGroupBox, "Frame_7"); brush7->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush7, 3, 0); brush8 = new BrushSelect(tmpQGroupBox, "Frame_8"); brush8->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush8, 3, 1); brush9 = new BrushSelect(tmpQGroupBox, "Frame_9"); brush9->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush9, 3, 2); brush10 = new BrushSelect(tmpQGroupBox, "Frame_10"); brush10->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush10, 4, 0); brush11 = new BrushSelect(tmpQGroupBox, "Frame_11"); brush11->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush11, 4, 1); brush12 = new BrushSelect(tmpQGroupBox, "Frame_12"); brush12->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush12, 4, 2); brush13 = new BrushSelect(tmpQGroupBox, "Frame_13"); brush13->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush13, 5, 0); brush14 = new BrushSelect(tmpQGroupBox, "Frame_14"); brush14->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush14, 5, 1); brush15 = new BrushSelect(tmpQGroupBox, "Frame_15"); brush15->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(brush15, 5, 2); QGridLayout *grid3 = new QGridLayout(); color = new KColorButton(tmpQGroupBox); grid3->addWidget(color, 0, 1); QLabel *tmpQLabel = new QLabel(tmpQGroupBox); tmpQLabel->setText(i18n("Color:")); grid3->addWidget(tmpQLabel, 0, 0); grid2->addItem(grid3, 6, 0, 1, 3); grid3 = new QGridLayout(); tmpQLabel = new QLabel(tmpQGroupBox); grid3->addWidget(tmpQLabel, 0, 0); tmpQLabel->setText(i18n("Background color:")); bgColorButton = new KColorButton(tmpQGroupBox); grid3->addWidget(bgColorButton, 0, 1); if (dlg->bBgColor) bgColor = dlg->bgColor; else bgColor = palette().base().color(); if (!bgColor.isValid()) bgColor = palette().base().color(); bgColorButton->setColor(bgColor); connect(bgColorButton, SIGNAL(changed(QColor)), this, SLOT(slotSetBackgroundColor(QColor))); notAnyColor = new QPushButton(i18n("No Color"), tmpQGroupBox); grid3->addWidget(notAnyColor, 0, 2); connect(notAnyColor, SIGNAL(clicked()), this, SLOT(slotNotAnyColor())); b_notAnyColor = true; grid2->addItem(grid3, 7, 0, 1, 3); grid->addWidget(tmpQGroupBox, 0, 0, 4, 1); tmpQGroupBox = new QGroupBox(this); tmpQGroupBox->setTitle(i18n("Preview")); tmpQGroupBox->setAlignment(Qt::AlignLeft); grid2 = new QGridLayout(tmpQGroupBox); fHeight = tmpQGroupBox->fontMetrics().height(); grid2->addItem(new QSpacerItem(0, fHeight / 2), 0, 0); // groupbox title current = new BrushSelect(tmpQGroupBox, "Current"); current->setFrameStyle(QFrame::Panel | QFrame::Sunken); grid2->addWidget(current, 1, 0); grid->addWidget(tmpQGroupBox, 4, 0); connect(brush1, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush2, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush3, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush4, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush5, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush6, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush7, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush8, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush9, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush10, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush11, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush12, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush13, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush14, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); connect(brush15, SIGNAL(clicked(BrushSelect*)), this, SLOT(slotUnselect2(BrushSelect*))); brush1->setPattern(Qt::red, Qt::VerPattern); brush2->setPattern(Qt::red, Qt::HorPattern); brush3->setPattern(Qt::red, Qt::Dense1Pattern); brush4->setPattern(Qt::red, Qt::Dense2Pattern); brush5->setPattern(Qt::red, Qt::Dense3Pattern); brush6->setPattern(Qt::red, Qt::Dense4Pattern); brush7->setPattern(Qt::red, Qt::Dense5Pattern); brush8->setPattern(Qt::red, Qt::Dense6Pattern); brush9->setPattern(Qt::red, Qt::Dense7Pattern); brush10->setPattern(Qt::red, Qt::CrossPattern); brush11->setPattern(Qt::red, Qt::BDiagPattern); brush12->setPattern(Qt::red, Qt::FDiagPattern); brush13->setPattern(Qt::red, Qt::DiagCrossPattern); brush14->setPattern(Qt::red, Qt::SolidPattern); brush15->setPattern(Qt::red, Qt::NoBrush); current->setPattern(dlg->brushColor, dlg->brushStyle); current->slotSelect(); selectedBrush = current; color->setColor(dlg->brushColor); QPalette palette = current->palette(); palette.setColor(current->backgroundRole(), bgColor); current->setPalette(palette); connect(color, SIGNAL(changed(QColor)), this, SLOT(slotSetColorButton(QColor))); slotSetColorButton(dlg->brushColor); init(); this->resize(400, 400); } void CellFormatPagePattern::slotNotAnyColor() { b_notAnyColor = true; bgColorButton->setColor(palette().base().color()); QPalette palette = current->palette(); palette.setColor(current->backgroundRole(), this->palette().base().color()); current->setPalette(palette); } void CellFormatPagePattern::slotSetBackgroundColor(const QColor &_color) { bgColor = _color; QPalette palette = current->palette(); palette.setColor(current->backgroundRole(), bgColor); current->setPalette(palette); b_notAnyColor = false; } void CellFormatPagePattern::init() { if (dlg->brushStyle == Qt::VerPattern) { brush1->slotSelect(); } else if (dlg->brushStyle == Qt::HorPattern) { brush2->slotSelect(); } else if (dlg->brushStyle == Qt::Dense1Pattern) { brush3->slotSelect(); } else if (dlg->brushStyle == Qt::Dense2Pattern) { brush4->slotSelect(); } else if (dlg->brushStyle == Qt::Dense3Pattern) { brush5->slotSelect(); } else if (dlg->brushStyle == Qt::Dense4Pattern) { brush6->slotSelect(); } else if (dlg->brushStyle == Qt::Dense5Pattern) { brush7->slotSelect(); } else if (dlg->brushStyle == Qt::Dense6Pattern) { brush8->slotSelect(); } else if (dlg->brushStyle == Qt::Dense7Pattern) { brush9->slotSelect(); } else if (dlg->brushStyle == Qt::CrossPattern) { brush10->slotSelect(); } else if (dlg->brushStyle == Qt::BDiagPattern) { brush11->slotSelect(); } else if (dlg->brushStyle == Qt::FDiagPattern) { brush12->slotSelect(); } else if (dlg->brushStyle == Qt::DiagCrossPattern) { brush13->slotSelect(); } else if (dlg->brushStyle == Qt::SolidPattern) { brush14->slotSelect(); } else if (dlg->brushStyle == Qt::NoBrush) { brush15->slotSelect(); } else debugSheets << "Error in brushStyle"; } void CellFormatPagePattern::slotSetColorButton(const QColor &_color) { currentColor = _color; brush1->setBrushColor(currentColor); brush2->setBrushColor(currentColor); brush3->setBrushColor(currentColor); brush4->setBrushColor(currentColor); brush5->setBrushColor(currentColor); brush6->setBrushColor(currentColor); brush7->setBrushColor(currentColor); brush8->setBrushColor(currentColor); brush9->setBrushColor(currentColor); brush10->setBrushColor(currentColor); brush11->setBrushColor(currentColor); brush12->setBrushColor(currentColor); brush13->setBrushColor(currentColor); brush14->setBrushColor(currentColor); brush15->setBrushColor(currentColor); current->setBrushColor(currentColor); } void CellFormatPagePattern::slotUnselect2(BrushSelect *_p) { selectedBrush = _p; if (brush1 != _p) brush1->slotUnselect(); if (brush2 != _p) brush2->slotUnselect(); if (brush3 != _p) brush3->slotUnselect(); if (brush4 != _p) brush4->slotUnselect(); if (brush5 != _p) brush5->slotUnselect(); if (brush6 != _p) brush6->slotUnselect(); if (brush7 != _p) brush7->slotUnselect(); if (brush8 != _p) brush8->slotUnselect(); if (brush9 != _p) brush9->slotUnselect(); if (brush10 != _p) brush10->slotUnselect(); if (brush11 != _p) brush11->slotUnselect(); if (brush12 != _p) brush12->slotUnselect(); if (brush13 != _p) brush13->slotUnselect(); if (brush14 != _p) brush14->slotUnselect(); if (brush15 != _p) brush15->slotUnselect(); current->setBrushStyle(selectedBrush->getBrushStyle()); } void CellFormatPagePattern::apply(CustomStyle * style) { if (selectedBrush != 0 && (dlg->brushStyle != selectedBrush->getBrushStyle() || dlg->brushColor != selectedBrush->getBrushColor())) style->setBackgroundBrush(QBrush(selectedBrush->getBrushColor(), selectedBrush->getBrushStyle())); if (!b_notAnyColor && bgColor != dlg->getStyle()->backgroundColor()) style->setBackgroundColor(bgColor); } void CellFormatPagePattern::apply(StyleCommand *_obj) { if (selectedBrush != 0 && (dlg->brushStyle != selectedBrush->getBrushStyle() || dlg->brushColor != selectedBrush->getBrushColor())) _obj->setBackgroundBrush(QBrush(selectedBrush->getBrushColor(), selectedBrush->getBrushStyle())); if (bgColor == dlg->bgColor) return; if (!b_notAnyColor) _obj->setBackgroundColor(bgColor); } diff --git a/words/part/dialogs/KWAnchoringProperties.cpp b/words/part/dialogs/KWAnchoringProperties.cpp index d64208cbdb6..bfddb3a03f5 100644 --- a/words/part/dialogs/KWAnchoringProperties.cpp +++ b/words/part/dialogs/KWAnchoringProperties.cpp @@ -1,595 +1,596 @@ /* This file is part of the KDE project * Copyright (C) 2006, 2009 Thomas Zander * Copyright (C) 2011 KoGmbh * * 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 "KWAnchoringProperties.h" #include "KWFrameDialog.h" #include "KWDocument.h" #include "KWCanvas.h" #include "frames/KWFrame.h" #include "frames/KWTextFrameSet.h" #include #include #include #include #include #include #include #include +#include #include const int KWAnchoringProperties::vertRels[4][20] = { { // KoShapeAnchor::AnchorAsCharacter KoShapeAnchor::VBaseline, KoShapeAnchor::VChar, KoShapeAnchor::VLine, -1 }, { // KoShapeAnchor::AnchorToCharacter KoShapeAnchor::VChar, KoShapeAnchor::VLine, KoShapeAnchor::VParagraph, KoShapeAnchor::VParagraphContent, KoShapeAnchor::VPage, KoShapeAnchor::VPageContent, -1 }, { // KoShapeAnchor::AnchorParagraph KoShapeAnchor::VParagraph, KoShapeAnchor::VParagraphContent, KoShapeAnchor::VPage, KoShapeAnchor::VPageContent, -1 }, { // KoShapeAnchor::AnchorPage KoShapeAnchor::VPage, KoShapeAnchor::VPageContent, -1 } }; const int KWAnchoringProperties::horizRels[4][20] = { { // KoShapeAnchor::AnchorAsCharacter -1 }, { // KoShapeAnchor::AnchorToCharacter KoShapeAnchor::HChar, KoShapeAnchor::HParagraph, KoShapeAnchor::HParagraphContent, KoShapeAnchor::HParagraphStartMargin, KoShapeAnchor::HParagraphEndMargin, KoShapeAnchor::HPageStartMargin, KoShapeAnchor::HPageEndMargin, KoShapeAnchor::HPage, KoShapeAnchor::HPageContent, -1 }, { // KoShapeAnchor::AnchorParagraph KoShapeAnchor::HParagraph, KoShapeAnchor::HParagraphContent, KoShapeAnchor::HParagraphStartMargin, KoShapeAnchor::HParagraphEndMargin, KoShapeAnchor::HPageStartMargin, KoShapeAnchor::HPageEndMargin, KoShapeAnchor::HPage, KoShapeAnchor::HPageContent, -1 }, { // KoShapeAnchor::AnchorPage KoShapeAnchor::HPageStartMargin, KoShapeAnchor::HPageEndMargin, KoShapeAnchor::HPage, KoShapeAnchor::HPageContent, -1 } }; KWAnchoringProperties::KWAnchoringProperties(FrameConfigSharedState *state) : m_state(state) { widget.setupUi(this); m_anchorTypeGroup = new QButtonGroup(); m_anchorTypeGroup->addButton(widget.rAnchorAsCharacter); m_anchorTypeGroup->setId(widget.rAnchorAsCharacter, KoShapeAnchor::AnchorAsCharacter); m_anchorTypeGroup->addButton(widget.rAnchorToCharacter); m_anchorTypeGroup->setId(widget.rAnchorToCharacter, KoShapeAnchor::AnchorToCharacter); m_anchorTypeGroup->addButton(widget.rAnchorParagraph); m_anchorTypeGroup->setId(widget.rAnchorParagraph, KoShapeAnchor::AnchorParagraph); m_anchorTypeGroup->addButton(widget.rAnchorPage); m_anchorTypeGroup->setId(widget.rAnchorPage, KoShapeAnchor::AnchorPage); connect(m_anchorTypeGroup, SIGNAL(buttonClicked(int)), this, SLOT(anchorTypeChanged(int))); m_vertPosGroup = new QButtonGroup(); m_vertPosGroup->addButton(widget.rTop); m_vertPosGroup->setId(widget.rTop, KoShapeAnchor::VTop); m_vertPosGroup->addButton(widget.rVCenter); m_vertPosGroup->setId(widget.rVCenter, KoShapeAnchor::VMiddle); m_vertPosGroup->addButton(widget.rBottom); m_vertPosGroup->setId(widget.rBottom, KoShapeAnchor::VBottom); m_vertPosGroup->addButton(widget.rVOffset); m_vertPosGroup->setId(widget.rVOffset, KoShapeAnchor::VFromTop); connect(m_vertPosGroup, SIGNAL(buttonClicked(int)), this, SLOT(vertPosChanged(int))); m_horizPosGroup = new QButtonGroup(); m_horizPosGroup->addButton(widget.rLeft); m_horizPosGroup->setId(widget.rLeft, KoShapeAnchor::HLeft); m_horizPosGroup->addButton(widget.rHCenter); m_horizPosGroup->setId(widget.rHCenter, KoShapeAnchor::HCenter); m_horizPosGroup->addButton(widget.rRight); m_horizPosGroup->setId(widget.rRight, KoShapeAnchor::HRight); m_horizPosGroup->addButton(widget.rHOffset); m_horizPosGroup->setId(widget.rHOffset, KoShapeAnchor::HFromLeft); connect(m_horizPosGroup, SIGNAL(buttonClicked(int)), this, SLOT(horizPosChanged(int))); connect(widget.cTopArea, SIGNAL(currentIndexChanged(int)), this, SLOT(vertRelChanged(int))); connect(widget.cVCenterArea, SIGNAL(currentIndexChanged(int)), this, SLOT(vertRelChanged(int))); connect(widget.cBottomArea, SIGNAL(currentIndexChanged(int)), this, SLOT(vertRelChanged(int))); connect(widget.cVOffsetArea, SIGNAL(currentIndexChanged(int)), this, SLOT(vertRelChanged(int))); connect(widget.cLeftArea, SIGNAL(currentIndexChanged(int)), this, SLOT(horizRelChanged(int))); connect(widget.cHCenterArea, SIGNAL(currentIndexChanged(int)), this, SLOT(horizRelChanged(int))); connect(widget.cRightArea, SIGNAL(currentIndexChanged(int)), this, SLOT(horizRelChanged(int))); connect(widget.cHOffsetArea, SIGNAL(currentIndexChanged(int)), this, SLOT(horizRelChanged(int))); } bool KWAnchoringProperties::open(const QList &shapes) { m_state->addUser(); m_shapes = shapes; GuiHelper::State anchorTypeHelper = GuiHelper::Unset; GuiHelper::State vertHelper = GuiHelper::Unset; GuiHelper::State horizHelper = GuiHelper::Unset; KoShapeAnchor::AnchorType anchorType = KoShapeAnchor::AnchorPage; m_vertPos = -1; m_horizPos = -1; m_vertRel = -1; m_horizRel = -1; QPointF offset; bool atLeastOne = false; foreach (KoShape *shape, shapes) { KWFrameSet *fs = KWFrameSet::from(shape); if (fs && fs->type() == Words::TextFrameSet) { if (static_cast(fs)->textFrameSetType() != Words::OtherTextFrameSet) { continue; // we don't change for main or headers or footers } } atLeastOne = true; KoShapeAnchor *anchor = shape->anchor(); KoShapeAnchor::AnchorType anchorTypeOfFrame = anchor ? anchor->anchorType() : KoShapeAnchor::AnchorPage; // FIXME these should fetch correct values if anchor == 0 int vertPosOfFrame = anchor ? anchor->verticalPos() : KoShapeAnchor::VFromTop; int horizPosOfFrame = anchor ? anchor->horizontalPos() : KoShapeAnchor::HFromLeft; int vertRelOfFrame = anchor ? anchor->verticalRel() : KoShapeAnchor::VPage; int horizRelOfFrame = anchor ? anchor->horizontalRel() : KoShapeAnchor::HPage; QPointF offsetOfFrame = anchor ? anchor->offset() : QPointF(); if (anchorTypeHelper == GuiHelper::Unset) { anchorType = anchorTypeOfFrame; anchorTypeHelper = GuiHelper::On; } else if (anchorType != anchorTypeOfFrame) anchorTypeHelper = GuiHelper::TriState; if (vertHelper == GuiHelper::Unset) { m_vertPos = vertPosOfFrame; m_vertRel = vertRelOfFrame; offset = offsetOfFrame; vertHelper = GuiHelper::On; } else if (m_vertPos != vertPosOfFrame || m_vertRel != vertRelOfFrame || (m_vertPos == KoShapeAnchor::VFromTop && offset.y() != offsetOfFrame.y())) { vertHelper = GuiHelper::TriState; m_vertPos = vertPosOfFrame; m_vertRel = vertRelOfFrame; } if (horizHelper == GuiHelper::Unset) { m_horizPos = horizPosOfFrame; m_horizRel = horizRelOfFrame; offset = offsetOfFrame; horizHelper = GuiHelper::On; } else if (m_horizPos != horizPosOfFrame || m_horizRel != horizRelOfFrame || (m_horizPos == KoShapeAnchor::HFromLeft && offset.x() != offsetOfFrame.x())) { horizHelper = GuiHelper::TriState; m_horizPos = -1; m_horizRel = -1; } } if (!atLeastOne) { return false; } if (anchorTypeHelper != GuiHelper::TriState) { m_anchorTypeGroup->button(anchorType)->setChecked(true); anchorTypeChanged(anchorType); if (vertHelper != GuiHelper::TriState) { m_vertPosGroup->button(m_vertPos)->setChecked(true); vertPosChanged(m_vertPos, offset); } else { vertPosChanged(-1, QPointF()); } if (horizHelper != GuiHelper::TriState) { m_horizPosGroup->button(m_horizPos)->setChecked(true); horizPosChanged(m_horizPos, offset); } else { horizPosChanged(-1, QPointF()); } } else { m_anchorType = -1; widget.grpVert->setEnabled(false); widget.grpHoriz->setEnabled(false); } return true; } void KWAnchoringProperties::vertPosChanged(int vertPos, QPointF offset) { if (m_anchorType == -1) { return; //we should already be disabled } switch (vertPos) { case KoShapeAnchor::VTop: widget.cTopArea->setEnabled(true); widget.cVCenterArea->setEnabled(false); widget.cRightArea->setEnabled(false); widget.cVOffsetArea->setEnabled(false); widget.sVOffset->setEnabled(false); widget.lVOffset->setEnabled(false); for (int i = 0; vertRels[m_anchorType][i] != -1; i++) { if (vertRels[m_anchorType][i] == m_vertRel) { widget.cTopArea->setCurrentIndex(i); } } break; case KoShapeAnchor::VMiddle: widget.cTopArea->setEnabled(false); widget.cVCenterArea->setEnabled(true); widget.cBottomArea->setEnabled(false); widget.cVOffsetArea->setEnabled(false); widget.sVOffset->setEnabled(false); widget.lVOffset->setEnabled(false); for (int i = 0; vertRels[m_anchorType][i] != -1; i++) { if (vertRels[m_anchorType][i] == m_vertRel) { widget.cVCenterArea->setCurrentIndex(i); } } break; case KoShapeAnchor::VBottom: widget.cTopArea->setEnabled(false); widget.cVCenterArea->setEnabled(false); widget.cBottomArea->setEnabled(true); widget.cVOffsetArea->setEnabled(false); widget.sVOffset->setEnabled(false); widget.lVOffset->setEnabled(false); for (int i = 0; vertRels[m_anchorType][i] != -1; i++) { if (vertRels[m_anchorType][i] == m_vertRel) { widget.cBottomArea->setCurrentIndex(i); } } break; case KoShapeAnchor::VFromTop: widget.cTopArea->setEnabled(false); widget.cVCenterArea->setEnabled(false); widget.cBottomArea->setEnabled(false); widget.cVOffsetArea->setEnabled(true); widget.sVOffset->setEnabled(true); widget.lVOffset->setEnabled(true); for (int i = 0; vertRels[m_anchorType][i] != -1; i++) { if (vertRels[m_anchorType][i] == m_vertRel) { widget.cVOffsetArea->setCurrentIndex(i); } } if (m_vertRel != 1) { widget.sVOffset->setValue(offset.y()); } break; case -1: widget.cTopArea->setEnabled(false); widget.cVCenterArea->setEnabled(false); widget.cBottomArea->setEnabled(false); widget.cVOffsetArea->setEnabled(false); widget.sVOffset->setEnabled(false); widget.lVOffset->setEnabled(false); break; default: break; } m_vertPos = vertPos; } void KWAnchoringProperties::vertRelChanged(int index) { if (m_anchorType == -1) { return; //we should already be disabled } m_vertRel = vertRels[m_anchorType][index]; } void KWAnchoringProperties::horizPosChanged(int horizPos, QPointF offset) { if (m_anchorType == -1) { return; //we should already be disabled } switch (horizPos) { case KoShapeAnchor::HLeft: widget.cLeftArea->setEnabled(true); widget.cHCenterArea->setEnabled(false); widget.cRightArea->setEnabled(false); widget.cHOffsetArea->setEnabled(false); widget.sHOffset->setEnabled(false); widget.lHOffset->setEnabled(false); for (int i = 0; horizRels[m_anchorType][i] != -1; i++) { if (horizRels[m_anchorType][i] == m_horizRel) { widget.cLeftArea->setCurrentIndex(i); } } break; case KoShapeAnchor::HCenter: widget.cLeftArea->setEnabled(false); widget.cHCenterArea->setEnabled(true); widget.cRightArea->setEnabled(false); widget.cHOffsetArea->setEnabled(false); widget.sHOffset->setEnabled(false); widget.lHOffset->setEnabled(false); for (int i = 0; horizRels[m_anchorType][i] != -1; i++) { if (horizRels[m_anchorType][i] == m_horizRel) { widget.cHCenterArea->setCurrentIndex(i); } } break; case KoShapeAnchor::HRight: widget.cLeftArea->setEnabled(false); widget.cHCenterArea->setEnabled(false); widget.cRightArea->setEnabled(true); widget.cHOffsetArea->setEnabled(false); widget.sHOffset->setEnabled(false); widget.lHOffset->setEnabled(false); for (int i = 0; horizRels[m_anchorType][i] != -1; i++) { if (horizRels[m_anchorType][i] == m_horizRel) { widget.cRightArea->setCurrentIndex(i); } } break; case KoShapeAnchor::HFromLeft: widget.cLeftArea->setEnabled(false); widget.cHCenterArea->setEnabled(false); widget.cRightArea->setEnabled(false); widget.cHOffsetArea->setEnabled(true); widget.sHOffset->setEnabled(true); widget.lHOffset->setEnabled(true); for (int i = 0; horizRels[m_anchorType][i] != -1; i++) { if (horizRels[m_anchorType][i] == m_horizRel) { widget.cHOffsetArea->setCurrentIndex(i); } } if (m_horizRel != -1) { widget.sHOffset->setValue(offset.x()); } break; case -1: widget.cLeftArea->setEnabled(false); widget.cHCenterArea->setEnabled(false); widget.cRightArea->setEnabled(false); widget.cHOffsetArea->setEnabled(false); widget.sHOffset->setEnabled(false); widget.lHOffset->setEnabled(false); break; default: break; } m_horizPos = horizPos; } void KWAnchoringProperties::horizRelChanged(int index) { if (m_anchorType == -1) { return; //we should already be disabled } m_horizRel = horizRels[m_anchorType][index]; } void KWAnchoringProperties::anchorTypeChanged(int type) { KoShapeAnchor::AnchorType anchorType = KoShapeAnchor::AnchorType(type); QString vertRelStrings[20]; //NOTE: order needs to be the same as KoShapeAnchor::VerticalRel vertRelStrings[0] = i18n("Baseline"); // KoShapeAnchor::VBaseline vertRelStrings[1] = i18n("Character"); // KoShapeAnchor::VChar vertRelStrings[2].clear(); // KoShapeAnchor::VFrame vertRelStrings[3].clear(); // KoShapeAnchor::VFrameContent vertRelStrings[4] = i18n("Row"); // KoShapeAnchor::VLine vertRelStrings[5] = i18n("Page (entire) area"); // KoShapeAnchor::VPage vertRelStrings[6] = i18n("Page text area"); // KoShapeAnchor::VPageContent vertRelStrings[7] = i18n("Paragraph area"); // KoShapeAnchor::VParagraph vertRelStrings[8] = i18n("Paragraph text area"); // KoShapeAnchor::VParagraphContent vertRelStrings[9].clear(); // KoShapeAnchor::VText QString horizRelStrings[20]; //NOTE: order needs to be the same as KoShapeAnchor::HorizontalRel horizRelStrings[0] = i18n("Character"); // KoShapeAnchor::HChar horizRelStrings[1] = i18n("Page (entire) area"); // KoShapeAnchor::HPage horizRelStrings[2] = i18n("Page text area"); // KoShapeAnchor::HPageContent horizRelStrings[3] = i18n("Left page border"); // KoShapeAnchor::HPageStartMargin horizRelStrings[4] = i18n("Right page border"); // KoShapeAnchor::HPageEndMargin horizRelStrings[5].clear(); // KoShapeAnchor::HFrame horizRelStrings[6].clear(); // KoShapeAnchor::HFrameContent horizRelStrings[7].clear(); // KoShapeAnchor::HFrameEndMargin horizRelStrings[8].clear(); // KoShapeAnchor::HFrameStartMargin horizRelStrings[9] = i18n("Paragraph area"); // KoShapeAnchor::HParagraph horizRelStrings[10] = i18n("Paragraph text area"); // KoShapeAnchor::HParagraphContent horizRelStrings[11] = i18n("Right paragraph border"); // KoShapeAnchor::HParagraphEndMargin horizRelStrings[12] = i18n("Left paragraph border"); // KoShapeAnchor::HParagraphStartMargin m_anchorType = -1; widget.cTopArea->clear(); widget.cVCenterArea->clear(); widget.cBottomArea->clear(); widget.cVOffsetArea->clear(); for (int i = 0; vertRels[anchorType][i] != -1; i++) { widget.cTopArea->addItem(vertRelStrings[vertRels[anchorType][i]]); widget.cVCenterArea->addItem(vertRelStrings[vertRels[anchorType][i]]); widget.cBottomArea->addItem(vertRelStrings[vertRels[anchorType][i]]); widget.cVOffsetArea->addItem(vertRelStrings[vertRels[anchorType][i]]); } widget.cLeftArea->clear(); widget.cHCenterArea->clear(); widget.cRightArea->clear(); widget.cHOffsetArea->clear(); for (int i = 0; horizRels[anchorType][i] != -1; i++) { widget.cLeftArea->addItem(horizRelStrings[horizRels[anchorType][i]]); widget.cHCenterArea->addItem(horizRelStrings[horizRels[anchorType][i]]); widget.cRightArea->addItem(horizRelStrings[horizRels[anchorType][i]]); widget.cHOffsetArea->addItem(horizRelStrings[horizRels[anchorType][i]]); } if (anchorType == KoShapeAnchor::AnchorAsCharacter) { widget.grpHoriz->setEnabled(false); } else { widget.grpHoriz->setEnabled(true); } m_anchorType = type; vertPosChanged(m_vertPos); horizPosChanged(m_horizPos); } void KWAnchoringProperties::open(KoShape *shape) { QList list; list.append(shape); open(list); } void KWAnchoringProperties::save() { save(0,0); } void KWAnchoringProperties::save(KUndo2Command *macro, KWCanvas *canvas) { Q_ASSERT(macro); Q_ASSERT(m_shapes.count() > 0); if (m_anchorTypeGroup->checkedId() != -1) { foreach (KoShape *shape, m_shapes) { KWFrameSet *fs = KWFrameSet::from(shape); if (fs && fs->type() == Words::TextFrameSet) { if (static_cast(fs)->textFrameSetType() != Words::OtherTextFrameSet) { continue; // we don't change for main or headers or footers } } KoShapeAnchor::AnchorType type = KoShapeAnchor::AnchorType(m_anchorTypeGroup->checkedId()); KoShapeAnchor *anchor = shape->anchor(); if (!anchor) { anchor = new KoShapeAnchor(shape); anchor->setAnchorType(KoShapeAnchor::AnchorPage); anchor->setHorizontalPos(KoShapeAnchor::HFromLeft); anchor->setVerticalPos(KoShapeAnchor::VFromTop); shape->setAnchor(anchor); } KoShapeContainer *container = 0; // we change from page anchored to text shape anchored. if (type != KoShapeAnchor::AnchorPage && anchor->anchorType() == KoShapeAnchor::AnchorPage) { KoShape *targetShape = m_state->document()->findTargetTextShape(anchor->shape()); if (targetShape != 0) { KoTextShapeData *textData = qobject_cast(targetShape->userData()); if (textData) { container = static_cast(targetShape); } } } else if (type != KoShapeAnchor::AnchorPage) { container = anchor->shape()->parent(); } // if there was no textshape found then we have no choice but to anchor to page. if (!container) { type = KoShapeAnchor::AnchorPage; } QPointF offset = anchor->offset(); if (m_horizPos == KoShapeAnchor::HFromLeft) { offset.setX(widget.sHOffset->value()); } if (m_vertPos == KoShapeAnchor::VFromTop) { offset.setY(widget.sVOffset->value()); } KoShapeAnchor anchorProperties(0); anchorProperties.setAnchorType(type); anchorProperties.setOffset(offset); anchorProperties.setHorizontalRel(KoShapeAnchor::HorizontalRel(m_horizRel)); anchorProperties.setVerticalRel(KoShapeAnchor::VerticalRel(m_vertRel)); anchorProperties.setHorizontalPos(KoShapeAnchor::HorizontalPos(m_horizPos)); anchorProperties.setVerticalPos(KoShapeAnchor::VerticalPos(m_vertPos)); KoTextShapeDataBase *textData = 0; KoShape *oldParent = anchor->shape()->parent(); if (oldParent) { textData = qobject_cast(oldParent->userData()); } else if (container) { textData = qobject_cast(container->userData()); } ChangeAnchorPropertiesCommand *cmd = new ChangeAnchorPropertiesCommand(anchor, anchorProperties, container, macro); if (textData) { KoTextDocument doc(textData->document()); doc.textEditor()->addCommand(cmd); //will call redo too } else { cmd->redo(); } if (type == KoShapeAnchor::AnchorPage) { // new is AnchorPage so better make sure it adheres to the restrictions // as no other mechanism will ensure this QPointF delta; canvas->clipToDocument(anchor->shape(), delta); anchor->shape()->setPosition(anchor->shape()->position() + delta); } } } m_state->removeUser(); } diff --git a/words/part/dialogs/KWRunAroundProperties.cpp b/words/part/dialogs/KWRunAroundProperties.cpp index e38599a06d7..7e8b2d51ef9 100644 --- a/words/part/dialogs/KWRunAroundProperties.cpp +++ b/words/part/dialogs/KWRunAroundProperties.cpp @@ -1,239 +1,241 @@ /* This file is part of the KDE project * Copyright (C) 2006, 2009 Thomas Zander * * 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 "KWRunAroundProperties.h" #include "KWFrameDialog.h" #include "KWDocument.h" #include "frames/KWFrame.h" #include "frames/KWTextFrameSet.h" #include #include #include +#include + KWRunAroundProperties::KWRunAroundProperties(FrameConfigSharedState *state) : m_state(state) { widget.setupUi(this); m_runAroundSide = new QButtonGroup(); m_runAroundSide->addButton(widget.left); m_runAroundSide->setId(widget.left, KoShape::LeftRunAroundSide); m_runAroundSide->addButton(widget.right); m_runAroundSide->setId(widget.right, KoShape::RightRunAroundSide); m_runAroundSide->addButton(widget.longest); m_runAroundSide->setId(widget.longest, KoShape::BiggestRunAroundSide); m_runAroundSide->addButton(widget.both); m_runAroundSide->setId(widget.both, KoShape::BothRunAroundSide); m_runAroundSide->addButton(widget.runThrough); m_runAroundSide->setId(widget.runThrough, KoShape::RunThrough); m_runAroundSide->addButton(widget.noRunaround); m_runAroundSide->setId(widget.noRunaround, KoShape::NoRunAround); m_runAroundSide->addButton(widget.enough); m_runAroundSide->setId(widget.enough, KoShape::EnoughRunAroundSide); widget.threshold->setUnit(state->document()->unit()); m_runAroundContour = new QButtonGroup(); m_runAroundContour->addButton(widget.box); m_runAroundContour->setId(widget.box, KoShape::ContourBox); m_runAroundContour->addButton(widget.outside); m_runAroundContour->setId(widget.outside, KoShape::ContourOutside); widget.distanceLeft->setUnit(state->document()->unit()); widget.distanceTop->setUnit(state->document()->unit()); widget.distanceRight->setUnit(state->document()->unit()); widget.distanceBottom->setUnit(state->document()->unit()); connect(widget.enough, SIGNAL(toggled(bool)), this, SLOT(enoughRunAroundToggled(bool))); } bool KWRunAroundProperties::open(const QList &shapes) { m_state->addUser(); m_shapes = shapes; GuiHelper::State runaround = GuiHelper::Unset; GuiHelper::State raDistanceLeft = GuiHelper::Unset; GuiHelper::State raDistanceTop = GuiHelper::Unset; GuiHelper::State raDistanceRight = GuiHelper::Unset; GuiHelper::State raDistanceBottom = GuiHelper::Unset; GuiHelper::State raThreshold = GuiHelper::Unset; GuiHelper::State raContour = GuiHelper::Unset; KoShape::TextRunAroundSide side = KoShape::BiggestRunAroundSide; qreal distanceLeft = 0.0; qreal distanceTop = 0.0; qreal distanceRight = 0.0; qreal distanceBottom = 0.0; qreal threshold = 0.0; KoShape::TextRunAroundContour contour = KoShape::ContourBox; bool atLeastOne = false; foreach (KoShape *shape, shapes) { KWFrameSet *fs = KWFrameSet::from(shape); if (fs && fs->type() == Words::TextFrameSet) { if (static_cast(fs)->textFrameSetType() != Words::OtherTextFrameSet) { continue; // we don't change for main or headers or footers } } atLeastOne = true; if (runaround == GuiHelper::Unset) { side = shape->textRunAroundSide(); runaround = GuiHelper::On; } else if (side != shape->textRunAroundSide()) runaround = GuiHelper::TriState; if (raThreshold == GuiHelper::Unset) { threshold = shape->textRunAroundThreshold(); raThreshold = GuiHelper::On; } else if (threshold != shape->textRunAroundThreshold()) raThreshold = GuiHelper::TriState; if (raContour == GuiHelper::Unset) { contour = shape->textRunAroundContour(); raContour = GuiHelper::On; } else if (contour != shape->textRunAroundContour()) raContour = GuiHelper::TriState; if (raDistanceLeft == GuiHelper::Unset) { distanceLeft = shape->textRunAroundDistanceLeft(); raDistanceLeft = GuiHelper::On; } else if (distanceLeft != shape->textRunAroundDistanceLeft()) raDistanceLeft = GuiHelper::TriState; if (raDistanceTop == GuiHelper::Unset) { distanceTop = shape->textRunAroundDistanceTop(); raDistanceTop = GuiHelper::On; } else if (distanceTop != shape->textRunAroundDistanceTop()) raDistanceTop = GuiHelper::TriState; if (raDistanceRight == GuiHelper::Unset) { distanceRight = shape->textRunAroundDistanceRight(); raDistanceRight = GuiHelper::On; } else if (distanceRight != shape->textRunAroundDistanceRight()) raDistanceRight = GuiHelper::TriState; if (raDistanceBottom == GuiHelper::Unset) { distanceBottom = shape->textRunAroundDistanceBottom(); raDistanceBottom = GuiHelper::On; } else if (distanceBottom != shape->textRunAroundDistanceBottom()) raDistanceBottom = GuiHelper::TriState; } if (!atLeastOne) { return false; } if (runaround != GuiHelper::TriState) m_runAroundSide->button(side)->setChecked(true); widget.threshold->changeValue(threshold); if (contour == KoShape::ContourFull) { contour = KoShape::ContourOutside; } if (raContour != GuiHelper::TriState) { m_runAroundContour->button(contour)->setChecked(true); } widget.distanceLeft->changeValue(distanceLeft); widget.distanceTop->changeValue(distanceTop); widget.distanceRight->changeValue(distanceRight); widget.distanceBottom->changeValue(distanceBottom); return true; } void KWRunAroundProperties::open(KoShape *shape) { QList list; list.append(shape); open(list); } void KWRunAroundProperties::save() { save(0); } void KWRunAroundProperties::save(KUndo2Command *macro) { foreach (KoShape *shape, m_shapes) { KWFrameSet *fs = KWFrameSet::from(shape); if (fs && fs->type() == Words::TextFrameSet) { if (static_cast(fs)->textFrameSetType() != Words::OtherTextFrameSet) { continue; // we don't change for main or headers or footers } } KoShape::TextRunAroundSide side = shape->textRunAroundSide(); int runThrough = shape->runThrough(); qreal distanceLeft = shape->textRunAroundDistanceLeft(); qreal distanceTop = shape->textRunAroundDistanceTop(); qreal distanceRight = shape->textRunAroundDistanceRight(); qreal distanceBottom = shape->textRunAroundDistanceBottom(); qreal threshold = shape->textRunAroundThreshold(); KoShape::TextRunAroundContour contour = shape->textRunAroundContour(); if (m_runAroundSide->checkedId() != -1) { KoShape::TextRunAroundSide rrs = static_cast(m_runAroundSide->checkedId()); if (side != rrs) { side = rrs; } } if (shape->textRunAroundThreshold() != widget.threshold->value()) { threshold = widget.threshold->value(); } if (m_runAroundContour->checkedId() != -1) { KoShape::TextRunAroundContour rrc = static_cast(m_runAroundContour->checkedId()); if (contour != rrc) { contour = rrc; } } if (distanceLeft != widget.distanceLeft->value()) { distanceLeft = widget.distanceLeft->value(); } if (distanceTop != widget.distanceTop->value()) { distanceTop = widget.distanceTop->value(); } if (distanceRight != widget.distanceRight->value()) { distanceRight = widget.distanceRight->value(); } if (distanceBottom != widget.distanceBottom->value()) { distanceBottom = widget.distanceBottom->value(); } if (macro) { new KoShapeRunAroundCommand(shape, side, runThrough, distanceLeft, distanceTop, distanceRight, distanceBottom, threshold, contour, macro); } else { shape->setTextRunAroundSide(side, KoShape::Background); shape->setRunThrough(runThrough); shape->setTextRunAroundThreshold(threshold); shape->setTextRunAroundContour(contour); shape->setTextRunAroundDistanceLeft(distanceLeft); shape->setTextRunAroundDistanceTop(distanceTop); shape->setTextRunAroundDistanceRight(distanceRight); shape->setTextRunAroundDistanceBottom(distanceBottom); shape->notifyChanged(); } } m_state->removeUser(); } void KWRunAroundProperties::enoughRunAroundToggled(bool checked) { widget.threshold->setEnabled(checked); }