id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,016
|
colordelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/colordelegate.cpp
|
#include "colordelegate.hpp"
#include <QColor>
#include <QModelIndex>
#include <QPainter>
#include <QRect>
#include <apps/opencs/view/world/util.hpp>
namespace CSMDoc
{
class Document;
}
namespace CSMWorld
{
class CommandDispatcher;
}
CSVWorld::ColorDelegate::ColorDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: CommandDelegate(dispatcher, document, parent)
{
}
void CSVWorld::ColorDelegate::paint(
QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
int colorInt = index.data().toInt();
QColor color(colorInt & 0xff, (colorInt >> 8) & 0xff, (colorInt >> 16) & 0xff);
QRect coloredRect(option.rect.x() + qRound(option.rect.width() / 4.0),
option.rect.y() + qRound(option.rect.height() / 4.0), option.rect.width() / 2, option.rect.height() / 2);
painter->save();
painter->fillRect(coloredRect, color);
painter->setPen(Qt::black);
painter->drawRect(coloredRect);
painter->restore();
}
CSVWorld::CommandDelegate* CSVWorld::ColorDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new ColorDelegate(dispatcher, document, parent);
}
| 1,272
|
C++
|
.cpp
| 37
| 31.324324
| 113
| 0.737571
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,017
|
enumdelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/enumdelegate.cpp
|
#include "enumdelegate.hpp"
#include <cassert>
#include <memory>
#include <QApplication>
#include <QComboBox>
#include "../../model/world/commands.hpp"
#include <apps/opencs/view/world/util.hpp>
int CSVWorld::EnumDelegate::getValueIndex(const QModelIndex& index, int role) const
{
if (index.isValid() && index.data(role).isValid())
{
int value = index.data(role).toInt();
int size = static_cast<int>(mValues.size());
for (int i = 0; i < size; ++i)
{
if (value == mValues.at(i).first)
{
return i;
}
}
}
return -1;
}
void CSVWorld::EnumDelegate::setModelDataImp(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
if (QComboBox* comboBox = dynamic_cast<QComboBox*>(editor))
{
QString value = comboBox->currentText();
for (std::vector<std::pair<int, QString>>::const_iterator iter(mValues.begin()); iter != mValues.end(); ++iter)
if (iter->second == value)
{
// do nothing if the value has not changed
if (model->data(index).toInt() != iter->first)
addCommands(model, index, iter->first);
break;
}
}
}
void CSVWorld::EnumDelegate::addCommands(QAbstractItemModel* model, const QModelIndex& index, int type) const
{
getUndoStack().push(new CSMWorld::ModifyCommand(*model, index, type));
}
CSVWorld::EnumDelegate::EnumDelegate(const std::vector<std::pair<int, QString>>& values,
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: CommandDelegate(dispatcher, document, parent)
, mValues(values)
{
}
QWidget* CSVWorld::EnumDelegate::createEditor(
QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_None);
}
QWidget* CSVWorld::EnumDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option,
const QModelIndex& index, CSMWorld::ColumnBase::Display display) const
{
if (!index.data(Qt::EditRole).isValid() && !index.data(Qt::DisplayRole).isValid())
return nullptr;
QComboBox* comboBox = new QComboBox(parent);
for (std::vector<std::pair<int, QString>>::const_iterator iter(mValues.begin()); iter != mValues.end(); ++iter)
comboBox->addItem(iter->second);
comboBox->setMaxVisibleItems(20);
return comboBox;
}
void CSVWorld::EnumDelegate::setEditorData(QWidget* editor, const QModelIndex& index, bool tryDisplay) const
{
if (QComboBox* comboBox = dynamic_cast<QComboBox*>(editor))
{
int role = Qt::EditRole;
if (tryDisplay && !index.data(role).isValid())
{
role = Qt::DisplayRole;
if (!index.data(role).isValid())
{
return;
}
}
int valueIndex = getValueIndex(index, role);
if (valueIndex != -1)
{
comboBox->setCurrentIndex(valueIndex);
}
}
}
void CSVWorld::EnumDelegate::paint(
QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
int valueIndex = getValueIndex(index);
if (valueIndex != -1)
{
QStyleOptionViewItem itemOption(option);
itemOption.text = mValues.at(valueIndex).second;
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter);
}
}
QSize CSVWorld::EnumDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
int valueIndex = getValueIndex(index);
if (valueIndex != -1)
{
// Calculate the size hint as for a combobox.
// So, the whole text is visible (isn't elided) when the editor is created
QStyleOptionComboBox itemOption;
itemOption.fontMetrics = option.fontMetrics;
itemOption.palette = option.palette;
itemOption.rect = option.rect;
itemOption.state = option.state;
const QString& valueText = mValues.at(valueIndex).second;
QSize valueSize = QSize(itemOption.fontMetrics.horizontalAdvance(valueText), itemOption.fontMetrics.height());
itemOption.currentText = valueText;
return QApplication::style()->sizeFromContents(QStyle::CT_ComboBox, &itemOption, valueSize);
}
return option.rect.size();
}
CSVWorld::EnumDelegateFactory::EnumDelegateFactory(const char** names, bool allowNone)
{
assert(names);
if (allowNone)
add(-1, "");
for (int i = 0; names[i]; ++i)
add(i, names[i]);
}
CSVWorld::EnumDelegateFactory::EnumDelegateFactory(
const std::vector<std::pair<int, std::string>>& names, bool allowNone)
{
if (allowNone)
add(-1, "");
int size = static_cast<int>(names.size());
for (int i = 0; i < size; ++i)
add(names[i].first, names[i].second.c_str());
}
CSVWorld::CommandDelegate* CSVWorld::EnumDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new EnumDelegate(mValues, dispatcher, document, parent);
}
void CSVWorld::EnumDelegateFactory::add(int value, const QString& name)
{
auto pair = std::make_pair(value, name);
for (auto it = mValues.begin(); it != mValues.end(); ++it)
{
if (it->second > name)
{
mValues.insert(it, pair);
return;
}
}
mValues.emplace_back(value, name);
}
| 5,524
|
C++
|
.cpp
| 149
| 30.872483
| 120
| 0.661302
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,018
|
dragrecordtable.cpp
|
OpenMW_openmw/apps/opencs/view/world/dragrecordtable.cpp
|
#include "dragrecordtable.hpp"
#include <QDrag>
#include <QDragEnterEvent>
#include <algorithm>
#include <string>
#include "../../model/doc/document.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/tablemimedata.hpp"
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <components/misc/scalableicon.hpp>
#include "dragdroputils.hpp"
void CSVWorld::DragRecordTable::startDragFromTable(const CSVWorld::DragRecordTable& table, const QModelIndex& index)
{
std::vector<CSMWorld::UniversalId> records = table.getDraggedRecords();
if (records.empty())
{
return;
}
CSMWorld::TableMimeData* mime = new CSMWorld::TableMimeData(records, mDocument);
mime->setTableOfDragStart(&table);
mime->setIndexAtDragStart(index);
QDrag* drag = new QDrag(this);
drag->setMimeData(mime);
drag->setPixmap(Misc::ScalableIcon::load(mime->getIcon().c_str()).pixmap(QSize(16, 16)));
drag->exec(Qt::CopyAction);
}
CSVWorld::DragRecordTable::DragRecordTable(CSMDoc::Document& document, QWidget* parent)
: QTableView(parent)
, mDocument(document)
, mEditLock(false)
{
setAcceptDrops(true);
}
void CSVWorld::DragRecordTable::setEditLock(bool locked)
{
mEditLock = locked;
}
void CSVWorld::DragRecordTable::dragEnterEvent(QDragEnterEvent* event)
{
event->acceptProposedAction();
}
void CSVWorld::DragRecordTable::dragMoveEvent(QDragMoveEvent* event)
{
QModelIndex index = indexAt(event->pos());
if (CSVWorld::DragDropUtils::canAcceptData(*event, getIndexDisplayType(index))
|| CSVWorld::DragDropUtils::isInfo(*event, getIndexDisplayType(index))
|| CSVWorld::DragDropUtils::isTopicOrJournal(*event, getIndexDisplayType(index)))
{
if (index.flags() & Qt::ItemIsEditable)
{
event->accept();
return;
}
}
event->ignore();
}
void CSVWorld::DragRecordTable::dropEvent(QDropEvent* event)
{
QModelIndex index = indexAt(event->pos());
CSMWorld::ColumnBase::Display display = getIndexDisplayType(index);
if (CSVWorld::DragDropUtils::canAcceptData(*event, display))
{
const CSMWorld::TableMimeData* tableMimeData = CSVWorld::DragDropUtils::getTableMimeData(*event);
if (tableMimeData->fromDocument(mDocument))
{
CSMWorld::UniversalId id = CSVWorld::DragDropUtils::getAcceptedData(*event, display);
QVariant newIndexData = QString::fromUtf8(id.getId().c_str());
QVariant oldIndexData = index.data(Qt::EditRole);
if (newIndexData != oldIndexData)
{
mDocument.getUndoStack().push(new CSMWorld::ModifyCommand(*model(), index, newIndexData));
}
}
}
else if (CSVWorld::DragDropUtils::isInfo(*event, display) && event->source() == this)
{
emit moveRecordsFromSameTable(event);
}
if (CSVWorld::DragDropUtils::isTopicOrJournal(*event, display))
{
const CSMWorld::TableMimeData* tableMimeData = CSVWorld::DragDropUtils::getTableMimeData(*event);
for (const auto& universalId : tableMimeData->getData())
{
emit createNewInfoRecord(universalId.getId());
}
}
}
CSMWorld::ColumnBase::Display CSVWorld::DragRecordTable::getIndexDisplayType(const QModelIndex& index) const
{
Q_ASSERT(model() != nullptr);
if (index.isValid())
{
QVariant display = model()->headerData(index.column(), Qt::Horizontal, CSMWorld::ColumnBase::Role_Display);
if (display.isValid())
{
return static_cast<CSMWorld::ColumnBase::Display>(display.toInt());
}
}
return CSMWorld::ColumnBase::Display_None;
}
int CSVWorld::DragRecordTable::sizeHintForColumn(int column) const
{
// Prevent the column width from getting too long or too short
constexpr int minWidth = 100;
constexpr int maxWidth = 300;
int width = QTableView::sizeHintForColumn(column);
return std::clamp(width, minWidth, maxWidth);
}
| 4,067
|
C++
|
.cpp
| 109
| 31.93578
| 116
| 0.699315
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,019
|
tableeditidaction.cpp
|
OpenMW_openmw/apps/opencs/view/world/tableeditidaction.cpp
|
#include "tableeditidaction.hpp"
#include <QTableView>
#include <memory>
#include <type_traits>
#include "../../model/world/tablemimedata.hpp"
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/universalid.hpp>
CSVWorld::TableEditIdAction::CellData CSVWorld::TableEditIdAction::getCellData(int row, int column) const
{
QModelIndex index = mTable.model()->index(row, column);
if (index.isValid())
{
QVariant display = mTable.model()->data(index, CSMWorld::ColumnBase::Role_Display);
QString value = mTable.model()->data(index).toString();
return std::make_pair(static_cast<CSMWorld::ColumnBase::Display>(display.toInt()), value);
}
return std::make_pair(CSMWorld::ColumnBase::Display_None, "");
}
CSVWorld::TableEditIdAction::TableEditIdAction(const QTableView& table, QWidget* parent)
: QAction(parent)
, mTable(table)
, mCurrentId(CSMWorld::UniversalId::Type_None)
{
}
void CSVWorld::TableEditIdAction::setCell(int row, int column)
{
CellData data = getCellData(row, column);
CSMWorld::UniversalId::Type idType = CSMWorld::TableMimeData::convertEnums(data.first);
if (idType != CSMWorld::UniversalId::Type_None)
{
mCurrentId = CSMWorld::UniversalId(idType, data.second.toUtf8().constData());
setText("Edit '" + data.second + "'");
}
}
CSMWorld::UniversalId CSVWorld::TableEditIdAction::getCurrentId() const
{
return mCurrentId;
}
bool CSVWorld::TableEditIdAction::isValidIdCell(int row, int column) const
{
CellData data = getCellData(row, column);
CSMWorld::UniversalId::Type idType = CSMWorld::TableMimeData::convertEnums(data.first);
return CSMWorld::ColumnBase::isId(data.first) && idType != CSMWorld::UniversalId::Type_None
&& !data.second.isEmpty();
}
| 1,818
|
C++
|
.cpp
| 45
| 36.6
| 105
| 0.729438
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,020
|
idcompletiondelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/idcompletiondelegate.cpp
|
#include "idcompletiondelegate.hpp"
#include "../../model/world/idcompletionmanager.hpp"
#include "../../model/world/infoselectwrapper.hpp"
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/view/world/util.hpp>
#include <memory>
#include "../widget/droplineedit.hpp"
namespace CSMWorld
{
class CommandDispatcher;
}
class QObject;
class QWidget;
CSVWorld::IdCompletionDelegate::IdCompletionDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: CommandDelegate(dispatcher, document, parent)
{
}
QWidget* CSVWorld::IdCompletionDelegate::createEditor(
QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return createEditor(parent, option, index, getDisplayTypeFromIndex(index));
}
QWidget* CSVWorld::IdCompletionDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option,
const QModelIndex& index, CSMWorld::ColumnBase::Display display) const
{
if (!index.data(Qt::EditRole).isValid() && !index.data(Qt::DisplayRole).isValid())
{
return nullptr;
}
// The completer for InfoCondVar needs to return a completer based on the first column
if (display == CSMWorld::ColumnBase::Display_InfoCondVar)
{
QModelIndex sibling = index.sibling(index.row(), 0);
int conditionFunction = sibling.model()->data(sibling, Qt::EditRole).toInt();
switch (conditionFunction)
{
case ESM::DialogueCondition::Function_Global:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_GlobalVariable);
}
case ESM::DialogueCondition::Function_Journal:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Journal);
}
case ESM::DialogueCondition::Function_Item:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Referenceable);
}
case ESM::DialogueCondition::Function_Dead:
case ESM::DialogueCondition::Function_NotId:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Referenceable);
}
case ESM::DialogueCondition::Function_NotFaction:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Faction);
}
case ESM::DialogueCondition::Function_NotClass:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Class);
}
case ESM::DialogueCondition::Function_NotRace:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Race);
}
case ESM::DialogueCondition::Function_NotCell:
{
return createEditor(parent, option, index, CSMWorld::ColumnBase::Display_Cell);
}
case ESM::DialogueCondition::Function_Local:
case ESM::DialogueCondition::Function_NotLocal:
{
return new CSVWidget::DropLineEdit(display, parent);
}
default:
return nullptr; // The rest of them can't be edited anyway
}
}
CSMWorld::IdCompletionManager& completionManager = getDocument().getIdCompletionManager();
CSVWidget::DropLineEdit* editor = new CSVWidget::DropLineEdit(display, parent);
editor->setCompleter(completionManager.getCompleter(display).get());
// The savegame format limits the player faction string to 32 characters.
// The region sound name is limited to 32 characters. (ESM::Region::SoundRef::mSound)
// The script name is limited to 32 characters. (ESM::Script::SCHD::mName)
// The cell name is limited to 64 characters. (ESM::Header::GMDT::mCurrentCell)
if (display == CSMWorld::ColumnBase::Display_Faction || display == CSMWorld::ColumnBase::Display_Sound
|| display == CSMWorld::ColumnBase::Display_Script || display == CSMWorld::ColumnBase::Display_Referenceable)
{
editor->setMaxLength(32);
}
else if (display == CSMWorld::ColumnBase::Display_Cell)
{
editor->setMaxLength(64);
}
return editor;
}
CSVWorld::CommandDelegate* CSVWorld::IdCompletionDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new IdCompletionDelegate(dispatcher, document, parent);
}
| 4,575
|
C++
|
.cpp
| 102
| 36.764706
| 117
| 0.677658
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,021
|
idtypedelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/idtypedelegate.cpp
|
#include "idtypedelegate.hpp"
#include "../../model/world/universalid.hpp"
#include <apps/opencs/view/world/datadisplaydelegate.hpp>
#include <apps/opencs/view/world/util.hpp>
#include <string>
class QObject;
namespace CSMDoc
{
class Document;
}
namespace CSMWorld
{
class CommandDispatcher;
}
CSVWorld::IdTypeDelegate::IdTypeDelegate(const ValueList& values, const IconList& icons,
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: DataDisplayDelegate(values, icons, dispatcher, document, "Records", "type-format", parent)
{
}
CSVWorld::IdTypeDelegateFactory::IdTypeDelegateFactory()
{
for (int i = 0; i < CSMWorld::UniversalId::NumberOfTypes; ++i)
{
CSMWorld::UniversalId id(static_cast<CSMWorld::UniversalId::Type>(i));
DataDisplayDelegateFactory::add(
id.getType(), QString::fromUtf8(id.getTypeName().c_str()), QString::fromUtf8(id.getIcon().c_str()));
}
}
CSVWorld::CommandDelegate* CSVWorld::IdTypeDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new IdTypeDelegate(mValues, mIcons, dispatcher, document, parent);
}
| 1,217
|
C++
|
.cpp
| 33
| 33.636364
| 112
| 0.755537
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,022
|
datadisplaydelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/datadisplaydelegate.cpp
|
#include "datadisplaydelegate.hpp"
#include "../../model/prefs/state.hpp"
#include <QApplication>
#include <QIcon>
#include <QPainter>
#include <QRect>
#include <QSize>
#include <QString>
#include <QStyle>
#include <memory>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/view/world/enumdelegate.hpp>
#include <apps/opencs/view/world/util.hpp>
#include <components/misc/scalableicon.hpp>
class QModelIndex;
class QObject;
namespace CSMDoc
{
class Document;
}
namespace CSMWorld
{
class CommandDispatcher;
}
CSVWorld::DataDisplayDelegate::DataDisplayDelegate(const ValueList& values, const IconList& icons,
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, const std::string& pageName,
const std::string& settingName, QObject* parent)
: EnumDelegate(values, dispatcher, document, parent)
, mDisplayMode(Mode_TextOnly)
, mIcons(icons)
, mIconSize(QSize(16, 16))
, mHorizontalMargin(QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1)
, mTextLeftOffset(8)
, mPixmapsColor(QApplication::palette().text().color())
, mUiScale(static_cast<QGuiApplication*>(QGuiApplication::instance())->devicePixelRatio())
, mSettingKey(pageName + '/' + settingName)
{
if (parent)
parent->installEventFilter(this);
buildPixmaps();
if (!pageName.empty())
updateDisplayMode(CSMPrefs::get()[pageName][settingName].toString());
}
bool CSVWorld::DataDisplayDelegate::eventFilter(QObject* target, QEvent* event)
{
if (event->type() == QEvent::Resize)
{
auto uiScale = static_cast<QGuiApplication*>(QGuiApplication::instance())->devicePixelRatio();
if (mUiScale != uiScale)
{
mUiScale = uiScale;
buildPixmaps();
}
}
else if (event->type() == QEvent::PaletteChange)
{
QColor themeColor = QApplication::palette().text().color();
if (themeColor != mPixmapsColor)
{
mPixmapsColor = std::move(themeColor);
buildPixmaps();
}
}
return false;
}
void CSVWorld::DataDisplayDelegate::buildPixmaps()
{
if (!mPixmaps.empty())
mPixmaps.clear();
IconList::iterator it = mIcons.begin();
while (it != mIcons.end())
{
mPixmaps.emplace_back(it->mValue, it->mIcon.pixmap(mIconSize));
++it;
}
}
void CSVWorld::DataDisplayDelegate::setIconSize(const QSize& size)
{
mIconSize = size;
buildPixmaps();
}
void CSVWorld::DataDisplayDelegate::setTextLeftOffset(int offset)
{
mTextLeftOffset = offset;
}
QSize CSVWorld::DataDisplayDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QSize size = EnumDelegate::sizeHint(option, index);
int valueIndex = getValueIndex(index);
if (valueIndex != -1)
{
if (mDisplayMode == Mode_IconOnly)
{
size.setWidth(mIconSize.width() + 2 * mHorizontalMargin);
}
else if (mDisplayMode == Mode_IconAndText)
{
size.setWidth(size.width() + mIconSize.width() + mTextLeftOffset);
}
if (mDisplayMode != Mode_TextOnly)
{
size.setHeight(qMax(size.height(), mIconSize.height()));
}
}
return size;
}
void CSVWorld::DataDisplayDelegate::paint(
QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
// default to enum delegate's paint method for text-only conditions
if (mDisplayMode == Mode_TextOnly)
EnumDelegate::paint(painter, option, index);
else
{
int valueIndex = getValueIndex(index);
if (valueIndex != -1)
{
paintIcon(painter, option, valueIndex);
}
}
painter->restore();
}
void CSVWorld::DataDisplayDelegate::paintIcon(QPainter* painter, const QStyleOptionViewItem& option, int index) const
{
QRect iconRect = option.rect;
QRect textRect = iconRect;
iconRect.setLeft(iconRect.left() + mHorizontalMargin);
iconRect.setRight(option.rect.right() - mHorizontalMargin);
if (mDisplayMode == Mode_IconAndText)
{
iconRect.setWidth(mIconSize.width());
textRect.setLeft(iconRect.right() + mTextLeftOffset);
textRect.setRight(option.rect.right() - mHorizontalMargin);
QString text = option.fontMetrics.elidedText(mValues.at(index).second, option.textElideMode, textRect.width());
QApplication::style()->drawItemText(
painter, textRect, Qt::AlignLeft | Qt::AlignVCenter, option.palette, true, text);
}
QApplication::style()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, mPixmaps.at(index).second);
}
void CSVWorld::DataDisplayDelegate::updateDisplayMode(const std::string& mode)
{
if (mode == "Icon and Text")
mDisplayMode = Mode_IconAndText;
else if (mode == "Icon Only")
mDisplayMode = Mode_IconOnly;
else if (mode == "Text Only")
mDisplayMode = Mode_TextOnly;
}
void CSVWorld::DataDisplayDelegate::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == mSettingKey)
updateDisplayMode(setting->toString());
}
void CSVWorld::DataDisplayDelegateFactory::add(int enumValue, const QString& enumName, const QString& iconFilename)
{
EnumDelegateFactory::add(enumValue, enumName);
Icon icon;
icon.mValue = enumValue;
icon.mName = enumName;
icon.mIcon = Misc::ScalableIcon::load(iconFilename);
for (auto it = mIcons.begin(); it != mIcons.end(); ++it)
{
if (it->mName > enumName)
{
mIcons.insert(it, icon);
return;
}
}
mIcons.push_back(icon);
}
CSVWorld::CommandDelegate* CSVWorld::DataDisplayDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new DataDisplayDelegate(mValues, mIcons, dispatcher, document, "", "", parent);
}
| 6,026
|
C++
|
.cpp
| 177
| 28.785311
| 119
| 0.688866
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,024
|
util.cpp
|
OpenMW_openmw/apps/opencs/view/world/util.cpp
|
#include "util.hpp"
#include <limits>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <QCheckBox>
#include <QItemEditorFactory>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QStyledItemDelegate>
#include <QUndoStack>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/view/world/scripthighlighter.hpp>
#include "../../model/world/commanddispatcher.hpp"
#include "../widget/coloreditor.hpp"
#include "../widget/droplineedit.hpp"
#include "dialoguespinbox.hpp"
#include "scriptedit.hpp"
CSVWorld::NastyTableModelHack::NastyTableModelHack(QAbstractItemModel& model)
: mModel(model)
{
}
int CSVWorld::NastyTableModelHack::rowCount(const QModelIndex& parent) const
{
return mModel.rowCount(parent);
}
int CSVWorld::NastyTableModelHack::columnCount(const QModelIndex& parent) const
{
return mModel.columnCount(parent);
}
QVariant CSVWorld::NastyTableModelHack::data(const QModelIndex& index, int role) const
{
return mModel.data(index, role);
}
bool CSVWorld::NastyTableModelHack::setData(const QModelIndex& index, const QVariant& value, int role)
{
mData = value;
return true;
}
QVariant CSVWorld::NastyTableModelHack::getData() const
{
return mData;
}
CSVWorld::CommandDelegateFactoryCollection* CSVWorld::CommandDelegateFactoryCollection::sThis = nullptr;
CSVWorld::CommandDelegateFactoryCollection::CommandDelegateFactoryCollection()
{
if (sThis)
throw std::logic_error("multiple instances of CSVWorld::CommandDelegateFactoryCollection");
sThis = this;
}
CSVWorld::CommandDelegateFactoryCollection::~CommandDelegateFactoryCollection()
{
sThis = nullptr;
for (std::map<CSMWorld::ColumnBase::Display, CommandDelegateFactory*>::iterator iter(mFactories.begin());
iter != mFactories.end(); ++iter)
delete iter->second;
}
void CSVWorld::CommandDelegateFactoryCollection::add(
CSMWorld::ColumnBase::Display display, CommandDelegateFactory* factory)
{
mFactories.insert(std::make_pair(display, factory));
}
CSVWorld::CommandDelegate* CSVWorld::CommandDelegateFactoryCollection::makeDelegate(
CSMWorld::ColumnBase::Display display, CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document,
QObject* parent) const
{
std::map<CSMWorld::ColumnBase::Display, CommandDelegateFactory*>::const_iterator iter = mFactories.find(display);
if (iter != mFactories.end())
return iter->second->makeDelegate(dispatcher, document, parent);
return new CommandDelegate(dispatcher, document, parent);
}
const CSVWorld::CommandDelegateFactoryCollection& CSVWorld::CommandDelegateFactoryCollection::get()
{
if (!sThis)
throw std::logic_error("no instance of CSVWorld::CommandDelegateFactoryCollection");
return *sThis;
}
QUndoStack& CSVWorld::CommandDelegate::getUndoStack() const
{
return mDocument.getUndoStack();
}
CSMDoc::Document& CSVWorld::CommandDelegate::getDocument() const
{
return mDocument;
}
CSMWorld::ColumnBase::Display CSVWorld::CommandDelegate::getDisplayTypeFromIndex(const QModelIndex& index) const
{
int rawDisplay = index.data(CSMWorld::ColumnBase::Role_Display).toInt();
return static_cast<CSMWorld::ColumnBase::Display>(rawDisplay);
}
void CSVWorld::CommandDelegate::setModelDataImp(
QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
if (!mCommandDispatcher)
return;
QVariant variant;
// Color columns use a custom editor, so we need to fetch selected color from it.
CSVWidget::ColorEditor* colorEditor = qobject_cast<CSVWidget::ColorEditor*>(editor);
if (colorEditor != nullptr)
{
variant = colorEditor->colorInt();
}
else
{
NastyTableModelHack hack(*model);
QStyledItemDelegate::setModelData(editor, &hack, index);
variant = hack.getData();
}
if ((model->data(index) != variant) && (model->flags(index) & Qt::ItemIsEditable))
mCommandDispatcher->executeModify(model, index, variant);
}
CSVWorld::CommandDelegate::CommandDelegate(
CSMWorld::CommandDispatcher* commandDispatcher, CSMDoc::Document& document, QObject* parent)
: QStyledItemDelegate(parent)
, mEditLock(false)
, mCommandDispatcher(commandDispatcher)
, mDocument(document)
{
}
void CSVWorld::CommandDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
if (!mEditLock)
{
setModelDataImp(editor, model, index);
}
///< \todo provide some kind of feedback to the user, indicating that editing is currently not possible.
}
QWidget* CSVWorld::CommandDelegate::createEditor(
QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
CSMWorld::ColumnBase::Display display = getDisplayTypeFromIndex(index);
// This createEditor() method is called implicitly from tables.
// For boolean values in tables use the default editor (combobox).
// Checkboxes is looking ugly in the table view.
// TODO: Find a better solution?
if (display == CSMWorld::ColumnBase::Display_Boolean)
{
return QItemEditorFactory::defaultFactory()->createEditor(QVariant::Bool, parent);
}
// For tables the pop-up of the color editor should appear immediately after the editor creation
// (the third parameter of ColorEditor's constructor)
else if (display == CSMWorld::ColumnBase::Display_Colour)
{
return new CSVWidget::ColorEditor(index.data().toInt(), parent, true);
}
return createEditor(parent, option, index, display);
}
QWidget* CSVWorld::CommandDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option,
const QModelIndex& index, CSMWorld::ColumnBase::Display display) const
{
QVariant variant = index.data();
if (!variant.isValid())
{
variant = index.data(Qt::DisplayRole);
if (!variant.isValid())
{
return nullptr;
}
}
// NOTE: for each editor type (e.g. QLineEdit) there needs to be a corresponding
// entry in CSVWorld::DialogueDelegateDispatcher::makeEditor()
switch (display)
{
case CSMWorld::ColumnBase::Display_Colour:
{
return new CSVWidget::ColorEditor(variant.toInt(), parent);
}
case CSMWorld::ColumnBase::Display_Integer:
{
DialogueSpinBox* sb = new DialogueSpinBox(parent);
sb->setRange(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
return sb;
}
case CSMWorld::ColumnBase::Display_SignedInteger8:
{
DialogueSpinBox* sb = new DialogueSpinBox(parent);
sb->setRange(std::numeric_limits<signed char>::min(), std::numeric_limits<signed char>::max());
return sb;
}
case CSMWorld::ColumnBase::Display_SignedInteger16:
{
DialogueSpinBox* sb = new DialogueSpinBox(parent);
sb->setRange(std::numeric_limits<short>::min(), std::numeric_limits<short>::max());
return sb;
}
case CSMWorld::ColumnBase::Display_UnsignedInteger8:
{
DialogueSpinBox* sb = new DialogueSpinBox(parent);
sb->setRange(0, std::numeric_limits<unsigned char>::max());
return sb;
}
case CSMWorld::ColumnBase::Display_UnsignedInteger16:
{
DialogueSpinBox* sb = new DialogueSpinBox(parent);
sb->setRange(0, std::numeric_limits<unsigned short>::max());
return sb;
}
case CSMWorld::ColumnBase::Display_Var:
return new QLineEdit(parent);
case CSMWorld::ColumnBase::Display_Float:
{
DialogueDoubleSpinBox* dsb = new DialogueDoubleSpinBox(parent);
dsb->setRange(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
dsb->setSingleStep(0.01f);
dsb->setDecimals(3);
return dsb;
}
case CSMWorld::ColumnBase::Display_Double:
{
DialogueDoubleSpinBox* dsb = new DialogueDoubleSpinBox(parent);
dsb->setRange(-std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
dsb->setSingleStep(0.01f);
dsb->setDecimals(6);
return dsb;
}
/// \todo implement size limit. QPlainTextEdit does not support a size limit.
case CSMWorld::ColumnBase::Display_LongString:
case CSMWorld::ColumnBase::Display_LongString256:
{
QPlainTextEdit* edit = new QPlainTextEdit(parent);
edit->setUndoRedoEnabled(false);
return edit;
}
case CSMWorld::ColumnBase::Display_Boolean:
return new QCheckBox(parent);
case CSMWorld::ColumnBase::Display_ScriptLines:
return new ScriptEdit(mDocument, ScriptHighlighter::Mode_Console, parent);
case CSMWorld::ColumnBase::Display_String:
// For other Display types (that represent record IDs) with drop support IdCompletionDelegate is used
return new CSVWidget::DropLineEdit(display, parent);
case CSMWorld::ColumnBase::Display_String32:
{
// For other Display types (that represent record IDs) with drop support IdCompletionDelegate is used
CSVWidget::DropLineEdit* widget = new CSVWidget::DropLineEdit(display, parent);
widget->setMaxLength(32);
return widget;
}
case CSMWorld::ColumnBase::Display_String64:
{
// For other Display types (that represent record IDs) with drop support IdCompletionDelegate is used
CSVWidget::DropLineEdit* widget = new CSVWidget::DropLineEdit(display, parent);
widget->setMaxLength(64);
return widget;
}
default:
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
void CSVWorld::CommandDelegate::setEditLock(bool locked)
{
mEditLock = locked;
}
bool CSVWorld::CommandDelegate::isEditLocked() const
{
return mEditLock;
}
void CSVWorld::CommandDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
setEditorData(editor, index, false);
}
void CSVWorld::CommandDelegate::setEditorData(QWidget* editor, const QModelIndex& index, bool tryDisplay) const
{
QVariant variant = index.data(Qt::EditRole);
if (tryDisplay)
{
if (!variant.isValid())
{
variant = index.data(Qt::DisplayRole);
if (!variant.isValid())
{
return;
}
}
QPlainTextEdit* plainTextEdit = qobject_cast<QPlainTextEdit*>(editor);
if (plainTextEdit) // for some reason it is easier to brake the loop here
{
if (plainTextEdit->toPlainText() == variant.toString())
{
return;
}
}
}
// Color columns use a custom editor, so we need explicitly set a data for it
CSVWidget::ColorEditor* colorEditor = qobject_cast<CSVWidget::ColorEditor*>(editor);
if (colorEditor != nullptr)
{
colorEditor->setColor(variant.toInt());
return;
}
QByteArray n = editor->metaObject()->userProperty().name();
if (n == "dateTime")
{
if (editor->inherits("QTimeEdit"))
n = "time";
else if (editor->inherits("QDateEdit"))
n = "date";
}
if (!n.isEmpty())
{
if (!variant.isValid())
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
variant = QVariant(editor->property(n).metaType(), (const void*)nullptr);
#else
variant = QVariant(editor->property(n).userType(), (const void*)nullptr);
#endif
editor->setProperty(n, variant);
}
}
void CSVWorld::CommandDelegate::settingChanged(const CSMPrefs::Setting* setting) {}
| 11,965
|
C++
|
.cpp
| 310
| 32.174194
| 120
| 0.687516
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,025
|
scriptedit.cpp
|
OpenMW_openmw/apps/opencs/view/world/scriptedit.cpp
|
#include "scriptedit.hpp"
#include <vector>
#include <QApplication>
#include <QDragEnterEvent>
#include <QMenu>
#include <QPainter>
#include <QString>
#include <QTextDocumentFragment>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/world/scripthighlighter.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/prefs/shortcut.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../../model/world/universalid.hpp"
CSVWorld::ScriptEdit::ChangeLock::ChangeLock(ScriptEdit& edit)
: mEdit(edit)
{
++mEdit.mChangeLocked;
}
CSVWorld::ScriptEdit::ChangeLock::~ChangeLock()
{
--mEdit.mChangeLocked;
}
bool CSVWorld::ScriptEdit::event(QEvent* event)
{
// ignore undo and redo shortcuts
if (event->type() == QEvent::ShortcutOverride)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->matches(QKeySequence::Undo) || keyEvent->matches(QKeySequence::Redo))
return true;
}
return QPlainTextEdit::event(event);
}
CSVWorld::ScriptEdit::ScriptEdit(const CSMDoc::Document& document, ScriptHighlighter::Mode mode, QWidget* parent)
: QPlainTextEdit(parent)
, mChangeLocked(0)
, mShowLineNum(false)
, mLineNumberArea(nullptr)
, mDefaultFont(font())
, mMonoFont(QFont("Monospace"))
, mTabCharCount(4)
, mMarkOccurrences(true)
, mDocument(document)
, mWhiteListQuotes("^[a-zA-Z_][a-zA-Z0-9_]*$")
{
wrapLines(false);
setTabWidth();
setUndoRedoEnabled(false); // we use OpenCS-wide undo/redo instead
mAllowedTypes << CSMWorld::UniversalId::Type_Journal << CSMWorld::UniversalId::Type_Global
<< CSMWorld::UniversalId::Type_Topic << CSMWorld::UniversalId::Type_Sound
<< CSMWorld::UniversalId::Type_Spell << CSMWorld::UniversalId::Type_Cell
<< CSMWorld::UniversalId::Type_Referenceable << CSMWorld::UniversalId::Type_Activator
<< CSMWorld::UniversalId::Type_Potion << CSMWorld::UniversalId::Type_Apparatus
<< CSMWorld::UniversalId::Type_Armor << CSMWorld::UniversalId::Type_Book
<< CSMWorld::UniversalId::Type_Clothing << CSMWorld::UniversalId::Type_Container
<< CSMWorld::UniversalId::Type_Creature << CSMWorld::UniversalId::Type_Door
<< CSMWorld::UniversalId::Type_Ingredient << CSMWorld::UniversalId::Type_CreatureLevelledList
<< CSMWorld::UniversalId::Type_ItemLevelledList << CSMWorld::UniversalId::Type_Light
<< CSMWorld::UniversalId::Type_Lockpick << CSMWorld::UniversalId::Type_Miscellaneous
<< CSMWorld::UniversalId::Type_Npc << CSMWorld::UniversalId::Type_Probe
<< CSMWorld::UniversalId::Type_Repair << CSMWorld::UniversalId::Type_Static
<< CSMWorld::UniversalId::Type_Weapon << CSMWorld::UniversalId::Type_Script
<< CSMWorld::UniversalId::Type_Region;
connect(this, &ScriptEdit::cursorPositionChanged, this, &ScriptEdit::markOccurrences);
mCommentAction = new QAction(tr("Comment Selection"), this);
connect(mCommentAction, &QAction::triggered, this, &ScriptEdit::commentSelection);
CSMPrefs::Shortcut* commentShortcut = new CSMPrefs::Shortcut("script-editor-comment", this);
commentShortcut->associateAction(mCommentAction);
mUncommentAction = new QAction(tr("Uncomment Selection"), this);
connect(mUncommentAction, &QAction::triggered, this, &ScriptEdit::uncommentSelection);
CSMPrefs::Shortcut* uncommentShortcut = new CSMPrefs::Shortcut("script-editor-uncomment", this);
uncommentShortcut->associateAction(mUncommentAction);
mHighlighter = new ScriptHighlighter(document.getData(), mode, ScriptEdit::document());
connect(&document.getData(), &CSMWorld::Data::idListChanged, this, &ScriptEdit::idListChanged);
connect(&mUpdateTimer, &QTimer::timeout, this, &ScriptEdit::updateHighlighting);
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &ScriptEdit::settingChanged);
{
ChangeLock lock(*this);
CSMPrefs::get()["Scripts"].update();
}
mUpdateTimer.setSingleShot(true);
// TODO: provide a font selector dialogue
mMonoFont.setStyleHint(QFont::TypeWriter);
mLineNumberArea = new LineNumberArea(this);
updateLineNumberAreaWidth(0);
connect(this, &ScriptEdit::blockCountChanged, this, &ScriptEdit::updateLineNumberAreaWidth);
connect(this, &ScriptEdit::updateRequest, this, &ScriptEdit::updateLineNumberArea);
updateHighlighting();
}
void CSVWorld::ScriptEdit::showLineNum(bool show)
{
if (show != mShowLineNum)
{
mShowLineNum = show;
updateLineNumberAreaWidth(0);
}
}
bool CSVWorld::ScriptEdit::isChangeLocked() const
{
return mChangeLocked != 0;
}
void CSVWorld::ScriptEdit::dragEnterEvent(QDragEnterEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime)
QPlainTextEdit::dragEnterEvent(event);
else
{
setTextCursor(cursorForPosition(event->pos()));
event->acceptProposedAction();
}
}
void CSVWorld::ScriptEdit::dragMoveEvent(QDragMoveEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime)
QPlainTextEdit::dragMoveEvent(event);
else
{
setTextCursor(cursorForPosition(event->pos()));
event->accept();
}
}
void CSVWorld::ScriptEdit::dropEvent(QDropEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime) // May happen when non-records (e.g. plain text) are dragged and dropped
{
QPlainTextEdit::dropEvent(event);
return;
}
setTextCursor(cursorForPosition(event->pos()));
if (mime->fromDocument(mDocument))
{
std::vector<CSMWorld::UniversalId> records(mime->getData());
for (std::vector<CSMWorld::UniversalId>::iterator it = records.begin(); it != records.end(); ++it)
{
if (mAllowedTypes.contains(it->getType()))
{
if (stringNeedsQuote(it->getId()))
{
insertPlainText(QString::fromUtf8(('"' + it->getId() + '"').c_str()));
}
else
{
insertPlainText(QString::fromUtf8(it->getId().c_str()));
}
}
}
}
}
bool CSVWorld::ScriptEdit::stringNeedsQuote(const std::string& id) const
{
const QString string(QString::fromUtf8(id.c_str()));
// I'm not quite sure when do we need to put quotes. To be safe we will use quotes for anything other than…
return !(string.contains(mWhiteListQuotes));
}
void CSVWorld::ScriptEdit::setTabWidth()
{
// Set tab width to specified number of characters using current font.
setTabStopDistance(mTabCharCount * fontMetrics().horizontalAdvance(' '));
}
void CSVWorld::ScriptEdit::wrapLines(bool wrap)
{
if (wrap)
{
setLineWrapMode(QPlainTextEdit::WidgetWidth);
}
else
{
setLineWrapMode(QPlainTextEdit::NoWrap);
}
}
void CSVWorld::ScriptEdit::settingChanged(const CSMPrefs::Setting* setting)
{
// Determine which setting was changed.
if (mHighlighter->settingChanged(setting))
{
updateHighlighting();
}
else if (*setting == "Scripts/mono-font")
{
setFont(setting->isTrue() ? mMonoFont : mDefaultFont);
setTabWidth();
}
else if (*setting == "Scripts/show-linenum")
{
showLineNum(setting->isTrue());
}
else if (*setting == "Scripts/wrap-lines")
{
wrapLines(setting->isTrue());
}
else if (*setting == "Scripts/tab-width")
{
mTabCharCount = setting->toInt();
setTabWidth();
}
else if (*setting == "Scripts/highlight-occurrences")
{
mMarkOccurrences = setting->isTrue();
mHighlighter->setMarkedWord("");
updateHighlighting();
mHighlighter->setMarkOccurrences(mMarkOccurrences);
}
}
void CSVWorld::ScriptEdit::idListChanged()
{
mHighlighter->invalidateIds();
if (!mUpdateTimer.isActive())
mUpdateTimer.start(0);
}
void CSVWorld::ScriptEdit::updateHighlighting()
{
if (isChangeLocked())
return;
ChangeLock lock(*this);
mHighlighter->rehighlight();
}
int CSVWorld::ScriptEdit::lineNumberAreaWidth()
{
if (!mShowLineNum)
return 0;
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10)
{
max /= 10;
++digits;
}
int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
return space;
}
void CSVWorld::ScriptEdit::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CSVWorld::ScriptEdit::updateLineNumberArea(const QRect& rect, int dy)
{
if (dy)
mLineNumberArea->scroll(0, dy);
else
mLineNumberArea->update(0, rect.y(), mLineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CSVWorld::ScriptEdit::markOccurrences()
{
if (mMarkOccurrences)
{
QTextCursor cursor = textCursor();
// prevent infinite recursion with cursor.select(),
// which ends up calling this function again
// could be fixed with blockSignals, but mDocument is const
disconnect(this, &ScriptEdit::cursorPositionChanged, this, nullptr);
cursor.select(QTextCursor::WordUnderCursor);
connect(this, &ScriptEdit::cursorPositionChanged, this, &ScriptEdit::markOccurrences);
QString word = cursor.selectedText();
mHighlighter->setMarkedWord(word.toStdString());
mHighlighter->rehighlight();
}
}
void CSVWorld::ScriptEdit::commentSelection()
{
QTextCursor begin = textCursor();
QTextCursor end = begin;
begin.setPosition(begin.selectionStart());
begin.movePosition(QTextCursor::StartOfLine);
end.setPosition(end.selectionEnd());
end.movePosition(QTextCursor::EndOfLine);
begin.beginEditBlock();
for (; begin < end; begin.movePosition(QTextCursor::EndOfLine), begin.movePosition(QTextCursor::Right))
{
begin.insertText(";");
}
begin.endEditBlock();
}
void CSVWorld::ScriptEdit::uncommentSelection()
{
QTextCursor begin = textCursor();
QTextCursor end = begin;
begin.setPosition(begin.selectionStart());
begin.movePosition(QTextCursor::StartOfLine);
end.setPosition(end.selectionEnd());
end.movePosition(QTextCursor::EndOfLine);
begin.beginEditBlock();
for (; begin < end; begin.movePosition(QTextCursor::EndOfLine), begin.movePosition(QTextCursor::Right))
{
begin.select(QTextCursor::LineUnderCursor);
QString line = begin.selectedText();
if (line.size() == 0)
continue;
// get first nonspace character in line
int index;
for (index = 0; index != line.size(); ++index)
{
if (!line[index].isSpace())
break;
}
if (index != line.size() && line[index] == ';')
{
// remove the semicolon
line.remove(index, 1);
// put the line back
begin.insertText(line);
}
}
begin.endEditBlock();
}
void CSVWorld::ScriptEdit::resizeEvent(QResizeEvent* e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
mLineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CSVWorld::ScriptEdit::contextMenuEvent(QContextMenuEvent* event)
{
QMenu* menu = createStandardContextMenu();
// remove redo/undo since they are disabled
QList<QAction*> menuActions = menu->actions();
for (QList<QAction*>::iterator i = menuActions.begin(); i < menuActions.end(); ++i)
{
if ((*i)->text().contains("Undo") || (*i)->text().contains("Redo"))
{
(*i)->setVisible(false);
}
}
menu->addAction(mCommentAction);
menu->addAction(mUncommentAction);
menu->exec(event->globalPos());
delete menu;
}
void CSVWorld::ScriptEdit::lineNumberAreaPaintEvent(QPaintEvent* event)
{
QPainter painter(mLineNumberArea);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int)blockBoundingRect(block).height();
int startBlock = textCursor().blockNumber();
int endBlock = textCursor().blockNumber();
if (textCursor().hasSelection())
{
QString str = textCursor().selection().toPlainText();
int offset = str.count("\n");
if (textCursor().position() < textCursor().anchor())
endBlock += offset;
else
startBlock -= offset;
}
painter.setBackgroundMode(Qt::OpaqueMode);
QFont font = painter.font();
QBrush background = painter.background();
QColor textColor = QApplication::palette().text().color();
while (block.isValid() && top <= event->rect().bottom())
{
if (block.isVisible() && bottom >= event->rect().top())
{
QFont newFont = painter.font();
QString number = QString::number(blockNumber + 1);
if (blockNumber >= startBlock && blockNumber <= endBlock)
{
painter.setBackground(Qt::cyan);
painter.setPen(Qt::darkMagenta);
newFont.setBold(true);
}
else
{
painter.setBackground(background);
painter.setPen(textColor);
}
painter.setFont(newFont);
painter.drawText(0, top, mLineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number);
painter.setFont(font);
}
block = block.next();
top = bottom;
bottom = top + (int)blockBoundingRect(block).height();
++blockNumber;
}
}
CSVWorld::LineNumberArea::LineNumberArea(ScriptEdit* editor)
: QWidget(editor)
, mScriptEdit(editor)
{
}
QSize CSVWorld::LineNumberArea::sizeHint() const
{
return QSize(mScriptEdit->lineNumberAreaWidth(), 0);
}
void CSVWorld::LineNumberArea::paintEvent(QPaintEvent* event)
{
mScriptEdit->lineNumberAreaPaintEvent(event);
}
| 14,695
|
C++
|
.cpp
| 398
| 30.547739
| 113
| 0.664815
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,026
|
globalcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/globalcreator.cpp
|
#include "globalcreator.hpp"
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include <components/esm3/variant.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
class QUndoStack;
namespace CSVWorld
{
void GlobalCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
CSMWorld::IdTable* table = static_cast<CSMWorld::IdTable*>(getData().getTableModel(getCollectionId()));
int index = table->findColumnIndex(CSMWorld::Columns::ColumnId_ValueType);
int type = (int)ESM::VT_Float;
command.addValue(index, type);
}
GlobalCreator::GlobalCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id)
: GenericCreator(data, undoStack, id, true)
{
}
}
| 891
|
C++
|
.cpp
| 22
| 36.227273
| 111
| 0.732869
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,027
|
dragdroputils.cpp
|
OpenMW_openmw/apps/opencs/view/world/dragdroputils.cpp
|
#include "dragdroputils.hpp"
#include <QDropEvent>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include "../../model/world/tablemimedata.hpp"
const CSMWorld::TableMimeData* CSVWorld::DragDropUtils::getTableMimeData(const QDropEvent& event)
{
return dynamic_cast<const CSMWorld::TableMimeData*>(event.mimeData());
}
bool CSVWorld::DragDropUtils::canAcceptData(const QDropEvent& event, CSMWorld::ColumnBase::Display type)
{
const CSMWorld::TableMimeData* data = getTableMimeData(event);
return data != nullptr && data->holdsType(type);
}
bool CSVWorld::DragDropUtils::isTopicOrJournal(const QDropEvent& event, CSMWorld::ColumnBase::Display type)
{
const CSMWorld::TableMimeData* data = getTableMimeData(event);
return data != nullptr
&& (data->holdsType(CSMWorld::UniversalId::Type_Topic) || data->holdsType(CSMWorld::UniversalId::Type_Journal));
}
bool CSVWorld::DragDropUtils::isInfo(const QDropEvent& event, CSMWorld::ColumnBase::Display type)
{
const CSMWorld::TableMimeData* data = getTableMimeData(event);
return data != nullptr
&& (data->holdsType(CSMWorld::UniversalId::Type_TopicInfo)
|| data->holdsType(CSMWorld::UniversalId::Type_JournalInfo));
}
CSMWorld::UniversalId CSVWorld::DragDropUtils::getAcceptedData(
const QDropEvent& event, CSMWorld::ColumnBase::Display type)
{
if (canAcceptData(event, type))
{
if (const CSMWorld::TableMimeData* data = getTableMimeData(event))
return data->returnMatching(type);
}
return CSMWorld::UniversalId::Type_None;
}
| 1,625
|
C++
|
.cpp
| 37
| 40.108108
| 120
| 0.752532
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,028
|
recordstatusdelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/recordstatusdelegate.cpp
|
#include "recordstatusdelegate.hpp"
#include "../../model/world/columns.hpp"
#include <apps/opencs/view/world/datadisplaydelegate.hpp>
#include <apps/opencs/view/world/util.hpp>
#include <string>
#include <utility>
#include <vector>
class QObject;
namespace CSMDoc
{
class Document;
}
namespace CSMWorld
{
class CommandDispatcher;
}
CSVWorld::RecordStatusDelegate::RecordStatusDelegate(const ValueList& values, const IconList& icons,
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: DataDisplayDelegate(values, icons, dispatcher, document, "Records", "status-format", parent)
{
}
CSVWorld::CommandDelegate* CSVWorld::RecordStatusDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new RecordStatusDelegate(mValues, mIcons, dispatcher, document, parent);
}
CSVWorld::RecordStatusDelegateFactory::RecordStatusDelegateFactory()
{
std::vector<std::pair<int, std::string>> enums
= CSMWorld::Columns::getEnums(CSMWorld::Columns::ColumnId_Modification);
static const char* sIcons[]
= { ":list-base", ":list-modified", ":list-added", ":list-removed", ":list-removed", 0 };
for (int i = 0; sIcons[i]; ++i)
{
auto& enumPair = enums.at(i);
add(enumPair.first, enumPair.second.c_str(), sIcons[i]);
}
}
| 1,396
|
C++
|
.cpp
| 38
| 33.447368
| 100
| 0.74239
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,029
|
referencecreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/referencecreator.cpp
|
#include "referencecreator.hpp"
#include <QLabel>
#include <memory>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/refcollection.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idcompletionmanager.hpp"
#include "../../model/world/idtable.hpp"
#include "../widget/droplineedit.hpp"
std::string CSVWorld::ReferenceCreator::getId() const
{
return mId;
}
void CSVWorld::ReferenceCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
// Set cellID
int cellIdColumn = dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()))
.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
command.addValue(cellIdColumn, mCell->text());
}
CSVWorld::ReferenceCreator::ReferenceCreator(CSMWorld::Data& data, QUndoStack& undoStack,
const CSMWorld::UniversalId& id, CSMWorld::IdCompletionManager& completionManager)
: GenericCreator(data, undoStack, id)
{
QLabel* label = new QLabel("Cell", this);
insertBeforeButtons(label, false);
// Add cell ID input with auto-completion.
// Only existing cell IDs are accepted so no ID validation is performed.
mCell = new CSVWidget::DropLineEdit(CSMWorld::ColumnBase::Display_Cell, this);
mCell->setCompleter(completionManager.getCompleter(CSMWorld::ColumnBase::Display_Cell).get());
insertBeforeButtons(mCell, true);
setManualEditing(false);
connect(mCell, &CSVWidget::DropLineEdit::textChanged, this, &ReferenceCreator::cellChanged);
connect(mCell, &CSVWidget::DropLineEdit::returnPressed, this, &ReferenceCreator::inputReturnPressed);
}
void CSVWorld::ReferenceCreator::reset()
{
GenericCreator::reset();
mCell->setText("");
mId = getData().getReferences().getNewId();
}
std::string CSVWorld::ReferenceCreator::getErrors() const
{
// We are ignoring errors coming from GenericCreator here, because the ID of the new
// record is internal and requires neither user input nor verification.
std::string errors;
const ESM::RefId cell = ESM::RefId::stringRefId(mCell->text().toStdString());
if (cell.empty())
errors += "Missing Cell ID";
else if (getData().getCells().searchId(cell) == -1)
errors += "Invalid Cell ID";
return errors;
}
void CSVWorld::ReferenceCreator::focus()
{
mCell->setFocus();
}
void CSVWorld::ReferenceCreator::cellChanged()
{
update();
}
void CSVWorld::ReferenceCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
CSMWorld::IdTable& referenceTable
= dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(CSMWorld::UniversalId::Type_References));
int cellIdColumn = referenceTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
mCell->setText(referenceTable.data(referenceTable.getModelIndex(originId, cellIdColumn)).toString());
CSVWorld::GenericCreator::cloneMode(originId, type);
cellChanged(); // otherwise ok button will remain disabled
}
CSVWorld::Creator* CSVWorld::ReferenceCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new ReferenceCreator(document.getData(), document.getUndoStack(), id, document.getIdCompletionManager());
}
| 3,522
|
C++
|
.cpp
| 80
| 40.325
| 116
| 0.747732
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,030
|
regionmap.cpp
|
OpenMW_openmw/apps/opencs/view/world/regionmap.cpp
|
#include "regionmap.hpp"
#include <algorithm>
#include <iterator>
#include <set>
#include <sstream>
#include <QAbstractItemModel>
#include <QAction>
#include <QBrush>
#include <QDropEvent>
#include <QHeaderView>
#include <QItemSelectionModel>
#include <QMenu>
#include <QTableView>
#include <apps/opencs/view/world/dragrecordtable.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/commandmacro.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/regionmap.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../../model/world/universalid.hpp"
void CSVWorld::RegionMap::contextMenuEvent(QContextMenuEvent* event)
{
QMenu menu(this);
if (getUnselectedCells().size() > 0)
menu.addAction(mSelectAllAction);
if (selectionModel()->selectedIndexes().size() > 0)
menu.addAction(mClearSelectionAction);
if (getMissingRegionCells().size() > 0)
menu.addAction(mSelectRegionsAction);
int selectedNonExistentCells = getSelectedCells(false, true).size();
if (selectedNonExistentCells > 0)
{
if (selectedNonExistentCells == 1)
mCreateCellsAction->setText("Create one Cell");
else
{
std::ostringstream stream;
stream << "Create " << selectedNonExistentCells << " cells";
mCreateCellsAction->setText(QString::fromUtf8(stream.str().c_str()));
}
menu.addAction(mCreateCellsAction);
}
if (getSelectedCells().size() > 0)
{
if (!mRegionId.empty())
{
mSetRegionAction->setText(QString::fromUtf8(("Set Region to " + mRegionId).c_str()));
menu.addAction(mSetRegionAction);
}
menu.addAction(mUnsetRegionAction);
menu.addAction(mViewInTableAction);
}
if (selectionModel()->selectedIndexes().size() > 0)
menu.addAction(mViewAction);
menu.exec(event->globalPos());
}
QModelIndexList CSVWorld::RegionMap::getUnselectedCells() const
{
const QAbstractItemModel* model = QTableView::model();
int rows = model->rowCount();
int columns = model->columnCount();
QModelIndexList selected = selectionModel()->selectedIndexes();
std::sort(selected.begin(), selected.end());
QModelIndexList all;
for (int y = 0; y < rows; ++y)
for (int x = 0; x < columns; ++x)
{
QModelIndex index = model->index(y, x);
if (model->data(index, Qt::BackgroundRole) != QBrush(Qt::DiagCrossPattern))
all.push_back(index);
}
std::sort(all.begin(), all.end());
QModelIndexList list;
std::set_difference(all.begin(), all.end(), selected.begin(), selected.end(), std::back_inserter(list));
return list;
}
QModelIndexList CSVWorld::RegionMap::getSelectedCells(bool existent, bool nonExistent) const
{
const QAbstractItemModel* model = QTableView::model();
QModelIndexList selected = selectionModel()->selectedIndexes();
QModelIndexList list;
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
bool exists = model->data(*iter, Qt::BackgroundRole) != QBrush(Qt::DiagCrossPattern);
if ((exists && existent) || (!exists && nonExistent))
list.push_back(*iter);
}
return list;
}
QModelIndexList CSVWorld::RegionMap::getMissingRegionCells() const
{
const QAbstractItemModel* model = QTableView::model();
QModelIndexList selected = selectionModel()->selectedIndexes();
std::set<std::string> regions;
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
std::string region = model->data(*iter, CSMWorld::RegionMap::Role_Region).toString().toUtf8().constData();
if (!region.empty())
regions.insert(region);
}
QModelIndexList list;
QModelIndexList unselected = getUnselectedCells();
for (QModelIndexList::const_iterator iter(unselected.begin()); iter != unselected.end(); ++iter)
{
std::string region = model->data(*iter, CSMWorld::RegionMap::Role_Region).toString().toUtf8().constData();
if (!region.empty() && regions.find(region) != regions.end())
list.push_back(*iter);
}
return list;
}
void CSVWorld::RegionMap::setRegion(const std::string& regionId)
{
QModelIndexList selected = getSelectedCells();
QAbstractItemModel* regionModel = model();
CSMWorld::IdTable* cellsModel
= &dynamic_cast<CSMWorld::IdTable&>(*mDocument.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
QString regionId2 = QString::fromUtf8(regionId.c_str());
CSMWorld::CommandMacro macro(mDocument.getUndoStack(), selected.size() > 1 ? tr("Set Region") : "");
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
std::string cellId = regionModel->data(*iter, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData();
QModelIndex index
= cellsModel->getModelIndex(cellId, cellsModel->findColumnIndex(CSMWorld::Columns::ColumnId_Region));
macro.push(new CSMWorld::ModifyCommand(*cellsModel, index, regionId2));
}
}
CSVWorld::RegionMap::RegionMap(const CSMWorld::UniversalId& universalId, CSMDoc::Document& document, QWidget* parent)
: DragRecordTable(document, parent)
{
verticalHeader()->hide();
horizontalHeader()->hide();
setSelectionMode(QAbstractItemView::ExtendedSelection);
setModel(document.getData().getTableModel(universalId));
resizeColumnsToContents();
resizeRowsToContents();
mSelectAllAction = new QAction(tr("Select All"), this);
connect(mSelectAllAction, &QAction::triggered, this, &RegionMap::selectAll);
addAction(mSelectAllAction);
mClearSelectionAction = new QAction(tr("Clear Selection"), this);
connect(mClearSelectionAction, &QAction::triggered, this, &RegionMap::clearSelection);
addAction(mClearSelectionAction);
mSelectRegionsAction = new QAction(tr("Select Regions"), this);
connect(mSelectRegionsAction, &QAction::triggered, this, &RegionMap::selectRegions);
addAction(mSelectRegionsAction);
mCreateCellsAction = new QAction(tr("Create Cells Action"), this);
connect(mCreateCellsAction, &QAction::triggered, this, &RegionMap::createCells);
addAction(mCreateCellsAction);
mSetRegionAction = new QAction(tr("Set Region"), this);
connect(mSetRegionAction, &QAction::triggered, this, qOverload<>(&RegionMap::setRegion));
addAction(mSetRegionAction);
mUnsetRegionAction = new QAction(tr("Unset Region"), this);
connect(mUnsetRegionAction, &QAction::triggered, this, &RegionMap::unsetRegion);
addAction(mUnsetRegionAction);
mViewAction = new QAction(tr("View Cells"), this);
connect(mViewAction, &QAction::triggered, this, &RegionMap::view);
addAction(mViewAction);
mViewInTableAction = new QAction(tr("View Cells in Table"), this);
connect(mViewInTableAction, &QAction::triggered, this, &RegionMap::viewInTable);
addAction(mViewInTableAction);
setAcceptDrops(true);
// Make columns square incase QSizeHint doesnt apply
for (int column = 0; column < this->model()->columnCount(); ++column)
this->setColumnWidth(column, this->rowHeight(0));
}
void CSVWorld::RegionMap::selectAll()
{
QModelIndexList unselected = getUnselectedCells();
for (QModelIndexList::const_iterator iter(unselected.begin()); iter != unselected.end(); ++iter)
selectionModel()->select(*iter, QItemSelectionModel::Select);
}
void CSVWorld::RegionMap::clearSelection()
{
selectionModel()->clearSelection();
}
void CSVWorld::RegionMap::selectRegions()
{
QModelIndexList unselected = getMissingRegionCells();
for (QModelIndexList::const_iterator iter(unselected.begin()); iter != unselected.end(); ++iter)
selectionModel()->select(*iter, QItemSelectionModel::Select);
}
void CSVWorld::RegionMap::createCells()
{
if (mEditLock)
return;
QModelIndexList selected = getSelectedCells(false, true);
CSMWorld::IdTable* cellsModel
= &dynamic_cast<CSMWorld::IdTable&>(*mDocument.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
CSMWorld::CommandMacro macro(mDocument.getUndoStack(), selected.size() > 1 ? tr("Create cells") : "");
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
std::string cellId = model()->data(*iter, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData();
macro.push(new CSMWorld::CreateCommand(*cellsModel, cellId));
}
}
void CSVWorld::RegionMap::setRegion()
{
if (mEditLock)
return;
setRegion(mRegionId);
}
void CSVWorld::RegionMap::unsetRegion()
{
if (mEditLock)
return;
setRegion("");
}
void CSVWorld::RegionMap::view()
{
std::ostringstream hint;
hint << "c:";
QModelIndexList selected = selectionModel()->selectedIndexes();
bool first = true;
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
std::string cellId = model()->data(*iter, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData();
if (first)
first = false;
else
hint << "; ";
hint << cellId;
}
emit editRequest(
CSMWorld::UniversalId(CSMWorld::UniversalId::Type_Scene, ESM::Cell::sDefaultWorldspaceId.getValue()),
hint.str());
}
void CSVWorld::RegionMap::viewInTable()
{
std::ostringstream hint;
hint << "f:!or(";
QModelIndexList selected = getSelectedCells();
bool first = true;
for (QModelIndexList::const_iterator iter(selected.begin()); iter != selected.end(); ++iter)
{
std::string cellId = model()->data(*iter, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData();
if (first)
first = false;
else
hint << ",";
hint << "string(ID,\"" << cellId << "\")";
}
hint << ")";
emit editRequest(CSMWorld::UniversalId::Type_Cells, hint.str());
}
void CSVWorld::RegionMap::mouseMoveEvent(QMouseEvent* event)
{
startDragFromTable(*this, indexAt(event->pos()));
}
std::vector<CSMWorld::UniversalId> CSVWorld::RegionMap::getDraggedRecords() const
{
QModelIndexList selected(getSelectedCells(true, false));
std::vector<CSMWorld::UniversalId> ids;
for (const QModelIndex& it : selected)
{
ids.emplace_back(CSMWorld::UniversalId::Type_Cell,
model()->data(it, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData());
}
selected = getSelectedCells(false, true);
for (const QModelIndex& it : selected)
{
ids.emplace_back(CSMWorld::UniversalId::Type_Cell_Missing,
model()->data(it, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData());
}
return ids;
}
void CSVWorld::RegionMap::dragMoveEvent(QDragMoveEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (mime != nullptr && (mime->holdsType(CSMWorld::UniversalId::Type_Region)))
{
event->accept();
return;
}
event->ignore();
}
void CSVWorld::RegionMap::dropEvent(QDropEvent* event)
{
QModelIndex index = indexAt(event->pos());
bool exists = QTableView::model()->data(index, Qt::BackgroundRole) != QBrush(Qt::DiagCrossPattern);
if (!index.isValid() || !exists)
{
return;
}
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime) // May happen when non-records (e.g. plain text) are dragged and dropped
return;
if (mime->fromDocument(mDocument) && mime->holdsType(CSMWorld::UniversalId::Type_Region))
{
CSMWorld::UniversalId record(mime->returnMatching(CSMWorld::UniversalId::Type_Region));
QAbstractItemModel* regionModel = model();
CSMWorld::IdTable* cellsModel
= &dynamic_cast<CSMWorld::IdTable&>(*mDocument.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
std::string cellId(regionModel->data(index, CSMWorld::RegionMap::Role_CellId).toString().toUtf8().constData());
QModelIndex index2(
cellsModel->getModelIndex(cellId, cellsModel->findColumnIndex(CSMWorld::Columns::ColumnId_Region)));
mDocument.getUndoStack().push(
new CSMWorld::ModifyCommand(*cellsModel, index2, QString::fromUtf8(record.getId().c_str())));
mRegionId = record.getId();
}
}
| 12,790
|
C++
|
.cpp
| 302
| 36.635762
| 120
| 0.687964
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,031
|
idvalidator.cpp
|
OpenMW_openmw/apps/opencs/view/world/idvalidator.cpp
|
#include "idvalidator.hpp"
#include <components/misc/strings/lower.hpp>
CSVWorld::IdValidator::IdValidator(bool relaxed, QObject* parent)
: QValidator(parent)
, mRelaxed(relaxed)
{
}
QValidator::State CSVWorld::IdValidator::validate(QString& input, int& pos) const
{
mError.clear();
if (mRelaxed)
{
if (input.indexOf('"') != -1 || input.indexOf("::") != -1 || input.indexOf("#") != -1)
return QValidator::Invalid;
}
else
{
if (input.isEmpty())
{
mError = "Missing ID";
return QValidator::Intermediate;
}
bool first = true;
bool scope = false;
bool prevScope = false;
QString::const_iterator iter = input.begin();
if (!mNamespace.empty())
{
std::string namespace_ = input.left(static_cast<int>(mNamespace.size())).toUtf8().constData();
if (Misc::StringUtils::lowerCase(namespace_) != mNamespace)
return QValidator::Invalid; // incorrect namespace
iter += namespace_.size();
first = false;
prevScope = true;
}
else
{
int index = input.indexOf(":");
if (index != -1)
{
QString namespace_ = input.left(index);
if (namespace_ == "project" || namespace_ == "session")
return QValidator::Invalid; // reserved namespace
}
}
for (; iter != input.end(); ++iter, first = false)
{
if (*iter == ':')
{
if (first)
return QValidator::Invalid; // scope operator at the beginning
if (scope)
{
scope = false;
prevScope = true;
}
else
{
if (prevScope)
return QValidator::Invalid; // sequence of two scope operators
scope = true;
}
}
else if (scope)
return QValidator::Invalid; // incomplete scope operator
else
{
prevScope = false;
if (!iter->isPrint())
return QValidator::Invalid;
}
}
if (scope)
{
mError = "ID ending with incomplete scope operator";
return QValidator::Intermediate;
}
if (prevScope)
{
mError = "ID ending with scope operator";
return QValidator::Intermediate;
}
}
return QValidator::Acceptable;
}
void CSVWorld::IdValidator::setNamespace(const std::string& namespace_)
{
mNamespace = Misc::StringUtils::lowerCase(namespace_);
}
std::string CSVWorld::IdValidator::getError() const
{
return mError;
}
| 2,899
|
C++
|
.cpp
| 93
| 20.494624
| 106
| 0.507179
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,032
|
dialoguespinbox.cpp
|
OpenMW_openmw/apps/opencs/view/world/dialoguespinbox.cpp
|
#include "dialoguespinbox.hpp"
#include <QWheelEvent>
CSVWorld::DialogueSpinBox::DialogueSpinBox(QWidget* parent)
: QSpinBox(parent)
{
setFocusPolicy(Qt::StrongFocus);
}
void CSVWorld::DialogueSpinBox::focusInEvent(QFocusEvent* event)
{
setFocusPolicy(Qt::WheelFocus);
QSpinBox::focusInEvent(event);
}
void CSVWorld::DialogueSpinBox::focusOutEvent(QFocusEvent* event)
{
setFocusPolicy(Qt::StrongFocus);
QSpinBox::focusOutEvent(event);
}
void CSVWorld::DialogueSpinBox::wheelEvent(QWheelEvent* event)
{
if (!hasFocus())
event->ignore();
else
QSpinBox::wheelEvent(event);
}
CSVWorld::DialogueDoubleSpinBox::DialogueDoubleSpinBox(QWidget* parent)
: QDoubleSpinBox(parent)
{
setFocusPolicy(Qt::StrongFocus);
}
void CSVWorld::DialogueDoubleSpinBox::focusInEvent(QFocusEvent* event)
{
setFocusPolicy(Qt::WheelFocus);
QDoubleSpinBox::focusInEvent(event);
}
void CSVWorld::DialogueDoubleSpinBox::focusOutEvent(QFocusEvent* event)
{
setFocusPolicy(Qt::StrongFocus);
QDoubleSpinBox::focusOutEvent(event);
}
void CSVWorld::DialogueDoubleSpinBox::wheelEvent(QWheelEvent* event)
{
if (!hasFocus())
event->ignore();
else
QDoubleSpinBox::wheelEvent(event);
}
| 1,249
|
C++
|
.cpp
| 46
| 23.869565
| 71
| 0.764657
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,033
|
genericcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/genericcreator.cpp
|
#include "genericcreator.hpp"
#include <memory>
#include <utility>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QUndoStack>
#include <apps/opencs/model/world/universalid.hpp>
#include <components/misc/strings/lower.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
#include "idvalidator.hpp"
void CSVWorld::GenericCreator::update()
{
mErrors = getErrors();
mCreate->setToolTip(QString::fromUtf8(mErrors.c_str()));
mId->setToolTip(QString::fromUtf8(mErrors.c_str()));
mCreate->setEnabled(mErrors.empty() && !mLocked);
}
void CSVWorld::GenericCreator::setManualEditing(bool enabled)
{
mId->setVisible(enabled);
}
void CSVWorld::GenericCreator::insertAtBeginning(QWidget* widget, bool stretched)
{
mLayout->insertWidget(0, widget, stretched ? 1 : 0);
}
void CSVWorld::GenericCreator::insertBeforeButtons(QWidget* widget, bool stretched)
{
mLayout->insertWidget(mLayout->count() - 2, widget, stretched ? 1 : 0);
// Reset tab order relative to buttons.
setTabOrder(widget, mCreate);
setTabOrder(mCreate, mCancel);
}
std::string CSVWorld::GenericCreator::getId() const
{
return mId->text().toUtf8().constData();
}
std::string CSVWorld::GenericCreator::getClonedId() const
{
return mClonedId;
}
std::string CSVWorld::GenericCreator::getIdValidatorResult() const
{
std::string errors;
if (!mId->hasAcceptableInput())
errors = mValidator->getError();
return errors;
}
void CSVWorld::GenericCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const {}
void CSVWorld::GenericCreator::pushCommand(std::unique_ptr<CSMWorld::CreateCommand> command, const std::string& id)
{
mUndoStack.push(command.release());
}
CSMWorld::Data& CSVWorld::GenericCreator::getData() const
{
return mData;
}
QUndoStack& CSVWorld::GenericCreator::getUndoStack()
{
return mUndoStack;
}
const CSMWorld::UniversalId& CSVWorld::GenericCreator::getCollectionId() const
{
return mListId;
}
std::string CSVWorld::GenericCreator::getNamespace() const
{
CSMWorld::Scope scope = CSMWorld::Scope_Content;
if (mScope)
{
scope = static_cast<CSMWorld::Scope>(mScope->itemData(mScope->currentIndex()).toInt());
}
else
{
if (mScopes & CSMWorld::Scope_Project)
scope = CSMWorld::Scope_Project;
else if (mScopes & CSMWorld::Scope_Session)
scope = CSMWorld::Scope_Session;
}
switch (scope)
{
case CSMWorld::Scope_Content:
return "";
case CSMWorld::Scope_Project:
return "project::";
case CSMWorld::Scope_Session:
return "session::";
}
return "";
}
void CSVWorld::GenericCreator::updateNamespace()
{
std::string namespace_ = getNamespace();
mValidator->setNamespace(namespace_);
int index = mId->text().indexOf("::");
if (index == -1)
{
// no namespace in old text
mId->setText(QString::fromUtf8(namespace_.c_str()) + mId->text());
}
else
{
std::string oldNamespace = Misc::StringUtils::lowerCase(mId->text().left(index).toUtf8().constData());
if (oldNamespace == "project" || oldNamespace == "session")
mId->setText(QString::fromUtf8(namespace_.c_str()) + mId->text().mid(index + 2));
}
}
void CSVWorld::GenericCreator::addScope(const QString& name, CSMWorld::Scope scope, const QString& tooltip)
{
mScope->addItem(name, static_cast<int>(scope));
mScope->setItemData(mScope->count() - 1, tooltip, Qt::ToolTipRole);
}
CSVWorld::GenericCreator::GenericCreator(
CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id, bool relaxedIdRules)
: mData(data)
, mUndoStack(undoStack)
, mListId(id)
, mLocked(false)
, mClonedType(CSMWorld::UniversalId::Type_None)
, mScopes(CSMWorld::Scope_Content)
, mScope(nullptr)
, mScopeLabel(nullptr)
, mCloneMode(false)
{
// If the collection ID has a parent type, use it instead.
// It will change IDs with Record/SubRecord class (used for creators in Dialogue subviews)
// to IDs with general RecordList class (used for creators in Table subviews).
CSMWorld::UniversalId::Type listParentType = CSMWorld::UniversalId::getParentType(mListId.getType());
if (listParentType != CSMWorld::UniversalId::Type_None)
{
mListId = listParentType;
}
mLayout = new QHBoxLayout;
mLayout->setContentsMargins(0, 0, 0, 0);
mId = new QLineEdit;
mId->setValidator(mValidator = new IdValidator(relaxedIdRules, this));
mLayout->addWidget(mId, 1);
mCreate = new QPushButton("Create");
mLayout->addWidget(mCreate);
mCancel = new QPushButton("Cancel");
mLayout->addWidget(mCancel);
setLayout(mLayout);
connect(mCancel, &QPushButton::clicked, this, &GenericCreator::done);
connect(mCreate, &QPushButton::clicked, this, &GenericCreator::create);
connect(mId, &QLineEdit::textChanged, this, &GenericCreator::textChanged);
connect(mId, &QLineEdit::returnPressed, this, &GenericCreator::inputReturnPressed);
connect(&mData, &CSMWorld::Data::idListChanged, this, &GenericCreator::dataIdListChanged);
}
void CSVWorld::GenericCreator::setEditorMaxLength(int length)
{
mId->setMaxLength(length);
}
void CSVWorld::GenericCreator::setEditLock(bool locked)
{
mLocked = locked;
update();
}
void CSVWorld::GenericCreator::reset()
{
mCloneMode = false;
mId->setText("");
update();
updateNamespace();
}
std::string CSVWorld::GenericCreator::getErrors() const
{
std::string errors;
if (!mId->hasAcceptableInput())
errors = mValidator->getError();
else if (mData.hasId(getId()))
errors = "ID is already in use";
return errors;
}
void CSVWorld::GenericCreator::textChanged(const QString& text)
{
update();
}
void CSVWorld::GenericCreator::inputReturnPressed()
{
if (mCreate->isEnabled())
{
create();
}
}
void CSVWorld::GenericCreator::create()
{
if (!mLocked)
{
std::string id = getId();
std::unique_ptr<CSMWorld::CreateCommand> command;
if (mCloneMode)
{
command = std::make_unique<CSMWorld::CloneCommand>(
dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(mListId)), mClonedId, id, mClonedType);
}
else
{
command = std::make_unique<CSMWorld::CreateCommand>(
dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(mListId)), id);
}
configureCreateCommand(*command);
pushCommand(std::move(command), id);
emit done();
emit requestFocus(id);
}
}
void CSVWorld::GenericCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
mCloneMode = true;
mClonedId = originId;
mClonedType = type;
}
void CSVWorld::GenericCreator::touch(const std::vector<CSMWorld::UniversalId>& ids)
{
// Combine multiple touch commands into one "macro" command
mUndoStack.beginMacro("Touch Records");
CSMWorld::IdTable& table = dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(mListId));
for (const CSMWorld::UniversalId& uid : ids)
{
CSMWorld::TouchCommand* touchCmd = new CSMWorld::TouchCommand(table, uid.getId());
mUndoStack.push(touchCmd);
}
// Execute
mUndoStack.endMacro();
}
void CSVWorld::GenericCreator::toggleWidgets(bool active) {}
void CSVWorld::GenericCreator::focus()
{
mId->setFocus();
}
void CSVWorld::GenericCreator::setScope(unsigned int scope)
{
mScopes = scope;
int count = (mScopes & CSMWorld::Scope_Content) + (mScopes & CSMWorld::Scope_Project)
+ (mScopes & CSMWorld::Scope_Session);
// scope selector widget
if (count > 1)
{
mScope = new QComboBox(this);
insertAtBeginning(mScope, false);
if (mScopes & CSMWorld::Scope_Content)
addScope("Content", CSMWorld::Scope_Content, "Record will be stored in the currently edited content file.");
if (mScopes & CSMWorld::Scope_Project)
addScope("Project", CSMWorld::Scope_Project,
"Record will be stored in a local project file.<p>"
"Record will be created in the reserved namespace \"project\".<p>"
"Record is available when running OpenMW via OpenCS.");
if (mScopes & CSMWorld::Scope_Session)
addScope("Session", CSMWorld::Scope_Session,
"Record exists only for the duration of the current editing session.<p>"
"Record will be created in the reserved namespace \"session\".<p>"
"Record is not available when running OpenMW via OpenCS.");
connect(mScope, qOverload<int>(&QComboBox::currentIndexChanged), this, &GenericCreator::scopeChanged);
mScopeLabel = new QLabel("Scope", this);
insertAtBeginning(mScopeLabel, false);
mScope->setCurrentIndex(0);
}
else
{
delete mScope;
mScope = nullptr;
delete mScopeLabel;
mScopeLabel = nullptr;
}
updateNamespace();
}
void CSVWorld::GenericCreator::scopeChanged(int index)
{
update();
updateNamespace();
}
void CSVWorld::GenericCreator::dataIdListChanged()
{
// If the original ID of cloned record was removed, cancel the creator
if (mCloneMode && !mData.hasId(mClonedId))
{
emit done();
}
}
| 9,587
|
C++
|
.cpp
| 283
| 28.773852
| 120
| 0.685516
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,034
|
tablebottombox.cpp
|
OpenMW_openmw/apps/opencs/view/world/tablebottombox.cpp
|
#include "tablebottombox.hpp"
#include <sstream>
#include <QEvent>
#include <QKeyEvent>
#include <QLabel>
#include <QStackedLayout>
#include <QStatusBar>
#include <components/debug/debuglog.hpp>
#include <apps/opencs/view/world/extendedcommandconfigurator.hpp>
#include "creator.hpp"
#include "infocreator.hpp"
namespace
{
constexpr const char* statusBarStyle = "QStatusBar::item { border: 0px }";
}
void CSVWorld::TableBottomBox::updateSize()
{
// Make sure that the size of the bottom box is determined by the currently visible widget
for (int i = 0; i < mLayout->count(); ++i)
{
QSizePolicy::Policy verPolicy = QSizePolicy::Ignored;
if (mLayout->widget(i) == mLayout->currentWidget())
{
verPolicy = QSizePolicy::Expanding;
}
mLayout->widget(i)->setSizePolicy(QSizePolicy::Expanding, verPolicy);
}
}
void CSVWorld::TableBottomBox::updateStatus()
{
if (mShowStatusBar)
{
if (!mStatusMessage.isEmpty())
{
mStatus->setText(mStatusMessage);
return;
}
static const char* sLabels[4] = { "record", "deleted", "touched", "selected" };
static const char* sLabelsPlural[4] = { "records", "deleted", "touched", "selected" };
std::ostringstream stream;
bool first = true;
for (int i = 0; i < 4; ++i)
{
if (mStatusCount[i] > 0)
{
if (first)
first = false;
else
stream << ", ";
stream << mStatusCount[i] << ' ' << (mStatusCount[i] == 1 ? sLabels[i] : sLabelsPlural[i]);
}
}
if (mHasPosition)
{
if (!first)
stream << " -- ";
stream << "(" << mRow << ", " << mColumn << ")";
}
mStatus->setText(QString::fromUtf8(stream.str().c_str()));
}
}
void CSVWorld::TableBottomBox::extendedConfigRequest(
CSVWorld::ExtendedCommandConfigurator::Mode mode, const std::vector<std::string>& selectedIds)
{
mExtendedConfigurator->configure(mode, selectedIds);
mLayout->setCurrentWidget(mExtendedConfigurator);
mEditMode = EditMode_ExtendedConfig;
setVisible(true);
mExtendedConfigurator->setFocus();
}
CSVWorld::TableBottomBox::TableBottomBox(const CreatorFactoryBase& creatorFactory, CSMDoc::Document& document,
const CSMWorld::UniversalId& id, QWidget* parent)
: QWidget(parent)
, mShowStatusBar(false)
, mEditMode(EditMode_None)
, mHasPosition(false)
, mRow(0)
, mColumn(0)
{
for (int i = 0; i < 4; ++i)
mStatusCount[i] = 0;
setVisible(false);
mLayout = new QStackedLayout;
mLayout->setContentsMargins(0, 0, 0, 0);
connect(mLayout, &QStackedLayout::currentChanged, this, &TableBottomBox::currentWidgetChanged);
mStatus = new QLabel;
mStatusBar = new QStatusBar(this);
mStatusBar->addWidget(mStatus);
mStatusBar->setStyleSheet(statusBarStyle);
mLayout->addWidget(mStatusBar);
setLayout(mLayout);
mCreator = creatorFactory.makeCreator(document, id);
if (mCreator)
{
mCreator->installEventFilter(this);
mLayout->addWidget(mCreator);
connect(mCreator, &Creator::done, this, &TableBottomBox::requestDone);
connect(mCreator, &Creator::requestFocus, this, &TableBottomBox::requestFocus);
}
mExtendedConfigurator = new ExtendedCommandConfigurator(document, id, this);
mExtendedConfigurator->installEventFilter(this);
mLayout->addWidget(mExtendedConfigurator);
connect(mExtendedConfigurator, &ExtendedCommandConfigurator::done, this, &TableBottomBox::requestDone);
updateSize();
}
bool CSVWorld::TableBottomBox::event(QEvent* event)
{
// Apply style sheet again if style was changed
if (event->type() == QEvent::PaletteChange)
{
if (mStatusBar != nullptr)
mStatusBar->setStyleSheet(statusBarStyle);
}
return QWidget::event(event);
}
void CSVWorld::TableBottomBox::setEditLock(bool locked)
{
if (mCreator)
mCreator->setEditLock(locked);
mExtendedConfigurator->setEditLock(locked);
}
CSVWorld::TableBottomBox::~TableBottomBox()
{
delete mCreator;
}
bool CSVWorld::TableBottomBox::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Escape)
{
requestDone();
return true;
}
}
return QWidget::eventFilter(object, event);
}
void CSVWorld::TableBottomBox::setStatusBar(bool show)
{
if (show != mShowStatusBar)
{
setVisible(show || (mEditMode != EditMode_None));
mShowStatusBar = show;
if (show)
updateStatus();
}
}
bool CSVWorld::TableBottomBox::canCreateAndDelete() const
{
return mCreator;
}
void CSVWorld::TableBottomBox::requestDone()
{
if (!mShowStatusBar)
setVisible(false);
else
updateStatus();
mLayout->setCurrentWidget(mStatusBar);
mEditMode = EditMode_None;
}
void CSVWorld::TableBottomBox::currentWidgetChanged(int /*index*/)
{
updateSize();
}
void CSVWorld::TableBottomBox::setStatusMessage(const QString& message)
{
mStatusMessage = message;
updateStatus();
}
void CSVWorld::TableBottomBox::selectionSizeChanged(int size)
{
if (mStatusCount[3] != size)
{
mStatusMessage = "";
mStatusCount[3] = size;
updateStatus();
}
}
void CSVWorld::TableBottomBox::tableSizeChanged(int size, int deleted, int modified)
{
bool changed = false;
if (mStatusCount[0] != size)
{
mStatusCount[0] = size;
changed = true;
}
if (mStatusCount[1] != deleted)
{
mStatusCount[1] = deleted;
changed = true;
}
if (mStatusCount[2] != modified)
{
mStatusCount[2] = modified;
changed = true;
}
if (changed)
{
mStatusMessage = "";
updateStatus();
}
}
void CSVWorld::TableBottomBox::positionChanged(int row, int column)
{
mRow = row;
mColumn = column;
mHasPosition = true;
updateStatus();
}
void CSVWorld::TableBottomBox::noMorePosition()
{
mHasPosition = false;
updateStatus();
}
void CSVWorld::TableBottomBox::createRequest()
{
mCreator->reset();
mCreator->toggleWidgets(true);
mLayout->setCurrentWidget(mCreator);
setVisible(true);
mEditMode = EditMode_Creation;
mCreator->focus();
}
void CSVWorld::TableBottomBox::createRecordsDirectlyRequest(const std::string& id)
{
if (InfoCreator* creator = dynamic_cast<InfoCreator*>(mCreator))
{
creator->reset();
creator->setText(id);
creator->callReturnPressed();
}
else
{
Log(Debug::Warning) << "Creating a record directly failed.";
}
}
void CSVWorld::TableBottomBox::cloneRequest(const std::string& id, const CSMWorld::UniversalId::Type type)
{
mCreator->reset();
mCreator->cloneMode(id, type);
mLayout->setCurrentWidget(mCreator);
mCreator->toggleWidgets(false);
setVisible(true);
mEditMode = EditMode_Creation;
mCreator->focus();
}
void CSVWorld::TableBottomBox::touchRequest(const std::vector<CSMWorld::UniversalId>& ids)
{
mCreator->touch(ids);
}
void CSVWorld::TableBottomBox::extendedDeleteConfigRequest(const std::vector<std::string>& selectedIds)
{
extendedConfigRequest(ExtendedCommandConfigurator::Mode_Delete, selectedIds);
}
void CSVWorld::TableBottomBox::extendedRevertConfigRequest(const std::vector<std::string>& selectedIds)
{
extendedConfigRequest(ExtendedCommandConfigurator::Mode_Revert, selectedIds);
}
| 7,764
|
C++
|
.cpp
| 259
| 24.583012
| 110
| 0.669531
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,035
|
scripterrortable.cpp
|
OpenMW_openmw/apps/opencs/view/world/scripterrortable.cpp
|
#include "scripterrortable.hpp"
#include <exception>
#include <sstream>
#include <QHeaderView>
#include <apps/opencs/model/doc/messages.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/scriptcontext.hpp>
#include <components/compiler/exception.hpp>
#include <components/compiler/extensions0.hpp>
#include <components/compiler/fileparser.hpp>
#include <components/compiler/scanner.hpp>
#include <components/compiler/tokenloc.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/prefs/state.hpp"
void CSVWorld::ScriptErrorTable::report(const std::string& message, const Compiler::TokenLoc& loc, Type type)
{
std::ostringstream stream;
stream << message << " (" << loc.mLiteral << ")";
addMessage(stream.str(),
type == Compiler::ErrorHandler::WarningMessage ? CSMDoc::Message::Severity_Warning
: CSMDoc::Message::Severity_Error,
loc.mLine, loc.mColumn - loc.mLiteral.length());
}
void CSVWorld::ScriptErrorTable::report(const std::string& message, Type type)
{
addMessage(message,
type == Compiler::ErrorHandler::WarningMessage ? CSMDoc::Message::Severity_Warning
: CSMDoc::Message::Severity_Error);
}
void CSVWorld::ScriptErrorTable::addMessage(
const std::string& message, CSMDoc::Message::Severity severity, int line, int column)
{
int row = rowCount();
setRowCount(row + 1);
QTableWidgetItem* severityItem
= new QTableWidgetItem(QString::fromUtf8(CSMDoc::Message::toString(severity).c_str()));
severityItem->setFlags(severityItem->flags() ^ Qt::ItemIsEditable);
setItem(row, 0, severityItem);
if (line != -1)
{
QTableWidgetItem* lineItem = new QTableWidgetItem;
lineItem->setData(Qt::DisplayRole, line + 1);
lineItem->setFlags(lineItem->flags() ^ Qt::ItemIsEditable);
setItem(row, 1, lineItem);
QTableWidgetItem* columnItem = new QTableWidgetItem;
columnItem->setData(Qt::DisplayRole, column);
columnItem->setFlags(columnItem->flags() ^ Qt::ItemIsEditable);
setItem(row, 3, columnItem);
}
else
{
QTableWidgetItem* lineItem = new QTableWidgetItem;
lineItem->setData(Qt::DisplayRole, "-");
lineItem->setFlags(lineItem->flags() ^ Qt::ItemIsEditable);
setItem(row, 1, lineItem);
}
QTableWidgetItem* messageItem = new QTableWidgetItem(QString::fromUtf8(message.c_str()));
messageItem->setFlags(messageItem->flags() ^ Qt::ItemIsEditable);
setItem(row, 2, messageItem);
}
void CSVWorld::ScriptErrorTable::setWarningsMode(const std::string& value)
{
if (value == "Ignore")
Compiler::ErrorHandler::setWarningsMode(0);
else if (value == "Normal")
Compiler::ErrorHandler::setWarningsMode(1);
else if (value == "Strict")
Compiler::ErrorHandler::setWarningsMode(2);
}
CSVWorld::ScriptErrorTable::ScriptErrorTable(const CSMDoc::Document& document, QWidget* parent)
: QTableWidget(parent)
, mContext(document.getData())
{
setColumnCount(4);
QStringList headers;
headers << "Severity"
<< "Line"
<< "Description";
setHorizontalHeaderLabels(headers);
horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
horizontalHeader()->setStretchLastSection(true);
verticalHeader()->hide();
setColumnHidden(3, true);
setSelectionMode(QAbstractItemView::NoSelection);
Compiler::registerExtensions(mExtensions);
mContext.setExtensions(&mExtensions);
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &ScriptErrorTable::settingChanged);
CSMPrefs::get()["Scripts"].update();
connect(this, &QTableWidget::cellClicked, this, &ScriptErrorTable::cellClicked);
}
void CSVWorld::ScriptErrorTable::update(const std::string& source)
{
clear();
try
{
std::istringstream input(source);
Compiler::Scanner scanner(*this, input, mContext.getExtensions());
Compiler::FileParser parser(*this, mContext);
scanner.scan(parser);
}
catch (const Compiler::SourceException&)
{
// error has already been reported via error handler
}
catch (const std::exception& error)
{
addMessage(error.what(), CSMDoc::Message::Severity_SeriousError);
}
}
void CSVWorld::ScriptErrorTable::clear()
{
setRowCount(0);
}
bool CSVWorld::ScriptErrorTable::clearLocals(const std::string& script)
{
return mContext.clearLocals(script);
}
void CSVWorld::ScriptErrorTable::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "Scripts/warnings")
setWarningsMode(setting->toString());
}
void CSVWorld::ScriptErrorTable::cellClicked(int row, int column)
{
if (item(row, 3))
{
int scriptLine = item(row, 1)->data(Qt::DisplayRole).toInt();
int scriptColumn = item(row, 3)->data(Qt::DisplayRole).toInt();
emit highlightError(scriptLine - 1, scriptColumn);
}
}
| 5,227
|
C++
|
.cpp
| 133
| 33.661654
| 112
| 0.696425
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,036
|
vartypedelegate.cpp
|
OpenMW_openmw/apps/opencs/view/world/vartypedelegate.cpp
|
#include "vartypedelegate.hpp"
#include <algorithm>
#include <memory>
#include <stdexcept>
#include <string>
#include <apps/opencs/view/world/enumdelegate.hpp>
#include "../../model/world/columns.hpp"
#include "../../model/world/commandmacro.hpp"
#include "../../model/world/commands.hpp"
namespace CSMDoc
{
class Document;
}
namespace CSMWorld
{
class CommandDispatcher;
}
void CSVWorld::VarTypeDelegate::addCommands(QAbstractItemModel* model, const QModelIndex& index, int type) const
{
QModelIndex next = model->index(index.row(), index.column() + 1);
QVariant old = model->data(next);
QVariant value;
switch (type)
{
case ESM::VT_Short:
case ESM::VT_Int:
case ESM::VT_Long:
value = old.toInt();
break;
case ESM::VT_Float:
value = old.toFloat();
break;
case ESM::VT_String:
value = old.toString();
break;
default:
break; // ignore the rest
}
CSMWorld::CommandMacro macro(
getUndoStack(), "Modify " + model->headerData(index.column(), Qt::Horizontal, Qt::DisplayRole).toString());
macro.push(new CSMWorld::ModifyCommand(*model, index, type));
macro.push(new CSMWorld::ModifyCommand(*model, next, value));
}
CSVWorld::VarTypeDelegate::VarTypeDelegate(const std::vector<std::pair<int, QString>>& values,
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent)
: EnumDelegate(values, dispatcher, document, parent)
{
}
CSVWorld::VarTypeDelegateFactory::VarTypeDelegateFactory(
ESM::VarType type0, ESM::VarType type1, ESM::VarType type2, ESM::VarType type3)
{
if (type0 != ESM::VT_Unknown)
add(type0);
if (type1 != ESM::VT_Unknown)
add(type1);
if (type2 != ESM::VT_Unknown)
add(type2);
if (type3 != ESM::VT_Unknown)
add(type3);
}
CSVWorld::CommandDelegate* CSVWorld::VarTypeDelegateFactory::makeDelegate(
CSMWorld::CommandDispatcher* dispatcher, CSMDoc::Document& document, QObject* parent) const
{
return new VarTypeDelegate(mValues, dispatcher, document, parent);
}
void CSVWorld::VarTypeDelegateFactory::add(ESM::VarType type)
{
std::vector<std::pair<int, std::string>> enums = CSMWorld::Columns::getEnums(CSMWorld::Columns::ColumnId_ValueType);
if (static_cast<size_t>(type) >= enums.size())
throw std::logic_error("Unsupported variable type");
mValues.emplace_back(type, QString::fromUtf8(enums[type].second.c_str()));
}
| 2,551
|
C++
|
.cpp
| 72
| 30.291667
| 120
| 0.684876
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,037
|
bodypartcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/bodypartcreator.cpp
|
#include "bodypartcreator.hpp"
#include <QCheckBox>
#include "../../model/world/data.hpp"
#include "../../model/world/universalid.hpp"
#include <apps/opencs/view/world/genericcreator.hpp>
std::string CSVWorld::BodyPartCreator::getId() const
{
std::string id = CSVWorld::GenericCreator::getId();
if (mFirstPerson->isChecked())
{
id += ".1st";
}
return id;
}
CSVWorld::BodyPartCreator::BodyPartCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id)
: GenericCreator(data, undoStack, id)
{
mFirstPerson = new QCheckBox("First Person", this);
insertBeforeButtons(mFirstPerson, false);
connect(mFirstPerson, &QCheckBox::clicked, this, &BodyPartCreator::checkboxClicked);
}
std::string CSVWorld::BodyPartCreator::getErrors() const
{
std::string errors;
std::string id = getId();
if (getData().hasId(id))
{
errors = "ID is already in use";
}
return errors;
}
void CSVWorld::BodyPartCreator::reset()
{
CSVWorld::GenericCreator::reset();
mFirstPerson->setChecked(false);
}
void CSVWorld::BodyPartCreator::checkboxClicked()
{
update();
}
| 1,160
|
C++
|
.cpp
| 40
| 25.475
| 120
| 0.711834
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,038
|
startscriptcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/startscriptcreator.cpp
|
#include "startscriptcreator.hpp"
#include <QLabel>
#include <memory>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idcompletionmanager.hpp"
#include "../../model/world/idtable.hpp"
#include "../widget/droplineedit.hpp"
class QUndoStack;
std::string CSVWorld::StartScriptCreator::getId() const
{
return mScript->text().toUtf8().constData();
}
CSMWorld::IdTable& CSVWorld::StartScriptCreator::getStartScriptsTable() const
{
return dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()));
}
CSVWorld::StartScriptCreator::StartScriptCreator(CSMWorld::Data& data, QUndoStack& undoStack,
const CSMWorld::UniversalId& id, CSMWorld::IdCompletionManager& completionManager)
: GenericCreator(data, undoStack, id)
{
setManualEditing(false);
// Add script ID input label.
QLabel* label = new QLabel("Script", this);
insertBeforeButtons(label, false);
// Add script ID input with auto-completion.
// Only existing script IDs are accepted so no ID validation is performed.
CSMWorld::ColumnBase::Display displayType = CSMWorld::ColumnBase::Display_Script;
mScript = new CSVWidget::DropLineEdit(displayType, this);
mScript->setCompleter(completionManager.getCompleter(displayType).get());
insertBeforeButtons(mScript, true);
connect(mScript, &CSVWidget::DropLineEdit::textChanged, this, &StartScriptCreator::scriptChanged);
connect(mScript, &CSVWidget::DropLineEdit::returnPressed, this, &StartScriptCreator::inputReturnPressed);
}
void CSVWorld::StartScriptCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
CSVWorld::GenericCreator::cloneMode(originId, type);
// Look up cloned record in start scripts table and set script ID text.
CSMWorld::IdTable& table = getStartScriptsTable();
int column = table.findColumnIndex(CSMWorld::Columns::ColumnId_Id);
mScript->setText(table.data(table.getModelIndex(originId, column)).toString());
}
std::string CSVWorld::StartScriptCreator::getErrors() const
{
const ESM::RefId scriptId = ESM::RefId::stringRefId(getId());
// Check user input for any errors.
std::string errors;
if (scriptId.empty())
{
errors = "No Script ID entered";
}
else if (getData().getScripts().searchId(scriptId) == -1)
{
errors = "Script ID not found";
}
else if (getData().getStartScripts().searchId(scriptId) > -1)
{
errors = "Script with this ID already registered as Start Script";
}
return errors;
}
void CSVWorld::StartScriptCreator::focus()
{
mScript->setFocus();
}
void CSVWorld::StartScriptCreator::reset()
{
CSVWorld::GenericCreator::reset();
mScript->setText("");
}
void CSVWorld::StartScriptCreator::scriptChanged()
{
update();
}
CSVWorld::Creator* CSVWorld::StartScriptCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new StartScriptCreator(document.getData(), document.getUndoStack(), id, document.getIdCompletionManager());
}
| 3,318
|
C++
|
.cpp
| 83
| 36.493976
| 118
| 0.745098
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,039
|
referenceablecreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/referenceablecreator.cpp
|
#include "referenceablecreator.hpp"
#include <vector>
#include <QComboBox>
#include <QLabel>
#include <apps/opencs/view/world/genericcreator.hpp>
#include <components/misc/scalableicon.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/universalid.hpp"
class QUndoStack;
namespace CSMWorld
{
class Data;
}
void CSVWorld::ReferenceableCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
command.setType(static_cast<CSMWorld::UniversalId::Type>(mType->itemData(mType->currentIndex()).toInt()));
}
CSVWorld::ReferenceableCreator::ReferenceableCreator(
CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id)
: GenericCreator(data, undoStack, id)
{
QLabel* label = new QLabel("Type", this);
insertBeforeButtons(label, false);
std::vector<CSMWorld::UniversalId::Type> types = CSMWorld::UniversalId::listReferenceableTypes();
mType = new QComboBox(this);
mType->setMaxVisibleItems(20);
for (std::vector<CSMWorld::UniversalId::Type>::const_iterator iter(types.begin()); iter != types.end(); ++iter)
{
CSMWorld::UniversalId id2(*iter, "");
mType->addItem(Misc::ScalableIcon::load(id2.getIcon().c_str()), id2.getTypeName().c_str(),
static_cast<int>(id2.getType()));
}
mType->model()->sort(0);
insertBeforeButtons(mType, false);
connect(mType, qOverload<int>(&QComboBox::currentIndexChanged), this, &ReferenceableCreator::setType);
}
void CSVWorld::ReferenceableCreator::reset()
{
mType->setCurrentIndex(0);
GenericCreator::reset();
}
void CSVWorld::ReferenceableCreator::setType(int index)
{
// container items have name limit of 32 characters
std::string text = mType->currentText().toStdString();
if (text == "Potion" || text == "Apparatus" || text == "Armor" || text == "Book" || text == "Clothing"
|| text == "Ingredient" || text == "ItemLevelledList" || text == "Light" || text == "Lockpick"
|| text == "Miscellaneous" || text == "Probe" || text == "Repair" || text == "Weapon")
{
GenericCreator::setEditorMaxLength(32);
}
else
GenericCreator::setEditorMaxLength(32767);
}
void CSVWorld::ReferenceableCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
GenericCreator::cloneMode(originId, type);
mType->setCurrentIndex(mType->findData(static_cast<int>(type)));
}
void CSVWorld::ReferenceableCreator::toggleWidgets(bool active)
{
CSVWorld::GenericCreator::toggleWidgets(active);
mType->setEnabled(active);
}
| 2,597
|
C++
|
.cpp
| 64
| 36.640625
| 115
| 0.711898
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,040
|
scriptsubview.cpp
|
OpenMW_openmw/apps/opencs/view/world/scriptsubview.cpp
|
#include "scriptsubview.hpp"
#include <istream>
#include <vector>
#include <QSplitter>
#include <QTimer>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/commanddispatcher.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/view/doc/subview.hpp>
#include <apps/opencs/view/world/creator.hpp>
#include <apps/opencs/view/world/scripthighlighter.hpp>
#include <components/debug/debuglog.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/universalid.hpp"
#include "genericcreator.hpp"
#include "recordbuttonbar.hpp"
#include "scriptedit.hpp"
#include "scripterrortable.hpp"
#include "tablebottombox.hpp"
void CSVWorld::ScriptSubView::addButtonBar()
{
if (mButtons)
return;
mButtons = new RecordButtonBar(getUniversalId(), *mModel, mBottom, &mCommandDispatcher, this);
mLayout.insertWidget(1, mButtons);
connect(mButtons, &RecordButtonBar::switchToRow, this, &ScriptSubView::switchToRow);
connect(this, &ScriptSubView::universalIdChanged, mButtons, &RecordButtonBar::universalIdChanged);
}
void CSVWorld::ScriptSubView::recompile()
{
if (!mCompileDelay->isActive() && !isDeleted())
mCompileDelay->start(CSMPrefs::get()["Scripts"]["compile-delay"].toInt());
}
bool CSVWorld::ScriptSubView::isDeleted() const
{
return mModel->data(mModel->getModelIndex(getUniversalId().getId(), mStateColumn)).toInt()
== CSMWorld::RecordBase::State_Deleted;
}
void CSVWorld::ScriptSubView::updateDeletedState()
{
if (isDeleted())
{
mErrors->clear();
adjustSplitter();
mEditor->setEnabled(false);
}
else
{
mEditor->setEnabled(true);
recompile();
}
}
void CSVWorld::ScriptSubView::adjustSplitter()
{
QList<int> sizes;
if (mErrors->rowCount())
{
if (mErrors->height())
return; // keep old height if the error panel was already open
sizes << (mMain->height() - mErrorHeight - mMain->handleWidth()) << mErrorHeight;
}
else
{
if (mErrors->height())
mErrorHeight = mErrors->height();
sizes << 1 << 0;
}
mMain->setSizes(sizes);
}
CSVWorld::ScriptSubView::ScriptSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
: SubView(id)
, mDocument(document)
, mColumn(-1)
, mBottom(nullptr)
, mButtons(nullptr)
, mCommandDispatcher(document, CSMWorld::UniversalId::getParentType(id.getType()))
, mErrorHeight(CSMPrefs::get()["Scripts"]["error-height"].toInt())
{
std::vector<std::string> selection(1, id.getId());
mCommandDispatcher.setSelection(selection);
mMain = new QSplitter(this);
mMain->setOrientation(Qt::Vertical);
mLayout.addWidget(mMain, 2);
mEditor = new ScriptEdit(mDocument, ScriptHighlighter::Mode_General, this);
mMain->addWidget(mEditor);
mMain->setCollapsible(0, false);
mErrors = new ScriptErrorTable(document, this);
mMain->addWidget(mErrors);
QList<int> sizes;
sizes << 1 << 0;
mMain->setSizes(sizes);
QWidget* widget = new QWidget(this);
widget->setLayout(&mLayout);
setWidget(widget);
mModel = &dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Scripts));
mColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_ScriptText);
mIdColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
mStateColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Modification);
QString source = mModel->data(mModel->getModelIndex(id.getId(), mColumn)).toString();
mEditor->setPlainText(source);
// bottom box and buttons
mBottom = new TableBottomBox(CreatorFactory<GenericCreator>(), document, id, this);
connect(mBottom, &TableBottomBox::requestFocus, this, &ScriptSubView::switchToId);
mLayout.addWidget(mBottom);
// signals
connect(mEditor, &ScriptEdit::textChanged, this, &ScriptSubView::textChanged);
connect(mModel, &CSMWorld::IdTable::dataChanged, this, &ScriptSubView::dataChanged);
connect(mModel, &CSMWorld::IdTable::rowsAboutToBeRemoved, this, &ScriptSubView::rowsAboutToBeRemoved);
updateStatusBar();
connect(mEditor, &ScriptEdit::cursorPositionChanged, this, &ScriptSubView::updateStatusBar);
mErrors->update(source.toUtf8().constData());
connect(mErrors, &ScriptErrorTable::highlightError, this, &ScriptSubView::highlightError);
mCompileDelay = new QTimer(this);
mCompileDelay->setSingleShot(true);
connect(mCompileDelay, &QTimer::timeout, this, &ScriptSubView::updateRequest);
updateDeletedState();
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &ScriptSubView::settingChanged);
CSMPrefs::get()["Scripts"].update();
}
void CSVWorld::ScriptSubView::setStatusBar(bool show)
{
mBottom->setStatusBar(show);
}
void CSVWorld::ScriptSubView::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "Scripts/toolbar")
{
if (setting->isTrue())
{
addButtonBar();
}
else if (mButtons)
{
mLayout.removeWidget(mButtons);
delete mButtons;
mButtons = nullptr;
}
}
else if (*setting == "Scripts/compile-delay")
{
mCompileDelay->setInterval(setting->toInt());
}
else if (*setting == "Scripts/warnings")
recompile();
}
void CSVWorld::ScriptSubView::updateStatusBar()
{
mBottom->positionChanged(mEditor->textCursor().blockNumber() + 1, mEditor->textCursor().columnNumber() + 1);
}
void CSVWorld::ScriptSubView::setEditLock(bool locked)
{
mEditor->setReadOnly(locked);
if (mButtons)
mButtons->setEditLock(locked);
mCommandDispatcher.setEditLock(locked);
}
void CSVWorld::ScriptSubView::useHint(const std::string& hint)
{
if (hint.empty())
return;
int line = 0, column = 0;
char c;
std::istringstream stream(hint.c_str() + 1);
switch (hint[0])
{
case 'R':
case 'r':
{
QModelIndex index = mModel->getModelIndex(getUniversalId().getId(), mColumn);
QString source = mModel->data(index).toString();
int stringSize = static_cast<int>(source.length());
int pos, dummy;
if (!(stream >> c >> dummy >> pos))
return;
if (pos > stringSize)
{
Log(Debug::Warning)
<< "CSVWorld::ScriptSubView: requested position is higher than actual string length";
pos = stringSize;
}
for (int i = 0; i <= pos; ++i)
{
if (source[i] == '\n')
{
++line;
column = i + 1;
}
}
column = pos - column;
break;
}
case 'l':
if (!(stream >> c >> line >> column))
return;
}
QTextCursor cursor = mEditor->textCursor();
cursor.movePosition(QTextCursor::Start);
if (cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line))
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column);
mEditor->setFocus();
mEditor->setTextCursor(cursor);
}
void CSVWorld::ScriptSubView::textChanged()
{
if (mEditor->isChangeLocked())
return;
ScriptEdit::ChangeLock lock(*mEditor);
QString source = mEditor->toPlainText();
mDocument.getUndoStack().push(
new CSMWorld::ModifyCommand(*mModel, mModel->getModelIndex(getUniversalId().getId(), mColumn), source));
recompile();
}
void CSVWorld::ScriptSubView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
if (mEditor->isChangeLocked())
return;
ScriptEdit::ChangeLock lock(*mEditor);
bool updateRequired = false;
for (int i = topLeft.row(); i <= bottomRight.row(); ++i)
{
std::string id = mModel->data(mModel->index(i, mIdColumn)).toString().toUtf8().constData();
if (mErrors->clearLocals(id))
updateRequired = true;
}
QModelIndex index = mModel->getModelIndex(getUniversalId().getId(), mColumn);
if (index.row() >= topLeft.row() && index.row() <= bottomRight.row())
{
if (mStateColumn >= topLeft.column() && mStateColumn <= bottomRight.column())
updateDeletedState();
if (mColumn >= topLeft.column() && mColumn <= bottomRight.column())
{
QString source = mModel->data(index).toString();
QTextCursor cursor = mEditor->textCursor();
mEditor->setPlainText(source);
mEditor->setTextCursor(cursor);
updateRequired = true;
}
}
if (updateRequired)
recompile();
}
void CSVWorld::ScriptSubView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
bool updateRequired = false;
for (int i = start; i <= end; ++i)
{
std::string id = mModel->data(mModel->index(i, mIdColumn)).toString().toUtf8().constData();
if (mErrors->clearLocals(id))
updateRequired = true;
}
if (updateRequired)
recompile();
QModelIndex index = mModel->getModelIndex(getUniversalId().getId(), mColumn);
if (!parent.isValid() && index.row() >= start && index.row() <= end)
emit closeRequest();
}
void CSVWorld::ScriptSubView::switchToRow(int row)
{
int idColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
std::string id = mModel->data(mModel->index(row, idColumn)).toString().toUtf8().constData();
setUniversalId(CSMWorld::UniversalId(CSMWorld::UniversalId::Type_Script, id));
bool oldSignalsState = mEditor->blockSignals(true);
mEditor->setPlainText(mModel->data(mModel->index(row, mColumn)).toString());
mEditor->blockSignals(oldSignalsState);
std::vector<std::string> selection(1, id);
mCommandDispatcher.setSelection(selection);
updateDeletedState();
}
void CSVWorld::ScriptSubView::switchToId(const std::string& id)
{
switchToRow(mModel->getModelIndex(id, 0).row());
}
void CSVWorld::ScriptSubView::highlightError(int line, int column)
{
QTextCursor cursor = mEditor->textCursor();
cursor.movePosition(QTextCursor::Start);
if (cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line))
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column);
mEditor->setFocus();
mEditor->setTextCursor(cursor);
}
void CSVWorld::ScriptSubView::updateRequest()
{
QModelIndex index = mModel->getModelIndex(getUniversalId().getId(), mColumn);
QString source = mModel->data(index).toString();
mErrors->update(source.toUtf8().constData());
adjustSplitter();
}
| 11,086
|
C++
|
.cpp
| 294
| 31.697279
| 119
| 0.672457
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,041
|
landcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/landcreator.cpp
|
#include "landcreator.hpp"
#include <limits>
#include <QLabel>
#include <QSpinBox>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/land.hpp"
namespace CSVWorld
{
LandCreator::LandCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id)
: GenericCreator(data, undoStack, id)
, mXLabel(nullptr)
, mYLabel(nullptr)
, mX(nullptr)
, mY(nullptr)
{
const int MaxInt = std::numeric_limits<int>::max();
const int MinInt = std::numeric_limits<int>::min();
setManualEditing(false);
mXLabel = new QLabel("X: ");
mX = new QSpinBox();
mX->setMinimum(MinInt);
mX->setMaximum(MaxInt);
insertBeforeButtons(mXLabel, false);
insertBeforeButtons(mX, true);
mYLabel = new QLabel("Y: ");
mY = new QSpinBox();
mY->setMinimum(MinInt);
mY->setMaximum(MaxInt);
insertBeforeButtons(mYLabel, false);
insertBeforeButtons(mY, true);
connect(mX, qOverload<int>(&QSpinBox::valueChanged), this, &LandCreator::coordChanged);
connect(mY, qOverload<int>(&QSpinBox::valueChanged), this, &LandCreator::coordChanged);
}
void LandCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
GenericCreator::cloneMode(originId, type);
int x = 0, y = 0;
CSMWorld::Land::parseUniqueRecordId(originId, x, y);
mX->setValue(x);
mY->setValue(y);
}
void LandCreator::touch(const std::vector<CSMWorld::UniversalId>& ids)
{
// Combine multiple touch commands into one "macro" command
getUndoStack().beginMacro("Touch records");
CSMWorld::IdTable& lands
= dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(CSMWorld::UniversalId::Type_Lands));
CSMWorld::IdTable& ltexs
= dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
for (const CSMWorld::UniversalId& uid : ids)
{
CSMWorld::TouchLandCommand* touchCmd = new CSMWorld::TouchLandCommand(lands, ltexs, uid.getId());
getUndoStack().push(touchCmd);
}
// Execute
getUndoStack().endMacro();
}
void LandCreator::focus()
{
mX->setFocus();
}
void LandCreator::reset()
{
GenericCreator::reset();
mX->setValue(0);
mY->setValue(0);
}
std::string LandCreator::getErrors() const
{
if (getData().getLand().searchId(ESM::RefId::stringRefId(getId())) >= 0)
return "A land with that name already exists.";
return "";
}
std::string LandCreator::getId() const
{
return CSMWorld::Land::createUniqueRecordId(mX->value(), mY->value());
}
void LandCreator::pushCommand(std::unique_ptr<CSMWorld::CreateCommand> command, const std::string& id)
{
if (mCloneMode)
{
CSMWorld::IdTable& lands
= dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(CSMWorld::UniversalId::Type_Lands));
CSMWorld::IdTable& ltexs
= dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
getUndoStack().beginMacro(("Clone " + id).c_str());
getUndoStack().push(command.release());
CSMWorld::CopyLandTexturesCommand* ltexCopy
= new CSMWorld::CopyLandTexturesCommand(lands, ltexs, getClonedId(), getId());
getUndoStack().push(ltexCopy);
getUndoStack().endMacro();
}
else
getUndoStack().push(command.release());
}
void LandCreator::coordChanged(int value)
{
update();
}
}
| 4,020
|
C++
|
.cpp
| 104
| 30.721154
| 119
| 0.630172
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,042
|
infocreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/infocreator.cpp
|
#include "infocreator.hpp"
#include <algorithm>
#include <charconv>
#include <memory>
#include <QLabel>
#include <QRandomGenerator>
#include <QString>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include <components/misc/strings/lower.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idcompletionmanager.hpp"
#include "../../model/world/idtable.hpp"
#include "../widget/droplineedit.hpp"
class QUndoStack;
std::string CSVWorld::InfoCreator::getId() const
{
std::string id = mTopic->text().toStdString();
size_t length = id.size();
// We want generated ids to be at most 31 + \0 characters
id.resize(length + 32);
id[length] = '#';
// Combine a random 32bit number with a random 64bit number for a max 30 character string
quint32 gen32 = QRandomGenerator::global()->generate();
char* start = id.data() + length + 1;
char* end = start + 10; // 2^32 is a 10 digit number
auto result = std::to_chars(start, end, gen32);
quint64 gen64 = QRandomGenerator::global()->generate64();
if (gen64)
{
// 0-pad the first number so 10 + 11 isn't the same as 101 + 1
std::fill(result.ptr, end, '0');
start = end;
end = start + 20; // 2^64 is a 20 digit number
result = std::to_chars(start, end, gen64);
}
id.resize(result.ptr - id.data());
return id;
}
void CSVWorld::InfoCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
CSMWorld::IdTable& table = dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()));
CSMWorld::CloneCommand* cloneCommand = dynamic_cast<CSMWorld::CloneCommand*>(&command);
if (getCollectionId() == CSMWorld::UniversalId::Type_TopicInfos)
{
if (!cloneCommand)
{
command.addValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Topic), mTopic->text());
command.addValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Rank), -1);
command.addValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Gender), -1);
command.addValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_PcRank), -1);
}
else
{
cloneCommand->setOverrideValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Topic), mTopic->text());
}
}
else
{
if (!cloneCommand)
{
command.addValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Journal), mTopic->text());
}
else
cloneCommand->setOverrideValue(table.findColumnIndex(CSMWorld::Columns::ColumnId_Journal), mTopic->text());
}
}
CSVWorld::InfoCreator::InfoCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id,
CSMWorld::IdCompletionManager& completionManager)
: GenericCreator(data, undoStack, id)
{
// Determine if we're dealing with topics or journals.
CSMWorld::ColumnBase::Display displayType = CSMWorld::ColumnBase::Display_Topic;
QString labelText = "Topic";
if (getCollectionId().getType() == CSMWorld::UniversalId::Type_JournalInfos)
{
displayType = CSMWorld::ColumnBase::Display_Journal;
labelText = "Journal";
}
QLabel* label = new QLabel(labelText, this);
insertBeforeButtons(label, false);
// Add topic/journal ID input with auto-completion.
// Only existing topic/journal IDs are accepted so no ID validation is performed.
mTopic = new CSVWidget::DropLineEdit(displayType, this);
mTopic->setCompleter(completionManager.getCompleter(displayType).get());
insertBeforeButtons(mTopic, true);
setManualEditing(false);
connect(mTopic, &CSVWidget::DropLineEdit::textChanged, this, &InfoCreator::topicChanged);
connect(mTopic, &CSVWidget::DropLineEdit::returnPressed, this, &InfoCreator::inputReturnPressed);
}
void CSVWorld::InfoCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
CSMWorld::IdTable& infoTable = dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()));
int topicColumn = infoTable.findColumnIndex(getCollectionId().getType() == CSMWorld::UniversalId::Type_TopicInfos
? CSMWorld::Columns::ColumnId_Topic
: CSMWorld::Columns::ColumnId_Journal);
mTopic->setText(infoTable.data(infoTable.getModelIndex(originId, topicColumn)).toString());
GenericCreator::cloneMode(originId, type);
}
void CSVWorld::InfoCreator::reset()
{
mTopic->setText("");
GenericCreator::reset();
}
void CSVWorld::InfoCreator::setText(const std::string& text)
{
QString qText = QString::fromStdString(text);
mTopic->setText(qText);
}
std::string CSVWorld::InfoCreator::getErrors() const
{
// We ignore errors from GenericCreator here, because they can never happen in an InfoCreator.
std::string errors;
const ESM::RefId topic = ESM::RefId::stringRefId(mTopic->text().toStdString());
if ((getCollectionId().getType() == CSMWorld::UniversalId::Type_TopicInfos ? getData().getTopics()
: getData().getJournals())
.searchId(topic)
== -1)
{
errors += "Invalid Topic ID";
}
return errors;
}
void CSVWorld::InfoCreator::focus()
{
mTopic->setFocus();
}
void CSVWorld::InfoCreator::callReturnPressed()
{
emit inputReturnPressed();
}
void CSVWorld::InfoCreator::topicChanged()
{
update();
}
CSVWorld::Creator* CSVWorld::InfoCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new InfoCreator(document.getData(), document.getUndoStack(), id, document.getIdCompletionManager());
}
| 5,963
|
C++
|
.cpp
| 144
| 36.041667
| 119
| 0.696321
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,043
|
regionmapsubview.cpp
|
OpenMW_openmw/apps/opencs/view/world/regionmapsubview.cpp
|
#include "regionmapsubview.hpp"
#include <apps/opencs/view/doc/subview.hpp>
#include "regionmap.hpp"
CSVWorld::RegionMapSubView::RegionMapSubView(CSMWorld::UniversalId universalId, CSMDoc::Document& document)
: CSVDoc::SubView(universalId)
{
mRegionMap = new RegionMap(universalId, document, this);
setWidget(mRegionMap);
connect(mRegionMap, &RegionMap::editRequest, this, &RegionMapSubView::editRequest);
}
void CSVWorld::RegionMapSubView::setEditLock(bool locked)
{
mRegionMap->setEditLock(locked);
}
void CSVWorld::RegionMapSubView::editRequest(const CSMWorld::UniversalId& id, const std::string& hint)
{
focusId(id, hint);
}
| 660
|
C++
|
.cpp
| 18
| 33.944444
| 107
| 0.785827
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,044
|
tablesubview.cpp
|
OpenMW_openmw/apps/opencs/view/world/tablesubview.cpp
|
#include "tablesubview.hpp"
#include <QApplication>
#include <QCheckBox>
#include <QDropEvent>
#include <QEvent>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QPushButton>
#include <QScreen>
#include <QVBoxLayout>
#include <QVariant>
#include <algorithm>
#include <utility>
#include <variant>
#include <apps/opencs/view/doc/subview.hpp>
#include <components/misc/scalableicon.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../doc/sizehint.hpp"
#include "../doc/view.hpp"
#include "../filter/filterbox.hpp"
#include "../filter/filterdata.hpp"
#include "table.hpp"
#include "tablebottombox.hpp"
CSVWorld::TableSubView::TableSubView(
const CSMWorld::UniversalId& id, CSMDoc::Document& document, const CreatorFactoryBase& creatorFactory, bool sorting)
: SubView(id)
, mShowOptions(false)
, mOptions(0)
{
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(mBottom = new TableBottomBox(creatorFactory, document, id, this), 0);
layout->insertWidget(0, mTable = new Table(id, mBottom->canCreateAndDelete(), sorting, document), 2);
mFilterBox = new CSVFilter::FilterBox(document.getData(), this);
QHBoxLayout* hLayout = new QHBoxLayout;
hLayout->insertWidget(0, mFilterBox);
mOptions = new QWidget;
QHBoxLayout* optHLayout = new QHBoxLayout;
QCheckBox* autoJump = new QCheckBox("Auto Jump");
autoJump->setToolTip(
"Whether to jump to the modified record."
"\nCan be useful in finding the moved or modified"
"\nobject instance while 3D editing.");
autoJump->setCheckState(Qt::Unchecked);
connect(autoJump, &QCheckBox::stateChanged, mTable, &Table::jumpAfterModChanged);
optHLayout->insertWidget(0, autoJump);
optHLayout->setContentsMargins(QMargins(0, 3, 0, 0));
mOptions->setLayout(optHLayout);
mOptions->resize(mOptions->width(), mFilterBox->height());
mOptions->hide();
QPushButton* opt = new QPushButton();
opt->setIcon(Misc::ScalableIcon::load(":startup/configure"));
opt->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
opt->setToolTip("Open additional options for this subview.");
connect(opt, &QPushButton::clicked, this, &TableSubView::toggleOptions);
QVBoxLayout* buttonLayout = new QVBoxLayout; // work around margin issues
buttonLayout->setContentsMargins(QMargins(0 /*left*/, 3 /*top*/, 3 /*right*/, 0 /*bottom*/));
buttonLayout->insertWidget(0, opt, 0, Qt::AlignVCenter | Qt::AlignRight);
hLayout->insertWidget(1, mOptions);
hLayout->insertLayout(2, buttonLayout);
layout->insertLayout(0, hLayout);
CSVDoc::SizeHintWidget* widget = new CSVDoc::SizeHintWidget;
widget->setLayout(layout);
setWidget(widget);
QScreen* screen = CSVDoc::View::getWidgetScreen(pos());
// prefer height of the screen and full width of the table
const QRect rect = screen->geometry();
int frameHeight = 40; // set a reasonable default
QWidget* topLevel = QApplication::topLevelAt(pos());
if (topLevel)
frameHeight = topLevel->frameGeometry().height() - topLevel->height();
widget->setSizeHint(QSize(mTable->horizontalHeader()->length(), rect.height() - frameHeight));
connect(mTable, &Table::editRequest, this, &TableSubView::editRequest);
connect(mTable, &Table::selectionSizeChanged, mBottom, &TableBottomBox::selectionSizeChanged);
connect(mTable, &Table::tableSizeChanged, mBottom, &TableBottomBox::tableSizeChanged);
mTable->tableSizeUpdate();
mTable->selectionSizeUpdate();
mTable->viewport()->installEventFilter(this);
mBottom->installEventFilter(this);
mFilterBox->installEventFilter(this);
if (mBottom->canCreateAndDelete())
{
connect(mTable, &Table::createRequest, mBottom, &TableBottomBox::createRequest);
connect(
mTable, &Table::cloneRequest, this, qOverload<const CSMWorld::UniversalId&>(&TableSubView::cloneRequest));
connect(this, qOverload<const std::string&, const CSMWorld::UniversalId::Type>(&TableSubView::cloneRequest),
mBottom, &TableBottomBox::cloneRequest);
connect(mTable, &Table::createRecordsDirectlyRequest, mBottom, &TableBottomBox::createRecordsDirectlyRequest);
connect(mTable, &Table::touchRequest, mBottom, &TableBottomBox::touchRequest);
connect(mTable, &Table::extendedDeleteConfigRequest, mBottom, &TableBottomBox::extendedDeleteConfigRequest);
connect(mTable, &Table::extendedRevertConfigRequest, mBottom, &TableBottomBox::extendedRevertConfigRequest);
}
connect(mBottom, &TableBottomBox::requestFocus, mTable, &Table::requestFocus);
connect(mFilterBox, &CSVFilter::FilterBox::recordFilterChanged, mTable, &Table::recordFilterChanged);
connect(mFilterBox, &CSVFilter::FilterBox::recordDropped, this, &TableSubView::createFilterRequest);
connect(mTable, &Table::closeRequest, this, qOverload<>(&TableSubView::closeRequest));
}
void CSVWorld::TableSubView::setEditLock(bool locked)
{
mTable->setEditLock(locked);
mBottom->setEditLock(locked);
}
void CSVWorld::TableSubView::editRequest(const CSMWorld::UniversalId& id, const std::string& hint)
{
focusId(id, hint);
}
void CSVWorld::TableSubView::setStatusBar(bool show)
{
mBottom->setStatusBar(show);
}
void CSVWorld::TableSubView::useHint(const std::string& hint)
{
if (hint.empty())
return;
if (hint[0] == 'f' && hint.size() >= 2)
mFilterBox->setRecordFilter(hint.substr(2));
}
void CSVWorld::TableSubView::cloneRequest(const CSMWorld::UniversalId& toClone)
{
emit cloneRequest(toClone.getId(), toClone.getType());
}
void CSVWorld::TableSubView::createFilterRequest(std::vector<CSMWorld::UniversalId>& types,
const std::pair<QVariant, std::string>& columnSearchData, Qt::DropAction action)
{
std::vector<CSVFilter::FilterData> sourceFilter;
std::vector<std::string> refIdColumns = mTable->getColumnsWithDisplay(
CSMWorld::TableMimeData::convertEnums(CSMWorld::UniversalId::Type_Referenceable));
bool hasRefIdDisplay = !refIdColumns.empty();
for (std::vector<CSMWorld::UniversalId>::iterator it(types.begin()); it != types.end(); ++it)
{
CSMWorld::UniversalId::Type type = it->getType();
std::vector<std::string> col = mTable->getColumnsWithDisplay(CSMWorld::TableMimeData::convertEnums(type));
if (!col.empty())
{
CSVFilter::FilterData filterData;
filterData.searchData = it->getId();
filterData.columns = std::move(col);
sourceFilter.emplace_back(filterData);
}
if (hasRefIdDisplay && CSMWorld::TableMimeData::isReferencable(type))
{
CSVFilter::FilterData filterData;
filterData.searchData = it->getId();
filterData.columns = refIdColumns;
sourceFilter.emplace_back(filterData);
}
}
if (!sourceFilter.empty())
mFilterBox->createFilterRequest(sourceFilter, action);
else
{
std::vector<CSVFilter::FilterData> sourceFilterByValue;
QVariant qData = columnSearchData.first;
std::string searchColumn = columnSearchData.second;
std::vector<std::string> searchColumns;
searchColumns.emplace_back(searchColumn);
CSVFilter::FilterData filterData;
filterData.searchData = qData;
filterData.columns = std::move(searchColumns);
sourceFilterByValue.emplace_back(filterData);
mFilterBox->createFilterRequest(sourceFilterByValue, action);
}
}
bool CSVWorld::TableSubView::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::Drop)
{
if (QDropEvent* drop = dynamic_cast<QDropEvent*>(event))
{
const CSMWorld::TableMimeData* tableMimeData
= dynamic_cast<const CSMWorld::TableMimeData*>(drop->mimeData());
if (!tableMimeData) // May happen when non-records (e.g. plain text) are dragged and dropped
return false;
bool handled = tableMimeData->holdsType(CSMWorld::UniversalId::Type_Filter);
if (handled)
{
mFilterBox->setRecordFilter(tableMimeData->returnMatching(CSMWorld::UniversalId::Type_Filter).getId());
}
return handled;
}
}
return false;
}
void CSVWorld::TableSubView::toggleOptions()
{
if (mShowOptions)
{
mShowOptions = false;
mOptions->hide();
}
else
{
mShowOptions = true;
mOptions->show();
}
}
void CSVWorld::TableSubView::requestFocus(const std::string& id)
{
mTable->requestFocus(id);
}
| 8,730
|
C++
|
.cpp
| 200
| 37.815
| 120
| 0.707866
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,045
|
scripthighlighter.cpp
|
OpenMW_openmw/apps/opencs/view/world/scripthighlighter.cpp
|
#include "scripthighlighter.hpp"
#include <sstream>
#include <utility>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/scriptcontext.hpp>
#include <components/compiler/extensions0.hpp>
#include <components/compiler/scanner.hpp>
#include <components/compiler/tokenloc.hpp>
#include <components/esm/refid.hpp>
class QTextDocument;
namespace CSMWorld
{
class Data;
}
bool CSVWorld::ScriptHighlighter::parseInt(int value, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
highlight(loc, Type_Int);
return true;
}
bool CSVWorld::ScriptHighlighter::parseFloat(float value, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
highlight(loc, Type_Float);
return true;
}
bool CSVWorld::ScriptHighlighter::parseName(
const std::string& name, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
highlight(loc, mContext.isId(ESM::RefId::stringRefId(name)) ? Type_Id : Type_Name);
return true;
}
bool CSVWorld::ScriptHighlighter::parseKeyword(int keyword, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
if (((mMode == Mode_Console || mMode == Mode_Dialogue)
&& (keyword == Compiler::Scanner::K_begin || keyword == Compiler::Scanner::K_end
|| keyword == Compiler::Scanner::K_short || keyword == Compiler::Scanner::K_long
|| keyword == Compiler::Scanner::K_float))
|| (mMode == Mode_Console
&& (keyword == Compiler::Scanner::K_if || keyword == Compiler::Scanner::K_endif
|| keyword == Compiler::Scanner::K_else || keyword == Compiler::Scanner::K_elseif
|| keyword == Compiler::Scanner::K_while || keyword == Compiler::Scanner::K_endwhile)))
return parseName(loc.mLiteral, loc, scanner);
highlight(loc, Type_Keyword);
return true;
}
bool CSVWorld::ScriptHighlighter::parseSpecial(int code, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
highlight(loc, Type_Special);
return true;
}
bool CSVWorld::ScriptHighlighter::parseComment(
const std::string& comment, const Compiler::TokenLoc& loc, Compiler::Scanner& scanner)
{
highlight(loc, Type_Comment);
return true;
}
void CSVWorld::ScriptHighlighter::parseEOF(Compiler::Scanner& scanner) {}
void CSVWorld::ScriptHighlighter::highlight(const Compiler::TokenLoc& loc, Type type)
{
// We should take in account multibyte characters
int length = 0;
const char* token = loc.mLiteral.c_str();
while (*token)
length += (*token++ & 0xc0) != 0x80;
int index = loc.mColumn;
// compensate for bug in Compiler::Scanner (position of token is the character after the token)
index -= length;
QTextCharFormat scheme = mScheme[type];
if (mMarkOccurrences && type == Type_Name && loc.mLiteral == mMarkedWord)
scheme.merge(mScheme[Type_Highlight]);
setFormat(index, length, scheme);
}
CSVWorld::ScriptHighlighter::ScriptHighlighter(const CSMWorld::Data& data, Mode mode, QTextDocument* parent)
: QSyntaxHighlighter(parent)
, Compiler::Parser(mErrorHandler, mContext)
, mContext(data)
, mMode(mode)
, mMarkOccurrences(false)
{
QColor color("black");
QTextCharFormat format;
format.setForeground(color);
for (int i = 0; i <= Type_Id; ++i)
mScheme.insert(std::make_pair(static_cast<Type>(i), format));
// configure compiler
Compiler::registerExtensions(mExtensions);
mContext.setExtensions(&mExtensions);
}
void CSVWorld::ScriptHighlighter::highlightBlock(const QString& text)
{
std::istringstream stream(text.toUtf8().constData());
Compiler::Scanner scanner(mErrorHandler, stream, mContext.getExtensions());
try
{
scanner.scan(*this);
}
catch (...)
{
} // ignore syntax errors
}
void CSVWorld::ScriptHighlighter::setMarkOccurrences(bool flag)
{
mMarkOccurrences = flag;
}
void CSVWorld::ScriptHighlighter::setMarkedWord(const std::string& name)
{
mMarkedWord = name;
}
void CSVWorld::ScriptHighlighter::invalidateIds()
{
mContext.invalidateIds();
}
bool CSVWorld::ScriptHighlighter::settingChanged(const CSMPrefs::Setting* setting)
{
if (setting->getParent()->getKey() == "Scripts")
{
static const char* const colours[Type_Id + 2] = { "colour-int", "colour-float", "colour-name", "colour-keyword",
"colour-special", "colour-comment", "colour-highlight", "colour-id", 0 };
for (int i = 0; colours[i]; ++i)
if (setting->getKey() == colours[i])
{
QTextCharFormat format;
if (i == Type_Highlight)
format.setBackground(setting->toColor());
else
format.setForeground(setting->toColor());
mScheme[static_cast<Type>(i)] = format;
return true;
}
}
return false;
}
| 4,964
|
C++
|
.cpp
| 132
| 32.356061
| 120
| 0.683948
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,046
|
subviews.cpp
|
OpenMW_openmw/apps/opencs/view/world/subviews.cpp
|
#include "subviews.hpp"
#include "../doc/subviewfactoryimp.hpp"
#include "bodypartcreator.hpp"
#include "cellcreator.hpp"
#include "dialoguecreator.hpp"
#include "dialoguesubview.hpp"
#include "genericcreator.hpp"
#include "globalcreator.hpp"
#include "infocreator.hpp"
#include "landcreator.hpp"
#include "pathgridcreator.hpp"
#include "previewsubview.hpp"
#include "referenceablecreator.hpp"
#include "referencecreator.hpp"
#include "regionmapsubview.hpp"
#include "scenesubview.hpp"
#include "scriptsubview.hpp"
#include "startscriptcreator.hpp"
#include "tablesubview.hpp"
#include <apps/opencs/model/world/scope.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/doc/subview.hpp>
#include <apps/opencs/view/doc/subviewfactory.hpp>
#include <apps/opencs/view/world/creator.hpp>
void CSVWorld::addSubViewFactories(CSVDoc::SubViewFactoryManager& manager)
{
// Regular record tables (including references which are actually sub-records, but are promoted
// to top-level records within the editor)
manager.add(
CSMWorld::UniversalId::Type_Gmsts, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Skills, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(CSMWorld::UniversalId::Type_MagicEffects,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
static const CSMWorld::UniversalId::Type sTableTypes[] = {
CSMWorld::UniversalId::Type_Classes,
CSMWorld::UniversalId::Type_Factions,
CSMWorld::UniversalId::Type_Races,
CSMWorld::UniversalId::Type_Sounds,
CSMWorld::UniversalId::Type_Regions,
CSMWorld::UniversalId::Type_Birthsigns,
CSMWorld::UniversalId::Type_Spells,
CSMWorld::UniversalId::Type_Enchantments,
CSMWorld::UniversalId::Type_SoundGens,
// end marker
CSMWorld::UniversalId::Type_None,
};
for (int i = 0; sTableTypes[i] != CSMWorld::UniversalId::Type_None; ++i)
manager.add(
sTableTypes[i], new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<GenericCreator>>);
manager.add(CSMWorld::UniversalId::Type_BodyParts,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<BodyPartCreator>>);
manager.add(CSMWorld::UniversalId::Type_StartScripts,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, StartScriptCreatorFactory>);
manager.add(CSMWorld::UniversalId::Type_Cells,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<CellCreator>>);
manager.add(CSMWorld::UniversalId::Type_Referenceables,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<ReferenceableCreator>>);
manager.add(CSMWorld::UniversalId::Type_References,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, ReferenceCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Topics, new CSVDoc::SubViewFactoryWithCreator<TableSubView, TopicCreatorFactory>);
manager.add(CSMWorld::UniversalId::Type_Journals,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, JournalCreatorFactory>);
manager.add(CSMWorld::UniversalId::Type_TopicInfos,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, InfoCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_JournalInfos,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, InfoCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Pathgrids,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, PathgridCreatorFactory>);
manager.add(CSMWorld::UniversalId::Type_Lands,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<LandCreator>>);
manager.add(CSMWorld::UniversalId::Type_LandTextures,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<GenericCreator>>);
manager.add(CSMWorld::UniversalId::Type_Globals,
new CSVDoc::SubViewFactoryWithCreator<TableSubView, CreatorFactory<GlobalCreator>>);
// Subviews for resources tables
manager.add(
CSMWorld::UniversalId::Type_Meshes, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Icons, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Musics, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_SoundsRes, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Textures, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
manager.add(
CSMWorld::UniversalId::Type_Videos, new CSVDoc::SubViewFactoryWithCreator<TableSubView, NullCreatorFactory>);
// Subviews for editing/viewing individual records
manager.add(CSMWorld::UniversalId::Type_Script, new CSVDoc::SubViewFactory<ScriptSubView>);
// Other stuff (combined record tables)
manager.add(CSMWorld::UniversalId::Type_RegionMap, new CSVDoc::SubViewFactory<RegionMapSubView>);
manager.add(CSMWorld::UniversalId::Type_Scene, new CSVDoc::SubViewFactory<SceneSubView>);
// More other stuff
manager.add(CSMWorld::UniversalId::Type_Filters,
new CSVDoc::SubViewFactoryWithCreator<TableSubView,
CreatorFactory<GenericCreator, CSMWorld::Scope_Project | CSMWorld::Scope_Session>>);
manager.add(CSMWorld::UniversalId::Type_DebugProfiles,
new CSVDoc::SubViewFactoryWithCreator<TableSubView,
CreatorFactory<GenericCreator, CSMWorld::Scope_Project | CSMWorld::Scope_Session>>);
manager.add(CSMWorld::UniversalId::Type_Scripts,
new CSVDoc::SubViewFactoryWithCreator<TableSubView,
CreatorFactory<GenericCreator, CSMWorld::Scope_Project | CSMWorld::Scope_Content>>);
// Dialogue subviews
static const CSMWorld::UniversalId::Type sTableTypes2[] = {
CSMWorld::UniversalId::Type_Region,
CSMWorld::UniversalId::Type_Spell,
CSMWorld::UniversalId::Type_Birthsign,
CSMWorld::UniversalId::Type_Global,
CSMWorld::UniversalId::Type_Race,
CSMWorld::UniversalId::Type_Class,
CSMWorld::UniversalId::Type_Sound,
CSMWorld::UniversalId::Type_Faction,
CSMWorld::UniversalId::Type_Enchantment,
CSMWorld::UniversalId::Type_SoundGen,
// end marker
CSMWorld::UniversalId::Type_None,
};
for (int i = 0; sTableTypes2[i] != CSMWorld::UniversalId::Type_None; ++i)
manager.add(sTableTypes2[i],
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<GenericCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_BodyPart,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<BodyPartCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_StartScript,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, StartScriptCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Skill,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, NullCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_MagicEffect,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, NullCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Gmst,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, NullCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Referenceable,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<ReferenceableCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_Reference,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, ReferenceCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Cell,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<CellCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_JournalInfo,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, InfoCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_TopicInfo,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, InfoCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Topic,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, TopicCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Journal,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, JournalCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Pathgrid,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, PathgridCreatorFactory>(false));
manager.add(CSMWorld::UniversalId::Type_Land,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<LandCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_LandTexture,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView, CreatorFactory<GenericCreator>>(false));
manager.add(CSMWorld::UniversalId::Type_DebugProfile,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView,
CreatorFactory<GenericCreator, CSMWorld::Scope_Project | CSMWorld::Scope_Session>>(false));
manager.add(CSMWorld::UniversalId::Type_Filter,
new CSVDoc::SubViewFactoryWithCreator<DialogueSubView,
CreatorFactory<GenericCreator, CSMWorld::Scope_Project | CSMWorld::Scope_Session>>(false));
manager.add(CSMWorld::UniversalId::Type_MetaData, new CSVDoc::SubViewFactory<SimpleDialogueSubView>);
// preview
manager.add(CSMWorld::UniversalId::Type_Preview, new CSVDoc::SubViewFactory<PreviewSubView>);
}
| 9,811
|
C++
|
.cpp
| 162
| 53.925926
| 120
| 0.765521
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,047
|
previewsubview.cpp
|
OpenMW_openmw/apps/opencs/view/world/previewsubview.cpp
|
#include "previewsubview.hpp"
#include <QHBoxLayout>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/ref.hpp>
#include <apps/opencs/model/world/refcollection.hpp>
#include <apps/opencs/model/world/refidcollection.hpp>
#include <apps/opencs/view/doc/subview.hpp>
#include "../render/previewwidget.hpp"
#include "../widget/scenetoolbar.hpp"
#include "../widget/scenetoolmode.hpp"
#include "../../model/doc/document.hpp"
CSVWorld::PreviewSubView::PreviewSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
: SubView(id)
, mTitle(id.toString().c_str())
{
QHBoxLayout* layout = new QHBoxLayout;
if (document.getData().getReferenceables().searchId(ESM::RefId::stringRefId(id.getId())) == -1)
{
std::string referenceableId = document.getData()
.getReferences()
.getRecord(ESM::RefId::stringRefId(id.getId()))
.get()
.mRefID.getRefIdString();
referenceableIdChanged(referenceableId);
mScene = new CSVRender::PreviewWidget(document.getData(), id.getId(), false, this);
}
else
mScene = new CSVRender::PreviewWidget(document.getData(), id.getId(), true, this);
mScene->setExterior(true);
CSVWidget::SceneToolbar* toolbar = new CSVWidget::SceneToolbar(48 + 6, this);
CSVWidget::SceneToolMode* lightingTool = mScene->makeLightingSelector(toolbar);
toolbar->addTool(lightingTool);
layout->addWidget(toolbar, 0);
layout->addWidget(mScene, 1);
QWidget* widget = new QWidget;
widget->setLayout(layout);
setWidget(widget);
connect(mScene, &CSVRender::PreviewWidget::closeRequest, this, qOverload<>(&PreviewSubView::closeRequest));
connect(mScene, &CSVRender::PreviewWidget::referenceableIdChanged, this, &PreviewSubView::referenceableIdChanged);
connect(mScene, &CSVRender::PreviewWidget::focusToolbarRequest, toolbar,
qOverload<>(&CSVWidget::SceneToolbar::setFocus));
connect(
toolbar, &CSVWidget::SceneToolbar::focusSceneRequest, mScene, qOverload<>(&CSVRender::PreviewWidget::setFocus));
}
void CSVWorld::PreviewSubView::setEditLock(bool locked) {}
std::string CSVWorld::PreviewSubView::getTitle() const
{
return mTitle;
}
void CSVWorld::PreviewSubView::referenceableIdChanged(const std::string& id)
{
if (id.empty())
mTitle = "Preview: Reference to <nothing>";
else
mTitle = "Preview: Reference to " + id;
setWindowTitle(QString::fromUtf8(mTitle.c_str()));
emit updateTitle();
}
| 2,713
|
C++
|
.cpp
| 59
| 38.966102
| 120
| 0.689092
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,048
|
creator.cpp
|
OpenMW_openmw/apps/opencs/view/world/creator.cpp
|
#include "creator.hpp"
#include <apps/opencs/model/world/scope.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <stdexcept>
namespace CSMDoc
{
class Document;
}
void CSVWorld::Creator::setScope(unsigned int scope)
{
if (scope != CSMWorld::Scope_Content)
throw std::logic_error("Invalid scope in creator");
}
CSVWorld::Creator* CSVWorld::NullCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return nullptr;
}
| 502
|
C++
|
.cpp
| 18
| 25.277778
| 70
| 0.759916
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,049
|
cellcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/cellcreator.cpp
|
#include "cellcreator.hpp"
#include <limits>
#include <sstream>
#include <QComboBox>
#include <QLabel>
#include <QSpinBox>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/idtree.hpp"
class QUndoStack;
std::string CSVWorld::CellCreator::getId() const
{
if (mType->currentIndex() == 0)
return GenericCreator::getId();
std::ostringstream stream;
stream << "#" << mX->value() << " " << mY->value();
return stream.str();
}
void CSVWorld::CellCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
CSMWorld::IdTree* model = &dynamic_cast<CSMWorld::IdTree&>(*getData().getTableModel(getCollectionId()));
int parentIndex = model->findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
int index = model->findNestedColumnIndex(parentIndex, CSMWorld::Columns::ColumnId_Interior);
command.addNestedValue(parentIndex, index, mType->currentIndex() == 0);
}
CSVWorld::CellCreator::CellCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id)
: GenericCreator(data, undoStack, id)
{
mY = new QSpinBox(this);
mY->setVisible(false);
mY->setMinimum(std::numeric_limits<int>::min());
mY->setMaximum(std::numeric_limits<int>::max());
connect(mY, qOverload<int>(&QSpinBox::valueChanged), this, &CellCreator::valueChanged);
insertAtBeginning(mY, true);
mYLabel = new QLabel("Y", this);
mYLabel->setVisible(false);
insertAtBeginning(mYLabel, false);
mX = new QSpinBox(this);
mX->setVisible(false);
mX->setMinimum(std::numeric_limits<int>::min());
mX->setMaximum(std::numeric_limits<int>::max());
connect(mX, qOverload<int>(&QSpinBox::valueChanged), this, &CellCreator::valueChanged);
insertAtBeginning(mX, true);
mXLabel = new QLabel("X", this);
mXLabel->setVisible(false);
insertAtBeginning(mXLabel, false);
mType = new QComboBox(this);
mType->addItem("Interior Cell");
mType->addItem("Exterior Cell");
connect(mType, qOverload<int>(&QComboBox::currentIndexChanged), this, &CellCreator::setType);
insertAtBeginning(mType, false);
}
void CSVWorld::CellCreator::reset()
{
mX->setValue(0);
mY->setValue(0);
mType->setCurrentIndex(0);
setType(0);
GenericCreator::reset();
}
void CSVWorld::CellCreator::setType(int index)
{
setManualEditing(index == 0);
mXLabel->setVisible(index == 1);
mX->setVisible(index == 1);
mYLabel->setVisible(index == 1);
mY->setVisible(index == 1);
// The cell name is limited to 64 characters. (ESM::Header::GMDT::mCurrentCell)
std::string text = mType->currentText().toStdString();
if (text == "Interior Cell")
GenericCreator::setEditorMaxLength(64);
else
GenericCreator::setEditorMaxLength(32767);
update();
}
void CSVWorld::CellCreator::valueChanged(int index)
{
update();
}
void CSVWorld::CellCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
CSVWorld::GenericCreator::cloneMode(originId, type);
if (*(originId.begin()) == '#') // if originid points to the exterior cell
{
setType(1); // enable x and y controls
mType->setCurrentIndex(1);
}
else
{
setType(0);
mType->setCurrentIndex(0);
}
}
std::string CSVWorld::CellCreator::getErrors() const
{
std::string errors;
if (mType->currentIndex() == 0)
{
errors = GenericCreator::getErrors();
}
else if (getData().hasId(getId()))
{
errors = "The Exterior Cell is already exist";
}
return errors;
}
| 3,748
|
C++
|
.cpp
| 108
| 30.462963
| 112
| 0.693138
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,050
|
dialoguecreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/dialoguecreator.cpp
|
#include "dialoguecreator.hpp"
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include <components/esm3/loaddial.hpp>
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
class QUndoStack;
void CSVWorld::DialogueCreator::configureCreateCommand(CSMWorld::CreateCommand& command) const
{
int index = dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()))
.findColumnIndex(CSMWorld::Columns::ColumnId_DialogueType);
command.addValue(index, mType);
}
CSVWorld::DialogueCreator::DialogueCreator(
CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id, int type)
: GenericCreator(data, undoStack, id, true)
, mType(type)
{
}
CSVWorld::Creator* CSVWorld::TopicCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new DialogueCreator(document.getData(), document.getUndoStack(), id, ESM::Dialogue::Topic);
}
CSVWorld::Creator* CSVWorld::JournalCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new DialogueCreator(document.getData(), document.getUndoStack(), id, ESM::Dialogue::Journal);
}
| 1,372
|
C++
|
.cpp
| 31
| 41.16129
| 104
| 0.766517
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,051
|
extendedcommandconfigurator.cpp
|
OpenMW_openmw/apps/opencs/view/world/extendedcommandconfigurator.cpp
|
#include "extendedcommandconfigurator.hpp"
#include <algorithm>
#include <type_traits>
#include <utility>
#include <QCheckBox>
#include <QGroupBox>
#include <QLayout>
#include <QPushButton>
#include "../../model/doc/document.hpp"
#include "../../model/world/commanddispatcher.hpp"
#include "../../model/world/data.hpp"
#include <apps/opencs/model/world/universalid.hpp>
CSVWorld::ExtendedCommandConfigurator::ExtendedCommandConfigurator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id, QWidget* parent)
: QWidget(parent)
, mNumUsedCheckBoxes(0)
, mNumChecked(0)
, mMode(Mode_None)
, mData(document.getData())
, mEditLock(false)
{
mCommandDispatcher = new CSMWorld::CommandDispatcher(document, id, this);
connect(&mData, &CSMWorld::Data::idListChanged, this, &ExtendedCommandConfigurator::dataIdListChanged);
mPerformButton = new QPushButton(this);
mPerformButton->setDefault(true);
mPerformButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(mPerformButton, &QPushButton::clicked, this, &ExtendedCommandConfigurator::performExtendedCommand);
mCancelButton = new QPushButton("Cancel", this);
mCancelButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(mCancelButton, &QPushButton::clicked, this, &ExtendedCommandConfigurator::done);
mTypeGroup = new QGroupBox(this);
QGridLayout* groupLayout = new QGridLayout(mTypeGroup);
groupLayout->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
mTypeGroup->setLayout(groupLayout);
QHBoxLayout* mainLayout = new QHBoxLayout(this);
mainLayout->setSizeConstraint(QLayout::SetNoConstraint);
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->addWidget(mTypeGroup);
mainLayout->addWidget(mPerformButton);
mainLayout->addWidget(mCancelButton);
}
void CSVWorld::ExtendedCommandConfigurator::configure(
CSVWorld::ExtendedCommandConfigurator::Mode mode, const std::vector<std::string>& selectedIds)
{
mMode = mode;
if (mMode != Mode_None)
{
mPerformButton->setText((mMode == Mode_Delete) ? "Extended Delete" : "Extended Revert");
mSelectedIds = selectedIds;
mCommandDispatcher->setSelection(mSelectedIds);
setupCheckBoxes(mCommandDispatcher->getExtendedTypes());
setupGroupLayout();
lockWidgets(mEditLock);
}
}
void CSVWorld::ExtendedCommandConfigurator::setEditLock(bool locked)
{
if (mEditLock != locked)
{
mEditLock = locked;
lockWidgets(mEditLock);
}
}
void CSVWorld::ExtendedCommandConfigurator::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
setupGroupLayout();
}
void CSVWorld::ExtendedCommandConfigurator::setupGroupLayout()
{
if (mMode == Mode_None)
{
return;
}
int groupWidth = mTypeGroup->geometry().width();
QGridLayout* layout = qobject_cast<QGridLayout*>(mTypeGroup->layout());
// Find the optimal number of rows to place the checkboxes within the available space
int divider = 1;
do
{
while (layout->itemAt(0) != nullptr)
{
layout->removeItem(layout->itemAt(0));
}
int counter = 0;
int itemsPerRow = mNumUsedCheckBoxes / divider;
CheckBoxMap::const_iterator current = mTypeCheckBoxes.begin();
CheckBoxMap::const_iterator end = mTypeCheckBoxes.end();
for (; current != end; ++current)
{
if (counter < mNumUsedCheckBoxes)
{
int row = counter / itemsPerRow;
int column = counter - (counter / itemsPerRow) * itemsPerRow;
layout->addWidget(current->first, row, column);
}
++counter;
}
divider *= 2;
} while (groupWidth < mTypeGroup->sizeHint().width() && divider <= mNumUsedCheckBoxes);
}
void CSVWorld::ExtendedCommandConfigurator::setupCheckBoxes(const std::vector<CSMWorld::UniversalId>& types)
{
// Make sure that we have enough checkboxes
int numTypes = static_cast<int>(types.size());
int numCheckBoxes = static_cast<int>(mTypeCheckBoxes.size());
if (numTypes > numCheckBoxes)
{
for (int i = numTypes - numCheckBoxes; i > 0; --i)
{
QCheckBox* checkBox = new QCheckBox(mTypeGroup);
connect(checkBox, &QCheckBox::stateChanged, this, &ExtendedCommandConfigurator::checkBoxStateChanged);
mTypeCheckBoxes.insert(std::make_pair(checkBox, CSMWorld::UniversalId::Type_None));
}
}
// Set up the checkboxes
int counter = 0;
CheckBoxMap::iterator current = mTypeCheckBoxes.begin();
CheckBoxMap::iterator end = mTypeCheckBoxes.end();
for (; current != end; ++current)
{
if (counter < numTypes)
{
CSMWorld::UniversalId type = types[counter];
current->first->setText(QString::fromUtf8(type.getTypeName().c_str()));
current->first->setChecked(true);
current->second = std::move(type);
++counter;
}
else
{
current->first->hide();
}
}
mNumChecked = mNumUsedCheckBoxes = numTypes;
}
void CSVWorld::ExtendedCommandConfigurator::lockWidgets(bool locked)
{
mPerformButton->setEnabled(!mEditLock && mNumChecked > 0);
CheckBoxMap::const_iterator current = mTypeCheckBoxes.begin();
CheckBoxMap::const_iterator end = mTypeCheckBoxes.end();
for (int i = 0; current != end && i < mNumUsedCheckBoxes; ++current, ++i)
{
current->first->setEnabled(!mEditLock);
}
}
void CSVWorld::ExtendedCommandConfigurator::performExtendedCommand()
{
std::vector<CSMWorld::UniversalId> types;
CheckBoxMap::const_iterator current = mTypeCheckBoxes.begin();
CheckBoxMap::const_iterator end = mTypeCheckBoxes.end();
for (; current != end; ++current)
{
if (current->first->isChecked())
{
types.push_back(current->second);
}
}
mCommandDispatcher->setExtendedTypes(types);
if (mMode == Mode_Delete)
{
mCommandDispatcher->executeExtendedDelete();
}
else
{
mCommandDispatcher->executeExtendedRevert();
}
emit done();
}
void CSVWorld::ExtendedCommandConfigurator::checkBoxStateChanged(int state)
{
switch (state)
{
case Qt::Unchecked:
--mNumChecked;
break;
case Qt::Checked:
++mNumChecked;
break;
case Qt::PartiallyChecked: // Not used
break;
}
mPerformButton->setEnabled(mNumChecked > 0);
}
void CSVWorld::ExtendedCommandConfigurator::dataIdListChanged()
{
bool idsRemoved = false;
for (int i = 0; i < static_cast<int>(mSelectedIds.size()); ++i)
{
if (!mData.hasId(mSelectedIds[i]))
{
std::swap(mSelectedIds[i], mSelectedIds.back());
mSelectedIds.pop_back();
idsRemoved = true;
--i;
}
}
// If all selected IDs were removed, cancel the configurator
if (mSelectedIds.empty())
{
emit done();
return;
}
if (idsRemoved)
{
mCommandDispatcher->setSelection(mSelectedIds);
}
}
| 7,233
|
C++
|
.cpp
| 208
| 28.485577
| 114
| 0.669241
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,052
|
tableheadermouseeventhandler.cpp
|
OpenMW_openmw/apps/opencs/view/world/tableheadermouseeventhandler.cpp
|
#include "tableheadermouseeventhandler.hpp"
#include "dragrecordtable.hpp"
#include <QAction>
#include <QEvent>
#include <QHeaderView>
#include <QMenu>
#include <QMouseEvent>
#include <QObject>
#include <QPoint>
namespace CSVWorld
{
TableHeaderMouseEventHandler::TableHeaderMouseEventHandler(DragRecordTable* parent)
: QWidget(parent)
, table(*parent)
, header(*table.horizontalHeader())
{
header.setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
connect(&header, &QHeaderView::customContextMenuRequested,
[this](const QPoint& position) { showContextMenu(position); });
header.viewport()->installEventFilter(this);
}
bool TableHeaderMouseEventHandler::eventFilter(QObject* tableWatched, QEvent* event)
{
if (event->type() == QEvent::Type::MouseButtonPress)
{
auto& clickEvent = static_cast<QMouseEvent&>(*event);
if ((clickEvent.button() == Qt::MiddleButton))
{
const auto& index = table.indexAt(clickEvent.pos());
table.setColumnHidden(index.column(), true);
clickEvent.accept();
return true;
}
}
return false;
}
void TableHeaderMouseEventHandler::showContextMenu(const QPoint& position)
{
auto& menu{ createContextMenu() };
menu.popup(header.viewport()->mapToGlobal(position));
}
QMenu& TableHeaderMouseEventHandler::createContextMenu()
{
auto* menu = new QMenu(this);
for (int i = 0; i < table.model()->columnCount(); ++i)
{
const auto& name = table.model()->headerData(i, Qt::Horizontal, Qt::DisplayRole);
QAction* action{ new QAction(name.toString(), this) };
action->setCheckable(true);
action->setChecked(!table.isColumnHidden(i));
menu->addAction(action);
connect(action, &QAction::triggered, [this, action, i]() {
table.setColumnHidden(i, !action->isChecked());
action->setChecked(!action->isChecked());
action->toggle();
});
}
return *menu;
}
} // namespace CSVWorld
| 2,240
|
C++
|
.cpp
| 60
| 28.85
| 93
| 0.622754
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,053
|
pathgridcreator.cpp
|
OpenMW_openmw/apps/opencs/view/world/pathgridcreator.cpp
|
#include "pathgridcreator.hpp"
#include <QLabel>
#include <memory>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/subcellcollection.hpp>
#include <apps/opencs/view/world/genericcreator.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idcompletionmanager.hpp"
#include "../../model/world/idtable.hpp"
#include "../widget/droplineedit.hpp"
class QUndoStack;
std::string CSVWorld::PathgridCreator::getId() const
{
return mCell->text().toUtf8().constData();
}
CSMWorld::IdTable& CSVWorld::PathgridCreator::getPathgridsTable() const
{
return dynamic_cast<CSMWorld::IdTable&>(*getData().getTableModel(getCollectionId()));
}
CSVWorld::PathgridCreator::PathgridCreator(CSMWorld::Data& data, QUndoStack& undoStack, const CSMWorld::UniversalId& id,
CSMWorld::IdCompletionManager& completionManager)
: GenericCreator(data, undoStack, id)
{
setManualEditing(false);
QLabel* label = new QLabel("Cell", this);
insertBeforeButtons(label, false);
// Add cell ID input with auto-completion.
// Only existing cell IDs are accepted so no ID validation is performed.
CSMWorld::ColumnBase::Display displayType = CSMWorld::ColumnBase::Display_Cell;
mCell = new CSVWidget::DropLineEdit(displayType, this);
mCell->setCompleter(completionManager.getCompleter(displayType).get());
insertBeforeButtons(mCell, true);
connect(mCell, &CSVWidget::DropLineEdit::textChanged, this, &PathgridCreator::cellChanged);
connect(mCell, &CSVWidget::DropLineEdit::returnPressed, this, &PathgridCreator::inputReturnPressed);
}
void CSVWorld::PathgridCreator::cloneMode(const std::string& originId, const CSMWorld::UniversalId::Type type)
{
CSVWorld::GenericCreator::cloneMode(originId, type);
// Look up cloned record in pathgrids table and set cell ID text.
CSMWorld::IdTable& table = getPathgridsTable();
int column = table.findColumnIndex(CSMWorld::Columns::ColumnId_Id);
mCell->setText(table.data(table.getModelIndex(originId, column)).toString());
}
std::string CSVWorld::PathgridCreator::getErrors() const
{
const ESM::RefId cellId = ESM::RefId::stringRefId(getId());
// Check user input for any errors.
std::string errors;
if (cellId.empty())
{
errors = "No cell ID selected";
}
else if (getData().getPathgrids().searchId(cellId) > -1)
{
errors = "Pathgrid for selected cell ID already exists";
}
else if (getData().getCells().searchId(cellId) == -1)
{
errors = "Cell with selected cell ID does not exist";
}
return errors;
}
void CSVWorld::PathgridCreator::focus()
{
mCell->setFocus();
}
void CSVWorld::PathgridCreator::reset()
{
CSVWorld::GenericCreator::reset();
mCell->setText("");
}
void CSVWorld::PathgridCreator::cellChanged()
{
update();
}
CSVWorld::Creator* CSVWorld::PathgridCreatorFactory::makeCreator(
CSMDoc::Document& document, const CSMWorld::UniversalId& id) const
{
return new PathgridCreator(document.getData(), document.getUndoStack(), id, document.getIdCompletionManager());
}
| 3,255
|
C++
|
.cpp
| 83
| 35.783133
| 120
| 0.740635
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,054
|
recordbuttonbar.cpp
|
OpenMW_openmw/apps/opencs/view/world/recordbuttonbar.cpp
|
#include "recordbuttonbar.hpp"
#include <QHBoxLayout>
#include <QToolButton>
#include <memory>
#include "../../model/world/commanddispatcher.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/prefs/state.hpp"
#include "../world/tablebottombox.hpp"
#include <components/misc/scalableicon.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/idtablebase.hpp>
#include <apps/opencs/model/world/universalid.hpp>
void CSVWorld::RecordButtonBar::updateModificationButtons()
{
bool createAndDeleteDisabled = !mBottom || !mBottom->canCreateAndDelete() || mLocked;
mCloneButton->setDisabled(createAndDeleteDisabled);
mAddButton->setDisabled(createAndDeleteDisabled);
bool commandDisabled = !mCommandDispatcher || mLocked;
mRevertButton->setDisabled(commandDisabled);
mDeleteButton->setDisabled(commandDisabled || createAndDeleteDisabled);
}
void CSVWorld::RecordButtonBar::updatePrevNextButtons()
{
int rows = mTable.rowCount();
if (rows <= 1)
{
mPrevButton->setDisabled(true);
mNextButton->setDisabled(true);
}
else if (CSMPrefs::get()["General Input"]["cycle"].isTrue())
{
mPrevButton->setDisabled(false);
mNextButton->setDisabled(false);
}
else
{
int row = mTable.getModelIndex(mId.getId(), 0).row();
mPrevButton->setDisabled(row <= 0);
mNextButton->setDisabled(row >= rows - 1);
}
}
CSVWorld::RecordButtonBar::RecordButtonBar(const CSMWorld::UniversalId& id, CSMWorld::IdTable& table,
TableBottomBox* bottomBox, CSMWorld::CommandDispatcher* commandDispatcher, QWidget* parent)
: QWidget(parent)
, mId(id)
, mTable(table)
, mBottom(bottomBox)
, mCommandDispatcher(commandDispatcher)
, mLocked(false)
{
QHBoxLayout* buttonsLayout = new QHBoxLayout;
buttonsLayout->setContentsMargins(0, 0, 0, 0);
// left section
mPrevButton = new QToolButton(this);
mPrevButton->setIcon(Misc::ScalableIcon::load(":record-previous"));
mPrevButton->setToolTip("Switch to previous record");
buttonsLayout->addWidget(mPrevButton, 0);
mNextButton = new QToolButton(this);
mNextButton->setIcon(Misc::ScalableIcon::load(":/record-next"));
mNextButton->setToolTip("Switch to next record");
buttonsLayout->addWidget(mNextButton, 1);
buttonsLayout->addStretch(2);
// optional buttons of the right section
if (mTable.getFeatures() & CSMWorld::IdTable::Feature_Preview)
{
QToolButton* previewButton = new QToolButton(this);
previewButton->setIcon(Misc::ScalableIcon::load(":edit-preview"));
previewButton->setToolTip("Open a preview of this record");
buttonsLayout->addWidget(previewButton);
connect(previewButton, &QToolButton::clicked, this, &RecordButtonBar::showPreview);
}
if (mTable.getFeatures() & CSMWorld::IdTable::Feature_View)
{
QToolButton* viewButton = new QToolButton(this);
viewButton->setIcon(Misc::ScalableIcon::load(":cell"));
viewButton->setToolTip("Open a scene view of the cell this record is located in");
buttonsLayout->addWidget(viewButton);
connect(viewButton, &QToolButton::clicked, this, &RecordButtonBar::viewRecord);
}
// right section
mCloneButton = new QToolButton(this);
mCloneButton->setIcon(Misc::ScalableIcon::load(":edit-clone"));
mCloneButton->setToolTip("Clone record");
buttonsLayout->addWidget(mCloneButton);
mAddButton = new QToolButton(this);
mAddButton->setIcon(Misc::ScalableIcon::load(":edit-add"));
mAddButton->setToolTip("Add new record");
buttonsLayout->addWidget(mAddButton);
mDeleteButton = new QToolButton(this);
mDeleteButton->setIcon(Misc::ScalableIcon::load(":edit-delete"));
mDeleteButton->setToolTip("Delete record");
buttonsLayout->addWidget(mDeleteButton);
mRevertButton = new QToolButton(this);
mRevertButton->setIcon(Misc::ScalableIcon::load(":edit-undo"));
mRevertButton->setToolTip("Revert record");
buttonsLayout->addWidget(mRevertButton);
setLayout(buttonsLayout);
// connections
if (mBottom && mBottom->canCreateAndDelete())
{
connect(mAddButton, &QToolButton::clicked, mBottom, &TableBottomBox::createRequest);
connect(mCloneButton, &QToolButton::clicked, this, &RecordButtonBar::cloneRequest);
}
connect(mNextButton, &QToolButton::clicked, this, &RecordButtonBar::nextId);
connect(mPrevButton, &QToolButton::clicked, this, &RecordButtonBar::prevId);
if (mCommandDispatcher)
{
connect(mRevertButton, &QToolButton::clicked, mCommandDispatcher, &CSMWorld::CommandDispatcher::executeRevert);
connect(mDeleteButton, &QToolButton::clicked, mCommandDispatcher, &CSMWorld::CommandDispatcher::executeDelete);
}
connect(&mTable, &CSMWorld::IdTable::rowsInserted, this, &RecordButtonBar::rowNumberChanged);
connect(&mTable, &CSMWorld::IdTable::rowsRemoved, this, &RecordButtonBar::rowNumberChanged);
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &RecordButtonBar::settingChanged);
updateModificationButtons();
updatePrevNextButtons();
}
void CSVWorld::RecordButtonBar::setEditLock(bool locked)
{
mLocked = locked;
updateModificationButtons();
}
void CSVWorld::RecordButtonBar::universalIdChanged(const CSMWorld::UniversalId& id)
{
mId = id;
updatePrevNextButtons();
}
void CSVWorld::RecordButtonBar::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "General Input/cycle")
updatePrevNextButtons();
}
void CSVWorld::RecordButtonBar::cloneRequest()
{
if (mBottom)
{
int typeColumn = mTable.findColumnIndex(CSMWorld::Columns::ColumnId_RecordType);
QModelIndex typeIndex = mTable.getModelIndex(mId.getId(), typeColumn);
CSMWorld::UniversalId::Type type = static_cast<CSMWorld::UniversalId::Type>(mTable.data(typeIndex).toInt());
mBottom->cloneRequest(mId.getId(), type);
}
}
void CSVWorld::RecordButtonBar::nextId()
{
int newRow = mTable.getModelIndex(mId.getId(), 0).row() + 1;
if (newRow >= mTable.rowCount())
{
if (CSMPrefs::get()["General Input"]["cycle"].isTrue())
newRow = 0;
else
return;
}
emit switchToRow(newRow);
}
void CSVWorld::RecordButtonBar::prevId()
{
int newRow = mTable.getModelIndex(mId.getId(), 0).row() - 1;
if (newRow < 0)
{
if (CSMPrefs::get()["General Input"]["cycle"].isTrue())
newRow = mTable.rowCount() - 1;
else
return;
}
emit switchToRow(newRow);
}
void CSVWorld::RecordButtonBar::rowNumberChanged(const QModelIndex& parent, int start, int end)
{
updatePrevNextButtons();
}
| 6,912
|
C++
|
.cpp
| 171
| 35.304094
| 119
| 0.717187
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,056
|
nestedtable.cpp
|
OpenMW_openmw/apps/opencs/view/world/nestedtable.cpp
|
#include "nestedtable.hpp"
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QMenu>
#include "../../model/prefs/shortcut.hpp"
#include "../../model/world/commanddispatcher.hpp"
#include "../../model/world/commandmacro.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/nestedtableproxymodel.hpp"
#include "../../model/world/universalid.hpp"
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/view/world/dragrecordtable.hpp>
#include "tableeditidaction.hpp"
#include "util.hpp"
CSVWorld::NestedTable::NestedTable(CSMDoc::Document& document, const CSMWorld::UniversalId& id,
CSMWorld::NestedTableProxyModel* model, QWidget* parent, bool editable, bool fixedRows)
: DragRecordTable(document, parent)
, mAddNewRowAction(nullptr)
, mRemoveRowAction(nullptr)
, mEditIdAction(nullptr)
, mModel(model)
{
mDispatcher = new CSMWorld::CommandDispatcher(document, id, this);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection);
horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
verticalHeader()->hide();
int columns = model->columnCount(QModelIndex());
for (int i = 0; i < columns; ++i)
{
CSMWorld::ColumnBase::Display display = static_cast<CSMWorld::ColumnBase::Display>(
model->headerData(i, Qt::Horizontal, CSMWorld::ColumnBase::Role_Display).toInt());
CommandDelegate* delegate
= CommandDelegateFactoryCollection::get().makeDelegate(display, mDispatcher, document, this);
setItemDelegateForColumn(i, delegate);
}
setModel(model);
if (editable)
{
if (!fixedRows)
{
mAddNewRowAction = new QAction(tr("Add new row"), this);
connect(mAddNewRowAction, &QAction::triggered, this, &NestedTable::addNewRowActionTriggered);
CSMPrefs::Shortcut* addRowShortcut = new CSMPrefs::Shortcut("table-add", this);
addRowShortcut->associateAction(mAddNewRowAction);
mRemoveRowAction = new QAction(tr("Remove rows"), this);
connect(mRemoveRowAction, &QAction::triggered, this, &NestedTable::removeRowActionTriggered);
CSMPrefs::Shortcut* removeRowShortcut = new CSMPrefs::Shortcut("table-remove", this);
removeRowShortcut->associateAction(mRemoveRowAction);
}
mEditIdAction = new TableEditIdAction(*this, this);
connect(mEditIdAction, &QAction::triggered, this, &NestedTable::editCell);
}
}
std::vector<CSMWorld::UniversalId> CSVWorld::NestedTable::getDraggedRecords() const
{
// No drag support for nested tables
return std::vector<CSMWorld::UniversalId>();
}
void CSVWorld::NestedTable::contextMenuEvent(QContextMenuEvent* event)
{
if (!mEditIdAction)
return;
QModelIndexList selectedRows = selectionModel()->selectedRows();
QMenu menu(this);
int currentRow = rowAt(event->y());
int currentColumn = columnAt(event->x());
if (mEditIdAction->isValidIdCell(currentRow, currentColumn))
{
mEditIdAction->setCell(currentRow, currentColumn);
menu.addAction(mEditIdAction);
menu.addSeparator();
}
if (mAddNewRowAction && mRemoveRowAction)
{
menu.addAction(mAddNewRowAction);
menu.addAction(mRemoveRowAction);
}
menu.exec(event->globalPos());
}
void CSVWorld::NestedTable::removeRowActionTriggered()
{
CSMWorld::CommandMacro macro(
mDocument.getUndoStack(), selectionModel()->selectedRows().size() > 1 ? tr("Remove rows") : "");
// Remove rows in reverse order
for (int i = selectionModel()->selectedRows().size() - 1; i >= 0; --i)
{
macro.push(new CSMWorld::DeleteNestedCommand(*(mModel->model()), mModel->getParentId(),
selectionModel()->selectedRows()[i].row(), mModel->getParentColumn()));
}
}
void CSVWorld::NestedTable::addNewRowActionTriggered()
{
int row = 0;
if (!selectionModel()->selectedRows().empty())
row = selectionModel()->selectedRows().back().row() + 1;
mDocument.getUndoStack().push(
new CSMWorld::AddNestedCommand(*(mModel->model()), mModel->getParentId(), row, mModel->getParentColumn()));
}
void CSVWorld::NestedTable::editCell()
{
emit editRequest(mEditIdAction->getCurrentId(), "");
}
| 4,423
|
C++
|
.cpp
| 104
| 36.980769
| 115
| 0.705361
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,057
|
table.cpp
|
OpenMW_openmw/apps/opencs/view/world/table.cpp
|
#include "table.hpp"
#include <QAction>
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QMenu>
#include <QMetaObject>
#include <QString>
#include <algorithm>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/idtableproxymodel.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/world/dragrecordtable.hpp>
#include <components/debug/debuglog.hpp>
#include <components/misc/helpviewer.hpp>
#include <components/misc/scalableicon.hpp>
#include <components/misc/strings/algorithm.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/commanddispatcher.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/idtablebase.hpp"
#include "../../model/world/infotableproxymodel.hpp"
#include "../../model/world/landtexturetableproxymodel.hpp"
#include "../../model/prefs/shortcut.hpp"
#include "../../model/prefs/state.hpp"
#include "tableeditidaction.hpp"
#include "tableheadermouseeventhandler.hpp"
#include "util.hpp"
namespace CSMFilter
{
class Node;
}
void CSVWorld::Table::contextMenuEvent(QContextMenuEvent* event)
{
// configure dispatcher
mDispatcher->setSelection(getSelectedIds());
std::vector<CSMWorld::UniversalId> extendedTypes = mDispatcher->getExtendedTypes();
mDispatcher->setExtendedTypes(extendedTypes);
// create context menu
QModelIndexList selectedRows = selectionModel()->selectedRows();
QMenu menu(this);
/// \todo add menu items for select all and clear selection
int currentRow = rowAt(event->y());
int currentColumn = columnAt(event->x());
if (mEditIdAction->isValidIdCell(currentRow, currentColumn))
{
mEditIdAction->setCell(currentRow, currentColumn);
menu.addAction(mEditIdAction);
menu.addSeparator();
}
if (!mEditLock && !(mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
{
if (selectedRows.size() == 1)
{
menu.addAction(mEditAction);
if (mCreateAction)
menu.addAction(mCloneAction);
}
if (mTouchAction)
menu.addAction(mTouchAction);
if (mCreateAction)
menu.addAction(mCreateAction);
if (mDispatcher->canRevert())
{
menu.addAction(mRevertAction);
if (!extendedTypes.empty())
menu.addAction(mExtendedRevertAction);
}
if (mDispatcher->canDelete())
{
menu.addAction(mDeleteAction);
if (!extendedTypes.empty())
menu.addAction(mExtendedDeleteAction);
}
if (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_ReorderWithinTopic)
{
/// \todo allow reordering of multiple rows
if (selectedRows.size() == 1)
{
int column = mModel->searchColumnIndex(CSMWorld::Columns::ColumnId_Topic);
if (column == -1)
column = mModel->searchColumnIndex(CSMWorld::Columns::ColumnId_Journal);
if (column != -1)
{
int row = mProxyModel->mapToSource(mProxyModel->index(selectedRows.begin()->row(), 0)).row();
QString curData = mModel->data(mModel->index(row, column)).toString();
if (row > 0)
{
QString prevData = mModel->data(mModel->index(row - 1, column)).toString();
if (Misc::StringUtils::ciEqual(curData.toStdString(), prevData.toStdString()))
{
menu.addAction(mMoveUpAction);
}
}
if (row < mModel->rowCount() - 1)
{
QString nextData = mModel->data(mModel->index(row + 1, column)).toString();
if (Misc::StringUtils::ciEqual(curData.toStdString(), nextData.toStdString()))
{
menu.addAction(mMoveDownAction);
}
}
}
}
}
}
if (selectedRows.size() == 1)
{
int row = selectedRows.begin()->row();
row = mProxyModel->mapToSource(mProxyModel->index(row, 0)).row();
if (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_View)
{
CSMWorld::UniversalId id = mModel->view(row).first;
const int index = mDocument.getData().getCells().searchId(ESM::RefId::stringRefId(id.getId()));
// index==-1: the ID references a worldspace instead of a cell (ignore for now and go
// ahead)
if (index == -1 || !mDocument.getData().getCells().getRecord(index).isDeleted())
menu.addAction(mViewAction);
}
if (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Preview)
{
const CSMWorld::UniversalId id = getUniversalId(currentRow);
const CSMWorld::UniversalId::Type type = id.getType();
QModelIndex index = mModel->index(row, mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Modification));
CSMWorld::RecordBase::State state = static_cast<CSMWorld::RecordBase::State>(mModel->data(index).toInt());
if (state != CSMWorld::RecordBase::State_Deleted && type != CSMWorld::UniversalId::Type_ItemLevelledList)
menu.addAction(mPreviewAction);
}
}
if (mHelpAction)
menu.addAction(mHelpAction);
menu.exec(event->globalPos());
}
void CSVWorld::Table::mouseDoubleClickEvent(QMouseEvent* event)
{
Qt::KeyboardModifiers modifiers = event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier);
QModelIndex index = currentIndex();
selectionModel()->select(
index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Rows);
std::map<Qt::KeyboardModifiers, DoubleClickAction>::iterator iter = mDoubleClickActions.find(modifiers);
if (iter == mDoubleClickActions.end())
{
event->accept();
return;
}
switch (iter->second)
{
case Action_None:
event->accept();
break;
case Action_InPlaceEdit:
DragRecordTable::mouseDoubleClickEvent(event);
break;
case Action_EditRecord:
event->accept();
editRecord();
break;
case Action_View:
event->accept();
viewRecord();
break;
case Action_Revert:
event->accept();
if (mDispatcher->canRevert())
mDispatcher->executeRevert();
break;
case Action_Delete:
event->accept();
if (mDispatcher->canDelete())
mDispatcher->executeDelete();
break;
case Action_EditRecordAndClose:
event->accept();
editRecord();
emit closeRequest();
break;
case Action_ViewAndClose:
event->accept();
viewRecord();
emit closeRequest();
break;
}
}
CSVWorld::Table::Table(const CSMWorld::UniversalId& id, bool createAndDelete, bool sorting, CSMDoc::Document& document)
: DragRecordTable(document)
, mCreateAction(nullptr)
, mCloneAction(nullptr)
, mTouchAction(nullptr)
, mRecordStatusDisplay(0)
, mJumpToAddedRecord(false)
, mUnselectAfterJump(false)
, mAutoJump(false)
{
mModel = &dynamic_cast<CSMWorld::IdTableBase&>(*mDocument.getData().getTableModel(id));
bool isInfoTable = id.getType() == CSMWorld::UniversalId::Type_TopicInfos
|| id.getType() == CSMWorld::UniversalId::Type_JournalInfos;
bool isLtexTable = (id.getType() == CSMWorld::UniversalId::Type_LandTextures);
if (isInfoTable)
{
mProxyModel = new CSMWorld::InfoTableProxyModel(id.getType(), this);
connect(this, &CSVWorld::DragRecordTable::moveRecordsFromSameTable, this, &CSVWorld::Table::moveRecords);
connect(this, &CSVWorld::DragRecordTable::createNewInfoRecord, this,
&CSVWorld::Table::createRecordsDirectlyRequest);
}
else if (isLtexTable)
{
mProxyModel = new CSMWorld::LandTextureTableProxyModel(this);
}
else
{
mProxyModel = new CSMWorld::IdTableProxyModel(this);
}
mProxyModel->setSourceModel(mModel);
mDispatcher = new CSMWorld::CommandDispatcher(document, id, this);
setModel(mProxyModel);
horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
// The number is arbitrary but autoresize would be way too slow otherwise.
constexpr int autoResizePrecision = 500;
horizontalHeader()->setResizeContentsPrecision(autoResizePrecision);
resizeColumnsToContents();
verticalHeader()->hide();
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection);
int columns = mModel->columnCount();
for (int i = 0; i < columns; ++i)
{
int flags = mModel->headerData(i, Qt::Horizontal, CSMWorld::ColumnBase::Role_Flags).toInt();
if (flags & CSMWorld::ColumnBase::Flag_Table)
{
CSMWorld::ColumnBase::Display display = static_cast<CSMWorld::ColumnBase::Display>(
mModel->headerData(i, Qt::Horizontal, CSMWorld::ColumnBase::Role_Display).toInt());
CommandDelegate* delegate
= CommandDelegateFactoryCollection::get().makeDelegate(display, mDispatcher, document, this);
mDelegates.push_back(delegate);
setItemDelegateForColumn(i, delegate);
}
else
hideColumn(i);
}
if (sorting)
{
// FIXME: some tables (e.g. CellRef) have this column hidden, which makes it confusing
sortByColumn(mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id), Qt::AscendingOrder);
}
setSortingEnabled(sorting);
mEditAction = new QAction(tr("Edit Record"), this);
connect(mEditAction, &QAction::triggered, this, &Table::editRecord);
mEditAction->setIcon(Misc::ScalableIcon::load(":edit-edit"));
addAction(mEditAction);
CSMPrefs::Shortcut* editShortcut = new CSMPrefs::Shortcut("table-edit", this);
editShortcut->associateAction(mEditAction);
if (createAndDelete)
{
mCreateAction = new QAction(tr("Add Record"), this);
connect(mCreateAction, &QAction::triggered, this, &Table::createRequest);
mCreateAction->setIcon(Misc::ScalableIcon::load(":edit-add"));
addAction(mCreateAction);
CSMPrefs::Shortcut* createShortcut = new CSMPrefs::Shortcut("table-add", this);
createShortcut->associateAction(mCreateAction);
mCloneAction = new QAction(tr("Clone Record"), this);
connect(mCloneAction, &QAction::triggered, this, &Table::cloneRecord);
mCloneAction->setIcon(Misc::ScalableIcon::load(":edit-clone"));
addAction(mCloneAction);
CSMPrefs::Shortcut* cloneShortcut = new CSMPrefs::Shortcut("table-clone", this);
cloneShortcut->associateAction(mCloneAction);
}
if (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_AllowTouch)
{
mTouchAction = new QAction(tr("Touch Record"), this);
connect(mTouchAction, &QAction::triggered, this, &Table::touchRecord);
mTouchAction->setIcon(Misc::ScalableIcon::load(":edit-touch"));
addAction(mTouchAction);
CSMPrefs::Shortcut* touchShortcut = new CSMPrefs::Shortcut("table-touch", this);
touchShortcut->associateAction(mTouchAction);
}
mRevertAction = new QAction(tr("Revert Record"), this);
connect(mRevertAction, &QAction::triggered, mDispatcher, &CSMWorld::CommandDispatcher::executeRevert);
mRevertAction->setIcon(Misc::ScalableIcon::load(":edit-undo"));
addAction(mRevertAction);
CSMPrefs::Shortcut* revertShortcut = new CSMPrefs::Shortcut("table-revert", this);
revertShortcut->associateAction(mRevertAction);
mDeleteAction = new QAction(tr("Delete Record"), this);
connect(mDeleteAction, &QAction::triggered, mDispatcher, &CSMWorld::CommandDispatcher::executeDelete);
mDeleteAction->setIcon(Misc::ScalableIcon::load(":edit-delete"));
addAction(mDeleteAction);
CSMPrefs::Shortcut* deleteShortcut = new CSMPrefs::Shortcut("table-remove", this);
deleteShortcut->associateAction(mDeleteAction);
mMoveUpAction = new QAction(tr("Move Up"), this);
connect(mMoveUpAction, &QAction::triggered, this, &Table::moveUpRecord);
mMoveUpAction->setIcon(Misc::ScalableIcon::load(":record-up"));
addAction(mMoveUpAction);
CSMPrefs::Shortcut* moveUpShortcut = new CSMPrefs::Shortcut("table-moveup", this);
moveUpShortcut->associateAction(mMoveUpAction);
mMoveDownAction = new QAction(tr("Move Down"), this);
connect(mMoveDownAction, &QAction::triggered, this, &Table::moveDownRecord);
mMoveDownAction->setIcon(Misc::ScalableIcon::load(":record-down"));
addAction(mMoveDownAction);
CSMPrefs::Shortcut* moveDownShortcut = new CSMPrefs::Shortcut("table-movedown", this);
moveDownShortcut->associateAction(mMoveDownAction);
mViewAction = new QAction(tr("View"), this);
connect(mViewAction, &QAction::triggered, this, &Table::viewRecord);
mViewAction->setIcon(Misc::ScalableIcon::load(":cell"));
addAction(mViewAction);
CSMPrefs::Shortcut* viewShortcut = new CSMPrefs::Shortcut("table-view", this);
viewShortcut->associateAction(mViewAction);
mPreviewAction = new QAction(tr("Preview"), this);
connect(mPreviewAction, &QAction::triggered, this, &Table::previewRecord);
mPreviewAction->setIcon(Misc::ScalableIcon::load(":edit-preview"));
addAction(mPreviewAction);
CSMPrefs::Shortcut* previewShortcut = new CSMPrefs::Shortcut("table-preview", this);
previewShortcut->associateAction(mPreviewAction);
mExtendedDeleteAction = new QAction(tr("Extended Delete Record"), this);
connect(mExtendedDeleteAction, &QAction::triggered, this, &Table::executeExtendedDelete);
mExtendedDeleteAction->setIcon(Misc::ScalableIcon::load(":edit-delete"));
addAction(mExtendedDeleteAction);
CSMPrefs::Shortcut* extendedDeleteShortcut = new CSMPrefs::Shortcut("table-extendeddelete", this);
extendedDeleteShortcut->associateAction(mExtendedDeleteAction);
mExtendedRevertAction = new QAction(tr("Extended Revert Record"), this);
connect(mExtendedRevertAction, &QAction::triggered, this, &Table::executeExtendedRevert);
mExtendedRevertAction->setIcon(Misc::ScalableIcon::load(":edit-undo"));
addAction(mExtendedRevertAction);
CSMPrefs::Shortcut* extendedRevertShortcut = new CSMPrefs::Shortcut("table-extendedrevert", this);
extendedRevertShortcut->associateAction(mExtendedRevertAction);
mEditIdAction = new TableEditIdAction(*this, this);
connect(mEditIdAction, &QAction::triggered, this, &Table::editCell);
addAction(mEditIdAction);
mHelpAction = new QAction(tr("Help"), this);
connect(mHelpAction, &QAction::triggered, this, &Table::openHelp);
mHelpAction->setIcon(Misc::ScalableIcon::load(":info"));
addAction(mHelpAction);
CSMPrefs::Shortcut* openHelpShortcut = new CSMPrefs::Shortcut("help", this);
openHelpShortcut->associateAction(mHelpAction);
connect(mProxyModel, &CSMWorld::IdTableProxyModel::rowsRemoved, this, &Table::tableSizeUpdate);
connect(mProxyModel, &CSMWorld::IdTableProxyModel::rowAdded, this, &Table::rowAdded);
/// \note This signal could instead be connected to a slot that filters out changes not affecting
/// the records status column (for permanence reasons)
connect(mProxyModel, &CSMWorld::IdTableProxyModel::dataChanged, this, &Table::dataChangedEvent);
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, &Table::selectionSizeUpdate);
setAcceptDrops(true);
mDoubleClickActions.insert(std::make_pair(Qt::NoModifier, Action_InPlaceEdit));
mDoubleClickActions.insert(std::make_pair(Qt::ShiftModifier, Action_EditRecord));
mDoubleClickActions.insert(std::make_pair(Qt::ControlModifier, Action_View));
mDoubleClickActions.insert(std::make_pair(Qt::ShiftModifier | Qt::ControlModifier, Action_EditRecordAndClose));
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &Table::settingChanged);
CSMPrefs::get()["ID Tables"].update();
new TableHeaderMouseEventHandler(this);
}
void CSVWorld::Table::setEditLock(bool locked)
{
for (std::vector<CommandDelegate*>::iterator iter(mDelegates.begin()); iter != mDelegates.end(); ++iter)
(*iter)->setEditLock(locked);
DragRecordTable::setEditLock(locked);
mDispatcher->setEditLock(locked);
}
CSMWorld::UniversalId CSVWorld::Table::getUniversalId(int row) const
{
row = mProxyModel->mapToSource(mProxyModel->index(row, 0)).row();
int idColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
int typeColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_RecordType);
return CSMWorld::UniversalId(
static_cast<CSMWorld::UniversalId::Type>(mModel->data(mModel->index(row, typeColumn)).toInt()),
mModel->data(mModel->index(row, idColumn)).toString().toUtf8().constData());
}
std::vector<std::string> CSVWorld::Table::getSelectedIds() const
{
std::vector<std::string> ids;
QModelIndexList selectedRows = selectionModel()->selectedRows();
int columnIndex = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
for (QModelIndexList::const_iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
int row = mProxyModel->mapToSource(mProxyModel->index(iter->row(), 0)).row();
ids.emplace_back(mModel->data(mModel->index(row, columnIndex)).toString().toUtf8().constData());
}
return ids;
}
void CSVWorld::Table::editRecord()
{
if (!mEditLock || (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
if (selectedRows.size() == 1)
emit editRequest(getUniversalId(selectedRows.begin()->row()), "");
}
}
void CSVWorld::Table::cloneRecord()
{
if (!mEditLock || (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
const CSMWorld::UniversalId& toClone = getUniversalId(selectedRows.begin()->row());
if (selectedRows.size() == 1)
{
emit cloneRequest(toClone);
}
}
}
void CSVWorld::Table::touchRecord()
{
if (!mEditLock && mModel->getFeatures() & CSMWorld::IdTableBase::Feature_AllowTouch)
{
std::vector<CSMWorld::UniversalId> touchIds;
QModelIndexList selectedRows = selectionModel()->selectedRows();
for (auto it = selectedRows.begin(); it != selectedRows.end(); ++it)
{
touchIds.push_back(getUniversalId(it->row()));
}
emit touchRequest(touchIds);
}
}
void CSVWorld::Table::moveUpRecord()
{
if (mEditLock || (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
return;
QModelIndexList selectedRows = selectionModel()->selectedRows();
if (selectedRows.size() == 1)
{
int row2 = selectedRows.begin()->row();
if (row2 > 0)
{
int row = row2 - 1;
row = mProxyModel->mapToSource(mProxyModel->index(row, 0)).row();
row2 = mProxyModel->mapToSource(mProxyModel->index(row2, 0)).row();
if (row2 <= row)
throw std::runtime_error("Inconsistent row order");
std::vector<int> newOrder(row2 - row + 1);
newOrder[0] = row2 - row;
newOrder[row2 - row] = 0;
for (int i = 1; i < row2 - row; ++i)
newOrder[i] = i;
mDocument.getUndoStack().push(
new CSMWorld::ReorderRowsCommand(dynamic_cast<CSMWorld::IdTable&>(*mModel), row, newOrder));
}
}
}
void CSVWorld::Table::moveDownRecord()
{
if (mEditLock || (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
return;
QModelIndexList selectedRows = selectionModel()->selectedRows();
if (selectedRows.size() == 1)
{
int row = selectedRows.begin()->row();
if (row < mProxyModel->rowCount() - 1)
{
int row2 = row + 1;
row = mProxyModel->mapToSource(mProxyModel->index(row, 0)).row();
row2 = mProxyModel->mapToSource(mProxyModel->index(row2, 0)).row();
if (row2 <= row)
throw std::runtime_error("Inconsistent row order");
std::vector<int> newOrder(row2 - row + 1);
newOrder[0] = row2 - row;
newOrder[row2 - row] = 0;
for (int i = 1; i < row2 - row; ++i)
newOrder[i] = i;
mDocument.getUndoStack().push(
new CSMWorld::ReorderRowsCommand(dynamic_cast<CSMWorld::IdTable&>(*mModel), row, newOrder));
}
}
}
void CSVWorld::Table::moveRecords(QDropEvent* event)
{
if (mEditLock || (mModel->getFeatures() & CSMWorld::IdTableBase::Feature_Constant))
return;
QModelIndex targedIndex = indexAt(event->pos());
QModelIndexList selectedRows = selectionModel()->selectedRows();
int targetRowRaw = targedIndex.row();
int targetRow = mProxyModel->mapToSource(mProxyModel->index(targetRowRaw, 0)).row();
int baseRowRaw = targedIndex.row() - 1;
int baseRow = mProxyModel->mapToSource(mProxyModel->index(baseRowRaw, 0)).row();
int highestDifference = 0;
for (const auto& thisRowData : selectedRows)
{
int thisRow = mProxyModel->mapToSource(mProxyModel->index(thisRowData.row(), 0)).row();
if (std::abs(targetRow - thisRow) > highestDifference)
highestDifference = std::abs(targetRow - thisRow);
if (thisRow - 1 < baseRow)
baseRow = thisRow - 1;
}
std::vector<int> newOrder(highestDifference + 1);
for (int i = 0; i <= highestDifference; ++i)
{
newOrder[i] = i;
}
if (selectedRows.size() > 1)
{
Log(Debug::Warning) << "Move operation failed: Moving multiple selections isn't implemented.";
return;
}
for (const auto& thisRowData : selectedRows)
{
/*
Moving algorithm description
a) Remove the (ORIGIN + 1)th list member.
b) Add (ORIGIN+1)th list member with value TARGET
c) If ORIGIN > TARGET,d_INC; ELSE d_DEC
d_INC) increase all members after (and including) the TARGET by one, stop before hitting ORIGINth address
d_DEC) decrease all members after the ORIGIN by one, stop after hitting address TARGET
*/
int originRowRaw = thisRowData.row();
int originRow = mProxyModel->mapToSource(mProxyModel->index(originRowRaw, 0)).row();
newOrder.erase(newOrder.begin() + originRow - baseRow - 1);
newOrder.emplace(newOrder.begin() + originRow - baseRow - 1, targetRow - baseRow - 1);
if (originRow > targetRow)
{
for (int i = targetRow - baseRow - 1; i < originRow - baseRow - 1; ++i)
{
++newOrder[i];
}
}
else
{
for (int i = originRow - baseRow; i <= targetRow - baseRow - 1; ++i)
{
--newOrder[i];
}
}
}
mDocument.getUndoStack().push(
new CSMWorld::ReorderRowsCommand(dynamic_cast<CSMWorld::IdTable&>(*mModel), baseRow + 1, newOrder));
}
void CSVWorld::Table::editCell()
{
emit editRequest(mEditIdAction->getCurrentId(), "");
}
void CSVWorld::Table::openHelp()
{
Misc::HelpViewer::openHelp("manuals/openmw-cs/tables.html");
}
void CSVWorld::Table::viewRecord()
{
if (!(mModel->getFeatures() & CSMWorld::IdTableBase::Feature_View))
return;
QModelIndexList selectedRows = selectionModel()->selectedRows();
if (selectedRows.size() == 1)
{
int row = selectedRows.begin()->row();
row = mProxyModel->mapToSource(mProxyModel->index(row, 0)).row();
std::pair<CSMWorld::UniversalId, std::string> params = mModel->view(row);
if (params.first.getType() != CSMWorld::UniversalId::Type_None)
emit editRequest(params.first, params.second);
}
}
void CSVWorld::Table::previewRecord()
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
if (selectedRows.size() == 1)
{
CSMWorld::UniversalId id = getUniversalId(selectedRows.begin()->row());
QModelIndex index
= mModel->getModelIndex(id.getId(), mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Modification));
if (mModel->data(index) != CSMWorld::RecordBase::State_Deleted)
emit editRequest(CSMWorld::UniversalId(CSMWorld::UniversalId::Type_Preview, id), "");
}
}
void CSVWorld::Table::executeExtendedDelete()
{
if (CSMPrefs::get()["ID Tables"]["extended-config"].isTrue())
{
emit extendedDeleteConfigRequest(getSelectedIds());
}
else
{
QMetaObject::invokeMethod(mDispatcher, "executeExtendedDelete", Qt::QueuedConnection);
}
}
void CSVWorld::Table::executeExtendedRevert()
{
if (CSMPrefs::get()["ID Tables"]["extended-config"].isTrue())
{
emit extendedRevertConfigRequest(getSelectedIds());
}
else
{
QMetaObject::invokeMethod(mDispatcher, "executeExtendedRevert", Qt::QueuedConnection);
}
}
void CSVWorld::Table::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "ID Tables/jump-to-added")
{
if (setting->toString() == "Jump and Select")
{
mJumpToAddedRecord = true;
mUnselectAfterJump = false;
}
else if (setting->toString() == "Jump Only")
{
mJumpToAddedRecord = true;
mUnselectAfterJump = true;
}
else // No Jump
{
mJumpToAddedRecord = false;
mUnselectAfterJump = false;
}
}
else if (*setting == "Records/type-format" || *setting == "Records/status-format")
{
int columns = mModel->columnCount();
for (int i = 0; i < columns; ++i)
if (QAbstractItemDelegate* delegate = itemDelegateForColumn(i))
{
dynamic_cast<CommandDelegate&>(*delegate).settingChanged(setting);
emit dataChanged(mModel->index(0, i), mModel->index(mModel->rowCount() - 1, i));
}
}
else if (setting->getParent()->getKey() == "ID Tables" && setting->getKey().substr(0, 6) == "double")
{
std::string modifierString = setting->getKey().substr(6);
Qt::KeyboardModifiers modifiers;
if (modifierString == "-s")
modifiers = Qt::ShiftModifier;
else if (modifierString == "-c")
modifiers = Qt::ControlModifier;
else if (modifierString == "-sc")
modifiers = Qt::ShiftModifier | Qt::ControlModifier;
DoubleClickAction action = Action_None;
std::string value = setting->toString();
if (value == "Edit in Place")
action = Action_InPlaceEdit;
else if (value == "Edit Record")
action = Action_EditRecord;
else if (value == "View")
action = Action_View;
else if (value == "Revert")
action = Action_Revert;
else if (value == "Delete")
action = Action_Delete;
else if (value == "Edit Record and Close")
action = Action_EditRecordAndClose;
else if (value == "View and Close")
action = Action_ViewAndClose;
mDoubleClickActions[modifiers] = action;
}
}
void CSVWorld::Table::tableSizeUpdate()
{
int size = 0;
int deleted = 0;
int modified = 0;
if (mProxyModel->columnCount() > 0)
{
int rows = mProxyModel->rowCount();
int columnIndex = mModel->searchColumnIndex(CSMWorld::Columns::ColumnId_Modification);
if (columnIndex != -1)
{
for (int i = 0; i < rows; ++i)
{
QModelIndex index = mProxyModel->mapToSource(mProxyModel->index(i, 0));
int state = mModel->data(mModel->index(index.row(), columnIndex)).toInt();
switch (state)
{
case CSMWorld::RecordBase::State_BaseOnly:
++size;
break;
case CSMWorld::RecordBase::State_Modified:
++size;
++modified;
break;
case CSMWorld::RecordBase::State_ModifiedOnly:
++size;
++modified;
break;
case CSMWorld::RecordBase::State_Deleted:
++deleted;
++modified;
break;
}
}
}
else
size = rows;
}
emit tableSizeChanged(size, deleted, modified);
}
void CSVWorld::Table::selectionSizeUpdate()
{
emit selectionSizeChanged(selectionModel()->selectedRows().size());
}
void CSVWorld::Table::requestFocus(const std::string& id)
{
QModelIndex index = mProxyModel->getModelIndex(id, 0);
if (index.isValid())
{
// This will scroll to the row.
selectRow(index.row());
// This will actually select it.
selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
void CSVWorld::Table::recordFilterChanged(std::shared_ptr<CSMFilter::Node> filter)
{
mProxyModel->setFilter(filter);
tableSizeUpdate();
selectionSizeUpdate();
}
void CSVWorld::Table::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton)
{
startDragFromTable(*this, indexAt(event->pos()));
}
}
std::vector<std::string> CSVWorld::Table::getColumnsWithDisplay(CSMWorld::ColumnBase::Display display) const
{
const int count = mModel->columnCount();
std::vector<std::string> titles;
for (int i = 0; i < count; ++i)
{
CSMWorld::ColumnBase::Display columndisplay = static_cast<CSMWorld::ColumnBase::Display>(
mModel->headerData(i, Qt::Horizontal, CSMWorld::ColumnBase::Role_Display).toInt());
if (display == columndisplay)
{
titles.emplace_back(mModel->headerData(i, Qt::Horizontal).toString().toUtf8().constData());
}
}
return titles;
}
std::vector<CSMWorld::UniversalId> CSVWorld::Table::getDraggedRecords() const
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
std::vector<CSMWorld::UniversalId> idToDrag;
for (QModelIndex& it : selectedRows)
idToDrag.push_back(getUniversalId(it.row()));
return idToDrag;
}
// parent, start and end depend on the model sending the signal, in this case mProxyModel
//
// If, for example, mModel was used instead, then scrolTo() should use the index
// mProxyModel->mapFromSource(mModel->index(end, 0))
void CSVWorld::Table::rowAdded(const std::string& id)
{
tableSizeUpdate();
if (mJumpToAddedRecord)
{
int idColumn = mModel->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
int end = mProxyModel->getModelIndex(id, idColumn).row();
selectRow(end);
// without this delay the scroll works but goes to top for add/clone
QMetaObject::invokeMethod(this, "queuedScrollTo", Qt::QueuedConnection, Q_ARG(int, end));
if (mUnselectAfterJump)
clearSelection();
}
}
void CSVWorld::Table::queuedScrollTo(int row)
{
scrollTo(mProxyModel->index(row, 0), QAbstractItemView::PositionAtCenter);
}
void CSVWorld::Table::dataChangedEvent(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
tableSizeUpdate();
if (mAutoJump)
{
selectRow(bottomRight.row());
scrollTo(bottomRight, QAbstractItemView::PositionAtCenter);
}
}
void CSVWorld::Table::jumpAfterModChanged(int state)
{
if (state == Qt::Checked)
mAutoJump = true;
else
mAutoJump = false;
}
| 32,822
|
C++
|
.cpp
| 773
| 34.518758
| 119
| 0.649776
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,058
|
reportsubview.cpp
|
OpenMW_openmw/apps/opencs/view/tools/reportsubview.cpp
|
#include "reportsubview.hpp"
#include "reporttable.hpp"
#include <apps/opencs/view/doc/subview.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/doc/state.hpp"
CSVTools::ReportSubView::ReportSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
: CSVDoc::SubView(id)
, mDocument(document)
, mRefreshState(0)
{
if (id.getType() == CSMWorld::UniversalId::Type_VerificationResults)
mRefreshState = CSMDoc::State_Verifying;
setWidget(mTable = new ReportTable(document, id, false, mRefreshState, this));
connect(mTable, &ReportTable::editRequest, this, &ReportSubView::focusId);
if (mRefreshState == CSMDoc::State_Verifying)
{
connect(mTable, &ReportTable::refreshRequest, this, &ReportSubView::refreshRequest);
connect(&document, &CSMDoc::Document::stateChanged, mTable, &ReportTable::stateChanged);
}
}
void CSVTools::ReportSubView::setEditLock(bool locked)
{
// ignored. We don't change document state anyway.
}
void CSVTools::ReportSubView::refreshRequest()
{
if (!(mDocument.getState() & mRefreshState))
{
if (mRefreshState == CSMDoc::State_Verifying)
{
mTable->clear();
mDocument.verify(getUniversalId());
}
}
}
| 1,279
|
C++
|
.cpp
| 35
| 31.714286
| 99
| 0.700972
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,059
|
searchbox.cpp
|
OpenMW_openmw/apps/opencs/view/tools/searchbox.cpp
|
#include "searchbox.hpp"
#include <stdexcept>
#include <QGridLayout>
#include "../../model/world/columns.hpp"
#include "../../model/tools/search.hpp"
void CSVTools::SearchBox::updateSearchButton()
{
if (!mSearchEnabled)
mSearch.setEnabled(false);
else
{
switch (mMode.currentIndex())
{
case 0:
case 1:
case 2:
case 3:
mSearch.setEnabled(!mText.text().isEmpty());
break;
case 4:
mSearch.setEnabled(true);
break;
}
}
}
CSVTools::SearchBox::SearchBox(QWidget* parent)
: QWidget(parent)
, mSearch(tr("Search"))
, mSearchEnabled(false)
, mReplace(tr("Replace All"))
{
mLayout = new QGridLayout(this);
// search panel
std::vector<std::pair<int, std::string>> states
= CSMWorld::Columns::getEnums(CSMWorld::Columns::ColumnId_Modification);
states.resize(states.size() - 1); // ignore erased state
for (std::vector<std::pair<int, std::string>>::const_iterator iter(states.begin()); iter != states.end(); ++iter)
mRecordState.addItem(QString::fromUtf8(iter->second.c_str()));
mMode.addItem(tr("Text"));
mMode.addItem(tr("Text (RegEx)"));
mMode.addItem(tr("ID"));
mMode.addItem(tr("ID (RegEx)"));
mMode.addItem(tr("Record State"));
connect(&mMode, qOverload<int>(&QComboBox::activated), this, &SearchBox::modeSelected);
mLayout->addWidget(&mMode, 0, 0);
connect(&mText, &QLineEdit::textChanged, this, &SearchBox::textChanged);
connect(&mText, &QLineEdit::returnPressed, this, [this]() { this->startSearch(false); });
mInput.insertWidget(0, &mText);
mInput.insertWidget(1, &mRecordState);
mLayout->addWidget(&mInput, 0, 1);
mCaseSensitive.setText(tr("Case"));
mLayout->addWidget(&mCaseSensitive, 0, 2);
connect(&mSearch, &QPushButton::clicked, this, qOverload<bool>(&SearchBox::startSearch));
mLayout->addWidget(&mSearch, 0, 3);
// replace panel
mReplaceInput.insertWidget(0, &mReplaceText);
mReplaceInput.insertWidget(1, &mReplacePlaceholder);
mLayout->addWidget(&mReplaceInput, 1, 1);
mLayout->addWidget(&mReplace, 1, 3);
// layout adjustments
mLayout->setColumnMinimumWidth(2, 50);
mLayout->setColumnStretch(1, 1);
mLayout->setContentsMargins(0, 0, 0, 0);
connect(&mReplace, &QPushButton::clicked, this, qOverload<bool>(&SearchBox::replaceAll));
// update
modeSelected(0);
updateSearchButton();
}
void CSVTools::SearchBox::setSearchMode(bool enabled)
{
mSearchEnabled = enabled;
updateSearchButton();
}
CSMTools::Search CSVTools::SearchBox::getSearch() const
{
CSMTools::Search::Type type = static_cast<CSMTools::Search::Type>(mMode.currentIndex());
bool caseSensitive = mCaseSensitive.isChecked();
switch (type)
{
case CSMTools::Search::Type_Text:
case CSMTools::Search::Type_Id:
return CSMTools::Search(type, caseSensitive, std::string(mText.text().toUtf8().data()));
case CSMTools::Search::Type_TextRegEx:
case CSMTools::Search::Type_IdRegEx:
return CSMTools::Search(type, caseSensitive,
QRegularExpression(mText.text().toUtf8().data(), QRegularExpression::CaseInsensitiveOption));
case CSMTools::Search::Type_RecordState:
return CSMTools::Search(type, caseSensitive, mRecordState.currentIndex());
case CSMTools::Search::Type_None:
break;
}
throw std::logic_error("invalid search mode index");
}
std::string CSVTools::SearchBox::getReplaceText() const
{
CSMTools::Search::Type type = static_cast<CSMTools::Search::Type>(mMode.currentIndex());
switch (type)
{
case CSMTools::Search::Type_Text:
case CSMTools::Search::Type_TextRegEx:
case CSMTools::Search::Type_Id:
case CSMTools::Search::Type_IdRegEx:
return mReplaceText.text().toUtf8().data();
default:
throw std::logic_error("Invalid search mode for replace");
}
}
void CSVTools::SearchBox::setEditLock(bool locked)
{
mReplace.setEnabled(!locked);
}
void CSVTools::SearchBox::focus()
{
mInput.currentWidget()->setFocus();
}
void CSVTools::SearchBox::modeSelected(int index)
{
switch (index)
{
case CSMTools::Search::Type_Text:
case CSMTools::Search::Type_TextRegEx:
case CSMTools::Search::Type_Id:
case CSMTools::Search::Type_IdRegEx:
mInput.setCurrentIndex(0);
mReplaceInput.setCurrentIndex(0);
break;
case CSMTools::Search::Type_RecordState:
mInput.setCurrentIndex(1);
mReplaceInput.setCurrentIndex(1);
break;
}
mInput.currentWidget()->setFocus();
updateSearchButton();
}
void CSVTools::SearchBox::textChanged(const QString& text)
{
updateSearchButton();
}
void CSVTools::SearchBox::startSearch(bool checked)
{
if (mSearch.isEnabled())
emit startSearch(getSearch());
}
void CSVTools::SearchBox::replaceAll(bool checked)
{
emit replaceAll();
}
| 5,166
|
C++
|
.cpp
| 147
| 28.877551
| 117
| 0.662709
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,060
|
reporttable.cpp
|
OpenMW_openmw/apps/opencs/view/tools/reporttable.cpp
|
#include "reporttable.hpp"
#include <algorithm>
#include <utility>
#include <QAction>
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>
#include <QTextDocument>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/view/world/dragrecordtable.hpp>
#include <apps/opencs/view/world/util.hpp>
#include "../../model/tools/reportmodel.hpp"
#include "../../model/prefs/shortcut.hpp"
#include "../../model/prefs/state.hpp"
#include "../../view/world/idtypedelegate.hpp"
namespace CSVTools
{
class RichTextDelegate : public QStyledItemDelegate
{
public:
RichTextDelegate(QObject* parent = nullptr);
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
};
}
CSVTools::RichTextDelegate::RichTextDelegate(QObject* parent)
: QStyledItemDelegate(parent)
{
}
void CSVTools::RichTextDelegate::paint(
QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QTextDocument document;
QVariant value = index.data(Qt::DisplayRole);
if (value.isValid() && !value.isNull())
{
document.setHtml(value.toString());
painter->translate(option.rect.topLeft());
document.drawContents(painter);
painter->translate(-option.rect.topLeft());
}
}
void CSVTools::ReportTable::contextMenuEvent(QContextMenuEvent* event)
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
// create context menu
QMenu menu(this);
if (!selectedRows.empty())
{
menu.addAction(mShowAction);
menu.addAction(mRemoveAction);
bool found = false;
for (QModelIndexList::const_iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
QString hint = mProxyModel->data(mProxyModel->index(iter->row(), 2)).toString();
if (!hint.isEmpty() && hint[0] == 'R')
{
found = true;
break;
}
}
if (found)
menu.addAction(mReplaceAction);
}
if (mRefreshAction)
menu.addAction(mRefreshAction);
menu.exec(event->globalPos());
}
void CSVTools::ReportTable::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton)
startDragFromTable(*this, indexAt(event->pos()));
}
void CSVTools::ReportTable::mouseDoubleClickEvent(QMouseEvent* event)
{
Qt::KeyboardModifiers modifiers = event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier);
QModelIndex index = currentIndex();
selectionModel()->select(
index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Rows);
std::map<Qt::KeyboardModifiers, DoubleClickAction>::iterator iter = mDoubleClickActions.find(modifiers);
if (iter == mDoubleClickActions.end())
{
event->accept();
return;
}
switch (iter->second)
{
case Action_None:
event->accept();
break;
case Action_Edit:
event->accept();
showSelection();
break;
case Action_Remove:
event->accept();
removeSelection();
break;
case Action_EditAndRemove:
event->accept();
showSelection();
removeSelection();
break;
}
}
CSVTools::ReportTable::ReportTable(CSMDoc::Document& document, const CSMWorld::UniversalId& id,
bool richTextDescription, int refreshState, QWidget* parent)
: CSVWorld::DragRecordTable(document, parent)
, mModel(document.getReport(id))
, mRefreshAction(nullptr)
, mRefreshState(refreshState)
{
horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
horizontalHeader()->setStretchLastSection(true);
verticalHeader()->hide();
setSortingEnabled(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection);
mProxyModel = new QSortFilterProxyModel(this);
mProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
mProxyModel->setSourceModel(mModel);
mProxyModel->setSortRole(Qt::UserRole);
setModel(mProxyModel);
setColumnHidden(2, true);
mIdTypeDelegate = CSVWorld::IdTypeDelegateFactory().makeDelegate(nullptr, mDocument, this);
setItemDelegateForColumn(0, mIdTypeDelegate);
if (richTextDescription)
setItemDelegateForColumn(mModel->columnCount() - 1, new RichTextDelegate(this));
mShowAction = new QAction(tr("Show"), this);
connect(mShowAction, &QAction::triggered, this, &ReportTable::showSelection);
addAction(mShowAction);
CSMPrefs::Shortcut* showShortcut = new CSMPrefs::Shortcut("reporttable-show", this);
showShortcut->associateAction(mShowAction);
mRemoveAction = new QAction(tr("Remove from list"), this);
connect(mRemoveAction, &QAction::triggered, this, &ReportTable::removeSelection);
addAction(mRemoveAction);
CSMPrefs::Shortcut* removeShortcut = new CSMPrefs::Shortcut("reporttable-remove", this);
removeShortcut->associateAction(mRemoveAction);
mReplaceAction = new QAction(tr("Replace"), this);
connect(mReplaceAction, &QAction::triggered, this, &ReportTable::replaceRequest);
addAction(mReplaceAction);
CSMPrefs::Shortcut* replaceShortcut = new CSMPrefs::Shortcut("reporttable-replace", this);
replaceShortcut->associateAction(mReplaceAction);
if (mRefreshState)
{
mRefreshAction = new QAction(tr("Refresh"), this);
mRefreshAction->setEnabled(!(mDocument.getState() & mRefreshState));
connect(mRefreshAction, &QAction::triggered, this, &ReportTable::refreshRequest);
addAction(mRefreshAction);
CSMPrefs::Shortcut* refreshShortcut = new CSMPrefs::Shortcut("reporttable-refresh", this);
refreshShortcut->associateAction(mRefreshAction);
}
mDoubleClickActions.insert(std::make_pair(Qt::NoModifier, Action_Edit));
mDoubleClickActions.insert(std::make_pair(Qt::ShiftModifier, Action_Remove));
mDoubleClickActions.insert(std::make_pair(Qt::ControlModifier, Action_EditAndRemove));
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &ReportTable::settingChanged);
CSMPrefs::get()["Reports"].update();
}
std::vector<CSMWorld::UniversalId> CSVTools::ReportTable::getDraggedRecords() const
{
std::vector<CSMWorld::UniversalId> ids;
QModelIndexList selectedRows = selectionModel()->selectedRows();
for (QModelIndexList::const_iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
ids.push_back(mModel->getUniversalId(mProxyModel->mapToSource(*iter).row()));
}
return ids;
}
std::vector<int> CSVTools::ReportTable::getReplaceIndices(bool selection) const
{
std::vector<int> indices;
if (selection)
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
std::vector<int> rows;
for (QModelIndexList::const_iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
rows.push_back(mProxyModel->mapToSource(*iter).row());
}
std::sort(rows.begin(), rows.end());
for (std::vector<int>::const_iterator iter(rows.begin()); iter != rows.end(); ++iter)
{
QString hint = mModel->data(mModel->index(*iter, 2)).toString();
if (!hint.isEmpty() && hint[0] == 'R')
indices.push_back(*iter);
}
}
else
{
for (int i = 0; i < mModel->rowCount(); ++i)
{
QString hint = mModel->data(mModel->index(i, 2)).toString();
if (!hint.isEmpty() && hint[0] == 'R')
indices.push_back(i);
}
}
return indices;
}
void CSVTools::ReportTable::flagAsReplaced(int index)
{
mModel->flagAsReplaced(index);
}
void CSVTools::ReportTable::settingChanged(const CSMPrefs::Setting* setting)
{
if (setting->getParent()->getKey() == "Reports")
{
QString base("double");
QString key = setting->getKey().c_str();
if (key.startsWith(base))
{
QString modifierString = key.mid(base.size());
Qt::KeyboardModifiers modifiers;
if (modifierString == "-s")
modifiers = Qt::ShiftModifier;
else if (modifierString == "-c")
modifiers = Qt::ControlModifier;
else if (modifierString == "-sc")
modifiers = Qt::ShiftModifier | Qt::ControlModifier;
DoubleClickAction action = Action_None;
std::string value = setting->toString();
if (value == "Edit")
action = Action_Edit;
else if (value == "Remove")
action = Action_Remove;
else if (value == "Edit And Remove")
action = Action_EditAndRemove;
mDoubleClickActions[modifiers] = action;
return;
}
}
else if (*setting == "Records/type-format")
mIdTypeDelegate->settingChanged(setting);
}
void CSVTools::ReportTable::showSelection()
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
for (QModelIndexList::const_iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
int row = mProxyModel->mapToSource(*iter).row();
emit editRequest(mModel->getUniversalId(row), mModel->getHint(row));
}
}
void CSVTools::ReportTable::removeSelection()
{
QModelIndexList selectedRows = selectionModel()->selectedRows();
std::vector<int> rows;
for (QModelIndexList::iterator iter(selectedRows.begin()); iter != selectedRows.end(); ++iter)
{
rows.push_back(mProxyModel->mapToSource(*iter).row());
}
std::sort(rows.begin(), rows.end());
for (std::vector<int>::const_reverse_iterator iter(rows.rbegin()); iter != rows.rend(); ++iter)
mProxyModel->removeRows(*iter, 1);
selectionModel()->clear();
}
void CSVTools::ReportTable::clear()
{
mModel->clear();
}
void CSVTools::ReportTable::stateChanged(int state, CSMDoc::Document* document)
{
if (mRefreshAction)
mRefreshAction->setEnabled(!(state & mRefreshState));
}
| 10,474
|
C++
|
.cpp
| 269
| 32.394052
| 115
| 0.674235
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,061
|
subviews.cpp
|
OpenMW_openmw/apps/opencs/view/tools/subviews.cpp
|
#include "subviews.hpp"
#include "../doc/subviewfactoryimp.hpp"
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/doc/subview.hpp>
#include <apps/opencs/view/doc/subviewfactory.hpp>
#include "reportsubview.hpp"
#include "searchsubview.hpp"
void CSVTools::addSubViewFactories(CSVDoc::SubViewFactoryManager& manager)
{
manager.add(CSMWorld::UniversalId::Type_VerificationResults, new CSVDoc::SubViewFactory<ReportSubView>);
manager.add(CSMWorld::UniversalId::Type_LoadErrorLog, new CSVDoc::SubViewFactory<ReportSubView>);
manager.add(CSMWorld::UniversalId::Type_Search, new CSVDoc::SubViewFactory<SearchSubView>);
}
| 658
|
C++
|
.cpp
| 13
| 48.384615
| 108
| 0.809672
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,062
|
searchsubview.cpp
|
OpenMW_openmw/apps/opencs/view/tools/searchsubview.cpp
|
#include "searchsubview.hpp"
#include <QVBoxLayout>
#include "../../model/doc/document.hpp"
#include "../../model/doc/state.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/tools/reportmodel.hpp"
#include "../../model/tools/search.hpp"
#include "../../model/world/idtablebase.hpp"
#include "../world/creator.hpp"
#include "../world/tablebottombox.hpp"
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/doc/subview.hpp>
#include "reporttable.hpp"
#include "searchbox.hpp"
void CSVTools::SearchSubView::replace(bool selection)
{
if (mLocked)
return;
std::vector<int> indices = mTable->getReplaceIndices(selection);
std::string replace = mSearchBox.getReplaceText();
const CSMTools::ReportModel& model = dynamic_cast<const CSMTools::ReportModel&>(*mTable->model());
bool autoDelete = CSMPrefs::get()["Search & Replace"]["auto-delete"].isTrue();
CSMTools::Search search(mSearch);
CSMWorld::IdTableBase* currentTable = nullptr;
// We are running through the indices in reverse order to avoid messing up multiple results
// in a single string.
for (std::vector<int>::const_reverse_iterator iter(indices.rbegin()); iter != indices.rend(); ++iter)
{
const CSMWorld::UniversalId& id = model.getUniversalId(*iter);
CSMWorld::UniversalId::Type type = CSMWorld::UniversalId::getParentType(id.getType());
CSMWorld::IdTableBase* table = &dynamic_cast<CSMWorld::IdTableBase&>(*mDocument.getData().getTableModel(type));
if (table != currentTable)
{
search.configure(table);
currentTable = table;
}
std::string hint = model.getHint(*iter);
if (search.verify(mDocument, table, id, hint))
{
search.replace(mDocument, table, id, hint, replace);
mTable->flagAsReplaced(*iter);
if (autoDelete)
mTable->model()->removeRows(*iter, 1);
}
}
}
void CSVTools::SearchSubView::showEvent(QShowEvent* event)
{
CSVDoc::SubView::showEvent(event);
mSearchBox.focus();
}
CSVTools::SearchSubView::SearchSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
: CSVDoc::SubView(id)
, mDocument(document)
, mLocked(false)
{
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(&mSearchBox);
layout->addWidget(mTable = new ReportTable(document, id, true), 2);
layout->addWidget(mBottom = new CSVWorld::TableBottomBox(CSVWorld::NullCreatorFactory(), document, id, this), 0);
QWidget* widget = new QWidget;
widget->setLayout(layout);
setWidget(widget);
stateChanged(document.getState(), &document);
connect(mTable, &ReportTable::editRequest, this, &SearchSubView::focusId);
connect(mTable, &ReportTable::replaceRequest, this, &SearchSubView::replaceRequest);
connect(&document, &CSMDoc::Document::stateChanged, this, &SearchSubView::stateChanged);
connect(
&mSearchBox, qOverload<const CSMTools::Search&>(&SearchBox::startSearch), this, &SearchSubView::startSearch);
connect(&mSearchBox, qOverload<>(&SearchBox::replaceAll), this, &SearchSubView::replaceAllRequest);
connect(document.getReport(id), &CSMTools::ReportModel::rowsRemoved, this, &SearchSubView::tableSizeUpdate);
connect(document.getReport(id), &CSMTools::ReportModel::rowsInserted, this, &SearchSubView::tableSizeUpdate);
connect(&document, &CSMDoc::Document::operationDone, this, &SearchSubView::operationDone);
}
void CSVTools::SearchSubView::setEditLock(bool locked)
{
mLocked = locked;
mSearchBox.setEditLock(locked);
}
void CSVTools::SearchSubView::setStatusBar(bool show)
{
mBottom->setStatusBar(show);
}
void CSVTools::SearchSubView::stateChanged(int state, CSMDoc::Document* document)
{
mSearchBox.setSearchMode(!(state & CSMDoc::State_Searching));
}
void CSVTools::SearchSubView::startSearch(const CSMTools::Search& search)
{
CSMPrefs::Category& settings = CSMPrefs::get()["Search & Replace"];
mSearch = search;
mSearch.setPadding(settings["char-before"].toInt(), settings["char-after"].toInt());
mTable->clear();
mDocument.runSearch(getUniversalId(), mSearch);
}
void CSVTools::SearchSubView::replaceRequest()
{
replace(true);
}
void CSVTools::SearchSubView::replaceAllRequest()
{
replace(false);
}
void CSVTools::SearchSubView::tableSizeUpdate()
{
mBottom->tableSizeChanged(mDocument.getReport(getUniversalId())->rowCount(), 0, 0);
}
void CSVTools::SearchSubView::operationDone(int type, bool failed)
{
if (type == CSMDoc::State_Searching && !failed && !mDocument.getReport(getUniversalId())->rowCount())
{
mBottom->setStatusMessage("No Results");
}
}
| 4,852
|
C++
|
.cpp
| 116
| 37.232759
| 119
| 0.716905
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,063
|
merge.cpp
|
OpenMW_openmw/apps/opencs/view/tools/merge.cpp
|
#include "merge.hpp"
#include <QDialogButtonBox>
#include <QKeyEvent>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QSplitter>
#include <QVBoxLayout>
#include <components/files/qtconversion.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/doc/documentmanager.hpp"
#include "../../model/doc/state.hpp"
#include "../doc/adjusterwidget.hpp"
#include "../doc/filewidget.hpp"
void CSVTools::Merge::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Escape)
{
event->accept();
cancel();
}
else
QWidget::keyPressEvent(event);
}
CSVTools::Merge::Merge(CSMDoc::DocumentManager& documentManager, QWidget* parent)
: QWidget(parent)
, mDocument(nullptr)
, mDocumentManager(documentManager)
{
setWindowTitle("Merge Content Files into a new Game File");
QVBoxLayout* mainLayout = new QVBoxLayout;
setLayout(mainLayout);
QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
mainLayout->addWidget(splitter, 1);
// left panel (files to be merged)
QWidget* left = new QWidget(this);
left->setContentsMargins(0, 0, 0, 0);
splitter->addWidget(left);
QVBoxLayout* leftLayout = new QVBoxLayout;
left->setLayout(leftLayout);
leftLayout->addWidget(new QLabel("Files to be merged", this));
mFiles = new QListWidget(this);
leftLayout->addWidget(mFiles, 1);
// right panel (new game file)
QWidget* right = new QWidget(this);
right->setContentsMargins(0, 0, 0, 0);
splitter->addWidget(right);
QVBoxLayout* rightLayout = new QVBoxLayout;
rightLayout->setAlignment(Qt::AlignTop);
right->setLayout(rightLayout);
rightLayout->addWidget(new QLabel("New game file", this));
mNewFile = new CSVDoc::FileWidget(this);
mNewFile->setType(false);
mNewFile->extensionLabelIsVisible(true);
rightLayout->addWidget(mNewFile);
mAdjuster = new CSVDoc::AdjusterWidget(this);
rightLayout->addWidget(mAdjuster);
connect(mNewFile, &CSVDoc::FileWidget::nameChanged, mAdjuster, &CSVDoc::AdjusterWidget::setName);
connect(mAdjuster, &CSVDoc::AdjusterWidget::stateChanged, this, &Merge::stateChanged);
// buttons
QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Cancel, Qt::Horizontal, this);
connect(buttons->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &Merge::cancel);
mOkay = new QPushButton("Merge", this);
connect(mOkay, &QPushButton::clicked, this, &Merge::accept);
mOkay->setDefault(true);
buttons->addButton(mOkay, QDialogButtonBox::AcceptRole);
mainLayout->addWidget(buttons);
}
void CSVTools::Merge::configure(CSMDoc::Document* document)
{
mDocument = document;
mNewFile->setName("");
// content files
while (mFiles->count())
delete mFiles->takeItem(0);
std::vector<std::filesystem::path> files = document->getContentFiles();
for (std::vector<std::filesystem::path>::const_iterator iter(files.begin()); iter != files.end(); ++iter)
mFiles->addItem(Files::pathToQString(iter->filename()));
}
void CSVTools::Merge::setLocalData(const std::filesystem::path& localData)
{
mAdjuster->setLocalData(localData);
}
CSMDoc::Document* CSVTools::Merge::getDocument() const
{
return mDocument;
}
void CSVTools::Merge::cancel()
{
mDocument = nullptr;
hide();
}
void CSVTools::Merge::accept()
{
if ((mDocument->getState() & CSMDoc::State_Merging) == 0)
{
std::vector<std::filesystem::path> files{ mAdjuster->getPath() };
std::unique_ptr<CSMDoc::Document> target(mDocumentManager.makeDocument(files, files[0], true));
mDocument->runMerge(std::move(target));
hide();
}
}
void CSVTools::Merge::stateChanged(bool valid)
{
mOkay->setEnabled(valid);
}
| 3,833
|
C++
|
.cpp
| 106
| 31.896226
| 109
| 0.71022
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,064
|
completerpopup.cpp
|
OpenMW_openmw/apps/opencs/view/widget/completerpopup.cpp
|
#include "completerpopup.hpp"
CSVWidget::CompleterPopup::CompleterPopup(QWidget* parent)
: QListView(parent)
{
setEditTriggers(QAbstractItemView::NoEditTriggers);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
}
int CSVWidget::CompleterPopup::sizeHintForRow(int row) const
{
if (model() == nullptr)
{
return -1;
}
if (row < 0 || row >= model()->rowCount())
{
return -1;
}
ensurePolished();
QModelIndex index = model()->index(row, modelColumn());
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QStyleOptionViewItem option;
initViewItemOption(&option);
#else
QStyleOptionViewItem option = viewOptions();
#endif
QAbstractItemDelegate* delegate = itemDelegate(index);
return delegate->sizeHint(option, index).height();
}
| 919
|
C++
|
.cpp
| 30
| 26.6
| 60
| 0.724605
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,065
|
scenetoolshapebrush.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetoolshapebrush.cpp
|
#include "scenetoolshapebrush.hpp"
#include <QButtonGroup>
#include <QComboBox>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFrame>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QIcon>
#include <QLabel>
#include <QSizePolicy>
#include <QSlider>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QWidget>
#include <components/misc/scalableicon.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/view/widget/pushbutton.hpp>
#include "brushshapes.hpp"
#include "scenetool.hpp"
#include "../../model/prefs/state.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
namespace CSMDoc
{
class Document;
}
CSVWidget::ShapeBrushSizeControls::ShapeBrushSizeControls(const QString& title, QWidget* parent)
: QGroupBox(title, parent)
{
mBrushSizeSlider->setTickPosition(QSlider::TicksBothSides);
mBrushSizeSlider->setTickInterval(10);
mBrushSizeSlider->setRange(1, CSMPrefs::get()["3D Scene Editing"]["shapebrush-maximumsize"].toInt());
mBrushSizeSlider->setSingleStep(1);
mBrushSizeSpinBox->setRange(1, CSMPrefs::get()["3D Scene Editing"]["shapebrush-maximumsize"].toInt());
mBrushSizeSpinBox->setSingleStep(1);
QHBoxLayout* layoutSliderSize = new QHBoxLayout;
layoutSliderSize->addWidget(mBrushSizeSlider);
layoutSliderSize->addWidget(mBrushSizeSpinBox);
connect(mBrushSizeSlider, &QSlider::valueChanged, mBrushSizeSpinBox, &QSpinBox::setValue);
connect(mBrushSizeSpinBox, qOverload<int>(&QSpinBox::valueChanged), mBrushSizeSlider, &QSlider::setValue);
setLayout(layoutSliderSize);
}
CSVWidget::ShapeBrushWindow::ShapeBrushWindow(CSMDoc::Document& document, QWidget* parent)
: QFrame(parent, Qt::Popup)
, mDocument(document)
{
mButtonPoint = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-point"), "", this);
mButtonSquare = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-square"), "", this);
mButtonCircle = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-circle"), "", this);
mButtonCustom = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-custom"), "", this);
mSizeSliders = new ShapeBrushSizeControls("Brush size", this);
QVBoxLayout* layoutMain = new QVBoxLayout;
layoutMain->setSpacing(0);
layoutMain->setContentsMargins(4, 0, 4, 4);
QHBoxLayout* layoutHorizontal = new QHBoxLayout;
layoutHorizontal->setSpacing(0);
layoutHorizontal->setContentsMargins(QMargins(0, 0, 0, 0));
configureButtonInitialSettings(mButtonPoint);
configureButtonInitialSettings(mButtonSquare);
configureButtonInitialSettings(mButtonCircle);
configureButtonInitialSettings(mButtonCustom);
mButtonPoint->setToolTip(toolTipPoint);
mButtonSquare->setToolTip(toolTipSquare);
mButtonCircle->setToolTip(toolTipCircle);
mButtonCustom->setToolTip(toolTipCustom);
QButtonGroup* brushButtonGroup = new QButtonGroup(this);
brushButtonGroup->addButton(mButtonPoint);
brushButtonGroup->addButton(mButtonSquare);
brushButtonGroup->addButton(mButtonCircle);
brushButtonGroup->addButton(mButtonCustom);
brushButtonGroup->setExclusive(true);
layoutHorizontal->addWidget(mButtonPoint, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonSquare, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonCircle, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonCustom, 0, Qt::AlignTop);
mHorizontalGroupBox = new QGroupBox(tr(""));
mHorizontalGroupBox->setLayout(layoutHorizontal);
mToolSelector = new QComboBox(this);
mToolSelector->addItem(tr("Height (drag)"));
mToolSelector->addItem(tr("Height, raise (paint)"));
mToolSelector->addItem(tr("Height, lower (paint)"));
mToolSelector->addItem(tr("Smooth (paint)"));
mToolSelector->addItem(tr("Flatten (paint)"));
mToolSelector->addItem(tr("Equalize (paint)"));
QLabel* brushStrengthLabel = new QLabel(this);
brushStrengthLabel->setText("Brush strength:");
mToolStrengthSlider = new QSlider(Qt::Horizontal);
mToolStrengthSlider->setTickPosition(QSlider::TicksBothSides);
mToolStrengthSlider->setTickInterval(8);
mToolStrengthSlider->setRange(8, 128);
mToolStrengthSlider->setSingleStep(8);
mToolStrengthSlider->setValue(8);
layoutMain->addWidget(mHorizontalGroupBox);
layoutMain->addWidget(mSizeSliders);
layoutMain->addWidget(mToolSelector);
layoutMain->addWidget(brushStrengthLabel);
layoutMain->addWidget(mToolStrengthSlider);
setLayout(layoutMain);
connect(mButtonPoint, &QPushButton::clicked, this, &ShapeBrushWindow::setBrushShape);
connect(mButtonSquare, &QPushButton::clicked, this, &ShapeBrushWindow::setBrushShape);
connect(mButtonCircle, &QPushButton::clicked, this, &ShapeBrushWindow::setBrushShape);
connect(mButtonCustom, &QPushButton::clicked, this, &ShapeBrushWindow::setBrushShape);
}
void CSVWidget::ShapeBrushWindow::configureButtonInitialSettings(QPushButton* button)
{
button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
button->setContentsMargins(QMargins(0, 0, 0, 0));
button->setIconSize(QSize(48 - 6, 48 - 6));
button->setFixedSize(48, 48);
button->setCheckable(true);
}
void CSVWidget::ShapeBrushWindow::setBrushSize(int brushSize)
{
mBrushSize = brushSize;
emit passBrushSize(mBrushSize);
}
void CSVWidget::ShapeBrushWindow::setBrushShape()
{
if (mButtonPoint->isChecked())
mBrushShape = BrushShape_Point;
if (mButtonSquare->isChecked())
mBrushShape = BrushShape_Square;
if (mButtonCircle->isChecked())
mBrushShape = BrushShape_Circle;
if (mButtonCustom->isChecked())
mBrushShape = BrushShape_Custom;
emit passBrushShape(mBrushShape);
}
void CSVWidget::SceneToolShapeBrush::adjustToolTips() {}
CSVWidget::SceneToolShapeBrush::SceneToolShapeBrush(
SceneToolbar* parent, const QString& toolTip, CSMDoc::Document& document)
: SceneTool(parent, Type_TopAction)
, mToolTip(toolTip)
, mDocument(document)
, mShapeBrushWindow(new ShapeBrushWindow(document, this))
{
setAcceptDrops(true);
connect(mShapeBrushWindow, &ShapeBrushWindow::passBrushShape, this, &SceneToolShapeBrush::setButtonIcon);
setButtonIcon(mShapeBrushWindow->mBrushShape);
mPanel = new QFrame(this, Qt::Popup);
QHBoxLayout* layout = new QHBoxLayout(mPanel);
layout->setContentsMargins(QMargins(0, 0, 0, 0));
mTable = new QTableWidget(0, 2, this);
mTable->setShowGrid(true);
mTable->verticalHeader()->hide();
mTable->horizontalHeader()->hide();
mTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
mTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
mTable->setSelectionMode(QAbstractItemView::NoSelection);
layout->addWidget(mTable);
connect(mTable, &QTableWidget::clicked, this, &SceneToolShapeBrush::clicked);
}
void CSVWidget::SceneToolShapeBrush::setButtonIcon(CSVWidget::BrushShape brushShape)
{
QString tooltip = "Change brush settings <p>Currently selected: ";
switch (brushShape)
{
case BrushShape_Point:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-point"));
tooltip += mShapeBrushWindow->toolTipPoint;
break;
case BrushShape_Square:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-square"));
tooltip += mShapeBrushWindow->toolTipSquare;
break;
case BrushShape_Circle:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-circle"));
tooltip += mShapeBrushWindow->toolTipCircle;
break;
case BrushShape_Custom:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-custom"));
tooltip += mShapeBrushWindow->toolTipCustom;
break;
}
setToolTip(tooltip);
}
void CSVWidget::SceneToolShapeBrush::showPanel(const QPoint& position) {}
void CSVWidget::SceneToolShapeBrush::updatePanel() {}
void CSVWidget::SceneToolShapeBrush::clicked(const QModelIndex& index) {}
void CSVWidget::SceneToolShapeBrush::activate()
{
QPoint position = QCursor::pos();
mShapeBrushWindow->mSizeSliders->mBrushSizeSlider->setRange(
1, CSMPrefs::get()["3D Scene Editing"]["shapebrush-maximumsize"].toInt());
mShapeBrushWindow->mSizeSliders->mBrushSizeSpinBox->setRange(
1, CSMPrefs::get()["3D Scene Editing"]["shapebrush-maximumsize"].toInt());
mShapeBrushWindow->move(position);
mShapeBrushWindow->show();
}
void CSVWidget::SceneToolShapeBrush::dragEnterEvent(QDragEnterEvent* event)
{
emit passEvent(event);
event->accept();
}
void CSVWidget::SceneToolShapeBrush::dropEvent(QDropEvent* event)
{
emit passEvent(event);
event->accept();
}
| 8,919
|
C++
|
.cpp
| 204
| 39.019608
| 110
| 0.75127
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,066
|
droplineedit.cpp
|
OpenMW_openmw/apps/opencs/view/widget/droplineedit.cpp
|
#include "droplineedit.hpp"
#include <string>
#include <QDropEvent>
#include "../../model/world/tablemimedata.hpp"
#include "../../model/world/universalid.hpp"
#include <apps/opencs/model/world/columnbase.hpp>
#include "../world/dragdroputils.hpp"
CSVWidget::DropLineEdit::DropLineEdit(CSMWorld::ColumnBase::Display type, QWidget* parent)
: QLineEdit(parent)
, mDropType(type)
{
setAcceptDrops(true);
}
void CSVWidget::DropLineEdit::dragEnterEvent(QDragEnterEvent* event)
{
if (CSVWorld::DragDropUtils::canAcceptData(*event, mDropType))
{
event->acceptProposedAction();
}
}
void CSVWidget::DropLineEdit::dragMoveEvent(QDragMoveEvent* event)
{
if (CSVWorld::DragDropUtils::canAcceptData(*event, mDropType))
{
event->accept();
}
}
void CSVWidget::DropLineEdit::dropEvent(QDropEvent* event)
{
if (CSVWorld::DragDropUtils::canAcceptData(*event, mDropType))
{
CSMWorld::UniversalId id = CSVWorld::DragDropUtils::getAcceptedData(*event, mDropType);
setText(QString::fromUtf8(id.getId().c_str()));
emit tableMimeDataDropped(id, CSVWorld::DragDropUtils::getTableMimeData(*event)->getDocumentPtr());
}
}
| 1,192
|
C++
|
.cpp
| 36
| 29.416667
| 107
| 0.734089
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,067
|
pushbutton.cpp
|
OpenMW_openmw/apps/opencs/view/widget/pushbutton.cpp
|
#include "pushbutton.hpp"
#include <QKeyEvent>
#include <QMouseEvent>
#include <string>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include "../../model/prefs/shortcutmanager.hpp"
#include "../../model/prefs/state.hpp"
void CSVWidget::PushButton::processShortcuts()
{
mProcessedToolTip = CSMPrefs::State::get().getShortcutManager().processToolTip(mToolTip);
}
void CSVWidget::PushButton::setExtendedToolTip()
{
QString tooltip = mProcessedToolTip;
if (tooltip.isEmpty())
tooltip = "(Tool tip not implemented yet)";
switch (mType)
{
case Type_TopMode:
tooltip += "<p>(left click to change mode)";
break;
case Type_TopAction:
break;
case Type_Mode:
tooltip +=
"<p>(left click to activate,"
"<br>shift-left click to activate and keep panel open)";
break;
case Type_Toggle:
tooltip += "<p>(left click to ";
tooltip += isChecked() ? "disable" : "enable";
tooltip += "<p>shift-left click to ";
tooltip += isChecked() ? "disable" : "enable";
tooltip += " and keep panel open)";
break;
}
setToolTip(tooltip);
}
void CSVWidget::PushButton::keyPressEvent(QKeyEvent* event)
{
if (event->key() != Qt::Key_Shift)
mKeepOpen = false;
QPushButton::keyPressEvent(event);
}
void CSVWidget::PushButton::keyReleaseEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Space)
mKeepOpen = event->modifiers() & Qt::ShiftModifier;
QPushButton::keyReleaseEvent(event);
}
void CSVWidget::PushButton::mouseReleaseEvent(QMouseEvent* event)
{
mKeepOpen = event->button() == Qt::LeftButton && (event->modifiers() & Qt::ShiftModifier);
QPushButton::mouseReleaseEvent(event);
}
CSVWidget::PushButton::PushButton(const QIcon& icon, Type type, const QString& tooltip, QWidget* parent)
: QPushButton(icon, "", parent)
, mKeepOpen(false)
, mType(type)
, mToolTip(tooltip)
{
if (type == Type_Mode || type == Type_Toggle)
{
setCheckable(true);
connect(this, &PushButton::toggled, this, &PushButton::checkedStateChanged);
}
setCheckable(type == Type_Mode || type == Type_Toggle);
processShortcuts();
setExtendedToolTip();
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &PushButton::settingChanged);
}
CSVWidget::PushButton::PushButton(Type type, const QString& tooltip, QWidget* parent)
: QPushButton(parent)
, mKeepOpen(false)
, mType(type)
, mToolTip(tooltip)
{
setCheckable(type == Type_Mode || type == Type_Toggle);
processShortcuts();
setExtendedToolTip();
}
bool CSVWidget::PushButton::hasKeepOpen() const
{
return mKeepOpen;
}
QString CSVWidget::PushButton::getBaseToolTip() const
{
return mProcessedToolTip;
}
CSVWidget::PushButton::Type CSVWidget::PushButton::getType() const
{
return mType;
}
void CSVWidget::PushButton::checkedStateChanged(bool checked)
{
setExtendedToolTip();
}
void CSVWidget::PushButton::settingChanged(const CSMPrefs::Setting* setting)
{
if (setting->getParent()->getKey() == "Key Bindings")
{
processShortcuts();
setExtendedToolTip();
}
}
| 3,347
|
C++
|
.cpp
| 106
| 26.462264
| 106
| 0.669679
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,068
|
scenetooltoggle2.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetooltoggle2.cpp
|
#include "scenetooltoggle2.hpp"
#include <sstream>
#include <type_traits>
#include <utility>
#include <QFrame>
#include <QHBoxLayout>
#include <QIcon>
#include <apps/opencs/view/widget/scenetool.hpp>
#include <components/misc/scalableicon.hpp>
#include "pushbutton.hpp"
#include "scenetoolbar.hpp"
void CSVWidget::SceneToolToggle2::adjustToolTip()
{
QString toolTip = mToolTip;
toolTip += "<p>Currently enabled: ";
bool first = true;
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
if (iter->first->isChecked())
{
if (!first)
toolTip += ", ";
else
first = false;
toolTip += iter->second.mName;
}
if (first)
toolTip += "none";
toolTip += "<p>(left click to alter selection)";
setToolTip(toolTip);
}
void CSVWidget::SceneToolToggle2::adjustIcon()
{
unsigned int buttonIds = 0;
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
if (iter->first->isChecked())
buttonIds |= iter->second.mButtonId;
std::ostringstream stream;
stream << mCompositeIcon << buttonIds;
setIcon(Misc::ScalableIcon::load(QString::fromUtf8(stream.str().c_str())));
}
CSVWidget::SceneToolToggle2::SceneToolToggle2(
SceneToolbar* parent, const QString& toolTip, const std::string& compositeIcon, const std::string& singleIcon)
: SceneTool(parent)
, mCompositeIcon(compositeIcon)
, mSingleIcon(singleIcon)
, mButtonSize(parent->getButtonSize())
, mIconSize(parent->getIconSize())
, mToolTip(toolTip)
, mFirst(nullptr)
{
mPanel = new QFrame(this, Qt::Popup);
mLayout = new QHBoxLayout(mPanel);
mLayout->setContentsMargins(QMargins(0, 0, 0, 0));
mPanel->setLayout(mLayout);
}
void CSVWidget::SceneToolToggle2::showPanel(const QPoint& position)
{
mPanel->move(position);
mPanel->show();
if (mFirst)
mFirst->setFocus(Qt::OtherFocusReason);
}
void CSVWidget::SceneToolToggle2::addButton(
unsigned int id, unsigned int mask, const QString& name, const QString& tooltip, bool disabled)
{
std::ostringstream stream;
stream << mSingleIcon << id;
PushButton* button = new PushButton(Misc::ScalableIcon::load(stream.str().c_str()), PushButton::Type_Toggle,
tooltip.isEmpty() ? name : tooltip, mPanel);
button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
button->setIconSize(QSize(mIconSize, mIconSize));
button->setFixedSize(mButtonSize, mButtonSize);
if (disabled)
button->setDisabled(true);
mLayout->addWidget(button);
ButtonDesc desc;
desc.mButtonId = id;
desc.mMask = mask;
desc.mName = name;
desc.mIndex = static_cast<int>(mButtons.size());
mButtons.insert(std::make_pair(button, desc));
connect(button, &QPushButton::clicked, this, &SceneToolToggle2::selected);
if (mButtons.size() == 1 && !disabled)
mFirst = button;
}
unsigned int CSVWidget::SceneToolToggle2::getSelectionMask() const
{
unsigned int selection = 0;
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
if (iter->first->isChecked())
selection |= iter->second.mMask;
return selection;
}
void CSVWidget::SceneToolToggle2::setSelectionMask(unsigned int selection)
{
for (std::map<PushButton*, ButtonDesc>::iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
iter->first->setChecked(selection & iter->second.mMask);
adjustToolTip();
adjustIcon();
}
void CSVWidget::SceneToolToggle2::selected()
{
std::map<PushButton*, ButtonDesc>::const_iterator iter = mButtons.find(dynamic_cast<PushButton*>(sender()));
if (iter != mButtons.end())
{
if (!iter->first->hasKeepOpen())
mPanel->hide();
adjustToolTip();
adjustIcon();
emit selectionChanged();
}
}
| 4,067
|
C++
|
.cpp
| 112
| 31.026786
| 114
| 0.68046
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,069
|
scenetoolrun.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetoolrun.cpp
|
#include "scenetoolrun.hpp"
#include <iterator>
#include <QApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QTableWidget>
#include <components/misc/scalableicon.hpp>
#include <apps/opencs/view/widget/pushbutton.hpp>
#include <apps/opencs/view/widget/scenetool.hpp>
class QPoint;
namespace CSVWidget
{
class SceneToolbar;
}
void CSVWidget::SceneToolRun::adjustToolTips()
{
QString toolTip = mToolTip;
if (mSelected == mProfiles.end())
toolTip += "<p>No debug profile selected (function disabled)";
else
{
toolTip += "<p>Debug profile: " + QString::fromUtf8(mSelected->c_str());
toolTip += "<p>(right click to switch to a different profile)";
}
setToolTip(toolTip);
}
void CSVWidget::SceneToolRun::updateIcon()
{
setDisabled(mSelected == mProfiles.end());
}
void CSVWidget::SceneToolRun::updatePanel()
{
mTable->setRowCount(static_cast<int>(mProfiles.size()));
int i = 0;
for (std::set<std::string>::const_iterator iter(mProfiles.begin()); iter != mProfiles.end(); ++iter, ++i)
{
mTable->setItem(i, 0, new QTableWidgetItem(QString::fromUtf8(iter->c_str())));
mTable->setItem(
i, 1, new QTableWidgetItem(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton), ""));
}
}
CSVWidget::SceneToolRun::SceneToolRun(
SceneToolbar* parent, const QString& toolTip, const QString& icon, const std::vector<std::string>& profiles)
: SceneTool(parent, Type_TopAction)
, mProfiles(profiles.begin(), profiles.end())
, mSelected(mProfiles.begin())
, mToolTip(toolTip)
{
setIcon(Misc::ScalableIcon::load(icon));
updateIcon();
adjustToolTips();
mPanel = new QFrame(this, Qt::Popup);
QHBoxLayout* layout = new QHBoxLayout(mPanel);
layout->setContentsMargins(QMargins(0, 0, 0, 0));
mTable = new QTableWidget(0, 2, this);
mTable->setShowGrid(false);
mTable->verticalHeader()->hide();
mTable->horizontalHeader()->hide();
mTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
mTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
mTable->setSelectionMode(QAbstractItemView::NoSelection);
layout->addWidget(mTable);
connect(mTable, &QTableWidget::clicked, this, &SceneToolRun::clicked);
}
void CSVWidget::SceneToolRun::showPanel(const QPoint& position)
{
updatePanel();
mPanel->move(position);
mPanel->show();
}
void CSVWidget::SceneToolRun::activate()
{
if (mSelected != mProfiles.end())
emit runRequest(*mSelected);
}
void CSVWidget::SceneToolRun::removeProfile(const std::string& profile)
{
std::set<std::string>::iterator iter = mProfiles.find(profile);
if (iter != mProfiles.end())
{
if (iter == mSelected)
{
if (iter != mProfiles.begin())
--mSelected;
else
++mSelected;
}
mProfiles.erase(iter);
if (mSelected == mProfiles.end())
updateIcon();
adjustToolTips();
}
}
void CSVWidget::SceneToolRun::addProfile(const std::string& profile)
{
std::set<std::string>::iterator iter = mProfiles.find(profile);
if (iter == mProfiles.end())
{
mProfiles.insert(profile);
if (mSelected == mProfiles.end())
{
mSelected = mProfiles.begin();
updateIcon();
}
adjustToolTips();
}
}
void CSVWidget::SceneToolRun::clicked(const QModelIndex& index)
{
if (index.column() == 0)
{
// select profile
mSelected = mProfiles.begin();
std::advance(mSelected, index.row());
mPanel->hide();
adjustToolTips();
}
else if (index.column() == 1)
{
// remove profile from list
std::set<std::string>::iterator iter = mProfiles.begin();
std::advance(iter, index.row());
removeProfile(*iter);
updatePanel();
}
}
| 4,010
|
C++
|
.cpp
| 127
| 26.173228
| 113
| 0.659304
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,070
|
scenetool.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetool.cpp
|
#include "scenetool.hpp"
#include <QMouseEvent>
#include <apps/opencs/view/widget/pushbutton.hpp>
#include "scenetoolbar.hpp"
CSVWidget::SceneTool::SceneTool(SceneToolbar* parent, Type type)
: PushButton(type, "", parent)
{
setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
setIconSize(QSize(parent->getIconSize(), parent->getIconSize()));
setFixedSize(parent->getButtonSize(), parent->getButtonSize());
connect(this, &SceneTool::clicked, this, &SceneTool::openRequest);
}
void CSVWidget::SceneTool::activate() {}
void CSVWidget::SceneTool::mouseReleaseEvent(QMouseEvent* event)
{
if (getType() == Type_TopAction && event->button() == Qt::RightButton)
showPanel(parentWidget()->mapToGlobal(pos()));
else
PushButton::mouseReleaseEvent(event);
}
void CSVWidget::SceneTool::openRequest()
{
if (getType() == Type_TopAction)
activate();
else
showPanel(parentWidget()->mapToGlobal(pos()));
}
| 980
|
C++
|
.cpp
| 27
| 32.481481
| 74
| 0.722751
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,071
|
scenetoolmode.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetoolmode.cpp
|
#include "scenetoolmode.hpp"
#include <QContextMenuEvent>
#include <QEvent>
#include <QFrame>
#include <QHBoxLayout>
#include <QIcon>
#include <QMenu>
#include <apps/opencs/view/widget/pushbutton.hpp>
#include <apps/opencs/view/widget/scenetool.hpp>
#include <components/misc/scalableicon.hpp>
#include <type_traits>
#include <utility>
#include "modebutton.hpp"
#include "scenetoolbar.hpp"
void CSVWidget::SceneToolMode::contextMenuEvent(QContextMenuEvent* event)
{
QMenu menu(this);
if (createContextMenu(&menu))
menu.exec(event->globalPos());
}
bool CSVWidget::SceneToolMode::createContextMenu(QMenu* menu)
{
if (mCurrent)
return mCurrent->createContextMenu(menu);
return false;
}
void CSVWidget::SceneToolMode::adjustToolTip(const ModeButton* activeMode)
{
QString toolTip = mToolTip;
toolTip += "<p>Currently selected: " + activeMode->getBaseToolTip();
toolTip += "<p>(left click to change mode)";
if (createContextMenu(nullptr))
toolTip += "<br>(right click to access context menu)";
setToolTip(toolTip);
}
void CSVWidget::SceneToolMode::setButton(std::map<ModeButton*, std::string>::iterator iter)
{
for (std::map<ModeButton*, std::string>::const_iterator iter2 = mButtons.begin(); iter2 != mButtons.end(); ++iter2)
iter2->first->setChecked(iter2 == iter);
setIcon(iter->first->icon());
adjustToolTip(iter->first);
if (mCurrent != iter->first)
{
if (mCurrent)
mCurrent->deactivate(mToolbar);
mCurrent = iter->first;
mCurrent->activate(mToolbar);
}
emit modeChanged(iter->second);
}
CSVWidget::SceneToolMode::SceneToolMode(SceneToolbar* parent, const QString& toolTip)
: SceneTool(parent)
, mButtonSize(parent->getButtonSize())
, mIconSize(parent->getIconSize())
, mToolTip(toolTip)
, mFirst(nullptr)
, mCurrent(nullptr)
, mToolbar(parent)
{
mPanel = new QFrame(this, Qt::Popup);
mLayout = new QHBoxLayout(mPanel);
mLayout->setContentsMargins(QMargins(0, 0, 0, 0));
mPanel->setLayout(mLayout);
}
void CSVWidget::SceneToolMode::showPanel(const QPoint& position)
{
mPanel->move(position);
mPanel->show();
if (mFirst)
mFirst->setFocus(Qt::OtherFocusReason);
}
void CSVWidget::SceneToolMode::addButton(const std::string& icon, const std::string& id, const QString& tooltip)
{
ModeButton* button = new ModeButton(Misc::ScalableIcon::load(icon.c_str()), tooltip, mPanel);
addButton(button, id);
}
void CSVWidget::SceneToolMode::addButton(ModeButton* button, const std::string& id)
{
button->setParent(mPanel);
button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
button->setIconSize(QSize(mIconSize, mIconSize));
button->setFixedSize(mButtonSize, mButtonSize);
mLayout->addWidget(button);
mButtons.insert(std::make_pair(button, id));
connect(button, &ModeButton::clicked, this, &SceneToolMode::selected);
if (mButtons.size() == 1)
{
mFirst = mCurrent = button;
setIcon(button->icon());
button->setChecked(true);
adjustToolTip(button);
mCurrent->activate(mToolbar);
}
}
CSVWidget::ModeButton* CSVWidget::SceneToolMode::getCurrent()
{
return mCurrent;
}
std::string CSVWidget::SceneToolMode::getCurrentId() const
{
auto currentButton = mButtons.find(mCurrent);
assert(currentButton != mButtons.end());
return currentButton->second;
}
void CSVWidget::SceneToolMode::setButton(const std::string& id)
{
for (std::map<ModeButton*, std::string>::iterator iter = mButtons.begin(); iter != mButtons.end(); ++iter)
if (iter->second == id)
{
setButton(iter);
break;
}
}
bool CSVWidget::SceneToolMode::event(QEvent* event)
{
if (event->type() == QEvent::ToolTip)
{
adjustToolTip(mCurrent);
}
return SceneTool::event(event);
}
void CSVWidget::SceneToolMode::selected()
{
std::map<ModeButton*, std::string>::iterator iter = mButtons.find(dynamic_cast<ModeButton*>(sender()));
if (iter != mButtons.end())
{
if (!iter->first->hasKeepOpen())
mPanel->hide();
setButton(iter);
}
}
| 4,243
|
C++
|
.cpp
| 131
| 27.885496
| 119
| 0.69482
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,072
|
scenetooltexturebrush.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetooltexturebrush.cpp
|
#include "scenetooltexturebrush.hpp"
#include <QButtonGroup>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFrame>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QIcon>
#include <QLabel>
#include <QMargins>
#include <QModelIndex>
#include <QSizePolicy>
#include <QSlider>
#include <QSpinBox>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QWidget>
#include <algorithm>
#include <limits>
#include <memory>
#include "scenetool.hpp"
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/commandmacro.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/view/widget/brushshapes.hpp>
#include <apps/opencs/view/widget/pushbutton.hpp>
#include <components/misc/scalableicon.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idcollection.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/universalid.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
CSVWidget::BrushSizeControls::BrushSizeControls(const QString& title, QWidget* parent)
: QGroupBox(title, parent)
, mLayoutSliderSize(new QHBoxLayout)
, mBrushSizeSlider(new QSlider(Qt::Horizontal))
, mBrushSizeSpinBox(new QSpinBox)
{
mBrushSizeSlider->setTickPosition(QSlider::TicksBothSides);
mBrushSizeSlider->setTickInterval(10);
mBrushSizeSlider->setRange(1, CSMPrefs::get()["3D Scene Editing"]["texturebrush-maximumsize"].toInt());
mBrushSizeSlider->setSingleStep(1);
mBrushSizeSpinBox->setRange(1, CSMPrefs::get()["3D Scene Editing"]["texturebrush-maximumsize"].toInt());
mBrushSizeSpinBox->setSingleStep(1);
mLayoutSliderSize->addWidget(mBrushSizeSlider);
mLayoutSliderSize->addWidget(mBrushSizeSpinBox);
connect(mBrushSizeSlider, &QSlider::valueChanged, mBrushSizeSpinBox, &QSpinBox::setValue);
connect(mBrushSizeSpinBox, qOverload<int>(&QSpinBox::valueChanged), mBrushSizeSlider, &QSlider::setValue);
setLayout(mLayoutSliderSize);
}
CSVWidget::TextureBrushWindow::TextureBrushWindow(CSMDoc::Document& document, QWidget* parent)
: QFrame(parent, Qt::Popup)
, mDocument(document)
{
mBrushTextureLabel = "Selected texture: " + mBrushTexture.getRefIdString() + " ";
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = mDocument.getData().getLandTextures();
int landTextureFilename = landtexturesCollection.findColumnIndex(CSMWorld::Columns::ColumnId_Texture);
const int index = landtexturesCollection.searchId(mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted())
{
mSelectedBrush = new QLabel(QString::fromStdString(mBrushTextureLabel)
+ landtexturesCollection.getData(index, landTextureFilename).value<QString>());
}
else
{
mBrushTextureLabel = "No selected texture or invalid texture";
mSelectedBrush = new QLabel(QString::fromStdString(mBrushTextureLabel));
}
mButtonPoint = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-point"), "", this);
mButtonSquare = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-square"), "", this);
mButtonCircle = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-circle"), "", this);
mButtonCustom = new QPushButton(Misc::ScalableIcon::load(":scenetoolbar/brush-custom"), "", this);
mSizeSliders = new BrushSizeControls("Brush size", this);
QVBoxLayout* layoutMain = new QVBoxLayout;
layoutMain->setSpacing(0);
layoutMain->setContentsMargins(4, 0, 4, 4);
QHBoxLayout* layoutHorizontal = new QHBoxLayout;
layoutHorizontal->setSpacing(0);
layoutHorizontal->setContentsMargins(QMargins(0, 0, 0, 0));
configureButtonInitialSettings(mButtonPoint);
configureButtonInitialSettings(mButtonSquare);
configureButtonInitialSettings(mButtonCircle);
configureButtonInitialSettings(mButtonCustom);
mButtonPoint->setToolTip(toolTipPoint);
mButtonSquare->setToolTip(toolTipSquare);
mButtonCircle->setToolTip(toolTipCircle);
mButtonCustom->setToolTip(toolTipCustom);
QButtonGroup* brushButtonGroup = new QButtonGroup(this);
brushButtonGroup->addButton(mButtonPoint);
brushButtonGroup->addButton(mButtonSquare);
brushButtonGroup->addButton(mButtonCircle);
brushButtonGroup->addButton(mButtonCustom);
brushButtonGroup->setExclusive(true);
layoutHorizontal->addWidget(mButtonPoint, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonSquare, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonCircle, 0, Qt::AlignTop);
layoutHorizontal->addWidget(mButtonCustom, 0, Qt::AlignTop);
mHorizontalGroupBox = new QGroupBox(tr(""));
mHorizontalGroupBox->setLayout(layoutHorizontal);
layoutMain->addWidget(mHorizontalGroupBox);
layoutMain->addWidget(mSizeSliders);
layoutMain->addWidget(mSelectedBrush);
setLayout(layoutMain);
connect(mButtonPoint, &QPushButton::clicked, this, &TextureBrushWindow::setBrushShape);
connect(mButtonSquare, &QPushButton::clicked, this, &TextureBrushWindow::setBrushShape);
connect(mButtonCircle, &QPushButton::clicked, this, &TextureBrushWindow::setBrushShape);
connect(mButtonCustom, &QPushButton::clicked, this, &TextureBrushWindow::setBrushShape);
}
void CSVWidget::TextureBrushWindow::configureButtonInitialSettings(QPushButton* button)
{
button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
button->setContentsMargins(QMargins(0, 0, 0, 0));
button->setIconSize(QSize(48 - 6, 48 - 6));
button->setFixedSize(48, 48);
button->setCheckable(true);
}
void CSVWidget::TextureBrushWindow::setBrushTexture(ESM::RefId brushTexture)
{
CSMWorld::IdTable& ltexTable = dynamic_cast<CSMWorld::IdTable&>(
*mDocument.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
QUndoStack& undoStack = mDocument.getUndoStack();
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = mDocument.getData().getLandTextures();
int landTextureFilename = landtexturesCollection.findColumnIndex(CSMWorld::Columns::ColumnId_Texture);
int row = landtexturesCollection.getIndex(brushTexture);
const auto& record = landtexturesCollection.getRecord(row);
if (!record.isDeleted())
{
// Ensure the texture is defined by the current plugin
if (!record.isModified())
{
CSMWorld::CommandMacro macro(undoStack);
macro.push(new CSMWorld::TouchCommand(ltexTable, brushTexture.getRefIdString()));
}
mBrushTextureLabel = "Selected texture: " + brushTexture.getRefIdString() + " ";
mSelectedBrush->setText(QString::fromStdString(mBrushTextureLabel)
+ landtexturesCollection.getData(row, landTextureFilename).value<QString>());
}
else
{
brushTexture = {};
mBrushTextureLabel = "No selected texture or invalid texture";
mSelectedBrush->setText(QString::fromStdString(mBrushTextureLabel));
}
mBrushTexture = brushTexture;
emit passTextureId(mBrushTexture);
emit passBrushShape(mBrushShape); // updates the icon tooltip
}
void CSVWidget::TextureBrushWindow::setBrushSize(int brushSize)
{
mBrushSize = brushSize;
emit passBrushSize(mBrushSize);
}
void CSVWidget::TextureBrushWindow::setBrushShape()
{
if (mButtonPoint->isChecked())
mBrushShape = CSVWidget::BrushShape_Point;
if (mButtonSquare->isChecked())
mBrushShape = CSVWidget::BrushShape_Square;
if (mButtonCircle->isChecked())
mBrushShape = CSVWidget::BrushShape_Circle;
if (mButtonCustom->isChecked())
mBrushShape = CSVWidget::BrushShape_Custom;
emit passBrushShape(mBrushShape);
}
void CSVWidget::SceneToolTextureBrush::adjustToolTips() {}
CSVWidget::SceneToolTextureBrush::SceneToolTextureBrush(
SceneToolbar* parent, const QString& toolTip, CSMDoc::Document& document)
: SceneTool(parent, Type_TopAction)
, mToolTip(toolTip)
, mDocument(document)
, mTextureBrushWindow(new TextureBrushWindow(document, this))
{
mBrushHistory.resize(1);
setAcceptDrops(true);
connect(mTextureBrushWindow, &TextureBrushWindow::passBrushShape, this, &SceneToolTextureBrush::setButtonIcon);
setButtonIcon(mTextureBrushWindow->mBrushShape);
mPanel = new QFrame(this, Qt::Popup);
QHBoxLayout* layout = new QHBoxLayout(mPanel);
layout->setContentsMargins(QMargins(0, 0, 0, 0));
mTable = new QTableWidget(0, 2, this);
mTable->setShowGrid(true);
mTable->verticalHeader()->hide();
mTable->horizontalHeader()->hide();
mTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
mTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
mTable->setSelectionMode(QAbstractItemView::NoSelection);
layout->addWidget(mTable);
connect(mTable, &QTableWidget::clicked, this, &SceneToolTextureBrush::clicked);
}
void CSVWidget::SceneToolTextureBrush::setButtonIcon(CSVWidget::BrushShape brushShape)
{
QString tooltip = "Change brush settings <p>Currently selected: ";
switch (brushShape)
{
case BrushShape_Point:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-point"));
tooltip += mTextureBrushWindow->toolTipPoint;
break;
case BrushShape_Square:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-square"));
tooltip += mTextureBrushWindow->toolTipSquare;
break;
case BrushShape_Circle:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-circle"));
tooltip += mTextureBrushWindow->toolTipCircle;
break;
case BrushShape_Custom:
setIcon(Misc::ScalableIcon::load(":scenetoolbar/brush-custom"));
tooltip += mTextureBrushWindow->toolTipCustom;
break;
}
tooltip += "<p>(right click to access of previously used brush settings)";
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = mDocument.getData().getLandTextures();
int landTextureFilename = landtexturesCollection.findColumnIndex(CSMWorld::Columns::ColumnId_Texture);
const int index = landtexturesCollection.searchId(mTextureBrushWindow->mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted())
{
tooltip += "<p>Selected texture: " + QString::fromStdString(mTextureBrushWindow->mBrushTexture.getRefIdString())
+ " ";
tooltip += landtexturesCollection.getData(index, landTextureFilename).value<QString>();
}
else
{
tooltip += "<p>No selected texture or invalid texture";
}
tooltip += "<br>(drop texture here to change)";
setToolTip(tooltip);
}
void CSVWidget::SceneToolTextureBrush::showPanel(const QPoint& position)
{
updatePanel();
mPanel->move(position);
mPanel->show();
}
void CSVWidget::SceneToolTextureBrush::updatePanel()
{
mTable->setRowCount(mBrushHistory.size());
for (int i = mBrushHistory.size() - 1; i >= 0; --i)
{
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = mDocument.getData().getLandTextures();
int landTextureFilename = landtexturesCollection.findColumnIndex(CSMWorld::Columns::ColumnId_Texture);
const int index = landtexturesCollection.searchId(mBrushHistory[i]);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted())
{
mTable->setItem(i, 1,
new QTableWidgetItem(landtexturesCollection.getData(index, landTextureFilename).value<QString>()));
mTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i].getRefIdString())));
}
else
{
mTable->setItem(i, 1, new QTableWidgetItem("Invalid/deleted texture"));
mTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(mBrushHistory[i].getRefIdString())));
}
}
}
void CSVWidget::SceneToolTextureBrush::updateBrushHistory(ESM::RefId brushTexture)
{
mBrushHistory.insert(mBrushHistory.begin(), brushTexture);
if (mBrushHistory.size() > 5)
mBrushHistory.pop_back();
}
void CSVWidget::SceneToolTextureBrush::clicked(const QModelIndex& index)
{
if (index.column() == 0 || index.column() == 1)
{
ESM::RefId brushTexture = mBrushHistory[index.row()];
std::swap(mBrushHistory[index.row()], mBrushHistory[0]);
mTextureBrushWindow->setBrushTexture(brushTexture);
emit passTextureId(brushTexture);
updatePanel();
mPanel->hide();
}
}
void CSVWidget::SceneToolTextureBrush::activate()
{
QPoint position = QCursor::pos();
mTextureBrushWindow->mSizeSliders->mBrushSizeSlider->setRange(
1, CSMPrefs::get()["3D Scene Editing"]["texturebrush-maximumsize"].toInt());
mTextureBrushWindow->mSizeSliders->mBrushSizeSpinBox->setRange(
1, CSMPrefs::get()["3D Scene Editing"]["texturebrush-maximumsize"].toInt());
mTextureBrushWindow->move(position);
mTextureBrushWindow->show();
}
void CSVWidget::SceneToolTextureBrush::dragEnterEvent(QDragEnterEvent* event)
{
emit passEvent(event);
event->accept();
}
void CSVWidget::SceneToolTextureBrush::dropEvent(QDropEvent* event)
{
emit passEvent(event);
event->accept();
}
| 13,613
|
C++
|
.cpp
| 302
| 39.827815
| 120
| 0.737538
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,073
|
modebutton.cpp
|
OpenMW_openmw/apps/opencs/view/widget/modebutton.cpp
|
#include "modebutton.hpp"
#include <apps/opencs/view/widget/pushbutton.hpp>
class QWidget;
CSVWidget::ModeButton::ModeButton(const QIcon& icon, const QString& tooltip, QWidget* parent)
: PushButton(icon, Type_Mode, tooltip, parent)
{
}
void CSVWidget::ModeButton::activate(SceneToolbar* toolbar) {}
void CSVWidget::ModeButton::deactivate(SceneToolbar* toolbar) {}
bool CSVWidget::ModeButton::createContextMenu(QMenu* menu)
{
return false;
}
| 455
|
C++
|
.cpp
| 13
| 32.923077
| 93
| 0.788991
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,074
|
scenetooltoggle.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetooltoggle.cpp
|
#include "scenetooltoggle.hpp"
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <QFrame>
#include <QHBoxLayout>
#include <QIcon>
#include <QPainter>
#include <apps/opencs/view/widget/scenetool.hpp>
#include "pushbutton.hpp"
#include "scenetoolbar.hpp"
void CSVWidget::SceneToolToggle::adjustToolTip()
{
QString toolTip = mToolTip;
toolTip += "<p>Currently enabled: ";
bool first = true;
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
if (iter->first->isChecked())
{
if (!first)
toolTip += ", ";
else
first = false;
toolTip += iter->second.mName;
}
if (first)
toolTip += "none";
toolTip += "<p>(left click to alter selection)";
setToolTip(toolTip);
}
void CSVWidget::SceneToolToggle::adjustIcon()
{
unsigned int selection = getSelectionMask();
if (!selection)
setIcon(QIcon(QString::fromUtf8(mEmptyIcon.c_str())));
else
{
QPixmap pixmap(48, 48);
pixmap.fill(QColor(0, 0, 0, 0));
{
QPainter painter(&pixmap);
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end();
++iter)
if (iter->first->isChecked())
{
painter.drawImage(
getIconBox(iter->second.mIndex), QImage(QString::fromUtf8(iter->second.mSmallIcon.c_str())));
}
}
setIcon(pixmap);
}
}
QRect CSVWidget::SceneToolToggle::getIconBox(int index) const
{
// layout for a 3x3 grid
int xMax = 3;
int yMax = 3;
// icon size
int xBorder = 1;
int yBorder = 1;
int iconXSize = (mIconSize - xBorder * (xMax + 1)) / xMax;
int iconYSize = (mIconSize - yBorder * (yMax + 1)) / yMax;
int y = index / xMax;
int x = index % xMax;
int total = static_cast<int>(mButtons.size());
int actualYIcons = total / xMax;
if (total % xMax)
++actualYIcons;
if (actualYIcons != yMax)
{
// space out icons vertically, if there aren't enough to populate all rows
int diff = yMax - actualYIcons;
yBorder += (diff * (yBorder + iconXSize)) / (actualYIcons + 1);
}
if (y == actualYIcons - 1)
{
// generating the last row of icons
int actualXIcons = total % xMax;
if (actualXIcons)
{
// space out icons horizontally, if there aren't enough to fill the last row
int diff = xMax - actualXIcons;
xBorder += (diff * (xBorder + iconXSize)) / (actualXIcons + 1);
}
}
return QRect((iconXSize + xBorder) * x + xBorder, (iconYSize + yBorder) * y + yBorder, iconXSize, iconYSize);
}
CSVWidget::SceneToolToggle::SceneToolToggle(SceneToolbar* parent, const QString& toolTip, const std::string& emptyIcon)
: SceneTool(parent)
, mEmptyIcon(emptyIcon)
, mButtonSize(parent->getButtonSize())
, mIconSize(parent->getIconSize())
, mToolTip(toolTip)
, mFirst(nullptr)
{
mPanel = new QFrame(this, Qt::Popup);
mLayout = new QHBoxLayout(mPanel);
mLayout->setContentsMargins(QMargins(0, 0, 0, 0));
mPanel->setLayout(mLayout);
}
void CSVWidget::SceneToolToggle::showPanel(const QPoint& position)
{
mPanel->move(position);
mPanel->show();
if (mFirst)
mFirst->setFocus(Qt::OtherFocusReason);
}
void CSVWidget::SceneToolToggle::addButton(const std::string& icon, unsigned int mask, const std::string& smallIcon,
const QString& name, const QString& tooltip)
{
if (mButtons.size() >= 9)
throw std::runtime_error("Exceeded number of buttons in toggle type tool");
PushButton* button = new PushButton(
QIcon(QPixmap(icon.c_str())), PushButton::Type_Toggle, tooltip.isEmpty() ? name : tooltip, mPanel);
button->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
button->setIconSize(QSize(mIconSize, mIconSize));
button->setFixedSize(mButtonSize, mButtonSize);
mLayout->addWidget(button);
ButtonDesc desc;
desc.mMask = mask;
desc.mSmallIcon = smallIcon;
desc.mName = name;
desc.mIndex = static_cast<int>(mButtons.size());
mButtons.insert(std::make_pair(button, desc));
connect(button, &PushButton::clicked, this, &SceneToolToggle::selected);
if (mButtons.size() == 1)
mFirst = button;
}
unsigned int CSVWidget::SceneToolToggle::getSelectionMask() const
{
unsigned int selection = 0;
for (std::map<PushButton*, ButtonDesc>::const_iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
if (iter->first->isChecked())
selection |= iter->second.mMask;
return selection;
}
void CSVWidget::SceneToolToggle::setSelectionMask(unsigned int selection)
{
for (std::map<PushButton*, ButtonDesc>::iterator iter(mButtons.begin()); iter != mButtons.end(); ++iter)
iter->first->setChecked(selection & iter->second.mMask);
adjustToolTip();
adjustIcon();
}
void CSVWidget::SceneToolToggle::selected()
{
std::map<PushButton*, ButtonDesc>::const_iterator iter = mButtons.find(dynamic_cast<PushButton*>(sender()));
if (iter != mButtons.end())
{
if (!iter->first->hasKeepOpen())
mPanel->hide();
adjustToolTip();
adjustIcon();
emit selectionChanged();
}
}
| 5,500
|
C++
|
.cpp
| 155
| 29.167742
| 119
| 0.640348
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,075
|
colorpickerpopup.cpp
|
OpenMW_openmw/apps/opencs/view/widget/colorpickerpopup.cpp
|
#include "colorpickerpopup.hpp"
#include <QColorDialog>
#include <QEvent>
#include <QKeyEvent>
#include <QPushButton>
#include <QStyleOptionButton>
#include <QVBoxLayout>
CSVWidget::ColorPickerPopup::ColorPickerPopup(QWidget* parent)
: QFrame(parent)
{
setWindowFlags(Qt::Popup);
setFrameStyle(QFrame::Box | static_cast<int>(QFrame::Plain));
hide();
mColorPicker = new QColorDialog(this);
mColorPicker->setWindowFlags(Qt::Widget);
mColorPicker->setOptions(QColorDialog::NoButtons | QColorDialog::DontUseNativeDialog);
mColorPicker->installEventFilter(this);
connect(mColorPicker, &QColorDialog::currentColorChanged, this, &ColorPickerPopup::colorChanged);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(mColorPicker);
layout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
setFixedSize(mColorPicker->size());
}
void CSVWidget::ColorPickerPopup::showPicker(const QPoint& position, const QColor& initialColor)
{
QRect geometry = this->geometry();
geometry.moveTo(position);
setGeometry(geometry);
// Calling getColor() creates a blocking dialog that will continue execution once the user chooses OK or Cancel
QColor color = mColorPicker->getColor(initialColor);
if (color.isValid())
mColorPicker->setCurrentColor(color);
}
void CSVWidget::ColorPickerPopup::mousePressEvent(QMouseEvent* event)
{
QPushButton* button = qobject_cast<QPushButton*>(parentWidget());
if (button != nullptr)
{
QStyleOptionButton option;
option.initFrom(button);
QRect buttonRect = option.rect;
buttonRect.moveTo(button->mapToGlobal(buttonRect.topLeft()));
// If the mouse is pressed above the pop-up parent,
// the pop-up will be hidden and the pressed signal won't be repeated for the parent
if (buttonRect.contains(event->globalPos()) || buttonRect.contains(event->pos()))
{
setAttribute(Qt::WA_NoMouseReplay);
}
}
QFrame::mousePressEvent(event);
}
bool CSVWidget::ColorPickerPopup::eventFilter(QObject* object, QEvent* event)
{
if (object == mColorPicker && event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
// Prevent QColorDialog from closing when Escape is pressed.
// Instead, hide the popup.
if (keyEvent->key() == Qt::Key_Escape)
{
hide();
return true;
}
}
return QFrame::eventFilter(object, event);
}
| 2,591
|
C++
|
.cpp
| 68
| 32.794118
| 115
| 0.706444
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,076
|
scenetoolbar.cpp
|
OpenMW_openmw/apps/opencs/view/widget/scenetoolbar.cpp
|
#include "scenetoolbar.hpp"
#include <QVBoxLayout>
#include <memory>
#include "../../model/prefs/shortcut.hpp"
#include "scenetool.hpp"
void CSVWidget::SceneToolbar::focusInEvent(QFocusEvent* event)
{
QWidget::focusInEvent(event);
if (mLayout->count())
dynamic_cast<QWidgetItem&>(*mLayout->itemAt(0)).widget()->setFocus();
}
CSVWidget::SceneToolbar::SceneToolbar(int buttonSize, QWidget* parent)
: QWidget(parent)
, mButtonSize(buttonSize)
, mIconSize(buttonSize - 6)
{
setFixedWidth(mButtonSize);
mLayout = new QVBoxLayout(this);
mLayout->setAlignment(Qt::AlignTop);
mLayout->setContentsMargins(QMargins(0, 0, 0, 0));
setLayout(mLayout);
CSMPrefs::Shortcut* focusSceneShortcut = new CSMPrefs::Shortcut("scene-focus-toolbar", this);
connect(focusSceneShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &SceneToolbar::focusSceneRequest);
}
void CSVWidget::SceneToolbar::addTool(SceneTool* tool, SceneTool* insertPoint)
{
if (!insertPoint)
mLayout->addWidget(tool, 0, Qt::AlignTop);
else
{
int index = mLayout->indexOf(insertPoint);
mLayout->insertWidget(index + 1, tool, 0, Qt::AlignTop);
}
}
void CSVWidget::SceneToolbar::removeTool(SceneTool* tool)
{
mLayout->removeWidget(tool);
}
int CSVWidget::SceneToolbar::getButtonSize() const
{
return mButtonSize;
}
int CSVWidget::SceneToolbar::getIconSize() const
{
return mIconSize;
}
| 1,462
|
C++
|
.cpp
| 46
| 28.108696
| 117
| 0.729479
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,077
|
coloreditor.cpp
|
OpenMW_openmw/apps/opencs/view/widget/coloreditor.cpp
|
#include "coloreditor.hpp"
#include <QGuiApplication>
#include <QPainter>
#include <QScreen>
#include "colorpickerpopup.hpp"
class QShowEvent;
CSVWidget::ColorEditor::ColorEditor(const QColor& color, QWidget* parent, const bool popupOnStart)
: ColorEditor(parent, popupOnStart)
{
setColor(color);
}
CSVWidget::ColorEditor::ColorEditor(const int colorInt, QWidget* parent, const bool popupOnStart)
: ColorEditor(parent, popupOnStart)
{
setColor(colorInt);
}
CSVWidget::ColorEditor::ColorEditor(QWidget* parent, const bool popupOnStart)
: QPushButton(parent)
, mColorPicker(new ColorPickerPopup(this))
, mPopupOnStart(popupOnStart)
{
connect(this, &ColorEditor::clicked, this, &ColorEditor::showPicker);
connect(mColorPicker, &ColorPickerPopup::colorChanged, this, &ColorEditor::pickerColorChanged);
}
void CSVWidget::ColorEditor::paintEvent(QPaintEvent* event)
{
QPushButton::paintEvent(event);
QRect buttonRect = rect();
QRect coloredRect(buttonRect.x() + qRound(buttonRect.width() / 4.0),
buttonRect.y() + qRound(buttonRect.height() / 4.0), buttonRect.width() / 2, buttonRect.height() / 2);
QPainter painter(this);
painter.fillRect(coloredRect, mColor);
painter.setPen(Qt::black);
painter.drawRect(coloredRect);
}
void CSVWidget::ColorEditor::showEvent(QShowEvent* event)
{
QPushButton::showEvent(event);
if (isVisible() && mPopupOnStart)
{
setChecked(true);
showPicker();
mPopupOnStart = false;
}
}
QColor CSVWidget::ColorEditor::color() const
{
return mColor;
}
int CSVWidget::ColorEditor::colorInt() const
{
return (mColor.blue() << 16) | (mColor.green() << 8) | (mColor.red());
}
void CSVWidget::ColorEditor::setColor(const QColor& color)
{
mColor = color;
update();
}
void CSVWidget::ColorEditor::setColor(const int colorInt)
{
// Color RGB values are stored in given integer.
// First byte is red, second byte is green, third byte is blue.
QColor color = QColor(colorInt & 0xff, (colorInt >> 8) & 0xff, (colorInt >> 16) & 0xff);
setColor(color);
}
void CSVWidget::ColorEditor::showPicker()
{
mColorPicker->showPicker(calculatePopupPosition(), mColor);
emit pickingFinished();
}
void CSVWidget::ColorEditor::pickerColorChanged(const QColor& color)
{
mColor = color;
update();
}
QPoint CSVWidget::ColorEditor::calculatePopupPosition()
{
QRect editorGeometry = geometry();
QRect popupGeometry = mColorPicker->geometry();
QRect screenGeometry = QGuiApplication::primaryScreen()->geometry();
// Center the popup horizontally relative to the editor
int localPopupX = (editorGeometry.width() - popupGeometry.width()) / 2;
// Popup position need to be specified in global coords
QPoint popupPosition = mapToGlobal(QPoint(localPopupX, editorGeometry.height()));
// Make sure that the popup isn't out of the screen
if (popupPosition.x() < screenGeometry.left())
{
popupPosition.setX(screenGeometry.left() + 1);
}
else if (popupPosition.x() + popupGeometry.width() > screenGeometry.right())
{
popupPosition.setX(screenGeometry.right() - popupGeometry.width() - 1);
}
if (popupPosition.y() + popupGeometry.height() > screenGeometry.bottom())
{
// Place the popup above the editor
popupPosition.setY(popupPosition.y() - popupGeometry.height() - editorGeometry.height() - 1);
}
return popupPosition;
}
| 3,478
|
C++
|
.cpp
| 100
| 30.95
| 109
| 0.72075
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,078
|
pagebase.cpp
|
OpenMW_openmw/apps/opencs/view/prefs/pagebase.cpp
|
#include "pagebase.hpp"
#include <QContextMenuEvent>
#include <QMenu>
#include "../../model/prefs/category.hpp"
#include "../../model/prefs/state.hpp"
CSVPrefs::PageBase::PageBase(CSMPrefs::Category& category, QWidget* parent)
: QScrollArea(parent)
, mCategory(category)
{
}
CSMPrefs::Category& CSVPrefs::PageBase::getCategory()
{
return mCategory;
}
void CSVPrefs::PageBase::contextMenuEvent(QContextMenuEvent* e)
{
QMenu* menu = new QMenu();
menu->addAction("Reset category to default", this, SLOT(resetCategory()));
menu->addAction("Reset all to default", this, SLOT(resetAll()));
menu->exec(e->globalPos());
delete menu;
}
void CSVPrefs::PageBase::resetCategory()
{
CSMPrefs::State::get().resetCategory(getCategory().getKey());
}
void CSVPrefs::PageBase::resetAll()
{
CSMPrefs::State::get().resetAll();
}
| 859
|
C++
|
.cpp
| 30
| 25.966667
| 78
| 0.722833
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,079
|
contextmenulist.cpp
|
OpenMW_openmw/apps/opencs/view/prefs/contextmenulist.cpp
|
#include "contextmenulist.hpp"
#include <QContextMenuEvent>
#include <QMenu>
#include <QMouseEvent>
#include "../../model/prefs/state.hpp"
CSVPrefs::ContextMenuList::ContextMenuList(QWidget* parent)
: QListWidget(parent)
{
}
void CSVPrefs::ContextMenuList::contextMenuEvent(QContextMenuEvent* e)
{
QMenu* menu = new QMenu();
menu->addAction("Reset category to default", this, SLOT(resetCategory()));
menu->addAction("Reset all to default", this, SLOT(resetAll()));
menu->exec(e->globalPos());
delete menu;
}
void CSVPrefs::ContextMenuList::mousePressEvent(QMouseEvent* e)
{
// enable all buttons except right click
// This means that when right-clicking to enable the
// context menu, the page doesn't switch at the same time.
if (!(e->buttons() & Qt::RightButton))
{
QListWidget::mousePressEvent(e);
}
}
void CSVPrefs::ContextMenuList::resetCategory()
{
CSMPrefs::State::get().resetCategory(currentItem()->text().toStdString());
}
void CSVPrefs::ContextMenuList::resetAll()
{
CSMPrefs::State::get().resetAll();
}
| 1,087
|
C++
|
.cpp
| 35
| 27.971429
| 78
| 0.722915
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,080
|
keybindingpage.cpp
|
OpenMW_openmw/apps/opencs/view/prefs/keybindingpage.cpp
|
#include "keybindingpage.hpp"
#include <cassert>
#include <string>
#include <utility>
#include <vector>
#include <QComboBox>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <apps/opencs/view/prefs/pagebase.hpp>
#include "../../model/prefs/category.hpp"
#include "../../model/prefs/setting.hpp"
#include "../../model/prefs/state.hpp"
namespace CSVPrefs
{
KeyBindingPage::KeyBindingPage(CSMPrefs::Category& category, QWidget* parent)
: PageBase(category, parent)
, mStackedLayout(nullptr)
, mPageLayout(nullptr)
, mPageSelector(nullptr)
{
// Need one widget for scroll area
QWidget* topWidget = new QWidget();
QVBoxLayout* topLayout = new QVBoxLayout(topWidget);
// Allows switching between "pages"
QWidget* stackedWidget = new QWidget();
mStackedLayout = new QStackedLayout(stackedWidget);
mPageSelector = new QComboBox();
connect(mPageSelector, qOverload<int>(&QComboBox::currentIndexChanged), mStackedLayout,
&QStackedLayout::setCurrentIndex);
QFrame* lineSeparator = new QFrame(topWidget);
lineSeparator->setFrameShape(QFrame::HLine);
lineSeparator->setFrameShadow(QFrame::Sunken);
// Reset key bindings button
QPushButton* resetButton = new QPushButton("Reset to Defaults", topWidget);
connect(resetButton, &QPushButton::clicked, this, &KeyBindingPage::resetKeyBindings);
topLayout->addWidget(mPageSelector);
topLayout->addWidget(stackedWidget);
topLayout->addWidget(lineSeparator);
topLayout->addWidget(resetButton);
topLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
// Add each option
for (CSMPrefs::Category::Iterator iter = category.begin(); iter != category.end(); ++iter)
addSetting(*iter);
setWidgetResizable(true);
setWidget(topWidget);
}
void KeyBindingPage::addSetting(CSMPrefs::Setting* setting)
{
const CSMPrefs::SettingWidgets widgets = setting->makeWidgets(this);
if (widgets.mLabel != nullptr && widgets.mInput != nullptr)
{
// Label, Option widgets
assert(mPageLayout);
int next = mPageLayout->rowCount();
mPageLayout->addWidget(widgets.mLabel, next, 0);
mPageLayout->addWidget(widgets.mInput, next, 1);
}
else if (widgets.mInput != nullptr)
{
// Wide single widget
assert(mPageLayout);
int next = mPageLayout->rowCount();
mPageLayout->addWidget(widgets.mInput, next, 0, 1, 2);
}
else
{
// Create new page
QWidget* pageWidget = new QWidget();
mPageLayout = new QGridLayout(pageWidget);
mPageLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
mStackedLayout->addWidget(pageWidget);
mPageSelector->addItem(setting->getLabel());
}
}
void KeyBindingPage::resetKeyBindings()
{
CSMPrefs::State::get().resetCategory("Key Bindings");
}
}
| 3,196
|
C++
|
.cpp
| 82
| 31.109756
| 98
| 0.657189
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,081
|
page.cpp
|
OpenMW_openmw/apps/opencs/view/prefs/page.cpp
|
#include "page.hpp"
#include <utility>
#include <vector>
#include <apps/opencs/view/prefs/pagebase.hpp>
#include <QGridLayout>
#include <QLabel>
#include "../../model/prefs/category.hpp"
#include "../../model/prefs/setting.hpp"
CSVPrefs::Page::Page(CSMPrefs::Category& category, QWidget* parent)
: PageBase(category, parent)
{
QWidget* widget = new QWidget(parent);
mGrid = new QGridLayout(widget);
for (CSMPrefs::Category::Iterator iter = category.begin(); iter != category.end(); ++iter)
addSetting(*iter);
setWidget(widget);
}
void CSVPrefs::Page::addSetting(CSMPrefs::Setting* setting)
{
const CSMPrefs::SettingWidgets widgets = setting->makeWidgets(this);
int next = mGrid->rowCount();
if (widgets.mLabel != nullptr && widgets.mInput != nullptr)
{
mGrid->addWidget(widgets.mLabel, next, 0);
mGrid->addWidget(widgets.mInput, next, 1);
}
else if (widgets.mInput != nullptr)
{
mGrid->addWidget(widgets.mInput, next, 0, 1, 2);
}
}
| 1,026
|
C++
|
.cpp
| 31
| 29.064516
| 94
| 0.685279
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,082
|
dialogue.cpp
|
OpenMW_openmw/apps/opencs/view/prefs/dialogue.cpp
|
#include "dialogue.hpp"
#include <exception>
#include <map>
#include <utility>
#include <QApplication>
#include <QListWidgetItem>
#include <QScreen>
#include <QSplitter>
#include <QStackedWidget>
#include <components/debug/debuglog.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/view/prefs/pagebase.hpp>
#include "../../model/prefs/state.hpp"
#include "contextmenulist.hpp"
#include "keybindingpage.hpp"
#include "page.hpp"
void CSVPrefs::Dialogue::buildCategorySelector(QSplitter* main)
{
CSVPrefs::ContextMenuList* list = new CSVPrefs::ContextMenuList(main);
list->setMinimumWidth(50);
list->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
list->setSelectionBehavior(QAbstractItemView::SelectItems);
main->addWidget(list);
QFontMetrics metrics(QApplication::font(list));
int maxWidth = 1;
for (CSMPrefs::State::Iterator iter = CSMPrefs::get().begin(); iter != CSMPrefs::get().end(); ++iter)
{
QString label = QString::fromUtf8(iter->second.getKey().c_str());
maxWidth = std::max(maxWidth, metrics.horizontalAdvance(label));
list->addItem(label);
}
list->setMaximumWidth(maxWidth + 50);
connect(list, &ContextMenuList::currentItemChanged, this, &Dialogue::selectionChanged);
}
void CSVPrefs::Dialogue::buildContentArea(QSplitter* main)
{
mContent = new QStackedWidget(main);
mContent->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
main->addWidget(mContent);
}
CSVPrefs::PageBase* CSVPrefs::Dialogue::makePage(const std::string& key)
{
// special case page code goes here
if (key == "Key Bindings")
return new KeyBindingPage(CSMPrefs::get()[key], mContent);
else
return new Page(CSMPrefs::get()[key], mContent);
}
CSVPrefs::Dialogue::Dialogue()
{
setWindowTitle("User Settings");
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
setMinimumSize(600, 400);
resize(810, 680);
QSplitter* main = new QSplitter(this);
setCentralWidget(main);
buildCategorySelector(main);
buildContentArea(main);
}
CSVPrefs::Dialogue::~Dialogue()
{
try
{
if (isVisible())
CSMPrefs::State::get().save();
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
}
void CSVPrefs::Dialogue::closeEvent(QCloseEvent* event)
{
QMainWindow::closeEvent(event);
CSMPrefs::State::get().save();
}
void CSVPrefs::Dialogue::show()
{
if (QWidget* active = QApplication::activeWindow())
{
// place at the centre of the window with focus
QSize size = active->size();
move(active->geometry().x() + (size.width() - frameGeometry().width()) / 2,
active->geometry().y() + (size.height() - frameGeometry().height()) / 2);
}
else
{
QRect scr = QGuiApplication::primaryScreen()->geometry();
// otherwise place at the centre of the screen
QPoint screenCenter = scr.center();
move(screenCenter - QPoint(frameGeometry().width() / 2, frameGeometry().height() / 2));
}
QWidget::show();
}
void CSVPrefs::Dialogue::selectionChanged(QListWidgetItem* current, QListWidgetItem* previous)
{
if (current)
{
std::string key = current->text().toUtf8().data();
for (int i = 0; i < mContent->count(); ++i)
{
PageBase& page = dynamic_cast<PageBase&>(*mContent->widget(i));
if (page.getCategory().getKey() == key)
{
mContent->setCurrentIndex(i);
return;
}
}
PageBase* page = makePage(key);
mContent->setCurrentIndex(mContent->addWidget(page));
}
}
| 3,788
|
C++
|
.cpp
| 112
| 28.580357
| 105
| 0.670695
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,083
|
operation.cpp
|
OpenMW_openmw/apps/opencs/view/doc/operation.cpp
|
#include "operation.hpp"
#include <sstream>
#include <string>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QPushButton>
#include "../../model/doc/state.hpp"
void CSVDoc::Operation::updateLabel(int threads)
{
if (threads == -1 || ((threads == 0) != mStalling))
{
std::string name("Unknown operation");
switch (mType)
{
case CSMDoc::State_Saving:
name = "Saving";
break;
case CSMDoc::State_Verifying:
name = "Verifying";
break;
case CSMDoc::State_Searching:
name = "Searching";
break;
case CSMDoc::State_Merging:
name = "Merging";
break;
}
std::ostringstream stream;
if ((mStalling = (threads <= 0)))
{
stream << name << " (waiting for a free worker thread)";
}
else
{
stream << name << " (%p%)";
}
mProgressBar->setFormat(stream.str().c_str());
}
}
CSVDoc::Operation::Operation(int type, QWidget* parent)
: mType(type)
, mStalling(false)
{
/// \todo Add a cancel button or a pop up menu with a cancel item
initWidgets();
setBarColor(type);
updateLabel();
/// \todo assign different progress bar colours to allow the user to distinguish easily between operation types
}
CSVDoc::Operation::~Operation()
{
delete mLayout;
delete mProgressBar;
delete mAbortButton;
}
void CSVDoc::Operation::initWidgets()
{
mProgressBar = new QProgressBar();
mAbortButton = new QPushButton("Abort");
mLayout = new QHBoxLayout();
mLayout->setContentsMargins(8, 4, 8, 4);
mLayout->addWidget(mProgressBar);
mLayout->addWidget(mAbortButton);
connect(mAbortButton, &QPushButton::clicked, this, qOverload<>(&Operation::abortOperation));
}
void CSVDoc::Operation::setProgress(int current, int max, int threads)
{
updateLabel(threads);
mProgressBar->setRange(0, max);
mProgressBar->setValue(current);
}
int CSVDoc::Operation::getType() const
{
return mType;
}
void CSVDoc::Operation::setBarColor(int type)
{
QString style
= "QProgressBar {"
"text-align: center;"
"border: 1px solid #4e4e4e;"
"}"
"QProgressBar::chunk {"
"background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 %1, stop:.50 %2 stop: .51 %3 stop:1 %4);"
"text-align: center;"
"margin: 2px;"
"}";
QString topColor = "#9e9e9e";
QString bottomColor = "#919191";
QString midTopColor = "#848484";
QString midBottomColor = "#717171"; // default gray
// colors inspired by samples from:
// http://www.colorzilla.com/gradient-editor/
switch (type)
{
case CSMDoc::State_Saving:
topColor = "#f27d6e";
midTopColor = "#ee6954";
midBottomColor = "#f05536";
bottomColor = "#de511e"; // red
break;
case CSMDoc::State_Searching:
topColor = "#6db3f2";
midTopColor = "#54a3ee";
midBottomColor = "#3690f0";
bottomColor = "#1e69de"; // blue
break;
case CSMDoc::State_Verifying:
topColor = "#bfd255";
midTopColor = "#8eb92a";
midBottomColor = "#72aa00";
bottomColor = "#9ecb2d"; // green
break;
case CSMDoc::State_Merging:
topColor = "#d89188";
midTopColor = "#d07f72";
midBottomColor = "#cc6d5a";
bottomColor = "#b86344"; // brown
break;
}
mProgressBar->setStyleSheet(style.arg(topColor).arg(midTopColor).arg(midBottomColor).arg(bottomColor));
}
QHBoxLayout* CSVDoc::Operation::getLayout() const
{
return mLayout;
}
void CSVDoc::Operation::abortOperation()
{
emit abortOperation(mType);
}
| 3,953
|
C++
|
.cpp
| 130
| 22.992308
| 115
| 0.589771
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,084
|
globaldebugprofilemenu.cpp
|
OpenMW_openmw/apps/opencs/view/doc/globaldebugprofilemenu.cpp
|
#include "globaldebugprofilemenu.hpp"
#include <algorithm>
#include <vector>
#include <QAction>
#include <QActionGroup>
#include <QMenu>
#include <QModelIndex>
#include <apps/opencs/model/world/columns.hpp>
#include "../../model/world/idtable.hpp"
#include "../../model/world/record.hpp"
class QWidget;
void CSVDoc::GlobalDebugProfileMenu::rebuild()
{
clear();
delete mActions;
mActions = nullptr;
int idColumn = mDebugProfiles->findColumnIndex(CSMWorld::Columns::ColumnId_Id);
int stateColumn = mDebugProfiles->findColumnIndex(CSMWorld::Columns::ColumnId_Modification);
int globalColumn = mDebugProfiles->findColumnIndex(CSMWorld::Columns::ColumnId_GlobalProfile);
int size = mDebugProfiles->rowCount();
std::vector<QString> ids;
for (int i = 0; i < size; ++i)
{
int state = mDebugProfiles->data(mDebugProfiles->index(i, stateColumn)).toInt();
bool global = mDebugProfiles->data(mDebugProfiles->index(i, globalColumn)).toInt();
if (state != CSMWorld::RecordBase::State_Deleted && global)
ids.push_back(mDebugProfiles->data(mDebugProfiles->index(i, idColumn)).toString());
}
mActions = new QActionGroup(this);
connect(mActions, &QActionGroup::triggered, this, &GlobalDebugProfileMenu::actionTriggered);
std::sort(ids.begin(), ids.end());
for (std::vector<QString>::const_iterator iter(ids.begin()); iter != ids.end(); ++iter)
{
mActions->addAction(addAction(*iter));
}
}
CSVDoc::GlobalDebugProfileMenu::GlobalDebugProfileMenu(CSMWorld::IdTable* debugProfiles, QWidget* parent)
: QMenu(parent)
, mDebugProfiles(debugProfiles)
, mActions(nullptr)
{
rebuild();
connect(mDebugProfiles, &CSMWorld::IdTable::rowsAboutToBeRemoved, this,
&GlobalDebugProfileMenu::profileAboutToBeRemoved);
connect(mDebugProfiles, &CSMWorld::IdTable::rowsInserted, this, &GlobalDebugProfileMenu::profileInserted);
connect(mDebugProfiles, &CSMWorld::IdTable::dataChanged, this, &GlobalDebugProfileMenu::profileChanged);
}
void CSVDoc::GlobalDebugProfileMenu::updateActions(bool running)
{
if (mActions)
mActions->setEnabled(!running);
}
void CSVDoc::GlobalDebugProfileMenu::profileAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
rebuild();
}
void CSVDoc::GlobalDebugProfileMenu::profileInserted(const QModelIndex& parent, int start, int end)
{
rebuild();
}
void CSVDoc::GlobalDebugProfileMenu::profileChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
rebuild();
}
void CSVDoc::GlobalDebugProfileMenu::actionTriggered(QAction* action)
{
emit triggered(std::string(action->text().toUtf8().constData()));
}
| 2,716
|
C++
|
.cpp
| 68
| 35.985294
| 111
| 0.744567
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,085
|
operations.cpp
|
OpenMW_openmw/apps/opencs/view/doc/operations.cpp
|
#include "operations.hpp"
#include <algorithm>
#include <QDockWidget>
#include <QVBoxLayout>
#include <QWidget>
#include "operation.hpp"
namespace
{
constexpr int operationLineHeight = 36;
}
CSVDoc::Operations::Operations()
{
setFeatures(QDockWidget::NoDockWidgetFeatures);
QWidget* widgetContainer = new QWidget(this);
mLayout = new QVBoxLayout;
mLayout->setContentsMargins(0, 0, 0, 0);
widgetContainer->setContentsMargins(0, 0, 0, 0);
widgetContainer->setLayout(mLayout);
setWidget(widgetContainer);
setVisible(false);
setFixedHeight(operationLineHeight);
setTitleBarWidget(new QWidget(this));
}
void CSVDoc::Operations::setProgress(int current, int max, int type, int threads)
{
for (std::vector<Operation*>::iterator iter(mOperations.begin()); iter != mOperations.end(); ++iter)
if ((*iter)->getType() == type)
{
(*iter)->setProgress(current, max, threads);
return;
}
Operation* operation = new Operation(type, this);
connect(operation, qOverload<int>(&Operation::abortOperation), this, &Operations::abortOperation);
mLayout->addLayout(operation->getLayout());
mOperations.push_back(operation);
operation->setProgress(current, max, threads);
int newCount = static_cast<int>(mOperations.size());
setFixedHeight(operationLineHeight * newCount);
setVisible(true);
}
void CSVDoc::Operations::quitOperation(int type)
{
for (std::vector<Operation*>::iterator iter(mOperations.begin()); iter != mOperations.end(); ++iter)
if ((*iter)->getType() == type)
{
mLayout->removeItem((*iter)->getLayout());
(*iter)->deleteLater();
mOperations.erase(iter);
int newCount = static_cast<int>(mOperations.size());
if (newCount > 0)
setFixedHeight(operationLineHeight * newCount);
else
setVisible(false);
break;
}
}
| 1,987
|
C++
|
.cpp
| 56
| 29.339286
| 104
| 0.668407
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,086
|
adjusterwidget.cpp
|
OpenMW_openmw/apps/opencs/view/doc/adjusterwidget.cpp
|
#include "adjusterwidget.hpp"
#include <QHBoxLayout>
#include <QLabel>
#include <QStyle>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <components/files/qtconversion.hpp>
#include <components/misc/strings/lower.hpp>
CSVDoc::AdjusterWidget::AdjusterWidget(QWidget* parent)
: QWidget(parent)
, mValid(false)
, mAction(ContentAction_Undefined)
{
QHBoxLayout* layout = new QHBoxLayout(this);
mIcon = new QLabel(this);
layout->addWidget(mIcon, 0);
mMessage = new QLabel(this);
mMessage->setWordWrap(true);
mMessage->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
layout->addWidget(mMessage, 1);
setName("", false);
setLayout(layout);
}
void CSVDoc::AdjusterWidget::setAction(ContentAction action)
{
mAction = action;
}
void CSVDoc::AdjusterWidget::setLocalData(const std::filesystem::path& localData)
{
mLocalData = localData;
}
std::filesystem::path CSVDoc::AdjusterWidget::getPath() const
{
if (!mValid)
throw std::logic_error("invalid content file path");
return mResultPath;
}
bool CSVDoc::AdjusterWidget::isValid() const
{
return mValid;
}
void CSVDoc::AdjusterWidget::setFilenameCheck(bool doCheck)
{
mDoFilenameCheck = doCheck;
}
void CSVDoc::AdjusterWidget::setName(const QString& name, bool addon)
{
QString message;
mValid = (!name.isEmpty());
bool warning = false;
if (!mValid)
{
message = "No name.";
}
else
{
auto path = Files::pathFromQString(name);
const auto extension = Misc::StringUtils::lowerCase(path.extension().u8string());
bool isLegacyPath = (extension == u8".esm" || extension == u8".esp");
bool isFilePathChanged = (path.parent_path() != mLocalData);
if (isLegacyPath)
path.replace_extension(addon ? ".omwaddon" : ".omwgame");
// if the file came from data-local and is not a legacy file to be converted,
// don't worry about doing a file check.
if (!isFilePathChanged && !isLegacyPath)
{
// path already points to the local data directory
message = "Will be saved as: " + Files::pathToQString(path);
mResultPath = std::move(path);
}
// in all other cases, ensure the path points to data-local and do an existing file check
else
{
// path points somewhere else or is a leaf name.
if (isFilePathChanged)
path = mLocalData / path.filename();
message = "Will be saved as: " + Files::pathToQString(path);
mResultPath = path;
if (std::filesystem::exists(path))
{
/// \todo add an user setting to make this an error.
message += "<p>A file with the same name already exists. If you continue, it will be overwritten.";
warning = true;
}
}
}
mMessage->setText(message);
mIcon->setPixmap(
style()
->standardIcon(mValid ? (warning ? QStyle::SP_MessageBoxWarning : QStyle::SP_MessageBoxInformation)
: QStyle::SP_MessageBoxCritical)
.pixmap(QSize(16, 16)));
emit stateChanged(mValid);
}
| 3,282
|
C++
|
.cpp
| 95
| 27.884211
| 115
| 0.645457
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,087
|
newgame.cpp
|
OpenMW_openmw/apps/opencs/view/doc/newgame.cpp
|
#include "newgame.hpp"
#include <QDialogButtonBox>
#include <QGuiApplication>
#include <QPushButton>
#include <QScreen>
#include <QVBoxLayout>
#include "adjusterwidget.hpp"
#include "filewidget.hpp"
CSVDoc::NewGameDialogue::NewGameDialogue()
{
setWindowTitle("Create New Game");
QVBoxLayout* layout = new QVBoxLayout(this);
mFileWidget = new FileWidget(this);
mFileWidget->setType(false);
layout->addWidget(mFileWidget, 1);
mAdjusterWidget = new AdjusterWidget(this);
layout->addWidget(mAdjusterWidget, 1);
QDialogButtonBox* buttons = new QDialogButtonBox(this);
mCreate = new QPushButton("Create", this);
mCreate->setDefault(true);
mCreate->setEnabled(false);
buttons->addButton(mCreate, QDialogButtonBox::AcceptRole);
QPushButton* cancel = new QPushButton("Cancel", this);
buttons->addButton(cancel, QDialogButtonBox::RejectRole);
layout->addWidget(buttons);
setLayout(layout);
connect(mAdjusterWidget, &AdjusterWidget::stateChanged, this, &NewGameDialogue::stateChanged);
connect(mCreate, &QPushButton::clicked, this, &NewGameDialogue::create);
connect(cancel, &QPushButton::clicked, this, &NewGameDialogue::reject);
connect(mFileWidget, &FileWidget::nameChanged, mAdjusterWidget, &AdjusterWidget::setName);
QRect scr = QGuiApplication::primaryScreen()->geometry();
QRect rect = geometry();
move(scr.center().x() - rect.center().x(), scr.center().y() - rect.center().y());
}
void CSVDoc::NewGameDialogue::setLocalData(const std::filesystem::path& localData)
{
mAdjusterWidget->setLocalData(localData);
}
void CSVDoc::NewGameDialogue::stateChanged(bool valid)
{
mCreate->setEnabled(valid);
}
void CSVDoc::NewGameDialogue::create()
{
emit createRequest(mAdjusterWidget->getPath());
}
void CSVDoc::NewGameDialogue::reject()
{
emit cancelCreateGame();
QDialog::reject();
}
| 1,905
|
C++
|
.cpp
| 51
| 33.745098
| 98
| 0.749591
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,088
|
subview.cpp
|
OpenMW_openmw/apps/opencs/view/doc/subview.cpp
|
#include "subview.hpp"
#include <QEvent>
#include <QKeyEvent>
#include <apps/opencs/model/world/universalid.hpp>
bool CSVDoc::SubView::event(QEvent* event)
{
if (event->type() == QEvent::ShortcutOverride)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_W && keyEvent->modifiers() == (Qt::ShiftModifier | Qt::ControlModifier))
emit closeRequest();
return true;
}
return QDockWidget::event(event);
}
CSVDoc::SubView::SubView(const CSMWorld::UniversalId& id)
: mUniversalId(id)
{
/// \todo add a button to the title bar that clones this sub view
setWindowTitle(QString::fromUtf8(mUniversalId.toString().c_str()));
setAttribute(Qt::WA_DeleteOnClose);
}
CSMWorld::UniversalId CSVDoc::SubView::getUniversalId() const
{
return mUniversalId;
}
void CSVDoc::SubView::setStatusBar(bool show) {}
void CSVDoc::SubView::useHint(const std::string& hint) {}
void CSVDoc::SubView::setUniversalId(const CSMWorld::UniversalId& id)
{
mUniversalId = id;
setWindowTitle(QString::fromUtf8(mUniversalId.toString().c_str()));
emit universalIdChanged(mUniversalId);
}
void CSVDoc::SubView::closeEvent(QCloseEvent* event)
{
emit updateSubViewIndices(this);
}
std::string CSVDoc::SubView::getTitle() const
{
return mUniversalId.toString();
}
void CSVDoc::SubView::closeRequest()
{
emit closeRequest(this);
}
| 1,431
|
C++
|
.cpp
| 46
| 27.717391
| 111
| 0.723559
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,089
|
runlogsubview.cpp
|
OpenMW_openmw/apps/opencs/view/doc/runlogsubview.cpp
|
#include "runlogsubview.hpp"
#include "../../model/doc/document.hpp"
#include <apps/opencs/view/doc/subview.hpp>
#include <QTextEdit>
CSVDoc::RunLogSubView::RunLogSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
: SubView(id)
{
QTextEdit* edit = new QTextEdit(this);
edit->setDocument(document.getRunLog());
edit->setReadOnly(true);
setWidget(edit);
}
void CSVDoc::RunLogSubView::setEditLock(bool locked)
{
// ignored since this SubView does not have editing
}
| 511
|
C++
|
.cpp
| 16
| 29.0625
| 97
| 0.748466
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,090
|
subviewfactory.cpp
|
OpenMW_openmw/apps/opencs/view/doc/subviewfactory.cpp
|
#include "subviewfactory.hpp"
#include <cassert>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <apps/opencs/model/world/universalid.hpp>
CSVDoc::SubViewFactoryManager::~SubViewFactoryManager()
{
for (std::map<CSMWorld::UniversalId::Type, SubViewFactoryBase*>::iterator iter(mSubViewFactories.begin());
iter != mSubViewFactories.end(); ++iter)
delete iter->second;
}
void CSVDoc::SubViewFactoryManager::add(const CSMWorld::UniversalId::Type& id, SubViewFactoryBase* factory)
{
assert(mSubViewFactories.find(id) == mSubViewFactories.end());
mSubViewFactories.insert(std::make_pair(id, factory));
}
CSVDoc::SubView* CSVDoc::SubViewFactoryManager::makeSubView(const CSMWorld::UniversalId& id, CSMDoc::Document& document)
{
std::map<CSMWorld::UniversalId::Type, SubViewFactoryBase*>::iterator iter = mSubViewFactories.find(id.getType());
if (iter == mSubViewFactories.end())
throw std::runtime_error("Failed to create a sub view for: " + id.toString());
return iter->second->makeSubView(id, document);
}
| 1,100
|
C++
|
.cpp
| 25
| 40.72
| 120
| 0.75164
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,091
|
filewidget.cpp
|
OpenMW_openmw/apps/opencs/view/doc/filewidget.cpp
|
#include "filewidget.hpp"
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
QString CSVDoc::FileWidget::getExtension() const
{
return mAddon ? ".omwaddon" : ".omwgame";
}
CSVDoc::FileWidget::FileWidget(QWidget* parent)
: QWidget(parent)
, mAddon(false)
{
QHBoxLayout* layout = new QHBoxLayout(this);
mInput = new QLineEdit(this);
layout->addWidget(mInput, 1);
mType = new QLabel(this);
layout->addWidget(mType);
connect(mInput, &QLineEdit::textChanged, this, &FileWidget::textChanged);
setLayout(layout);
}
void CSVDoc::FileWidget::setType(bool addon)
{
mAddon = addon;
mType->setText(getExtension());
}
QString CSVDoc::FileWidget::getName() const
{
QString text = mInput->text();
if (text.isEmpty())
return "";
return text + getExtension();
}
void CSVDoc::FileWidget::textChanged(const QString& text)
{
emit nameChanged(getName(), mAddon);
}
void CSVDoc::FileWidget::extensionLabelIsVisible(bool visible)
{
mType->setVisible(visible);
}
void CSVDoc::FileWidget::setName(const std::string& text)
{
QString text2 = QString::fromUtf8(text.c_str());
mInput->setText(text2);
textChanged(text2);
}
| 1,211
|
C++
|
.cpp
| 46
| 23.021739
| 77
| 0.714908
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,092
|
sizehint.cpp
|
OpenMW_openmw/apps/opencs/view/doc/sizehint.cpp
|
#include "sizehint.hpp"
CSVDoc::SizeHintWidget::SizeHintWidget(QWidget* parent)
: QWidget(parent)
{
}
QSize CSVDoc::SizeHintWidget::sizeHint() const
{
return mSize;
}
void CSVDoc::SizeHintWidget::setSizeHint(const QSize& size)
{
mSize = size;
}
| 260
|
C++
|
.cpp
| 13
| 17.846154
| 59
| 0.758197
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,093
|
view.cpp
|
OpenMW_openmw/apps/opencs/view/doc/view.cpp
|
#include "view.hpp"
#include <QApplication>
#include <QCloseEvent>
#include <QMenuBar>
#include <QMessageBox>
#include <QScreen>
#include <QScrollArea>
#include <QScrollBar>
#include <algorithm>
#include <filesystem>
#include <sstream>
#include "../../model/doc/document.hpp"
#include "../../model/doc/state.hpp"
#include "../../model/prefs/shortcut.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/idtable.hpp"
#include "../world/dialoguesubview.hpp"
#include "../world/scenesubview.hpp"
#include "../world/scriptsubview.hpp"
#include "../world/subviews.hpp"
#include "../world/tablesubview.hpp"
#include "../tools/subviews.hpp"
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/prefs/shortcutmanager.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/view/doc/subviewfactory.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/helpviewer.hpp>
#include <components/misc/scalableicon.hpp>
#include <components/misc/strings/format.hpp>
#include <components/misc/timeconvert.hpp>
#include <components/version/version.hpp>
#include "globaldebugprofilemenu.hpp"
#include "operations.hpp"
#include "runlogsubview.hpp"
#include "subview.hpp"
#include "subviewfactoryimp.hpp"
#include "viewmanager.hpp"
QRect desktopRect()
{
QRegion virtualGeometry;
for (auto screen : QGuiApplication::screens())
{
virtualGeometry += screen->geometry();
}
return virtualGeometry.boundingRect();
}
void CSVDoc::View::closeEvent(QCloseEvent* event)
{
if (!mViewManager.closeRequest(this))
event->ignore();
else
{
// closeRequest() returns true if last document
mViewManager.removeDocAndView(mDocument);
}
}
void CSVDoc::View::setupFileMenu()
{
QMenu* file = menuBar()->addMenu(tr("File"));
QAction* newGame = createMenuEntry("New Game", ":menu-new-game", file, "document-file-newgame");
connect(newGame, &QAction::triggered, this, &View::newGameRequest);
QAction* newAddon = createMenuEntry("New Addon", ":menu-new-addon", file, "document-file-newaddon");
connect(newAddon, &QAction::triggered, this, &View::newAddonRequest);
QAction* open = createMenuEntry("Open", ":menu-open", file, "document-file-open");
connect(open, &QAction::triggered, this, &View::loadDocumentRequest);
QAction* save = createMenuEntry("Save", ":menu-save", file, "document-file-save");
connect(save, &QAction::triggered, this, &View::save);
mSave = save;
file->addSeparator();
QAction* verify = createMenuEntry("Verify", ":menu-verify", file, "document-file-verify");
connect(verify, &QAction::triggered, this, &View::verify);
mVerify = verify;
QAction* merge = createMenuEntry("Merge", ":menu-merge", file, "document-file-merge");
connect(merge, &QAction::triggered, this, &View::merge);
mMerge = merge;
QAction* loadErrors = createMenuEntry("Error Log", ":error-log", file, "document-file-errorlog");
connect(loadErrors, &QAction::triggered, this, &View::loadErrorLog);
QAction* meta = createMenuEntry(CSMWorld::UniversalId::Type_MetaDatas, file, "document-file-metadata");
connect(meta, &QAction::triggered, this, &View::addMetaDataSubView);
file->addSeparator();
QAction* close = createMenuEntry("Close", ":menu-close", file, "document-file-close");
connect(close, &QAction::triggered, this, &View::close);
QAction* exit = createMenuEntry("Exit", ":menu-exit", file, "document-file-exit");
connect(exit, &QAction::triggered, this, &View::exit);
connect(this, &View::exitApplicationRequest, &mViewManager, &ViewManager::exitApplication);
}
namespace
{
void updateUndoRedoAction(QAction* action, const std::string& settingsKey)
{
QKeySequence seq;
CSMPrefs::State::get().getShortcutManager().getSequence(settingsKey, seq);
action->setShortcut(seq);
}
}
void CSVDoc::View::undoActionChanged()
{
updateUndoRedoAction(mUndo, "document-edit-undo");
}
void CSVDoc::View::redoActionChanged()
{
updateUndoRedoAction(mRedo, "document-edit-redo");
}
void CSVDoc::View::setupEditMenu()
{
QMenu* edit = menuBar()->addMenu(tr("Edit"));
mUndo = mDocument->getUndoStack().createUndoAction(this, tr("Undo"));
setupShortcut("document-edit-undo", mUndo);
connect(mUndo, &QAction::changed, this, &View::undoActionChanged);
mUndo->setIcon(Misc::ScalableIcon::load(":menu-undo"));
edit->addAction(mUndo);
mRedo = mDocument->getUndoStack().createRedoAction(this, tr("Redo"));
connect(mRedo, &QAction::changed, this, &View::redoActionChanged);
setupShortcut("document-edit-redo", mRedo);
mRedo->setIcon(Misc::ScalableIcon::load(":menu-redo"));
edit->addAction(mRedo);
QAction* userSettings = createMenuEntry("Preferences", ":menu-preferences", edit, "document-edit-preferences");
connect(userSettings, &QAction::triggered, this, &View::editSettingsRequest);
QAction* search = createMenuEntry(CSMWorld::UniversalId::Type_Search, edit, "document-edit-search");
connect(search, &QAction::triggered, this, &View::addSearchSubView);
}
void CSVDoc::View::setupViewMenu()
{
QMenu* view = menuBar()->addMenu(tr("View"));
QAction* newWindow = createMenuEntry("New View", ":menu-new-window", view, "document-view-newview");
connect(newWindow, &QAction::triggered, this, &View::newView);
mShowStatusBar = createMenuEntry("Toggle Status Bar", ":menu-status-bar", view, "document-view-statusbar");
connect(mShowStatusBar, &QAction::toggled, this, &View::toggleShowStatusBar);
mShowStatusBar->setCheckable(true);
mShowStatusBar->setChecked(CSMPrefs::get()["Windows"]["show-statusbar"].isTrue());
view->addAction(mShowStatusBar);
QAction* filters = createMenuEntry(CSMWorld::UniversalId::Type_Filters, view, "document-mechanics-filters");
connect(filters, &QAction::triggered, this, &View::addFiltersSubView);
}
void CSVDoc::View::setupWorldMenu()
{
QMenu* world = menuBar()->addMenu(tr("World"));
QAction* referenceables
= createMenuEntry(CSMWorld::UniversalId::Type_Referenceables, world, "document-world-referencables");
connect(referenceables, &QAction::triggered, this, &View::addReferenceablesSubView);
QAction* references = createMenuEntry(CSMWorld::UniversalId::Type_References, world, "document-world-references");
connect(references, &QAction::triggered, this, &View::addReferencesSubView);
world->addSeparator();
QAction* cells = createMenuEntry(CSMWorld::UniversalId::Type_Cells, world, "document-world-cells");
connect(cells, &QAction::triggered, this, &View::addCellsSubView);
QAction* lands = createMenuEntry(CSMWorld::UniversalId::Type_Lands, world, "document-world-lands");
connect(lands, &QAction::triggered, this, &View::addLandsSubView);
QAction* landTextures
= createMenuEntry(CSMWorld::UniversalId::Type_LandTextures, world, "document-world-landtextures");
connect(landTextures, &QAction::triggered, this, &View::addLandTexturesSubView);
QAction* grid = createMenuEntry(CSMWorld::UniversalId::Type_Pathgrids, world, "document-world-pathgrid");
connect(grid, &QAction::triggered, this, &View::addPathgridSubView);
world->addSeparator();
QAction* regions = createMenuEntry(CSMWorld::UniversalId::Type_Regions, world, "document-world-regions");
connect(regions, &QAction::triggered, this, &View::addRegionsSubView);
QAction* regionMap = createMenuEntry(CSMWorld::UniversalId::Type_RegionMap, world, "document-world-regionmap");
connect(regionMap, &QAction::triggered, this, &View::addRegionMapSubView);
}
void CSVDoc::View::setupMechanicsMenu()
{
QMenu* mechanics = menuBar()->addMenu(tr("Mechanics"));
QAction* scripts = createMenuEntry(CSMWorld::UniversalId::Type_Scripts, mechanics, "document-mechanics-scripts");
connect(scripts, &QAction::triggered, this, &View::addScriptsSubView);
QAction* startScripts
= createMenuEntry(CSMWorld::UniversalId::Type_StartScripts, mechanics, "document-mechanics-startscripts");
connect(startScripts, &QAction::triggered, this, &View::addStartScriptsSubView);
QAction* globals = createMenuEntry(CSMWorld::UniversalId::Type_Globals, mechanics, "document-mechanics-globals");
connect(globals, &QAction::triggered, this, &View::addGlobalsSubView);
QAction* gmsts = createMenuEntry(CSMWorld::UniversalId::Type_Gmsts, mechanics, "document-mechanics-gamesettings");
connect(gmsts, &QAction::triggered, this, &View::addGmstsSubView);
mechanics->addSeparator();
QAction* spells = createMenuEntry(CSMWorld::UniversalId::Type_Spells, mechanics, "document-mechanics-spells");
connect(spells, &QAction::triggered, this, &View::addSpellsSubView);
QAction* enchantments
= createMenuEntry(CSMWorld::UniversalId::Type_Enchantments, mechanics, "document-mechanics-enchantments");
connect(enchantments, &QAction::triggered, this, &View::addEnchantmentsSubView);
QAction* magicEffects
= createMenuEntry(CSMWorld::UniversalId::Type_MagicEffects, mechanics, "document-mechanics-magiceffects");
connect(magicEffects, &QAction::triggered, this, &View::addMagicEffectsSubView);
}
void CSVDoc::View::setupCharacterMenu()
{
QMenu* characters = menuBar()->addMenu(tr("Characters"));
QAction* skills = createMenuEntry(CSMWorld::UniversalId::Type_Skills, characters, "document-character-skills");
connect(skills, &QAction::triggered, this, &View::addSkillsSubView);
QAction* classes = createMenuEntry(CSMWorld::UniversalId::Type_Classes, characters, "document-character-classes");
connect(classes, &QAction::triggered, this, &View::addClassesSubView);
QAction* factions = createMenuEntry(CSMWorld::UniversalId::Type_Faction, characters, "document-character-factions");
connect(factions, &QAction::triggered, this, &View::addFactionsSubView);
QAction* races = createMenuEntry(CSMWorld::UniversalId::Type_Races, characters, "document-character-races");
connect(races, &QAction::triggered, this, &View::addRacesSubView);
QAction* birthsigns
= createMenuEntry(CSMWorld::UniversalId::Type_Birthsigns, characters, "document-character-birthsigns");
connect(birthsigns, &QAction::triggered, this, &View::addBirthsignsSubView);
QAction* bodyParts
= createMenuEntry(CSMWorld::UniversalId::Type_BodyParts, characters, "document-character-bodyparts");
connect(bodyParts, &QAction::triggered, this, &View::addBodyPartsSubView);
characters->addSeparator();
QAction* topics = createMenuEntry(CSMWorld::UniversalId::Type_Topics, characters, "document-character-topics");
connect(topics, &QAction::triggered, this, &View::addTopicsSubView);
QAction* topicInfos
= createMenuEntry(CSMWorld::UniversalId::Type_TopicInfos, characters, "document-character-topicinfos");
connect(topicInfos, &QAction::triggered, this, &View::addTopicInfosSubView);
characters->addSeparator();
QAction* journals
= createMenuEntry(CSMWorld::UniversalId::Type_Journals, characters, "document-character-journals");
connect(journals, &QAction::triggered, this, &View::addJournalsSubView);
QAction* journalInfos
= createMenuEntry(CSMWorld::UniversalId::Type_JournalInfos, characters, "document-character-journalinfos");
connect(journalInfos, &QAction::triggered, this, &View::addJournalInfosSubView);
}
void CSVDoc::View::setupAssetsMenu()
{
QMenu* assets = menuBar()->addMenu(tr("Assets"));
QAction* reload = createMenuEntry("Reload", ":menu-reload", assets, "document-assets-reload");
connect(reload, &QAction::triggered, &mDocument->getData(), &CSMWorld::Data::assetsChanged);
assets->addSeparator();
QAction* sounds = createMenuEntry(CSMWorld::UniversalId::Type_Sounds, assets, "document-assets-sounds");
connect(sounds, &QAction::triggered, this, &View::addSoundsSubView);
QAction* soundGens = createMenuEntry(CSMWorld::UniversalId::Type_SoundGens, assets, "document-assets-soundgens");
connect(soundGens, &QAction::triggered, this, &View::addSoundGensSubView);
assets->addSeparator(); // resources follow here
QAction* meshes = createMenuEntry(CSMWorld::UniversalId::Type_Meshes, assets, "document-assets-meshes");
connect(meshes, &QAction::triggered, this, &View::addMeshesSubView);
QAction* icons = createMenuEntry(CSMWorld::UniversalId::Type_Icons, assets, "document-assets-icons");
connect(icons, &QAction::triggered, this, &View::addIconsSubView);
QAction* musics = createMenuEntry(CSMWorld::UniversalId::Type_Musics, assets, "document-assets-musics");
connect(musics, &QAction::triggered, this, &View::addMusicsSubView);
QAction* soundFiles = createMenuEntry(CSMWorld::UniversalId::Type_SoundsRes, assets, "document-assets-soundres");
connect(soundFiles, &QAction::triggered, this, &View::addSoundsResSubView);
QAction* textures = createMenuEntry(CSMWorld::UniversalId::Type_Textures, assets, "document-assets-textures");
connect(textures, &QAction::triggered, this, &View::addTexturesSubView);
QAction* videos = createMenuEntry(CSMWorld::UniversalId::Type_Videos, assets, "document-assets-videos");
connect(videos, &QAction::triggered, this, &View::addVideosSubView);
}
void CSVDoc::View::setupDebugMenu()
{
QMenu* debug = menuBar()->addMenu(tr("Debug"));
QAction* profiles = createMenuEntry(CSMWorld::UniversalId::Type_DebugProfiles, debug, "document-debug-profiles");
connect(profiles, &QAction::triggered, this, &View::addDebugProfilesSubView);
debug->addSeparator();
mGlobalDebugProfileMenu = new GlobalDebugProfileMenu(
&dynamic_cast<CSMWorld::IdTable&>(
*mDocument->getData().getTableModel(CSMWorld::UniversalId::Type_DebugProfiles)),
this);
connect(mGlobalDebugProfileMenu, &GlobalDebugProfileMenu::triggered, this,
[this](const std::string& profile) { this->run(profile, ""); });
QAction* runDebug = debug->addMenu(mGlobalDebugProfileMenu);
runDebug->setText(tr("Run OpenMW"));
setupShortcut("document-debug-run", runDebug);
runDebug->setIcon(Misc::ScalableIcon::load(":run-openmw"));
QAction* stopDebug = createMenuEntry("Stop OpenMW", ":stop-openmw", debug, "document-debug-shutdown");
connect(stopDebug, &QAction::triggered, this, &View::stop);
mStopDebug = stopDebug;
QAction* runLog = createMenuEntry(CSMWorld::UniversalId::Type_RunLog, debug, "document-debug-runlog");
connect(runLog, &QAction::triggered, this, &View::addRunLogSubView);
}
void CSVDoc::View::setupHelpMenu()
{
QMenu* help = menuBar()->addMenu(tr("Help"));
QAction* helpInfo = createMenuEntry("Help", ":info", help, "document-help-help");
connect(helpInfo, &QAction::triggered, this, &View::openHelp);
QAction* tutorial = createMenuEntry("Tutorial", ":info", help, "document-help-tutorial");
connect(tutorial, &QAction::triggered, this, &View::tutorial);
QAction* about = createMenuEntry("About OpenMW-CS", ":info", help, "document-help-about");
connect(about, &QAction::triggered, this, &View::infoAbout);
QAction* aboutQt = createMenuEntry("About Qt", ":qt", help, "document-help-qt");
connect(aboutQt, &QAction::triggered, this, &View::infoAboutQt);
}
QAction* CSVDoc::View::createMenuEntry(CSMWorld::UniversalId::Type type, QMenu* menu, const char* shortcutName)
{
const std::string title = CSMWorld::UniversalId(type).getTypeName();
QAction* entry = new QAction(QString::fromStdString(title), this);
setupShortcut(shortcutName, entry);
const std::string iconName = CSMWorld::UniversalId(type).getIcon();
if (!iconName.empty() && iconName != ":placeholder")
entry->setIcon(Misc::ScalableIcon::load(QString::fromStdString(iconName)));
menu->addAction(entry);
return entry;
}
QAction* CSVDoc::View::createMenuEntry(
const std::string& title, const std::string& iconName, QMenu* menu, const char* shortcutName)
{
QAction* entry = new QAction(QString::fromStdString(title), this);
setupShortcut(shortcutName, entry);
if (!iconName.empty() && iconName != ":placeholder")
entry->setIcon(Misc::ScalableIcon::load(QString::fromStdString(iconName)));
menu->addAction(entry);
return entry;
}
void CSVDoc::View::setupUi()
{
setupFileMenu();
setupEditMenu();
setupViewMenu();
setupWorldMenu();
setupMechanicsMenu();
setupCharacterMenu();
setupAssetsMenu();
setupDebugMenu();
setupHelpMenu();
}
void CSVDoc::View::setupShortcut(const char* name, QAction* action)
{
CSMPrefs::Shortcut* shortcut = new CSMPrefs::Shortcut(name, this);
shortcut->associateAction(action);
}
void CSVDoc::View::updateTitle()
{
std::ostringstream stream;
stream << Files::pathToUnicodeString(mDocument->getSavePath().filename());
if (mDocument->getState() & CSMDoc::State_Modified)
stream << " *";
if (mViewTotal > 1)
stream << " [" << (mViewIndex + 1) << "/" << mViewTotal << "]";
CSMPrefs::Category& windows = CSMPrefs::State::get()["Windows"];
bool hideTitle = windows["hide-subview"].isTrue() && mSubViews.size() == 1 && !mSubViews.at(0)->isFloating();
if (hideTitle)
stream << " - " << mSubViews.at(0)->getTitle();
setWindowTitle(QString::fromUtf8(stream.str().c_str()));
}
void CSVDoc::View::updateSubViewIndices(SubView* view)
{
CSMPrefs::Category& windows = CSMPrefs::State::get()["Windows"];
if (view && mSubViews.contains(view))
{
mSubViews.removeOne(view);
// adjust (reduce) the scroll area (even floating), except when it is "Scrollbar Only"
if (windows["mainwindow-scrollbar"].toString() == "Grow then Scroll")
updateScrollbar();
}
bool hideTitle = windows["hide-subview"].isTrue() && mSubViews.size() == 1 && !mSubViews.at(0)->isFloating();
updateTitle();
for (SubView* subView : mSubViews)
{
if (!subView->isFloating())
{
if (hideTitle)
{
subView->setTitleBarWidget(new QWidget(this));
subView->setWindowTitle(QString::fromUtf8(subView->getTitle().c_str()));
}
else
{
delete subView->titleBarWidget();
subView->setTitleBarWidget(nullptr);
}
}
}
}
void CSVDoc::View::updateActions()
{
bool editing = !(mDocument->getState() & CSMDoc::State_Locked);
bool running = mDocument->getState() & CSMDoc::State_Running;
for (std::vector<QAction*>::iterator iter(mEditingActions.begin()); iter != mEditingActions.end(); ++iter)
(*iter)->setEnabled(editing);
mUndo->setEnabled(editing && mDocument->getUndoStack().canUndo());
mRedo->setEnabled(editing && mDocument->getUndoStack().canRedo());
mSave->setEnabled(!(mDocument->getState() & CSMDoc::State_Saving) && !running);
mVerify->setEnabled(!(mDocument->getState() & CSMDoc::State_Verifying));
mGlobalDebugProfileMenu->updateActions(running);
mStopDebug->setEnabled(running);
mMerge->setEnabled(mDocument->getContentFiles().size() > 1 && !(mDocument->getState() & CSMDoc::State_Merging));
}
CSVDoc::View::View(ViewManager& viewManager, CSMDoc::Document* document, int totalViews)
: mViewManager(viewManager)
, mDocument(document)
, mViewIndex(totalViews - 1)
, mViewTotal(totalViews)
, mScroll(nullptr)
, mScrollbarOnly(false)
{
CSMPrefs::Category& windows = CSMPrefs::State::get()["Windows"];
int width = std::max(windows["default-width"].toInt(), 300);
int height = std::max(windows["default-height"].toInt(), 300);
resize(width, height);
mSubViewWindow.setDockOptions(QMainWindow::AllowNestedDocks);
if (windows["mainwindow-scrollbar"].toString() == "Grow Only")
{
setCentralWidget(&mSubViewWindow);
}
else
{
createScrollArea();
}
mOperations = new Operations;
addDockWidget(Qt::BottomDockWidgetArea, mOperations);
setContextMenuPolicy(Qt::NoContextMenu);
updateTitle();
setupUi();
updateActions();
CSVWorld::addSubViewFactories(mSubViewFactory);
CSVTools::addSubViewFactories(mSubViewFactory);
mSubViewFactory.add(CSMWorld::UniversalId::Type_RunLog, new SubViewFactory<RunLogSubView>);
connect(mOperations, &Operations::abortOperation, this, &View::abortOperation);
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &View::settingChanged);
}
const CSMDoc::Document* CSVDoc::View::getDocument() const
{
return mDocument;
}
CSMDoc::Document* CSVDoc::View::getDocument()
{
return mDocument;
}
void CSVDoc::View::setIndex(int viewIndex, int totalViews)
{
mViewIndex = viewIndex;
mViewTotal = totalViews;
updateTitle();
}
void CSVDoc::View::updateDocumentState()
{
updateTitle();
updateActions();
static const int operations[] = {
CSMDoc::State_Saving,
CSMDoc::State_Verifying,
CSMDoc::State_Searching,
CSMDoc::State_Merging,
// end marker
-1,
};
int state = mDocument->getState();
for (int i = 0; operations[i] != -1; ++i)
if (!(state & operations[i]))
mOperations->quitOperation(operations[i]);
QList<CSVDoc::SubView*> subViews = findChildren<CSVDoc::SubView*>();
for (QList<CSVDoc::SubView*>::iterator iter(subViews.begin()); iter != subViews.end(); ++iter)
(*iter)->setEditLock(state & CSMDoc::State_Locked);
}
void CSVDoc::View::updateProgress(int current, int max, int type, int threads)
{
mOperations->setProgress(current, max, type, threads);
}
void CSVDoc::View::addSubView(const CSMWorld::UniversalId& id, const std::string& hint)
{
CSMPrefs::Category& windows = CSMPrefs::State::get()["Windows"];
bool isReferenceable = id.getClass() == CSMWorld::UniversalId::Class_RefRecord;
// User setting to reuse sub views (on a per top level view basis)
if (windows["reuse"].isTrue())
{
for (SubView* sb : mSubViews)
{
bool isSubViewReferenceable = sb->getUniversalId().getType() == CSMWorld::UniversalId::Type_Referenceable;
if ((isReferenceable && isSubViewReferenceable && id.getId() == sb->getUniversalId().getId())
|| (!isReferenceable && id == sb->getUniversalId()))
{
sb->setFocus();
if (!hint.empty())
sb->useHint(hint);
return;
}
}
}
if (mScroll)
QObject::connect(mScroll->horizontalScrollBar(), &QScrollBar::rangeChanged, this, &View::moveScrollBarToEnd);
// User setting for limiting the number of sub views per top level view.
// Automatically open a new top level view if this number is exceeded
//
// If the sub view limit setting is one, the sub view title bar is hidden and the
// text in the main title bar is adjusted accordingly
if (mSubViews.size() >= windows["max-subviews"].toInt()) // create a new top level view
{
mViewManager.addView(mDocument, id, hint);
return;
}
SubView* view = nullptr;
if (isReferenceable)
{
view = mSubViewFactory.makeSubView(
CSMWorld::UniversalId(CSMWorld::UniversalId::Type_Referenceable, id), *mDocument);
}
else
{
view = mSubViewFactory.makeSubView(id, *mDocument);
}
assert(view);
view->setParent(this);
view->setEditLock(mDocument->getState() & CSMDoc::State_Locked);
mSubViews.append(view); // only after assert
int minWidth = windows["minimum-width"].toInt();
view->setMinimumWidth(minWidth);
view->setStatusBar(mShowStatusBar->isChecked());
// Work out how to deal with additional subviews
//
// Policy for "Grow then Scroll":
//
// - Increase the horizontal width of the mainwindow until it becomes greater than or equal
// to the screen (monitor) width.
// - Move the mainwindow position sideways if necessary to fit within the screen.
// - Any more additions increases the size of the mSubViewWindow (horizontal scrollbar
// should become visible)
// - Move the scroll bar to the newly added subview
//
mScrollbarOnly = windows["mainwindow-scrollbar"].toString() == "Scrollbar Only";
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
updateWidth(windows["grow-limit"].isTrue(), minWidth);
#else
updateWidth(true, minWidth);
#endif
mSubViewWindow.addDockWidget(Qt::TopDockWidgetArea, view);
updateSubViewIndices();
connect(view, &SubView::focusId, this, &View::addSubView);
connect(view, qOverload<SubView*>(&SubView::closeRequest), this, &View::closeRequest);
connect(view, &SubView::updateTitle, this, &View::updateTitle);
connect(view, &SubView::updateSubViewIndices, this, &View::updateSubViewIndices);
CSVWorld::TableSubView* tableView = dynamic_cast<CSVWorld::TableSubView*>(view);
if (tableView)
{
connect(this, &View::requestFocus, tableView, &CSVWorld::TableSubView::requestFocus);
}
CSVWorld::SceneSubView* sceneView = dynamic_cast<CSVWorld::SceneSubView*>(view);
if (sceneView)
{
connect(sceneView, &CSVWorld::SceneSubView::requestFocus, this, &View::onRequestFocus);
}
if (CSMPrefs::State::get()["ID Tables"]["subview-new-window"].isTrue())
{
CSVWorld::DialogueSubView* dialogueView = dynamic_cast<CSVWorld::DialogueSubView*>(view);
if (dialogueView)
dialogueView->setFloating(true);
CSVWorld::ScriptSubView* scriptView = dynamic_cast<CSVWorld::ScriptSubView*>(view);
if (scriptView)
scriptView->setFloating(true);
}
view->show();
if (!hint.empty())
view->useHint(hint);
}
void CSVDoc::View::moveScrollBarToEnd(int min, int max)
{
if (mScroll)
{
mScroll->horizontalScrollBar()->setValue(max);
QObject::disconnect(mScroll->horizontalScrollBar(), &QScrollBar::rangeChanged, this, &View::moveScrollBarToEnd);
}
}
void CSVDoc::View::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "Windows/hide-subview")
updateSubViewIndices(nullptr);
else if (*setting == "Windows/mainwindow-scrollbar")
{
if (setting->toString() != "Grow Only")
{
if (mScroll)
{
if (setting->toString() == "Scrollbar Only")
{
mScrollbarOnly = true;
mSubViewWindow.setMinimumWidth(0);
}
else if (mScrollbarOnly)
{
mScrollbarOnly = false;
updateScrollbar();
}
}
else
{
createScrollArea();
}
}
else if (mScroll)
{
mScroll->takeWidget();
setCentralWidget(&mSubViewWindow);
mScroll->deleteLater();
mScroll = nullptr;
}
}
}
void CSVDoc::View::newView()
{
mViewManager.addView(mDocument);
}
void CSVDoc::View::save()
{
mDocument->save();
}
void CSVDoc::View::openHelp()
{
Misc::HelpViewer::openHelp("manuals/openmw-cs/index.html");
}
void CSVDoc::View::tutorial()
{
Misc::HelpViewer::openHelp("manuals/openmw-cs/tour.html");
}
void CSVDoc::View::infoAbout()
{
// Get current OpenMW version
QString versionInfo = (Version::getOpenmwVersionDescription() +
#if defined(__x86_64__) || defined(_M_X64)
" (64-bit)")
.c_str();
#else
" (32-bit)")
.c_str();
#endif
// Get current year
const auto copyrightInfo = Misc::timeToString(std::chrono::system_clock::now(), "Copyright © 2008-%Y OpenMW Team");
QString aboutText = QString(
"<p style=\"white-space: pre-wrap;\">"
"<b><h2>OpenMW Construction Set</h2></b>"
"%1\n\n"
"%2\n\n"
"%3\n\n"
"<table>"
"<tr><td>%4</td><td><a href=\"https://openmw.org\">https://openmw.org</a></td></tr>"
"<tr><td>%5</td><td><a href=\"https://forum.openmw.org\">https://forum.openmw.org</a></td></tr>"
"<tr><td>%6</td><td><a "
"href=\"https://gitlab.com/OpenMW/openmw/issues\">https://gitlab.com/OpenMW/openmw/issues</a></td></tr>"
"<tr><td>%7</td><td><a href=\"https://web.libera.chat/#openmw\">ircs://irc.libera.chat/#openmw</a></td></tr>"
"</table>"
"</p>")
.arg(versionInfo,
tr("OpenMW-CS is a content file editor for OpenMW, a modern, free and open source game "
"engine."),
tr(copyrightInfo.c_str()), tr("Home Page:"), tr("Forum:"), tr("Bug Tracker:"),
tr("IRC:"));
QMessageBox::about(this, "About OpenMW-CS", aboutText);
}
void CSVDoc::View::infoAboutQt()
{
QMessageBox::aboutQt(this);
}
void CSVDoc::View::verify()
{
addSubView(mDocument->verify());
}
void CSVDoc::View::addGlobalsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Globals);
}
void CSVDoc::View::addGmstsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Gmsts);
}
void CSVDoc::View::addSkillsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Skills);
}
void CSVDoc::View::addClassesSubView()
{
addSubView(CSMWorld::UniversalId::Type_Classes);
}
void CSVDoc::View::addFactionsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Factions);
}
void CSVDoc::View::addRacesSubView()
{
addSubView(CSMWorld::UniversalId::Type_Races);
}
void CSVDoc::View::addSoundsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Sounds);
}
void CSVDoc::View::addScriptsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Scripts);
}
void CSVDoc::View::addRegionsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Regions);
}
void CSVDoc::View::addBirthsignsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Birthsigns);
}
void CSVDoc::View::addSpellsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Spells);
}
void CSVDoc::View::addCellsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Cells);
}
void CSVDoc::View::addReferenceablesSubView()
{
addSubView(CSMWorld::UniversalId::Type_Referenceables);
}
void CSVDoc::View::addReferencesSubView()
{
addSubView(CSMWorld::UniversalId::Type_References);
}
void CSVDoc::View::addRegionMapSubView()
{
addSubView(CSMWorld::UniversalId::Type_RegionMap);
}
void CSVDoc::View::addFiltersSubView()
{
addSubView(CSMWorld::UniversalId::Type_Filters);
}
void CSVDoc::View::addTopicsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Topics);
}
void CSVDoc::View::addJournalsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Journals);
}
void CSVDoc::View::addTopicInfosSubView()
{
addSubView(CSMWorld::UniversalId::Type_TopicInfos);
}
void CSVDoc::View::addJournalInfosSubView()
{
addSubView(CSMWorld::UniversalId::Type_JournalInfos);
}
void CSVDoc::View::addEnchantmentsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Enchantments);
}
void CSVDoc::View::addBodyPartsSubView()
{
addSubView(CSMWorld::UniversalId::Type_BodyParts);
}
void CSVDoc::View::addSoundGensSubView()
{
addSubView(CSMWorld::UniversalId::Type_SoundGens);
}
void CSVDoc::View::addMeshesSubView()
{
addSubView(CSMWorld::UniversalId::Type_Meshes);
}
void CSVDoc::View::addIconsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Icons);
}
void CSVDoc::View::addMusicsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Musics);
}
void CSVDoc::View::addSoundsResSubView()
{
addSubView(CSMWorld::UniversalId::Type_SoundsRes);
}
void CSVDoc::View::addMagicEffectsSubView()
{
addSubView(CSMWorld::UniversalId::Type_MagicEffects);
}
void CSVDoc::View::addTexturesSubView()
{
addSubView(CSMWorld::UniversalId::Type_Textures);
}
void CSVDoc::View::addVideosSubView()
{
addSubView(CSMWorld::UniversalId::Type_Videos);
}
void CSVDoc::View::addDebugProfilesSubView()
{
addSubView(CSMWorld::UniversalId::Type_DebugProfiles);
}
void CSVDoc::View::addRunLogSubView()
{
addSubView(CSMWorld::UniversalId::Type_RunLog);
}
void CSVDoc::View::addLandsSubView()
{
addSubView(CSMWorld::UniversalId::Type_Lands);
}
void CSVDoc::View::addLandTexturesSubView()
{
addSubView(CSMWorld::UniversalId::Type_LandTextures);
}
void CSVDoc::View::addPathgridSubView()
{
addSubView(CSMWorld::UniversalId::Type_Pathgrids);
}
void CSVDoc::View::addStartScriptsSubView()
{
addSubView(CSMWorld::UniversalId::Type_StartScripts);
}
void CSVDoc::View::addSearchSubView()
{
addSubView(mDocument->newSearch());
}
void CSVDoc::View::addMetaDataSubView()
{
addSubView(CSMWorld::UniversalId(CSMWorld::UniversalId::Type_MetaData, "sys::meta"));
}
void CSVDoc::View::abortOperation(int type)
{
mDocument->abortOperation(type);
updateActions();
}
CSVDoc::Operations* CSVDoc::View::getOperations() const
{
return mOperations;
}
void CSVDoc::View::exit()
{
emit exitApplicationRequest(this);
}
void CSVDoc::View::resizeViewWidth(int width)
{
if (width >= 0)
resize(width, geometry().height());
}
void CSVDoc::View::resizeViewHeight(int height)
{
if (height >= 0)
resize(geometry().width(), height);
}
void CSVDoc::View::toggleShowStatusBar(bool show)
{
for (QObject* view : mSubViewWindow.children())
{
if (CSVDoc::SubView* subView = dynamic_cast<CSVDoc::SubView*>(view))
subView->setStatusBar(show);
}
}
void CSVDoc::View::toggleStatusBar(bool checked)
{
mShowStatusBar->setChecked(checked);
}
void CSVDoc::View::loadErrorLog()
{
addSubView(CSMWorld::UniversalId(CSMWorld::UniversalId::Type_LoadErrorLog, 0));
}
void CSVDoc::View::run(const std::string& profile, const std::string& startupInstruction)
{
mDocument->startRunning(profile, startupInstruction);
}
void CSVDoc::View::stop()
{
mDocument->stopRunning();
}
void CSVDoc::View::closeRequest(SubView* subView)
{
CSMPrefs::Category& windows = CSMPrefs::State::get()["Windows"];
if (mSubViews.size() > 1 || mViewTotal <= 1 || !windows["hide-subview"].isTrue())
{
subView->deleteLater();
mSubViews.removeOne(subView);
}
else if (mViewManager.closeRequest(this))
mViewManager.removeDocAndView(mDocument);
}
void CSVDoc::View::updateScrollbar()
{
QRect rect;
QWidget* topLevel = QApplication::topLevelAt(pos());
if (topLevel)
rect = topLevel->rect();
else
rect = this->rect();
int newWidth = 0;
for (int i = 0; i < mSubViews.size(); ++i)
{
newWidth += mSubViews[i]->width();
}
int frameWidth = frameGeometry().width() - width();
if ((newWidth + frameWidth) >= rect.width())
mSubViewWindow.setMinimumWidth(newWidth);
else
mSubViewWindow.setMinimumWidth(0);
}
void CSVDoc::View::merge()
{
emit mergeDocument(mDocument);
}
void CSVDoc::View::updateWidth(bool isGrowLimit, int minSubViewWidth)
{
QRect rect;
if (isGrowLimit)
{
QScreen* screen = getWidgetScreen(pos());
rect = screen->geometry();
}
else
rect = desktopRect();
if (!mScrollbarOnly && mScroll && mSubViews.size() > 1)
{
int newWidth = width() + minSubViewWidth;
int frameWidth = frameGeometry().width() - width();
if (newWidth + frameWidth <= rect.width())
{
resize(newWidth, height());
// WARNING: below code assumes that new subviews are added to the right
if (x() > rect.width() - (newWidth + frameWidth))
move(rect.width() - (newWidth + frameWidth), y()); // shift left to stay within the screen
}
else
{
// full width
resize(rect.width() - frameWidth, height());
mSubViewWindow.setMinimumWidth(mSubViewWindow.width() + minSubViewWidth);
move(0, y());
}
}
}
void CSVDoc::View::createScrollArea()
{
mScroll = new QScrollArea(this);
mScroll->setWidgetResizable(true);
mScroll->setWidget(&mSubViewWindow);
setCentralWidget(mScroll);
}
void CSVDoc::View::onRequestFocus(const std::string& id)
{
if (CSMPrefs::get()["3D Scene Editing"]["open-list-view"].isTrue())
{
addReferencesSubView();
emit requestFocus(id);
}
else
{
addSubView(CSMWorld::UniversalId(CSMWorld::UniversalId::Type_Reference, id));
}
}
QScreen* CSVDoc::View::getWidgetScreen(const QPoint& position)
{
QScreen* screen = QApplication::screenAt(position);
if (screen == nullptr)
{
QPoint clampedPosition = position;
// If we failed to find the screen,
// clamp negative positions and try again
if (clampedPosition.x() <= 0)
clampedPosition.setX(0);
if (clampedPosition.y() <= 0)
clampedPosition.setY(0);
screen = QApplication::screenAt(clampedPosition);
}
if (screen == nullptr)
throw std::runtime_error(
Misc::StringUtils::format("Can not detect the screen for position [%d, %d]", position.x(), position.y()));
return screen;
}
| 37,472
|
C++
|
.cpp
| 934
| 34.928266
| 120
| 0.694262
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,094
|
startup.cpp
|
OpenMW_openmw/apps/opencs/view/doc/startup.cpp
|
#include "startup.hpp"
#include <components/misc/scalableicon.hpp>
#include <QGridLayout>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QPushButton>
#include <QRect>
#include <QScreen>
#include <QVBoxLayout>
QPushButton* CSVDoc::StartupDialogue::addButton(const QString& label, const QString& icon)
{
int column = mColumn--;
QPushButton* button = new QPushButton(this);
button->setIcon(Misc::ScalableIcon::load(icon));
button->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
mLayout->addWidget(button, 0, column);
mLayout->addWidget(new QLabel(label, this), 1, column, Qt::AlignCenter);
int width = mLayout->itemAtPosition(1, column)->widget()->sizeHint().width();
if (width > mWidth)
mWidth = width;
return button;
}
QWidget* CSVDoc::StartupDialogue::createButtons()
{
QWidget* widget = new QWidget(this);
mLayout = new QGridLayout(widget);
/// \todo add icons
QPushButton* loadDocument = addButton("Edit A Content File", ":startup/edit-content");
connect(loadDocument, &QPushButton::clicked, this, &StartupDialogue::loadDocument);
QPushButton* createAddon = addButton("Create A New Addon", ":startup/create-addon");
connect(createAddon, &QPushButton::clicked, this, &StartupDialogue::createAddon);
QPushButton* createGame = addButton("Create A New Game", ":startup/create-game");
connect(createGame, &QPushButton::clicked, this, &StartupDialogue::createGame);
for (int i = 0; i < 3; ++i)
mLayout->setColumnMinimumWidth(i, mWidth);
mLayout->setRowMinimumHeight(0, mWidth);
mLayout->setSizeConstraint(QLayout::SetMinimumSize);
mLayout->setHorizontalSpacing(32);
mLayout->setContentsMargins(16, 16, 16, 8);
loadDocument->setIconSize(QSize(mWidth, mWidth));
createGame->setIconSize(QSize(mWidth, mWidth));
createAddon->setIconSize(QSize(mWidth, mWidth));
widget->setLayout(mLayout);
return widget;
}
QWidget* CSVDoc::StartupDialogue::createTools()
{
QWidget* widget = new QWidget(this);
QHBoxLayout* layout = new QHBoxLayout(widget);
layout->setDirection(QBoxLayout::RightToLeft);
layout->setContentsMargins(4, 4, 4, 4);
QPushButton* config = new QPushButton(widget);
config->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
config->setIcon(Misc::ScalableIcon::load(":startup/configure"));
config->setToolTip("Open user settings");
layout->addWidget(config);
layout->addWidget(new QWidget, 1); // dummy widget; stops buttons from taking all the space
widget->setLayout(layout);
connect(config, &QPushButton::clicked, this, &StartupDialogue::editConfig);
return widget;
}
CSVDoc::StartupDialogue::StartupDialogue()
: mWidth(0)
, mColumn(2)
{
setWindowTitle("OpenMW-CS");
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(createButtons());
layout->addWidget(createTools());
/// \todo remove this label once we are feature complete and convinced that this thing is
/// working properly.
QLabel* warning = new QLabel(
"<font color=Red>WARNING: OpenMW-CS is in alpha stage.<p>The editor is not feature complete and not "
"sufficiently tested.<br>In theory your data should be safe. But we strongly advise to make backups regularly "
"if you are working with live data.</font color>");
QFont font;
font.setPointSize(12);
font.setBold(true);
warning->setFont(font);
warning->setWordWrap(true);
layout->addWidget(warning, 1);
setLayout(layout);
QRect scr = QGuiApplication::primaryScreen()->geometry();
QRect rect = geometry();
move(scr.center().x() - rect.center().x(), scr.center().y() - rect.center().y());
}
| 3,877
|
C++
|
.cpp
| 89
| 38.898876
| 119
| 0.719701
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,095
|
filedialog.cpp
|
OpenMW_openmw/apps/opencs/view/doc/filedialog.cpp
|
#include "filedialog.hpp"
#include <QDialogButtonBox>
#include <QPushButton>
#include <components/contentselector/model/contentmodel.hpp>
#include <components/contentselector/model/esmfile.hpp>
#include <components/contentselector/view/contentselector.hpp>
#include <components/files/qtconversion.hpp>
#include <string>
#include "adjusterwidget.hpp"
#include "filewidget.hpp"
#include "ui_filedialog.h"
CSVDoc::FileDialog::FileDialog(QWidget* parent)
: QDialog(parent)
, mSelector(nullptr)
, ui(std::make_unique<Ui::FileDialog>())
, mAction(ContentAction_Undefined)
, mFileWidget(nullptr)
, mAdjusterWidget(nullptr)
, mDialogBuilt(false)
{
ui->setupUi(this);
resize(400, 400);
setObjectName("FileDialog");
mSelector = new ContentSelectorView::ContentSelector(ui->contentSelectorWidget, /*showOMWScripts=*/false);
mAdjusterWidget = new AdjusterWidget(this);
}
CSVDoc::FileDialog::~FileDialog() = default;
void CSVDoc::FileDialog::addFiles(const std::vector<std::filesystem::path>& dataDirs)
{
for (auto iter = dataDirs.rbegin(); iter != dataDirs.rend(); ++iter)
{
QString path = Files::pathToQString(*iter);
mSelector->addFiles(path);
}
mSelector->sortFiles();
}
void CSVDoc::FileDialog::setEncoding(const QString& encoding)
{
mSelector->setEncoding(encoding);
}
void CSVDoc::FileDialog::clearFiles()
{
mSelector->clearFiles();
}
QStringList CSVDoc::FileDialog::selectedFilePaths()
{
QStringList filePaths;
for (ContentSelectorModel::EsmFile* file : mSelector->selectedFiles())
filePaths.append(file->filePath());
return filePaths;
}
void CSVDoc::FileDialog::setLocalData(const std::filesystem::path& localData)
{
mAdjusterWidget->setLocalData(localData);
}
void CSVDoc::FileDialog::showDialog(ContentAction action)
{
mAction = action;
ui->projectGroupBoxLayout->insertWidget(0, mAdjusterWidget);
switch (mAction)
{
case ContentAction_New:
buildNewFileView();
break;
case ContentAction_Edit:
buildOpenFileView();
break;
default:
break;
}
mAdjusterWidget->setFilenameCheck(mAction == ContentAction_New);
if (!mDialogBuilt)
{
// connections common to both dialog view flavors
connect(mSelector, &ContentSelectorView::ContentSelector::signalCurrentGamefileIndexChanged, this,
qOverload<int>(&FileDialog::slotUpdateAcceptButton));
connect(ui->projectButtonBox, &QDialogButtonBox::rejected, this, &FileDialog::slotRejected);
mDialogBuilt = true;
}
show();
raise();
activateWindow();
}
void CSVDoc::FileDialog::buildNewFileView()
{
setWindowTitle(tr("Create a new addon"));
QPushButton* createButton = ui->projectButtonBox->button(QDialogButtonBox::Ok);
createButton->setText("Create");
createButton->setEnabled(false);
if (!mFileWidget)
{
mFileWidget = new FileWidget(this);
mFileWidget->setType(true);
mFileWidget->extensionLabelIsVisible(true);
connect(mFileWidget, &FileWidget::nameChanged, mAdjusterWidget, &AdjusterWidget::setName);
connect(mFileWidget, &FileWidget::nameChanged, this,
qOverload<const QString&, bool>(&FileDialog::slotUpdateAcceptButton));
}
ui->projectGroupBoxLayout->insertWidget(0, mFileWidget);
connect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotNewFile);
}
void CSVDoc::FileDialog::buildOpenFileView()
{
setWindowTitle(tr("Open"));
ui->projectGroupBox->setTitle(QString(""));
ui->projectButtonBox->button(QDialogButtonBox::Ok)->setText("Open");
if (mSelector->isGamefileSelected())
ui->projectButtonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
else
ui->projectButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
if (!mDialogBuilt)
{
connect(mSelector, &ContentSelectorView::ContentSelector::signalAddonDataChanged, this,
&FileDialog::slotAddonDataChanged);
}
connect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotOpenFile);
}
void CSVDoc::FileDialog::slotAddonDataChanged(const QModelIndex& topleft, const QModelIndex& bottomright)
{
slotUpdateAcceptButton(0);
}
void CSVDoc::FileDialog::slotUpdateAcceptButton(int)
{
QString name = "";
if (mFileWidget && mAction == ContentAction_New)
name = mFileWidget->getName();
slotUpdateAcceptButton(name, true);
}
void CSVDoc::FileDialog::slotUpdateAcceptButton(const QString& name, bool)
{
bool success = !mSelector->selectedFiles().empty();
bool isNew = (mAction == ContentAction_New);
if (isNew)
success = !name.isEmpty();
else if (success)
{
ContentSelectorModel::EsmFile* file = mSelector->selectedFiles().back();
mAdjusterWidget->setName(file->filePath(), !file->isGameFile());
}
else
mAdjusterWidget->setName("", true);
ui->projectButtonBox->button(QDialogButtonBox::Ok)->setEnabled(success);
}
QString CSVDoc::FileDialog::filename() const
{
if (mAction == ContentAction_New)
return "";
return mSelector->currentFile();
}
void CSVDoc::FileDialog::slotRejected()
{
emit rejected();
disconnect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotNewFile);
disconnect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotOpenFile);
if (mFileWidget)
{
delete mFileWidget;
mFileWidget = nullptr;
}
close();
}
void CSVDoc::FileDialog::slotNewFile()
{
emit signalCreateNewFile(mAdjusterWidget->getPath());
if (mFileWidget)
{
delete mFileWidget;
mFileWidget = nullptr;
}
disconnect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotNewFile);
close();
}
void CSVDoc::FileDialog::slotOpenFile()
{
ContentSelectorModel::EsmFile* file = mSelector->selectedFiles().back();
mAdjusterWidget->setName(file->filePath(), !file->isGameFile());
emit signalOpenFiles(mAdjusterWidget->getPath());
disconnect(ui->projectButtonBox, &QDialogButtonBox::accepted, this, &FileDialog::slotOpenFile);
close();
}
| 6,298
|
C++
|
.cpp
| 180
| 30.072222
| 110
| 0.71824
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,096
|
viewmanager.cpp
|
OpenMW_openmw/apps/opencs/view/doc/viewmanager.cpp
|
#include "viewmanager.hpp"
#include <algorithm>
#include <cstddef>
#include <filesystem>
#include <map>
#include <type_traits>
#include <utility>
#include <vector>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/columnbase.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/doc/loader.hpp>
#include <components/esm3/variant.hpp>
#include <components/files/qtconversion.hpp>
#include <QApplication>
#include <QMessageBox>
#include <QPushButton>
#include "../../model/doc/document.hpp"
#include "../../model/doc/documentmanager.hpp"
#include "../../model/prefs/state.hpp"
#include "../world/colordelegate.hpp"
#include "../world/enumdelegate.hpp"
#include "../world/idcompletiondelegate.hpp"
#include "../world/idtypedelegate.hpp"
#include "../world/recordstatusdelegate.hpp"
#include "../world/vartypedelegate.hpp"
#include "view.hpp"
void CSVDoc::ViewManager::updateIndices()
{
std::map<CSMDoc::Document*, std::pair<int, int>> documents;
for (std::vector<View*>::const_iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
{
std::map<CSMDoc::Document*, std::pair<int, int>>::iterator document = documents.find((*iter)->getDocument());
if (document == documents.end())
document = documents
.insert(std::make_pair(
(*iter)->getDocument(), std::make_pair(0, countViews((*iter)->getDocument()))))
.first;
(*iter)->setIndex(document->second.first++, document->second.second);
}
}
CSVDoc::ViewManager::ViewManager(CSMDoc::DocumentManager& documentManager)
: mDocumentManager(documentManager)
, mExitOnSaveStateChange(false)
, mUserWarned(false)
{
mDelegateFactories = new CSVWorld::CommandDelegateFactoryCollection;
mDelegateFactories->add(CSMWorld::ColumnBase::Display_GmstVarType,
new CSVWorld::VarTypeDelegateFactory(ESM::VT_None, ESM::VT_String, ESM::VT_Int, ESM::VT_Float));
mDelegateFactories->add(CSMWorld::ColumnBase::Display_GlobalVarType,
new CSVWorld::VarTypeDelegateFactory(ESM::VT_Short, ESM::VT_Long, ESM::VT_Float));
mDelegateFactories->add(CSMWorld::ColumnBase::Display_RecordState, new CSVWorld::RecordStatusDelegateFactory());
mDelegateFactories->add(CSMWorld::ColumnBase::Display_RefRecordType, new CSVWorld::IdTypeDelegateFactory());
mDelegateFactories->add(CSMWorld::ColumnBase::Display_Colour, new CSVWorld::ColorDelegateFactory());
std::vector<CSMWorld::ColumnBase::Display> idCompletionColumns = CSMWorld::IdCompletionManager::getDisplayTypes();
for (std::vector<CSMWorld::ColumnBase::Display>::const_iterator current = idCompletionColumns.begin();
current != idCompletionColumns.end(); ++current)
{
mDelegateFactories->add(*current, new CSVWorld::IdCompletionDelegateFactory());
}
struct Mapping
{
CSMWorld::ColumnBase::Display mDisplay;
CSMWorld::Columns::ColumnId mColumnId;
bool mAllowNone;
};
static const Mapping sMapping[] = {
{ CSMWorld::ColumnBase::Display_Specialisation, CSMWorld::Columns::ColumnId_Specialisation, false },
{ CSMWorld::ColumnBase::Display_Attribute, CSMWorld::Columns::ColumnId_Attribute, true },
{ CSMWorld::ColumnBase::Display_SpellType, CSMWorld::Columns::ColumnId_SpellType, false },
{ CSMWorld::ColumnBase::Display_ApparatusType, CSMWorld::Columns::ColumnId_ApparatusType, false },
{ CSMWorld::ColumnBase::Display_ArmorType, CSMWorld::Columns::ColumnId_ArmorType, false },
{ CSMWorld::ColumnBase::Display_ClothingType, CSMWorld::Columns::ColumnId_ClothingType, false },
{ CSMWorld::ColumnBase::Display_CreatureType, CSMWorld::Columns::ColumnId_CreatureType, false },
{ CSMWorld::ColumnBase::Display_WeaponType, CSMWorld::Columns::ColumnId_WeaponType, false },
{ CSMWorld::ColumnBase::Display_DialogueType, CSMWorld::Columns::ColumnId_DialogueType, false },
{ CSMWorld::ColumnBase::Display_QuestStatusType, CSMWorld::Columns::ColumnId_QuestStatusType, false },
{ CSMWorld::ColumnBase::Display_EnchantmentType, CSMWorld::Columns::ColumnId_EnchantmentType, false },
{ CSMWorld::ColumnBase::Display_BodyPartType, CSMWorld::Columns::ColumnId_BodyPartType, false },
{ CSMWorld::ColumnBase::Display_MeshType, CSMWorld::Columns::ColumnId_MeshType, false },
{ CSMWorld::ColumnBase::Display_Gender, CSMWorld::Columns::ColumnId_Gender, true },
{ CSMWorld::ColumnBase::Display_SoundGeneratorType, CSMWorld::Columns::ColumnId_SoundGeneratorType, false },
{ CSMWorld::ColumnBase::Display_School, CSMWorld::Columns::ColumnId_School, false },
{ CSMWorld::ColumnBase::Display_SkillId, CSMWorld::Columns::ColumnId_Skill, true },
{ CSMWorld::ColumnBase::Display_EffectRange, CSMWorld::Columns::ColumnId_EffectRange, false },
{ CSMWorld::ColumnBase::Display_EffectId, CSMWorld::Columns::ColumnId_EffectId, false },
{ CSMWorld::ColumnBase::Display_PartRefType, CSMWorld::Columns::ColumnId_PartRefType, false },
{ CSMWorld::ColumnBase::Display_AiPackageType, CSMWorld::Columns::ColumnId_AiPackageType, false },
{ CSMWorld::ColumnBase::Display_InfoCondFunc, CSMWorld::Columns::ColumnId_InfoCondFunc, false },
{ CSMWorld::ColumnBase::Display_InfoCondComp, CSMWorld::Columns::ColumnId_InfoCondComp, false },
{ CSMWorld::ColumnBase::Display_IngredEffectId, CSMWorld::Columns::ColumnId_EffectId, true },
{ CSMWorld::ColumnBase::Display_EffectSkill, CSMWorld::Columns::ColumnId_Skill, false },
{ CSMWorld::ColumnBase::Display_EffectAttribute, CSMWorld::Columns::ColumnId_Attribute, false },
{ CSMWorld::ColumnBase::Display_BookType, CSMWorld::Columns::ColumnId_BookType, false },
{ CSMWorld::ColumnBase::Display_BloodType, CSMWorld::Columns::ColumnId_BloodType, false },
{ CSMWorld::ColumnBase::Display_EmitterType, CSMWorld::Columns::ColumnId_EmitterType, false },
{ CSMWorld::ColumnBase::Display_GenderNpc, CSMWorld::Columns::ColumnId_Gender, false },
};
for (std::size_t i = 0; i < sizeof(sMapping) / sizeof(Mapping); ++i)
mDelegateFactories->add(sMapping[i].mDisplay,
new CSVWorld::EnumDelegateFactory(
CSMWorld::Columns::getEnums(sMapping[i].mColumnId), sMapping[i].mAllowNone));
connect(&mDocumentManager, &CSMDoc::DocumentManager::loadRequest, &mLoader, &Loader::add);
connect(&mDocumentManager, &CSMDoc::DocumentManager::loadingStopped, &mLoader, &Loader::loadingStopped);
connect(&mDocumentManager, &CSMDoc::DocumentManager::nextStage, &mLoader, &Loader::nextStage);
connect(&mDocumentManager, &CSMDoc::DocumentManager::nextRecord, &mLoader, &Loader::nextRecord);
connect(&mDocumentManager, &CSMDoc::DocumentManager::loadMessage, &mLoader, &Loader::loadMessage);
connect(&mLoader, &Loader::cancel, &mDocumentManager, &CSMDoc::DocumentManager::cancelLoading);
connect(&mLoader, &Loader::close, &mDocumentManager, &CSMDoc::DocumentManager::removeDocument);
}
CSVDoc::ViewManager::~ViewManager()
{
delete mDelegateFactories;
for (std::vector<View*>::iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
delete *iter;
}
CSVDoc::View* CSVDoc::ViewManager::addView(CSMDoc::Document* document)
{
if (countViews(document) == 0)
{
// new document
connect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::documentStateChanged);
connect(document, qOverload<int, int, int, int, CSMDoc::Document*>(&CSMDoc::Document::progress), this,
&ViewManager::progress);
}
View* view = new View(*this, document, countViews(document) + 1);
mViews.push_back(view);
view->toggleStatusBar(CSMPrefs::get()["Windows"]["show-statusbar"].isTrue());
view->show();
connect(view, &View::newGameRequest, this, &ViewManager::newGameRequest);
connect(view, &View::newAddonRequest, this, &ViewManager::newAddonRequest);
connect(view, &View::loadDocumentRequest, this, &ViewManager::loadDocumentRequest);
connect(view, &View::editSettingsRequest, this, &ViewManager::editSettingsRequest);
connect(view, &View::mergeDocument, this, &ViewManager::mergeDocument);
updateIndices();
return view;
}
CSVDoc::View* CSVDoc::ViewManager::addView(
CSMDoc::Document* document, const CSMWorld::UniversalId& id, const std::string& hint)
{
View* view = addView(document);
view->addSubView(id, hint);
return view;
}
int CSVDoc::ViewManager::countViews(const CSMDoc::Document* document) const
{
int count = 0;
for (std::vector<View*>::const_iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
if ((*iter)->getDocument() == document)
++count;
return count;
}
bool CSVDoc::ViewManager::closeRequest(View* view)
{
std::vector<View*>::iterator iter = std::find(mViews.begin(), mViews.end(), view);
bool continueWithClose = false;
if (iter != mViews.end())
{
bool last = countViews(view->getDocument()) <= 1;
if (last)
continueWithClose = notifySaveOnClose(view);
else
{
(*iter)->deleteLater();
mViews.erase(iter);
updateIndices();
}
}
return continueWithClose;
}
// NOTE: This method assumes that it is called only if the last document
void CSVDoc::ViewManager::removeDocAndView(CSMDoc::Document* document)
{
for (std::vector<View*>::iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
{
// the first match should also be the only match
if ((*iter)->getDocument() == document)
{
mDocumentManager.removeDocument(document);
(*iter)->deleteLater();
mViews.erase(iter);
updateIndices();
return;
}
}
}
bool CSVDoc::ViewManager::notifySaveOnClose(CSVDoc::View* view)
{
bool result = true;
CSMDoc::Document* document = view->getDocument();
// notify user of saving in progress
if ((document->getState() & CSMDoc::State_Saving))
result = showSaveInProgressMessageBox(view);
// notify user of unsaved changes and process response
else if (document->getState() & CSMDoc::State_Modified)
result = showModifiedDocumentMessageBox(view);
return result;
}
bool CSVDoc::ViewManager::showModifiedDocumentMessageBox(CSVDoc::View* view)
{
emit closeMessageBox();
QMessageBox messageBox(view);
CSMDoc::Document* document = view->getDocument();
messageBox.setWindowTitle(Files::pathToQString(document->getSavePath().filename()));
messageBox.setText("The document has been modified.");
messageBox.setInformativeText("Do you want to save your changes?");
messageBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
messageBox.setDefaultButton(QMessageBox::Save);
messageBox.setWindowModality(Qt::NonModal);
messageBox.hide();
messageBox.show();
bool retVal = true;
connect(this, &ViewManager::closeMessageBox, &messageBox, &QMessageBox::close);
connect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
mUserWarned = true;
int response = messageBox.exec();
mUserWarned = false;
switch (response)
{
case QMessageBox::Save:
document->save();
mExitOnSaveStateChange = true;
retVal = false;
break;
case QMessageBox::Discard:
disconnect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
break;
case QMessageBox::Cancel:
// disconnect to prevent unintended view closures
disconnect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
retVal = false;
break;
default:
break;
}
return retVal;
}
bool CSVDoc::ViewManager::showSaveInProgressMessageBox(CSVDoc::View* view)
{
QMessageBox messageBox;
CSMDoc::Document* document = view->getDocument();
messageBox.setText("The document is currently being saved.");
messageBox.setInformativeText("Do you want to close now and abort saving, or wait until saving has completed?");
QPushButton* waitButton = messageBox.addButton(tr("Wait"), QMessageBox::YesRole);
QPushButton* closeButton = messageBox.addButton(tr("Close Now"), QMessageBox::RejectRole);
QPushButton* cancelButton = messageBox.addButton(tr("Cancel"), QMessageBox::NoRole);
messageBox.setDefaultButton(waitButton);
bool retVal = true;
// Connections shut down message box if operation ends before user makes a decision.
connect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
connect(this, &ViewManager::closeMessageBox, &messageBox, &QMessageBox::close);
// set / clear the user warned flag to indicate whether or not the message box is currently active.
mUserWarned = true;
messageBox.exec();
mUserWarned = false;
// if closed by the warning handler, defaults to the RejectRole button (closeButton)
if (messageBox.clickedButton() == waitButton)
{
// save the View iterator for shutdown after the save operation ends
mExitOnSaveStateChange = true;
retVal = false;
}
else if (messageBox.clickedButton() == closeButton)
{
// disconnect to avoid segmentation fault
disconnect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
view->abortOperation(CSMDoc::State_Saving);
mExitOnSaveStateChange = true;
}
else if (messageBox.clickedButton() == cancelButton)
{
// abort shutdown, allow save to complete
// disconnection to prevent unintended view closures
mExitOnSaveStateChange = false;
disconnect(document, &CSMDoc::Document::stateChanged, this, &ViewManager::onExitWarningHandler);
retVal = false;
}
return retVal;
}
void CSVDoc::ViewManager::documentStateChanged(int state, CSMDoc::Document* document)
{
for (std::vector<View*>::const_iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
if ((*iter)->getDocument() == document)
(*iter)->updateDocumentState();
}
void CSVDoc::ViewManager::progress(int current, int max, int type, int threads, CSMDoc::Document* document)
{
for (std::vector<View*>::const_iterator iter(mViews.begin()); iter != mViews.end(); ++iter)
if ((*iter)->getDocument() == document)
(*iter)->updateProgress(current, max, type, threads);
}
void CSVDoc::ViewManager::onExitWarningHandler(int state, CSMDoc::Document* document)
{
if (!(state & CSMDoc::State_Saving))
{
// if the user is being warned (message box is active), shut down the message box,
// as there is no save operation currently running
if (mUserWarned)
emit closeMessageBox();
// otherwise, the user has closed the message box before the save operation ended.
// exit the application
else if (mExitOnSaveStateChange)
QApplication::instance()->exit();
}
}
bool CSVDoc::ViewManager::removeDocument(CSVDoc::View* view)
{
if (!notifySaveOnClose(view))
return false;
else
{
// don't bother closing views or updating indicies, but remove from mViews
CSMDoc::Document* document = view->getDocument();
std::vector<View*> remainingViews;
std::vector<View*>::const_iterator iter = mViews.begin();
for (; iter != mViews.end(); ++iter)
{
if (document == (*iter)->getDocument())
(*iter)->setVisible(false);
else
remainingViews.push_back(*iter);
}
mDocumentManager.removeDocument(document);
mViews = std::move(remainingViews);
}
return true;
}
void CSVDoc::ViewManager::exitApplication(CSVDoc::View* view)
{
if (!removeDocument(view)) // close the current document first
return;
while (!mViews.empty()) // attempt to close all other documents
{
mViews.back()->activateWindow();
mViews.back()->raise(); // raise the window to alert the user
if (!removeDocument(mViews.back()))
return;
}
// Editor exits (via a signal) when the last document is deleted
}
| 16,633
|
C++
|
.cpp
| 341
| 42.252199
| 118
| 0.697321
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,097
|
loader.cpp
|
OpenMW_openmw/apps/opencs/view/doc/loader.cpp
|
#include "loader.hpp"
#include <QCloseEvent>
#include <QCursor>
#include <QDialogButtonBox>
#include <QLabel>
#include <QListWidget>
#include <QProgressBar>
#include <QVBoxLayout>
#include <apps/opencs/model/world/data.hpp>
#include <components/debug/debuglog.hpp>
#include <components/files/qtconversion.hpp>
#include <filesystem>
#include <stddef.h>
#include <type_traits>
#include <utility>
#include <vector>
#include "../../model/doc/document.hpp"
void CSVDoc::LoadingDocument::closeEvent(QCloseEvent* event)
{
event->ignore();
cancel();
}
CSVDoc::LoadingDocument::LoadingDocument(CSMDoc::Document* document)
: mDocument(document)
, mTotalRecordsLabel(0)
, mRecordsLabel(0)
, mAborted(false)
, mMessages(nullptr)
, mRecords(0)
{
setWindowTitle("Opening " + Files::pathToQString(document->getSavePath().filename()));
setMinimumWidth(400);
mLayout = new QVBoxLayout(this);
// total progress
mTotalRecordsLabel = new QLabel(this);
mLayout->addWidget(mTotalRecordsLabel);
mTotalProgress = new QProgressBar(this);
mLayout->addWidget(mTotalProgress);
mTotalProgress->setMinimum(0);
mTotalProgress->setMaximum(document->getData().getTotalRecords(document->getContentFiles()));
mTotalProgress->setTextVisible(true);
mTotalProgress->setValue(0);
mTotalRecords = 0;
mFilesLoaded = 0;
// record progress
mLayout->addWidget(mRecordsLabel = new QLabel("Records", this));
mRecordProgress = new QProgressBar(this);
mLayout->addWidget(mRecordProgress);
mRecordProgress->setMinimum(0);
mRecordProgress->setTextVisible(true);
mRecordProgress->setValue(0);
// error message
mError = new QLabel(this);
mError->setWordWrap(true);
mError->setTextInteractionFlags(Qt::TextSelectableByMouse);
mLayout->addWidget(mError);
// buttons
mButtons = new QDialogButtonBox(QDialogButtonBox::Cancel, Qt::Horizontal, this);
mLayout->addWidget(mButtons);
setLayout(mLayout);
move(QCursor::pos());
show();
connect(mButtons, &QDialogButtonBox::rejected, this, qOverload<>(&LoadingDocument::cancel));
}
void CSVDoc::LoadingDocument::nextStage(const std::string& name, int fileRecords)
{
++mFilesLoaded;
size_t numFiles = mDocument->getContentFiles().size();
mTotalRecordsLabel->setText(QString::fromUtf8(
("Loading: " + name + " (" + std::to_string(mFilesLoaded) + " of " + std::to_string((numFiles)) + ")")
.c_str()));
mTotalRecords = mTotalProgress->value();
mRecordProgress->setValue(0);
mRecordProgress->setMaximum(fileRecords > 0 ? fileRecords : 1);
mRecords = fileRecords;
}
void CSVDoc::LoadingDocument::nextRecord(int records)
{
if (records <= mRecords)
{
mTotalProgress->setValue(mTotalRecords + records);
mRecordProgress->setValue(records);
mRecordsLabel->setText("Records: " + QString::number(records) + " of " + QString::number(mRecords));
}
}
void CSVDoc::LoadingDocument::abort(const std::string& error)
{
mAborted = true;
mError->setText(QString::fromUtf8(("<font color=red>Loading failed: " + error + "</font>").c_str()));
Log(Debug::Error) << "Loading failed: " << error;
mButtons->setStandardButtons(QDialogButtonBox::Close);
}
void CSVDoc::LoadingDocument::addMessage(const std::string& message)
{
if (!mMessages)
{
mMessages = new QListWidget(this);
mLayout->insertWidget(4, mMessages);
}
new QListWidgetItem(QString::fromUtf8(message.c_str()), mMessages);
}
void CSVDoc::LoadingDocument::cancel()
{
if (!mAborted)
emit cancel(mDocument);
else
{
emit close(mDocument);
deleteLater();
}
}
CSVDoc::Loader::~Loader()
{
for (std::map<CSMDoc::Document*, LoadingDocument*>::iterator iter(mDocuments.begin()); iter != mDocuments.end();
++iter)
delete iter->second;
}
void CSVDoc::Loader::add(CSMDoc::Document* document)
{
LoadingDocument* loading = new LoadingDocument(document);
mDocuments.insert(std::make_pair(document, loading));
connect(loading, qOverload<CSMDoc::Document*>(&LoadingDocument::cancel), this, &Loader::cancel);
connect(loading, &LoadingDocument::close, this, &Loader::close);
}
void CSVDoc::Loader::loadingStopped(CSMDoc::Document* document, bool completed, const std::string& error)
{
std::map<CSMDoc::Document*, LoadingDocument*>::iterator iter = mDocuments.begin();
for (; iter != mDocuments.end(); ++iter)
if (iter->first == document)
break;
if (iter == mDocuments.end())
return;
if (completed || error.empty())
{
delete iter->second;
mDocuments.erase(iter);
}
else
{
iter->second->abort(error);
// Leave the window open for now (wait for the user to close it)
mDocuments.erase(iter);
}
}
void CSVDoc::Loader::nextStage(CSMDoc::Document* document, const std::string& name, int fileRecords)
{
std::map<CSMDoc::Document*, LoadingDocument*>::iterator iter = mDocuments.find(document);
if (iter != mDocuments.end())
iter->second->nextStage(name, fileRecords);
}
void CSVDoc::Loader::nextRecord(CSMDoc::Document* document, int records)
{
std::map<CSMDoc::Document*, LoadingDocument*>::iterator iter = mDocuments.find(document);
if (iter != mDocuments.end())
iter->second->nextRecord(records);
}
void CSVDoc::Loader::loadMessage(CSMDoc::Document* document, const std::string& message)
{
std::map<CSMDoc::Document*, LoadingDocument*>::iterator iter = mDocuments.find(document);
if (iter != mDocuments.end())
iter->second->addMessage(message);
}
| 5,717
|
C++
|
.cpp
| 162
| 30.728395
| 116
| 0.699618
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,098
|
cellborder.cpp
|
OpenMW_openmw/apps/opencs/view/render/cellborder.cpp
|
#include "cellborder.hpp"
#include <osg/Array>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/PositionAttitudeTransform>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <components/esm3/loadland.hpp>
#include "mask.hpp"
#include "../../model/world/cellcoordinates.hpp"
const int CSVRender::CellBorder::CellSize = ESM::Land::REAL_SIZE;
/*
The number of vertices per cell border is equal to the number of vertices per edge
minus the duplicated corner vertices. An additional vertex to close the loop is NOT needed.
*/
const int CSVRender::CellBorder::VertexCount = (ESM::Land::LAND_SIZE * 4) - 4;
CSVRender::CellBorder::CellBorder(osg::Group* cellNode, const CSMWorld::CellCoordinates& coords)
: mParentNode(cellNode)
{
mBorderGeometry = new osg::Geometry();
mBaseNode = new osg::PositionAttitudeTransform();
mBaseNode->setNodeMask(Mask_CellBorder);
mBaseNode->setPosition(osg::Vec3f(coords.getX() * CellSize, coords.getY() * CellSize, 10));
mBaseNode->addChild(mBorderGeometry);
mParentNode->addChild(mBaseNode);
}
CSVRender::CellBorder::~CellBorder()
{
mParentNode->removeChild(mBaseNode);
}
void CSVRender::CellBorder::buildShape(const ESM::Land& esmLand)
{
const ESM::Land::LandData* landData = esmLand.getLandData(ESM::Land::DATA_VHGT);
mBaseNode->removeChild(mBorderGeometry);
mBorderGeometry = new osg::Geometry();
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array();
int x = 0;
int y = 0;
/*
Traverse the cell border counter-clockwise starting at the SW corner vertex (0, 0).
Each loop starts at a corner vertex and ends right before the next corner vertex.
*/
if (landData)
{
for (; x < ESM::Land::LAND_SIZE - 1; ++x)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), landData->mHeights[landIndex(x, y)]));
x = ESM::Land::LAND_SIZE - 1;
for (; y < ESM::Land::LAND_SIZE - 1; ++y)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), landData->mHeights[landIndex(x, y)]));
y = ESM::Land::LAND_SIZE - 1;
for (; x > 0; --x)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), landData->mHeights[landIndex(x, y)]));
x = 0;
for (; y > 0; --y)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), landData->mHeights[landIndex(x, y)]));
}
else
{
for (; x < ESM::Land::LAND_SIZE - 1; ++x)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), ESM::Land::DEFAULT_HEIGHT));
x = ESM::Land::LAND_SIZE - 1;
for (; y < ESM::Land::LAND_SIZE - 1; ++y)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), ESM::Land::DEFAULT_HEIGHT));
y = ESM::Land::LAND_SIZE - 1;
for (; x > 0; --x)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), ESM::Land::DEFAULT_HEIGHT));
x = 0;
for (; y > 0; --y)
vertices->push_back(osg::Vec3f(scaleToWorld(x), scaleToWorld(y), ESM::Land::DEFAULT_HEIGHT));
}
mBorderGeometry->setVertexArray(vertices);
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array();
colors->push_back(osg::Vec4f(0.f, 0.5f, 0.f, 1.f));
mBorderGeometry->setColorArray(colors, osg::Array::BIND_PER_PRIMITIVE_SET);
osg::ref_ptr<osg::DrawElementsUShort> primitives
= new osg::DrawElementsUShort(osg::PrimitiveSet::LINE_STRIP, VertexCount + 1);
// Assign one primitive to each vertex.
for (size_t i = 0; i < VertexCount; ++i)
primitives->setElement(i, i);
// Assign the last primitive to the first vertex to close the loop.
primitives->setElement(VertexCount, 0);
mBorderGeometry->addPrimitiveSet(primitives);
mBorderGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mBaseNode->addChild(mBorderGeometry);
}
size_t CSVRender::CellBorder::landIndex(int x, int y)
{
return static_cast<size_t>(y) * ESM::Land::LAND_SIZE + x;
}
float CSVRender::CellBorder::scaleToWorld(int value)
{
return (CellSize + 128) * (float)value / ESM::Land::LAND_SIZE;
}
| 4,299
|
C++
|
.cpp
| 97
| 38.958763
| 115
| 0.67298
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,099
|
scenewidget.cpp
|
OpenMW_openmw/apps/opencs/view/render/scenewidget.cpp
|
#include "scenewidget.hpp"
#include <chrono>
#include <exception>
#include <thread>
#include <QLayout>
#include <QMouseEvent>
#include <QSurfaceFormat>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/view/render/lightingbright.hpp>
#include <apps/opencs/view/render/lightingday.hpp>
#include <apps/opencs/view/render/lightingnight.hpp>
#include <extern/osgQt/CompositeOsgRenderer.hpp>
#include <extern/osgQt/osgQOpenGLWidget.hpp>
#include <osg/Array>
#include <osg/Camera>
#include <osg/DisplaySettings>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/GraphicsContext>
#include <osg/Group>
#include <osg/LightModel>
#include <osg/Material>
#include <osg/Matrix>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Transform>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Vec4ub>
#include <osg/View>
#include <osg/Viewport>
#include <osgGA/EventQueue>
#include <osgGA/GUIEventAdapter>
#include <osgViewer/GraphicsWindow>
#include <osgViewer/View>
#include <osgViewer/ViewerBase>
#include <osgViewer/ViewerEventHandlers>
#include <components/debug/debuglog.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/glextensions.hpp>
#include <components/sceneutil/lightmanager.hpp>
#include "../widget/scenetoolmode.hpp"
#include "../../model/prefs/shortcut.hpp"
#include "../../model/prefs/state.hpp"
#include "cameracontroller.hpp"
#include "lighting.hpp"
#include "mask.hpp"
namespace CSVRender
{
RenderWidget::RenderWidget(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f)
, mRootNode(nullptr)
{
mView = new osgViewer::View;
updateCameraParameters(width() / static_cast<double>(height()));
mWidget = new osgQOpenGLWidget(this);
mRenderer = mWidget->getCompositeViewer();
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> window
= new osgViewer::GraphicsWindowEmbedded(0, 0, width(), height());
mWidget->setGraphicsWindowEmbedded(window);
mRenderer->setRealizeOperation(new SceneUtil::GetGLExtensionsOperation());
int frameRateLimit = CSMPrefs::get()["Rendering"]["framerate-limit"].toInt();
mRenderer->setRunMaxFrameRate(frameRateLimit);
mRenderer->setUseConfigureAffinity(false);
QLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(mWidget);
setLayout(layout);
mView->getCamera()->setGraphicsContext(window);
osg::ref_ptr<SceneUtil::LightManager> lightMgr = new SceneUtil::LightManager;
lightMgr->setStartLight(1);
lightMgr->setLightingMask(Mask_Lighting);
mRootNode = std::move(lightMgr);
mView->getCamera()->setViewport(new osg::Viewport(0, 0, width(), height()));
mView->getCamera()->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
mView->getCamera()->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
osg::ref_ptr<osg::Material> defaultMat(new osg::Material);
defaultMat->setColorMode(osg::Material::OFF);
defaultMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
defaultMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1));
defaultMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 0.f));
mView->getCamera()->getOrCreateStateSet()->setAttribute(defaultMat);
mView->setSceneData(mRootNode);
// Add ability to signal osg to show its statistics for debugging purposes
mView->addEventHandler(new osgViewer::StatsHandler);
mRenderer->addView(mView);
mRenderer->setDone(false);
}
RenderWidget::~RenderWidget()
{
try
{
mRenderer->removeView(mView);
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Error in the destructor: " << e.what();
}
delete mWidget;
}
void RenderWidget::flagAsModified()
{
mView->requestRedraw();
}
void RenderWidget::setVisibilityMask(unsigned int mask)
{
mView->getCamera()->setCullMask(mask | Mask_ParticleSystem | Mask_Lighting);
}
osg::Camera* RenderWidget::getCamera()
{
return mView->getCamera();
}
void RenderWidget::toggleRenderStats()
{
osgViewer::GraphicsWindow* window
= static_cast<osgViewer::GraphicsWindow*>(mView->getCamera()->getGraphicsContext());
window->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KEY_S);
window->getEventQueue()->keyRelease(osgGA::GUIEventAdapter::KEY_S);
}
// ---------------------------------------------------
SceneWidget::SceneWidget(std::shared_ptr<Resource::ResourceSystem> resourceSystem, QWidget* parent,
Qt::WindowFlags f, bool retrieveInput)
: RenderWidget(parent, f)
, mResourceSystem(std::move(resourceSystem))
, mLighting(nullptr)
, mHasDefaultAmbient(false)
, mIsExterior(true)
, mPrevMouseX(0)
, mPrevMouseY(0)
, mCamPositionSet(false)
{
mFreeCamControl = new FreeCameraController(this);
mOrbitCamControl = new OrbitCameraController(this);
mCurrentCamControl = mFreeCamControl;
mOrbitCamControl->setPickingMask(Mask_Reference | Mask_Terrain);
mOrbitCamControl->setConstRoll(CSMPrefs::get()["3D Scene Input"]["navi-orbit-const-roll"].isTrue());
// set up gradient view or configured clear color
QColor bgColour = CSMPrefs::get()["Rendering"]["scene-day-background-colour"].toColor();
if (CSMPrefs::get()["Rendering"]["scene-use-gradient"].isTrue())
{
QColor gradientColour = CSMPrefs::get()["Rendering"]["scene-day-gradient-colour"].toColor();
mGradientCamera = createGradientCamera(bgColour, gradientColour);
mView->getCamera()->setClearMask(0);
mView->getCamera()->addChild(mGradientCamera.get());
}
else
{
mView->getCamera()->setClearColor(osg::Vec4(bgColour.redF(), bgColour.greenF(), bgColour.blueF(), 1.0f));
}
// we handle lighting manually
mView->setLightingMode(osgViewer::View::NO_LIGHT);
setLighting(&mLightingDay);
mResourceSystem->getSceneManager()->setParticleSystemMask(Mask_ParticleSystem);
// Recieve mouse move event even if mouse button is not pressed
setMouseTracking(true);
setFocusPolicy(Qt::ClickFocus);
connect(&CSMPrefs::State::get(), &CSMPrefs::State::settingChanged, this, &SceneWidget::settingChanged);
// TODO update this outside of the constructor where virtual methods can be used
if (retrieveInput)
{
CSMPrefs::get()["3D Scene Input"].update();
CSMPrefs::get()["Tooltips"].update();
}
connect(mRenderer, &CompositeOsgRenderer::simulationUpdated, this, &SceneWidget::update);
// Shortcuts
CSMPrefs::Shortcut* focusToolbarShortcut = new CSMPrefs::Shortcut("scene-focus-toolbar", this);
connect(
focusToolbarShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &SceneWidget::focusToolbarRequest);
CSMPrefs::Shortcut* renderStatsShortcut = new CSMPrefs::Shortcut("scene-render-stats", this);
connect(
renderStatsShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &SceneWidget::toggleRenderStats);
}
SceneWidget::~SceneWidget()
{
// Since we're holding on to the resources past the existence of this graphics context, we'll need to manually
// release the created objects
mResourceSystem->releaseGLObjects(mView->getCamera()->getGraphicsContext()->getState());
}
osg::ref_ptr<osg::Geometry> SceneWidget::createGradientRectangle(QColor& bgColour, QColor& gradientColour)
{
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
vertices->push_back(osg::Vec3(0.0f, 0.0f, -1.0f));
vertices->push_back(osg::Vec3(1.0f, 0.0f, -1.0f));
vertices->push_back(osg::Vec3(0.0f, 1.0f, -1.0f));
vertices->push_back(osg::Vec3(1.0f, 1.0f, -1.0f));
geometry->setVertexArray(vertices);
osg::ref_ptr<osg::DrawElementsUShort> primitives = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, 0);
// triangle 1
primitives->push_back(0);
primitives->push_back(1);
primitives->push_back(2);
// triangle 2
primitives->push_back(2);
primitives->push_back(1);
primitives->push_back(3);
geometry->addPrimitiveSet(primitives);
osg::ref_ptr<osg::Vec4ubArray> colours = new osg::Vec4ubArray;
colours->push_back(osg::Vec4ub(gradientColour.red(), gradientColour.green(), gradientColour.blue(), 1.0f));
colours->push_back(osg::Vec4ub(gradientColour.red(), gradientColour.green(), gradientColour.blue(), 1.0f));
colours->push_back(osg::Vec4ub(bgColour.red(), bgColour.green(), bgColour.blue(), 1.0f));
colours->push_back(osg::Vec4ub(bgColour.red(), bgColour.green(), bgColour.blue(), 1.0f));
geometry->setColorArray(colours, osg::Array::BIND_PER_VERTEX);
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
return geometry;
}
osg::ref_ptr<osg::Camera> SceneWidget::createGradientCamera(QColor& bgColour, QColor& gradientColour)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera();
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
camera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1.0f, 0, 1.0f));
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
camera->setViewMatrix(osg::Matrix::identity());
camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
camera->setAllowEventFocus(false);
// draw subgraph before main camera view.
camera->setRenderOrder(osg::Camera::PRE_RENDER);
camera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
osg::ref_ptr<osg::Geometry> gradientQuad = createGradientRectangle(bgColour, gradientColour);
camera->addChild(std::move(gradientQuad));
return camera;
}
void SceneWidget::updateGradientCamera(QColor& bgColour, QColor& gradientColour)
{
osg::ref_ptr<osg::Geometry> gradientRect = createGradientRectangle(bgColour, gradientColour);
// Replaces previous rectangle
mGradientCamera->setChild(0, gradientRect.get());
}
void SceneWidget::setLighting(Lighting* lighting)
{
if (mLighting)
mLighting->deactivate();
mLighting = lighting;
mLighting->activate(mRootNode, mIsExterior);
osg::Vec4f ambient = mLighting->getAmbientColour(mHasDefaultAmbient ? &mDefaultAmbient : nullptr);
setAmbient(ambient);
flagAsModified();
}
void SceneWidget::setAmbient(const osg::Vec4f& ambient)
{
osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet;
osg::ref_ptr<osg::LightModel> lightmodel = new osg::LightModel;
lightmodel->setAmbientIntensity(ambient);
stateset->setMode(GL_LIGHTING, osg::StateAttribute::ON);
stateset->setMode(GL_LIGHT0, osg::StateAttribute::ON);
stateset->setAttributeAndModes(lightmodel, osg::StateAttribute::ON);
mRootNode->setStateSet(stateset);
}
void SceneWidget::selectLightingMode(const std::string& mode)
{
QColor backgroundColour;
QColor gradientColour;
if (mode == "day")
{
backgroundColour = CSMPrefs::get()["Rendering"]["scene-day-background-colour"].toColor();
gradientColour = CSMPrefs::get()["Rendering"]["scene-day-gradient-colour"].toColor();
setLighting(&mLightingDay);
}
else if (mode == "night")
{
backgroundColour = CSMPrefs::get()["Rendering"]["scene-night-background-colour"].toColor();
gradientColour = CSMPrefs::get()["Rendering"]["scene-night-gradient-colour"].toColor();
setLighting(&mLightingNight);
}
else if (mode == "bright")
{
backgroundColour = CSMPrefs::get()["Rendering"]["scene-bright-background-colour"].toColor();
gradientColour = CSMPrefs::get()["Rendering"]["scene-bright-gradient-colour"].toColor();
setLighting(&mLightingBright);
}
if (CSMPrefs::get()["Rendering"]["scene-use-gradient"].isTrue())
{
if (mGradientCamera.get() != nullptr)
{
// we can go ahead and update since this camera still exists
updateGradientCamera(backgroundColour, gradientColour);
if (!mView->getCamera()->containsNode(mGradientCamera.get()))
{
// need to re-attach the gradient camera
mView->getCamera()->setClearMask(0);
mView->getCamera()->addChild(mGradientCamera.get());
}
}
else
{
// need to create the gradient camera
mGradientCamera = createGradientCamera(backgroundColour, gradientColour);
mView->getCamera()->setClearMask(0);
mView->getCamera()->addChild(mGradientCamera.get());
}
}
else
{
// Fall back to using the clear color for the camera
mView->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mView->getCamera()->setClearColor(
osg::Vec4(backgroundColour.redF(), backgroundColour.greenF(), backgroundColour.blueF(), 1.0f));
if (mGradientCamera.get() != nullptr && mView->getCamera()->containsNode(mGradientCamera.get()))
{
// Remove the child to prevent the gradient from rendering
mView->getCamera()->removeChild(mGradientCamera.get());
}
}
}
CSVWidget::SceneToolMode* SceneWidget::makeLightingSelector(CSVWidget::SceneToolbar* parent)
{
CSVWidget::SceneToolMode* tool = new CSVWidget::SceneToolMode(parent, "Lighting Mode");
/// \todo replace icons
tool->addButton(":scenetoolbar/day", "day",
"Day"
"<ul><li>Cell specific ambient in interiors</li>"
"<li>Low ambient in exteriors</li>"
"<li>Strong directional light source</li>"
"<li>This mode closely resembles day time in-game</li></ul>");
tool->addButton(":scenetoolbar/night", "night",
"Night"
"<ul><li>Cell specific ambient in interiors</li>"
"<li>Low ambient in exteriors</li>"
"<li>Weak directional light source</li>"
"<li>This mode closely resembles night time in-game</li></ul>");
tool->addButton(":scenetoolbar/bright", "bright",
"Bright"
"<ul><li>Maximum ambient</li>"
"<li>Strong directional light source</li></ul>");
connect(tool, &CSVWidget::SceneToolMode::modeChanged, this, &SceneWidget::selectLightingMode);
return tool;
}
void SceneWidget::setDefaultAmbient(const osg::Vec4f& colour)
{
mDefaultAmbient = colour;
mHasDefaultAmbient = true;
setAmbient(mLighting->getAmbientColour(&mDefaultAmbient));
}
void SceneWidget::setExterior(bool isExterior)
{
mIsExterior = isExterior;
}
void SceneWidget::mouseMoveEvent(QMouseEvent* event)
{
mCurrentCamControl->handleMouseMoveEvent(event->x() - mPrevMouseX, event->y() - mPrevMouseY);
mPrevMouseX = event->x();
mPrevMouseY = event->y();
}
void SceneWidget::wheelEvent(QWheelEvent* event)
{
mCurrentCamControl->handleMouseScrollEvent(event->angleDelta().y());
}
void SceneWidget::update(double dt)
{
if (mCamPositionSet)
{
mCurrentCamControl->update(dt);
}
else
{
mCurrentCamControl->setup(mRootNode, Mask_Reference | Mask_Terrain, CameraController::WorldUp);
mCamPositionSet = true;
}
}
void SceneWidget::settingChanged(const CSMPrefs::Setting* setting)
{
if (*setting == "3D Scene Input/p-navi-free-sensitivity")
{
mFreeCamControl->setCameraSensitivity(setting->toDouble());
}
else if (*setting == "3D Scene Input/p-navi-orbit-sensitivity")
{
mOrbitCamControl->setCameraSensitivity(setting->toDouble());
}
else if (*setting == "3D Scene Input/p-navi-free-invert")
{
mFreeCamControl->setInverted(setting->isTrue());
}
else if (*setting == "3D Scene Input/p-navi-orbit-invert")
{
mOrbitCamControl->setInverted(setting->isTrue());
}
else if (*setting == "3D Scene Input/s-navi-sensitivity")
{
mFreeCamControl->setSecondaryMovementMultiplier(setting->toDouble());
mOrbitCamControl->setSecondaryMovementMultiplier(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-wheel-factor")
{
mFreeCamControl->setWheelMovementMultiplier(setting->toDouble());
mOrbitCamControl->setWheelMovementMultiplier(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-free-lin-speed")
{
mFreeCamControl->setLinearSpeed(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-free-rot-speed")
{
mFreeCamControl->setRotationalSpeed(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-free-speed-mult")
{
mFreeCamControl->setSpeedMultiplier(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-orbit-rot-speed")
{
mOrbitCamControl->setOrbitSpeed(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-orbit-speed-mult")
{
mOrbitCamControl->setOrbitSpeedMultiplier(setting->toDouble());
}
else if (*setting == "3D Scene Input/navi-orbit-const-roll")
{
mOrbitCamControl->setConstRoll(setting->isTrue());
}
else if (*setting == "Rendering/framerate-limit")
{
mRenderer->setRunMaxFrameRate(setting->toInt());
}
else if (*setting == "Rendering/camera-fov" || *setting == "Rendering/camera-ortho"
|| *setting == "Rendering/camera-ortho-size")
{
updateCameraParameters();
}
else if (*setting == "Rendering/scene-day-night-switch-nodes")
{
if (mLighting)
setLighting(mLighting);
}
}
void RenderWidget::updateCameraParameters(double overrideAspect)
{
const float nearDist = 1.0;
const float farDist = 1000.0;
if (CSMPrefs::get()["Rendering"]["camera-ortho"].isTrue())
{
const float size = CSMPrefs::get()["Rendering"]["camera-ortho-size"].toInt();
const float aspect = overrideAspect >= 0.0 ? overrideAspect : (width() / static_cast<double>(height()));
const float halfH = size * 10.0;
const float halfW = halfH * aspect;
mView->getCamera()->setProjectionMatrixAsOrtho(-halfW, halfW, -halfH, halfH, nearDist, farDist);
}
else
{
mView->getCamera()->setProjectionMatrixAsPerspective(CSMPrefs::get()["Rendering"]["camera-fov"].toInt(),
static_cast<double>(width()) / static_cast<double>(height()), nearDist, farDist);
}
}
void SceneWidget::selectNavigationMode(const std::string& mode)
{
if (mode == "1st")
{
mCurrentCamControl->setCamera(nullptr);
mCurrentCamControl = mFreeCamControl;
mFreeCamControl->setCamera(getCamera());
mFreeCamControl->fixUpAxis(CameraController::WorldUp);
}
else if (mode == "free")
{
mCurrentCamControl->setCamera(nullptr);
mCurrentCamControl = mFreeCamControl;
mFreeCamControl->setCamera(getCamera());
mFreeCamControl->unfixUpAxis();
}
else if (mode == "orbit")
{
mCurrentCamControl->setCamera(nullptr);
mCurrentCamControl = mOrbitCamControl;
mOrbitCamControl->setCamera(getCamera());
mOrbitCamControl->reset();
}
}
}
| 21,043
|
C++
|
.cpp
| 473
| 35.735729
| 120
| 0.642414
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,100
|
pathgridselectionmode.cpp
|
OpenMW_openmw/apps/opencs/view/render/pathgridselectionmode.cpp
|
#include "pathgridselectionmode.hpp"
#include <QAction>
#include <QMenu>
#include <vector>
#include <osg/ref_ptr>
#include "../../model/world/commandmacro.hpp"
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/view/render/mask.hpp>
#include <apps/opencs/view/render/selectionmode.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
#include "pathgrid.hpp"
#include "worldspacewidget.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
namespace CSVRender
{
PathgridSelectionMode::PathgridSelectionMode(CSVWidget::SceneToolbar* parent, WorldspaceWidget& worldspaceWidget)
: SelectionMode(parent, worldspaceWidget, Mask_Pathgrid)
{
mRemoveSelectedNodes = new QAction("Remove selected nodes", this);
mRemoveSelectedEdges = new QAction("Remove edges between selected nodes", this);
connect(mRemoveSelectedNodes, &QAction::triggered, this, &PathgridSelectionMode::removeSelectedNodes);
connect(mRemoveSelectedEdges, &QAction::triggered, this, &PathgridSelectionMode::removeSelectedEdges);
}
bool PathgridSelectionMode::createContextMenu(QMenu* menu)
{
if (menu)
{
SelectionMode::createContextMenu(menu);
menu->addAction(mRemoveSelectedNodes);
menu->addAction(mRemoveSelectedEdges);
}
return true;
}
void PathgridSelectionMode::removeSelectedNodes()
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
for (std::vector<osg::ref_ptr<TagBase>>::iterator it = selection.begin(); it != selection.end(); ++it)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(it->get()))
{
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Remove selected nodes";
CSMWorld::CommandMacro macro(undoStack, description);
tag->getPathgrid()->applyRemoveNodes(macro);
}
}
}
void PathgridSelectionMode::removeSelectedEdges()
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
for (std::vector<osg::ref_ptr<TagBase>>::iterator it = selection.begin(); it != selection.end(); ++it)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(it->get()))
{
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Remove edges between selected nodes";
CSMWorld::CommandMacro macro(undoStack, description);
tag->getPathgrid()->applyRemoveEdges(macro);
}
}
}
}
| 2,761
|
C++
|
.cpp
| 65
| 34.676923
| 117
| 0.673637
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,101
|
selectionmode.cpp
|
OpenMW_openmw/apps/opencs/view/render/selectionmode.cpp
|
#include "selectionmode.hpp"
#include <QAction>
#include <QMenu>
#include <memory>
#include <apps/opencs/view/widget/scenetoolmode.hpp>
#include "worldspacewidget.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
namespace CSVRender
{
SelectionMode::SelectionMode(
CSVWidget::SceneToolbar* parent, WorldspaceWidget& worldspaceWidget, unsigned int interactionMask)
: SceneToolMode(parent, "Selection mode")
, mWorldspaceWidget(worldspaceWidget)
, mInteractionMask(interactionMask)
{
addButton(":scenetoolbar/selection-mode-cube", "cube-centre",
"Centred cube"
"<ul><li>Drag with {scene-select-primary} for primary select or {scene-select-secondary} for secondary "
"select "
"from the centre of the selection cube outwards.</li>"
"<li>The selection cube is aligned to the word space axis</li>"
"<li>If context selection mode is enabled, a drag with {scene-edit-primary} or {scene-edit-secondary} not "
"starting on an instance will have the same effect</li>"
"</ul>");
addButton(":scenetoolbar/selection-mode-cube-corner", "cube-corner",
"Cube corner to corner"
"<ul><li>Drag with {scene-select-primary} for primary select or {scene-select-secondary} for secondary "
"select "
"from one corner of the selection cube to the opposite corner</li>"
"<li>The selection cube is aligned to the word space axis</li>"
"<li>If context selection mode is enabled, a drag with {scene-edit-primary} or {scene-edit-secondary} not "
"starting on an instance will have the same effect</li>"
"</ul>");
addButton(":scenetoolbar/selection-mode-cube-sphere", "sphere",
"Centred sphere"
"<ul><li>Drag with {scene-select-primary} for primary select or {scene-select-secondary} for secondary "
"select "
"from the centre of the selection sphere outwards</li>"
"<li>If context selection mode is enabled, a drag with {scene-edit-primary} or {scene-edit-secondary} not "
"starting on an instance will have the same effect</li>"
"</ul>");
mSelectAll = new QAction("Select all", this);
mDeselectAll = new QAction("Clear selection", this);
mInvertSelection = new QAction("Invert selection", this);
connect(mSelectAll, &QAction::triggered, this, &SelectionMode::selectAll);
connect(mDeselectAll, &QAction::triggered, this, &SelectionMode::clearSelection);
connect(mInvertSelection, &QAction::triggered, this, &SelectionMode::invertSelection);
}
WorldspaceWidget& SelectionMode::getWorldspaceWidget()
{
return mWorldspaceWidget;
}
bool SelectionMode::createContextMenu(QMenu* menu)
{
if (menu)
{
menu->addAction(mSelectAll);
menu->addAction(mDeselectAll);
menu->addAction(mInvertSelection);
}
return true;
}
void SelectionMode::selectAll()
{
getWorldspaceWidget().selectAll(mInteractionMask);
}
void SelectionMode::clearSelection()
{
getWorldspaceWidget().clearSelection(mInteractionMask);
}
void SelectionMode::invertSelection()
{
getWorldspaceWidget().invertSelection(mInteractionMask);
}
}
| 3,430
|
C++
|
.cpp
| 78
| 35.666667
| 119
| 0.660276
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,104
|
terrainstorage.cpp
|
OpenMW_openmw/apps/opencs/view/render/terrainstorage.cpp
|
#include "terrainstorage.hpp"
#include <components/esm3/loadltex.hpp>
#include <components/esmterrain/storage.hpp>
#include <components/resource/resourcesystem.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/land.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <algorithm>
#include <cmath>
#include <iterator>
#include <memory>
#include <osg/Vec4ub>
#include <stdexcept>
#include <stdlib.h>
#include <string>
namespace CSVRender
{
TerrainStorage::TerrainStorage(const CSMWorld::Data& data)
: ESMTerrain::Storage(data.getResourceSystem()->getVFS())
, mData(data)
{
resetHeights();
}
osg::ref_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation)
{
// The cell isn't guaranteed to have Land. This is because the terrain implementation
// has to wrap the vertices of the last row and column to the next cell, which may be a nonexisting cell
const int index = mData.getLand().searchId(
ESM::RefId::stringRefId(CSMWorld::Land::createUniqueRecordId(cellLocation.mX, cellLocation.mY)));
if (index == -1)
return nullptr;
const ESM::Land& land = mData.getLand().getRecord(index).get();
return new ESMTerrain::LandObject(
land, ESM::Land::DATA_VHGT | ESM::Land::DATA_VNML | ESM::Land::DATA_VCLR | ESM::Land::DATA_VTEX);
}
const std::string* TerrainStorage::getLandTexture(std::uint16_t index, int plugin)
{
return mData.getLandTextures().getLandTexture(index, plugin);
}
void TerrainStorage::setAlteredHeight(int inCellX, int inCellY, float height)
{
mAlteredHeight[inCellY * ESM::Land::LAND_SIZE + inCellX]
= height - fmod(height, 8); // Limit to divisible by 8 to avoid cell seam breakage
}
void TerrainStorage::resetHeights()
{
std::fill(std::begin(mAlteredHeight), std::end(mAlteredHeight), 0);
}
float TerrainStorage::getSumOfAlteredAndTrueHeight(int cellX, int cellY, int inCellX, int inCellY)
{
float height = 0.f;
const int index
= mData.getLand().searchId(ESM::RefId::stringRefId(CSMWorld::Land::createUniqueRecordId(cellX, cellY)));
if (index == -1) // no land!
return height;
const ESM::Land::LandData* landData = mData.getLand().getRecord(index).get().getLandData(ESM::Land::DATA_VHGT);
height = landData->mHeights[inCellY * ESM::Land::LAND_SIZE + inCellX];
return mAlteredHeight[inCellY * ESM::Land::LAND_SIZE + inCellX] + height;
}
float* TerrainStorage::getAlteredHeight(int inCellX, int inCellY)
{
return &mAlteredHeight[inCellY * ESM::Land::LAND_SIZE + inCellX];
}
void TerrainStorage::getBounds(float& minX, float& maxX, float& minY, float& maxY, ESM::RefId worldspace)
{
// not needed at the moment - this returns the bounds of the whole world, but we only edit individual cells
throw std::runtime_error("getBounds not implemented");
}
int TerrainStorage::getThisHeight(int col, int row, std::span<const float> heightData) const
{
return heightData[col * ESM::Land::LAND_SIZE + row]
+ mAlteredHeight[static_cast<unsigned int>(col * ESM::Land::LAND_SIZE + row)];
}
int TerrainStorage::getLeftHeight(int col, int row, std::span<const float> heightData) const
{
return heightData[(col)*ESM::Land::LAND_SIZE + row - 1]
+ mAlteredHeight[static_cast<unsigned int>((col)*ESM::Land::LAND_SIZE + row - 1)];
}
int TerrainStorage::getRightHeight(int col, int row, std::span<const float> heightData) const
{
return heightData[col * ESM::Land::LAND_SIZE + row + 1]
+ mAlteredHeight[static_cast<unsigned int>(col * ESM::Land::LAND_SIZE + row + 1)];
}
int TerrainStorage::getUpHeight(int col, int row, std::span<const float> heightData) const
{
return heightData[(col - 1) * ESM::Land::LAND_SIZE + row]
+ mAlteredHeight[static_cast<unsigned int>((col - 1) * ESM::Land::LAND_SIZE + row)];
}
int TerrainStorage::getDownHeight(int col, int row, std::span<const float> heightData) const
{
return heightData[(col + 1) * ESM::Land::LAND_SIZE + row]
+ mAlteredHeight[static_cast<unsigned int>((col + 1) * ESM::Land::LAND_SIZE + row)];
}
int TerrainStorage::getHeightDifferenceToLeft(int col, int row, std::span<const float> heightData) const
{
return abs(getThisHeight(col, row, heightData) - getLeftHeight(col, row, heightData));
}
int TerrainStorage::getHeightDifferenceToRight(int col, int row, std::span<const float> heightData) const
{
return abs(getThisHeight(col, row, heightData) - getRightHeight(col, row, heightData));
}
int TerrainStorage::getHeightDifferenceToUp(int col, int row, std::span<const float> heightData) const
{
return abs(getThisHeight(col, row, heightData) - getUpHeight(col, row, heightData));
}
int TerrainStorage::getHeightDifferenceToDown(int col, int row, std::span<const float> heightData) const
{
return abs(getThisHeight(col, row, heightData) - getDownHeight(col, row, heightData));
}
bool TerrainStorage::leftOrUpIsOverTheLimit(
int col, int row, int heightWarningLimit, std::span<const float> heightData) const
{
return getHeightDifferenceToLeft(col, row, heightData) >= heightWarningLimit
|| getHeightDifferenceToUp(col, row, heightData) >= heightWarningLimit;
}
bool TerrainStorage::rightOrDownIsOverTheLimit(
int col, int row, int heightWarningLimit, std::span<const float> heightData) const
{
return getHeightDifferenceToRight(col, row, heightData) >= heightWarningLimit
|| getHeightDifferenceToDown(col, row, heightData) >= heightWarningLimit;
}
void TerrainStorage::adjustColor(int col, int row, const ESM::LandData* heightData, osg::Vec4ub& color) const
{
if (!heightData)
return;
// Highlight broken height changes
int heightWarningLimit = 1024;
if (((col > 0 && row > 0) && leftOrUpIsOverTheLimit(col, row, heightWarningLimit, heightData->getHeights()))
|| ((col < ESM::Land::LAND_SIZE - 1 && row < ESM::Land::LAND_SIZE - 1)
&& rightOrDownIsOverTheLimit(col, row, heightWarningLimit, heightData->getHeights())))
{
color.r() = 255;
color.g() = 0;
color.b() = 0;
}
}
float TerrainStorage::getAlteredHeight(int col, int row) const
{
return mAlteredHeight[static_cast<unsigned int>(col * ESM::Land::LAND_SIZE + row)];
}
}
| 6,832
|
C++
|
.cpp
| 142
| 41.204225
| 119
| 0.676272
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,105
|
pathgrid.cpp
|
OpenMW_openmw/apps/opencs/view/render/pathgrid.cpp
|
#include "pathgrid.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <set>
#include <stddef.h>
#include <osg/Array>
#include <osg/Callback>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/MixinVector>
#include <osg/Node>
#include <osg/PositionAttitudeTransform>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <apps/opencs/model/world/cell.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/pathgrid.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/subcellcollection.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/render/mask.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/loadpgrd.hpp>
#include <components/sceneutil/pathgridutil.hpp>
#include "../../model/world/commandmacro.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtree.hpp"
#include "worldspacewidget.hpp"
namespace osg
{
class NodeVisitor;
}
namespace CSVRender
{
class PathgridNodeCallback : public osg::NodeCallback
{
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override
{
PathgridTag* tag = static_cast<PathgridTag*>(node->getUserData());
tag->getPathgrid()->update();
}
};
PathgridTag::PathgridTag(Pathgrid* pathgrid)
: TagBase(Mask_Pathgrid)
, mPathgrid(pathgrid)
{
}
Pathgrid* PathgridTag::getPathgrid() const
{
return mPathgrid;
}
QString PathgridTag::getToolTip(bool /*hideBasics*/, const WorldspaceHitResult& hit) const
{
QString text("Pathgrid: ");
text += mPathgrid->getId().c_str();
text += " (";
text += QString::number(SceneUtil::getPathgridNode(hit.index0));
text += ")";
return text;
}
Pathgrid::Pathgrid(CSMWorld::Data& data, osg::Group* parent, const std::string& pathgridId,
const CSMWorld::CellCoordinates& coordinates)
: mData(data)
, mPathgridCollection(mData.getPathgrids())
, mId(ESM::RefId::stringRefId(pathgridId))
, mCoords(coordinates)
, mInterior(false)
, mDragOrigin(0)
, mChangeGeometry(true)
, mRemoveGeometry(false)
, mUseOffset(true)
, mParent(parent)
, mPathgridGeometry(nullptr)
, mDragGeometry(nullptr)
, mTag(new PathgridTag(this))
{
const float CoordScalar = ESM::Land::REAL_SIZE;
mBaseNode = new osg::PositionAttitudeTransform();
mBaseNode->setPosition(osg::Vec3f(mCoords.getX() * CoordScalar, mCoords.getY() * CoordScalar, 0.f));
mBaseNode->setUserData(mTag);
mBaseNode->setUpdateCallback(new PathgridNodeCallback());
mBaseNode->setNodeMask(Mask_Pathgrid);
mParent->addChild(mBaseNode);
mPathgridGroup = new osg::Group();
mBaseNode->addChild(mPathgridGroup);
recreateGeometry();
int index = mData.getCells().searchId(mId);
if (index != -1)
{
const CSMWorld::Cell& cell = mData.getCells().getRecord(index).get();
mInterior = cell.mData.mFlags & ESM::Cell::Interior;
}
}
Pathgrid::~Pathgrid()
{
mParent->removeChild(mBaseNode);
}
const CSMWorld::CellCoordinates& Pathgrid::getCoordinates() const
{
return mCoords;
}
const std::string& Pathgrid::getId() const
{
return mId.getRefIdString();
}
bool Pathgrid::isSelected() const
{
return !mSelected.empty();
}
const Pathgrid::NodeList& Pathgrid::getSelected() const
{
return mSelected;
}
void Pathgrid::selectAll()
{
mSelected.clear();
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
for (unsigned short i = 0; i < static_cast<unsigned short>(source->mPoints.size()); ++i)
mSelected.push_back(i);
createSelectedGeometry(*source);
}
else
{
removeSelectedGeometry();
}
}
void Pathgrid::toggleSelected(unsigned short node)
{
NodeList::iterator searchResult = std::find(mSelected.begin(), mSelected.end(), node);
if (searchResult != mSelected.end())
{
mSelected.erase(searchResult);
}
else
{
mSelected.push_back(node);
}
createSelectedGeometry();
}
void Pathgrid::invertSelected()
{
NodeList temp = NodeList(mSelected);
mSelected.clear();
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
for (unsigned short i = 0; i < static_cast<unsigned short>(source->mPoints.size()); ++i)
{
if (std::find(temp.begin(), temp.end(), i) == temp.end())
mSelected.push_back(i);
}
createSelectedGeometry(*source);
}
else
{
removeSelectedGeometry();
}
}
void Pathgrid::clearSelected()
{
mSelected.clear();
removeSelectedGeometry();
}
void Pathgrid::moveSelected(const osg::Vec3d& offset)
{
mUseOffset = true;
mMoveOffset += offset;
recreateGeometry();
}
void Pathgrid::setDragOrigin(unsigned short node)
{
mDragOrigin = node;
}
void Pathgrid::setDragEndpoint(unsigned short node)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
const CSMWorld::Pathgrid::Point& pointA = source->mPoints[mDragOrigin];
const CSMWorld::Pathgrid::Point& pointB = source->mPoints[node];
osg::Vec3f start = osg::Vec3f(pointA.mX, pointA.mY, pointA.mZ + SceneUtil::DiamondHalfHeight);
osg::Vec3f end = osg::Vec3f(pointB.mX, pointB.mY, pointB.mZ + SceneUtil::DiamondHalfHeight);
createDragGeometry(start, end, true);
}
}
void Pathgrid::setDragEndpoint(const osg::Vec3d& pos)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
const CSMWorld::Pathgrid::Point& point = source->mPoints[mDragOrigin];
osg::Vec3f start = osg::Vec3f(point.mX, point.mY, point.mZ + SceneUtil::DiamondHalfHeight);
osg::Vec3f end = pos - mBaseNode->getPosition();
createDragGeometry(start, end, false);
}
}
void Pathgrid::resetIndicators()
{
mUseOffset = false;
mMoveOffset.set(0, 0, 0);
mPathgridGroup->removeChild(mDragGeometry);
mDragGeometry = nullptr;
}
void Pathgrid::applyPoint(CSMWorld::CommandMacro& commands, const osg::Vec3d& worldPos)
{
CSMWorld::IdTree* model
= &dynamic_cast<CSMWorld::IdTree&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Pathgrids));
const std::string& idString = mId.getRefIdString();
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
osg::Vec3d localCoords = worldPos - mBaseNode->getPosition();
int posX = clampToCell(static_cast<int>(localCoords.x()));
int posY = clampToCell(static_cast<int>(localCoords.y()));
int posZ = clampToCell(static_cast<int>(localCoords.z()));
int recordIndex = mPathgridCollection.getIndex(mId);
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridPoints);
int posXColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosX);
int posYColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosY);
int posZColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosZ);
QModelIndex parent = model->index(recordIndex, parentColumn);
int row = static_cast<int>(source->mPoints.size());
// Add node to end of list
commands.push(new CSMWorld::AddNestedCommand(*model, idString, row, parentColumn));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, posXColumn, parent), posX));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, posYColumn, parent), posY));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, posZColumn, parent), posZ));
}
else
{
int index = mPathgridCollection.searchId(mId);
if (index == -1)
{
// Does not exist
commands.push(new CSMWorld::CreatePathgridCommand(*model, idString));
}
else
{
source = &mPathgridCollection.getRecord(index).get();
// Deleted, so revert and remove all data
commands.push(new CSMWorld::RevertCommand(*model, idString));
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridPoints);
for (int row = source->mPoints.size() - 1; row >= 0; --row)
{
commands.push(new CSMWorld::DeleteNestedCommand(*model, idString, row, parentColumn));
}
parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridEdges);
for (int row = source->mEdges.size() - 1; row >= 0; --row)
{
commands.push(new CSMWorld::DeleteNestedCommand(*model, idString, row, parentColumn));
}
}
}
}
void Pathgrid::applyPosition(CSMWorld::CommandMacro& commands)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
osg::Vec3d localCoords = mMoveOffset;
int offsetX = static_cast<int>(localCoords.x());
int offsetY = static_cast<int>(localCoords.y());
int offsetZ = static_cast<int>(localCoords.z());
QAbstractItemModel* model = mData.getTableModel(CSMWorld::UniversalId::Type_Pathgrids);
int recordIndex = mPathgridCollection.getIndex(mId);
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridPoints);
int posXColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosX);
int posYColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosY);
int posZColumn
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridPosZ);
QModelIndex parent = model->index(recordIndex, parentColumn);
for (const auto& selected : mSelected)
{
const CSMWorld::Pathgrid::Point& point = source->mPoints[selected];
int row = static_cast<int>(selected);
commands.push(new CSMWorld::ModifyCommand(
*model, model->index(row, posXColumn, parent), clampToCell(point.mX + offsetX)));
commands.push(new CSMWorld::ModifyCommand(
*model, model->index(row, posYColumn, parent), clampToCell(point.mY + offsetY)));
commands.push(new CSMWorld::ModifyCommand(
*model, model->index(row, posZColumn, parent), clampToCell(point.mZ + offsetZ)));
}
}
}
void Pathgrid::applyEdge(CSMWorld::CommandMacro& commands, unsigned short node1, unsigned short node2)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
addEdge(commands, *source, node1, node2);
}
}
void Pathgrid::applyEdges(CSMWorld::CommandMacro& commands, unsigned short node)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
for (const auto& selected : mSelected)
{
addEdge(commands, *source, node, selected);
}
}
}
void Pathgrid::applyRemoveNodes(CSMWorld::CommandMacro& commands)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
CSMWorld::IdTree* model
= &dynamic_cast<CSMWorld::IdTree&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Pathgrids));
// Want to remove nodes from end of list first
std::sort(mSelected.begin(), mSelected.end(), std::greater<int>());
int recordIndex = mPathgridCollection.getIndex(mId);
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridPoints);
for (std::vector<unsigned short>::iterator row = mSelected.begin(); row != mSelected.end(); ++row)
{
commands.push(new CSMWorld::DeleteNestedCommand(
*model, mId.getRefIdString(), static_cast<int>(*row), parentColumn));
}
// Fix/remove edges
std::set<int, std::greater<int>> edgeRowsToRemove;
parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridEdges);
int edge0Column
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridEdge0);
int edge1Column
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridEdge1);
QModelIndex parent = model->index(recordIndex, parentColumn);
for (size_t edge = 0; edge < source->mEdges.size(); ++edge)
{
int adjustment0 = 0;
int adjustment1 = 0;
// Determine necessary adjustment
for (const auto point : mSelected)
{
if (source->mEdges[edge].mV0 == point || source->mEdges[edge].mV1 == point)
{
edgeRowsToRemove.insert(static_cast<int>(edge));
adjustment0 = 0; // No need to adjust, its getting removed
adjustment1 = 0;
break;
}
if (source->mEdges[edge].mV0 > point)
--adjustment0;
if (source->mEdges[edge].mV1 > point)
--adjustment1;
}
if (adjustment0 != 0)
{
int adjustedEdge = source->mEdges[edge].mV0 + adjustment0;
commands.push(
new CSMWorld::ModifyCommand(*model, model->index(edge, edge0Column, parent), adjustedEdge));
}
if (adjustment1 != 0)
{
int adjustedEdge = source->mEdges[edge].mV1 + adjustment1;
commands.push(
new CSMWorld::ModifyCommand(*model, model->index(edge, edge1Column, parent), adjustedEdge));
}
}
for (const auto row : edgeRowsToRemove)
{
commands.push(new CSMWorld::DeleteNestedCommand(*model, mId.getRefIdString(), row, parentColumn));
}
}
clearSelected();
}
void Pathgrid::applyRemoveEdges(CSMWorld::CommandMacro& commands)
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
// Want to remove from end of row first
std::set<int, std::greater<int>> rowsToRemove;
for (size_t i = 0; i <= mSelected.size(); ++i)
{
for (size_t j = i + 1; j < mSelected.size(); ++j)
{
int row = edgeExists(*source, mSelected[i], mSelected[j]);
if (row != -1)
{
rowsToRemove.insert(row);
}
row = edgeExists(*source, mSelected[j], mSelected[i]);
if (row != -1)
{
rowsToRemove.insert(row);
}
}
}
CSMWorld::IdTree* model
= &dynamic_cast<CSMWorld::IdTree&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Pathgrids));
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridEdges);
std::set<int, std::greater<int>>::iterator row;
for (row = rowsToRemove.begin(); row != rowsToRemove.end(); ++row)
{
commands.push(new CSMWorld::DeleteNestedCommand(*model, mId.getRefIdString(), *row, parentColumn));
}
}
}
osg::ref_ptr<PathgridTag> Pathgrid::getTag() const
{
return mTag;
}
void Pathgrid::recreateGeometry()
{
mChangeGeometry = true;
}
void Pathgrid::removeGeometry()
{
mRemoveGeometry = true;
}
void Pathgrid::update()
{
if (mRemoveGeometry)
{
removePathgridGeometry();
removeSelectedGeometry();
}
else if (mChangeGeometry)
{
createGeometry();
}
mChangeGeometry = false;
mRemoveGeometry = false;
}
void Pathgrid::createGeometry()
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
CSMWorld::Pathgrid temp;
if (mUseOffset)
{
temp = *source;
for (NodeList::iterator it = mSelected.begin(); it != mSelected.end(); ++it)
{
temp.mPoints[*it].mX += mMoveOffset.x();
temp.mPoints[*it].mY += mMoveOffset.y();
temp.mPoints[*it].mZ += mMoveOffset.z();
}
source = &temp;
}
removePathgridGeometry();
mPathgridGeometry = SceneUtil::createPathgridGeometry(*source);
mPathgridGroup->addChild(mPathgridGeometry);
createSelectedGeometry(*source);
}
else
{
removePathgridGeometry();
removeSelectedGeometry();
}
}
void Pathgrid::createSelectedGeometry()
{
const CSMWorld::Pathgrid* source = getPathgridSource();
if (source)
{
createSelectedGeometry(*source);
}
else
{
removeSelectedGeometry();
}
}
void Pathgrid::createSelectedGeometry(const CSMWorld::Pathgrid& source)
{
removeSelectedGeometry();
mSelectedGeometry = SceneUtil::createPathgridSelectedWireframe(source, mSelected);
mPathgridGroup->addChild(mSelectedGeometry);
}
void Pathgrid::removePathgridGeometry()
{
if (mPathgridGeometry)
{
mPathgridGroup->removeChild(mPathgridGeometry);
mPathgridGeometry = nullptr;
}
}
void Pathgrid::removeSelectedGeometry()
{
if (mSelectedGeometry)
{
mPathgridGroup->removeChild(mSelectedGeometry);
mSelectedGeometry = nullptr;
}
}
void Pathgrid::createDragGeometry(const osg::Vec3f& start, const osg::Vec3f& end, bool valid)
{
if (mDragGeometry)
mPathgridGroup->removeChild(mDragGeometry);
mDragGeometry = new osg::Geometry();
osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(2);
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1);
osg::ref_ptr<osg::DrawElementsUShort> indices = new osg::DrawElementsUShort(osg::PrimitiveSet::LINES, 2);
(*vertices)[0] = start;
(*vertices)[1] = end;
if (valid)
{
(*colors)[0] = osg::Vec4f(0.91f, 0.66f, 1.f, 1.f);
}
else
{
(*colors)[0] = osg::Vec4f(1.f, 0.f, 0.f, 1.f);
}
indices->setElement(0, 0);
indices->setElement(1, 1);
mDragGeometry->setVertexArray(vertices);
mDragGeometry->setColorArray(colors, osg::Array::BIND_OVERALL);
mDragGeometry->addPrimitiveSet(indices);
mDragGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mPathgridGroup->addChild(mDragGeometry);
}
const CSMWorld::Pathgrid* Pathgrid::getPathgridSource()
{
int index = mPathgridCollection.searchId(mId);
if (index != -1 && !mPathgridCollection.getRecord(index).isDeleted())
{
return &mPathgridCollection.getRecord(index).get();
}
return nullptr;
}
int Pathgrid::edgeExists(const CSMWorld::Pathgrid& source, unsigned short node1, unsigned short node2)
{
for (size_t i = 0; i < source.mEdges.size(); ++i)
{
if (source.mEdges[i].mV0 == node1 && source.mEdges[i].mV1 == node2)
return static_cast<int>(i);
}
return -1;
}
void Pathgrid::addEdge(
CSMWorld::CommandMacro& commands, const CSMWorld::Pathgrid& source, unsigned short node1, unsigned short node2)
{
CSMWorld::IdTree* model
= &dynamic_cast<CSMWorld::IdTree&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Pathgrids));
int recordIndex = mPathgridCollection.getIndex(mId);
int parentColumn = mPathgridCollection.findColumnIndex(CSMWorld::Columns::ColumnId_PathgridEdges);
int edge0Column
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridEdge0);
int edge1Column
= mPathgridCollection.searchNestedColumnIndex(parentColumn, CSMWorld::Columns::ColumnId_PathgridEdge1);
QModelIndex parent = model->index(recordIndex, parentColumn);
int row = static_cast<int>(source.mEdges.size());
if (edgeExists(source, node1, node2) == -1)
{
commands.push(new CSMWorld::AddNestedCommand(*model, mId.getRefIdString(), row, parentColumn));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, edge0Column, parent), node1));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, edge1Column, parent), node2));
++row;
}
if (edgeExists(source, node2, node1) == -1)
{
commands.push(new CSMWorld::AddNestedCommand(*model, mId.getRefIdString(), row, parentColumn));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, edge0Column, parent), node2));
commands.push(new CSMWorld::ModifyCommand(*model, model->index(row, edge1Column, parent), node1));
}
}
int Pathgrid::clampToCell(int v)
{
const int CellExtent = ESM::Land::REAL_SIZE;
if (mInterior)
return v;
else if (v > CellExtent)
return CellExtent;
else if (v < 0)
return 0;
else
return v;
}
}
| 23,686
|
C++
|
.cpp
| 589
| 29.932088
| 119
| 0.600636
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,106
|
terraintexturemode.cpp
|
OpenMW_openmw/apps/opencs/view/render/terraintexturemode.cpp
|
#include "terraintexturemode.hpp"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <limits>
#include <string>
#include <QDropEvent>
#include <QIcon>
#include <QSlider>
#include <QWidget>
#include <osg/Vec2f>
#include <osg/Vec3d>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/cellselection.hpp>
#include <apps/opencs/model/world/columnimp.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/view/render/terrainselection.hpp>
#include <apps/opencs/view/widget/scenetool.hpp>
#include <components/misc/scalableicon.hpp>
#include <components/misc/strings/conversion.hpp>
#include "../widget/scenetoolbar.hpp"
#include "../widget/scenetooltexturebrush.hpp"
#include "../../model/doc/document.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/idtree.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../../model/world/universalid.hpp"
#include "brushdraw.hpp"
#include "editmode.hpp"
#include "mask.hpp"
#include "pagedworldspacewidget.hpp"
#include "worldspacewidget.hpp"
CSVRender::TerrainTextureMode::TerrainTextureMode(
WorldspaceWidget* worldspaceWidget, osg::Group* parentNode, QWidget* parent)
: EditMode(worldspaceWidget, Misc::ScalableIcon::load(":scenetoolbar/editing-terrain-texture"),
Mask_Terrain | Mask_Reference, "Terrain texture editing", parent)
, mBrushSize(1)
, mBrushShape(CSVWidget::BrushShape_Point)
, mTextureBrushScenetool(nullptr)
, mDragMode(InteractionType_None)
, mParentNode(parentNode)
, mIsEditing(false)
{
}
void CSVRender::TerrainTextureMode::activate(CSVWidget::SceneToolbar* toolbar)
{
if (!mTextureBrushScenetool)
{
mTextureBrushScenetool = new CSVWidget::SceneToolTextureBrush(
toolbar, "scenetooltexturebrush", getWorldspaceWidget().getDocument());
connect(mTextureBrushScenetool, &CSVWidget::SceneTool::clicked, mTextureBrushScenetool,
&CSVWidget::SceneToolTextureBrush::activate);
connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passBrushSize, this,
&TerrainTextureMode::setBrushSize);
connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passBrushShape, this,
&TerrainTextureMode::setBrushShape);
connect(mTextureBrushScenetool->mTextureBrushWindow->mSizeSliders->mBrushSizeSlider, &QSlider::valueChanged,
this, &TerrainTextureMode::setBrushSize);
connect(mTextureBrushScenetool, &CSVWidget::SceneToolTextureBrush::passTextureId, this,
&TerrainTextureMode::setBrushTexture);
connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passTextureId, this,
&TerrainTextureMode::setBrushTexture);
connect(mTextureBrushScenetool, qOverload<QDropEvent*>(&CSVWidget::SceneToolTextureBrush::passEvent), this,
&TerrainTextureMode::handleDropEvent);
connect(this, &TerrainTextureMode::passBrushTexture, mTextureBrushScenetool->mTextureBrushWindow,
&CSVWidget::TextureBrushWindow::setBrushTexture);
connect(this, &TerrainTextureMode::passBrushTexture, mTextureBrushScenetool,
&CSVWidget::SceneToolTextureBrush::updateBrushHistory);
}
if (!mTerrainTextureSelection)
{
mTerrainTextureSelection
= std::make_shared<TerrainSelection>(mParentNode, &getWorldspaceWidget(), TerrainSelectionType::Texture);
}
if (!mBrushDraw)
mBrushDraw = std::make_unique<BrushDraw>(mParentNode, true);
EditMode::activate(toolbar);
toolbar->addTool(mTextureBrushScenetool);
}
void CSVRender::TerrainTextureMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
if (mTextureBrushScenetool)
{
toolbar->removeTool(mTextureBrushScenetool);
delete mTextureBrushScenetool;
mTextureBrushScenetool = nullptr;
}
if (mTerrainTextureSelection)
{
mTerrainTextureSelection.reset();
}
if (mBrushDraw)
mBrushDraw.reset();
EditMode::deactivate(toolbar);
}
void CSVRender::TerrainTextureMode::primaryOpenPressed(const WorldspaceHitResult& hit) // Apply changes here
{
}
void CSVRender::TerrainTextureMode::primaryEditPressed(const WorldspaceHitResult& hit) // Apply changes here
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTable& ltexTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
mCellId = getWorldspaceWidget().getCellId(hit.worldPos);
QUndoStack& undoStack = document.getUndoStack();
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
int index = landtexturesCollection.searchId(mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
{
undoStack.beginMacro("Edit texture records");
if (allowLandTextureEditing(mCellId))
{
undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, mCellId));
editTerrainTextureGrid(hit);
}
undoStack.endMacro();
}
}
void CSVRender::TerrainTextureMode::primarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.hit && hit.tag == nullptr)
{
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
mTerrainTextureSelection->clearTemporarySelection();
}
}
void CSVRender::TerrainTextureMode::secondarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.hit && hit.tag == nullptr)
{
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
mTerrainTextureSelection->clearTemporarySelection();
}
}
bool CSVRender::TerrainTextureMode::primaryEditStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTable& ltexTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
mCellId = getWorldspaceWidget().getCellId(hit.worldPos);
QUndoStack& undoStack = document.getUndoStack();
mDragMode = InteractionType_PrimaryEdit;
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
const int index = landtexturesCollection.searchId(mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
{
undoStack.beginMacro("Edit texture records");
mIsEditing = true;
if (allowLandTextureEditing(mCellId))
{
undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, mCellId));
editTerrainTextureGrid(hit);
}
}
return true;
}
bool CSVRender::TerrainTextureMode::secondaryEditStartDrag(const QPoint& pos)
{
return false;
}
bool CSVRender::TerrainTextureMode::primarySelectStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mDragMode = InteractionType_PrimarySelect;
if (!hit.hit || hit.tag != nullptr)
{
mDragMode = InteractionType_None;
return false;
}
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
return true;
}
bool CSVRender::TerrainTextureMode::secondarySelectStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mDragMode = InteractionType_SecondarySelect;
if (!hit.hit || hit.tag != nullptr)
{
mDragMode = InteractionType_None;
return false;
}
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
return true;
}
void CSVRender::TerrainTextureMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor)
{
if (mDragMode == InteractionType_PrimaryEdit)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
std::string cellId = getWorldspaceWidget().getCellId(hit.worldPos);
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
const int index = landtexturesCollection.searchId(mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
{
editTerrainTextureGrid(hit);
}
}
if (mDragMode == InteractionType_PrimarySelect)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.hit && hit.tag == nullptr)
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
}
if (mDragMode == InteractionType_SecondarySelect)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.hit && hit.tag == nullptr)
selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
}
}
void CSVRender::TerrainTextureMode::dragCompleted(const QPoint& pos)
{
if (mDragMode == InteractionType_PrimaryEdit && mIsEditing)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
QUndoStack& undoStack = document.getUndoStack();
CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
const int index = landtexturesCollection.searchId(mBrushTexture);
if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted())
{
undoStack.endMacro();
mIsEditing = false;
}
}
mTerrainTextureSelection->clearTemporarySelection();
}
void CSVRender::TerrainTextureMode::dragAborted() {}
void CSVRender::TerrainTextureMode::dragWheel(int diff, double speedFactor) {}
void CSVRender::TerrainTextureMode::handleDropEvent(QDropEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime) // May happen when non-records (e.g. plain text) are dragged and dropped
return;
if (mime->holdsType(CSMWorld::UniversalId::Type_LandTexture))
{
const std::vector<CSMWorld::UniversalId> ids = mime->getData();
for (const CSMWorld::UniversalId& uid : ids)
{
mBrushTexture = ESM::RefId::stringRefId(uid.getId());
emit passBrushTexture(mBrushTexture);
}
}
}
void CSVRender::TerrainTextureMode::editTerrainTextureGrid(const WorldspaceHitResult& hit)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
mCellId = getWorldspaceWidget().getCellId(hit.worldPos);
if (allowLandTextureEditing(mCellId))
{
}
std::pair<CSMWorld::CellCoordinates, bool> cellCoordinates_pair = CSMWorld::CellCoordinates::fromId(mCellId);
int cellX = cellCoordinates_pair.first.getX();
int cellY = cellCoordinates_pair.first.getY();
// The coordinates of hit in mCellId
int xHitInCell(float(((hit.worldPos.x() - (cellX * cellSize)) * landTextureSize / cellSize) - 0.25));
int yHitInCell(float(((hit.worldPos.y() - (cellY * cellSize)) * landTextureSize / cellSize) + 0.25));
if (xHitInCell < 0)
{
xHitInCell = xHitInCell + landTextureSize;
cellX = cellX - 1;
}
if (yHitInCell > 15)
{
yHitInCell = yHitInCell - landTextureSize;
cellY = cellY + 1;
}
mCellId = CSMWorld::CellCoordinates::generateId(cellX, cellY);
if (allowLandTextureEditing(mCellId))
{
}
std::string iteratedCellId;
int textureColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandTexturesIndex);
// All indices are offset by +1
uint32_t brushInt = document.getData().getLandTextures().getRecord(mBrushTexture).get().mIndex + 1;
int r = static_cast<float>(mBrushSize) / 2;
if (mBrushShape == CSVWidget::BrushShape_Point)
{
CSMWorld::LandTexturesColumn::DataType newTerrain
= landTable.data(landTable.getModelIndex(mCellId, textureColumn))
.value<CSMWorld::LandTexturesColumn::DataType>();
if (allowLandTextureEditing(mCellId))
{
newTerrain[yHitInCell * landTextureSize + xHitInCell] = brushInt;
pushEditToCommand(newTerrain, document, landTable, mCellId);
}
}
if (mBrushShape == CSVWidget::BrushShape_Square)
{
int upperLeftCellX = cellX - std::floor(r / landTextureSize);
int upperLeftCellY = cellY - std::floor(r / landTextureSize);
if (xHitInCell - (r % landTextureSize) < 0)
upperLeftCellX--;
if (yHitInCell - (r % landTextureSize) < 0)
upperLeftCellY--;
int lowerrightCellX = cellX + std::floor(r / landTextureSize);
int lowerrightCellY = cellY + std::floor(r / landTextureSize);
if (xHitInCell + (r % landTextureSize) > landTextureSize - 1)
lowerrightCellX++;
if (yHitInCell + (r % landTextureSize) > landTextureSize - 1)
lowerrightCellY++;
for (int i_cell = upperLeftCellX; i_cell <= lowerrightCellX; i_cell++)
{
for (int j_cell = upperLeftCellY; j_cell <= lowerrightCellY; j_cell++)
{
iteratedCellId = CSMWorld::CellCoordinates::generateId(i_cell, j_cell);
if (allowLandTextureEditing(iteratedCellId))
{
CSMWorld::LandTexturesColumn::DataType newTerrain
= landTable.data(landTable.getModelIndex(iteratedCellId, textureColumn))
.value<CSMWorld::LandTexturesColumn::DataType>();
for (int i = 0; i < landTextureSize; i++)
{
for (int j = 0; j < landTextureSize; j++)
{
if (i_cell == cellX && j_cell == cellY && abs(i - xHitInCell) < r
&& abs(j - yHitInCell) < r)
{
newTerrain[j * landTextureSize + i] = brushInt;
}
else
{
int distanceX(0);
int distanceY(0);
if (i_cell < cellX)
distanceX = xHitInCell + landTextureSize * abs(i_cell - cellX) - i;
if (j_cell < cellY)
distanceY = yHitInCell + landTextureSize * abs(j_cell - cellY) - j;
if (i_cell > cellX)
distanceX = -xHitInCell + landTextureSize * abs(i_cell - cellX) + i;
if (j_cell > cellY)
distanceY = -yHitInCell + landTextureSize * abs(j_cell - cellY) + j;
if (i_cell == cellX)
distanceX = abs(i - xHitInCell);
if (j_cell == cellY)
distanceY = abs(j - yHitInCell);
if (distanceX < r && distanceY < r)
newTerrain[j * landTextureSize + i] = brushInt;
}
}
}
pushEditToCommand(newTerrain, document, landTable, iteratedCellId);
}
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Circle)
{
int upperLeftCellX = cellX - std::floor(r / landTextureSize);
int upperLeftCellY = cellY - std::floor(r / landTextureSize);
if (xHitInCell - (r % landTextureSize) < 0)
upperLeftCellX--;
if (yHitInCell - (r % landTextureSize) < 0)
upperLeftCellY--;
int lowerrightCellX = cellX + std::floor(r / landTextureSize);
int lowerrightCellY = cellY + std::floor(r / landTextureSize);
if (xHitInCell + (r % landTextureSize) > landTextureSize - 1)
lowerrightCellX++;
if (yHitInCell + (r % landTextureSize) > landTextureSize - 1)
lowerrightCellY++;
for (int i_cell = upperLeftCellX; i_cell <= lowerrightCellX; i_cell++)
{
for (int j_cell = upperLeftCellY; j_cell <= lowerrightCellY; j_cell++)
{
iteratedCellId = CSMWorld::CellCoordinates::generateId(i_cell, j_cell);
if (allowLandTextureEditing(iteratedCellId))
{
CSMWorld::LandTexturesColumn::DataType newTerrain
= landTable.data(landTable.getModelIndex(iteratedCellId, textureColumn))
.value<CSMWorld::LandTexturesColumn::DataType>();
for (int i = 0; i < landTextureSize; i++)
{
for (int j = 0; j < landTextureSize; j++)
{
if (i_cell == cellX && j_cell == cellY && abs(i - xHitInCell) < r
&& abs(j - yHitInCell) < r)
{
int distanceX = abs(i - xHitInCell);
int distanceY = abs(j - yHitInCell);
float distance = std::round(sqrt(pow(distanceX, 2) + pow(distanceY, 2)));
float rf = static_cast<float>(mBrushSize) / 2;
if (distance < rf)
newTerrain[j * landTextureSize + i] = brushInt;
}
else
{
int distanceX(0);
int distanceY(0);
if (i_cell < cellX)
distanceX = xHitInCell + landTextureSize * abs(i_cell - cellX) - i;
if (j_cell < cellY)
distanceY = yHitInCell + landTextureSize * abs(j_cell - cellY) - j;
if (i_cell > cellX)
distanceX = -xHitInCell + landTextureSize * abs(i_cell - cellX) + i;
if (j_cell > cellY)
distanceY = -yHitInCell + landTextureSize * abs(j_cell - cellY) + j;
if (i_cell == cellX)
distanceX = abs(i - xHitInCell);
if (j_cell == cellY)
distanceY = abs(j - yHitInCell);
float distance = std::round(sqrt(pow(distanceX, 2) + pow(distanceY, 2)));
float rf = static_cast<float>(mBrushSize) / 2;
if (distance < rf)
newTerrain[j * landTextureSize + i] = brushInt;
}
}
}
pushEditToCommand(newTerrain, document, landTable, iteratedCellId);
}
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Custom)
{
CSMWorld::LandTexturesColumn::DataType newTerrain
= landTable.data(landTable.getModelIndex(mCellId, textureColumn))
.value<CSMWorld::LandTexturesColumn::DataType>();
if (allowLandTextureEditing(mCellId) && !mCustomBrushShape.empty())
{
for (auto const& value : mCustomBrushShape)
{
if (yHitInCell + value.second >= 0 && yHitInCell + value.second <= 15 && xHitInCell + value.first >= 0
&& xHitInCell + value.first <= 15)
{
newTerrain[(yHitInCell + value.second) * landTextureSize + xHitInCell + value.first] = brushInt;
}
else
{
int cellXDifference = std::floor(1.0f * (xHitInCell + value.first) / landTextureSize);
int cellYDifference = std::floor(1.0f * (yHitInCell + value.second) / landTextureSize);
int xInOtherCell = xHitInCell + value.first - cellXDifference * landTextureSize;
int yInOtherCell = yHitInCell + value.second - cellYDifference * landTextureSize;
std::string cellId
= CSMWorld::CellCoordinates::generateId(cellX + cellXDifference, cellY + cellYDifference);
if (allowLandTextureEditing(cellId))
{
CSMWorld::LandTexturesColumn::DataType newTerrainOtherCell
= landTable.data(landTable.getModelIndex(cellId, textureColumn))
.value<CSMWorld::LandTexturesColumn::DataType>();
newTerrainOtherCell[yInOtherCell * landTextureSize + xInOtherCell] = brushInt;
pushEditToCommand(newTerrainOtherCell, document, landTable, std::move(cellId));
}
}
}
pushEditToCommand(newTerrain, document, landTable, mCellId);
}
}
}
bool CSVRender::TerrainTextureMode::isInCellSelection(int globalSelectionX, int globalSelectionY)
{
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
std::pair<int, int> textureCoords = std::make_pair(globalSelectionX, globalSelectionY);
std::string cellId = CSMWorld::CellCoordinates::textureGlobalToCellId(textureCoords);
return paged->getCellSelection().has(CSMWorld::CellCoordinates::fromId(cellId).first);
}
return false;
}
void CSVRender::TerrainTextureMode::selectTerrainTextures(
const std::pair<int, int>& texCoords, unsigned char selectMode)
{
int r = mBrushSize / 2;
std::vector<std::pair<int, int>> selections;
if (mBrushShape == CSVWidget::BrushShape_Point)
{
if (isInCellSelection(texCoords.first, texCoords.second))
selections.emplace_back(texCoords);
}
if (mBrushShape == CSVWidget::BrushShape_Square)
{
for (int i = -r; i <= r; i++)
{
for (int j = -r; j <= r; j++)
{
int x = i + texCoords.first;
int y = j + texCoords.second;
if (isInCellSelection(x, y))
{
selections.emplace_back(x, y);
}
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Circle)
{
for (int i = -r; i <= r; i++)
{
for (int j = -r; j <= r; j++)
{
osg::Vec2f coords(i, j);
float rf = static_cast<float>(mBrushSize) / 2;
if (std::round(coords.length()) < rf)
{
int x = i + texCoords.first;
int y = j + texCoords.second;
if (isInCellSelection(x, y))
{
selections.emplace_back(x, y);
}
}
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Custom)
{
if (!mCustomBrushShape.empty())
{
for (auto const& value : mCustomBrushShape)
{
int x = texCoords.first + value.first;
int y = texCoords.second + value.second;
if (isInCellSelection(x, y))
{
selections.emplace_back(x, y);
}
}
}
}
std::string selectAction;
if (selectMode == 0)
selectAction = CSMPrefs::get()["3D Scene Editing"]["primary-select-action"].toString();
else
selectAction = CSMPrefs::get()["3D Scene Editing"]["secondary-select-action"].toString();
if (selectAction == "Select only")
mTerrainTextureSelection->onlySelect(selections);
else if (selectAction == "Add to selection")
mTerrainTextureSelection->addSelect(selections);
else if (selectAction == "Remove from selection")
mTerrainTextureSelection->removeSelect(selections);
else if (selectAction == "Invert selection")
mTerrainTextureSelection->toggleSelect(selections);
}
void CSVRender::TerrainTextureMode::pushEditToCommand(CSMWorld::LandTexturesColumn::DataType& newLandGrid,
CSMDoc::Document& document, CSMWorld::IdTable& landTable, std::string cellId)
{
CSMWorld::IdTable& ltexTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
QVariant changedLand;
changedLand.setValue(newLandGrid);
QModelIndex index(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandTexturesIndex)));
QUndoStack& undoStack = document.getUndoStack();
undoStack.push(new CSMWorld::ModifyCommand(landTable, index, changedLand));
undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, cellId));
}
bool CSVRender::TerrainTextureMode::allowLandTextureEditing(const std::string& cellId)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTree& cellTable
= dynamic_cast<CSMWorld::IdTree&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
const ESM::RefId cellRefId = ESM::RefId::stringRefId(cellId);
const bool noCell = document.getData().getCells().searchId(cellRefId) == -1;
const bool noLand = document.getData().getLand().searchId(cellRefId) == -1;
if (noCell)
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();
// target cell does not exist
if (mode == "Discard")
return false;
if (mode == "Create cell and land, then edit")
{
auto createCommand = std::make_unique<CSMWorld::CreateCommand>(cellTable, cellId);
int parentIndex = cellTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
int index = cellTable.findNestedColumnIndex(parentIndex, CSMWorld::Columns::ColumnId_Interior);
createCommand->addNestedValue(parentIndex, index, false);
document.getUndoStack().push(createCommand.release());
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
else if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
if (!selection.has(CSMWorld::CellCoordinates::fromId(cellId).first))
{
// target cell exists, but is not shown
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-visible-landedit"].toString();
if (mode == "Discard")
return false;
if (mode == "Show cell and edit")
{
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
if (noLand)
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();
// target cell does not exist
if (mode == "Discard")
return false;
if (mode == "Create cell and land, then edit")
{
document.getUndoStack().push(new CSMWorld::CreateCommand(landTable, cellId));
}
}
return true;
}
void CSVRender::TerrainTextureMode::dragMoveEvent(QDragMoveEvent* event) {}
void CSVRender::TerrainTextureMode::mouseMoveEvent(QMouseEvent* event)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(event->pos(), getInteractionMask());
if (hit.hit && mBrushDraw)
mBrushDraw->update(hit.worldPos, mBrushSize, mBrushShape);
if (!hit.hit && mBrushDraw)
mBrushDraw->hide();
}
std::shared_ptr<CSVRender::TerrainSelection> CSVRender::TerrainTextureMode::getTerrainSelection()
{
return mTerrainTextureSelection;
}
void CSVRender::TerrainTextureMode::setBrushSize(int brushSize)
{
mBrushSize = brushSize;
}
void CSVRender::TerrainTextureMode::setBrushShape(CSVWidget::BrushShape brushShape)
{
mBrushShape = brushShape;
// Set custom brush shape
if (mBrushShape == CSVWidget::BrushShape_Custom && !mTerrainTextureSelection->getTerrainSelection().empty())
{
auto terrainSelection = mTerrainTextureSelection->getTerrainSelection();
int selectionCenterX = 0;
int selectionCenterY = 0;
int selectionAmount = 0;
for (auto const& value : terrainSelection)
{
selectionCenterX += value.first;
selectionCenterY += value.second;
++selectionAmount;
}
if (selectionAmount != 0)
{
selectionCenterX /= selectionAmount;
selectionCenterY /= selectionAmount;
}
mCustomBrushShape.clear();
for (auto const& value : terrainSelection)
mCustomBrushShape.emplace_back(value.first - selectionCenterX, value.second - selectionCenterY);
}
}
void CSVRender::TerrainTextureMode::setBrushTexture(ESM::RefId brushTexture)
{
mBrushTexture = brushTexture;
}
| 31,248
|
C++
|
.cpp
| 670
| 36.131343
| 120
| 0.62747
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,108
|
instancemode.cpp
|
OpenMW_openmw/apps/opencs/view/render/instancemode.cpp
|
#include "instancemode.hpp"
#include <QDragEnterEvent>
#include <QPoint>
#include <QString>
#include <algorithm>
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <utility>
#include "../../model/prefs/state.hpp"
#include <osg/BoundingBox>
#include <osg/Camera>
#include <osg/ComputeBoundsVisitor>
#include <osg/Group>
#include <osg/Math>
#include <osg/Matrix>
#include <osg/Matrixd>
#include <osg/Vec3d>
#include <osg/Viewport>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/LineSegmentIntersector>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/cellselection.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/refcollection.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/render/editmode.hpp>
#include <apps/opencs/view/render/instancedragmodes.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
#include <components/esm/defs.hpp>
#include <components/misc/scalableicon.hpp>
#include "../../model/prefs/shortcut.hpp"
#include "../../model/world/commandmacro.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/idtree.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../widget/scenetoolbar.hpp"
#include "../widget/scenetoolmode.hpp"
#include "mask.hpp"
#include "instancemovemode.hpp"
#include "instanceselectionmode.hpp"
#include "object.hpp"
#include "pagedworldspacewidget.hpp"
#include "worldspacewidget.hpp"
int CSVRender::InstanceMode::getSubModeFromId(const std::string& id) const
{
return id == "move" ? 0 : (id == "rotate" ? 1 : 2);
}
osg::Vec3f CSVRender::InstanceMode::quatToEuler(const osg::Quat& rot) const
{
float x, y, z;
float test = 2 * (rot.w() * rot.y() + rot.x() * rot.z());
if (std::abs(test) >= 1.f)
{
x = atan2(rot.x(), rot.w());
y = (test > 0) ? (osg::PI / 2) : (-osg::PI / 2);
z = 0;
}
else
{
x = std::atan2(2 * (rot.w() * rot.x() - rot.y() * rot.z()), 1 - 2 * (rot.x() * rot.x() + rot.y() * rot.y()));
y = std::asin(test);
z = std::atan2(2 * (rot.w() * rot.z() - rot.x() * rot.y()), 1 - 2 * (rot.y() * rot.y() + rot.z() * rot.z()));
}
return osg::Vec3f(-x, -y, -z);
}
osg::Quat CSVRender::InstanceMode::eulerToQuat(const osg::Vec3f& euler) const
{
osg::Quat xr = osg::Quat(-euler[0], osg::Vec3f(1, 0, 0));
osg::Quat yr = osg::Quat(-euler[1], osg::Vec3f(0, 1, 0));
osg::Quat zr = osg::Quat(-euler[2], osg::Vec3f(0, 0, 1));
return zr * yr * xr;
}
float CSVRender::InstanceMode::roundFloatToMult(const float val, const double mult) const
{
if (mult == 0)
return val;
return round(val / mult) * mult;
}
osg::Vec3 CSVRender::InstanceMode::calculateSnapPositionRelativeToTarget(osg::Vec3 initalPosition,
osg::Vec3 targetPosition, osg::Vec3 targetRotation, osg::Vec3 translation, double snap) const
{
auto quatTargetRotation
= osg::Quat(targetRotation[0], osg::X_AXIS, targetRotation[1], osg::Y_AXIS, targetRotation[2], osg::Z_AXIS);
// Break object world coords into snap target space
auto localWorld = osg::Matrix::translate(initalPosition)
* osg::Matrix::inverse(osg::Matrix::translate(targetPosition)) * osg::Matrix::rotate(quatTargetRotation);
osg::Vec3 localPosition = localWorld.getTrans();
osg::Vec3 newTranslation;
newTranslation[0] = CSVRender::InstanceMode::roundFloatToMult(localPosition[0] + translation[0], snap);
newTranslation[1] = CSVRender::InstanceMode::roundFloatToMult(localPosition[1] + translation[1], snap);
newTranslation[2] = CSVRender::InstanceMode::roundFloatToMult(localPosition[2] + translation[2], snap);
// rebuild object's world coordinates (note: inverse operations from local construction)
auto newObjectWorld = osg::Matrix::translate(newTranslation)
* osg::Matrix::inverse(osg::Matrix::rotate(quatTargetRotation)) * osg::Matrix::translate(targetPosition);
osg::Vec3 newObjectPosition = newObjectWorld.getTrans();
return newObjectPosition;
}
osg::Vec3f CSVRender::InstanceMode::getSelectionCenter(const std::vector<osg::ref_ptr<TagBase>>& selection) const
{
osg::Vec3f center = osg::Vec3f(0, 0, 0);
int objectCount = 0;
for (std::vector<osg::ref_ptr<TagBase>>::const_iterator iter(selection.begin()); iter != selection.end(); ++iter)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
const ESM::Position& position = objectTag->mObject->getPosition();
center += osg::Vec3f(position.pos[0], position.pos[1], position.pos[2]);
++objectCount;
}
}
if (objectCount > 0)
center /= objectCount;
return center;
}
osg::Vec3f CSVRender::InstanceMode::getScreenCoords(const osg::Vec3f& pos)
{
osg::Matrix viewMatrix = getWorldspaceWidget().getCamera()->getViewMatrix();
osg::Matrix projMatrix = getWorldspaceWidget().getCamera()->getProjectionMatrix();
osg::Matrix windowMatrix = getWorldspaceWidget().getCamera()->getViewport()->computeWindowMatrix();
osg::Matrix combined = viewMatrix * projMatrix * windowMatrix;
return pos * combined;
}
osg::Vec3f CSVRender::InstanceMode::getProjectionSpaceCoords(const osg::Vec3f& pos)
{
osg::Matrix viewMatrix = getWorldspaceWidget().getCamera()->getViewMatrix();
osg::Matrix projMatrix = getWorldspaceWidget().getCamera()->getProjectionMatrix();
osg::Matrix combined = viewMatrix * projMatrix;
return pos * combined;
}
osg::Vec3f CSVRender::InstanceMode::getMousePlaneCoords(const QPoint& point, const osg::Vec3d& dragStart)
{
osg::Matrix viewMatrix;
viewMatrix.invert(getWorldspaceWidget().getCamera()->getViewMatrix());
osg::Matrix projMatrix;
projMatrix.invert(getWorldspaceWidget().getCamera()->getProjectionMatrix());
osg::Matrix combined = projMatrix * viewMatrix;
/* calculate viewport normalized coordinates
note: is there a reason to use getCamera()->getViewport()->computeWindowMatrix() instead? */
float x = (point.x() * 2) / getWorldspaceWidget().getCamera()->getViewport()->width() - 1.0f;
float y = 1.0f - (point.y() * 2) / getWorldspaceWidget().getCamera()->getViewport()->height();
osg::Vec3f mousePlanePoint = osg::Vec3f(x, y, dragStart.z()) * combined;
return mousePlanePoint;
}
void CSVRender::InstanceMode::saveSelectionGroup(const int group)
{
QStringList strings;
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QVariant selectionObjects;
CSMWorld::CommandMacro macro(undoStack, "Replace Selection Group");
std::string groupName = "project::" + std::to_string(group);
const auto& selection = getWorldspaceWidget().getSelection(Mask_Reference);
const int selectionObjectsIndex
= mSelectionGroups->findColumnIndex(CSMWorld::Columns::ColumnId_SelectionGroupObjects);
if (dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
groupName += "-ext";
else
groupName += "-" + getWorldspaceWidget().getCellId(osg::Vec3f(0, 0, 0));
CSMWorld::CreateCommand* newGroup = new CSMWorld::CreateCommand(*mSelectionGroups, groupName);
newGroup->setType(CSMWorld::UniversalId::Type_SelectionGroup);
for (const auto& object : selection)
if (const CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(object.get()))
strings << QString::fromStdString(objectTag->mObject->getReferenceId());
selectionObjects.setValue(strings);
newGroup->addValue(selectionObjectsIndex, selectionObjects);
if (mSelectionGroups->getModelIndex(groupName, 0).row() != -1)
macro.push(new CSMWorld::DeleteCommand(*mSelectionGroups, groupName));
macro.push(newGroup);
getWorldspaceWidget().clearSelection(Mask_Reference);
}
void CSVRender::InstanceMode::getSelectionGroup(const int group)
{
std::string groupName = "project::" + std::to_string(group);
std::vector<std::string> targets;
const auto& selection = getWorldspaceWidget().getSelection(Mask_Reference);
const int selectionObjectsIndex
= mSelectionGroups->findColumnIndex(CSMWorld::Columns::ColumnId_SelectionGroupObjects);
if (dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
groupName += "-ext";
else
groupName += "-" + getWorldspaceWidget().getCellId(osg::Vec3f(0, 0, 0));
const QModelIndex groupSearch = mSelectionGroups->getModelIndex(groupName, selectionObjectsIndex);
if (groupSearch.row() == -1)
return;
for (const QString& target : groupSearch.data().toStringList())
targets.push_back(target.toStdString());
if (!selection.empty())
getWorldspaceWidget().clearSelection(Mask_Reference);
getWorldspaceWidget().selectGroup(targets);
}
void CSVRender::InstanceMode::setDragAxis(const char axis)
{
int newDragAxis;
const std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return;
switch (axis)
{
case 'x':
newDragAxis = 0;
break;
case 'y':
newDragAxis = 1;
break;
case 'z':
newDragAxis = 2;
break;
default:
return;
}
if (newDragAxis == mDragAxis)
newDragAxis = -1;
if (mSubModeId == "move")
{
mObjectsAtDragStart.clear();
for (const auto& object : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(object.get()))
{
const osg::Vec3f thisPoint = objectTag->mObject->getPosition().asVec3();
mDragStart = thisPoint;
mObjectsAtDragStart.emplace_back(thisPoint);
}
}
mDragAxis = newDragAxis;
}
CSVRender::InstanceMode::InstanceMode(
WorldspaceWidget* worldspaceWidget, osg::ref_ptr<osg::Group> parentNode, QWidget* parent)
: EditMode(worldspaceWidget, Misc::ScalableIcon::load(":scenetoolbar/editing-instance"),
Mask_Reference | Mask_Terrain, "Instance editing", parent)
, mSubMode(nullptr)
, mSubModeId("move")
, mSelectionMode(nullptr)
, mDragMode(DragMode_None)
, mDragAxis(-1)
, mLocked(false)
, mUnitScaleDist(1)
, mParentNode(std::move(parentNode))
{
mSelectionGroups = dynamic_cast<CSMWorld::IdTable*>(
worldspaceWidget->getDocument().getData().getTableModel(CSMWorld::UniversalId::Type_SelectionGroup));
connect(this, &InstanceMode::requestFocus, worldspaceWidget, &WorldspaceWidget::requestFocus);
CSMPrefs::Shortcut* deleteShortcut = new CSMPrefs::Shortcut("scene-delete", worldspaceWidget);
connect(deleteShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &InstanceMode::deleteSelectedInstances);
CSMPrefs::Shortcut* duplicateShortcut = new CSMPrefs::Shortcut("scene-duplicate", worldspaceWidget);
connect(
duplicateShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &InstanceMode::cloneSelectedInstances);
// Following classes could be simplified by using QSignalMapper, which is obsolete in Qt5.10, but not in Qt4.8 and
// Qt5.14
CSMPrefs::Shortcut* dropToCollisionShortcut
= new CSMPrefs::Shortcut("scene-instance-drop-collision", worldspaceWidget);
connect(dropToCollisionShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this,
&InstanceMode::dropSelectedInstancesToCollision);
CSMPrefs::Shortcut* dropToTerrainLevelShortcut
= new CSMPrefs::Shortcut("scene-instance-drop-terrain", worldspaceWidget);
connect(dropToTerrainLevelShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this,
&InstanceMode::dropSelectedInstancesToTerrain);
CSMPrefs::Shortcut* dropToCollisionShortcut2
= new CSMPrefs::Shortcut("scene-instance-drop-collision-separately", worldspaceWidget);
connect(dropToCollisionShortcut2, qOverload<>(&CSMPrefs::Shortcut::activated), this,
&InstanceMode::dropSelectedInstancesToCollisionSeparately);
CSMPrefs::Shortcut* dropToTerrainLevelShortcut2
= new CSMPrefs::Shortcut("scene-instance-drop-terrain-separately", worldspaceWidget);
connect(dropToTerrainLevelShortcut2, qOverload<>(&CSMPrefs::Shortcut::activated), this,
&InstanceMode::dropSelectedInstancesToTerrainSeparately);
for (short i = 0; i <= 9; i++)
{
connect(new CSMPrefs::Shortcut("scene-group-" + std::to_string(i), worldspaceWidget),
qOverload<>(&CSMPrefs::Shortcut::activated), this, [this, i] { this->getSelectionGroup(i); });
connect(new CSMPrefs::Shortcut("scene-save-" + std::to_string(i), worldspaceWidget),
qOverload<>(&CSMPrefs::Shortcut::activated), this, [this, i] { this->saveSelectionGroup(i); });
}
connect(new CSMPrefs::Shortcut("scene-submode-move", worldspaceWidget), qOverload<>(&CSMPrefs::Shortcut::activated),
this, [this] { mSubMode->setButton("move"); });
connect(new CSMPrefs::Shortcut("scene-submode-scale", worldspaceWidget),
qOverload<>(&CSMPrefs::Shortcut::activated), this, [this] { mSubMode->setButton("scale"); });
connect(new CSMPrefs::Shortcut("scene-submode-rotate", worldspaceWidget),
qOverload<>(&CSMPrefs::Shortcut::activated), this, [this] { mSubMode->setButton("rotate"); });
for (const char axis : "xyz")
connect(new CSMPrefs::Shortcut(std::string("scene-axis-") + axis, worldspaceWidget),
qOverload<>(&CSMPrefs::Shortcut::activated), this, [this, axis] { this->setDragAxis(axis); });
}
void CSVRender::InstanceMode::activate(CSVWidget::SceneToolbar* toolbar)
{
if (!mSubMode)
{
mSubMode = new CSVWidget::SceneToolMode(toolbar, "Edit Sub-Mode");
mSubMode->addButton(new InstanceMoveMode(this), "move");
mSubMode->addButton(":scenetoolbar/transform-rotate", "rotate",
"Rotate selected instances"
"<ul><li>Use {scene-edit-primary} to rotate instances freely</li>"
"<li>Use {scene-edit-secondary} to rotate instances within the grid</li>"
"<li>The center of the view acts as the axis of rotation</li>"
"</ul>");
mSubMode->addButton(":scenetoolbar/transform-scale", "scale",
"Scale selected instances"
"<ul><li>Use {scene-edit-primary} to scale instances freely</li>"
"<li>Use {scene-edit-secondary} to scale instances along the grid</li>"
"<li>The scaling rate is based on how close the start of a drag is to the center of the screen</li>"
"</ul>");
mSubMode->setButton(mSubModeId);
connect(mSubMode, &CSVWidget::SceneToolMode::modeChanged, this, &InstanceMode::subModeChanged);
}
if (!mSelectionMode)
mSelectionMode = new InstanceSelectionMode(toolbar, getWorldspaceWidget(), mParentNode);
mDragMode = DragMode_None;
EditMode::activate(toolbar);
toolbar->addTool(mSubMode);
toolbar->addTool(mSelectionMode);
std::string subMode = mSubMode->getCurrentId();
getWorldspaceWidget().setSubMode(getSubModeFromId(subMode), Mask_Reference);
}
void CSVRender::InstanceMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
mDragMode = DragMode_None;
getWorldspaceWidget().reset(Mask_Reference);
if (mSelectionMode)
{
toolbar->removeTool(mSelectionMode);
delete mSelectionMode;
mSelectionMode = nullptr;
}
if (mSubMode)
{
toolbar->removeTool(mSubMode);
delete mSubMode;
mSubMode = nullptr;
}
EditMode::deactivate(toolbar);
}
void CSVRender::InstanceMode::setEditLock(bool locked)
{
mLocked = locked;
if (mLocked)
getWorldspaceWidget().abortDrag();
}
void CSVRender::InstanceMode::primaryEditPressed(const WorldspaceHitResult& hit)
{
if (CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue())
primarySelectPressed(hit);
}
void CSVRender::InstanceMode::primaryOpenPressed(const WorldspaceHitResult& hit)
{
if (hit.tag)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
const std::string refId = objectTag->mObject->getReferenceId();
emit requestFocus(refId);
}
}
}
void CSVRender::InstanceMode::secondaryEditPressed(const WorldspaceHitResult& hit)
{
if (CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue())
secondarySelectPressed(hit);
}
void CSVRender::InstanceMode::primarySelectPressed(const WorldspaceHitResult& hit)
{
getWorldspaceWidget().clearSelection(Mask_Reference);
if (hit.tag)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
// hit an Object, select it
CSVRender::Object* object = objectTag->mObject;
object->setSelected(true);
return;
}
}
}
void CSVRender::InstanceMode::secondarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.tag)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
// hit an Object, toggle its selection state
CSVRender::Object* object = objectTag->mObject;
object->setSelected(!object->getSelected());
return;
}
}
}
void CSVRender::InstanceMode::tertiarySelectPressed(const WorldspaceHitResult& hit)
{
auto* snapTarget = dynamic_cast<CSVRender::ObjectTag*>(getWorldspaceWidget().getSnapTarget(Mask_Reference).get());
if (snapTarget)
{
snapTarget->mObject->setSnapTarget(false);
}
if (hit.tag)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
// hit an Object, toggle its selection state
CSVRender::Object* object = objectTag->mObject;
object->setSnapTarget(!object->getSnapTarget());
return;
}
}
}
bool CSVRender::InstanceMode::primaryEditStartDrag(const QPoint& pos)
{
if (mDragMode != DragMode_None || mLocked)
return false;
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
{
// Only change selection at the start of drag if no object is already selected
if (hit.tag && CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue())
{
getWorldspaceWidget().clearSelection(Mask_Reference);
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
CSVRender::Object* object = objectTag->mObject;
object->setSelected(true);
}
}
selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return false;
}
mObjectsAtDragStart.clear();
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter(selection.begin()); iter != selection.end(); ++iter)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
if (mSubModeId == "move")
{
objectTag->mObject->setEdited(Object::Override_Position);
float x = objectTag->mObject->getPosition().pos[0];
float y = objectTag->mObject->getPosition().pos[1];
float z = objectTag->mObject->getPosition().pos[2];
osg::Vec3f thisPoint(x, y, z);
mDragStart = getMousePlaneCoords(pos, getProjectionSpaceCoords(thisPoint));
mObjectsAtDragStart.emplace_back(thisPoint);
mDragMode = DragMode_Move;
}
else if (mSubModeId == "rotate")
{
objectTag->mObject->setEdited(Object::Override_Rotation);
mDragMode = DragMode_Rotate;
}
else if (mSubModeId == "scale")
{
objectTag->mObject->setEdited(Object::Override_Scale);
mDragMode = DragMode_Scale;
// Calculate scale factor
std::vector<osg::ref_ptr<TagBase>> editedSelection = getWorldspaceWidget().getEdited(Mask_Reference);
osg::Vec3f center = getScreenCoords(getSelectionCenter(editedSelection));
int widgetHeight = getWorldspaceWidget().height();
float dx = pos.x() - center.x();
float dy = (widgetHeight - pos.y()) - center.y();
mUnitScaleDist = std::sqrt(dx * dx + dy * dy);
}
}
}
if (CSVRender::ObjectMarkerTag* objectTag = dynamic_cast<CSVRender::ObjectMarkerTag*>(hit.tag.get()))
{
mDragAxis = objectTag->mAxis;
}
else
mDragAxis = -1;
return true;
}
bool CSVRender::InstanceMode::secondaryEditStartDrag(const QPoint& pos)
{
if (mDragMode != DragMode_None || mLocked)
return false;
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
{
// Only change selection at the start of drag if no object is already selected
if (hit.tag && CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue())
{
getWorldspaceWidget().clearSelection(Mask_Reference);
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(hit.tag.get()))
{
CSVRender::Object* object = objectTag->mObject;
object->setSelected(true);
}
}
selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return false;
}
mObjectsAtDragStart.clear();
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter(selection.begin()); iter != selection.end(); ++iter)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
if (mSubModeId == "move")
{
objectTag->mObject->setEdited(Object::Override_Position);
float x = objectTag->mObject->getPosition().pos[0];
float y = objectTag->mObject->getPosition().pos[1];
float z = objectTag->mObject->getPosition().pos[2];
osg::Vec3f thisPoint(x, y, z);
mDragStart = getMousePlaneCoords(pos, getProjectionSpaceCoords(thisPoint));
mObjectsAtDragStart.emplace_back(thisPoint);
mDragMode = DragMode_Move_Snap;
}
else if (mSubModeId == "rotate")
{
objectTag->mObject->setEdited(Object::Override_Rotation);
mDragMode = DragMode_Rotate_Snap;
}
else if (mSubModeId == "scale")
{
objectTag->mObject->setEdited(Object::Override_Scale);
mDragMode = DragMode_Scale_Snap;
// Calculate scale factor
std::vector<osg::ref_ptr<TagBase>> editedSelection = getWorldspaceWidget().getEdited(Mask_Reference);
osg::Vec3f center = getScreenCoords(getSelectionCenter(editedSelection));
int widgetHeight = getWorldspaceWidget().height();
float dx = pos.x() - center.x();
float dy = (widgetHeight - pos.y()) - center.y();
mUnitScaleDist = std::sqrt(dx * dx + dy * dy);
}
}
}
if (CSVRender::ObjectMarkerTag* objectTag = dynamic_cast<CSVRender::ObjectMarkerTag*>(hit.tag.get()))
{
mDragAxis = objectTag->mAxis;
}
else
mDragAxis = -1;
return true;
}
bool CSVRender::InstanceMode::primarySelectStartDrag(const QPoint& pos)
{
if (mDragMode != DragMode_None || mLocked)
return false;
std::string primarySelectAction = CSMPrefs::get()["3D Scene Editing"]["primary-select-action"].toString();
if (primarySelectAction == "Select only")
mDragMode = DragMode_Select_Only;
else if (primarySelectAction == "Add to selection")
mDragMode = DragMode_Select_Add;
else if (primarySelectAction == "Remove from selection")
mDragMode = DragMode_Select_Remove;
else if (primarySelectAction == "Invert selection")
mDragMode = DragMode_Select_Invert;
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mSelectionMode->setDragStart(hit.worldPos);
return true;
}
bool CSVRender::InstanceMode::secondarySelectStartDrag(const QPoint& pos)
{
if (mDragMode != DragMode_None || mLocked)
return false;
std::string secondarySelectAction = CSMPrefs::get()["3D Scene Editing"]["secondary-select-action"].toString();
if (secondarySelectAction == "Select only")
mDragMode = DragMode_Select_Only;
else if (secondarySelectAction == "Add to selection")
mDragMode = DragMode_Select_Add;
else if (secondarySelectAction == "Remove from selection")
mDragMode = DragMode_Select_Remove;
else if (secondarySelectAction == "Invert selection")
mDragMode = DragMode_Select_Invert;
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mSelectionMode->setDragStart(hit.worldPos);
return true;
}
void CSVRender::InstanceMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor)
{
osg::Vec3f offset;
osg::Quat rotation;
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getEdited(Mask_Reference);
auto* snapTarget = dynamic_cast<CSVRender::ObjectTag*>(getWorldspaceWidget().getSnapTarget(Mask_Reference).get());
if (mDragMode == DragMode_Move || mDragMode == DragMode_Move_Snap)
{
}
else if (mDragMode == DragMode_Rotate || mDragMode == DragMode_Rotate_Snap)
{
osg::Vec3f eye, centre, up;
getWorldspaceWidget().getCamera()->getViewMatrix().getLookAt(eye, centre, up);
float angle;
osg::Vec3f axis;
if (mDragAxis == -1)
{
// Free rotate
float rotationFactor = CSMPrefs::get()["3D Scene Input"]["rotate-factor"].toDouble() * speedFactor;
osg::Quat cameraRotation = getWorldspaceWidget().getCamera()->getInverseViewMatrix().getRotate();
osg::Vec3f camForward = centre - eye;
osg::Vec3f screenDir = cameraRotation * osg::Vec3f(diffX, diffY, 0);
screenDir.normalize();
angle = std::sqrt(diffX * diffX + diffY * diffY) * rotationFactor;
axis = screenDir ^ camForward;
}
else
{
// Global axis rotation
osg::Vec3f camBack = eye - centre;
for (int i = 0; i < 3; ++i)
{
if (i == mDragAxis)
axis[i] = 1;
else
axis[i] = 0;
}
// Flip axis if facing opposite side
if (camBack * axis < 0)
axis *= -1;
// Convert coordinate system
osg::Vec3f screenCenter = getScreenCoords(getSelectionCenter(selection));
int widgetHeight = getWorldspaceWidget().height();
float newX = pos.x() - screenCenter.x();
float newY = (widgetHeight - pos.y()) - screenCenter.y();
float oldX = newX - diffX;
float oldY = newY - diffY; // diffY appears to already be flipped
osg::Vec3f oldVec = osg::Vec3f(oldX, oldY, 0);
oldVec.normalize();
osg::Vec3f newVec = osg::Vec3f(newX, newY, 0);
newVec.normalize();
// Find angle and axis of rotation
angle = std::acos(oldVec * newVec) * speedFactor;
if (((oldVec ^ newVec) * camBack < 0) ^ (camBack.z() < 0))
angle *= -1;
}
rotation = osg::Quat(angle, axis);
}
else if (mDragMode == DragMode_Scale || mDragMode == DragMode_Scale_Snap)
{
osg::Vec3f center = getScreenCoords(getSelectionCenter(selection));
// Calculate scaling distance/rate
int widgetHeight = getWorldspaceWidget().height();
float dx = pos.x() - center.x();
float dy = (widgetHeight - pos.y()) - center.y();
float dist = std::sqrt(dx * dx + dy * dy);
float scale = dist / mUnitScaleDist;
// Only uniform scaling is currently supported
offset = osg::Vec3f(scale, scale, scale);
}
else if (mSelectionMode->getCurrentId() == "cube-centre")
{
osg::Vec3f mousePlanePoint = getMousePlaneCoords(pos, getProjectionSpaceCoords(mSelectionMode->getDragStart()));
mSelectionMode->drawSelectionCubeCentre(mousePlanePoint);
return;
}
else if (mSelectionMode->getCurrentId() == "cube-corner")
{
osg::Vec3f mousePlanePoint = getMousePlaneCoords(pos, getProjectionSpaceCoords(mSelectionMode->getDragStart()));
mSelectionMode->drawSelectionCubeCorner(mousePlanePoint);
return;
}
else if (mSelectionMode->getCurrentId() == "sphere")
{
osg::Vec3f mousePlanePoint = getMousePlaneCoords(pos, getProjectionSpaceCoords(mSelectionMode->getDragStart()));
mSelectionMode->drawSelectionSphere(mousePlanePoint);
return;
}
int i = 0;
// Apply
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter(selection.begin()); iter != selection.end(); ++iter, i++)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
if (mDragMode == DragMode_Move || mDragMode == DragMode_Move_Snap)
{
ESM::Position position = objectTag->mObject->getPosition();
osg::Vec3f mousePos = getMousePlaneCoords(pos, getProjectionSpaceCoords(mDragStart));
float addToX = mousePos.x() - mDragStart.x();
float addToY = mousePos.y() - mDragStart.y();
float addToZ = mousePos.z() - mDragStart.z();
position.pos[0] = mObjectsAtDragStart[i].x() + addToX;
position.pos[1] = mObjectsAtDragStart[i].y() + addToY;
position.pos[2] = mObjectsAtDragStart[i].z() + addToZ;
if (mDragMode == DragMode_Move_Snap)
{
double snap = CSMPrefs::get()["3D Scene Editing"]["gridsnap-movement"].toDouble();
if (snapTarget)
{
osg::Vec3 translation(addToX, addToY, addToZ);
auto snapTargetPosition = snapTarget->mObject->getPosition();
auto newPosition = calculateSnapPositionRelativeToTarget(mObjectsAtDragStart[i],
snapTargetPosition.asVec3(), snapTargetPosition.asRotationVec3(), translation, snap);
position.pos[0] = newPosition[0];
position.pos[1] = newPosition[1];
position.pos[2] = newPosition[2];
}
else
{
position.pos[0] = CSVRender::InstanceMode::roundFloatToMult(position.pos[0], snap);
position.pos[1] = CSVRender::InstanceMode::roundFloatToMult(position.pos[1], snap);
position.pos[2] = CSVRender::InstanceMode::roundFloatToMult(position.pos[2], snap);
}
}
// XYZ-locking
if (mDragAxis != -1)
{
for (int j = 0; j < 3; ++j)
{
if (j != mDragAxis)
position.pos[j] = mObjectsAtDragStart[i][j];
}
}
objectTag->mObject->setPosition(position.pos);
}
else if (mDragMode == DragMode_Rotate || mDragMode == DragMode_Rotate_Snap)
{
ESM::Position position = objectTag->mObject->getPosition();
osg::Quat currentRot = eulerToQuat(osg::Vec3f(position.rot[0], position.rot[1], position.rot[2]));
osg::Quat combined = currentRot * rotation;
osg::Vec3f euler = quatToEuler(combined);
// There appears to be a very rare rounding error that can cause asin to return NaN
if (!euler.isNaN())
{
position.rot[0] = euler.x();
position.rot[1] = euler.y();
position.rot[2] = euler.z();
}
objectTag->mObject->setRotation(position.rot);
}
else if (mDragMode == DragMode_Scale || mDragMode == DragMode_Scale_Snap)
{
// Reset scale
objectTag->mObject->setEdited(0);
objectTag->mObject->setEdited(Object::Override_Scale);
float scale = objectTag->mObject->getScale();
scale *= offset.x();
if (mDragMode == DragMode_Scale_Snap)
{
scale = CSVRender::InstanceMode::roundFloatToMult(
scale, CSMPrefs::get()["3D Scene Editing"]["gridsnap-scale"].toDouble());
}
objectTag->mObject->setScale(scale);
}
}
}
}
void CSVRender::InstanceMode::dragCompleted(const QPoint& pos)
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getEdited(Mask_Reference);
auto* snapTarget = dynamic_cast<CSVRender::ObjectTag*>(getWorldspaceWidget().getSnapTarget(Mask_Reference).get());
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description;
switch (mDragMode)
{
case DragMode_Move:
description = "Move Instances";
break;
case DragMode_Rotate:
description = "Rotate Instances";
break;
case DragMode_Scale:
description = "Scale Instances";
break;
case DragMode_Select_Only:
handleSelectDrag(pos);
return;
break;
case DragMode_Select_Add:
handleSelectDrag(pos);
return;
break;
case DragMode_Select_Remove:
handleSelectDrag(pos);
return;
break;
case DragMode_Select_Invert:
handleSelectDrag(pos);
return;
break;
case DragMode_Move_Snap:
description = "Move Instances";
break;
case DragMode_Rotate_Snap:
description = "Rotate Instances";
break;
case DragMode_Scale_Snap:
description = "Scale Instances";
break;
case DragMode_None:
break;
}
CSMWorld::CommandMacro macro(undoStack, description);
// Is this even supposed to be here?
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter(selection.begin()); iter != selection.end(); ++iter)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
if (mDragMode == DragMode_Rotate_Snap)
{
ESM::Position position = objectTag->mObject->getPosition();
double snap = CSMPrefs::get()["3D Scene Editing"]["gridsnap-rotation"].toDouble();
float xOffset = 0;
float yOffset = 0;
float zOffset = 0;
if (snapTarget)
{
auto snapTargetPosition = snapTarget->mObject->getPosition();
auto rotation = snapTargetPosition.rot;
if (rotation)
{
xOffset = remainder(rotation[0], osg::DegreesToRadians(snap));
yOffset = remainder(rotation[1], osg::DegreesToRadians(snap));
zOffset = remainder(rotation[2], osg::DegreesToRadians(snap));
}
}
position.rot[0]
= CSVRender::InstanceMode::roundFloatToMult(position.rot[0], osg::DegreesToRadians(snap)) + xOffset;
position.rot[1]
= CSVRender::InstanceMode::roundFloatToMult(position.rot[1], osg::DegreesToRadians(snap)) + yOffset;
position.rot[2]
= CSVRender::InstanceMode::roundFloatToMult(position.rot[2], osg::DegreesToRadians(snap)) + zOffset;
objectTag->mObject->setRotation(position.rot);
}
objectTag->mObject->apply(macro);
}
}
mObjectsAtDragStart.clear();
mDragMode = DragMode_None;
}
void CSVRender::InstanceMode::dragAborted()
{
getWorldspaceWidget().reset(Mask_Reference);
mDragMode = DragMode_None;
}
void CSVRender::InstanceMode::dragWheel(int diff, double speedFactor)
{
if (mDragMode == DragMode_Move || mDragMode == DragMode_Move_Snap)
{
osg::Vec3f eye;
osg::Vec3f centre;
osg::Vec3f up;
getWorldspaceWidget().getCamera()->getViewMatrix().getLookAt(eye, centre, up);
osg::Vec3f offset = centre - eye;
offset.normalize();
offset *= diff * speedFactor;
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getEdited(Mask_Reference);
auto snapTarget
= dynamic_cast<CSVRender::ObjectTag*>(getWorldspaceWidget().getSnapTarget(Mask_Reference).get());
int j = 0;
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter(selection.begin()); iter != selection.end(); ++iter, j++)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(iter->get()))
{
ESM::Position position = objectTag->mObject->getPosition();
auto preMovedObjectPosition = position.asVec3();
for (int i = 0; i < 3; ++i)
position.pos[i] += offset[i];
if (mDragMode == DragMode_Move_Snap)
{
double snap = CSMPrefs::get()["3D Scene Editing"]["gridsnap-movement"].toDouble();
if (snapTarget)
{
osg::Vec3 translation(snap, snap, snap);
auto snapTargetPosition = snapTarget->mObject->getPosition();
auto newPosition = calculateSnapPositionRelativeToTarget(preMovedObjectPosition,
snapTargetPosition.asVec3(), snapTargetPosition.asRotationVec3(), translation, snap);
position.pos[0] = newPosition[0];
position.pos[1] = newPosition[1];
position.pos[2] = newPosition[2];
}
else
{
position.pos[0] = CSVRender::InstanceMode::roundFloatToMult(position.pos[0], snap);
position.pos[1] = CSVRender::InstanceMode::roundFloatToMult(position.pos[1], snap);
position.pos[2] = CSVRender::InstanceMode::roundFloatToMult(position.pos[2], snap);
}
}
objectTag->mObject->setPosition(position.pos);
osg::Vec3f thisPoint(position.pos[0], position.pos[1], position.pos[2]);
mDragStart = getMousePlaneCoords(
getWorldspaceWidget().mapFromGlobal(QCursor::pos()), getProjectionSpaceCoords(thisPoint));
mObjectsAtDragStart[j] = thisPoint;
}
}
}
}
void CSVRender::InstanceMode::dragEnterEvent(QDragEnterEvent* event)
{
if (const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData()))
{
if (!mime->fromDocument(getWorldspaceWidget().getDocument()))
return;
if (mime->holdsType(CSMWorld::UniversalId::Type_Referenceable))
event->accept();
}
}
void CSVRender::InstanceMode::dropEvent(QDropEvent* event)
{
if (const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData()))
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
if (!mime->fromDocument(document))
return;
WorldspaceHitResult hit
= getWorldspaceWidget().mousePick(event->pos(), getWorldspaceWidget().getInteractionMask());
std::string cellId = getWorldspaceWidget().getCellId(hit.worldPos);
CSMWorld::IdTree& cellTable
= dynamic_cast<CSMWorld::IdTree&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
const bool noCell = document.getData().getCells().searchId(ESM::RefId::stringRefId(cellId)) == -1;
if (noCell)
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-drop"].toString();
// target cell does not exist
if (mode == "Discard")
return;
if (mode == "Create cell and insert")
{
std::unique_ptr<CSMWorld::CreateCommand> createCommand(new CSMWorld::CreateCommand(cellTable, cellId));
int parentIndex = cellTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
int index = cellTable.findNestedColumnIndex(parentIndex, CSMWorld::Columns::ColumnId_Interior);
createCommand->addNestedValue(parentIndex, index, false);
document.getUndoStack().push(createCommand.release());
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
else if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
if (!selection.has(CSMWorld::CellCoordinates::fromId(cellId).first))
{
// target cell exists, but is not shown
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-visible-drop"].toString();
if (mode == "Discard")
return;
if (mode == "Show cell and insert")
{
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
CSMWorld::IdTable& referencesTable = dynamic_cast<CSMWorld::IdTable&>(
*document.getData().getTableModel(CSMWorld::UniversalId::Type_References));
bool dropped = false;
std::vector<CSMWorld::UniversalId> ids = mime->getData();
for (std::vector<CSMWorld::UniversalId>::const_iterator iter(ids.begin()); iter != ids.end(); ++iter)
if (mime->isReferencable(iter->getType()))
{
// create reference
std::unique_ptr<CSMWorld::CreateCommand> createCommand(
new CSMWorld::CreateCommand(referencesTable, document.getData().getReferences().getNewId()));
createCommand->addValue(referencesTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell),
QString::fromUtf8(cellId.c_str()));
createCommand->addValue(
referencesTable.findColumnIndex(CSMWorld::Columns::ColumnId_PositionXPos), hit.worldPos.x());
createCommand->addValue(
referencesTable.findColumnIndex(CSMWorld::Columns::ColumnId_PositionYPos), hit.worldPos.y());
createCommand->addValue(
referencesTable.findColumnIndex(CSMWorld::Columns::ColumnId_PositionZPos), hit.worldPos.z());
createCommand->addValue(referencesTable.findColumnIndex(CSMWorld::Columns::ColumnId_ReferenceableId),
QString::fromUtf8(iter->getId().c_str()));
document.getUndoStack().push(createCommand.release());
dropped = true;
}
if (dropped)
event->accept();
}
}
int CSVRender::InstanceMode::getSubMode() const
{
return mSubMode ? getSubModeFromId(mSubMode->getCurrentId()) : 0;
}
void CSVRender::InstanceMode::subModeChanged(const std::string& id)
{
mSubModeId = id;
getWorldspaceWidget().abortDrag();
getWorldspaceWidget().setSubMode(getSubModeFromId(id), Mask_Reference);
}
void CSVRender::InstanceMode::handleSelectDrag(const QPoint& pos)
{
osg::Vec3f mousePlanePoint = getMousePlaneCoords(pos, getProjectionSpaceCoords(mSelectionMode->getDragStart()));
mSelectionMode->dragEnded(mousePlanePoint, mDragMode);
mDragMode = DragMode_None;
}
void CSVRender::InstanceMode::deleteSelectedInstances()
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return;
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& referencesTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_References));
QUndoStack& undoStack = document.getUndoStack();
CSMWorld::CommandMacro macro(undoStack, "Delete Instances");
for (osg::ref_ptr<TagBase> tag : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
macro.push(new CSMWorld::DeleteCommand(referencesTable, objectTag->mObject->getReferenceId()));
getWorldspaceWidget().clearSelection(Mask_Reference);
}
void CSVRender::InstanceMode::cloneSelectedInstances()
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return;
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& referencesTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_References));
QUndoStack& undoStack = document.getUndoStack();
CSMWorld::CommandMacro macro(undoStack, "Clone Instances");
for (osg::ref_ptr<TagBase> tag : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
macro.push(new CSMWorld::CloneCommand(referencesTable, objectTag->mObject->getReferenceId(),
"ref#" + std::to_string(referencesTable.rowCount()), CSMWorld::UniversalId::Type_Reference));
}
// getWorldspaceWidget().clearSelection(Mask_Reference);
}
void CSVRender::InstanceMode::dropInstance(CSVRender::Object* object, float dropHeight)
{
object->setEdited(Object::Override_Position);
ESM::Position position = object->getPosition();
position.pos[2] -= dropHeight;
object->setPosition(position.pos);
}
float CSVRender::InstanceMode::calculateDropHeight(DropMode dropMode, CSVRender::Object* object, float objectHeight)
{
osg::Vec3d point = object->getPosition().asVec3();
osg::Vec3d start = point;
start.z() += objectHeight;
osg::Vec3d end = point;
end.z() = std::numeric_limits<float>::lowest();
osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector(
new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, start, end));
intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::NO_LIMIT);
osgUtil::IntersectionVisitor visitor(intersector);
if (dropMode & Terrain)
visitor.setTraversalMask(Mask_Terrain);
if (dropMode & Collision)
visitor.setTraversalMask(Mask_Terrain | Mask_Reference);
mParentNode->accept(visitor);
osgUtil::LineSegmentIntersector::Intersections::iterator it = intersector->getIntersections().begin();
if (it != intersector->getIntersections().end())
{
osgUtil::LineSegmentIntersector::Intersection intersection = *it;
float collisionLevel = intersection.getWorldIntersectPoint().z();
return point.z() - collisionLevel + objectHeight;
}
return 0.0f;
}
void CSVRender::InstanceMode::dropSelectedInstancesToCollision()
{
handleDropMethod(Collision, "Drop instances to next collision");
}
void CSVRender::InstanceMode::dropSelectedInstancesToTerrain()
{
handleDropMethod(Terrain, "Drop instances to terrain level");
}
void CSVRender::InstanceMode::dropSelectedInstancesToCollisionSeparately()
{
handleDropMethod(CollisionSep, "Drop instances to next collision level separately");
}
void CSVRender::InstanceMode::dropSelectedInstancesToTerrainSeparately()
{
handleDropMethod(TerrainSep, "Drop instances to terrain level separately");
}
void CSVRender::InstanceMode::handleDropMethod(DropMode dropMode, QString commandMsg)
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
if (selection.empty())
return;
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
QUndoStack& undoStack = document.getUndoStack();
CSMWorld::CommandMacro macro(undoStack, commandMsg);
DropObjectHeightHandler dropObjectDataHandler(&getWorldspaceWidget());
if (dropMode & Separate)
{
int counter = 0;
for (osg::ref_ptr<TagBase> tag : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
float objectHeight = dropObjectDataHandler.mObjectHeights[counter];
float dropHeight = calculateDropHeight(dropMode, objectTag->mObject, objectHeight);
dropInstance(objectTag->mObject, dropHeight);
objectTag->mObject->apply(macro);
counter++;
}
}
else
{
float smallestDropHeight = std::numeric_limits<float>::max();
int counter = 0;
for (osg::ref_ptr<TagBase> tag : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
float objectHeight = dropObjectDataHandler.mObjectHeights[counter];
float thisDrop = calculateDropHeight(dropMode, objectTag->mObject, objectHeight);
if (thisDrop < smallestDropHeight)
smallestDropHeight = thisDrop;
counter++;
}
for (osg::ref_ptr<TagBase> tag : selection)
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
dropInstance(objectTag->mObject, smallestDropHeight);
objectTag->mObject->apply(macro);
}
}
}
CSVRender::DropObjectHeightHandler::DropObjectHeightHandler(WorldspaceWidget* worldspacewidget)
: mWorldspaceWidget(worldspacewidget)
{
std::vector<osg::ref_ptr<TagBase>> selection = mWorldspaceWidget->getSelection(Mask_Reference);
for (osg::ref_ptr<TagBase> tag : selection)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
osg::ref_ptr<osg::Group> objectNodeWithGUI = objectTag->mObject->getRootNode();
osg::ref_ptr<osg::Group> objectNodeWithoutGUI = objectTag->mObject->getBaseNode();
osg::ComputeBoundsVisitor computeBounds;
computeBounds.setTraversalMask(Mask_Reference);
objectNodeWithoutGUI->accept(computeBounds);
osg::BoundingBox bounds = computeBounds.getBoundingBox();
float boundingBoxOffset = 0.0f;
if (bounds.valid())
boundingBoxOffset = bounds.zMin();
mObjectHeights.emplace_back(boundingBoxOffset);
mOldMasks.emplace_back(objectNodeWithGUI->getNodeMask());
objectNodeWithGUI->setNodeMask(0);
}
}
}
CSVRender::DropObjectHeightHandler::~DropObjectHeightHandler()
{
std::vector<osg::ref_ptr<TagBase>> selection = mWorldspaceWidget->getSelection(Mask_Reference);
int counter = 0;
for (osg::ref_ptr<TagBase> tag : selection)
{
if (CSVRender::ObjectTag* objectTag = dynamic_cast<CSVRender::ObjectTag*>(tag.get()))
{
osg::ref_ptr<osg::Group> objectNodeWithGUI = objectTag->mObject->getRootNode();
objectNodeWithGUI->setNodeMask(mOldMasks[counter]);
counter++;
}
}
}
| 53,442
|
C++
|
.cpp
| 1,145
| 37.441048
| 120
| 0.641675
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,109
|
cellmarker.cpp
|
OpenMW_openmw/apps/opencs/view/render/cellmarker.cpp
|
#include "cellmarker.hpp"
#include <string>
#include <osg/AutoTransform>
#include <osg/GL>
#include <osg/Group>
#include <osg/Material>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <osgText/Text>
#include <osgText/TextBase>
#include <components/misc/constants.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/view/render/mask.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
CSVRender::CellMarkerTag::CellMarkerTag(CellMarker* marker)
: TagBase(Mask_CellMarker)
, mMarker(marker)
{
}
CSVRender::CellMarker* CSVRender::CellMarkerTag::getCellMarker() const
{
return mMarker;
}
void CSVRender::CellMarker::buildMarker()
{
const int characterSize = 20;
// Set up attributes of marker text.
osg::ref_ptr<osgText::Text> markerText(new osgText::Text);
markerText->setLayout(osgText::Text::LEFT_TO_RIGHT);
markerText->setCharacterSize(characterSize);
markerText->setAlignment(osgText::Text::CENTER_CENTER);
markerText->setDrawMode(osgText::Text::TEXT | osgText::Text::FILLEDBOUNDINGBOX);
// If cell exists then show black bounding box otherwise show red.
if (mExists)
{
markerText->setBoundingBoxColor(osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f));
}
else
{
markerText->setBoundingBoxColor(osg::Vec4f(1.0f, 0.0f, 0.0f, 1.0f));
}
// Add text containing cell's coordinates.
std::string coordinatesText = std::to_string(mCoordinates.getX()) + "," + std::to_string(mCoordinates.getY());
markerText->setText(coordinatesText);
// Add text to marker node.
mMarkerNode->addChild(markerText);
}
void CSVRender::CellMarker::positionMarker()
{
const int cellSize = Constants::CellSizeInUnits;
const int markerHeight = 0;
// Move marker to center of cell.
int x = (mCoordinates.getX() * cellSize) + (cellSize / 2);
int y = (mCoordinates.getY() * cellSize) + (cellSize / 2);
mMarkerNode->setPosition(osg::Vec3f(x, y, markerHeight));
}
CSVRender::CellMarker::CellMarker(
osg::Group* cellNode, const CSMWorld::CellCoordinates& coordinates, const bool cellExists)
: mCellNode(cellNode)
, mCoordinates(coordinates)
, mExists(cellExists)
{
// Set up node for cell marker.
mMarkerNode = new osg::AutoTransform();
mMarkerNode->setAutoRotateMode(osg::AutoTransform::ROTATE_TO_SCREEN);
mMarkerNode->setAutoScaleToScreen(true);
mMarkerNode->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
mMarkerNode->getOrCreateStateSet()->setRenderBinDetails(11, "RenderBin");
osg::ref_ptr<osg::Material> mat = new osg::Material;
mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
mMarkerNode->getOrCreateStateSet()->setAttribute(mat);
mMarkerNode->setUserData(new CellMarkerTag(this));
mMarkerNode->setNodeMask(Mask_CellMarker);
mCellNode->addChild(mMarkerNode);
buildMarker();
positionMarker();
}
CSVRender::CellMarker::~CellMarker()
{
mCellNode->removeChild(mMarkerNode);
}
| 3,069
|
C++
|
.cpp
| 83
| 33.301205
| 114
| 0.734164
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,110
|
brushdraw.cpp
|
OpenMW_openmw/apps/opencs/view/render/brushdraw.cpp
|
#include "brushdraw.hpp"
#include <limits>
#include <set>
#include <utility>
#include <osg/Array>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Math>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec4f>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/LineSegmentIntersector>
#include <components/esm3/loadland.hpp>
#include "../../model/world/cellcoordinates.hpp"
#include "../widget/brushshapes.hpp"
#include "mask.hpp"
CSVRender::BrushDraw::BrushDraw(osg::ref_ptr<osg::Group> parentNode, bool textureMode)
: mParentNode(std::move(parentNode))
, mTextureMode(textureMode)
{
mBrushDrawNode = new osg::Group();
mGeometry = new osg::Geometry();
mBrushDrawNode->addChild(mGeometry);
mBrushDrawNode->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
mBrushDrawNode->getOrCreateStateSet()->setRenderBinDetails(11, "RenderBin");
mParentNode->addChild(mBrushDrawNode);
if (mTextureMode)
mLandSizeFactor = static_cast<float>(ESM::Land::REAL_SIZE) / static_cast<float>(ESM::Land::LAND_TEXTURE_SIZE);
else
mLandSizeFactor = static_cast<float>(ESM::Land::REAL_SIZE) / static_cast<float>(ESM::Land::LAND_SIZE - 1);
}
CSVRender::BrushDraw::~BrushDraw()
{
mBrushDrawNode->removeChild(mGeometry);
mParentNode->removeChild(mBrushDrawNode);
}
float CSVRender::BrushDraw::getIntersectionHeight(const osg::Vec3d& point)
{
osg::Vec3d start = point;
osg::Vec3d end = point;
start.z() = std::numeric_limits<int>::max();
end.z() = std::numeric_limits<int>::lowest();
osg::Vec3d direction = end - start;
// Get intersection
osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector(
new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, start, end));
intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::NO_LIMIT);
osgUtil::IntersectionVisitor visitor(intersector);
visitor.setTraversalMask(Mask_Terrain);
mParentNode->accept(visitor);
for (osgUtil::LineSegmentIntersector::Intersections::iterator it = intersector->getIntersections().begin();
it != intersector->getIntersections().end(); ++it)
{
osgUtil::LineSegmentIntersector::Intersection intersection = *it;
// reject back-facing polygons
if (direction * intersection.getWorldIntersectNormal() > 0)
{
continue;
}
return intersection.getWorldIntersectPoint().z();
}
return 0.0f;
}
void CSVRender::BrushDraw::buildPointGeometry(const osg::Vec3d& point)
{
osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());
osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array());
osg::ref_ptr<osg::Vec4Array> colors(new osg::Vec4Array());
const float brushOutlineHeight(1.0f);
const float crossHeadSize(8.0f);
osg::Vec4f lineColor(1.0f, 1.0f, 1.0f, 0.6f);
vertices->push_back(osg::Vec3d(point.x() - crossHeadSize, point.y() - crossHeadSize,
getIntersectionHeight(osg::Vec3d(point.x() - crossHeadSize, point.y() - crossHeadSize, point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
vertices->push_back(osg::Vec3d(point.x() + crossHeadSize, point.y() + crossHeadSize,
getIntersectionHeight(osg::Vec3d(point.x() + crossHeadSize, point.y() + crossHeadSize, point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
vertices->push_back(osg::Vec3d(point.x() + crossHeadSize, point.y() - crossHeadSize,
getIntersectionHeight(osg::Vec3d(point.x() + crossHeadSize, point.y() - crossHeadSize, point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
vertices->push_back(osg::Vec3d(point.x() - crossHeadSize, point.y() + crossHeadSize,
getIntersectionHeight(osg::Vec3d(point.x() - crossHeadSize, point.y() + crossHeadSize, point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
geom->setVertexArray(vertices);
geom->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 4));
mGeometry = geom;
}
void CSVRender::BrushDraw::buildSquareGeometry(const float& radius, const osg::Vec3d& point)
{
osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());
osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array());
osg::ref_ptr<osg::Vec4Array> colors(new osg::Vec4Array());
const float brushOutlineHeight(1.0f);
float diameter = radius * 2;
int resolution = static_cast<int>(2.f * diameter / mLandSizeFactor); // half a vertex resolution
float resAdjustedLandSizeFactor = mLandSizeFactor / 2; // 128
if (resolution > 128) // limit accuracy for performance
{
resolution = 128;
resAdjustedLandSizeFactor = diameter / resolution;
}
osg::Vec4f lineColor(1.0f, 1.0f, 1.0f, 0.6f);
for (int i = 0; i < resolution; i++)
{
int step = i * resAdjustedLandSizeFactor;
int step2 = (i + 1) * resAdjustedLandSizeFactor;
osg::Vec3d upHorizontalLinePoint1(point.x() - radius + step, point.y() - radius,
getIntersectionHeight(osg::Vec3d(point.x() - radius + step, point.y() - radius, point.z()))
+ brushOutlineHeight);
osg::Vec3d upHorizontalLinePoint2(point.x() - radius + step2, point.y() - radius,
getIntersectionHeight(osg::Vec3d(point.x() - radius + step2, point.y() - radius, point.z()))
+ brushOutlineHeight);
osg::Vec3d upVerticalLinePoint1(point.x() - radius, point.y() - radius + step,
getIntersectionHeight(osg::Vec3d(point.x() - radius, point.y() - radius + step, point.z()))
+ brushOutlineHeight);
osg::Vec3d upVerticalLinePoint2(point.x() - radius, point.y() - radius + step2,
getIntersectionHeight(osg::Vec3d(point.x() - radius, point.y() - radius + step2, point.z()))
+ brushOutlineHeight);
osg::Vec3d downHorizontalLinePoint1(point.x() + radius - step, point.y() + radius,
getIntersectionHeight(osg::Vec3d(point.x() + radius - step, point.y() + radius, point.z()))
+ brushOutlineHeight);
osg::Vec3d downHorizontalLinePoint2(point.x() + radius - step2, point.y() + radius,
getIntersectionHeight(osg::Vec3d(point.x() + radius - step2, point.y() + radius, point.z()))
+ brushOutlineHeight);
osg::Vec3d downVerticalLinePoint1(point.x() + radius, point.y() + radius - step,
getIntersectionHeight(osg::Vec3d(point.x() + radius, point.y() + radius - step, point.z()))
+ brushOutlineHeight);
osg::Vec3d downVerticalLinePoint2(point.x() + radius, point.y() + radius - step2,
getIntersectionHeight(osg::Vec3d(point.x() + radius, point.y() + radius - step2, point.z()))
+ brushOutlineHeight);
vertices->push_back(upHorizontalLinePoint1);
colors->push_back(lineColor);
vertices->push_back(upHorizontalLinePoint2);
colors->push_back(lineColor);
vertices->push_back(upVerticalLinePoint1);
colors->push_back(lineColor);
vertices->push_back(upVerticalLinePoint2);
colors->push_back(lineColor);
vertices->push_back(downHorizontalLinePoint1);
colors->push_back(lineColor);
vertices->push_back(downHorizontalLinePoint2);
colors->push_back(lineColor);
vertices->push_back(downVerticalLinePoint1);
colors->push_back(lineColor);
vertices->push_back(downVerticalLinePoint2);
colors->push_back(lineColor);
}
geom->setVertexArray(vertices);
geom->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, resolution * 8));
mGeometry = geom;
}
void CSVRender::BrushDraw::buildCircleGeometry(const float& radius, const osg::Vec3d& point)
{
osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());
osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array());
osg::ref_ptr<osg::Vec4Array> colors(new osg::Vec4Array());
const int amountOfPoints = 128;
const float step((osg::PI * 2.0f) / static_cast<float>(amountOfPoints));
const float brushOutlineHeight(1.0f);
osg::Vec4f lineColor(1.0f, 1.0f, 1.0f, 0.6f);
for (int i = 0; i < amountOfPoints + 2; i++)
{
float angle(i * step);
vertices->push_back(osg::Vec3d(point.x() + radius * cosf(angle), point.y() + radius * sinf(angle),
getIntersectionHeight(
osg::Vec3d(point.x() + radius * cosf(angle), point.y() + radius * sinf(angle), point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
angle = static_cast<float>(i + 1) * step;
vertices->push_back(osg::Vec3d(point.x() + radius * cosf(angle), point.y() + radius * sinf(angle),
getIntersectionHeight(
osg::Vec3d(point.x() + radius * cosf(angle), point.y() + radius * sinf(angle), point.z()))
+ brushOutlineHeight));
colors->push_back(lineColor);
}
geom->setVertexArray(vertices);
geom->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP, 0, amountOfPoints * 2));
mGeometry = geom;
}
void CSVRender::BrushDraw::buildCustomGeometry(const float& radius, const osg::Vec3d& point)
{
// Not implemented
}
void CSVRender::BrushDraw::update(osg::Vec3d point, int brushSize, CSVWidget::BrushShape toolShape)
{
if (mBrushDrawNode->containsNode(mGeometry))
mBrushDrawNode->removeChild(mGeometry);
float radius = (mLandSizeFactor * brushSize) / 2;
osg::Vec3d snapToGridPoint = point;
if (mTextureMode)
{
std::pair<int, int> snapToGridXY = CSMWorld::CellCoordinates::toTextureCoords(point);
float offsetToMiddle = mLandSizeFactor * 0.5f;
snapToGridPoint = osg::Vec3d(
CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(snapToGridXY.first) + offsetToMiddle,
CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(snapToGridXY.second) + offsetToMiddle, point.z());
}
else
{
std::pair<int, int> snapToGridXY = CSMWorld::CellCoordinates::toVertexCoords(point);
snapToGridPoint = osg::Vec3d(CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(snapToGridXY.first),
CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(snapToGridXY.second), point.z());
}
switch (toolShape)
{
case (CSVWidget::BrushShape_Point):
buildPointGeometry(snapToGridPoint);
break;
case (CSVWidget::BrushShape_Square):
buildSquareGeometry(radius, snapToGridPoint);
break;
case (CSVWidget::BrushShape_Circle):
buildCircleGeometry(radius, snapToGridPoint);
break;
case (CSVWidget::BrushShape_Custom):
buildSquareGeometry(1, snapToGridPoint);
// buildCustomGeometry
break;
}
mGeometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mBrushDrawNode->addChild(mGeometry);
}
void CSVRender::BrushDraw::hide()
{
if (mBrushDrawNode->containsNode(mGeometry))
mBrushDrawNode->removeChild(mGeometry);
}
| 11,432
|
C++
|
.cpp
| 237
| 41.350211
| 118
| 0.675925
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,111
|
actor.cpp
|
OpenMW_openmw/apps/opencs/view/render/actor.cpp
|
#include "actor.hpp"
#include <memory>
#include <unordered_map>
#include <utility>
#include <osg/Group>
#include <osg/MatrixTransform>
#include <osg/Node>
#include <osg/Vec3d>
#include <apps/opencs/model/world/actoradapter.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <components/esm3/loadbody.hpp>
#include <components/esm3/mappings.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/sceneutil/attach.hpp>
#include <components/sceneutil/skeleton.hpp>
#include "../../model/world/data.hpp"
namespace CSVRender
{
const std::string Actor::MeshPrefix = "meshes\\";
Actor::Actor(const ESM::RefId& id, CSMWorld::Data& data)
: mId(id)
, mData(data)
, mBaseNode(new osg::PositionAttitudeTransform())
, mSkeleton(nullptr)
{
mActorData = mData.getActorAdapter()->getActorData(mId);
connect(mData.getActorAdapter(), &CSMWorld::ActorAdapter::actorChanged, this, &Actor::handleActorChanged);
}
osg::Group* Actor::getBaseNode()
{
return mBaseNode;
}
void Actor::update()
{
mBaseNode->removeChildren(0, mBaseNode->getNumChildren());
// Load skeleton
VFS::Path::Normalized skeletonModel = mActorData->getSkeleton();
skeletonModel
= Misc::ResourceHelpers::correctActorModelPath(skeletonModel, mData.getResourceSystem()->getVFS());
loadSkeleton(skeletonModel);
if (!mActorData->isCreature())
{
// Get rid of the extra attachments
SceneUtil::CleanObjectRootVisitor cleanVisitor;
mSkeleton->accept(cleanVisitor);
cleanVisitor.remove();
// Attach parts to skeleton
loadBodyParts();
const osg::Vec2f& attributes = mActorData->getRaceWeightHeight();
mBaseNode->setScale(osg::Vec3d(attributes.x(), attributes.x(), attributes.y()));
}
else
{
SceneUtil::RemoveTriBipVisitor removeTriBipVisitor;
mSkeleton->accept(removeTriBipVisitor);
removeTriBipVisitor.remove();
}
// Post setup
mSkeleton->markDirty();
mSkeleton->setActive(SceneUtil::Skeleton::Active);
}
void Actor::handleActorChanged(const ESM::RefId& refId)
{
if (mId == refId)
{
update();
}
}
void Actor::loadSkeleton(const std::string& model)
{
auto sceneMgr = mData.getResourceSystem()->getSceneManager();
osg::ref_ptr<osg::Node> temp = sceneMgr->getInstance(VFS::Path::toNormalized(model));
mSkeleton = dynamic_cast<SceneUtil::Skeleton*>(temp.get());
if (!mSkeleton)
{
mSkeleton = new SceneUtil::Skeleton();
mSkeleton->addChild(temp);
}
mBaseNode->addChild(mSkeleton);
// Map bone names to bones
mNodeMap.clear();
SceneUtil::NodeMapVisitor nmVisitor(mNodeMap);
mSkeleton->accept(nmVisitor);
}
void Actor::loadBodyParts()
{
for (int i = 0; i < ESM::PRT_Count; ++i)
{
const auto type = static_cast<ESM::PartReferenceType>(i);
attachBodyPart(type, getBodyPartMesh(mActorData->getPart(type)));
}
}
void Actor::attachBodyPart(ESM::PartReferenceType type, const std::string& mesh)
{
auto sceneMgr = mData.getResourceSystem()->getSceneManager();
// Attach to skeleton
std::string boneName = ESM::getBoneName(type);
auto node = mNodeMap.find(boneName);
if (!mesh.empty() && node != mNodeMap.end())
{
auto instance = sceneMgr->getInstance(VFS::Path::toNormalized(mesh));
SceneUtil::attach(instance, mSkeleton, boneName, node->second, sceneMgr);
}
}
std::string Actor::getBodyPartMesh(const ESM::RefId& bodyPartId)
{
const auto& bodyParts = mData.getBodyParts();
const int index = bodyParts.searchId(bodyPartId);
if (index != -1 && !bodyParts.getRecord(index).isDeleted())
return MeshPrefix + bodyParts.getRecord(index).get().mModel;
else
return "";
}
}
| 4,334
|
C++
|
.cpp
| 117
| 29.478632
| 114
| 0.645123
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,112
|
cameracontroller.cpp
|
OpenMW_openmw/apps/opencs/view/render/cameracontroller.cpp
|
#include "cameracontroller.hpp"
#include <algorithm>
#include <cmath>
#include <set>
#include <QWidget>
#include <osg/BoundingBox>
#include <osg/Camera>
#include <osg/ComputeBoundsVisitor>
#include <osg/Group>
#include <osg/Math>
#include <osg/Matrixd>
#include <osg/Quat>
#include <osg/Vec3>
#include <osg/ref_ptr>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/LineSegmentIntersector>
#include "../../model/prefs/shortcut.hpp"
namespace CSVRender
{
/*
Camera Controller
*/
const osg::Vec3d CameraController::WorldUp = osg::Vec3d(0, 0, 1);
const osg::Vec3d CameraController::LocalUp = osg::Vec3d(0, 1, 0);
const osg::Vec3d CameraController::LocalLeft = osg::Vec3d(1, 0, 0);
const osg::Vec3d CameraController::LocalForward = osg::Vec3d(0, 0, 1);
CameraController::CameraController(QObject* parent)
: QObject(parent)
, mActive(false)
, mInverted(false)
, mCameraSensitivity(1 / 650.f)
, mSecondaryMoveMult(50)
, mWheelMoveMult(8)
, mCamera(nullptr)
{
}
bool CameraController::isActive() const
{
return mActive;
}
osg::Camera* CameraController::getCamera() const
{
return mCamera;
}
double CameraController::getCameraSensitivity() const
{
return mCameraSensitivity;
}
bool CameraController::getInverted() const
{
return mInverted;
}
double CameraController::getSecondaryMovementMultiplier() const
{
return mSecondaryMoveMult;
}
double CameraController::getWheelMovementMultiplier() const
{
return mWheelMoveMult;
}
void CameraController::setCamera(osg::Camera* camera)
{
bool wasActive = mActive;
mCamera = camera;
mActive = (mCamera != nullptr);
if (mActive != wasActive)
{
for (std::vector<CSMPrefs::Shortcut*>::iterator it = mShortcuts.begin(); it != mShortcuts.end(); ++it)
{
CSMPrefs::Shortcut* shortcut = *it;
shortcut->enable(mActive);
}
}
}
void CameraController::setCameraSensitivity(double value)
{
mCameraSensitivity = value;
}
void CameraController::setInverted(bool value)
{
mInverted = value;
}
void CameraController::setSecondaryMovementMultiplier(double value)
{
mSecondaryMoveMult = value;
}
void CameraController::setWheelMovementMultiplier(double value)
{
mWheelMoveMult = value;
}
void CameraController::setup(osg::Group* root, unsigned int mask, const osg::Vec3d& up)
{
// Find World bounds
osg::ComputeBoundsVisitor boundsVisitor;
osg::BoundingBox& boundingBox = boundsVisitor.getBoundingBox();
boundsVisitor.setTraversalMask(mask);
root->accept(boundsVisitor);
if (!boundingBox.valid())
{
// Try again without any mask
boundsVisitor.reset();
boundsVisitor.setTraversalMask(~0u);
root->accept(boundsVisitor);
// Last resort, set a default
if (!boundingBox.valid())
{
boundingBox.set(-1, -1, -1, 1, 1, 1);
}
}
// Calculate a good starting position
osg::Vec3d minBounds = boundingBox.corner(0) - boundingBox.center();
osg::Vec3d maxBounds = boundingBox.corner(7) - boundingBox.center();
osg::Vec3d camOffset = up * maxBounds > 0 ? maxBounds : minBounds;
camOffset *= 2;
osg::Vec3d eye = camOffset + boundingBox.center();
osg::Vec3d center = boundingBox.center();
getCamera()->setViewMatrixAsLookAt(eye, center, up);
}
void CameraController::addShortcut(CSMPrefs::Shortcut* shortcut)
{
mShortcuts.push_back(shortcut);
}
/*
Free Camera Controller
*/
FreeCameraController::FreeCameraController(QWidget* widget)
: CameraController(widget)
, mLockUpright(false)
, mModified(false)
, mNaviPrimary(false)
, mNaviSecondary(false)
, mFast(false)
, mFastAlternate(false)
, mLeft(false)
, mRight(false)
, mForward(false)
, mBackward(false)
, mRollLeft(false)
, mRollRight(false)
, mUp(LocalUp)
, mLinSpeed(1000)
, mRotSpeed(osg::PI / 2)
, mSpeedMult(8)
{
CSMPrefs::Shortcut* naviPrimaryShortcut = new CSMPrefs::Shortcut("scene-navi-primary", widget);
naviPrimaryShortcut->enable(false);
connect(naviPrimaryShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this,
&FreeCameraController::naviPrimary);
addShortcut(naviPrimaryShortcut);
CSMPrefs::Shortcut* naviSecondaryShortcut = new CSMPrefs::Shortcut("scene-navi-secondary", widget);
naviSecondaryShortcut->enable(false);
connect(naviSecondaryShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this,
&FreeCameraController::naviSecondary);
addShortcut(naviSecondaryShortcut);
CSMPrefs::Shortcut* forwardShortcut
= new CSMPrefs::Shortcut("free-forward", "scene-speed-modifier", CSMPrefs::Shortcut::SM_Detach, widget);
forwardShortcut->enable(false);
connect(forwardShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::forward);
connect(forwardShortcut, qOverload<bool>(&CSMPrefs::Shortcut::secondary), this,
&FreeCameraController::alternateFast);
addShortcut(forwardShortcut);
CSMPrefs::Shortcut* leftShortcut = new CSMPrefs::Shortcut("free-left", widget);
leftShortcut->enable(false);
connect(leftShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::left);
addShortcut(leftShortcut);
CSMPrefs::Shortcut* backShortcut = new CSMPrefs::Shortcut("free-backward", widget);
backShortcut->enable(false);
connect(backShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::backward);
addShortcut(backShortcut);
CSMPrefs::Shortcut* rightShortcut = new CSMPrefs::Shortcut("free-right", widget);
rightShortcut->enable(false);
connect(rightShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::right);
addShortcut(rightShortcut);
CSMPrefs::Shortcut* rollLeftShortcut = new CSMPrefs::Shortcut("free-roll-left", widget);
rollLeftShortcut->enable(false);
connect(
rollLeftShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::rollLeft);
addShortcut(rollLeftShortcut);
CSMPrefs::Shortcut* rollRightShortcut = new CSMPrefs::Shortcut("free-roll-right", widget);
rollRightShortcut->enable(false);
connect(
rollRightShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::rollRight);
addShortcut(rollRightShortcut);
CSMPrefs::Shortcut* speedModeShortcut = new CSMPrefs::Shortcut("free-speed-mode", widget);
speedModeShortcut->enable(false);
connect(
speedModeShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &FreeCameraController::swapSpeedMode);
addShortcut(speedModeShortcut);
}
double FreeCameraController::getLinearSpeed() const
{
return mLinSpeed;
}
double FreeCameraController::getRotationalSpeed() const
{
return mRotSpeed;
}
double FreeCameraController::getSpeedMultiplier() const
{
return mSpeedMult;
}
void FreeCameraController::setLinearSpeed(double value)
{
mLinSpeed = value;
}
void FreeCameraController::setRotationalSpeed(double value)
{
mRotSpeed = value;
}
void FreeCameraController::setSpeedMultiplier(double value)
{
mSpeedMult = value;
}
void FreeCameraController::fixUpAxis(const osg::Vec3d& up)
{
mLockUpright = true;
mUp = up;
mModified = true;
}
void FreeCameraController::unfixUpAxis()
{
mLockUpright = false;
}
void FreeCameraController::handleMouseMoveEvent(int x, int y)
{
if (!isActive())
return;
if (mNaviPrimary)
{
double scalar = getCameraSensitivity() * (getInverted() ? -1.0 : 1.0);
yaw(x * scalar);
pitch(y * scalar);
}
else if (mNaviSecondary)
{
osg::Vec3d movement;
movement += LocalLeft * -x * getSecondaryMovementMultiplier();
movement += LocalUp * y * getSecondaryMovementMultiplier();
translate(movement);
}
}
void FreeCameraController::handleMouseScrollEvent(int x)
{
if (!isActive())
return;
translate(LocalForward * x * ((mFast ^ mFastAlternate) ? getWheelMovementMultiplier() : 1));
}
void FreeCameraController::update(double dt)
{
if (!isActive())
return;
double linDist = mLinSpeed * dt;
double rotDist = mRotSpeed * dt;
if (mFast ^ mFastAlternate)
linDist *= mSpeedMult;
if (mLeft)
translate(LocalLeft * linDist);
if (mRight)
translate(LocalLeft * -linDist);
if (mForward)
translate(LocalForward * linDist);
if (mBackward)
translate(LocalForward * -linDist);
if (!mLockUpright)
{
if (mRollLeft)
roll(-rotDist);
if (mRollRight)
roll(rotDist);
}
else if (mModified)
{
stabilize();
mModified = false;
}
// Normalize the matrix to counter drift
getCamera()->getViewMatrix().orthoNormal(getCamera()->getViewMatrix());
}
void FreeCameraController::yaw(double value)
{
getCamera()->getViewMatrix() *= osg::Matrixd::rotate(value, LocalUp);
mModified = true;
}
void FreeCameraController::pitch(double value)
{
const double Constraint = osg::PI / 2 - 0.1;
if (mLockUpright)
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
osg::Vec3d forward = center - eye;
osg::Vec3d left = up ^ forward;
double pitchAngle = std::acos(up * mUp);
if ((mUp ^ up) * left < 0)
pitchAngle *= -1;
if (std::abs(pitchAngle + value) > Constraint)
value = (pitchAngle > 0 ? 1 : -1) * Constraint - pitchAngle;
}
getCamera()->getViewMatrix() *= osg::Matrixd::rotate(value, LocalLeft);
mModified = true;
}
void FreeCameraController::roll(double value)
{
getCamera()->getViewMatrix() *= osg::Matrixd::rotate(value, LocalForward);
mModified = true;
}
void FreeCameraController::translate(const osg::Vec3d& offset)
{
getCamera()->getViewMatrix() *= osg::Matrixd::translate(offset);
mModified = true;
}
void FreeCameraController::stabilize()
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
getCamera()->setViewMatrixAsLookAt(eye, center, mUp);
}
void FreeCameraController::naviPrimary(bool active)
{
mNaviPrimary = active;
}
void FreeCameraController::naviSecondary(bool active)
{
mNaviSecondary = active;
}
void FreeCameraController::forward(bool active)
{
mForward = active;
}
void FreeCameraController::left(bool active)
{
mLeft = active;
}
void FreeCameraController::backward(bool active)
{
mBackward = active;
}
void FreeCameraController::right(bool active)
{
mRight = active;
}
void FreeCameraController::rollLeft(bool active)
{
mRollLeft = active;
}
void FreeCameraController::rollRight(bool active)
{
mRollRight = active;
}
void FreeCameraController::alternateFast(bool active)
{
mFastAlternate = active;
}
void FreeCameraController::swapSpeedMode()
{
mFast = !mFast;
}
/*
Orbit Camera Controller
*/
OrbitCameraController::OrbitCameraController(QWidget* widget)
: CameraController(widget)
, mInitialized(false)
, mNaviPrimary(false)
, mNaviSecondary(false)
, mFast(false)
, mFastAlternate(false)
, mLeft(false)
, mRight(false)
, mUp(false)
, mDown(false)
, mRollLeft(false)
, mRollRight(false)
, mPickingMask(~0u)
, mCenter(0, 0, 0)
, mDistance(0)
, mOrbitSpeed(osg::PI / 4)
, mOrbitSpeedMult(4)
, mConstRoll(false)
{
CSMPrefs::Shortcut* naviPrimaryShortcut = new CSMPrefs::Shortcut("scene-navi-primary", widget);
naviPrimaryShortcut->enable(false);
connect(naviPrimaryShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this,
&OrbitCameraController::naviPrimary);
addShortcut(naviPrimaryShortcut);
CSMPrefs::Shortcut* naviSecondaryShortcut = new CSMPrefs::Shortcut("scene-navi-secondary", widget);
naviSecondaryShortcut->enable(false);
connect(naviSecondaryShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this,
&OrbitCameraController::naviSecondary);
addShortcut(naviSecondaryShortcut);
CSMPrefs::Shortcut* upShortcut
= new CSMPrefs::Shortcut("orbit-up", "scene-speed-modifier", CSMPrefs::Shortcut::SM_Detach, widget);
upShortcut->enable(false);
connect(upShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraController::up);
connect(
upShortcut, qOverload<bool>(&CSMPrefs::Shortcut::secondary), this, &OrbitCameraController::alternateFast);
addShortcut(upShortcut);
CSMPrefs::Shortcut* leftShortcut = new CSMPrefs::Shortcut("orbit-left", widget);
leftShortcut->enable(false);
connect(leftShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraController::left);
addShortcut(leftShortcut);
CSMPrefs::Shortcut* downShortcut = new CSMPrefs::Shortcut("orbit-down", widget);
downShortcut->enable(false);
connect(downShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraController::down);
addShortcut(downShortcut);
CSMPrefs::Shortcut* rightShortcut = new CSMPrefs::Shortcut("orbit-right", widget);
rightShortcut->enable(false);
connect(rightShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraController::right);
addShortcut(rightShortcut);
CSMPrefs::Shortcut* rollLeftShortcut = new CSMPrefs::Shortcut("orbit-roll-left", widget);
rollLeftShortcut->enable(false);
connect(
rollLeftShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraController::rollLeft);
addShortcut(rollLeftShortcut);
CSMPrefs::Shortcut* rollRightShortcut = new CSMPrefs::Shortcut("orbit-roll-right", widget);
rollRightShortcut->enable(false);
connect(rollRightShortcut, qOverload<bool>(&CSMPrefs::Shortcut::activated), this,
&OrbitCameraController::rollRight);
addShortcut(rollRightShortcut);
CSMPrefs::Shortcut* speedModeShortcut = new CSMPrefs::Shortcut("orbit-speed-mode", widget);
speedModeShortcut->enable(false);
connect(speedModeShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this,
&OrbitCameraController::swapSpeedMode);
addShortcut(speedModeShortcut);
}
osg::Vec3d OrbitCameraController::getCenter() const
{
return mCenter;
}
double OrbitCameraController::getOrbitSpeed() const
{
return mOrbitSpeed;
}
double OrbitCameraController::getOrbitSpeedMultiplier() const
{
return mOrbitSpeedMult;
}
unsigned int OrbitCameraController::getPickingMask() const
{
return mPickingMask;
}
void OrbitCameraController::setCenter(const osg::Vec3d& value)
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
mCenter = value;
mDistance = (eye - mCenter).length();
getCamera()->setViewMatrixAsLookAt(eye, mCenter, up);
mInitialized = true;
}
void OrbitCameraController::setOrbitSpeed(double value)
{
mOrbitSpeed = value;
}
void OrbitCameraController::setOrbitSpeedMultiplier(double value)
{
mOrbitSpeedMult = value;
}
void OrbitCameraController::setPickingMask(unsigned int value)
{
mPickingMask = value;
}
void OrbitCameraController::handleMouseMoveEvent(int x, int y)
{
if (!isActive())
return;
if (!mInitialized)
initialize();
if (mNaviPrimary)
{
double scalar = getCameraSensitivity() * (getInverted() ? -1.0 : 1.0);
rotateHorizontal(x * scalar);
rotateVertical(-y * scalar);
}
else if (mNaviSecondary)
{
osg::Vec3d movement;
movement += LocalLeft * x * getSecondaryMovementMultiplier();
movement += LocalUp * -y * getSecondaryMovementMultiplier();
translate(movement);
}
}
void OrbitCameraController::handleMouseScrollEvent(int x)
{
if (!isActive())
return;
zoom(-x * ((mFast ^ mFastAlternate) ? getWheelMovementMultiplier() : 1));
}
void OrbitCameraController::update(double dt)
{
if (!isActive())
return;
if (!mInitialized)
initialize();
double rotDist = mOrbitSpeed * dt;
if (mFast ^ mFastAlternate)
rotDist *= mOrbitSpeedMult;
if (mLeft)
rotateHorizontal(-rotDist);
if (mRight)
rotateHorizontal(rotDist);
if (mUp)
rotateVertical(rotDist);
if (mDown)
rotateVertical(-rotDist);
if (mRollLeft)
roll(-rotDist);
if (mRollRight)
roll(rotDist);
// Normalize the matrix to counter drift
getCamera()->getViewMatrix().orthoNormal(getCamera()->getViewMatrix());
}
void OrbitCameraController::reset()
{
mInitialized = false;
}
void OrbitCameraController::initialize()
{
static const int DefaultStartDistance = 10000.f;
// Try to intelligently pick focus object
osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector(
new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, osg::Vec3d(0, 0, 0), LocalForward));
intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::LIMIT_NEAREST);
osgUtil::IntersectionVisitor visitor(intersector);
visitor.setTraversalMask(mPickingMask);
getCamera()->accept(visitor);
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up, DefaultStartDistance);
if (intersector->getIntersections().begin() != intersector->getIntersections().end())
{
mCenter = intersector->getIntersections().begin()->getWorldIntersectPoint();
mDistance = (eye - mCenter).length();
}
else
{
mCenter = center;
mDistance = DefaultStartDistance;
}
mInitialized = true;
}
void OrbitCameraController::setConstRoll(bool enabled)
{
mConstRoll = enabled;
}
void OrbitCameraController::rotateHorizontal(double value)
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
osg::Vec3d absoluteUp = osg::Vec3(0, 0, 1);
osg::Quat rotation = osg::Quat(value, mConstRoll ? absoluteUp : up);
osg::Vec3d oldOffset = eye - mCenter;
osg::Vec3d newOffset = rotation * oldOffset;
if (mConstRoll)
up = rotation * up;
getCamera()->setViewMatrixAsLookAt(mCenter + newOffset, mCenter, up);
}
void OrbitCameraController::rotateVertical(double value)
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
osg::Vec3d forward = center - eye;
osg::Vec3d axis = up ^ forward;
osg::Quat rotation = osg::Quat(value, axis);
osg::Vec3d oldOffset = eye - mCenter;
osg::Vec3d newOffset = rotation * oldOffset;
if (mConstRoll)
up = rotation * up;
getCamera()->setViewMatrixAsLookAt(mCenter + newOffset, mCenter, up);
}
void OrbitCameraController::roll(double value)
{
getCamera()->getViewMatrix() *= osg::Matrixd::rotate(value, LocalForward);
}
void OrbitCameraController::translate(const osg::Vec3d& offset)
{
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up);
osg::Vec3d newOffset = getCamera()->getViewMatrix().getRotate().inverse() * offset;
mCenter += newOffset;
eye += newOffset;
getCamera()->setViewMatrixAsLookAt(eye, mCenter, up);
}
void OrbitCameraController::zoom(double value)
{
mDistance = std::max(10., mDistance + value);
osg::Vec3d eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up, 1.f);
osg::Vec3d offset = (eye - center) * mDistance;
getCamera()->setViewMatrixAsLookAt(mCenter + offset, mCenter, up);
}
void OrbitCameraController::naviPrimary(bool active)
{
mNaviPrimary = active;
}
void OrbitCameraController::naviSecondary(bool active)
{
mNaviSecondary = active;
}
void OrbitCameraController::up(bool active)
{
mUp = active;
}
void OrbitCameraController::left(bool active)
{
mLeft = active;
}
void OrbitCameraController::down(bool active)
{
mDown = active;
}
void OrbitCameraController::right(bool active)
{
mRight = active;
}
void OrbitCameraController::rollLeft(bool active)
{
if (isActive())
mRollLeft = active;
}
void OrbitCameraController::rollRight(bool active)
{
mRollRight = active;
}
void OrbitCameraController::alternateFast(bool active)
{
mFastAlternate = active;
}
void OrbitCameraController::swapSpeedMode()
{
mFast = !mFast;
}
}
| 22,906
|
C++
|
.cpp
| 632
| 28.075949
| 120
| 0.639703
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,113
|
lightingday.cpp
|
OpenMW_openmw/apps/opencs/view/render/lightingday.cpp
|
#include "lightingday.hpp"
#include <osg/Group>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/ref_ptr>
void CSVRender::LightingDay::activate(osg::Group* rootNode, bool /*isExterior*/)
{
mRootNode = rootNode;
mLightSource = new osg::LightSource;
osg::ref_ptr<osg::Light> light(new osg::Light);
light->setPosition(osg::Vec4f(0.f, 0.f, 1.f, 0.f));
light->setAmbient(osg::Vec4f(0.f, 0.f, 0.f, 1.f));
light->setDiffuse(osg::Vec4f(1.f, 1.f, 1.f, 1.f));
light->setSpecular(osg::Vec4f(0.f, 0.f, 0.f, 0.f));
light->setConstantAttenuation(1.f);
mLightSource->setLight(light);
mRootNode->addChild(mLightSource);
updateDayNightMode(0);
}
void CSVRender::LightingDay::deactivate()
{
if (mRootNode && mLightSource.get())
mRootNode->removeChild(mLightSource);
}
osg::Vec4f CSVRender::LightingDay::getAmbientColour(osg::Vec4f* defaultAmbient)
{
if (defaultAmbient)
return *defaultAmbient;
else
return osg::Vec4f(0.7f, 0.7f, 0.7f, 1.f);
}
| 1,026
|
C++
|
.cpp
| 31
| 29.258065
| 80
| 0.688956
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,114
|
cellwater.cpp
|
OpenMW_openmw/apps/opencs/view/render/cellwater.cpp
|
#include "cellwater.hpp"
#include <memory>
#include <string_view>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/PositionAttitudeTransform>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Texture2D>
#include <osg/Texture>
#include <osg/Vec3d>
#include <osg/Vec3f>
#include <apps/opencs/model/world/collection.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <components/esm3/loadland.hpp>
#include <components/fallback/fallback.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/resource/resourcesystem.hpp>
#include <components/sceneutil/waterutil.hpp>
#include "../../model/world/cell.hpp"
#include "../../model/world/cellcoordinates.hpp"
#include "../../model/world/data.hpp"
#include "mask.hpp"
namespace CSVRender
{
const int CellWater::CellSize = ESM::Land::REAL_SIZE;
CellWater::CellWater(
CSMWorld::Data& data, osg::Group* cellNode, const std::string& id, const CSMWorld::CellCoordinates& cellCoords)
: mData(data)
, mId(id)
, mParentNode(cellNode)
, mWaterTransform(nullptr)
, mWaterGroup(nullptr)
, mWaterGeometry(nullptr)
, mDeleted(false)
, mExterior(false)
, mHasWater(false)
{
mWaterTransform = new osg::PositionAttitudeTransform();
mWaterTransform->setPosition(osg::Vec3f(
cellCoords.getX() * CellSize + CellSize / 2.f, cellCoords.getY() * CellSize + CellSize / 2.f, 0));
mWaterTransform->setNodeMask(Mask_Water);
mParentNode->addChild(mWaterTransform);
mWaterGroup = new osg::Group();
mWaterTransform->addChild(mWaterGroup);
const int cellIndex = mData.getCells().searchId(ESM::RefId::stringRefId(mId));
if (cellIndex > -1)
{
updateCellData(mData.getCells().getRecord(cellIndex));
}
// Keep water existence/height up to date
QAbstractItemModel* cells = mData.getTableModel(CSMWorld::UniversalId::Type_Cells);
connect(cells, &QAbstractItemModel::dataChanged, this, &CellWater::cellDataChanged);
}
CellWater::~CellWater()
{
mParentNode->removeChild(mWaterTransform);
}
void CellWater::updateCellData(const CSMWorld::Record<CSMWorld::Cell>& cellRecord)
{
mDeleted = cellRecord.isDeleted();
if (!mDeleted)
{
const CSMWorld::Cell& cell = cellRecord.get();
if (mExterior != cell.isExterior() || mHasWater != cell.hasWater())
{
mExterior = cellRecord.get().isExterior();
mHasWater = cellRecord.get().hasWater();
recreate();
}
float waterHeight = -1;
if (!mExterior)
{
waterHeight = cellRecord.get().mWater;
}
osg::Vec3d pos = mWaterTransform->getPosition();
pos.z() = waterHeight;
mWaterTransform->setPosition(pos);
}
else
{
recreate();
}
}
void CellWater::reloadAssets()
{
recreate();
}
void CellWater::cellDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
const CSMWorld::Collection<CSMWorld::Cell>& cells = mData.getCells();
int rowStart = -1;
int rowEnd = -1;
if (topLeft.parent().isValid())
{
rowStart = topLeft.parent().row();
rowEnd = bottomRight.parent().row();
}
else
{
rowStart = topLeft.row();
rowEnd = bottomRight.row();
}
for (int row = rowStart; row <= rowEnd; ++row)
{
const CSMWorld::Record<CSMWorld::Cell>& cellRecord = cells.getRecord(row);
if (cellRecord.get().mId == ESM::RefId::stringRefId(mId))
updateCellData(cellRecord);
}
}
void CellWater::recreate()
{
const int InteriorScalar = 20;
const int SegmentsPerCell = 1;
const int TextureRepeatsPerCell = 6;
const float Alpha = 0.5f;
const int RenderBin = osg::StateSet::TRANSPARENT_BIN - 1;
if (mWaterGeometry)
{
mWaterGroup->removeChild(mWaterGeometry);
mWaterGeometry = nullptr;
}
if (mDeleted || !mHasWater)
return;
float size;
int segments;
float textureRepeats;
if (mExterior)
{
size = CellSize;
segments = SegmentsPerCell;
textureRepeats = TextureRepeatsPerCell;
}
else
{
size = CellSize * InteriorScalar;
segments = SegmentsPerCell * InteriorScalar;
textureRepeats = TextureRepeatsPerCell * InteriorScalar;
}
mWaterGeometry = SceneUtil::createWaterGeometry(size, segments, textureRepeats);
mWaterGeometry->setStateSet(SceneUtil::createSimpleWaterStateSet(Alpha, RenderBin));
// Add water texture
constexpr VFS::Path::NormalizedView prefix("textures/water");
VFS::Path::Normalized texturePath(prefix);
texturePath /= std::string(Fallback::Map::getString("Water_SurfaceTexture")) + "00.dds";
Resource::ImageManager* imageManager = mData.getResourceSystem()->getImageManager();
osg::ref_ptr<osg::Texture2D> waterTexture = new osg::Texture2D();
waterTexture->setImage(imageManager->getImage(texturePath));
waterTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
waterTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
mWaterGeometry->getStateSet()->setTextureAttributeAndModes(0, waterTexture, osg::StateAttribute::ON);
mWaterGroup->addChild(mWaterGeometry);
}
}
| 5,946
|
C++
|
.cpp
| 157
| 29.605096
| 119
| 0.635083
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,115
|
cell.cpp
|
OpenMW_openmw/apps/opencs/view/render/cell.cpp
|
#include "cell.hpp"
#include <algorithm>
#include <set>
#include <utility>
#include <osg/Callback>
#include <osg/Group>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Referenced>
#include <components/esm/defs.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/loadland.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/terrain/terraingrid.hpp>
#include "../../model/doc/document.hpp"
#include "../../model/world/idtable.hpp"
#include "cellarrow.hpp"
#include "cellborder.hpp"
#include "cellmarker.hpp"
#include "cellwater.hpp"
#include "instancedragmodes.hpp"
#include "mask.hpp"
#include "object.hpp"
#include "pathgrid.hpp"
#include "terrainstorage.hpp"
#include <apps/opencs/model/world/cell.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/commands.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/land.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/ref.hpp>
#include <apps/opencs/model/world/refcollection.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
namespace CSVRender
{
class CellNodeContainer : public osg::Referenced
{
public:
CellNodeContainer(Cell* cell)
: mCell(cell)
{
}
Cell* getCell() { return mCell; }
private:
Cell* mCell;
};
class CellNodeCallback : public osg::NodeCallback
{
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override
{
traverse(node, nv);
CellNodeContainer* container = static_cast<CellNodeContainer*>(node->getUserData());
container->getCell()->updateLand();
}
};
}
bool CSVRender::Cell::removeObject(const std::string& id)
{
std::map<std::string, Object*>::iterator iter = mObjects.find(Misc::StringUtils::lowerCase(id));
if (iter == mObjects.end())
return false;
removeObject(iter);
return true;
}
std::map<std::string, CSVRender::Object*>::iterator CSVRender::Cell::removeObject(
std::map<std::string, Object*>::iterator iter)
{
delete iter->second;
mObjects.erase(iter++);
return iter;
}
bool CSVRender::Cell::addObjects(int start, int end)
{
bool modified = false;
const CSMWorld::RefCollection& collection = mData.getReferences();
for (int i = start; i <= end; ++i)
{
const auto& cellId = ESM::RefId::stringRefId(collection.getRecord(i).get().mCell.toString());
CSMWorld::RecordBase::State state = collection.getRecord(i).mState;
if (cellId == mId && state != CSMWorld::RecordBase::State_Deleted)
{
const std::string& id = collection.getRecord(i).get().mId.getRefIdString();
auto object = std::make_unique<Object>(mData, mCellNode, id, false);
if (mSubModeElementMask & Mask_Reference)
object->setSubMode(mSubMode);
mObjects.insert(std::make_pair(id, object.release()));
modified = true;
}
}
return modified;
}
void CSVRender::Cell::updateLand()
{
if (!mUpdateLand || mLandDeleted)
return;
mUpdateLand = false;
// Cell is deleted
if (mDeleted)
{
unloadLand();
return;
}
const CSMWorld::IdCollection<CSMWorld::Land>& land = mData.getLand();
if (land.getRecord(mId).isDeleted())
return;
const ESM::Land& esmLand = land.getRecord(mId).get();
if (mTerrain)
{
mTerrain->unloadCell(mCoordinates.getX(), mCoordinates.getY());
mTerrain->clearAssociatedCaches();
}
else
{
constexpr double expiryDelay = 0;
mTerrain = std::make_unique<Terrain::TerrainGrid>(mCellNode, mCellNode, mData.getResourceSystem().get(),
mTerrainStorage, Mask_Terrain, ESM::Cell::sDefaultWorldspaceId, expiryDelay);
}
mTerrain->loadCell(esmLand.mX, esmLand.mY);
if (!mCellBorder)
mCellBorder = std::make_unique<CellBorder>(mCellNode, mCoordinates);
mCellBorder->buildShape(esmLand);
}
void CSVRender::Cell::unloadLand()
{
if (mTerrain)
mTerrain->unloadCell(mCoordinates.getX(), mCoordinates.getY());
if (mCellBorder)
mCellBorder.reset();
}
CSVRender::Cell::Cell(
CSMDoc::Document& document, osg::Group* rootNode, const std::string& id, bool deleted, bool isExterior)
: mData(document.getData())
, mId(ESM::RefId::stringRefId(id))
, mDeleted(deleted)
, mSubMode(0)
, mSubModeElementMask(0)
, mUpdateLand(isExterior)
, mLandDeleted(false)
{
std::pair<CSMWorld::CellCoordinates, bool> result = CSMWorld::CellCoordinates::fromId(id);
mTerrainStorage = new TerrainStorage(mData);
if (result.second)
mCoordinates = result.first;
mCellNode = new osg::Group;
mCellNode->setUserData(new CellNodeContainer(this));
mCellNode->setUpdateCallback(new CellNodeCallback);
rootNode->addChild(mCellNode);
setCellMarker();
if (!mDeleted)
{
CSMWorld::IdTable& references
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_References));
int rows = references.rowCount();
addObjects(0, rows - 1);
if (mUpdateLand)
{
int landIndex = document.getData().getLand().searchId(mId);
if (landIndex == -1)
{
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Land));
document.getUndoStack().push(new CSMWorld::CreateCommand(landTable, mId.getRefIdString()));
}
updateLand();
}
mPathgrid = std::make_unique<Pathgrid>(mData, mCellNode, mId.getRefIdString(), mCoordinates);
mCellWater = std::make_unique<CellWater>(mData, mCellNode, mId.getRefIdString(), mCoordinates);
}
}
CSVRender::Cell::~Cell()
{
for (std::map<std::string, Object*>::iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
delete iter->second;
mCellNode->getParent(0)->removeChild(mCellNode);
}
CSVRender::Pathgrid* CSVRender::Cell::getPathgrid() const
{
return mPathgrid.get();
}
bool CSVRender::Cell::referenceableDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
bool modified = false;
for (std::map<std::string, Object*>::iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
if (iter->second->referenceableDataChanged(topLeft, bottomRight))
modified = true;
return modified;
}
bool CSVRender::Cell::referenceableAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
if (parent.isValid())
return false;
bool modified = false;
for (std::map<std::string, Object*>::iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
if (iter->second->referenceableAboutToBeRemoved(parent, start, end))
modified = true;
return modified;
}
bool CSVRender::Cell::referenceDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
if (mDeleted)
return false;
CSMWorld::IdTable& references
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_References));
int idColumn = references.findColumnIndex(CSMWorld::Columns::ColumnId_Id);
int cellColumn = references.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
int stateColumn = references.findColumnIndex(CSMWorld::Columns::ColumnId_Modification);
// list IDs in cell
std::map<std::string, bool> ids; // id, deleted state
for (int i = topLeft.row(); i <= bottomRight.row(); ++i)
{
auto cell
= ESM::RefId::stringRefId(references.data(references.index(i, cellColumn)).toString().toUtf8().constData());
if (cell == mId)
{
std::string id = Misc::StringUtils::lowerCase(
references.data(references.index(i, idColumn)).toString().toUtf8().constData());
int state = references.data(references.index(i, stateColumn)).toInt();
ids.insert(std::make_pair(id, state == CSMWorld::RecordBase::State_Deleted));
}
}
// perform update and remove where needed
bool modified = false;
std::map<std::string, Object*>::iterator iter = mObjects.begin();
while (iter != mObjects.end())
{
if (iter->second->referenceDataChanged(topLeft, bottomRight))
modified = true;
std::map<std::string, bool>::iterator iter2 = ids.find(iter->first);
if (iter2 != ids.end())
{
bool deleted = iter2->second;
ids.erase(iter2);
if (deleted)
{
iter = removeObject(iter);
modified = true;
continue;
}
}
++iter;
}
// add new objects
for (std::map<std::string, bool>::iterator mapIter(ids.begin()); mapIter != ids.end(); ++mapIter)
{
if (!mapIter->second)
{
mObjects.insert(std::make_pair(mapIter->first, new Object(mData, mCellNode, mapIter->first, false)));
modified = true;
}
}
return modified;
}
bool CSVRender::Cell::referenceAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
if (parent.isValid())
return false;
if (mDeleted)
return false;
CSMWorld::IdTable& references
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_References));
int idColumn = references.findColumnIndex(CSMWorld::Columns::ColumnId_Id);
bool modified = false;
for (int row = start; row <= end; ++row)
if (removeObject(references.data(references.index(row, idColumn)).toString().toUtf8().constData()))
modified = true;
return modified;
}
bool CSVRender::Cell::referenceAdded(const QModelIndex& parent, int start, int end)
{
if (parent.isValid())
return false;
if (mDeleted)
return false;
return addObjects(start, end);
}
void CSVRender::Cell::setAlteredHeight(int inCellX, int inCellY, float height)
{
mTerrainStorage->setAlteredHeight(inCellX, inCellY, height);
mUpdateLand = true;
}
float CSVRender::Cell::getSumOfAlteredAndTrueHeight(int cellX, int cellY, int inCellX, int inCellY)
{
return mTerrainStorage->getSumOfAlteredAndTrueHeight(cellX, cellY, inCellX, inCellY);
}
float* CSVRender::Cell::getAlteredHeight(int inCellX, int inCellY)
{
return mTerrainStorage->getAlteredHeight(inCellX, inCellY);
}
void CSVRender::Cell::resetAlteredHeights()
{
mTerrainStorage->resetHeights();
mUpdateLand = true;
}
void CSVRender::Cell::pathgridModified()
{
if (mPathgrid)
mPathgrid->recreateGeometry();
}
void CSVRender::Cell::pathgridRemoved()
{
if (mPathgrid)
mPathgrid->removeGeometry();
}
void CSVRender::Cell::landDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
mUpdateLand = true;
}
void CSVRender::Cell::landAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
mLandDeleted = true;
unloadLand();
}
void CSVRender::Cell::landAdded(const QModelIndex& parent, int start, int end)
{
mUpdateLand = true;
mLandDeleted = false;
}
void CSVRender::Cell::landTextureChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
mUpdateLand = true;
}
void CSVRender::Cell::landTextureAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
mUpdateLand = true;
}
void CSVRender::Cell::landTextureAdded(const QModelIndex& parent, int start, int end)
{
mUpdateLand = true;
}
void CSVRender::Cell::reloadAssets()
{
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
{
iter->second->reloadAssets();
}
if (mTerrain)
{
mTerrain->unloadCell(mCoordinates.getX(), mCoordinates.getY());
mTerrain->loadCell(mCoordinates.getX(), mCoordinates.getY());
}
if (mCellWater)
mCellWater->reloadAssets();
}
void CSVRender::Cell::setSelection(int elementMask, Selection mode)
{
if (elementMask & Mask_Reference)
{
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
{
bool selected = false;
switch (mode)
{
case Selection_Clear:
selected = false;
break;
case Selection_All:
selected = true;
break;
case Selection_Invert:
selected = !iter->second->getSelected();
break;
}
iter->second->setSelected(selected);
}
}
if (mPathgrid && elementMask & Mask_Pathgrid)
{
// Only one pathgrid may be selected, so some operations will only have an effect
// if the pathgrid is already focused
switch (mode)
{
case Selection_Clear:
mPathgrid->clearSelected();
break;
case Selection_All:
if (mPathgrid->isSelected())
mPathgrid->selectAll();
break;
case Selection_Invert:
if (mPathgrid->isSelected())
mPathgrid->invertSelected();
break;
}
}
}
void CSVRender::Cell::selectAllWithSameParentId(int elementMask)
{
std::set<std::string> ids;
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
{
if (iter->second->getSelected())
ids.insert(iter->second->getReferenceableId());
}
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
{
if (!iter->second->getSelected() && ids.find(iter->second->getReferenceableId()) != ids.end())
{
iter->second->setSelected(true);
}
}
}
void CSVRender::Cell::handleSelectDrag(Object* object, DragMode dragMode)
{
if (dragMode == DragMode_Select_Only || dragMode == DragMode_Select_Add)
object->setSelected(true);
else if (dragMode == DragMode_Select_Remove)
object->setSelected(false);
else if (dragMode == DragMode_Select_Invert)
object->setSelected(!object->getSelected());
}
void CSVRender::Cell::selectInsideCube(const osg::Vec3d& pointA, const osg::Vec3d& pointB, DragMode dragMode)
{
for (auto& object : mObjects)
{
if (dragMode == DragMode_Select_Only)
object.second->setSelected(false);
if ((object.second->getPosition().pos[0] > pointA[0] && object.second->getPosition().pos[0] < pointB[0])
|| (object.second->getPosition().pos[0] > pointB[0] && object.second->getPosition().pos[0] < pointA[0]))
{
if ((object.second->getPosition().pos[1] > pointA[1] && object.second->getPosition().pos[1] < pointB[1])
|| (object.second->getPosition().pos[1] > pointB[1] && object.second->getPosition().pos[1] < pointA[1]))
{
if ((object.second->getPosition().pos[2] > pointA[2] && object.second->getPosition().pos[2] < pointB[2])
|| (object.second->getPosition().pos[2] > pointB[2]
&& object.second->getPosition().pos[2] < pointA[2]))
handleSelectDrag(object.second, dragMode);
}
}
}
}
void CSVRender::Cell::selectWithinDistance(const osg::Vec3d& point, float distance, DragMode dragMode)
{
for (auto& object : mObjects)
{
if (dragMode == DragMode_Select_Only)
object.second->setSelected(false);
float distanceFromObject = (point - object.second->getPosition().asVec3()).length();
if (distanceFromObject < distance)
handleSelectDrag(object.second, dragMode);
}
}
void CSVRender::Cell::setCellArrows(int mask)
{
for (int i = 0; i < 4; ++i)
{
CellArrow::Direction direction = static_cast<CellArrow::Direction>(1 << i);
bool enable = mask & direction;
if (enable != (mCellArrows[i].get() != nullptr))
{
if (enable)
mCellArrows[i] = std::make_unique<CellArrow>(mCellNode, direction, mCoordinates);
else
mCellArrows[i].reset(nullptr);
}
}
}
void CSVRender::Cell::setCellMarker()
{
bool cellExists = false;
bool isInteriorCell = false;
int cellIndex = mData.getCells().searchId(mId);
if (cellIndex > -1)
{
const CSMWorld::Record<CSMWorld::Cell>& cellRecord = mData.getCells().getRecord(cellIndex);
cellExists = !cellRecord.isDeleted();
isInteriorCell = cellRecord.get().mData.mFlags & ESM::Cell::Interior;
}
if (!isInteriorCell)
{
mCellMarker = std::make_unique<CellMarker>(mCellNode, mCoordinates, cellExists);
}
}
CSMWorld::CellCoordinates CSVRender::Cell::getCoordinates() const
{
return mCoordinates;
}
bool CSVRender::Cell::isDeleted() const
{
return mDeleted;
}
osg::ref_ptr<CSVRender::TagBase> CSVRender::Cell::getSnapTarget(unsigned int elementMask) const
{
osg::ref_ptr<TagBase> result;
if (elementMask & Mask_Reference)
for (auto& obj : mObjects)
if (obj.second->getSnapTarget())
return obj.second->getTag();
return result;
}
void CSVRender::Cell::selectFromGroup(const std::vector<std::string>& group)
{
for (const auto& [_, object] : mObjects)
{
for (const auto& objectName : group)
{
if (objectName == object->getReferenceId())
{
object->setSelected(true, osg::Vec4f(1, 0, 1, 1));
}
}
}
}
void CSVRender::Cell::unhideAll()
{
for (const auto& [_, object] : mObjects)
{
osg::ref_ptr<osg::Group> rootNode = object->getRootNode();
if (rootNode->getNodeMask() == Mask_Hidden)
rootNode->setNodeMask(Mask_Reference);
}
}
std::vector<osg::ref_ptr<CSVRender::TagBase>> CSVRender::Cell::getSelection(unsigned int elementMask) const
{
std::vector<osg::ref_ptr<TagBase>> result;
if (elementMask & Mask_Reference)
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
if (iter->second->getSelected())
result.push_back(iter->second->getTag());
if (mPathgrid && elementMask & Mask_Pathgrid)
if (mPathgrid->isSelected())
result.emplace_back(mPathgrid->getTag());
return result;
}
std::vector<osg::ref_ptr<CSVRender::TagBase>> CSVRender::Cell::getEdited(unsigned int elementMask) const
{
std::vector<osg::ref_ptr<TagBase>> result;
if (elementMask & Mask_Reference)
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
if (iter->second->isEdited())
result.push_back(iter->second->getTag());
return result;
}
void CSVRender::Cell::setSubMode(int subMode, unsigned int elementMask)
{
mSubMode = subMode;
mSubModeElementMask = elementMask;
if (elementMask & Mask_Reference)
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
iter->second->setSubMode(subMode);
}
void CSVRender::Cell::reset(unsigned int elementMask)
{
if (elementMask & Mask_Reference)
for (std::map<std::string, Object*>::const_iterator iter(mObjects.begin()); iter != mObjects.end(); ++iter)
iter->second->reset();
if (mPathgrid && elementMask & Mask_Pathgrid)
mPathgrid->resetIndicators();
}
| 20,056
|
C++
|
.cpp
| 553
| 29.701627
| 120
| 0.64913
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,116
|
cellarrow.cpp
|
OpenMW_openmw/apps/opencs/view/render/cellarrow.cpp
|
#include "cellarrow.hpp"
#include <osg/Array>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Math>
#include <osg/PositionAttitudeTransform>
#include <osg/PrimitiveSet>
#include <osg/Quat>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include "../../model/prefs/state.hpp"
#include <apps/opencs/model/prefs/shortcutmanager.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
#include <components/misc/constants.hpp>
#include "mask.hpp"
namespace CSVRender
{
struct WorldspaceHitResult;
}
CSVRender::CellArrowTag::CellArrowTag(CellArrow* arrow)
: TagBase(Mask_CellArrow)
, mArrow(arrow)
{
}
CSVRender::CellArrow* CSVRender::CellArrowTag::getCellArrow() const
{
return mArrow;
}
QString CSVRender::CellArrowTag::getToolTip(bool hideBasics, const WorldspaceHitResult& /*hit*/) const
{
QString text("Direction: ");
switch (mArrow->getDirection())
{
case CellArrow::Direction_North:
text += "North";
break;
case CellArrow::Direction_West:
text += "West";
break;
case CellArrow::Direction_South:
text += "South";
break;
case CellArrow::Direction_East:
text += "East";
break;
}
if (!hideBasics)
{
text +=
"<p>"
"Modify which cells are shown"
"<ul><li>{scene-edit-primary}: Add cell in given direction</li>"
"<li>{scene-edit-secondary}: Add cell and remove old cell</li>"
"<li>{scene-select-primary}: Add cells in given direction</li>"
"<li>{scene-select-secondary}: Add cells and remove old cells</li>"
"<li>{scene-load-cam-cell}: Load cell where camera is located</li>"
"<li>{scene-load-cam-eastcell}: Load cell to east</li>"
"<li>{scene-load-cam-northcell}: Load cell to north</li>"
"<li>{scene-load-cam-westcell}: Load cell to west</li>"
"<li>{scene-load-cam-southcell}: Load cell to south</li>"
"</ul>";
}
return CSMPrefs::State::get().getShortcutManager().processToolTip(text);
}
void CSVRender::CellArrow::adjustTransform()
{
// position
const int cellSize = Constants::CellSizeInUnits;
const int offset = cellSize / 2 + 600;
int x = mCoordinates.getX() * cellSize + cellSize / 2;
int y = mCoordinates.getY() * cellSize + cellSize / 2;
float xr = 0;
float yr = 0;
float zr = 0;
float angle = osg::DegreesToRadians(90.0f);
switch (mDirection)
{
case Direction_North:
y += offset;
xr = -angle;
zr = angle;
break;
case Direction_West:
x -= offset;
yr = -angle;
break;
case Direction_South:
y -= offset;
xr = angle;
zr = angle;
break;
case Direction_East:
x += offset;
yr = angle;
break;
};
mBaseNode->setPosition(osg::Vec3f(x, y, 0));
// orientation
osg::Quat xr2(xr, osg::Vec3f(1, 0, 0));
osg::Quat yr2(yr, osg::Vec3f(0, 1, 0));
osg::Quat zr2(zr, osg::Vec3f(0, 0, 1));
mBaseNode->setAttitude(zr2 * yr2 * xr2);
}
void CSVRender::CellArrow::buildShape()
{
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
const int arrowWidth = 2700;
const int arrowLength = 1350;
const int arrowHeight = 300;
osg::Vec3Array* vertices = new osg::Vec3Array;
for (int i2 = 0; i2 < 2; ++i2)
for (int i = 0; i < 2; ++i)
{
float height = i ? -arrowHeight / 2 : arrowHeight / 2;
vertices->push_back(osg::Vec3f(height, -arrowWidth / 2, 0));
vertices->push_back(osg::Vec3f(height, arrowWidth / 2, 0));
vertices->push_back(osg::Vec3f(height, 0, arrowLength));
}
geometry->setVertexArray(vertices);
osg::DrawElementsUShort* primitives = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, 0);
// top
primitives->push_back(0);
primitives->push_back(1);
primitives->push_back(2);
// bottom
primitives->push_back(5);
primitives->push_back(4);
primitives->push_back(3);
// back
primitives->push_back(3 + 6);
primitives->push_back(4 + 6);
primitives->push_back(1 + 6);
primitives->push_back(3 + 6);
primitives->push_back(1 + 6);
primitives->push_back(0 + 6);
// sides
primitives->push_back(0 + 6);
primitives->push_back(2 + 6);
primitives->push_back(5 + 6);
primitives->push_back(0 + 6);
primitives->push_back(5 + 6);
primitives->push_back(3 + 6);
primitives->push_back(4 + 6);
primitives->push_back(5 + 6);
primitives->push_back(2 + 6);
primitives->push_back(4 + 6);
primitives->push_back(2 + 6);
primitives->push_back(1 + 6);
geometry->addPrimitiveSet(primitives);
osg::Vec4Array* colours = new osg::Vec4Array;
for (int i = 0; i < 6; ++i)
colours->push_back(osg::Vec4f(0.11f, 0.6f, 0.95f, 1.0f));
for (int i = 0; i < 6; ++i)
colours->push_back(osg::Vec4f(0.08f, 0.44f, 0.7f, 1.0f));
geometry->setColorArray(colours, osg::Array::BIND_PER_VERTEX);
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
mBaseNode->addChild(geometry);
}
CSVRender::CellArrow::CellArrow(osg::Group* cellNode, Direction direction, const CSMWorld::CellCoordinates& coordinates)
: mDirection(direction)
, mParentNode(cellNode)
, mCoordinates(coordinates)
{
mBaseNode = new osg::PositionAttitudeTransform;
mBaseNode->setUserData(new CellArrowTag(this));
mParentNode->addChild(mBaseNode);
mBaseNode->setNodeMask(Mask_CellArrow);
adjustTransform();
buildShape();
}
CSVRender::CellArrow::~CellArrow()
{
mParentNode->removeChild(mBaseNode);
}
CSMWorld::CellCoordinates CSVRender::CellArrow::getCoordinates() const
{
return mCoordinates;
}
CSVRender::CellArrow::Direction CSVRender::CellArrow::getDirection() const
{
return mDirection;
}
| 6,202
|
C++
|
.cpp
| 186
| 27.215054
| 120
| 0.630821
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,117
|
commands.cpp
|
OpenMW_openmw/apps/opencs/view/render/commands.cpp
|
#include "commands.hpp"
#include <memory>
#include <apps/opencs/view/render/editmode.hpp>
#include <apps/opencs/view/render/terrainselection.hpp>
#include <components/debug/debuglog.hpp>
#include "terrainshapemode.hpp"
#include "worldspacewidget.hpp"
CSVRender::DrawTerrainSelectionCommand::DrawTerrainSelectionCommand(
WorldspaceWidget* worldspaceWidget, QUndoCommand* parent)
: mWorldspaceWidget(worldspaceWidget)
{
}
void CSVRender::DrawTerrainSelectionCommand::redo()
{
tryUpdate();
}
void CSVRender::DrawTerrainSelectionCommand::undo()
{
tryUpdate();
}
void CSVRender::DrawTerrainSelectionCommand::tryUpdate()
{
if (!mWorldspaceWidget)
{
Log(Debug::Verbose) << "Can't update terrain selection, no WorldspaceWidget found!";
return;
}
auto terrainMode = dynamic_cast<CSVRender::TerrainShapeMode*>(mWorldspaceWidget->getEditMode());
if (!terrainMode)
{
Log(Debug::Verbose) << "Can't update terrain selection in current EditMode";
return;
}
terrainMode->getTerrainSelection()->update();
}
| 1,080
|
C++
|
.cpp
| 35
| 27.285714
| 100
| 0.755556
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,118
|
instancemovemode.cpp
|
OpenMW_openmw/apps/opencs/view/render/instancemovemode.cpp
|
#include "instancemovemode.hpp"
#include <QIcon>
#include <QPixmap>
#include <apps/opencs/view/widget/modebutton.hpp>
#include <components/misc/scalableicon.hpp>
class QWidget;
CSVRender::InstanceMoveMode::InstanceMoveMode(QWidget* parent)
: ModeButton(Misc::ScalableIcon::load(":scenetoolbar/transform-move"),
"Move selected instances"
"<ul><li>Use {scene-edit-primary} to move instances around freely</li>"
"<li>Use {scene-edit-secondary} to move instances around within the grid</li>"
"</ul>",
parent)
{
}
| 558
|
C++
|
.cpp
| 15
| 32.933333
| 86
| 0.723048
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,119
|
lighting.cpp
|
OpenMW_openmw/apps/opencs/view/render/lighting.cpp
|
#include "lighting.hpp"
#include <string>
#include <osg/Group>
#include <osg/LightSource>
#include <osg/NodeVisitor>
#include <osg/Object>
#include <osg/Switch>
#include <osg/ValueObject>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <components/misc/constants.hpp>
#include "../../model/prefs/state.hpp"
class DayNightSwitchVisitor : public osg::NodeVisitor
{
public:
DayNightSwitchVisitor(int index)
: osg::NodeVisitor(TRAVERSE_ALL_CHILDREN)
, mIndex(index)
{
}
void apply(osg::Switch& switchNode) override
{
constexpr int NoIndex = -1;
int initialIndex = NoIndex;
if (!switchNode.getUserValue("initialIndex", initialIndex))
{
for (size_t i = 0; i < switchNode.getValueList().size(); ++i)
{
if (switchNode.getValueList()[i])
{
initialIndex = i;
break;
}
}
if (initialIndex != NoIndex)
switchNode.setUserValue("initialIndex", initialIndex);
}
if (CSMPrefs::get()["Rendering"]["scene-day-night-switch-nodes"].isTrue())
{
if (switchNode.getName() == Constants::NightDayLabel)
switchNode.setSingleChildOn(mIndex);
}
else if (initialIndex != NoIndex)
{
switchNode.setSingleChildOn(initialIndex);
}
traverse(switchNode);
}
private:
int mIndex;
};
void CSVRender::Lighting::updateDayNightMode(int index)
{
if (mRootNode == nullptr)
return;
DayNightSwitchVisitor visitor(index);
mRootNode->accept(visitor);
}
| 1,727
|
C++
|
.cpp
| 58
| 22.465517
| 82
| 0.616918
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,120
|
previewwidget.cpp
|
OpenMW_openmw/apps/opencs/view/render/previewwidget.cpp
|
#include "previewwidget.hpp"
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/render/object.hpp>
#include <apps/opencs/view/render/scenewidget.hpp>
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
class QWidget;
CSVRender::PreviewWidget::PreviewWidget(
CSMWorld::Data& data, const std::string& id, bool referenceable, QWidget* parent)
: SceneWidget(data.getResourceSystem(), parent)
, mData(data)
, mObject(data, mRootNode, id, referenceable)
{
selectNavigationMode("orbit");
QAbstractItemModel* referenceables = mData.getTableModel(CSMWorld::UniversalId::Type_Referenceables);
connect(referenceables, &QAbstractItemModel::dataChanged, this, &PreviewWidget::referenceableDataChanged);
connect(
referenceables, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PreviewWidget::referenceableAboutToBeRemoved);
connect(&mData, &CSMWorld::Data::assetTablesChanged, this, &PreviewWidget::assetTablesChanged);
setExterior(false);
if (!referenceable)
{
QAbstractItemModel* references = mData.getTableModel(CSMWorld::UniversalId::Type_References);
connect(references, &QAbstractItemModel::dataChanged, this, &PreviewWidget::referenceDataChanged);
connect(references, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PreviewWidget::referenceAboutToBeRemoved);
}
}
void CSVRender::PreviewWidget::referenceableDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
if (mObject.referenceableDataChanged(topLeft, bottomRight))
flagAsModified();
if (mObject.getReferenceId().empty())
{
CSMWorld::IdTable& referenceables
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Referenceables));
QModelIndex index = referenceables.getModelIndex(
mObject.getReferenceableId(), referenceables.findColumnIndex(CSMWorld::Columns::ColumnId_Modification));
if (referenceables.data(index).toInt() == CSMWorld::RecordBase::State_Deleted)
emit closeRequest();
}
}
void CSVRender::PreviewWidget::referenceableAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
if (mObject.referenceableAboutToBeRemoved(parent, start, end))
flagAsModified();
if (mObject.getReferenceableId().empty())
return;
CSMWorld::IdTable& referenceables
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_Referenceables));
QModelIndex index = referenceables.getModelIndex(mObject.getReferenceableId(), 0);
if (index.row() >= start && index.row() <= end)
{
if (mObject.getReferenceId().empty())
{
// this is a preview for a referenceble
emit closeRequest();
}
}
}
void CSVRender::PreviewWidget::referenceDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
if (mObject.referenceDataChanged(topLeft, bottomRight))
flagAsModified();
if (mObject.getReferenceId().empty())
return;
CSMWorld::IdTable& references
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_References));
// check for deleted state
{
QModelIndex index = references.getModelIndex(
mObject.getReferenceId(), references.findColumnIndex(CSMWorld::Columns::ColumnId_Modification));
if (references.data(index).toInt() == CSMWorld::RecordBase::State_Deleted)
{
emit closeRequest();
return;
}
}
int columnIndex = references.findColumnIndex(CSMWorld::Columns::ColumnId_ReferenceableId);
QModelIndex index = references.getModelIndex(mObject.getReferenceId(), columnIndex);
if (index.row() >= topLeft.row() && index.row() <= bottomRight.row())
if (index.column() >= topLeft.column() && index.column() <= bottomRight.row())
emit referenceableIdChanged(mObject.getReferenceableId());
}
void CSVRender::PreviewWidget::referenceAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
if (mObject.getReferenceId().empty())
return;
CSMWorld::IdTable& references
= dynamic_cast<CSMWorld::IdTable&>(*mData.getTableModel(CSMWorld::UniversalId::Type_References));
QModelIndex index = references.getModelIndex(mObject.getReferenceId(), 0);
if (index.row() >= start && index.row() <= end)
emit closeRequest();
}
void CSVRender::PreviewWidget::assetTablesChanged()
{
mObject.reloadAssets();
}
| 4,683
|
C++
|
.cpp
| 99
| 41.333333
| 120
| 0.726714
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.