| 1 |
/*************************************************************************** |
| 2 |
* Copyright (c) 2015 Eivind Kvedalen <[email protected]> * |
| 3 |
* * |
| 4 |
* This file is part of the FreeCAD CAx development system. * |
| 5 |
* * |
| 6 |
* This library is free software; you can redistribute it and/or * |
| 7 |
* modify it under the terms of the GNU Library General Public * |
| 8 |
* License as published by the Free Software Foundation; either * |
| 9 |
* version 2 of the License, or (at your option) any later version. * |
| 10 |
* * |
| 11 |
* This library is distributed in the hope that it will be useful, * |
| 12 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 13 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 14 |
* GNU Library General Public License for more details. * |
| 15 |
* * |
| 16 |
* You should have received a copy of the GNU Library General Public * |
| 17 |
* License along with this library; see the file COPYING.LIB. If not, * |
| 18 |
* write to the Free Software Foundation, Inc., 59 Temple Place, * |
| 19 |
* Suite 330, Boston, MA 02111-1307, USA * |
| 20 |
* * |
| 21 |
***************************************************************************/ |
| 22 |
|
| 23 |
|
| 24 |
#include <boost/algorithm/string/predicate.hpp> |
| 25 |
#include <QAbstractItemView> |
| 26 |
#include <QContextMenuEvent> |
| 27 |
#include <QLineEdit> |
| 28 |
#include <QMenu> |
| 29 |
#include <QTextBlock> |
| 30 |
#include <QGuiApplication> |
| 31 |
#include <QScreen> |
| 32 |
|
| 33 |
|
| 34 |
#include <App/Application.h> |
| 35 |
#include <App/Document.h> |
| 36 |
#include <App/DocumentObject.h> |
| 37 |
#include <App/ExpressionParser.h> |
| 38 |
#include <App/ObjectIdentifier.h> |
| 39 |
#include <Gui/Application.h> |
| 40 |
#include <Gui/MainWindow.h> |
| 41 |
#include <Base/Tools.h> |
| 42 |
#include <CXX/Extensions.hxx> |
| 43 |
|
| 44 |
#include "ExpressionCompleter.h" |
| 45 |
|
| 46 |
|
| 47 |
FC_LOG_LEVEL_INIT("Completer", true, true) |
| 48 |
|
| 49 |
Q_DECLARE_METATYPE(App::ObjectIdentifier) |
| 50 |
|
| 51 |
using namespace App; |
| 52 |
using namespace Gui; |
| 53 |
|
| 54 |
class ExpressionCompleterModel: public QAbstractItemModel |
| 55 |
{ |
| 56 |
public: |
| 57 |
ExpressionCompleterModel(QObject* parent, bool noProperty) |
| 58 |
: QAbstractItemModel(parent) |
| 59 |
, noProperty(noProperty) |
| 60 |
{} |
| 61 |
|
| 62 |
void setNoProperty(bool enabled) |
| 63 |
{ |
| 64 |
noProperty = enabled; |
| 65 |
} |
| 66 |
|
| 67 |
void setDocumentObject(const App::DocumentObject* obj, bool checkInList) |
| 68 |
{ |
| 69 |
beginResetModel(); |
| 70 |
if (obj) { |
| 71 |
currentDoc = obj->getDocument()->getName(); |
| 72 |
currentObj = obj->getNameInDocument(); |
| 73 |
if (!noProperty && checkInList) { |
| 74 |
inList = obj->getInListEx(true); |
| 75 |
} |
| 76 |
} |
| 77 |
else { |
| 78 |
currentDoc.clear(); |
| 79 |
currentObj.clear(); |
| 80 |
inList.clear(); |
| 81 |
} |
| 82 |
endResetModel(); |
| 83 |
} |
| 84 |
|
| 85 |
// clang-format off |
| 86 |
// This ExpressionCompleter model works without any physical items. |
| 87 |
// Everything item related is stored inside QModelIndex.InternalPointer/InternalId(), |
| 88 |
// using the following Info structure. |
| 89 |
// |
| 90 |
// The Info contains two indices, one for document and the other for object. |
| 91 |
// For 32-bit system, the index is 16bit which limits the size to 64K. For |
| 92 |
// 64-bit system, the index is 32bit. |
| 93 |
// |
| 94 |
// The "virtual" items are organized as a tree. The root items are special, |
| 95 |
// which consists of three types in the following order, |
| 96 |
// |
| 97 |
// * Document, even index contains item using document's name, while |
| 98 |
// odd index with quoted document label. |
| 99 |
// * Objects of the current document, even index with object's internal |
| 100 |
// name, and odd index with quoted object label. |
| 101 |
// * Properties of the current object. |
| 102 |
// |
| 103 |
// Document item contains object item as child, and object item contains |
| 104 |
// property item. |
| 105 |
// |
| 106 |
// The QModelIndex of a root item has both the doc field and obj field set |
| 107 |
// to -1, and uses the row as the item index. We can figure out the type of |
| 108 |
// the item solely based on this row index. |
| 109 |
// |
| 110 |
// QModelIndex of a non-root object item has doc field as the document |
| 111 |
// index, and obj field set to -1. |
| 112 |
// |
| 113 |
// QModelIndex of a non-root property item has doc field as the document |
| 114 |
// index, and obj field as the object index. |
| 115 |
// |
| 116 |
// An item is uniquely identified by the pair (row, father_link) in the QModelIndex |
| 117 |
// |
| 118 |
// The completion tree structure created takes into account the current document and object |
| 119 |
// |
| 120 |
// It is done as such, in order to have contextual completion (prop -> object -> files): |
| 121 |
// * root (-1,-1) |
| 122 |
// | |
| 123 |
// |----- documents |
| 124 |
// |----- current documents' objects [externally set] |
| 125 |
// |----- current objects' props [externally set] |
| 126 |
// |
| 127 |
// This complicates the decoding schema for the root, where the childcount will be |
| 128 |
// doc.size() + current_doc.Objects.size() + current_obj.Props.size(). |
| 129 |
// |
| 130 |
// This is reflected in the complexity of the DATA function. |
| 131 |
// |
| 132 |
// Example encoding of a QMODEL Index |
| 133 |
// |
| 134 |
// ROOT (row -1, [-1,-1,-1,0]), info represented as [-1,-1,-1,0] |
| 135 |
// |-- doc 1 (non contextual) - (row 0, [-1,-1,-1,0]) = encode as parent => [0,-1,-1,0] |
| 136 |
// |-- doc 2 (non contextual) - (row 1, [-1,-1,-1,0]) = encode as parent => [1,-1,-1,0] |
| 137 |
// | |- doc 2.obj1 - (row 0, [1,-1,-1,0]) = encode as parent => [1, 0,-1,0] |
| 138 |
// | |- doc 2.obj2 - (row 1, [1,-1,-1,0]) = encode as parent => [1, 1,-1,0] |
| 139 |
// | |- doc 2.obj3 - (row 2, [1,-1,-1,0]) = encode as parent => [1, 2,-1,0] |
| 140 |
// | |- doc 2.obj3.prop1 - (row 0, [1, 2,-1,0]) = encode as parent => [1, 2, 0,0] |
| 141 |
// | |- doc 2.obj3.prop2 - (row 1, [1, 2,-1,0]) = encode as parent => [1, 2, 1,0] |
| 142 |
// | |- doc 2.obj3.prop3 - (row 2, [1, 2,-1,0]) = encode as parent => [1, 2, 2,0] |
| 143 |
// | |- doc 2.obj3.prop3.path0 - (row 0, [1, 2, 2,0]) = encode as parent => INVALID, LEAF ITEM |
| 144 |
// | |- doc 2.obj3.prop3.path1 - (row 1, [1, 2, 2,0]) = encode as parent => INVALID, LEAF ITEM |
| 145 |
// | |
| 146 |
// | |
| 147 |
// |-- doc 3 (non contextual) - (row 2, [-1,-1,-1,0]) = encode as parent => [2,-1,-1,0] |
| 148 |
// | |
| 149 |
// |-- obj1 (current doc - contextual) - (row 3, [-1,-1,-1,0]) = encode as parent => [3,-1,-1,1] |
| 150 |
// |-- obj2 (current doc - contextual) - (row 4, [-1,-1,-1,0]) = encode as parent => [4,-1,-1,1] |
| 151 |
// | |- obj2.prop1 (contextual) - (row 0, [4,-1,-1,1]) = encode as parent => [4,-1,0,1] |
| 152 |
// | |- obj2.prop2 (contextual) - (row 1, [4,-1,-1,1]) = encode as parent => [4,-1,1,1] |
| 153 |
// | | - obj2.prop2.path1 (contextual) - (row 0, [4,-1,0 ,1]) = encode as parent => INVALID, LEAF ITEM |
| 154 |
// | | - obj2.prop2.path2 (contextual) - (row 1, [4,-1,1 ,1]) = encode as parent => INVALID, LEAF ITEM |
| 155 |
// | |
| 156 |
// |-- prop1 (current obj - contextual) - (row 5, [-1,-1,-1,0]) = encode as parent => [5,-1,-1,1] |
| 157 |
// |-- prop2 (current obj - contextual) - (row 6, [-1,-1,-1,0]) = encode as parent => [6,-1,-1,1] |
| 158 |
// |-- prop2.path1 (contextual) - (row 0, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM |
| 159 |
// |-- prop2.path2 (contextual) - (row 1, [ 6,-1,-1,0]) = encode as parent => INVALID, LEAF ITEM |
| 160 |
// |
| 161 |
// clang-format on |
| 162 |
|
| 163 |
struct Info |
| 164 |
{ |
| 165 |
qint32 doc; |
| 166 |
qint32 obj; |
| 167 |
qint32 prop; |
| 168 |
quint32 contextualHierarchy : 1; |
| 169 |
|
| 170 |
static const Info root; |
| 171 |
}; |
| 172 |
|
| 173 |
static const quint64 k_numBitsProp = 16ULL; // 0 .. 15 |
| 174 |
static const quint64 k_numBitsObj = 24ULL; // 16.. 39 |
| 175 |
static const quint64 k_numBitsContextualHierarchy = 1; // 40 |
| 176 |
static const quint64 k_numBitsDocuments = 23ULL; // 41.. 63 |
| 177 |
|
| 178 |
static const quint64 k_offsetProp = 0; |
| 179 |
static const quint64 k_offsetObj = k_offsetProp + k_numBitsProp; |
| 180 |
static const quint64 k_offsetContextualHierarchy = k_offsetObj + k_numBitsObj; |
| 181 |
static const quint64 k_offsetDocuments = k_offsetContextualHierarchy |
| 182 |
+ k_numBitsContextualHierarchy; |
| 183 |
|
| 184 |
static const quint64 k_maskProp = ((1ULL << k_numBitsProp) - 1); |
| 185 |
static const quint64 k_maskObj = ((1ULL << k_numBitsObj) - 1); |
| 186 |
static const quint64 k_maskContextualHierarchy = ((1ULL << k_numBitsContextualHierarchy) - 1); |
| 187 |
static const quint64 k_maskDocuments = ((1ULL << k_numBitsDocuments) - 1); |
| 188 |
|
| 189 |
union InfoPtrEncoding |
| 190 |
{ |
| 191 |
quint64 d_enc; |
| 192 |
struct |
| 193 |
{ |
| 194 |
quint8 doc; |
| 195 |
quint8 prop; |
| 196 |
quint16 obj : 15; |
| 197 |
quint16 contextualHierarchy : 1; |
| 198 |
} d32; |
| 199 |
void* ptr; |
| 200 |
|
| 201 |
InfoPtrEncoding(const Info& info) |
| 202 |
: d_enc(0) |
| 203 |
{ |
| 204 |
if (sizeof(void*) < sizeof(InfoPtrEncoding)) { |
| 205 |
d32.doc = (quint8)(info.doc + 1); |
| 206 |
d32.obj = (quint16)(info.obj + 1); |
| 207 |
d32.prop = (quint8)(info.prop + 1); |
| 208 |
d32.contextualHierarchy = info.contextualHierarchy; |
| 209 |
} |
| 210 |
else { |
| 211 |
d_enc = ((quint64(info.doc + 1) & k_maskDocuments) << k_offsetDocuments) |
| 212 |
| ((quint64(info.contextualHierarchy) & k_maskContextualHierarchy) |
| 213 |
<< k_offsetContextualHierarchy) |
| 214 |
| ((quint64(info.obj + 1) & k_maskObj) << k_offsetObj) |
| 215 |
| ((quint64(info.prop + 1) & k_maskProp) << k_offsetProp); |
| 216 |
} |
| 217 |
} |
| 218 |
InfoPtrEncoding(void* pointer) |
| 219 |
: d_enc(0) |
| 220 |
{ |
| 221 |
this->ptr = pointer; |
| 222 |
} |
| 223 |
|
| 224 |
Info DecodeInfo() |
| 225 |
{ |
| 226 |
Info info; |
| 227 |
if (sizeof(void*) < sizeof(InfoPtrEncoding)) { |
| 228 |
info.doc = qint32(d32.doc) - 1; |
| 229 |
info.obj = qint32(d32.obj) - 1; |
| 230 |
info.prop = qint32(d32.prop) - 1; |
| 231 |
info.contextualHierarchy = d32.contextualHierarchy; |
| 232 |
} |
| 233 |
else { |
| 234 |
info.doc = ((d_enc >> k_offsetDocuments) & k_maskDocuments) - 1; |
| 235 |
info.contextualHierarchy |
| 236 |
= ((d_enc >> k_offsetContextualHierarchy) & k_maskContextualHierarchy); |
| 237 |
info.obj = ((d_enc >> k_offsetObj) & k_maskObj) - 1; |
| 238 |
info.prop = ((d_enc >> k_offsetProp) & k_maskProp) - 1; |
| 239 |
} |
| 240 |
return info; |
| 241 |
} |
| 242 |
}; |
| 243 |
|
| 244 |
static void* infoId(const Info& info) |
| 245 |
{ |
| 246 |
InfoPtrEncoding ptrEnc(info); |
| 247 |
return ptrEnc.ptr; |
| 248 |
} |
| 249 |
|
| 250 |
static Info getInfo(const QModelIndex& index) |
| 251 |
{ |
| 252 |
InfoPtrEncoding enc(index.internalPointer()); |
| 253 |
return enc.DecodeInfo(); |
| 254 |
} |
| 255 |
|
| 256 |
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override |
| 257 |
{ |
| 258 |
if (role != Qt::EditRole && role != Qt::DisplayRole && role != Qt::UserRole) { |
| 259 |
return {}; |
| 260 |
} |
| 261 |
QVariant variant; |
| 262 |
Info info = getInfo(index); |
| 263 |
_data(info, index.row(), &variant, nullptr, role == Qt::UserRole); |
| 264 |
FC_TRACE( |
| 265 |
info.doc << "," << info.obj << "," << info.prop << "," << info.contextualHierarchy |
| 266 |
<< "," << index.row() << ": " << variant.toString().toUtf8().constData() |
| 267 |
); |
| 268 |
return variant; |
| 269 |
} |
| 270 |
|
| 271 |
static std::vector<App::ObjectIdentifier> retrieveSubPaths(const App::Property* prop) |
| 272 |
{ |
| 273 |
std::vector<App::ObjectIdentifier> result; |
| 274 |
if (prop) { |
| 275 |
prop->getPaths(result); |
| 276 |
// need to filter out irrelevant paths (len 1, aka just this object identifier) |
| 277 |
auto res = std::remove_if( |
| 278 |
result.begin(), |
| 279 |
result.end(), |
| 280 |
[](const App::ObjectIdentifier& path) -> bool { |
| 281 |
return path.getComponents().empty(); |
| 282 |
} |
| 283 |
); |
| 284 |
result.erase(res, result.end()); |
| 285 |
} |
| 286 |
return result; |
| 287 |
} |
| 288 |
|
| 289 |
// Store named object property list in cache for performance purposes, |
| 290 |
// to avoid building it again for each requested index |
| 291 |
std::vector<std::pair<const char*, App::Property*>>& getCachedPropertyNamedList( |
| 292 |
DocumentObject* obj |
| 293 |
) const |
| 294 |
{ |
| 295 |
if (!this->namedPropsCache.contains(obj)) { |
| 296 |
this->namedPropsCache[obj]; |
| 297 |
obj->getPropertyNamedList(this->namedPropsCache[obj]); |
| 298 |
} |
| 299 |
return this->namedPropsCache[obj]; |
| 300 |
} |
| 301 |
|
| 302 |
// The completion tree structure created takes into account the current document and object |
| 303 |
// |
| 304 |
// It is done as such: |
| 305 |
// * root (-1,-1) |
| 306 |
// | |
| 307 |
// |----- documents |
| 308 |
// |----- current documents' objects [externally set] |
| 309 |
// |----- current objects' props [externally set] |
| 310 |
// |
| 311 |
// This complicates the decoding schema for the root, where the childcount will be |
| 312 |
// doc.size() + current_doc.Objects.size() + current_obj.Props.size(). |
| 313 |
// |
| 314 |
// this function is called in two modes: |
| 315 |
// - obtain the count of a node identified by Info,row => count != nullptr, v==nullptr |
| 316 |
// - get the text of an item. This text will contain separators but NO full path |
| 317 |
void _data(const Info& info, int row, QVariant* v, int* count, bool sep = false) const |
| 318 |
{ |
| 319 |
int idx; |
| 320 |
// identify the document index. For any children of the root, it is given by traversing |
| 321 |
// the flat list and identified by [row] |
| 322 |
idx = info.doc < 0 ? row : info.doc; |
| 323 |
const auto& docs = App::GetApplication().getDocuments(); |
| 324 |
int docSize = (int)docs.size() * 2; |
| 325 |
int objSize = 0; |
| 326 |
int propSize = 0; |
| 327 |
App::Document* doc = nullptr; |
| 328 |
App::DocumentObject* obj = nullptr; |
| 329 |
const char* propName = nullptr; |
| 330 |
App::Property* prop = nullptr; |
| 331 |
// check if the document is uniquely identified: either the correct index in info.doc |
| 332 |
// OR if, the node is a descendant of the root, its row lands within 0...docsize |
| 333 |
if (idx >= 0 && idx < docSize) { |
| 334 |
doc = docs[idx / 2]; |
| 335 |
} |
| 336 |
else { |
| 337 |
// if we're looking at the ROOT, or the row identifies one of the other ROOT elements |
| 338 |
// |----- current documents' objects, rows: docs.size ... docs.size + |
| 339 |
// objs.size |
| 340 |
// |----- current objects' props, rows: docs.size + objs.size ... docs.size + |
| 341 |
// objs.size+ props.size |
| 342 |
// |
| 343 |
// We need to process the ROOT so we get the correct count for its children |
| 344 |
doc = App::GetApplication().getDocument(currentDoc.c_str()); |
| 345 |
if (!doc) { // no current, there are no additional objects |
| 346 |
return; |
| 347 |
} |
| 348 |
|
| 349 |
// move to the current documents' objects' range |
| 350 |
idx -= docSize; |
| 351 |
if (info.doc < 0) { |
| 352 |
row = idx; |
| 353 |
} |
| 354 |
|
| 355 |
const auto& objs = doc->getObjects(); |
| 356 |
objSize = (int)objs.size() * 2; |
| 357 |
// if this is a valid object, we found our object and break. |
| 358 |
// if not, this may be the root or one of current object's properties |
| 359 |
if (idx >= 0 && idx < objSize) { |
| 360 |
obj = objs[idx / 2]; |
| 361 |
// if they are in the ignore list skip |
| 362 |
if (inList.contains(obj)) { |
| 363 |
return; |
| 364 |
} |
| 365 |
} |
| 366 |
else if (!noProperty) { |
| 367 |
// need to check the current object's props range, or we're parsing the ROOT |
| 368 |
auto cobj = doc->getObject(currentObj.c_str()); |
| 369 |
if (cobj) { |
| 370 |
// move to the props range of the current object |
| 371 |
idx -= objSize; |
| 372 |
if (info.doc < 0) { |
| 373 |
row = idx; |
| 374 |
} |
| 375 |
// get the properties |
| 376 |
auto& props = this->getCachedPropertyNamedList(cobj); |
| 377 |
propSize = (int)props.size(); |
| 378 |
|
| 379 |
// if this is an invalid index, bail out |
| 380 |
// if it's the ROOT break! |
| 381 |
if (idx >= propSize) { |
| 382 |
return; |
| 383 |
} |
| 384 |
if (idx >= 0) { |
| 385 |
obj = cobj; // we only set the active object if we're not processing the |
| 386 |
// root. |
| 387 |
propName = props[idx].first; |
| 388 |
prop = props[idx].second; |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
// the item is the ROOT or a CHILD of the root |
| 394 |
if (info.doc < 0) { |
| 395 |
// and we're asking for a count, compute it |
| 396 |
if (count) { |
| 397 |
// note that if we're dealing with a valid DOC node (row>0, ROOT_info) |
| 398 |
// objSize and propSize will be zero because of the early exit above |
| 399 |
*count = docSize + objSize + propSize; |
| 400 |
} |
| 401 |
if (idx >= 0 && v) { |
| 402 |
// we're asking for this child's data, and IT's NOT THE ROOT |
| 403 |
QString res; |
| 404 |
// we resolved the property |
| 405 |
if (propName) { |
| 406 |
res = QString::fromLatin1(propName); |
| 407 |
// resolve the property |
| 408 |
if (sep && !noProperty && !retrieveSubPaths(prop).empty()) { |
| 409 |
res += QLatin1Char('.'); |
| 410 |
} |
| 411 |
} |
| 412 |
else if (obj) { |
| 413 |
// the object has been resolved, use the saved idx to figure out quotation or |
| 414 |
// not. |
| 415 |
if (idx & 1) { |
| 416 |
res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str()); |
| 417 |
} |
| 418 |
else { |
| 419 |
res = QString::fromLatin1(obj->getNameInDocument()); |
| 420 |
} |
| 421 |
if (sep && !noProperty) { |
| 422 |
res += QLatin1Char('.'); |
| 423 |
} |
| 424 |
} |
| 425 |
else { |
| 426 |
// the document has been resolved, use the saved idx to figure out quotation or |
| 427 |
// not. |
| 428 |
if (idx & 1) { |
| 429 |
res = QString::fromUtf8(quote(doc->Label.getStrValue()).c_str()); |
| 430 |
} |
| 431 |
else { |
| 432 |
res = QString::fromUtf8(doc->getName()); |
| 433 |
} |
| 434 |
if (sep) { |
| 435 |
res += QLatin1Char('#'); |
| 436 |
} |
| 437 |
} |
| 438 |
v->setValue(res); |
| 439 |
} |
| 440 |
// done processing the ROOT or any child items |
| 441 |
return; |
| 442 |
} |
| 443 |
|
| 444 |
// object not resolved |
| 445 |
if (!obj) { |
| 446 |
// are we pointing to an object item, or our father (info) is an object |
| 447 |
idx = info.obj < 0 ? row : info.obj; |
| 448 |
const auto& objs = doc->getObjects(); |
| 449 |
objSize = (int)objs.size() * 2; |
| 450 |
// if invalid index, or in the ignore list bail out |
| 451 |
if (idx < 0 || idx >= objSize || inList.contains(obj)) { |
| 452 |
return; |
| 453 |
} |
| 454 |
obj = objs[idx / 2]; |
| 455 |
|
| 456 |
if (info.obj < 0) { |
| 457 |
// if this is AN actual Object item and not a root |
| 458 |
if (count) { |
| 459 |
*count = objSize; // set the correct count if requested |
| 460 |
} |
| 461 |
if (v) { |
| 462 |
// resolve the name |
| 463 |
QString res; |
| 464 |
if (idx & 1) { |
| 465 |
res = QString::fromUtf8(quote(obj->Label.getStrValue()).c_str()); |
| 466 |
} |
| 467 |
else { |
| 468 |
res = QString::fromLatin1(obj->getNameInDocument()); |
| 469 |
} |
| 470 |
if (sep && !noProperty) { |
| 471 |
res += QLatin1Char('.'); |
| 472 |
} |
| 473 |
v->setValue(res); |
| 474 |
} |
| 475 |
return; |
| 476 |
} |
| 477 |
} |
| 478 |
|
| 479 |
if (noProperty) { |
| 480 |
return; |
| 481 |
} |
| 482 |
if (!propName) { |
| 483 |
idx = info.prop < 0 ? row : info.prop; |
| 484 |
auto& props = this->getCachedPropertyNamedList(obj); |
| 485 |
propSize = (int)props.size(); |
| 486 |
// return if the property is invalid |
| 487 |
if (idx < 0 || idx >= propSize) { |
| 488 |
return; |
| 489 |
} |
| 490 |
propName = props[idx].first; |
| 491 |
prop = props[idx].second; |
| 492 |
// if this is a root object item |
| 493 |
if (info.prop < 0) { |
| 494 |
// set the property size count |
| 495 |
if (count) { |
| 496 |
*count = propSize; |
| 497 |
} |
| 498 |
if (v) { |
| 499 |
QString res = QString::fromLatin1(propName); |
| 500 |
|
| 501 |
// check to see if we have accessible paths from this prop name? |
| 502 |
if (sep && !retrieveSubPaths(prop).empty()) { |
| 503 |
res += QLatin1Char('.'); |
| 504 |
} |
| 505 |
*v = res; |
| 506 |
} |
| 507 |
return; |
| 508 |
} |
| 509 |
} |
| 510 |
|
| 511 |
// resolve paths |
| 512 |
if (prop) { |
| 513 |
// idx identifies the path |
| 514 |
idx = row; |
| 515 |
std::vector<App::ObjectIdentifier> paths = retrieveSubPaths(prop); |
| 516 |
|
| 517 |
if (count) { |
| 518 |
*count = paths.size(); |
| 519 |
} |
| 520 |
|
| 521 |
// check to see if this is a valid path |
| 522 |
if (idx < 0 || idx >= static_cast<int>(paths.size())) { |
| 523 |
return; |
| 524 |
} |
| 525 |
|
| 526 |
if (v) { |
| 527 |
auto str = paths[idx].getSubPathStr(); |
| 528 |
if (str.size() && (str[0] == '.' || str[0] == '#')) { |
| 529 |
// skip the "." |
| 530 |
*v = QString::fromLatin1(str.c_str() + 1); |
| 531 |
} |
| 532 |
else { |
| 533 |
*v = QString::fromLatin1(str.c_str()); |
| 534 |
} |
| 535 |
} |
| 536 |
} |
| 537 |
} |
| 538 |
|
| 539 |
QModelIndex parent(const QModelIndex& index) const override |
| 540 |
{ |
| 541 |
if (!index.isValid()) { |
| 542 |
return {}; |
| 543 |
} |
| 544 |
|
| 545 |
Info parentInfo = getInfo(index); |
| 546 |
Info grandParentInfo = parentInfo; |
| 547 |
|
| 548 |
if (parentInfo.contextualHierarchy) { |
| 549 |
// for contextual hierarchy we have this: |
| 550 |
// ROOT -> Object in Current Doc -> Prop In Object -> PropPath |
| 551 |
// ROOT -> prop in Current Object -> prop Path |
| 552 |
|
| 553 |
if (parentInfo.prop >= 0) { |
| 554 |
grandParentInfo.prop = -1; |
| 555 |
return createIndex(parentInfo.prop, 0, infoId(grandParentInfo)); |
| 556 |
} |
| 557 |
// if the parent is the object or a prop attached to the root, we just need the below |
| 558 |
// line |
| 559 |
return createIndex(parentInfo.doc, 0, infoId(Info::root)); |
| 560 |
} |
| 561 |
else { |
| 562 |
if (parentInfo.prop >= 0) { |
| 563 |
grandParentInfo.prop = -1; |
| 564 |
return createIndex(parentInfo.prop, 0, infoId(grandParentInfo)); |
| 565 |
} |
| 566 |
if (parentInfo.obj >= 0) { |
| 567 |
grandParentInfo.obj = -1; |
| 568 |
return createIndex(parentInfo.obj, 0, infoId(grandParentInfo)); |
| 569 |
} |
| 570 |
if (parentInfo.doc >= 0) { |
| 571 |
grandParentInfo.doc = -1; |
| 572 |
return createIndex(parentInfo.doc, 0, infoId(grandParentInfo)); |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
|
| 577 |
return {}; |
| 578 |
} |
| 579 |
|
| 580 |
// returns true if successful, false if 'element' identifies a Leaf |
| 581 |
bool modelIndexToParentInfo(QModelIndex element, Info& info) const |
| 582 |
{ |
| 583 |
Info parentInfo; |
| 584 |
info = Info::root; |
| 585 |
|
| 586 |
if (element.isValid()) { |
| 587 |
parentInfo = getInfo(element); |
| 588 |
info = parentInfo; |
| 589 |
|
| 590 |
// Our wonderful element is a child of the root |
| 591 |
if (parentInfo.doc < 0) { |
| 592 |
// need special casing to properly identify this model's object |
| 593 |
const auto& docs = App::GetApplication().getDocuments(); |
| 594 |
auto docsSize = static_cast<int>(docs.size() * 2); |
| 595 |
|
| 596 |
info.doc = element.row(); |
| 597 |
|
| 598 |
// if my element is a contextual descendant of root (current doc object list, |
| 599 |
// current object prop list) mark it as such |
| 600 |
if (element.row() >= docsSize) { |
| 601 |
info.contextualHierarchy = 1; |
| 602 |
} |
| 603 |
} |
| 604 |
else if (parentInfo.contextualHierarchy) { |
| 605 |
const auto& docs = App::GetApplication().getDocuments(); |
| 606 |
auto cdoc = App::GetApplication().getDocument(currentDoc.c_str()); |
| 607 |
|
| 608 |
if (cdoc) { |
| 609 |
int objsSize = static_cast<int>(cdoc->getObjects().size() * 2); |
| 610 |
int idx = parentInfo.doc - static_cast<int>(docs.size()); |
| 611 |
if (idx < objsSize) { |
| 612 |
// |-- Parent (OBJECT) - (row 4, [-1,-1,-1,0]) = encode as element => |
| 613 |
// [parent.row,-1,-1,1] |
| 614 |
// |- element (PROP) - (row 0, [parent.row,-1,-1,1]) = encode as |
| 615 |
// element => [parent.row,-1,parent.row,1] |
| 616 |
|
| 617 |
info.doc = parentInfo.doc; |
| 618 |
info.obj = -1; // object information is determined by the DOC index actually |
| 619 |
info.prop = element.row(); |
| 620 |
info.contextualHierarchy = 1; |
| 621 |
} |
| 622 |
else { |
| 623 |
// if my parent (parentInfo) is a prop, it means that our element is a prop |
| 624 |
// path and that is a leaf item (we don't split prop paths further) we can't |
| 625 |
// encode leaf items into an "Info" |
| 626 |
return false; |
| 627 |
} |
| 628 |
} |
| 629 |
else { |
| 630 |
// no contextual document |
| 631 |
return false; |
| 632 |
} |
| 633 |
} |
| 634 |
// regular hierarchy |
| 635 |
else if (parentInfo.obj <= 0) { |
| 636 |
info.obj = element.row(); |
| 637 |
} |
| 638 |
else if (parentInfo.prop <= 0) { |
| 639 |
info.prop = element.row(); |
| 640 |
} |
| 641 |
else { |
| 642 |
return false; |
| 643 |
} |
| 644 |
} |
| 645 |
return true; |
| 646 |
} |
| 647 |
|
| 648 |
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override |
| 649 |
{ |
| 650 |
if (row < 0) { |
| 651 |
return {}; |
| 652 |
} |
| 653 |
Info myParentInfoEncoded = Info::root; |
| 654 |
|
| 655 |
// encode the parent's QModelIndex into an 'Info' structure |
| 656 |
bool parentCanHaveChildren = modelIndexToParentInfo(parent, myParentInfoEncoded); |
| 657 |
if (!parentCanHaveChildren) { |
| 658 |
return {}; |
| 659 |
} |
| 660 |
return createIndex(row, column, infoId(myParentInfoEncoded)); |
| 661 |
} |
| 662 |
|
| 663 |
// function returns how many children the QModelIndex parent has |
| 664 |
int rowCount(const QModelIndex& parent = QModelIndex()) const override |
| 665 |
{ |
| 666 |
Info info; |
| 667 |
int row = 0; |
| 668 |
if (!parent.isValid()) { |
| 669 |
// we're getting the row count for the root |
| 670 |
// that is: document hierarchy _and_ contextual completion |
| 671 |
info = Info::root; |
| 672 |
row = -1; |
| 673 |
} |
| 674 |
else { |
| 675 |
// try to encode the parent's QModelIndex into an info structure |
| 676 |
// if the paren't can't have any children, return 0 |
| 677 |
if (!modelIndexToParentInfo(parent, info)) { |
| 678 |
return 0; |
| 679 |
} |
| 680 |
} |
| 681 |
int count = 0; |
| 682 |
_data(info, row, nullptr, &count); |
| 683 |
FC_TRACE( |
| 684 |
info.doc << "," << info.obj << "," << info.prop << "," << info.contextualHierarchy |
| 685 |
<< "," << row << " row count " << count |
| 686 |
); |
| 687 |
return count; |
| 688 |
} |
| 689 |
|
| 690 |
int columnCount(const QModelIndex&) const override |
| 691 |
{ |
| 692 |
return 1; |
| 693 |
} |
| 694 |
|
| 695 |
private: |
| 696 |
mutable std::map<DocumentObject*, std::vector<std::pair<const char*, App::Property*>>> namedPropsCache; |
| 697 |
std::set<App::DocumentObject*> inList; |
| 698 |
std::string currentDoc; |
| 699 |
std::string currentObj; |
| 700 |
bool noProperty; |
| 701 |
}; |
| 702 |
|
| 703 |
const ExpressionCompleterModel::Info ExpressionCompleterModel::Info::root = {-1, -1, -1, 0}; |
| 704 |
|
| 705 |
/** |
| 706 |
* @brief Construct an ExpressionCompleter object. |
| 707 |
* @param currentDoc Current document to generate the model from. |
| 708 |
* @param currentDocObj Current document object to generate model from. |
| 709 |
* @param parent Parent object owning the completer. |
| 710 |
*/ |
| 711 |
|
| 712 |
ExpressionCompleter::ExpressionCompleter( |
| 713 |
const App::DocumentObject* currentDocObj, |
| 714 |
QObject* parent, |
| 715 |
bool noProperty, |
| 716 |
bool checkInList |
| 717 |
) |
| 718 |
: QCompleter(parent) |
| 719 |
, currentObj(currentDocObj) |
| 720 |
, noProperty(noProperty) |
| 721 |
, checkInList(checkInList) |
| 722 |
{ |
| 723 |
setCaseSensitivity(Qt::CaseInsensitive); |
| 724 |
} |
| 725 |
|
| 726 |
void ExpressionCompleter::init() |
| 727 |
{ |
| 728 |
if (model()) { |
| 729 |
return; |
| 730 |
} |
| 731 |
|
| 732 |
auto m = new ExpressionCompleterModel(this, noProperty); |
| 733 |
m->setDocumentObject(currentObj.getObject(), checkInList); |
| 734 |
setModel(m); |
| 735 |
} |
| 736 |
|
| 737 |
void ExpressionCompleter::setDocumentObject(const App::DocumentObject* obj, bool _checkInList) |
| 738 |
{ |
| 739 |
if (!obj || !obj->isAttachedToDocument()) { |
| 740 |
currentObj = App::DocumentObjectT(); |
| 741 |
} |
| 742 |
else { |
| 743 |
currentObj = obj; |
| 744 |
} |
| 745 |
setCompletionPrefix(QString()); |
| 746 |
checkInList = _checkInList; |
| 747 |
auto m = model(); |
| 748 |
if (m) { |
| 749 |
static_cast<ExpressionCompleterModel*>(m)->setDocumentObject(obj, checkInList); |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
void ExpressionCompleter::setNoProperty(bool enabled) |
| 754 |
{ |
| 755 |
noProperty = enabled; |
| 756 |
auto m = model(); |
| 757 |
if (m) { |
| 758 |
static_cast<ExpressionCompleterModel*>(m)->setNoProperty(enabled); |
| 759 |
} |
| 760 |
} |
| 761 |
|
| 762 |
QString ExpressionCompleter::pathFromIndex(const QModelIndex& index) const |
| 763 |
{ |
| 764 |
auto m = model(); |
| 765 |
if (!m || !index.isValid()) { |
| 766 |
return {}; |
| 767 |
} |
| 768 |
|
| 769 |
QString res; |
| 770 |
auto parent = index; |
| 771 |
do { |
| 772 |
res = m->data(parent, Qt::UserRole).toString() + res; |
| 773 |
parent = parent.parent(); |
| 774 |
} while (parent.isValid()); |
| 775 |
|
| 776 |
auto info = ExpressionCompleterModel::getInfo(index); |
| 777 |
FC_TRACE( |
| 778 |
"join path " << info.doc << "," << info.obj << "," << info.prop << "," |
| 779 |
<< info.contextualHierarchy << "," << index.row() << ": " |
| 780 |
<< res.toUtf8().constData() |
| 781 |
); |
| 782 |
return res; |
| 783 |
} |
| 784 |
|
| 785 |
QStringList ExpressionCompleter::splitPath(const QString& input) const |
| 786 |
{ |
| 787 |
QStringList resultList; |
| 788 |
std::string path = input.toUtf8().constData(); |
| 789 |
if (path.empty()) { |
| 790 |
return resultList; |
| 791 |
} |
| 792 |
|
| 793 |
int retry = 0; |
| 794 |
std::string lastElem; // used to recover in case of parse failure after ".". |
| 795 |
std::string trim; // used to delete ._self added for another recovery path |
| 796 |
while (true) { |
| 797 |
try { |
| 798 |
// this will not work for incomplete Tokens at the end |
| 799 |
// "Sketch." will fail to parse and complete. |
| 800 |
|
| 801 |
App::ObjectIdentifier ident = ObjectIdentifier::parse(currentObj.getObject(), path); |
| 802 |
|
| 803 |
std::vector<std::string> stringList = ident.getStringList(); |
| 804 |
auto stringListIter = stringList.begin(); |
| 805 |
if (retry > 1 && !stringList.empty()) { |
| 806 |
stringList.pop_back(); |
| 807 |
} |
| 808 |
|
| 809 |
if (!stringList.empty()) { |
| 810 |
if (!trim.empty() && boost::ends_with(stringList.back(), trim)) { |
| 811 |
stringList.back().resize(stringList.back().size() - trim.size()); |
| 812 |
} |
| 813 |
while (stringListIter != stringList.end()) { |
| 814 |
resultList << QString::fromStdString(*stringListIter); |
| 815 |
++stringListIter; |
| 816 |
} |
| 817 |
} |
| 818 |
if (lastElem.size()) { |
| 819 |
// if we finish in a trailing separator |
| 820 |
if (!lastElem.empty()) { |
| 821 |
// erase the separator |
| 822 |
lastElem.erase(lastElem.begin()); |
| 823 |
resultList << QString::fromStdString(lastElem); |
| 824 |
} |
| 825 |
else { |
| 826 |
// add empty string to allow completion after "." or "#" |
| 827 |
resultList << QString(); |
| 828 |
} |
| 829 |
} |
| 830 |
FC_TRACE( |
| 831 |
"split path " << path << " -> " |
| 832 |
<< resultList.join(QLatin1String("/")).toUtf8().constData() |
| 833 |
); |
| 834 |
return resultList; |
| 835 |
} |
| 836 |
catch (const Base::Exception& except) { |
| 837 |
FC_TRACE("split path " << path << " error: " << except.what()); |
| 838 |
if (retry == 0) { |
| 839 |
size_t lastElemStart = path.rfind('.'); |
| 840 |
|
| 841 |
if (lastElemStart == std::string::npos) { |
| 842 |
lastElemStart = path.rfind('#'); |
| 843 |
} |
| 844 |
if (lastElemStart != std::string::npos) { |
| 845 |
lastElem = path.substr(lastElemStart); |
| 846 |
path = path.substr(0, lastElemStart); |
| 847 |
} |
| 848 |
retry++; |
| 849 |
continue; |
| 850 |
} |
| 851 |
else if (retry == 1) { |
| 852 |
// restore path from retry 0 |
| 853 |
if (lastElem.size() > 1) { |
| 854 |
path = path + lastElem; |
| 855 |
lastElem = ""; |
| 856 |
} |
| 857 |
// else... we don't reset lastElem if it's a '.' or '#' to allow chaining |
| 858 |
// completions |
| 859 |
if (!path.empty()) { |
| 860 |
char last = path[path.size() - 1]; |
| 861 |
if (last != '#' && last != '.' && path.find('#') != std::string::npos) { |
| 862 |
path += "._self"; |
| 863 |
++retry; |
| 864 |
continue; |
| 865 |
} |
| 866 |
} |
| 867 |
} |
| 868 |
else if (retry == 2) { |
| 869 |
if (path.size() >= 6) { |
| 870 |
path.resize(path.size() - 6); |
| 871 |
} |
| 872 |
if (!path.empty()) { |
| 873 |
char last = path[path.size() - 1]; |
| 874 |
if (last != '.' && last != '<' && path.find("#<<") != std::string::npos) { |
| 875 |
path += ">>._self"; |
| 876 |
++retry; |
| 877 |
trim = ">>"; |
| 878 |
continue; |
| 879 |
} |
| 880 |
} |
| 881 |
} |
| 882 |
return QStringList() << input; |
| 883 |
} |
| 884 |
} |
| 885 |
} |
| 886 |
|
| 887 |
// Code below inspired by blog entry: |
| 888 |
// https://john.nachtimwald.com/2009/07/04/qcompleter-and-comma-separated-tags/ |
| 889 |
|
| 890 |
void ExpressionCompleter::slotUpdate(const QString& prefix, int pos) |
| 891 |
{ |
| 892 |
FC_TRACE("SlotUpdate:" << prefix.toUtf8().constData()); |
| 893 |
|
| 894 |
init(); |
| 895 |
|
| 896 |
QString completionPrefix = tokenizer.perform(prefix, pos); |
| 897 |
if (completionPrefix.isEmpty()) { |
| 898 |
if (auto itemView = popup()) { |
| 899 |
itemView->setVisible(false); |
| 900 |
} |
| 901 |
return; |
| 902 |
} |
| 903 |
|
| 904 |
FC_TRACE("Completion Prefix:" << completionPrefix.toUtf8().constData()); |
| 905 |
// Set completion prefix |
| 906 |
setCompletionPrefix(completionPrefix); |
| 907 |
|
| 908 |
if (widget()->hasFocus()) { |
| 909 |
FC_TRACE("Complete on Prefix" << completionPrefix.toUtf8().constData()); |
| 910 |
complete(); |
| 911 |
FC_TRACE("Complete Done"); |
| 912 |
} |
| 913 |
else if (auto itemView = popup()) { |
| 914 |
itemView->setVisible(false); |
| 915 |
} |
| 916 |
|
| 917 |
Q_EMIT completerSlotUpdated(); |
| 918 |
} |
| 919 |
|
| 920 |
ExpressionValidator::ExpressionValidator(QObject* parent) |
| 921 |
: QValidator(parent) |
| 922 |
{} |
| 923 |
|
| 924 |
void ExpressionValidator::fixup(QString& input) const |
| 925 |
{ |
| 926 |
if (input.startsWith(QLatin1String("="))) { |
| 927 |
input = input.mid(1); |
| 928 |
} |
| 929 |
} |
| 930 |
|
| 931 |
QValidator::State ExpressionValidator::validate(QString& input, int& pos) const |
| 932 |
{ |
| 933 |
if (input.startsWith(QLatin1String("="))) { |
| 934 |
pos = 0; |
| 935 |
return QValidator::Invalid; |
| 936 |
} |
| 937 |
|
| 938 |
return QValidator::Acceptable; |
| 939 |
} |
| 940 |
|
| 941 |
ExpressionLineEdit::ExpressionLineEdit(QWidget* parent, bool noProperty, char checkPrefix, bool checkInList) |
| 942 |
: QLineEdit(parent) |
| 943 |
, completer(nullptr) |
| 944 |
, block(true) |
| 945 |
, noProperty(noProperty) |
| 946 |
, exactMatch(false) |
| 947 |
, checkInList(checkInList) |
| 948 |
{ |
| 949 |
setPrefix(checkPrefix); |
| 950 |
connect(this, &QLineEdit::textEdited, this, &ExpressionLineEdit::slotTextChanged); |
| 951 |
} |
| 952 |
|
| 953 |
void ExpressionLineEdit::setPrefix(char prefix) |
| 954 |
{ |
| 955 |
checkPrefix = prefix; |
| 956 |
setValidator(checkPrefix == '=' ? nullptr : new ExpressionValidator(this)); |
| 957 |
} |
| 958 |
|
| 959 |
void ExpressionLineEdit::setDocumentObject(const App::DocumentObject* currentDocObj, bool _checkInList) |
| 960 |
{ |
| 961 |
checkInList = _checkInList; |
| 962 |
if (completer) { |
| 963 |
completer->setDocumentObject(currentDocObj, checkInList); |
| 964 |
return; |
| 965 |
} |
| 966 |
if (currentDocObj) { |
| 967 |
completer = new ExpressionCompleter(currentDocObj, this, noProperty, checkInList); |
| 968 |
completer->setWidget(this); |
| 969 |
completer->setCaseSensitivity(Qt::CaseInsensitive); |
| 970 |
if (!exactMatch) { |
| 971 |
completer->setFilterMode(Qt::MatchContains); |
| 972 |
} |
| 973 |
connect( |
| 974 |
completer, |
| 975 |
qOverload<const QString&>(&QCompleter::activated), |
| 976 |
this, |
| 977 |
&ExpressionLineEdit::slotCompleteTextSelected |
| 978 |
); |
| 979 |
connect( |
| 980 |
completer, |
| 981 |
qOverload<const QString&>(&QCompleter::highlighted), |
| 982 |
this, |
| 983 |
&ExpressionLineEdit::slotCompleteTextHighlighted |
| 984 |
); |
| 985 |
connect(this, &ExpressionLineEdit::textChanged2, completer, &ExpressionCompleter::slotUpdate); |
| 986 |
} |
| 987 |
} |
| 988 |
|
| 989 |
void ExpressionLineEdit::setNoProperty(bool enabled) |
| 990 |
{ |
| 991 |
noProperty = enabled; |
| 992 |
if (completer) { |
| 993 |
completer->setNoProperty(enabled); |
| 994 |
} |
| 995 |
} |
| 996 |
|
| 997 |
void ExpressionLineEdit::setExactMatch(bool enabled) |
| 998 |
{ |
| 999 |
exactMatch = enabled; |
| 1000 |
if (completer) { |
| 1001 |
completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains); |
| 1002 |
} |
| 1003 |
} |
| 1004 |
|
| 1005 |
ExpressionCompleter* ExpressionLineEdit::getCompleter(void) |
| 1006 |
{ |
| 1007 |
return this->completer; |
| 1008 |
} |
| 1009 |
|
| 1010 |
bool ExpressionLineEdit::completerActive() const |
| 1011 |
{ |
| 1012 |
return completer && completer->popup() && completer->popup()->isVisible(); |
| 1013 |
} |
| 1014 |
|
| 1015 |
void ExpressionLineEdit::hideCompleter() |
| 1016 |
{ |
| 1017 |
if (completer && completer->popup()) { |
| 1018 |
completer->popup()->setVisible(false); |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
void ExpressionLineEdit::slotTextChanged(const QString& text) |
| 1023 |
{ |
| 1024 |
if (!block) { |
| 1025 |
if (!text.size() || (checkPrefix && text[0] != QLatin1Char(checkPrefix))) { |
| 1026 |
return; |
| 1027 |
} |
| 1028 |
Q_EMIT textChanged2(text, cursorPosition()); |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
void ExpressionLineEdit::slotCompleteText(const QString& completionPrefix, ActivationMode mode) |
| 1033 |
{ |
| 1034 |
int start, end; |
| 1035 |
completer->getPrefixRange(start, end); |
| 1036 |
QString before(text().left(start)); |
| 1037 |
QString after(text().mid(end)); |
| 1038 |
|
| 1039 |
{ |
| 1040 |
Base::FlagToggler<bool> flag(block, false); |
| 1041 |
before += completionPrefix; |
| 1042 |
setText(before + after); |
| 1043 |
setCursorPosition(before.length()); |
| 1044 |
completer->updatePrefixEnd(before.length()); |
| 1045 |
} |
| 1046 |
|
| 1047 |
// chain completions if we select an entry from the completer drop down |
| 1048 |
// and that entry ends with '.' or '#' |
| 1049 |
if (mode == ActivationMode::Activated) { |
| 1050 |
std::string textToComplete = completionPrefix.toUtf8().constData(); |
| 1051 |
if (textToComplete.size() |
| 1052 |
&& (*textToComplete.crbegin() == '.' || *textToComplete.crbegin() == '#')) { |
| 1053 |
Base::FlagToggler<bool> flag(block, true); |
| 1054 |
slotTextChanged(before + after); |
| 1055 |
} |
| 1056 |
} |
| 1057 |
} |
| 1058 |
|
| 1059 |
void ExpressionLineEdit::slotCompleteTextHighlighted(const QString& completionPrefix) |
| 1060 |
{ |
| 1061 |
slotCompleteText(completionPrefix, ActivationMode::Highlighted); |
| 1062 |
} |
| 1063 |
|
| 1064 |
void ExpressionLineEdit::slotCompleteTextSelected(const QString& completionPrefix) |
| 1065 |
{ |
| 1066 |
slotCompleteText(completionPrefix, ActivationMode::Activated); |
| 1067 |
} |
| 1068 |
|
| 1069 |
|
| 1070 |
void ExpressionLineEdit::keyPressEvent(QKeyEvent* e) |
| 1071 |
{ |
| 1072 |
Base::FlagToggler<bool> flag(block, true); |
| 1073 |
QLineEdit::keyPressEvent(e); |
| 1074 |
} |
| 1075 |
|
| 1076 |
void ExpressionLineEdit::contextMenuEvent(QContextMenuEvent* event) |
| 1077 |
{ |
| 1078 |
QMenu* menu = createStandardContextMenu(); |
| 1079 |
|
| 1080 |
if (completer) { |
| 1081 |
menu->addSeparator(); |
| 1082 |
QAction* match = menu->addAction(tr("Exact Match")); |
| 1083 |
match->setCheckable(true); |
| 1084 |
match->setChecked(completer->filterMode() == Qt::MatchStartsWith); |
| 1085 |
QObject::connect(match, &QAction::toggled, this, &Gui::ExpressionLineEdit::setExactMatch); |
| 1086 |
} |
| 1087 |
menu->setAttribute(Qt::WA_DeleteOnClose); |
| 1088 |
|
| 1089 |
menu->popup(event->globalPos()); |
| 1090 |
} |
| 1091 |
|
| 1092 |
|
| 1093 |
/////////////////////////////////////////////////////////////////////// |
| 1094 |
|
| 1095 |
ExpressionTextEdit::ExpressionTextEdit(QWidget* parent) |
| 1096 |
: QPlainTextEdit(parent) |
| 1097 |
, completer(nullptr) |
| 1098 |
, block(true) |
| 1099 |
, exactMatch(false) |
| 1100 |
{ |
| 1101 |
connect(this, &QPlainTextEdit::textChanged, this, &ExpressionTextEdit::slotTextChanged); |
| 1102 |
} |
| 1103 |
|
| 1104 |
void ExpressionTextEdit::setExactMatch(bool enabled) |
| 1105 |
{ |
| 1106 |
exactMatch = enabled; |
| 1107 |
if (completer) { |
| 1108 |
completer->setFilterMode(exactMatch ? Qt::MatchStartsWith : Qt::MatchContains); |
| 1109 |
} |
| 1110 |
} |
| 1111 |
|
| 1112 |
QSize ExpressionTextEdit::sizeHint() const |
| 1113 |
{ |
| 1114 |
return QSize(200, 30); |
| 1115 |
} |
| 1116 |
|
| 1117 |
void ExpressionTextEdit::setDocumentObject(const App::DocumentObject* currentDocObj) |
| 1118 |
{ |
| 1119 |
if (completer) { |
| 1120 |
completer->setDocumentObject(currentDocObj); |
| 1121 |
return; |
| 1122 |
} |
| 1123 |
|
| 1124 |
if (currentDocObj) { |
| 1125 |
completer = new ExpressionCompleter(currentDocObj, this); |
| 1126 |
if (!exactMatch) { |
| 1127 |
completer->setFilterMode(Qt::MatchContains); |
| 1128 |
} |
| 1129 |
completer->setWidget(this); |
| 1130 |
completer->setCaseSensitivity(Qt::CaseInsensitive); |
| 1131 |
connect( |
| 1132 |
completer, |
| 1133 |
qOverload<const QString&>(&QCompleter::activated), |
| 1134 |
this, |
| 1135 |
&ExpressionTextEdit::slotCompleteTextSelected |
| 1136 |
); |
| 1137 |
connect( |
| 1138 |
completer, |
| 1139 |
qOverload<const QString&>(&QCompleter::highlighted), |
| 1140 |
this, |
| 1141 |
&ExpressionTextEdit::slotCompleteTextHighlighted |
| 1142 |
); |
| 1143 |
connect(this, &ExpressionTextEdit::textChanged2, completer, &ExpressionCompleter::slotUpdate); |
| 1144 |
connect( |
| 1145 |
completer, |
| 1146 |
&ExpressionCompleter::completerSlotUpdated, |
| 1147 |
this, |
| 1148 |
&ExpressionTextEdit::adjustCompleterToCursor |
| 1149 |
); |
| 1150 |
} |
| 1151 |
} |
| 1152 |
|
| 1153 |
bool ExpressionTextEdit::completerActive() const |
| 1154 |
{ |
| 1155 |
return completer && completer->popup() && completer->popup()->isVisible(); |
| 1156 |
} |
| 1157 |
|
| 1158 |
void ExpressionTextEdit::hideCompleter() |
| 1159 |
{ |
| 1160 |
if (completer && completer->popup()) { |
| 1161 |
completer->popup()->setVisible(false); |
| 1162 |
} |
| 1163 |
} |
| 1164 |
|
| 1165 |
void ExpressionTextEdit::slotTextChanged() |
| 1166 |
{ |
| 1167 |
if (!block) { |
| 1168 |
QTextCursor cursor = textCursor(); |
| 1169 |
completer->popup()->setVisible(false); // hide the completer to avoid flickering |
| 1170 |
Q_EMIT textChanged2(cursor.block().text(), cursor.positionInBlock()); |
| 1171 |
} |
| 1172 |
} |
| 1173 |
|
| 1174 |
void ExpressionTextEdit::slotCompleteText(const QString& completionPrefix, ActivationMode mode) |
| 1175 |
{ |
| 1176 |
QTextCursor cursor = textCursor(); |
| 1177 |
int start, end; |
| 1178 |
completer->getPrefixRange(start, end); |
| 1179 |
int pos = cursor.positionInBlock(); |
| 1180 |
if (pos < end) { |
| 1181 |
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, end - pos); |
| 1182 |
} |
| 1183 |
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, end - start); |
| 1184 |
|
| 1185 |
Base::FlagToggler<bool> flag(block, false); |
| 1186 |
cursor.insertText(completionPrefix); |
| 1187 |
completer->updatePrefixEnd(cursor.positionInBlock()); |
| 1188 |
|
| 1189 |
// chain completions only when activated (Enter/Click), not when highlighted (arrow keys) |
| 1190 |
if (mode == ActivationMode::Activated) { |
| 1191 |
std::string textToComplete = completionPrefix.toUtf8().constData(); |
| 1192 |
if (!textToComplete.empty() |
| 1193 |
&& (*textToComplete.crbegin() == '.' || *textToComplete.crbegin() == '#')) { |
| 1194 |
completer->slotUpdate(cursor.block().text(), cursor.positionInBlock()); |
| 1195 |
} |
| 1196 |
} |
| 1197 |
} |
| 1198 |
|
| 1199 |
void ExpressionTextEdit::slotCompleteTextHighlighted(const QString& completionPrefix) |
| 1200 |
{ |
| 1201 |
slotCompleteText(completionPrefix, ActivationMode::Highlighted); |
| 1202 |
} |
| 1203 |
|
| 1204 |
void ExpressionTextEdit::slotCompleteTextSelected(const QString& completionPrefix) |
| 1205 |
{ |
| 1206 |
slotCompleteText(completionPrefix, ActivationMode::Activated); |
| 1207 |
} |
| 1208 |
|
| 1209 |
void ExpressionTextEdit::keyPressEvent(QKeyEvent* e) |
| 1210 |
{ |
| 1211 |
Base::FlagToggler<bool> flag(block, true); |
| 1212 |
|
| 1213 |
// Shift+Enter - insert a new line |
| 1214 |
if ((e->modifiers() & Qt::ShiftModifier) |
| 1215 |
&& (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)) { |
| 1216 |
this->setPlainText(this->toPlainText() + QLatin1Char('\n')); |
| 1217 |
this->moveCursor(QTextCursor::End); |
| 1218 |
if (completer) { |
| 1219 |
completer->popup()->setVisible(false); |
| 1220 |
} |
| 1221 |
e->accept(); |
| 1222 |
return; |
| 1223 |
} |
| 1224 |
|
| 1225 |
// handling if completer is visible |
| 1226 |
if (completer && completer->popup()->isVisible()) { |
| 1227 |
switch (e->key()) { |
| 1228 |
case Qt::Key_Enter: |
| 1229 |
case Qt::Key_Return: |
| 1230 |
case Qt::Key_Escape: |
| 1231 |
case Qt::Key_Backtab: |
| 1232 |
// default action |
| 1233 |
e->ignore(); |
| 1234 |
return; |
| 1235 |
|
| 1236 |
case Qt::Key_Tab: |
| 1237 |
// if no completion is selected, take top one |
| 1238 |
if (!completer->popup()->currentIndex().isValid()) { |
| 1239 |
completer->popup()->setCurrentIndex(completer->popup()->model()->index(0, 0)); |
| 1240 |
} |
| 1241 |
completer->setCurrentRow(completer->popup()->currentIndex().row()); |
| 1242 |
slotCompleteText(completer->currentCompletion(), ActivationMode::Highlighted); |
| 1243 |
|
| 1244 |
// refresh completion list |
| 1245 |
completer->setCompletionPrefix(completer->currentCompletion()); |
| 1246 |
adjustCompleterToCursor(); |
| 1247 |
if (completer->completionCount() == 1) { |
| 1248 |
completer->popup()->setVisible(false); |
| 1249 |
} |
| 1250 |
e->accept(); |
| 1251 |
return; |
| 1252 |
|
| 1253 |
default: |
| 1254 |
break; |
| 1255 |
} |
| 1256 |
} |
| 1257 |
|
| 1258 |
// Enter, Return or Tab - request default action |
| 1259 |
if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return || e->key() == Qt::Key_Tab) { |
| 1260 |
e->ignore(); |
| 1261 |
return; |
| 1262 |
} |
| 1263 |
|
| 1264 |
QPlainTextEdit::keyPressEvent(e); |
| 1265 |
} |
| 1266 |
|
| 1267 |
void ExpressionTextEdit::contextMenuEvent(QContextMenuEvent* event) |
| 1268 |
{ |
| 1269 |
QMenu* menu = createStandardContextMenu(); |
| 1270 |
menu->addSeparator(); |
| 1271 |
QAction* match = menu->addAction(tr("Exact Match")); |
| 1272 |
|
| 1273 |
if (completer) { |
| 1274 |
match->setCheckable(true); |
| 1275 |
match->setChecked(completer->filterMode() == Qt::MatchStartsWith); |
| 1276 |
} |
| 1277 |
else { |
| 1278 |
match->setVisible(false); |
| 1279 |
} |
| 1280 |
|
| 1281 |
QAction* action = menu->exec(event->globalPos()); |
| 1282 |
|
| 1283 |
if (completer) { |
| 1284 |
if (action == match) { |
| 1285 |
setExactMatch(match->isChecked()); |
| 1286 |
} |
| 1287 |
} |
| 1288 |
|
| 1289 |
delete menu; |
| 1290 |
} |
| 1291 |
|
| 1292 |
void ExpressionTextEdit::adjustCompleterToCursor() |
| 1293 |
{ |
| 1294 |
if (!completer || !completer->popup()) { |
| 1295 |
return; |
| 1296 |
} |
| 1297 |
|
| 1298 |
const int completionsCount = completer->completionModel()->rowCount(); |
| 1299 |
if (!completionsCount) { |
| 1300 |
return; |
| 1301 |
} |
| 1302 |
|
| 1303 |
// get longest string width |
| 1304 |
int maxCompletionWidth = 0; |
| 1305 |
for (int i = 0; i < completionsCount; ++i) { |
| 1306 |
const QModelIndex index = completer->completionModel()->index(i, 0); |
| 1307 |
const QString element = completer->completionModel()->data(index).toString(); |
| 1308 |
maxCompletionWidth = std::max( |
| 1309 |
maxCompletionWidth, |
| 1310 |
static_cast<int>(element.size()) * completer->popup()->fontMetrics().averageCharWidth() |
| 1311 |
); |
| 1312 |
} |
| 1313 |
if (maxCompletionWidth == 0) { |
| 1314 |
return; // no completions available |
| 1315 |
} |
| 1316 |
|
| 1317 |
const QPoint cursorPos = cursorRect(textCursor()).topLeft(); |
| 1318 |
int posX = cursorPos.x(); |
| 1319 |
int posY = cursorPos.y(); |
| 1320 |
|
| 1321 |
constexpr double popupLengthRatio = 0.6; // popup shall not be longer than 0.6 of |
| 1322 |
// TextEdit length |
| 1323 |
const int widthLimit = static_cast<int>(this->viewport()->width() * popupLengthRatio); |
| 1324 |
completer->popup()->setMaximumWidth(widthLimit); |
| 1325 |
maxCompletionWidth = std::min(maxCompletionWidth, widthLimit); |
| 1326 |
|
| 1327 |
QScreen* screen = QGuiApplication::primaryScreen(); |
| 1328 |
// looking for screen on which popup appears |
| 1329 |
const int cursorGlobalY = mapToGlobal(cursorPos).y(); |
| 1330 |
for (QScreen* elem : QGuiApplication::screens()) { |
| 1331 |
const int screenTopY = elem->geometry().top(); |
| 1332 |
const int screenBottomY = elem->geometry().bottom(); |
| 1333 |
|
| 1334 |
if (cursorGlobalY >= screenTopY && cursorGlobalY < screenBottomY) { |
| 1335 |
screen = elem; |
| 1336 |
break; |
| 1337 |
} |
| 1338 |
} |
| 1339 |
|
| 1340 |
constexpr double marginToScreen = 0.05; // margin to screen as percent of screen |
| 1341 |
// height; keep 5% margin to screen edge |
| 1342 |
constexpr int rowsLimit = 20; // max. count of rows that shall be shown at once |
| 1343 |
|
| 1344 |
const int rowHeight = completer->popup()->fontMetrics().height(); |
| 1345 |
int rowsToEdge = static_cast<int>( |
| 1346 |
(screen->geometry().bottom() * (1.0 - marginToScreen) |
| 1347 |
- (mapToGlobal(cursorPos).y() + rowHeight)) |
| 1348 |
/ rowHeight |
| 1349 |
); |
| 1350 |
const auto adjustHeight = [&rowHeight, &completionsCount](const int _rowsToEdge) -> int { |
| 1351 |
return std::min({ |
| 1352 |
rowHeight * rowsLimit, // up to 'rowsLimit' elements shall be shown at once |
| 1353 |
_rowsToEdge * rowHeight, // or less limited to screen edge |
| 1354 |
completionsCount * rowHeight + 5 // or all, if only there are only few; 5 is magic |
| 1355 |
// number, somehow last entry is partly hovered |
| 1356 |
}); |
| 1357 |
}; |
| 1358 |
|
| 1359 |
int adjustedPopupHeight = adjustHeight(rowsToEdge); |
| 1360 |
|
| 1361 |
// vertical correction to cursor |
| 1362 |
if (rowsToEdge < 4) { |
| 1363 |
// display above cursor |
| 1364 |
rowsToEdge = static_cast<int>( |
| 1365 |
mapToGlobal(cursorPos).y() - screen->geometry().height() * marginToScreen |
| 1366 |
); |
| 1367 |
adjustedPopupHeight = adjustHeight(rowsToEdge); |
| 1368 |
posY -= adjustedPopupHeight; |
| 1369 |
} |
| 1370 |
else { |
| 1371 |
// display under cursor |
| 1372 |
posY += rowHeight; |
| 1373 |
} |
| 1374 |
|
| 1375 |
const QSize completerSize {maxCompletionWidth + 40, adjustedPopupHeight}; // 40 is margin for |
| 1376 |
// scrollbar |
| 1377 |
|
| 1378 |
// horizontal correction to cursor |
| 1379 |
if (posX + completerSize.width() > viewport()->width()) { |
| 1380 |
posX = viewport()->width() - completerSize.width(); |
| 1381 |
} |
| 1382 |
|
| 1383 |
completer->popup()->resize(completerSize); |
| 1384 |
completer->popup()->move(mapToGlobal(QPoint {posX, posY})); |
| 1385 |
completer->popup()->setVisible(true); |
| 1386 |
} |
| 1387 |
|
| 1388 |
/////////////////////////////////////////////////////////////////////// |
| 1389 |
|
| 1390 |
ExpressionParameter* ExpressionParameter::instance() |
| 1391 |
{ |
| 1392 |
static auto inst = new ExpressionParameter(); |
| 1393 |
return inst; |
| 1394 |
} |
| 1395 |
|
| 1396 |
bool ExpressionParameter::isCaseSensitive() const |
| 1397 |
{ |
| 1398 |
auto handle = GetApplication().GetParameterGroupByPath( |
| 1399 |
"User parameter:BaseApp/Preferences/Expression" |
| 1400 |
); |
| 1401 |
return handle->GetBool("CompleterCaseSensitive", false); |
| 1402 |
} |
| 1403 |
|
| 1404 |
bool ExpressionParameter::isExactMatch() const |
| 1405 |
{ |
| 1406 |
auto handle = GetApplication().GetParameterGroupByPath( |
| 1407 |
"User parameter:BaseApp/Preferences/Expression" |
| 1408 |
); |
| 1409 |
return handle->GetBool("CompleterMatchExact", false); |
| 1410 |
} |
| 1411 |
|
| 1412 |
#include "moc_ExpressionCompleter.cpp" |