File size: 31,599 Bytes
985c397 | 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 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 | # SPDX-License-Identifier: LGPL-2.1-or-later
# ***************************************************************************
# * Copyright (c) 2022 Zheng Lei (realthunder) <realthunder.dev@gmail.com>*
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Utilities for generating C++ code for parameter management using Python Cog"""
import cog
import inspect
import re
from os import path
def quote(txt, indent=0):
lines = [
" " * indent + '"' + l.replace("\\", "\\\\").replace('"', '\\"') for l in txt.split("\n")
]
return '\\n"\n'.join(lines) + '"'
def init_params(params, namespace, class_name, param_path, header_file=None):
for param in params:
param.path = param_path
if not header_file:
header_file = [f"{namespace}/{class_name}.h"]
param.header_file = header_file + getattr(param.proxy, "header_file", [])
param.namespace = namespace
param.class_name = class_name
return params
def auto_comment(frame=1, msg=None, count=1):
trace = []
for stack in inspect.stack()[frame : frame + count]:
filename = path.normpath(stack[1]).split("/src/")[-1]
if filename.find("<") >= 0:
break
lineno = stack[2]
trace.insert(0, f"{filename}:{lineno}")
return f'{"// Auto generated code" if msg is None else msg} ({" <- ".join(trace)})'
def trace_comment():
return auto_comment(2)
def get_module_path(module):
return path.dirname(module.__file__.split(f"src{path.sep}")[-1])
def declare_begin(module, header=True):
class_name = module.ClassName
namespace = module.NameSpace
params = module.Params
param_path = module.ParamPath
file_path = getattr(module, "FilePath", get_module_path(module))
param_file = getattr(module, "ParamSource", f"{file_path}/{class_name}.py")
header_file = getattr(module, "HeaderFile", f"{file_path}/{class_name}.h")
source_file = getattr(module, "SourceFile", f"{file_path}/{class_name}.cpp")
class_doc = module.ClassDoc
signal = getattr(module, "Signal", False)
if header:
cog.out(
f"""
{trace_comment()}
#include <Base/Parameter.h>
{"#include <fastsignals/signal.h>" if signal else ""}
"""
)
cog.out(
f"""
{trace_comment()}
namespace {namespace} {{
/** {class_doc}
* The parameters are under group "{param_path}"
*
* This class is auto generated by {param_file}. Modify that file
* instead of this one, if you want to add any parameter. You need
* to install Cog Python package for code generation:
* @code
* pip install cogapp
* @endcode
*
* Once modified, you can regenerate the header and the source file,
* @code
* python3 -m cogapp -r {header_file} {source_file}
* @endcode
*
* You can add a new parameter by adding lines in {param_file}. Available
* parameter types are 'Int, UInt, String, Bool, Float'. For example, to add
* a new Int type parameter,
* @code
* ParamInt(parameter_name, default_value, documentation, on_change=False)
* @endcode
*
* If there is special handling on parameter change, pass in on_change=True.
* And you need to provide a function implementation in {source_file} with
* the following signature.
* @code
* void {class_name}:on<parameter_name>Changed()
* @endcode
*/
class {namespace}Export {class_name} {{
public:
static ParameterGrp::handle getHandle();
"""
)
if signal:
cog.out(
f"""
static fastsignals::signal<void (const char*)> &signalParamChanged();
static void signalAll();
"""
)
for param in params:
cog.out(
f"""
{trace_comment()}
//@{{
/// Accessor for parameter {param.name}"""
)
if param._doc:
cog.out(
f"""
///"""
)
for line in param._doc.split("\n"):
cog.out(
f"""
/// {line}"""
)
cog.out(
f"""
static const {param.C_Type} & get{param.name}();
static const {param.C_Type} & default{param.name}();
static void remove{param.name}();
static void set{param.name}(const {param.C_Type} &v);
static const char *doc{param.name}();"""
)
if param.on_change:
cog.out(
f"""
static void on{param.name}Changed();"""
)
cog.out(
f"""
//@}}
"""
)
def declare_end(module):
class_name = module.ClassName
namespace = module.NameSpace
cog.out(
f"""
{trace_comment()}
}}; // class {class_name}
}} // namespace {namespace}
"""
)
def define(module, header=True):
class_name = module.ClassName
namespace = module.NameSpace
params = module.Params
param_path = module.ParamPath
class_doc = module.ClassDoc
signal = getattr(module, "Signal", False)
if header:
cog.out(
f"""
{trace_comment()}
#include <unordered_map>
#include <App/Application.h>
#include <App/DynamicProperty.h>
#include "{class_name}.h"
using namespace {namespace};
"""
)
cog.out(
f"""
{trace_comment()}
namespace {{
class {class_name}P: public ParameterGrp::ObserverType {{
public:
ParameterGrp::handle handle;
std::unordered_map<const char *,void(*)({class_name}P*),App::CStringHasher,App::CStringHasher> funcs;
"""
)
if signal:
cog.out(
f"""
{trace_comment()}
fastsignals::signal<void (const char*)> signalParamChanged;
void signalAll()
{{"""
)
for param in params:
cog.out(
f"""
signalParamChanged("{param.name}");"""
)
cog.out(
f"""
{trace_comment()}
}}"""
)
for param in params:
cog.out(
f"""
{param.C_Type} {param.name};"""
)
cog.out(
f"""
{trace_comment()}
{class_name}P() {{
handle = App::GetApplication().GetParameterGroupByPath("{param_path}");
handle->Attach(this);
"""
)
for param in params:
cog.out(
f"""
{param.name} = {param.getter('handle')};
funcs["{param.name}"] = &{class_name}P::update{param.name};"""
)
cog.out(
f"""
}}
{trace_comment()}
~{class_name}P() {{
}}
"""
)
cog.out(
f"""
{trace_comment()}
void OnChange(Base::Subject<const char*> &, const char* sReason) {{
if(!sReason)
return;
auto it = funcs.find(sReason);
if(it == funcs.end())
return;
it->second(this);
{"signalParamChanged(sReason);" if signal else ""}
}}
"""
)
for param in params:
if not param.on_change:
cog.out(
f"""
{trace_comment()}
static void update{param.name}({class_name}P *self) {{
self->{param.name} = {param.getter('self->handle')};
}}"""
)
else:
cog.out(
f"""
{trace_comment()}
static void update{param.name}({class_name}P *self) {{
auto v = {param.getter('self->handle')};
if (self->{param.name} != v) {{
self->{param.name} = v;
{class_name}::on{param.name}Changed();
}}
}}"""
)
cog.out(
f"""
}};
{trace_comment()}
{class_name}P *instance() {{
static {class_name}P *inst = new {class_name}P;
return inst;
}}
}} // Anonymous namespace
"""
)
cog.out(
f"""
{trace_comment()}
ParameterGrp::handle {class_name}::getHandle() {{
return instance()->handle;
}}
"""
)
if signal:
cog.out(
f"""
{trace_comment()}
fastsignals::signal<void (const char*)> &
{class_name}::signalParamChanged() {{
return instance()->signalParamChanged;
}}
"""
)
cog.out(
f"""
{trace_comment()}
void signalAll() {{
instance()->signalAll();
}}
"""
)
for param in params:
cog.out(
f"""
{trace_comment()}
const char *{class_name}::doc{param.name}() {{
return {param.doc(class_name)};
}}
"""
)
cog.out(
f"""
{trace_comment()}
const {param.C_Type} & {class_name}::get{param.name}() {{
return instance()->{param.name};
}}
"""
)
cog.out(
f"""
{trace_comment()}
const {param.C_Type} & {class_name}::default{param.name}() {{
const static {param.C_Type} def = {param.default};
return def;
}}
"""
)
cog.out(
f"""
{trace_comment()}
void {class_name}::set{param.name}(const {param.C_Type} &v) {{
{param.setter()};
instance()->{param.name} = v;
}}
"""
)
cog.out(
f"""
{trace_comment()}
void {class_name}::remove{param.name}() {{
instance()->handle->Remove{param.Type}("{param.name}");
}}
"""
)
def widgets_declare(param_set):
param_group = param_set.ParamGroup
for title, params in param_group:
name = _regex.sub("", title)
cog.out(
f"""
{trace_comment()}
QGroupBox * group{name} = nullptr;"""
)
for param in params:
param.declare_widget()
def widgets_init(param_set):
param_group = param_set.ParamGroup
cog.out(
f"""
auto layout = new QVBoxLayout(this);"""
)
for title, params in param_group:
name = _regex.sub("", title)
cog.out(
f"""
{trace_comment()}
group{name} = new QGroupBox(this);
layout->addWidget(group{name});
auto layoutHoriz{name} = new QHBoxLayout(group{name});
auto layout{name} = new QGridLayout();
layoutHoriz{name}->addLayout(layout{name});
layoutHoriz{name}->addStretch();"""
)
for row, param in enumerate(params):
cog.out(
f"""
{trace_comment()}"""
)
param.init_widget(row, name)
cog.out(
"""
layout->addItem(new QSpacerItem(40, 20, QSizePolicy::Fixed, QSizePolicy::Expanding));
retranslateUi();"""
)
def widgets_restore(param_set):
param_group = param_set.ParamGroup
cog.out(
f"""
{trace_comment()}"""
)
for _, params in param_group:
for param in params:
param.widget_restore()
def widgets_save(param_set):
param_group = param_set.ParamGroup
cog.out(
f"""
{trace_comment()}"""
)
for _, params in param_group:
for param in params:
param.widget_save()
def preference_dialog_declare_begin(param_set, header=True):
namespace = param_set.NameSpace
class_name = param_set.ClassName
dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog")
param_group = param_set.ParamGroup
file_path = getattr(param_set, "FilePath", get_module_path(param_set))
param_file = getattr(param_set, "ParamSource", f"{file_path}/{class_name}.py")
header_file = getattr(param_set, "HeaderFile", f"{file_path}/{class_name}.h")
source_file = getattr(param_set, "SourceFile", f"{file_path}/{class_name}.cpp")
class_doc = param_set.ClassDoc
if header:
cog.out(
f"""
{trace_comment()}
#include <Gui/PropertyPage.h>
#include <Gui/PrefWidgets.h>"""
)
cog.out(
f"""
{trace_comment()}
class QLabel;
class QGroupBox;
namespace {namespace} {{
namespace {dialog_namespace} {{
/** {class_doc}
* This class is auto generated by {param_file}. Modify that file
* instead of this one, if you want to make any change. You need
* to install Cog Python package for code generation:
* @code
* pip install cogapp
* @endcode
*
* Once modified, you can regenerate the header and the source file,
* @code
* python3 -m cogapp -r {header_file} {source_file}
* @endcode
*/
class {class_name} : public Gui::Dialog::PreferencePage
{{
Q_OBJECT
public:
{class_name}( QWidget* parent = 0 );
~{class_name}();
void saveSettings();
void loadSettings();
void retranslateUi();
protected:
void changeEvent(QEvent *e);
private:"""
)
widgets_declare(param_set)
def preference_dialog_declare_end(param_set):
class_name = param_set.ClassName
namespace = param_set.NameSpace
dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog")
cog.out(
f"""
{trace_comment()}
}};
}} // namespace {dialog_namespace}
}} // namespace {namespace}
"""
)
def preference_dialog_declare(param_set, header=True):
preference_dialog_declare_begin(param_set, header)
preference_dialog_declare_end(param_set)
_regex = re.compile(r"[^a-zA-Z_]")
def preference_dialog_define(param_set, header=True):
param_group = param_set.ParamGroup
class_name = param_set.ClassName
dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog")
namespace = f"{param_set.NameSpace}::{dialog_namespace}"
file_path = getattr(param_set, "FilePath", get_module_path(param_set))
param_file = getattr(param_set, "ParamSource", f"{file_path}/{class_name}.py")
header_file = getattr(param_set, "HeaderFile", f"{file_path}/{class_name}.h")
source_file = getattr(param_set, "SourceFile", f"{file_path}/{class_name}.cpp")
user_init = getattr(param_set, "UserInit", "")
headers = set()
if header:
cog.out(
f"""
{trace_comment()}
# include <QApplication>
# include <QLabel>
# include <QGroupBox>
# include <QGridLayout>
# include <QVBoxLayout>
# include <QHBoxLayout>
"""
)
for _, params in param_group:
for param in params:
for header in param.header_file:
if header not in headers:
headers.add(header)
cog.out(
f"""
#include <{header}>"""
)
cog.out(
f"""
{trace_comment()}
#include "{header_file}"
using namespace {namespace};
/* TRANSLATOR {namespace}::{class_name} */
"""
)
cog.out(
f"""
{trace_comment()}
{class_name}::{class_name}(QWidget* parent)
: PreferencePage( parent )
{{
"""
)
widgets_init(param_set)
cog.out(
f"""
{trace_comment()}
{user_init}
}}
"""
)
cog.out(
f"""
{trace_comment()}
{class_name}::~{class_name}()
{{
}}
"""
)
cog.out(
f"""
{trace_comment()}
void {class_name}::saveSettings()
{{"""
)
widgets_save(param_set)
cog.out(
f"""
}}
{trace_comment()}
void {class_name}::loadSettings()
{{"""
)
widgets_restore(param_set)
cog.out(
f"""
}}
{trace_comment()}
void {class_name}::retranslateUi()
{{
setWindowTitle(QObject::tr("{param_set.Title}"));"""
)
for title, params in param_group:
name = _regex.sub("", title)
cog.out(
f"""
group{name}->setTitle(QObject::tr("{title}"));"""
)
for row, param in enumerate(params):
param.retranslate()
cog.out(
f"""
}}
{trace_comment()}
void {class_name}::changeEvent(QEvent *e)
{{
if (e->type() == QEvent::LanguageChange) {{
retranslateUi();
}}
QWidget::changeEvent(e);
}}
"""
)
cog.out(
f"""
{trace_comment()}
#include "moc_{class_name}.cpp"
"""
)
_ParamPrefix = "User parameter:BaseApp/Preferences/"
class Param:
WidgetPrefix = ""
def __init__(self, name, default, doc="", title="", on_change=False, proxy=None, **kwd):
self.name = name
self.title = title if title else name
self._default = default
self._doc = doc
self.on_change = on_change
self.proxy = proxy
def _declare_label(self):
cog.out(
f"""
QLabel *label{self.name} = nullptr;"""
)
def declare_label(self):
if self.proxy:
self.proxy.declare_label(self)
else:
self._declare_label()
def _init_label(self, row, group_name):
cog.out(
f"""
label{self.name} = new QLabel(this);
layout{group_name}->addWidget(label{self.name}, {row}, 0);"""
)
def init_label(self, row, group_name):
if self.proxy:
self.proxy.init_label(self, row, group_name)
else:
self._init_label(row, group_name)
def _declare_widget(self):
self.declare_label()
cog.out(
f"""
{self.widget_type} *{self.widget_name} = nullptr;"""
)
def declare_widget(self):
if self.proxy:
self.proxy.declare_widget(self)
else:
self._declare_widget()
def _init_widget(self, row, group_name):
self.init_label(row, group_name)
cog.out(
f"""
{self.widget_name} = new {self.widget_type}(this);
layout{group_name}->addWidget({self.widget_name}, {row}, {self.widget_column});"""
)
if self.widget_setter:
cog.out(
f"""
{self.widget_name}->{self.widget_setter}({self.namespace}::{self.class_name}::default{self.name}());"""
)
self._init_pref_widget()
def _init_pref_widget(self):
cog.out(
f"""
{self.widget_name}->setEntryName("{self.name}");"""
)
if self.path.startswith(_ParamPrefix):
cog.out(
f"""
{self.widget_name}->setParamGrpPath("{self.path[len(_ParamPrefix):]}");"""
)
else:
cog.out(
f"""
{self.widget_name}->setParamGrpPath("{self.path}");"""
)
def init_widget(self, row, group_name):
if self.proxy:
self.proxy.init_widget(self, row, group_name)
else:
self._init_widget(row, group_name)
def _widget_save(self):
cog.out(
f"""
{self.widget_name}->onSave();"""
)
def widget_save(self):
if self.proxy:
self.proxy.widget_save(self)
else:
self._widget_save()
def _widget_restore(self):
cog.out(
f"""
{self.widget_name}->onRestore();"""
)
def widget_restore(self):
if self.proxy:
self.proxy.widget_restore(self)
else:
self._widget_restore()
def _retranslate_label(self):
cog.out(
f"""
label{self.name}->setText(QObject::tr("{self.title}"));
label{self.name}->setToolTip({self.widget_name}->toolTip());"""
)
def retranslate_label(self):
if self.proxy:
self.proxy.retranslate_label(self)
else:
self._retranslate_label()
def _retranslate(self):
cog.out(
f"""
{self.widget_name}->setToolTip(QApplication::translate("{self.class_name}", {self.namespace}::{self.class_name}::doc{self.name}()));"""
)
self.retranslate_label()
def retranslate(self):
if self.proxy:
self.proxy.retranslate(self)
else:
self._retranslate()
@property
def default(self):
return self._default
def doc(self, class_name):
if not self._doc:
return '""'
return f"""QT_TRANSLATE_NOOP("{class_name}",
{quote(self._doc)})"""
@property
def widget_type(self):
if self.proxy:
return self.proxy.widget_type(self)
return self.WidgetType
@property
def widget_prefix(self):
if self.proxy:
return self.proxy.widget_prefix(self)
return self.WidgetPrefix
@property
def widget_setter(self):
if self.proxy:
return self.proxy.widget_setter(self)
return self.WidgetSetter
@property
def widget_name(self):
return f"{self.widget_prefix}{self.name}"
@property
def widget_column(self):
return 1
def getter(self, handle):
return f'{handle}->Get{self.Type}("{self.name}", {self.default})'
def setter(self):
return f'instance()->handle->Set{self.Type}("{self.name}",v)'
class ParamBool(Param):
Type = "Bool"
C_Type = "bool"
WidgetType = "Gui::PrefCheckBox"
WidgetSetter = "setChecked"
@property
def default(self):
if isinstance(self._default, str):
return self._default
return "true" if self._default else "false"
def _declare_label(self):
pass
def _init_label(self, _row, _group_name):
pass
@property
def widget_column(self):
return 0
def _retranslate_label(self):
cog.out(
f"""
{self.widget_name}->setText(QObject::tr("{self.title}"));"""
)
class ParamFloat(Param):
Type = "Float"
C_Type = "double"
WidgetType = "Gui::PrefDoubleSpinBox"
WidgetSetter = "setValue"
class ParamString(Param):
Type = "ASCII"
C_Type = "std::string"
WidgetType = "Gui::PrefLineEdit"
WidgetSetter = "setText"
@property
def default(self):
return f'"{self._default}"'
class ParamQString(Param):
Type = "ASCII"
C_Type = "QString"
WidgetType = "Gui::PrefLineEdit"
WidgetSetter = "setText"
@property
def default(self):
return f'QStringLiteral("{self._default}")'
def getter(self, handle):
return (
f'QString::fromUtf8({handle}->Get{self.Type}("{self.name}", "{self._default}").c_str())'
)
def setter(self):
return f'instance()->handle->Set{self.Type}("{self.name}",v.toUtf8().constData())'
class ParamInt(Param):
Type = "Int"
C_Type = "long"
WidgetType = "Gui::PrefSpinBox"
WidgetSetter = "setValue"
class ParamUInt(Param):
Type = "Unsigned"
C_Type = "unsigned long"
WidgetType = "Gui::PrefSpinBox"
WidgetSetter = "setValue"
class ParamHex(ParamUInt):
@property
def default(self):
return "0x%08X" % self._default
class ParamProxy:
WidgetType = None
WidgetPrefix = ""
WidgetSetter = None
def __init__(self, param_bool=None):
self.param_bool = param_bool
def declare_label(self, param):
if not self.param_bool:
param._declare_label()
def widget_prefix(self, param):
return self.WidgetPrefix if self.WidgetPrefix else param.WidgetPrefix
def widget_type(self, param):
return self.WidgetType if self.WidgetType else param.WidgetType
def widget_setter(self, param):
return self.WidgetSetter if self.WidgetSetter else param.WidgetSetter
def declare_widget(self, param):
if self.param_bool:
self.param_bool.declare_widget()
param._declare_widget()
def init_label(self, param, row, group_name):
if not self.param_bool:
param._init_label(row, group_name)
def init_widget(self, param, row, group_name):
param._init_widget(row, group_name)
if self.param_bool:
self.param_bool.init_widget(row, group_name)
cog.out(
f"""
{param.widget_name}->setEnabled({self.param_bool.widget_name}->isChecked());
connect({self.param_bool.widget_name}, SIGNAL(toggled(bool)), {param.widget_name}, SLOT(setEnabled(bool)));"""
)
def retranslate_label(self, param):
if not self.param_bool:
param._retranslate_label()
def retranslate(self, param):
param._retranslate()
if self.param_bool:
self.param_bool.retranslate()
def widget_save(self, param):
param._widget_save()
if self.param_bool:
self.param_bool.widget_save()
def widget_restore(self, param):
param._widget_restore()
if self.param_bool:
self.param_bool.widget_restore()
class ComboBoxItem:
def __init__(self, text, tooltips=None, data=None):
self.text = text
self.tooltips = tooltips
self._data = data
@property
def data(self):
if self._data is None:
return "QVariant()"
if isinstance(self._data, str):
return f'QByteArray("{self._data}")'
return self._data
class ParamComboBox(ParamProxy):
WidgetType = "Gui::PrefComboBox"
def __init__(self, items, translate=True, param_bool=None):
super().__init__(param_bool)
self.translate = translate
self.items = []
for item in items:
if isinstance(item, str):
item = ComboBoxItem(item)
elif isinstance(item, tuple):
item = ComboBoxItem(*item)
else:
assert isinstance(item, ComboBoxItem)
self.items.append(item)
def widget_setter(self, _param):
return None
def init_widget(self, param, row, group_name):
super().init_widget(param, row, group_name)
if self.translate:
cog.out(
f"""
for (int i=0; i<{len(self.items)}; ++i) {trace_comment()}
{param.widget_name}->addItem(QString());"""
)
for i, item in enumerate(self.items):
if not self.translate:
cog.out(
f"""
{param.widget_name}->addItem(QStringLiteral("{item.text}"));"""
)
if item._data is not None:
cog.out(
f"""
{param.widget_name}->setItemData({param.widget_name}->count()-1, {item.data});"""
)
cog.out(
f"""
{param.widget_name}->setCurrentIndex({param.namespace}::{param.class_name}::default{param.name}());"""
)
def retranslate(self, param):
super().retranslate(param)
cog.out(
f"""
{trace_comment()}"""
)
for i, item in enumerate(self.items):
if self.translate:
cog.out(
f"""
{param.widget_name}->setItemText({i}, QObject::tr("{item.text}"));"""
)
if item.tooltips:
cog.out(
f"""
{param.widget_name}->setItemData({i}, QObject::tr("{item.tooltips}"), Qt::ToolTipRole);"""
)
class ParamLinePattern(ParamProxy):
WidgetType = "Gui::PrefLinePattern"
def widget_setter(self, _param):
return None
def init_widget(self, param, row, group_name):
super().init_widget(param, row, group_name)
cog.out(
f"""
{trace_comment()}
for (int i=1; i<{param.widget_name}->count(); ++i) {{
if ({param.widget_name}->itemData(i).toInt() == {param.default})
{param.widget_name}->setCurrentIndex(i);
}}"""
)
class ParamColor(ParamProxy):
WidgetType = "Gui::PrefColorButton"
WidgetSetter = "setPackedColor"
def __init__(self, param_bool=None, transparency=True):
super().__init__(param_bool)
self.transparency = transparency
def init_widget(self, param, row, group_name):
super().init_widget(param, row, group_name)
if self.transparency:
cog.out(
f"""
{param.widget_name}->setAllowTransparency(true);"""
)
class ParamFile(ParamProxy):
WidgetType = "Gui::PrefFileChooser"
WidgetSetter = "setFileNameStd"
class ParamSpinBox(ParamProxy):
def __init__(self, value_min, value_max, value_step, decimals=0, param_bool=None, suffix=""):
super().__init__(param_bool)
self.value_min = value_min
self.value_max = value_max
self.value_step = value_step
self.decimals = decimals
self.suffix = suffix
def init_widget(self, param, row, group_name):
super().init_widget(param, row, group_name)
cog.out(
f"""
{trace_comment()}
{param.widget_name}->setMinimum({self.value_min});
{param.widget_name}->setMaximum({self.value_max});
{param.widget_name}->setSingleStep({self.value_step});
{param.widget_name}->setAlignment(Qt::AlignRight);"""
)
if self.decimals:
cog.out(
f"""
{param.widget_name}->setDecimals({self.decimals});"""
)
if self.suffix:
cog.out(
f"""
{param.widget_name}->setSuffix(QLatin1String("{self.suffix}"));"""
)
class ParamShortcutEdit(ParamProxy):
WidgetType = "Gui::PrefAccelLineEdit"
WidgetSetter = "setDisplayText"
class Property:
def __init__(self, name, property_type, doc, group=None, prop_flags=None, static=False):
self.name = name
self.type_name = property_type
self.doc = doc
self.prop_flags = prop_flags if prop_flags else "App::Prop_None"
self.static = static
self.group = group if group else ""
def declare(self):
if self.static:
cog.out(
f"""
static {self.type_name} *get{self.name}Property(App::DocumentObject *obj, bool force=false);
inline {self.type_name} *get{self.name}Property(bool force=false) {{
return get{self.name}Property(this, force);
}}"""
)
else:
cog.out(
f"""
{self.type_name} *get{self.name}Property(bool force=false);"""
)
def define(self, class_name):
if self.static:
cog.out(
f"""
{trace_comment()}
{self.type_name} *{class_name}::get{self.name}Property(App::DocumentObject *obj, bool force)
{{"""
)
else:
cog.out(
f"""
{trace_comment()}
{self.type_name} *{class_name}::get{self.name}Property(bool force)
{{
auto obj = this;"""
)
cog.out(
f"""
if (auto prop = Base::freecad_dynamic_cast<{self.type_name}>(
obj->getPropertyByName("{self.name}")))
{{
if (prop->getContainer() == obj)
return prop;
}}
if (!force)
return nullptr;
return static_cast<{self.type_name}*>(obj->addDynamicProperty(
"{self.type_name}", "{self.name}", "{self.group}",
{quote(self.doc)},
{self.prop_flags}));
}}
"""
)
def declare_properties(properties):
cog.out(
f"""
{trace_comment()}"""
)
for prop in properties:
prop.declare()
def define_properties(properties, class_name):
for prop in properties:
prop.define(class_name)
|