File size: 16,676 Bytes
a5ffdcd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | /****************************************************************************
**
** This file is part of the LibreCAD project, a 2D CAD program
**
** Copyright (C) 2011 Rallaz (rallazz@gmail.com)
** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
**
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file gpl-2.0.txt included in the
** packaging of this file.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** This copyright notice MUST APPEAR in all copies of the script!
**
**********************************************************************/
#include <QApplication>
#include <QDir>
#include <QFileInfo>
#include <QImageWriter>
#include <QKeyEvent>
#include <QListView>
#include <QPushButton>
#include <QStandardItemModel>
#include <QStandardPaths>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>
#include <QAbstractItemView>
#include "qg_librarywidget.h"
#include "lc_containertraverser.h"
#include "lc_documentsstorage.h"
#include "lc_graphicviewport.h"
#include "lc_printviewportrenderer.h"
#include "qg_actionhandler.h"
#include "rs_actioninterface.h"
#include "rs_actionlibraryinsert.h"
#include "rs_debug.h"
#include "rs_graphic.h"
#include "rs_painter.h"
#include "rs_settings.h"
#include "rs_system.h"
namespace {
// fixme - sand - rework, use reusable class
void writePng(const QString& pngPath, QPixmap pixmap)
{
QImageWriter iio;
QImage img = pixmap.toImage();
img = img.scaled(64,64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );
// iio.setImage(img);
iio.setFileName(pngPath);
iio.setFormat("PNG");
if (!iio.write(img)) {
RS_DEBUG->print(RS_Debug::D_ERROR,
"QG_LibraryWidget::getPathToPixmap: Cannot write thumbnail: '%s'",
pngPath.toLatin1().data());
}
}
}
/*
* Constructs a QG_LibraryWidget as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
* @author Rallaz
*/
QG_LibraryWidget::QG_LibraryWidget(QG_ActionHandler *action_handler, QWidget* parent, const char* name, Qt::WindowFlags fl)
: LC_GraphicViewAwareWidget(parent, name, fl), actionHandler{action_handler}{
auto vboxLayout = new QVBoxLayout(this);
vboxLayout->setSpacing(2);
vboxLayout->setContentsMargins(2, 2, 2, 2);
dirView = new QTreeView(this);
dirView->setRootIsDecorated(true);
dirView->setEditTriggers(QAbstractItemView::NoEditTriggers);
vboxLayout->addWidget(dirView);
ivPreview = new QListView(this);
ivPreview->setViewMode(QListView::IconMode);
vboxLayout->addWidget(ivPreview);
bInsert = new QPushButton(tr("Insert"), this);
vboxLayout->addWidget(bInsert);
QHBoxLayout *refreshButtonsLayout = new QHBoxLayout();
bRefresh = new QPushButton(tr("Refresh"), this);
refreshButtonsLayout->addWidget(bRefresh);
bRebuild = new QPushButton(tr("Rebuild"), this);
refreshButtonsLayout->addWidget(bRebuild);
vboxLayout->addLayout(refreshButtonsLayout);
buildTree();
connect(dirView, &QTreeView::expanded, this, &QG_LibraryWidget::expandView);
connect(dirView, &QTreeView::collapsed, this, &QG_LibraryWidget::collapseView);
connect(dirView, &QTreeView::clicked, this, &QG_LibraryWidget::updatePreview);
connect(bInsert, &QPushButton::clicked, this, &QG_LibraryWidget::insert);
connect(bRefresh, &QPushButton::clicked, this, &QG_LibraryWidget::refresh);
connect(bRebuild, &QPushButton::clicked, this, &QG_LibraryWidget::buildTree);
updateWidgetSettings();
}
QG_LibraryWidget::~QG_LibraryWidget() = default;
void QG_LibraryWidget::setGraphicView([[maybe_unused]]RS_GraphicView* gview) {
// todo - add further processing later
}
void QG_LibraryWidget::setActionHandler(QG_ActionHandler* ah) {
actionHandler = ah;
}
/**
* Escape releases focus.
*/
void QG_LibraryWidget::keyPressEvent(QKeyEvent* e) {
switch (e->key()) {
case Qt::Key_Escape:
emit escape();
break;
default:
QWidget::keyPressEvent(e);
break;
}
}
/**
* Insert.
*/
void QG_LibraryWidget::insert() {
QItemSelectionModel* selIconView = ivPreview->selectionModel();
QModelIndex idx = selIconView->currentIndex();
QStandardItem * item = iconModel->itemFromIndex ( idx );
if (item == nullptr) {
return;
}
QString dxfPath = getItemPath(item);
if (QFileInfo(dxfPath).isReadable()) {
if (actionHandler) {
std::shared_ptr<RS_ActionInterface> a =
actionHandler->setCurrentAction(RS2::ActionLibraryInsert);
if (a) {
auto* action = static_cast<RS_ActionLibraryInsert*>(a.get());
action->setFile(std::move(dxfPath));
} else {
RS_DEBUG->print(RS_Debug::D_ERROR,
"QG_LibraryWidget::insert:"
"Cannot create action RS_ActionLibraryInsert");
}
}
} else {
RS_DEBUG->print(RS_Debug::D_ERROR,
"QG_LibraryWidget::insert: Can't read file: '%s'", dxfPath.toLatin1().data());
}
}
/**
* Refresh
*/
void QG_LibraryWidget::refresh() {
scanTree();
updatePreview(dirView->selectionModel()->currentIndex());
}
/**
* Scan library tree for new items
*/
void QG_LibraryWidget::scanTree() {
QStringList directoryList = RS_SYSTEM->getDirectoryList("library");
foreach(auto& directory, directoryList) {
appendTree(nullptr, directory);
}
QString customPath= LC_GET_ONE_STR("Paths", "Library", "");
if(customPath.size()>0){
//todo: make the custom path more flexible
appendTree(nullptr,customPath);
}
}
/**
* (Re)build dirModel and iconModel from scratch
*/
void QG_LibraryWidget::buildTree() {
dirModel = std::make_unique<QStandardItemModel>();
iconModel = std::make_unique<QStandardItemModel>();
scanTree();
dirView->setModel(dirModel.get());
ivPreview->setModel(iconModel.get());
dirModel->setHorizontalHeaderLabels ( QStringList(tr("Directories")));
}
/**
* Appends the given directory to the given list view item. Called recursively until all
* library directories are appended.
*
* @author Rallaz
*/
void QG_LibraryWidget::appendTree(QStandardItem* item, QString directory) {
// QStringList::Iterator it;
QDir dir(directory);
if (!dir.exists()) {
return;
}
// read subdirectories of this directory:
QStringList lDirectoryList = dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot, QDir::Name);
if (!item) item = dirModel->invisibleRootItem();
foreach (const auto& lDirectory, lDirectoryList) {
QStandardItem* newItem=nullptr;
// Look for an item already existing and take this
// instead of making a new one:
for (int j = 0; j < item->rowCount(); ++j) {
QStandardItem* const searchItem = item->child (j);
if (searchItem->text() == lDirectory) {
newItem=searchItem;
break;
}
}
// Create new item if no existing was found:
if (!newItem) {
newItem = new QStandardItem(QIcon(":/icons/folderclosed.lci"), lDirectory);
item->setChild(item->rowCount(), newItem);
}
appendTree(newItem, directory+QDir::separator()+lDirectory);
}
item->sortChildren ( 0, Qt::AscendingOrder );
}
/**
* Change the icon item when is expanded.
*
* @author Rallaz
*/
void QG_LibraryWidget::expandView( QModelIndex idx ){
QStandardItem * item = dirModel->itemFromIndex ( idx );
if (item != nullptr) {
item->setIcon(QIcon(":/icons/fileopen.lci"));
}
}
/**
* Change the icon item when is collapsed.
*
* @author Rallaz
*/
void QG_LibraryWidget::collapseView( QModelIndex idx ){
QStandardItem * item = dirModel->itemFromIndex ( idx );
if (item != nullptr) {
item->setIcon(QIcon(":/icons/folderclosed.lci"));
}
}
/**
* Updates the icon preview.
*
* @author Rallaz
*/
void QG_LibraryWidget::updatePreview(QModelIndex idx) {
QStandardItem * item = dirModel->itemFromIndex ( idx );
if (item == nullptr) {
return;
}
QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
// dir from the point of view of the library browser (e.g. /mechanical/screws)
QString directory = getItemDir(item); //RLZ change to do-while
iconModel->clear();
// List of all directories that contain part libraries:
QStringList directoryList = RS_SYSTEM->getDirectoryList("library");
QDir itemDir;
QStringList itemPathList;
// look in all possible system directories for DXF files in the current library path:
for (int i = 0; i < directoryList.size(); ++i) {
itemDir.setPath(directoryList.at(i)+directory);
if (itemDir.exists()) {
QStringList itemNameList =
itemDir.entryList(QStringList("*.dxf"), QDir::Files, QDir::Name);
for (int j = 0; j < itemNameList.size(); ++j) {
itemPathList += itemDir.path()+QDir::separator()+itemNameList.at(j);
}
}
}
// Sort entries:
itemPathList.sort();
// Fill items into icon view:
for (int i = 0; i < itemPathList.size(); ++i) {
QString label = QFileInfo(itemPathList.at(i)).completeBaseName();
QIcon icon = getIcon(directory, QFileInfo(itemPathList.at(i)).fileName(), itemPathList.at(i));
auto newItem = new QStandardItem(icon, label);
iconModel->setItem(i, newItem);
}
QApplication::restoreOverrideCursor();
}
//RLZ change to do-while
/**
* @return Directory (in terms of the List view) to the given item (e.g. /mechanical/screws)
*/
QString QG_LibraryWidget::getItemDir(QStandardItem* item) {
if (item == nullptr)
return {};
QStandardItem* parent = item->parent();
return getItemDir(parent) + QDir::separator() + QString("%1").arg(item->text());
}
/**
* @return Path of the DXF file that is represented by the given item.
*/
QString QG_LibraryWidget::getItemPath(QStandardItem* item) {
if (item == nullptr)
return {};
QItemSelectionModel* selDirView = dirView->selectionModel();
QModelIndex idx = selDirView->currentIndex();
QStandardItem * dirItem = dirModel->itemFromIndex ( idx );
QString dir = getItemDir(dirItem);
// List of all directories that contain part libraries:
QStringList directoryList = RS_SYSTEM->getDirectoryList("library");
// look in all possible system directories for DXF files in the current library path:
for (auto it=directoryList.begin(); it!=directoryList.end(); ++it) {
QDir itemDir((*it)+dir);
if (itemDir.exists()) {
QString dxfFile = (*it) + dir + QDir::separator() + item->text() + ".dxf";
if (QFileInfo(dxfFile).isReadable()) {
return dxfFile;
}
}
}
return {};
}
/**
* @return Pixmap that serves as icon for the given DXF File.
* The existing PNG file is returned or created and returned..
*
* @param dir Library directory (e.g. "/mechanical/screws")
* @param dxfFile File name (e.g. "screw1.dxf")
* @param dxfPath Full path to the existing DXF file on disk
* (e.g. /home/tux/.qcad/library/mechanical/screws/screw1.dxf)
*/
QIcon QG_LibraryWidget::getIcon(const QString& dir, const QString& dxfFile,
const QString& dxfPath) {
QString pngFile = getPathToPixmap(dir, dxfFile, dxfPath);
QFileInfo fiPng(pngFile);
// found existing thumbnail:
if (fiPng.isFile()) {
return QIcon(pngFile);
}
// default thumbnail:
else {
return QIcon(QPixmap(64,64));
}
}
// fixme - sand - files - generation of thumbnails should be extracted!!! Do this on general rework of the library
/**
* @return Path to the thumbnail of the given DXF file. If no thumbnail exists, one is
* created in the user's home. If no thumbnail can be created, an empty string is returned.
*/
QString QG_LibraryWidget::getPathToPixmap(const QString& dir,
const QString& dxfFile,
const QString& dxfPath) {
// the thumbnail must be created in the user's home.
QString iconCacheLocation=QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + "iconCache" + QDir::separator();
RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: "
"dir: '%s' dxfFile: '%s' dxfPath: '%s'",
dir.toLatin1().data(), dxfFile.toLatin1().data(), dxfPath.toLatin1().data());
// List of all directories that contain part libraries:
QStringList directoryList = RS_SYSTEM->getDirectoryList("library");
directoryList.prepend(iconCacheLocation);
QFileInfo fiDxf(dxfPath);
// look in all possible system directories for PNG files
// in the current library path:
foreach (QString path, directoryList) {
QString itemDir = path + dir;
QString pngPath = itemDir + QDir::separator() + fiDxf.baseName() + ".png";
RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: checking: '%s'",
pngPath.toLatin1().data());
QFileInfo fiPng(pngPath);
// the thumbnail exists:
if (fiPng.isFile()) {
RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: dxf date: %s, png date: %s",
fiDxf.lastModified().toString().toLatin1().data(), fiPng.lastModified().toString().toLatin1().data());
if (fiPng.lastModified() > fiDxf.lastModified()) {
RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: thumbnail found: '%s'",
pngPath.toLatin1().data());
return pngPath;
} else {
RS_DEBUG->print("QG_LibraryWidget::getPathToPixmap: thumbnail needs to be updated: '%s'",
pngPath.toLatin1().data());
}
}
}
// create all directories needed:
RS_SYSTEM->createPaths(iconCacheLocation + dir);
QString pngPath = iconCacheLocation + dir + QDir::separator() + fiDxf.baseName() + ".png";
QPixmap buffer(128,128); // fixme - sand - add settings for thumbnail size, generate per setting!
RS_Painter painter(&buffer);
painter.setBackground(RS_Color(255,255,255));
painter.eraseRect(0,0, 128,128);
LC_GraphicViewport viewport;
viewport.setSize(128,128);
RS_Graphic graphic;
LC_DocumentsStorage storage;
if (!storage.loadDocument(&graphic, dxfPath, RS2::FormatUnknown)) {
RS_DEBUG->print(RS_Debug::D_ERROR,
"QG_LibraryWidget::getPathToPixmap: Cannot open file: '%s'",
dxfPath.toLatin1().data());
return {};
}
viewport.setContainer(&graphic);
viewport.initAfterDocumentOpen();
viewport.zoomAuto(false);
LC_PrintViewportRenderer renderer(&viewport, &painter);
renderer.loadSettings();
renderer.setupPainter(&painter);
for(RS_Entity* e: lc::LC_ContainerTraverser{graphic, RS2::ResolveAll}.entities()) {
if (e != nullptr && e->rtti() != RS2::EntityHatch) {
RS_Pen pen = e->getPen();
pen.setColor(Qt::black);
e->setPen(pen);
renderer.justDrawEntity(&painter, e);
}
}
// GraphicView deletes painter
painter.end();
// Write to PNG
writePng(pngPath, std::move(buffer));
LC_LOG << "Writing to " << pngPath << " OK";
return pngPath;
}
void QG_LibraryWidget::updateWidgetSettings(){
LC_GROUP("Widgets"); {
bool flatIcons = LC_GET_BOOL("DockWidgetsFlatIcons", true);
int iconSize = LC_GET_INT("DockWidgetsIconSize", 16);
QSize size(iconSize, iconSize);
QList<QToolButton *> widgets = this->findChildren<QToolButton *>();
foreach(QToolButton *w, widgets) {
w->setAutoRaise(flatIcons);
w->setIconSize(size);
}
}
LC_GROUP_END();
}
|