forked from bambulab/BambuStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGLGizmoText.cpp
More file actions
4111 lines (3732 loc) · 178 KB
/
Copy pathGLGizmoText.cpp
File metadata and controls
4111 lines (3732 loc) · 178 KB
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
// Include GLGizmoBase.hpp before I18N.hpp as it includes some libigl code, which overrides our localization "L" macro.
#include "GLGizmoText.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "slic3r/GUI/GLCanvas3D.hpp"
#include "slic3r/GUI/Gizmos/GLGizmosCommon.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/ImGuiWrapper.hpp"
#include "slic3r/GUI/GUI_ObjectList.hpp"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/MsgDialog.hpp"
#include "slic3r/GUI/format.hpp"
#include "libslic3r/Geometry/ConvexHull.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Timer.hpp"
#include "libslic3r/Shape/TextShape.hpp"
#include "slic3r/Utils/WxFontUtils.hpp"
#include "slic3r/GUI/Jobs/CreateFontNameImageJob.hpp"
#include "slic3r/GUI/Jobs/NotificationProgressIndicator.hpp"
#include "slic3r/GUI/UIHelpers/TextEllipsis.hpp"
#include "slic3r/Utils/UndoRedo.hpp"
#include <wx/font.h>
#include <wx/fontutil.h>
#include <wx/fontdlg.h>
#include <wx/fontenum.h>
#include <wx/display.h> // detection of change DPI
#include <wx/hashmap.h>
#include <wx/utils.h>
#include <numeric>
#include <codecvt>
#include <boost/log/trivial.hpp>
#include <GL/glew.h>
#include "imgui/imgui_stdlib.h" // using std::string for inputs
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include <imgui/imgui_internal.h>
#include "libslic3r/SVG.hpp"
#include <codecvt>
#include "../ParamsPanel.hpp"
using namespace Slic3r;
using namespace Slic3r::GUI;
using namespace Slic3r::GUI::Emboss;
using namespace Slic3r::Emboss;
static std::size_t hash_value(wxString const &s)
{
boost::hash<std::string> hasher;
return hasher(s.ToStdString());
}
// increase number when change struct FacenamesSerializer
constexpr std::uint32_t FACENAMES_VERSION = 1;
struct FacenamesSerializer
{
// hash number for unsorted vector of installed font into system
size_t hash = 0;
// assumption that is loadable
std::vector<wxString> good;
// Can't load for some reason
std::vector<wxString> bad;
};
template<class Archive> void save(Archive &archive, wxString const &d)
{
auto data = into_u8(d);
archive(data);
}
template<class Archive> void load(Archive &archive, wxString &d)
{
std::string s;
archive(s);
d = from_u8(s);
}
template<class Archive> void serialize(Archive &ar, FacenamesSerializer &t, const std::uint32_t version)
{
// When performing a load, the version associated with the class
// is whatever it was when that data was originally serialized
// When we save, we'll use the version that is defined in the macro
if (version != FACENAMES_VERSION) {
throw Slic3r::IOError("Version of hints.cereal is higher than current version.");
return;
}
ar(t.hash, t.good, t.bad);
}
CEREAL_CLASS_VERSION(FacenamesSerializer, FACENAMES_VERSION); // register class version
namespace Slic3r {
namespace GUI {
namespace Text {
template<typename T> struct Limit
{
// Limitation for view slider range in GUI
MinMax<T> gui;
// Real limits for setting exacts values
MinMax<T> values;
};
static const struct Limits
{
MinMax<double> emboss{0.01, 1e4}; // in mm
MinMax<float> size_in_mm{1.0f, 1000.f}; // in mm
Limit<float> boldness{{-0.1f, 0.5f}, {-5e5f, 5e5f}}; // in font points
Limit<float> skew{{-1.f, 1.f}, {-100.f, 100.f}}; // ration without unit
MinMax<int> char_gap{-20000, 20000}; // in font points
MinMax<int> line_gap{-20000, 20000}; // in font points
// distance text object from surface
MinMax<float> angle{-180.f, 180.f}; // in degrees
} limits;
enum class IconType : unsigned {
rename = 0,
warning,
undo,
save,
add,
erase,
/*
italic,
unitalic,
bold,
unbold,
system_selector,
open_file,
lock,
lock_bold,
unlock,
unlock_bold,
align_horizontal_left,
align_horizontal_center,
align_horizontal_right,
align_vertical_top,
align_vertical_center,
align_vertical_bottom,*/
// automatic calc of icon's count
_count
};
// Define rendered version of icon
enum class IconState : unsigned { activable = 0, hovered /*1*/, disabled /*2*/ };
// selector for icon by enum
const IconManager::Icon &get_icon(const IconManager::VIcons &icons, IconType type, IconState state);
struct CurGuiCfg
{
// Detect invalid config values when change monitor DPI
double screen_scale;
bool dark_mode = false;
// Zero means it is calculated in init function
float height_of_volume_type_selector = 0.f;
float input_width = 0.f;
float delete_pos_x = 0.f;
float max_style_name_width = 0.f;
unsigned int icon_width = 0;
float max_tooltip_width = 0.f;
// maximal width and height of style image
Vec2i32 max_style_image_size = Vec2i32(0, 0);
float indent = 0.f;
float input_offset = 0.f;
float advanced_input_offset = 0.f;
float lock_offset = 0.f;
ImVec2 text_size;
// maximal size of face name image
Vec2i32 face_name_size = Vec2i32(0, 0);
float face_name_texture_offset_x = 0.f;
// maximal texture generate jobs running at once
unsigned int max_count_opened_font_files = 10;
// Only translations needed for calc GUI size
struct Translations
{
std::string font;
std::string height;
std::string depth;
// advanced
std::string use_surface;
std::string per_glyph;
std::string alignment;
std::string char_gap;
std::string line_gap;
std::string boldness;
std::string skew_ration;
std::string from_surface;
std::string rotation;
};
Translations translations;
};
CurGuiCfg create_gui_configuration();
}
using namespace Text;
IconManager::VIcons init_text_icons(IconManager &mng, const CurGuiCfg &cfg)//init_icons
{
mng.release();
ImVec2 size(cfg.icon_width, cfg.icon_width);
// icon order has to match the enum IconType
std::vector<std::string> filenames{
"edit_button.svg",
"obj_warning.svg", // exclamation // ORCA: use obj_warning instead exclamation. exclamation is not compatible with low res
"text_undo.svg", // reset_value
"text_save.svg", // save
"add_copies.svg",
"delete2.svg",
//"text_refresh.svg", // refresh
//"text_open.svg", // changhe_file
//"text_bake.svg", // bake
//"text_obj_warning.svg", // exclamation // ORCA: use obj_warning instead exclamation. exclamation is not compatible with low res
//"text_lock_closed.svg", // lock
//"text_lock_open.svg", // unlock
//"text_reflection_x.svg", // reflection_x
//"text_reflection_y.svg", // reflection_y
};
assert(filenames.size() == static_cast<size_t>(IconType::_count));
std::string path = resources_dir() + "/images/";
for (std::string &filename : filenames)
filename = path + filename;
auto type = IconManager::RasterType::color_wite_gray;
return mng.init(filenames, size, type);
}
bool is_text_empty(std::string_view text) { return text.empty() || text.find_first_not_of(" \n\t\r") == std::string::npos; }
struct GLGizmoText::GuiCfg : public Text::CurGuiCfg
{};
static const wxColour FONT_TEXTURE_BG = wxColour(0, 0, 0, 0);
static const wxColour FONT_TEXTURE_FG = *wxWHITE;
static const int FONT_SIZE = 12;
static const float SELECTABLE_INNER_OFFSET = 8.0f;
const std::array<float, 4> TEXT_GRABBER_COLOR = {1.0, 1.0, 0.0, 1.0};
const std::array<float, 4> TEXT_GRABBER_HOVER_COLOR = {0.7, 0.7, 0.0, 1.0};
std::string formatFloat(float val)
{
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << val;
return ss.str();
}
bool draw_button(const IconManager::VIcons &icons, IconType type, bool disable = false);
struct FaceName
{
wxString wx_name;
std::string name_truncated = "";
size_t texture_index = 0;
// State for generation of texture
// when start generate create share pointers
std::shared_ptr<std::atomic<bool>> cancel = nullptr;
// R/W only on main thread - finalize of job
std::shared_ptr<bool> is_created = nullptr;
};
// Implementation of forwarded struct
// Keep sorted list of loadable face names
struct CurFacenames
{
// flag to keep need of enumeration fonts from OS
// false .. wants new enumeration check by Hash
// true .. already enumerated(During opened combo box)
bool is_init = false;
bool has_truncated_names = false;
// data of can_load() faces
std::vector<FaceName> faces = {};
std::vector<std::string> faces_names = {};
// Sorter set of Non valid face names in OS
std::vector<wxString> bad = {};
// Configuration of font encoding
static const wxFontEncoding encoding = wxFontEncoding::wxFONTENCODING_SYSTEM;
// Identify if preview texture exists
GLuint texture_id = 0;
// protection for open too much font files together
// Gtk:ERROR:../../../../gtk/gtkiconhelper.c:494:ensure_surface_for_gicon: assertion failed (error == NULL): Failed to load
// /usr/share/icons/Yaru/48x48/status/image-missing.png: Error opening file /usr/share/icons/Yaru/48x48/status/image-missing.png: Too
// many open files (g-io-error-quark, 31) This variable must exist until no CreateFontImageJob is running
unsigned int count_opened_font_files = 0;
// Configuration for texture height
const int count_cached_textures = 32;
// index for new generated texture index(must be lower than count_cached_textures)
size_t texture_index = 0;
// hash created from enumerated font from OS
// check when new font was installed
size_t hash = 0;
// filtration pattern
// std::string search = "";
// std::vector<bool> hide; // result of filtration
};
struct GLGizmoText::Facenames : public CurFacenames
{};
bool store(const CurFacenames &facenames);
bool load(CurFacenames &facenames,const std::vector<wxString>& delete_bad_font_list);
void init_face_names(CurFacenames &face_names);
void init_truncated_names(CurFacenames &face_names, float max_width);
std::optional<wxString> get_installed_face_name(const std::optional<std::string> &face_name_opt, CurFacenames &face_names);
void draw_font_preview(FaceName &face, const std::string &text, CurFacenames &faces, const CurGuiCfg &cfg, bool is_visible);
void init_text_lines(TextLinesModel &text_lines, const Selection &selection, /* const*/ StyleManager &style_manager, unsigned count_lines = 0);
class TextDataBase : public DataBase
{
public:
TextDataBase(DataBase &&parent, const FontFileWithCache &font_file, TextConfiguration &&text_configuration, const EmbossProjection &projection)
: DataBase(std::move(parent)), m_font_file(font_file) /* copy */, m_text_configuration(std::move(text_configuration))
{
assert(m_font_file.has_value());
shape.projection = projection; // copy
const FontProp &fp = m_text_configuration.style.prop;
const FontFile &ff = *m_font_file.font_file;
shape.scale = get_text_shape_scale(fp, ff);
}
// Create shape from text + font configuration
EmbossShape &create_shape() override;
void write(ModelVolume &volume) const override;
TextConfiguration get_text_configuration() override {
return m_text_configuration;
}
/// <summary>
/// Used only with text for embossing per glyph.
/// Create text lines only for new added volume to object
/// otherwise textline is already setted before
/// </summary>
/// <param name="tr">Embossed volume final transformation in object</param>
/// <param name="vols">Volumes to be sliced to text lines</param>
/// <returns>True on succes otherwise False(Per glyph shoud be disabled)</returns>
//bool create_text_lines(const Transform3d &tr, const ModelVolumePtrs &vols) override;
private:
// Keep pointer on Data of font (glyph shapes)
FontFileWithCache m_font_file;
// font item is not used for create object
TextConfiguration m_text_configuration;
};
void TextDataBase::write(ModelVolume &volume) const
{
//DataBase::write(volume);
volume.set_text_configuration(m_text_configuration);// volume.text_configuration = m_text_configuration; // copy
// Fix for object: stored attribute that volume is embossed per glyph when it is object
if (m_text_configuration.style.prop.per_glyph && volume.is_the_only_one_part()) {
volume.get_text_configuration().style.prop.per_glyph = false;
}
}
void GLGizmoText::calculate_scale()
{
Transform3d to_world = m_parent.get_selection().get_first_volume()->world_matrix();
auto to_world_linear = to_world.linear();
auto calc = [&to_world_linear](const Vec3d &axe, std::optional<float> &scale) -> bool {
Vec3d axe_world = to_world_linear * axe;
double norm_sq = axe_world.squaredNorm();
if (is_approx(norm_sq, 1.)) {
if (scale.has_value())
scale.reset();
else
return false;
} else {
scale = sqrt(norm_sq);
}
return true;
};
bool exist_change = calc(Vec3d::UnitY(), m_scale_height);
exist_change |= calc(Vec3d::UnitZ(), m_scale_depth);
// Change of scale has to change font imgui font size
if (exist_change)
m_style_manager.clear_imgui_font();
}
///////////////////////
class StyleNameEditDialog : public DPIDialog
{
public:
StyleNameEditDialog(wxWindow * parent,
Emboss::StyleManager &style_manager,
wxWindowID id = wxID_ANY,
const wxString &title = wxEmptyString,
const wxPoint & pos = wxDefaultPosition,
const wxSize & size = wxDefaultSize,
long style = wxCLOSE_BOX | wxCAPTION);
~StyleNameEditDialog();
void on_dpi_changed(const wxRect &suggested_rect) override;
wxString get_name() const;
void set_name(const wxString &name);
void on_edit_text(wxCommandEvent &event);
void add_tip_label();
private:
bool check_empty_or_iillegal_character(const std::string &name);
private:
Button * m_button_ok{nullptr};
Button * m_button_cancel{nullptr};
TextInput *m_name{nullptr};
Label * m_tip{nullptr};
bool m_add_tip{false};
wxPanel * m_row_panel{nullptr};
Emboss::StyleManager &m_style_manager;
wxFlexGridSizer * m_top_sizer{nullptr};
};
/// GLGizmoText start
GLGizmoText::GLGizmoText(GLCanvas3D& parent, unsigned int sprite_id)
: GLGizmoBase(parent, sprite_id),
m_face_names(std::make_unique<Facenames>()),
m_style_manager(m_imgui->get_glyph_ranges(), create_default_styles),
m_gui_cfg(nullptr), m_rotate_gizmo(parent, GLGizmoRotate::Axis::Z) // grab id = 2 (Z axis)
{
m_rotate_gizmo.set_group_id(0);
m_rotate_gizmo.set_force_local_coordinate(true);
if (GUI::wxGetApp().app_config->get_bool("support_backup_fonts")) {
Slic3r::GUI::BackupFonts::generate_backup_fonts();
}
}
GLGizmoText::~GLGizmoText()
{
if (m_thread.joinable())
m_thread.join();
for (int i = 0; i < m_textures.size(); i++) {
if (m_textures[i].texture != nullptr)
delete m_textures[i].texture;
}
}
bool GLGizmoText::on_init()
{
m_rotate_gizmo.init();
ColorRGBA gray_color(.6f, .6f, .6f, .3f);
m_rotate_gizmo.set_highlight_color(gray_color.get_data());
// Set rotation gizmo upwardrotate
m_rotate_gizmo.set_angle(PI / 2);
m_init_texture = false;
m_style_manager.init(wxGetApp().app_config);
Emboss::StyleManager::Style &style = m_style_manager.get_style();
std::optional<wxString> installed_name = get_installed_face_name(style.prop.face_name, *m_face_names);
//m_avail_font_names = init_face_names();//todo
//m_thread = std::thread(&GLGizmoText::update_font_status, this);
//m_avail_font_names = init_occt_fonts();
//update_font_texture();
m_scale = m_imgui->get_font_size();
m_shortcut_key = WXK_CONTROL_T;
reset_text_info();
return true;
}
void GLGizmoText::update_font_texture()
{
m_font_names.clear();
for (int i = 0; i < m_textures.size(); i++) {
if (m_textures[i].texture != nullptr)
delete m_textures[i].texture;
}
m_combo_width = 0.0f;
m_combo_height = 0.0f;
m_textures.clear();
m_textures.reserve(m_avail_font_names.size());
for (int i = 0; i < m_avail_font_names.size(); i++)
{
GLTexture* texture = new GLTexture();
auto face = wxString::FromUTF8(m_avail_font_names[i]);
auto retina_scale = m_parent.get_scale();
wxFont font { (int)round(retina_scale * FONT_SIZE), wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, face };
int w, h, hl;
std::unique_lock<std::mutex> lock(m_mutex);
if (m_font_status[i] && texture->generate_texture_from_text(m_avail_font_names[i], font, w, h, hl, FONT_TEXTURE_BG, FONT_TEXTURE_FG)) {
//if (h < m_imgui->scaled(2.f)) {
TextureInfo info;
info.texture = texture;
info.w = w;
info.h = h;
info.hl = hl;
info.font_name = m_avail_font_names[i];
m_textures.push_back(info);
m_combo_width = std::max(m_combo_width, static_cast<float>(texture->m_original_width));
m_font_names.push_back(info.font_name);
//}
}
}
m_combo_height = m_imgui->scaled(32.f / 15.f);
}
bool GLGizmoText::is_mesh_point_clipped(const Vec3d &point, const Transform3d &trafo) const
{
if (m_c->object_clipper()->get_position() == 0.)
return false;
auto sel_info = m_c->selection_info();
Vec3d transformed_point = trafo * point;
transformed_point(2) += sel_info->get_sla_shift();
return m_c->object_clipper()->get_clipping_plane()->is_point_clipped(transformed_point);
}
BoundingBoxf3 GLGizmoText::bounding_box() const
{
BoundingBoxf3 ret;
const Selection & selection = m_parent.get_selection();
const Selection::IndicesList &idxs = selection.get_volume_idxs();
for (unsigned int i : idxs) {
const GLVolume *volume = selection.get_volume(i);
if (!volume->is_modifier)
ret.merge(volume->transformed_convex_hull_bounding_box());
}
return ret;
}
#define SYSTEM_STYLE_MAX 6
EmbossStyles GLGizmoText::create_default_styles()
{
wxFontEnumerator::InvalidateCache();
wxArrayString facenames = wxFontEnumerator::GetFacenames(CurFacenames::encoding);
wxFont wx_font_normal = *wxNORMAL_FONT;
#ifdef __APPLE__
// Set normal font to helvetica when possible
for (const wxString &facename : facenames) {
if (facename.IsSameAs("Helvetica")) {
wx_font_normal = wxFont(wxFontInfo().FaceName(facename).Encoding(Facenames::encoding));
break;
}
}
#endif // __APPLE__
// https://docs.wxwidgets.org/3.0/classwx_font.html
// Predefined objects/pointers: wxNullFont, wxNORMAL_FONT, wxSMALL_FONT, wxITALIC_FONT, wxSWISS_FONT
EmbossStyles styles = {
#ifdef __APPLE__
WxFontUtils::create_emboss_style(wx_font_normal, _u8L("Recommend")), // v2.0 version
WxFontUtils::create_emboss_style(wx_font_normal, _u8L("Old version")), // for 1.10 and 1.9 and old version
#else
WxFontUtils::create_emboss_style(wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD), _u8L("Recommend")), //v2.0 version
WxFontUtils::create_emboss_style(wxFont(10, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD), _u8L("Old version")), // for 1.10 and 1.9 and old version
#endif
};
// Not all predefined font for wx must be valid TTF, but at least one style must be loadable
styles.erase(std::remove_if(styles.begin(), styles.end(),
[](const EmbossStyle &style) {
wxFont wx_font = WxFontUtils::create_wxFont(style);
// check that face name is setabled
if (style.prop.face_name.has_value()) {
wxString face_name = wxString::FromUTF8(style.prop.face_name->c_str());
wxFont wx_font_temp;
if (!wx_font_temp.SetFaceName(face_name))
return true;
}
// Check that exsit valid TrueType Font for wx font
return WxFontUtils::create_font_file(wx_font) == nullptr;
}),
styles.end());
// exist some valid style?
if (!styles.empty())
return styles;
// No valid style in defult list
// at least one style must contain loadable font
wxFont wx_font;
for (const wxString &face : facenames) {
wx_font = wxFont(face);
if (WxFontUtils::create_font_file(wx_font) != nullptr)
break;
wx_font = wxFont(); // NotOk
}
if (wx_font.IsOk()) {
// use first alphabetic sorted installed font
styles.push_back(WxFontUtils::create_emboss_style(wx_font, _u8L("First font")));
} else {
// On current OS is not installed any correct TTF font
// use font packed with Slic3r
std::string font_path = Slic3r::resources_dir() + "/fonts/NotoSans-Regular.ttf";
styles.push_back(EmbossStyle{_u8L("Default font"), font_path, EmbossStyle::Type::file_path});
}
return styles;
}
bool GLGizmoText::select_facename(const wxString &facename, bool update_text)
{
if (!wxFontEnumerator::IsValidFacename(facename))
return false;
// Select font
wxFont wx_font(wxFontInfo().FaceName(facename).Encoding(CurFacenames::encoding));
if (!wx_font.IsOk())
return false;
#ifdef USE_PIXEL_SIZE_IN_WX_FONT
// wx font could change source file by size of font
int point_size = static_cast<int>(m_style_manager.get_font_prop().size_in_mm);
wx_font.SetPointSize(point_size);
#endif // USE_PIXEL_SIZE_IN_WX_FONT
if (!m_style_manager.set_wx_font(wx_font))
return false;
if (update_text) {
process();
}
return true;
}
bool GLGizmoText::gizmo_event(SLAGizmoEventType action, const Vec2d &mouse_position, bool shift_down, bool alt_down, bool control_down)
{
std::string text = std::string(m_text);
if (text.empty())
return true;
if (m_object_idx < 0) {
return true;
}
const Selection &selection = m_parent.get_selection();
auto mo = selection.get_model()->objects[m_object_idx];
if (mo == nullptr)
return true;
const ModelInstance *mi = mo->instances[selection.get_instance_idx()];
const Camera & camera = wxGetApp().plater()->get_camera();
if (action == SLAGizmoEventType::Moving) {
m_mouse_position = mouse_position;
}
else if (action == SLAGizmoEventType::LeftDown) {
if (is_only_text_case()) {
return false;
}
if (!selection.is_empty() && get_hover_id() != -1) {
start_dragging();
return true;
}
}
return true;
}
void GLGizmoText::on_set_state()
{
m_rotate_gizmo.set_state(GLGizmoBase::m_state);
if (m_state == EState::On) {
m_text_tran_in_object.reset();
m_style_manager.get_style().angle = 0;
m_last_text_mv = nullptr;
m_show_text_normal_reset_tip = false;
load_init_text(true);
if (m_last_text_mv) {
m_reedit_text = true;
m_load_text_tran_in_object = m_text_tran_in_object;
if (m_really_use_surface_calc) {
m_show_warning_regenerated = true;
use_fix_normal_position();
} else if (m_fix_old_tran_flag && (m_font_version == "" || m_font_version == "1.0")) {
m_show_warning_old_tran = false;
auto offset = m_text_tran_in_object.get_offset();
auto rotation = m_text_tran_in_object.get_rotation();
float eps = 0.01f;
int count = 0;
bool has_rotation = rotation.norm() > eps;
count += has_rotation ? 1 : 0;
auto scaling_factor = m_text_tran_in_object.get_scaling_factor();
bool has_scale = (scaling_factor - Vec3d(1, 1, 1)).norm() > eps;
count += has_scale ? 1 : 0;
auto mirror = m_text_tran_in_object.get_mirror();
bool has_mirror = (mirror - Vec3d(1, 1, 1)).norm() > eps;
count += has_mirror ? 1 : 0;
Geometry::Transformation expert_text_tran_in_world;
generate_text_tran_in_world(m_fix_text_normal_in_world.cast<double>(), m_fix_text_position_in_world, m_rotate_angle, expert_text_tran_in_world);
auto temp_expert_text_tran_in_object = m_model_object_in_world_tran.get_matrix().inverse() * expert_text_tran_in_world.get_matrix();
Geometry::Transformation expert_text_tran_in_object(temp_expert_text_tran_in_object);
if (count >= 2) {
m_show_warning_old_tran = true;
}
if (m_is_version1_10_xoy) {
auto rotate_tran = Geometry::assemble_transform(Vec3d::Zero(), {0.5 * M_PI, 0.0, 0.0});
m_text_tran_in_object.set_from_transform(m_load_text_tran_in_object.get_matrix() * rotate_tran);
m_text_tran_in_object.set_offset(m_load_text_tran_in_object.get_offset() + Vec3d(0, 1.65, 0)); // for size 16
m_text_normal_in_world = m_fix_text_normal_in_world;
update_cut_plane_dir();
return;
} else if (m_is_version1_8_yoz) {//Box+172x125x30_All_Bases
const Selection &selection = m_parent.get_selection();
m_style_manager.get_style().angle = calc_angle(selection);
auto rotate_tran = Geometry::assemble_transform(Vec3d::Zero(), {0.0, 0.0, 0.5 * M_PI});
m_text_tran_in_object.set_from_transform(m_load_text_tran_in_object.get_matrix() * rotate_tran);
update_cut_plane_dir();
m_text_tran_in_object.set_offset(expert_text_tran_in_object.get_offset());
return;
}
//go on
if (has_rotation && m_show_warning_old_tran == false) {
m_show_warning_lost_rotate = true;
if (m_is_version1_9_xoz) {
expert_text_tran_in_object.set_rotation(rotation);
}
use_fix_normal_position();
}
//not need set set_rotation//has_rotation
if (has_scale) {
expert_text_tran_in_object.set_scaling_factor(scaling_factor);
}
if (has_mirror) {
expert_text_tran_in_object.set_mirror(mirror);
}
m_text_tran_in_object.set_from_transform(expert_text_tran_in_object.get_matrix());
update_cut_plane_dir();
}
}
}
else if (m_state == EState::Off) {
ImGui::FocusWindow(nullptr);//exit cursor
m_trafo_matrices.clear();
m_reedit_text = false;
m_fix_old_tran_flag = false;
m_warning_font = false;
close_warning_flag_after_close_or_drag();
reset_text_info();
m_parent.use_slope(false);
m_parent.toggle_model_objects_visibility(true);
m_style_manager.store_styles_to_app_config(false);
}
}
void GLGizmoText::load_old_font() {
const int old_font_index = 1;
const StyleManager::Style &style = m_style_manager.get_styles()[old_font_index];
// create copy to be able do fix transformation only when successfully load style
if (m_style_manager.load_style(old_font_index)) {
if (m_italic && m_thickness) {
m_style_manager.get_font_prop().size_in_mm = m_font_size * 0.92;
}
else if (m_italic){
m_style_manager.get_font_prop().size_in_mm = m_font_size * 0.98;
}
else if (m_thickness) {
m_style_manager.get_font_prop().size_in_mm = m_font_size * 0.93;
} else {
m_style_manager.get_font_prop().size_in_mm = m_font_size * 1.0;
}
wxString font_name(m_font_name);
bool update_text = !m_is_serializing ? true : false;
if (!select_facename(font_name, update_text)) {
wxString font_name("Arial");
select_facename(font_name, update_text);
}
}
}
wxString FindLastName(const wxString &input)
{
int lastSemicolonPos = input.Find(';', true);
if (lastSemicolonPos == wxNOT_FOUND) { return input; }
return input.Mid(lastSemicolonPos + 1);
}
void GLGizmoText::draw_style_list(float caption_size)
{
if (!m_style_manager.is_active_font())
return;
const StyleManager::Style *stored_style = nullptr;
bool is_stored = m_style_manager.exist_stored_style();
if (is_stored)
stored_style = m_style_manager.get_stored_style();
const StyleManager::Style ¤t_style = m_style_manager.get_style();
bool is_changed = true;
if (stored_style) {
wxString path0((*stored_style).path.c_str(), wxConvUTF8);
wxString path1(current_style.path.c_str(), wxConvUTF8);
auto stored_font_name = FindLastName(path0);
auto current_font_name = FindLastName(path1);
is_changed = !(*stored_style == current_style && stored_font_name == current_font_name);
}
bool is_modified = is_stored && is_changed;
const float &max_style_name_width = m_gui_cfg->max_style_name_width;
std::string &trunc_name = m_style_manager.get_truncated_name();
m_style_name = m_style_manager.get_truncated_name();
if (trunc_name.empty()) {
// generate trunc name
std::string current_name = current_style.name;
ImGuiWrapper::escape_double_hash(current_name);
trunc_name = ImGuiWrapper::trunc(current_name, max_style_name_width);
}
ImGui::AlignTextToFramePadding();
std::string title = _u8L("Style");
if (m_style_manager.exist_stored_style())
ImGui::Text("%s", title.c_str());
else
ImGui::TextColored(ImGuiWrapper::COL_BAMBU, "%s", title.c_str());
if (ImGui::IsItemHovered()) {
m_imgui->tooltip(_u8L("Save the parameters of the current text tool as a style for easy subsequent use."), m_gui_cfg->max_tooltip_width);
}
ImGui::SameLine(caption_size);
ImGui::PushItemWidth(m_gui_cfg->input_width);
auto add_text_modify = [&is_modified](const std::string &name) {
if (!is_modified)
return name;
return name + Preset::suffix_modified();
};
std::optional<size_t> selected_style_index;
std::string tooltip = "";
ImGuiWrapper::push_combo_style(m_parent.get_scale());
if (ImGui::BBLBeginCombo("##style_selector", add_text_modify(trunc_name).c_str())) {
m_style_manager.init_style_images(m_gui_cfg->max_style_image_size, m_text);
m_style_manager.init_trunc_names(max_style_name_width);
std::optional<std::pair<size_t, size_t>> swap_indexes;
const StyleManager::Styles & styles = m_style_manager.get_styles();
for (const StyleManager::Style &style : styles) {
size_t index = &style - &styles.front();
const std::string &actual_style_name = style.name;
ImGui::PushID(actual_style_name.c_str());
bool is_selected = (index == m_style_manager.get_style_index());
float select_height = static_cast<float>(m_gui_cfg->max_style_image_size.y());
ImVec2 select_size(0.f, select_height); // 0,0 --> calculate in draw
const std::optional<StyleManager::StyleImage> &img = style.image;
// allow click delete button
ImGuiSelectableFlags_ flags = ImGuiSelectableFlags_AllowItemOverlap;
if (ImGui::BBLSelectable(style.truncated_name.c_str(), is_selected, flags, select_size)) {
selected_style_index = index;
}/* else if (ImGui::IsItemHovered())
tooltip = actual_style_name;*/
// reorder items
if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) {
if (ImGui::GetMouseDragDelta(0).y < 0.f) {
if (index > 0) swap_indexes = {index, index - 1};
} else if ((index + 1) < styles.size())
swap_indexes = {index, index + 1};
if (swap_indexes.has_value()) ImGui::ResetMouseDragDelta();
}
// draw style name
if (img.has_value()) {
ImGui::SameLine(max_style_name_width);
ImVec4 tint_color = ImGui::GetStyleColorVec4(ImGuiCol_Text);
ImGui::Image(img->texture_id, img->tex_size, img->uv0, img->uv1, tint_color);
}
ImGui::PopID();
}
if (swap_indexes.has_value())
m_style_manager.swap(swap_indexes->first, swap_indexes->second);
ImGui::EndCombo();
} else {
// do not keep in memory style images when no combo box open
m_style_manager.free_style_images();
if (ImGui::IsItemHovered()) {
std::string style_name = add_text_modify(current_style.name);
tooltip = is_modified ? GUI::format(_L("Modified style \"%1%\""), current_style.name) : GUI::format(_L("Current style is \"%1%\""), current_style.name);
}
}
ImGuiWrapper::pop_combo_style();
if (!tooltip.empty())
m_imgui->tooltip(tooltip, m_gui_cfg->max_tooltip_width);
// Check whether user wants lose actual style modification
if (selected_style_index.has_value() && is_modified) {
const std::string &style_name = m_style_manager.get_styles()[*selected_style_index].name;
wxString message = GUI::format_wxstr(_L("Changing style to \"%1%\" will discard current style modification.\n\nWould you like to continue anyway?"), style_name);
MessageDialog not_loaded_style_message(nullptr, message, _L("Warning"), wxICON_WARNING | wxYES | wxNO);
if (not_loaded_style_message.ShowModal() != wxID_YES)
selected_style_index.reset();
}
// selected style from combo box
if (selected_style_index.has_value()) {
const StyleManager::Style &style = m_style_manager.get_styles()[*selected_style_index];
// create copy to be able do fix transformation only when successfully load style
StyleManager::Style cur_s = current_style; // copy
StyleManager::Style new_s = style; // copy
if (m_style_manager.load_style(*selected_style_index)) {
m_bold = m_style_manager.get_font_prop().boldness > 0;//for update_italic
m_italic = m_style_manager.get_font_prop().skew > 0;//for update_boldness
process(true);//, fix_transformation(cur_s, new_s, m_parent)//todo
} else {
wxString title = _L("Not valid style.");
wxString message = GUI::format_wxstr(_L("Style \"%1%\" can't be used and will be removed from a list."), style.name);
MessageDialog not_loaded_style_message(nullptr, message, title, wxOK);
not_loaded_style_message.ShowModal();
m_style_manager.erase(*selected_style_index);
}
}
/*ImGui::SameLine();
draw_style_rename_button();*/
ImGui::SameLine();
draw_style_save_button(is_modified);
ImGui::SameLine();
draw_style_add_button(is_modified);
// delete button
ImGui::SameLine();
draw_delete_style_button();
}
void GLGizmoText::draw_style_save_button(bool is_modified)
{
if (draw_button(m_icons, IconType::save, !is_modified)) {
// save styles to app config
m_style_manager.store_styles_to_app_config();
} else if (ImGui::IsItemHovered()) {
std::string tooltip;
if (!m_style_manager.exist_stored_style()) {
tooltip = _u8L("First Add style to list.");
} else if (is_modified) {
tooltip = GUI::format(_L("Save %1% style"), m_style_manager.get_style().name);
}
if (!tooltip.empty()) {
m_imgui->tooltip(tooltip, m_gui_cfg->max_tooltip_width);
}
}
}
bool draw_text_clickable(const IconManager::VIcons &icons, IconType type)
{
return clickable(get_icon(icons, type, IconState::activable), get_icon(icons, type, IconState::hovered));
}
bool reset_text_button(const IconManager::VIcons &icons,int pos =-1)
{
ImGui::SameLine(pos == -1 ? ImGui::GetStyle().WindowPadding.x : pos);
// from GLGizmoCut
// std::string label_id = "neco";
// std::string btn_label;
// btn_label += ImGui::RevertButton;
// return ImGui::Button((btn_label + "##" + label_id).c_str());
return draw_text_clickable(icons, IconType::undo);
}
void GLGizmoText::draw_style_save_as_popup()
{
ImGuiWrapper::text_colored(ImGuiWrapper::COL_WINDOW_BG_DARK, _u8L("New name of style") + ": ");
//use name inside of volume configuration as temporary new name
std::string& new_name = m_style_new_name; // text_volume->get_text_configuration()->style.name;//BBS modify
bool is_unique = m_style_manager.is_unique_style_name(new_name);
bool allow_change = false;
if (new_name.empty()) {
ImGuiWrapper::text_colored(ImGuiWrapper::COL_WINDOW_BG_DARK, _u8L("Name can't be empty."));
} else if (!is_unique) {
ImGuiWrapper::text_colored(ImGuiWrapper::COL_WINDOW_BG_DARK, _u8L("Name has to be unique."));
} else {
allow_change = true;
}
bool save_style = false;
ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue;
if (ImGui::InputText("##save as style", &new_name, flags))
save_style = true;
if (m_imgui->button(_L("OK"), ImVec2(0.f, 0.f), allow_change))
save_style = true;
ImGui::SameLine();
if (ImGui::Button(_u8L("Cancel").c_str())) {
// write original name to volume TextConfiguration
//new_name = m_style_manager.get_style().name;
ImGui::CloseCurrentPopup();
}
if (save_style && allow_change) {
m_style_manager.add_style(new_name);
m_style_manager.store_styles_to_app_config();
ImGui::CloseCurrentPopup();
}
}
void GLGizmoText::draw_style_add_button(bool is_modified)
{
bool only_add_style = !m_style_manager.exist_stored_style();
bool can_add = true;
//auto text_volume = m_last_text_mv; // m_volume
if (only_add_style)//&& text_volume->get_text_configuration().has_value() && text_volume->get_text_configuration()->style.type != WxFontUtils::get_current_type()
can_add = false;
std::string title = _u8L("Save as new style");