Merge branch 'main' into feat/plater-notification-api

This commit is contained in:
Ian Chua
2026-09-14 11:46:36 +08:00
committed by GitHub
5054 changed files with 103238 additions and 22848 deletions
+67 -22
View File
@@ -38,6 +38,8 @@ set(SLIC3R_GUI_SOURCES
GUI/AuxiliaryDataViewModel.hpp
GUI/AuxiliaryDialog.cpp
GUI/AuxiliaryDialog.hpp
GUI/AVVideoDecoder.cpp
GUI/AVVideoDecoder.hpp
GUI/Auxiliary.hpp
GUI/BackgroundSlicingProcess.cpp
GUI/BackgroundSlicingProcess.hpp
@@ -61,6 +63,8 @@ set(SLIC3R_GUI_SOURCES
GUI/BitmapComboBox.hpp
GUI/BonjourDialog.cpp
GUI/BonjourDialog.hpp
GUI/BuildCommit.cpp
GUI/BuildCommit.hpp
GUI/CrealityDiscoveryDialog.cpp
GUI/CrealityDiscoveryDialog.hpp
GUI/calib_dlg.cpp
@@ -93,6 +97,8 @@ set(SLIC3R_GUI_SOURCES
GUI/CloneDialog.hpp
GUI/ConfigManipulation.cpp
GUI/ConfigManipulation.hpp
GUI/ConfigValueFormatter.cpp
GUI/ConfigValueFormatter.hpp
GUI/ConfigWizard.cpp
GUI/ConfigWizard.hpp
GUI/ConfigWizard_private.hpp
@@ -353,6 +359,16 @@ set(SLIC3R_GUI_SOURCES
GUI/Monitor.hpp
GUI/MonitorPage.cpp
GUI/MonitorPage.hpp
GUI/MixedFilamentDialog.cpp
GUI/MixedFilamentDialog.hpp
GUI/GradientCurveEditor.cpp
GUI/GradientCurveEditor.hpp
GUI/ColorDecomposeDialog.cpp
GUI/ColorDecomposeDialog.hpp
GUI/ColorDecomposeSupport.cpp
GUI/ColorDecomposeSupport.hpp
GUI/TextureImportDialog.cpp
GUI/TextureImportDialog.hpp
GUI/Mouse3DController.cpp
GUI/Mouse3DController.hpp
GUI/MsgDialog.cpp
@@ -437,6 +453,8 @@ set(SLIC3R_GUI_SOURCES
GUI/Project.hpp
GUI/PublishDialog.cpp
GUI/PublishDialog.hpp
GUI/PublishSettingsDialog.cpp
GUI/PublishSettingsDialog.hpp
GUI/PurgeModeDialog.cpp
GUI/PurgeModeDialog.hpp
GUI/RammingChart.cpp
@@ -601,6 +619,8 @@ set(SLIC3R_GUI_SOURCES
GUI/WipeTowerDialog.cpp
GUI/wxExtensions.cpp
GUI/wxExtensions.hpp
GUI/wxMediaCtrl3.cpp
GUI/wxMediaCtrl3.h
plugin/PythonInterpreter.cpp
plugin/PythonInterpreter.hpp
plugin/PythonPluginBridge.cpp
@@ -789,21 +809,8 @@ if (APPLE)
GUI/DeepLinkHandlerMac.mm
GUI/DeepLinkHandlerMac.h
GUI/GUI_UtilsMac.mm
GUI/wxMediaCtrl2.mm
GUI/wxMediaCtrl2.h
)
FIND_LIBRARY(DISKARBITRATION_LIBRARY DiskArbitration)
else ()
list(APPEND SLIC3R_GUI_SOURCES
GUI/wxMediaCtrl2.cpp
GUI/wxMediaCtrl2.h
)
endif ()
if (UNIX AND NOT APPLE)
list(APPEND SLIC3R_GUI_SOURCES
GUI/Printer/gstbambusrc.c
)
endif ()
set(ORCA_UPDATER_SIG_KEY_B64 "${ORCA_UPDATER_SIG_KEY}")
@@ -844,6 +851,18 @@ source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SLIC3R_GUI_SOURCES})
encoding_check(libslic3r_gui)
# Only BuildCommit.cpp includes the generated header, plus BaseException.cpp on
# Windows. Both build into libslic3r_gui, so the header only has to exist before
# that target builds.
set(_git_commit_hash_header "${CMAKE_CURRENT_BINARY_DIR}/git_commit_hash.h")
add_custom_target(git_commit_hash_header
BYPRODUCTS "${_git_commit_hash_header}"
COMMAND ${CMAKE_COMMAND}
"-DSOURCE_DIR=${CMAKE_SOURCE_DIR}"
"-DOUT_FILE=${_git_commit_hash_header}"
-P "${CMAKE_CURRENT_LIST_DIR}/GitCommitHash.cmake"
COMMENT "Resolving the git commit hash")
add_dependencies(libslic3r_gui git_commit_hash_header)
if(APPLE AND CMAKE_VERSION VERSION_GREATER_EQUAL "4.0")
set(_opengl_link_lib "")
@@ -901,8 +920,43 @@ endif ()
if (SLIC3R_PCH AND NOT SLIC3R_SYNTAXONLY)
add_precompiled_header(libslic3r_gui pchheader.hpp FORCEINCLUDE)
elseif (MSVC)
# Puts the Windows headers first when the PCH is off.
target_compile_options(libslic3r_gui PRIVATE "/FIslic3r/win_platform.hpp")
endif ()
if (APPLE)
# Static FFmpeg from the deps install: nothing to bundle into the .app,
# no rpath/install_name handling. Order matters: avcodec -> swscale -> avutil.
find_library(LIBAVCODEC_LIBRARY NAMES libavcodec.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBSWSCALE_LIBRARY NAMES libswscale.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVUTIL_LIBRARY NAMES libavutil.a PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
if (NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY)
message(FATAL_ERROR "Static FFmpeg (libavcodec.a/libswscale.a/libavutil.a) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps — FFMPEG builds static-only on macOS.")
endif ()
target_link_libraries(libslic3r_gui ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY})
target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include)
elseif (WIN32)
# Prebuilt shared FFmpeg from the deps install. Windows has no pkg-config,
# so resolve the import libraries out of the deps prefix directly; the DLLs
# are copied next to the executable by the top level CMakeLists.
find_library(LIBAVCODEC_LIBRARY NAMES avcodec PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBSWSCALE_LIBRARY NAMES swscale PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
find_library(LIBAVUTIL_LIBRARY NAMES avutil PATHS ${CMAKE_PREFIX_PATH}/lib NO_DEFAULT_PATH)
if (NOT LIBAVCODEC_LIBRARY OR NOT LIBSWSCALE_LIBRARY OR NOT LIBAVUTIL_LIBRARY)
message(FATAL_ERROR "FFmpeg (avcodec/swscale/avutil) not found under ${CMAKE_PREFIX_PATH}/lib. Rebuild the deps.")
endif ()
target_link_libraries(libslic3r_gui ${LIBAVCODEC_LIBRARY} ${LIBSWSCALE_LIBRARY} ${LIBAVUTIL_LIBRARY})
target_include_directories(libslic3r_gui SYSTEM PRIVATE ${CMAKE_PREFIX_PATH}/include)
else ()
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
libavcodec
libswscale
libavutil
)
target_link_libraries(libslic3r_gui PkgConfig::LIBAV)
endif()
# We need to implement some hacks for wxWidgets and touch the underlying GTK
# layer and sub-libraries. This forces us to use the include locations and
# link these libraries.
@@ -929,20 +983,11 @@ if (UNIX AND NOT APPLE)
target_compile_definitions(libslic3r_gui PRIVATE wxHAVE_GDK_WAYLAND)
endif ()
# We add GStreamer for bambu:/// support.
pkg_check_modules(GSTREAMER REQUIRED gstreamer-1.0)
pkg_check_modules(GST_BASE REQUIRED gstreamer-base-1.0)
target_link_libraries(libslic3r_gui ${GSTREAMER_LIBRARIES} ${GST_BASE_LIBRARIES})
target_include_directories(libslic3r_gui SYSTEM PRIVATE ${GSTREAMER_INCLUDE_DIRS} ${GST_BASE_INCLUDE_DIRS})
endif ()
# Add a definition so that we can tell we are compiling slic3r.
target_compile_definitions(libslic3r_gui PRIVATE SLIC3R_CURRENTLY_COMPILING_GUI_MODULE)
if(ORCA_BUNDLED_UV_EXECUTABLE_CONFIG)
target_compile_definitions(libslic3r_gui PRIVATE "ORCA_BUNDLED_UV_EXECUTABLE=\"${ORCA_BUNDLED_UV_EXECUTABLE_CONFIG}\"")
endif()
if (ORCA_BUILD_PYTHON_STUBGEN_MODULE)
add_library(orca_stubgen MODULE
plugin/PythonPluginBridge.cpp
+37 -9
View File
@@ -20,6 +20,8 @@
#include "libslic3r/AppConfig.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/GCode/WipeTower.hpp"
#include "libslic3r/GCode/WipeTowerEstimate.hpp"
#include "libslic3r/Tesselate.hpp"
#include "libslic3r/PrintConfig.hpp"
@@ -682,13 +684,19 @@ void GLVolume::simple_render(GLShaderProgram* shader, ModelObjectPtrs& model_obj
if (shader) {
if (idx == 0) {
int extruder_id = model_volume->extruder_id();
//to make black not too hard too see
ColorRGBA new_color = adjust_color_for_rendering(extruder_colors[extruder_id - 1]);
if (ban_light) {
new_color[3] = (255 - (extruder_id - 1))/255.0f;
// ORCA: extruder_id may be 0 (unset) or point past the colour list after a
// filament is deleted/remapped, so clamp the index instead of reading out of
// bounds.
if (!extruder_colors.empty()) {
int color_idx = std::clamp(extruder_id - 1, 0, int(extruder_colors.size()) - 1);
//to make black not too hard too see
ColorRGBA new_color = adjust_color_for_rendering(extruder_colors[color_idx]);
if (ban_light) {
new_color[3] = (255 - color_idx)/255.0f;
}
m.set_color(new_color);
// shader->set_uniform("uniform_color", new_color);
}
m.set_color(new_color);
// shader->set_uniform("uniform_color", new_color);
}
else {
if (idx <= extruder_colors.size()) {
@@ -913,6 +921,21 @@ int GLVolumeCollection::load_wipe_tower_preview(
GUI::PartPlateList& ppl = GUI::wxGetApp().plater()->get_partplate_list();
std::vector<int> plate_extruders = ppl.get_plate(plate_idx)->get_extruders(true);
TriangleMesh wipe_tower_shell = make_cube(width, depth, height);
// The brim is part of the printed footprint: draw it and fold it into the shell so the
// outside-bed shader and the drag clamp react to the true first-layer extent.
const bool show_brim = brim_width > 0.f;
const float brim_height = 0.2f; // one first layer, visual only
TriangleMesh brim_slab;
if (show_brim) {
// The brim follows the real first-layer outline: a Type2 cone-wall tower's base bulges
// past the body box. The wall type and angle are print settings, the planner a printer one.
const DynamicPrintConfig &print_cfg = GUI::wxGetApp().preset_bundle->prints.get_edited_preset().config;
const DynamicPrintConfig &printer_cfg = GUI::wxGetApp().preset_bundle->printers.get_edited_preset().config;
const Polygon outline = estimate_wipe_tower_first_layer_outline(print_cfg, resolve_wipe_tower_type(printer_cfg), width, depth, height);
const Polygons brim_outline = offset(outline, scaled(brim_width));
brim_slab = WipeTower::its_make_rib_brim(brim_outline.empty() ? outline : brim_outline.front(), brim_height);
wipe_tower_shell.merge(brim_slab);
}
for (int extruder_id : plate_extruders) {
if (extruder_id <= extruder_colors.size())
colors.push_back(extruder_colors[extruder_id - 1]);
@@ -923,14 +946,19 @@ int GLVolumeCollection::load_wipe_tower_preview(
// Orca: make it transparent
for(auto& color : colors)
color.a(0.66f);
const size_t slab_count = colors.size(); // per-filament body slabs; the brim part comes after
if (show_brim && !colors.empty())
colors.push_back(colors.front());
volumes.emplace_back(new GLWipeTowerVolume(colors));
GLWipeTowerVolume& v = *dynamic_cast<GLWipeTowerVolume*>(volumes.back());
v.model_per_colors.resize(colors.size());
for (int i = 0; i < colors.size(); i++) {
TriangleMesh color_part = make_cube(width, depth / colors.size(), height);
color_part.translate({ 0.f, depth * i / colors.size(), 0. });
for (size_t i = 0; i < slab_count; i++) {
TriangleMesh color_part = make_cube(width, depth / slab_count, height);
color_part.translate({ 0.f, depth * i / slab_count, 0. });
v.model_per_colors[i].init_from(color_part);
}
if (show_brim && !colors.empty())
v.model_per_colors[slab_count].init_from(brim_slab);
v.model.init_from(wipe_tower_shell);
v.mesh_raycaster = std::make_unique<GUI::MeshRaycaster>(std::make_shared<const TriangleMesh>(wipe_tower_shell));
v.set_convex_hull(wipe_tower_shell);
+27 -37
View File
@@ -1,6 +1,7 @@
#include "AMSDryControl.hpp"
#include "slic3r/GUI/DeviceCore/DevFilaSystem.h"
#include "GUI_App.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "I18N.hpp"
#include "slic3r/GUI/DeviceCore/DevExtruderSystem.h"
@@ -437,7 +438,7 @@ wxBoxSizer* AMSDryCtrWin::create_normal_state_panel(wxPanel* parent)
m_temperature_input = new wxTextCtrl(parent, wxID_ANY, "", wxDefaultPosition, wxSize(FromDIP(80), -1));
m_temperature_input->SetMaxLength(3); // Limit to 3 digits
m_temperature_input->Bind(wxEVT_CHAR, [this](wxKeyEvent& event) {
m_temperature_input->Bind(wxEVT_CHAR, [](wxKeyEvent& event) {
int keycode = event.GetKeyCode();
if (keycode >= '0' && keycode <= '9') {
event.Skip();
@@ -464,7 +465,7 @@ wxBoxSizer* AMSDryCtrWin::create_normal_state_panel(wxPanel* parent)
m_time_input = new wxTextCtrl(parent, wxID_ANY, "", wxDefaultPosition, wxSize(FromDIP(100), -1));
m_time_input->SetMaxLength(3); // Limit to 3 digits
m_time_input->Bind(wxEVT_CHAR, [this](wxKeyEvent& event) {
m_time_input->Bind(wxEVT_CHAR, [](wxKeyEvent& event) {
int keycode = event.GetKeyCode();
if (keycode >= '0' && keycode <= '9') {
event.Skip();
@@ -698,7 +699,7 @@ wxBoxSizer* AMSDryCtrWin::create_guide_info_section(wxPanel* parent)
m_rotate_spool_toggle = new wxCheckBox(parent, wxID_ANY, "");
m_rotate_spool_toggle->SetValue(false);
m_rotate_spool_toggle->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& event) {
m_rotate_spool_toggle->Bind(wxEVT_CHECKBOX, [](wxCommandEvent& event) {
bool is_checked = event.IsChecked();
// Add toggle behavior logic here
});
@@ -1511,6 +1512,10 @@ void AMSDryCtrWin::update_filament_guide_info(DevAms* dev_ams)
m_temperature_input->GetValue().ToLong(&input_temp);
bool can_start = true;
// "GFA00" is Bambu's PLA id; GetFilamentDryingPreset is keyed by our OF ids.
auto* agent = wxGetApp().getAgent();
const std::string pla_filament_id = agent ? agent->to_orca_filament_id("GFA00") : std::string("GFA00");
int slot_count = 0, empty_count = 0;
for (auto& tray_pair : dev_ams->GetTrays()) {
if (!tray_pair.second) {
@@ -1526,13 +1531,15 @@ void AMSDryCtrWin::update_filament_guide_info(DevAms* dev_ams)
wxString filament_type = tray_pair.second->get_display_filament_type();
DevFilamentDryingPreset preset;
if (filament_type.IsEmpty()) {
auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset("GFA00");
auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset(pla_filament_id);
if (!fallback_preset) continue; // no PLA preset (e.g. the id map is missing): skip, don't throw
preset = fallback_preset.value();
filament_type = "?";
} else if (preset_opt.has_value()) {
preset = preset_opt.value();
} else {
auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset("GFA00");
auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset(pla_filament_id);
if (!fallback_preset) continue;
preset = fallback_preset.value();
}
std::string icon_path = "dev_ams_dry_ctr_enable";
@@ -1594,39 +1601,21 @@ int AMSDryCtrWin::update_filament_list(DevAms* dev_ams, MachineObject* obj)
}
stream << std::fixed << std::setprecision(1) << obj->GetExtderSystem()->GetNozzleDiameter(extruder_id);
std::string nozzle_diameter_str = stream.str();
std::set<std::string> printer_names = preset_bundle->get_printer_names_by_printer_type_and_nozzle(
DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str);
for (auto filament_it = filaments.begin(); filament_it != filaments.end(); ++filament_it) {
Preset& preset = *filament_it;
// Filter by system preset: root preset and (system preset or user preset is supported)
if (filaments.get_preset_base(*filament_it) != &preset || (!filament_it->is_system && !obj->is_support_user_preset)) {
for (Preset *filament_it : preset_bundle->get_filament_presets_for_machine(
DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str, obj->is_support_user_preset)) {
if (!filament_id_set.insert(filament_it->filament_id).second)
continue;
const std::string filament_alias = filaments.get_preset_alias(*filament_it, true);
if (filament_alias.empty())
continue;
auto opt_info = preset_bundle->get_filament_by_filament_id(filament_it->filament_id);
if (!opt_info.has_value())
continue;
}
ConfigOption * printer_opt = filament_it->config.option("compatible_printers");
ConfigOptionStrings *printer_strs = dynamic_cast<ConfigOptionStrings *>(printer_opt);
if (!printer_strs) continue;
for (auto printer_str : printer_strs->values) {
if (printer_names.find(printer_str) != printer_names.end()) {
if (filament_id_set.find(filament_it->filament_id) != filament_id_set.end()) {
continue;
}
filament_id_set.insert(filament_it->filament_id);
auto filament_alias = filaments.get_preset_alias(*filament_it, true);
if (!filament_alias.empty()) {
auto opt_info = preset_bundle->get_filament_by_filament_id(filament_it->filament_id);
if (opt_info.has_value()) {
auto real_info = opt_info.value();
real_info.filament_name = filament_alias;
m_tray_ids.push_back(std::move(real_info));
m_trays_combo->Append(wxString::FromUTF8(filament_alias));
}
}
}
}
opt_info->filament_name = filament_alias;
m_tray_ids.push_back(std::move(*opt_info));
m_trays_combo->Append(wxString::FromUTF8(filament_alias));
}
if (m_tray_ids.empty()) {
@@ -1701,9 +1690,10 @@ int AMSDryCtrWin::update_filament_list(DevAms* dev_ams, MachineObject* obj)
// Select recommended drying temperature and default filament
float min_dry_temp = std::numeric_limits<float>::max();
std::string default_filament_id = "GFA00";
auto* agent = wxGetApp().getAgent();
std::string default_filament_id = agent ? agent->to_orca_filament_id("GFA00") : std::string("GFA00"); // compared against m_tray_ids[i].filament_id (our OF ids) below
bool has_ready = false;
const auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset("GFA00");
const auto fallback_preset = DevUtilBackend::GetFilamentDryingPreset(default_filament_id);
for (const auto& tray_pair : dev_ams->GetTrays()) {
if (!tray_pair.second || !tray_pair.second->is_tray_info_ready()) continue;
has_ready = true;
+1 -7
View File
@@ -14,6 +14,7 @@
//Previous defintions
class wxGrid;
class ProgressBar;
namespace Slic3r {
@@ -55,7 +56,6 @@ private:
Label* m_text_label;
wxStaticBitmap* m_icon_bitmap;
int m_target_size;
std::string m_icon_name;
ScalableBitmap m_icon;
};
@@ -98,12 +98,6 @@ private:
wxSimplebook* m_main_simplebook{nullptr};
wxPanel* m_original_page{nullptr};
wxWindow* m_amswin{nullptr};
wxBoxSizer* m_sizer_ams_items{nullptr};
wxScrolledWindow* m_panel_prv_left {nullptr};
wxScrolledWindow* m_panel_prv_right{nullptr};
wxBoxSizer* m_sizer_prv_left{nullptr};
wxBoxSizer* m_sizer_prv_right{nullptr};
// left panel related members
ScalableBitmap m_humidity_image;
+95 -121
View File
@@ -2,6 +2,8 @@
#include "ExtrusionCalibration.hpp"
#include "MsgDialog.hpp"
#include "GUI_App.hpp"
#include "GUI.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "libslic3r/Preset.hpp"
#include "I18N.hpp"
#include <algorithm>
@@ -681,6 +683,19 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event)
}
// Orca: log the tray payload this dialog hands the printer, so the filament_id resolved from the
// dropdown selection can be checked against the tray_info_idx the AMS actually receives. A
// BBL-tagged (RFID) tray is read-only here, so nothing is published for it.
BOOST_LOG_TRIVIAL(info) << "ams_materials_setting: " << (m_is_third ? "sending" : "NOT sending (BBL RFID tray, read-only)")
<< ", ams_id = " << ams_id << ", slot_id = " << slot_id
<< ", selected = " << m_comboBox_filament->GetValue().ToStdString()
<< ", tray_info_idx (filament_id) = " << ams_filament_id
<< ", setting_id = " << ams_setting_id
<< ", tray_type = " << m_filament_type
<< ", tray_color = " << col_buf
<< ", nozzle_temp_min = " << nozzle_temp_min_int
<< ", nozzle_temp_max = " << nozzle_temp_max_int;
// set filament
if (m_is_third) {
obj->command_ams_filament_settings(ams_id, slot_id, ams_filament_id, ams_setting_id, std::string(col_buf), m_filament_type, nozzle_temp_min_int, nozzle_temp_max_int);
@@ -802,7 +817,10 @@ void AMSMaterialsSetting::set_color(wxColour color)
fila_color.m_colors.insert(color);
fila_color.EndSet(m_clr_picker->ctype);
auto clr_query = GUI::wxGetApp().get_filament_color_code_query();
m_clr_name->SetLabelText(clr_query->GetFilaColorName(ams_filament_id, fila_color));
// ams_filament_id is our OF id; GetFilaColorName looks up filaments_color_codes.json,
// downloaded from Bambu and keyed by the printer's own ids, so translate for this lookup only.
auto* agent = GUI::wxGetApp().getAgent();
m_clr_name->SetLabelText(clr_query->GetFilaColorName(agent ? agent->from_orca_filament_id(ams_filament_id) : ams_filament_id, fila_color));
}
void AMSMaterialsSetting::set_empty_color(wxColour color)
@@ -823,7 +841,10 @@ void AMSMaterialsSetting::set_colors(std::vector<wxColour> colors)
for (const auto& clr : colors) { fila_color.m_colors.insert(clr); }
fila_color.EndSet(m_clr_picker->ctype);
auto clr_query = GUI::wxGetApp().get_filament_color_code_query();
m_clr_name->SetLabelText(clr_query->GetFilaColorName(ams_filament_id, fila_color));
// ams_filament_id is our OF id; GetFilaColorName looks up filaments_color_codes.json,
// downloaded from Bambu and keyed by the printer's own ids, so translate for this lookup only.
auto* agent = GUI::wxGetApp().getAgent();
m_clr_name->SetLabelText(clr_query->GetFilaColorName(agent ? agent->from_orca_filament_id(ams_filament_id) : ams_filament_id, fila_color));
}
}
@@ -932,7 +953,6 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi
m_input_k_val->GetTextCtrl()->SetValue(k);
m_input_n_val->GetTextCtrl()->SetValue(n);
int idx = 0;
wxArrayString filament_items;
wxString bambu_filament_name;
wxString hint_filament_name; // the hint type to be selected
@@ -940,6 +960,9 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi
std::unordered_map<wxString, wxString> query_filament_types; //
std::set<std::string> filament_id_set;
// The alias keyed map has to start empty: it is a member, so a stale alias left by an earlier
// popup (a different printer, a different nozzle) would resolve to that printer's filament_id.
map_filament_items.clear();
PresetBundle * preset_bundle = wxGetApp().preset_bundle;
std::ostringstream stream;
// Defensive: this dialog is opened only from StatusPanel (BBL-only) today, so the fallback fires
@@ -952,83 +975,48 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi
}
stream << std::fixed << std::setprecision(1) << machine_diameter;
std::string nozzle_diameter_str = stream.str();
std::set<std::string> printer_names = preset_bundle->get_printer_names_by_printer_type_and_nozzle(DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str);
if (preset_bundle) {
BOOST_LOG_TRIVIAL(trace) << "system_preset_bundle filament number=" << preset_bundle->filaments.size();
for (auto filament_it = preset_bundle->filaments.begin(); filament_it != preset_bundle->filaments.end(); filament_it++) {
//filter by system preset
Preset& preset = *filament_it;
/*The situation where the user preset is not displayed is as follows:
1. Not a root preset
2. Not system preset and the printer firmware does not support user preset */
if (preset_bundle->filaments.get_preset_base(*filament_it) != &preset || (!filament_it->is_system && !obj->is_support_user_preset)) {
for (Preset *filament_it : preset_bundle->get_filament_presets_for_machine(
DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str, obj->is_support_user_preset)) {
if (!filament_id_set.insert(filament_it->filament_id).second)
continue;
const std::string alias = preset_bundle->filaments.get_preset_alias(*filament_it, true);
if (alias.empty())
continue;
}
ConfigOption * printer_opt = filament_it->config.option("compatible_printers");
ConfigOptionStrings *printer_strs = dynamic_cast<ConfigOptionStrings *>(printer_opt);
for (auto printer_str : printer_strs->values) {
if (printer_names.find(printer_str) != printer_names.end()) {
if (filament_id_set.find(filament_it->filament_id) != filament_id_set.end()) {
continue;
} else {
filament_id_set.insert(filament_it->filament_id);
// name matched
if (filament_it->is_system) {
filament_items.push_back(filament_it->alias);
_collect_filament_info(filament_it->alias, preset, query_filament_vendors, query_filament_types);
filament_items.push_back(alias);
_collect_filament_info(alias, *filament_it, query_filament_vendors, query_filament_types);
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[filament_it->alias] = filament_infos;
} else {
char target = '@';
size_t pos = filament_it->name.find(target);
if (pos != std::string::npos) {
std::string user_preset_alias = filament_it->name.substr(0, pos - 1);
wxString wx_user_preset_alias = wxString(user_preset_alias.c_str(), wxConvUTF8);
user_preset_alias = wx_user_preset_alias.ToStdString();
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[alias] = filament_infos;
filament_items.push_back(user_preset_alias);
_collect_filament_info(user_preset_alias, preset, query_filament_vendors, query_filament_types);
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[user_preset_alias] = filament_infos;
}
}
if (filament_it->filament_id == ams_filament_id) {
hint_filament_name = from_u8(filament_it->alias);
bambu_filament_name = from_u8(filament_it->alias);
if (filament_it->filament_id == ams_filament_id) {
hint_filament_name = from_u8(alias);
bambu_filament_name = from_u8(alias);
// update if nozzle_temperature_range is found
ConfigOption *opt_min = filament_it->config.option("nozzle_temperature_range_low");
if (opt_min) {
ConfigOptionInts *opt_min_ints = dynamic_cast<ConfigOptionInts *>(opt_min);
if (opt_min_ints) {
wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(0));
m_input_nozzle_min->GetTextCtrl()->SetValue(text_nozzle_temp_min);
}
}
ConfigOption *opt_max = filament_it->config.option("nozzle_temperature_range_high");
if (opt_max) {
ConfigOptionInts *opt_max_ints = dynamic_cast<ConfigOptionInts *>(opt_max);
if (opt_max_ints) {
wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(0));
m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max);
}
}
}
idx++;
// update if nozzle_temperature_range is found
ConfigOption *opt_min = filament_it->config.option("nozzle_temperature_range_low");
if (opt_min) {
ConfigOptionInts *opt_min_ints = dynamic_cast<ConfigOptionInts *>(opt_min);
if (opt_min_ints) {
wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(0));
m_input_nozzle_min->GetTextCtrl()->SetValue(text_nozzle_temp_min);
}
}
ConfigOption *opt_max = filament_it->config.option("nozzle_temperature_range_high");
if (opt_max) {
ConfigOptionInts *opt_max_ints = dynamic_cast<ConfigOptionInts *>(opt_max);
if (opt_max_ints) {
wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(0));
m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max);
}
}
}
}
}
@@ -1251,56 +1239,47 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt)
stream << std::fixed << std::setprecision(1) << machine_diameter;
}
std::string nozzle_diameter_str = stream.str();
std::set<std::string> printer_names = preset_bundle->get_printer_names_by_printer_type_and_nozzle(DevPrinterConfigUtil::get_printer_display_name(obj->printer_type),
nozzle_diameter_str);
for (auto it = preset_bundle->filaments.begin(); it != preset_bundle->filaments.end(); it++) {
if (!m_comboBox_filament->GetValue().IsEmpty()) {
auto filament_item = map_filament_items[m_comboBox_filament->GetValue().ToStdString()];
std::string filament_id = filament_item.filament_id;
if (it->filament_id.compare(filament_id) == 0) {
ConfigOption * printer_opt = it->config.option("compatible_printers");
ConfigOptionStrings *printer_strs = dynamic_cast<ConfigOptionStrings *>(printer_opt);
bool has_compatible_printer = false;
for (auto printer_str : printer_strs->values) {
if (printer_names.find(printer_str) != printer_names.end()) {
has_compatible_printer = true;
break;
}
// Resolve the selection against the same list Popup() built the dropdown from, so the two
// halves of the dialog cannot disagree about which filaments this machine can use.
const std::string selected = m_comboBox_filament->GetValue().ToStdString();
if (!selected.empty()) {
const std::string filament_id = map_filament_items[selected].filament_id;
for (Preset *it : preset_bundle->get_filament_presets_for_machine(
DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str, obj->is_support_user_preset)) {
if (it->filament_id != filament_id)
continue;
// ) if nozzle_temperature_range is found
ConfigOption* opt_min = it->config.option("nozzle_temperature_range_low");
if (opt_min) {
ConfigOptionInts* opt_min_ints = dynamic_cast<ConfigOptionInts*>(opt_min);
if (opt_min_ints) {
wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(0));
m_input_nozzle_min->GetTextCtrl()->SetValue(text_nozzle_temp_min);
}
if (!it->is_system && !has_compatible_printer) continue;
// ) if nozzle_temperature_range is found
ConfigOption* opt_min = it->config.option("nozzle_temperature_range_low");
if (opt_min) {
ConfigOptionInts* opt_min_ints = dynamic_cast<ConfigOptionInts*>(opt_min);
if (opt_min_ints) {
wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(0));
m_input_nozzle_min->GetTextCtrl()->SetValue(text_nozzle_temp_min);
}
}
ConfigOption* opt_max = it->config.option("nozzle_temperature_range_high");
if (opt_max) {
ConfigOptionInts* opt_max_ints = dynamic_cast<ConfigOptionInts*>(opt_max);
if (opt_max_ints) {
wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(0));
m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max);
}
}
ConfigOption* opt_type = it->config.option("filament_type");
bool found_filament_type = false;
if (opt_type) {
ConfigOptionStrings* opt_type_strs = dynamic_cast<ConfigOptionStrings*>(opt_type);
if (opt_type_strs) {
found_filament_type = true;
//m_filament_type = opt_type_strs->get_at(0);
std::string display_filament_type;
m_filament_type = it->config.get_filament_type(display_filament_type);
}
}
if (!found_filament_type)
m_filament_type = "";
break;
}
ConfigOption* opt_max = it->config.option("nozzle_temperature_range_high");
if (opt_max) {
ConfigOptionInts* opt_max_ints = dynamic_cast<ConfigOptionInts*>(opt_max);
if (opt_max_ints) {
wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(0));
m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max);
}
}
ConfigOption* opt_type = it->config.option("filament_type");
bool found_filament_type = false;
if (opt_type) {
ConfigOptionStrings* opt_type_strs = dynamic_cast<ConfigOptionStrings*>(opt_type);
if (opt_type_strs) {
found_filament_type = true;
//m_filament_type = opt_type_strs->get_at(0);
std::string display_filament_type;
m_filament_type = it->config.get_filament_type(display_filament_type);
}
}
if (!found_filament_type)
m_filament_type = "";
break;
}
}
}
@@ -1938,11 +1917,6 @@ void ColorPickerPopup::paintEvent(wxPaintEvent& evt)
void ColorPickerPopup::OnDismiss() {}
void ColorPickerPopup::Popup()
{
PopupWindow::Popup();
}
bool ColorPickerPopup::ProcessLeftDown(wxMouseEvent& event) {
return PopupWindow::ProcessLeftDown(event);
}
-1
View File
@@ -85,7 +85,6 @@ public:
void set_ams_colours(std::vector<wxColour> ams);
void set_def_colour(wxColour col);
void paintEvent(wxPaintEvent& evt);
void Popup();
virtual void OnDismiss() wxOVERRIDE;
virtual bool ProcessLeftDown(wxMouseEvent& event) wxOVERRIDE;
+2 -2
View File
@@ -292,7 +292,7 @@ void AMSSetting::UpdateByObj(MachineObject* obj)
update_ams_img(obj);
m_ams_type->Update(obj);
m_ams_type->UpdateInfo(obj);
//m_ams_arrange_order->Update(obj);
update_insert_material_read_mode(obj);
m_sizer_remain_block->Show(obj->is_support_update_remain);
@@ -624,7 +624,7 @@ void AMSSettingTypePanel::CreateGui()
Fit();
}
void AMSSettingTypePanel::Update(const MachineObject* obj)
void AMSSettingTypePanel::UpdateInfo(const MachineObject* obj)
{
if (!obj) {
Show(false);
+1 -1
View File
@@ -110,7 +110,7 @@ public:
~AMSSettingTypePanel();
public:
void Update(const MachineObject* obj);
void UpdateInfo(const MachineObject* obj);
private:
void CreateGui();
+170
View File
@@ -0,0 +1,170 @@
#include "AVVideoDecoder.hpp"
#include <assert.h>
extern "C"
{
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
}
AVVideoDecoder::AVVideoDecoder()
{
codec_ctx_ = avcodec_alloc_context3(nullptr);
}
AVVideoDecoder::~AVVideoDecoder()
{
if (sws_ctx_)
sws_freeContext(sws_ctx_);
if (frame_)
av_frame_free(&frame_);
if (codec_ctx_)
avcodec_free_context(&codec_ctx_);
}
int AVVideoDecoder::open(Bambu_StreamInfo const &info)
{
auto codec_id = info.sub_type == AVC1 ? AV_CODEC_ID_H264 : AV_CODEC_ID_MJPEG;
auto codec = avcodec_find_decoder(codec_id);
if (codec == nullptr) {
fprintf(stderr, "AVVideoDecoder: unsupported codec!\n");
return -1; // Codec not found
}
/* open the coderc */
if (avcodec_open2(codec_ctx_, codec, nullptr) < 0) {
fprintf(stderr, "AVVideoDecoder: could not open codec\n");
return -1;
}
// Allocate an AVFrame structure
frame_ = av_frame_alloc();
if (frame_ == nullptr)
return -1;
return 0;
}
int AVVideoDecoder::decode(const Bambu_Sample &sample)
{
int ret = -1;
AVPacket *pkt = av_packet_alloc();
if (!pkt) {
return ret;
}
ret = av_new_packet(pkt, sample.size);
if (ret != 0) {
av_packet_free(&pkt);
return ret;
}
memcpy(pkt->data, sample.buffer, size_t(sample.size));
ret = avcodec_send_packet(codec_ctx_, pkt);
if (ret == 0) {
got_frame_ = avcodec_receive_frame(codec_ctx_, frame_) == 0;
}
av_packet_unref(pkt);
av_packet_free(&pkt);
return ret;
}
int AVVideoDecoder::flush()
{
int ret = avcodec_send_packet(codec_ctx_, nullptr);
got_frame_ = avcodec_receive_frame(codec_ctx_, frame_) == 0;
return ret;
}
void AVVideoDecoder::close()
{
}
bool AVVideoDecoder::toWxImage(wxImage &image, wxSize const &size2)
{
if (!got_frame_)
return false;
auto size1 = size2;
if (!size1.IsFullySpecified())
size1 = {frame_->width, frame_->height };
auto size = size1;
if (size.GetWidth() & 0x0f) {
size.SetWidth((size.GetWidth() & ~0x0f) + 0x10);
if (size.GetWidth() != width_) {
std::fill(bits_.begin(), bits_.end(), 0);
width_ = size.GetWidth();
}
}
AVPixelFormat wxFmt = AV_PIX_FMT_RGB24;
sws_ctx_ = sws_getCachedContext(sws_ctx_,
frame_->width, frame_->height, AVPixelFormat(frame_->format),
size1.GetWidth(), size1.GetHeight(), wxFmt,
SWS_GAUSS,
nullptr, nullptr, nullptr);
if (sws_ctx_ == nullptr)
return false;
int length = size.GetWidth() * size.GetHeight() * 3;
if (bits_.size() < length)
bits_.resize(length);
uint8_t * datas[] = { bits_.data() };
int strides[] = { size.GetWidth() * 3 };
int result_h = sws_scale(sws_ctx_, frame_->data, frame_->linesize, 0, frame_->height, datas, strides);
if (result_h != size.GetHeight()) {
return false;
}
// Copy: the frame outlives this decoder and is painted by the GUI thread while the
// next sws_scale is already overwriting bits_, so it must own its pixels. The Windows
// path below needs no equivalent, wxBitmap copies the bits into GDI.
image = wxImage(size.GetWidth(), size.GetHeight(), bits_.data(), true).Copy();
if (!image.IsOk()) {
fprintf(stderr, "AVVideoDecoder: image not ok %dx%d\n", size.GetWidth(), size.GetHeight());
return false;
}
return true;
}
bool AVVideoDecoder::toWxBitmap(wxBitmap &bitmap, wxSize const &size2)
{
if (!got_frame_)
return false;
auto size1 = size2;
if (!size1.IsFullySpecified())
size1 = {frame_->width, frame_->height };
auto size = size1;
if (size.GetWidth() & 0x0f) {
size.SetWidth((size.GetWidth() & ~0x0f) + 0x10);
if (size.GetWidth() != width_) {
std::fill(bits_.begin(), bits_.end(), 0);
width_ = size.GetWidth();
}
}
AVPixelFormat wxFmt = AV_PIX_FMT_RGB32;
sws_ctx_ = sws_getCachedContext(sws_ctx_,
frame_->width, frame_->height, AVPixelFormat(frame_->format),
size1.GetWidth(), size1.GetHeight(), wxFmt,
SWS_GAUSS,
nullptr, nullptr, nullptr);
if (sws_ctx_ == nullptr)
return false;
int length = size.GetWidth() * size.GetHeight() * 4;
if (bits_.size() < length)
bits_.resize(length);
uint8_t *datas[] = { bits_.data() };
int strides[] = { size.GetWidth() * 4 };
int result_h = sws_scale(sws_ctx_, frame_->data, frame_->linesize, 0, frame_->height, datas, strides);
if (result_h != size.GetHeight()) {
fprintf(stderr, "AVVideoDecoder: result_h %d %d\n", result_h, size.GetHeight());
return false;
}
bitmap = wxBitmap((char const *) bits_.data(), size.GetWidth(), size.GetHeight(), 32);
assert(bitmap.IsOk());
if (!bitmap.IsOk()) {
fprintf(stderr, "AVVideoDecoder: bitmap not ok %dx%d\n", size.GetWidth(), size.GetHeight());
return false;
}
return true;
}
+46
View File
@@ -0,0 +1,46 @@
#ifndef AVVIDEODECODER_HPP
#define AVVIDEODECODER_HPP
#include "Printer/BambuTunnel.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
#include <vector>
#include <wx/bitmap.h>
#include <wx/gdicmn.h>
#include <wx/image.h>
class wxBitmap;
class AVVideoDecoder
{
public:
AVVideoDecoder();
~AVVideoDecoder();
public:
int open(Bambu_StreamInfo const &info);
int decode(Bambu_Sample const &sample);
int flush();
void close();
bool toWxImage(wxImage &image, wxSize const &size);
bool toWxBitmap(wxBitmap &bitmap, wxSize const & size);
private:
AVCodecContext *codec_ctx_ = nullptr;
AVFrame * frame_ = nullptr;
SwsContext * sws_ctx_ = nullptr;
bool got_frame_ = false;
int width_ { 0 }; // scale result width
std::vector<uint8_t> bits_;
};
#endif // AVVIDEODECODER_HPP
+2 -1
View File
@@ -3,6 +3,7 @@
#include "libslic3r/Utils.hpp"
#include "libslic3r/Color.hpp"
#include "BuildCommit.hpp"
#include "GUI.hpp"
#include "GUI_App.hpp"
#include "MainFrame.hpp"
@@ -245,7 +246,7 @@ AboutDialog::AboutDialog()
vesizer->Add(0, 0, 1, wxEXPAND, FromDIP(5));
auto version_string = std::string(SoftFever_VERSION); // _L("Orca Slicer ") + " " + std::string(SoftFever_VERSION);
wxStaticText* version = new wxStaticText(this, wxID_ANY, version_string.c_str(), wxDefaultPosition, wxDefaultSize);
wxStaticText* credits_string = new wxStaticText(this, wxID_ANY, wxString::Format("Build %s", std::string(GIT_COMMIT_HASH)), wxDefaultPosition, wxDefaultSize);
wxStaticText* credits_string = new wxStaticText(this, wxID_ANY, wxString::Format("Build %s", build_commit_label), wxDefaultPosition, wxDefaultSize);
credits_string->SetFont(_build_string_font);
wxFont version_font = GetFont();
version_font = version_font.Scaled(1.85f); // SetPointSize(20) not works on macOS because it uses a 72 PPI reference
-1
View File
@@ -60,7 +60,6 @@ class AboutDialog : public DPIDialog
wxHtmlWindow* m_html;
wxStaticBitmap* m_logo;
int m_copy_rights_btn_id { wxID_ANY };
int m_copy_version_btn_id { wxID_ANY };
public:
AboutDialog();
+1
View File
@@ -11,6 +11,7 @@
#include "MainFrame.hpp"
#include "format.hpp"
#include "Widgets/ProgressDialog.hpp"
#include <wx/tooltip.h>
#include "Widgets/RoundedRectangle.hpp"
#include "Widgets/StaticBox.hpp"
-1
View File
@@ -457,7 +457,6 @@ private:
ScalableBitmap close_img;
wxStaticBitmap* curr_humidity_img;
wxStaticBitmap* m_img;
Label* m_staticText;;
Label* m_staticText_note;
+1 -1
View File
@@ -406,7 +406,7 @@ void AmsMapingPopup::update_ams_data_multi_machines()
int ams_type = 1;
int nozzle_id = 0;
if (ams_type >= 1 || ams_type <= 3) { // 1:ams 2:ams-lite 3:n3f
if (ams_type >= 1 && ams_type <= 3) { // 1:ams 2:ams-lite 3:n3f
auto sizer_mapping_list = new wxBoxSizer(wxHORIZONTAL);
auto ams_mapping_item_container = new MappingContainer(nozzle_id == 0 ? m_right_marea_panel : m_left_marea_panel, "AMS-1", 4);
-2
View File
@@ -93,8 +93,6 @@ private:
CenteredTitle* m_title_ctrl { nullptr };
wxString m_titleText;
wxAuiToolBarItem* m_account_item;
wxAuiToolBarItem* m_model_store_item;
//wxAuiToolBarItem *m_publish_item;
wxAuiToolBarItem* m_undo_item;
+3 -1
View File
@@ -848,7 +848,9 @@ void BackgroundSlicingProcess::finalize_gcode()
case CopyFileResult::SUCCESS: break; // no error
case CopyFileResult::FAIL_COPY_FILE:
throw Slic3r::ExportError(GUI::format(
_L("Copying of the temporary G-code to the output G-code failed. Maybe the SD card is write locked?\nError message: %1%"),
m_export_path_on_removable_media ?
_L("Copying of the temporary G-code to the output G-code failed. Maybe the SD card is write locked?\nError message: %1%") :
_L("Copying of the temporary G-code to the output G-code failed.\nError message: %1%"),
error_message));
break;
case CopyFileResult::FAIL_FILES_DIFFERENT:
-30
View File
@@ -1,30 +0,0 @@
//
// BambuPlayer.h
// BambuPlayer
//
// Created by cmguo on 2021/12/6.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVSampleBufferDisplayLayer.h>
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface BambuPlayer : NSObject
+ (void) initialize;
- (instancetype) initWithDisplayLayer: (AVSampleBufferDisplayLayer*) layer;
- (instancetype) initWithImageView: (NSView*) view;
- (int) open: (char const *) url;
- (NSSize) videoSize;
- (int) play;
- (void) stop;
- (void) close;
- (void) setLogger: (void (*)(void const * context, int level, char const * msg)) logger withContext: (void const *) context;
@end
NS_ASSUME_NONNULL_END
@@ -5,8 +5,10 @@
#include <thread>
#include "GUI_App.hpp"
#include "GUI_Utils.hpp"
#include <wx/timer.h>
class Button;
class Label;
class CheckBox;
namespace Slic3r { namespace GUI {
class CapsuleButton;
+3 -3
View File
@@ -468,7 +468,7 @@ PingCodeBindDialog::~PingCodeBindDialog() {
m_link_privacy_title->SetFont(Label::Head_13);
m_link_privacy_title->SetMaxSize(wxSize(FromDIP(450), -1));
m_link_privacy_title->Wrap(FromDIP(450));
m_link_privacy_title->Bind(wxEVT_LEFT_DOWN, [this](auto& e) {
m_link_privacy_title->Bind(wxEVT_LEFT_DOWN, [](auto& e) {
std::string url;
std::string country_code = Slic3r::GUI::wxGetApp().app_config->get_country_code();
@@ -893,7 +893,7 @@ void BindMachineDialog::on_show(wxShowEvent &event)
}
}
})
.on_error([this](std::string body, std::string error, unsigned status) {
.on_error([](std::string body, std::string error, unsigned status) {
//BOOST_LOG_TRIVIAL(info) << "load oss picture failed, oss path: " << oss_path << " status:" << status << " error:" << error;
}).perform();
}
@@ -1099,7 +1099,7 @@ void UnBindMachineDialog::on_show(wxShowEvent &event)
}
}
})
.on_error([this](std::string body, std::string error, unsigned status) {
.on_error([](std::string body, std::string error, unsigned status) {
//BOOST_LOG_TRIVIAL(info) << "load oss picture failed, oss path: " << oss_path << " status:" << status << " error:" << error;
}).perform();
-9
View File
@@ -65,18 +65,10 @@ private:
wxPanel* request_bind_panel;
wxPanel* binding_panel;
wxScrolledWindow* m_sw_bind_failed_info;
Label* m_bind_failed_info;
Label* m_st_txt_error_code{ nullptr };
Label* m_st_txt_error_desc{ nullptr };
Label* m_st_txt_extra_info{ nullptr };
HyperLink* m_link_network_state{ nullptr };
wxString m_result_info;
wxString m_result_extra;
wxString m_ping_code_wiki;
bool m_show_error_info_state = true;
int m_result_code;
std::shared_ptr<BBLStatusBarBind> m_status_bar;
public:
@@ -110,7 +102,6 @@ private:
wxBitmap m_bitmap_show_error_close;
wxBitmap m_bitmap_show_error_open;
wxScrolledWindow* m_sw_bind_failed_info;
Label* m_bind_failed_info;
Label* m_st_txt_error_code{ nullptr };
Label* m_st_txt_error_desc{ nullptr };
Label* m_st_txt_extra_info{ nullptr };
+9
View File
@@ -0,0 +1,9 @@
#include "BuildCommit.hpp"
#include "git_commit_hash.h"
namespace Slic3r { namespace GUI {
const char *const build_commit_hash = GIT_COMMIT_HASH;
const char *const build_commit_label = GIT_COMMIT_HASH GIT_COMMIT_SUFFIX;
}} // namespace Slic3r::GUI
+15
View File
@@ -0,0 +1,15 @@
#pragma once
// Read these rather than including git_commit_hash.h, which changes with every
// commit and rebuilds everything that includes it.
namespace Slic3r { namespace GUI {
// The commit alone, safe to use in a commit URL.
extern const char *const build_commit_hash;
// The same, with "-dirty" when the build had uncommitted changes. Use this
// wherever the build is shown to a person.
extern const char *const build_commit_label;
}} // namespace Slic3r::GUI
+13 -60
View File
@@ -443,7 +443,7 @@ void HistoryWindow::sync_history_data() {
auto edit_button = new Button(m_history_data_panel, _L("Edit"));
edit_button->SetStyle(ButtonStyle::Confirm, ButtonType::Window);
edit_button->Bind(wxEVT_BUTTON, [this, result, k_value, name_value, edit_button](auto& e) {
edit_button->Bind(wxEVT_BUTTON, [this, result, k_value, name_value](auto& e) {
if (m_ui_op_lock) return;
PACalibResult result_buffer = result;
@@ -702,7 +702,6 @@ wxArrayString NewCalibrationHistoryDialog::get_all_filaments(const MachineObject
wxArrayString filament_items;
std::set<std::string> filament_id_set;
std::set<std::string> printer_names;
std::ostringstream stream;
// If the machine didn't report a nozzle diameter (0.0 = unknown), fall back to the currently
// selected printer preset so the filament list isn't empty.
@@ -714,67 +713,21 @@ wxArrayString NewCalibrationHistoryDialog::get_all_filaments(const MachineObject
stream << std::fixed << std::setprecision(1) << machine_diameter;
std::string nozzle_diameter_str = stream.str();
for (auto printer_it = preset_bundle->printers.begin(); printer_it != preset_bundle->printers.end(); printer_it++) {
// filter by system preset
if (!printer_it->is_system)
continue;
// get printer_model
ConfigOption * printer_model_opt = printer_it->config.option("printer_model");
ConfigOptionString *printer_model_str = dynamic_cast<ConfigOptionString *>(printer_model_opt);
if (!printer_model_str)
continue;
// use printer_model as printer type
if (printer_model_str->value != DevPrinterConfigUtil::get_printer_display_name(obj->printer_type))
continue;
if (printer_it->name.find(nozzle_diameter_str) != std::string::npos)
printer_names.insert(printer_it->name);
}
if (preset_bundle) {
BOOST_LOG_TRIVIAL(trace) << "system_preset_bundle filament number=" << preset_bundle->filaments.size();
for (auto filament_it = preset_bundle->filaments.begin(); filament_it != preset_bundle->filaments.end(); filament_it++) {
// filter by system preset
Preset &preset = *filament_it;
/*The situation where the user preset is not displayed is as follows:
1. Not a root preset
2. Not system preset and the printer firmware does not support user preset */
if (preset_bundle->filaments.get_preset_base(*filament_it) != &preset || (!filament_it->is_system && ! obj->is_support_user_preset)) { continue; }
for (Preset *filament_it : preset_bundle->get_filament_presets_for_machine(
DevPrinterConfigUtil::get_printer_display_name(obj->printer_type), nozzle_diameter_str, obj->is_support_user_preset)) {
if (!filament_id_set.insert(filament_it->filament_id).second)
continue;
const std::string alias = preset_bundle->filaments.get_preset_alias(*filament_it, true);
if (alias.empty())
continue;
ConfigOption * printer_opt = filament_it->config.option("compatible_printers");
ConfigOptionStrings *printer_strs = dynamic_cast<ConfigOptionStrings *>(printer_opt);
for (auto printer_str : printer_strs->values) {
if (printer_names.find(printer_str) != printer_names.end()) {
if (filament_id_set.find(filament_it->filament_id) != filament_id_set.end()) {
continue;
} else {
filament_id_set.insert(filament_it->filament_id);
// name matched
if (filament_it->is_system) {
filament_items.push_back(filament_it->alias);
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[filament_it->alias] = filament_infos;
} else {
char target = '@';
size_t pos = filament_it->name.find(target);
if (pos != std::string::npos) {
std::string user_preset_alias = filament_it->name.substr(0, pos - 1);
wxString wx_user_preset_alias = wxString(user_preset_alias.c_str(), wxConvUTF8);
user_preset_alias = wx_user_preset_alias.ToStdString();
filament_items.push_back(user_preset_alias);
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[user_preset_alias] = filament_infos;
}
}
}
}
}
filament_items.push_back(alias);
FilamentInfos filament_infos;
filament_infos.filament_id = filament_it->filament_id;
filament_infos.setting_id = filament_it->setting_id;
map_filament_items[alias] = filament_infos;
}
}
return filament_items;
+1 -1
View File
@@ -201,7 +201,7 @@ wxWindow* CalibrationDialog::create_check_option(wxString title, wxWindow* paren
checkbox->SetToolTip(tooltip);
text->SetToolTip(tooltip);
text->Bind(wxEVT_LEFT_DOWN, [this, check](wxMouseEvent&) { check->SetValue(check->GetValue() ? false : true); });
text->Bind(wxEVT_LEFT_DOWN, [check](wxMouseEvent&) { check->SetValue(check->GetValue() ? false : true); });
m_checkbox_list[param] = check;
m_checkbox_list[param]->SetValue(true);
return checkbox;
-4
View File
@@ -70,11 +70,7 @@ public:
private:
int m_my_devices_count{ 0 };
int m_other_devices_count{ 0 };
bool m_dismiss{ false };
wxWindow* m_placeholder_panel { nullptr };
wxWindow* m_panel_body{ nullptr };
wxBoxSizer* m_sizer_body{ nullptr };
wxBoxSizer* m_sizer_my_devices{ nullptr };
wxScrolledWindow* m_scrolledWindow{ nullptr };
wxTimer* m_refresh_timer{ nullptr };
+2 -1
View File
@@ -1,6 +1,7 @@
#include "CalibrationWizard.hpp"
#include "I18N.hpp"
#include "GUI_App.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "MsgDialog.hpp"
#include "CalibrationWizardPage.hpp"
#include "../../libslic3r/calib.hpp"
@@ -477,7 +478,7 @@ void CalibrationWizard::on_cali_go_home()
if (go_home_dialog == nullptr)
go_home_dialog = new SecondaryCheckDialog(this, wxID_ANY, _L("Confirm"));
go_home_dialog->Bind(EVT_SECONDARY_CHECK_CONFIRM, [this, method](wxCommandEvent &e) {
go_home_dialog->Bind(EVT_SECONDARY_CHECK_CONFIRM, [this](wxCommandEvent &e) {
if (curr_obj) {
curr_obj->command_task_abort();
} else {
+1 -1
View File
@@ -90,7 +90,7 @@ void CalibrationCaliPage::on_subtask_abort(wxCommandEvent& event)
if (abort_dlg == nullptr) {
abort_dlg = new SecondaryCheckDialog(this->GetParent(), wxID_ANY, _L("Cancel print"));
abort_dlg->Bind(EVT_SECONDARY_CHECK_CONFIRM, [this, obj](wxCommandEvent& e) {
abort_dlg->Bind(EVT_SECONDARY_CHECK_CONFIRM, [obj](wxCommandEvent& e) {
if (obj) obj->command_task_abort();
});
}
+1 -1
View File
@@ -762,7 +762,7 @@ void CaliPageActionPanel::bind_button(CaliPageActionType action_type, bool is_bl
if (is_block) {
m_action_btns[i]->Bind(wxEVT_BUTTON,
[this](wxCommandEvent& evt) {
[](wxCommandEvent& evt) {
MessageDialog msg(nullptr, _L("The current firmware version of the printer does not support calibration.\nPlease upgrade the printer firmware."), _L("Calibration not supported"), wxOK | wxICON_WARNING);
msg.ShowModal();
});
@@ -1,5 +1,7 @@
#include <regex>
#include "CalibrationWizardPresetPage.hpp"
#include "GUI.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "I18N.hpp"
#include "Widgets/Label.hpp"
#include "MsgDialog.hpp"
@@ -360,7 +362,7 @@ void CaliPresetCustomRangePanel::create_panel(wxWindow* parent)
int max_decimal_length;
if (i <= 1)
max_decimal_length = 3;
else if (i >= 2)
else
max_decimal_length = 4;
if (decimal_number > max_decimal_length) {
int allowed_length = number.length() - decimal_number + max_decimal_length;
@@ -1015,7 +1017,7 @@ wxBoxSizer* CalibrationPresetPage::create_ams_items_sizer(MachineObject* obj, wx
auto ams_items_sizer = new wxBoxSizer(wxHORIZONTAL);
for (auto &info : ams_info) {
auto preview_ams_item = new AMSPreview(ams_preview_panel, wxID_ANY, info, info.ams_type);
preview_ams_item->Update(info);
preview_ams_item->UpdateInfo(info);
preview_ams_item->Open();
ams_preview_list.push_back(preview_ams_item);
std::string ams_id = preview_ams_item->get_ams_id();
+4 -3
View File
@@ -1,4 +1,5 @@
#include "CalibrationWizardSavePage.hpp"
#include "GUI.hpp"
#include "I18N.hpp"
#include "Widgets/Label.hpp"
#include "MsgDialog.hpp"
@@ -272,7 +273,7 @@ void CaliPASaveAutoPanel::sync_cali_result(const std::vector<PACalibResult>& cal
preset_names = default_naming(preset_names);
std::vector<PACalibResult> sorted_cali_result = cali_result;
std::sort(sorted_cali_result.begin(), sorted_cali_result.end(), [this](const PACalibResult &left, const PACalibResult& right) {
std::sort(sorted_cali_result.begin(), sorted_cali_result.end(), [](const PACalibResult &left, const PACalibResult& right) {
return left.tray_id < right.tray_id;
});
@@ -366,7 +367,7 @@ void CaliPASaveAutoPanel::sync_cali_result(const std::vector<PACalibResult>& cal
}
}
comboBox_tray_name->Bind(wxEVT_COMBOBOX, [this, comboBox_tray_name, k_value, n_value](auto& e) {
comboBox_tray_name->Bind(wxEVT_COMBOBOX, [comboBox_tray_name](auto& e) {
int selection = comboBox_tray_name->GetSelection();
auto history = filtered_results[selection];
});
@@ -744,7 +745,7 @@ void CaliPASaveAutoPanel::sync_cali_result_for_multi_extruder(const std::vector<
}
}
comboBox_tray_name->Bind(wxEVT_COMBOBOX, [this, comboBox_tray_name, k_value, n_value](auto &e) {
comboBox_tray_name->Bind(wxEVT_COMBOBOX, [comboBox_tray_name](auto &e) {
int selection = comboBox_tray_name->GetSelection();
auto history = filtered_results[selection];
});
+1 -1
View File
@@ -193,7 +193,7 @@ public:
void show_panels(CalibrationMethod method, const PrinterSeries printer_ser);
void on_device_connected(MachineObject* obj);
void on_device_connected(MachineObject* obj) override;
void update(MachineObject* obj) override;
@@ -48,8 +48,8 @@ public:
void create_page(wxWindow* parent);
void on_reset_page();
void on_device_connected(MachineObject* obj);
void on_reset_page() override;
void on_device_connected(MachineObject* obj) override;
void msw_rescale() override;
};
@@ -63,8 +63,8 @@ public:
long style = wxTAB_TRAVERSAL);
void create_page(wxWindow* parent);
void on_reset_page();
void on_device_connected(MachineObject* obj);
void on_reset_page() override;
void on_device_connected(MachineObject* obj) override;
void msw_rescale() override;
};
+1 -1
View File
@@ -140,7 +140,7 @@ CameraPopup::CameraPopup(wxWindow *parent)
vcamera_guide_link->Wrap(-1);
vcamera_guide_link->SetForegroundColour(wxColour(0x1F, 0x8E, 0xEA));
auto text_size = vcamera_guide_link->GetTextExtent(text);
vcamera_guide_link->Bind(wxEVT_LEFT_DOWN, [this, url](wxMouseEvent& e) {wxLaunchDefaultBrowser(url); });
vcamera_guide_link->Bind(wxEVT_LEFT_DOWN, [url](wxMouseEvent& e) {wxLaunchDefaultBrowser(url); });
link_underline = new wxPanel(m_panel, wxID_ANY, wxDefaultPosition, wxSize(-1, 1), wxTAB_TRAVERSAL);
link_underline->SetBackgroundColour(wxColour(0x1F, 0x8E, 0xEA));
+2
View File
@@ -72,8 +72,10 @@ private:
SwitchButton* m_switch_recording;
wxStaticText* m_text_vcamera;
SwitchButton* m_switch_vcamera;
#if !BBL_RELEASE_TO_PUBLIC
wxStaticText* m_text_liveview_retry;
SwitchButton* m_switch_liveview_retry;
#endif //BBL_RELEASE_TO_PUBLIC
wxStaticText* m_custom_camera_hint;
TextInput* m_custom_camera_input;
Button* m_custom_camera_input_confirm;
+1
View File
@@ -1,5 +1,6 @@
#include "GUI_App.hpp"
#include "CapsuleButton.hpp"
#include "Widgets/StateColor.hpp"
#include <wx/dcbuffer.h>
#include "wx/graphics.h"
#include "Widgets/Label.hpp"
+951
View File
@@ -0,0 +1,951 @@
#include "ColorDecomposeDialog.hpp"
#include <algorithm>
#include <cmath>
#include <functional>
#include <memory>
#include <set>
#include <wx/sizer.h>
#include <wx/dcclient.h>
#include <wx/dcbuffer.h>
#include "wx/graphics.h"
#include "I18N.hpp"
#include "GUI.hpp"
#include "GUI_App.hpp"
#include "format.hpp"
#include "Widgets/ComboBox.hpp"
#include "Widgets/DropDown.hpp"
#include "Widgets/Button.hpp"
#include "Widgets/CheckBox.hpp"
#include "Widgets/Label.hpp"
#include "wxExtensions.hpp"
#include "ColorDecomposeSupport.hpp"
#include "libslic3r/ColorDecomposeRecipe.hpp"
namespace Slic3r {
namespace GUI {
static const wxColour COLOR_BRAND("#009688");
static const wxColour COLOR_BORDER_NORMAL("#EEEEEE");
static const wxColour COLOR_BG_CARD("#F8F8F8");
static const wxColour COLOR_LABEL_GREY("#ACACAC");
static const wxColour COLOR_TEXT_DARK("#262E30");
static const wxColour COLOR_DIVIDER("#EEEEEE");
// Standard CMYW base colors
static const wxColour CMYW_CYAN(0, 255, 255);
static const wxColour CMYW_MAGENTA(255, 0, 255);
static const wxColour CMYW_YELLOW(255, 255, 0);
static const wxColour CMYW_WHITE(255, 255, 255);
// Standard RYBW base colors
static const wxColour RYBW_RED(255, 0, 0);
static const wxColour RYBW_YELLOW(255, 255, 0);
static const wxColour RYBW_BLUE(0, 0, 255);
static const wxColour RYBW_WHITE(255, 255, 255);
static size_t mode_index(DecomposeMode mode)
{
return static_cast<size_t>(mode);
}
static ColorDecomposeRgb wx_colour_to_recipe_rgb(const wxColour& color)
{
return {
static_cast<unsigned char>(color.Red()),
static_cast<unsigned char>(color.Green()),
static_cast<unsigned char>(color.Blue())
};
}
static wxColour hex_to_wx_colour(const std::string& hex, const wxColour& fallback)
{
wxColour color(hex);
return color.IsOk() ? color : fallback;
}
static bool same_rgb(const wxColour& lhs, const wxColour& rhs)
{
return lhs.Red() == rhs.Red() && lhs.Green() == rhs.Green() && lhs.Blue() == rhs.Blue();
}
static DecomposeBaseColor standard_base_color_from_key(const std::string& key)
{
if (key == "Cyan") return DecomposeBaseColor::Cyan;
if (key == "Magenta") return DecomposeBaseColor::Magenta;
if (key == "Yellow") return DecomposeBaseColor::Yellow;
if (key == "White") return DecomposeBaseColor::White;
if (key == "Red") return DecomposeBaseColor::Red;
if (key == "Green") return DecomposeBaseColor::Green;
if (key == "Blue") return DecomposeBaseColor::Blue;
return DecomposeBaseColor::None;
}
static wxColour pure_color_for_base(DecomposeBaseColor base)
{
switch (base) {
case DecomposeBaseColor::Cyan: return CMYW_CYAN;
case DecomposeBaseColor::Magenta: return CMYW_MAGENTA;
case DecomposeBaseColor::Yellow: return CMYW_YELLOW;
case DecomposeBaseColor::White: return CMYW_WHITE;
case DecomposeBaseColor::Red: return RYBW_RED;
case DecomposeBaseColor::Blue: return RYBW_BLUE;
default: return *wxBLACK;
}
}
static DecomposeBaseColor standard_base_color_for(DecomposeMode mode, const wxColour& color)
{
if (mode == DecomposeMode::CMYW) {
if (same_rgb(color, CMYW_CYAN)) return DecomposeBaseColor::Cyan;
if (same_rgb(color, CMYW_MAGENTA)) return DecomposeBaseColor::Magenta;
if (same_rgb(color, CMYW_YELLOW)) return DecomposeBaseColor::Yellow;
if (same_rgb(color, CMYW_WHITE)) return DecomposeBaseColor::White;
} else if (mode == DecomposeMode::RYBW) {
if (same_rgb(color, RYBW_RED)) return DecomposeBaseColor::Red;
if (same_rgb(color, RYBW_YELLOW)) return DecomposeBaseColor::Yellow;
if (same_rgb(color, RYBW_BLUE)) return DecomposeBaseColor::Blue;
if (same_rgb(color, RYBW_WHITE)) return DecomposeBaseColor::White;
}
return DecomposeBaseColor::None;
}
static ColorDecomposeResult to_dialog_result(const ColorDecomposeRecipeResult& recipe,
const wxColour& fallback)
{
ColorDecomposeResult result;
result.mode = recipe.mode;
result.matched_color = hex_to_wx_colour(recipe.matched_color_hex, fallback);
for (const auto& comp_recipe : recipe.components) {
DecomposeComponent comp;
comp.colour = hex_to_wx_colour(comp_recipe.color_hex, fallback);
comp.ratio = comp_recipe.ratio;
comp.filament_index = static_cast<int>(comp_recipe.filament_index);
comp.base_color = standard_base_color_from_key(comp_recipe.base_color);
if (comp.base_color == DecomposeBaseColor::None)
comp.base_color = standard_base_color_for(recipe.mode, comp.colour);
result.components.push_back(comp);
}
return result;
}
static wxPanel* create_h_divider(wxWindow* parent, int fixed_width = -1)
{
const int h = parent->FromDIP(1);
int w = fixed_width > 0 ? fixed_width : -1;
auto* panel = new wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(w, h));
panel->SetMinSize(wxSize(w, h));
if (fixed_width > 0)
panel->SetMaxSize(wxSize(fixed_width, h));
panel->SetBackgroundColour(StateColor::darkModeColorFor(COLOR_DIVIDER));
return panel;
}
static wxStaticText* create_mode_group_label(wxWindow* parent, const wxString& text)
{
auto* label = new wxStaticText(parent, wxID_ANY, text);
label->SetFont(Label::Body_11);
label->SetForegroundColour(StateColor::darkModeColorFor(COLOR_LABEL_GREY));
return label;
}
static void match_parent_bg(wxWindow* w, const wxColour& bg)
{
w->SetBackgroundColour(bg);
}
static bool material_type_matches(const std::string& a, const std::string& b)
{
if (a.empty() || b.empty())
return false;
return a == b || a == b + " Basic" || b == a + " Basic";
}
ColorDecomposeDialog::ColorDecomposeDialog(wxWindow* parent,
int filament_idx,
const wxColour& target_color,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& filament_names,
const std::vector<std::string>& filament_types,
size_t current_filament_count,
size_t max_filament_count,
std::vector<size_t> physical_config_indices)
: DPIDialog(parent, wxID_ANY, _L("Decompose Color"), wxDefaultPosition,
wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
, m_filament_idx(filament_idx)
, m_target_color(target_color)
, m_physical_colors(physical_colors)
, m_filament_names(filament_names)
, m_filament_types(filament_types)
, m_current_filament_count(current_filament_count)
, m_max_filament_count(max_filament_count)
, m_physical_config_indices(std::move(physical_config_indices))
{
for (const auto& t : m_filament_types) {
if (std::find(m_project_types.begin(), m_project_types.end(), t) == m_project_types.end())
m_project_types.push_back(t);
}
if (m_filament_idx >= 0 && static_cast<size_t>(m_filament_idx) < m_filament_types.size())
m_preferred_type = m_filament_types[m_filament_idx];
else if (!m_project_types.empty())
m_preferred_type = m_project_types.front();
build_ui();
wxGetApp().UpdateDlgDarkUI(this);
// Restore target swatch after dark mode color remapping
if (m_target_swatch) {
m_target_swatch->SetBackgroundColour(m_target_color);
m_target_swatch->Refresh();
}
update_card_visibility();
Fit();
compute_decomposition();
update_matched_color_display();
update_ok_button_state();
}
void ColorDecomposeDialog::on_dpi_changed(const wxRect& suggested_rect)
{
(void)suggested_rect;
Fit();
Refresh();
}
void ColorDecomposeDialog::build_ui()
{
SetBackgroundColour(StateColor::darkModeColorFor(*wxWHITE));
auto* main_sizer = new wxBoxSizer(wxVERTICAL);
const int selector_side_margin = FromDIP(26);
const int selector_top_gap = FromDIP(22);
const int content_side_margin = FromDIP(30);
const int target_section_top_gap = FromDIP(18);
main_sizer->AddSpacer(selector_top_gap);
main_sizer->Add(create_filament_selector(), 0, wxEXPAND | wxLEFT | wxRIGHT, selector_side_margin);
main_sizer->AddSpacer(target_section_top_gap);
main_sizer->Add(create_target_color_section(), 0, wxEXPAND | wxLEFT | wxRIGHT, content_side_margin);
main_sizer->AddSpacer(FromDIP(16));
main_sizer->Add(create_h_divider(this), 0, wxEXPAND | wxLEFT | wxRIGHT, content_side_margin);
main_sizer->AddSpacer(FromDIP(16));
main_sizer->Add(create_mode_selection_section(), 0, wxEXPAND | wxLEFT | wxRIGHT, content_side_margin);
main_sizer->AddSpacer(FromDIP(16));
main_sizer->Add(create_button_panel(), 0, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, content_side_margin);
SetSizer(main_sizer);
SetMinSize(wxSize(FromDIP(477), FromDIP(380)));
Fit();
CenterOnParent();
}
wxBoxSizer* ColorDecomposeDialog::create_filament_selector()
{
auto* sizer = new wxBoxSizer(wxHORIZONTAL);
m_type_combo = new ComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition,
wxSize(-1, FromDIP(36)), 0, nullptr, wxCB_READONLY);
m_type_combo->SetFont(Label::Body_13);
m_combo_item_types.clear();
int default_sel = -1;
// --- Group 1: Project filament list (deduplicated by type) ---
m_type_combo->Append(_L("Project Filament List"), wxNullBitmap, DD_ITEM_STYLE_SPLIT_ITEM | DD_ITEM_STYLE_DISABLED);
m_combo_item_types.push_back(std::string());
std::set<std::string> seen_types;
for (size_t i = 0; i < m_filament_names.size(); ++i) {
const std::string& type = (i < m_filament_types.size()) ? m_filament_types[i] : "PLA";
if (!seen_types.insert(type).second)
continue;
int idx = m_type_combo->Append(wxString::FromUTF8(m_filament_names[i]));
m_combo_item_types.push_back(type);
if (type == m_preferred_type && default_sel < 0)
default_sel = idx;
}
// --- Group 2: Standard mode material recommendations ---
static const char* kStandardTypes[] = {
kDecomposePlaBasicType
};
m_type_combo->Append(_L("Standard Mode Recommendations"), wxNullBitmap, DD_ITEM_STYLE_SPLIT_ITEM | DD_ITEM_STYLE_DISABLED);
m_combo_item_types.push_back(std::string());
for (size_t s = 0; s < sizeof(kStandardTypes) / sizeof(kStandardTypes[0]); ++s) {
// Always show standard recommendations, even if the same type already
// appears in the project filament list above.
const std::string label = std::string(kDecomposeBambuPresetPrefix) + kStandardTypes[s];
int idx = m_type_combo->Append(wxString::FromUTF8(label));
m_combo_item_types.push_back(kStandardTypes[s]);
if (kStandardTypes[s] == m_preferred_type && default_sel < 0)
default_sel = idx;
}
if (default_sel < 0) {
for (int i = 0; i < static_cast<int>(m_combo_item_types.size()); ++i) {
if (!m_combo_item_types[i].empty()) {
default_sel = i;
break;
}
}
}
if (default_sel >= 0) {
m_type_combo->SetSelection(default_sel);
if (!m_combo_item_types[default_sel].empty())
m_preferred_type = m_combo_item_types[default_sel];
}
m_type_combo->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent& evt) {
evt.StopPropagation();
int sel = m_type_combo->GetSelection();
if (sel >= 0 && static_cast<size_t>(sel) < m_combo_item_types.size()
&& !m_combo_item_types[sel].empty()) {
m_preferred_type = m_combo_item_types[sel];
}
update_card_visibility();
compute_decomposition();
update_matched_color_display();
update_ok_button_state();
});
sizer->Add(m_type_combo, 1, wxEXPAND);
return sizer;
}
static wxPanel* create_color_swatch(wxWindow* parent, const wxColour& color, int size)
{
auto* panel = new wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(size, size));
panel->SetBackgroundColour(color);
panel->SetMinSize(wxSize(size, size));
panel->SetBackgroundStyle(wxBG_STYLE_PAINT);
panel->Bind(wxEVT_PAINT, [panel](wxPaintEvent&) {
wxAutoBufferedPaintDC dc(panel);
wxSize sz = panel->GetClientSize();
wxColour c = panel->GetBackgroundColour();
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(c));
dc.DrawRectangle(0, 0, sz.GetWidth(), sz.GetHeight());
// Mirror sidebar (FilamentBitmapUtils::create_single_filament_bitmap):
// gray border for near-white in light mode so white swatches stay
// visible on a white background; light border for near-black in dark mode.
const bool light_mode = !wxGetApp().dark_mode();
if ((light_mode && c.Red() > 224 && c.Green() > 224 && c.Blue() > 224) ||
(!light_mode && c.Red() < 45 && c.Green() < 45 && c.Blue() < 45)) {
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.SetPen(wxPen(light_mode ? wxColour(130, 130, 128) : wxColour(207, 207, 207),
1, wxPENSTYLE_SOLID));
dc.DrawRectangle(0, 0, sz.GetWidth(), sz.GetHeight());
}
});
return panel;
}
wxBoxSizer* ColorDecomposeDialog::create_target_color_section()
{
auto* sizer = new wxBoxSizer(wxHORIZONTAL);
auto* label = new wxStaticText(this, wxID_ANY, _L("Target Color"));
label->SetFont(Label::Head_14);
label->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
sizer->Add(label, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(19));
m_target_swatch = create_color_swatch(this, m_target_color, FromDIP(28));
sizer->Add(m_target_swatch, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(12));
m_target_rgb_text = new wxStaticText(this, wxID_ANY,
wxString::Format("RGB: %d, %d, %d", m_target_color.Red(), m_target_color.Green(), m_target_color.Blue()));
m_target_rgb_text->SetFont(Label::Body_13);
m_target_rgb_text->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
sizer->Add(m_target_rgb_text, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(12));
auto* arrow_text = new wxStaticText(this, wxID_ANY, wxString::FromUTF8("\xe2\x86\x92"));
arrow_text->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
sizer->Add(arrow_text, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(12));
m_matched_swatch = create_color_swatch(this, m_target_color, FromDIP(28));
sizer->Add(m_matched_swatch, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(12));
m_matched_rgb_text = new wxStaticText(this, wxID_ANY,
wxString::Format("RGB: %d, %d, %d", m_target_color.Red(), m_target_color.Green(), m_target_color.Blue()));
m_matched_rgb_text->SetFont(Label::Head_13);
m_matched_rgb_text->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
sizer->Add(m_matched_rgb_text, 0, wxALIGN_CENTER_VERTICAL);
return sizer;
}
wxPanel* ColorDecomposeDialog::create_mode_card(wxWindow* parent, DecomposeMode mode,
const wxString& title)
{
const int pad = FromDIP(12);
auto* card = new wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE);
card->SetBackgroundStyle(wxBG_STYLE_PAINT);
auto* card_sizer = new wxBoxSizer(wxVERTICAL);
auto* title_sizer = new wxBoxSizer(wxHORIZONTAL);
auto* title_label = new wxStaticText(card, wxID_ANY, title);
title_label->SetFont(Label::Body_14);
title_label->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#6B6A6A")));
match_parent_bg(title_label, StateColor::darkModeColorFor(COLOR_BG_CARD));
title_sizer->Add(title_label, 1, wxALIGN_CENTER_VERTICAL);
auto* chk = new ::CheckBox(card);
chk->SetValue(mode == m_selected_mode);
match_parent_bg(chk, StateColor::darkModeColorFor(COLOR_BG_CARD));
switch (mode) {
case DecomposeMode::MaterialList: m_chk_material_list = chk; break;
case DecomposeMode::CMYW: m_chk_cmyw = chk; break;
case DecomposeMode::RYBW: m_chk_rybw = chk; break;
}
chk->Bind(wxEVT_TOGGLEBUTTON, [this, mode](wxCommandEvent& e) {
select_mode(mode);
e.Skip(); // let CheckBox::update() re-sync its bitmap to GetValue()
});
title_sizer->Add(chk, 0, wxALIGN_CENTER_VERTICAL);
card_sizer->Add(title_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, pad);
card_sizer->Add(create_h_divider(card), 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, FromDIP(8));
auto* colors_sizer = new wxBoxSizer(wxHORIZONTAL);
card_sizer->Add(colors_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP | wxBOTTOM, pad);
auto& controls = m_mode_cards[mode_index(mode)];
controls.card = card;
controls.components_sizer = colors_sizer;
card->SetSizer(card_sizer);
card->SetMinSize(wxSize(FromDIP(128), FromDIP(111)));
card->SetMaxSize(wxSize(FromDIP(128), FromDIP(111)));
card->Bind(wxEVT_PAINT, [this, card, mode](wxPaintEvent&) {
wxBufferedPaintDC dc(card);
wxSize sz = card->GetClientSize();
dc.SetBackground(wxBrush(StateColor::darkModeColorFor(*wxWHITE)));
dc.Clear();
bool selected = (m_selected_mode == mode);
wxColour border_col = selected
? StateColor::darkModeColorFor(COLOR_BRAND)
: StateColor::darkModeColorFor(COLOR_BORDER_NORMAL);
const int border_width = FromDIP(selected ? 2 : 1);
const double inset = border_width / 2.0;
std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(dc));
if (gc) {
gc->SetPen(wxPen(border_col, border_width));
gc->SetBrush(wxBrush(StateColor::darkModeColorFor(COLOR_BG_CARD)));
gc->DrawRoundedRectangle(inset, inset, sz.x - 2 * inset, sz.y - 2 * inset, FromDIP(8));
} else {
const int fallback_inset = (border_width + 1) / 2;
dc.SetPen(wxPen(border_col, border_width));
dc.SetBrush(wxBrush(StateColor::darkModeColorFor(COLOR_BG_CARD)));
dc.DrawRoundedRectangle(fallback_inset, fallback_inset, sz.x - 2 * fallback_inset, sz.y - 2 * fallback_inset, FromDIP(8));
}
});
std::function<void(wxWindow*)> bind_click;
bind_click = [this, mode, chk, &bind_click](wxWindow* w) {
if (w == chk || dynamic_cast<::CheckBox*>(w))
return;
w->Bind(wxEVT_LEFT_UP, [this, mode](wxMouseEvent&) {
select_mode(mode);
});
w->SetCursor(wxCursor(wxCURSOR_HAND));
for (auto* child : w->GetChildren())
bind_click(child);
};
bind_click(card);
return card;
}
wxBoxSizer* ColorDecomposeDialog::create_mode_selection_section()
{
auto* sizer = new wxBoxSizer(wxVERTICAL);
auto* section_label = new wxStaticText(this, wxID_ANY, _L("Select Color Decomposition"));
section_label->SetFont(Label::Head_14);
section_label->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
sizer->Add(section_label, 0, wxBOTTOM, FromDIP(4));
auto* modes_sizer = new wxBoxSizer(wxHORIZONTAL);
// --- Arbitrary mode column (wrapped in a panel so the whole column hides together) ---
m_arb_column_panel = new wxPanel(this, wxID_ANY);
m_arb_column_panel->SetBackgroundColour(StateColor::darkModeColorFor(*wxWHITE));
auto* arb_col = new wxBoxSizer(wxVERTICAL);
{
auto* arb_header_sizer = new wxBoxSizer(wxHORIZONTAL);
arb_header_sizer->Add(create_mode_group_label(m_arb_column_panel, _L("Arbitrary Mode")),
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(5));
arb_header_sizer->Add(create_h_divider(m_arb_column_panel, FromDIP(88)), 0, wxALIGN_CENTER_VERTICAL);
arb_col->Add(arb_header_sizer, 0, wxEXPAND | wxBOTTOM, FromDIP(8));
m_card_material_list = create_mode_card(m_arb_column_panel, DecomposeMode::MaterialList,
_L("Material List"));
arb_col->Add(m_card_material_list, 0, wxEXPAND);
}
m_arb_column_panel->SetSizer(arb_col);
modes_sizer->Add(m_arb_column_panel, 0, wxEXPAND | wxRIGHT, FromDIP(16));
// --- Standard mode column ---
auto* std_col = new wxBoxSizer(wxVERTICAL);
{
auto* std_header_sizer = new wxBoxSizer(wxHORIZONTAL);
std_header_sizer->Add(create_mode_group_label(this, _L("Standard Mode")),
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, FromDIP(5));
std_header_sizer->Add(create_h_divider(this), 1, wxALIGN_CENTER_VERTICAL);
std_col->Add(std_header_sizer, 0, wxEXPAND | wxBOTTOM, FromDIP(8));
auto* cards_sizer = new wxBoxSizer(wxHORIZONTAL);
m_card_cmyw = create_mode_card(this, DecomposeMode::CMYW, "CMYW");
cards_sizer->Add(m_card_cmyw, 0, wxRIGHT, FromDIP(12));
m_card_rybw = create_mode_card(this, DecomposeMode::RYBW, "RYBW");
cards_sizer->Add(m_card_rybw, 0);
std_col->Add(cards_sizer, 0, wxEXPAND);
}
modes_sizer->Add(std_col, 0, wxEXPAND);
sizer->Add(modes_sizer, 0, wxEXPAND);
m_no_card_hint = new wxStaticText(this, wxID_ANY,
_L("At least two filaments of the same material type are required for decomposition"));
m_no_card_hint->SetFont(Label::Body_13);
m_no_card_hint->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#6B6A6A")));
m_no_card_hint->Wrap(FromDIP(400));
m_no_card_hint->Hide();
sizer->Add(m_no_card_hint, 0, wxTOP, FromDIP(8));
m_limit_warning_panel = new wxPanel(this, wxID_ANY);
m_limit_warning_panel->SetBackgroundColour(StateColor::darkModeColorFor(*wxWHITE));
auto* warning_sizer = new wxBoxSizer(wxHORIZONTAL);
auto* warn_bmp = new wxStaticBitmap(m_limit_warning_panel, wxID_ANY,
create_scaled_bitmap("obj_warning", m_limit_warning_panel, 16),
wxDefaultPosition, wxSize(FromDIP(16), FromDIP(16)));
m_limit_warning_text = new wxStaticText(m_limit_warning_panel, wxID_ANY, wxEmptyString);
m_limit_warning_text->SetFont(Label::Body_13);
m_limit_warning_text->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#D01B1B")));
m_limit_warning_text->Wrap(FromDIP(400));
warning_sizer->Add(warn_bmp, 0, wxALIGN_TOP | wxRIGHT, FromDIP(6));
warning_sizer->Add(m_limit_warning_text, 1, wxEXPAND);
m_limit_warning_panel->SetSizer(warning_sizer);
m_limit_warning_panel->Hide();
sizer->Add(m_limit_warning_panel, 0, wxEXPAND | wxTOP, FromDIP(8));
return sizer;
}
wxBoxSizer* ColorDecomposeDialog::create_button_panel()
{
auto* sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->AddStretchSpacer();
m_btn_cancel = new Button(this, _L("Cancel"));
m_btn_cancel->SetStyle(ButtonStyle::Regular, ButtonType::Choice);
m_btn_cancel->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { EndModal(wxID_CANCEL); });
m_btn_ok = new Button(this, _L("OK"));
m_btn_ok->SetStyle(ButtonStyle::Confirm, ButtonType::Choice);
m_btn_ok->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) {
EndModal(wxID_OK);
});
sizer->Add(m_btn_cancel, 0, wxRIGHT, FromDIP(12));
sizer->Add(m_btn_ok, 0);
return sizer;
}
void ColorDecomposeDialog::select_mode(DecomposeMode mode)
{
m_selected_mode = mode;
m_result = m_mode_results[mode_index(mode)];
update_card_styles();
update_matched_color_display();
update_ok_button_state();
}
void ColorDecomposeDialog::update_card_styles()
{
if (m_card_material_list) m_card_material_list->Refresh();
if (m_card_cmyw) m_card_cmyw->Refresh();
if (m_card_rybw) m_card_rybw->Refresh();
if (m_chk_material_list)
m_chk_material_list->SetValue(m_selected_mode == DecomposeMode::MaterialList);
if (m_chk_cmyw)
m_chk_cmyw->SetValue(m_selected_mode == DecomposeMode::CMYW);
if (m_chk_rybw)
m_chk_rybw->SetValue(m_selected_mode == DecomposeMode::RYBW);
}
void ColorDecomposeDialog::update_card_visibility()
{
// Count physical filaments of the same type (excluding the source filament)
int same_type_count = 0;
for (size_t i = 0; i < m_filament_types.size(); ++i) {
if (static_cast<int>(i) == m_filament_idx)
continue;
if (material_type_matches(m_filament_types[i], m_preferred_type))
++same_type_count;
}
bool show_arb = (same_type_count >= 2);
bool show_cmyw = (m_preferred_type == kDecomposePlaBasicType);
bool show_rybw = (m_preferred_type == kDecomposePlaBasicType);
if (m_arb_column_panel) m_arb_column_panel->Show(show_arb);
if (m_card_material_list) m_card_material_list->Show(show_arb);
if (m_card_cmyw) m_card_cmyw->Show(show_cmyw);
if (m_card_rybw) m_card_rybw->Show(show_rybw);
bool any_visible = show_arb || show_cmyw || show_rybw;
if (m_no_card_hint)
m_no_card_hint->Show(!any_visible);
// Auto-select a visible mode when current selection becomes hidden
if (any_visible) {
bool cur_visible = false;
if (m_selected_mode == DecomposeMode::MaterialList && show_arb) cur_visible = true;
if (m_selected_mode == DecomposeMode::CMYW && show_cmyw) cur_visible = true;
if (m_selected_mode == DecomposeMode::RYBW && show_rybw) cur_visible = true;
if (!cur_visible) {
if (show_arb) select_mode(DecomposeMode::MaterialList);
else if (show_cmyw) select_mode(DecomposeMode::CMYW);
else select_mode(DecomposeMode::RYBW);
}
}
Layout();
update_ok_button_state();
}
void ColorDecomposeDialog::update_filament_limit_warning()
{
if (!m_limit_warning_panel || !m_limit_warning_text)
return;
size_t missing_new = 0;
if (m_missing_calculator) {
missing_new = m_missing_calculator(m_result);
} else {
const size_t source_physical_idx = m_filament_idx >= 0 ? static_cast<size_t>(m_filament_idx) : size_t(-1);
const std::vector<size_t>* indices =
m_physical_config_indices.empty() ? nullptr : &m_physical_config_indices;
missing_new = count_decompose_new_physical_filaments(
m_result, m_physical_colors, m_filament_types, source_physical_idx, indices);
}
// A result with fewer than 2 components (e.g. target color is already a
// standard base color shown as "100%") creates no mixed filament and no new
// physical filament, so it can never exceed the limit.
const bool creates_mixed = m_result.components.size() >= 2;
// +1 for the mixed filament slot that will be created after decomposition.
const size_t needed = m_current_filament_count + missing_new + 1;
const bool blocked = creates_mixed && needed > m_max_filament_count;
const bool was_shown = m_limit_warning_panel->IsShown();
if (!blocked) {
if (was_shown) {
m_limit_warning_panel->Hide();
Layout();
Fit();
}
return;
}
wxString mode_name;
switch (m_selected_mode) {
case DecomposeMode::CMYW: mode_name = "CMYW"; break;
case DecomposeMode::RYBW: mode_name = "RYBW"; break;
case DecomposeMode::MaterialList: mode_name = _L("Material List"); break;
}
const wxString warning_text = format_wxstr(
_L("The material list supports at most %1% colors. After %2% decomposition, the material count would exceed %1%. Please delete unused filaments on the main screen before decomposing."),
m_max_filament_count, mode_name);
// Show first so the panel is laid out and the text control gets its real
// width, then wrap to that width so the paragraph fills the content area.
m_limit_warning_panel->Show();
Layout();
const int avail = m_limit_warning_text->GetClientSize().x;
m_limit_warning_text->SetLabel(warning_text);
if (avail > FromDIP(50))
m_limit_warning_text->Wrap(avail);
Layout();
// Only resize when the warning panel actually toggled from hidden to shown.
// While already visible, switching modes must not re-Fit the dialog, which
// would make it jump on every card switch. Fit keeps the user-moved position.
if (!was_shown) {
Fit();
}
}
void ColorDecomposeDialog::set_missing_physical_calculator(std::function<size_t(const ColorDecomposeResult&)> fn)
{
m_missing_calculator = std::move(fn);
update_ok_button_state();
}
void ColorDecomposeDialog::update_ok_button_state()
{
if (!m_btn_ok) return;
update_filament_limit_warning();
bool any_card_visible = (m_card_material_list && m_card_material_list->IsShown())
|| (m_card_cmyw && m_card_cmyw->IsShown())
|| (m_card_rybw && m_card_rybw->IsShown());
const bool blocked = m_limit_warning_panel && m_limit_warning_panel->IsShown();
m_btn_ok->Enable(any_card_visible && !blocked);
Layout();
}
void ColorDecomposeDialog::update_mode_card_content(DecomposeMode mode)
{
auto& controls = m_mode_cards[mode_index(mode)];
auto* sizer = controls.components_sizer;
auto* card = controls.card;
if (!sizer || !card)
return;
sizer->Clear(true);
const auto& components = m_mode_results[mode_index(mode)].components;
const size_t count = components.size();
if (count == 0) {
card->Layout();
card->Refresh();
return;
}
const int swatch_sz = FromDIP(24);
const int plus_gap = FromDIP(24);
const wxFont& ratio_font = Label::Body_13;
auto bind_select = [this, mode](wxWindow* w) {
w->Bind(wxEVT_LEFT_UP, [this, mode](wxMouseEvent&) {
select_mode(mode);
});
w->SetCursor(wxCursor(wxCURSOR_HAND));
};
for (size_t i = 0; i < count; ++i) {
auto* col = new wxBoxSizer(wxVERTICAL);
auto* swatch = create_color_swatch(card, components[i].colour, swatch_sz);
bind_select(swatch);
col->Add(swatch, 0, wxALIGN_CENTER_HORIZONTAL);
auto* ratio_text = new wxStaticText(card, wxID_ANY, wxString::Format("%d%%", components[i].ratio));
ratio_text->SetFont(ratio_font);
ratio_text->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
match_parent_bg(ratio_text, StateColor::darkModeColorFor(COLOR_BG_CARD));
bind_select(ratio_text);
col->Add(ratio_text, 0, wxALIGN_CENTER_HORIZONTAL | wxTOP, FromDIP(4));
sizer->Add(col, 0, wxALIGN_TOP);
if (i + 1 < count) {
sizer->AddStretchSpacer();
auto* plus_panel = new wxPanel(card, wxID_ANY, wxDefaultPosition, wxSize(plus_gap, swatch_sz));
plus_panel->SetMinSize(wxSize(plus_gap, swatch_sz));
plus_panel->SetMaxSize(wxSize(plus_gap, swatch_sz));
plus_panel->SetBackgroundColour(StateColor::darkModeColorFor(COLOR_BG_CARD));
auto* plus_sizer = new wxBoxSizer(wxVERTICAL);
auto* plus_label = new wxStaticText(plus_panel, wxID_ANY, "+");
plus_label->SetFont(Label::Body_13);
plus_label->SetForegroundColour(StateColor::darkModeColorFor(COLOR_TEXT_DARK));
match_parent_bg(plus_label, StateColor::darkModeColorFor(COLOR_BG_CARD));
bind_select(plus_panel);
bind_select(plus_label);
plus_sizer->AddStretchSpacer();
plus_sizer->Add(plus_label, 0, wxALIGN_CENTER_HORIZONTAL);
plus_sizer->AddStretchSpacer();
plus_panel->SetSizer(plus_sizer);
sizer->Add(plus_panel, 0, wxALIGN_TOP);
sizer->AddStretchSpacer();
}
}
const int card_width = FromDIP(128 + (count > 2 ? static_cast<int>(count - 2) * 31 : 0));
card->SetMinSize(wxSize(card_width, FromDIP(111)));
card->SetMaxSize(wxSize(card_width, FromDIP(111)));
card->Layout();
card->Refresh();
}
void ColorDecomposeDialog::update_mode_card_contents()
{
update_mode_card_content(DecomposeMode::MaterialList);
update_mode_card_content(DecomposeMode::CMYW);
update_mode_card_content(DecomposeMode::RYBW);
Layout();
Fit();
}
void ColorDecomposeDialog::update_matched_color_display()
{
if (!m_result.matched_color.IsOk())
m_result.matched_color = m_target_color;
if (m_matched_swatch) {
m_matched_swatch->SetBackgroundColour(m_result.matched_color);
m_matched_swatch->Refresh();
}
if (m_matched_rgb_text) {
m_matched_rgb_text->SetLabel(wxString::Format("RGB: %d, %d, %d",
m_result.matched_color.Red(), m_result.matched_color.Green(), m_result.matched_color.Blue()));
}
}
bool ColorDecomposeDialog::try_build_single_base_result(DecomposeMode mode, ColorDecomposeResult& out) const
{
// Gate by preferred type, matching card visibility: CMYW and RYBW only for PLA Basic.
if (mode == DecomposeMode::CMYW || mode == DecomposeMode::RYBW) {
if (m_preferred_type != kDecomposePlaBasicType)
return false;
} else {
return false;
}
static const DecomposeBaseColor cmyw_bases[] = {
DecomposeBaseColor::Cyan, DecomposeBaseColor::Magenta,
DecomposeBaseColor::Yellow, DecomposeBaseColor::White
};
static const DecomposeBaseColor rybw_bases[] = {
DecomposeBaseColor::Red, DecomposeBaseColor::Yellow,
DecomposeBaseColor::Blue, DecomposeBaseColor::White
};
const DecomposeBaseColor* bases = (mode == DecomposeMode::CMYW) ? cmyw_bases : rybw_bases;
const size_t base_count = (mode == DecomposeMode::CMYW)
? sizeof(cmyw_bases) / sizeof(cmyw_bases[0])
: sizeof(rybw_bases) / sizeof(rybw_bases[0]);
const std::string target_hex = decompose_normalize_color_hex(
m_target_color.GetAsString(wxC2S_HTML_SYNTAX).ToStdString());
for (size_t i = 0; i < base_count; ++i) {
const DecomposeBaseColor base = bases[i];
DecomposeOfficialComponent official =
lookup_decompose_official_component(m_preferred_type, base, pure_color_for_base(base));
if (decompose_normalize_color_hex(official.color_hex) != target_hex)
continue;
out = ColorDecomposeResult{};
out.mode = mode;
out.matched_color = hex_to_wx_colour(official.color_hex, m_target_color);
DecomposeComponent comp;
comp.colour = out.matched_color;
comp.ratio = 100;
comp.filament_index = -1;
comp.base_color = base;
out.components.push_back(comp);
return true;
}
return false;
}
void ColorDecomposeDialog::compute_decomposition()
{
auto fallback_result = [this](DecomposeMode mode, const std::vector<DecomposeComponent>& components) {
ColorDecomposeResult result;
result.mode = mode;
result.components = components;
int total = 0;
double r = 0.0, g = 0.0, b = 0.0;
for (const auto& comp : result.components)
total += comp.ratio;
if (total <= 0)
total = 100;
for (const auto& comp : result.components) {
const double w = static_cast<double>(comp.ratio) / total;
r += comp.colour.Red() * w;
g += comp.colour.Green() * w;
b += comp.colour.Blue() * w;
}
result.matched_color = result.components.empty()
? m_target_color
: wxColour(static_cast<unsigned char>(std::clamp(r, 0.0, 255.0)),
static_cast<unsigned char>(std::clamp(g, 0.0, 255.0)),
static_cast<unsigned char>(std::clamp(b, 0.0, 255.0)));
return result;
};
std::vector<ColorDecomposePhysicalFilament> physical_filaments;
physical_filaments.reserve(m_physical_colors.size());
for (size_t i = 0; i < m_physical_colors.size(); ++i) {
if (m_filament_idx >= 0 && i == static_cast<size_t>(m_filament_idx))
continue;
ColorDecomposePhysicalFilament filament;
filament.color_hex = m_physical_colors[i];
filament.name = i < m_filament_names.size() ? m_filament_names[i] : "";
filament.type = i < m_filament_types.size() ? m_filament_types[i] : "";
filament.filament_index = static_cast<unsigned int>(i + 1);
physical_filaments.push_back(std::move(filament));
}
const ColorDecomposeRgb target_rgb = wx_colour_to_recipe_rgb(m_target_color);
auto material_recipe = recommend_from_physical_filaments(target_rgb, physical_filaments, m_preferred_type);
if (material_recipe.valid) {
m_mode_results[mode_index(DecomposeMode::MaterialList)] =
to_dialog_result(material_recipe, m_target_color);
} else {
std::vector<DecomposeComponent> components;
for (size_t i = 0; i < std::min<size_t>(2, physical_filaments.size()); ++i) {
DecomposeComponent comp;
comp.colour = wxColour(physical_filaments[i].color_hex);
comp.ratio = 50;
comp.filament_index = static_cast<int>(physical_filaments[i].filament_index);
components.push_back(comp);
}
if (components.empty()) {
components.push_back({m_target_color, 100, -1});
} else if (components.size() == 1) {
components.front().ratio = 100;
}
m_mode_results[mode_index(DecomposeMode::MaterialList)] =
fallback_result(DecomposeMode::MaterialList, components);
}
ColorDecomposeResult single_base;
if (try_build_single_base_result(DecomposeMode::CMYW, single_base)) {
m_mode_results[mode_index(DecomposeMode::CMYW)] = single_base;
} else {
auto cmyw_recipe = lookup_standard_recipe(target_rgb, ColorDecomposeRecipeMode::CMYW, m_preferred_type);
m_mode_results[mode_index(DecomposeMode::CMYW)] = cmyw_recipe.valid
? to_dialog_result(cmyw_recipe, m_target_color)
: fallback_result(DecomposeMode::CMYW, {
{CMYW_YELLOW, 50, -1, DecomposeBaseColor::Yellow},
{CMYW_CYAN, 50, -1, DecomposeBaseColor::Cyan}
});
}
if (try_build_single_base_result(DecomposeMode::RYBW, single_base)) {
m_mode_results[mode_index(DecomposeMode::RYBW)] = single_base;
} else {
auto rybw_recipe = lookup_standard_recipe(target_rgb, ColorDecomposeRecipeMode::RYBW, m_preferred_type);
m_mode_results[mode_index(DecomposeMode::RYBW)] = rybw_recipe.valid
? to_dialog_result(rybw_recipe, m_target_color)
: fallback_result(DecomposeMode::RYBW, {
{RYBW_YELLOW, 50, -1, DecomposeBaseColor::Yellow},
{RYBW_BLUE, 50, -1, DecomposeBaseColor::Blue}
});
}
m_result = m_mode_results[mode_index(m_selected_mode)];
update_mode_card_contents();
update_ok_button_state();
}
} // namespace GUI
} // namespace Slic3r
+152
View File
@@ -0,0 +1,152 @@
#ifndef slic3r_ColorDecomposeDialog_hpp_
#define slic3r_ColorDecomposeDialog_hpp_
#include <array>
#include <functional>
#include <string>
#include <vector>
#include <utility>
#include <wx/colour.h>
#include <wx/panel.h>
#include <wx/statbmp.h>
#include <wx/stattext.h>
#include "GUI_Utils.hpp"
#include "libslic3r/ColorDecomposeRecipe.hpp"
class Button;
class CheckBox;
class ComboBox;
namespace Slic3r {
namespace GUI {
using DecomposeMode = ColorDecomposeRecipeMode;
enum class DecomposeBaseColor {
None,
Cyan,
Magenta,
Yellow,
White,
Red,
Green,
Blue
};
struct DecomposeComponent {
wxColour colour;
int ratio{50}; // percentage
int filament_index{-1}; // 1-based physical filament index, -1 if standard base color
DecomposeBaseColor base_color{DecomposeBaseColor::None};
};
struct ColorDecomposeResult {
DecomposeMode mode{DecomposeMode::MaterialList};
wxColour matched_color;
std::vector<DecomposeComponent> components;
};
class ColorDecomposeDialog : public DPIDialog
{
public:
ColorDecomposeDialog(wxWindow* parent,
int filament_idx,
const wxColour& target_color,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& filament_names,
const std::vector<std::string>& filament_types,
size_t current_filament_count = 0,
size_t max_filament_count = 32,
std::vector<size_t> physical_config_indices = {});
ColorDecomposeResult get_result() const { return m_result; }
// Override the "new physical filaments" count used by the filament-limit
// warning. The Texture import path supplies its own calculator so the
// pre-check shares the exact reuse rule as its write-back (existing +
// virtual physical filaments), instead of the project-config based default
// that cannot see not-yet-committed virtual base colors.
void set_missing_physical_calculator(std::function<size_t(const ColorDecomposeResult&)> fn);
protected:
void on_dpi_changed(const wxRect& suggested_rect) override;
private:
void build_ui();
wxBoxSizer* create_filament_selector();
wxBoxSizer* create_target_color_section();
wxBoxSizer* create_mode_selection_section();
wxPanel* create_mode_card(wxWindow* parent, DecomposeMode mode, const wxString& title);
wxBoxSizer* create_button_panel();
void select_mode(DecomposeMode mode);
void update_card_styles();
void update_card_visibility();
void update_mode_card_content(DecomposeMode mode);
void update_mode_card_contents();
void update_matched_color_display();
void update_ok_button_state();
void update_filament_limit_warning();
void compute_decomposition();
// When the target color is exactly one of the standard base colors for the
// preferred type, the standard card should show that base at 100% instead of
// a mix. PLA Basic covers CMYW and RYBW.
bool try_build_single_base_result(DecomposeMode mode, ColorDecomposeResult& out) const;
struct ModeCardControls {
wxPanel* card{nullptr};
wxBoxSizer* components_sizer{nullptr};
};
ColorDecomposeResult m_result;
std::array<ColorDecomposeResult, 3> m_mode_results;
std::array<ModeCardControls, 3> m_mode_cards;
int m_filament_idx{-1};
wxColour m_target_color;
std::vector<std::string> m_physical_colors;
std::vector<std::string> m_filament_names;
std::vector<std::string> m_filament_types;
std::vector<std::string> m_project_types;
std::string m_preferred_type;
// Dropdown selectable item index -> material type string
std::vector<std::string> m_combo_item_types;
size_t m_current_filament_count{0};
size_t m_max_filament_count{32};
std::vector<size_t> m_physical_config_indices;
std::function<size_t(const ColorDecomposeResult&)> m_missing_calculator;
// UI controls
ComboBox* m_type_combo{nullptr};
wxPanel* m_target_swatch{nullptr};
wxStaticText* m_target_rgb_text{nullptr};
wxPanel* m_matched_swatch{nullptr};
wxStaticText* m_matched_rgb_text{nullptr};
// Mode cards
wxPanel* m_card_material_list{nullptr};
wxPanel* m_card_cmyw{nullptr};
wxPanel* m_card_rybw{nullptr};
wxPanel* m_arb_column_panel{nullptr};
CheckBox* m_chk_material_list{nullptr};
CheckBox* m_chk_cmyw{nullptr};
CheckBox* m_chk_rybw{nullptr};
DecomposeMode m_selected_mode{DecomposeMode::MaterialList};
// Hint shown when no mode card is visible
wxStaticText* m_no_card_hint{nullptr};
// Warning shown when decomposition would exceed filament limit
wxPanel* m_limit_warning_panel{nullptr};
wxStaticText* m_limit_warning_text{nullptr};
Button* m_btn_ok{nullptr};
Button* m_btn_cancel{nullptr};
};
} // namespace GUI
} // namespace Slic3r
#endif // slic3r_ColorDecomposeDialog_hpp_
+409
View File
@@ -0,0 +1,409 @@
#include "ColorDecomposeSupport.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "MixedFilamentDialog.hpp"
#include "GUI_App.hpp"
#include "MsgDialog.hpp"
#include "I18N.hpp"
#include "libslic3r/Preset.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "libslic3r/Utils.hpp"
#include "nlohmann/json.hpp"
#include <fstream>
#include <algorithm>
#include <cctype>
using json = nlohmann::json;
namespace Slic3r { namespace GUI {
std::string decompose_normalize_color_hex(std::string color)
{
if (color.size() >= 7)
color = color.substr(0, 7);
std::transform(color.begin(), color.end(), color.begin(), [](unsigned char c) {
return static_cast<char>(std::toupper(c));
});
return color;
}
const char* decompose_base_color_en(DecomposeBaseColor color)
{
switch (color) {
case DecomposeBaseColor::Cyan: return "Cyan";
case DecomposeBaseColor::Magenta: return "Magenta";
case DecomposeBaseColor::Yellow: return "Yellow";
case DecomposeBaseColor::White: return "White";
case DecomposeBaseColor::Red: return "Red";
case DecomposeBaseColor::Green: return "Green";
case DecomposeBaseColor::Blue: return "Blue";
default: return "";
}
}
wxString decompose_base_color_display(DecomposeBaseColor color)
{
switch (color) {
case DecomposeBaseColor::Cyan: return _L("Cyan");
case DecomposeBaseColor::Magenta: return _L("Magenta");
case DecomposeBaseColor::Yellow: return _L("Yellow");
case DecomposeBaseColor::White: return _L("White");
case DecomposeBaseColor::Red: return _L("Red");
case DecomposeBaseColor::Green: return _L("Green");
case DecomposeBaseColor::Blue: return _L("Blue");
default: return wxString();
}
}
std::string decompose_basic_type_from_source(size_t source_config_idx,
size_t source_physical_idx,
const std::vector<std::string>& physical_types)
{
auto& project_config = wxGetApp().preset_bundle->project_config;
if (auto* filament_id_opt = project_config.option<ConfigOptionStrings>("filament_id")) {
if (source_config_idx < filament_id_opt->values.size()) {
// Dead in practice: "filament_id" is not in PresetBundle's s_project_options, so this
// option() lookup (create=false) always returns null and the block never runs. Kept as
// found, with the translation the values would need: they would be our OF ids, and the
// two constants are the printer's own ids.
auto* agent = wxGetApp().getAgent();
const std::string& orca_filament_id = filament_id_opt->values[source_config_idx];
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(orca_filament_id) : orca_filament_id;
if (printer_filament_id == kDecomposePetgFilamentId)
return kDecomposePetgBasicType;
if (printer_filament_id == kDecomposePlaFilamentId)
return kDecomposePlaBasicType;
}
}
if (source_physical_idx < physical_types.size()) {
const std::string& type = physical_types[source_physical_idx];
if (type == kDecomposePetgShortType || type == kDecomposePetgBasicType)
return kDecomposePetgBasicType;
if (type == kDecomposePlaShortType || type == kDecomposePlaBasicType)
return kDecomposePlaBasicType;
}
return kDecomposePlaBasicType;
}
std::string decompose_basic_filament_id(const std::string& basic_type)
{
// The result becomes DecomposeOfficialComponent::filament_id, which the rest of this file
// reads as one of our OF ids (translating back before it compares against the printer's
// ids), so translate on the way out; kDecompose*FilamentId itself stays the printer-side
// literal. The only place that would carry it further, project_config's "filament_id", is
// dead code: that key is not in PresetBundle's s_project_options.
const std::string printer_filament_id = basic_type == kDecomposePetgBasicType ? kDecomposePetgFilamentId : kDecomposePlaFilamentId;
auto* agent = wxGetApp().getAgent();
return agent ? agent->to_orca_filament_id(printer_filament_id) : printer_filament_id;
}
void set_created_standard_component_metadata(size_t config_idx, const DecomposeOfficialComponent& component)
{
auto& project_config = wxGetApp().preset_bundle->project_config;
if (!component.filament_id.empty()) {
if (auto* filament_id_opt = project_config.option<ConfigOptionStrings>("filament_id")) {
while (filament_id_opt->values.size() <= config_idx)
filament_id_opt->values.push_back("");
filament_id_opt->values[config_idx] = component.filament_id;
}
}
// component.filament_id is our OF id; the two constants are the printer's own ids.
auto* agent = wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(component.filament_id) : component.filament_id;
const std::string type = printer_filament_id == kDecomposePetgFilamentId ? kDecomposePetgShortType :
printer_filament_id == kDecomposePlaFilamentId ? kDecomposePlaShortType : "";
if (!type.empty()) {
if (auto* type_opt = project_config.option<ConfigOptionStrings>("filament_type")) {
while (type_opt->values.size() <= config_idx)
type_opt->values.push_back("");
type_opt->values[config_idx] = type;
}
}
}
DecomposeOfficialComponent lookup_decompose_official_component(
const std::string& basic_type,
DecomposeBaseColor base_color,
const wxColour& fallback)
{
DecomposeOfficialComponent result;
result.base_color = base_color;
result.color_hex = decompose_normalize_color_hex(fallback.GetAsString(wxC2S_HTML_SYNTAX).ToStdString());
result.filament_id = decompose_basic_filament_id(basic_type);
const char* color_name = decompose_base_color_en(base_color);
if (color_name[0] == '\0')
return result;
// Some materials name a standard base color differently in the color-code
// table. PETG Basic's RYBW blue base is "Reflex Blue" (deep blue, B00,
// #001489), not "Blue". Match by an ordered list of exact English names so
// "Navy Blue" (B01, #0086D6) is never picked up by mistake.
std::vector<std::string> candidate_names;
candidate_names.emplace_back(color_name);
if (base_color == DecomposeBaseColor::Blue && basic_type == kDecomposePetgBasicType)
candidate_names.emplace_back("Reflex Blue");
std::ifstream ifs(resources_dir() + "/profiles/BBL/filament/filaments_color_codes.json");
if (!ifs)
return result;
json root = json::parse(ifs, nullptr, false);
if (root.is_discarded() || !root.contains("data") || !root["data"].is_array())
return result;
for (const std::string& candidate : candidate_names) {
for (const auto& item : root["data"]) {
if (!item.is_object() || item.value("fila_type", "") != basic_type)
continue;
if (!item.contains("fila_color_name"))
continue;
const auto& names = item["fila_color_name"];
if (!names.is_object() || names.value("en", "") != candidate)
continue;
if (item.contains("fila_color") && item["fila_color"].is_array() && !item["fila_color"].empty())
result.color_hex = decompose_normalize_color_hex(item["fila_color"][0].get<std::string>());
// fila_id from this shipped, Bambu-keyed color table is a printer-side id; translate it so
// result.filament_id stays an OF id like the rest of this struct (the fallback default,
// result.filament_id, is already OF and passes through unchanged).
const std::string fila_id = item.value("fila_id", result.filament_id);
auto* agent = wxGetApp().getAgent();
result.filament_id = agent ? agent->to_orca_filament_id(fila_id) : fila_id;
return result;
}
}
return result;
}
std::string find_decompose_standard_preset_name(size_t source_config_idx, const std::string& basic_type)
{
const PresetBundle& preset_bundle = *wxGetApp().preset_bundle;
if (source_config_idx < preset_bundle.filament_presets.size()) {
const std::string& source_name = preset_bundle.filament_presets[source_config_idx];
if (source_name.find(std::string(kDecomposeBambuPresetPrefix) + basic_type) != std::string::npos)
return source_name;
}
const std::string prefix = std::string(kDecomposeBambuPresetPrefix) + basic_type + " @BBL ";
for (const std::string& preset_name : preset_bundle.filament_presets) {
if (preset_name.find(prefix) == 0)
return preset_name;
}
return {};
}
std::string official_basic_type_from_preset_name(const std::string& preset_name)
{
if (preset_name.find(std::string(kDecomposeBambuPresetPrefix) + kDecomposePlaBasicType) != std::string::npos)
return kDecomposePlaBasicType;
if (preset_name.find(std::string(kDecomposeBambuPresetPrefix) + kDecomposePetgBasicType) != std::string::npos)
return kDecomposePetgBasicType;
return {};
}
std::string filament_type_for_color_decompose(Preset* preset)
{
if (!preset)
return kDecomposePlaShortType;
std::string display_type;
std::string ft = preset->config.get_filament_type(display_type);
const std::string basic = official_basic_type_from_preset_name(preset->name);
if (!basic.empty())
ft = basic;
if (ft.empty())
ft = kDecomposePlaShortType;
return ft;
}
int find_existing_decompose_component(
const DecomposeOfficialComponent& component,
const std::vector<std::string>& physical_colors,
const std::vector<size_t>& physical_config_indices,
size_t source_config_idx)
{
auto& project_config = wxGetApp().preset_bundle->project_config;
auto* filament_id_opt = project_config.option<ConfigOptionStrings>("filament_id");
auto* type_opt = project_config.option<ConfigOptionStrings>("filament_type");
const PresetBundle& preset_bundle = *wxGetApp().preset_bundle;
const size_t num_physical = physical_colors.size();
// component.filament_id is our OF id; the two constants are the printer's own ids.
auto* agent = wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(component.filament_id) : component.filament_id;
const std::string expected_basic_type = printer_filament_id == kDecomposePetgFilamentId ? kDecomposePetgBasicType :
printer_filament_id == kDecomposePlaFilamentId ? kDecomposePlaBasicType : "";
const std::string expected_short_type = expected_basic_type == kDecomposePetgBasicType ? kDecomposePetgShortType :
expected_basic_type == kDecomposePlaBasicType ? kDecomposePlaShortType : "";
const std::string expected_preset_part = expected_basic_type.empty() ? "" : std::string(kDecomposeBambuPresetPrefix) + expected_basic_type;
for (size_t i = 0; i < num_physical && i < physical_config_indices.size(); ++i) {
const size_t config_idx = physical_config_indices[i];
const std::string slot_color = decompose_normalize_color_hex(physical_colors[i]);
const std::string slot_filament_id = (filament_id_opt && config_idx < filament_id_opt->values.size()) ? filament_id_opt->values[config_idx] : "";
const std::string slot_type = (type_opt && config_idx < type_opt->values.size()) ? type_opt->values[config_idx] : "";
const std::string preset_name = config_idx < preset_bundle.filament_presets.size() ? preset_bundle.filament_presets[config_idx] : "";
if (config_idx == source_config_idx) {
continue;
}
if (slot_color != component.color_hex) {
continue;
}
if (!component.filament_id.empty() && slot_filament_id == component.filament_id) {
return static_cast<int>(config_idx + 1);
}
if (!expected_basic_type.empty() && (slot_type == expected_basic_type || slot_type == expected_short_type)) {
return static_cast<int>(config_idx + 1);
}
if (!expected_preset_part.empty() && preset_name.find(expected_preset_part) != std::string::npos) {
return static_cast<int>(config_idx + 1);
}
const bool has_material_hint = !slot_filament_id.empty() || !slot_type.empty() || !preset_name.empty();
if (!expected_basic_type.empty() && has_material_hint)
continue;
return static_cast<int>(config_idx + 1);
}
return -1;
}
bool prepare_decompose_mixed_result(
const ColorDecomposeResult& result,
size_t source_config_idx,
size_t source_physical_idx,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& physical_types,
const std::vector<size_t>& physical_config_indices,
MixedFilamentResult& out_result,
std::vector<DecomposeMissingComponent>& missing)
{
out_result = {};
missing.clear();
if (result.components.size() < 2) {
return false;
}
const bool standard_mode = result.mode == DecomposeMode::CMYW || result.mode == DecomposeMode::RYBW;
std::string basic_type;
std::string preset_name;
if (standard_mode) {
basic_type = decompose_basic_type_from_source(source_config_idx, source_physical_idx, physical_types);
preset_name = find_decompose_standard_preset_name(source_config_idx, basic_type);
}
for (size_t i = 0; i < result.components.size(); ++i) {
const DecomposeComponent& comp = result.components[i];
out_result.ratios.push_back(comp.ratio);
if (!standard_mode) {
if (comp.filament_index <= 0) {
return false;
}
const size_t physical_idx = static_cast<size_t>(comp.filament_index - 1);
if (physical_idx >= physical_config_indices.size()) {
return false;
}
out_result.components.push_back(static_cast<unsigned int>(physical_config_indices[physical_idx] + 1));
continue;
}
if (comp.base_color == DecomposeBaseColor::None) {
return false;
}
DecomposeOfficialComponent official_component =
lookup_decompose_official_component(basic_type, comp.base_color, comp.colour);
int existing_idx = find_existing_decompose_component(official_component, physical_colors,
physical_config_indices, source_config_idx);
if (existing_idx > 0) {
out_result.components.push_back(static_cast<unsigned int>(existing_idx));
continue;
}
DecomposeMissingComponent missing_comp;
missing_comp.component_idx = out_result.components.size();
missing_comp.official_component = official_component;
missing_comp.preset_name = preset_name;
missing_comp.display_name = decompose_base_color_display(comp.base_color) +
wxString::FromUTF8(" ") + wxString::FromUTF8(basic_type);
missing.push_back(std::move(missing_comp));
out_result.components.push_back(0);
}
const bool ok = out_result.components.size() == out_result.ratios.size() && out_result.components.size() >= 2;
return ok;
}
size_t count_decompose_new_physical_filaments(
const ColorDecomposeResult& result,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& physical_types,
size_t source_physical_idx,
const std::vector<size_t>* physical_config_indices)
{
if (result.mode != DecomposeMode::CMYW && result.mode != DecomposeMode::RYBW)
return 0;
std::vector<size_t> fallback_indices;
const std::vector<size_t>* indices = physical_config_indices;
if (!indices) {
fallback_indices.resize(physical_colors.size());
for (size_t i = 0; i < fallback_indices.size(); ++i)
fallback_indices[i] = i;
indices = &fallback_indices;
}
size_t source_config_idx = size_t(-1);
if (source_physical_idx < indices->size())
source_config_idx = (*indices)[source_physical_idx];
const std::string basic_type =
decompose_basic_type_from_source(source_config_idx, source_physical_idx, physical_types);
size_t missing_count = 0;
for (const DecomposeComponent& comp : result.components) {
if (comp.base_color == DecomposeBaseColor::None)
continue;
DecomposeOfficialComponent official_component =
lookup_decompose_official_component(basic_type, comp.base_color, comp.colour);
int existing_idx = find_existing_decompose_component(official_component, physical_colors,
*indices, source_config_idx);
if (existing_idx <= 0)
++missing_count;
}
return missing_count;
}
bool confirm_create_decompose_missing_components(wxWindow* parent, const std::vector<DecomposeMissingComponent>& missing)
{
if (missing.empty())
return true;
static const char* config_key = "not_show_color_decompose_missing_component_tip";
if (wxGetApp().app_config->get(config_key) == "1") {
return true;
}
wxString missing_text;
for (size_t i = 0; i < missing.size(); ++i) {
if (i > 0)
missing_text += _L(", ");
missing_text += missing[i].display_name;
}
wxString message = _L("The current filament list does not contain ") + missing_text +
_L(". A project filament required by the mixed filament will be created automatically after decomposition.");
MessageDialog dlg(parent, message, _L("Tip"), wxOK | wxCANCEL | wxICON_INFORMATION);
dlg.show_dsa_button();
int res = dlg.ShowModal();
if (res == wxID_OK && dlg.get_checkbox_state())
wxGetApp().app_config->set(config_key, "1");
return res == wxID_OK;
}
}} // namespace Slic3r::GUI
+104
View File
@@ -0,0 +1,104 @@
#ifndef slic3r_GUI_ColorDecomposeSupport_hpp_
#define slic3r_GUI_ColorDecomposeSupport_hpp_
#include <string>
#include <vector>
#include <wx/string.h>
#include <wx/colour.h>
#include "ColorDecomposeDialog.hpp"
class wxWindow;
namespace Slic3r {
class Preset;
namespace GUI {
// ---- Constants ----
inline constexpr const char* kDecomposePlaBasicType = "PLA Basic";
inline constexpr const char* kDecomposePetgBasicType = "PETG Basic";
inline constexpr const char* kDecomposePlaShortType = "PLA";
inline constexpr const char* kDecomposePetgShortType = "PETG";
inline constexpr const char* kDecomposePlaFilamentId = "GFA00";
inline constexpr const char* kDecomposePetgFilamentId = "GFG00";
inline constexpr const char* kDecomposeBambuPresetPrefix = "Bambu ";
// ---- Types ----
struct DecomposeOfficialComponent {
DecomposeBaseColor base_color{DecomposeBaseColor::None};
std::string color_hex;
std::string filament_id;
};
struct DecomposeMissingComponent {
size_t component_idx{0};
DecomposeOfficialComponent official_component;
std::string preset_name;
wxString display_name;
};
struct MixedFilamentResult;
// ---- Functions ----
std::string decompose_normalize_color_hex(std::string color);
const char* decompose_base_color_en(DecomposeBaseColor color);
wxString decompose_base_color_display(DecomposeBaseColor color);
std::string decompose_basic_type_from_source(size_t source_config_idx,
size_t source_physical_idx,
const std::vector<std::string>& physical_types);
std::string decompose_basic_filament_id(const std::string& basic_type);
void set_created_standard_component_metadata(size_t config_idx, const DecomposeOfficialComponent& component);
DecomposeOfficialComponent lookup_decompose_official_component(
const std::string& basic_type,
DecomposeBaseColor base_color,
const wxColour& fallback);
std::string find_decompose_standard_preset_name(size_t source_config_idx, const std::string& basic_type);
// Returns "PLA Basic" / "PETG Basic" when preset_name names an official Bambu
// basic filament, else an empty string.
std::string official_basic_type_from_preset_name(const std::string& preset_name);
// Resolve display type for color-decompose: official Bambu Basic overrides
// get_filament_type when preset name matches; empty/missing -> "PLA".
std::string filament_type_for_color_decompose(Preset* preset);
int find_existing_decompose_component(
const DecomposeOfficialComponent& component,
const std::vector<std::string>& physical_colors,
const std::vector<size_t>& physical_config_indices,
size_t source_config_idx);
bool prepare_decompose_mixed_result(
const ColorDecomposeResult& result,
size_t source_config_idx,
size_t source_physical_idx,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& physical_types,
const std::vector<size_t>& physical_config_indices,
MixedFilamentResult& out_result,
std::vector<DecomposeMissingComponent>& missing);
// For standard modes: how many base colors are not reusable from physical list.
// MaterialList returns 0. When physical_config_indices is null, indices are 0..n-1.
size_t count_decompose_new_physical_filaments(
const ColorDecomposeResult& result,
const std::vector<std::string>& physical_colors,
const std::vector<std::string>& physical_types,
size_t source_physical_idx,
const std::vector<size_t>* physical_config_indices);
bool confirm_create_decompose_missing_components(wxWindow* parent,
const std::vector<DecomposeMissingComponent>& missing);
}} // namespace Slic3r::GUI
#endif // slic3r_GUI_ColorDecomposeSupport_hpp_
+71 -18
View File
@@ -2,6 +2,7 @@
#include "ConfigManipulation.hpp"
#include "I18N.hpp"
#include "GUI_App.hpp"
#include "DeviceCore/DevConfigUtil.h"
#include "format.hpp"
#include "libslic3r/Config.hpp"
#include "libslic3r/Model.hpp"
@@ -453,7 +454,7 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con
if (config->opt_bool("alternate_extra_wall") &&
(config->opt_enum<EnsureVerticalShellThickness>("ensure_vertical_shell_thickness") == evstAll)) {
wxString msg_text = _(L("Alternate extra wall does't work well when ensure vertical shell thickness is set to All."));
wxString msg_text = _(L("Alternate extra wall doesn't work well when ensure vertical shell thickness is set to All."));
if (is_global_config)
msg_text += "\n\n" + _(L("Change these settings automatically?\n"
@@ -577,27 +578,72 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con
}
// BBS
static const char* keys[] = { "support_filament", "support_interface_filament"};
for (int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
std::string key = std::string(keys[i]);
// Reset filament overrides pointing at a slot that no longer exists. Support and the wipe
// tower additionally reject mixed slots: the engine consumes those keys directly, so a virtual
// slot would reach the G-code unresolved, while the per-feature keys are resolved per layer.
static const char* physical_only_keys[] = { "support_filament", "support_interface_filament", "wipe_tower_filament" };
static const char* feature_keys[] = { "outer_wall_filament_id", "inner_wall_filament_id",
"sparse_infill_filament_id", "internal_solid_filament_id",
"top_surface_filament_id", "bottom_surface_filament_id" };
auto reset_invalid_filament = [this, config, filament_cnt](const char* key, bool allow_mixed) {
auto* opt = dynamic_cast<ConfigOptionInt*>(config->option(key, false));
if (opt != nullptr) {
if (opt->getInt() > filament_cnt) {
DynamicPrintConfig new_conf = *config;
const DynamicPrintConfig *conf_temp = wxGetApp().plater()->config();
int new_value = 0;
if (conf_temp != nullptr && conf_temp->has(key)) {
new_value = conf_temp->opt_int(key);
if (opt == nullptr)
return;
const int val = opt->getInt();
const bool out_of_range = val > filament_cnt;
const bool is_mixed = !allow_mixed && val > 0 && val <= filament_cnt &&
wxGetApp().preset_bundle->is_mixed_filament(val - 1);
if (!out_of_range && !is_mixed)
return;
DynamicPrintConfig new_conf = *config;
int new_value = 0;
if (out_of_range) {
const DynamicPrintConfig *conf_temp = wxGetApp().plater()->config();
if (conf_temp != nullptr && conf_temp->has(key))
new_value = conf_temp->opt_int(key);
}
new_conf.set_key_value(key, new ConfigOptionInt(new_value));
apply(config, &new_conf);
};
for (const char* key : physical_only_keys)
reset_invalid_filament(key, false);
for (const char* key : feature_keys)
reset_invalid_filament(key, true);
// Sub-layer splitting divides each layer by the mix ratio; an adaptive layer profile makes
// those sub-layer heights vary per layer, which degrades the blend. Warn once per enable.
{
static bool s_mixed_sublayer_warned = false;
bool sublayer_on = config->opt_bool("enable_mixed_color_sublayer");
if (sublayer_on && !s_mixed_sublayer_warned &&
wxGetApp().app_config->get("no_warn_mixed_sublayer_variable_layer") != "1") {
bool has_variable_layer = false;
for (const auto* obj : wxGetApp().model().objects) {
if (obj->layer_height_profile.get().size() > 4) {
has_variable_layer = true;
break;
}
new_conf.set_key_value(key, new ConfigOptionInt(new_value));
apply(config, &new_conf);
}
if (has_variable_layer) {
MessageDialog dialog(m_msg_dlg_parent,
_L("Using variable layer height together with mixed color sublayer may result in poor color mixing quality."),
"", wxICON_WARNING | wxOK);
dialog.show_dsa_button();
is_msg_dlg_already_exist = true;
dialog.ShowModal();
is_msg_dlg_already_exist = false;
if (dialog.get_checkbox_state())
wxGetApp().app_config->set("no_warn_mixed_sublayer_variable_layer", "1");
s_mixed_sublayer_warned = true;
}
}
if (!sublayer_on)
s_mixed_sublayer_warned = false;
}
if (config->opt_enum<SeamScarfType>("seam_slope_type") != SeamScarfType::None &&
config->get_abs_value("seam_slope_start_height") >= layer_height) {
const wxString msg_text = _(L("seam_slope_start_height need to be smaller than layer_height.\nReset to 0."));
const wxString msg_text = _(L("seam_slope_start_height needs to be smaller than layer_height.\nReset to 0."));
MessageDialog dialog(m_msg_dlg_parent, msg_text, "", wxICON_WARNING | wxOK);
DynamicPrintConfig new_conf = *config;
is_msg_dlg_already_exist = true;
@@ -611,7 +657,7 @@ void ConfigManipulation::update_print_fff_config(DynamicPrintConfig* config, con
float skin_depth = config->opt_float("skin_infill_depth");
if (config->opt_float("infill_lock_depth") > skin_depth) {
// xgettext:no-c-format, no-boost-format
const wxString msg_text = _(L("Lock depth should smaller than skin depth.\nReset to 50% of skin depth."));
const wxString msg_text = _(L("Lock depth should be smaller than skin depth.\nReset to 50% of skin depth."));
MessageDialog dialog(m_msg_dlg_parent, msg_text, "", wxICON_WARNING | wxOK);
DynamicPrintConfig new_conf = *config;
is_msg_dlg_already_exist = true;
@@ -696,14 +742,21 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
bool have_infill = config->option<ConfigOptionPercent>("sparse_infill_density")->value > 0;
// sparse_infill_filament_id uses the same logic as in Print::extruders()
for (auto el : { "sparse_infill_pattern", "infill_combination", "fill_multiline","infill_direction",
"minimum_sparse_infill_area", "sparse_infill_filament_id", "infill_anchor", "infill_anchor_max","infill_shift_step","sparse_infill_rotate_template","symmetric_infill_y_axis"})
"minimum_sparse_infill_area", "sparse_infill_filament_id","infill_shift_step","sparse_infill_rotate_template","symmetric_infill_y_axis"})
toggle_line(el, have_infill);
InfillPattern pattern = config->opt_enum<InfillPattern>("sparse_infill_pattern");
// Orca: the concentric patterns follow the surface outline instead of crossing it, so there is
// nothing for an infill anchor to attach to. Hide the anchor settings for them.
bool have_infill_anchor = have_infill && pattern != ipConcentric && pattern != ipSpiralInset;
toggle_line("infill_anchor", have_infill_anchor);
toggle_line("infill_anchor_max", have_infill_anchor);
bool have_combined_infill = config->opt_bool("infill_combination") && have_infill;
toggle_line("infill_combination_max_layer_height", have_combined_infill);
// Infill patterns that support multiline infill.
InfillPattern pattern = config->opt_enum<InfillPattern>("sparse_infill_pattern");
bool have_multiline_infill_pattern = pattern == ipGyroid || pattern == ipGrid || pattern == ipRectilinear || pattern == ipTpmsD || pattern == ipTpmsFK || pattern == ipCrossHatch || pattern == ipHoneycomb || pattern == ipLateralLattice || pattern == ipLateralHoneycomb || pattern == ipConcentric ||
pattern == ipCubic || pattern == ipStars || pattern == ipAlignedRectilinear || pattern == ipLightning || pattern == ip3DHoneycomb || pattern == ipAdaptiveCubic || pattern == ipSupportCubic|| pattern == ipTriangles || pattern == ipQuarterCubic|| pattern == ipArchimedeanChords || pattern == ipHilbertCurve || pattern == ipOctagramSpiral;
@@ -786,7 +839,7 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
toggle_line("separated_infills", is_internal_infill_separable);
// Fill order is only meaningful for the center-based surface fill patterns; hide it otherwise.
auto is_centered_fill = [](InfillPattern p) { return p == ipConcentric || p == ipArchimedeanChords || p == ipOctagramSpiral; };
auto is_centered_fill = [](InfillPattern p) { return p == ipConcentric || p == ipSpiralInset || p == ipArchimedeanChords || p == ipOctagramSpiral; };
toggle_line("top_surface_fill_order", has_top_shell && is_centered_fill(config->opt_enum<InfillPattern>("top_surface_pattern")));
toggle_line("bottom_surface_fill_order", has_bottom_shell && is_centered_fill(config->opt_enum<InfillPattern>("bottom_surface_pattern")));
+245
View File
@@ -0,0 +1,245 @@
#include "ConfigValueFormatter.hpp"
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include "libslic3r/Config.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "I18N.hpp"
#include "GUI.hpp"
#include "Field.hpp"
namespace Slic3r {
namespace GUI {
std::string get_pure_opt_key(const std::string& opt_key)
{
std::string pure_key = opt_key;
const int pos = pure_key.find("#");
if (pos > 0)
boost::erase_tail(pure_key, pure_key.size() - pos);
return pure_key;
}
wxString get_string_from_enum(const std::string& opt_key, const DynamicPrintConfig& config, bool is_infill, int idx)
{
const ConfigOptionDef& def = config.def()->options.at(opt_key);
const std::vector<std::string>& names = def.enum_labels;//ConfigOptionEnum<T>::get_enum_names();
int val = 0;
if (idx >= 0)
val = dynamic_cast<const ConfigOptionInts*>(config.option(opt_key))->get_at(idx);
else
val = config.option(opt_key)->getInt();
// Each infill doesn't use all list of infill declared in PrintConfig.hpp.
// So we should "convert" val to the correct one
if (is_infill) {
for (auto key_val : *def.enum_keys_map)
if (int(key_val.second) == val) {
auto it = std::find(def.enum_values.begin(), def.enum_values.end(), key_val.first);
if (it == def.enum_values.end())
return "";
return from_u8(_utf8(names[it - def.enum_values.begin()]));
}
return _L("Undefined");
}
return from_u8(_utf8(names[val]));
}
wxString get_full_label(const std::string& opt_key, const DynamicPrintConfig& config)
{
const std::string pure_key = get_pure_opt_key(opt_key);
auto option = config.option(pure_key);
if (!option || option->is_nil())
return _L("N/A");
const ConfigOptionDef* opt = config.def()->get(pure_key);
return opt->full_label.empty() ? opt->label : opt->full_label;
}
wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig& config)
{
int orig_opt_idx = -1;
int opt_idx = -1;
int pos = opt_key.find("#");
std::string temp_str = opt_key;
if (pos > 0) {
boost::erase_head(temp_str, pos + 1);
orig_opt_idx = std::atoi(temp_str.c_str());
}
opt_idx = orig_opt_idx >= 0 ? orig_opt_idx : 0;
const std::string pure_key = get_pure_opt_key(opt_key);
auto option = config.option(pure_key);
if (!option) {
return _L("N/A");
}
auto opt_vector = dynamic_cast<const ConfigOptionVectorBase *>(option);
if ((option->is_scalar() && option->is_nil()) ||
(option->is_vector() && opt_vector && opt_idx >= 0 && opt_idx < opt_vector->size() && opt_vector->is_nil(opt_idx)))
return _L("N/A");
wxString out;
const ConfigOptionDef* opt = config.def()->get(pure_key);
bool is_nullable = opt->nullable;
switch (opt->type) {
case coInt:
return from_u8((boost::format("%1%") % config.opt_int(pure_key)).str());
case coInts: {
if (is_nullable) {
auto values = config.opt<ConfigOptionIntsNullable>(pure_key);
if (opt_idx < values->size())
return from_u8((boost::format("%1%") % values->get_at(opt_idx)).str());
}
else {
auto values = config.opt<ConfigOptionInts>(pure_key);
if (orig_opt_idx >= 0 && orig_opt_idx < values->size()) {
return from_u8((boost::format("%1%") % values->get_at(opt_idx)).str());
}
else {
std::string value_str;
for (int i = 0; i < values->size(); i++) {
value_str += std::to_string(values->get_at(i));
if (i != values->size() - 1) {
value_str += ",";
}
}
return from_u8(value_str);
}
}
return _L("Undefined");
}
case coBool:
return config.opt_bool(pure_key) ? "true" : "false";
case coBools: {
if (is_nullable) {
auto values = config.opt<ConfigOptionBoolsNullable>(pure_key);
if (opt_idx < values->size())
return values->get_at(opt_idx) ? "true" : "false";
}
else {
auto values = config.opt<ConfigOptionBools>(pure_key);
if (opt_idx < values->size())
return values->get_at(opt_idx) ? "true" : "false";
}
return _L("Undefined");
}
case coPercent:
return from_u8((boost::format("%1%%%") % int(config.optptr(pure_key)->getFloat())).str());
case coPercents: {
if (is_nullable) {
auto values = config.opt<ConfigOptionPercentsNullable>(pure_key);
if (opt_idx < values->size())
return from_u8((boost::format("%1%%%") % values->get_at(opt_idx)).str());
}
else {
auto values = config.opt<ConfigOptionPercents>(pure_key);
if (opt_idx < values->size())
return from_u8((boost::format("%1%%%") % values->get_at(opt_idx)).str());
}
return _L("Undefined");
}
case coFloat:
return double_to_string(config.opt_float(pure_key));
case coFloats: {
if (is_nullable) {
auto values = config.opt<ConfigOptionFloatsNullable>(pure_key);
if (opt_idx < values->size())
return double_to_string(values->get_at(opt_idx));
}
else {
auto values = config.opt<ConfigOptionFloats>(pure_key);
if (values && opt_idx < values->size())
return double_to_string(values->get_at(opt_idx));
}
return _L("Undefined");
}
case coString:
return from_u8(config.opt_string(pure_key));
case coStrings: {
const ConfigOptionStrings* strings = config.opt<ConfigOptionStrings>(pure_key);
if (strings) {
if (pure_key == "compatible_printers" || pure_key == "compatible_prints") {
if (strings->empty())
return _L("All");
for (size_t id = 0; id < strings->size(); id++)
out += from_u8(strings->get_at(id)) + "\n";
out.RemoveLast(1);
return out;
}
if (!strings->empty() && opt_idx < strings->values.size())
return from_u8(strings->get_at(opt_idx));
}
break;
}
case coFloatOrPercent: {
const ConfigOptionFloatOrPercent* opt = config.opt<ConfigOptionFloatOrPercent>(pure_key);
if (opt)
out = double_to_string(opt->value) + (opt->percent ? "%" : "");
return out;
}
case coEnum: {
return get_string_from_enum(pure_key, config,
pure_key == "top_surface_pattern" ||
pure_key == "bottom_surface_pattern" ||
pure_key == "internal_solid_infill_pattern" ||
pure_key == "sparse_infill_pattern" ||
pure_key == "ironing_pattern" ||
pure_key == "support_ironing_pattern" ||
pure_key == "support_pattern" ||
pure_key == "support_interface_pattern")
;
}
case coEnums: {
return get_string_from_enum(pure_key, config,
pure_key == "top_surface_pattern" ||
pure_key == "bottom_surface_pattern" ||
pure_key == "internal_solid_infill_pattern" ||
pure_key == "sparse_infill_pattern" ||
pure_key == "ironing_pattern" ||
pure_key == "support_ironing_pattern" ||
pure_key == "support_pattern" ||
pure_key == "support_interface_pattern"
, opt_idx);
}
case coPoint: {
Vec2d val = config.opt<ConfigOptionPoint>(pure_key)->value;
return from_u8((boost::format("[%1%]") % ConfigOptionPoint(val).serialize()).str());
}
case coPoints: {
//BBS: add bed_exclude_area
if (pure_key == "printable_area" || pure_key == "thumbnails") {
ConfigOptionPoints points = *config.option<ConfigOptionPoints>(pure_key);
//BuildVolume build_volume = {points.values, 0.};
return get_thumbnails_string(points.values);
}
else if (pure_key == "bed_exclude_area") {
return get_thumbnails_string(config.option<ConfigOptionPoints>(pure_key)->values);
}
else if (pure_key == "head_wrap_detect_zone") {
return get_thumbnails_string(config.option<ConfigOptionPoints>(pure_key)->values);
}
else if (pure_key == "wrapping_exclude_area") {
return get_thumbnails_string(config.option<ConfigOptionPoints>(pure_key)->values);
}
Vec2d val = config.opt<ConfigOptionPoints>(pure_key)->get_at(opt_idx);
return from_u8((boost::format("[%1%]") % ConfigOptionPoint(val).serialize()).str());
}
default:
break;
}
return out;
}
} // namespace GUI
} // namespace Slic3r
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <string>
#include <wx/string.h>
namespace Slic3r {
class DynamicPrintConfig;
namespace GUI {
// Human-readable value of opt_key (may carry a "#<index>" suffix) in config.
wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig& config);
// Full label of opt_key; "N/A" when the option is not set.
wxString get_full_label(const std::string& opt_key, const DynamicPrintConfig& config);
// Strip the "#<index>" suffix (if any) from the option key.
std::string get_pure_opt_key(const std::string& opt_key);
// Localized label of the currently selected value of an enum option.
wxString get_string_from_enum(const std::string& opt_key, const DynamicPrintConfig& config, bool is_infill = false, int idx = -1);
} // namespace GUI
} // namespace Slic3r
+1 -1
View File
@@ -2752,7 +2752,7 @@ ConfigWizard::ConfigWizard(wxWindow *parent)
});
if (wxLinux_gtk3)
this->Bind(wxEVT_SHOW, [this, vsizer](const wxShowEvent& e) {
this->Bind(wxEVT_SHOW, [](const wxShowEvent& e) {
;
});
+7 -5
View File
@@ -599,7 +599,9 @@ static char* read_json_file(const std::string &preset_path)
return NULL;
}
fread(json_contents, 1, file_size, json_file);
const size_t read_bytes = fread(json_contents, 1, file_size, json_file);
if (read_bytes != static_cast<size_t>(file_size))
BOOST_LOG_TRIVIAL(error) << "Read " << read_bytes << " of " << file_size << " bytes from the JSON file";
fclose(json_file);
return json_contents;
@@ -1885,7 +1887,7 @@ wxBoxSizer *CreatePrinterPresetDialog::create_nozzle_diameter_item(wxWindow *par
m_custom_nozzle_diameter_ctrl = new wxTextCtrl(parent, wxID_ANY, "", wxDefaultPosition, NAME_OPTION_COMBOBOX_SIZE);
m_custom_nozzle_diameter_ctrl->SetHint(_L("Input Custom Nozzle Diameter"));
m_custom_nozzle_diameter_ctrl->Bind(wxEVT_CHAR, [this](wxKeyEvent &event) {
m_custom_nozzle_diameter_ctrl->Bind(wxEVT_CHAR, [](wxKeyEvent &event) {
int key = event.GetKeyCode();
if (key != 44 && key != 46 && cannot_input_key.find(key) != cannot_input_key.end()) { // "@" can not be inputed
event.Skip(false);
@@ -3867,14 +3869,14 @@ void ExportConfigsDialog::select_curr_radiobox(std::vector<std::pair<RadioBox *,
m_preset_sizer->Add(create_checkbox(m_presets_window, preset.second, printer_name, m_preset), 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT,
FromDIP(5));
}
m_serial_text->SetLabel(_L("Only printer names with user printer presets will be displayed, and each preset you choose will be exported as a zip."));
m_serial_text->SetLabel(_L("Only printer names with user printer presets will be displayed, and each preset you choose will be exported as a ZIP archive."));
} else if (export_type == m_exprot_type.filament_preset) {
for (std::pair<std::string, std::vector<std::pair<std::string, Preset *>>> filament_name_to_preset : m_filament_name_to_presets) {
if (filament_name_to_preset.second.empty()) continue;
wxString filament_name = wxString::FromUTF8(filament_name_to_preset.first);
m_preset_sizer->Add(create_checkbox(m_presets_window, filament_name, m_printer_name), 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, FromDIP(5));
}
m_serial_text->SetLabel(_L("Only the filament names with user filament presets will be displayed, \nand all user filament presets in each filament name you select will be exported as a zip."));
m_serial_text->SetLabel(_L("Only the filament names with user filament presets will be displayed, \nand all user filament presets in each filament name you select will be exported as a ZIP archive."));
} else if (export_type == m_exprot_type.process_preset) {
for (std::pair<std::string, std::vector<Preset *>> presets : m_process_presets) {
Preset * printer_preset = preset_bundle->printers.find_preset(presets.first, false);
@@ -3890,7 +3892,7 @@ void ExportConfigsDialog::select_curr_radiobox(std::vector<std::pair<RadioBox *,
}
}
m_serial_text->SetLabel(_L("Only printer names with changed process presets will be displayed, \nand all user process presets in each printer name you select will be exported as a zip."));
m_serial_text->SetLabel(_L("Only printer names with changed process presets will be displayed, \nand all user process presets in each printer name you select will be exported as a ZIP archive."));
}
//m_presets_window->SetSizerAndFit(m_preset_sizer);
m_presets_window->Layout();
-3
View File
@@ -74,12 +74,9 @@ private:
std::unordered_set<std::string> m_system_filament_types_set;
std::set<std::string> m_visible_printers;
CreateType m_create_type;
Button * m_button_create = nullptr;
Button * m_button_cancel = nullptr;
ComboBox * m_filament_vendor_combobox = nullptr;
::CheckBox * m_can_not_find_vendor_checkbox = nullptr;
ComboBox * m_filament_type_combobox = nullptr;
ComboBox * m_exist_vendor_combobox = nullptr;
ComboBox * m_filament_preset_combobox = nullptr;
TextInput * m_filament_custom_vendor_input = nullptr;
wxGridSizer * m_filament_presets_sizer = nullptr;
+1 -1
View File
@@ -1,4 +1,5 @@
#include "DailyTips.hpp"
#include "slic3r/GUI/Widgets/Label.hpp"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
@@ -245,7 +246,6 @@ DailyTipsPanel::DailyTipsPanel(bool can_expand, DailyTipsLayout layout)
m_width(0),
m_height(0),
m_can_expand(can_expand),
m_layout(layout),
m_uid(DailyTipsPanel::uid++),
m_dailytips_renderer(std::make_unique<DailyTipsDataRenderer>(layout))
{
-1
View File
@@ -51,7 +51,6 @@ private:
int m_uid;
bool m_first_enter{ false };
bool m_is_dark{ false };
DailyTipsLayout m_layout{ DailyTipsLayout::Vertical };
float m_fade_opacity{ 1.0f };
};
+2
View File
@@ -1,5 +1,7 @@
#include <boost/log/trivial.hpp>
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/DeviceManager.hpp"
#include "slic3r/GUI/UserNotification.hpp"
#include "libslic3r/PrintConfig.hpp"
+1 -1
View File
@@ -54,7 +54,7 @@ public:
void ParseCalibrationConfig(const json& print_json); //cali
private:
MachineObject* m_obj;
[[maybe_unused]] MachineObject* m_obj;
/*configure vals*/
// chamber
+21 -18
View File
@@ -16,24 +16,27 @@ namespace Slic3r
// This block is never executed at runtime.
static void _toolhead_translation_markers()
{
// Dynamic toolhead display names from JSON config — xgettext cannot scan these
L("Main Extruder"); L("Main extruder"); L("main extruder");
L("Auxiliary Extruder"); L("Auxiliary extruder"); L("auxiliary extruder");
L("Left Extruder"); L("Left extruder"); L("left extruder");
L("Right Extruder"); L("Right extruder"); L("right extruder");
L("Main Nozzle"); L("Main nozzle"); L("main nozzle");
L("Auxiliary Nozzle"); L("Auxiliary nozzle"); L("auxiliary nozzle");
L("Left Nozzle"); L("Left nozzle"); L("left nozzle");
L("Right Nozzle"); L("Right nozzle"); L("right nozzle");
L("Main Hotend"); L("Main hotend"); L("main hotend");
L("Auxiliary Hotend"); L("Auxiliary hotend"); L("auxiliary hotend");
L("Left Hotend"); L("Left hotend"); L("left hotend");
L("Right Hotend"); L("Right hotend"); L("right hotend");
// standalone position words (short_name=true runtime results)
L("main"); L("auxiliary");
L("Main"); L("Auxiliary");
L("left"); L("right");
L("Left"); L("Right");
// Possible runtime values of tool_head_display_names, marked for extraction.
static const char *const markers[] = {
L("Main Extruder"), L("Main extruder"), L("main extruder"),
L("Auxiliary Extruder"), L("Auxiliary extruder"), L("auxiliary extruder"),
L("Left Extruder"), L("Left extruder"), L("left extruder"),
L("Right Extruder"), L("Right extruder"), L("right extruder"),
L("Main Nozzle"), L("Main nozzle"), L("main nozzle"),
L("Auxiliary Nozzle"), L("Auxiliary nozzle"), L("auxiliary nozzle"),
L("Left Nozzle"), L("Left nozzle"), L("left nozzle"),
L("Right Nozzle"), L("Right nozzle"), L("right nozzle"),
L("Main Hotend"), L("Main hotend"), L("main hotend"),
L("Auxiliary Hotend"), L("Auxiliary hotend"), L("auxiliary hotend"),
L("Left Hotend"), L("Left hotend"), L("left hotend"),
L("Right Hotend"), L("Right hotend"), L("right hotend"),
// standalone position words (short_name=true runtime results)
L("main"), L("auxiliary"),
L("Main"), L("Auxiliary"),
L("left"), L("right"),
L("Left"), L("Right"),
};
(void) markers;
}
std::string DevPrinterConfigUtil::m_resource_file_path = "";
+1 -1
View File
@@ -31,7 +31,7 @@ protected:
DevExtensionTool(MachineObject* obj);
private:
MachineObject* m_owner = nullptr;
[[maybe_unused]] MachineObject* m_owner = nullptr;
enum MountState
{
@@ -28,7 +28,7 @@ public:
void SetAutoRefillEnabled(bool enable) { m_enable_auto_refill = enable; }
private:
DevFilaSystem* m_owner = nullptr;
[[maybe_unused]] DevFilaSystem* m_owner = nullptr;
std::optional<bool> m_enable_detect_on_insert = false;
bool m_enable_detect_on_powerup = false;
@@ -4,6 +4,8 @@
#include <set>
#include "DevFilaBlackList.h"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "slic3r/GUI/DeviceManager.hpp"
#include "DevFilaSystem.h"
#include "DevManager.h"
#include "DevConfigUtil.h"
@@ -241,8 +243,11 @@ void check_filaments(const DevFilaBlacklist::CheckFilamentInfo& check_info, DevF
std::set<std::string> white_fila_ids = filament_item.contains("white_fila_ids") ? filament_item["white_fila_ids"].get<std::set<std::string>>() : std::set<std::string>();
if (!white_fila_ids.empty() && !check_info.fila_id.empty())
{
auto it = std::find_if(white_fila_ids.begin(), white_fila_ids.end(), [&check_info](const std::string& white_fila_id) {
return white_fila_id == check_info.fila_id;
// check_info.fila_id is our OF id; white_fila_ids in filaments_blacklist.json holds the printer's own.
auto* agent = Slic3r::GUI::wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(check_info.fila_id) : check_info.fila_id;
auto it = std::find_if(white_fila_ids.begin(), white_fila_ids.end(), [&printer_filament_id](const std::string& white_fila_id) {
return white_fila_id == printer_filament_id;
});
if (it != white_fila_ids.end()) { continue; }
}
+13 -3
View File
@@ -1,10 +1,12 @@
#include <nlohmann/json.hpp>
#include "DevFilaSystem.h"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "DevNozzleSystem.h" // DevNozzle / DevNozzleSystem for GetNozzleFlowStringByAmsId
// TODO: remove this include
#include "slic3r/GUI/DeviceManager.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "DevUtil.h"
#include "DevUtilBackend.h"
@@ -95,7 +97,12 @@ std::string DevAmsTray::get_filament_type()
if (m_fila_type == "Sup.ABS") { return "ABS-S"; }
if (m_fila_type == "Support W") { return "PLA-S"; }
if (m_fila_type == "Support G") { return "PA-S"; }
if (m_fila_type == "Support") { if (setting_id == "GFS00") { m_fila_type = "PLA-S"; } else if (setting_id == "GFS01") { m_fila_type = "PA-S"; } else { return "PLA-S"; } }
// setting_id is our OF id; GFS00/GFS01 are the printer's own support-filament ids.
if (m_fila_type == "Support") {
auto* agent = GUI::wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(setting_id) : setting_id;
if (printer_filament_id == "GFS00") { m_fila_type = "PLA-S"; } else if (printer_filament_id == "GFS01") { m_fila_type = "PA-S"; } else { return "PLA-S"; }
}
return m_fila_type;
}
@@ -654,11 +661,14 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS
curr_tray->setting_id = (*tray_it)["tray_info_idx"].get<std::string>();
//std::string type = (*tray_it)["tray_type"].get<std::string>();
std::string type = MachineObject::setting_id_to_type(curr_tray->setting_id, (*tray_it)["tray_type"].get<std::string>());
if (curr_tray->setting_id == "GFS00")
// curr_tray->setting_id is our OF id; GFS00/GFS01 are the printer's own support-filament ids.
auto* agent = GUI::wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(curr_tray->setting_id) : curr_tray->setting_id;
if (printer_filament_id == "GFS00")
{
curr_tray->m_fila_type = "PLA-S";
}
else if (curr_tray->setting_id == "GFS01")
else if (printer_filament_id == "GFS01")
{
curr_tray->m_fila_type = "PA-S";
}
+1 -1
View File
@@ -58,7 +58,7 @@ public:
std::string id;
std::string tag_uid; // tag_uid
std::string setting_id; // tray_info_idx
std::string setting_id; // tray_info_idx, map to the filament_id
std::string filament_setting_id; // setting_id
std::string m_fila_type;
std::string sub_brands;
+1 -1
View File
@@ -64,7 +64,7 @@ public:
DevFirmware(MachineObject* obj) : m_owner(obj) {}
private:
MachineObject* m_owner = nullptr;
[[maybe_unused]] MachineObject* m_owner = nullptr;
};
} // namespace Slic3r
+1 -1
View File
@@ -21,7 +21,7 @@ public:
const std::vector<DevHMSItem>& GetHMSItems() const { return m_hms_list; };
private:
MachineObject* m_object = nullptr;
[[maybe_unused]] MachineObject* m_object = nullptr;
// all hms for this machine
std::vector<DevHMSItem> m_hms_list;
+1 -1
View File
@@ -34,7 +34,7 @@ private:
//std::string m_connect_type;
//std::string m_bind_state;
MachineObject* m_owner = nullptr;
[[maybe_unused]] MachineObject* m_owner = nullptr;
};
} // namespace Slic3r
+1 -1
View File
@@ -872,7 +872,7 @@ namespace Slic3r
obj->m_is_online = elem["dev_online"].get<bool>();
if (elem.contains("dev_model_name") && !elem["dev_model_name"].is_null()) {
auto printer_type = elem["dev_model_name"].get<std::string>();
for (const std::pair<std::string, std::vector<std::string>> &pair : device_subseries) {
for (const auto &pair : device_subseries) {
auto it = std::find(pair.second.begin(), pair.second.end(), printer_type);
if (it != pair.second.end())
{
+3 -1
View File
@@ -1,3 +1,5 @@
#include <limits>
#include <nlohmann/json.hpp>
#include "DevMapping.h"
#include "DevFilaSystem.h"
@@ -270,7 +272,7 @@ namespace Slic3r
std::set<int> picked_tar;
for (int k = 0; k < distance_map.size(); k++)
{
float min_val = INT_MAX;
float min_val = std::numeric_limits<float>::max();
int picked_src_idx = -1;
int picked_tar_idx = -1;
for (int i = 0; i < distance_map.size(); i++)
+1 -1
View File
@@ -36,7 +36,7 @@ public:
void ParseStatus(const nlohmann::json& print_jj);
private:
MachineObject *m_owner = nullptr;
[[maybe_unused]] MachineObject *m_owner = nullptr;
std::optional<DevJobState> m_job_state; // could be nullopt for some old firmware
};
+1 -1
View File
@@ -31,7 +31,7 @@ public:
bool is_timelapse_storage_low(const std::string& storage) const;
private:
MachineObject *m_owner;
[[maybe_unused]] MachineObject *m_owner;
SdcardState m_sdcard_state { NO_SDCARD };
// timelapse storage space info (from device push cam data)
int tl_internal_free_kb{-1};
+29 -4
View File
@@ -1,5 +1,7 @@
#include "libslic3r/libslic3r.h"
#include "DeviceManager.hpp"
#include "HMS.hpp"
#include "I18N.hpp"
#include "libslic3r/Time.hpp"
#include "libslic3r/Thread.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
@@ -110,7 +112,9 @@ bool Slic3r::is_stringing_prone_filament(const std::string& filament_id, float n
if (filament_id.empty()) return false;
const auto* set = pick_stringing_set(nozzle_diameter);
if (!set) return false;
return set->count(filament_id) > 0;
// filament_id is one of our content-addressed OF ids; the table above is keyed by the printer's own.
auto* agent = Slic3r::GUI::wxGetApp().getAgent();
return set->count(agent ? agent->from_orca_filament_id(filament_id) : filament_id) > 0;
}
wxString Slic3r::get_stage_string(int stage)
@@ -5048,10 +5052,13 @@ DevAmsTray MachineObject::parse_vt_tray(json vtray)
vt_tray.setting_id = vtray["tray_info_idx"].get<std::string>();
//std::string type = vtray["tray_type"].get<std::string>();
std::string type = setting_id_to_type(vt_tray.setting_id, vtray["tray_type"].get<std::string>());
if (vt_tray.setting_id == "GFS00") {
// vt_tray.setting_id is our OF id (translated on the way in); the two support ids below are the printer's own.
auto* agent = GUI::wxGetApp().getAgent();
const std::string printer_filament_id = agent ? agent->from_orca_filament_id(vt_tray.setting_id) : vt_tray.setting_id;
if (printer_filament_id == "GFS00") {
vt_tray.m_fila_type = "PLA-S";
}
else if (vt_tray.setting_id == "GFS01") {
else if (printer_filament_id == "GFS01") {
vt_tray.m_fila_type = "PA-S";
}
else {
@@ -5592,7 +5599,10 @@ void MachineObject::update_filament_list()
for (auto it = filament_list.begin(); it != filament_list.end(); it++) {
if (m_filament_list.find(it->first) != m_filament_list.end()) {
assert(it->first.size() == 8 && it->first[0] == 'P');
// User roots may legitimately carry adopted system-shaped ids (GF*/OF*/P-hex
// system), so a non-'P' id here is expected, not an invariant violation.
if (it->first.size() != 8 || it->first[0] != 'P')
BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": user-root filament_id is not user-shaped: " << it->first;
if (it->second.first != m_filament_list[it->first].first) {
BOOST_LOG_TRIVIAL(info) << "old min temp is not equal to new min temp and filament id: " << it->first;
@@ -5654,6 +5664,17 @@ void MachineObject::update_printer_preset_name()
void MachineObject::check_ams_filament_valid()
{
PresetBundle * preset_bundle = Slic3r::GUI::wxGetApp().preset_bundle;
// A tray id carried by ANY system filament preset is not a dangling user-preset id
// (ten shipped P-hex system ids pass the 'P' shape gates below), so the destructive
// tray-wipe / temp-rewrite handling must never fire for it.
auto is_system_filament_id = [preset_bundle](const std::string &id) {
if (!preset_bundle)
return false;
for (auto it = preset_bundle->filaments.begin(); it != preset_bundle->filaments.end(); it++)
if (it->is_system && it->filament_id == id)
return true;
return false;
};
auto printer_model = DevPrinterConfigUtil::get_printer_display_name(this->printer_type);
std::map<std::string, std::set<std::string>> need_checked_filament_id;
for (auto &ams_pair : m_fila_system->GetAmsList()) {
@@ -5675,6 +5696,8 @@ void MachineObject::check_ams_filament_valid()
auto &checked_filament = data.checked_filament;
for (const auto &[slot_id, curr_tray] : ams->GetTrays()) {
if (curr_tray->setting_id.size() == 8 && curr_tray->setting_id[0] == 'P' && is_system_filament_id(curr_tray->setting_id))
continue;
if (curr_tray->setting_id.size() == 8 && curr_tray->setting_id[0] == 'P' && filament_list.find(curr_tray->setting_id) == filament_list.end()) {
if (checked_filament.find(curr_tray->setting_id) != checked_filament.end()) {
need_checked_filament_id[nozzle_diameter_str].insert(curr_tray->setting_id);
@@ -5735,6 +5758,8 @@ void MachineObject::check_ams_filament_valid()
auto &data = m_nozzle_filament_data[nozzle_diameter_str];
auto &checked_filament = data.checked_filament;
auto &filament_list = data.filament_list;
if (vt_tray.setting_id.size() == 8 && vt_tray.setting_id[0] == 'P' && is_system_filament_id(vt_tray.setting_id))
continue;
if (vt_tray.setting_id.size() == 8 && vt_tray.setting_id[0] == 'P' && filament_list.find(vt_tray.setting_id) == filament_list.end()) {
if (checked_filament.find(vt_tray.setting_id) != checked_filament.end()) {
need_checked_filament_id[nozzle_diameter_str].insert(vt_tray.setting_id);
@@ -2,7 +2,7 @@
/* File: uiAMSBestPositionPopup.hpp
* Description: The popup with suggest best ams position
*
//**********************************************************/
************************************************************/
#include "uiAMSBestPositionPopup.hpp"
@@ -705,7 +705,7 @@ ReselectMachineDialog::ReselectMachineDialog(wxWindow* parent)
Centre();
}
void ReselectMachineDialog::Update(MachineObject* obj, const std::map<int, int>& best_pos_map, const std::vector<FilamentInfo>& ams_mapping, wxString save_time)
void ReselectMachineDialog::UpdateInfo(MachineObject* obj, const std::map<int, int>& best_pos_map, const std::vector<FilamentInfo>& ams_mapping, wxString save_time)
{
if (suggestText)
@@ -2,7 +2,7 @@
/* File: uiAMSBestPositionPopup.hpp
* Description: The popup with suggest best ams position
*
//**********************************************************/
************************************************************/
#pragma once
#include "slic3r/GUI/Widgets/AMSItem.hpp"
@@ -188,7 +188,7 @@ class ReselectMachineDialog : public wxDialog
public:
ReselectMachineDialog(wxWindow* parent);
~ReselectMachineDialog();
void Update(MachineObject* obj,
void UpdateInfo(MachineObject* obj,
const std::map<int, int>& best_pos_map,
const std::vector<FilamentInfo>& ams_mapping,
wxString save_time);
@@ -199,7 +199,6 @@ private:
void OnRefreshButton(wxCommandEvent& event);
private:
int saveTimes{0};
wxBoxSizer* mainSizer{nullptr};
wxPanel* textPanel{nullptr};
wxBoxSizer* textSizer{nullptr};
@@ -98,7 +98,7 @@ void uiAmsPercentHumidityDryPopup::Create()
Refresh();
}
void uiAmsPercentHumidityDryPopup::Update(int humidiy_level, int humidity_percent, int left_dry_time, float current_temperature)
void uiAmsPercentHumidityDryPopup::UpdateInfo(int humidiy_level, int humidity_percent, int left_dry_time, float current_temperature)
{
if (m_humidity_level != humidiy_level || m_humidity_percent != humidity_percent ||
m_left_dry_time != left_dry_time || m_current_temperature != current_temperature)
@@ -38,14 +38,14 @@ public:
~uiAmsPercentHumidityDryPopup() = default;
public:
void Update(uiAmsHumidityInfo *info) { m_ams_id = info->ams_id; Update(info->humidity_display_idx, info->humidity_percent, info->left_dry_time, info->current_temperature); };
void UpdateInfo(uiAmsHumidityInfo *info) { m_ams_id = info->ams_id; UpdateInfo(info->humidity_display_idx, info->humidity_percent, info->left_dry_time, info->current_temperature); };
std::string get_owner_ams_id() const { return m_ams_id; }
void msw_rescale();
private:
void Update(int humidiy_level, int humidity_percent, int left_dry_time, float current_temperature);
void UpdateInfo(int humidiy_level, int humidity_percent, int left_dry_time, float current_temperature);
void UpdateContents();
void Create();
@@ -6,7 +6,7 @@
* \n class wgtDeviceNozzleRackNozzleItem;
* \n class wgtDeviceNozzleRackToolHead;
* \n class wgtDeviceNozzleRackPos;
//**********************************************************/
************************************************************/
#include "wgtDeviceNozzleRack.h"
#include "wgtDeviceNozzleRackUpdate.h"
@@ -399,7 +399,7 @@ void wgtDeviceNozzleRackArea::UpdateNozzleItems(const std::unordered_map<int, wg
{
for (auto iter : nozzle_items)
{
iter.second->Update(nozzle_rack);
iter.second->UpdateInfo(nozzle_rack);
}
/*update nozzle possition and background*/
@@ -837,7 +837,7 @@ void wgtDeviceNozzleRackNozzleItem::SetSelected(bool selected)
}
}
void wgtDeviceNozzleRackNozzleItem::Update(const std::shared_ptr<DevNozzleRack> rack, bool on_rack /*= true*/)
void wgtDeviceNozzleRackNozzleItem::UpdateInfo(const std::shared_ptr<DevNozzleRack> rack, bool on_rack /*= true*/)
{
m_rack = rack;
@@ -6,7 +6,7 @@
* \n class wgtDeviceNozzleRackNozzleItem;
* \n class wgtDeviceNozzleRackToolHead;
* \n class wgtDeviceNozzleRackPos;
//**********************************************************/
************************************************************/
#pragma once
#include "slic3r/GUI/DeviceCore/DevNozzleRack.h"
@@ -200,7 +200,7 @@ public:
wgtDeviceNozzleRackNozzleItem(wxWindow* parent, int nozzle_id);
public:
void Update(const std::shared_ptr<DevNozzleRack> rack, bool on_rack = true); // on_rack is false means extruder nozzle
void UpdateInfo(const std::shared_ptr<DevNozzleRack> rack, bool on_rack = true); // on_rack is false means extruder nozzle
int GetNozzleId() const { return m_nozzle_id; }
void SetDisplayIdText(const wxString& text) { m_nozzle_label_id->SetLabel(text);};
@@ -3,7 +3,7 @@
* Description: The panel with rack updating
*
* \n class wgtDeviceNozzleRackUpdate
//**********************************************************/
************************************************************/
#include "wgtDeviceNozzleRackUpdate.h"
@@ -3,7 +3,7 @@
* Description: The panel for updating hotends
*
* \n class wgtDeviceNozzleRackUpdate
//**********************************************************/
************************************************************/
#pragma once
#include "slic3r/GUI/DeviceCore/DevNozzleRack.h"
@@ -122,7 +122,6 @@ private:
private:
int m_ext_nozzle_id = -1;
int m_rack_nozzle_id = -1;
bool m_isRefreshFinish = false;
bool findNozzleImage = false;
NozzleStatus m_nozzle_status = NOZZLE_STATUS_DC;
@@ -154,7 +153,6 @@ private:
Label* m_diameter_label;
Label* m_flowtype_label;
Label* m_type_label;
ScalableButton* m_error_button{ nullptr };
Label* m_sn_label;
Label* m_version_label;
@@ -3,7 +3,7 @@
* Description: The panel to select nozzle
*
* \n class wgtDeviceNozzleSelect;
//**********************************************************/
************************************************************/
#include "wgtDeviceNozzleSelect.h"
#include "wgtDeviceNozzleRack.h"
@@ -114,7 +114,7 @@ static void s_update_nozzle_info(wgtDeviceNozzleRackNozzleItem* item,
std::shared_ptr<DevNozzleRack> rack,
const DevNozzle& nozzle_info)
{
item->Update(rack, nozzle_info.IsOnRack());
item->UpdateInfo(rack, nozzle_info.IsOnRack());
if (nozzle_info.IsUnknown()) {
if (item->GetToolTipText() != _L("Nozzle information needs to be read")) {
item->SetToolTip(_L("Nozzle information needs to be read"));
@@ -266,7 +266,7 @@ void wgtDeviceNozzleRackSelect::OnNozzleItemSelected(wxCommandEvent &evt)
}
auto *item = dynamic_cast<wgtDeviceNozzleRackNozzleItem *>(evt.GetEventObject());
if (item; auto ptr = m_nozzle_rack.lock()) {
if (auto ptr = m_nozzle_rack.lock(); item && ptr) {
int to_select_pos_id = sGetNozzlePosId(item, m_toolhead_nozzle_l, m_toolhead_nozzle_r);
if (to_select_pos_id > -1 && to_select_pos_id != GetSelectedNozzlePosID()) {
SetSelectedNozzle(ptr->GetNozzleSystem()->GetNozzleByPosId(to_select_pos_id));
@@ -3,7 +3,7 @@
* Description: The panel to select nozzle
*
* \n class wgtDeviceNozzleSelect;
//**********************************************************/
************************************************************/
#pragma once
+1
View File
@@ -1,6 +1,7 @@
#include "wgtMsgPanel.h"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/Widgets/Label.hpp"
#include "slic3r/GUI/Widgets/StateColor.hpp"
#include "slic3r/GUI/wxExtensions.hpp"
+1
View File
@@ -1,6 +1,7 @@
#include "DragCanvas.hpp"
#include "wxExtensions.hpp"
#include "GUI_App.hpp"
#include "Widgets/StateColor.hpp"
namespace Slic3r { namespace GUI {
+1
View File
@@ -3,6 +3,7 @@
#include "wx/bitmap.h"
#include "wx/dragimag.h"
#include "wx/panel.h"
namespace Slic3r { namespace GUI {
+3
View File
@@ -1,7 +1,10 @@
#include "EncodedFilament.hpp"
#include <nlohmann/json.hpp>
#include "GUI_App.hpp"
using json = nlohmann::json;
namespace Slic3r
{
@@ -1,4 +1,5 @@
#include "ExportPresetBundleDialog.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "GUI_App.hpp"
#include "ConfigWizard.hpp"
#include "I18N.hpp"
@@ -12,7 +13,11 @@
#include <libslic3r/PresetBundle.hpp>
#include <wx/string.h>
#include <miniz.h>
#include <nlohmann/json.hpp>
#include <slic3r/GUI/MsgDialog.hpp>
using json = nlohmann::json;
namespace Slic3r { namespace GUI {
ExportPresetBundleDialog::ExportPresetBundleDialog(
+1
View File
@@ -1,6 +1,7 @@
#include "ExtraRenderers.hpp"
#include "wxExtensions.hpp"
#include "GUI.hpp"
#include "I18N.hpp"
#include "BitmapComboBox.hpp"
#include "Plater.hpp"
#include "Widgets/ComboBox.hpp"
+29 -32
View File
@@ -1,7 +1,9 @@
#include "ExtrusionCalibration.hpp"
#include "GUI_App.hpp"
#include "GUI.hpp"
#include "MsgDialog.hpp"
#include "libslic3r/Preset.hpp"
#include <algorithm>
#include "I18N.hpp"
#include <boost/log/trivial.hpp>
#include <wx/dcgraph.h>
@@ -599,8 +601,10 @@ void ExtrusionCalibration::update_combobox_filaments()
PresetBundle* preset_bundle = wxGetApp().preset_bundle;
if (preset_bundle && obj) {
BOOST_LOG_TRIVIAL(trace) << "system_preset_bundle filament number=" << preset_bundle->filaments.size();
std::string printer_type = obj->printer_type;
std::set<std::string> printer_preset_list;
double nozzle_value = 0.4;
m_comboBox_nozzle_dia->GetValue().ToDouble(&nozzle_value);
std::vector<PresetWithVendorProfile> printer_profiles;
for (auto printer_it = preset_bundle->printers.begin(); printer_it != preset_bundle->printers.end(); printer_it++) {
// only use system printer preset
if (!printer_it->is_system) continue;
@@ -610,49 +614,42 @@ void ExtrusionCalibration::update_combobox_filaments()
ConfigOptionFloats* printer_nozzle_vals = nullptr;
if (printer_nozzle_opt)
printer_nozzle_vals = dynamic_cast<ConfigOptionFloats*>(printer_nozzle_opt);
double nozzle_value = 0.4;
wxString nozzle_value_str = m_comboBox_nozzle_dia->GetValue();
try {
nozzle_value_str.ToDouble(&nozzle_value);
} catch(...) {
;
}
if (!model_id.empty() && model_id.compare(obj->printer_type) == 0
&& printer_nozzle_vals
&& abs(printer_nozzle_vals->get_at(0) - nozzle_value) < 1e-3) {
printer_preset_list.insert(printer_it->name);
printer_profiles.push_back(preset_bundle->printers.get_preset_with_vendor_profile(*printer_it));
BOOST_LOG_TRIVIAL(trace) << "extrusion_cali: printer_model = " << model_id;
} else {
BOOST_LOG_TRIVIAL(error) << "extrusion_cali: printer_model = " << model_id;
}
}
// Unlike the AMS dialogs this one offers every matching preset by full name rather than one
// root preset per alias, so it filters the collection itself instead of calling
// PresetBundle::get_filament_presets_for_machine().
for (auto filament_it = preset_bundle->filaments.begin(); filament_it != preset_bundle->filaments.end(); filament_it++) {
ConfigOption* printer_opt = filament_it->config.option("compatible_printers");
ConfigOptionStrings* printer_strs = dynamic_cast<ConfigOptionStrings*>(printer_opt);
for (auto printer_str : printer_strs->values) {
if (printer_preset_list.find(printer_str) != printer_preset_list.end()) {
user_filaments.push_back(&(*filament_it));
const PresetWithVendorProfile filament = preset_bundle->filaments.get_preset_with_vendor_profile(*filament_it);
if (std::none_of(printer_profiles.begin(), printer_profiles.end(),
[&filament](const PresetWithVendorProfile &printer) { return is_compatible_with_printer(filament, printer); }))
continue;
// set default filament id
filament_index++;
if (filament_it->is_system
&& !ams_filament_id.empty()
&& filament_it->filament_id == ams_filament_id
) {
curr_selection = filament_index;
}
user_filaments.push_back(&(*filament_it));
if (filament_it->name == obj->extrusion_cali_filament_name && !obj->extrusion_cali_filament_name.empty())
{
curr_selection = filament_index;
}
wxString filament_name = wxString::FromUTF8(filament_it->name);
filament_items.Add(filament_name);
break;
}
// set default filament id
filament_index++;
if (filament_it->is_system
&& !ams_filament_id.empty()
&& filament_it->filament_id == ams_filament_id
) {
curr_selection = filament_index;
}
if (filament_it->name == obj->extrusion_cali_filament_name && !obj->extrusion_cali_filament_name.empty())
{
curr_selection = filament_index;
}
filament_items.Add(wxString::FromUTF8(filament_it->name));
}
m_comboBox_filament->Set(filament_items);
m_comboBox_filament->SetSelection(curr_selection);
+127 -127
View File
@@ -11,6 +11,7 @@
#include "libslic3r/PrintConfig.hpp"
#include <algorithm>
#include <cmath>
#include <regex>
#include <utility>
#include <cstdint>
@@ -540,51 +541,95 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true
case coStrings:
case coFloatOrPercent:
case coFloatsOrPercents: {
if ((m_opt.type == coFloatOrPercent || m_opt.type == coFloatsOrPercents) && !str.IsEmpty() && str.Last() != '%')
{
if ((m_opt.type == coFloatOrPercent || m_opt.type == coFloatsOrPercents) && !str.IsEmpty() &&
!(m_opt.nullable && str == m_na_value)) {
bool update_control = false;
wxString numeric_str = str;
double val = 0.;
const char dec_sep = is_decimal_separator_point() ? '.' : ',';
const char dec_sep_alt = dec_sep == '.' ? ',' : '.';
// Replace the first incorrect separator in decimal number.
if (str.Replace(dec_sep_alt, dec_sep, false) != 0)
set_value(str, false);
// Orca: normalize the decimal separator and optional unit before
// detecting the percentage suffix and parsing the numeric part.
update_control |= numeric_str.Replace(dec_sep_alt, dec_sep, false) != 0;
update_control |= numeric_str.Replace(" ", "", true) != 0;
const bool has_literal_unit = numeric_str.EndsWith("mm");
if (has_literal_unit) {
numeric_str.RemoveLast(2);
update_control = true;
}
bool is_percent = !numeric_str.IsEmpty() && numeric_str.Last() == '%';
if (is_percent)
numeric_str.RemoveLast();
// remove space and "mm" substring, if any exists
str.Replace(" ", "", true);
str.Replace("m", "", true);
if (!str.ToDouble(&val))
{
if ((has_literal_unit && is_percent) || !numeric_str.ToDouble(&val) || !std::isfinite(val)) {
if (!check_value) {
m_value.clear();
break;
}
show_error(m_parent, _L("Invalid numeric."));
set_value(double_to_string(val), true);
}
else if (((m_opt.sidetext.rfind("mm/s") != std::string::npos && val > m_opt.max) ||
(m_opt.sidetext.rfind("mm ") != std::string::npos && val > /*1*/m_opt.max_literal)) &&
(m_value.empty() || into_u8(str) != boost::any_cast<std::string>(m_value)))
{
if (!check_value) {
m_value.clear();
break;
numeric_str = double_to_string(std::clamp(0., double(m_opt.min), double(m_opt.max)));
is_percent = false;
update_control = true;
} else {
const bool looks_like_missing_percent = !is_percent && !has_literal_unit &&
((m_opt.sidetext.rfind("mm/s") != std::string::npos && val > m_opt.max) ||
(m_opt.sidetext.rfind("mm ") != std::string::npos && val > m_opt.max_literal));
// Orca: validate explicit percentages and literal values before
// asking whether an otherwise valid literal was meant as a percentage.
const bool out_of_range = !m_opt.is_value_valid(val);
if (out_of_range) {
if (!check_value) {
m_value.clear();
break;
}
show_error(m_parent, _L("Value is out of range."));
val = std::clamp(val, double(m_opt.min), double(m_opt.max));
// Orca: retain the inferred percent unit when clamping a
// suspicious unitless value, so 2000 becomes 100%, not 100 mm.
is_percent |= looks_like_missing_percent;
numeric_str = double_to_string(val);
update_control = true;
} else {
const bool value_changed = m_value.empty() || into_u8(str) != boost::any_cast<std::string>(m_value);
if (looks_like_missing_percent && value_changed) {
if (!check_value) {
m_value.clear();
break;
}
const std::string sidetext = m_opt.sidetext.rfind("mm/s") != std::string::npos ? "mm/s" : "mm";
const wxString stVal = numeric_str;
const wxString msg_text = from_u8((boost::format(_utf8(L("Is it %s%% or %s %s?"))) %
stVal % stVal % sidetext).str());
WarningDialog dialog(m_parent, msg_text, _L("Parameter validation") + ": " + m_opt_id, wxYES | wxNO);
dialog.SetButtonLabel(wxID_YES, stVal + _L("%"));
dialog.SetButtonLabel(wxID_NO, stVal + " " + _L(sidetext));
dialog.GetSizer()->SetSizeHints(&dialog);
dialog.Fit();
dialog.CenterOnParent();
is_percent = dialog.ShowModal() == wxID_YES;
update_control = true;
}
}
const std::string sidetext = m_opt.sidetext.rfind("mm/s") != std::string::npos ? "mm/s" : "mm";
const wxString stVal = double_to_string(val, 2);
const wxString msg_text = from_u8((boost::format(_utf8(L("Is it %s%% or %s %s?\n"
"YES for %s%%, \n"
"NO for %s %s."))) %
stVal % stVal % sidetext % stVal % stVal % sidetext)
.str());
WarningDialog dialog(m_parent, msg_text, _L("Parameter validation") + ": " + m_opt_id, wxYES | wxNO);
if ((val > 100) && dialog.ShowModal() == wxID_YES) {
set_value(from_u8((boost::format("%s%%") % stVal).str()), false /*true*/);
str += "%%";
} else
set_value(stVal, false); // it's no needed but can be helpful, when inputted value contained "," instead of "."
// Orca: also enforce the literal limit after clamping an explicit mm input.
if (!is_percent && m_opt.sidetext.rfind("mm ") != std::string::npos && val > m_opt.max_literal) {
if (!check_value) {
m_value.clear();
break;
}
if (!out_of_range)
show_error(m_parent, _L("Value is out of range."));
val = m_opt.max_literal;
numeric_str = double_to_string(val);
update_control = true;
}
}
if (update_control) {
str = numeric_str + (is_percent ? "%" : "");
set_value(str, true);
}
}
if (m_opt.opt_key == "thumbnails") {
@@ -941,7 +986,11 @@ void TextCtrl::BUILD() {
temp->SetToolTip(get_tooltip_text(text_value));
if (!m_opt.multiline) {
text_ctrl->Bind(wxEVT_TEXT_ENTER, ([this, temp](wxEvent &e)
text_ctrl->Bind(wxEVT_TEXT_ENTER, ([
#if !defined(__WXGTK__)
temp,
#endif // __WXGTK__
this](wxEvent &e)
{
#if !defined(__WXGTK__)
e.Skip();
@@ -973,7 +1022,11 @@ void TextCtrl::BUILD() {
temp->GetToolTip()->Enable(flag);
}), text_ctrl->GetId());
temp->Bind(wxEVT_KILL_FOCUS, ([this, temp](wxEvent &e)
temp->Bind(wxEVT_KILL_FOCUS, ([
#if !defined(__WXGTK__)
temp,
#endif // __WXGTK__
this](wxEvent &e)
{
e.Skip();
#if !defined(__WXGTK__)
@@ -1324,7 +1377,7 @@ void SpinCtrl::BUILD() {
bEnterPressed = true;
}), temp->GetId());
temp->GetTextCtrl()->Bind(wxEVT_TEXT, ([this, temp](wxCommandEvent e)
temp->GetTextCtrl()->Bind(wxEVT_TEXT, ([this](wxCommandEvent e)
{
// # On OSX / Cocoa, SpinInput::GetValue() doesn't return the new value
// # when it was changed from the text control, so the on_change callback
@@ -2146,6 +2199,7 @@ void PrinterAgentChoice::msw_rescale()
void PluginField::BUILD()
{
auto* panel = new wxPanel(m_parent, wxID_ANY);
panel->SetBackgroundColour(*wxWHITE);
wxGetApp().UpdateDarkUI(panel);
window = panel;
@@ -2188,9 +2242,8 @@ void PluginField::rebuild_ui()
m_rows.clear();
m_standalone_add_btn = nullptr;
if (m_values.empty()) {
add_empty_state_row();
} else {
add_empty_state_row();
if (!m_values.empty()) {
for (size_t i = 0; i < m_values.size(); ++i)
add_plugin_row(display_name_for_value(m_values[i]), i == m_values.size() - 1);
}
@@ -2207,94 +2260,43 @@ void PluginField::rebuild_ui()
void PluginField::add_empty_state_row()
{
const auto button_size = wxSize(def_width_thinner() * m_em_unit, -1);
auto row_sizer = new wxBoxSizer(wxHORIZONTAL);
wxTextCtrl* display = new wxTextCtrl(window, wxID_ANY, _L("No plugin selected"),
wxDefaultPosition, wxSize(def_width_wider() * m_em_unit, wxDefaultCoord),
wxTE_READONLY);
display->SetEditable(false);
wxGetApp().UpdateDarkUI(display);
display->SetToolTip(_L("No plugin selected"));
auto add_btn = new ScalableButton(window, wxID_ANY, "param_add", wxEmptyString,
button_size, wxDefaultPosition, wxBU_EXACTFIT | wxNO_BORDER, true, 16);
wxGetApp().UpdateDarkUI(add_btn);
add_btn->SetToolTip(_L("Add plugin"));
auto add_btn = new Button(window, _L("Add plugin"), "param_add", 0, 16);
add_btn->SetStyle(ButtonStyle::Regular, ButtonType::Parameter);
add_btn->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { on_add_clicked(); });
row_sizer->Add(display, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
row_sizer->Add(add_btn, 0, wxALIGN_CENTER_VERTICAL);
m_main_sizer->Add(row_sizer, 0, wxEXPAND);
PluginRow row;
row.display = display;
row.add_btn = add_btn;
row.sizer = row_sizer;
m_rows.push_back(row);
m_main_sizer->Add(add_btn, 0, wxEXPAND | wxBOTTOM, window->FromDIP(SidebarProps::ContentMarginV()));
m_standalone_add_btn = add_btn;
}
void PluginField::add_plugin_row(const wxString& value, bool is_last)
{
const auto button_size = wxSize(def_width_thinner() * m_em_unit, -1);
auto row_sizer = new wxBoxSizer(wxHORIZONTAL);
ScalableButton* select_btn = new ScalableButton(window, wxID_ANY, "search", wxEmptyString,
button_size, wxDefaultPosition, wxBU_EXACTFIT | wxNO_BORDER, true, 16);
wxGetApp().UpdateDarkUI(select_btn);
select_btn->SetToolTip(_L("Select plugin"));
wxTextCtrl* display = new wxTextCtrl(window, wxID_ANY, value,
wxDefaultPosition, wxSize(def_width_wider() * m_em_unit, wxDefaultCoord),
wxTE_READONLY);
display->SetEditable(false);
wxGetApp().UpdateDarkUI(display);
ComboBox* display = new ComboBox(window, wxID_ANY, value, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY | CB_NO_DROP_ICON);
display->SetIcon("edit");
display->SetToolTip(get_tooltip_text(value));
ScalableButton* remove_btn = nullptr;
if (!m_opt.readonly) {
remove_btn = new ScalableButton(window, wxID_ANY, "cross", wxEmptyString,
button_size, wxDefaultPosition, wxBU_EXACTFIT | wxNO_BORDER, true, 16);
wxGetApp().UpdateDarkUI(remove_btn);
remove_btn->SetToolTip(_L("Remove plugin"));
}
ScalableButton* remove_btn = new ScalableButton(window, wxID_ANY, "cross", wxEmptyString,
wxDefaultSize, wxDefaultPosition, wxBU_EXACTFIT | wxNO_BORDER, true, 16);
remove_btn->SetToolTip(_L("Remove plugin"));
ScalableButton* add_btn = nullptr;
if (is_last && !m_opt.readonly) {
add_btn = new ScalableButton(window, wxID_ANY, "param_add", wxEmptyString,
button_size, wxDefaultPosition, wxBU_EXACTFIT | wxNO_BORDER, true, 16);
wxGetApp().UpdateDarkUI(add_btn);
add_btn->SetToolTip(_L("Add plugin"));
add_btn->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { on_add_clicked(); });
}
if (m_opt.readonly)
remove_btn->Disable();
const size_t row_index = m_rows.size();
select_btn->Bind(wxEVT_BUTTON, [this, row_index](wxCommandEvent&) { on_select_clicked(row_index); });
if (remove_btn)
remove_btn->Bind(wxEVT_BUTTON, [this, row_index](wxCommandEvent&) { on_remove_clicked(row_index); });
display->Bind(wxEVT_LEFT_DOWN, [this, row_index](wxMouseEvent& ) { on_select_clicked(row_index); });
remove_btn->Bind(wxEVT_BUTTON, [this, row_index](wxCommandEvent&) { on_remove_clicked(row_index); });
row_sizer->Add(select_btn, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
row_sizer->Add(display, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
if (remove_btn)
row_sizer->Add(remove_btn, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 4);
if (add_btn)
row_sizer->Add(add_btn, 0, wxALIGN_CENTER_VERTICAL);
else if (!m_opt.readonly) {
// Reserve space equal to the add button so all rows align.
row_sizer->Add(button_size.GetWidth(), button_size.GetHeight(), 0, wxALIGN_CENTER_VERTICAL);
}
row_sizer->Add(display , 1, wxALIGN_CENTER_VERTICAL);
row_sizer->Add(remove_btn, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, window->FromDIP(SidebarProps::ElementSpacing()));
const int bottom_gap = is_last ? 0 : 4;
m_main_sizer->Add(row_sizer, 0, wxEXPAND | (bottom_gap > 0 ? wxBOTTOM : 0), bottom_gap);
m_main_sizer->Add(row_sizer, 0, wxEXPAND | wxBOTTOM, window->FromDIP(is_last ? SidebarProps::ContentMarginV() : 4));
PluginRow row;
row.select_btn = select_btn;
row.display = display;
row.remove_btn = remove_btn;
row.add_btn = add_btn;
row.sizer = row_sizer;
m_rows.push_back(row);
}
@@ -2346,9 +2348,9 @@ void PluginField::on_add_clicked()
m_values.push_back(selected);
m_value = m_values;
rebuild_ui();
on_change_field();
// Defer: don't destroy the clicked button from inside its own handler.
if(window)
window->CallAfter([this]() {rebuild_ui(); on_change_field();});
}
void PluginField::on_remove_clicked(size_t index)
@@ -2359,8 +2361,9 @@ void PluginField::on_remove_clicked(size_t index)
m_values.erase(m_values.begin() + index);
m_value = m_values;
rebuild_ui();
on_change_field();
// Defer: don't destroy the clicked button from inside its own handler.
if(window)
window->CallAfter([this]() {rebuild_ui(); on_change_field();});
}
wxString PluginField::get_row_value(size_t index) const
@@ -2374,7 +2377,7 @@ void PluginField::set_row_value(size_t index, const wxString& value)
{
if (index >= m_rows.size() || !m_rows[index].display)
return;
m_rows[index].display->ChangeValue(value);
m_rows[index].display->SetValue(value);
m_rows[index].display->SetToolTip(get_tooltip_text(value));
}
@@ -2417,14 +2420,10 @@ boost::any& PluginField::get_value()
void PluginField::enable()
{
for (auto& row : m_rows) {
if (row.select_btn)
row.select_btn->Enable();
if (row.display)
row.display->Enable();
if (row.remove_btn)
row.remove_btn->Enable();
if (row.add_btn)
row.add_btn->Enable();
}
if (m_standalone_add_btn)
m_standalone_add_btn->Enable();
@@ -2433,14 +2432,10 @@ void PluginField::enable()
void PluginField::disable()
{
for (auto& row : m_rows) {
if (row.select_btn)
row.select_btn->Disable();
if (row.display)
row.display->Disable();
if (row.remove_btn)
row.remove_btn->Disable();
if (row.add_btn)
row.add_btn->Disable();
}
if (m_standalone_add_btn)
m_standalone_add_btn->Disable();
@@ -2597,7 +2592,11 @@ void ColourPicker::BUILD()
// // recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(temp);
temp->Bind(wxEVT_COLOURPICKER_CHANGED, ([this,temp](wxCommandEvent e) {
temp->Bind(wxEVT_COLOURPICKER_CHANGED, ([
#ifdef __WXMSW__
temp,
#endif
this](wxCommandEvent e) {
#ifdef __WXMSW__
draw_bmp_btn(temp, temp->GetColour());
#endif
@@ -2699,7 +2698,8 @@ void ColourPicker::set_value(const boost::any& value, bool change_event)
auto field = dynamic_cast<wxColourPickerCtrl*>(window);
#ifdef __WXMSW__
wxColour clr = (clr_str.IsEmpty() || !clr.IsOk()) ? wxTransparentColour : clr_str;
const wxColour parsed_clr(clr_str);
wxColour clr = (clr_str.IsEmpty() || !parsed_clr.IsOk()) ? wxTransparentColour : parsed_clr;
field->SetColour(clr);
draw_bmp_btn(field, clr);
#else
@@ -2850,11 +2850,11 @@ void PointCtrl::BUILD()
//temp->Add(static_text_y, 0, wxALIGN_CENTER_VERTICAL, 0);
temp->Add(y_input);
x_textctrl->Bind(wxEVT_TEXT_ENTER, ([this](wxCommandEvent e) { propagate_value(x_textctrl); }), x_textctrl->GetId());
y_textctrl->Bind(wxEVT_TEXT_ENTER, ([this](wxCommandEvent e) { propagate_value(y_textctrl); }), y_textctrl->GetId());
x_textctrl->Bind(wxEVT_TEXT_ENTER, ([this](wxCommandEvent e) { propagate_input_value(x_textctrl); }), x_textctrl->GetId());
y_textctrl->Bind(wxEVT_TEXT_ENTER, ([this](wxCommandEvent e) { propagate_input_value(y_textctrl); }), y_textctrl->GetId());
x_textctrl->Bind(wxEVT_KILL_FOCUS, ([this](wxEvent& e) { e.Skip(); propagate_value(x_textctrl); }), x_textctrl->GetId());
y_textctrl->Bind(wxEVT_KILL_FOCUS, ([this](wxEvent& e) { e.Skip(); propagate_value(y_textctrl); }), y_textctrl->GetId());
x_textctrl->Bind(wxEVT_KILL_FOCUS, ([this](wxEvent& e) { e.Skip(); propagate_input_value(x_textctrl); }), x_textctrl->GetId());
y_textctrl->Bind(wxEVT_KILL_FOCUS, ([this](wxEvent& e) { e.Skip(); propagate_input_value(y_textctrl); }), y_textctrl->GetId());
// // recast as a wxWindow to fit the calling convention
window = dynamic_cast<wxWindow*>(x_input);
@@ -2903,7 +2903,7 @@ bool PointCtrl::value_was_changed(wxTextCtrl* win)
return boost::any_cast<Vec2d>(m_value) != boost::any_cast<Vec2d>(val);
}
void PointCtrl::propagate_value(wxTextCtrl* win)
void PointCtrl::propagate_input_value(wxTextCtrl* win)
{
if (win->GetValue().empty())
on_kill_focus();
+8 -7
View File
@@ -25,6 +25,7 @@
#include "wxExtensions.hpp"
#include "Widgets/SpinInput.hpp"
#include "Widgets/TextInput.hpp"
#include "Widgets/ComboBox.hpp"
#ifdef __WXMSW__
#define wxMSW true
@@ -385,7 +386,7 @@ public:
wxWindow* window{ nullptr };
void BUILD() override;
/// Propagate value from field to the OptionGroupe and Config after kill_focus/ENTER
void propagate_value() ;
void propagate_value() override;
void set_value(const std::string& value, bool change_event = false) {
m_disable_change_event = !change_event;
@@ -440,7 +441,7 @@ public:
wxWindow* window{ nullptr };
void BUILD() override;
// Propagate value from field to the OptionGroupe and Config after kill_focus/ENTER
void propagate_value();
void propagate_value() override;
/* Under OSX: wxBitmapComboBox->GetWindowStyle() returns some weard value,
* so let use a flag, which has TRUE value for a control without wxCB_READONLY style
@@ -532,10 +533,8 @@ public:
private:
struct PluginRow {
ScalableButton* select_btn { nullptr };
wxTextCtrl* display { nullptr };
ComboBox* display { nullptr };
ScalableButton* remove_btn { nullptr };
ScalableButton* add_btn { nullptr };
wxBoxSizer* sizer { nullptr };
};
@@ -553,7 +552,7 @@ private:
wxBoxSizer* m_main_sizer { nullptr };
std::vector<PluginRow> m_rows;
std::vector<std::string> m_values;
ScalableButton* m_standalone_add_btn { nullptr };
Button* m_standalone_add_btn { nullptr };
std::function<std::string()> m_selector;
};
@@ -628,8 +627,10 @@ private:
void on_button_click(wxCommandEvent &WXUNUSED(ev));
void save_colors_to_config();
private:
#if !defined(__linux__) && !defined(__LINUX__)
wxColourData* m_clrData{nullptr};
wxColourPickerWidget* m_picker_widget{nullptr};
#endif
};
class PointCtrl : public Field {
@@ -649,7 +650,7 @@ public:
void BUILD() override;
bool value_was_changed(wxTextCtrl* win);
// Propagate value from field to the OptionGroupe and Config after kill_focus/ENTER
void propagate_value(wxTextCtrl* win);
void propagate_input_value(wxTextCtrl* win);
void set_value(const Vec2d& value, bool change_event = false);
void set_value(const boost::any& value, bool change_event = false) override;
boost::any& get_value() override;
+608
View File
@@ -1,13 +1,66 @@
#include <wx/dcmemory.h>
#include <wx/dcgraph.h>
#include <wx/graphics.h>
#include <wx/settings.h>
#include <wx/window.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <numeric>
#include <string>
#include <tuple>
#include "EncodedFilament.hpp"
#include "FilamentBitmapUtils.hpp"
#include "GUI_App.hpp"
#include "GuiColor.hpp"
#include "I18N.hpp"
#include "Widgets/Label.hpp"
#include "Widgets/StateColor.hpp"
#include "libslic3r/FilamentMixer.hpp"
#include "libslic3r/PrintConfig.hpp"
namespace Slic3r { namespace GUI {
// Barycentric utilities for a ternary (triangle) ratio picker.
double tri_signed_area2(TriPoint a, TriPoint b, TriPoint c)
{
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
}
bool tri_contains(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2)
{
double total = tri_signed_area2(v0, v1, v2);
if (std::abs(total) < 1e-9) return false;
double s0 = tri_signed_area2(p, v1, v2) / total;
double s1 = tri_signed_area2(v0, p, v2) / total;
double s2 = 1.0 - s0 - s1;
return s0 >= -0.001 && s1 >= -0.001 && s2 >= -0.001;
}
void tri_barycentric(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2,
double& w0, double& w1, double& w2)
{
double total = std::abs(tri_signed_area2(v0, v1, v2));
if (total < 1e-9) { w0 = w1 = w2 = 1.0 / 3.0; return; }
w0 = std::abs(tri_signed_area2(p, v1, v2)) / total;
w1 = std::abs(tri_signed_area2(v0, p, v2)) / total;
w2 = 1.0 - w0 - w1;
w0 = std::clamp(w0, 0.0, 1.0);
w1 = std::clamp(w1, 0.0, 1.0);
w2 = std::clamp(w2, 0.0, 1.0);
double s = w0 + w1 + w2;
if (s > 0) { w0 /= s; w1 /= s; w2 /= s; }
}
TriPoint tri_clamp(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2)
{
double w0, w1, w2;
tri_barycentric(p, v0, v1, v2, w0, w1, w2);
return {w0 * v0.x + w1 * v1.x + w2 * v2.x,
w0 * v0.y + w1 * v1.y + w2 * v2.y};
}
void fill_gradient_rect_east(wxDC& dc, const wxRect& rect, const wxColour& from, const wxColour& to)
{
if (rect.width <= 0 || rect.height <= 0) return;
@@ -28,6 +81,113 @@ void fill_gradient_rect_east(wxDC& dc, const wxRect& rect, const wxColour& from,
}
}
static std::string to_hex(const wxColour& c)
{
return wxString::Format("#%02X%02X%02X", c.Red(), c.Green(), c.Blue()).ToStdString();
}
wxColour blend_n_colors(const std::vector<wxColour>& cols, const std::vector<double>& weights)
{
const size_t n = std::min(cols.size(), weights.size());
std::vector<std::string> hex_colors;
std::vector<int> int_weights;
hex_colors.reserve(n);
int_weights.reserve(n);
for (size_t i = 0; i < n; ++i) {
hex_colors.push_back(to_hex(cols[i]));
// Scale double weights (e.g. 0.5) to int (5000) for blend_color_multi;
// only relative magnitude matters.
int_weights.push_back(static_cast<int>(std::lround(weights[i] * 10000.0)));
}
wxColour blended(Slic3r::blend_color_multi(hex_colors, int_weights));
return blended.IsOk() ? blended : wxColour(128, 128, 128);
}
std::vector<wxColour> sample_gradient_ramp(const wxColour& first,
const wxColour& second,
const Slic3r::GradientCurve& curve,
int steps)
{
std::vector<wxColour> ramp;
if (steps <= 0 || curve.points.size() < 2) return ramp;
ramp.reserve(steps);
for (int i = 0; i < steps; ++i) {
const double t = (steps > 1) ? (i + 0.5) / steps : 0.5;
const double r1 = Slic3r::sample_gradient_curve(curve, t);
ramp.push_back(blend_n_colors({first, second}, {r1, 1.0 - r1}));
}
return ramp;
}
// Resolve the curve a gradient slot is sampled with, mirroring the slicer's fallback in
// ToolOrdering: a custom curve wins, otherwise a straight line between gradient_range's
// endpoints, otherwise the 0.10 -> 0.90 default.
Slic3r::GradientCurve mixed_gradient_curve(const Slic3r::DynamicPrintConfig& cfg, size_t slot)
{
const auto* curve_opt = cfg.option<ConfigOptionStrings>("filament_mixed_gradient_curve");
if (curve_opt && slot < curve_opt->values.size() && !curve_opt->values[slot].empty()) {
Slic3r::GradientCurve custom = Slic3r::parse_gradient_curve(curve_opt->values[slot]);
if (custom.points.size() >= 2) return custom;
}
double start = kGradientMinRatio, end = kGradientMaxRatio;
const auto* range_opt = cfg.option<ConfigOptionStrings>("filament_mixed_gradient_range");
if (range_opt && slot < range_opt->values.size() && !range_opt->values[slot].empty()) {
CNumericLocalesSetter c_locale_setter;
float v0 = 0, v1 = 0;
if (std::sscanf(range_opt->values[slot].c_str(), "%f,%f", &v0, &v1) == 2 &&
v0 > 0 && v0 < 1.0 && v1 > 0 && v1 < 1.0) {
start = v0;
end = v1;
}
}
Slic3r::GradientCurve curve;
curve.points = {{0.0, start, NAN, NAN}, {1.0, end, NAN, NAN}};
return curve;
}
std::vector<wxColour> mixed_gradient_ramp(const Slic3r::DynamicPrintConfig& cfg, size_t slot, int steps)
{
const auto* is_mixed_opt = cfg.option<ConfigOptionBools>("filament_is_mixed");
const auto* grad_opt = cfg.option<ConfigOptionBools>("filament_mixed_gradient");
const auto* comp_opt = cfg.option<ConfigOptionStrings>("filament_mixed_components");
const auto* colour_opt = cfg.option<ConfigOptionStrings>("filament_colour");
if (!is_mixed_opt || !grad_opt || !comp_opt || !colour_opt) return {};
if (slot >= is_mixed_opt->values.size() || !is_mixed_opt->values[slot]) return {};
if (slot >= grad_opt->values.size() || !grad_opt->values[slot]) return {};
if (slot >= comp_opt->values.size()) return {};
// Only two-component slots fade; anything else stays on the plain blended swatch.
const auto comp_ids = Slic3r::parse_mixed_components(comp_opt->values[slot]);
if (comp_ids.size() != 2) return {};
auto component_colour = [&](unsigned int id) {
wxColour c = (id >= 1 && id <= colour_opt->values.size()) ? wxColour(colour_opt->values[id - 1]) : wxColour();
return c.IsOk() ? c : wxColour("#D9D9D9");
};
// Both gradient_range and the curve express the *first* component's ratio over Z, so
// the components stay in config order and the curve alone decides which end is which.
return sample_gradient_ramp(component_colour(comp_ids[0]), component_colour(comp_ids[1]),
mixed_gradient_curve(cfg, slot), steps);
}
void fill_gradient_ramp_rect(wxDC& dc, const wxRect& rect, const std::vector<wxColour>& ramp)
{
if (rect.width <= 0 || rect.height <= 0 || ramp.empty()) return;
dc.SetPen(*wxTRANSPARENT_PEN);
for (int y = 0; y < rect.height; ++y) {
// Row 0 is the top of the rect and so takes the ramp's last entry, the model's top.
// Mapping over height - 1 puts both ends of the ramp on screen even in a short swatch.
const double t = (rect.height > 1) ? (double) (rect.height - 1 - y) / (rect.height - 1) : 0.5;
dc.SetBrush(wxBrush(ramp[static_cast<size_t>(t * (ramp.size() - 1) + 0.5)]));
dc.DrawRectangle(rect.x, rect.y + y, rect.width, 1);
}
}
// Helper struct to hold bitmap and DC
struct BitmapDC {
wxBitmap bitmap;
@@ -47,6 +207,19 @@ static BitmapDC init_bitmap_dc(const wxSize& size) {
return BitmapDC(size);
}
wxBitmap create_gradient_ramp_bitmap(const std::vector<wxColour>& ramp, const wxSize& size)
{
if (ramp.empty()) return wxNullBitmap;
BitmapDC bdc = init_bitmap_dc(size);
if (!bdc.dc.IsOk()) return wxNullBitmap;
fill_gradient_ramp_rect(bdc.dc, wxRect(0, 0, size.GetWidth(), size.GetHeight()), ramp);
bdc.dc.SelectObject(wxNullBitmap);
return bdc.bitmap;
}
// Check if a color is transparent (alpha == 0)
static bool is_transparent_color(const wxColour& color) {
return color.Alpha() == 0;
@@ -265,4 +438,439 @@ wxBitmap create_filament_bitmap(const std::vector<wxColour>& colors, const wxSiz
}
}
void recompute_mixed_slot_colors(std::vector<wxColour>& colors,
const Slic3r::DynamicPrintConfig& cfg)
{
const auto* is_mixed_opt = cfg.option<ConfigOptionBools>("filament_is_mixed");
const auto* comp_opt = cfg.option<ConfigOptionStrings>("filament_mixed_components");
const auto* ratio_opt = cfg.option<ConfigOptionStrings>("filament_mixed_sublayer_ratios");
const auto* grad_opt = cfg.option<ConfigOptionBools>("filament_mixed_gradient");
if (!is_mixed_opt || !comp_opt) return;
const size_t n = is_mixed_opt->values.size();
if (colors.size() < n) colors.resize(n);
const auto* colour_opt = cfg.option<ConfigOptionStrings>("filament_colour");
const auto kFallback = wxColour(128, 128, 128, 255);
for (size_t i = 0; i < n; ++i) {
if (!is_mixed_opt->values[i]) continue;
if (i >= comp_opt->values.size()) { colors[i] = kFallback; continue; }
auto comp_ids = Slic3r::parse_mixed_components(comp_opt->values[i]);
if (comp_ids.empty()) { colors[i] = kFallback; continue; }
bool is_gradient = grad_opt && i < grad_opt->values.size() && grad_opt->values[i];
std::vector<unsigned int> use_ids = comp_ids;
std::vector<int> weights;
if (is_gradient && comp_ids.size() >= 2) {
use_ids = { comp_ids.front(), comp_ids.back() };
weights = { 5000, 5000 };
} else {
auto ratios_d = Slic3r::parse_mixed_ratios(
(ratio_opt && i < ratio_opt->values.size()) ? ratio_opt->values[i] : std::string{},
comp_ids.size());
weights.reserve(comp_ids.size());
for (double r : ratios_d)
weights.push_back(static_cast<int>(std::lround(r * 10000.0)));
}
std::vector<std::string> hex_colors;
hex_colors.reserve(use_ids.size());
bool any_invalid = false;
for (unsigned int id : use_ids) {
if (id == 0 || id > colors.size()) { any_invalid = true; break; }
wxColour c = colors[id - 1];
if (c.IsOk() && (c.Red() > 0 || c.Green() > 0 || c.Blue() > 0)) {
hex_colors.push_back(to_hex(c));
} else if (colour_opt && (id - 1) < colour_opt->values.size()) {
hex_colors.push_back(colour_opt->values[id - 1]);
} else {
any_invalid = true; break;
}
}
if (any_invalid) { colors[i] = kFallback; continue; }
std::string hex = Slic3r::blend_color_multi(hex_colors, weights);
wxColour blended(hex);
if (!blended.IsOk()) blended = kFallback;
colors[i] = wxColour(blended.Red(), blended.Green(), blended.Blue(), 255);
}
}
namespace {
// Layout ratios of the gradient plot rect, copied from GradientCurveEditor so the read-only
// preview and the interactive editor stay pixel-identical. Plot rect is square 1:1; the
// right/bottom margins host the axis arrows and labels.
constexpr double kPlotLeftRatio = 0.0316;
constexpr double kPlotRightRatio = 0.6766;
constexpr double kPlotTopRatio = 0.1529;
constexpr double kPlotBottomRatio = 0.8474;
constexpr int kGridDivisions = 9; // 10 grid lines including the outer borders.
constexpr int kStrokeAxis = 2; // axis line width (px, no DPI scaling)
constexpr int kAxisArrowHalf = 5; // half-base of the axis arrow triangle (DIP)
constexpr int kAxisArrowLen = 10; // length of the axis arrow triangle (DIP)
constexpr int kPointRadius = 4; // anchor outer radius (DIP)
constexpr float kBgSimilarThreshold = 15.0f;
constexpr int kOutlineExtraDip = 2;
constexpr double kTriangleMarginDip = 20.0;
// Quadratic blend that never goes out of gamut, matching MixedFilamentDialog::blend_colors.
wxColour lerp_blend(const wxColour& a, const wxColour& b, double ratio_a)
{
unsigned char r, g, bl;
Slic3r::filament_mixer_lerp(a.Red(), a.Green(), a.Blue(),
b.Red(), b.Green(), b.Blue(),
static_cast<float>(1.0 - ratio_a), &r, &g, &bl);
return wxColour(r, g, bl);
}
// DIP conversion for these free functions: unlike the wxWindow member FromDIP, it needs the
// window parameter explicitly; nullptr picks the app's default DPI like the Publish dialog does.
int dip_px(int v) { return wxWindow::FromDIP(v, nullptr); }
} // namespace
wxRect mixed_gradient_plot_rect(const wxSize& sz)
{
const int x = static_cast<int>(std::lround(sz.x * kPlotLeftRatio));
const int y = static_cast<int>(std::lround(sz.y * kPlotTopRatio));
const int x2 = static_cast<int>(std::lround(sz.x * kPlotRightRatio));
const int y2 = static_cast<int>(std::lround(sz.y * kPlotBottomRatio));
const int side = std::max(1, std::min(x2 - x, y2 - y));
return wxRect(x, y, side, side);
}
void draw_mixed_gradient_plot(wxDC& raw_dc, const wxSize& canvas,
const std::vector<MixedGradientCurve>& curves,
const std::vector<wxPoint2DDouble>& anchors,
const MixedGradientTheme& theme)
{
// Draw into an internal opaque buffer so wxGCDC text/curves anti-alias against a solid
// background (never a transparent one), then blit the finished image onto the caller's
// buffered paint DC. wxGCDC cannot wrap a generic wxDC&, so the buffer is always a
// wxMemoryDC -- the one type wxGCDC accepts on every platform.
if (canvas.x <= 0 || canvas.y <= 0)
return;
const wxRect rc = mixed_gradient_plot_rect(canvas);
if (rc.width <= 0 || rc.height <= 0)
return;
wxBitmap buf(canvas);
wxMemoryDC memdc(buf);
memdc.SetBackground(wxBrush(theme.background));
memdc.Clear();
wxGCDC dc(memdc);
wxGraphicsContext* gc = dc.GetGraphicsContext();
// 10x10 light grid (10 lines including outer borders, 9 equal divisions).
dc.SetPen(wxPen(theme.grid, 1));
for (int i = 0; i <= kGridDivisions; ++i) {
const int x = rc.x + rc.width * i / kGridDivisions;
const int y = rc.y + rc.height * i / kGridDivisions;
dc.DrawLine(x, rc.y, x, rc.y + rc.height);
dc.DrawLine(rc.x, y, rc.x + rc.width, y);
}
// Set the label font first so text width measurements drive arrow / label placement.
wxFont label_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
label_font.SetPointSize(std::max(7, label_font.GetPointSize() - 1));
dc.SetFont(label_font);
const wxString axis_y_title = _L("Material Ratio");
const wxString axis_x_title = _L("Model Height");
const wxString pct_text = wxT("100%");
const wxSize x_title_sz = dc.GetTextExtent(axis_x_title);
const wxSize y_title_sz = dc.GetTextExtent(axis_y_title);
wxFont strong_font = label_font;
strong_font.SetWeight(wxFONTWEIGHT_SEMIBOLD);
dc.SetFont(strong_font);
const wxSize pct_text_sz = dc.GetTextExtent(pct_text);
dc.SetFont(label_font);
// Axes (grey 700) with filled triangle arrows. Y-axis extends above the plot top to the
// canvas top edge; X-axis extends past the plot right toward the canvas right edge.
const int arrow_half = dip_px(kAxisArrowHalf);
const int arrow_len = dip_px(kAxisArrowLen);
dc.SetPen(wxPen(theme.axis, kStrokeAxis));
dc.SetBrush(wxBrush(theme.axis));
const int y_axis_x = rc.x;
const int y_title_pct_gap = dip_px(1);
const int y_title_bottom_pad = dip_px(2);
const int y_title_y = std::max(0, rc.y - y_title_sz.y - y_title_pct_gap - pct_text_sz.y - y_title_bottom_pad);
const int y_arrow_tip_y = y_title_y;
const int y_arrow_ty = y_arrow_tip_y + arrow_len;
dc.DrawLine(y_axis_x, y_arrow_ty, y_axis_x, rc.y + rc.height);
{
wxPoint tri[3] = {
wxPoint(y_axis_x, y_arrow_tip_y),
wxPoint(y_axis_x - arrow_half, y_arrow_ty),
wxPoint(y_axis_x + arrow_half, y_arrow_ty),
};
dc.DrawPolygon(3, tri);
}
const int x_axis_y = rc.y + rc.height;
const int x_label_gap = dip_px(4);
const int x_edge_pad = dip_px(6);
const int x_arrow_ideal = rc.x + rc.width + dip_px(10);
const int x_arrow_max = canvas.x - x_title_sz.x - x_label_gap - x_edge_pad - arrow_len;
const int x_arrow_tx = std::max(rc.x + rc.width + arrow_len, std::min(x_arrow_ideal, x_arrow_max));
const int x_arrow_tip_x = x_arrow_tx + arrow_len;
const int x_title_x = x_arrow_tip_x + x_label_gap;
dc.DrawLine(rc.x, x_axis_y, x_arrow_tx, x_axis_y);
{
wxPoint tri[3] = {
wxPoint(x_arrow_tip_x, x_axis_y),
wxPoint(x_arrow_tx, x_axis_y - arrow_half),
wxPoint(x_arrow_tx, x_axis_y + arrow_half),
};
dc.DrawPolygon(3, tri);
}
// Labels: "Material Ratio" and the leading "100%" share the same left x; the trailing
// "Model Height" follows the X-axis arrow tip (already clamped to make room).
const int label_left_x = y_axis_x + dip_px(10);
dc.SetTextForeground(theme.label);
dc.DrawText(axis_y_title, label_left_x, y_title_y);
dc.SetFont(strong_font);
dc.SetTextForeground(theme.label_strong);
dc.DrawText(pct_text, label_left_x, y_title_y + y_title_sz.y + y_title_pct_gap);
dc.DrawText(pct_text, rc.x + rc.width - pct_text_sz.x, x_axis_y);
dc.SetFont(label_font);
dc.SetTextForeground(theme.label);
dc.DrawText(axis_x_title, x_title_x, x_axis_y - x_title_sz.y / 2);
if (!gc)
return;
// Outline only when the curve colour is perceptually close to the background; otherwise the
// plain filament colour reads fine and the extra stroke would look heavy.
auto needs_outline = [&](const wxColour& c) {
return calc_color_distance(c, theme.background) < kBgSimilarThreshold;
};
// Only the geometry goes through the graphics context: dc.DrawLines() takes integer wxPoint
// and would quantize the curve back to whole pixels. The pen is still set on the dc, which
// forwards it here while keeping its own cached state in sync for later dc drawing.
auto draw_polyline = [&](const MixedGradientCurve& curve) {
if (curve.points.size() < 2)
return;
dc.SetPen(wxPen(curve.colour, dip_px(curve.stroke_dip)));
gc->StrokeLines(curve.points.size(), curve.points.data());
};
for (const MixedGradientCurve& curve : curves) {
if (needs_outline(curve.colour))
draw_polyline({curve.points, theme.outline, curve.stroke_dip + kOutlineExtraDip});
draw_polyline(curve);
}
// Control points: hollow circle with axis-colour border, theme-aware fill, drawn with a
// sub-pixel centre so the ring stays centred on the curve.
if (!anchors.empty()) {
const double r = dip_px(kPointRadius);
dc.SetPen(wxPen(theme.axis, 1));
dc.SetBrush(wxBrush(theme.point_fill));
for (const wxPoint2DDouble& p : anchors)
gc->DrawEllipse(p.m_x - r, p.m_y - r, r * 2, r * 2);
}
memdc.SelectObject(wxNullBitmap);
raw_dc.DrawBitmap(buf, 0, 0);
}
void draw_mixed_ratio_blend_bar(wxDC& dc, const wxRect& rect, const wxColour& first,
const wxColour& second, double second_fraction)
{
if (rect.width <= 0 || rect.height <= 0)
return;
for (int x = 0; x < rect.width; ++x) {
const double t = rect.width > 1 ? double(x) / rect.width : 0.0;
const wxColour c = lerp_blend(first, second, 1.0 - t);
dc.SetPen(wxPen(c));
dc.DrawLine(rect.x + x, rect.y, rect.x + x, rect.y + rect.height);
}
// Fixed in both themes, like the triangle picker's drag handle: the divider is drawn over
// blended filament colour, so it has to keep its contrast against data rather than chrome.
const int div_x = rect.x + static_cast<int>(second_fraction * rect.width);
dc.SetPen(wxPen(wxColour(80, 80, 80), dip_px(4)));
dc.DrawLine(div_x, rect.y, div_x, rect.y + rect.height);
dc.SetPen(wxPen(*wxWHITE, dip_px(2)));
dc.DrawLine(div_x, rect.y, div_x, rect.y + rect.height);
}
void draw_mixed_ratio_segments(wxDC& dc, const wxRect& rect, const std::vector<wxColour>& colours,
const std::vector<double>& shares)
{
const size_t n = std::min(colours.size(), shares.size());
if (n == 0 || rect.width <= 0 || rect.height <= 0)
return;
std::vector<double> norm = shares;
double total = 0.0;
for (double s : norm)
total += s;
if (total <= 0.0) {
norm.assign(n, 1.0 / n);
total = 1.0;
}
auto share_to_px = [&](double share_sum) { return rect.x + int(std::lround(share_sum / total * double(rect.width))); };
int x0 = rect.x;
std::vector<wxRect> segs(n);
for (size_t i = 0; i < n; ++i) {
int x1 = rect.x + rect.width;
if (i + 1 < n)
x1 = share_to_px(std::accumulate(norm.begin(), norm.begin() + i + 1, 0.0));
segs[i] = wxRect(x0, rect.y, std::max(1, x1 - x0), rect.height);
x0 = segs[i].GetRight() + 1;
}
for (size_t i = 0; i < n; ++i) {
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(wxBrush(colours[i]));
dc.DrawRectangle(segs[i]);
}
dc.SetBrush(*wxTRANSPARENT_BRUSH);
dc.SetPen(wxPen(StateColor::darkModeColorFor(wxColour("#ACACAC")), 1));
dc.DrawRectangle(rect);
}
namespace {
struct TriCacheKey
{
int w, h;
int c0r, c0g, c0b, c1r, c1g, c1b, c2r, c2g, c2b;
int bg_r, bg_g, bg_b, ol_r, ol_g, ol_b;
bool operator<(const TriCacheKey& o) const
{
return std::tie(w, h, c0r, c0g, c0b, c1r, c1g, c1b, c2r, c2g, c2b, bg_r, bg_g, bg_b, ol_r, ol_g, ol_b) <
std::tie(o.w, o.h, o.c0r, o.c0g, o.c0b, o.c1r, o.c1g, o.c1b, o.c2r, o.c2g, o.c2b, o.bg_r, o.bg_g, o.bg_b, o.ol_r, o.ol_g, o.ol_b);
}
};
std::map<TriCacheKey, wxBitmap>& tri_cache()
{
static std::map<TriCacheKey, wxBitmap> cache;
return cache;
}
} // namespace
std::array<TriPoint, 3> mixed_triangle_vertices(const wxSize& size, double margin_dip)
{
const double pw = size.GetWidth(), ph = size.GetHeight();
const double margin = dip_px(int(margin_dip));
const double avail = std::min(pw, ph) - 2.0 * margin;
const double side = avail;
const double tri_h = side * std::sqrt(3.0) / 2.0;
const double cx = pw / 2.0;
const double top_y = (ph - tri_h) / 2.0;
return {{{cx, top_y}, {cx - side / 2.0, top_y + tri_h}, {cx + side / 2.0, top_y + tri_h}}};
}
void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array<wxColour, 3>& colours,
const std::array<double, 3>& weights, const MixedTriangleTheme& theme)
{
if (size.GetWidth() <= 0 || size.GetHeight() <= 0)
return;
const std::array<TriPoint, 3> v = mixed_triangle_vertices(size, kTriangleMarginDip);
dc.SetBrush(wxBrush(theme.background));
dc.SetPen(*wxTRANSPARENT_PEN);
dc.DrawRectangle(0, 0, size.GetWidth(), size.GetHeight());
const wxColour& c0 = colours[0];
const wxColour& c1 = colours[1];
const wxColour& c2 = colours[2];
const TriCacheKey key{size.GetWidth(), size.GetHeight(),
c0.Red(), c0.Green(), c0.Blue(),
c1.Red(), c1.Green(), c1.Blue(),
c2.Red(), c2.Green(), c2.Blue(),
theme.background.Red(), theme.background.Green(), theme.background.Blue(),
theme.outline.Red(), theme.outline.Green(), theme.outline.Blue()};
wxBitmap& bmp = tri_cache()[key];
if (!bmp.IsOk()) {
bmp = wxBitmap(size.GetWidth(), size.GetHeight(), 24);
wxMemoryDC mdc(bmp);
mdc.SetBrush(wxBrush(theme.background));
mdc.SetPen(*wxTRANSPARENT_PEN);
mdc.DrawRectangle(0, 0, size.GetWidth(), size.GetHeight());
const int min_y = int(std::min({v[0].y, v[1].y, v[2].y}));
const int max_y = int(std::max({v[0].y, v[1].y, v[2].y}));
const int min_x = int(std::min({v[0].x, v[1].x, v[2].x}));
const int max_x = int(std::max({v[0].x, v[1].x, v[2].x}));
for (int py = min_y; py <= max_y; ++py) {
for (int px = min_x; px <= max_x; ++px) {
const TriPoint p = {double(px), double(py)};
if (!tri_contains(p, v[0], v[1], v[2]))
continue;
double w0, w1, w2;
tri_barycentric(p, v[0], v[1], v[2], w0, w1, w2);
unsigned char mr, mg, mb;
if (w0 + w1 > 1e-6) {
float t01 = float(w1 / (w0 + w1));
Slic3r::filament_mixer_lerp(c0.Red(), c0.Green(), c0.Blue(), c1.Red(), c1.Green(), c1.Blue(), t01, &mr, &mg, &mb);
Slic3r::filament_mixer_lerp(mr, mg, mb, c2.Red(), c2.Green(), c2.Blue(), float(w2), &mr, &mg, &mb);
} else {
mr = c2.Red(); mg = c2.Green(); mb = c2.Blue();
}
mdc.SetPen(wxPen(wxColour(mr, mg, mb)));
mdc.DrawPoint(px, py);
}
}
mdc.SetPen(wxPen(theme.outline, 1));
mdc.SetBrush(*wxTRANSPARENT_BRUSH);
const wxPoint pts[3] = {{int(v[0].x), int(v[0].y)}, {int(v[1].x), int(v[1].y)}, {int(v[2].x), int(v[2].y)}};
mdc.DrawPolygon(3, pts);
mdc.SelectObject(wxNullBitmap);
// Keep the cache from growing without bound across DPI/size changes.
if (tri_cache().size() > 6) {
auto& cache = tri_cache();
cache.erase(cache.begin());
}
}
dc.DrawBitmap(bmp, 0, 0);
// Published-ratio marker (read-only twin of the editor's drag handle).
const double w0 = weights[0], w1 = weights[1], w2 = weights[2];
const int hx = int(w0 * v[0].x + w1 * v[1].x + w2 * v[2].x);
const int hy = int(w0 * v[0].y + w1 * v[1].y + w2 * v[2].y);
dc.SetBrush(*wxWHITE_BRUSH);
dc.SetPen(wxPen(theme.ring, dip_px(2)));
dc.DrawCircle(hx, hy, dip_px(5));
}
void draw_mixed_triangle_labels(wxDC& dc, const wxSize& size, const std::array<double, 3>& weights,
const MixedTriangleTheme& theme)
{
const std::array<TriPoint, 3> v = mixed_triangle_vertices(size, kTriangleMarginDip);
dc.SetFont(::Label::Body_12);
dc.SetTextForeground(theme.label);
// "Ratio" title, sitting above the top vertex.
const wxString title = _L("Ratio");
dc.DrawText(title, dip_px(2), std::max(0, int(v[0].y - dc.GetTextExtent(title).GetHeight() - dip_px(4))));
for (int i = 0; i < 3; ++i) {
const wxString text = wxString::Format("%d%%", int(std::lround(weights[i] * 100.0)));
const wxSize tsz = dc.GetTextExtent(text);
int lx = int(v[i].x - tsz.GetWidth() / 2.0);
int ly = (i == 0) ? int(v[i].y - tsz.GetHeight() - dip_px(4)) : int(v[i].y + dip_px(3));
ly = std::clamp(ly, 0, size.GetHeight() - tsz.GetHeight());
lx = std::clamp(lx, 0, size.GetWidth() - tsz.GetWidth());
dc.DrawText(text, lx, ly);
}
}
}} // namespace Slic3r::GUI
+129
View File
@@ -5,10 +5,27 @@
#include <wx/colour.h>
#include <wx/dc.h>
#include <wx/gdicmn.h>
#include <wx/geometry.h>
#include <wx/graphics.h>
#include <array>
#include <vector>
// Orca: forward-declare so the header is self-contained outside libslic3r_gui's
// force-included pch (the GUI test suite includes it directly).
namespace Slic3r { class DynamicPrintConfig; struct GradientCurve; }
namespace Slic3r { namespace GUI {
// Barycentric utilities for a ternary (triangle) ratio picker, shared by the mixed-filament
// editor and the Publish dialog's read-only definition preview.
struct TriPoint { double x, y; };
double tri_signed_area2(TriPoint a, TriPoint b, TriPoint c);
bool tri_contains(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2);
void tri_barycentric(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2,
double& w0, double& w1, double& w2);
TriPoint tri_clamp(TriPoint p, TriPoint v0, TriPoint v1, TriPoint v2);
// Fills a rect with a west->east linear gradient by drawing solid 1px columns.
// Use instead of wxDC::GradientFillLinear, whose CoreGraphics (CGShading) backend
// fails to render on some macOS builds; solid fills are unaffected.
@@ -28,6 +45,118 @@ wxBitmap create_filament_bitmap(const std::vector<wxColour>& colors,
const wxSize& size,
bool force_gradient = false);
// Blend colours at the given relative weights through blend_color_multi, so a measured
// real-world mix is used where one exists instead of a plain channel lerp.
wxColour blend_n_colors(const std::vector<wxColour>& cols, const std::vector<double>& weights);
// Sample a gradient mixed filament the way the slicer builds it: t runs 0..1 over the
// model's height, the curve gives the first component's ratio at t, and the two
// components are blended at that ratio through blend_n_colors. Entry 0 is the bottom
// of the model, the last entry its top.
std::vector<wxColour> sample_gradient_ramp(const wxColour& first,
const wxColour& second,
const Slic3r::GradientCurve& curve,
int steps);
// Same ramp for a project config slot, resolving components, colours and curve (or the
// linear gradient_range fallback) from cfg. Returns empty for any slot that is not a
// two-component gradient mixed filament. steps is the ramp's resolution; pass the
// destination's height in pixels.
std::vector<wxColour> mixed_gradient_ramp(const Slic3r::DynamicPrintConfig& cfg, size_t slot, int steps);
// Resolve the curve a gradient slot is sampled with: the custom curve wins when it has at
// least two points, otherwise a straight line between gradient_range's endpoints, otherwise
// the 0.10 -> 0.90 default. Mirrors the slicer's ToolOrdering fallback so every preview
// agrees with what gets sliced. Always returns a two-point curve.
Slic3r::GradientCurve mixed_gradient_curve(const Slic3r::DynamicPrintConfig& cfg, size_t slot);
// Fill rect with a ramp, ramp.front() along the bottom edge.
void fill_gradient_ramp_rect(wxDC& dc, const wxRect& rect, const std::vector<wxColour>& ramp);
// Swatch bitmap for a gradient mixed filament, drawn bottom to top from the ramp.
wxBitmap create_gradient_ramp_bitmap(const std::vector<wxColour>& ramp, const wxSize& size);
// Recompute blended representative colors for mixed (virtual) filament slots.
// Reads mixed-filament config keys from cfg and writes back into colors[i]
// for every slot where filament_is_mixed[i] is true.
void recompute_mixed_slot_colors(std::vector<wxColour>& colors,
const Slic3r::DynamicPrintConfig& cfg);
// --- Gradient plot (shared by GradientCurveEditor and the Publish dialog's read-only
// preview). The plot is a square 1:1 rect laid out with the editor's ratios so both
// render identically; curves are drawn as sub-pixel anti-aliased polylines through
// wxGCDC so they never quantize to whole pixels.
// One curve of the plot: screen-space sub-pixel points already mapped into the plot
// rect, the stroke colour and the stroke width in DIP.
struct MixedGradientCurve
{
std::vector<wxPoint2DDouble> points;
wxColour colour;
int stroke_dip;
};
// Theme tokens, resolved by the caller through StateColor::darkModeColorFor.
struct MixedGradientTheme
{
wxColour background; // for near-background outline detection
wxColour grid; // grid line
wxColour axis; // axis + arrow fill
wxColour label; // "Material Ratio" / "Model Height"
wxColour label_strong; // "100%"
wxColour outline; // near-background curve lift
wxColour point_fill; // anchor fill
};
// Square 1:1 plot rect inside `canvas`, using the editor's plot ratios.
wxRect mixed_gradient_plot_rect(const wxSize& canvas);
// Draw the whole plot (grid, axes + arrowheads, axis labels, each curve with an optional
// near-background outline, and anchor circles). `anchors` are empty when the caller has
// none to show. `dc` is the caller's buffered paint DC; a wxGCDC is created inside so the
// geometry gets anti-aliased.
void draw_mixed_gradient_plot(wxDC& dc, const wxSize& canvas,
const std::vector<MixedGradientCurve>& curves,
const std::vector<wxPoint2DDouble>& anchors,
const MixedGradientTheme& theme);
// --- Ratio bar (2-component continuous blend + divider, matching MixedFilamentDialog).
// Colours blend first->second across the rect; the divider marks `second_fraction` of the
// rect's width (the second component's share, 0..1).
void draw_mixed_ratio_blend_bar(wxDC& dc, const wxRect& rect, const wxColour& first,
const wxColour& second, double second_fraction);
// Fallback ratio bar for N>2 non-gradient slots: one solid segment per component,
// widths proportional to shares. Label text (the "NN%" inside wide-enough segments) is
// the caller's concern.
void draw_mixed_ratio_segments(wxDC& dc, const wxRect& rect, const std::vector<wxColour>& colours,
const std::vector<double>& shares);
// --- Triangle picker (3-component), shared by MixedFilamentDialog and the Publish preview.
struct MixedTriangleTheme
{
wxColour background;
wxColour outline; // triangle border
wxColour ring; // drag-handle ring
wxColour label; // "Ratio" title + per-vertex labels
};
// The three vertices of the read-only/miniature triangle inside a `size` square panel,
// with `margin_dip` inset. Order: top, bottom-left, bottom-right.
std::array<TriPoint, 3> mixed_triangle_vertices(const wxSize& size, double margin_dip = 20.0);
// Draw background, the cached barycentric fill, the outline and the drag-handle marker.
// `weights` are the three barycentric shares (sum 1). The "Ratio" title and per-vertex
// percentage labels are drawn by the caller so the interactive editor can keep its own
// live child labels while the read-only preview draws them as text.
void draw_mixed_triangle_picker(wxDC& dc, const wxSize& size, const std::array<wxColour, 3>& colours,
const std::array<double, 3>& weights, const MixedTriangleTheme& theme);
// Draw the "Ratio" title plus one "NN%" label per vertex (used by the read-only preview;
// the interactive editor positions its own live labels instead).
void draw_mixed_triangle_labels(wxDC& dc, const wxSize& size, const std::array<double, 3>& weights,
const MixedTriangleTheme& theme);
}} // namespace Slic3r::GUI
#endif // slic3r_GUI_FilamentBitmapUtils_hpp_
+1 -1
View File
@@ -241,7 +241,7 @@ FilamentMapDialog::FilamentMapDialog(wxWindow *parent,
wxBoxSizer *mode_sizer = new wxBoxSizer(wxHORIZONTAL);
m_auto_btn = new CapsuleButton(this, PageType::ptAuto, only_saving_mode ? _L("Fila Saving") : _L("Auto"), false);
m_auto_btn = new CapsuleButton(this, PageType::ptAuto, only_saving_mode ? _L("File Saving") : _L("Auto"), false);
m_manual_btn = new CapsuleButton(this, PageType::ptManual, _L("Custom"), false);
if (show_default)
m_default_btn = new CapsuleButton(this, PageType::ptDefault, _L("Same as Global"), true);
+13 -32
View File
@@ -1,5 +1,6 @@
#include "FilamentMapPanel.hpp"
#include "GUI_App.hpp"
#include "I18N.hpp"
#include "Plater.hpp"
#include "Widgets/MultiNozzleSync.hpp" // manuallySetNozzleCount producer for extruder_nozzle_stats
#include <algorithm>
@@ -642,19 +643,12 @@ void FilamentMapBtnPanel::Select(bool selected)
Refresh();
}
void GUI::FilamentMapBtnPanel::Hide()
bool GUI::FilamentMapBtnPanel::Show(bool show)
{
m_btn->Hide();
m_label->Hide();
m_detail->Hide();
wxPanel::Hide();
}
void GUI::FilamentMapBtnPanel::Show()
{
m_btn->Show();
m_label->Show();
m_detail->Show();
wxPanel::Show();
m_btn->Show(show);
m_label->Show(show);
m_detail->Show(show);
return wxPanel::Show(show);
}
FilamentMapAutoPanel::FilamentMapAutoPanel(wxWindow *parent, FilamentMapMode mode, bool machine_synced) : wxPanel(parent)
@@ -694,18 +688,11 @@ FilamentMapAutoPanel::FilamentMapAutoPanel(wxWindow *parent, FilamentMapMode mod
Layout();
GUI::wxGetApp().UpdateDarkUIWin(this);
}
void FilamentMapAutoPanel::Hide()
bool FilamentMapAutoPanel::Show(bool show)
{
m_flush_panel->Hide();
m_match_panel->Hide();
wxPanel::Hide();
}
void FilamentMapAutoPanel::Show()
{
m_flush_panel->Show();
m_match_panel->Show();
wxPanel::Show();
m_flush_panel->Show(show);
m_match_panel->Show(show);
return wxPanel::Show(show);
}
void FilamentMapAutoPanel::UpdateStatus()
@@ -743,16 +730,10 @@ FilamentMapDefaultPanel::FilamentMapDefaultPanel(wxWindow *parent) : wxPanel(par
GUI::wxGetApp().UpdateDarkUIWin(this);
}
void FilamentMapDefaultPanel::Hide()
bool FilamentMapDefaultPanel::Show(bool show)
{
m_label->Hide();
wxPanel::Hide();
}
void FilamentMapDefaultPanel::Show()
{
m_label->Show();
wxPanel::Show();
m_label->Show(show);
return wxPanel::Show(show);
}
}} // namespace Slic3r::GUI
+4 -7
View File
@@ -69,10 +69,9 @@ class FilamentMapBtnPanel : public wxPanel
{
public:
FilamentMapBtnPanel(wxWindow *parent, const wxString &label, const wxString &detail, const std::string &icon_path);
void Hide();
void Show();
bool Show(bool show = true) override;
void Select(bool selected);
bool Enable(bool enable);
bool Enable(bool enable) override;
bool IsEnabled() const { return m_enabled; }
protected:
void OnPaint(wxPaintEvent &event);
@@ -99,8 +98,7 @@ class FilamentMapAutoPanel : public wxPanel
{
public:
FilamentMapAutoPanel(wxWindow *parent, FilamentMapMode mode, bool machine_synced);
void Hide();
void Show();
bool Show(bool show = true) override;
FilamentMapMode GetMode() const { return m_mode; }
private:
@@ -116,8 +114,7 @@ class FilamentMapDefaultPanel : public wxPanel
{
public:
FilamentMapDefaultPanel(wxWindow *parent);
void Hide();
void Show();
bool Show(bool show = true) override;
private:
Label *m_label;
+2 -2
View File
@@ -426,11 +426,11 @@ wxScrolledWindow* FilamentPickerDialog::CreateColorGrid()
});
// Hover highlight
btn->Bind(wxEVT_ENTER_WINDOW, [btn](wxMouseEvent& evt) {
btn->Bind(wxEVT_ENTER_WINDOW, [](wxMouseEvent& evt) {
evt.Skip();
});
btn->Bind(wxEVT_LEAVE_WINDOW, [btn](wxMouseEvent& evt) {
btn->Bind(wxEVT_LEAVE_WINDOW, [](wxMouseEvent& evt) {
evt.Skip();
});
+39 -22
View File
@@ -785,6 +785,19 @@ void GCodeViewer::SequentialView::GCodeWindow::load_gcode(const std::string& fil
}
}
// Byte offset just past the first count characters of str, or its length if it is shorter.
static size_t utf8_offset(const std::string& str, size_t count)
{
const char* const begin = str.c_str();
const char* const end = begin + str.size();
const char* pos = begin;
for (size_t i = 0; i < count && pos < end; ++i) {
unsigned int codepoint = 0;
pos += ImTextCharFromUtf8(&codepoint, pos, end);
}
return pos - begin;
}
//BBS: GUI refactor: move to right
void GCodeViewer::SequentialView::GCodeWindow::render(float top, float bottom, float right, uint64_t curr_line_id) const
{
@@ -796,23 +809,27 @@ void GCodeViewer::SequentialView::GCodeWindow::render(float top, float bottom, f
// read line from file
const size_t start = id == 1 ? 0 : m_lines_ends[id - 2];
const size_t original_len = m_lines_ends[id - 1] - start;
const size_t len = std::min(original_len, (size_t) 55);
// A character is four bytes at most, so 55 of them always fit in 220.
const size_t len = std::min(original_len, (size_t) 55 * 4);
std::string gline(m_file.data() + start, len);
// If original line is longer than 55 characters, truncate and append "..."
if (original_len > 55)
gline = gline.substr(0, 52) + "...";
// If original line is longer than 55 characters, truncate and append "...".
// The cut must land on a character boundary or it leaves half a character behind.
if (len < original_len || utf8_offset(gline, 55) < gline.size())
gline = gline.substr(0, utf8_offset(gline, 52)) + "...";
std::string command, parameters, comment;
// extract comment
std::vector<std::string> tokens;
boost::split(tokens, gline, boost::is_any_of(";"), boost::token_compress_on);
command = tokens.front();
if (tokens.size() > 1)
comment = ";" + tokens.back();
const size_t comment_start = gline.find(';');
if (comment_start == std::string::npos)
command = gline;
else {
command = gline.substr(0, comment_start);
comment = gline.substr(comment_start);
}
// extract gcode command and parameters
if (!command.empty()) {
std::vector<std::string> tokens;
boost::split(tokens, command, boost::is_any_of(" "), boost::token_compress_on);
command = tokens.front();
if (tokens.size() > 1) {
@@ -2613,7 +2630,7 @@ void GCodeViewer::render_all_plates_stats(const std::vector<const GCodeProcessor
return ret;
};
auto append_item = [icon_size, &imgui, imperial_units, &window_padding, &draw_list, this](const ColorRGBA& color, const std::vector<std::pair<std::string, float>>& columns_offsets)
auto append_item = [icon_size, &imgui, &window_padding, &draw_list, this](const ColorRGBA& color, const std::vector<std::pair<std::string, float>>& columns_offsets)
{
// render icon
ImVec2 pos = ImVec2(ImGui::GetCursorScreenPos().x + window_padding * 3, ImGui::GetCursorScreenPos().y);
@@ -2648,7 +2665,7 @@ void GCodeViewer::render_all_plates_stats(const std::vector<const GCodeProcessor
}
ImGui::Separator();
};
auto get_used_filament_from_volume = [this, imperial_units, &filament_diameters, &filament_densities](double volume, int extruder_id) {
auto get_used_filament_from_volume = [imperial_units, &filament_diameters, &filament_densities](double volume, int extruder_id) {
double koef = imperial_units ? 1.0 / GizmoObjectManipulation::in_to_mm : 0.001;
std::pair<double, double> ret = { koef * volume / (PI * sqr(0.5 * filament_diameters[extruder_id])),
volume * filament_densities[extruder_id] * 0.001 };
@@ -3233,7 +3250,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
//ImVec2(pos_rect.x + ImGui::GetWindowWidth() + ImGui::GetFrameHeight(),pos_rect.y + ImGui::GetFrameHeight() + window_padding * 2.5),
//ImGui::GetColorU32(ImVec4(0,0,0,0.3)));
auto append_item = [icon_size, &imgui, imperial_units, &window_padding, &draw_list, this](
auto append_item = [icon_size, &imgui, &window_padding, &draw_list, this](
EItemType type,
const ColorRGBA& color,
const std::vector<std::pair<std::string, float>>& columns_offsets,
@@ -3368,7 +3385,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
return ret;
};
auto calculate_offsets = [&imgui, max_width, window_padding, this](const std::vector<std::pair<std::string, std::vector<::string>>>& title_columns, float extra_size = 0.0f) {
auto calculate_offsets = [max_width, this](const std::vector<std::pair<std::string, std::vector<::string>>>& title_columns, float extra_size = 0.0f) {
const ImGuiStyle& style = ImGui::GetStyle();
std::vector<float> offsets;
// ORCA increase spacing for more readable format. Using direct number requires much less code change in here. GetTextLineHeight for additional spacing for icon_size
@@ -3856,7 +3873,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
columns_offsets.push_back({ distance_text, offsets[3] });
if (full_layout && !count_text.empty())
columns_offsets.push_back({ count_text, distance_text.empty() ? offsets[3] : offsets[4] });
append_item(EItemType::Rect, color, columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, type, visible]() {
append_item(EItemType::Rect, color, columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, type]() {
m_viewer.toggle_option_visibility(type);
update_moves_slider();
});
@@ -3913,7 +3930,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
columns_offsets.push_back({used_filaments_length[i], offsets[3]});
columns_offsets.push_back({used_filaments_weight[i], offsets[4]});
append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_extrusion_role_color(role)), columns_offsets,
true, offsets.back(), visible, [this, role, visible]() {
true, offsets.back(), visible, [this, role]() {
m_viewer.toggle_extrusion_role_visibility(role);
update_moves_slider();
});
@@ -3932,7 +3949,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
columns_offsets.push_back({ travel_percent, offsets[2] });
columns_offsets.push_back({ travel_distance, offsets[3] }); // Usage column
columns_offsets.push_back({ travel_moves, offsets[4] }); // Usage column
append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, item, visible]() {
append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, item]() {
m_viewer.toggle_option_visibility(item);
update_moves_slider();
});
@@ -3951,7 +3968,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
append_headers({ {_u8L("Options"), offsets[0] }, { _u8L("Display"), offsets[1]} });
const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f));
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this, travel_visible]() {
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() {
m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels);
// refresh(*m_gcode_result, wxGetApp().plater()->get_extruder_colors_from_plater_config(m_gcode_result));
update_moves_slider();
@@ -3968,7 +3985,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
append_headers({ {_u8L("Options"), offsets[0] }, { _u8L("Display"), offsets[1]} });
const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f));
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this, travel_visible]() {
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() {
m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels);
// refresh(*m_gcode_result, wxGetApp().plater()->get_extruder_colors_from_plater_config(m_gcode_result));
update_moves_slider();
@@ -3985,7 +4002,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
append_headers({ {_u8L("Options"), offsets[0] }, { _u8L("Display"), offsets[1]} });
const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f));
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this, travel_visible]() {
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() {
m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels);
update_moves_slider();
});
@@ -4001,7 +4018,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
append_headers({ {_u8L("Options"), offsets[0] }, { _u8L("Display"), offsets[1]} });
const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f));
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this, travel_visible]() {
append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() {
m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels);
update_moves_slider();
});
@@ -4121,7 +4138,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv
}
float checkbox_pos = std::max(predictable_icon_pos, color_print_offsets[_u8L("Display")]); // ORCA prefer predictable_icon_pos when header not reacing end
append_item(EItemType::Rect, libvgcode::convert(tool_colors[extruder_idx]), columns_offsets, false, checkbox_pos/*ORCA*/, true, [this, extruder_idx]() {});
append_item(EItemType::Rect, libvgcode::convert(tool_colors[extruder_idx]), columns_offsets, false, checkbox_pos/*ORCA*/, true, []() {});
}
i++;
}
-1
View File
@@ -72,7 +72,6 @@ public:
float m_model_z_offset{ 0.5f };
bool m_visible{ true };
bool m_is_dark = false;
bool m_fixed_screen_size{ false };
float m_scale_factor{ 1.0f };
#if ENABLE_ACTUAL_SPEED_DEBUG
ActualSpeedImguiWidget m_actual_speed_imgui_widget;
+145 -124
View File
@@ -155,6 +155,11 @@ std::string& get_filament_mixture_warning_text(){
return filament_mixture_warning_text;
}
std::string& get_single_extruder_mixed_filament_warning_text(){
static std::string single_extruder_mixed_filament_warning_text;
return single_extruder_mixed_filament_warning_text;
}
static std::string format_number(float value)
{
@@ -1073,56 +1078,36 @@ const double GLCanvas3D::DefaultCameraZoomToPlateMarginFactor = 1.25;
void GLCanvas3D::load_arrange_settings()
{
std::string dist_fff_str =
wxGetApp().app_config->get("arrange", "min_object_distance_fff");
// Each key must match what _render_arrange_menu writes, which appends a per-mode
// postfix to the base name.
auto load_float = [](const char *key, float &out) {
// The menu writes these with float_to_string_decimal_point, so parse them back
// the same way rather than with anything locale-dependent.
std::string value = wxGetApp().app_config->get("arrange", key);
size_t parsed = 0;
double number = string_to_double_decimal_point(value, &parsed);
if (parsed > 0)
out = float(number);
};
auto load_bool = [](const char *key, bool &out) {
std::string value = wxGetApp().app_config->get("arrange", key);
if (!value.empty())
out = (value == "1" || value == "true");
};
std::string dist_fff_seq_print_str =
wxGetApp().app_config->get("arrange", "min_object_distance_seq_print_fff");
load_float("min_object_distance_fff", m_arrange_settings_fff.distance);
load_float("min_object_distance_fff_seq_print", m_arrange_settings_fff_seq_print.distance);
load_float("min_object_distance_sla", m_arrange_settings_sla.distance);
std::string dist_sla_str =
wxGetApp().app_config->get("arrange", "min_object_distance_sla");
load_bool("enable_rotation_fff", m_arrange_settings_fff.enable_rotation);
load_bool("enable_rotation_fff_seq_print", m_arrange_settings_fff_seq_print.enable_rotation);
load_bool("enable_rotation_sla", m_arrange_settings_sla.enable_rotation);
std::string en_rot_fff_str =
wxGetApp().app_config->get("arrange", "enable_rotation_fff");
std::string en_rot_fff_seqp_str =
wxGetApp().app_config->get("arrange", "enable_rotation_seq_print");
std::string en_rot_sla_str =
wxGetApp().app_config->get("arrange", "enable_rotation_sla");
std::string en_allow_multiple_materials_str =
wxGetApp().app_config->get("arrange", "allow_multi_materials_on_same_plate");
std::string en_avoid_region_str =
wxGetApp().app_config->get("arrange", "avoid_extrusion_cali_region");
if (!dist_fff_str.empty())
m_arrange_settings_fff.distance = std::stof(dist_fff_str);
if (!dist_fff_seq_print_str.empty())
m_arrange_settings_fff_seq_print.distance = std::stof(dist_fff_seq_print_str);
if (!dist_sla_str.empty())
m_arrange_settings_sla.distance = std::stof(dist_sla_str);
if (!en_rot_fff_str.empty())
m_arrange_settings_fff.enable_rotation = (en_rot_fff_str == "1" || en_rot_fff_str == "true");
if (!en_allow_multiple_materials_str.empty())
m_arrange_settings_fff.allow_multi_materials_on_same_plate = (en_allow_multiple_materials_str == "1" || en_allow_multiple_materials_str == "true");
if (!en_rot_fff_seqp_str.empty())
m_arrange_settings_fff_seq_print.enable_rotation = (en_rot_fff_seqp_str == "1" || en_rot_fff_seqp_str == "true");
if(!en_avoid_region_str.empty())
m_arrange_settings_fff.avoid_extrusion_cali_region = (en_avoid_region_str == "1" || en_avoid_region_str == "true");
if (!en_rot_sla_str.empty())
m_arrange_settings_sla.enable_rotation = (en_rot_sla_str == "1" || en_rot_sla_str == "true");
// These two keys carry no postfix, so the one stored value covers both FFF modes.
load_bool("allow_multi_materials_on_same_plate", m_arrange_settings_fff.allow_multi_materials_on_same_plate);
load_bool("allow_multi_materials_on_same_plate", m_arrange_settings_fff_seq_print.allow_multi_materials_on_same_plate);
load_bool("avoid_extrusion_cali_region", m_arrange_settings_fff.avoid_extrusion_cali_region);
load_bool("avoid_extrusion_cali_region", m_arrange_settings_fff_seq_print.avoid_extrusion_cali_region);
//BBS: add specific arrange settings
m_arrange_settings_fff_seq_print.is_seq_print = true;
@@ -2186,7 +2171,7 @@ void GLCanvas3D::render(bool only_init)
// Negative coordinate means out of the window, likely because the window was deactivated.
// In that case the tooltip should be hidden.
if (m_mouse.position.x() >= 0. && m_mouse.position.y() >= 0. || has_mouse_capture()) { // ORCA continue to capture mouse pos mid drag
if ((m_mouse.position.x() >= 0. && m_mouse.position.y() >= 0.) || has_mouse_capture()) { // ORCA continue to capture mouse pos mid drag
if (tooltip.empty())
tooltip = m_layers_editing.get_tooltip(*this);
@@ -2886,23 +2871,37 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re
DynamicPrintConfig& proj_cfg = wxGetApp().preset_bundle->project_config;
float x = dynamic_cast<const ConfigOptionFloats*>(proj_cfg.option("wipe_tower_x"))->get_at(plate_id);
float y = dynamic_cast<const ConfigOptionFloats*>(proj_cfg.option("wipe_tower_y"))->get_at(plate_id);
float w = dynamic_cast<const ConfigOptionFloat*>(m_config->option("prime_tower_width"))->value;
float a = dynamic_cast<const ConfigOptionFloat*>(m_config->option("wipe_tower_rotation_angle"))->value;
// BBS
float v = dynamic_cast<const ConfigOptionFloat*>(m_config->option("prime_volume"))->value;
Vec3d plate_origin = ppl.get_plate(plate_id)->get_origin();
const Print* print = m_process->fff_print();
const Print* current_print = part_plate->fff_print();
if (!need_wipe_tower && part_plate->get_extruders(true).size() < 2) continue;
if (part_plate->get_objects_on_this_plate().empty()) continue;
float brim_width = print->wipe_tower_data(filaments_count).brim_width;
int nozzle_nums = wxGetApp().preset_bundle->get_printer_extruder_count();
Vec3d wipe_tower_size = ppl.get_plate(plate_id)->estimate_wipe_tower_size(full_config, w, v, nozzle_nums, 0, false, dynamic_cast<const ConfigOptionBool*>(dconfig.option("enable_wrapping_detection"))->value);
// Body and brim from this plate's own estimate: m_process->fff_print() is the
// selected plate's, so an auto brim drew every tower with that plate's brim.
const WipeTowerFootprint footprint = part_plate->estimate_wipe_tower_footprint(full_config);
// The estimate is also the answer to whether this plate prints a tower;
// deciding it here as well only gave the two room to drift.
if (footprint.depth <= 0.) continue;
float brim_width = float(footprint.brim_width);
Vec3d wipe_tower_size(footprint.width, footprint.depth, footprint.height);
// set_default_wipe_tower_pos_for_plate doesn't rerun when painting changes the
// filament count, so redo its clamp here on every reload — unconditionally: a
// paint-triggered reload can arrive before the background process invalidates
// psWipeTower, so gating on it would skip the clamp exactly when it is needed.
{
Vec3d clamped_pos, clamped_size;
part_plate->estimate_wipe_tower_polygon(full_config, plate_id, clamped_pos, clamped_size);
if (std::abs(x - (float) clamped_pos(0)) > EPSILON || std::abs(y - (float) clamped_pos(1)) > EPSILON) {
x = (float) clamped_pos(0);
y = (float) clamped_pos(1);
ConfigOptionFloat wt_x_opt(x), wt_y_opt(y);
dynamic_cast<ConfigOptionFloats*>(proj_cfg.option("wipe_tower_x"))->set_at(&wt_x_opt, plate_id, 0);
dynamic_cast<ConfigOptionFloats*>(proj_cfg.option("wipe_tower_y"))->set_at(&wt_y_opt, plate_id, 0);
}
}
// The stored position is already clamped onto the bed, by
// set_default_wipe_tower_pos_for_plate and again on every drag.
if (!current_print->is_step_done(psWipeTower) || !current_print->wipe_tower_data().wipe_tower_mesh_data) {
// update for wipe tower position
int volume_idx_wipe_tower_new = m_volumes.load_wipe_tower_preview(1000 + plate_id, x + plate_origin(0), y + plate_origin(1),
@@ -2984,6 +2983,9 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re
bool mix_pla_and_petg = cur_plate->check_mixture_of_pla_and_petg(full_config_temp);
_set_warning_notification(EWarning::MixUsePLAAndPETG, !mix_pla_and_petg);
bool single_extruder_mixed_risk = cur_plate->check_single_extruder_mixed_filament_risk(full_config_temp, get_single_extruder_mixed_filament_warning_text());
_set_warning_notification(EWarning::SingleExtruderMixedFilament, single_extruder_mixed_risk);
bool filament_nozzle_compatible = cur_plate->check_compatible_of_nozzle_and_filament(full_config_temp, wxGetApp().preset_bundle->filament_presets, get_nozzle_filament_incompatible_text());
_set_warning_notification(EWarning::NozzleFilamentIncompatible, !filament_nozzle_compatible);
@@ -3010,6 +3012,7 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re
_set_warning_notification(EWarning::TPUPrintableError, false);
_set_warning_notification(EWarning::FilamentPrintableError, false);
_set_warning_notification(EWarning::MixUsePLAAndPETG, false);
_set_warning_notification(EWarning::SingleExtruderMixedFilament, false);
_set_warning_notification(EWarning::PrimeTowerOutside, false);
_set_warning_notification(EWarning::MultiExtruderPrintableError,false);
_set_warning_notification(EWarning::MultiExtruderHeightOutside,false);
@@ -4159,7 +4162,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt)
// https://github.com/OrcaSlicer/OrcaSlicer/pull/14999#issuecomment-5151344759
// We solve this by correcting the state of the event from the actual mouse state querying with `wxGetMouseState()`
// so it works like on other platforms.
{
// Only fill in state the event does not carry, to preserve wx's synthetic right button for Ctrl+left.
if (!evt.ButtonIsDown(wxMOUSE_BTN_ANY)) {
const auto state = wxGetMouseState();
evt.SetLeftDown(state.LeftIsDown());
evt.SetMiddleDown(state.MiddleIsDown());
@@ -5035,7 +5039,21 @@ void GLCanvas3D::do_move(const std::string& snapshot_type)
}
//BBS: notify instance updates to part plater list
m_selection.notify_instance_update(-1, 0);
// Only what moved: the selected instances, or every instance of an object one of whose
// parts moved. Notifying a plate about an instance that stayed put invalidates its slice
// result, and notifying instance 0 alone left a moved copy unregistered on its new plate.
{
std::set<std::pair<int, int>> notified;
for (unsigned int i : m_selection.get_volume_idxs()) {
const GLVolume* v = m_volumes.volumes[i];
const int object_idx = v->object_idx();
if (object_idx < 0 || object_idx >= static_cast<int>(m_model->objects.size()))
continue;
const std::pair<int, int> key(object_idx, selection_mode == Selection::Volume ? -1 : v->instance_idx());
if (notified.insert(key).second)
m_selection.notify_instance_update(key.first, key.second);
}
}
// Fixes sinking/flying instances (snaps object to buildplate)
for (const std::pair<int, int>& i : done) {
@@ -5921,7 +5939,7 @@ bool GLCanvas3D::_render_orient_menu(float left, float right, float bottom, floa
}
//BBS: GUI refactor: adjust main toolbar position
bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, float top)
void GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, float top)
{
ImGuiWrapper *imgui = wxGetApp().imgui();
@@ -5946,7 +5964,6 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
imgui->begin(_L("Arrange options"), ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar);
ArrangeSettings settings = get_arrange_settings();
ArrangeSettings &settings_out = get_arrange_settings();
const float slider_icon_width = imgui->get_slider_icon_size().x;
const float cursor_slider_left = imgui->calc_text_size(_L("Spacing")).x + imgui->scaled(1.5f);
@@ -5955,13 +5972,9 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
auto &appcfg = wxGetApp().app_config;
PrinterTechnology ptech = current_printer_technology();
bool settings_changed = false;
float dist_min = 0.f; // 0 means auto
std::string dist_key = "min_object_distance", rot_key = "enable_rotation";
std::string bed_shrink_x_key = "bed_shrink_x", bed_shrink_y_key = "bed_shrink_y";
std::string multi_material_key = "allow_multi_materials_on_same_plate";
std::string avoid_extrusion_key = "avoid_extrusion_cali_region";
std::string align_to_y_axis_key = "align_to_y_axis";
std::string postfix;
//BBS:
bool seq_print = false;
@@ -5969,59 +5982,41 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
if (ptech == ptSLA) {
postfix = "_sla";
} else if (ptech == ptFFF) {
seq_print = &settings == &m_arrange_settings_fff_seq_print;
if (seq_print) {
postfix = "_fff_seq_print";
} else {
postfix = "_fff";
}
seq_print = wxGetApp().global_print_sequence() == PrintSequence::ByObject;
postfix = seq_print ? "_fff_seq_print" : "_fff";
}
dist_key += postfix;
rot_key += postfix;
bed_shrink_x_key += postfix;
bed_shrink_y_key += postfix;
ImGui::AlignTextToFramePadding();
imgui->text(_L("Spacing"));
ImGui::SameLine(1.2 * cursor_slider_left);
ImGui::PushItemWidth(window_width - slider_icon_width);
bool b_Spacing = imgui->bbl_slider_float_style("##Spacing", &settings.distance, dist_min, 100.0f, "%5.2f") || dist_min > settings.distance;
bool b_Spacing = imgui->bbl_slider_float_style("##Spacing", &settings_out.distance, 0.f, 100.0f, "%5.2f", 1.0f, /*clamp=*/false);
ImGui::SameLine(window_width - slider_icon_width + 1.3 * cursor_slider_left);
ImGui::PushItemWidth(1.5 * slider_icon_width);
bool b_spacing_input = ImGui::BBLDragFloat("##spacing_input", &settings.distance, 0.05f, 0.0f, 0.0f, "%.2f");
if (b_Spacing || b_spacing_input)
{
settings.distance = std::max(dist_min, settings.distance);
settings_out.distance = settings.distance;
bool b_spacing_input = ImGui::BBLDragFloat("##spacing_input", &settings_out.distance, 0.05f, 0.0f, 0.0f, "%.2f");
if (b_Spacing || b_spacing_input) {
settings_out.distance = std::max(0.f, settings_out.distance);
appcfg->set("arrange", dist_key.c_str(), float_to_string_decimal_point(settings_out.distance));
settings_changed = true;
}
imgui->text(_L("0 means auto spacing."));
ImGui::Separator();
if (imgui->bbl_checkbox(_L("Auto rotate for arrangement"), settings.enable_rotation)) {
settings_out.enable_rotation = settings.enable_rotation;
if (imgui->bbl_checkbox(_L("Auto rotate for arrangement"), settings_out.enable_rotation))
appcfg->set("arrange", rot_key.c_str(), settings_out.enable_rotation);
settings_changed = true;
}
if (imgui->bbl_checkbox(_L("Allow multiple materials on same plate"), settings.allow_multi_materials_on_same_plate)) {
settings_out.allow_multi_materials_on_same_plate = settings.allow_multi_materials_on_same_plate;
appcfg->set("arrange", multi_material_key.c_str(), settings_out.allow_multi_materials_on_same_plate );
settings_changed = true;
}
if (imgui->bbl_checkbox(_L("Allow multiple materials on same plate"), settings_out.allow_multi_materials_on_same_plate))
appcfg->set("arrange", multi_material_key.c_str(), settings_out.allow_multi_materials_on_same_plate);
// only show this option if the printer has micro Lidar and can do first layer scan
DynamicPrintConfig &current_config = wxGetApp().preset_bundle->printers.get_edited_preset().config;
const bool has_lidar = wxGetApp().preset_bundle->is_bbl_vendor();
auto op = current_config.option("scan_first_layer");
if (has_lidar && op && op->getBool()) {
if (imgui->bbl_checkbox(_L("Avoid extrusion calibration region"), settings.avoid_extrusion_cali_region)) {
settings_out.avoid_extrusion_cali_region = settings.avoid_extrusion_cali_region;
appcfg->set("arrange", avoid_extrusion_key.c_str(), settings_out.avoid_extrusion_cali_region ? "1" : "0");
settings_changed = true;
}
if (imgui->bbl_checkbox(_L("Avoid extrusion calibration region"), settings_out.avoid_extrusion_cali_region))
appcfg->set("arrange", avoid_extrusion_key.c_str(), settings_out.avoid_extrusion_cali_region);
} else {
settings_out.avoid_extrusion_cali_region = false;
}
@@ -6033,11 +6028,7 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
settings_out.align_to_y_axis = false;
}
if (imgui->bbl_checkbox(_L("Align to Y axis"), settings.align_to_y_axis)) {
settings_out.align_to_y_axis = settings.align_to_y_axis;
appcfg->set("arrange", align_to_y_axis_key, settings_out.align_to_y_axis ? "1" : "0");
settings_changed = true;
}
imgui->bbl_checkbox(_L("Align to Y axis"), settings_out.align_to_y_axis);
if (settings_out.enable_rotation == true) { imgui->disabled_end(); }
}
@@ -6053,7 +6044,6 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
if (imgui->button(_L("Reset"))) {
settings_out = ArrangeSettings{};
settings_out.distance = std::max(dist_min, settings_out.distance);
//BBS: add specific arrange settings
if (seq_print) settings_out.is_seq_print = true;
@@ -6063,18 +6053,16 @@ bool GLCanvas3D::_render_arrange_menu(float left, float right, float bottom, flo
else
settings_out.align_to_y_axis = false;
appcfg->set("arrange", dist_key, float_to_string_decimal_point(settings_out.distance));
appcfg->set("arrange", rot_key, settings_out.enable_rotation ? "1" : "0");
appcfg->set("arrange", align_to_y_axis_key, settings_out.align_to_y_axis ? "1" : "0");
settings_changed = true;
appcfg->erase("arrange", dist_key);
appcfg->erase("arrange", rot_key);
appcfg->erase("arrange", multi_material_key);
appcfg->erase("arrange", avoid_extrusion_key);
}
ImGui::PopStyleVar(1);
imgui->end();
//BBS
ImGuiWrapper::pop_toolbar_style();
return settings_changed;
}
static const float cameraProjection[16] = {1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f};
@@ -8902,7 +8890,10 @@ void GLCanvas3D::_render_imgui_select_plate_toolbar()
m_sel_plate_toolbar.m_items[i]->slice_state = IMToolbarItem::SliceState::SLICE_FAILED;
}
else {
if ((!is_empty && !can_slice) || (plate_list.get_plate(i)->has_printable_instances() && !plate_list.get_plate(i)->can_slice()))
// A plate using a mixed filament whose components are broken cannot be sliced,
// so surface that on the plate toolbar the same way an unsliceable plate is.
if ((!is_empty && !can_slice) || (plate_list.get_plate(i)->has_printable_instances() && !plate_list.get_plate(i)->can_slice())
|| wxGetApp().plater()->sidebar().has_broken_mixed_filament(plate_list.get_plate(i)))
m_sel_plate_toolbar.m_items[i]->slice_state = IMToolbarItem::SliceState::SLICE_FAILED;
else {
if (plate_list.get_plate(i)->get_slicing_percent() < 0.0f)
@@ -9224,7 +9215,7 @@ void GLCanvas3D::_render_imgui_select_plate_toolbar()
ImVec2 size = ImVec2(button_width, button_height);
ImVec2 end_pos = ImVec2(start_pos.x + size.x, start_pos.y + size.y);
// ORCA show additional information depends on state
auto draw_info_btn = [end_pos, f_scale, margin, window_bg](std::string str, ImVec4 bg_color, ImVec4 fg_color){
auto draw_info_btn = [end_pos, f_scale, margin](std::string str, ImVec4 bg_color, ImVec4 fg_color){
GImGui->FontSize = 15.0f * f_scale;
ImVec2 txt_slice_sz = ImGui::CalcTextSize(str.c_str());
ImVec2 btn_pad = ImVec2(8.f, 1.f) * f_scale;
@@ -9480,7 +9471,7 @@ void GLCanvas3D::_render_canvas_toolbar()
Plater* p = wxGetApp().plater();
AppConfig* cfg = wxGetApp().app_config;
auto create_menu_item = [this, sc](
auto create_menu_item = [sc](
const std::string& name,
bool enable,
bool condition,
@@ -9497,7 +9488,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("3D Navigator")),
m_canvas_type != ECanvasType::CanvasAssembleView, // not work on assembly
wxGetApp().show_3d_navigator(),
[this]{
[]{
wxGetApp().toggle_show_3d_navigator();
ImGui::CloseCurrentPopup(); // Close popup to show changes on UI
}
@@ -9506,7 +9497,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Zoom button")),
true, // work on all
wxGetApp().show_canvas_zoom_button(),
[this]{
[]{
wxGetApp().toggle_canvas_zoom_button();
ImGui::CloseCurrentPopup(); // Close popup to show changes on UI
}
@@ -9517,13 +9508,13 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Overhangs")),
m_canvas_type == ECanvasType::CanvasView3D, // work only on prepare
p->is_view3D_overhang_shown(),
[this, p]{p->show_view3D_overhang(!p->is_view3D_overhang_shown());}
[p]{p->show_view3D_overhang(!p->is_view3D_overhang_shown());}
);
create_menu_item( _utf8(L("Outline")),
m_canvas_type != ECanvasType::CanvasPreview, // not work on preview
wxGetApp().show_outline(),
[this]{wxGetApp().toggle_show_outline();}
[]{wxGetApp().toggle_show_outline();}
);
create_menu_item( _utf8(L("Wireframe")),
@@ -9535,7 +9526,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Realistic View")),
m_canvas_type != ECanvasType::CanvasPreview, // not work on preview
cfg->get_bool(SETTING_OPENGL_REALISTIC_MODE),
[this, &cfg]{
[&cfg]{
cfg->set_bool(SETTING_OPENGL_REALISTIC_MODE, !cfg->get_bool(SETTING_OPENGL_REALISTIC_MODE));
cfg->save();
}
@@ -9546,7 +9537,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Perspective")),
true, // work on all
cfg->get_bool("use_perspective_camera"),
[this, &cfg]{
[&cfg]{
cfg->set_bool("use_perspective_camera", !(cfg->get_bool("use_perspective_camera")));
wxGetApp().update_ui_from_settings();
}
@@ -9563,7 +9554,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Gridlines")),
m_canvas_type != ECanvasType::CanvasAssembleView, // not work on assembly
wxGetApp().show_plate_gridlines(),
[this]{wxGetApp().toggle_show_plate_gridlines();}
[]{wxGetApp().toggle_show_plate_gridlines();}
);
ImGui::Separator();
@@ -9571,7 +9562,7 @@ void GLCanvas3D::_render_canvas_toolbar()
create_menu_item( _utf8(L("Labels")),
m_canvas_type == ECanvasType::CanvasView3D, // work only on prepare
p->are_view3D_labels_shown(),
[this, p]{p->show_view3D_labels(!p->are_view3D_labels_shown());}
[p]{p->show_view3D_labels(!p->are_view3D_labels_shown());}
);
ImGui::PopItemFlag();
@@ -9669,6 +9660,13 @@ void GLCanvas3D::_render_paint_toolbar() const
}
}
}
// ORCA: the loop above only labels a slot whose preset was found in the preset collection,
// while the render loop below iterates extruder_num. Pad the label arrays so a slot without a
// matching preset cannot index past them; a garbage std::string crashes ImGui::CalcTextSize.
while (int(filament_text_first_line.size()) < extruder_num) {
filament_text_first_line.emplace_back();
filament_text_second_line.emplace_back();
}
ImGuiWrapper& imgui = *wxGetApp().imgui();
const float canvas_w = float(get_canvas_size().get_width());
@@ -9698,6 +9696,10 @@ void GLCanvas3D::_render_paint_toolbar() const
bool disabled = !wxGetApp().plater()->can_fillcolor();
ColorRGBA rgba;
// Gradient mixed filaments fade over Z, so their swatch is drawn as that fade rather than
// the single blended colour in `colors`. Every other slot's ramp is empty.
const auto& gradient_ramps = wxGetApp().plater()->get_filament_gradient_ramps();
for (int i = 0; i < extruder_num; i++) {
if (i > 0)
ImGui::SameLine();
@@ -9711,6 +9713,8 @@ void GLCanvas3D::_render_paint_toolbar() const
if (!ImGui::IsMouseHoveringRect(left_arrow_button.Min, left_arrow_button.Max) && !ImGui::IsMouseHoveringRect(right_arrow_button.Min, right_arrow_button.Max))
wxPostEvent(m_canvas, IntEvent(EVT_GLTOOLBAR_FILLCOLOR, i + 1));
}
if (i < (int) gradient_ramps.size() && !gradient_ramps[i].empty())
ImGuiWrapper::draw_gradient_ramp(draw_list, ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), gradient_ramps[i]);
if (ImGui::IsItemHovered() && i < 9) {
if (!ImGui::IsMouseHoveringRect(left_arrow_button.Min, left_arrow_button.Max) && !ImGui::IsMouseHoveringRect(right_arrow_button.Min, right_arrow_button.Max)) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 20.0f * f_scale, 10.0f * f_scale });
@@ -9726,7 +9730,13 @@ void GLCanvas3D::_render_paint_toolbar() const
const float text_offset_y = 4.0f * em_unit * f_scale;
for (int i = 0; i < extruder_num; i++) {
decode_color(colors[i], rgba);
// A gradient slot's swatch shows its fade instead of the blended colour in `colors`, so the
// labels take their contrast from the colour printed at the middle of the fade they sit on.
if (i < (int) gradient_ramps.size() && !gradient_ramps[i].empty()) {
const wxColour& c = gradient_ramps[i][gradient_ramps[i].size() / 2];
rgba = ColorRGBA(c.Red(), c.Green(), c.Blue(), c.Alpha());
} else
decode_color(colors[i], rgba);
float gray = 0.299 * rgba.r_uchar() + 0.587 * rgba.g_uchar() + 0.114 * rgba.b_uchar();
ImVec4 text_color = gray < 80 ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : ImVec4(0, 0, 0, 1.0f);
@@ -9734,18 +9744,18 @@ void GLCanvas3D::_render_paint_toolbar() const
ImVec2 number_label_size = ImGui::CalcTextSize(std::to_string(i + 1).c_str());
ImGui::SetCursorPosY(cursor_y + text_offset_y);
ImGui::SetCursorPosX(spacing + i * (spacing + button_size.x) + (button_size.x - number_label_size.x) / 2);
ImGui::TextColored(text_color, std::to_string(i + 1).c_str());
ImGui::TextColored(text_color, "%s", std::to_string(i + 1).c_str());
imgui.pop_bold_font();
ImVec2 filament_first_line_label_size = ImGui::CalcTextSize(filament_text_first_line[i].c_str());
ImGui::SetCursorPosY(cursor_y + text_offset_y + number_label_size.y);
ImGui::SetCursorPosX(spacing + i * (spacing + button_size.x) + (button_size.x - filament_first_line_label_size.x) / 2);
ImGui::TextColored(text_color, filament_text_first_line[i].c_str());
ImGui::TextColored(text_color, "%s", filament_text_first_line[i].c_str());
ImVec2 filament_second_line_label_size = ImGui::CalcTextSize(filament_text_second_line[i].c_str());
ImGui::SetCursorPosY(cursor_y + text_offset_y + number_label_size.y + filament_first_line_label_size.y);
ImGui::SetCursorPosX(spacing + i * (spacing + button_size.x) + (button_size.x - filament_second_line_label_size.x) / 2);
ImGui::TextColored(text_color, filament_text_second_line[i].c_str());
ImGui::TextColored(text_color, "%s", filament_text_second_line[i].c_str());
}
if (ImGui::GetWindowWidth() == constraint_window_width) {
@@ -9972,9 +9982,9 @@ void GLCanvas3D::_render_assemble_info() const
double size1 = m_selection.get_bounding_box().size()(1);
double size2 = m_selection.get_bounding_box().size()(2);
if (!m_selection.is_empty()) {
ImGui::Text(_L("Volume:").ToUTF8()); ImGui::SameLine(caption_max);
ImGui::Text("%s", _L("Volume:").ToUTF8().data()); ImGui::SameLine(caption_max);
ImGui::Text("%.2f", size0 * size1 * size2);
ImGui::Text(_L("Size:").ToUTF8()); ImGui::SameLine(caption_max);
ImGui::Text("%s", _L("Size:").ToUTF8().data()); ImGui::SameLine(caption_max);
ImGui::Text("%.2f x %.2f x %.2f", size0, size1, size2);
}
imgui->end();
@@ -10570,6 +10580,9 @@ void GLCanvas3D::_set_warning_notification(EWarning warning, bool state)
case EWarning::MixUsePLAAndPETG:
text = _u8L("PLA and PETG filaments detected in the mixture. Adjust parameters according to the Wiki to ensure print quality.");
break;
case EWarning::SingleExtruderMixedFilament:
text = get_single_extruder_mixed_filament_warning_text();
break;
case EWarning::PrimeTowerOutside:
text = _u8L("The prime tower extends beyond the plate boundary.");
break;
@@ -10618,6 +10631,14 @@ void GLCanvas3D::_set_warning_notification(EWarning warning, bool state)
notification_manager.close_slicing_customize_error_notification(NotificationType::BBLNozzleFilamentIncompatible, NotificationLevel::WarningNotificationLevel);
}
}
else if (warning == EWarning::SingleExtruderMixedFilament) {
// Close by type: check_single_extruder_mixed_filament_risk() clears the shared text
// buffer on every call, so a close-by-text would miss once the risk is gone.
if (state)
notification_manager.push_slicing_customize_error_notification(NotificationType::BBLSingleExtruderMixedFilamentRisk, NotificationLevel::WarningNotificationLevel, text);
else
notification_manager.close_slicing_customize_error_notification(NotificationType::BBLSingleExtruderMixedFilamentRisk, NotificationLevel::WarningNotificationLevel);
}
else {
if (state)
notification_manager.push_plater_warning_notification(text);
+3 -17
View File
@@ -391,6 +391,7 @@ class GLCanvas3D
PrimeTowerOutside,
NozzleFilamentIncompatible,
MixtureFilamentIncompatible,
SingleExtruderMixedFilament,
FlushingVolumeZero
};
@@ -655,11 +656,7 @@ public:
}
void load_arrange_settings();
ArrangeSettings& get_arrange_settings();// { return get_arrange_settings(this); }
ArrangeSettings& get_arrange_settings(PrintSequence print_seq) {
return (print_seq == PrintSequence::ByObject) ? m_arrange_settings_fff_seq_print
: m_arrange_settings_fff;
}
ArrangeSettings& get_arrange_settings();
class SequentialPrintClearance
{
@@ -1162,17 +1159,6 @@ public:
void highlight_toolbar_item(const std::string& item_name);
void highlight_gizmo(const std::string& gizmo_name);
ArrangeSettings get_arrange_settings() const {
const ArrangeSettings &settings = get_arrange_settings();
ArrangeSettings ret = settings;
if (&settings == &m_arrange_settings_fff_seq_print) {
ret.distance = std::max(ret.distance,
float(min_object_distance(*m_config)));
}
return ret;
}
// Timestamp for FPS calculation and notification fade-outs.
static int64_t timestamp_now() {
#ifdef _WIN32
@@ -1307,7 +1293,7 @@ private:
void _render_selection_sidebar_hints() { m_selection.render_sidebar_hints(m_sidebar_field, m_gizmos.get_uniform_scaling()); }
//BBS: GUI refactor: adjust main toolbar position
bool _render_orient_menu(float left, float right, float bottom, float top);
bool _render_arrange_menu(float left, float right, float bottom, float top);
void _render_arrange_menu(float left, float right, float bottom, float top);
void _render_3d_navigator();
void _update_volumes_hover_state();
+2
View File
@@ -9,6 +9,7 @@
#include "3DScene.hpp"
#include "OpenGLManager.hpp"
#include "GUI_App.hpp"
#include "GUI.hpp"
#include "GLModel.hpp"
#include <glad/gl.h>
@@ -31,6 +32,7 @@
#include "GUI_App.hpp"
#include <boost/log/trivial.hpp>
#include <wx/dcgraph.h>
#include <wx/dcmemory.h>
namespace Slic3r {
namespace GUI {
-1
View File
@@ -327,7 +327,6 @@ private:
GLTexture m_icons_texture;
bool m_icons_texture_dirty;
mutable GLTexture m_images_texture;
mutable bool m_images_texture_dirty;
BackgroundTexture m_background_texture;
GLTexture m_arrow_texture;
Layout m_layout;
+32 -233
View File
@@ -3,14 +3,24 @@
#include "libslic3r/Technologies.hpp"
#include "libslic3r/Platform.hpp"
#include "GUI_App.hpp"
#include "BindDialog.hpp"
#include "DeviceManager.hpp"
#include "HMS.hpp"
#include "PresetBundleDialog.hpp"
#include "WebUserLoginDialog.hpp"
#include "WebViewDialog.hpp"
#include "slic3r/Utils/BBLCloudServiceAgent.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "GUI_Init.hpp"
#include "GUI_ObjectList.hpp"
#include "slic3r/GUI/UserManager.hpp"
#include "slic3r/GUI/TaskManager.hpp"
#include "format.hpp"
#include "libslic3r_version.h"
#include "BuildCommit.hpp"
#include "Downloader.hpp"
#include <boost/chrono/duration.hpp>
#include <boost/locale/encoding_utf.hpp>
#include <boost/log/detail/native_typeof.hpp>
#include <libslic3r/Config.hpp>
#include <mutex>
@@ -521,10 +531,10 @@ static const FileWildcards file_wildcards_by_type[FT_SIZE] = {
/* FT_GCODE */ { L("G-code files"), { ".gcode"sv} },
#ifdef __APPLE__
/* FT_MODEL */
{L("Supported files"), {".3mf"sv, ".stl"sv, ".oltp"sv, ".stp"sv, ".step"sv, ".svg"sv, ".amf"sv, ".obj"sv, ".usd"sv, ".usda"sv, ".usdc"sv, ".usdz"sv, ".abc"sv, ".ply"sv, ".drc"sv}},
{L("Supported files"), {".3mf"sv, ".stl"sv, ".oltp"sv, ".stp"sv, ".step"sv, ".svg"sv, ".amf"sv, ".obj"sv, ".gltf"sv, ".glb"sv, ".fbx"sv, ".usd"sv, ".usda"sv, ".usdc"sv, ".usdz"sv, ".abc"sv, ".ply"sv, ".drc"sv}},
#else
/* FT_MODEL */
{L("Supported files"), {".3mf"sv, ".stl"sv, ".oltp"sv, ".stp"sv, ".step"sv, ".svg"sv, ".amf"sv, ".obj"sv, ".drc"sv}},
{L("Supported files"), {".3mf"sv, ".stl"sv, ".oltp"sv, ".stp"sv, ".step"sv, ".svg"sv, ".amf"sv, ".obj"sv, ".gltf"sv, ".glb"sv, ".fbx"sv, ".drc"sv}},
#endif
/* FT_ZIP */ { L("ZIP files"), { ".zip"sv } },
/* FT_PROJECT */ { L("Project files"), { ".3mf"sv} },
@@ -596,7 +606,7 @@ wxString file_wildcards(FileType file_type, const std::string &custom_extension)
static std::string libslic3r_translate_callback(const char *s) { return wxGetTranslation(wxString(s, wxConvUTF8)).utf8_str().data(); }
#ifdef WIN32
static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2, 0xF16F, 0x11CF, 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 };
static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } };
static void register_win32_device_notification_event()
{
@@ -2580,7 +2590,7 @@ void GUI_App::init_app_config()
set_log_path_and_level(log_filename, 3);
#endif
BOOST_LOG_TRIVIAL(info) << boost::format("gui mode, Current OrcaSlicer Version %1% build %2%") % SoftFever_VERSION % GIT_COMMIT_HASH;
BOOST_LOG_TRIVIAL(info) << boost::format("gui mode, Current OrcaSlicer Version %1% build %2%") % SoftFever_VERSION % build_commit_label;
//BBS: remove GCodeViewer as seperate APP logic
if (!app_config)
@@ -2641,7 +2651,7 @@ std::string GUI_App::get_bbl_client_version()
void GUI_App::on_start_subscribe_again(std::string dev_id)
{
auto start_subscribe_timer = new wxTimer(this, wxID_ANY);
Bind(wxEVT_TIMER, [this, start_subscribe_timer, dev_id](auto& e) {
Bind(wxEVT_TIMER, [start_subscribe_timer, dev_id](auto& e) {
start_subscribe_timer->Stop();
Slic3r::DeviceManager* dev = Slic3r::GUI::wxGetApp().getDeviceManager();
if (!dev) return;
@@ -3231,7 +3241,7 @@ bool GUI_App::on_init_inner()
}
});
Bind(EVT_SHOW_NO_NEW_VERSION, [this](const wxCommandEvent& evt) {
Bind(EVT_SHOW_NO_NEW_VERSION, [](const wxCommandEvent& evt) {
wxString msg = _L("This is the newest version.");
InfoDialog dlg(nullptr, _L("Info"), msg);
dlg.ShowModal();
@@ -5256,7 +5266,7 @@ std::string GUI_App::handle_web_request(std::string cmd)
}
}
else if (command_str.compare("begin_network_plugin_download") == 0) {
CallAfter([this] { wxGetApp().ShowDownNetPluginDlg(); });
CallAfter([] { wxGetApp().ShowDownNetPluginDlg(); });
}
else if (command_str.compare("get_web_shortcut") == 0) {
if (root.get_child_optional("key_event") != boost::none) {
@@ -6806,7 +6816,7 @@ bool GUI_App::check_preset_parent_available(const std::pair<std::string, std::ma
void GUI_App::add_pending_vendor_preset(const std::pair<std::string, std::map<std::string, std::string>>& preset_data)
{
Preset::Type type;
Preset::Type type = Preset::Type::TYPE_INVALID;
if (preset_data.second.at(BBL_JSON_KEY_TYPE) == PRESET_IOT_PRINT_TYPE)
type = Preset::Type::TYPE_PRINT;
else if (preset_data.second.at(BBL_JSON_KEY_TYPE) == PRESET_IOT_PRINTER_TYPE)
@@ -7767,21 +7777,6 @@ void GUI_App::stop_http_server()
m_http_server.stop();
}
void GUI_App::switch_staff_pick(bool on)
{
mainframe->m_webview->SendDesignStaffpick(on);
}
bool GUI_App::switch_language()
{
if (select_language()) {
recreate_GUI(_L("Switching application language") + dots);
return true;
} else {
return false;
}
}
#ifdef __linux__
static const wxLanguageInfo* linux_get_existing_locale_language(const wxLanguageInfo* language,
const wxLanguageInfo* system_language)
@@ -7876,72 +7871,6 @@ int GUI_App::GetSingleChoiceIndex(const wxString& message,
#endif
}
// select language from the list of installed languages
bool GUI_App::select_language()
{
wxArrayString translations = wxTranslations::Get()->GetAvailableTranslations(SLIC3R_APP_KEY);
std::vector<const wxLanguageInfo*> language_infos;
language_infos.emplace_back(wxLocale::GetLanguageInfo(wxLANGUAGE_ENGLISH));
for (size_t i = 0; i < translations.GetCount(); ++ i) {
const wxLanguageInfo *langinfo = wxLocale::FindLanguageInfo(translations[i]);
if (langinfo != nullptr)
language_infos.emplace_back(langinfo);
}
sort_remove_duplicates(language_infos);
std::sort(language_infos.begin(), language_infos.end(), [](const wxLanguageInfo* l, const wxLanguageInfo* r) { return l->Description < r->Description; });
wxArrayString names;
names.Alloc(language_infos.size());
// Some valid language should be selected since the application start up.
const wxString active_language_code = current_language_code();
const wxLanguageInfo* active_language_info = wxLocale::FindLanguageInfo(active_language_code);
const wxLanguage current_language = active_language_info != nullptr ? wxLanguage(active_language_info->Language) : wxLanguage(m_wxLocale->GetLanguage());
const wxString active_lang_prefix = active_language_code.BeforeFirst('_');
int init_selection = -1;
int init_selection_alt = -1;
int init_selection_default = -1;
for (size_t i = 0; i < language_infos.size(); ++ i) {
if (wxLanguage(language_infos[i]->Language) == current_language)
// The dictionary matches the active language and country.
init_selection = i;
else if ((language_infos[i]->CanonicalName.BeforeFirst('_') == active_lang_prefix) ||
// if the active language is Slovak, mark the Czech language as active.
(language_infos[i]->CanonicalName.BeforeFirst('_') == "cs" && active_lang_prefix == "sk"))
// The dictionary matches the active language, it does not necessarily match the country.
init_selection_alt = i;
if (language_infos[i]->CanonicalName.BeforeFirst('_') == "en")
// This will be the default selection if the active language does not match any dictionary.
init_selection_default = i;
names.Add(language_infos[i]->Description);
}
if (init_selection == -1)
// This is the dictionary matching the active language.
init_selection = init_selection_alt;
if (init_selection != -1)
// This is the language to highlight in the choice dialog initially.
init_selection_default = init_selection;
const long index = GetSingleChoiceIndex(_L("Select the language"), _L("Language"), names, init_selection_default);
// Try to load a new language.
if (index != -1 && (init_selection == -1 || init_selection != index)) {
const wxLanguageInfo *new_language_info = language_infos[index];
if (this->load_language(new_language_info->CanonicalName, false)) {
// Save language at application config.
// Which language to save as the selected dictionary language?
// 1) Hopefully the language set to wxTranslations by this->load_language(), but that API is weird and we don't want to rely on its
// stability in the future:
// wxTranslations::Get()->GetBestTranslation(SLIC3R_APP_KEY, wxLANGUAGE_ENGLISH);
// 2) Current locale language may not match the dictionary name, see GH issue #3901
// m_wxLocale->GetCanonicalName()
// 3) new_language_info->CanonicalName is a safe bet. It points to a valid dictionary name.
app_config->set("language", new_language_info->CanonicalName.ToUTF8().data());
return true;
}
}
return false;
}
// Load gettext translation files and activate them at the start of the application,
// based on the "language" key stored in the application config.
@@ -8297,7 +8226,7 @@ bool GUI_App::show_modal_ip_address_enter_dialog(bool input_sn, wxString title)
dlg.set_machine_obj(obj);
if (!title.empty()) dlg.update_title(title);
dlg.Bind(EVT_ENTER_IP_ADDRESS, [this, obj](wxCommandEvent& e) {
dlg.Bind(EVT_ENTER_IP_ADDRESS, [obj](wxCommandEvent& e) {
auto selection_data_arr = wxSplit(e.GetString().ToStdString(), '|');
if (selection_data_arr.size() == 2) {
@@ -8328,146 +8257,6 @@ void GUI_App::show_ip_address_enter_dialog_handler(wxCommandEvent& evt)
show_modal_ip_address_enter_dialog(mode == -1?false:true, title);
}
//void GUI_App::add_config_menu(wxMenuBar *menu)
//void GUI_App::add_config_menu(wxMenu *menu)
//{
// auto local_menu = new wxMenu();
// wxWindowID config_id_base = wxWindow::NewControlId(int(ConfigMenuCnt));
//
// const auto config_wizard_name = _(ConfigWizard::name(true));
// const auto config_wizard_tooltip = from_u8((boost::format(_utf8(L("Open %s"))) % config_wizard_name).str());
// // Cmd+, is standard on OS X - what about other operating systems?
// if (is_editor()) {
// local_menu->Append(config_id_base + ConfigMenuWizard, config_wizard_name + dots, config_wizard_tooltip);
// local_menu->Append(config_id_base + ConfigMenuUpdate, _L("Check for Configuration Updates"), _L("Check for configuration updates"));
// local_menu->AppendSeparator();
// }
// local_menu->Append(config_id_base + ConfigMenuPreferences, _L("Preferences") + dots +
//#ifdef __APPLE__
// "\tCtrl+,",
//#else
// "\tCtrl+P",
//#endif
// _L("Application preferences"));
// wxMenu* mode_menu = nullptr;
// if (is_editor()) {
// local_menu->AppendSeparator();
// mode_menu = new wxMenu();
// mode_menu->AppendRadioItem(config_id_base + ConfigMenuModeSimple, _L("Simple"), _L("Simple Mode"));
// mode_menu->AppendRadioItem(config_id_base + ConfigMenuModeAdvanced, _L("Advanced"), _L("Advanced Mode"));
// Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent& evt) { if (get_mode() == comSimple) evt.Check(true); }, config_id_base + ConfigMenuModeSimple);
// Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent& evt) { if (get_mode() == comAdvanced) evt.Check(true); }, config_id_base + ConfigMenuModeAdvanced);
//
// local_menu->AppendSubMenu(mode_menu, _L("Mode"), wxString::Format(_L("%s Mode"), SLIC3R_APP_NAME));
// }
// local_menu->AppendSeparator();
// local_menu->Append(config_id_base + ConfigMenuLanguage, _L("Language"));
// if (is_editor()) {
// local_menu->AppendSeparator();
// }
//
// local_menu->Bind(wxEVT_MENU, [this, config_id_base](wxEvent &event) {
// switch (event.GetId() - config_id_base) {
// case ConfigMenuWizard:
// run_wizard(ConfigWizard::RR_USER);
// break;
// case ConfigMenuUpdate:
// check_updates(true);
// break;
//#ifdef __linux__
// case ConfigMenuDesktopIntegration:
// show_desktop_integration_dialog();
// break;
//#endif
// case ConfigMenuSnapshots:
// //BBS do not support task snapshot
// break;
// case ConfigMenuPreferences:
// {
// //BBS GUI refactor: remove unuse layout logic
// //bool app_layout_changed = false;
// {
// // the dialog needs to be destroyed before the call to recreate_GUI()
// // or sometimes the application crashes into wxDialogBase() destructor
// // so we put it into an inner scope
// PreferencesDialog dlg(mainframe);
// dlg.ShowModal();
// //BBS GUI refactor: remove unuse layout logic
// //app_layout_changed = dlg.settings_layout_changed();
// if (dlg.seq_top_layer_only_changed())
// this->plater_->refresh_print();
//
// if (dlg.recreate_GUI()) {
// recreate_GUI(_L("Restart application") + dots);
// return;
// }
//#ifdef _WIN32
// if (is_editor()) {
// if (app_config->get("associate_3mf") == "true")
// associate_3mf_files();
// if (app_config->get("associate_stl") == "true")
// associate_stl_files();
// }
// else {
// if (app_config->get("associate_gcode") == "true")
// associate_gcode_files();
// }
//#endif // _WIN32
// }
// //BBS GUI refactor: remove unuse layout logic
// /*if (app_layout_changed) {
// // hide full main_sizer for mainFrame
// mainframe->GetSizer()->Show(false);
// mainframe->update_layout();
// mainframe->select_tab(size_t(0));
// }*/
// break;
// }
// case ConfigMenuLanguage:
// {
// /* Before change application language, let's check unsaved changes on 3D-Scene
// * and draw user's attention to the application restarting after a language change
// */
// {
// // the dialog needs to be destroyed before the call to switch_language()
// // or sometimes the application crashes into wxDialogBase() destructor
// // so we put it into an inner scope
// wxString title = is_editor() ? wxString(SLIC3R_APP_NAME) : wxString(GCODEVIEWER_APP_NAME);
// title += " - " + _L("Choose language");
// //wxMessageDialog dialog(nullptr,
// MessageDialog dialog(nullptr,
// _L("Switching the language requires application restart.\n") + "\n\n" +
// _L("Do you want to continue?"),
// title,
// wxICON_QUESTION | wxOK | wxCANCEL);
// if (dialog.ShowModal() == wxID_CANCEL)
// return;
// }
//
// switch_language();
// break;
// }
// case ConfigMenuFlashFirmware:
// //BBS FirmwareDialog::run(mainframe);
// break;
// default:
// break;
// }
// });
//
// using std::placeholders::_1;
//
// if (mode_menu != nullptr) {
// auto modfn = [this](int mode, wxCommandEvent&) { if (get_mode() != mode) save_mode(mode); };
// mode_menu->Bind(wxEVT_MENU, std::bind(modfn, comSimple, _1), config_id_base + ConfigMenuModeSimple);
// mode_menu->Bind(wxEVT_MENU, std::bind(modfn, comAdvanced, _1), config_id_base + ConfigMenuModeAdvanced);
// }
//
// // BBS
// //menu->Append(local_menu, _L("Configuration"));
// menu->AppendSubMenu(local_menu, _L("Configuration"));
//}
void GUI_App::open_presetbundledialog(size_t open_on_tab, const std::string& highlight_option)
{
bool app_layout_changed = false;
@@ -8777,7 +8566,7 @@ bool GUI_App::check_and_keep_current_preset_changes(const wxString& caption, con
if (!no_need_change && dlg.ShowModal() == wxID_CANCEL)
return false;
auto reset_modifications = [this, is_called_from_configwizard]() {
auto reset_modifications = [this]() {
//if (is_called_from_configwizard)
// return; // no need to discared changes. It will be done fromConfigWizard closing
@@ -8905,7 +8694,17 @@ void GUI_App::load_current_presets(bool active_preset_combox/*= false*/, bool ch
if (printer_technology == ptFFF && !edited_printer_preset.config.opt_bool("single_extruder_multi_material")) {
auto* nozzle_diameter = edited_printer_preset.config.option<ConfigOptionFloats>("nozzle_diameter");
if (nozzle_diameter) {
preset_bundle->set_num_filaments(nozzle_diameter->values.size());
// Mixed-color slots are virtual filaments kept at the tail of the list, so they have no
// nozzle of their own and the count has to allow for them. Only ever grow: this sizes
// the list so the combo boxes have something to bind to, and set_num_filaments() trims
// at the raw tail, so shrinking here would eat the mixes rather than the surplus
// physical slots. A list longer than the nozzle count is a state the app reaches
// legitimately - raising the extruder count and not saving the printer preset leaves
// exactly that on the next start - and losing the project's mixes to it is worse than
// carrying a filament the printer has no nozzle for until the count is next changed.
const size_t target = nozzle_diameter->values.size() + preset_bundle->num_mixed_filaments();
if (target > preset_bundle->filament_presets.size())
preset_bundle->set_num_filaments(target);
}
}
this->plater()->set_printer_technology(printer_technology);
@@ -9406,7 +9205,7 @@ int GUI_App::filaments_cnt() const
PrintSequence GUI_App::global_print_sequence() const
{
PrintSequence global_print_seq = PrintSequence::ByDefault;
auto curr_preset_config = preset_bundle->prints.get_edited_preset().config;
const auto &curr_preset_config = preset_bundle->prints.get_edited_preset().config;
if (curr_preset_config.has("print_sequence"))
global_print_seq = curr_preset_config.option<ConfigOptionEnum<PrintSequence>>("print_sequence")->value;
return global_print_seq;
+10 -12
View File
@@ -1,23 +1,17 @@
#ifndef slic3r_GUI_App_hpp_
#define slic3r_GUI_App_hpp_
#include <functional>
#include <memory>
#include <string>
#include "ActionRegistry.hpp"
#include "ImGuiWrapper.hpp"
#include "ConfigWizard.hpp"
#include "OpenGLManager.hpp"
#include "PresetBundleDialog.hpp"
#include "libslic3r/Preset.hpp"
#include "libslic3r/PresetBundle.hpp"
#include "slic3r/GUI/DeviceManager.hpp"
#include "slic3r/GUI/UserNotification.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "slic3r/Utils/BBLCloudServiceAgent.hpp"
#include "slic3r/GUI/WebViewDialog.hpp"
#include "slic3r/GUI/WebUserLoginDialog.hpp"
#include "slic3r/GUI/BindDialog.hpp"
#include "slic3r/GUI/HMS.hpp"
#include "slic3r/Utils/CloudProvider.hpp"
#include "slic3r/GUI/Jobs/UpgradeNetworkJob.hpp"
#include "slic3r/GUI/HttpServer.hpp"
#include "../Utils/PrintHost.hpp"
@@ -64,9 +58,14 @@ class ModelObject;
class Model;
class UserManager;
class DeviceManager;
class MachineObject;
class NetworkAgent;
class IPrinterAgent;
class TaskManager;
// Same typedef as in bambu_networking.hpp, so this header need not include it.
typedef std::function<bool()> WasCancelledFn;
namespace GUI{
class RemovableDriveManager;
@@ -85,6 +84,8 @@ class ParamsDialog;
class HMSQuery;
class ModelMallDialog;
class PingCodeBindDialog;
class PresetBundleDialog;
class ZUserLogin;
class NetworkErrorDialog;
class PluginsDialog;
class SpeedDialWebDialog;
@@ -569,7 +570,6 @@ public:
void start_http_server(const std::string& provider = ORCA_CLOUD_PROVIDER);
void start_http_server(int port, const std::string& provider = ORCA_CLOUD_PROVIDER);
void stop_http_server();
void switch_staff_pick(bool on);
void on_show_check_privacy_dlg(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER);
void show_check_privacy_dlg(wxCommandEvent& evt);
@@ -583,7 +583,6 @@ public:
void persist_window_geometry(wxTopLevelWindow *window, bool default_maximized = false);
void update_ui_from_settings();
bool switch_language();
bool load_language(wxString language, bool initial);
Tab* get_tab(Preset::Type type);
@@ -801,7 +800,6 @@ private:
bool window_pos_restore(wxTopLevelWindow* window, const std::string &name, bool default_maximized = false);
void window_pos_sanitize(wxTopLevelWindow* window);
void window_pos_center(wxTopLevelWindow *window);
bool select_language();
// Dynamic printer agent selection - internal helpers for switch_printer_agent
// and the plugin load/unload callbacks (init_plugin_gui_wiring).
@@ -832,7 +830,7 @@ wxDECLARE_EVENT(EVT_UPDATE_BUNDLE_COMPLETE, wxCommandEvent);
bool is_support_filament(int extruder_id, bool strict_check = true);
bool is_soluble_filament(int extruder_id);
// check if the filament for model is in the list
bool has_filaments(const std::vector<string>& model_filaments);
bool has_filaments(const std::vector<std::string>& model_filaments);
} // namespace GUI
} // Slic3r
+1 -1
View File
@@ -217,7 +217,7 @@ void AuxiliaryList::on_context_menu(wxDataViewEvent& evt)
}
else {
append_menu_item(menu, wxID_ANY, _L("Open"), wxEmptyString,
[this, node](wxCommandEvent&)
[node](wxCommandEvent&)
{
wxLaunchDefaultApplication(node->path, 0);
});
+23 -37
View File
@@ -1392,7 +1392,7 @@ void MenuFactory::create_default_menu()
{
wxMenu* sub_menu_primitives = append_submenu_add_generic(&m_default_menu, ModelVolumeType::INVALID);
wxMenu* sub_menu_handy = append_submenu_add_handy_model(&m_default_menu, ModelVolumeType::INVALID);
#ifdef __WINDOWS__
append_submenu(&m_default_menu, sub_menu_primitives, wxID_ANY, _L("Add Primitive"), "", "menu_add_part",
[]() {return true; }, m_parent);
append_submenu(&m_default_menu, sub_menu_handy, wxID_ANY, _L("Add Handy models"), "", "menu_add_part",
@@ -1400,21 +1400,12 @@ void MenuFactory::create_default_menu()
append_menu_item(&m_default_menu, wxID_ANY, _L("Add Models"), "", // ORCA: Add Models
[](wxCommandEvent&) { plater()->add_file(); }, "menu_add_part", &m_default_menu,
[]() {return wxGetApp().plater()->can_add_model(); }, m_parent);
#else
append_submenu(&m_default_menu, sub_menu_primitives, wxID_ANY, _L("Add Primitive"), "", "",
[]() {return true; }, m_parent);
append_submenu(&m_default_menu, sub_menu_handy, wxID_ANY, _L("Add Handy models"), "", "",
[]() {return true; }, m_parent);
append_menu_item(&m_default_menu, wxID_ANY, _L("Add Models"), "", // ORCA: Add Models
[](wxCommandEvent&) { plater()->add_file(); }, "", &m_default_menu,
[]() {return wxGetApp().plater()->can_add_model(); }, m_parent);
#endif
m_default_menu.AppendSeparator();
append_menu_check_item(&m_default_menu, wxID_ANY, _L("Show Labels"), "",
[](wxCommandEvent&) { plater()->show_view3D_labels(!plater()->are_view3D_labels_shown()); plater()->get_current_canvas3D()->post_event(SimpleEvent(wxEVT_PAINT)); }, &m_default_menu,
[]() { return plater()->is_view3D_shown(); }, [this]() { return plater()->are_view3D_labels_shown(); }, m_parent);
[]() { return plater()->is_view3D_shown(); }, []() { return plater()->are_view3D_labels_shown(); }, m_parent);
}
void MenuFactory::create_common_object_menu(wxMenu* menu)
@@ -1656,16 +1647,16 @@ void MenuFactory::create_filament_action_menu(bool init, int active_filament_men
{
wxMenu *menu = &m_filament_action_menu;
if (init) {
// ORCA rebuild menu everytime instead checking existing of every item then deleting
while (menu->GetMenuItemCount() > 0)
menu->Destroy(menu->FindItemByPosition(0));
//if (init) { //
append_menu_item(
menu, wxID_ANY, _L("Edit"), "", [](wxCommandEvent&) {
plater()->sidebar().edit_filament(); }, "", nullptr,
[]() { return true; }, m_parent);
}
const int item_id = menu->FindItem(_L("Merge with"));
if (item_id != wxNOT_FOUND)
menu->Destroy(item_id);
//}
wxMenu* sub_menu = new wxMenu();
std::vector<wxBitmap*> icons = get_extruder_color_icons(true);
@@ -1684,11 +1675,15 @@ void MenuFactory::create_filament_action_menu(bool init, int active_filament_men
append_submenu(menu, sub_menu, wxID_ANY, _L("Merge with"), "", "",
[filaments_cnt]() { return filaments_cnt > 1; }, m_parent);
// Decompose a target colour into a printable mix of the loaded filaments. Placed before the
append_menu_item(
menu, wxID_ANY, _L("Decompose Color"), "", [](wxCommandEvent&) {
plater()->sidebar().decompose_filament_color(kSidebarContextMenuFilamentId); }, "", nullptr,
[]() { return plater()->sidebar().combos_filament().size() >= 2; }, m_parent);
menu->AppendSeparator(); // ORCA use seperator for reducing accidental clicks to delete
// ORCA use delete item on end of menu to prevent accidental clicks. clicking to submenus(merge) already not allowed by OS
const int delete_id = menu->FindItem(_L("Delete"));
if (delete_id != wxNOT_FOUND)
menu->Destroy(delete_id);
append_menu_item(
menu, wxID_ANY, _L("Delete"), _L("Delete this filament"), [](wxCommandEvent&) {
plater()->sidebar().delete_filament(-2); }, "", nullptr,
@@ -1785,7 +1780,6 @@ void MenuFactory::create_plate_menu()
wxMenu* sub_menu_primitives = append_submenu_add_generic(menu, ModelVolumeType::INVALID);
wxMenu* sub_menu_handy = append_submenu_add_handy_model(menu, ModelVolumeType::INVALID);
#ifdef __WINDOWS__
append_submenu(menu, sub_menu_primitives, wxID_ANY, _L("Add Primitive"), "", "menu_add_part",
[]() {return true; }, m_parent);
append_submenu(menu, sub_menu_handy, wxID_ANY, _L("Add Handy models"), "", "menu_add_part",
@@ -1793,15 +1787,7 @@ void MenuFactory::create_plate_menu()
append_menu_item(menu, wxID_ANY, _L("Add Models"), "", // ORCA: Add Models
[](wxCommandEvent&) { plater()->add_file(); }, "menu_add_part", menu,
[]() {return wxGetApp().plater()->can_add_model(); }, m_parent);
#else
append_submenu(menu, sub_menu_primitives, wxID_ANY, _L("Add Primitive"), "", "",
[]() {return true; }, m_parent);
append_submenu(menu, sub_menu_handy, wxID_ANY, _L("Add Handy models"), "", "",
[]() {return true; }, m_parent);
append_menu_item(menu, wxID_ANY, _L("Add Models"), "", // ORCA: Add Models
[](wxCommandEvent&) { plater()->add_file(); }, "", menu,
[]() {return wxGetApp().plater()->can_add_model(); }, m_parent);
#endif
append_menu_item_replace_all_with_stl(menu);
@@ -2086,7 +2072,7 @@ void MenuFactory::append_menu_item_clone(wxMenu* menu)
static const wxString ctrl = _L("Ctrl+");
#endif
append_menu_item(menu, wxID_ANY, _L("Clone") + "\t" + ctrl + "K", "",
[this](wxCommandEvent&) {
[](wxCommandEvent&) {
plater()->clone_selection();
}, "", nullptr,
[]() {
@@ -2111,7 +2097,7 @@ void MenuFactory::append_menu_item_smooth_mesh(wxMenu *menu)
void MenuFactory::append_menu_item_center(wxMenu* menu)
{
append_menu_item(menu, wxID_ANY, _L("Center") , "",
[this](wxCommandEvent&) {
[](wxCommandEvent&) {
plater()->center_selection();
}, "", nullptr,
[]() {
@@ -2130,7 +2116,7 @@ void MenuFactory::append_menu_item_center(wxMenu* menu)
void MenuFactory::append_menu_item_drop(wxMenu* menu)
{
append_menu_item(menu, wxID_ANY, _L("Drop") , "",
[this](wxCommandEvent&) {
[](wxCommandEvent&) {
plater()->drop_selection();
}, "", nullptr,
[]() {
@@ -2305,7 +2291,7 @@ void MenuFactory::append_menu_item_set_printable(wxMenu* menu)
}
}
wxMenuItem* menu_item_set_printable = append_menu_check_item(menu, wxID_ANY, _L("Printable") + "\t" + "V", "", [this, all_printable](wxCommandEvent&) {
wxMenuItem* menu_item_set_printable = append_menu_check_item(menu, wxID_ANY, _L("Printable") + "\t" + "V", "", [all_printable](wxCommandEvent&) {
Selection& selection = plater()->canvas3D()->get_selection();
selection.set_printable(!all_printable);
}, menu);
@@ -2325,7 +2311,7 @@ void MenuFactory::append_menu_item_set_auto_drop(wxMenu* menu)
wxString menu_tooltip = _L("Automatically snaps the selected object to the build plate.");
wxMenuItem* menu_item_set_auto_drop = append_menu_check_item(
menu, wxID_ANY, menu_text, menu_tooltip,
[this, current_auto_drop](wxCommandEvent&) {
[current_auto_drop](wxCommandEvent&) {
Selection& selection = plater()->canvas3D()->get_selection();
selection.set_auto_drop(!current_auto_drop);
},
@@ -2380,7 +2366,7 @@ void MenuFactory::append_menu_item_plate_name(wxMenu *menu)
auto item = append_menu_item(
menu, wxID_ANY, name, "",
[plate](wxCommandEvent &e) {
[](wxCommandEvent &e) {
int hover_idx =plater()->canvas3D()->GetHoverId();
if (hover_idx == -1) {
int plate_idx=plater()->GetPlateIndexByRightMenuInLeftUI();
+2 -2
View File
@@ -48,7 +48,7 @@ void ObjectLayers::select_editor(LayerRangeEditor* editor, const bool is_last_ed
* And as a result we couldn't edit this control.
* */
#ifdef __WXOSX__
wxTheApp->CallAfter([editor]() {
wxTheApp->CallAfter([]() {
#endif
//editor->SetFocus();
//editor->SelectAll();
@@ -223,7 +223,7 @@ void ObjectLayers::update_layers_list()
// only call sizer->Clear(true) via CallAfter, otherwise crash happens in Linux when press enter in Height Range
// because an element cannot be destroyed while there are pending events for this element.(https://github.com/wxWidgets/Phoenix/issues/1854)
wxGetApp().CallAfter([this, type, objects_ctrl, range]() {
wxGetApp().CallAfter([this, type, range]() {
m_og->ctrl_parent()->Freeze();
// Delete all controls from options group

Some files were not shown because too many files have changed in this diff Show More