diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 60f973f7f..83b625e74 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -48,7 +48,6 @@ api = Blueprint("api", __name__) from . import access as api_access # noqa: F401,E402 from . import connection as api_connection # noqa: F401,E402 -from . import connection_profiles as api_connection_profiles # noqa: F401,E402 from . import files as api_files # noqa: F401,E402 from . import job as api_job # noqa: F401,E402 from . import languages as api_languages # noqa: F401,E402 diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index b80c8a27f..90537169b 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -2,9 +2,13 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -from flask import abort, jsonify, request +import logging + +from flask import abort, jsonify, make_response, request +from werkzeug.exceptions import BadRequest from octoprint.access.permissions import Permissions +from octoprint.comm.connectionprofile import InvalidProfileError, SaveError from octoprint.comm.protocol import all_protocols from octoprint.comm.transport import all_transports from octoprint.server import ( @@ -13,17 +17,16 @@ from octoprint.server import ( printer, printerProfileManager, ) -from octoprint.server.api import api -from octoprint.server.util.flask import get_json_command_from_request, no_firstrun_access +from octoprint.server.api import api, valid_boolean_trues +from octoprint.server.util.flask import ( + get_json_command_from_request, + no_firstrun_access, + with_revalidation_checking, +) from octoprint.settings import settings +from octoprint.util import dict_merge - -def _convert_transport_options(options): - return [option.as_dict() for option in options] - - -def _convert_protocol_options(options): - return [option.as_dict() for option in options] +##~~ Connection state & commands @api.route("/connection", methods=["GET"]) @@ -39,8 +42,7 @@ def connectionState(): "transport": params["transport"], "transportOptions": params["transport_args"], } - - return jsonify({"current": current, "options": _get_options()}) + return jsonify(current=current) @api.route("/connection", methods=["POST"]) @@ -104,29 +106,15 @@ def connectionCommand(): return NO_CONTENT -def _get_options(): - transports = [] - for transport in all_transports(): - transports.append( - { - "name": transport.name, - "key": transport.key, - "options": _convert_transport_options(transport.get_connection_options()), - } - ) +##~~ Connection options (profiles, protocols, transports) - protocols = [] - for protocol in all_protocols(): - protocols.append( - { - "name": protocol.name, - "key": protocol.key, - "options": _convert_protocol_options(protocol.get_connection_options()), - } - ) - profile_options = printerProfileManager.get_all() - default_profile = printerProfileManager.get_default() +@api.route("/connection/options", methods=["GET"]) +@Permissions.STATUS.require(403) +def connectionOptions(): + + printer_profiles = printerProfileManager.get_all() + default_printer = printerProfileManager.get_default() connection_profiles = connectionProfileManager.get_all() default_connection = connectionProfileManager.get_default() @@ -139,21 +127,250 @@ def _get_options(): if "name" in printer_profile else printer_profile["id"], } - for printer_profile in profile_options.values() + for printer_profile in printer_profiles.values() if "id" in printer_profile ], "connectionProfiles": [ connection_profile.as_dict() for connection_profile in connection_profiles.values() ], - "printerProfilePreference": default_profile["id"] - if "id" in default_profile + "printerProfilePreference": default_printer["id"] + if "id" in default_printer else None, "connectionProfilePreference": default_connection.id if default_connection else None, - "protocols": protocols, - "transports": transports, + "protocols": _get_protocols(), + "transports": _get_transports(), } - return options + return jsonify(options=options) + + +##~~ Connection profiles + + +def _connection_profiles_lastmodified(): + return connectionProfileManager.last_modified + + +def _connection_profiles_etag(lm=None): + if lm is None: + lm = _connection_profiles_lastmodified() + + import hashlib + + hash = hashlib.sha1() + + def hash_update(value): + value = value.encode("utf-8") + hash.update(value) + + hash_update(str(lm)) + hash_update(repr(connectionProfileManager.get_default())) + hash_update(repr(connectionProfileManager.get_current())) + return hash.hexdigest() + + +@api.route("/connection/profiles", methods=["GET"]) +@with_revalidation_checking( + etag_factory=_connection_profiles_etag, + lastmodified_factory=_connection_profiles_lastmodified, + unless=lambda: request.values.get("force", "false") in valid_boolean_trues, +) +@no_firstrun_access +@Permissions.CONNECTION.require(403) +def connectionProfilesList(): + all_profiles = connectionProfileManager.get_all() + return jsonify({"profiles": _convert_connection_profiles(all_profiles)}) + + +@api.route("/connection/profiles/", methods=["GET"]) +@no_firstrun_access +@Permissions.CONNECTION.require(403) +def connectionProfilesGet(identifier): + profile = connectionProfileManager.get(identifier) + if profile is None: + return make_response(f"Unknown profile: {identifier}", 404) + else: + return jsonify({"profile": _convert_connection_profile(profile)}) + + +@api.route("/connection/profiles/", methods=["PUT"]) +@no_firstrun_access +@Permissions.CONNECTION.require(403) +def connectionProfileSet(identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) + + if json_data is None: + return make_response("Malformed JSON body in request", 400) + + if "profile" not in json_data: + return make_response("No profile included in request", 400) + + allow_overwrite = json_data.get("overwrite", False) + make_default = json_data.get("default", False) + + new_profile = json_data["profile"] + if "name" not in new_profile: + return make_response("Profile does not contain mandatory 'name' field", 400) + + if "id" not in new_profile: + new_profile["id"] = identifier + + profile = connectionProfileManager.to_profile(new_profile) + + try: + connectionProfileManager.save( + profile, allow_overwrite=allow_overwrite, make_default=make_default + ) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except SaveError: + return make_response(f"Profile {profile.id} could not be saved", 400) + except Exception as e: + logging.getLogger(__name__).exception(e) + return make_response( + f"Could not save profile due to an unexpected error: {e}", 500 + ) + else: + return jsonify({"profile": _convert_connection_profile(profile)}) + + +@api.route("/connection/profiles/", methods=["DELETE"]) +@no_firstrun_access +@Permissions.SETTINGS.require(403) +def connectionProfilesDelete(identifier): + current_profile = connectionProfileManager.get_current() + if current_profile and current_profile.id == identifier: + return make_response( + f"Cannot delete currently selected profile: {identifier}", 409 + ) + + default_profile = connectionProfileManager.get_default() + if default_profile and default_profile.id == identifier: + return make_response(f"Cannot delete default profile: {identifier}", 409) + + connectionProfileManager.remove(identifier) + return NO_CONTENT + + +@api.route("/connection/profiles/", methods=["PATCH"]) +@no_firstrun_access +@Permissions.SETTINGS.require(403) +def connectionProfilesUpdate(identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.get_json() + except BadRequest: + return make_response("Malformed JSON body in request", 400) + + if json_data is None: + return make_response("Malformed JSON body in request", 400) + + if "profile" not in json_data: + return make_response("No profile included in request", 400) + + profile = connectionProfileManager.get(identifier) + if profile is None: + return make_response("Profile {} doesn't exist", 404) + + profile_data = json_data["profile"] + make_default = profile_data.pop("default", False) + profile_data.pop("id", None) + + merged_profile_data = dict_merge(profile.as_dict(), profile_data) + new_profile = connectionProfileManager.to_profile(merged_profile_data) + + try: + saved_profile = connectionProfileManager.save( + new_profile, allow_overwrite=True, make_default=make_default + ) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except SaveError: + return make_response(f"Profile {profile.id} could not be saved", 400) + except Exception as e: + return make_response( + f"Could not save profile due to an unexpected error: {e}", 500 + ) + else: + return jsonify({"profile": _convert_connection_profile(saved_profile)}) + + +def _convert_connection_profiles(profiles): + result = {} + for identifier, profile in profiles.items(): + result[identifier] = _convert_connection_profile(profile) + return result + + +def _convert_connection_profile(profile): + current = connectionProfileManager.get_current() + default = connectionProfileManager.get_default() + + result = profile.as_dict() + result["current"] = profile.id == current.id if current is not None else False + result["default"] = profile.id == default.id if default is not None else False + return result + + +##~~ Protocols + + +@api.route("/connection/protocols", methods=["GET"]) +@no_firstrun_access +@Permissions.CONNECTION.require(403) +def getProtocols(): + return jsonify({"protocols": _get_protocols()}) + + +##~~ Transports + + +@api.route("/connection/transports", methods=["GET"]) +@no_firstrun_access +@Permissions.CONNECTION.require(403) +def getTransports(): + return jsonify({"transports": _get_transports()}) + + +##~~ Helpers + + +def _get_protocols(): + protocols = [] + for protocol in all_protocols(): + protocols.append( + { + "name": protocol.name, + "key": protocol.key, + "options": _convert_options(protocol.get_connection_options()), + } + ) + return protocols + + +def _get_transports(): + transports = [] + for transport in all_transports(): + transports.append( + { + "name": transport.name, + "key": transport.key, + "options": _convert_options(transport.get_connection_options()), + } + ) + return transports + + +def _convert_options(options): + return [option.as_dict() for option in options] diff --git a/src/octoprint/server/api/connection_profiles.py b/src/octoprint/server/api/connection_profiles.py deleted file mode 100644 index 77669c29a..000000000 --- a/src/octoprint/server/api/connection_profiles.py +++ /dev/null @@ -1,188 +0,0 @@ -__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" -__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" - - -import logging - -from flask import jsonify, make_response, request -from werkzeug.exceptions import BadRequest - -from octoprint.access.permissions import Permissions -from octoprint.comm.connectionprofile import InvalidProfileError, SaveError -from octoprint.server import connectionProfileManager -from octoprint.server.api import NO_CONTENT, api, valid_boolean_trues -from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking -from octoprint.util import dict_merge - - -def _lastmodified(): - return connectionProfileManager.last_modified - - -def _etag(lm=None): - if lm is None: - lm = _lastmodified() - - import hashlib - - hash = hashlib.sha1() - - def hash_update(value): - value = value.encode("utf-8") - hash.update(value) - - hash_update(str(lm)) - hash_update(repr(connectionProfileManager.get_default())) - hash_update(repr(connectionProfileManager.get_current())) - return hash.hexdigest() - - -@api.route("/connectionprofiles", methods=["GET"]) -@with_revalidation_checking( - etag_factory=_etag, - lastmodified_factory=_lastmodified, - unless=lambda: request.values.get("force", "false") in valid_boolean_trues, -) -@no_firstrun_access -@Permissions.CONNECTION.require(403) -def connectionProfilesList(): - all_profiles = connectionProfileManager.get_all() - return jsonify({"profiles": _convert_profiles(all_profiles)}) - - -@api.route("/connectionprofiles/", methods=["GET"]) -@no_firstrun_access -@Permissions.CONNECTION.require(403) -def connectionProfilesGet(identifier): - profile = connectionProfileManager.get(identifier) - if profile is None: - return make_response(f"Unknown profile: {identifier}", 404) - else: - return jsonify({"profile": _convert_profile(profile)}) - - -@api.route("/connectionprofiles/", methods=["PUT"]) -@no_firstrun_access -@Permissions.CONNECTION.require(403) -def connectionProfileSet(identifier): - if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) - - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) - - if json_data is None: - return make_response("Malformed JSON body in request", 400) - - if "profile" not in json_data: - return make_response("No profile included in request", 400) - - allow_overwrite = json_data.get("overwrite", False) - make_default = json_data.get("default", False) - - new_profile = json_data["profile"] - if "name" not in new_profile: - return make_response("Profile does not contain mandatory 'name' field", 400) - - if "id" not in new_profile: - new_profile["id"] = identifier - - profile = connectionProfileManager.to_profile(new_profile) - - try: - connectionProfileManager.save( - profile, allow_overwrite=allow_overwrite, make_default=make_default - ) - except InvalidProfileError: - return make_response("Profile is invalid", 400) - except SaveError: - return make_response(f"Profile {profile.id} could not be saved", 400) - except Exception as e: - logging.getLogger(__name__).exception(e) - return make_response( - f"Could not save profile due to an unexpected error: {e}", 500 - ) - else: - return jsonify({"profile": _convert_profile(profile)}) - - -@api.route("/connectionprofiles/", methods=["DELETE"]) -@no_firstrun_access -@Permissions.SETTINGS.require(403) -def connectionProfilesDelete(identifier): - current_profile = connectionProfileManager.get_current() - if current_profile and current_profile.id == identifier: - return make_response( - f"Cannot delete currently selected profile: {identifier}", 409 - ) - - default_profile = connectionProfileManager.get_default() - if default_profile and default_profile.id == identifier: - return make_response(f"Cannot delete default profile: {identifier}", 409) - - connectionProfileManager.remove(identifier) - return NO_CONTENT - - -@api.route("/connectionprofiles/", methods=["PATCH"]) -@no_firstrun_access -@Permissions.SETTINGS.require(403) -def connectionProfilesUpdate(identifier): - if "application/json" not in request.headers["Content-Type"]: - return make_response("Expected content-type JSON", 400) - - try: - json_data = request.get_json() - except BadRequest: - return make_response("Malformed JSON body in request", 400) - - if json_data is None: - return make_response("Malformed JSON body in request", 400) - - if "profile" not in json_data: - return make_response("No profile included in request", 400) - - profile = connectionProfileManager.get(identifier) - if profile is None: - return make_response("Profile {} doesn't exist", 404) - - profile_data = json_data["profile"] - make_default = profile_data.pop("default", False) - profile_data.pop("id", None) - - merged_profile_data = dict_merge(profile.as_dict(), profile_data) - new_profile = connectionProfileManager.to_profile(merged_profile_data) - - try: - saved_profile = connectionProfileManager.save( - new_profile, allow_overwrite=True, make_default=make_default - ) - except InvalidProfileError: - return make_response("Profile is invalid", 400) - except SaveError: - return make_response(f"Profile {profile.id} could not be saved", 400) - except Exception as e: - return make_response( - f"Could not save profile due to an unexpected error: {e}", 500 - ) - else: - return jsonify({"profile": _convert_profile(saved_profile)}) - - -def _convert_profiles(profiles): - result = {} - for identifier, profile in profiles.items(): - result[identifier] = _convert_profile(profile) - return result - - -def _convert_profile(profile): - current = connectionProfileManager.get_current() - default = connectionProfileManager.get_default() - - result = profile.as_dict() - result["current"] = profile.id == current.id if current is not None else False - result["default"] = profile.id == default.id if default is not None else False - return result diff --git a/src/octoprint/static/js/app/client/connection.js b/src/octoprint/static/js/app/client/connection.js index 9763d1584..1924e484a 100644 --- a/src/octoprint/static/js/app/client/connection.js +++ b/src/octoprint/static/js/app/client/connection.js @@ -6,6 +6,9 @@ } })(this, function (OctoPrintClient) { var url = "api/connection"; + var optionsUrl = url + "/options"; + var protocolsUrl = url + "/protocols"; + var transportsUrl = url + "/transports"; var OctoPrintConnectionClient = function (base) { this.base = base; @@ -27,6 +30,18 @@ return this.base.issueCommand(url, "fake_ack", {}, opts); }; + OctoPrintConnectionClient.prototype.getOptions = function (opts) { + return this.base.get(optionsUrl, opts); + }; + + OctoPrintConnectionClient.prototype.getProtocols = function (opts) { + return this.base.get(protocolsUrl, opts); + }; + + OctoPrintConnectionClient.prototype.getTransports = function (opts) { + return this.base.get(transportsUrl, opts); + }; + OctoPrintClient.registerComponent("connection", OctoPrintConnectionClient); return OctoPrintConnectionClient; }); diff --git a/src/octoprint/static/js/app/client/connectionprofiles.js b/src/octoprint/static/js/app/client/connectionprofiles.js index 2e7a31e9b..da8bbe574 100644 --- a/src/octoprint/static/js/app/client/connectionprofiles.js +++ b/src/octoprint/static/js/app/client/connectionprofiles.js @@ -5,7 +5,7 @@ factory(global.OctoPrintClient, global.$); } })(this, function (OctoPrintClient, $) { - var url = "api/connectionprofiles"; + var url = "api/connection/profiles"; var profileUrl = function (profile) { return url + "/" + profile; diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 7ee6483c4..0531d3e9d 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -15,6 +15,13 @@ $(function () { var convertValue = function (value, option, override) { /** + * Picks the right value to apply based on value, defaults and overrides. + * + * override > value > override + * + * In case of list or smalllist, the value will also be converted from a + * list to a comma separated string. + * * @param value the value to apply * @param option the option object, to lookup a default if needed * @param override the current override value, or undefined @@ -34,44 +41,34 @@ $(function () { return value; }; - var extendOption = function (option, value, data) { + var setOptionValue = function (option, value, data) { /** + * Sets the given value on the given option. + * + * In case of a group option, the value will be considered a dictionary of values + * to apply to the children of the group. + * * @param option the option to extend * @param value the value to apply to the option, or undefined * @param data the currently active data object, or undefined */ + if (option.type === "group") { if (value === undefined) { value = {}; } _.each(option.params, function (option) { - extendOption( + setOptionValue( option, value[option.name], data ? data[option.name] : undefined ); }); - option.modified = ko.pureComputed(function () { - return _.any(option.params, function (p) { - return p.modified(); - }); - }); - - option.advancedParameters = - option.advanced || - _.any(option.params, function (p) { - return p.advanced; - }); - option.expertParameters = - option.expert || - _.any(option.params, function (p) { - return p.expert; - }); } else { if (option.type === "presetchoice") { value = convertValue(value, option, data ? data[option.name] : undefined); _.each(option.group.params, function (p) { - extendOption( + setOptionValue( p, option.defaults[value] ? option.defaults[value][p.name] @@ -84,7 +81,7 @@ $(function () { option.expertParameters = {}; _.each(option.groups, function (group, key) { _.each(group, function (p) { - extendOption(p, undefined, data); + setOptionValue(p, undefined, data); }); option.expertParameters[key] = _.any(group, function (p) { return p.expert; @@ -94,64 +91,7 @@ $(function () { value = convertValue(value, option, data ? data[option.name] : undefined); } - if (option.value) { - option.value(value); - } else { - option.value = ko.observable(value); - option.defaultValue = ko.observable(option.default); - option.reset = function () { - option.value(option.defaultValue()); - }; - - option.modified = ko.pureComputed(function () { - // noinspection EqualityComparisonWithCoercionJS - return option.value() != option.defaultValue(); - }); - - if (option.type === "presetchoice" && option.defaults) { - option.group.advancedParameters = - option.group.advanced || - _.any(option.group.params, function (p) { - return p.advanced; - }); - option.group.expertParameters = - option.group.expert || - _.any(option.group.params, function (p) { - return p.expert; - }); - - var updateDefaults = function (keepValue) { - keepValue = !!keepValue; - - var choice = _.find(option.choices, function (c) { - return c.value === option.value(); - }); - if (choice) { - _.each(option.group.params, function (p) { - if (option.defaults[choice.value]) { - var d = option.defaults[choice.value][p.name]; - if (d !== undefined) { - p.defaultValue( - convertValue( - d, - p, - data ? data[p.name] : undefined - ) - ); - if (!keepValue) { - p.value(p.defaultValue()); - } - } - } - }); - } - }; - option.value.subscribe(function () { - updateDefaults(); - }); - updateDefaults(true); - } - } + option.value(value); } }; @@ -413,14 +353,24 @@ $(function () { self.printerProfiles = parameters[2]; self.access = parameters[3]; + self.sychronizeSettings = function (observable, settings) { + var parameters = observable(); + _.each(parameters, function (option) { + setOptionValue( + option, + settings ? settings[option.name] : undefined, + settings + ); + }); + observable(parameters); + }; + // Connection profiles self.availableConnectionProfiles = ko.observableArray(); self.preferredConnectionProfile = ko.observable(); self.selectedConnectionProfile = ko.observable(undefined); self.selectedConnectionProfile.subscribe(function () { - var protocolParameters, transportParameters; - var profile = self.selectedConnectionProfile(); if (profile) { @@ -439,40 +389,10 @@ $(function () { return t.key === profile.transport; }) ); - - var processParameters = function (parameters, profile_parameters) { - _.each(parameters, function (option) { - extendOption( - option, - profile_parameters[option.name], - profile_parameters - ); - }); - }; - - protocolParameters = self.protocolParameters(); - processParameters(protocolParameters, profile.protocol_parameters); - self.protocolParameters(protocolParameters); - - transportParameters = self.transportParameters(); - processParameters(transportParameters, profile.transport_parameters); - self.transportParameters(transportParameters); } else { self.selectedPrinter(undefined); self.selectedProtocol(undefined); self.selectedTransport(undefined); - - protocolParameters = self.protocolParameters(); - _.each(protocolParameters, function (option) { - extendOption(option); - }); - self.protocolParameters(protocolParameters); - - transportParameters = self.transportParameters(); - _.each(transportParameters, function (option) { - extendOption(option); - }); - self.transportParameters(transportParameters); } }); @@ -517,22 +437,27 @@ $(function () { self.selectedProtocol.subscribe(function () { var protocol = self.selectedProtocol(); + var protocolOptions = []; if (protocol) { - self.protocolParameters(protocol.options); - } else { - self.protocolParameters([]); + protocolOptions = protocol.options; } self.advancedProtocolParameters( - _.any(self.protocolParameters(), function (p) { + _.any(protocolOptions, function (p) { return p.advanced; }) ); self.expertProtocolParameters( - _.any(self.protocolParameters(), function (p) { + _.any(protocolOptions, function (p) { return p.expert; }) ); + + var connectionProfile = self.selectedConnectionProfile(); + self.sychronizeSettings( + self.protocolParameters, + connectionProfile ? connectionProfile.protocol_parameters : undefined + ); }); self.lookupProtocolName = function (key) { @@ -578,6 +503,12 @@ $(function () { return p.expert; }) ); + + var connectionProfile = self.selectedConnectionProfile(); + self.sychronizeSettings( + self.transportParameters, + connectionProfile ? connectionProfile.transport_parameters : undefined + ); }); self.lookupTransportName = function (key) { @@ -632,22 +563,154 @@ $(function () { return; } - return OctoPrint.connection.getSettings().done(self.fromResponse); + var deferred = $.Deferred(); + + var options = OctoPrint.connection.getOptions(); + var current = OctoPrint.connection.getSettings(); + + $.when(options, current).done(function (options, current) { + var data = { + options: options[0].options, + current: current[0].current + }; + + self.fromResponse(data); + + deferred.resolve(data); + }); + + return deferred.promise(); }; - self.fromResponse = function (response) { - //~~ Preferences... + self.requestOptionsData = function () { + if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) { + return; + } + return OctoPrint.connection.getOptions().done(self.fromOptionsRespons); + }; - self.preferredConnectionProfile(response.options.connectionProfilePreference); - self.preferredPrinter(response.options.printerProfilePreference); + self.requestCurrentData = function () { + if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) { + return; + } + return OctoPrint.connection.getSettings().done(self.fromCurrentResponse); + }; - //~~ Available options... + self.fromResponse = function (data) { + // first the options... + self.fromOptionsResponse(data.options); + + // ...then the current config + self.fromCurrentResponse(data.current); + }; + + self.fromOptionsResponse = function (options) { + var extendOption = function (option) { + if (option.type === "group") { + _.each(option.params, function (param) { + extendOption(param); + }); + + option.modified = ko.pureComputed(function () { + return _.any(option.params, function (p) { + return p.modified(); + }); + }); + + option.advancedParameters = + option.advanced || + _.any(option.params, function (p) { + return p.advanced; + }); + option.expertParameters = + option.expert || + _.any(option.params, function (p) { + return p.expert; + }); + } else { + if (option.type === "presetchoice") { + _.each(option.group.params, function (option) { + extendOption(option); + }); + } + + if (option.type === "conditionalgroup") { + option.expertParameters = {}; + _.each(option.groups, function (group, key) { + _.each(group, function (option) { + extendOption(option); + }); + option.expertParameters[key] = _.any(group, function (p) { + return p.expert; + }); + }); + } + + option.value = ko.observable(option.default); + option.defaultValue = ko.observable(option.default); + option.reset = function () { + option.value(option.defaultValue()); + }; + + option.modified = ko.pureComputed(function () { + // noinspection EqualityComparisonWithCoercionJS + return option.value() != option.defaultValue(); + }); + + if (option.type === "presetchoice" && option.defaults) { + option.group.advancedParameters = + option.group.advanced || + _.any(option.group.params, function (p) { + return p.advanced; + }); + option.group.expertParameters = + option.group.expert || + _.any(option.group.params, function (p) { + return p.expert; + }); + + var updateDefaults = function (keepValue) { + keepValue = !!keepValue; + + var choice = _.find(option.choices, function (c) { + return c.value === option.value(); + }); + if (choice) { + _.each(option.group.params, function (p) { + if (option.defaults[choice.value]) { + var d = option.defaults[choice.value][p.name]; + if (d !== undefined) { + p.defaultValue(convertValue(d, p)); + if (!keepValue) { + p.value(p.defaultValue()); + } + } + } + }); + } + }; + option.value.subscribe(function () { + updateDefaults(); + }); + updateDefaults(true); + } + } + }; + + var extendOptions = function (input) { + _.each(input, function (i) { + _.each(i.options, function (option) { + extendOption(option); + }); + }); + }; // printer profiles - var printers = response.options.printerProfiles; + self.preferredPrinter(options.printerProfilePreference); + var printers = options.printerProfiles; _.each(printers, function (p) { p.isDefault = ko.pureComputed(function () { - return p.id === preferredPrinter(); + return p.id === self.preferredPrinter(); }); p.isCurrent = ko.pureComputed(function () { return p.id === self.selectedPrinter(); @@ -656,37 +719,22 @@ $(function () { self.availablePrinterProfiles(printers); // protocols - var protocols = response.options.protocols; - var protocolOptions = response.current.protocolOptions; - if (!protocolOptions) { - protocolOptions = {}; - } - - _.each(protocols, function (protocol) { - _.each(protocol.options, function (option) { - extendOption(option, protocolOptions[option.name], protocolOptions); - }); - }); - + var protocols = options.protocols; + extendOptions(protocols); self.availableProtocols(protocols); // transports - var transports = response.options.transports; - var transportOptions = response.current.transportOptions; - if (!transportOptions) { - transportOptions = {}; - } - - _.each(transports, function (transport) { - _.each(transport.options, function (option) { - extendOption(option, transportOptions[option.name], transportOptions); - }); - }); - + var transports = options.transports; + extendOptions(transports); self.availableTransports(transports); // connection profiles - var connections = response.options.connectionProfiles; + // + // this has to be processed after the rest for the + // subscriptions to fire off in the right order + + self.preferredConnectionProfile(options.connectionProfilePreference); + var connections = options.connectionProfiles; _.each(connections, function (c) { c.isDefault = ko.pureComputed(function () { return c.id === self.preferredConnectionProfile(); @@ -696,17 +744,17 @@ $(function () { }); }); self.availableConnectionProfiles(connections); + }; - //~~ Currently active config - - var connectionKey = response.current.connection; + self.fromCurrentResponse = function (current) { + var connectionKey = current.connection; if (!connectionKey) { - connectionKey = response.options.connectionProfilePreference; + connectionKey = self.preferredConnectionProfile(); } if (connectionKey) { // there's currently a connection profile selected on the server - var connection = _.find(connections, function (c) { + var connection = _.find(self.availableConnectionProfiles(), function (c) { return c.id === connectionKey; }); self.selectedConnectionProfile(connection); @@ -715,21 +763,21 @@ $(function () { self.saveSettings(false); } - var printerKey = response.current.profile; + var printerKey = current.profile; if (!connectionKey && !printerKey) { - printerKey = response.options.printerProfilePreference; + printerKey = self.preferredPrinter(); } if (printerKey) { - var printer = _.find(printers, function (p) { + var printer = _.find(self.availablePrinterProfiles(), function (p) { return p.id === printerKey; }); self.selectedPrinter(printer); } - var protocolKey = response.current.protocol; + var protocolKey = current.protocol; if (protocolKey) { - var protocol = _.find(protocols, function (p) { + var protocol = _.find(self.availableProtocols(), function (p) { return p.key === protocolKey; }); self.selectedProtocol(protocol); @@ -737,16 +785,16 @@ $(function () { _.each(protocolParameters, function (option) { extendOption( option, - response.current.protocolOptions[option.name], - response.current.protocolOptions + current.protocolOptions[option.name], + current.protocolOptions ); }); self.protocolParameters(protocolParameters); } - var transportKey = response.current.transport; + var transportKey = current.transport; if (transportKey) { - var transport = _.find(transports, function (t) { + var transport = _.find(self.availableTransports(), function (t) { return t.key === transportKey; }); self.selectedTransport(transport); @@ -754,8 +802,8 @@ $(function () { _.each(transportParameters, function (option) { extendOption( option, - response.current.transportOptions[option.name], - response.current.transportOptions + current.transportOptions[option.name], + current.transportOptions ); }); self.transportParameters(transportParameters); @@ -879,11 +927,11 @@ $(function () { }; self.onEventConnected = function () { - self.requestData(); + self.requestCurrentData(); }; self.onEventDisconnected = function () { - self.requestData(); + self.requestCurrentData(); }; self.onStartup = function () { diff --git a/src/octoprint/templates/sidebar/connection_header.jinja2 b/src/octoprint/templates/sidebar/connection_header.jinja2 index 1f115868a..1306fddfc 100644 --- a/src/octoprint/templates/sidebar/connection_header.jinja2 +++ b/src/octoprint/templates/sidebar/connection_header.jinja2 @@ -1,5 +1,5 @@