File size: 11,961 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 | /****************************************************************************
**
** This file is part of the LibreCAD project, a 2D CAD program
**
** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
** Copyright (C) 2016 ravas (github.com/r-a-v-a-s)
**
** 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 <QClipboard>
#include <QFile>
#include <QKeyEvent>
#include <QRegularExpression>
#include "qg_commandedit.h"
#include "rs_dialogfactory.h"
#include "rs_dialogfactoryinterface.h"
#include "rs_math.h"
#include "rs_settings.h"
namespace {
// Limits for command file reading
// limit for the number of lines read together
constexpr unsigned g_maxLinesToRead = 10240;
// the maximum line length allowed
constexpr unsigned g_maxLineLength = 4096;
// returns true, if value exists, evaluated and printed to output
bool calculatorEvaluation(const QString& input){
int pos = input.indexOf(' ');
if (pos == -1)
pos = input.indexOf(':');
if (pos == -1)
return false;
QString expression = input.mid(pos);
if (expression.isEmpty())
return false;
bool okay=false;
double value = RS_Math::eval(expression, &okay);
if (okay) {
RS_DIALOGFACTORY->commandMessage(QObject::tr("Calculator: ") + expression
+ QString{" = %1"}.arg(value, 0, 'g', 10));
}
return okay;
}
}
/**
* Default Constructor. You must call init manually if you choose
* to use this constructor.
*/
QG_CommandEdit::QG_CommandEdit(QWidget* parent)
: QLineEdit(parent)
, m_keycode_mode(false)
, m_relative_ray("none")
, m_calculator_mode(false)
{
#ifndef DONT_FORCE_WIDGETS_CSS
setStyleSheet("selection-color: white; selection-background-color: green;");
#endif
setFrame(false);
setFocusPolicy(Qt::StrongFocus);
}
/**
* Bypass for key press events from the tab key.
*/
bool QG_CommandEdit::event(QEvent* e) {
if (e != nullptr && e->type()==QEvent::KeyPress) {
QKeyEvent* k = static_cast<QKeyEvent*>(e);
switch(k->key()) {
case Qt::Key_Tab:
emit tabPressed();
return true;
// case Qt::Key_Space:
// if (RS_SETTINGS->readNumEntry("/Keyboard/ToggleFreeSnapOnSpace", false)) {
// emit spacePressed();
// }
// break;
default:
break;
}
}
return QLineEdit::event(e);
}
/**
* History (arrow key up/down) support, tab.
*/
void QG_CommandEdit::keyPressEvent(QKeyEvent* e) {
if (e->modifiers() & Qt::ControlModifier) {
auto value = text();
if (value.isEmpty())
value = m_relative_ray;
QString r_string;
switch (e->key()) {
case Qt::Key_Up:
r_string = "0," + value;
break;
case Qt::Key_Down:
r_string = "0,-" + value;
break;
case Qt::Key_Right:
r_string = value + ",0";
break;
case Qt::Key_Left:
r_string = "-" + value + ",0";
break;
default:
QLineEdit::keyPressEvent(e);
return;
}
// r_string is empty when Ctrl is pressed
if (!r_string.isEmpty()) {
if (value == "none") {
emit message(
QObject::tr("You must input a distance first.")
);
}
else {
m_relative_ray = value;
emit command("@" + r_string);
}
}
return;
}
switch (e->key()) {
case Qt::Key_Up:
if (!m_historyList.isEmpty() && it > m_historyList.begin()) {
it--;
setText(*it);
}
break;
case Qt::Key_Down:
if (!m_historyList.isEmpty() && it < m_historyList.end()) {
it++;
if (it < m_historyList.end()) {
setText(*it);
}
else {
setText("");
}
}
break;
case Qt::Key_Enter:
case Qt::Key_Return:
processInput(text());
break;
case Qt::Key_Space:
if (LC_GET_ONE_BOOL("Keyboard","EvaluateCommandOnSpace", false)) {
processInput(text());
}
else if (!text().isEmpty()) {
QLineEdit::keyPressEvent(e);
}
break;
case Qt::Key_Escape:
if (text().isEmpty()) {
emit escape();
}
else {
setText("");
}
break;
default:
QLineEdit::keyPressEvent(e);
break;
}
if (m_keycode_mode) {
auto input = text();
if (input.size() == 2) {
emit keycode(input);
}
}
}
void QG_CommandEdit::evaluateExpression(QString input) {
static QRegularExpression regex(R"~(([\d\.]+)deg|d)~");
input.replace(regex, R"~(\1*pi/180)~");
bool ok = true;
double result = RS_Math::eval(input, &ok);
if (ok)
emit message(input + " = " + QString::number(result, 'g', 12));
else
emit message(QObject::tr("Calculator error for input: ") + input);
}
void QG_CommandEdit::focusInEvent(QFocusEvent *e) {
emit focusIn();
QLineEdit::focusInEvent(e);
}
void QG_CommandEdit::focusOutEvent(QFocusEvent *e) {
emit focusOut();
QLineEdit::focusOutEvent(e);
}
void QG_CommandEdit::processInput(QString input) {
// author: ravas
// convert 10..0 to @10,0
QRegularExpression regex(R"~(([-\w\.\\]+)\.\.)~");
input.replace(regex, "@\\1,");
if (isForeignCommand(input)) {
if (input.contains(";")) {
foreach(auto str, input.split(";")) {
if (str.contains("\\"))
processVariable(str);
else
emit command(str);
}
}
else {
if (input.contains("\\"))
processVariable(input);
else
emit command(input);
}
m_historyList.append(input);
it = m_historyList.end();
}
else if (input == "") {
emit command("");
}
clear();
}
/**
* @brief extractCliCal, filter cli calculator math expression
* @param cmd, cli string
* @return empty string, if calculation is performed; the input string, otherwise
*/
QString QG_CommandEdit::filterCliCal(const QString& cmd) {
QString str = cmd.trimmed();
static const QRegularExpression calCmd(R"(^\s*(cal|calculate)\s?)", QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = calCmd.match(str);
if (!(match.hasMatch()
|| str.startsWith(QObject::tr("cal ", "command to trigger cli calculator"), Qt::CaseInsensitive)
|| str.startsWith(QObject::tr("calculate ", "command to trigger cli calculator"), Qt::CaseInsensitive)
)) {
return cmd;
}
int index = match.capturedEnd(0);
bool spaceFound = (index >= 0);
str = str.mid(index);
static QRegularExpression reSpace(R"(\S)");
index = str.indexOf(reSpace);
if (!(spaceFound && index >= 0))
return cmd;
str = str.mid(index);
if (!str.isEmpty()) {
// Do calculation
bool okay = false;
double result = RS_Math::eval(str, &okay);
if (okay) {
emit message(QString("%1 =%2").arg(str).arg(result, 12, 'g'));
return {};
}
}
return cmd;
}
bool QG_CommandEdit::isForeignCommand(QString input) {
// author: ravas
bool r_value = true;
if (input == tr("clear")) {
emit clearCommandsHistory();
r_value = false;
}
else if ((input = filterCliCal(input)).isEmpty()) {
r_value = false;
}
else if (input.startsWith(QObject::tr("cal"))) {
// Allow inline calculation. Tweak the calculator mode only if there's
// no expression after "cal " or "cal:"
if (!calculatorEvaluation(input)) {
m_calculator_mode = !m_calculator_mode;
if (m_calculator_mode)
emit message(QObject::tr("Calculator mode: On"));
else
emit message(QObject::tr("Calculator mode: Off"));
}
r_value = false;
}
else if (m_calculator_mode) {
evaluateExpression(input);
r_value = false;
}
else if (input.contains("=")) {
auto var_value = input.split("=");
m_variables[var_value[0]] = var_value[1];
r_value = false;
}
return r_value;
}
void QG_CommandEdit::processVariable(QString input) {
// author: ravas
if (input.contains(",")) {
QString rel = "";
if (input.contains("@")) {
rel = "@";
input.remove("@");
}
auto x_y = input.split(",");
if (x_y[0].contains("\\")) {
x_y[0].remove("\\");
if (m_variables.contains(x_y[0]))
x_y[0] = m_variables[x_y[0]];
}
if (x_y[1].contains("\\")) {
x_y[1].remove("\\");
if (m_variables.contains(x_y[1]))
x_y[1] = m_variables[x_y[1]];
}
emit command(rel + x_y[0] + "," + x_y[1]);
return;
}
input.remove("\\");
if (m_variables.contains(input)) {
input = m_variables[input];
if (input.contains(";")) {
foreach(auto str, input.split(";")) {
if (str.contains("\\"))
processVariable(str);
else
emit command(str);
}
}
else emit command(input);
}
}
void QG_CommandEdit::readCommandFile(const QString& path) {
// author: ravas
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
// keep the pos of the read part
size_t pos = 0;
bool ended = false;
while (!ended) {
if (!file.isOpen()) {
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
break;
file.skip(pos);
}
// read lines to buffer and close the file immediately
QTextStream txt_stream(&file);
QStringList lines;
for (unsigned i = 0; i < g_maxLinesToRead; ++i) {
if (txt_stream.atEnd())
break;
lines << txt_stream.readLine(g_maxLineLength);
}
ended = txt_stream.atEnd();
pos = txt_stream.pos();
// Issue #1803: close the file to avoid blocking command loading
file.close();
// Process the commands while the file is closed
for (QString line : lines) {
line.remove(" ");
if (!line.startsWith("#"))
processInput(line);
}
}
}
void QG_CommandEdit::modifiedPaste() {
auto txt = qApp->clipboard()->text();
txt.replace("\n", ";");
setText(txt);
}
|