diff --git a/src/libslic3r/PresetBundle.cpp b/src/libslic3r/PresetBundle.cpp index eb8321e4bd..4ba991e00e 100644 --- a/src/libslic3r/PresetBundle.cpp +++ b/src/libslic3r/PresetBundle.cpp @@ -3893,42 +3893,58 @@ unsigned int PresetBundle::sync_ams_list(std::vector= 0; j--) { - if (maps[j].slot_id == slot_id && maps[j].ams_id == ams_id) { - maps.erase(j); + // A tray written by the printer UI carries a material type but no + // OrcaSlicer preset id. Resolve it to the matching Generic preset with + // the tray's own color instead of dropping it (direct sync) or forcing + // "Generic PLA" (mapping sync). Placeholders and typeless trays keep + // the previous behavior. + const auto tray_type = ams.opt_string("filament_type", 0u); + if (is_placeholder || tray_type.empty()) { + if (use_map) { + for (int j = maps.size() - 1; j >= 0; j--) { + if (maps[j].slot_id == slot_id && maps[j].ams_id == ams_id) { + maps.erase(j); + } } + ams_filament_presets.push_back("Generic PLA");//for unknow matieral + auto default_unknown_color = "#CECECE"; + ams_filament_colors.push_back(default_unknown_color); + ams_filament_color_types.push_back("1"); + if (filament_multi_color.size() == 0) { + filament_multi_color.push_back(default_unknown_color); + } + ams_multi_color_filment.push_back(filament_multi_color); + } else if (is_placeholder) { + // Orca: push placeholders to keep index alignment with ams_infos + ams_filament_presets.push_back(""); + ams_filament_colors.push_back(""); + ams_filament_color_types.push_back(""); + ams_multi_color_filment.push_back({}); } - ams_filament_presets.push_back("Generic PLA");//for unknow matieral - auto default_unknown_color = "#CECECE"; - ams_filament_colors.push_back(default_unknown_color); - ams_filament_color_types.push_back("1"); - if (filament_multi_color.size() == 0) { - filament_multi_color.push_back(default_unknown_color); - } - ams_multi_color_filment.push_back(filament_multi_color); - } else if (is_placeholder) { - // Orca: push placeholders to keep index alignment with ams_infos - ams_filament_presets.push_back(""); - ams_filament_colors.push_back(""); - ams_filament_color_types.push_back(""); - ams_multi_color_filment.push_back({}); + continue; } - continue; } if (!filament_changed && this->filament_presets.size() > ams_filament_presets.size()) { ams_filament_presets.push_back(this->filament_presets[ams_filament_presets.size()]); ams_filament_colors.push_back(filament_color); ams_filament_color_types.push_back(filament_color_type); ams_multi_color_filment.push_back(filament_multi_color); + ams_infos.back().valid = true; continue; } bool has_type = false; auto filament_type = ams.opt_string("filament_type", 0u); - auto iter = std::find_if(filaments.begin(), filaments.end(), [this, &filament_id, &has_type, filament_type](auto &f) { - has_type |= f.config.opt_string("filament_type", 0u) == filament_type; - return f.is_compatible && filaments.get_preset_base(f) == &f && f.filament_id == filament_id; }); - warn_ambiguous_filament_id_match(filaments, iter, filament_id); + auto iter = filaments.end(); + if (!filament_id.empty()) { + iter = std::find_if(filaments.begin(), filaments.end(), [this, &filament_id, &has_type, filament_type](auto &f) { + has_type |= f.config.opt_string("filament_type", 0u) == filament_type; + return f.is_compatible && filaments.get_preset_base(f) == &f && f.filament_id == filament_id; }); + warn_ambiguous_filament_id_match(filaments, iter, filament_id); + } else { + // The material type is the only identity a printer-set tray carries. + has_type = std::any_of(filaments.begin(), filaments.end(), [&filament_type](auto &f) { + return f.is_compatible && f.config.opt_string("filament_type", 0u) == filament_type; }); + } if (iter == filaments.end()) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": filament_id %1% not found or system or compatible") % filament_id; if (!filament_type.empty()) { @@ -3975,6 +3991,7 @@ unsigned int PresetBundle::sync_ams_list(std::vector> PresetBundle::get_extruder_filament return filament_infos; } -// ORCA TODO: currently, this function assumes the printer name follows the pattern of " ", e.g. -// printer_type: "Bambu Lab X2D", nozzle_diameter_str: "0.4 nozzle" => printer_name: "Bambu Lab X2D 0.4 nozzle". If the printer name does -// not follow this pattern, the function may not work correctly. +std::string PresetBundle::get_printer_model_display_name(const std::string &model_id) const +{ + if (model_id.empty()) + return {}; + for (const auto &vendor_entry : vendors) { + for (const auto &model : vendor_entry.second.models) { + if (model.model_id == model_id) + return model.name; + } + } + return {}; +} + +// ORCA TODO: this assumes printer names follow " ", e.g. +// "Bambu Lab X2D 0.4 nozzle". Other naming schemes may not resolve correctly. std::set PresetBundle::get_printer_names_by_printer_type_and_nozzle(const std::string &printer_type, std::string nozzle_diameter_str, bool system_only) { std::set printer_names; @@ -4464,7 +4494,9 @@ std::set PresetBundle::get_printer_names_by_printer_type_and_nozzle if (printer_it->name.find(nozzle_diameter_str) != std::string::npos) printer_names.insert(printer_it->name); } - assert(printer_names.size() == 1); + // No match is normal for a connected machine the user has not installed; only an + // ambiguous match is a bug (the caller assumes one preset per model and nozzle). + assert(printer_names.size() <= 1); for (auto& printer_name : printer_names) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " " << __LINE__ << " printer name: " << printer_name; @@ -4477,8 +4509,8 @@ std::vector PresetBundle::get_filament_presets_for_machine(const std:: const std::string &nozzle_diameter_str, bool include_user_presets) { - // Printer model plus nozzle diameter is expected to resolve to a single system printer preset; - // get_printer_names_by_printer_type_and_nozzle asserts as much in debug builds. + // Printer model plus nozzle diameter normally resolves to a single system printer preset. + // Zero matches is normal for a connected machine the user never installed. const std::set printer_names = get_printer_names_by_printer_type_and_nozzle(printer_type, nozzle_diameter_str); const Preset *printer = printer_names.empty() ? nullptr : printers.find_preset(*printer_names.begin()); if (printer == nullptr) diff --git a/src/libslic3r/PresetBundle.hpp b/src/libslic3r/PresetBundle.hpp index 797602922b..e7a7e183d4 100644 --- a/src/libslic3r/PresetBundle.hpp +++ b/src/libslic3r/PresetBundle.hpp @@ -411,6 +411,9 @@ public: std::vector> get_extruder_filament_info() const; + // Resolve a vendor model id (an agent-reported machine identity) to the display name + // printer profiles use as printer_model. Empty when no loaded vendor declares it. + std::string get_printer_model_display_name(const std::string &model_id) const; std::set get_printer_names_by_printer_type_and_nozzle(const std::string &printer_type, std::string nozzle_diameter_str, bool system_only = true); // Orca: the root filament presets a connected machine can use, resolved with the rule the rest // of the app applies (is_compatible_with_printer): an empty compatible_printers means every diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index d1227b930b..fcde9aa9aa 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -366,6 +366,10 @@ set(SLIC3R_GUI_SOURCES GUI/MarkdownTip.hpp GUI/MediaFilePanel.cpp GUI/MediaFilePanel.h + GUI/OrcaFilesPanel.cpp + GUI/OrcaFilesPanel.h + GUI/StoragePanel.cpp + GUI/StoragePanel.h GUI/MediaPlayCtrl.cpp GUI/MediaPlayCtrl.h GUI/WebRtcMediaController.cpp @@ -455,6 +459,11 @@ set(SLIC3R_GUI_SOURCES GUI/PresetHints.hpp GUI/PrinterCloudAuthDialog.cpp GUI/PrinterCloudAuthDialog.hpp + GUI/Printer/BambuFileGridModel.cpp + GUI/Printer/BambuFileGridModel.h + GUI/Printer/IFileGridModel.h + GUI/Printer/RemoteFileGridModel.cpp + GUI/Printer/RemoteFileGridModel.h GUI/Printer/PrinterFileSystem.cpp GUI/Printer/PrinterFileSystem.h GUI/PrinterWebView.cpp diff --git a/src/slic3r/GUI/AMSDryControl.cpp b/src/slic3r/GUI/AMSDryControl.cpp index a45a5fb4fd..bdabd31f1d 100644 --- a/src/slic3r/GUI/AMSDryControl.cpp +++ b/src/slic3r/GUI/AMSDryControl.cpp @@ -7,6 +7,7 @@ #include "slic3r/GUI/DeviceCore/DevExtruderSystem.h" #include "slic3r/GUI/DeviceCore/DevManager.h" +#include "slic3r/GUI/DeviceManager.hpp" #include "slic3r/GUI/MsgDialog.hpp" @@ -1633,8 +1634,16 @@ 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(); + // The connected device's model may not resolve (OrcaSonar's is optional); the + // helper falls back to the selected profile so the list is never empty. + const std::string filament_printer_model = resolve_filament_printer_model(obj->printer_type, preset_bundle); + if (filament_printer_model.empty()) { + BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " cannot resolve a printer model for the filament list"; + return false; + } + 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)) { + filament_printer_model, 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); diff --git a/src/slic3r/GUI/AMSMaterialsSetting.cpp b/src/slic3r/GUI/AMSMaterialsSetting.cpp index 66e87ac3af..d8bacb5e38 100644 --- a/src/slic3r/GUI/AMSMaterialsSetting.cpp +++ b/src/slic3r/GUI/AMSMaterialsSetting.cpp @@ -472,6 +472,11 @@ void AMSMaterialsSetting::update_filament_editing(bool is_printing) m_button_confirm->Show(true); } + // A third-party tray owns its temp range; BBL RFID trays keep the read-only preset values. + const bool can_edit = !is_printing || obj->is_support_filament_setting_inprinting; + m_input_nozzle_min->Enable(m_is_third && can_edit); + m_input_nozzle_max->Enable(m_is_third && can_edit); + if (!m_is_third) { m_tip_readonly->SetLabelText(wxEmptyString); m_tip_readonly->Hide(); @@ -494,6 +499,8 @@ void AMSMaterialsSetting::update_filament_editing(bool is_printing) if (m_view_only) { // Orca: view-only (2D laser/cut) — lock every edit control and hide apply/reset m_comboBox_filament->Enable(false); m_comboBox_cali_result->Enable(false); + m_input_nozzle_min->Enable(false); + m_input_nozzle_max->Enable(false); m_input_k_val->Enable(false); m_input_n_val->Enable(false); m_button_confirm->Hide(); @@ -543,7 +550,7 @@ void AMSMaterialsSetting::on_select_reset(wxCommandEvent& event) { } // set k / n value - if (obj->cali_version <= -1 && obj->get_printer_series() == PrinterSeries::SERIES_P1P) { + if (obj->supports_extrusion_cali() && obj->cali_version <= -1 && obj->get_printer_series() == PrinterSeries::SERIES_P1P) { // set extrusion cali ratio int cali_tray_id = ams_id * 4 + slot_id; @@ -564,7 +571,7 @@ void AMSMaterialsSetting::on_select_reset(wxCommandEvent& event) { } obj->command_extrusion_cali_set(cali_tray_id, "", "", k, n); } - else { + else if (obj->supports_extrusion_cali()) { PACalibIndexInfo select_index_info; int tray_id = ams_id * 4 + slot_id; if (is_virtual_tray()) { @@ -746,7 +753,7 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event) wxString k_text = m_input_k_val->GetTextCtrl()->GetValue(); wxString n_text = m_input_n_val->GetTextCtrl()->GetValue(); - if (obj->cali_version <= -1 && (obj->get_printer_series() != PrinterSeries::SERIES_X1) && !ExtrusionCalibration::check_k_validation(k_text)) { + if (obj->supports_extrusion_cali() && obj->cali_version <= -1 && (obj->get_printer_series() != PrinterSeries::SERIES_X1) && !ExtrusionCalibration::check_k_validation(k_text)) { wxString k_tips = wxString::Format(_L("Please input a valid value (K in %.1f~%.1f)"), MIN_PA_K_VALUE, MAX_PA_K_VALUE); wxString kn_tips = wxString::Format(_L("Please input a valid value (K in %.1f~%.1f, N in %.1f~%.1f)"), MIN_PA_K_VALUE, MAX_PA_K_VALUE, 0.6, 2.0); MessageDialog msg_dlg(nullptr, k_tips, wxEmptyString, wxICON_WARNING | wxOK); @@ -776,7 +783,7 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event) vt_tray = VIRTUAL_TRAY_DEPUTY_ID; } - if (obj->cali_version >= 0) { + if (obj->supports_extrusion_cali() && obj->cali_version >= 0) { PACalibIndexInfo select_index_info; select_index_info.tray_id = vt_tray; select_index_info.ams_id = ams_id; @@ -795,7 +802,7 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event) CalibUtils::select_PA_calib_result(select_index_info); } - else { + else if (obj->supports_extrusion_cali()) { obj->command_extrusion_cali_set(vt_tray, "", "", k, n); } } @@ -817,7 +824,7 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event) ; } - if (obj->cali_version >= 0) { + if (obj->supports_extrusion_cali() && obj->cali_version >= 0) { PACalibIndexInfo select_index_info; select_index_info.tray_id = cali_tray_id; select_index_info.ams_id = ams_id; @@ -836,7 +843,7 @@ void AMSMaterialsSetting::on_select_ok(wxCommandEvent &event) CalibUtils::select_PA_calib_result(select_index_info); } - else { + else if (obj->supports_extrusion_cali()) { obj->command_extrusion_cali_set(cali_tray_id, "", "", k, n); } } @@ -932,7 +939,12 @@ bool AMSMaterialsSetting::is_virtual_tray() void AMSMaterialsSetting::update_widgets() { - if (obj && obj->get_printer_series() == PrinterSeries::SERIES_X1 && obj->cali_version <= -1) { + if (obj && !obj->supports_extrusion_cali()) { + // No printer-side K/N records: do not offer them. + m_panel_normal->Show(); + m_panel_kn->Hide(); + } + else if (obj && obj->get_printer_series() == PrinterSeries::SERIES_X1 && obj->cali_version <= -1) { // Low version firmware does not display k value m_panel_kn->Hide(); } @@ -993,6 +1005,9 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi m_input_k_val->GetTextCtrl()->SetValue(k); m_input_n_val->GetTextCtrl()->SetValue(n); + // Tray values are re-supplied by every caller; clear so a previous popup cannot leak in. + m_input_nozzle_min->GetTextCtrl()->SetValue(wxEmptyString); + m_input_nozzle_max->GetTextCtrl()->SetValue(wxEmptyString); wxArrayString filament_items; wxString bambu_filament_name; @@ -1016,11 +1031,14 @@ 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(); + // OrcaSonar's model id is optional, so the device model alone can resolve to nothing; + // the helper falls back to the selected profile so the dropdown is never empty. + const std::string filament_printer_model = resolve_filament_printer_model(obj->printer_type, preset_bundle); - if (preset_bundle) { + if (preset_bundle && !filament_printer_model.empty()) { BOOST_LOG_TRIVIAL(trace) << "system_preset_bundle filament number=" << preset_bundle->filaments.size(); 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)) { + filament_printer_model, 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); @@ -1087,6 +1105,12 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi else { m_comboBox_filament->Show(); m_readonly_filament->Hide(); + // A printer-set tray carries its own temps; the preset selection only fills + // them when the tray has none. + if (!temp_min.IsEmpty() && temp_min != "0") + m_input_nozzle_min->GetTextCtrl()->SetValue(temp_min); + if (!temp_max.IsEmpty() && temp_max != "0") + m_input_nozzle_max->GetTextCtrl()->SetValue(temp_max); } if (obj->cali_version >= 0) { @@ -1223,7 +1247,12 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi } } + if (filament_items.IsEmpty()) + BOOST_LOG_TRIVIAL(warning) << "ams_materials_setting: no filament presets for printer model \"" + << filament_printer_model << "\" at nozzle " << nozzle_diameter_str; + m_comboBox_filament->Set(filament_items); + m_comboBox_from_printer = true; m_comboBox_filament->SetSelection(selection_idx); post_select_event(selection_idx); @@ -1231,9 +1260,6 @@ void AMSMaterialsSetting::Popup(wxString filament, wxString sn, wxString temp_mi m_comboBox_filament->SetValue(wxEmptyString); } - // Set the flag whether to open the filament setting dialog from the device page - m_comboBox_filament->SetClientData(new int(1)); - update(); Layout(); Fit(); @@ -1277,50 +1303,53 @@ int AMSMaterialsSetting::get_filament_variant_index(const Preset &filament, cons void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) { - // Get the flag whether to open the filament setting dialog from the device page - int* from_printer = static_cast(m_comboBox_filament->GetClientData()); + // True for the popup's own initial selection: the dialog pre-filled the tray's + // temps, so the matching preset must not overwrite them. + const bool initial_printer_selection = m_comboBox_from_printer; m_filament_type = ""; PresetBundle* preset_bundle = wxGetApp().preset_bundle; + std::string filament_printer_model; if (preset_bundle) { std::ostringstream stream; if (obj) { - // Defensive: this dialog is opened only from StatusPanel (BBL-only) today, so the fallback fires - // only during the brief BBL startup window before firmware reports nozzle info. Without this, - // the "0.0" lookup string returns an empty set and filament lookup yields no results. + // Use the selected profile's nozzle diameter until the connected device reports one. float machine_diameter = obj->GetExtderSystem()->GetNozzleDiameter(0); if (machine_diameter == 0.0f) { const ConfigOption *opt = preset_bundle->printers.get_selected_preset().config.option("nozzle_diameter"); if (opt) machine_diameter = static_cast(opt)->values[0]; } stream << std::fixed << std::setprecision(1) << machine_diameter; + filament_printer_model = resolve_filament_printer_model(obj->printer_type, preset_bundle); } std::string nozzle_diameter_str = stream.str(); // 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()) { + if (!selected.empty() && !filament_printer_model.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)) { + filament_printer_model, nozzle_diameter_str, obj->is_support_user_preset)) { if (it->filament_id != filament_id) continue; - // ) if nozzle_temperature_range is found - const int variant_index = get_filament_variant_index(*it, nozzle_diameter_str); - ConfigOption* opt_min = it->config.option("nozzle_temperature_range_low"); - if (opt_min) { - ConfigOptionInts* opt_min_ints = dynamic_cast(opt_min); - if (opt_min_ints) { - wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(variant_index)); - m_input_nozzle_min->GetTextCtrl()->SetValue(text_nozzle_temp_min); + if (!initial_printer_selection) { + // ) if nozzle_temperature_range is found + const int variant_index = get_filament_variant_index(*it, nozzle_diameter_str); + ConfigOption* opt_min = it->config.option("nozzle_temperature_range_low"); + if (opt_min) { + ConfigOptionInts* opt_min_ints = dynamic_cast(opt_min); + if (opt_min_ints) { + wxString text_nozzle_temp_min = wxString::Format("%d", opt_min_ints->get_at(variant_index)); + 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(opt_max); - if (opt_max_ints) { - wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(variant_index)); - m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max); + ConfigOption* opt_max = it->config.option("nozzle_temperature_range_high"); + if (opt_max) { + ConfigOptionInts* opt_max_ints = dynamic_cast(opt_max); + if (opt_max_ints) { + wxString text_nozzle_temp_max = wxString::Format("%d", opt_max_ints->get_at(variant_index)); + m_input_nozzle_max->GetTextCtrl()->SetValue(text_nozzle_temp_max); + } } } ConfigOption* opt_type = it->config.option("filament_type"); @@ -1359,13 +1388,16 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) m_button_confirm->Disable(); // ORCA No need to change style m_comboBox_cali_result->Clear(); m_comboBox_cali_result->SetValue(wxEmptyString); - m_input_k_val->GetTextCtrl()->SetValue(wxEmptyString); - m_input_n_val->GetTextCtrl()->SetValue(wxEmptyString); - m_comboBox_filament->SetClientData(new int(0)); + if (!initial_printer_selection) { + m_input_k_val->GetTextCtrl()->SetValue(wxEmptyString); + m_input_n_val->GetTextCtrl()->SetValue(wxEmptyString); + } + m_comboBox_from_printer = false; return; } else { - m_button_confirm->Enable(true); // ORCA No need to change style + if (!m_view_only) + m_button_confirm->Enable(true); // ORCA No need to change style } //filament id @@ -1389,6 +1421,9 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) } } + if (!ams_filament_id.empty()) + m_clr_picker->is_empty(false); + wxArrayString items; m_pa_profile_items.clear(); m_comboBox_cali_result->SetValue(wxEmptyString); @@ -1444,7 +1479,7 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) m_comboBox_cali_result->Set(items); if (ams_id == VIRTUAL_TRAY_MAIN_ID || ams_id == VIRTUAL_TRAY_DEPUTY_ID) { - if (from_printer && (*from_printer == 1)) { + if (initial_printer_selection) { for (auto slot : obj->vt_slot) { if (slot.id == std::to_string(ams_id)) cali_select_idx = CalibUtils::get_selected_calib_idx(m_pa_profile_items, slot.cali_idx); @@ -1461,10 +1496,11 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) } } else { - if (from_printer && (*from_printer == 1)) { + if (initial_printer_selection) { DevAmsTray* selected_tray = this->obj->GetFilaSystem()->GetAmsTray(std::to_string(ams_id), std::to_string(slot_id)); if (!selected_tray) { + m_comboBox_from_printer = false; return; } @@ -1495,7 +1531,7 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) else { if (!ams_filament_id.empty()) { //m_input_k_val->GetTextCtrl()->SetValue("0.00"); - m_input_k_val->Enable(true); + m_input_k_val->Enable(!m_view_only); } else { //m_input_k_val->GetTextCtrl()->SetValue("0.00"); @@ -1503,7 +1539,7 @@ void AMSMaterialsSetting::on_select_filament(wxCommandEvent &evt) } } - m_comboBox_filament->SetClientData(new int(0)); + m_comboBox_from_printer = false; } void AMSMaterialsSetting::on_dpi_changed(const wxRect &suggested_rect) diff --git a/src/slic3r/GUI/AMSMaterialsSetting.hpp b/src/slic3r/GUI/AMSMaterialsSetting.hpp index 0ecc8809be..76dd560efe 100644 --- a/src/slic3r/GUI/AMSMaterialsSetting.hpp +++ b/src/slic3r/GUI/AMSMaterialsSetting.hpp @@ -138,7 +138,7 @@ public: std::string ams_filament_id; std::string ams_setting_id; - bool m_is_third; + bool m_is_third = false; // Orca: view-only mode (laser/cut). When set, the dialog is inspectable but every // editing control is disabled and no command is sent. bool m_view_only = false; @@ -200,6 +200,9 @@ protected: wxStaticText* m_n_param; TextInput* m_input_n_val; int m_filament_selection; + // True while the popup's initial, printer-driven selection is being handled; it + // keeps that selection from overwriting the tray's own temps with preset temps. + bool m_comboBox_from_printer = false; int m_pa_cali_select_id = 0; diff --git a/src/slic3r/GUI/AMSSetting.cpp b/src/slic3r/GUI/AMSSetting.cpp index f953dd115a..cc74fbd07c 100644 --- a/src/slic3r/GUI/AMSSetting.cpp +++ b/src/slic3r/GUI/AMSSetting.cpp @@ -530,7 +530,8 @@ void AMSSetting::on_insert_material_read(wxCommandEvent &event) bool tray_read_opt = m_checkbox_Insert_material_auto_read->GetValue(); bool remain_opt = m_checkbox_remain->GetValue(); - m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt); + if (m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt) != 0) + UpdateByObj(m_obj); m_sizer_Insert_material_tip_inline->Layout(); Layout(); @@ -556,7 +557,8 @@ void AMSSetting::on_starting_read(wxCommandEvent &event) bool tray_read_opt = m_checkbox_Insert_material_auto_read->GetValue(); bool remain_opt = m_checkbox_remain->GetValue(); - m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt); + if (m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt) != 0) + UpdateByObj(m_obj); m_sizer_starting_tip_inline->Layout(); Layout(); @@ -570,7 +572,8 @@ void AMSSetting::on_remain(wxCommandEvent& event) bool start_read_opt = m_checkbox_starting_auto_read->GetValue(); bool tray_read_opt = m_checkbox_Insert_material_auto_read->GetValue(); bool remain_opt = m_checkbox_remain->GetValue(); - m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt); + if (m_obj->command_ams_user_settings(start_read_opt, tray_read_opt, remain_opt) != 0) + UpdateByObj(m_obj); event.Skip(); } @@ -806,4 +809,4 @@ void AMSSettingArrangeAMSOrder::OnBtnRearrangeClicked(wxCommandEvent& event) } #endif -}} // namespace Slic3r::GUI \ No newline at end of file +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/CaliHistoryDialog.cpp b/src/slic3r/GUI/CaliHistoryDialog.cpp index 1c2c0b9217..60866a3595 100644 --- a/src/slic3r/GUI/CaliHistoryDialog.cpp +++ b/src/slic3r/GUI/CaliHistoryDialog.cpp @@ -745,9 +745,15 @@ wxArrayString NewCalibrationHistoryDialog::get_all_filaments(const MachineObject std::string nozzle_diameter_str = stream.str(); if (preset_bundle) { + // OrcaSonar's model id is optional; the helper falls back to the selected profile + // so the list is never empty. + const std::string filament_printer_model = resolve_filament_printer_model(obj->printer_type, preset_bundle); + if (filament_printer_model.empty()) + return filament_items; + BOOST_LOG_TRIVIAL(trace) << "system_preset_bundle filament number=" << preset_bundle->filaments.size(); 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)) { + filament_printer_model, 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); diff --git a/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp b/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp index bef0391109..32f683e42e 100644 --- a/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp +++ b/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp @@ -30,6 +30,8 @@ #include "DevUtil.h" #include "DevUtilBackend.h" +#include + using namespace nlohmann; namespace Slic3r { @@ -61,6 +63,15 @@ void DevAmsTray::UpdateColorFromStr(const std::string& color) } } +void DevAmsTray::UpdateEmptyState(bool material_fields_present) +{ + const auto is_zero_or_empty = [](const std::string& value) { + return value.empty() || std::all_of(value.begin(), value.end(), [](char c) { return c == '0'; }); + }; + is_empty = material_fields_present && setting_id.empty() && m_fila_type.empty() && + is_zero_or_empty(color) && is_zero_or_empty(tag_uid); +} + void DevAmsTray::reset() { tag_uid = ""; @@ -82,6 +93,7 @@ void DevAmsTray::reset() k = 0.0f; n = 0.0f; is_bbl = false; + is_empty = false; hold_count = 0; remain = 0; } @@ -681,7 +693,7 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS //std::string type = (*tray_it)["tray_type"].get(); std::string type = MachineObject::setting_id_to_type(curr_tray->setting_id, (*tray_it)["tray_type"].get()); // curr_tray->setting_id is our OF id; GFS00/GFS01 are the printer's own support-filament ids. - auto* agent = GUI::wxGetApp().getAgent(); + auto* agent = wxTheApp != nullptr ? GUI::wxGetApp().getAgent() : nullptr; 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") { @@ -781,6 +793,7 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS { curr_tray->remain = -1; } + curr_tray->UpdateEmptyState(tray_it->contains("tray_info_idx") && tray_it->contains("tray_type")); // The tray objects are reused across status updates. Reset this // state when a previously empty slot receives a filament again. curr_tray->is_slot_placeholder = tray_it->contains("tray_slot_placeholder"); diff --git a/src/slic3r/GUI/DeviceCore/DevFilaSystem.h b/src/slic3r/GUI/DeviceCore/DevFilaSystem.h index 32edc06a32..c357c45ab0 100644 --- a/src/slic3r/GUI/DeviceCore/DevFilaSystem.h +++ b/src/slic3r/GUI/DeviceCore/DevFilaSystem.h @@ -83,6 +83,7 @@ public: wxColour wx_color; bool is_bbl; bool is_exists = false; + bool is_empty = false; // Explicitly reported as having no filament. bool is_slot_placeholder = false; // Orca: True for empty tray slots from pull-mode agents int hold_count = 0; int remain = 0; // filament remain: 0 ~ 100 @@ -91,13 +92,15 @@ public: // operators bool operator==(DevAmsTray const& o) const { - return id == o.id && m_fila_type == o.m_fila_type && filament_setting_id == o.filament_setting_id && color == o.color; + return id == o.id && m_fila_type == o.m_fila_type && filament_setting_id == o.filament_setting_id && + color == o.color && is_empty == o.is_empty; } bool operator!=(DevAmsTray const& o) const { return !operator==(o); } // setters void reset(); void UpdateColorFromStr(const std::string& color); + void UpdateEmptyState(bool material_fields_present); void set_hold_count() { hold_count = HOLD_COUNT_MAX; } // getter diff --git a/src/slic3r/GUI/DeviceManager.cpp b/src/slic3r/GUI/DeviceManager.cpp index 290f1dc4ca..c036b704f8 100644 --- a/src/slic3r/GUI/DeviceManager.cpp +++ b/src/slic3r/GUI/DeviceManager.cpp @@ -432,6 +432,32 @@ NozzleVolumeType convert_to_nozzle_type(const std::string &str) return res; } +std::string resolve_filament_printer_model(const std::string& printer_type, PresetBundle* preset_bundle) +{ + if (!preset_bundle) + return {}; + + // Devices with a shipped printer config (Bambu) resolve directly. + if (const std::string display_name = DevPrinterConfigUtil::get_printer_display_name(printer_type); !display_name.empty()) + return display_name; + + // A vendor model id the device reported (SSDP modelNumber, manual binding). + if (!printer_type.empty()) { + if (const std::string model_name = preset_bundle->get_printer_model_display_name(printer_type); !model_name.empty()) + return model_name; + } + + // OrcaSonar's model id is optional; a generic device resolves against the selected profile. + if (const ConfigOptionString* model = preset_bundle->printers.get_selected_preset().config.opt("printer_model"); + model && !model->value.empty()) { + BOOST_LOG_TRIVIAL(info) << "resolve_filament_printer_model: device type \"" << printer_type + << "\" has no installed model; using the selected profile \"" << model->value << "\""; + return model->value; + } + + return {}; +} + wxString MachineObject::get_printer_type_display_str() const { std::string display_name = DevPrinterConfigUtil::get_printer_display_name(printer_type); @@ -1734,6 +1760,10 @@ int MachineObject::check_resume_condition() } int MachineObject::command_ams_change_filament(bool load, std::string ams_id, std::string slot_id, int old_temp, int new_temp, std::optional extruder_id) { + if (!printer_supports_command("print.ams_change_filament")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_change_filament: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } json j; try { auto tray_id = 0; @@ -1777,6 +1807,10 @@ int MachineObject::command_ams_change_filament(bool load, std::string ams_id, st int MachineObject::command_ams_user_settings(bool start_read_opt, bool tray_read_opt, bool remain_flag) { + if (!printer_supports_command("print.ams_user_setting")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_user_settings: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } json j; j["print"]["command"] = "ams_user_setting"; j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id++); @@ -1785,22 +1819,59 @@ int MachineObject::command_ams_user_settings(bool start_read_opt, bool tray_read j["print"]["tray_read_option"] = tray_read_opt; j["print"]["calibrate_remain_flag"] = remain_flag; - m_fila_system->GetAmsSystemSetting().SetDetectOnInsertEnabled(tray_read_opt); - m_fila_system->GetAmsSystemSetting().SetDetectOnPowerupEnabled(start_read_opt); - m_fila_system->GetAmsSystemSetting().SetDetectRemainEnabled(remain_flag); - ams_user_setting_start = time(nullptr); - - return this->publish_json(j); + const int rc = this->publish_json(j); + if (rc == 0) { + m_fila_system->GetAmsSystemSetting().SetDetectOnInsertEnabled(tray_read_opt); + m_fila_system->GetAmsSystemSetting().SetDetectOnPowerupEnabled(start_read_opt); + m_fila_system->GetAmsSystemSetting().SetDetectRemainEnabled(remain_flag); + ams_user_setting_start = time(nullptr); + } + return rc; } int MachineObject::command_ams_calibrate(int ams_id) { if (!m_agent) return -1; + if (!m_agent->owns_agent(printer_agent_id)) + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); return command_with_dialog(m_agent->command_ams_calibrate(get_dev_id(), ams_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); } +bool MachineObject::printer_supports_command(const char* command) const +{ + if (!command || !m_agent) + return false; + return m_agent->supports_command(printer_agent_id, get_dev_id(), command); +} + +bool MachineObject::printer_uses_filament_mapping() const +{ + if (!m_agent) + return false; + // An unrecorded owner goes through owns_agent() like any other, because + // whichever agent is active is also the one formatting the payload. Only a + // recorded owner that differs from the active agent is a mismatch. + return m_agent->uses_filament_mapping(printer_agent_id); +} + +bool MachineObject::printer_supports_feature(const char* feature) const +{ + return feature && m_agent && m_agent->supports_feature(printer_agent_id, get_dev_id(), feature); +} + +bool MachineObject::supports_extrusion_cali() const +{ + // Devices with no agent id predate the agent split and keep the Bambu path. + return printer_agent_id.empty() || printer_agent_id == BBL_PRINTER_AGENT_ID; +} + int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::string filament_id, std::string setting_id, std::string tray_color, std::string tray_type, int nozzle_temp_min, int nozzle_temp_max) { + if (!printer_supports_command("print.ams_filament_setting")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_filament_settings: printer agent does not support slot metadata updates"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } + int tag_tray_id = 0; int tag_ams_id = ams_id; int tag_slot_id = slot_id; @@ -1835,6 +1906,10 @@ int MachineObject::command_ams_filament_settings(int ams_id, int slot_id, std::s int MachineObject::command_ams_refresh_rfid(int ams_id, int slot_id) { if (!m_agent) return -1; + if (!printer_supports_command("print.ams_get_rfid")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_refresh_rfid: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } return command_with_dialog(m_agent->command_ams_refresh_rfid(get_dev_id(), ams_id, slot_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); } @@ -1848,11 +1923,19 @@ int MachineObject::command_start_camera() int MachineObject::command_ams_select_tray(std::string tray_id) { if (!m_agent) return -1; + if (!printer_supports_command("print.ams_change_filament")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_select_tray: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } return command_with_dialog(m_agent->command_ams_select_tray(get_dev_id(), tray_id, MachineObject::m_sequence_id++, is_lan_mode_printer())); } int MachineObject::command_ams_control(std::string action) { + if (!printer_supports_command("print.ams_control")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_control: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } if (action == "resume" && check_resume_condition()) return 0; //valid actions @@ -1868,6 +1951,10 @@ int MachineObject::command_ams_control(std::string action) int MachineObject::command_ams_drying_stop() { + if (!printer_supports_command("print.auto_stop_ams_dry")) { + BOOST_LOG_TRIVIAL(warning) << "command_ams_drying_stop: printer agent does not support the command"; + return command_with_dialog(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + } json j; j["print"]["command"] = "auto_stop_ams_dry"; j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id++); @@ -2818,7 +2905,9 @@ bool MachineObject::is_camera_busy_off() int MachineObject::publish_json(const json& json_item, int qos, int flag) { int rtn = 0; - if (is_lan_mode_printer()) { + if (m_agent && !m_agent->owns_agent(printer_agent_id)) { + rtn = ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } else if (is_lan_mode_printer()) { rtn = local_publish_json(json_item.dump(), qos, flag); } else { rtn = cloud_publish_json(json_item.dump(), qos, flag); @@ -2862,6 +2951,7 @@ int MachineObject::local_publish_json(std::string json_str, int qos, int flag) std::string MachineObject::setting_id_to_type(std::string setting_id, std::string tray_type) { std::string type; + if (wxTheApp == nullptr) return tray_type; PresetBundle* preset_bundle = GUI::wxGetApp().preset_bundle; if (preset_bundle) { for (auto it = preset_bundle->filaments.begin(); it != preset_bundle->filaments.end(); it++) { @@ -4198,6 +4288,9 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_ vt_slot[0].setting_id = jj["tray_info_idx"].get(); //vt_tray.type = jj["tray_type"].get(); vt_slot[0].m_fila_type = setting_id_to_type(vt_slot[0].setting_id, jj["tray_type"].get()); + // The ack carries the whole slot; re-derive empty so the panel flips off + // "Empty" without waiting out the hold. + vt_slot[0].UpdateEmptyState(true); // delay update vt_slot[0].set_hold_count(); } else { @@ -4223,6 +4316,9 @@ int MachineObject::parse_json(std::string tunnel, std::string payload, bool key_ tray_it->second->setting_id = jj["tray_info_idx"].get(); tray_it->second->m_fila_type = setting_id_to_type(tray_it->second->setting_id, jj["tray_type"].get()); + // The ack carries the whole slot; re-derive empty so the panel flips off + // "Empty" without waiting out the hold. + tray_it->second->UpdateEmptyState(true); // delay update tray_it->second->set_hold_count(); } else { @@ -5161,7 +5257,7 @@ DevAmsTray MachineObject::parse_vt_tray(json vtray) //std::string type = vtray["tray_type"].get(); std::string type = setting_id_to_type(vt_tray.setting_id, vtray["tray_type"].get()); // 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(); + auto* agent = wxTheApp != nullptr ? GUI::wxGetApp().getAgent() : nullptr; 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"; @@ -5256,6 +5352,7 @@ DevAmsTray MachineObject::parse_vt_tray(json vtray) else { vt_tray.remain = -1; } + vt_tray.UpdateEmptyState(vtray.contains("tray_info_idx") && vtray.contains("tray_type")); } return vt_tray; @@ -5549,11 +5646,11 @@ void MachineObject::parse_new_info2(const json& info) if (capabilities_it == info.end() || !capabilities_it->is_object()) return; const auto flags_it = capabilities_it->find("flags"); - if (flags_it == capabilities_it->end() || !flags_it->is_object()) + const bool has_flags = flags_it != capabilities_it->end() && flags_it->is_object(); + if (!has_flags) return; - const json& flags = *flags_it; - BOOST_LOG_TRIVIAL(info) << "parse_new_info2: OrcaSonar capability flags=" << flags.dump(); + BOOST_LOG_TRIVIAL(info) << "parse_new_info2: capability flags=" << flags.dump(); auto parse_bool = [&flags](const char* name, bool& target) { const auto it = flags.find(name); diff --git a/src/slic3r/GUI/DeviceManager.hpp b/src/slic3r/GUI/DeviceManager.hpp index c4a63cb588..08a80b3bf7 100644 --- a/src/slic3r/GUI/DeviceManager.hpp +++ b/src/slic3r/GUI/DeviceManager.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -73,6 +74,7 @@ class DeviceErrorDialog; // Previous definitions class NetworkAgent; // Orca: ManualPaCaliMethod now provided by DeviceCore/DevCalib.h (enum class) +class PresetBundle; #define UpgradeNoError 0 #define UpgradeDownloadFailed -1 @@ -108,6 +110,11 @@ struct DevPrintTaskRatingInfo; // given nozzle diameter (mm), bucketed per nozzle size to mirror the printer firmware. bool is_stringing_prone_filament(const std::string& filament_id, float nozzle_diameter); +// The printer model filament presets are matched against for a connected machine. OrcaSonar's +// model id is optional, so a device with no installed vendor model falls back to the selected +// printer profile rather than resolving to no filament list at all. +std::string resolve_filament_printer_model(const std::string& printer_type, PresetBundle* preset_bundle); + class MachineObject { private: @@ -796,6 +803,13 @@ public: int command_refresh_nozzle(); int command_set_chamber(int temp); int check_resume_condition(); + bool printer_supports_command(const char* command) const; + bool printer_supports_feature(const char* feature) const; + bool printer_uses_filament_mapping() const; + // The per-tray flow-dynamics K/N records are a Bambu firmware feature. Other + // agents have no printer-side calibration to read or write, so the AMS UI must + // not offer K/N for them. + bool supports_extrusion_cali() const; // ams controls //int command_ams_switch(int tray_index, int old_temp = 210, int new_temp = 210); int command_ams_change_filament(bool load, std::string ams_id, std::string slot_id, int old_temp = 210, int new_temp = 210, std::optional extruder_id = std::nullopt); diff --git a/src/slic3r/GUI/DeviceTab/uiAMSBestPositionPopup.cpp b/src/slic3r/GUI/DeviceTab/uiAMSBestPositionPopup.cpp index 151d53810b..eda7682372 100644 --- a/src/slic3r/GUI/DeviceTab/uiAMSBestPositionPopup.cpp +++ b/src/slic3r/GUI/DeviceTab/uiAMSBestPositionPopup.cpp @@ -970,7 +970,11 @@ int ReselectMachineDialog::CaculateSwitcherDistribution(MachineObject* obj, cons const auto& can = ams.cans[j]; auto id = getTrayID(obj, ams.ams_id, can.can_id); auto material = can.material_name; - if (can.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND || + if (can.is_empty || can.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) + { + material = L("Empty"); + } + else if (can.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND || can.material_state == AMSCanType::AMS_CAN_TYPE_BRAND || can.material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL) { @@ -979,10 +983,6 @@ int ReselectMachineDialog::CaculateSwitcherDistribution(MachineObject* obj, cons material = L("?"); } } - if (can.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) - { - material = "Empty"; - } auto itOK = std::find_if(posOK.begin(), posOK.end(), [&](const trayHelper& tray){ auto amsID = std::get<0>(tray); diff --git a/src/slic3r/GUI/FilamentMappingUtils.hpp b/src/slic3r/GUI/FilamentMappingUtils.hpp new file mode 100644 index 0000000000..377c4190fe --- /dev/null +++ b/src/slic3r/GUI/FilamentMappingUtils.hpp @@ -0,0 +1,105 @@ +#pragma once + +#include +#include + +#include + +#include "libslic3r/ProjectTask.hpp" +#include "DeviceManager.hpp" + +namespace Slic3r { +namespace GUI { + +// True when the normalized ams_mapping2 carries any entry the agent's serializer +// would put on the wire: every integer pair except the {255,255} unmatched +// sentinel, external slots ({255,0}/{254,0}) included. This mirrors +// OrcaPrinterAgent::build_filament_mapping exactly, so the GUI gate and the +// agent gate agree; a mismatch lets an entry reach the agent and be refused late +// with a generic publish error instead of the designed message. +inline bool has_engaged_filament_mapping(const std::string& ams_mapping2) +{ + const nlohmann::json mapping = nlohmann::json::parse(ams_mapping2, nullptr, false); + if (mapping.is_discarded() || !mapping.is_array()) + return false; + for (const auto& entry : mapping) { + if (!entry.is_object()) + continue; + const auto ams_id_it = entry.find("ams_id"); + const auto slot_id_it = entry.find("slot_id"); + if (ams_id_it == entry.end() || slot_id_it == entry.end()) + continue; + if (!ams_id_it->is_number_integer() || !slot_id_it->is_number_integer()) + continue; + if (ams_id_it->get() == 255 && slot_id_it->get() == 255) + continue; // unmatched/unused sentinel: the serializer drops it + return true; + } + return false; +} + +// A device with no AMS units has a single source: the external spool. OrcaSlicer's +// auto-mapping force-selects it for every filament (DevMapping.cpp), but that is not +// a lane choice: keep it out of the send gate and off print.gcode_file. +inline void drop_forced_external_selection(bool device_has_ams, std::string& ams_mapping2) +{ + if (!device_has_ams) + ams_mapping2.clear(); +} + +// A used filament with no target would be silently dropped from the wire +// mapping, so the print must be refused rather than run the wrong material. +// m_ams_mapping_result carries exactly the filaments the slice uses. +inline bool has_used_filament_without_target(const std::vector& result) +{ + for (const auto& f : result) { + if (f.get_ams_id() < 0 || f.get_slot_id() < 0) + return true; + } + return false; +} + +// True when at least one used filament already has a target. The used-unmapped +// refusal applies to a partially mapped print; a print with no mapping at all +// is handled by the existing all-invalid send-path flow. +inline bool has_any_mapped_target(const std::vector& result) +{ + for (const auto& f : result) { + if (f.get_ams_id() >= 0 && f.get_slot_id() >= 0) + return true; + } + return false; +} + + +// Refusal reason for a printer agent that serializes lane selection into +// print.gcode_file's per-print filament_mapping field. +enum class MappingSendError { + none, // no refusal; ams_mapping2 is normalized for send + unsupported, // a mapping is engaged but the connector did not advertise it + incomplete, // a used filament has no target while others do +}; + +// Applies the send-time mapping policy and normalizes ams_mapping2 in place. +// Agents that do not speak filament_mapping keep their legacy payload untouched. +inline MappingSendError prepare_filament_mapping_for_send(MachineObject* obj, + std::string& ams_mapping2, + const std::vector& mapping_result) +{ + if (!obj || !obj->printer_uses_filament_mapping()) + return MappingSendError::none; + + // A device with no AMS units has one source, the external spool: + // auto-mapping force-selects it, which is not a lane choice. Drop it before + // the capability gate so it cannot refuse a print nobody mapped. + drop_forced_external_selection(obj->HasAms(), ams_mapping2); + + if (!obj->printer_supports_feature("filament_mapping") && has_engaged_filament_mapping(ams_mapping2)) + return MappingSendError::unsupported; + if (has_any_mapped_target(mapping_result) && has_used_filament_without_target(mapping_result)) + return MappingSendError::incomplete; + return MappingSendError::none; +} + +} // namespace GUI +} // namespace Slic3r diff --git a/src/slic3r/GUI/ImageGrid.cpp b/src/slic3r/GUI/ImageGrid.cpp index 280b95055d..5ef8524ef1 100644 --- a/src/slic3r/GUI/ImageGrid.cpp +++ b/src/slic3r/GUI/ImageGrid.cpp @@ -1,5 +1,6 @@ #include "ImageGrid.h" #include "Printer/PrinterFileSystem.h" +#include "Printer/BambuFileGridModel.h" #include "wxExtensions.hpp" #include "Widgets/Label.hpp" #include "I18N.hpp" @@ -8,6 +9,7 @@ #include #include +#include #include #include #include @@ -76,18 +78,11 @@ ImageGrid::ImageGrid(wxWindow * parent) void ImageGrid::SetFileSystem(boost::shared_ptr file_sys) { - if (m_file_sys) { - m_file_sys->Unbind(EVT_MODE_CHANGED, &ImageGrid::changedEvent, this); - m_file_sys->Unbind(EVT_FILE_CHANGED, &ImageGrid::changedEvent, this); - m_file_sys->Unbind(EVT_THUMBNAIL, &ImageGrid::changedEvent, this); - m_file_sys->Unbind(EVT_DOWNLOAD, &ImageGrid::changedEvent, this); - } m_file_sys = file_sys; - if (m_file_sys) { - m_file_sys->Bind(EVT_MODE_CHANGED, &ImageGrid::changedEvent, this); - m_file_sys->Bind(EVT_FILE_CHANGED, &ImageGrid::changedEvent, this); - m_file_sys->Bind(EVT_THUMBNAIL, &ImageGrid::changedEvent, this); - m_file_sys->Bind(EVT_DOWNLOAD, &ImageGrid::changedEvent, this); + m_model.reset(); + if (file_sys) { + m_model = boost::make_shared(file_sys); + m_model->SetChangeHandler([this](FileGridChange c) { onModelChange(c); }); } m_row_count = 0; m_col_count = 1; @@ -96,9 +91,22 @@ void ImageGrid::SetFileSystem(boost::shared_ptr file_sys) UpdateFileSystem(); } +void ImageGrid::SetModel(boost::shared_ptr model) +{ + m_file_sys.reset(); + m_model = std::move(model); + if (m_model) + m_model->SetChangeHandler([this](FileGridChange c) { onModelChange(c); }); + m_row_count = 0; + m_col_count = 1; + m_row_offset = 0; + m_scroll_offset = 0; + UpdateFileSystem(); +} + void ImageGrid::SetStatus(ScalableBitmap const & icon, wxString const &msg) { - int code = m_file_sys ? m_file_sys->GetLastError() : 1; + int code = m_model ? m_model->GetLastError() : 1; m_status_icon = icon; m_status_msg = wxString::Format(msg, code); BOOST_LOG_TRIVIAL(info) << "ImageGrid::SetStatus: " << m_status_msg.ToUTF8().data(); @@ -107,26 +115,26 @@ void ImageGrid::SetStatus(ScalableBitmap const & icon, wxString const &msg) void Slic3r::GUI::ImageGrid::SetFileType(int type, std::string const &storage) { - if (!m_file_sys) + if (!m_model) return; - m_file_sys->SetFileType((PrinterFileSystem::FileType) type, storage); + m_model->SetFileType((FileGridType) type, storage); } void Slic3r::GUI::ImageGrid::SetGroupMode(int mode) { - if (!m_file_sys) + if (!m_model) return; - if (m_file_sys->GetCount() == 0) { - m_file_sys->SetGroupMode((PrinterFileSystem::GroupMode) mode); + if (m_model->GetCount() == 0) { + m_model->SetGroupMode((FileGridGroup) mode); return; } wxSize size = GetClientSize(); int index = (m_row_offset + 1 < m_row_count || m_row_count == 0) ? m_row_offset / 4 * m_col_count - : ((m_file_sys->GetCount() + m_col_count - 1) / m_col_count - (size.y + m_border_size.GetHeight() - 1) / m_cell_size.GetHeight()) * m_col_count; - auto & file = m_file_sys->GetFile(index); - m_file_sys->SetGroupMode((PrinterFileSystem::GroupMode) mode); - index = m_file_sys->GetIndexAtTime(file.time); + : ((m_model->GetCount() + m_col_count - 1) / m_col_count - (size.y + m_border_size.GetHeight() - 1) / m_cell_size.GetHeight()) * m_col_count; + time_t time = m_model->GetFile(index).time; + m_model->SetGroupMode((FileGridGroup) mode); + index = m_model->GetIndexAtTime(time); // UpdateFileSystem(); call by changed event m_row_offset = index / m_col_count * 4; if (m_row_offset >= m_row_count) @@ -137,8 +145,8 @@ void Slic3r::GUI::ImageGrid::SetGroupMode(int mode) void Slic3r::GUI::ImageGrid::SetSelecting(bool selecting) { m_selecting = selecting; - if (m_file_sys) - m_file_sys->SelectAll(false); + if (m_model) + m_model->SelectAll(false); Refresh(); } @@ -166,14 +174,14 @@ void Slic3r::GUI::ImageGrid::Rescale() void Slic3r::GUI::ImageGrid::Select(size_t index) { if (m_selecting) { - m_file_sys->ToggleSelect(index); + m_model->ToggleSelect(index); Refresh(); return; } - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) { + if (m_model->GetGroupMode() == FileGridGroup::All) { return; } - index = m_file_sys->EnterSubGroup(index); + index = m_model->EnterSubGroup(index); // UpdateFileSystem(); call by changed event m_row_offset = index / m_col_count * 4; if (m_row_offset >= m_row_count) @@ -193,9 +201,9 @@ void Slic3r::GUI::ImageGrid::DoAction(size_t index, int action) void Slic3r::GUI::ImageGrid::UpdateFileSystem() { - if (!m_file_sys) return; - if (m_file_sys->GetFileType() < PrinterFileSystem::F_MODEL) { - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) { + if (!m_model) return; + if (m_model->GetFileType() < FileGridType::Model) { + if (m_model->GetGroupMode() == FileGridGroup::All) { m_cell_size.Set(396, 228); m_border_size.Set(384, 216); } @@ -216,10 +224,10 @@ void Slic3r::GUI::ImageGrid::UpdateFileSystem() void ImageGrid::UpdateLayout() { - if (!m_file_sys) return; + if (!m_model) return; wxSize size = GetClientSize(); wxSize title_mask_size{0, 60 * em_unit(this) / 10}; - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) { + if (m_model->GetGroupMode() == FileGridGroup::All) { title_mask_size.y = 20 * em_unit(this) / 10; size.y -= title_mask_size.y; } @@ -227,7 +235,7 @@ void ImageGrid::UpdateLayout() int cell_height = m_cell_size.GetHeight(); int ncol = (size.GetWidth() - cell_width + m_border_size.GetWidth()) / cell_width; if (ncol <= 0) ncol = 1; - int total_height = (m_file_sys->GetCount() + ncol - 1) / ncol * cell_height + cell_height - m_border_size.GetHeight(); + int total_height = (m_model->GetCount() + ncol - 1) / ncol * cell_height + cell_height - m_border_size.GetHeight(); int nrow = (total_height - size.GetHeight() + cell_height / 4 - 1) / (cell_height / 4); m_row_offset = m_row_offset * m_col_count / ncol; m_col_count = ncol; @@ -236,7 +244,7 @@ void ImageGrid::UpdateLayout() m_row_offset = m_row_count == 0 ? 0 : m_row_count - 1; m_scroll_offset = 0; // create mask - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) { + if (m_model->GetGroupMode() == FileGridGroup::All) { title_mask_size.x = (m_col_count - 1) * m_cell_size.GetWidth() + m_border_size.GetWidth(); } else { @@ -252,7 +260,7 @@ void ImageGrid::UpdateLayout() void Slic3r::GUI::ImageGrid::UpdateFocusRange() { - if (!m_file_sys) return; + if (!m_model) return; wxSize size = GetClientSize(); wxPoint off; int index = firstItem(size, off); @@ -261,15 +269,21 @@ void Slic3r::GUI::ImageGrid::UpdateFocusRange() count += m_col_count; off.y += m_cell_size.y; } - m_file_sys->SetFocusRange(index, count); + m_model->SetFocusRange(index, count); +} + +bool Slic3r::GUI::ImageGrid::hasSecondAction(const FileGridCard &card) const +{ + return m_show_download || card.downloading || + (m_model->GetFileType() == FileGridType::Model && card.printable); } std::pair Slic3r::GUI::ImageGrid::HitTest(wxPoint const &pt) { - if (!m_file_sys) + if (!m_model) return {HIT_NONE, -1}; wxSize size = GetClientSize(); - if (m_file_sys->GetCount() == 0) { + if (m_model->GetCount() == 0) { if (wxRect({0, 0}, m_border_size).CenterIn(wxRect({0, 0}, size)).Contains(pt)) return {HIT_STATUS, 0}; return {HIT_NONE, -1}; @@ -287,17 +301,19 @@ std::pair Slic3r::GUI::ImageGrid::HitTest(wxPoint const &pt) index += m_col_count; off.y -= m_cell_size.GetHeight(); } - if (index >= m_file_sys->GetCount()) { return {HIT_NONE, -1}; } + if (index >= m_model->GetCount()) { return {HIT_NONE, -1}; } if (!m_content_rect.Contains(off)) { return {HIT_NONE, -1}; } if (!m_selecting) { wxRect hover_rect{0, m_content_rect.GetHeight() - m_buttons_background.GetHeight(), m_content_rect.GetWidth(), m_buttons_background.GetHeight()}; - auto & file = m_file_sys->GetFile(index); - int btn = file.IsDownload() && file.DownloadProgress() >= 0 ? 3 : 2; - if (m_file_sys->GetFileType() == PrinterFileSystem::F_MODEL) { - if (m_show_download) + const FileGridCard &card = m_model->GetFile(index); + int btn = card.downloading && card.download_progress >= 0 ? 3 : 2; + if (m_model->GetFileType() == FileGridType::Model) { + if (m_show_download && card.printable) btn = 3; hover_rect.y -= m_content_rect.GetHeight() * 64 / 264; } + if (!hasSecondAction(card)) + btn = 1; if (hover_rect.Contains(off.x, off.y)) { return {HIT_ACTION, index * 4 + off.x * btn / hover_rect.GetWidth()}; } // Two buttons @@ -315,12 +331,12 @@ void ImageGrid::mouseMoved(wxMouseEvent& event) m_hit_item = hit.second; if (hit.first == HIT_ITEM) { SetToolTip({}); - auto & file = m_file_sys->GetFile(hit.second); - if (auto title = file.Title(); !title.empty()) { - auto tip = wxString::Format(_L("File: %s\nTitle: %s\n"), from_u8(file.name), from_u8(title)); + const FileGridCard &card = m_model->GetFile(hit.second); + if (auto title = card.title; !title.empty()) { + auto tip = wxString::Format(_L("File: %s\nTitle: %s\n"), from_u8(card.name), from_u8(title)); SetToolTip(tip); } else { - SetToolTip(from_u8(file.name)); + SetToolTip(from_u8(card.name)); } } else SetToolTip({}); @@ -372,9 +388,9 @@ void ImageGrid::mouseReleased(wxMouseEvent& event) else if (m_hit_type == HIT_ACTION) DoAction(m_hit_item / 4, m_hit_item & 3); else if (m_hit_type == HIT_MODE) - SetGroupMode(static_cast(2 - m_hit_item)); + SetGroupMode(static_cast(2 - m_hit_item)); else if (m_hit_type == HIT_STATUS) - m_file_sys->Retry(); + m_model->Retry(); else Refresh(); } else { @@ -403,20 +419,11 @@ void ImageGrid::mouseWheelMoved(wxMouseEvent &event) Refresh(); } -void Slic3r::GUI::ImageGrid::changedEvent(wxCommandEvent& evt) +void Slic3r::GUI::ImageGrid::onModelChange(FileGridChange change) { - evt.Skip(); - BOOST_LOG_TRIVIAL(debug) << "ImageGrid::changedEvent: " << evt.GetEventType() << " index: " << evt.GetInt() - << " name: " << evt.GetString().ToUTF8().data() << " extra: " << evt.GetExtraLong(); - if (evt.GetEventType() == EVT_FILE_CHANGED) { - if (evt.GetInt() == -1) - m_file_sys->DownloadCheckFiles(wxGetApp().app_config->get("download_path")); + BOOST_LOG_TRIVIAL(debug) << "ImageGrid::onModelChange: " << (int) change; + if (change == FileGridChange::Files || change == FileGridChange::Mode) UpdateFileSystem(); - } - else if (evt.GetEventType() == EVT_MODE_CHANGED) - UpdateFileSystem(); - //else if (evt.GetEventType() == EVT_THUMBNAIL) - // RefreshRect(itemRect(evt.GetInt()), false); else Refresh(); } @@ -431,7 +438,7 @@ void ImageGrid::paintEvent(wxPaintEvent& evt) size_t Slic3r::GUI::ImageGrid::firstItem(wxSize const &size, wxPoint &off) { int size_y = size.y; - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) + if (m_model->GetGroupMode() == FileGridGroup::All) size_y -= m_title_mask.GetHeight(); int offx = (size.x - (m_col_count - 1) * m_cell_size.GetWidth() - m_border_size.GetWidth()) / 2; int offy = (m_row_offset + 1 < m_row_count || m_row_count == 0) ? @@ -439,8 +446,8 @@ size_t Slic3r::GUI::ImageGrid::firstItem(wxSize const &size, wxPoint &off) size_y - (size_y + m_border_size.GetHeight() - 1) / m_cell_size.GetHeight() * m_cell_size.GetHeight(); int index = (m_row_offset + 1 < m_row_count || m_row_count == 0) ? m_row_offset / 4 * m_col_count : - ((m_file_sys->GetCount() + m_col_count - 1) / m_col_count - (size_y + m_border_size.GetHeight() - 1) / m_cell_size.GetHeight()) * m_col_count; - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) + ((m_model->GetCount() + m_col_count - 1) / m_col_count - (size_y + m_border_size.GetHeight() - 1) / m_cell_size.GetHeight()) * m_col_count; + if (m_model->GetGroupMode() == FileGridGroup::All) offy += m_title_mask.GetHeight(); off = wxPoint{offx, offy}; return index; @@ -534,7 +541,7 @@ void ImageGrid::render(wxDC& dc) wxSize size = GetClientSize(); dc.SetPen(wxPen(GetBackgroundColour())); dc.SetBrush(wxBrush(GetBackgroundColour())); - if (!m_file_sys || m_file_sys->GetCount() == 0) { + if (!m_model || m_model->GetCount() == 0) { dc.DrawRectangle({ 0, 0, size.x, size.y }); if (!m_status_msg.IsEmpty()) { auto si = m_status_icon.GetBmpSize(); @@ -562,7 +569,7 @@ void ImageGrid::render(wxDC& dc) { // Draw one line wxPoint pt{off.x, off.y}; - end = (index + m_col_count) < m_file_sys->GetCount() ? index + m_col_count : m_file_sys->GetCount(); + end = (index + m_col_count) < m_model->GetCount() ? index + m_col_count : m_model->GetCount(); while (index < end) { pt += m_content_rect.GetTopLeft(); // Draw content @@ -571,7 +578,7 @@ void ImageGrid::render(wxDC& dc) &ImageGrid::renderContent1, &ImageGrid::renderContent2 }; - (this->*contentRender[m_file_sys->GetFileType()])(dc, pt, index, hit_image == index); + (this->*contentRender[static_cast(m_model->GetFileType())])(dc, pt, index, hit_image == index); pt -= m_content_rect.GetTopLeft(); // Draw colume spacing at right dc.DrawRectangle({pt.x + m_border_size.GetWidth(), pt.y, m_cell_size.GetWidth() - m_border_size.GetWidth(), m_border_size.GetHeight()}); @@ -588,13 +595,13 @@ void ImageGrid::render(wxDC& dc) off.y += m_cell_size.GetHeight(); } // Draw floating date range for non-group list - if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE && m_file_sys->GetCount() > 0) { + if (m_model->GetGroupMode() == FileGridGroup::All && m_model->GetCount() > 0) { //dc.DrawBitmap(m_title_mask, {off.x, 0}); dc.DrawRectangle({off.x, 0}, m_title_mask.GetSize()); - auto & file1 = m_file_sys->GetFile(start); - auto & file2 = m_file_sys->GetFile(end - 1); - auto date1 = wxDateTime((time_t) file1.time).Format(_L(TIME_FORMATS[m_file_sys->GetGroupMode()])); - auto date2 = wxDateTime((time_t) file2.time).Format(_L(TIME_FORMATS[m_file_sys->GetGroupMode()])); + const FileGridCard & file1 = m_model->GetFile(start); + const FileGridCard & file2 = m_model->GetFile(end - 1); + auto date1 = wxDateTime((time_t) file1.time).Format(_L(TIME_FORMATS[static_cast(m_model->GetGroupMode())])); + auto date2 = wxDateTime((time_t) file2.time).Format(_L(TIME_FORMATS[static_cast(m_model->GetGroupMode())])); dc.SetFont(Label::Head_16); dc.SetTextForeground(StateColor::darkModeColorFor("#262E30")); dc.DrawText(date1 + " - " + date2, wxPoint{off.x, 2}); @@ -604,7 +611,7 @@ void ImageGrid::render(wxDC& dc) dc.DrawRectangle({off.x, off.y, size.x - off.x * 2, size.y - off.y}); // Draw position bar if (m_timer.IsRunning()) { - int total_height = (m_file_sys->GetCount() + m_col_count - 1) / m_col_count * m_cell_size.GetHeight() + m_cell_size.GetHeight() - m_border_size.GetHeight(); + int total_height = (m_model->GetCount() + m_col_count - 1) / m_col_count * m_cell_size.GetHeight() + m_cell_size.GetHeight() - m_border_size.GetHeight(); if (total_height > size.y) { int offset = (m_row_offset + 1 < m_row_count || m_row_count == 0) ? m_row_offset * (m_cell_size.GetHeight() / 4) : total_height - size.y; wxRect rect = {size.x - 16, offset * size.y / total_height, 8, @@ -618,15 +625,35 @@ void ImageGrid::render(wxDC& dc) void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int index, bool hit) { bool selected = false; - auto &file = m_file_sys->GetFile(index, selected); + const FileGridCard &card = m_model->GetFile(index, selected); // Draw thumbnail - if (file.thumbnail.IsOk()) { - float hs = (float) m_content_rect.GetWidth() / file.thumbnail.GetWidth(); - float vs = (float) m_content_rect.GetHeight() / file.thumbnail.GetHeight(); - dc.SetUserScale(hs, vs); - dc.DrawBitmap(file.thumbnail, {(int) (pt.x / hs), (int) (pt.y / vs)}); - dc.SetUserScale(1, 1); - if (m_file_sys->GetGroupMode() != PrinterFileSystem::G_NONE) { dc.DrawBitmap(m_title_mask, pt); } + if (card.thumbnail.IsOk()) { + if (m_model->preserve_thumbnail_aspect()) { + // Contain: fit the whole thumbnail and letterbox against the tile background. + float scale = std::min((float) m_content_rect.GetWidth() / card.thumbnail.GetWidth(), + (float) m_content_rect.GetHeight() / card.thumbnail.GetHeight()); + int thumb_w = (int) (card.thumbnail.GetWidth() * scale); + int thumb_h = (int) (card.thumbnail.GetHeight() * scale); + int offx = (m_content_rect.GetWidth() - thumb_w) / 2; + int offy = (m_content_rect.GetHeight() - thumb_h) / 2; + auto brush = dc.GetBrush(); + auto pen = dc.GetPen(); + dc.SetBrush(StateColor::darkModeColorFor(0xEEEEEE)); + dc.SetPen(StateColor::darkModeColorFor(0xEEEEEE)); + dc.DrawRectangle(pt, m_content_rect.GetSize()); + dc.SetUserScale(scale, scale); + dc.DrawBitmap(card.thumbnail, {(int) ((pt.x + offx) / scale), (int) ((pt.y + offy) / scale)}); + dc.SetUserScale(1, 1); + dc.SetBrush(brush); + dc.SetPen(pen); + } else { + float hs = (float) m_content_rect.GetWidth() / card.thumbnail.GetWidth(); + float vs = (float) m_content_rect.GetHeight() / card.thumbnail.GetHeight(); + dc.SetUserScale(hs, vs); + dc.DrawBitmap(card.thumbnail, {(int) (pt.x / hs), (int) (pt.y / vs)}); + dc.SetUserScale(1, 1); + } + if (m_model->GetGroupMode() != FileGridGroup::All) { dc.DrawBitmap(m_title_mask, pt); } } bool show_download_state_always = true; // Draw checked icon @@ -634,14 +661,14 @@ void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int ind dc.DrawBitmap(selected ? m_checked_icon.bmp() : m_unchecked_icon.bmp(), pt + wxPoint{10, 10}); // can't handle alpha // dc.GradientFillLinear({pt.x, pt.y, m_border_size.GetWidth(), 60}, wxColour(0x6F, 0x6F, 0x6F, 0x99), wxColour(0x6F, 0x6F, 0x6F, 0), wxBOTTOM); - else if (m_file_sys->GetGroupMode() == PrinterFileSystem::G_NONE) { + else if (m_model->GetGroupMode() == FileGridGroup::All) { wxString nonHoverText; wxString secondAction = m_show_download ? _L("Download") : ""; wxString thirdAction; int states = 0; // Draw download progress - if (file.IsDownload()) { - int progress = file.DownloadProgress(); + if (card.downloading) { + int progress = card.download_progress; if (progress == -1) { secondAction = _L("Cancel"); nonHoverText = _L("Download waiting..."); @@ -659,7 +686,7 @@ void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int ind thirdAction = wxString::Format(L"%d%%...", progress); } } - if (m_file_sys->GetFileType() == PrinterFileSystem::F_MODEL) { + if (m_model->GetFileType() == FileGridType::Model && card.printable) { if (secondAction != _L("Play")) thirdAction = secondAction; secondAction = _L_CONTEXT("Print", "Verb"); @@ -669,7 +696,8 @@ void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int ind wxArrayString texts; if (hit) { texts.Add(_L("Delete")); - texts.Add(secondAction); + if (hasSecondAction(card)) + texts.Add(secondAction); if (!thirdAction.IsEmpty()) texts.Add(thirdAction); renderButtons(dc, texts, rect, m_hit_type == HIT_ACTION ? m_hit_item & 3 : -1, states); @@ -679,7 +707,7 @@ void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int ind } } else { dc.SetTextForeground(*wxWHITE); // time text color - auto date = wxDateTime((time_t) file.time).Format(_L(TIME_FORMATS[m_file_sys->GetGroupMode()])); + auto date = wxDateTime((time_t) card.time).Format(_L(TIME_FORMATS[static_cast(m_model->GetGroupMode())])); dc.DrawText(date, pt + wxPoint{24, 16}); } if (m_selecting && show_download_state_always) @@ -688,7 +716,7 @@ void Slic3r::GUI::ImageGrid::renderContent1(wxDC &dc, wxPoint const &pt, int ind void Slic3r::GUI::ImageGrid::renderContent2(wxDC &dc, wxPoint const &pt, int index, bool hit) { - auto &file = m_file_sys->GetFile(index); + const FileGridCard &card = m_model->GetFile(index); // Draw thumbnail & buttons int h = m_content_rect.GetHeight() * 64 / 264; m_content_rect.SetHeight(m_content_rect.GetHeight() - h); @@ -711,14 +739,14 @@ void Slic3r::GUI::ImageGrid::renderContent2(wxDC &dc, wxPoint const &pt, int ind auto em = em_unit(this); wxRect rect{pt.x, pt.y + m_content_rect.GetHeight() - h, m_content_rect.GetWidth(), h / 2}; rect.Deflate(em, 0); - renderText2(dc, from_u8(file.name), rect); + renderText2(dc, from_u8(card.name), rect); rect.Offset(0, h / 2); rect.SetWidth(rect.GetWidth() / 2 - em); dc.SetFont(Label::Body_13); dc.SetTextForeground(StateColor::darkModeColorFor("#6B6B6B")); - renderIconText(dc, m_model_time_icon, file.Metadata("Time", "0m"), rect); + renderIconText(dc, m_model_time_icon, card.time_text.empty() ? wxString("0m") : from_u8(card.time_text), rect); rect.Offset(m_content_rect.GetWidth() / 2, 0); - renderIconText(dc, m_model_weight_icon, file.Metadata("Weight", "0g"), rect); + renderIconText(dc, m_model_weight_icon, card.weight_text.empty() ? wxString("0g") : from_u8(card.weight_text), rect); } void Slic3r::GUI::ImageGrid::renderButtons(wxDC &dc, wxArrayString const &texts, wxRect const &rect2, size_t hit, int states) diff --git a/src/slic3r/GUI/ImageGrid.h b/src/slic3r/GUI/ImageGrid.h index b2025c91ed..9fd38d2125 100644 --- a/src/slic3r/GUI/ImageGrid.h +++ b/src/slic3r/GUI/ImageGrid.h @@ -23,6 +23,7 @@ #include "Widgets/StateColor.hpp" #include "wxExtensions.hpp" +#include "Printer/IFileGridModel.h" class Button; class Label; @@ -44,6 +45,8 @@ public: void SetFileSystem(boost::shared_ptr file_sys); + void SetModel(boost::shared_ptr model); + void SetStatus(ScalableBitmap const & icon, wxString const &msg); boost::shared_ptr GetFileSystem() { return m_file_sys; } @@ -76,9 +79,12 @@ protected: std::pair HitTest(wxPoint const &pt); + // True when the hover bar shows a second action next to Delete. + bool hasSecondAction(const FileGridCard &card) const; + protected: - void changedEvent(wxCommandEvent& evt); + void onModelChange(FileGridChange change); void paintEvent(wxPaintEvent& evt); @@ -117,6 +123,7 @@ protected: private: boost::shared_ptr m_file_sys; + boost::shared_ptr m_model; ScalableBitmap m_status_icon; wxString m_status_msg; diff --git a/src/slic3r/GUI/MediaFilePanel.cpp b/src/slic3r/GUI/MediaFilePanel.cpp index 23aff37f77..143207cfdf 100644 --- a/src/slic3r/GUI/MediaFilePanel.cpp +++ b/src/slic3r/GUI/MediaFilePanel.cpp @@ -230,7 +230,13 @@ MediaFilePanel::MediaFilePanel(wxWindow * parent) }); }; Bind(wxEVT_SHOW, onShowHide); - parent->GetParent()->Bind(wxEVT_SHOW, onShowHide); + // Watch the page host's show/hide. Walk up past any wrapper containers (e.g. a + // StoragePanel) so the target stays the same regardless of nesting depth. + wxWindow* host = parent; + while (host && !host->IsTopLevel() && host->GetParent() && !host->GetParent()->IsTopLevel()) + host = host->GetParent(); + if (host && host != this) + host->Bind(wxEVT_SHOW, onShowHide); m_lan_user = "bblp"; } diff --git a/src/slic3r/GUI/Monitor.cpp b/src/slic3r/GUI/Monitor.cpp index b05ededd62..5735060dfa 100644 --- a/src/slic3r/GUI/Monitor.cpp +++ b/src/slic3r/GUI/Monitor.cpp @@ -16,7 +16,6 @@ #include "slic3r/GUI/StatusPanel.hpp" #include "slic3r/GUI/UpgradePanel.hpp" #include "slic3r/GUI/Widgets/SideTools.hpp" -#include "slic3r/GUI/Printer/PrinterFileSystem.h" #include #include #include @@ -47,7 +46,7 @@ #include "Widgets/Label.hpp" #include "format.hpp" #include "MediaPlayCtrl.h" -#include "MediaFilePanel.h" +#include "StoragePanel.h" #include "Plater.hpp" #include "BindDialog.hpp" @@ -198,9 +197,9 @@ void MonitorPanel::init_tabpanel() m_tabpanel->SetBackgroundColour(wxColour("#FEFFFF")); m_tabpanel->Bind(wxEVT_BOOKCTRL_PAGE_CHANGED, [this](wxBookCtrlEvent& e) { auto page = m_tabpanel->GetCurrentPage(); - if (page == m_media_file_panel) { + if (page == m_storage_panel) { auto title = m_tabpanel->GetPageText(m_tabpanel->GetSelection()); - m_media_file_panel->SwitchStorage(title == _L("Storage")); + m_storage_panel->SwitchStorage(title == _L("Storage")); } // The first page is selected while the panel is built off screen. if (page->IsShownOnScreen()) @@ -214,8 +213,8 @@ void MonitorPanel::init_tabpanel() add_build_steps_of(*m_status_info_panel); m_tabpanel->AddPage(m_status_info_panel, _L("Status"), true); add_build_step([this] { - m_media_file_panel = new MediaFilePanel(m_tabpanel); - m_tabpanel->AddPage(m_media_file_panel, _L("Storage"), false); + m_storage_panel = new StoragePanel(m_tabpanel); + m_tabpanel->AddPage(m_storage_panel, _L("Storage"), false); }); add_build_step([this] { m_upgrade_panel = new UpgradePanel(m_tabpanel); @@ -264,7 +263,8 @@ void MonitorPanel::on_sys_color_changed() { m_status_info_panel->on_sys_color_changed(); m_upgrade_panel->on_sys_color_changed(); - m_media_file_panel->Rescale(); + m_storage_panel->on_sys_color_changed(); + m_storage_panel->Rescale(); } void MonitorPanel::msw_rescale() @@ -276,7 +276,7 @@ void MonitorPanel::msw_rescale() m_tabpanel->Rescale(); //m_status_add_machine_panel->msw_rescale(); m_status_info_panel->msw_rescale(); - m_media_file_panel->Rescale(); + m_storage_panel->Rescale(); m_upgrade_panel->msw_rescale(); m_hms_panel->msw_rescale(); @@ -423,8 +423,8 @@ void MonitorPanel::update_all() } } else if (current_page == m_upgrade_panel) { m_upgrade_panel->update(obj); - } else if (current_page == m_media_file_panel) { - m_media_file_panel->UpdateByObj(obj); + } else if (current_page == m_storage_panel) { + m_storage_panel->UpdateByObj(obj); } if (current_page == m_hms_panel || (obj->GetHMS()->GetHMSItems().size() != m_hms_panel->temp_hms_list.size())) { diff --git a/src/slic3r/GUI/Monitor.hpp b/src/slic3r/GUI/Monitor.hpp index ce7fcf0570..88f64685e8 100644 --- a/src/slic3r/GUI/Monitor.hpp +++ b/src/slic3r/GUI/Monitor.hpp @@ -60,7 +60,7 @@ namespace Slic3r { namespace GUI { -class MediaFilePanel; +class StoragePanel; class AddMachinePanel : public wxPanel { @@ -86,7 +86,7 @@ private: wxSizer* m_main_sizer{ nullptr }; StatusPanel* m_status_info_panel{ nullptr }; - MediaFilePanel* m_media_file_panel{ nullptr }; + StoragePanel* m_storage_panel{ nullptr }; UpgradePanel* m_upgrade_panel{ nullptr }; HMSPanel* m_hms_panel{ nullptr }; diff --git a/src/slic3r/GUI/OrcaFilesPanel.cpp b/src/slic3r/GUI/OrcaFilesPanel.cpp new file mode 100644 index 0000000000..6a5cda0016 --- /dev/null +++ b/src/slic3r/GUI/OrcaFilesPanel.cpp @@ -0,0 +1,268 @@ +#include "OrcaFilesPanel.h" + +#include "DeviceManager.hpp" +#include "GUI_App.hpp" +#include "GUI.hpp" +#include "I18N.hpp" +#include "ImageGrid.h" +#include "MsgDialog.hpp" +#include "Widgets/Button.hpp" +#include "Widgets/Label.hpp" +#include "Widgets/StaticBox.hpp" +#include "Widgets/StateColor.hpp" +#include "slic3r/Utils/NetworkAgent.hpp" +#include "slic3r/Utils/bambu_networking.hpp" + +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +OrcaFilesPanel::OrcaFilesPanel(wxWindow* parent) + : wxPanel(parent, wxID_ANY) + , m_bmp_loading(this, "media_loading", 0) + , m_bmp_failed(this, "media_failed", 0) + , m_bmp_empty(this, "media_empty", 0) +{ + const wxColour light_background("#EEEEEE"); + SetBackgroundColour(wxGetApp().dark_mode() ? StateColor::darkModeColorFor(light_background) : light_background); + + auto* sizer = new wxBoxSizer(wxVERTICAL); + auto* toolbar = new wxBoxSizer(wxHORIZONTAL); + toolbar->SetMinSize({-1, 75 * em_unit(this) / 10}); + + m_root_label = new Label(this, _L("gcodes")); + m_root_label->SetFont(Label::Head_16); + toolbar->Add(m_root_label, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, 24); + + m_time_panel = new ::StaticBox(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); + m_time_panel->SetCornerRadius(0); + m_button_year = new ::Button(m_time_panel, _L("Year"), "", wxBORDER_NONE); + m_button_month = new ::Button(m_time_panel, _L("Month"), "", wxBORDER_NONE); + m_button_all = new ::Button(m_time_panel, _L("All Files"), "", wxBORDER_NONE); + m_button_year->SetToolTip(_L("Group files by year, recent first.")); + m_button_month->SetToolTip(_L("Group files by month, recent first.")); + m_button_all->SetToolTip(_L("Show all files, recent first.")); + for (auto* button : {m_button_year, m_button_month, m_button_all}) { + button->SetBackgroundColor(StateColor( + std::make_pair(0xEEEEEE, static_cast(StateColor::Checked)), + std::make_pair(*wxLIGHT_GREY, static_cast(StateColor::Hovered)), + std::make_pair(*wxWHITE, static_cast(StateColor::Normal)))); + button->SetTextColor(StateColor( + std::make_pair(0x3B4446, static_cast(StateColor::Checked)), + std::make_pair(*wxLIGHT_GREY, static_cast(StateColor::Hovered)), + std::make_pair(0xABACAC, static_cast(StateColor::Normal)))); + button->SetCanFocus(false); + } + auto* time_sizer = new wxBoxSizer(wxHORIZONTAL); + time_sizer->Add(m_button_year, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 24); + time_sizer->Add(m_button_month, 0, wxALIGN_CENTER_VERTICAL); + time_sizer->Add(m_button_all, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 24); + m_time_panel->SetSizer(time_sizer); + toolbar->AddStretchSpacer(1); + toolbar->Add(m_time_panel, 0, wxALIGN_CENTER_VERTICAL); + toolbar->AddStretchSpacer(1); + + m_button_refresh = new ::Button(this, _L("Refresh")); + m_button_refresh->SetToolTip(_L("Reload file list from printer.")); + m_button_refresh->SetFont(Label::Body_12); + m_button_refresh->SetCornerRadius(12); + m_button_refresh->SetPaddingSize({10, 6}); + m_button_refresh->SetCanFocus(false); + m_button_refresh->SetBorderWidth(0); + toolbar->Add(m_button_refresh, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 24); + sizer->Add(toolbar, 0, wxEXPAND); + + m_image_grid = new ImageGrid(this); + // Theme this grid instance without changing the shared Bambu defaults. + m_image_grid->SetBackgroundColour(GetBackgroundColour()); + m_image_grid->SetSelecting(false); + m_image_grid->ShowDownload(false); + m_image_grid->SetStatus(m_bmp_failed, _L("Please confirm if the printer is connected.")); + sizer->Add(m_image_grid, 1, wxEXPAND); + SetSizer(sizer); + applyThemeColors(); + updateGroupButtons(m_group_mode); + + auto group_clicked = [this](wxCommandEvent& event) { + const FileGridGroup mode = event.GetEventObject() == m_button_year ? FileGridGroup::Year : + event.GetEventObject() == m_button_month ? FileGridGroup::Month : FileGridGroup::All; + m_image_grid->SetGroupMode(static_cast(mode)); + updateGroupButtons(mode); + }; + m_button_year->Bind(wxEVT_COMMAND_BUTTON_CLICKED, group_clicked); + m_button_month->Bind(wxEVT_COMMAND_BUTTON_CLICKED, group_clicked); + m_button_all->Bind(wxEVT_COMMAND_BUTTON_CLICKED, group_clicked); + + m_button_refresh->Bind(wxEVT_COMMAND_BUTTON_CLICKED, [this](wxCommandEvent& event) { + event.Skip(); + if (m_model) + m_model->Refresh(); + }); + + m_image_grid->Bind(EVT_ITEM_ACTION, [this](wxCommandEvent& event) { + const int action = event.GetInt(); + if (!m_model || m_device_id.empty()) + return; + + const size_t index = static_cast(event.GetExtraLong()); + if (index >= m_model->GetCount()) + return; + const FileGridCard& card = m_model->GetFile(index); + if (card.id.empty()) + return; + const std::string path = card.id; + const std::string name = card.name; + + if (action == 0) { + MessageDialog dlg(this, + wxString::Format(_L("Do you want to delete the file '%s' from printer?"), from_u8(name)), + _L("Delete file"), wxYES_NO | wxICON_WARNING); + if (dlg.ShowModal() != wxID_YES) + return; + + m_model->DeleteFile(path, [this](bool ok) { + if (ok) + return; + MessageDialog(this, _L("Failed to delete the file from printer."), _L("Delete file"), + wxOK | wxICON_ERROR).ShowModal(); + }); + } else if (action == 1) { + // Print is .gcode-only for now; .gcode.3mf support to be added later. + MessageDialog dlg(this, + wxString::Format(_L("Do you want to print the file '%s' from printer?"), from_u8(name)), + _L("Print file"), wxYES_NO | wxICON_WARNING); + if (dlg.ShowModal() != wxID_YES) + return; + + NetworkAgent* agent = wxGetApp().getAgent(); + if (!agent) + return; + + PrintParams params; + params.dev_id = m_device_id; + params.dst_file = path; + params.connection_type = "lan"; + if (agent->start_sdcard_print(params, {}, {}) != BAMBU_NETWORK_SUCCESS) + MessageDialog(this, _L("Failed to start the print job."), _L("Print file"), + wxOK | wxICON_ERROR).ShowModal(); + } + }); +} + +OrcaFilesPanel::~OrcaFilesPanel() +{ + if (m_model) + m_model->SetStatusHandler({}); + if (m_model) + m_model->SetGroupModeHandler({}); + m_image_grid->SetModel(nullptr); + m_model.reset(); +} + +void OrcaFilesPanel::UpdateByObj(MachineObject* obj) +{ + const std::string device_id = obj ? obj->get_dev_id() : std::string(); + if (device_id == m_device_id) + return; + + m_device_id = device_id; + if (m_model) + m_model->SetStatusHandler({}); + if (m_model) + m_model->SetGroupModeHandler({}); + m_image_grid->SetModel(nullptr); + m_model.reset(); + + if (m_device_id.empty()) { + m_button_refresh->Enable(false); + m_image_grid->SetStatus(m_bmp_failed, _L("Please confirm if the printer is connected.")); + return; + } + + m_model = boost::make_shared(m_device_id); + m_model->SetStatusHandler([this](RemoteFileGridModel::Status status) { updateStatus(status); }); + m_model->SetGroupModeHandler([this](FileGridGroup mode) { updateGroupButtons(mode); }); + m_model->SetGroupMode(m_group_mode); + m_image_grid->SetModel(m_model); + m_image_grid->SetFileType(static_cast(FileGridType::Model), {}); + m_button_refresh->Enable(true); + m_model->Refresh(); +} + +void OrcaFilesPanel::updateStatus(RemoteFileGridModel::Status status) +{ + switch (status) { + case RemoteFileGridModel::Status::Loading: + m_image_grid->SetStatus(m_bmp_loading, _L("Loading file list...")); + break; + case RemoteFileGridModel::Status::Ready: + break; + case RemoteFileGridModel::Status::Empty: + m_image_grid->SetStatus(m_bmp_empty, _L("No files")); + break; + case RemoteFileGridModel::Status::Failed: + m_image_grid->SetStatus(m_bmp_failed, _L("Load failed")); + break; + } +} + +void OrcaFilesPanel::Rescale() +{ + m_bmp_loading.msw_rescale(); + m_bmp_failed.msw_rescale(); + m_bmp_empty.msw_rescale(); + + auto* toolbar = GetSizer()->GetItem(static_cast(0))->GetSizer(); + toolbar->SetMinSize({-1, 75 * em_unit(this) / 10}); + m_root_label->SetFont(Label::Head_16); + m_button_refresh->Rescale(); + m_button_year->Rescale(); + m_button_month->Rescale(); + m_button_all->Rescale(); + m_image_grid->Rescale(); +} + +void OrcaFilesPanel::on_sys_color_changed() +{ + applyThemeColors(); + Layout(); + Refresh(); +} + +void OrcaFilesPanel::applyThemeColors() +{ + const bool dark = wxGetApp().dark_mode(); + const wxColour light_background("#EEEEEE"); + const wxColour light_text("#262E30"); + const wxColour light_teal("#009688"); + const wxColour background = dark ? StateColor::darkModeColorFor(light_background) : light_background; + + SetBackgroundColour(background); + m_root_label->SetBackgroundColour(background); + m_root_label->SetForegroundColour(dark ? StateColor::darkModeColorFor(light_text) : light_text); + m_time_panel->SetBackgroundColour(background); + m_button_refresh->SetBackgroundColorNormal(dark ? StateColor::darkModeColorFor(light_teal) : light_teal); + m_button_refresh->SetTextColorNormal(*wxWHITE); + m_image_grid->SetBackgroundColour(background); + m_image_grid->Refresh(); + m_button_year->Refresh(); + m_button_month->Refresh(); + m_button_all->Refresh(); +} + +void OrcaFilesPanel::updateGroupButtons(FileGridGroup mode) +{ + m_group_mode = mode; + ::Button* buttons[] = {m_button_all, m_button_month, m_button_year}; + const int selected = static_cast(mode); + for (int i = 0; i < 3; ++i) { + buttons[i]->SetValue(i == selected); + buttons[i]->SetFont(i == selected ? Label::Head_14 : Label::Body_14); + } +} + +}} diff --git a/src/slic3r/GUI/OrcaFilesPanel.h b/src/slic3r/GUI/OrcaFilesPanel.h new file mode 100644 index 0000000000..0257afc49f --- /dev/null +++ b/src/slic3r/GUI/OrcaFilesPanel.h @@ -0,0 +1,51 @@ +#pragma once + +#include "GUI_Utils.hpp" +#include "wxExtensions.hpp" +#include "Printer/RemoteFileGridModel.h" + +#include +#include + +class Button; +class Label; +class StaticBox; + +namespace Slic3r { +class MachineObject; + +namespace GUI { + +class ImageGrid; + +class OrcaFilesPanel : public wxPanel +{ +public: + explicit OrcaFilesPanel(wxWindow* parent); + ~OrcaFilesPanel() override; + + void UpdateByObj(MachineObject* obj); + void Rescale(); + void on_sys_color_changed(); + +private: + void applyThemeColors(); + void updateGroupButtons(FileGridGroup mode); + void updateStatus(RemoteFileGridModel::Status status); + + ScalableBitmap m_bmp_loading; + ScalableBitmap m_bmp_failed; + ScalableBitmap m_bmp_empty; + Label* m_root_label = nullptr; + ::StaticBox* m_time_panel = nullptr; + ::Button* m_button_year = nullptr; + ::Button* m_button_month = nullptr; + ::Button* m_button_all = nullptr; + ::Button* m_button_refresh = nullptr; + ImageGrid* m_image_grid = nullptr; + boost::shared_ptr m_model; + std::string m_device_id; + FileGridGroup m_group_mode = FileGridGroup::All; +}; + +}} diff --git a/src/slic3r/GUI/Printer/BambuFileGridModel.cpp b/src/slic3r/GUI/Printer/BambuFileGridModel.cpp new file mode 100644 index 0000000000..eaa1aa47ca --- /dev/null +++ b/src/slic3r/GUI/Printer/BambuFileGridModel.cpp @@ -0,0 +1,197 @@ +#include "BambuFileGridModel.h" + +#include "slic3r/GUI/GUI_App.hpp" + +#include + +namespace Slic3r { +namespace GUI { + +static const FileGridCard& emptyCard() +{ + static const FileGridCard card; + return card; +} + +BambuFileGridModel::BambuFileGridModel(boost::shared_ptr fs) + : m_fs(std::move(fs)) +{ + if (m_fs) { + m_fs->Bind(EVT_FILE_CHANGED, &BambuFileGridModel::onFileChanged, this); + m_fs->Bind(EVT_MODE_CHANGED, &BambuFileGridModel::onModeChanged, this); + m_fs->Bind(EVT_THUMBNAIL, &BambuFileGridModel::onThumbnail, this); + m_fs->Bind(EVT_DOWNLOAD, &BambuFileGridModel::onDownload, this); + } +} + +BambuFileGridModel::~BambuFileGridModel() +{ + if (m_fs) { + m_fs->Unbind(EVT_FILE_CHANGED, &BambuFileGridModel::onFileChanged, this); + m_fs->Unbind(EVT_MODE_CHANGED, &BambuFileGridModel::onModeChanged, this); + m_fs->Unbind(EVT_THUMBNAIL, &BambuFileGridModel::onThumbnail, this); + m_fs->Unbind(EVT_DOWNLOAD, &BambuFileGridModel::onDownload, this); + } +} + +void BambuFileGridModel::EnsureCards() const +{ + if (!m_dirty && (!m_fs || m_cards.size() == m_fs->GetCount())) + return; + m_dirty = false; + m_cards.clear(); + if (!m_fs) + return; + size_t count = m_fs->GetCount(); + m_cards.reserve(count); + for (size_t i = 0; i < count; ++i) { + bool selected = false; + PrinterFileSystem::File const &file = m_fs->GetFile(i, selected); + FileGridCard card; + card.id = file.path; + card.name = file.name; + card.title = file.Title(); + card.time_text = file.Metadata("Time", ""); + card.weight_text = file.Metadata("Weight", ""); + card.time = file.time; + card.downloading = file.IsDownload(); + card.download_progress = file.DownloadProgress(); + card.selected = selected; + card.thumbnail = file.thumbnail; + m_cards.push_back(std::move(card)); + } +} + +size_t BambuFileGridModel::GetCount() const +{ + return m_fs ? m_fs->GetCount() : 0; +} + +const FileGridCard& BambuFileGridModel::GetFile(size_t index, bool& selected) const +{ + EnsureCards(); + if (!m_fs || index >= m_cards.size()) { + selected = false; + return emptyCard(); + } + m_fs->GetFile(index, selected); + return m_cards[index]; +} + +const FileGridCard& BambuFileGridModel::GetFile(size_t index) const +{ + EnsureCards(); + if (index >= m_cards.size()) + return emptyCard(); + return m_cards[index]; +} + +FileGridType BambuFileGridModel::GetFileType() const +{ + return m_fs ? static_cast(m_fs->GetFileType()) : FileGridType::Timelapse; +} + +void BambuFileGridModel::SetFileType(FileGridType type, const std::string& storage) +{ + if (m_fs) + m_fs->SetFileType(static_cast(type), storage); +} + +FileGridGroup BambuFileGridModel::GetGroupMode() const +{ + return m_fs ? static_cast(m_fs->GetGroupMode()) : FileGridGroup::All; +} + +void BambuFileGridModel::SetGroupMode(FileGridGroup mode) +{ + if (m_fs) + m_fs->SetGroupMode(static_cast(mode)); +} + +size_t BambuFileGridModel::GetIndexAtTime(time_t time) const +{ + return m_fs ? m_fs->GetIndexAtTime(static_cast(time)) : 0; +} + +size_t BambuFileGridModel::EnterSubGroup(size_t index) +{ + return m_fs ? m_fs->EnterSubGroup(index) : index; +} + +void BambuFileGridModel::ToggleSelect(size_t index) +{ + if (m_fs) + m_fs->ToggleSelect(index); +} + +void BambuFileGridModel::SelectAll(bool select) +{ + if (m_fs) + m_fs->SelectAll(select); +} + +void BambuFileGridModel::SetFocusRange(size_t start, size_t count) +{ + if (m_fs) + m_fs->SetFocusRange(start, count); +} + +void BambuFileGridModel::Retry() +{ + if (m_fs) + m_fs->Retry(); +} + +int BambuFileGridModel::GetLastError() const +{ + return m_fs ? m_fs->GetLastError() : 1; +} + +void BambuFileGridModel::DownloadCheckFiles(const std::string& path) +{ + if (m_fs) + m_fs->DownloadCheckFiles(path); +} + +void BambuFileGridModel::SetChangeHandler(std::function handler) +{ + m_handler = std::move(handler); +} + +void BambuFileGridModel::notify(FileGridChange change) +{ + if (m_handler) + m_handler(change); +} + +void BambuFileGridModel::onFileChanged(wxCommandEvent& evt) +{ + evt.Skip(); + if (evt.GetInt() == -1 && m_fs) + m_fs->DownloadCheckFiles(wxGetApp().app_config->get("download_path")); + m_dirty = true; + notify(FileGridChange::Files); +} + +void BambuFileGridModel::onModeChanged(wxCommandEvent& evt) +{ + evt.Skip(); + m_dirty = true; + notify(FileGridChange::Mode); +} + +void BambuFileGridModel::onThumbnail(wxCommandEvent& evt) +{ + evt.Skip(); + m_dirty = true; + notify(FileGridChange::Thumbnail); +} + +void BambuFileGridModel::onDownload(wxCommandEvent& evt) +{ + evt.Skip(); + m_dirty = true; + notify(FileGridChange::Download); +} + +}} diff --git a/src/slic3r/GUI/Printer/BambuFileGridModel.h b/src/slic3r/GUI/Printer/BambuFileGridModel.h new file mode 100644 index 0000000000..93a4fccbd4 --- /dev/null +++ b/src/slic3r/GUI/Printer/BambuFileGridModel.h @@ -0,0 +1,61 @@ +#pragma once + +#include "IFileGridModel.h" +#include "PrinterFileSystem.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +// IFileGridModel over PrinterFileSystem, behavior-identical to ImageGrid's direct use. +class BambuFileGridModel : public wxEvtHandler, public IFileGridModel +{ +public: + explicit BambuFileGridModel(boost::shared_ptr fs); + ~BambuFileGridModel() override; + + size_t GetCount() const override; + const FileGridCard& GetFile(size_t index, bool& selected) const override; + const FileGridCard& GetFile(size_t index) const override; + + FileGridType GetFileType() const override; + void SetFileType(FileGridType type, const std::string& storage) override; + FileGridGroup GetGroupMode() const override; + void SetGroupMode(FileGridGroup mode) override; + + size_t GetIndexAtTime(time_t time) const override; + size_t EnterSubGroup(size_t index) override; + + void ToggleSelect(size_t index) override; + void SelectAll(bool select) override; + void SetFocusRange(size_t start, size_t count) override; + + void Retry() override; + int GetLastError() const override; + void DownloadCheckFiles(const std::string& path) override; + + void SetChangeHandler(std::function handler) override; + +private: + void EnsureCards() const; + void notify(FileGridChange change); + + void onFileChanged(wxCommandEvent& evt); + void onModeChanged(wxCommandEvent& evt); + void onThumbnail(wxCommandEvent& evt); + void onDownload(wxCommandEvent& evt); + + boost::shared_ptr m_fs; + std::function m_handler; + mutable std::vector m_cards; + mutable bool m_dirty = true; +}; + +}} diff --git a/src/slic3r/GUI/Printer/IFileGridModel.h b/src/slic3r/GUI/Printer/IFileGridModel.h new file mode 100644 index 0000000000..6f9ea775b7 --- /dev/null +++ b/src/slic3r/GUI/Printer/IFileGridModel.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +// Mirrors PrinterFileSystem::FileType ordering (F_TIMELAPSE=0, F_VIDEO=1, F_MODEL=2). +enum class FileGridType { Timelapse = 0, Video = 1, Model = 2 }; +// Mirrors PrinterFileSystem::GroupMode ordering (G_NONE=0, G_MONTH=1, G_YEAR=2). +enum class FileGridGroup { All = 0, Month = 1, Year = 2 }; +// Mirrors the PrinterFileSystem wx events ImageGrid listens to. +enum class FileGridChange { Files, Mode, Thumbnail, Download }; + +// One rendered card. Neutral: no Bambu transfer internals, no filesystem paths beyond id. +struct FileGridCard { + std::string id; + std::string name; + std::string title; + std::string time_text; + std::string weight_text; + time_t time = 0; + bool downloading = false; + int download_progress = 0; // -1 waiting, <0 failed, 0..100 progress + bool selected = false; + bool printable = true; + wxBitmap thumbnail; +}; + +// Data source behind ImageGrid. Implemented today by BambuFileGridModel (wrapping +// PrinterFileSystem); a non-Bambu model can implement the same surface later. +class IFileGridModel { +public: + virtual ~IFileGridModel() = default; + + virtual size_t GetCount() const = 0; + virtual const FileGridCard& GetFile(size_t index, bool& selected) const = 0; + virtual const FileGridCard& GetFile(size_t index) const = 0; + + virtual FileGridType GetFileType() const = 0; + virtual void SetFileType(FileGridType type, const std::string& storage) = 0; + virtual FileGridGroup GetGroupMode() const = 0; + virtual void SetGroupMode(FileGridGroup mode) = 0; + + // When true, the thumbnail is fitted inside the tile instead of stretched to fill it. + virtual bool preserve_thumbnail_aspect() const { return false; } + + virtual size_t GetIndexAtTime(time_t time) const = 0; + virtual size_t EnterSubGroup(size_t index) = 0; + + virtual void ToggleSelect(size_t index) = 0; + virtual void SelectAll(bool select) = 0; + virtual void SetFocusRange(size_t start, size_t count) = 0; + + virtual void Retry() = 0; + virtual int GetLastError() const = 0; + virtual void DownloadCheckFiles(const std::string& path) = 0; + + // ImageGrid sets one handler; the model invokes it on the UI thread on change. + virtual void SetChangeHandler(std::function) = 0; +}; + +}} diff --git a/src/slic3r/GUI/Printer/RemoteFileGridModel.cpp b/src/slic3r/GUI/Printer/RemoteFileGridModel.cpp new file mode 100644 index 0000000000..851c288aea --- /dev/null +++ b/src/slic3r/GUI/Printer/RemoteFileGridModel.cpp @@ -0,0 +1,534 @@ +#include "RemoteFileGridModel.h" + +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/Utils/NetworkAgent.hpp" + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +namespace { + +const FileGridCard& emptyCard() +{ + static const FileGridCard card; + return card; +} + +// Same display format as PrinterFileSystem: "1d2h3m", dropping a leading "0d"/"0h". +std::string durationString(long duration) +{ + static boost::regex rx("^0d(0h)?"); + auto time = boost::format("%1%d%2%h%3%m") % (duration / 86400) % ((duration % 86400) / 3600) % ((duration % 3600) / 60); + return boost::regex_replace(time.str(), rx, ""); +} + +// Case-insensitive suffix test shared by the file filters below. +bool ends_with_ci(const std::string& name, const std::string& suffix) +{ + return name.size() >= suffix.size() && + std::equal(suffix.rbegin(), suffix.rend(), name.rbegin(), + [](char a, char b) { + return std::tolower(static_cast(a)) == + std::tolower(static_cast(b)); + }); +} + +// .gcode / .3mf only, case-insensitive; a .gcode.3mf name matches via the .3mf suffix. +bool is_displayable_file(const std::string& name) +{ + return ends_with_ci(name, ".gcode") || ends_with_ci(name, ".3mf"); +} + +// Only .gcode is printable today; .gcode.3mf support to be added later. +bool is_printable_gcode(const std::string& name) +{ + return ends_with_ci(name, ".gcode"); +} + +} + +RemoteFileGridModel::RemoteFileGridModel(std::string device_id) + : m_device_id(std::move(device_id)) +{ +} + +RemoteFileGridModel::~RemoteFileGridModel() +{ + m_lifetime.reset(); +} + +void RemoteFileGridModel::Refresh() +{ + const std::uint64_t request = ++m_request; + const std::string device_id = m_device_id; + m_thumbnail_cache.clear(); + m_thumbnail_requested.clear(); + m_thumbnail_queue.clear(); + m_metadata_cache.clear(); + m_metadata_requested.clear(); + m_metadata_queue.clear(); + for (FileGridCard& card : m_cards) + card.thumbnail = wxBitmap(); + m_last_error = 0; + setStatus(Status::Loading); + + NetworkAgent* agent = wxGetApp().getAgent(); + if (!agent) { + m_last_error = -1; + m_cards.clear(); + m_month.clear(); + m_year.clear(); + setStatus(Status::Failed); + if (m_change_handler) + m_change_handler(FileGridChange::Files); + return; + } + + std::weak_ptr lifetime = m_lifetime; + int result = agent->list_printer_files(device_id, + [this, lifetime, request, device_id](int result, std::vector files) { + if (lifetime.expired()) + return; + onFilesLoaded(request, device_id, result, std::move(files)); + }); + + if (result != 0 && request == m_request && m_status == Status::Loading) { + m_last_error = result; + m_cards.clear(); + m_month.clear(); + m_year.clear(); + setStatus(Status::Failed); + if (m_change_handler) + m_change_handler(FileGridChange::Files); + } +} + +void RemoteFileGridModel::onFilesLoaded(std::uint64_t request, const std::string& device_id, int result, + std::vector files) +{ + if (request != m_request || device_id != m_device_id) + return; + + m_last_error = result; + m_cards.clear(); + if (result == 0) { + files.erase(std::remove_if(files.begin(), files.end(), + [](const PrinterFileEntry& file) { return !is_displayable_file(file.name); }), + files.end()); + std::sort(files.begin(), files.end(), [](const PrinterFileEntry& lhs, const PrinterFileEntry& rhs) { + return lhs.modified > rhs.modified; + }); + m_cards.reserve(files.size()); + for (const PrinterFileEntry& file : files) { + FileGridCard card; + card.id = file.path; + card.name = file.name; + card.time = static_cast(file.modified); + card.printable = is_printable_gcode(file.name); + m_cards.emplace_back(std::move(card)); + } + buildGroups(); + setStatus(m_cards.empty() ? Status::Empty : Status::Ready); + } else { + m_month.clear(); + m_year.clear(); + setStatus(Status::Failed); + } + + if (m_change_handler) + m_change_handler(FileGridChange::Files); +} + +void RemoteFileGridModel::setStatus(Status status) +{ + m_status = status; + if (m_status_handler) + m_status_handler(status); +} + +void RemoteFileGridModel::SetStatusHandler(std::function handler) +{ + m_status_handler = std::move(handler); +} + +size_t RemoteFileGridModel::GetCount() const +{ + if (m_group_mode == FileGridGroup::Year) + return m_year.size(); + if (m_group_mode == FileGridGroup::Month) + return m_month.size(); + return m_cards.size(); +} + +const FileGridCard& RemoteFileGridModel::GetFile(size_t index, bool& selected) const +{ + selected = false; + const size_t card_index = cardIndexForGroup(index); + if (card_index >= m_cards.size()) + return emptyCard(); + FileGridCard& card = m_cards[card_index]; + const auto thumbnail = m_thumbnail_cache.find(card.id); + card.thumbnail = thumbnail == m_thumbnail_cache.end() ? wxBitmap() : thumbnail->second; + return card; +} + +const FileGridCard& RemoteFileGridModel::GetFile(size_t index) const +{ + bool selected = false; + return GetFile(index, selected); +} + +size_t RemoteFileGridModel::cardIndexForGroup(size_t index) const +{ + if (m_group_mode == FileGridGroup::All) + return index; + if (m_group_mode == FileGridGroup::Month) + return index < m_month.size() ? m_month[index] : m_cards.size(); + return index < m_year.size() && m_year[index] < m_month.size() ? m_month[m_year[index]] : m_cards.size(); +} + +FileGridType RemoteFileGridModel::GetFileType() const +{ + return m_file_type; +} + +void RemoteFileGridModel::SetFileType(FileGridType type, const std::string&) +{ + m_file_type = type; +} + +FileGridGroup RemoteFileGridModel::GetGroupMode() const +{ + return m_group_mode; +} + +void RemoteFileGridModel::SetGroupMode(FileGridGroup mode) +{ + if (mode != FileGridGroup::All && mode != FileGridGroup::Month && mode != FileGridGroup::Year) + return; + if (m_group_mode == mode) + return; + m_group_mode = mode; + if (m_group_mode_handler) + m_group_mode_handler(mode); + if (m_change_handler) + m_change_handler(FileGridChange::Mode); +} + +size_t RemoteFileGridModel::GetIndexAtTime(time_t time) const +{ + if (m_cards.empty()) + return 0; + + size_t low = 0; + size_t high = m_cards.size(); + while (low < high) { + const size_t middle = low + (high - low) / 2; + if (m_cards[middle].time >= time) + low = middle + 1; + else + high = middle; + } + const size_t card_index = low == 0 ? 0 : low - 1; + if (m_group_mode == FileGridGroup::All) + return card_index; + + const auto month = std::upper_bound(m_month.begin(), m_month.end(), card_index); + const size_t month_index = month == m_month.begin() ? 0 : static_cast(month - m_month.begin() - 1); + if (m_group_mode == FileGridGroup::Month) + return month_index; + + const auto year = std::upper_bound(m_year.begin(), m_year.end(), card_index, + [this](size_t file_index, size_t month_index) { + return file_index < m_month[month_index]; + }); + return year == m_year.begin() ? 0 : static_cast(year - m_year.begin() - 1); +} + +size_t RemoteFileGridModel::EnterSubGroup(size_t index) +{ + if (m_group_mode == FileGridGroup::All) + return index; + if (m_group_mode == FileGridGroup::Year) { + if (index >= m_year.size()) + return 0; + index = m_year[index]; + } else { + if (index >= m_month.size()) + return 0; + index = m_month[index]; + } + SetGroupMode(static_cast(static_cast(m_group_mode) - 1)); + return index; +} + +void RemoteFileGridModel::ToggleSelect(size_t) +{ +} + +void RemoteFileGridModel::SelectAll(bool) +{ +} + +void RemoteFileGridModel::SetFocusRange(size_t start, size_t count) +{ + if (m_status == Status::Loading || start >= GetCount()) + return; + const size_t end = start + std::min(count, GetCount() - start); + for (size_t i = start; i < end; ++i) { + const FileGridCard& card = GetFile(i); + if (!card.id.empty()) { + requestThumbnail(card.id); + requestMetadata(card.id); + } + } + pumpThumbnailQueue(); + pumpMetadataQueue(); +} + +void RemoteFileGridModel::Retry() +{ + Refresh(); +} + +int RemoteFileGridModel::GetLastError() const +{ + return m_last_error; +} + +void RemoteFileGridModel::DownloadCheckFiles(const std::string&) +{ +} + +void RemoteFileGridModel::DeleteFile(const std::string& path, std::function done) +{ + NetworkAgent* agent = wxGetApp().getAgent(); + if (!agent || m_device_id.empty() || path.empty()) { + if (done) + done(false); + return; + } + + const std::uint64_t request = m_request; + const std::string device_id = m_device_id; + const std::weak_ptr lifetime = m_lifetime; + const auto completed = std::make_shared(false); + auto finish = [this, lifetime, completed, request, device_id, path, done = std::move(done)](int result) { + if (*completed) + return; + *completed = true; + if (lifetime.expired()) + return; + + const bool ok = result == 0; + if (ok && request == m_request && device_id == m_device_id) { + m_thumbnail_cache.erase(path); + m_thumbnail_requested.erase(path); + m_cards.erase(std::remove_if(m_cards.begin(), m_cards.end(), + [&path](const FileGridCard& card) { return card.id == path; }), + m_cards.end()); + buildGroups(); + setStatus(m_cards.empty() ? Status::Empty : Status::Ready); + if (m_change_handler) + m_change_handler(FileGridChange::Files); + } + if (done) + done(ok); + }; + + const int result = agent->delete_printer_file(device_id, path, finish); + if (result != 0) + finish(result); +} + +void RemoteFileGridModel::SetChangeHandler(std::function handler) +{ + m_change_handler = std::move(handler); +} + +void RemoteFileGridModel::SetGroupModeHandler(std::function handler) +{ + m_group_mode_handler = std::move(handler); +} + +void RemoteFileGridModel::buildGroups() +{ + m_month.clear(); + m_year.clear(); + if (m_cards.empty()) + return; + + m_month.push_back(0); + m_year.push_back(0); + wxDateTime previous(static_cast(m_cards.front().time)); + for (size_t i = 1; i < m_cards.size(); ++i) { + const wxDateTime current(static_cast(m_cards[i].time)); + if (current.GetYear() != previous.GetYear()) { + m_year.push_back(m_month.size()); + m_month.push_back(i); + } else if (current.GetMonth() != previous.GetMonth()) { + m_month.push_back(i); + } + previous = current; + } +} + +void RemoteFileGridModel::requestThumbnail(const std::string& path) +{ + if (m_thumbnail_cache.find(path) != m_thumbnail_cache.end() || !m_thumbnail_requested.insert(path).second) + return; + m_thumbnail_queue.push_back(path); +} + +void RemoteFileGridModel::pumpThumbnailQueue() +{ + constexpr size_t MAX_THUMBNAIL_REQUESTS = 4; + if (m_pumping_thumbnail_queue) + return; + m_pumping_thumbnail_queue = true; + + NetworkAgent* agent = wxGetApp().getAgent(); + if (!agent) { + while (!m_thumbnail_queue.empty()) { + m_thumbnail_cache.emplace(m_thumbnail_queue.front(), wxBitmap()); + m_thumbnail_queue.pop_front(); + } + m_pumping_thumbnail_queue = false; + return; + } + + while (!m_thumbnail_queue.empty() && m_thumbnail_requests_in_flight < MAX_THUMBNAIL_REQUESTS) { + std::string path = std::move(m_thumbnail_queue.front()); + m_thumbnail_queue.pop_front(); + ++m_thumbnail_requests_in_flight; + + const std::uint64_t request = m_request; + const std::string device_id = m_device_id; + const std::weak_ptr lifetime = m_lifetime; + const auto completed = std::make_shared(false); + auto finish = [this, lifetime, completed, request, device_id, path](int result, std::string image) { + if (*completed) + return; + *completed = true; + if (lifetime.expired()) + return; + onThumbnailLoaded(request, device_id, path, result, std::move(image)); + }; + + const int result = agent->get_printer_file_thumbnail(device_id, path, finish); + if (result != 0) + finish(result, {}); + } + m_pumping_thumbnail_queue = false; +} + +void RemoteFileGridModel::onThumbnailLoaded(std::uint64_t request, const std::string& device_id, + const std::string& path, int result, std::string image) +{ + if (m_thumbnail_requests_in_flight > 0) + --m_thumbnail_requests_in_flight; + + if (request == m_request && device_id == m_device_id) { + wxBitmap bitmap; + if (result == 0 && !image.empty()) { + wxMemoryInputStream stream(image.data(), image.size()); + wxImage decoded(stream, wxBITMAP_TYPE_PNG); + if (decoded.IsOk()) + bitmap = wxBitmap(decoded); + } + m_thumbnail_cache[path] = std::move(bitmap); + if (m_change_handler) + m_change_handler(FileGridChange::Thumbnail); + } + + pumpThumbnailQueue(); +} + +void RemoteFileGridModel::requestMetadata(const std::string& path) +{ + if (m_metadata_cache.find(path) != m_metadata_cache.end() || !m_metadata_requested.insert(path).second) + return; + m_metadata_queue.push_back(path); +} + +void RemoteFileGridModel::pumpMetadataQueue() +{ + constexpr size_t MAX_METADATA_REQUESTS = 4; + if (m_pumping_metadata_queue) + return; + m_pumping_metadata_queue = true; + + NetworkAgent* agent = wxGetApp().getAgent(); + if (!agent) { + while (!m_metadata_queue.empty()) { + m_metadata_cache.emplace(m_metadata_queue.front(), PrinterFileMetadata{}); + m_metadata_queue.pop_front(); + } + m_pumping_metadata_queue = false; + return; + } + + while (!m_metadata_queue.empty() && m_metadata_requests_in_flight < MAX_METADATA_REQUESTS) { + std::string path = std::move(m_metadata_queue.front()); + m_metadata_queue.pop_front(); + ++m_metadata_requests_in_flight; + + const std::uint64_t request = m_request; + const std::string device_id = m_device_id; + const std::weak_ptr lifetime = m_lifetime; + const auto completed = std::make_shared(false); + auto finish = [this, lifetime, completed, request, device_id, path](int result, PrinterFileMetadata meta) { + if (*completed) + return; + *completed = true; + if (lifetime.expired()) + return; + onMetadataLoaded(request, device_id, path, result, meta); + }; + + const int result = agent->get_printer_file_metadata(device_id, path, finish); + if (result != 0) + finish(result, {}); + } + m_pumping_metadata_queue = false; +} + +void RemoteFileGridModel::onMetadataLoaded(std::uint64_t request, const std::string& device_id, + const std::string& path, int result, PrinterFileMetadata meta) +{ + if (m_metadata_requests_in_flight > 0) + --m_metadata_requests_in_flight; + + if (request == m_request && device_id == m_device_id) { + m_metadata_cache[path] = meta; + if (result == 0) { + for (FileGridCard& card : m_cards) { + if (card.id != path) + continue; + card.time_text = meta.estimated_time > 0 ? durationString(meta.estimated_time) : std::string(); + card.weight_text = meta.filament_weight > 0 + ? std::to_string(int(std::round(meta.filament_weight))) + 'g' + : std::string(); + break; + } + if (m_change_handler) + m_change_handler(FileGridChange::Thumbnail); + } + } + + pumpMetadataQueue(); +} + +}} diff --git a/src/slic3r/GUI/Printer/RemoteFileGridModel.h b/src/slic3r/GUI/Printer/RemoteFileGridModel.h new file mode 100644 index 0000000000..82cccb7412 --- /dev/null +++ b/src/slic3r/GUI/Printer/RemoteFileGridModel.h @@ -0,0 +1,98 @@ +#pragma once + +#include "IFileGridModel.h" + +#include "slic3r/Utils/IPrinterAgent.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { +namespace GUI { + +class RemoteFileGridModel : public IFileGridModel +{ +public: + enum class Status { Loading, Ready, Empty, Failed }; + + explicit RemoteFileGridModel(std::string device_id); + ~RemoteFileGridModel() override; + + void Refresh(); + Status GetStatus() const { return m_status; } + void SetStatusHandler(std::function handler); + void SetGroupModeHandler(std::function handler); + + size_t GetCount() const override; + const FileGridCard& GetFile(size_t index, bool& selected) const override; + const FileGridCard& GetFile(size_t index) const override; + + FileGridType GetFileType() const override; + void SetFileType(FileGridType type, const std::string& storage) override; + FileGridGroup GetGroupMode() const override; + void SetGroupMode(FileGridGroup mode) override; + + size_t GetIndexAtTime(time_t time) const override; + size_t EnterSubGroup(size_t index) override; + + void ToggleSelect(size_t index) override; + void SelectAll(bool select) override; + void SetFocusRange(size_t start, size_t count) override; + + void Retry() override; + int GetLastError() const override; + void DownloadCheckFiles(const std::string& path) override; + bool preserve_thumbnail_aspect() const override { return true; } + + // Delete `path` from the printer; `done` reports success on the UI thread. + void DeleteFile(const std::string& path, std::function done); + + void SetChangeHandler(std::function handler) override; + +private: + void setStatus(Status status); + void onFilesLoaded(std::uint64_t request, const std::string& device_id, int result, + std::vector files); + void buildGroups(); + size_t cardIndexForGroup(size_t index) const; + void requestThumbnail(const std::string& path); + void pumpThumbnailQueue(); + void onThumbnailLoaded(std::uint64_t request, const std::string& device_id, + const std::string& path, int result, std::string image); + void requestMetadata(const std::string& path); + void pumpMetadataQueue(); + void onMetadataLoaded(std::uint64_t request, const std::string& device_id, + const std::string& path, int result, PrinterFileMetadata meta); + + std::string m_device_id; + mutable std::vector m_cards; + std::vector m_month; + std::vector m_year; + std::function m_change_handler; + std::function m_status_handler; + std::function m_group_mode_handler; + std::shared_ptr m_lifetime = std::make_shared(0); + std::unordered_map m_thumbnail_cache; + std::unordered_set m_thumbnail_requested; + std::deque m_thumbnail_queue; + std::unordered_map m_metadata_cache; + std::unordered_set m_metadata_requested; + std::deque m_metadata_queue; + std::uint64_t m_request = 0; + size_t m_thumbnail_requests_in_flight = 0; + bool m_pumping_thumbnail_queue = false; + size_t m_metadata_requests_in_flight = 0; + bool m_pumping_metadata_queue = false; + int m_last_error = 0; + FileGridType m_file_type = FileGridType::Timelapse; + FileGridGroup m_group_mode = FileGridGroup::All; + Status m_status = Status::Loading; +}; + +}} diff --git a/src/slic3r/GUI/SelectMachine.cpp b/src/slic3r/GUI/SelectMachine.cpp index 2fe8d416c6..9c3fe2e2e2 100644 --- a/src/slic3r/GUI/SelectMachine.cpp +++ b/src/slic3r/GUI/SelectMachine.cpp @@ -37,6 +37,8 @@ #include "libslic3r/MultiNozzleUtils.hpp" // filament-change-gap model for the best-position popup #include "BackgroundSlicingProcess.hpp" // complete type for background_process().get_current_gcode_result() #include "DeviceCore/DevStorage.h" +#include "slic3r/Utils/NetworkAgentFactory.hpp" +#include "FilamentMappingUtils.hpp" #include #include @@ -3553,6 +3555,9 @@ void SelectMachineDialog::navigate_to_timelapse_page() this->EndModal(wxID_CANCEL); } +// Mapping helpers live in FilamentMappingUtils.hpp (shared with +// SendMultiMachinePage); they mirror the agent serializer exactly. + void SelectMachineDialog::on_send_print() { BOOST_LOG_TRIVIAL(info) << "print_job: on_ok to send"; @@ -3607,6 +3612,28 @@ void SelectMachineDialog::on_send_print() get_ams_mapping_result(ams_mapping_array,ams_mapping_array2, ams_mapping_info); + // The policy lives in FilamentMappingUtils.hpp; this dialog only differs + // from the multi-device page in how it reports a refusal. + switch (prepare_filament_mapping_for_send(obj_, ams_mapping_array2, m_ams_mapping_result)) { + case MappingSendError::unsupported: + BOOST_LOG_TRIVIAL(warning) << "print_job: connector does not advertise filament_mapping; refusing mapped print"; + m_status_bar->set_status_text(_L("AMS filament mapping is not available for this printer. Clear the AMS mapping before printing.")); + Enable_Send_Button(true); + return; + case MappingSendError::incomplete: + BOOST_LOG_TRIVIAL(warning) << "print_job: a used filament has no AMS target; refusing print"; + m_status_bar->set_status_text(_L("A filament used by this print has no AMS mapping. Assign it before printing.")); + Enable_Send_Button(true); + return; + case MappingSendError::none: + break; + default: + // A refusal added without a handler here must not silently send. + BOOST_LOG_TRIVIAL(warning) << "print_job: unrecognized mapping refusal; refusing print"; + Enable_Send_Button(true); + return; + } + if (m_print_type == PrintFromType::FROM_NORMAL) { result = m_plater->send_gcode(m_print_plate_idx, [this](int export_stage, int current, int total, bool& cancel) { if (this->m_is_canceled) return; diff --git a/src/slic3r/GUI/SendMultiMachinePage.cpp b/src/slic3r/GUI/SendMultiMachinePage.cpp index 809a8b4715..1e03f9e659 100644 --- a/src/slic3r/GUI/SendMultiMachinePage.cpp +++ b/src/slic3r/GUI/SendMultiMachinePage.cpp @@ -61,6 +61,8 @@ #include "DeviceCore/DevManager.h" #include "DeviceCore/DevStorage.h" +#include "slic3r/Utils/NetworkAgentFactory.hpp" +#include "FilamentMappingUtils.hpp" #include namespace fs = boost::filesystem; @@ -746,6 +748,8 @@ bool SendMultiMachinePage::get_ams_mapping_result(std::string &mapping_array_str return true; } +// Mapping helpers live in FilamentMappingUtils.hpp, shared with SelectMachine. + void SendMultiMachinePage::on_send(wxCommandEvent& event) { event.Skip(); @@ -794,6 +798,30 @@ void SendMultiMachinePage::on_send(wxCommandEvent& event) if (!wxGetApp().is_blocking_printing(obj)) { PrintParams params = request_params(obj); + switch (prepare_filament_mapping_for_send(obj, params.ams_mapping2, m_ams_mapping_result)) { + case MappingSendError::unsupported: + { + BOOST_LOG_TRIVIAL(warning) << "SendMultiMachinePage: connector does not advertise filament_mapping; refusing mapped print for " + << obj->get_dev_id(); + MessageDialog unavailable_msg(nullptr, _L("AMS filament mapping is not available for this printer. Clear the AMS mapping before printing."), "", wxICON_WARNING | wxOK); + unavailable_msg.ShowModal(); + return; + } + case MappingSendError::incomplete: + { + BOOST_LOG_TRIVIAL(warning) << "SendMultiMachinePage: a used filament has no target; refusing print for " << obj->get_dev_id(); + MessageDialog incomplete_msg(nullptr, _L("A filament used by this print has no AMS mapping. Assign it before printing."), "", wxICON_WARNING | wxOK); + incomplete_msg.ShowModal(); + return; + } + case MappingSendError::none: + break; + default: + // A refusal added without a handler here must not silently send. + BOOST_LOG_TRIVIAL(warning) << "SendMultiMachinePage: unrecognized mapping refusal for " + << obj->get_dev_id(); + return; + } print_params.push_back(params); } } diff --git a/src/slic3r/GUI/StatusPanel.cpp b/src/slic3r/GUI/StatusPanel.cpp index 6cea75fb71..e06d17ce13 100644 --- a/src/slic3r/GUI/StatusPanel.cpp +++ b/src/slic3r/GUI/StatusPanel.cpp @@ -4695,12 +4695,14 @@ void StatusPanel::on_filament_edit(wxCommandEvent &event) } m_filament_setting_dlg->m_is_third = !DevFilaSystem::IsBBL_Filament(tray->tag_uid); + // The tray's own temps pre-fill the dialog for every tray type; a BBL tray + // additionally carries the SN and brand. + temp_max = tray->nozzle_temp_max; + temp_min = tray->nozzle_temp_min; if (!m_filament_setting_dlg->m_is_third) { sn_number = tray->uuid; filament = tray->sub_brands; - temp_max = tray->nozzle_temp_max; - temp_min = tray->nozzle_temp_min; } } @@ -4761,11 +4763,11 @@ void StatusPanel::on_ext_spool_edit(wxCommandEvent &event) } m_filament_setting_dlg->m_is_third = !DevFilaSystem::IsBBL_Filament(obj->vt_slot[nozzle_index].tag_uid); + temp_max = obj->vt_slot[nozzle_index].nozzle_temp_max; + temp_min = obj->vt_slot[nozzle_index].nozzle_temp_min; if (!m_filament_setting_dlg->m_is_third) { sn_number = obj->vt_slot[nozzle_index].uuid; filament = obj->vt_slot[nozzle_index].sub_brands; - temp_max = obj->vt_slot[nozzle_index].nozzle_temp_max; - temp_min = obj->vt_slot[nozzle_index].nozzle_temp_min; } m_filament_setting_dlg->Move(wxPoint(current_position_x,current_position_y)); diff --git a/src/slic3r/GUI/StoragePanel.cpp b/src/slic3r/GUI/StoragePanel.cpp new file mode 100644 index 0000000000..6771c13b49 --- /dev/null +++ b/src/slic3r/GUI/StoragePanel.cpp @@ -0,0 +1,110 @@ +#include "StoragePanel.h" + +#include "DeviceManager.hpp" +#include "GUI_App.hpp" +#include "MediaFilePanel.h" +#include "OrcaFilesPanel.h" +#include "Widgets/StateColor.hpp" + +#include +#include + +namespace Slic3r { +namespace GUI { + +StoragePanel::StoragePanel(wxWindow* parent) + : wxPanel(parent, wxID_ANY) +{ + const wxColour light_background("#EEEEEE"); + SetBackgroundColour(wxGetApp().dark_mode() ? StateColor::darkModeColorFor(light_background) : light_background); + SetSizer(new wxBoxSizer(wxVERTICAL)); +} + +MediaFilePanel* StoragePanel::ensureBambuPanel() +{ + if (!m_bambu_panel) { + m_bambu_panel = new MediaFilePanel(this); + m_bambu_panel->Hide(); + GetSizer()->Add(m_bambu_panel, 1, wxEXPAND); + wxGetApp().UpdateDarkUIWin(m_bambu_panel); + } + return m_bambu_panel; +} + +OrcaFilesPanel* StoragePanel::ensureOrcaPanel() +{ + if (!m_orca_panel) { + m_orca_panel = new OrcaFilesPanel(this); + m_orca_panel->Hide(); + GetSizer()->Add(m_orca_panel, 1, wxEXPAND); + wxGetApp().UpdateDarkUIWin(m_orca_panel); + } + return m_orca_panel; +} + +void StoragePanel::showChild(Child child) +{ + if (m_bambu_panel) + m_bambu_panel->Show(child == Child::Bambu); + if (m_orca_panel) + m_orca_panel->Show(child == Child::Orca); + m_active_child = child; + Layout(); +} + +void StoragePanel::UpdateByObj(MachineObject* obj) +{ + // Agent capability controls the page; Bambu remains the fallback for other printers. + Child target = m_active_child; + if (obj) + target = obj->printer_supports_feature("printer_files") ? Child::Orca : Child::Bambu; + else if (target == Child::None) + target = Child::Bambu; + + if (target != m_active_child) { + if (m_active_child == Child::Bambu && m_bambu_panel) + m_bambu_panel->UpdateByObj(nullptr); + else if (m_active_child == Child::Orca && m_orca_panel) + m_orca_panel->UpdateByObj(nullptr); + + if (target == Child::Bambu) + ensureBambuPanel(); + else + ensureOrcaPanel(); + showChild(target); + } + + if (target == Child::Bambu) + ensureBambuPanel()->UpdateByObj(obj); + else if (target == Child::Orca) + ensureOrcaPanel()->UpdateByObj(obj); +} + +void StoragePanel::SwitchStorage(bool external) +{ + if (m_bambu_panel) + m_bambu_panel->SwitchStorage(external); +} + +void StoragePanel::Rescale() +{ + if (m_bambu_panel) + m_bambu_panel->Rescale(); + if (m_orca_panel) + m_orca_panel->Rescale(); +} + +void StoragePanel::on_sys_color_changed() +{ + const wxColour light_background("#EEEEEE"); + SetBackgroundColour(wxGetApp().dark_mode() ? StateColor::darkModeColorFor(light_background) : light_background); + if (m_bambu_panel) + wxGetApp().UpdateDarkUIWin(m_bambu_panel); + if (m_orca_panel) + wxGetApp().UpdateDarkUIWin(m_orca_panel); + if (m_orca_panel) + m_orca_panel->on_sys_color_changed(); + Refresh(); +} + +}} diff --git a/src/slic3r/GUI/StoragePanel.h b/src/slic3r/GUI/StoragePanel.h new file mode 100644 index 0000000000..78426ce903 --- /dev/null +++ b/src/slic3r/GUI/StoragePanel.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +namespace Slic3r { +class MachineObject; + +namespace GUI { + +class MediaFilePanel; +class OrcaFilesPanel; + +class StoragePanel : public wxPanel +{ +public: + explicit StoragePanel(wxWindow* parent); + + void UpdateByObj(MachineObject* obj); + void SwitchStorage(bool external); + void Rescale(); + void on_sys_color_changed(); + +private: + enum class Child { None, Bambu, Orca }; + + MediaFilePanel* ensureBambuPanel(); + OrcaFilesPanel* ensureOrcaPanel(); + void showChild(Child child); + + MediaFilePanel* m_bambu_panel = nullptr; + OrcaFilesPanel* m_orca_panel = nullptr; + Child m_active_child = Child::None; +}; + +}} diff --git a/src/slic3r/GUI/SyncAmsInfoDialog.cpp b/src/slic3r/GUI/SyncAmsInfoDialog.cpp index 67efdd6ff7..21a403651c 100644 --- a/src/slic3r/GUI/SyncAmsInfoDialog.cpp +++ b/src/slic3r/GUI/SyncAmsInfoDialog.cpp @@ -1421,6 +1421,12 @@ bool SyncAmsInfoDialog::get_ams_mapping_result(std::string &mapping_array_str, s BOOST_LOG_TRIVIAL(error) << "get_ams_mapping_result, plater is nullptr"; } + // mapping_v1_json is built one entry per filament preset, in preset order, so the + // array position is the logical filament index the generated G-code toolchange + // references (the identifier handed to the Klipper toolchange macro; see + // OrcaPrinterAgent::build_filament_mapping and the index-correlation test in + // tests/slic3rutils/test_orca_printer_agent.cpp). Never re-densify after dropping + // sentinel entries, or a used filament would be aimed at the wrong lane. for (int i = 0; i < wxGetApp().preset_bundle->filament_presets.size(); i++) { int tray_id = -1; json mapping_item_v1; diff --git a/src/slic3r/GUI/Widgets/AMSItem.cpp b/src/slic3r/GUI/Widgets/AMSItem.cpp index 303b4221bb..e28338073d 100644 --- a/src/slic3r/GUI/Widgets/AMSItem.cpp +++ b/src/slic3r/GUI/Widgets/AMSItem.cpp @@ -99,6 +99,7 @@ bool AMSinfo::parse_ams_info(MachineObject *obj, DevAms *ams, bool remain_flag, Caninfo info; // tray is exists if (it != ams->GetTrays().end() && it->second->is_exists) { + info.is_empty = it->second->is_empty; if (it->second->is_tray_info_ready()) { info.can_id = it->second->id; info.ctype = it->second->ctype; @@ -166,6 +167,7 @@ void AMSinfo::parse_ext_info(MachineObject* obj, DevAmsTray tray) { this->ams_type = AMSModel::EXT_AMS; Caninfo info; info.can_id = std::to_string(0); + info.is_empty = tray.is_empty; this->cans.clear(); if (tray.id == std::to_string(VIRTUAL_TRAY_MAIN_ID)) @@ -1128,9 +1130,9 @@ void AMSLib::render_lite_text(wxDC& dc) dc.SetTextForeground(temp_text_colour); auto libsize = GetSize(); - if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND + if (!m_info.is_empty && (m_info.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND || m_info.material_state == AMSCanType::AMS_CAN_TYPE_BRAND - || m_info.material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL) { + || m_info.material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL)) { if (m_info.material_name.empty()) { auto tsize = dc.GetMultiLineTextExtent("?"); @@ -1178,7 +1180,7 @@ void AMSLib::render_lite_text(wxDC& dc) } } - if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) { + if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY || m_info.is_empty) { auto tsize = dc.GetMultiLineTextExtent(_L("/")); auto pot = wxPoint((libsize.x - tsize.x) / 2 + FromDIP(2), (libsize.y - tsize.y) / 2 + FromDIP(3)); dc.DrawText(_L("/"), pot); @@ -1187,8 +1189,12 @@ void AMSLib::render_lite_text(wxDC& dc) void AMSLib::render_generic_text(wxDC &dc) { - bool show_k_value = true; - if (m_info.material_name.empty()) { + // K/N is Bambu firmware's flow-dynamics calibration; agents with no printer-side + // records (OrcaSonar, Moonraker) must not show a synthesized value. + const bool k_supported = !m_obj || m_obj->supports_extrusion_cali(); + const bool show_kn = m_show_kn && k_supported; + bool show_k_value = k_supported; + if (!k_supported || m_info.material_name.empty()) { show_k_value = false; } else if (m_info.cali_idx == -1 || (m_obj && (CalibUtils::get_selected_calib_idx(m_obj->pa_calib_tab, m_info.cali_idx) == -1))) { @@ -1229,9 +1235,9 @@ void AMSLib::render_generic_text(wxDC &dc) } auto libsize = GetSize(); - if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND + if (!m_info.is_empty && (m_info.material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND || m_info.material_state == AMSCanType::AMS_CAN_TYPE_BRAND - || m_info.material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL) { + || m_info.material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL)) { if (m_info.material_name.empty() /*&& m_info.material_state != AMSCanType::AMS_CAN_TYPE_VIRTUAL*/) { auto tsize = dc.GetMultiLineTextExtent("?"); @@ -1269,7 +1275,7 @@ void AMSLib::render_generic_text(wxDC &dc) auto line_top_tsize = dc.GetMultiLineTextExtent(line_top); auto line_bottom_tsize = dc.GetMultiLineTextExtent(line_bottom); - if (!m_show_kn) { + if (!show_kn) { auto pot_top = wxPoint((libsize.x - line_top_tsize.x) / 2, (libsize.y - line_top_tsize.y) / 2 - line_top_tsize.y + FromDIP(6)); dc.DrawText(line_top, pot_top); @@ -1300,7 +1306,7 @@ void AMSLib::render_generic_text(wxDC &dc) //draw k&n if (m_obj && show_k_value) { - if (m_show_kn) { + if (show_kn) { wxString str_k = wxString::Format("K %1.3f", m_info.k); wxString str_n = wxString::Format("N %1.3f", m_info.n); dc.SetFont(::Label::Body_11); @@ -1311,7 +1317,7 @@ void AMSLib::render_generic_text(wxDC &dc) } } - if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) { + if (m_info.material_state == AMSCanType::AMS_CAN_TYPE_EMPTY || m_info.is_empty) { auto tsize = dc.GetMultiLineTextExtent(_L("Empty")); auto pot = wxPoint((libsize.x - tsize.x) / 2, (libsize.y - tsize.y) / 2 + FromDIP(3)); dc.DrawText(_L("Empty"), pot); @@ -2808,7 +2814,7 @@ void AMSPreview::doRender(wxDC &dc) } else { wxRect rect(left, (size.y - AMS_ITEM_CUBE_SIZE.y) / 2, AMS_ITEM_CUBE_SIZE.x, AMS_ITEM_CUBE_SIZE.y); - if (iter->material_state == AMSCanType::AMS_CAN_TYPE_EMPTY) { + if (iter->material_state == AMSCanType::AMS_CAN_TYPE_EMPTY || iter->is_empty) { dc.SetPen(wxPen(wxColor(0, 0, 0))); dc.DrawLine(rect.GetRight() - FromDIP(1), rect.GetTop() + FromDIP(1), rect.GetLeft() + FromDIP(1), rect.GetBottom() - FromDIP(1)); } diff --git a/src/slic3r/GUI/Widgets/AMSItem.hpp b/src/slic3r/GUI/Widgets/AMSItem.hpp index 55c0a3ca8d..7a8798bf0b 100644 --- a/src/slic3r/GUI/Widgets/AMSItem.hpp +++ b/src/slic3r/GUI/Widgets/AMSItem.hpp @@ -200,6 +200,7 @@ struct Caninfo wxString material_name; wxColour material_colour = {*wxWHITE}; AMSCanType material_state; + bool is_empty = false; int ctype=0; int material_remain = 100; int cali_idx = -1; @@ -215,6 +216,7 @@ public: material_name == other.material_name && material_colour == other.material_colour && material_state == other.material_state && + is_empty == other.is_empty && ctype == other.ctype && material_remain == other.material_remain && cali_idx == other.cali_idx && diff --git a/src/slic3r/Utils/IPrinterAgent.hpp b/src/slic3r/Utils/IPrinterAgent.hpp index 293b0af2b8..d907bba438 100644 --- a/src/slic3r/Utils/IPrinterAgent.hpp +++ b/src/slic3r/Utils/IPrinterAgent.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,34 @@ enum class CameraStreamMode { http_snapshot // HTTP endpoint returning one image per request }; +struct PrinterFileEntry { + std::string path; // gcodes-root-relative, e.g. "sub/foo.gcode" + std::string name; // basename for display + std::uint64_t size = 0; // bytes + std::int64_t modified = 0; // unix seconds +}; + +// Moonraker per-file metadata: print time and filament usage. Missing fields are 0. +struct PrinterFileMetadata { + int estimated_time = 0; // seconds + double filament_total = 0; // millimetres + double filament_weight = 0; // grams +}; + +// Async listing of the printer's G-code files. The return value reports whether +// the request was dispatched; `callback` is invoked once with the result. +using PrinterFileListFn = std::function files)>; + +// Async fetch of one G-code file's embedded thumbnail. `image` is the raw image +// bytes (empty when the file has no thumbnail); result reports dispatch/transfer. +using PrinterFileThumbnailFn = std::function; + +// Async deletion of one printer G-code file. `result` reports dispatch and outcome. +using PrinterFileDeleteFn = std::function; + +// Async fetch of one G-code file's Moonraker metadata. `meta` fields default to 0. +using PrinterFileMetadataFn = std::function; + /** * IPrinterAgent - Interface for printer operations. * @@ -109,6 +138,16 @@ public: */ virtual int send_message(std::string dev_id, std::string json_str, int qos, int flag) = 0; + // Capability queries are per-device because one agent may own many printers. + // Legacy agents keep their existing behavior unless they override these. + virtual bool supports_command(const std::string& /*dev_id*/, const std::string& /*command*/) const { return true; } + virtual bool supports_feature(const std::string& /*dev_id*/, const std::string& /*feature*/) const { return false; } + + // Whether this agent serializes AMS lane selection into print.gcode_file's + // per-print filament_mapping field. A dialect question, not a capability one: + // the no-AMS external-spool normalization runs before capabilities are known. + virtual bool uses_filament_mapping() const { return false; } + // why: gcode is firmware dialect, not a waist concept - commands whose body is Bambu-dialect // gcode live on the agent that speaks it; the default is an honest refusal that MachineObject's // publish funnel turns into a dialog. @@ -316,6 +355,48 @@ public: return -1; } + /** + * List the printer's G-code files, delivered asynchronously via callback. + * Agents without a file listing report ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED. + */ + virtual int list_printer_files(const std::string& dev_id, PrinterFileListFn callback) + { + (void) dev_id; + (void) callback; + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + + /** + * Fetch one G-code file's embedded thumbnail, delivered asynchronously via + * callback. Agents without thumbnail support report ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED. + */ + virtual int get_printer_file_thumbnail(const std::string& dev_id, const std::string& path, PrinterFileThumbnailFn callback) + { + (void) dev_id; (void) path; (void) callback; + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + + /** + * Delete one G-code file from the printer, delivered asynchronously via + * callback. Agents without file deletion report ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED. + */ + virtual int delete_printer_file(const std::string& dev_id, const std::string& path, PrinterFileDeleteFn callback) + { + (void) dev_id; (void) path; (void) callback; + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + + /** + * Fetch one G-code file's Moonraker metadata (print time and filament usage), + * delivered asynchronously via callback. Agents without metadata support + * report ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED. + */ + virtual int get_printer_file_metadata(const std::string& dev_id, const std::string& path, PrinterFileMetadataFn callback) + { + (void) dev_id; (void) path; (void) callback; + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + /** * Register callback for fatal HTTP errors. */ diff --git a/src/slic3r/Utils/NetworkAgent.cpp b/src/slic3r/Utils/NetworkAgent.cpp index 4e5154fd42..363ee71660 100644 --- a/src/slic3r/Utils/NetworkAgent.cpp +++ b/src/slic3r/Utils/NetworkAgent.cpp @@ -806,6 +806,36 @@ int NetworkAgent::send_message(std::string dev_id, std::string json_str, int qos return -1; } +bool NetworkAgent::owns_agent(const std::string& expected_agent_id) const +{ + if (!m_printer_agent) + return false; + return expected_agent_id.empty() || m_printer_agent->get_agent_info().id == expected_agent_id; +} + +bool NetworkAgent::supports_command(const std::string& expected_agent_id, const std::string& dev_id, + const std::string& command) const +{ + if (!owns_agent(expected_agent_id)) + return false; + return m_printer_agent->supports_command(dev_id, command); +} + +bool NetworkAgent::supports_feature(const std::string& expected_agent_id, const std::string& dev_id, + const std::string& feature) const +{ + if (!owns_agent(expected_agent_id)) + return false; + return m_printer_agent->supports_feature(dev_id, feature); +} + +bool NetworkAgent::uses_filament_mapping(const std::string& expected_agent_id) const +{ + if (!owns_agent(expected_agent_id)) + return false; + return m_printer_agent->uses_filament_mapping(); +} + int NetworkAgent::command_ams_refresh_rfid(std::string dev_id, int ams_id, int slot_id, int sequence_id, bool lan_mode) { if (m_printer_agent) @@ -1106,4 +1136,32 @@ int NetworkAgent::get_hms_snapshot(std::string dev_id, std::string file_name, st return -1; } +int NetworkAgent::list_printer_files(const std::string& dev_id, PrinterFileListFn callback) +{ + if (m_printer_agent) + return m_printer_agent->list_printer_files(dev_id, callback); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; +} + +int NetworkAgent::get_printer_file_thumbnail(const std::string& dev_id, const std::string& path, PrinterFileThumbnailFn callback) +{ + if (m_printer_agent) + return m_printer_agent->get_printer_file_thumbnail(dev_id, path, callback); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; +} + +int NetworkAgent::delete_printer_file(const std::string& dev_id, const std::string& path, PrinterFileDeleteFn callback) +{ + if (m_printer_agent) + return m_printer_agent->delete_printer_file(dev_id, path, callback); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; +} + +int NetworkAgent::get_printer_file_metadata(const std::string& dev_id, const std::string& path, PrinterFileMetadataFn callback) +{ + if (m_printer_agent) + return m_printer_agent->get_printer_file_metadata(dev_id, path, callback); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; +} + } // namespace Slic3r diff --git a/src/slic3r/Utils/NetworkAgent.hpp b/src/slic3r/Utils/NetworkAgent.hpp index c7813f2bb7..347b865bf7 100644 --- a/src/slic3r/Utils/NetworkAgent.hpp +++ b/src/slic3r/Utils/NetworkAgent.hpp @@ -153,6 +153,10 @@ public: int set_on_local_message_fn(OnMessageFn fn); int set_server_callback(OnServerErrFn fn); int send_message(std::string dev_id, std::string json_str, int qos, int flag); + bool owns_agent(const std::string& expected_agent_id) const; + bool supports_command(const std::string& expected_agent_id, const std::string& dev_id, const std::string& command) const; + bool supports_feature(const std::string& expected_agent_id, const std::string& dev_id, const std::string& feature) const; + bool uses_filament_mapping(const std::string& expected_agent_id) const; int command_ams_refresh_rfid(std::string dev_id, int ams_id, int slot_id, int sequence_id, bool lan_mode); int command_ams_calibrate(std::string dev_id, int ams_id, int sequence_id, bool lan_mode); int command_ams_select_tray(std::string dev_id, std::string tray_id, int sequence_id, bool lan_mode); @@ -194,6 +198,10 @@ public: std::string from_orca_filament_id(const std::string& orca_filament_id) const; int request_bind_ticket(std::string* ticket); int get_hms_snapshot(std::string dev_id, std::string file_name, std::function callback); + int list_printer_files(const std::string& dev_id, PrinterFileListFn callback); + int get_printer_file_thumbnail(const std::string& dev_id, const std::string& path, PrinterFileThumbnailFn callback); + int delete_printer_file(const std::string& dev_id, const std::string& path, PrinterFileDeleteFn callback); + int get_printer_file_metadata(const std::string& dev_id, const std::string& path, PrinterFileMetadataFn callback); private: struct PrinterCallbacks { diff --git a/src/slic3r/Utils/NetworkAgentFactory.hpp b/src/slic3r/Utils/NetworkAgentFactory.hpp index 0053a42466..40e1500b2d 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.hpp +++ b/src/slic3r/Utils/NetworkAgentFactory.hpp @@ -17,7 +17,7 @@ namespace Slic3r { static constexpr char ORCA_PRINTER_AGENT_ID[] = "orca"; -static constexpr char BBL_PRINTER_AGENT_ID[] = "bbl"; +static constexpr char BBL_PRINTER_AGENT_ID[] = "bbl"; // Factory function type for creating printer agents using PrinterAgentFactory = @@ -26,17 +26,20 @@ using PrinterAgentFactory = // Information about a registered printer agent struct PrinterAgentInfo { - std::string id; // Registry/config key, e.g. "orca" or a plugin AgentInfo::id - std::string display_name; // e.g., "Orca Native", "Bambu Lab" - std::string plugin_identifier; // Empty for built-ins, otherwise ;; - PrinterAgentFactory factory; // Function to create the agent + std::string id; // Registry/config key, e.g. "orca" or a plugin AgentInfo::id + std::string display_name; // e.g., "Orca Native", "Bambu Lab" + std::string plugin_identifier; // Empty for built-ins, otherwise ;; + PrinterAgentFactory factory; // Function to create the agent bool is_plugin() const { return !plugin_identifier.empty(); } PrinterAgentInfo(const std::string& id_, const std::string& display_name_, PrinterAgentFactory factory_) : id(id_), display_name(display_name_), factory(std::move(factory_)) {} - PrinterAgentInfo(const std::string& id_, const std::string& display_name_, const std::string& plugin_identifier, PrinterAgentFactory factory_) + PrinterAgentInfo(const std::string& id_, + const std::string& display_name_, + const std::string& plugin_identifier, + PrinterAgentFactory factory_) : id(id_), display_name(display_name_), plugin_identifier(plugin_identifier), factory(std::move(factory_)) {} }; @@ -118,9 +121,9 @@ public: * @param log_dir Directory for log files * @return Shared pointer to IPrinterAgent, or nullptr if ID not found */ - static std::shared_ptr create_printer_agent_by_id(const std::string& id, + static std::shared_ptr create_printer_agent_by_id(const std::string& id, std::shared_ptr cloud_agent, - const std::string& log_dir); + const std::string& log_dir); /** * Clear the printer agent cache. diff --git a/src/slic3r/Utils/OrcaPrinterAgent.cpp b/src/slic3r/Utils/OrcaPrinterAgent.cpp index 63f8158663..0ba810f998 100644 --- a/src/slic3r/Utils/OrcaPrinterAgent.cpp +++ b/src/slic3r/Utils/OrcaPrinterAgent.cpp @@ -44,6 +44,45 @@ namespace { namespace fs = boost::filesystem; +struct OrcaDeviceCapabilities +{ + bool fms = false; + bool filament_slots = false; + bool filament_mapping = false; + std::set supported_commands; +}; + +std::mutex g_capabilities_mutex; +std::unordered_map g_capabilities; + +OrcaDeviceCapabilities capabilities_for(const std::string& dev_id) +{ + std::lock_guard lock(g_capabilities_mutex); + const auto it = g_capabilities.find(dev_id); + return it == g_capabilities.end() ? OrcaDeviceCapabilities{} : it->second; +} + +bool command_supported(const OrcaDeviceCapabilities& capabilities, const std::string& command) +{ + if (command == "print.ams_filament_setting") + return capabilities.filament_slots; + + static const std::set macro_backed_commands = { + "print.ams_change_filament", + "print.ams_control", + "print.ams_user_setting", + "print.ams_get_rfid", + "print.auto_stop_ams_dry", + }; + if (macro_backed_commands.count(command) != 0) + return capabilities.fms && capabilities.supported_commands.count(command) != 0; + + if (command.rfind("print.ams_", 0) == 0) + return capabilities.supported_commands.count(command) != 0; + + return true; +} + // params.filename is normally the exported .3mf archive; the sliced G-code sits // beside it with the same stem (".12345.0.3mf" -> ".12345.0.gcode"). params.dst_file, // when set, already points straight at a file (the "print a file already on the @@ -448,6 +487,14 @@ OrcaPrinterAgent::~OrcaPrinterAgent() ++m_lan_generation; // fence any late worker callback ++m_cloud_generation; + std::string lan_dev_id; + std::string cloud_dev_id; + { + std::lock_guard lock(state_mutex); + lan_dev_id = m_lan_dev_id; + cloud_dev_id = selected_machine; + } + // Drop the cloud status callback before anything else: it holds `this`, and the // cloud agent outlives the printer agent (NetworkAgent::set_printer_agent swaps // the printer agent while m_cloud_agents persist). @@ -483,6 +530,8 @@ OrcaPrinterAgent::~OrcaPrinterAgent() std::lock_guard l(state_mutex); lan_mqtt_connection.reset(); } + forget_device_capabilities(lan_dev_id); + forget_device_capabilities(cloud_dev_id); } OrcaCloudServiceAgent* OrcaPrinterAgent::get_orca_cloud_agent() @@ -589,6 +638,52 @@ std::string OrcaPrinterAgent::merge_capabilities(const std::string& dev_id, cons std::lock_guard l(nozzle_diameter_cache_mutex); nozzle_diameter_cache[dev_id] = nozzle_dia; } + + // Connector capabilities are retained per device for command dispatch + // and GUI capability queries. A fresh reply replaces stale support. + OrcaDeviceCapabilities device_capabilities; + auto parse_features = [&device_capabilities](const nlohmann::json& features) { + if (!features.is_object()) + return; + auto read_bool = [&features](const char* key, bool& output) { + const auto it = features.find(key); + if (it != features.end() && it->is_boolean()) + output = it->get(); + }; + read_bool("fms", device_capabilities.fms); + read_bool("filament_slots", device_capabilities.filament_slots); + read_bool("filament_mapping", device_capabilities.filament_mapping); + }; + auto parse_commands = [&device_capabilities](const nlohmann::json& commands) { + if (!commands.is_array()) + return; + for (const auto& item : commands) { + if (item.is_string()) + device_capabilities.supported_commands.insert(item.get()); + } + }; + + const auto top_features = info_it->find("supported_features"); + if (top_features != info_it->end()) + parse_features(*top_features); + const auto top_commands = info_it->find("supported_commands"); + if (top_commands != info_it->end()) + parse_commands(*top_commands); + if (caps_it != info_it->end() && caps_it->is_object()) { + const auto protocol_it = caps_it->find("protocol"); + if (protocol_it != caps_it->end() && protocol_it->is_object()) { + const auto protocol_features = protocol_it->find("features"); + if (protocol_features != protocol_it->end()) + parse_features(*protocol_features); + const auto protocol_commands = protocol_it->find("supported_commands"); + if (protocol_commands != protocol_it->end()) + parse_commands(*protocol_commands); + } + } + { + std::lock_guard lock(g_capabilities_mutex); + g_capabilities[dev_id] = std::move(device_capabilities); + } // The capabilities reply itself is forwarded unchanged. } else { @@ -615,6 +710,14 @@ std::string OrcaPrinterAgent::merge_capabilities(const std::string& dev_id, cons return modified ? envelope.dump() : payload; } +void OrcaPrinterAgent::forget_device_capabilities(const std::string& dev_id) +{ + if (dev_id.empty()) + return; + std::lock_guard lock(g_capabilities_mutex); + g_capabilities.erase(dev_id); +} + void OrcaPrinterAgent::deliver_to_sink(const std::string& dev_id, const std::string& payload, bool local) { parse_ipcam_info(dev_id, payload); @@ -702,6 +805,58 @@ void OrcaPrinterAgent::set_cloud_agent(std::shared_ptr cloud int OrcaPrinterAgent::send_message(std::string dev_id, std::string json_str, int /*qos*/, int /*flag*/) { return route_send(/*is_lan=*/false, dev_id, json_str); } +bool OrcaPrinterAgent::supports_command(const std::string& dev_id, const std::string& command) const +{ + return command_supported(capabilities_for(dev_id), command); +} + +bool OrcaPrinterAgent::supports_feature(const std::string& dev_id, const std::string& feature) const +{ + const OrcaDeviceCapabilities capabilities = capabilities_for(dev_id); + if (feature == "fms") + return capabilities.fms; + if (feature == "filament_slots") + return capabilities.filament_slots; + if (feature == "filament_mapping") + return capabilities.filament_mapping; + if (feature == "printer_files") + return true; + return false; +} + +int OrcaPrinterAgent::prepare_outgoing_request(const std::string& dev_id, const std::string& payload, + std::string& command, std::string& prepared) const +{ + command = ""; + prepared = payload; + nlohmann::json envelope = nlohmann::json::parse(payload, nullptr, false); + if (envelope.is_discarded() || !envelope.is_object()) + return BAMBU_NETWORK_SUCCESS; + + nlohmann::json* print = nullptr; + for (const char* namespace_name : {"pushing", "info", "print", "system", "camera", "xcam", "upgrade", "event", "files"}) { + const auto namespace_it = envelope.find(namespace_name); + if (namespace_it == envelope.end() || !namespace_it->is_object()) + continue; + const auto command_it = namespace_it->find("command"); + if (command_it == namespace_it->end() || !command_it->is_string()) + continue; + command = std::string(namespace_name) + "." + command_it->get(); + if (std::string(namespace_name) == "print") + print = &*namespace_it; + break; + } + + if (!supports_command(dev_id, command)) + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + + if (command == "print.ams_filament_setting" && print && print->contains("setting_id")) { + print->erase("setting_id"); + prepared = envelope.dump(); + } + return BAMBU_NETWORK_SUCCESS; +} + int OrcaPrinterAgent::command_ams_refresh_rfid(std::string dev_id, int ams_id, int tray_id, int sequence_id, bool lan_mode) { (void) ams_id; @@ -1012,6 +1167,7 @@ int OrcaPrinterAgent::connect_printer(const PrinterConnectionParams& params) BOOST_LOG_TRIVIAL(warning) << "Orca diagnostic: connect_printer rejected unparsable LAN endpoint dev_ip=" << params.host; return BAMBU_NETWORK_ERR_INVALID_HANDLE; } + forget_device_capabilities(params.dev_id); disconnect_printer(); const uint64_t gen = ++m_lan_generation; @@ -1068,6 +1224,7 @@ int OrcaPrinterAgent::connect_printer(const PrinterConnectionParams& params) on_connected(params.dev_id, conn, gen); dispatch_local_connect(ConnectStatusOk, params.dev_id, "0"); } else if (!connected && !initial) { + forget_device_capabilities(params.dev_id); dispatch_local_connect(ConnectStatusLost, params.dev_id, "connection_lost"); } }); @@ -1119,6 +1276,7 @@ int OrcaPrinterAgent::disconnect_printer() } current_connection = m_current_connection; } + forget_device_capabilities(prev_dev); BOOST_LOG_TRIVIAL(info) << "Orca diagnostic: LAN disconnect generation=" << m_lan_generation.load() << " previous_dev_id=" << prev_dev << " had_connection=" << (doomed ? "yes" : "no") << " connected=" << (doomed && doomed->is_connected() ? "yes" : "no") @@ -1143,31 +1301,21 @@ int OrcaPrinterAgent::send_message_to_printer(std::string dev_id, std::string js int OrcaPrinterAgent::route_send(bool is_lan, const std::string& dev_id, const std::string& json_str) { - std::string command = ""; - try { - const nlohmann::json envelope = nlohmann::json::parse(json_str); - for (const char* namespace_name : {"pushing", "info", "print", "system", "camera", "xcam", "upgrade", "event", "files"}) { - const auto namespace_it = envelope.find(namespace_name); - if (namespace_it != envelope.end() && namespace_it->is_object()) { - const auto command_it = namespace_it->find("command"); - if (command_it != namespace_it->end() && command_it->is_string()) { - command = std::string(namespace_name) + "." + command_it->get(); - break; - } - } - } - } catch (const std::exception&) { - // Preserve the transport's existing behavior for malformed payloads; - // the printer will report the protocol error asynchronously. - } + std::string command; + std::string prepared; + const int prepare_rc = prepare_outgoing_request(dev_id, json_str, command, prepared); BOOST_LOG_TRIVIAL(info) << "OrcaPrinterAgent::route_send is_lan=" << is_lan << " dev_id=" << dev_id << " command=" << command << " payload_bytes=" << json_str.size(); if (dev_id.empty()) return BAMBU_NETWORK_ERR_INVALID_HANDLE; + if (prepare_rc != BAMBU_NETWORK_SUCCESS) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: refusing unsupported command " << command << " for dev_id=" << dev_id; + return prepare_rc; + } OrcaMqttConnection* conn = get_appropriate_mqtt_connection(is_lan); if (!conn) return BAMBU_NETWORK_ERR_INVALID_HANDLE; - const bool queued = conn->send_request(dev_id, json_str); + const bool queued = conn->send_request(dev_id, prepared); BOOST_LOG_TRIVIAL(info) << "OrcaPrinterAgent::route_send command=" << command << " queued=" << queued << " is_lan=" << is_lan << " dev_id=" << dev_id; return queued ? BAMBU_NETWORK_SUCCESS : BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; @@ -1297,19 +1445,20 @@ int OrcaPrinterAgent::set_user_selected_machine(std::string dev_id) } current_connection = m_current_connection; } + // Fence in-flight cloud callbacks before discarding their capability state. + const uint64_t gen = ++m_cloud_generation; BOOST_LOG_TRIVIAL(info) << "OrcaPrinterAgent::set_user_selected_machine: previous=" << previous << " new=" << dev_id << " cloud=" << (cloud ? "set" : "") << " transport=" << connection_type_name(previous_connection) << "->" << connection_type_name(current_connection); + if (previous != dev_id || previous_connection != current_connection) { + forget_device_capabilities(previous); + forget_device_capabilities(dev_id); + } if (!cloud) { BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent::set_user_selected_machine: no Orca cloud agent"; return BAMBU_NETWORK_SUCCESS; } - // Bump ONCE at the top for any change (select or deselect) so a deselect also - // fences an in-flight configure thread started by the previous selection. This is - // the CLOUD epoch only — a cloud selection must not fence a live LAN session. - const uint64_t gen = ++m_cloud_generation; - auto* conn = cloud->get_mqtt_connection(); if (!previous.empty()) { cloud->del_subscribe({previous}); @@ -1339,8 +1488,12 @@ int OrcaPrinterAgent::set_user_selected_machine(std::string dev_id) return; // superseded before we ran: do not raise a socket nobody owns auto state_handler = [this](bool connected, bool initial) { - if (!connected || initial) + if (initial) return; + if (!connected) { + forget_device_capabilities(get_user_selected_machine()); + return; + } auto* current_cloud = get_orca_cloud_agent(); OrcaMqttConnection* current_conn = current_cloud ? current_cloud->get_mqtt_connection() : nullptr; const std::string selected = get_user_selected_machine(); @@ -1356,6 +1509,12 @@ int OrcaPrinterAgent::set_user_selected_machine(std::string dev_id) return BAMBU_NETWORK_SUCCESS; } +int OrcaPrinterAgent::unbind(std::string dev_id) +{ + forget_device_capabilities(dev_id); + return BAMBU_NETWORK_SUCCESS; +} + // ============================================================================ // Agent Information // ============================================================================ @@ -1416,11 +1575,17 @@ int OrcaPrinterAgent::start_print(PrintParams params, OnUpdateStatusFn update_fn return BAMBU_NETWORK_SUCCESS; } -int OrcaPrinterAgent::start_local_print_with_record(PrintParams params, - OnUpdateStatusFn update_fn, - WasCancelledFn cancel_fn, - OnWaitFn wait_fn) -{ return BAMBU_NETWORK_SUCCESS; } +int OrcaPrinterAgent::start_local_print_with_record(PrintParams /*params*/, + OnUpdateStatusFn /*update_fn*/, + WasCancelledFn /*cancel_fn*/, + OnWaitFn /*wait_fn*/) +{ + // OrcaSonar has no FTP "send with record" path. Report a non-success result so + // PrintJob falls back to start_print() (cloud upload + start_sdcard_print) instead + // of treating a print that was never sent as successful. + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: start_local_print_with_record is unimplemented; deferring to start_print"; + return BAMBU_NETWORK_ERR_FTP_UPLOAD_FAILED; +} // Upload one G-code file to the printer's `gcodes` root over OrcaSonar's // Moonraker-compatible HTTP facade. No print is started here (print=false); the @@ -1572,6 +1737,424 @@ int OrcaPrinterAgent::start_send_gcode_to_sdcard(PrintParams params, return BAMBU_NETWORK_SUCCESS; } +// Pure normalization of Moonraker's /server/files/list reply: the `result` array +// of {path, modified, size}. `name` is the basename of `path`; malformed entries +// (non-object, missing/empty path) are skipped. size/modified default to 0. +std::vector OrcaPrinterAgent::parse_file_list(const std::string& body) +{ + std::vector files; + + const nlohmann::json envelope = nlohmann::json::parse(body, nullptr, false); + if (envelope.is_discarded() || !envelope.is_object()) + return files; + + const auto result_it = envelope.find("result"); + if (result_it == envelope.end() || !result_it->is_array()) + return files; + + for (const auto& item : *result_it) { + if (!item.is_object()) + continue; + + const auto path_it = item.find("path"); + if (path_it == item.end() || !path_it->is_string()) + continue; + const std::string path = path_it->get(); + if (path.empty()) + continue; + + PrinterFileEntry entry; + entry.path = path; + entry.name = fs::path(path).filename().string(); + + const auto size_it = item.find("size"); + if (size_it != item.end() && size_it->is_number()) + entry.size = size_it->get(); + + const auto modified_it = item.find("modified"); + if (modified_it != item.end() && modified_it->is_number()) + entry.modified = static_cast(modified_it->get()); + + files.push_back(std::move(entry)); + } + return files; +} + +int OrcaPrinterAgent::list_printer_files(const std::string& dev_id, PrinterFileListFn callback) +{ + std::string origin; + bool use_ssl = false; + std::string ca_file; + QueueOnMainFn queue; + bool live = false; + { + std::lock_guard lock(state_mutex); + live = m_current_connection == LAN && m_lan_dev_id == dev_id; + if (live) { + origin = http_origin_from_lan_ws(m_lan_url); + use_ssl = m_lan_use_ssl; + ca_file = m_lan_ca_file; + queue = queue_on_main_fn; + } + } + if (!live) { + if (callback) + callback(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED, {}); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + if (origin.empty()) { + if (callback) + callback(BAMBU_NETWORK_ERR_INVALID_HANDLE, {}); + return BAMBU_NETWORK_ERR_INVALID_HANDLE; + } + + // perform_sync blocks, so the request runs off the UI thread. The worker captures + // only values (never `this`). A trusted LAN facade needs no API key. + std::thread([dev_id, origin, use_ssl, ca_file, queue, callback = std::move(callback)]() mutable { + std::string body; + int result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + + auto http = Http::get(origin + "/server/files/list?root=gcodes"); + http.tls_verify(use_ssl); + if (!ca_file.empty()) + http.ca_file(ca_file); + http.timeout_connect(5) + .timeout_max(15) + .on_complete([&](std::string b, unsigned status) { + if (status == 200) { + body = std::move(b); + result = BAMBU_NETWORK_SUCCESS; + } + }) + .on_error([&](std::string, std::string err, unsigned status) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: file list request failed status=" << status << " err=" << err; + }) + .perform_sync(); + + std::vector files; + if (result == BAMBU_NETWORK_SUCCESS) { + files = parse_file_list(body); + // Empty is a valid listing; an unparseable body is not. + if (nlohmann::json::parse(body, nullptr, false).is_discarded()) + result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + } + + if (!callback) + return; + if (queue) + queue([callback, result, files = std::move(files)]() mutable { callback(result, std::move(files)); }); + else + callback(result, std::move(files)); + }).detach(); + + return BAMBU_NETWORK_SUCCESS; +} + +// Pure pick of the widest thumbnail path from Moonraker's /server/files/thumbnails +// reply. The `result` array is ordered smallest-first, so the largest `width` is +// chosen. The key was renamed across Moonraker versions; both spellings are accepted. +// Malformed replies and entries without a usable path yield an empty string. +std::string OrcaPrinterAgent::parse_thumbnail_path(const std::string& body) +{ + const nlohmann::json envelope = nlohmann::json::parse(body, nullptr, false); + if (envelope.is_discarded() || !envelope.is_object()) + return {}; + + const auto result_it = envelope.find("result"); + if (result_it == envelope.end() || !result_it->is_array()) + return {}; + + std::string path; + int best_width = -1; + for (const auto& item : *result_it) { + if (!item.is_object()) + continue; + + const char* key = item.contains("thumbnail_path") ? "thumbnail_path" : "relative_path"; + if (!item.contains(key) || !item[key].is_string()) + continue; + + const int width = (item.contains("width") && item["width"].is_number()) ? item["width"].get() : 0; + if (width > best_width) { + best_width = width; + path = item[key].get(); + } + } + return path; +} + +// Pure normalization of Moonraker's /server/files/metadata reply: the `result` +// object's estimated_time (seconds), filament_total (mm) and filament_weight_total +// (grams). A malformed reply or any non-numeric field defaults to 0. +PrinterFileMetadata OrcaPrinterAgent::parse_file_metadata(const std::string& body) +{ + PrinterFileMetadata meta; + + const nlohmann::json envelope = nlohmann::json::parse(body, nullptr, false); + if (envelope.is_discarded() || !envelope.is_object()) + return meta; + + const auto result_it = envelope.find("result"); + if (result_it == envelope.end() || !result_it->is_object()) + return meta; + + const auto time_it = result_it->find("estimated_time"); + if (time_it != result_it->end() && time_it->is_number()) + meta.estimated_time = static_cast(time_it->get()); + + const auto total_it = result_it->find("filament_total"); + if (total_it != result_it->end() && total_it->is_number()) + meta.filament_total = total_it->get(); + + const auto weight_it = result_it->find("filament_weight_total"); + if (weight_it != result_it->end() && weight_it->is_number()) + meta.filament_weight = weight_it->get(); + + return meta; +} + +// Percent-encode each '/'-separated segment, leaving the separators themselves +// intact so the caller keeps the directory structure of a gcodes-relative path. +std::string OrcaPrinterAgent::encode_file_path(const std::string& path) +{ + std::string encoded; + size_t segment_start = 0; + while (segment_start <= path.size()) { + const size_t segment_end = path.find('/', segment_start); + if (!encoded.empty() || segment_start > 0) + encoded += '/'; + encoded += Http::url_encode(path.substr(segment_start, segment_end - segment_start)); + if (segment_end == std::string::npos) + break; + segment_start = segment_end + 1; + } + return encoded; +} + +// Fetch one file's embedded thumbnail: first resolve its path via the thumbnails +// listing, then download the image bytes. Mirrors list_printer_files for the +// connection snapshot and off-thread marshalling; the worker captures no `this`. +int OrcaPrinterAgent::get_printer_file_thumbnail(const std::string& dev_id, const std::string& path, PrinterFileThumbnailFn callback) +{ + std::string origin; + bool use_ssl = false; + std::string ca_file; + QueueOnMainFn queue; + bool live = false; + { + std::lock_guard lock(state_mutex); + live = m_current_connection == LAN && m_lan_dev_id == dev_id; + if (live) { + origin = http_origin_from_lan_ws(m_lan_url); + use_ssl = m_lan_use_ssl; + ca_file = m_lan_ca_file; + queue = queue_on_main_fn; + } + } + if (!live) { + if (callback) + callback(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED, {}); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + if (origin.empty()) { + if (callback) + callback(BAMBU_NETWORK_ERR_INVALID_HANDLE, {}); + return BAMBU_NETWORK_ERR_INVALID_HANDLE; + } + + std::thread([path, origin, use_ssl, ca_file, queue, callback = std::move(callback)]() mutable { + std::string image; + int result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + + std::string thumb_body; + bool listed = false; + auto http = Http::get(origin + "/server/files/thumbnails?filename=" + Http::url_encode(path)); + http.tls_verify(use_ssl); + if (!ca_file.empty()) + http.ca_file(ca_file); + http.timeout_connect(5) + .timeout_max(15) + .on_complete([&](std::string b, unsigned status) { + if (status == 200) { + thumb_body = std::move(b); + listed = true; + } + }) + .on_error([&](std::string, std::string err, unsigned status) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: thumbnail list request failed status=" << status << " err=" << err; + }) + .perform_sync(); + + if (listed) { + if (nlohmann::json::parse(thumb_body, nullptr, false).is_discarded()) { + result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + } else { + const std::string thumb_path = parse_thumbnail_path(thumb_body); + if (thumb_path.empty()) { + // No embedded thumbnail: a success the caller caches. + result = BAMBU_NETWORK_SUCCESS; + } else { + // The returned path is relative to the gcodes root, served at + // /server/files/gcodes; an explicit gcodes/ prefix is served at /server/files. + const std::string root = thumb_path.rfind("gcodes/", 0) == 0 ? "/server/files/" : "/server/files/gcodes/"; + auto image_http = Http::get(origin + root + encode_file_path(thumb_path)); + image_http.tls_verify(use_ssl); + if (!ca_file.empty()) + image_http.ca_file(ca_file); + image_http.timeout_connect(5) + .timeout_max(15) + .on_complete([&](std::string b, unsigned status) { + if (status == 200) { + image = std::move(b); + result = BAMBU_NETWORK_SUCCESS; + } + }) + .on_error([&](std::string, std::string err, unsigned status) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: thumbnail fetch failed status=" << status << " err=" << err; + }) + .perform_sync(); + } + } + } + + if (!callback) + return; + if (queue) + queue([callback, result, image = std::move(image)]() mutable { callback(result, std::move(image)); }); + else + callback(result, std::move(image)); + }).detach(); + + return BAMBU_NETWORK_SUCCESS; +} + +// Delete one G-code file via Moonraker's HTTP DELETE endpoint. Mirrors +// list_printer_files for the connection snapshot and off-thread marshalling; the +// worker captures no `this`. +int OrcaPrinterAgent::delete_printer_file(const std::string& dev_id, const std::string& path, PrinterFileDeleteFn callback) +{ + std::string origin; + bool use_ssl = false; + std::string ca_file; + QueueOnMainFn queue; + bool live = false; + { + std::lock_guard lock(state_mutex); + live = m_current_connection == LAN && m_lan_dev_id == dev_id; + if (live) { + origin = http_origin_from_lan_ws(m_lan_url); + use_ssl = m_lan_use_ssl; + ca_file = m_lan_ca_file; + queue = queue_on_main_fn; + } + } + if (!live) { + if (callback) + callback(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + if (origin.empty()) { + if (callback) + callback(BAMBU_NETWORK_ERR_INVALID_HANDLE); + return BAMBU_NETWORK_ERR_INVALID_HANDLE; + } + + std::thread([path, origin, use_ssl, ca_file, queue, callback = std::move(callback)]() mutable { + int result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + + auto http = Http::del(origin + "/server/files/gcodes/" + encode_file_path(path)); + http.tls_verify(use_ssl); + if (!ca_file.empty()) + http.ca_file(ca_file); + http.timeout_connect(5) + .timeout_max(15) + .on_complete([&](std::string, unsigned status) { + if (status == 200) + result = BAMBU_NETWORK_SUCCESS; + }) + .on_error([&](std::string, std::string err, unsigned status) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: file delete request failed status=" << status << " err=" << err; + }) + .perform_sync(); + + if (!callback) + return; + if (queue) + queue([callback, result]() mutable { callback(result); }); + else + callback(result); + }).detach(); + + return BAMBU_NETWORK_SUCCESS; +} + +// Fetch one file's Moonraker metadata (print time and filament usage). Mirrors +// list_printer_files for the connection snapshot and off-thread marshalling; the +// worker captures no `this`. +int OrcaPrinterAgent::get_printer_file_metadata(const std::string& dev_id, const std::string& path, PrinterFileMetadataFn callback) +{ + std::string origin; + bool use_ssl = false; + std::string ca_file; + QueueOnMainFn queue; + bool live = false; + { + std::lock_guard lock(state_mutex); + live = m_current_connection == LAN && m_lan_dev_id == dev_id; + if (live) { + origin = http_origin_from_lan_ws(m_lan_url); + use_ssl = m_lan_use_ssl; + ca_file = m_lan_ca_file; + queue = queue_on_main_fn; + } + } + if (!live) { + if (callback) + callback(ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED, {}); + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + if (origin.empty()) { + if (callback) + callback(BAMBU_NETWORK_ERR_INVALID_HANDLE, {}); + return BAMBU_NETWORK_ERR_INVALID_HANDLE; + } + + std::thread([path, origin, use_ssl, ca_file, queue, callback = std::move(callback)]() mutable { + PrinterFileMetadata meta; + int result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + + auto http = Http::get(origin + "/server/files/metadata?filename=" + Http::url_encode(path)); + http.tls_verify(use_ssl); + if (!ca_file.empty()) + http.ca_file(ca_file); + http.timeout_connect(5) + .timeout_max(15) + .on_complete([&](std::string b, unsigned status) { + if (status == 200) { + if (nlohmann::json::parse(b, nullptr, false).is_discarded()) + result = BAMBU_NETWORK_ERR_CONNECTION_TO_SERVER_FAILED; + else { + meta = parse_file_metadata(b); + result = BAMBU_NETWORK_SUCCESS; + } + } + }) + .on_error([&](std::string, std::string err, unsigned status) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: file metadata request failed status=" << status << " err=" << err; + }) + .perform_sync(); + + if (!callback) + return; + if (queue) + queue([callback, result, meta]() mutable { callback(result, meta); }); + else + callback(result, meta); + }).detach(); + + return BAMBU_NETWORK_SUCCESS; +} + // Upload the sliced G-code, then start it: the LAN "print now" path. int OrcaPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) { @@ -1588,6 +2171,59 @@ int OrcaPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusFn upd return start_sdcard_print(params, update_fn, cancel_fn); } +// Serialize PrintParams::ams_mapping2 (the dialog's mapping_v1_json, one entry per logical +// filament in preset order) into the print.gcode_file `filament_mapping` array. The array +// position becomes `filament_index`; {255,255} (unmatched/unused) is dropped. Returns an +// empty array when nothing usable remains so the caller can omit the field entirely. +nlohmann::json OrcaPrinterAgent::build_filament_mapping(const std::string& ams_mapping2) +{ + nlohmann::json mapping = nlohmann::json::array(); + if (ams_mapping2.empty()) + return mapping; + + const nlohmann::json parsed = nlohmann::json::parse(ams_mapping2, nullptr, false); + if (parsed.is_discarded() || !parsed.is_array()) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: ams_mapping2 is not a JSON array; not sending filament_mapping"; + return mapping; + } + + for (std::size_t i = 0; i < parsed.size(); ++i) { + const nlohmann::json& entry = parsed[i]; + if (!entry.is_object()) + continue; + const auto ams_id_it = entry.find("ams_id"); + const auto slot_id_it = entry.find("slot_id"); + if (ams_id_it == entry.end() || slot_id_it == entry.end()) + continue; + if (!ams_id_it->is_number_integer() || !slot_id_it->is_number_integer()) + continue; + + const int ams_id = ams_id_it->get(); + const int slot_id = slot_id_it->get(); + if (ams_id == 255 && slot_id == 255) + continue; + + mapping.push_back({{"filament_index", static_cast(i)}, {"ams_id", ams_id}, {"slot_id", slot_id}}); + } + return mapping; +} + +// Pure builder for the print.gcode_file payload: the base command plus, only +// when non-empty, the filament_mapping array. An empty mapping leaves the +// payload byte-identical to today's unmapped command. +nlohmann::json OrcaPrinterAgent::build_gcode_file_payload(const std::string& sequence_id, + const std::string& target, + const nlohmann::json& filament_mapping) +{ + nlohmann::json j; + j["print"]["command"] = "gcode_file"; + j["print"]["sequence_id"] = sequence_id; + j["print"]["param"] = target; + if (filament_mapping.is_array() && !filament_mapping.empty()) + j["print"]["filament_mapping"] = filament_mapping; + return j; +} + // Start a file that already lives on the printer by publishing the canonical // OPCP print.gcode_file command to device//request. The acknowledgement // and lifecycle progress arrive asynchronously as print.push_status on the @@ -1603,12 +2239,25 @@ int OrcaPrinterAgent::start_sdcard_print(PrintParams params, OnUpdateStatusFn up // dst_file, when set, names a file already on the printer (print-from-SD flow); // otherwise start what start_send_gcode_to_sdcard just uploaded to `gcodes`. - const std::string target = params.dst_file.empty() ? remote_gcode_name(params) : fs::path(params.dst_file).filename().string(); + // Keep the gcodes-relative path with subfolders preserved, minus a leading '/'. + std::string target = params.dst_file.empty() ? remote_gcode_name(params) : params.dst_file; + if (!target.empty() && target.front() == '/') + target.erase(target.begin()); - nlohmann::json j; - j["print"]["command"] = "gcode_file"; - j["print"]["sequence_id"] = next_gcode_file_sequence_id(); - j["print"]["param"] = target; + // Per-print mapping. A mapped print is refused when the connector did not + // advertise filament_mapping: the GUI send gates make this visible first, and + // this is the defensive gate for callers that bypass them (calibration, + // plugin). Never start a mapped print with the map silently dropped. + const nlohmann::json filament_mapping = build_filament_mapping(params.ams_mapping2); + if (!filament_mapping.empty()) { + if (!supports_feature(params.dev_id, "filament_mapping")) { + BOOST_LOG_TRIVIAL(warning) << "OrcaPrinterAgent: refusing mapped print, connector does not advertise filament_mapping"; + return ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED; + } + BOOST_LOG_TRIVIAL(info) << "OrcaPrinterAgent: start_sdcard_print emitting filament_mapping entries=" << filament_mapping.size(); + } + + nlohmann::json j = build_gcode_file_payload(next_gcode_file_sequence_id(), target, filament_mapping); if (update_fn) update_fn(PrintingStageSending, 0, "Starting print..."); diff --git a/src/slic3r/Utils/OrcaPrinterAgent.hpp b/src/slic3r/Utils/OrcaPrinterAgent.hpp index 337850a3a0..a3adcbf0fd 100644 --- a/src/slic3r/Utils/OrcaPrinterAgent.hpp +++ b/src/slic3r/Utils/OrcaPrinterAgent.hpp @@ -37,9 +37,16 @@ public: void set_cloud_agent(std::shared_ptr cloud) override; CameraStreamMode get_camera_stream_mode() const override; std::string get_camera_url() const override; + int list_printer_files(const std::string& dev_id, PrinterFileListFn callback) override; + int get_printer_file_thumbnail(const std::string& dev_id, const std::string& path, PrinterFileThumbnailFn callback) override; + int delete_printer_file(const std::string& dev_id, const std::string& path, PrinterFileDeleteFn callback) override; + int get_printer_file_metadata(const std::string& dev_id, const std::string& path, PrinterFileMetadataFn callback) override; // Communication int send_message(std::string dev_id, std::string json_str, int qos, int flag) override; + bool supports_command(const std::string& dev_id, const std::string& command) const override; + bool supports_feature(const std::string& dev_id, const std::string& feature) const override; + bool uses_filament_mapping() const override { return true; } int connect_printer(const PrinterConnectionParams& params) override; int disconnect_printer() override; int send_message_to_printer(std::string dev_id, std::string json_str, int qos, int flag) override; @@ -54,6 +61,7 @@ public: // Machine Selection std::string get_user_selected_machine() override; int set_user_selected_machine(std::string dev_id) override; + int unbind(std::string dev_id) override; /** * Get agent information. @@ -65,6 +73,8 @@ public: // Print Job Operations int start_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) override; + // Unimplemented on OrcaSonar: reports a non-success result so callers fall back to + // start_print() instead of treating the missing send as success. int start_local_print_with_record(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) override; int start_send_gcode_to_sdcard(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) override; int start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) override; @@ -128,6 +138,9 @@ protected: // once parse_json reads the Orca dialect natively. See the definition for the // per-rule detail. Returns the payload unchanged when no rule applies. std::string merge_capabilities(const std::string& dev_id, const std::string& payload); + void forget_device_capabilities(const std::string& dev_id); + int prepare_outgoing_request(const std::string& dev_id, const std::string& payload, + std::string& command, std::string& prepared) const; // Report the asynchronous LAN connection state using the same callback contract as // the other printer agents. The transport result cannot be returned by @@ -141,6 +154,34 @@ protected: // Pure LAN-address parsing + client-id. protected static so the test Probe reaches them. static bool parse_lan_endpoint(const std::string& dev_ip, std::string& host, std::string& port); static std::string make_lan_client_id(const std::string& dev_id); + + // Pure serializer for PrintParams::ams_mapping2 -> print.gcode_file.filament_mapping. + // Entries are re-keyed by their array position; {255,255} is dropped. Empty when the + // input is empty, malformed, or has no usable entries. protected static for the test Probe. + static nlohmann::json build_filament_mapping(const std::string& ams_mapping2); + + // Pure builder for the print.gcode_file command payload. A non-empty mapping is + // included as filament_mapping; an empty one is omitted so the payload is + // byte-identical to an unmapped print. protected static for the test Probe. + static nlohmann::json build_gcode_file_payload(const std::string& sequence_id, + const std::string& target, + const nlohmann::json& filament_mapping); + + // Pure JSON -> entries normalization for OrcaSonar's /server/files/list reply. + // protected static so the test Probe reaches it. + static std::vector parse_file_list(const std::string& body); + + // Pick the widest thumbnail path from OrcaSonar's /server/files/thumbnails + // reply (the array is smallest-first). Empty when none carry a path. + static std::string parse_thumbnail_path(const std::string& body); + + // Pure JSON -> metadata normalization for OrcaSonar's /server/files/metadata + // reply. Missing or malformed fields default to 0. protected static for the Probe. + static PrinterFileMetadata parse_file_metadata(const std::string& body); + + // Percent-encode each '/'-separated segment for a Moonraker URL while keeping + // the separators intact. protected static for the test Probe. + static std::string encode_file_path(const std::string& path); // Test hook: the ws:// URL connect_printer built for the current LAN session ("" if none). std::string lan_connection_target() const; // Shared post-connect sequence: SUBSCRIBE, then pushing.start, pushall, diff --git a/tests/fff_print/test_multifilament.cpp b/tests/fff_print/test_multifilament.cpp index d3df8807e3..857ae833ee 100644 --- a/tests/fff_print/test_multifilament.cpp +++ b/tests/fff_print/test_multifilament.cpp @@ -49,6 +49,20 @@ static std::set tools_for_role(const std::string& gcode, const std::string& return tools; } +// Every id named by a Tn command anywhere in `gcode`. A non-BBL single-extruder multi-filament +// setup emits T, and that id is what the Klipper toolchange macro consumes. +static std::set tool_ids(const std::string& gcode) +{ + std::set tools; + GCodeReader reader; + reader.parse_buffer(gcode, [&tools](GCodeReader&, const GCodeReader::GCodeLine& line) { + const std::string cmd(line.cmd()); + if (cmd.size() >= 2 && cmd[0] == 'T' && std::isdigit((unsigned char)cmd[1])) + tools.insert(std::stoi(cmd.substr(1))); + }); + return tools; +} + // X where the nozzle sits while each tagged _WAIT_FOR_TEMP_ON_WIPE_TOWER M109 blocks: // the nearest preceding G1 carrying an X (the park travel emitted just before the wait). static std::vector wait_park_xs(const std::string& gcode) @@ -296,6 +310,29 @@ TEST_CASE("Each feature prints with its assigned filament (three filaments)", "[ CHECK(tools_for_role(gcode, "infill") == std::set{ 1 }); // filament 2 } +// The per-print wire mapping keys each entry by the filament's index in the config filament +// arrays (the ams_mapping2 position). Pin that the id the toolchange emits is that index even +// when the used filaments skip a middle one: filament 2 (index 1) is configured but unused, so +// a renumbering to the used set would emit {0, 1} instead of {0, 2} and aim the map at the +// wrong lane. +TEST_CASE("Toolchange ids keep the config index of the used filament when a middle filament is unused", "[MultiFilament]") +{ + const std::string gcode = slice({ cube(20) }, + multifilament_config(3, { + { "sparse_infill_filament_id", 1 }, + { "internal_solid_filament_id", 1 }, + { "top_surface_filament_id", 1 }, + { "bottom_surface_filament_id", 1 }, + { "outer_wall_filament_id", 3 }, + { "inner_wall_filament_id", 3 }, + { "skirt_loops", 0 }, + { "brim_type", "no_brim" }, + })); + CHECK(tools_for_role(gcode, "perimeter") == std::set{ 2 }); // filament 3 + CHECK(tools_for_role(gcode, "infill") == std::set{ 0 }); // filament 1 + CHECK(tool_ids(gcode) == std::set{ 0, 2 }); +} + // The override must survive tool ordering: object 1's walls print on their filament's // tool, object 0 stays on the first. If dropped, every wall prints on tool 0. TEST_CASE("Per-object wall filament override is honored", "[MultiFilament]") diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index dbcb23e015..17afd6e6cb 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -25,6 +25,7 @@ add_executable(${_TEST_NAME}_tests test_toolordering_nozzle_group.cpp test_parallel_resolve.cpp test_preset_bundle_loading.cpp + test_preset_bundle_ams_sync.cpp test_preset_setting_id.cpp test_preset_diff.cpp test_vendor_cache.cpp diff --git a/tests/libslic3r/test_preset_bundle_ams_sync.cpp b/tests/libslic3r/test_preset_bundle_ams_sync.cpp new file mode 100644 index 0000000000..ed57381a51 --- /dev/null +++ b/tests/libslic3r/test_preset_bundle_ams_sync.cpp @@ -0,0 +1,155 @@ +#include + +#include +#include +#include +#include + +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" + +using namespace Slic3r; + +namespace { + +// In-memory system filament preset. Mirrors the helper in test_preset_bundle_loading.cpp. +Preset &add_system_filament(PresetBundle &bundle, const std::string &name, const std::string &filament_id, const std::string &filament_type) +{ + DynamicPrintConfig config(bundle.filaments.default_preset().config); + config.option(BBL_JSON_KEY_INHERITS, true)->value = ""; + config.option("filament_type", true)->values = {filament_type}; + Preset &preset = bundle.filaments.load_preset(std::string(), name, config, /*select=*/false); + preset.is_system = true; + preset.filament_id = filament_id; + return preset; +} + +// One AMS tray entry as build_filament_ams_list produces it. +DynamicPrintConfig make_tray(const std::string &filament_id, const std::string &filament_type, const std::string &color, const std::string &ams_id, + const std::string &slot_id) +{ + DynamicPrintConfig tray; + tray.set_key_value("filament_id", new ConfigOptionStrings{filament_id}); + tray.set_key_value("filament_type", new ConfigOptionStrings{filament_type}); + tray.set_key_value("filament_colour", new ConfigOptionStrings{color}); + tray.set_key_value("filament_colour_type", new ConfigOptionStrings{"1"}); + tray.set_key_value("filament_multi_colour", new ConfigOptionStrings{}); + tray.set_key_value("ams_id", new ConfigOptionStrings{ams_id}); + tray.set_key_value("slot_id", new ConfigOptionStrings{slot_id}); + return tray; +} + +} // namespace + +// A tray the printer UI wrote carries a material type but no OrcaSlicer preset id. It must still +// sync, resolved to Generic with the tray's own color. +TEST_CASE("AMS sync resolves a printer-set tray to Generic by material type", "[Preset][AMS]") +{ + PresetBundle bundle; + add_system_filament(bundle, "Generic PETG @Q2", "OFYPdQJh", "PETG"); + add_system_filament(bundle, "Generic PLA @Q2", "GFL99", "PLA"); + + bundle.filament_ams_list[0] = make_tray("OFYPdQJh", "PETG", "#FE717A", "0", "0"); // preset-backed + bundle.filament_ams_list[1] = make_tray("", "PETG", "#898F9B", "0", "1"); // printer-set, no id + bundle.filament_ams_list[2] = make_tray("", "PLA", "#FAFAFA", "0", "2"); // printer-set, no id + bundle.filament_ams_list[3] = make_tray("", "", "#000000", "0", "3"); // empty slot + + std::vector> unknowns; + std::map maps; + MergeFilamentInfo merge; + + const unsigned int count = bundle.sync_ams_list(unknowns, /*use_map=*/false, maps, /*enable_append=*/false, merge); + + CHECK(count == 3); + REQUIRE(bundle.filament_presets.size() == 3); + CHECK(bundle.filament_presets[0] == "Generic PETG @Q2"); + CHECK(bundle.filament_presets[1] == "Generic PETG @Q2"); + CHECK(bundle.filament_presets[2] == "Generic PLA @Q2"); + + const ConfigOptionStrings *colors = bundle.project_config.option("filament_colour"); + REQUIRE(colors != nullptr); + REQUIRE(colors->values.size() == 3); + CHECK(colors->values[0] == "#FE717A"); + CHECK(colors->values[1] == "#898F9B"); + CHECK(colors->values[2] == "#FAFAFA"); +} + +// Without a preset id and without a material type there is nothing to resolve; the tray stays +// skipped in a direct sync. +TEST_CASE("AMS sync skips a tray without a preset id or a material type", "[Preset][AMS]") +{ + PresetBundle bundle; + add_system_filament(bundle, "Generic PETG @Q2", "OFYPdQJh", "PETG"); + bundle.filament_ams_list[0] = make_tray("", "", "#000000", "0", "0"); + + std::vector> unknowns; + std::map maps; + MergeFilamentInfo merge; + + CHECK(bundle.sync_ams_list(unknowns, /*use_map=*/false, maps, /*enable_append=*/false, merge) == 0); + CHECK(bundle.filament_presets.empty()); +} + +// Guard the pre-existing behavior: a non-empty id that matches no preset still resolves by type. +TEST_CASE("AMS sync still resolves an unmatched preset id by material type", "[Preset][AMS]") +{ + PresetBundle bundle; + add_system_filament(bundle, "Generic PETG @Q2", "OFYPdQJh", "PETG"); + bundle.filament_ams_list[0] = make_tray("REMOVED_ID", "PETG", "#123456", "0", "0"); + + std::vector> unknowns; + std::map maps; + MergeFilamentInfo merge; + + CHECK(bundle.sync_ams_list(unknowns, /*use_map=*/false, maps, /*enable_append=*/false, merge) == 1); + REQUIRE(bundle.filament_presets.size() == 1); + CHECK(bundle.filament_presets[0] == "Generic PETG @Q2"); +} + +// Mapping-mode sync used to force "Generic PLA" for an id-less tray; it must use the type instead. +TEST_CASE("AMS sync in mapping mode resolves a printer-set tray to Generic, not Generic PLA", "[Preset][AMS]") +{ + PresetBundle bundle; + add_system_filament(bundle, "Generic PETG @Q2", "OFYPdQJh", "PETG"); + add_system_filament(bundle, "Generic PLA @Q2", "GFL99", "PLA"); + + bundle.filament_presets = {"Generic PLA @Q2"}; + bundle.project_config.option("filament_colour")->values = {"#000000"}; + bundle.project_config.option("filament_colour_type")->values = {"1"}; + + bundle.filament_ams_list[0] = make_tray("", "PETG", "#898F9B", "0", "1"); + + std::map maps; + maps[0] = AMSMapInfo{"0", "1"}; + + std::vector> unknowns; + MergeFilamentInfo merge; + + const unsigned int count = bundle.sync_ams_list(unknowns, /*use_map=*/true, maps, /*enable_append=*/false, merge); + + CHECK(count == 1); + REQUIRE(bundle.filament_presets.size() == 1); + CHECK(bundle.filament_presets[0] == "Generic PETG @Q2"); + CHECK(bundle.project_config.option("filament_colour")->values[0] == "#898F9B"); +} + +// The dialog builds ams_mapping2 one entry per filament_presets index, while the generated +// G-code's toolchange names the filament's index in the slice's filament config arrays. Those +// are the same index only if full_config() collects the filament arrays in filament_presets +// order; if a refactor reorders one side, every mapped print aims at the wrong lane. +TEST_CASE("Full config filament arrays follow the selected filament preset order", "[Preset][AMS]") +{ + PresetBundle bundle; + add_system_filament(bundle, "Generic PETG @Q2", "OFYPdQJh", "PETG"); + add_system_filament(bundle, "Generic PLA @Q2", "GFL99", "PLA"); + + // Deliberately not the load order: the arrays must follow this selection. + bundle.filament_presets = {"Generic PLA @Q2", "Generic PETG @Q2"}; + + const DynamicPrintConfig full = bundle.full_config(/*apply_extruder=*/false); + REQUIRE(full.option("filament_type") != nullptr); + CHECK(full.option("filament_settings_id")->values == std::vector{"Generic PLA @Q2", "Generic PETG @Q2"}); + CHECK(full.option("filament_type")->values == std::vector{"PLA", "PETG"}); + // The AMS sync matches trays by filament_id, so this array must follow the same order. + CHECK(full.option("filament_ids")->values == std::vector{"GFL99", "OFYPdQJh"}); +} diff --git a/tests/libslic3r/test_preset_bundle_loading.cpp b/tests/libslic3r/test_preset_bundle_loading.cpp index 7dfba69cbd..8b1b970a9e 100644 --- a/tests/libslic3r/test_preset_bundle_loading.cpp +++ b/tests/libslic3r/test_preset_bundle_loading.cpp @@ -1601,6 +1601,23 @@ TEST_CASE("Filaments offered for a machine follow the app's compatibility rule", } } +// An agent-reported model id (SSDP modelNumber, manual binding) must resolve to the display +// name printer profiles use as printer_model; the AMS dialogs look filaments up by it. +TEST_CASE("Printer model ids resolve to vendor display names", "[Preset][Bundle]") +{ + PresetBundle bundle; + VendorProfile qidi("Qidi"); + qidi.name = "Qidi"; + VendorProfile::PrinterModel model; + model.model_id = "Qidi-Q1Pro"; + model.name = "Qidi Q1 Pro"; + qidi.models.push_back(model); + bundle.vendors.emplace(qidi.id, qidi); + + CHECK(bundle.get_printer_model_display_name("Qidi-Q1Pro") == "Qidi Q1 Pro"); + CHECK(bundle.get_printer_model_display_name("unknown-model").empty()); +} + namespace { diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 1ade7b3faf..a7d3e15169 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests test_dev_mapping.cpp test_filament_bitmap_utils.cpp test_device_progress.cpp + test_ams_item.cpp test_device_manager_integration.cpp test_web_media_controller.cpp test_scene_raycaster.cpp diff --git a/tests/slic3rutils/test_ams_item.cpp b/tests/slic3rutils/test_ams_item.cpp new file mode 100644 index 0000000000..0c92b551fc --- /dev/null +++ b/tests/slic3rutils/test_ams_item.cpp @@ -0,0 +1,86 @@ +// why: match the GUI include order to avoid rpcndr.h byte/std::byte +// ambiguity in the Windows COM headers. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include +#endif + +#include + +#include + +#include + +#include "slic3r/GUI/Widgets/AMSItem.hpp" +#include "slic3r/GUI/DeviceCore/DevFilaSystem.h" + +using json = nlohmann::json; +using namespace Slic3r; +using namespace Slic3r::GUI; + +// A configured slot the wire reports as having no filament (all material fields +// present and empty) is "Empty", not the unknown "?" the UI draws for a tray +// whose info is missing. The distinction must survive into the AMS panel model. +TEST_CASE("Configured empty AMS trays remain distinct from unknown trays", "[AMSItem]") +{ + MachineObject machine(nullptr, nullptr, "test", "test-device", "127.0.0.1"); + machine.printer_agent_id = "orca"; + + const json print_json = json::parse(R"({ + "ams": { + "ams_exist_bits": "1", + "tray_exist_bits": "3", + "ams": [ { "id": "0", "info": "0001", "tray": [ + { "id": "0", "tag_uid": "0000000000000000", "tray_info_idx": "", "tray_type": "", "tray_color": "00000000" }, + { "id": "1" } + ] } ] + } + })"); + DevFilaSystemParser::ParseV1_0(print_json, &machine, machine.GetFilaSystem().get(), false); + + const auto& ams_list = machine.GetFilaSystem()->GetAmsList(); + const auto ams_it = ams_list.find("0"); + REQUIRE(ams_it != ams_list.end()); + auto* ams = ams_it->second; + REQUIRE(ams != nullptr); + REQUIRE(ams->GetTray("0") != nullptr); + CHECK(ams->GetTray("0")->is_empty); + + AMSinfo info; + REQUIRE(info.parse_ams_info(&machine, ams)); + REQUIRE(info.cans.size() == 2); + + CHECK(info.cans[0].is_empty); + CHECK(info.cans[0].material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND); + CHECK_FALSE(info.cans[1].is_empty); + CHECK(info.cans[1].material_state == AMSCanType::AMS_CAN_TYPE_THIRDBRAND); +} + +TEST_CASE("Empty external slots remain distinct from unknown slots", "[AMSItem]") +{ + MachineObject machine(nullptr, nullptr, "test", "test-device", "127.0.0.1"); + machine.printer_agent_id = "orca"; + + DevAmsTray empty_slot = machine.parse_vt_tray(json::parse(R"({ + "id": "255", "tag_uid": "0000000000000000", "tray_info_idx": "", "tray_type": "", "tray_color": "00000000" + })")); + CHECK(empty_slot.is_empty); + + AMSinfo empty_info; + empty_info.parse_ext_info(&machine, empty_slot); + CHECK(empty_info.cans[0].is_empty); + CHECK(empty_info.cans[0].material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL); + + DevAmsTray unknown_slot = machine.parse_vt_tray(json::parse(R"({"id": "254"})")); + CHECK_FALSE(unknown_slot.is_empty); + + AMSinfo unknown_info; + unknown_info.parse_ext_info(&machine, unknown_slot); + CHECK_FALSE(unknown_info.cans[0].is_empty); + CHECK(unknown_info.cans[0].material_state == AMSCanType::AMS_CAN_TYPE_VIRTUAL); +} diff --git a/tests/slic3rutils/test_device_manager_integration.cpp b/tests/slic3rutils/test_device_manager_integration.cpp index 7e58dc7696..022c3ad3a8 100644 --- a/tests/slic3rutils/test_device_manager_integration.cpp +++ b/tests/slic3rutils/test_device_manager_integration.cpp @@ -3,7 +3,11 @@ #include #include +#include +#include #include +#include +#include #include "slic3r/Utils/IPrinterAgent.hpp" #include "slic3r/Utils/CloudProvider.hpp" #include @@ -18,6 +22,8 @@ #include using namespace Slic3r; +using Slic3r::GUI::MappingSendError; +using Slic3r::GUI::prepare_filament_mapping_for_send; using json = nlohmann::json; namespace { @@ -49,6 +55,30 @@ public: AgentInfo get_agent_info() override { return m_info; } + // This test double represents a legacy agent, not OrcaPrinterAgent behavior. + bool supports_command(const std::string&, const std::string&) const override { return true; } + + // It models whichever agent is registered under its id: only the Orca agent + // serializes per-print filament_mapping. + bool uses_filament_mapping() const override { return m_info.id == "orca"; } + + using OrcaPrinterAgent::deliver_to_sink; + + int send_message(std::string, std::string json_str, int, int) override + { + last_message = std::move(json_str); + return send_result; + } + + int send_message_to_printer(std::string, std::string json_str, int, int) override + { + last_message = std::move(json_str); + return send_result; + } + + std::string last_message; + int send_result = 0; + private: AgentInfo m_info; }; @@ -160,3 +190,183 @@ TEST_CASE("Device manager filters and rehomes devices by printer-agent ownership CHECK(manager.get_my_machine_list("integration-agent-a").empty()); CHECK(manager.get_my_machine_list("integration-agent-b").count(machine.dev_id) == 1); } + +TEST_CASE("Network agent rejects capability queries for a different device owner", "[DeviceManager][integration]") +{ + NetworkAgent network(nullptr, std::make_shared("bbl")); + + CHECK(network.owns_agent("bbl")); + CHECK_FALSE(network.owns_agent("orca")); + CHECK(network.supports_command("bbl", "device", "print.ams_control")); + CHECK_FALSE(network.supports_command("orca", "device", "print.ams_control")); + CHECK_FALSE(network.supports_feature("orca", "device", "filament_mapping")); + + // The mapping dialect is queried the same way: a legacy owner never inherits + // Orca's, and a non-owner is never queried at all. + CHECK_FALSE(network.uses_filament_mapping("bbl")); + CHECK_FALSE(network.uses_filament_mapping("orca")); + + NetworkAgent orca_network(nullptr, std::make_shared("orca")); + CHECK(orca_network.uses_filament_mapping("orca")); + CHECK_FALSE(orca_network.uses_filament_mapping("bbl")); +} + +// Send-time mapping policy belongs to the printer agent's dialect, not to an +// agent id: the Orca dialect gets the no-AMS normalization plus both refusals. +TEST_CASE("Per-print mapping send policy follows the owning agent's dialect", "[DeviceManager][integration]") +{ + auto orca_agent = std::make_shared("orca"); + NetworkAgent network(nullptr, orca_agent); + MachineObject obj(nullptr, &network, "test", "orca-mapping-policy", "127.0.0.1"); + obj.printer_agent_id = "orca"; + + // No AMS: the auto-selected external spool is dropped before the capability + // gate, so it cannot refuse a print nobody mapped. + std::string external_only = R"([{"ams_id":255,"slot_id":0}])"; + CHECK(prepare_filament_mapping_for_send(&obj, external_only, {}) == MappingSendError::none); + CHECK(external_only.empty()); + + // An AMS makes that a real target, but nothing advertised the capability yet. + obj.GetFilaSystem()->GetAmsList()["0"] = new DevAms("0", 0, DevAms::AMS); + std::string mapped = R"([{"ams_id":0,"slot_id":0}])"; + CHECK(prepare_filament_mapping_for_send(&obj, mapped, {}) == MappingSendError::unsupported); + CHECK(mapped == R"([{"ams_id":0,"slot_id":0}])"); // the refusal leaves it intact + + // Once the connector advertises the capability the mapping passes the gate. + orca_agent->deliver_to_sink(obj.get_dev_id(), + R"({"info":{"command":"get_capabilities","supported_features":{"filament_mapping":true}}})", + false); + CHECK(obj.printer_supports_feature("filament_mapping")); + CHECK(prepare_filament_mapping_for_send(&obj, mapped, {}) == MappingSendError::none); + + // An unrecorded owner still sends through the active agent, so it takes + // that agent's dialect too rather than falling back to the legacy payload. + MachineObject unowned(nullptr, &network, "test", "orca-unowned", "127.0.0.1"); + CHECK(unowned.printer_agent_id.empty()); + CHECK(unowned.printer_uses_filament_mapping()); + std::string unowned_external = R"([{"ams_id":255,"slot_id":0}])"; + CHECK(prepare_filament_mapping_for_send(&unowned, unowned_external, {}) == MappingSendError::none); + CHECK(unowned_external.empty()); // the Orca normalization ran + + // A partially mapped print is refused even while the capability holds. + FilamentInfo mapped_entry; + mapped_entry.ams_id = "0"; + mapped_entry.slot_id = "0"; + FilamentInfo unmapped_entry; + CHECK(prepare_filament_mapping_for_send(&obj, mapped, {mapped_entry, unmapped_entry}) == + MappingSendError::incomplete); +} + +// The legacy payload is the thing being protected: no normalization, no refusal. +TEST_CASE("A legacy printer agent keeps its mapping payload untouched", "[DeviceManager][integration]") +{ + NetworkAgent network(nullptr, std::make_shared("bbl")); + MachineObject obj(nullptr, &network, "test", "bbl-mapping-policy", "127.0.0.1"); + obj.printer_agent_id = "bbl"; + + FilamentInfo mapped_entry; + mapped_entry.ams_id = "0"; + mapped_entry.slot_id = "0"; + FilamentInfo unmapped_entry; + + std::string external_only = R"([{"ams_id":255,"slot_id":0}])"; + CHECK(prepare_filament_mapping_for_send(&obj, external_only, {mapped_entry, unmapped_entry}) == + MappingSendError::none); + CHECK(external_only == R"([{"ams_id":255,"slot_id":0}])"); +} + +TEST_CASE("AMS metadata retains setting_id for legacy printer agents", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + auto printer_agent = std::make_shared("bbl"); + NetworkAgent network(nullptr, printer_agent); + DeviceManager manager(&network, false, &app_config.config); + + BBLocalMachine machine; + machine.dev_id = "bbl-setting-id"; + machine.dev_name = "Bambu setting id"; + machine.dev_ip = "192.0.2.32"; + machine.printer_type = "C11"; + MachineObject* obj = manager.insert_local_device(machine, "lan", "free", "", "access-code"); + REQUIRE(obj != nullptr); + + REQUIRE(obj->command_ams_filament_settings(0, 1, "GFL99", "preset-setting", "00FF00FF", "PLA", 190, 220) == 0); + const json payload = json::parse(printer_agent->last_message); + CHECK(payload["print"]["setting_id"] == "preset-setting"); +} + +TEST_CASE("AMS user settings do not update local state when publishing fails", "[DeviceManager][integration]") +{ + ScopedAppConfig app_config; + auto printer_agent = std::make_shared("bbl"); + NetworkAgent network(nullptr, printer_agent); + DeviceManager manager(&network, false, &app_config.config); + + BBLocalMachine machine; + machine.dev_id = "bbl-ams-setting-failure"; + machine.dev_name = "Bambu AMS settings"; + machine.dev_ip = "192.0.2.33"; + machine.printer_type = "C11"; + MachineObject* obj = manager.insert_local_device(machine, "lan", "free", "", "access-code"); + REQUIRE(obj != nullptr); + + auto& settings = obj->GetFilaSystem()->GetAmsSystemSetting(); + settings.SetDetectOnInsertEnabled(false); + settings.SetDetectOnPowerupEnabled(false); + settings.SetDetectRemainEnabled(false); + printer_agent->send_result = -1; + + CHECK(obj->command_ams_user_settings(true, true, true) != 0); + CHECK(settings.IsDetectOnInsertEnabled() == false); + CHECK(settings.IsDetectOnPowerupEnabled() == false); + CHECK(settings.IsDetectRemainEnabled() == false); +} + +// The AMS dialogs resolve their filament list from the connected device's model. OrcaSonar's +// model id is optional (the agent falls back to "orcasonar"), so the resolver must stand in +// with the selected printer profile instead of yielding no model at all. +TEST_CASE("Filament printer model resolution falls back to the selected profile", "[DeviceManager][integration]") +{ + PresetBundle bundle; + + VendorProfile qidi("Qidi"); + qidi.name = "Qidi"; + VendorProfile::PrinterModel model; + model.model_id = "Qidi-Q1Pro"; + model.name = "Qidi Q1 Pro"; + qidi.models.push_back(model); + bundle.vendors.emplace(qidi.id, qidi); + + // A vendor model id the device reported resolves through the vendor catalog. + CHECK(resolve_filament_printer_model("Qidi-Q1Pro", &bundle) == "Qidi Q1 Pro"); + + // The OrcaSonar fallback id has no vendor model; the selected profile stands in. + CHECK(resolve_filament_printer_model("orcasonar", &bundle).empty()); + bundle.printers.get_selected_preset().config.set_key_value("printer_model", new ConfigOptionString("Generic Klipper Printer")); + CHECK(resolve_filament_printer_model("orcasonar", &bundle) == "Generic Klipper Printer"); + CHECK(resolve_filament_printer_model("", &bundle) == "Generic Klipper Printer"); + + CHECK(resolve_filament_printer_model("orcasonar", nullptr).empty()); +} + +// The per-tray K/N records are Bambu firmware's flow-dynamics calibration. Agents with no +// printer-side records must not offer the AMS K/N controls (they would show a synthesized +// default and then refuse to confirm it). +TEST_CASE("Flow-dynamics K/N is offered for Bambu agents only", "[DeviceManager][integration]") +{ + MachineObject bbl(nullptr, nullptr, "test", "bbl-device", "127.0.0.1"); + bbl.printer_agent_id = "bbl"; + CHECK(bbl.supports_extrusion_cali()); + + MachineObject orca(nullptr, nullptr, "test", "orca-device", "127.0.0.1"); + orca.printer_agent_id = "orca"; + CHECK_FALSE(orca.supports_extrusion_cali()); + + MachineObject moonraker(nullptr, nullptr, "test", "moonraker-device", "127.0.0.1"); + moonraker.printer_agent_id = "moonraker"; + CHECK_FALSE(moonraker.supports_extrusion_cali()); + + // No agent id predates the agent split and keeps the Bambu path. + MachineObject legacy(nullptr, nullptr, "test", "legacy-device", "127.0.0.1"); + CHECK(legacy.supports_extrusion_cali()); +} diff --git a/tests/slic3rutils/test_orca_printer_agent.cpp b/tests/slic3rutils/test_orca_printer_agent.cpp index 1ff111a879..f834d04449 100644 --- a/tests/slic3rutils/test_orca_printer_agent.cpp +++ b/tests/slic3rutils/test_orca_printer_agent.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include #include @@ -22,6 +24,13 @@ struct Probe : OrcaPrinterAgent { using OrcaPrinterAgent::parse_lan_endpoint; using OrcaPrinterAgent::make_lan_client_id; using OrcaPrinterAgent::lan_connection_target; + using OrcaPrinterAgent::build_filament_mapping; + using OrcaPrinterAgent::build_gcode_file_payload; + using OrcaPrinterAgent::prepare_outgoing_request; + using OrcaPrinterAgent::parse_file_list; + using OrcaPrinterAgent::parse_thumbnail_path; + using OrcaPrinterAgent::encode_file_path; + using OrcaPrinterAgent::parse_file_metadata; }; } @@ -68,6 +77,91 @@ TEST_CASE("OrcaPrinterAgent stamps the get_capabilities nozzle diameter onto pus CHECK(last_payload.find("N/A") == std::string::npos); } +TEST_CASE("OrcaPrinterAgent owns connector capabilities and fails closed for AMS commands", "[OrcaPrinterAgent]") { + Probe agent("/tmp"); + agent.deliver_to_sink("orca-caps", R"({ + "info": { + "command": "get_capabilities", + "supported_features": {"fms": true, "filament_slots": true, "filament_mapping": true}, + "supported_commands": ["print.ams_get_rfid"], + "capabilities": { + "protocol": { + "features": {"filament_mapping": true}, + "supported_commands": ["print.ams_change_filament"] + } + } + } + })", false); + + CHECK(agent.supports_feature("orca-caps", "filament_mapping")); + CHECK(agent.supports_command("orca-caps", "print.ams_filament_setting")); + CHECK(agent.supports_command("orca-caps", "print.ams_change_filament")); + CHECK(agent.supports_command("orca-caps", "print.ams_get_rfid")); + CHECK_FALSE(agent.supports_command("orca-caps", "print.ams_control")); + + agent.deliver_to_sink("orca-caps", R"({ + "info": { + "command": "get_capabilities", + "supported_features": {"fms": false, "filament_slots": false, "filament_mapping": false}, + "supported_commands": ["print.ams_control"], + "capabilities": {"protocol": {"features": {}, "supported_commands": []}} + } + })", false); + + CHECK_FALSE(agent.supports_feature("orca-caps", "filament_mapping")); + CHECK_FALSE(agent.supports_command("orca-caps", "print.ams_filament_setting")); + CHECK_FALSE(agent.supports_command("orca-caps", "print.ams_change_filament")); + CHECK_FALSE(agent.supports_command("orca-caps", "print.ams_control")); + CHECK_FALSE(agent.supports_command("orca-caps", "print.ams_calibrate")); + CHECK(agent.supports_command("orca-caps", "print.gcode_file")); +} + +TEST_CASE("OrcaPrinterAgent clears cached capabilities when a device is unbound", "[OrcaPrinterAgent]") { + Probe agent("/tmp"); + agent.deliver_to_sink("orca-forget", R"({ + "info": { + "command": "get_capabilities", + "supported_features": {"filament_slots": true}, + "supported_commands": [], + "capabilities": {"protocol": {"features": {}, "supported_commands": []}} + } + })", false); + REQUIRE(agent.supports_command("orca-forget", "print.ams_filament_setting")); + + agent.unbind("orca-forget"); + CHECK_FALSE(agent.supports_command("orca-forget", "print.ams_filament_setting")); +} + +TEST_CASE("OrcaPrinterAgent removes setting_id from AMS metadata and gates the request", "[OrcaPrinterAgent]") { + Probe agent("/tmp"); + agent.deliver_to_sink("orca-ams-write", R"({ + "info": { + "command": "get_capabilities", + "supported_features": {"fms": false, "filament_slots": true}, + "supported_commands": [], + "capabilities": {"protocol": {"features": {"filament_slots": true}, "supported_commands": []}} + } + })", false); + + const std::string request = R"({"print":{"command":"ams_filament_setting","sequence_id":"9","tray_info_idx":"GFL99","setting_id":"preset-setting"}})"; + std::string command; + std::string prepared; + CHECK(agent.prepare_outgoing_request("orca-ams-write", request, command, prepared) == BAMBU_NETWORK_SUCCESS); + CHECK(command == "print.ams_filament_setting"); + const nlohmann::json parsed = nlohmann::json::parse(prepared); + CHECK_FALSE(parsed["print"].contains("setting_id")); + CHECK(parsed["print"]["tray_info_idx"] == "GFL99"); + + agent.deliver_to_sink("orca-ams-write", R"({ + "info": { + "command": "get_capabilities", + "supported_features": {"filament_slots": false}, + "capabilities": {"protocol": {"features": {"filament_slots": false}}} + } + })", false); + CHECK(agent.prepare_outgoing_request("orca-ams-write", request, command, prepared) == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); +} + TEST_CASE("OrcaPrinterAgent::parse_lan_endpoint", "[OrcaPrinterAgent]") { std::string h, p; REQUIRE(Probe::parse_lan_endpoint("192.168.1.9", h, p)); @@ -84,6 +178,276 @@ TEST_CASE("OrcaPrinterAgent::make_lan_client_id is stable and prefixed", "[OrcaP CHECK(a.rfind("orcaslicer-lan-dev-1-", 0) == 0); } +TEST_CASE("OrcaPrinterAgent::parse_file_list normalizes Moonraker entries", "[OrcaPrinterAgent]") { + const std::vector files = Probe::parse_file_list(R"({ + "result": [ + {"path": "sub/foo.gcode", "modified": 1700000000.75, "size": 1234, "permissions": "rw"}, + {"path": "bar.gcode", "modified": 42, "size": 7} + ] + })"); + REQUIRE(files.size() == 2); + CHECK(files[0].path == "sub/foo.gcode"); + CHECK(files[0].name == "foo.gcode"); + CHECK(files[0].size == 1234); + CHECK(files[0].modified == 1700000000); // fractional seconds truncate + CHECK(files[1].path == "bar.gcode"); + CHECK(files[1].name == "bar.gcode"); + CHECK(files[1].size == 7); + CHECK(files[1].modified == 42); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_list handles an empty result", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_file_list(R"({"result": []})").empty()); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_list rejects malformed JSON", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_file_list("not json").empty()); + CHECK(Probe::parse_file_list(R"({"result": "nope"})").empty()); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_list skips entries missing fields", "[OrcaPrinterAgent]") { + const std::vector files = Probe::parse_file_list(R"({ + "result": [ + {"size": 5}, + {"path": ""}, + {"path": "kept.gcode"}, + "not-an-object" + ] + })"); + REQUIRE(files.size() == 1); + CHECK(files[0].path == "kept.gcode"); + CHECK(files[0].name == "kept.gcode"); + CHECK(files[0].size == 0); + CHECK(files[0].modified == 0); +} + +TEST_CASE("OrcaPrinterAgent::parse_thumbnail_path picks the largest width", "[OrcaPrinterAgent]") { + const std::string path = Probe::parse_thumbnail_path(R"({ + "result": [ + {"width": 32, "height": 32, "thumbnail_path": ".thumbs/foo.gcode-32x32.png"}, + {"width": 300, "height": 300, "thumbnail_path": ".thumbs/foo.gcode-300x300.png"}, + {"width": 100, "height": 100, "thumbnail_path": ".thumbs/foo.gcode-100x100.png"} + ] + })"); + CHECK(path == ".thumbs/foo.gcode-300x300.png"); +} + +TEST_CASE("OrcaPrinterAgent::parse_thumbnail_path accepts both key spellings", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_thumbnail_path(R"({"result": [{"width": 32, "relative_path": ".thumbs/old.png"}]})") == ".thumbs/old.png"); + CHECK(Probe::parse_thumbnail_path(R"({"result": [{"width": 32, "thumbnail_path": ".thumbs/new.png"}]})") == ".thumbs/new.png"); +} + +TEST_CASE("OrcaPrinterAgent::parse_thumbnail_path handles an empty result", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_thumbnail_path(R"({"result": []})").empty()); +} + +TEST_CASE("OrcaPrinterAgent::parse_thumbnail_path rejects malformed JSON", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_thumbnail_path("not json").empty()); + CHECK(Probe::parse_thumbnail_path(R"({"result": "nope"})").empty()); +} + +TEST_CASE("OrcaPrinterAgent::parse_thumbnail_path skips an entry without a path", "[OrcaPrinterAgent]") { + CHECK(Probe::parse_thumbnail_path(R"({"result": [{"width": 300, "height": 300}]})").empty()); + CHECK(Probe::parse_thumbnail_path(R"({"result": [{"width": 300, "thumbnail_path": 7}]})").empty()); +} + +TEST_CASE("OrcaPrinterAgent::encode_file_path preserves separators and encodes segments", "[OrcaPrinterAgent]") { + CHECK(Probe::encode_file_path("foo.gcode") == "foo.gcode"); // flat path + CHECK(Probe::encode_file_path("sub/foo.gcode") == "sub/foo.gcode"); // '/' kept as separator + CHECK(Probe::encode_file_path("a/b/c.gcode") == "a/b/c.gcode"); + CHECK(Probe::encode_file_path("sub dir/my file #1.gcode") == "sub%20dir/my%20file%20%231.gcode"); + CHECK(Probe::encode_file_path("design+part.gcode") == "design%2Bpart.gcode"); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_metadata parses the Moonraker fields", "[OrcaPrinterAgent]") { + using Catch::Matchers::WithinAbs; + const Slic3r::PrinterFileMetadata meta = Probe::parse_file_metadata(R"({ + "result": { + "filename": "sub/foo.gcode", + "size": 1234, + "modified": 1700000000.5, + "estimated_time": 3725, + "filament_total": 10500.5, + "filament_weight_total": 31.6, + "thumbnails": [] + } + })"); + CHECK(meta.estimated_time == 3725); + CHECK_THAT(meta.filament_total, WithinAbs(10500.5, 1e-9)); + CHECK_THAT(meta.filament_weight, WithinAbs(31.6, 1e-9)); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_metadata defaults missing fields to zero", "[OrcaPrinterAgent]") { + using Catch::Matchers::WithinAbs; + const Slic3r::PrinterFileMetadata meta = Probe::parse_file_metadata(R"({"result": {"filename": "foo.gcode"}})"); + CHECK(meta.estimated_time == 0); + CHECK_THAT(meta.filament_total, WithinAbs(0.0, 1e-12)); + CHECK_THAT(meta.filament_weight, WithinAbs(0.0, 1e-12)); +} + +TEST_CASE("OrcaPrinterAgent::parse_file_metadata yields zeros for a malformed reply", "[OrcaPrinterAgent]") { + using Catch::Matchers::WithinAbs; + const Slic3r::PrinterFileMetadata malformed = Probe::parse_file_metadata("not json"); + CHECK(malformed.estimated_time == 0); + CHECK_THAT(malformed.filament_total, WithinAbs(0.0, 1e-12)); + CHECK_THAT(malformed.filament_weight, WithinAbs(0.0, 1e-12)); + + const Slic3r::PrinterFileMetadata wrong_type = Probe::parse_file_metadata(R"({"result": "nope"})"); + CHECK(wrong_type.estimated_time == 0); + CHECK_THAT(wrong_type.filament_total, WithinAbs(0.0, 1e-12)); +} + +TEST_CASE("filament mapping is keyed by the ams_mapping2 array position", "[OrcaPrinterAgent]") { + const nlohmann::json mapping = Probe::build_filament_mapping( + R"([{"ams_id":1,"slot_id":5},{"ams_id":255,"slot_id":255},{"ams_id":255,"slot_id":0}])"); + REQUIRE(mapping.is_array()); + REQUIRE(mapping.size() == 2); + CHECK(mapping[0]["filament_index"] == 0); + CHECK(mapping[0]["ams_id"] == 1); + CHECK(mapping[0]["slot_id"] == 5); + // The unmatched middle entry is dropped; the third entry keeps index 2. + CHECK(mapping[1]["filament_index"] == 2); + CHECK(mapping[1]["ams_id"] == 255); + CHECK(mapping[1]["slot_id"] == 0); +} + +// Index-correlation merge gate (plan PR 3). `ams_mapping2` is built one entry +// per logical filament, so its array position is the identifier the generated +// G-code toolchange passes to the Klipper macro (`next_filament_id`). The +// serializer must key `filament_index` by that position and must never +// re-densify after dropping unused/sentinel entries, or a used filament would +// be aimed at the wrong lane. This test covers the plan's matrix: preset order +// differing from used order, a middle filament unused, and external slots. +TEST_CASE("filament mapping index correlates with the ams_mapping2 position", "[OrcaPrinterAgent]") { + // Positions 0..4. Used filaments are 0, 2 and 4; 1 and 3 are unused. + const nlohmann::json mapping = Probe::build_filament_mapping( + R"([{"ams_id":0,"slot_id":1},{"ams_id":255,"slot_id":255},{"ams_id":2,"slot_id":3},{"ams_id":255,"slot_id":255},{"ams_id":255,"slot_id":0}])"); + REQUIRE(mapping.size() == 3); + CHECK(mapping[0]["filament_index"] == 0); + CHECK(mapping[1]["filament_index"] == 2); + CHECK(mapping[2]["filament_index"] == 4); // external slot keeps its position + CHECK(mapping[2]["ams_id"] == 255); + CHECK(mapping[2]["slot_id"] == 0); + // No re-densification: a used filament after a dropped sentinel keeps its + // original logical index. + for (const auto& entry : mapping) + CHECK(entry.contains("filament_index")); +} + +TEST_CASE("filament mapping is omitted when nothing remains", "[OrcaPrinterAgent]") { + CHECK(Probe::build_filament_mapping("").empty()); + CHECK(Probe::build_filament_mapping(R"([{"ams_id":255,"slot_id":255}])").empty()); + CHECK(Probe::build_filament_mapping("not json").empty()); + CHECK(Probe::build_filament_mapping(R"({"ams_id":1,"slot_id":0})").empty()); // not an array +} + +// The GUI capability gate and the agent serializer must classify the same +// entries as engaged. External slots ({255,0}/{254,0}) are normalized as-is, so +// they engage; only the {255,255} unmatched sentinel is dropped. A mismatch lets +// an entry past the GUI and refused late with a generic publish error. +TEST_CASE("the GUI mapping gate engages exactly the entries the serializer sends", "[OrcaPrinterAgent]") { + using Slic3r::GUI::has_engaged_filament_mapping; + CHECK_FALSE(has_engaged_filament_mapping("")); + CHECK_FALSE(has_engaged_filament_mapping("[]")); + CHECK_FALSE(has_engaged_filament_mapping("not json")); + CHECK_FALSE(has_engaged_filament_mapping(R"([{"ams_id":255,"slot_id":255}])")); + CHECK(has_engaged_filament_mapping(R"([{"ams_id":255,"slot_id":0}])")); // external main + CHECK(has_engaged_filament_mapping(R"([{"ams_id":254,"slot_id":0}])")); // external deputy + CHECK(has_engaged_filament_mapping(R"([{"ams_id":0,"slot_id":0}])")); // box slot + CHECK(has_engaged_filament_mapping(R"([{"ams_id":255,"slot_id":255},{"ams_id":1,"slot_id":2}])")); + + for (const char* s : {"", "[]", "not json", R"([{"ams_id":255,"slot_id":255}])", + R"([{"ams_id":255,"slot_id":0}])", R"([{"ams_id":254,"slot_id":0}])", + R"([{"ams_id":0,"slot_id":0}])", + R"([{"ams_id":255,"slot_id":255},{"ams_id":1,"slot_id":2}])"}) { + CHECK(has_engaged_filament_mapping(s) == !Probe::build_filament_mapping(s).empty()); + } +} + +// The used-unmapped refusal reads m_ams_mapping_result: an entry with no target carries +// empty ams_id/slot_id, while an external-spool assignment (ams_id 255/254) is a real +// target. A wholly unmapped print reports no target and falls to the existing send flow. +TEST_CASE("used-filament targets split mapped from unmapped", "[OrcaPrinterAgent]") { + using Slic3r::GUI::has_any_mapped_target; + using Slic3r::GUI::has_used_filament_without_target; + + Slic3r::FilamentInfo box; box.ams_id = "0"; box.slot_id = "1"; // box slot + Slic3r::FilamentInfo external; external.ams_id = "255"; external.slot_id = "0"; // external spool + Slic3r::FilamentInfo unmapped; // no target + + CHECK_FALSE(has_used_filament_without_target({box, external})); + CHECK(has_used_filament_without_target({box, unmapped})); + CHECK(has_used_filament_without_target({external, unmapped})); + CHECK(has_used_filament_without_target({unmapped})); // wholly unmapped: all-invalid flow, not this refusal + CHECK(has_any_mapped_target({box, unmapped})); + CHECK(has_any_mapped_target({external, unmapped})); + CHECK_FALSE(has_any_mapped_target({unmapped})); +} + +// A device with no AMS units has one source, the external spool. OrcaSlicer's +// auto-mapping force-selects it for every filament; that is not a lane choice, so it +// must not gate the print or reach print.gcode_file. +TEST_CASE("a no-AMS device drops the forced external-spool selection", "[OrcaPrinterAgent]") { + using Slic3r::GUI::drop_forced_external_selection; + using Slic3r::GUI::has_engaged_filament_mapping; + + std::string external_only = R"([{"ams_id":255,"slot_id":0}])"; + drop_forced_external_selection(/*device_has_ams=*/false, external_only); + CHECK(external_only.empty()); + CHECK_FALSE(has_engaged_filament_mapping(external_only)); + CHECK(Probe::build_filament_mapping(external_only).empty()); + + std::string box_mapping = R"([{"ams_id":0,"slot_id":2}])"; + drop_forced_external_selection(/*device_has_ams=*/true, box_mapping); + CHECK(box_mapping == R"([{"ams_id":0,"slot_id":2}])"); + CHECK(has_engaged_filament_mapping(box_mapping)); +} + +// An empty mapping must leave the gcode_file payload byte-identical to today: +// exactly command, sequence_id and param, with no filament_mapping key. +TEST_CASE("gcode_file payload omits filament_mapping when the map is empty", "[OrcaPrinterAgent]") { + const nlohmann::json empty = Probe::build_gcode_file_payload("7", "job.gcode", nlohmann::json::array()); + REQUIRE(empty.contains("print")); + CHECK(empty["print"].size() == 3); + CHECK(empty["print"]["command"] == "gcode_file"); + CHECK(empty["print"]["sequence_id"] == "7"); + CHECK(empty["print"]["param"] == "job.gcode"); + CHECK_FALSE(empty["print"].contains("filament_mapping")); + + const nlohmann::json mapping = Probe::build_filament_mapping(R"([{"ams_id":1,"slot_id":0},{"ams_id":255,"slot_id":255}])"); + const nlohmann::json with = Probe::build_gcode_file_payload("8", "job.gcode", mapping); + REQUIRE(with["print"].contains("filament_mapping")); + REQUIRE(with["print"]["filament_mapping"].size() == 1); + CHECK(with["print"]["filament_mapping"][0]["filament_index"] == 0); +} + +// The defensive gate: a mapped print is refused before anything is published when the +// connector never advertised filament_mapping. The GUI send gates make this visible first; +// this covers callers that bypass them (calibration, plugin). A sentinel-only mapping does +// not engage the gate and falls through to the normal publish path. +TEST_CASE("an engaged mapping is refused when the connector never advertised filament_mapping", "[OrcaPrinterAgent]") { + OrcaPrinterAgent agent("/tmp"); + Slic3r::PrintParams params; + params.dev_id = "dev-no-mapping-cap"; + params.dst_file = "/tmp/job.gcode"; + params.ams_mapping2 = R"([{"ams_id":0,"slot_id":2}])"; + + CHECK(agent.start_sdcard_print(params, {}, {}) == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED); + + params.ams_mapping2 = R"([{"ams_id":255,"slot_id":255}])"; + CHECK(agent.start_sdcard_print(params, {}, {}) == BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED); +} + +// The FTP "send with record" transport does not exist on OrcaSonar. It must +// report a non-success result so PrintJob falls back to start_print() rather +// than treating a print that was never sent as successful. +TEST_CASE("start_local_print_with_record never reports silent success", "[OrcaPrinterAgent]") { + Probe agent("/tmp"); + Slic3r::PrintParams params; + const int rc = agent.start_local_print_with_record(params, {}, {}, {}); + CHECK(rc < 0); +} + TEST_CASE("connect_printer wires up a LAN Config", "[OrcaPrinterAgent][.integration]") { Probe agent("/tmp"); Slic3r::PrinterConnectionParams params{