// source: js/app/bindings/allowbindings.js
ko.bindingHandlers.allowBindings={init:function(elem,valueAccessor){return{controlsDescendantBindings:!valueAccessor()};}};ko.virtualElements.allowedBindings.allowBindings=true;
;

// source: js/app/bindings/contextmenu.js
ko.bindingHandlers.contextMenu={init:function(element,valueAccessor,allBindingsAccessor,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());$(element).contextMenu(val);},update:function(element,valueAccessor,allBindingsAccessor,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());$(element).contextMenu(val);}};
;

// source: js/app/bindings/gettext.js
ko.bindingHandlers.gettext={init:function(){return{controlsDescendantBindings:true};},update:function(element,valueAccessor){var gt=gettext||function(text){return text;};ko.utils.setTextContent(element,gt(valueAccessor()));}};ko.virtualElements.allowedBindings["gettext"]=true;
;

// source: js/app/bindings/invisible.js
ko.bindingHandlers.invisible={init:function(element,valueAccessor,allBindings,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());ko.bindingHandlers.style.update(element,function(){return{visibility:val?"hidden":"visible"};});},update:function(element,valueAccessor,allBindings,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());ko.bindingHandlers.style.update(element,function(){return{visibility:val?"hidden":"visible"};});}};
;

// source: js/app/bindings/popover.js
ko.bindingHandlers.popover={keys:["title","animation","placement","trigger","delay","content","html"],init:function(element,valueAccessor,allBindingsAccessor,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());var keys=ko.bindingHandlers.popover.keys;var options={};_.each(keys,function(key){options[key]=ko.utils.unwrapObservable(val[key]);});$(element).popover(options);},update:function(element,valueAccessor,allBindingsAccessor,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());var keys=ko.bindingHandlers.popover.keys;var value;_.each(keys,function(key){value=ko.utils.unwrapObservable(val[key]);$(element).data("popover").options[key]=value;});}};
;

// source: js/app/bindings/qrcode.js
ko.bindingHandlers.qrcode={update:function(element,valueAccessor,allBindings,viewModel,bindingContext){var val=ko.utils.unwrapObservable(valueAccessor());var defaultOptions={text:"",size:200,fill:"#000",background:null,label:"",fontname:"sans",fontcolor:"#000",radius:0,ecLevel:"L"};var options={};_.each(defaultOptions,function(value,key){options[key]=ko.utils.unwrapObservable(val[key])||value;});$(element).empty().qrcode(options);}};
;

// source: js/app/bindings/slimscrolledforeach.js
ko.bindingHandlers.slimScrolledForeach={makeTemplateValueAccessor:function(valueAccessor){var modelValue=valueAccessor(),unwrappedValue=ko.utils.peekObservable(modelValue),result,slimscroll;if(!unwrappedValue||typeof unwrappedValue.length==="number"){result={foreach:modelValue,templateEngine:ko.nativeTemplateEngine.instance};slimscroll={};}else{ko.utils.unwrapObservable(modelValue);result={foreach:unwrappedValue["data"],as:unwrappedValue["as"],includeDestroyed:unwrappedValue["includeDestroyed"],afterAdd:unwrappedValue["afterAdd"],beforeRemove:unwrappedValue["beforeRemove"],afterRender:unwrappedValue["afterRender"],beforeMove:unwrappedValue["beforeMove"],afterMove:unwrappedValue["afterMove"],templateEngine:ko.nativeTemplateEngine.instance};slimscroll=unwrappedValue["slimscroll"];}
return{accessor:function(){return result;},slimscroll:slimscroll};},slimscroll:function(element,options){options=options||{};setTimeout(function(){if(element.nodeName==="#comment"){$(element.parentElement).slimScroll(options);}else{$(element).slimScroll(options);}},10);},init:function(element,valueAccessor,allBindings,viewModel,bindingContext){var prepped=ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);ko.bindingHandlers["slimScrolledForeach"].slimscroll(element,prepped.slimscroll);return ko.bindingHandlers["template"]["init"](element,prepped.accessor);},update:function(element,valueAccessor,allBindings,viewModel,bindingContext){var prepped=ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);var options=$.extend(prepped.slimscroll,{scrollBy:0});ko.bindingHandlers["slimScrolledForeach"].slimscroll(element,options);return ko.bindingHandlers["template"]["update"](element,prepped.accessor,allBindings,viewModel,bindingContext);}};ko.virtualElements.allowedBindings.slimScrolledForeach=true;
;

// source: js/app/bindings/toggle.js
ko.bindingHandlers.toggle={init:function(element,valueAccessor){var value=valueAccessor();if(!ko.isObservable(value)){throw new Error("toggle binding should be used only with observable values");}
$(element).on("click",function(event){event.preventDefault();var previousValue=ko.utils.unwrapObservable(value);value(!previousValue);});},update:function(element,valueAccessor){ko.utils.toggleDomNodeCssClass(element,"active",ko.utils.unwrapObservable(valueAccessor()));}};
;

// source: js/app/bindings/togglecontent.js
ko.bindingHandlers.toggleContent={init:function(element,valueAccessor){var $elm=$(element),options=$.extend({class:null,container:null,parent:null,onComplete:function(){$(document).trigger("slideCompleted");}},valueAccessor());$elm.on("click",function(e){e.preventDefault();if(options.class){$elm.children('[class^="icon-"]').toggleClass(options.class);$elm.children('[class^="fa"]').toggleClass(options.class);}
if(options.container){if(options.parent){$elm.parents(options.parent).find(options.container).stop().slideToggle("fast",options.onComplete);}else{$(options.container).stop().slideToggle("fast",options.onComplete);}}});}};
;

// source: js/app/bindings/valuewithinit.js
ko.bindingHandlers.valueWithInit={init:function(element,valueAccessor,allBindingsAccessor,context){var observable=valueAccessor();var value=element.value;observable(value);ko.bindingHandlers.value.init(element,valueAccessor,allBindingsAccessor,context);},update:ko.bindingHandlers.value.update};
;

// source: js/app/viewmodels/access.js
$(function(){function AccessViewModel(parameters){var access=this;access.loginState=parameters[0];var GROUP_ADMINS="admins";var GROUP_GUESTS="guests";access.users=(function(){var self={};self.listHelper=new ItemListHelper("users",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;}},{},"name",[],[],CONFIG_USERSPERPAGE);self.emptyUser={name:"",active:false};self.currentUser=ko.observable(self.emptyUser).extend({notify:"always"});self.isCurrentUser=(user)=>{return user&&user.name&&user.name==access.loginState.username();};self.isDeleteUserEnabled=(user)=>{return!self.isCurrentUser(user);};self.editor={name:ko.observable(undefined),groups:ko.observableArray([]),permissions:ko.observableArray([]),password:ko.observable(undefined),currentPassword:ko.observable(undefined),repeatedPassword:ko.observable(undefined),passwordMismatch:ko.pureComputed(function(){return self.editor.password()!==self.editor.repeatedPassword();}),providedUsername:ko.pureComputed(function(){return self.editor.name()&&self.editor.name().trim();}),validUsername:ko.pureComputed(function(){return(!self.editor.name()||self.editor.name()==self.editor.name().trim());}),currentPasswordMismatch:ko.observable(false),apikey:ko.observable(undefined),active:ko.observable(undefined),permissionSelectable:function(permission){return true;},permissionSelected:function(permission){var index=self.editor.permissions().indexOf(permission);return index>=0;},togglePermission:function(permission){var permissions=self.editor.permissions();var index=permissions.indexOf(permission);if(index<0){permissions.push(permission);}else{permissions.splice(index,1);}
self.editor.permissions(permissions);},groupSelected:function(group){var index=self.editor.groups().indexOf(group);return index>=0;},toggleGroup:function(group){var groups=self.editor.groups();var index=groups.indexOf(group);if(index<0){groups.push(group);}else{groups.splice(index,1);}
self.editor.groups(groups);},joinedGroupPermissions:function(group){return access.permissionList(group);},header:ko.observable(undefined),new:ko.observable(true),confirm:undefined,valid:ko.pureComputed(function(){return(self.editor.providedUsername()&&self.editor.validUsername()&&(!self.editor.new()||(self.editor.password()&&self.editor.password().trim()&&!self.editor.passwordMismatch())));}),dangerRestricted:function(){return false;},dangerRestrictedText:gettext("This user may not have dangerous permissions.")};self.userEditorDialog=undefined;self.changePasswordDialog=undefined;self.currentUser.subscribe(function(newValue){if(newValue===undefined){self.editor.name(undefined);self.editor.groups(access.groups.defaults.slice(0));self.editor.permissions([]);self.editor.active(true);self.editor.apikey(undefined);self.editor.header(gettext("Add user"));self.editor.new(true);self.editor.confirm=self.confirmAddUser;}else{self.editor.name(newValue.name);self.editor.groups(newValue.groups.slice(0));self.editor.permissions(newValue.permissions.slice(0));self.editor.active(newValue.active);self.editor.apikey(newValue.apikey);self.editor.header(_.sprintf(gettext('Edit user "%(name)s"'),{name:newValue.name}));self.editor.new(false);self.editor.confirm=self.confirmEditUser;}
self.editor.password(undefined);self.editor.repeatedPassword(undefined);self.editor.currentPassword(undefined);self.editor.currentPasswordMismatch(false);});self.editor.currentPassword.subscribe(function(){self.editor.currentPasswordMismatch(false);});self.requestData=function(){if(!CONFIG_ACCESS_CONTROL)return;if(!access.loginState.hasPermissionKo(access.permissions.ADMIN))return;return OctoPrint.access.users.list().done(self.fromResponse);};self.fromResponse=function(response){self.listHelper.updateItems(response.users);};self.showAddUserDialog=function(){if(!CONFIG_ACCESS_CONTROL)return;access.loginState.reauthenticateIfNecessary(()=>{self.currentUser(undefined);$('ul.nav-pills a[data-toggle="tab"]:first',self.userEditorDialog).tab("show");self.userEditorDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});});};self.confirmAddUser=function(){if(!CONFIG_ACCESS_CONTROL)return;var user={name:self.editor.name(),password:self.editor.password(),groups:self.editor.groups(),permissions:self.editor.permissions(),active:self.editor.active()};access.loginState.reauthenticateIfNecessary(()=>{self.addUser(user).done(function(){self.currentUser(undefined);self.userEditorDialog.modal("hide");});});};self.showEditUserDialog=function(user){if(!CONFIG_ACCESS_CONTROL)return;var process=function(user){self.currentUser(user);$('ul.nav-pills a[data-toggle="tab"]:first',self.userEditorDialog).tab("show");self.userEditorDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});};access.loginState.reauthenticateIfNecessary(()=>{OctoPrint.users.get(user.name).done(function(data){process(data);}).fail(function(){log.warn("Could not fetch current user data, proceeding with client side data copy");process(user);});});};self.confirmEditUser=function(){if(!CONFIG_ACCESS_CONTROL)return;var user=self.currentUser();user.active=self.editor.active();user.groups=self.editor.groups();user.permissions=self.editor.permissions();access.loginState.reauthenticateIfNecessary(()=>{self.updateUser(user).done(function(){self.currentUser(undefined);self.userEditorDialog.modal("hide");});});};self.confirmRemoveUser=(user)=>{if(!CONFIG_ACCESS_CONTROL)return;if(user.name===access.loginState.username()){new PNotify({title:gettext("Not possible"),text:gettext("You may not delete your own account."),type:"error"});return $.Deferred().reject("You may not delete your own account").promise();}
access.loginState.reauthenticateIfNecessary(()=>{showConfirmationDialog({title:gettext("Are you sure?"),message:_.sprintf(gettext('You are about to delete the user "%(name)s".'),{name:_.escape(user.name)}),proceed:gettext("Delete"),onproceed:()=>{self.removeUser(user);}});});};self.showChangePasswordDialog=function(user){if(!CONFIG_ACCESS_CONTROL)return;const proceed=()=>{self.currentUser(user);self.changePasswordDialog.modal("show");};if(self.isCurrentUser(user)){proceed();}else{access.loginState.reauthenticateIfNecessary(proceed);}};self.confirmChangePassword=function(){if(!CONFIG_ACCESS_CONTROL)return;const proceed=()=>{self.updatePassword(self.currentUser().name,self.editor.password(),self.editor.currentPassword()).done(function(){self.currentUser(undefined);self.changePasswordDialog.modal("hide");}).fail(function(xhr){if(xhr.status===403){self.currentPasswordMismatch(true);}});};if(self.isCurrentUser()){proceed();}else{access.loginState.reauthenticateIfNecessary(proceed);}};self.confirmGenerateApikey=function(){if(!CONFIG_ACCESS_CONTROL)return;access.loginState.reauthenticateIfNecessary(()=>{self.generateApikey(self.currentUser().name).done(function(response){self._updateApikey(response.apikey);});});};self.copyApikey=function(){copyToClipboard(self.editor.apikey());};self._updateApikey=function(apikey){self.editor.apikey(apikey);self.requestData();};self.confirmDeleteApikey=function(){if(!CONFIG_ACCESS_CONTROL)return;access.loginState.reauthenticateIfNecessary(()=>{self.deleteApikey(self.currentUser().name).done(function(){self._updateApikey(undefined);});});};self.onStartup=function(){self.userEditorDialog=$("#settings-usersEditorDialog");self.changePasswordDialog=$("#settings-usersDialogChangePassword");};self.addUser=function(user){if(!user){throw OctoPrint.InvalidArgumentError("user must be set");}
if(!access.loginState.hasPermissionKo(access.permissions.ADMIN)){return $.Deferred().reject("You are not authorized to perform this action").promise();}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.add(user).done(self.fromResponse);};self.removeUser=function(user){if(!user){throw OctoPrint.InvalidArgumentError("user must be set");}
if(!access.loginState.hasPermissionKo(access.permissions.ADMIN)){return $.Deferred().reject("You are not authorized to perform this action").promise();}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.delete(user.name).done(self.fromResponse);};self.updateUser=function(user){if(!user){throw OctoPrint.InvalidArgumentError("user must be set");}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.update(user.name,user.active,user.admin,user.permissions,user.groups).done(self.fromResponse);};self.updatePassword=function(username,password,current){if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.changePassword(username,password,current);};self.generateApikey=function(username){if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.generateApiKey(username).done(function(){self.requestData();});};self.deleteApikey=function(username){if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.users.resetApiKey(username);};return self;})();access.groups=(function(){var self={};self.listHelper=new ItemListHelper("groups",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;}},{},"name",[],[],CONFIG_GROUPSPERPAGE);self.groupsList=self.listHelper.items;self.lookup={};self.defaults=[];self.emptyGroup={name:""};self.currentGroup=ko.observable(self.emptyGroup);self.editor={key:ko.observable(undefined),name:ko.observable(undefined),description:ko.observable(undefined),permissions:ko.observableArray([]),subgroups:ko.observableArray([]),default:ko.observable(false),permissionSelectable:function(permission){return self.editor.key()!==GROUP_GUESTS||!permission.dangerous;},permissionSelected:function(permission){var index=self.editor.permissions().indexOf(permission);return index>=0;},togglePermission:function(permission){var permissions=self.editor.permissions();var index=permissions.indexOf(permission);if(index<0){permissions.push(permission);}else{permissions.splice(index,1);}
self.editor.permissions(permissions);},subgroupSelectable:function(subgroup){return(self.editor.key()!==subgroup.key&&(self.editor.key()!==GROUP_GUESTS||!subgroup.dangerous));},subgroupSelected:function(subgroup){var index=self.editor.subgroups().indexOf(subgroup);return index>=0;},toggleSubgroup:function(subgroup){var subgroups=self.editor.subgroups();var index=subgroups.indexOf(subgroup);if(index<0){subgroups.push(subgroup);}else{subgroups.splice(index,1);}
self.editor.subgroups(subgroups);},joinedGroupPermissions:function(group){return access.permissionList(group);},header:ko.observable(undefined),new:ko.observable(true),confirm:undefined,valid:ko.pureComputed(function(){return self.editor.name()&&self.editor.name().trim();}),dangerRestricted:function(){return self.editor.key()===GROUP_GUESTS;},dangerRestrictedText:gettext("This group may not have dangerous permissions or subgroups.")};self.groupEditorDialog=undefined;self.groupsList.subscribe(function(oldValue){if(oldValue===undefined||oldValue.length===0)return;oldValue.forEach(function(p){delete self[p.key.toUpperCase()];});},null,"beforeChange");self.groupsList.subscribe(function(newValue){if(newValue===undefined)return;newValue.forEach(function(g){var needs=[];g.permissions.forEach(function(p){for(var key in p.needs){p.needs[key].forEach(function(value){needs.push(access.permissions.need(key,value));});}});if(needs.length>0){self.registerGroup(g.key.toUpperCase(),needs);}});});self.registerGroup=function(name,group){Object.defineProperty(self,name,{value:group,enumerable:true,configurable:true});};self.currentGroup.subscribe(function(newValue){if(newValue===undefined){self.editor.key(undefined);self.editor.name(undefined);self.editor.description(undefined);self.editor.permissions([]);self.editor.subgroups([]);self.editor.default(false);self.editor.header(gettext("Add group"));self.editor.new(true);self.editor.confirm=self.confirmAddGroup;}else{self.editor.key(newValue.key);self.editor.name(newValue.name);self.editor.description(newValue.description);self.editor.permissions(newValue.permissions.slice(0));self.editor.subgroups(newValue.subgroups.slice(0));self.editor.default(newValue.default);self.editor.header(_.sprintf(gettext('Edit group "%(name)s"'),{name:newValue.name}));self.editor.new(false);self.editor.confirm=self.confirmEditGroup;}});self.requestData=function(){return OctoPrint.access.groups.list().done(self.fromResponse);};self.fromResponse=function(response){var lookup={};var defaults=[];_.each(response.groups,function(group){lookup[group.key]=group;if(group.default){defaults.push(group.key);}});self.lookup=lookup;self.defaults=defaults;self.listHelper.updateItems(response.groups);};self.showAddGroupDialog=function(){access.loginState.reauthenticateIfNecessary(()=>{self.currentGroup(undefined);$('ul.nav-pills a[data-toggle="tab"]:first',self.groupEditorDialog).tab("show");self.groupEditorDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});});};self.confirmAddGroup=function(){var group={key:self.editor.name().toLowerCase().replace(/[^a-z0-9_ ]/g,"").replace(/ /g,"_"),name:self.editor.name(),description:self.editor.description(),permissions:self.editor.permissions(),subgroups:self.editor.subgroups(),default:self.editor.default()};self.addGroup(group).done(function(){self.currentGroup(undefined);self.groupEditorDialog.modal("hide");});};self.showEditGroupDialog=function(group){if(!group.changeable)return;access.loginState.reauthenticateIfNecessary(()=>{self.currentGroup(group);$('ul.nav-pills a[data-toggle="tab"]:first',self.groupEditorDialog).tab("show");self.groupEditorDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});});};self.confirmEditGroup=function(){var group=self.currentGroup();var data={key:group.key,name:group.name,description:self.editor.description(),permissions:self.editor.permissions(),subgroups:self.editor.subgroups(),default:self.editor.default()};self.updateGroup(data).done(function(){self.currentGroup(undefined);self.groupEditorDialog.modal("hide");});};self.confirmRemoveGroup=(group)=>{if(!group.removable)return;access.loginState.reauthenticateIfNecessary(()=>{showConfirmationDialog({title:gettext("Are you sure?"),message:_.sprintf(gettext('You are about to delete the group "%(name)s".'),{name:_.escape(group.name)}),proceed:gettext("Delete"),onproceed:()=>{self.removeGroup(group);}});});};self.onStartup=function(){self.groupEditorDialog=$("#settings-groupsEditorDialog");};self.addGroup=function(group){if(!group){throw OctoPrint.InvalidArgumentError("group must be set");}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.groups.add(group).done(self.fromResponse);};self.removeGroup=function(group){if(!group){throw OctoPrint.InvalidArgumentError("group must be set");}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
OctoPrint.access.groups.delete(group.key).done((response)=>{self.fromResponse(response);access.users.requestData();});};self.updateGroup=function(group){if(!group){throw OctoPrint.InvalidArgumentError("group must be set");}
if(!access.loginState.credentialsSeen()){return $.Deferred().reject("You need to reauthenticate to perform this action").promise();}
return OctoPrint.access.groups.update(group).done(self.fromResponse);};return self;})();access.permissions=(function(){var self={};self.need=function(method,value){return{method:method,value:value};};self.roleNeed=function(value){return self.need("role",value);};self.permissionList=ko.observableArray([]);self.lookup={};var registeredPermissions=[];var registerPermission=function(key,permission){Object.defineProperty(self,key,{value:permission,enumerable:true,configurable:true});registeredPermissions.push(key);};var clearAllRegisteredPermissions=function(){_.each(registeredPermissions,function(key){delete self[key];});registeredPermissions=[];};self.initialize=function(){clearAllRegisteredPermissions();var permissionList=[];var lookup={};_.each(PERMISSIONS,function(permission){var needs=[];_.each(permission.needs,function(value,key){needs.push(self.need(key,value));});if(needs.length>0){registerPermission(permission.key,needs);}
if(!permission.combined){permissionList.push(permission);}
lookup[permission.key]=permission;});permissionList.sort(access.permissionComparator);self.permissionList(permissionList);self.lookup=lookup;};return self;})();access.groupComparator=function(a,b){var nameA=a.name?a.name.toUpperCase():"";var nameB=b.name?b.name.toUpperCase():"";if(nameA<nameB){return-1;}else if(nameA>nameB){return 1;}else{return 0;}};access.permissionComparator=function(a,b){var nameA=a.name?a.name.toUpperCase():"";var nameB=b.name?b.name.toUpperCase():"";var pluginA=a.plugin||"";var pluginB=b.plugin||"";var compA=pluginA+":"+nameA;var compB=pluginB+":"+nameB;if(compA<compB){return-1;}else if(compA>compB){return 1;}else{return 0;}};access.groupList=function(data){if(data.groups===undefined)return"";var mappedGroups=_.filter(_.map(data.groups,function(g){return access.groups.lookup[g];}),function(g){return g!==undefined;});mappedGroups.sort(access.groupComparator);return _.map(mappedGroups,function(g){return g.name;}).join(", ");};access.subgroupList=function(data){if(data.subgroups===undefined)return"";var mappedGroups=_.filter(_.map(data.subgroups,function(g){return access.groups.lookup[g];}),function(g){return g!==undefined;});mappedGroups.sort(access.groupComparator);return _.map(mappedGroups,function(g){return g.name;}).join(", ");};access.permissionList=function(data){if(!data||data.permissions===undefined)return"";var mappedPermissions=_.filter(_.map(data.permissions,function(p){return access.permissions.lookup[p];}),function(p){return p!==undefined;});mappedPermissions.sort(access.permissionComparator);return _.map(mappedPermissions,function(p){return p.name;}).join(", ");};access.onStartup=function(){access.groups.onStartup();access.users.onStartup();};access.onServerConnect=function(){access.permissions.initialize();};access.onServerReconnect=function(){access.permissions.initialize();};access.onUserPermissionsChanged=access.onUserLoggedIn=access.onUserLoggedOut=function(user){if(access.loginState.hasPermission(access.permissions.ADMIN)){access.groups.requestData().done(function(){access.users.requestData();});}};}
OCTOPRINT_VIEWMODELS.push([AccessViewModel,["loginStateViewModel"],[]]);});
;

// source: js/app/viewmodels/appearance.js
$(function(){var save={};function themeFavicon(colorname){save.colorName=colorname;var link=document.querySelector("link[rel='shortcut icon']");if(!link){link=document.createElement("link");link.setAttribute("rel","shortcut icon");document.head.appendChild(link);}
var faviconUrl=document.querySelector("link[rel~='mask-icon-theme']").href||link.href||window.location.origin+"/favicon.ico";function onImageLoaded(){var icosize=256;var canvas=document.createElement("canvas");canvas.width=icosize;canvas.height=icosize;var context=canvas.getContext("2d");function grayscale(){var imageData=context.getImageData(0,0,canvas.width,canvas.height),pixels=imageData.data,i,l,r,g,b,a,luma;for(i=0,l=pixels.length;i<l;i+=4){a=pixels[i+3];if(a===0){continue;}
r=pixels[i];g=pixels[i+1];b=pixels[i+2];luma=r*0.2126+g*0.7152+b*0.0722;pixels[i]=pixels[i+1]=pixels[i+2]=luma;}
context.putImageData(imageData,0,0);}
function colorize(color,alpha){context.globalCompositeOperation="source-atop";context.globalAlpha=alpha;context.fillStyle=color;context.fillRect(0,0,canvas.width,canvas.height);context.globalCompositeOperation="source-over";context.globalAlpha=1.0;}
context.drawImage(img,0,0,canvas.width,canvas.height);if(save.colorName!=="default"){grayscale();colorize(save.colorName,0.3);}
link.type="image/x-icon";link.href=canvas.toDataURL();}
var img=document.createElement("img");img.addEventListener("load",onImageLoaded);img.src=faviconUrl;}
function AppearanceViewModel(parameters){var self=this;self.name=parameters[0].appearance_name;self.color=parameters[0].appearance_color;self.colorTransparent=parameters[0].appearance_colorTransparent;self.colorIcon=parameters[0].appearance_colorIcon;function updateIcon(){if(self.colorIcon()){themeFavicon(self.color());}else{themeFavicon("default");}}
self.color.subscribe(updateIcon);self.colorIcon.subscribe(updateIcon);updateIcon();self.brand=ko.pureComputed(function(){if(self.name())return self.name();else return gettext("OctoPrint");});self.fullbrand=ko.pureComputed(function(){if(self.name())return gettext("OctoPrint")+": "+self.name();else return gettext("OctoPrint");});self.title=ko.pureComputed(function(){if(self.name())return self.name()+" ["+gettext("OctoPrint")+"]";else return gettext("OctoPrint");});self.theme_color=ko.pureComputed(function(){switch(self.color()){case"red":return"#bb645f";case"orange":return"#e39665";case"yellow":return"#e3d765;";case"green":return"#98f064";case"blue":return"#2e63cc";case"violet":return"#9864f0";case"black":return"#4f4f4f";case"white":return"#e9e9e9";case"default":default:return"#ebebeb";}});}
OCTOPRINT_VIEWMODELS.push({construct:AppearanceViewModel,dependencies:["settingsViewModel"],elements:["head"]});});
;

// source: js/app/viewmodels/connection.js
$(function(){function ConnectionViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.printerProfiles=parameters[2];self.access=parameters[3];self.printerProfiles.profiles.items.subscribe(function(){var allProfiles=self.printerProfiles.profiles.items();var printerOptions=[];_.each(allProfiles,function(profile){printerOptions.push({id:profile.id,name:profile.name});});self.printerOptions(printerOptions);});self.printerProfiles.currentProfile.subscribe(function(){self.selectedPrinter(self.printerProfiles.currentProfile());});self.portOptionsFetched=ko.observable(false);self.portOptions=ko.observableArray(undefined);self.baudrateOptions=ko.observableArray(undefined);self.printerOptions=ko.observableArray(undefined);self.selectedPort=ko.observable(undefined);self.selectedBaudrate=ko.observable(undefined);self.selectedPrinter=ko.observable(undefined);self.saveSettings=ko.observable(undefined);self.autoconnect=ko.observable(undefined);self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.enableConnect=ko.pureComputed(function(){return true;});self.buttonText=ko.pureComputed(function(){if(self.isErrorOrClosed())return gettext("Connect");else return gettext("Disconnect");});self.portCaption=ko.pureComputed(function(){return self.validPort()?"AUTO":gettext("No serial port found");});self.validPort=ko.pureComputed(function(){return(!self.portOptionsFetched()||self.portOptions().length>0||self.settings.settings.serial.ignoreEmptyPorts());});self.enablePort=ko.pureComputed(function(){return self.validPort()&&self.isErrorOrClosed();});self.enableSaveSettings=ko.pureComputed(function(){return self.enableConnect()&&self.isErrorOrClosed();});self.enableAutoConnect=ko.pureComputed(function(){return self.enableConnect()&&self.isErrorOrClosed();});self.previousIsOperational=undefined;self.refreshVisible=ko.observable(true);self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.CONNECTION)){return;}
OctoPrint.connection.getSettings().done(self.fromResponse);};self.fromResponse=function(response){var ports=response.options.ports;var baudrates=response.options.baudrates;var currentPort=response.current.port;var currentBaudrate=response.current.baudrate;var currentPrinterProfile=response.current.printerProfile;var portPreference=response.options.portPreference;var baudratePreference=response.options.baudratePreference;var printerPreference=response.options.printerProfilePreference;var printerProfiles=response.options.printerProfiles;self.portOptions(ports);self.baudrateOptions(baudrates);if(!self.selectedPort()&&ports){if(ports.indexOf(currentPort)>=0){self.selectedPort(currentPort);}else if(ports.indexOf(portPreference)>=0){self.selectedPort(portPreference);}}
if(!self.selectedBaudrate()&&baudrates){if(baudrates.indexOf(currentBaudrate)>=0){self.selectedBaudrate(currentBaudrate);}else if(baudrates.indexOf(baudratePreference)>=0){self.selectedBaudrate(baudratePreference);}}
if(!self.selectedPrinter()&&printerProfiles){if(printerProfiles.indexOf(currentPrinterProfile)>=0){self.selectedPrinter(currentPrinterProfile);}else if(printerProfiles.indexOf(printerPreference)>=0){self.selectedPrinter(printerPreference);}}
self.saveSettings(false);self.portOptionsFetched(true);};self.fromHistoryData=function(data){self._processStateData(data.state);};self.fromCurrentData=function(data){self._processStateData(data.state);};self.openOrCloseOnStateChange=function(force){if(!self._startupComplete&&!force)return;var connectionTab=$("#connection");if(self.isOperational()&&connectionTab.hasClass("in")){connectionTab.collapse("hide");self.refreshVisible(false);}else if(!self.isOperational()&&!connectionTab.hasClass("in")){connectionTab.collapse("show");self.refreshVisible(true);}};self._processStateData=function(data){self.previousIsOperational=self.isOperational();self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);if(self.previousIsOperational!==self.isOperational()){self.openOrCloseOnStateChange();}};self.connect=function(){if(self.isErrorOrClosed()){var data={port:self.selectedPort()||"AUTO",baudrate:self.selectedBaudrate()||0,printerProfile:self.selectedPrinter(),autoconnect:self.settings.serial_autoconnect()};if(self.saveSettings())data["save"]=true;OctoPrint.connection.connect(data).done(function(){self.settings.requestData();self.settings.printerProfiles.requestData();});}else{if(!self.isPrinting()&&!self.isPaused()){self.requestData();OctoPrint.connection.disconnect();}else{showConfirmationDialog({title:gettext("Are you sure?"),message:gettext("<p><strong>You are about to disconnect from the printer while a print "+"is in progress.</strong></p>"+"<p>Disconnecting while a print is in progress will prevent OctoPrint from "+"completing the print. If you're printing from an SD card attached directly "+"to the printer, any attempt to restart OctoPrint or reconnect to the printer "+"could interrupt the print.<p>"),question:gettext("Are you sure you want to disconnect from the printer?"),cancel:gettext("Stay Connected"),proceed:gettext("Disconnect"),onproceed:function(){self.requestData();OctoPrint.connection.disconnect();}});}}};self.onEventSettingsUpdated=function(){self.requestData();};self.onEventConnected=function(){self.requestData();};self.onEventDisconnected=function(){self.requestData();};self.onEventConnectionsAutorefreshed=function(){self.requestData();};self.onStartup=function(){var connectionTab=$("#connection");connectionTab.on("show",function(){self.refreshVisible(true);});connectionTab.on("hide",function(){self.refreshVisible(false);});};self.onStartupComplete=function(){self.openOrCloseOnStateChange(true);};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};}
OCTOPRINT_VIEWMODELS.push({construct:ConnectionViewModel,dependencies:["loginStateViewModel","settingsViewModel","printerProfilesViewModel","accessViewModel"],elements:["#connection_wrapper"]});});
;

// source: js/app/viewmodels/control.js
$(function(){function ControlViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.access=parameters[2];self._createToolEntry=function(){return{name:ko.observable(),key:ko.observable()};};self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.extrusionAmount=ko.observable(undefined);self.controls=ko.observableArray([]);self.distances=ko.observableArray([0.1,1,10,100]);self.distance=ko.observable(10);self.tools=ko.observableArray([]);self.feedRate=ko.observable();self.flowRate=ko.observable();self.feedbackControlLookup={};self.controlsFromServer=[];self.additionalControls=[];self.intersectionObservers=[];self.keycontrolActive=ko.observable(false);self.keycontrolHelpActive=ko.observable(false);self.keycontrolPossible=ko.pureComputed(function(){return(self.loginState.hasPermission(self.access.permissions.CONTROL)&&self.settings.feature_keyboardControl()&&self.isOperational()&&!self.isPrinting()&&!$.browser.mobile);});self.showKeycontrols=ko.pureComputed(function(){return self.keycontrolPossible();});self._visibleWebcam=undefined;self._dispatchWebcamRefresh=function(target){log.debug(`Webcam refresh triggered for #${target.id}`);var vm=ko.dataFor(target.children[0]);if(vm===self){log.debug(`VM for webcam #${target.id} is not bound, skipping refresh`);}else if(vm===undefined){log.debug(`VM for webcam #${target.id} not found, skipping refresh`);}else if(typeof vm.onWebcamRefresh==="function"){vm.onWebcamRefresh();}else{log.debug(`VM for webcam #${target.id} does not declare 'onWebcamRefresh()', skipping refresh (vm=${vm.constructor.name})`);}};self._dispatchWebcamVisibilityChange=function(target,visible){log.debug(`Webcam visibility of #${target.id} changed to ${visible}`);var vm=ko.dataFor(target.children[0]);if(vm===self){log.debug(`VM for webcam #${target.id} is not bound, skipping visibility update`);}else if(vm===undefined){log.debug(`VM for webcam #${target.id} not found, skipping visibility update`);}else if(typeof vm.onWebcamVisibilityChange==="function"){vm.onWebcamVisibilityChange(visible);}else{log.debug(`VM for webcam #${target.id} does not declare 'onWebcamVisibilityChange(visible)', skipping visibility update (vm=${vm.constructor.name})`);}};const selectedCameraStorageKey="core.control.selectedCamera";self.selectDefaultWebcam=function(){if(!document.querySelector("#webcam_plugins_container .nav")){$("#webcam-group .tab-pane:first").addClass("active");return;}
let div=localStorage[selectedCameraStorageKey];if(!div||document.getElementById(div.slice(1))===null){div=undefined;}
if(div!==undefined){$(`${div}_link a`).tab("show");}else{$("#webcam_plugins_container .nav li:first a").tab("show");}};self.onStartupComplete=function(){$("#webcam_plugins_container .nav a[data-toggle='tab']").on("shown",(e)=>{localStorage[selectedCameraStorageKey]=e.target.hash;});self.selectDefaultWebcam();self.recreateIntersectionObservers();};self.recreateIntersectionObservers=function(){self.intersectionObservers.forEach(function(observer){observer.disconnect();});self.intersectionObservers=[];document.querySelectorAll("#webcam-group .tab-pane").forEach(function(target){var options={root:document.querySelector("#webcam_plugins_container"),rootMargin:"0px",threshold:0.01};var callback=function(entries){var visible=entries[0].isIntersecting;self._dispatchWebcamVisibilityChange(target,visible);if(visible){self._visibleWebcam=target;}else if(self._visibleWebcam===target&&!visible){self._visibleWebcam=undefined;}};var observer=new IntersectionObserver(callback,options);observer.observe(target);self.intersectionObservers.push(observer);});};self.onBrowserTabVisibilityChange=function(tabVisible){if(self._visibleWebcam!==undefined){self._dispatchWebcamVisibilityChange(self._visibleWebcam,tabVisible);}};self.refreshWebcam=function(){if(self._visibleWebcam!==undefined){self._dispatchWebcamRefresh(self._visibleWebcam);}};self.settings.printerProfiles.currentProfileData.subscribe(function(){self._updateExtruderCount();self._updateExtrusionAmount();const data=self.settings.printerProfiles.currentProfileData();if(data&&data.extruder){if(data.extruder.defaultExtrusionLength){data.extruder.defaultExtrusionLength.subscribe(self._updateExtrusionAmount);}
if(data.extruder.count){data.extruder.count.subscribe(self._updateExtruderCount);}}
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);});self._updateExtrusionAmount=function(){const data=self.settings.printerProfiles.currentProfileData();if(!data||!data.extruder){return;}
self.extrusionAmount(self.settings.printerProfiles.currentProfileData().extruder.defaultExtrusionLength());};self._updateExtruderCount=function(){const data=self.settings.printerProfiles.currentProfileData();if(!data||!data.extruder||!data.extruder.count){return;}
var tools=[];var numExtruders=self.settings.printerProfiles.currentProfileData().extruder.count();if(numExtruders>1){for(var extruder=0;extruder<numExtruders;extruder++){tools[extruder]=self._createToolEntry();tools[extruder]["name"](gettext("Tool")+" "+extruder);tools[extruder]["key"]("tool"+extruder);}}else if(numExtruders===1){tools[0]=self._createToolEntry();tools[0]["name"](gettext("Hotend"));tools[0]["key"]("tool0");}
self.tools(tools);};self.fromCurrentData=function(data){self._processStateData(data.state);};self.fromHistoryData=function(data){self._processStateData(data.state);};self._processStateData=function(data){self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);};self.onEventSettingsUpdated=function(){self.requestData();};self.onEventRegisteredMessageReceived=function(payload){if(payload.key in self.feedbackControlLookup){var outputs=self.feedbackControlLookup[payload.key];_.each(payload.outputs,function(value,key){if(outputs.hasOwnProperty(key)){outputs[key](value);}});}};self.rerenderControls=function(){var allControls=self.controlsFromServer.concat(self.additionalControls);self.controls(self._processControls(allControls));};self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.CONTROL)){return;}
OctoPrint.control.getCustomControls().done(function(response){self._fromResponse(response);});};self._fromResponse=function(response){self.controlsFromServer=response.controls;self.rerenderControls();};self._processControls=function(controls){for(var i=0;i<controls.length;i++){controls[i]=self._processControl(controls[i]);}
return controls;};self._processControl=function(control){if(control.hasOwnProperty("processed")&&control.processed){return control;}
if(control.hasOwnProperty("template")&&control.hasOwnProperty("key")&&control.hasOwnProperty("template_key")&&!control.hasOwnProperty("output")){control.output=ko.observable(control.default||"");if(!self.feedbackControlLookup.hasOwnProperty(control.key)){self.feedbackControlLookup[control.key]={};}
self.feedbackControlLookup[control.key][control.template_key]=control.output;}
if(control.hasOwnProperty("children")){control.children=ko.observableArray(self._processControls(control.children));if(!control.hasOwnProperty("layout")||!(control.layout=="vertical"||control.layout=="horizontal"||control.layout=="horizontal_grid")){control.layout="vertical";}
if(!control.hasOwnProperty("collapsed")){control.collapsed=false;}}
if(control.hasOwnProperty("input")){var attributeToInt=function(obj,key,def){if(obj.hasOwnProperty(key)){var val=obj[key];if(_.isNumber(val)){return val;}
var parsedVal=parseInt(val);if(!isNaN(parsedVal)){return parsedVal;}}
return def;};_.each(control.input,function(element){if(element.hasOwnProperty("slider")&&_.isObject(element.slider)){element.slider["min"]=attributeToInt(element.slider,"min",0);element.slider["max"]=attributeToInt(element.slider,"max",255);var defaultValue=attributeToInt(element,"default",element.slider.min);if(!_.inRange(defaultValue,element.slider.min,element.slider.max)){defaultValue=defaultValue<element.slider.min?element.slider.min:element.slider.max;}
element.value=ko.observable(defaultValue);}else{element.slider=false;element.value=ko.observable(element.hasOwnProperty("default")?element["default"]:undefined);}});}
if(control.hasOwnProperty("javascript")){var js=control.javascript;if(!_.isFunction(js)){control.javascript=function(data){eval(js);};}}
if(control.hasOwnProperty("enabled")){var enabled=control.enabled;if(!_.isFunction(enabled)){control.enabled=function(data){return eval(enabled);};}}
if(!control.hasOwnProperty("additionalClasses")){control.additionalClasses="";}
control.processed=true;return control;};self.isCustomEnabled=function(data){if(data.hasOwnProperty("enabled")){return data.enabled(data);}else{return(self.loginState.hasPermission(self.access.permissions.CONTROL)&&self.isOperational());}};self.clickCustom=function(data){var callback;if(data.hasOwnProperty("javascript")){callback=data.javascript;}else{callback=self.sendCustomCommand;}
if(data.confirm){showConfirmationDialog({message:data.confirm,onproceed:function(e){callback(data);}});}else{callback(data);}};self.sendJogCommand=function(axis,multiplier,distance){if(typeof distance==="undefined")distance=self.distance();if(self.settings.printerProfiles.currentProfileData()&&self.settings.printerProfiles.currentProfileData()["axes"]&&self.settings.printerProfiles.currentProfileData()["axes"][axis]&&self.settings.printerProfiles.currentProfileData()
["axes"][axis]["inverted"]()){multiplier*=-1;}
var data={};data[axis]=distance*multiplier;OctoPrint.printer.jog(data);};self.sendHomeCommand=function(axis){OctoPrint.printer.home(axis);};self.feedRateBusy=ko.observable(false);self.feedRateResetter=ko.observable();self.sendFeedRateCommand=function(){var rate=self.feedRate();if(!rate)return;rate=_.parseInt(self.feedRate());self.feedRateBusy(true);OctoPrint.printer.setFeedrate(rate).done(function(){self.feedRate(undefined);}).always(function(){self.feedRateBusy(false);});};self.resetFeedRateDisplay=function(){self.cancelFeedRateDisplayReset();self.feedRateResetter(setTimeout(function(){self.feedRate(undefined);self.feedRateResetter(undefined);},5000));};self.cancelFeedRateDisplayReset=function(){var resetter=self.feedRateResetter();if(resetter){clearTimeout(resetter);self.feedRateResetter(undefined);}};self.sendExtrudeCommand=function(){self._sendECommand(1);};self.sendRetractCommand=function(){self._sendECommand(-1);};self.flowRateBusy=ko.observable(false);self.flowRateResetter=ko.observable();self.sendFlowRateCommand=function(){var rate=self.flowRate();if(!rate)return;rate=_.parseInt(self.flowRate());self.flowRateBusy(true);OctoPrint.printer.setFlowrate(rate).done(function(){self.flowRate(undefined);}).always(function(){self.flowRateBusy(false);});};self.resetFlowRateDisplay=function(){self.cancelFlowRateDisplayReset();self.flowRateResetter(setTimeout(function(){self.flowRate(undefined);self.flowRateResetter(undefined);},5000));};self.cancelFlowRateDisplayReset=function(){var resetter=self.flowRateResetter();if(resetter){clearTimeout(resetter);self.flowRateResetter(undefined);}};self._sendECommand=function(dir){var length=self.extrusionAmount();OctoPrint.printer.extrude(length*dir);};self.sendSelectToolCommand=function(data){if(!data||!data.key())return;OctoPrint.printer.selectTool(data.key());};self.sendCustomCommand=function(command){if(!command)return;var parameters={};if(command.hasOwnProperty("input")){_.each(command.input,function(input){if(!input.hasOwnProperty("parameter")||!input.hasOwnProperty("value")){return;}
parameters[input.parameter]=input.value();});}
if(command.hasOwnProperty("command")||command.hasOwnProperty("commands")){var commands=command.commands||[command.command];OctoPrint.control.sendGcodeWithParameters(commands,parameters);}else if(command.hasOwnProperty("script")){var script=command.script;var context=command.context||{};OctoPrint.control.sendGcodeScriptWithParameters(script,context,parameters);}};self.displayMode=function(customControl){if(customControl.hasOwnProperty("children")){if(customControl.name){return"customControls_containerTemplate_collapsable";}else{return"customControls_containerTemplate_nameless";}}else{return"customControls_controlTemplate";}};self.rowCss=function(customControl){var span="span2";var offset="";if(customControl.hasOwnProperty("width")){span="span"+customControl.width;}
if(customControl.hasOwnProperty("offset")){offset="offset"+customControl.offset;}
return span+" "+offset;};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};self.onAllBound=function(allViewModels){var additionalControls=[];callViewModels(allViewModels,"getAdditionalControls",function(method){additionalControls=additionalControls.concat(method());});if(additionalControls.length>0){self.additionalControls=additionalControls;self.rerenderControls();}};self.onFocus=function(data,event){if(!self.settings.feature_keyboardControl())return;self.keycontrolActive(true);};self.onMouseOver=function(data,event){if(!self.settings.feature_keyboardControl())return;$("#webcam_plugins_container").focus();self.keycontrolActive(true);};self.onMouseOut=function(data,event){if(!self.settings.feature_keyboardControl())return;$("#webcam_plugins_container").blur();self.keycontrolActive(false);};self.toggleKeycontrolHelp=function(){self.keycontrolHelpActive(!self.keycontrolHelpActive());};self.onKeyDown=function(data,event){if(!self.settings.feature_keyboardControl())return;var button=undefined;var visualizeClick=true;switch(event.which){case 37:button=$("#control-xdec");break;case 38:button=$("#control-yinc");break;case 39:button=$("#control-xinc");break;case 40:button=$("#control-ydec");break;case 49:case 97:button=$("#control-distance01");visualizeClick=false;break;case 50:case 98:button=$("#control-distance1");visualizeClick=false;break;case 51:case 99:button=$("#control-distance10");visualizeClick=false;break;case 52:case 100:button=$("#control-distance100");visualizeClick=false;break;case 33:case 87:button=$("#control-zinc");break;case 34:case 83:button=$("#control-zdec");break;case 36:button=$("#control-xyhome");break;case 35:button=$("#control-zhome");break;case 9:event.preventDefault();return false;default:return true;}
if(button===undefined){return false;}else{event.preventDefault();if(visualizeClick){button.addClass("active");setTimeout(function(){button.removeClass("active");},150);}
button.click();}};self.stripDistanceDecimal=function(distance){return distance.toString().replace(".","");};}
OCTOPRINT_VIEWMODELS.push({construct:ControlViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel"],elements:["#control","#control_link"]});});
;

// source: js/app/viewmodels/files.js
$(function(){function FilesViewModel(parameters){var self=this;self.settingsViewModel=parameters[0];self.loginState=parameters[1];self.printerState=parameters[2];self.slicing=parameters[3];self.printerProfiles=parameters[4];self.access=parameters[5];self.allViewModels=undefined;self.filesListVisible=ko.observable(true);self.showInternalFilename=ko.observable(true);self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.isSdReady=ko.observable(undefined);self.searchQuery=ko.observable(undefined);self.searchQuery.subscribe(function(){self.performSearch();});self.freeSpace=ko.observable(undefined);self.totalSpace=ko.observable(undefined);self.freeSpaceString=ko.pureComputed(function(){if(!self.freeSpace())return"-";return formatSize(self.freeSpace());});self.totalSpaceString=ko.pureComputed(function(){if(!self.totalSpace())return"-";return formatSize(self.totalSpace());});self.diskusageWarning=ko.pureComputed(function(){return(self.freeSpace()!==undefined&&self.freeSpace()<self.settingsViewModel.server_diskspace_warning());});self.diskusageCritical=ko.pureComputed(function(){return(self.freeSpace()!==undefined&&self.freeSpace()<self.settingsViewModel.server_diskspace_critical());});self.diskusageString=ko.pureComputed(function(){if(self.diskusageCritical()){return gettext("Your available free disk space is critically low.");}else if(self.diskusageWarning()){return gettext("Your available free disk space is starting to run low.");}else{return gettext("Your current disk usage.");}});self.uploadButton=undefined;self.uploadSdButton=undefined;self.uploadProgressBar=undefined;self.localTarget=undefined;self.sdTarget=undefined;self.dropOverlay=undefined;self.dropZone=undefined;self.dropZoneLocal=undefined;self.dropZoneSd=undefined;self.dropZoneBackground=undefined;self.dropZoneLocalBackground=undefined;self.dropZoneSdBackground=undefined;self.listElement=undefined;self.ignoreUpdatedFilesEvent=false;self.addingFolder=ko.observable(false);self.activeRemovals=ko.observableArray([]);self.movingFileOrFolder=ko.observable(false);self.moveEntry=ko.observable({name:"",display:"",path:""});self.moveSource=ko.observable(undefined);self.moveDestination=ko.observable(undefined);self.moveSourceFilename=ko.observable(undefined);self.moveDestinationFilename=ko.observable(undefined);self.moveDestinationFullpath=ko.pureComputed(function(){if(self.moveSourceFilename()!==self.moveDestinationFilename()){if(self.moveDestination()==="/"){return self.moveDestination()+self.moveDestinationFilename();}else{return self.moveDestination()+"/"+self.moveDestinationFilename();}}else{return self.moveDestination();}});self.moveError=ko.observable("");self.moveButtonText=ko.pureComputed(function(){if(self.moveSource()===self.moveDestination()){return gettext("Rename");}else{if(self.moveSourceFilename()!==self.moveDestinationFilename()){return gettext("Move & Rename");}else return gettext("Move");}});self.folderList=ko.observableArray(["/"]);self.addFolderDialog=undefined;self.addFolderName=ko.observable(undefined);self.enableAddFolder=ko.pureComputed(function(){return(self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)&&self.addFolderName()&&self.addFolderName().trim()!==""&&!self.addingFolder());});self.uploadExistsDialog=undefined;self.uploadFilename=ko.observable(undefined);self.allItems=ko.observable(undefined);var optionsLocalStorageKey="gcodeFiles.options";self._toLocalStorage=function(){saveToLocalStorage(optionsLocalStorageKey,{currentPath:self.currentPath()});};self._fromLocalStorage=function(){var data=loadFromLocalStorage(optionsLocalStorageKey);if(data["currentPath"]!==undefined&&self.settingsViewModel.feature_rememberFileFolder()){self.currentPath(data["currentPath"]);}};self.currentPath=ko.observable("");self.currentPath.subscribe(function(){self._toLocalStorage();});self.uploadProgressText=ko.observable();self.uploadProgressPercentage=ko.observable();var listStyleStorageKey="gcodeFiles.currentListStyle";var defaultListStyle="folders_files";var saveListStyleToLocalStorage=function(){if(initListStyleLocalStorage()){localStorage[listStyleStorageKey]=self.listStyle();}};var loadListStyleFromLocalStorage=function(){if(initListStyleLocalStorage()){self.listStyle(localStorage[listStyleStorageKey]);}};var initListStyleLocalStorage=function(){if(!Modernizr.localstorage)return false;if(localStorage[listStyleStorageKey]!==undefined)return true;localStorage[listStyleStorageKey]=defaultListStyle;return true;};self.listStyle=ko.observable(defaultListStyle);self.listStyle.subscribe(saveListStyleToLocalStorage);loadListStyleFromLocalStorage();var listHelperFilters={printed:function(data){return!(data["prints"]&&data["prints"]["success"]&&data["prints"]["success"]>0);},sd:function(data){return data["origin"]&&data["origin"]==="sdcard";},local:function(data){return!(data["origin"]&&data["origin"]==="sdcard");}};var listHelperExclusiveFilters=[["sd","local"]];if(SUPPORTED_FILETYPES.length>1){_.each(SUPPORTED_FILETYPES,function(filetype){listHelperFilters[filetype]=function(data){return(data["type"]&&(data["type"]===filetype||data["type"]==="folder"));};});listHelperExclusiveFilters.push(SUPPORTED_FILETYPES);}
var sortByName=function(a,b){if(a["display"].toLowerCase()<b["display"].toLowerCase())return-1;if(a["display"].toLowerCase()>b["display"].toLowerCase())return 1;return 0;};self.listHelper=new ItemListHelper("gcodeFiles",{name:sortByName,upload:function(a,b){if(a["date"]===undefined&&b["date"]===undefined){return sortByName(a,b);}
if(b["date"]===undefined||a["date"]>b["date"])return-1;if(a["date"]===undefined||a["date"]<b["date"])return 1;return 0;},last_printed:function(a,b){var valA=a.prints&&a.prints.last&&a.prints.last.date?a.prints.last.date:"";var valB=b.prints&&b.prints.last&&b.prints.last.date?b.prints.last.date:"";if(valA>valB){return-1;}else if(valA<valB){return 1;}else{return 0;}},size:function(a,b){if(b["size"]===undefined||a["size"]>b["size"])return-1;if(a["size"]===undefined||a["size"]<b["size"])return 1;return 0;}},listHelperFilters,"name",[],listHelperExclusiveFilters,0);self.selectedFile=undefined;self.availableFiletypes=ko.pureComputed(function(){var mapping={model:gettext("Only show model files"),machinecode:gettext("Only show machine code files")};var result=[];_.each(SUPPORTED_FILETYPES,function(filetype){if(mapping[filetype]){result.push({key:filetype,text:mapping[filetype]});}else{result.push({key:filetype,text:_.sprintf(gettext("Only show %(type)s files"),{type:_.escape(filetype)})});}});return result;});self.folderDestinations=ko.pureComputed(function(){if(self.allItems()){return ko.utils.arrayFilter(self.allItems(),function(item){return item.type==="folder";});}});self.foldersOnlyList=ko.dependentObservable(function(){var filter=function(data){return data["type"]&&data["type"]==="folder";};return _.filter(self.listHelper.paginatedItems(),filter);});self.filesOnlyList=ko.dependentObservable(function(){var filter=function(data){return data["type"]&&data["type"]!=="folder";};return _.filter(self.listHelper.paginatedItems(),filter);});self.filesAndFolders=ko.dependentObservable(function(){var style=self.listStyle();if(style==="folders_files"||style==="files_folders"){var files=self.filesOnlyList();var folders=self.foldersOnlyList();if(style==="folders_files"){return folders.concat(files);}else{return files.concat(folders);}}else{return self.listHelper.paginatedItems();}});self.isLoadActionPossible=ko.pureComputed(function(){return(self.loginState.hasPermission(self.access.permissions.FILES_SELECT)&&self.isOperational()&&!self.isPrinting()&&!self.isPaused()&&!self.isLoading());});self.isLoadAndPrintActionPossible=ko.pureComputed(function(){return(self.loginState.hasPermission(self.access.permissions.PRINT)&&self.isOperational()&&self.isLoadActionPossible());});self.highlightCurrentFile=function(){self.highlightFile(self.selectedFile);};self.highlightFile=function(file){if(!file||!file.origin||!file.path){self.listHelper.selectNone();return;}
var result=self.listHelper.selectItem(function(item){if(item.origin!==file.origin)return false;if(item.type==="folder"){return _.startsWith(file.path,item.path+"/");}else{return item.path===file.path;}});if(!result){if(log.getLevel()<=log.levels.DEBUG){log.info("Couldn't find file "+
file.origin+":"+
file.path+" in current items, not selecting");}
self.listHelper.selectNone();}};self.fromCurrentData=function(data){self._processStateData(data.state);self._processJobData(data.job);};self.fromHistoryData=function(data){self._processStateData(data.state);self._processJobData(data.job);};self._processStateData=function(data){self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);self.isSdReady(data.flags.sdReady);};self._processJobData=function(data){if(!data)return;if(self.selectedFile&&self.file&&self.selectedFile.origin===data.file.origin&&self.selectedFile.path===data.file.path)
return;self.selectedFile=data.file;self.highlightFile(data.file);};self._otherRequestInProgress=undefined;self._filesToFocus=[];self._switchToPath=undefined;self.requestData=function(params){if(!self.loginState.hasPermission(self.access.permissions.FILES_LIST)){return;}
var focus,switchToPath,force;if(_.isObject(params)){focus=params.focus;switchToPath=params.switchToPath;force=params.force;}else if(arguments.length){log.warn("FilesViewModel.requestData called with old argument list. That is deprecated, please use parameter object instead.");if(arguments.length>=1){if(arguments.length>=2){focus={location:arguments[1],path:arguments[0]};}else{focus={location:"local",path:arguments[0]};}}
if(arguments.length>=3){switchToPath=arguments[2];}
if(arguments.length>=4){force=arguments[3];}}
self._filesToFocus=self._filesToFocus||focus;self._switchToPath=self._switchToPath||switchToPath;if(self._otherRequestInProgress!==undefined){return self._otherRequestInProgress;}
return(self._otherRequestInProgress=OctoPrint.files.list(true,force).done(function(response){self.fromResponse(response,{focus:self._filesToFocus,switchToPath:self._switchToPath});}).fail(function(){self.allItems(undefined);self.listHelper.updateItems([]);}).always(function(){self._otherRequestInProgress=undefined;self._filesToFocus=[];self._switchToPath=undefined;}));};self.fromResponse=function(response,params){var focus=[];var switchToPath;if(_.isObject(params)){focus=params.focus||undefined;switchToPath=params.switchToPath||undefined;}else if(arguments.length>1){log.warn("FilesViewModel.fromResponse called with old argument list. That is deprecated, please use parameter object instead.");if(arguments.length>2){focus={location:arguments[2],path:arguments[1]};}else{focus={location:"local",path:arguments[1]};}
if(arguments.length>3){switchToPath=arguments[3]||undefined;}}
var files=response.files;self.allItems(files);var createFolderList=function(entries){var result=[];_.each(entries,function(entry){if(entry.type!=="folder")return;result.push("/"+entry.path);if(entry.children){result=result.concat(createFolderList(entry.children));}});return result;};const folders=createFolderList(files);folders.sort();self.folderList(["/"].concat(folders));var nonrecursive=false;_.each(files,function(file){if(file.type==="folder"&&file.children===undefined){nonrecursive=true;}});if(nonrecursive){log.error("At least one folder doesn't have a 'children' element defined. That means the file list request "+"wasn't actually made with 'recursive=true' in the query.\n\n"+"This can happen on wrong reverse proxy configs that "+"swallow up query parameters, see https://github.com/OctoPrint/OctoPrint/issues/2572");}
if(!switchToPath){var currentPath=self.currentPath();if(currentPath===undefined){self.listHelper.updateItems(files);self.currentPath("");}else{self.changeFolderByPath(currentPath);}}else{self.changeFolderByPath(switchToPath);}
if(focus.length){_.each(focus,function(focusItem,index){var entryElement=self.getEntryElement({path:focusItem.path,origin:focusItem.location});if(entryElement){if(index+1===focus.length){self.listElement.scrollTop(entryElement.offsetTop);}
var element=$(entryElement);element.on("webkitAnimationEnd oanimationend msAnimationEnd animationend",function(e){element.removeClass("highlight");});element.addClass("highlight");}});}
if(response.free!==undefined){self.freeSpace(response.free);}
if(response.total!==undefined){self.totalSpace(response.total);}
self.highlightCurrentFile();};self.changeFolder=function(data){if(data.children===undefined){log.error("Can't switch to folder '"+data.path+"', no children available");return;}
self.currentPath(data.path);self.listHelper.updateItems(data.children);self.highlightCurrentFile();};self.navigateUp=function(){var path=self.currentPath().split("/");path.pop();self.changeFolderByPath(path.join("/"));};self.changeFolderByPath=function(path){var element=self.elementByPath(path);if(element){self.currentPath(path);self.listHelper.updateItems(element.children);}else{self.currentPath("");self.listHelper.updateItems(self.allItems());}
self.highlightCurrentFile();};self.showAddFolderDialog=function(){if(!self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD))
return;if(self.addFolderDialog){self.addFolderName("");self.addFolderDialog.modal("show");}};self.addFolder=function(){if(!self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD))
return;var name=self.addFolderName();var location="local";self.ignoreUpdatedFilesEvent=true;self.addingFolder(true);OctoPrint.files.createFolder(location,name,self.currentPath()).done(function(data){self.requestData({focus:{path:data.folder.name,location:data.folder.origin}}).done(function(){self.addFolderDialog.modal("hide");}).always(function(){self.addingFolder(false);});}).fail(function(){self.addingFolder(false);}).always(function(){self.ignoreUpdatedFilesEvent=false;});};self.removeFolder=function(folder,event){if(!self.loginState.hasPermission(self.access.permissions.FILES_DELETE))
return;if(!folder){return;}
if(folder.type!=="folder"){return;}
if(folder.weight>0){var options={message:_.sprintf(gettext('You are about to delete the folder "%(folder)s" which still contains files and/or sub folders.'),{folder:_.escape(folder.name)}),onproceed:function(){self._removeEntry(folder,event);}};showConfirmationDialog(options);}else{self._removeEntry(folder,event);}};self.loadFile=function(data,printAfterLoad){if(!self.loginState.hasPermission(self.access.permissions.FILES_SELECT))
return;if(!data){return;}
var proceed=function(p){var prevented=false;var callback=function(){OctoPrint.files.select(data.origin,data.path,p);};if(p){callViewModels(self.allViewModels,"onBeforePrintStart",function(method){prevented=prevented||method(callback)===false;});}
if(!prevented){callback();}};if(printAfterLoad&&self.listHelper.isSelectedByMatcher(function(item){return item&&item.origin===data.origin&&item.path===data.path;})&&self.enablePrint(data)){self.printerState.print();}else{var withinPrintDimensions=self.evaluatePrintDimensions(data,true);var print=printAfterLoad&&withinPrintDimensions;if(print&&self.settingsViewModel.feature_printStartConfirmation()){showConfirmationDialog({message:gettext("This will start a new print job. Please check that the print bed is clear."),question:gettext("Do you want to start the print job now?"),cancel:gettext("No"),proceed:gettext("Yes"),onproceed:function(){proceed(print);},nofade:true});}else{proceed(print);}}};self.showMoveDialog=function(entry,event){if(!self.loginState.hasAllPermissions(self.access.permissions.FILES_UPLOAD,self.access.permissions.FILES_DELETE)){return;}
if(!entry){return;}
if(entry.origin!=="local"){return;}
if(!self.moveDialog){return;}
var slashPos=entry.path.lastIndexOf("/");var current;if(slashPos>=0){current="/"+entry.path.substr(0,slashPos);}else{current="/";}
self.moveEntry(entry);self.moveError("");self.moveSource(current);self.moveDestination(current);self.moveSourceFilename(entry.name);self.moveDestinationFilename(entry.name);self.moveDialog.modal("show");};self.removeFile=function(file,event){if(!self.loginState.hasPermission(self.access.permissions.FILES_DELETE))
return;if(!file){return;}
if(file.type==="folder"){return;}
self._removeEntry(file,event);};self.sliceFile=function(file){if(!self.loginState.hasPermission(self.access.permissions.SLICE))return;if(!file){return;}
self.slicing.show(file.origin,file.path,true,undefined,{display:file.display});};self.initSdCard=function(){if(!self.loginState.hasPermission(self.access.permissions.CONTROL))return;OctoPrint.printer.initSd();};self.releaseSdCard=function(){if(!self.loginState.hasPermission(self.access.permissions.CONTROL))return;OctoPrint.printer.releaseSd();};self.refreshSdFiles=function(){if(!self.loginState.hasPermission(self.access.permissions.CONTROL))return;OctoPrint.printer.refreshSd();};self.moveFileOrFolder=function(source,destination){self.movingFileOrFolder(true);return OctoPrint.files.move("local",source,destination).done(function(){self.requestData().done(function(){self.moveDialog.modal("hide");}).always(function(){self.movingFileOrFolder(false);});}).fail(function(){self.moveError(gettext("Unable to move file or folder")+" "+
self.moveEntry().display+" "+
gettext("to")+" "+
self.moveDestination());self.movingFileOrFolder(false);});};self._removeEntry=function(entry,event){self.activeRemovals.push(entry.origin+":"+entry.path);var finishActiveRemoval=function(){self.activeRemovals(_.filter(self.activeRemovals(),function(e){return e!==entry.origin+":"+entry.path;}));};var activateSpinner=function(){},finishSpinner=function(){};if(event){var element=$(event.currentTarget);if(element.length){var icon=$("i.fa-trash-alt",element);if(icon.length){activateSpinner=function(){icon.removeClass("far fa-trash-alt").addClass("fas fa-spinner fa-spin");};finishSpinner=function(){icon.removeClass("fas fa-spinner fa-spin").addClass("far fa-trash-alt");};}}}
activateSpinner();var deferred=$.Deferred();OctoPrint.files.delete(entry.origin,entry.path).done(function(){self.requestData().done(function(){deferred.resolve();}).fail(function(){deferred.reject();});}).fail(function(data){deferred.reject();var error="<p>"+
gettext("Could not remove entry. Please check octoprint.log for possible reasons.")+"</p>";if(data.responseJSON&&data.responseJSON.error){error+=pnotifyAdditionalInfo("<pre>"+_.escape(data.responseJSON.error)+"</pre>");}
new PNotify({title:gettext("Failed to remove entry"),text:error,type:"error",hide:false});});return deferred.promise().always(function(){finishActiveRemoval();finishSpinner();});};self.downloadLink=function(data){if(data["refs"]&&data["refs"]["download"]){return data["refs"]["download"];}else{return false;}};self.lastTimePrinted=function(data){if(data["prints"]&&data["prints"]["last"]&&data["prints"]["last"]["date"]){return data["prints"]["last"]["date"];}else{return"-";}};self.getSuccessClass=function(data){if(!data["prints"]||!data["prints"]["last"]){return"";}
return data["prints"]["last"]["success"]?"text-success":"text-error";};self.templateFor=function(data){return"files_template_"+data.type;};self.getEntryId=function(data){return"gcode_file_"+md5(data["origin"]+":"+data["path"]);};self.getEntryElement=function(data){var entryId=self.getEntryId(data);var entryElements=$("#"+entryId);if(entryElements&&entryElements[0]){return entryElements[0];}else{return undefined;}};self.enableRemove=function(data){if(_.contains(self.activeRemovals(),data.origin+":"+data.path)){return false;}
var busy=false;if(data.type==="folder"){busy=_.any(self.printerState.busyFiles(),function(name){return _.startsWith(name,data.origin+":"+data.path+"/");});}else{busy=_.contains(self.printerState.busyFiles(),data.origin+":"+data.path);}
return(self.loginState.hasPermission(self.access.permissions.FILES_DELETE)&&!busy);};self.enableMove=function(data){return(self.loginState.hasAllPermissions(self.access.permissions.FILES_UPLOAD,self.access.permissions.FILES_DELETE)&&data.origin==="local");};self.enableSelect=function(data){return(self.isLoadAndPrintActionPossible()&&!self.listHelper.isSelected(data));};self.enablePrint=function(data){return(self.loginState.hasPermission(self.access.permissions.PRINT)&&self.isOperational()&&!(self.isPrinting()||self.isPaused()||self.isLoading()));};self.enableSelectAndPrint=function(data,printAfterSelect){return self.isLoadAndPrintActionPossible();};self.enableSlicing=function(data){return(self.loginState.hasPermission(self.access.permissions.SLICE)&&self.slicing.enableSlicingDialog()&&self.slicing.enableSlicingDialogForFile(data.name));};self.enableAdditionalData=function(data){return data["gcodeAnalysis"]||(data["prints"]&&data["prints"]["last"]);};self.toggleAdditionalData=function(data){var entryElement=self.getEntryElement(data);if(!entryElement)return;var additionalInfo=$(".additionalInfo",entryElement);additionalInfo.slideToggle("fast",function(){$(".toggleAdditionalData i",entryElement).toggleClass("fa-chevron-down fa-chevron-up");});};self.getAdditionalData=function(data){var output="";if(data["gcodeAnalysis"]){if(data["gcodeAnalysis"]["_empty"]||!data["gcodeAnalysis"]["dimensions"]||(data["gcodeAnalysis"]["dimensions"]["width"]===0&&data["gcodeAnalysis"]["dimensions"]["depth"]===0&&data["gcodeAnalysis"]["dimensions"]["height"]===0)){output+=gettext("Model contains no extrusion.<br>");}else{if(data["gcodeAnalysis"]["dimensions"]){var dimensions=data["gcodeAnalysis"]["dimensions"];output+=gettext("Model size")+": "+
_.sprintf("%(width).2fmm (X) &times; %(depth).2fmm (Y) &times; %(height).2fmm (Z)",dimensions);output+="<br>";}
if(data["gcodeAnalysis"]["filament"]&&typeof data["gcodeAnalysis"]["filament"]==="object"){var filament=data["gcodeAnalysis"]["filament"];if(_.keys(filament).length===1){output+=gettext("Filament")+": "+
formatFilament(data["gcodeAnalysis"]["filament"]["tool"+0])+"<br>";}else if(_.keys(filament).length>1){_.each(filament,function(f,k){if(!_.startsWith(k,"tool")||!f||!f.hasOwnProperty("length")||f["length"]<=0)
return;output+=gettext("Filament")+" ("+
gettext("Tool")+" "+
k.substr("tool".length)+"): "+
formatFilament(f)+"<br>";});}}
output+=gettext("Estimated print time")+": "+
(self.settingsViewModel.appearance_fuzzyTimes()?formatFuzzyPrintTime(data["gcodeAnalysis"]["estimatedPrintTime"]):formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]))+"<br>";}}
if(data["prints"]&&data["prints"]["last"]){output+=gettext("Last printed")+": "+
formatTimeAgo(data["prints"]["last"]["date"])+"<br>";if(data["prints"]["last"]["printTime"]){output+=gettext("Last print time")+": "+
formatDuration(data["prints"]["last"]["printTime"]);}}
return output;};self.evaluatePrintDimensions=function(data,notify){if(!self.settingsViewModel.feature_modelSizeDetection()){return true;}
var analysis=data["gcodeAnalysis"];if(!analysis){return true;}
var printingArea=data["gcodeAnalysis"]["printingArea"];if(!printingArea){return true;}
var travelArea=data["gcodeAnalysis"]["travelArea"];if(!travelArea){return true;}
var printerProfile=self.printerProfiles.currentProfileData();if(!printerProfile){return true;}
var volumeInfo=printerProfile.volume;if(!volumeInfo){return true;}
var boundaries;if(_.isPlainObject(volumeInfo.custom_box)){boundaries={minX:volumeInfo.custom_box.x_min(),minY:volumeInfo.custom_box.y_min(),minZ:volumeInfo.custom_box.z_min(),maxX:volumeInfo.custom_box.x_max(),maxY:volumeInfo.custom_box.y_max(),maxZ:volumeInfo.custom_box.z_max()};}else{boundaries={minX:0,maxX:volumeInfo.width(),minY:0,maxY:volumeInfo.depth(),minZ:0,maxZ:volumeInfo.height()};if(volumeInfo.origin()==="center"){boundaries["maxX"]=volumeInfo.width()/2;boundaries["minX"]=-1*boundaries["maxX"];boundaries["maxY"]=volumeInfo.depth()/2;boundaries["minY"]=-1*boundaries["maxY"];}}
var info="";var objectFits=true;var travelFits=true;function _area_exceeds_boundaries(ax,area){return(area["min"+ax]<boundaries["min"+ax]||area["max"+ax]>boundaries["max"+ax]);}
function _exceed_warning(culprit,dimension){return _.sprintf(gettext("%(culprit)s exceeds print volume in %(dimension)s.<br>"),{culprit:culprit,dimension:dimension});}
if(_area_exceeds_boundaries("X",printingArea)){info+=_exceed_warning(gettext("Object"),gettext("width"));objectFits=false;}
if(_area_exceeds_boundaries("Y",printingArea)){info+=_exceed_warning(gettext("Object"),gettext("depth"));objectFits=false;}
if(_area_exceeds_boundaries("Z",printingArea)){info+=_exceed_warning(gettext("Object"),gettext("height"));objectFits=false;}
if(_area_exceeds_boundaries("X",travelArea)){info+=_exceed_warning(gettext("Travel"),gettext("width"));travelFits=false;}
if(_area_exceeds_boundaries("Y",travelArea)){info+=_exceed_warning(gettext("Travel"),gettext("depth"));travelFits=false;}
if(_area_exceeds_boundaries("Z",travelArea)){info+=_exceed_warning(gettext("Travel"),gettext("height"));travelFits=false;}
if(travelFits&&objectFits){return true;}else{if(notify){var formatData={name:_.escape(data.name),profile:boundaries,object:printingArea,travel:travelArea,culprit:!objectFits?"Object":"Travel area"};info+=_.sprintf(gettext("Travel area: (%(travel.minX).2f, %(travel.minY).2f, %(travel.minZ).2f) &times; (%(travel.maxX).2f, %(travel.maxY).2f, %(travel.maxZ).2f)"),formatData);info+="<br>";info+=_.sprintf(gettext("Object's bounding box: (%(object.minX).2f, %(object.minY).2f, %(object.minZ).2f) &times; (%(object.maxX).2f, %(object.maxY).2f, %(object.maxZ).2f)"),formatData);info+="<br>";info+=_.sprintf(gettext("Print volume: (%(profile.minX).2f, %(profile.minY).2f, %(profile.minZ).2f) &times; (%(profile.maxX).2f, %(profile.maxY).2f, %(profile.maxZ).2f)"),formatData);var warning="<p>"+
_.sprintf(gettext("%(culprit)s in %(name)s exceeds the print volume of the currently selected printer profile, be careful when printing this."),formatData)+"</p>";warning+=pnotifyAdditionalInfo(info);warning+='<p><small>You can disable this check via Settings &gt; Features &gt; "Enable model size detection [...]"</small></p>';new PNotify({title:_.sprintf(gettext("%(culprit)s exceeds print volume"),formatData),text:warning,type:"warning",hide:false});}
return false;}};self.clearSearchQuery=function(){self.searchQuery("");};self.performSearch=function(e){var query=self.searchQuery();if(query!==undefined&&query.trim()!==""){query=query.toLocaleLowerCase();var recursiveSearch=function(entry){if(entry===undefined){return false;}
var success=(entry["display"]&&entry["display"].toLocaleLowerCase().indexOf(query)>-1)||entry["name"].toLocaleLowerCase().indexOf(query)>-1;if(!success&&entry["type"]==="folder"&&entry["children"]){return _.any(entry["children"],recursiveSearch);}
return success;};self.listHelper.changeSearchFunction(recursiveSearch);}else{self.listHelper.resetSearch();}
return false;};self.elementByPath=function(path,root){root=root||{children:self.allItems()};var recursiveSearch=function(location,element){if(location.length===0){return element;}
if(!element.hasOwnProperty("children")||!element.children){return undefined;}
var name=location.shift();for(var i=0;i<element.children.length;i++){if(name===element.children[i].name){return recursiveSearch(location,element.children[i]);}}
return undefined;};return recursiveSearch(path.split("/"),root);};self.updateButtons=function(){if(self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD)){self.uploadButton.fileupload("enable");if(self.uploadSdButton){self.uploadSdButton.fileupload("enable");}}else{self.uploadButton.fileupload("disable");if(self.uploadSdButton){self.uploadSdButton.fileupload("disable");}}};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.updateButtons();self.requestData();self._fromLocalStorage();};self.onStartup=function(){$(".accordion-toggle[data-target='#files']").click(function(){var files=$("#files");if(files.hasClass("in")){files.removeClass("overflow_visible");self.filesListVisible(false);}else{setTimeout(function(){files.addClass("overflow_visible");self.filesListVisible(true);},100);}});self.listElement=$("#files").find(".scroll-wrapper");self.moveDialog=$("#move_file_or_folder_dialog");self.addFolderDialog=$("#add_folder_dialog");self.addFolderDialog.on("shown",function(){$("input",self.addFolderDialog).focus();});$("form",self.addFolderDialog).on("submit",function(e){e.preventDefault();if(self.enableAddFolder()){self.addFolder();}});self.uploadExistsDialog=$("#upload_exists_dialog");self.uploadExistsDialog.on("shown",()=>{self._uploadExistsOpen=true;});self.uploadExistsDialog.on("hidden",()=>{self._uploadExistsOpen=false;});self.uploadButton=$("#gcode_upload");self.uploadSdButton=$("#gcode_upload_sd");if(!self.uploadSdButton.length){self.uploadSdButton=undefined;}
self.uploadProgress=$("#gcode_upload_progress");self.uploadProgressBar=$(".bar",self.uploadProgress);self.dropOverlay=$("#drop_overlay");self.dropZone=$("#drop");self.dropZoneLocal=$("#drop_locally");self.dropZoneSd=$("#drop_sd");self.dropZoneBackground=$("#drop_background");self.dropZoneLocalBackground=$("#drop_locally_background");self.dropZoneSdBackground=$("#drop_sd_background");if(CONFIG_SD_SUPPORT){self.localTarget=self.dropZoneLocal;}else{self.localTarget=self.dropZone;self.listHelper.removeFilter("sd");}
self.sdTarget=self.dropZoneSd;self.dropOverlay.on("drop",self._forceEndDragNDrop);function evaluateDropzones(){var enableLocal=self.loginState.hasPermission(self.access.permissions.FILES_UPLOAD);var enableSd=enableLocal&&CONFIG_SD_SUPPORT&&self.printerState.isSdReady()&&!self.isPrinting();self._setDropzone("local",enableLocal);self._setDropzone("sdcard",enableSd);}
self.loginState.currentUser.subscribe(evaluateDropzones);self.printerState.isSdReady.subscribe(evaluateDropzones);self.isPrinting.subscribe(evaluateDropzones);evaluateDropzones();};self.onEventUpdatedFiles=function(payload){if(self.ignoreUpdatedFilesEvent){return;}
if(payload.type!=="printables"){return;}
self.requestData();};self.onEventSlicingStarted=function(payload){self.uploadProgress.addClass("progress-striped").addClass("active");self.uploadProgressBar.css("width","100%");if(payload.progressAvailable){self.uploadProgressPercentage(0);self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"),{percentage:0}));}else{self.uploadProgressText(gettext("Slicing ..."));}};self.onSlicingProgress=function(slicer,modelPath,machinecodePath,progress){self.uploadProgressText(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"),{percentage:Math.round(progress)}));self.uploadProgressPercentage(Math.round(progress));};self.onEventSlicingCancelled=function(payload){self.uploadProgress.removeClass("progress-striped").removeClass("active");self.uploadProgressBar.css("width","0%");self.uploadProgressText("");self.uploadProgressPercentage(0);};self.onEventSlicingDone=function(payload){self.uploadProgress.removeClass("progress-striped").removeClass("active");self.uploadProgressBar.css("width","0%");self.uploadProgressText("");self.uploadProgressPercentage(0);new PNotify({title:gettext("Slicing done"),text:_.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"),{stl:_.escape(payload.stl),gcode:_.escape(payload.gcode),time:payload.time}),type:"success"});self.requestData();};self.onEventSlicingFailed=function(payload){self.uploadProgress.removeClass("progress-striped").removeClass("active");self.uploadProgressBar.css("width","0%");self.uploadProgressText("");self.uploadProgressPercentage(0);var html=_.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"),{stl:_.escape(payload.stl),gcode:_.escape(payload.gcode),reason:_.escape(payload.reason)});new PNotify({title:gettext("Slicing failed"),text:html,type:"error",hide:false});};self.onEventMetadataAnalysisFinished=function(payload){self.requestData();};self.onEventMetadataStatisticsUpdated=function(payload){self.requestData();};self.onEventTransferStarted=function(payload){self.uploadProgress.addClass("progress-striped").addClass("active");self.uploadProgressBar.css("width","100%");self.uploadProgressPercentage(100);self.uploadProgressText(gettext("Streaming ..."));};self.onEventTransferDone=function(payload){self.uploadProgress.removeClass("progress-striped").removeClass("active");self.uploadProgressBar.css("width","0");self.uploadProgressText("");self.uploadProgressPercentage(0);new PNotify({title:gettext("Streaming done"),text:_.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"),{local:_.escape(payload.local),remote:_.escape(payload.remote),time:payload.time}),type:"success"});self.requestData({focus:{location:"sdcard",path:payload.remote}});};self.onEventTransferFailed=function(payload){self.uploadProgress.removeClass("progress-striped").removeClass("active");self.uploadProgressBar.css("width","0");self.uploadProgressText("");self.uploadProgressPercentage(0);new PNotify({title:gettext("Streaming failed"),text:_.sprintf(gettext("Did not finish streaming %(local)s to %(remote)s on SD"),{local:_.escape(payload.local),remote:_.escape(payload.remote)}),type:"error"});self.requestData();};self._setDropzone=function(dropzone,enable){var button=dropzone==="local"?self.uploadButton:self.uploadSdButton;var drop=dropzone==="local"?self.localTarget:self.sdTarget;var url=API_BASEURL+"files/"+dropzone;if(button===undefined)return;button.fileupload({url:url,dataType:"json",dropZone:enable?drop:null,sequentialUploads:true,drop:function(e,data){},add:self._handleUploadAdd,submit:self._handleUploadStart,done:self._handleUploadDone,fail:self._handleUploadFail,stop:self._handleUploadStop,progressall:self._handleUploadProgress});};self._dragNDropEnabled=false;self._enableDragNDrop=()=>{if(!self.settingsViewModel.feature_enableDragDropUpload())return;if(self._dragNDropEnabled)return;self._dragNDropEnabled=true;$(document).bind("dragenter",self._handleDragEnter);$(document).bind("dragleave",self._handleDragLeave);log.debug("Enabled drag-n-drop");};self._disableDragNDrop=()=>{if(!self._dragNDropEnabled)return;self._dragNDropEnabled=false;$(document).unbind("dragenter",self._handleDragEnter);$(document).unbind("dragleave",self._handleDragLeave);log.debug("Disabled drag-n-drop");};self._setProgressBar=function(percentage,text,active){self.uploadProgressBar.css("width",percentage+"%");self.uploadProgressText(text);self.uploadProgressPercentage(percentage);if(active){self.uploadProgress.addClass("progress-striped active");}else{self.uploadProgress.removeClass("progress-striped active");}};self._uploadExistsQueue=[];self._uploadExistsOpen=false;self._processUploadQueue=function(){if(!self._uploadExistsQueue.length>0||self._uploadExistsOpen)return;const hideAndSubmit=function(data){self.uploadExistsDialog.modal("hide");data.submit();if(self._uploadExistsQueue.length>0){self._processUploadQueue();}};const{data,response,path,fileSizeTooBig}=self._uploadExistsQueue.shift();const file=data.files[0];const formData={};if(path!==""){formData.path=path;}
$("h3",self.uploadExistsDialog).text(_.sprintf(gettext("File already exists: %(name)s"),{name:file.name}));$("span.existing_size",self.uploadExistsDialog).text(response.size?formatSize(response.size):"unknown");$("span.existing_date",self.uploadExistsDialog).text(response.date?new Date(response.date*1000).toLocaleString():"unknown");$("span.new_size",self.uploadExistsDialog).text(formatSize(file.size));$("span.new_date",self.uploadExistsDialog).text(new Date(file.lastModified).toLocaleString());$("p, form, .file_data",self.uploadExistsDialog).toggle(!fileSizeTooBig);$("span.not_enough_space",self.uploadExistsDialog).toggle(fileSizeTooBig);$("input",self.uploadExistsDialog).val("").prop("placeholder",response.suggestion);$("a.upload-rename",self.uploadExistsDialog).toggle(!fileSizeTooBig).prop("disabled",false).off("click").on("click",function(){var newName=$("input",self.uploadExistsDialog).val();if(newName==="")newName=response.suggestion;OctoPrint.files.exists("local",path,newName).done(function(r){if(r.exists){$(".control-group",self.uploadExistsDialog).addClass("error");$(".help-block",self.uploadExistsDialog).show();}else{$(".control-group",self.uploadExistsDialog).removeClass("error");$(".help-block",self.uploadExistsDialog).hide();formData.filename=newName;formData.noOverwrite=true;data.formData=formData;hideAndSubmit(data);}});});if(self.loginState.hasPermission(self.access.permissions.FILES_DELETE)){$("a.upload-overwrite",self.uploadExistsDialog).off("click").show().on("click",function(){data.formData=formData;hideAndSubmit(data);});}else{$("a.upload-overwrite",self.uploadExistsDialog).hide();}
self.uploadExistsDialog.modal("show");};self._handleUploadAdd=function(e,data){var file=data.files[0];var path=self.currentPath();var fileSizeTooBig=file.size>self.freeSpace();var formData={};if(path!==""){formData.path=path;}
if(self.settingsViewModel.feature_uploadOverwriteConfirmation()){OctoPrint.files.exists("local",path,file.name).done(function(response){if(response.exists){const queueEntry={data,response,path,fileSizeTooBig};self._uploadExistsQueue.push(queueEntry);self._processUploadQueue();}else{data.formData=formData;data.submit();}});}else{if(fileSizeTooBig){var error="<p>"+
gettext("Could not upload the file. There is not enough disk space remaining.")+"</p>";error+="<pre>"+
_.sprintf(gettext("Free Space: %(freespace)s"),{freespace:self.freeSpaceString()})+"<br>"+
_.sprintf(gettext("File Size: %(filesize)s"),{filesize:formatSize(file.size)})+"</pre>";new PNotify({title:"Upload failed",text:error,type:"error",hide:false});}else{data.formData=formData;data.submit();}}};self._handleUploadStart=function(e,data){self.ignoreUpdatedFilesEvent=true;return true;};self._handleUploadDone=function(e,data){var focus=undefined;if(data.result.files.hasOwnProperty("sdcard")){focus={location:"sdcard",path:data.result.files.sdcard.path};}else if(data.result.files.hasOwnProperty("local")){focus={location:"local",path:data.result.files.local.path};}
if(focus){self._filesToFocus.push(focus);}
if(focus&&_.endsWith(focus.path.toLowerCase(),".stl")){self.slicing.show(focus.location,focus.path);}};self._handleUploadStop=function(e,data){var reset=function(){self.ignoreUpdatedFilesEvent=false;self._setProgressBar(0,"",false);};if(self._filesToFocus.length>0){self._setProgressBar(100,gettext("Refreshing list ..."),true);self.requestData({focus:self._filesToFocus}).always(function(){reset();});}else{reset();}};self._handleUploadFail=function(e,data){var extensions=_.map(SUPPORTED_EXTENSIONS,function(extension){return extension.toLowerCase();}).sort();extensions=extensions.join(", ");var error="<p><pre>"+_.escape(data.files[0].name)+"</pre></p><p>";switch(data.jqXHR.status){case 409:if(e.target.id==="gcode_upload_sd"){error+=gettext("Could not upload the file to the printer's SD. Make sure the SD is initialized and the printer is not busy with a print already.");}else{error+=gettext("Could not upload the file, overwrite not possible. Make sure it is not already printing and that you have allowed overwriting.");}
break;case 415:error+=_.sprintf(gettext("Could not upload the file. Make sure that it is a readable, valid file with one of these extensions: %(extensions)s"),{extensions:_.escape(extensions)});break;default:error+=gettext("Could not upload the file. Please check octoprint.log for possible reasons.");break;}
error+="</p>";if(data.jqXHR.responseJSON&&data.jqXHR.responseJSON.error){error+=pnotifyAdditionalInfo("<pre>"+_.escape(data.jqXHR.responseJSON.error)+"</pre>");}
new PNotify({title:"Upload failed",text:error,type:"error",hide:false});};self._handleUploadProgress=function(e,data){var progress=parseInt((data.loaded/data.total)*100,10);var uploaded=progress>=100;self._setProgressBar(progress,uploaded?gettext("Saving ..."):gettext("Uploading ..."),uploaded);};self._dragNDropTarget=null;self._dragNDropFFTimeout=undefined;self._dragNDropFFTimeoutDelay=100;self._forceEndDragNDrop=function(){self.dropOverlay.removeClass("in");if(self.dropZoneLocal)self.dropZoneLocalBackground.removeClass("hover");if(self.dropZoneSd)self.dropZoneSdBackground.removeClass("hover");if(self.dropZone)self.dropZoneBackground.removeClass("hover");self._dragNDropTarget=null;};self._handleDragLeave=function(e){if(e.target!==self._dragNDropTarget)return;self._forceEndDragNDrop();};self._handleDragEnter=function(e){if(!self.settingsViewModel.feature_enableDragDropUpload()){return;}
const draggedFiles=Array.from(e.originalEvent.dataTransfer.items).filter((item)=>item.kind==="file");if(!draggedFiles.length){return;}
self.dropOverlay.addClass("in");var foundLocal=false;var foundSd=false;var found=false;var node=e.target;do{if(self.dropZoneLocal&&node===self.dropZoneLocal[0]){foundLocal=true;break;}else if(self.dropZoneSd&&node===self.dropZoneSd[0]){foundSd=true;break;}else if(self.dropZone&&node===self.dropZone[0]){found=true;break;}
node=node.parentNode;}while(node!==null);if(foundLocal){self.dropZoneLocalBackground.addClass("hover");self.dropZoneSdBackground.removeClass("hover");}else if(foundSd&&self.printerState.isSdReady()&&!self.isPrinting()){self.dropZoneSdBackground.addClass("hover");self.dropZoneLocalBackground.removeClass("hover");}else if(found){self.dropZoneBackground.addClass("hover");}else{if(self.dropZoneLocalBackground)
self.dropZoneLocalBackground.removeClass("hover");if(self.dropZoneSdBackground)
self.dropZoneSdBackground.removeClass("hover");if(self.dropZoneBackground)self.dropZoneBackground.removeClass("hover");}
self._dragNDropTarget=e.target;self._dragNDropLastOver=Date.now();};self.onServerConnect=self.onServerReconnect=function(payload){self._enableDragNDrop();self.requestData();};self.onServerDisconnect=function(payload){self._disableDragNDrop();};self.onBeforeBinding=function(){self.showInternalFilename(self.settingsViewModel.settings.appearance.showInternalFilename());};self.onAllBound=function(allViewModels){self.allViewModels=allViewModels;};self.onStartupComplete=()=>{self.showInternalFilename(self.settingsViewModel.settings.appearance.showInternalFilename());self.settingsViewModel.settings.appearance.showInternalFilename.subscribe((value)=>{self.showInternalFilename(value);});self._enableDragNDrop();self.settingsViewModel.settings.feature.enableDragDropUpload.subscribe((value)=>{if(value){self._enableDragNDrop();}else{self._disableDragNDrop();}});};}
OCTOPRINT_VIEWMODELS.push({construct:FilesViewModel,name:"filesViewModel",additionalNames:["gcodeFilesViewModel"],dependencies:["settingsViewModel","loginStateViewModel","printerStateViewModel","slicingViewModel","printerProfilesViewModel","accessViewModel"],elements:["#files_wrapper","#add_folder_dialog","#move_file_or_folder_dialog","#upload_exists_dialog"]});});
;

// source: js/app/viewmodels/firstrun_wizard.js
$(function(){function FirstRunWizardViewModel(parameters){var self=this;self.dontPrintUnattendedAcknowledged=ko.observable(false);self.dontPortForwardAcknowledged=ko.observable(false);self.fundingRequestAcknowledged=ko.observable(false);self.error=ko.observable(false);self.acknowledgementNeeded=false;self.allAcknowledged=ko.pureComputed(function(){return(self.dontPrintUnattendedAcknowledged()&&self.dontPortForwardAcknowledged()&&self.fundingRequestAcknowledged());});self.onBeforeWizardTabChange=function(next,current){if(!self.acknowledgementNeeded){return true;}
if(!current||current!=="wizard_firstrun_end"||self.allAcknowledged()){return true;}
self._showAcknowledgementNeededDialog();return false;};self.onBeforeWizardFinish=function(){if(!self.acknowledgementNeeded||self.allAcknowledged()){return true;}
self._showAcknowledgementNeededDialog();return false;};self.onAfterBinding=function(){self.acknowledgementNeeded=document.getElementById("wizard_firstrun_end")!==null;};self._showAcknowledgementNeededDialog=function(){self.error(true);showMessageDialog({title:gettext("Please acknowledge the safety warnings and call for funding"),message:gettext("You haven't yet acknowledged all safety warnings and the call for funding. Please do so first.")});};}
OCTOPRINT_VIEWMODELS.push({construct:FirstRunWizardViewModel,elements:["#wizard_firstrun_start","#wizard_firstrun_end"]});});
;

// source: js/app/viewmodels/loginstate.js
$(function(){function LoginStateViewModel(parameters){var self=this;self.loginUser=ko.observable("");self.loginPass=ko.observable("");self.loginRemember=ko.observable(false);self.reauthenticateDialog=undefined;self.reauthenticatePass=ko.observable("");self.reauthenticateFailed=ko.observable(false);self.loggedIn=ko.observable(undefined);self.username=ko.observable(undefined);self.userneeds=ko.observable(undefined);self.isAdmin=ko.observable(false);self.isUser=ko.observable(false);self.allViewModels=undefined;self.startupDeferred=$.Deferred();self.currentUser=ko.observable(undefined);self.currentLoginMechanism=ko.observable(undefined);self.credentialsSeen=ko.observable(undefined);self.elementUsernameInput=undefined;self.elementPasswordInput=undefined;self.elementLoginButton=undefined;self.externalAddressNotification=undefined;self.userMenuText=ko.pureComputed(function(){if(self.loggedIn()){return self.username();}else{return gettext("Login");}});self.userMenuTitle=ko.pureComputed(function(){if(self.loggedIn()){return _.sprintf(gettext("Logged in as %(name)s"),{name:_.escape(self.username())});}else{return gettext("Login");}});self.logoutSupported=ko.pureComputed(function(){var mechanism=self.currentLoginMechanism();return!(mechanism==="apikey"||mechanism==="authheader"||mechanism==="remote_user");});self.logoutTooltip=ko.pureComputed(function(){var mechanism=self.currentLoginMechanism();if(!self.logoutSupported()){var methodMap={apikey:gettext("API key based login"),authheader:gettext("Authorization header based login"),remote_user:gettext("remote user based login")};return _.sprintf(gettext("Logout not supported for %(method)s, please close the browser instead"),{method:methodMap[mechanism]});}else{return gettext("Logout of OctoPrint");}});self.reloadUser=function(){if(self.currentUser()===undefined){return;}
return OctoPrint.access.users.get(self.currentUser().name).done(self.updateCurrentUserData);};self._reauthenticated=false;self.showReauthenticationDialog=()=>{const result=$.Deferred();self._reauthenticated=false;self.reauthenticateDialog.off("hidden");self.reauthenticateDialog.on("hidden",()=>{self.reauthenticatePass("");self.reauthenticateFailed(false);if(self._reauthenticated){result.resolve();}else{result.reject();}});self.reauthenticateDialog.modal("show");return result.promise();};self.reauthenticate=()=>{const user=self.currentUser().name;const pass=self.reauthenticatePass();return OctoPrint.browser.login(user,pass).done((response)=>{self.fromResponse(response);self.reauthenticateFailed(false);self._reauthenticated=self.credentialsSeen();$("#reauthenticate_dialog").modal("hide");}).fail((response)=>{self.reauthenticatePass("");self.reauthenticateFailed(true);});};self.reauthenticateIfNecessary=(callback)=>{if(!self.checkCredentialsSeen()){self.forceReauthentication(callback);}else{callback();}};self.forceReauthentication=(callback)=>{self.showReauthenticationDialog().done(()=>{callback();}).fail(()=>{});};self.checkCredentialsSeen=()=>{if(CONFIG_REAUTHENTICATION_TIMEOUT<=0)return true;const credentialsSeen=self.credentialsSeen();if(!credentialsSeen){return false;}
const now=new Date();const seen=new Date(credentialsSeen);return now-seen<CONFIG_REAUTHENTICATION_TIMEOUT*60*1000;};self.afterReauthenticationTimeout=(callback,timeout)=>{if(CONFIG_REAUTHENTICATION_TIMEOUT<=0)return;if(timeout)window.clearTimeout(timeout);return window.setTimeout(callback,(CONFIG_REAUTHENTICATION_TIMEOUT*60+10)*1000);};self.requestData=function(){return OctoPrint.browser.passiveLogin().done(self.fromResponse).fail(function(){self.fromResponse();});};self.fromResponse=function(response){var process=function(){var currentLoggedIn=self.loggedIn();var currentNeeds=self.userneeds();if(response&&response.name){self.loggedIn(true);self.currentLoginMechanism(response._login_mechanism);self.credentialsSeen(response._credentials_seen);self.updateCurrentUserData(response);if(!currentLoggedIn||currentLoggedIn===undefined){callViewModels(self.allViewModels,"onUserLoggedIn",[response]);log.info("User "+response.name+" logged in");}else if(!_.isEqual(currentNeeds,self.userneeds())){callViewModels(self.allViewModels,"onUserPermissionsChanged");log.info("User needs for "+response.name+" changed");}
if(response.session){OctoPrint.socket.sendAuth(response.name,response.session);}
var ignorePublicAddressWarning=localStorage["loginState.ignorePublicAddressWarning"];if(ignorePublicAddressWarning===undefined){ignorePublicAddressWarning=false;}else{ignorePublicAddressWarning=JSON.parse(ignorePublicAddressWarning);}
if(response._is_external_client&&!ignorePublicAddressWarning){var text=gettext("<p>It seems that you are connecting to OctoPrint over the public internet.</p>"+"<p>This is strongly discouraged unless you have taken proper network security precautions. "+"Your printer is an appliance you really should not be giving access to "+"everyone with an internet connection.</p><p><strong>Please see "+'<a href="%(url)s" target="_blank" rel="noreferrer noopener">this blog post</a> for '+"ways to safely access your OctoPrint instance from remote.</strong></p>"+"<p><small>If you know what you are doing or you are sure this message is "+"mistaken since you are in an isolated LAN, feel free to ignore it.</small></p>");text=_.sprintf(text,{url:"https://octoprint.org/blog/2018/09/03/safe-remote-access/"});if(self.externalAddressNotification!==undefined){self.externalAddressNotification.remove();}
self.externalAddressNotification=new PNotify({title:gettext("Possible external access detected"),text:text,hide:false,type:"error",confirm:{confirm:true,buttons:[{text:gettext("Ignore"),addClass:"btn btn-danger",click:function(notice){notice.remove();localStorage["loginState.ignorePublicAddressWarning"]=JSON.stringify(true);}},{text:gettext("Later"),addClass:"btn btn-primary",click:function(notice){notice.remove();}}]},buttons:{sticker:false}});}
if(response._login_mechanism){log.info("Login mechanism: "+response._login_mechanism);}}else{self.loggedIn(false);self.currentLoginMechanism(undefined);self.updateCurrentUserData(response);if(currentLoggedIn||currentLoggedIn===undefined){callViewModels(self.allViewModels,"onUserLoggedOut");log.info("User logged out");}else if(!_.isEqual(currentNeeds,self.userneeds())){callViewModels(self.allViewModels,"onUserPermissionsChanged");log.info("User needs for guest changed");}}
OctoPrint.coreui.updateTab();};if(self.startupDeferred!==undefined){self.startupDeferred.done(process);}else{process();}};self.updateCurrentUserData=function(data){if(data){self.userneeds(data.needs);}else{self.userneeds({});}
if(data&&data.name){self.username(data.name);self.currentUser(data);self.isUser(data.user);self.isAdmin(data.admin);}else{self.username(undefined);self.currentUser(undefined);self.isUser(false);self.isAdmin(false);}};self.login=function(u,p,r,notifications){var username=u||self.loginUser();var password=p||self.loginPass();var remember=r!==undefined?r:self.loginRemember();notifications=notifications!==false;return OctoPrint.browser.login(username,password,remember).done(function(response){if(notifications){new PNotify({title:gettext("Login successful"),text:_.sprintf(gettext('You are now logged in as "%(username)s"'),{username:_.escape(response.name)}),type:"success"});}
self.fromResponse(response);self.loginUser("");self.loginPass("");self.loginRemember(false);self.reauthenticatePass("");if(history&&history.replaceState){history.replaceState({success:true},document.title,window.location.pathname);}}).fail(function(response){if(!notifications){return;}
switch(response.status){case 403:{new PNotify({title:gettext("Login failed"),text:gettext("User unknown, wrong password or account deactivated"),type:"error"});break;}}});};var _logoutInProgress=false;self.logout=function(target,event){if(!self.logoutSupported()){event.stopPropagation();return;}
if(_logoutInProgress)return;_logoutInProgress=true;return OctoPrint.browser.logout().done(function(response){new PNotify({title:gettext("Logout successful"),text:gettext("You are now logged out"),type:"success"});self.fromResponse(response);}).fail(function(error){if(error&&error.status===403){self.fromResponse(false);}}).always(function(){_logoutInProgress=false;});};self.prepareLogin=function(data,event){if(event&&event.preventDefault){event.preventDefault();}
self.login();};self.onDataUpdaterReauthRequired=function(reason){if(reason==="logout"||reason==="stale"||reason==="removed"){self.logout();}else{self.requestData();}};self.onAllBound=function(allViewModels){self.allViewModels=allViewModels;self.startupDeferred.resolve();self.startupDeferred=undefined;};self.onStartup=function(){self.reauthenticateDialog=$("#reauthenticate_dialog");self.reauthenticateDialog.on("shown",function(){$("input[type=password]",self.reauthenticateDialog).focus();});self.elementUsernameInput=$("#login_user");self.elementPasswordInput=$("#login_pass");self.elementLoginButton=$("#login_button");var toggle=$("li.dropdown#navbar_login");var button=$("a",toggle);button.on("click",function(e){$(this).parent().toggleClass("open");});$("body").on("click",function(e){if(!toggle.hasClass("open")){return;}
var anyFormLinkOrButton=$("#login_dropdown_loggedout a, #login_dropdown_loggedin a, #login_dropdown_loggedout button, #login_dropdown_loggedin button");var dropdown=$("li.dropdown#navbar_login");var anyLastpassButton=$("#__lpform_login_user, #__lpform_login_pass");var isLinkOrButton=anyFormLinkOrButton.is(e.target)||anyFormLinkOrButton.has(e.target).length!==0;var isDropdown=dropdown.is(e.target)||dropdown.has(e.target).length!==0;var isLastpass=anyLastpassButton.is(e.target)||anyLastpassButton.has(e.target).length!==0;if(isLinkOrButton||!(isDropdown||isLastpass)){toggle.removeClass("open");}});if(self.elementUsernameInput&&self.elementUsernameInput.length&&self.elementLoginButton&&self.elementLoginButton.length){self.elementLoginButton.blur(function(){self.elementUsernameInput.focus();});}};self.hasPermission=function(permission){var userneeds=self.userneeds();if(userneeds===undefined||permission===undefined)return false;if($.isEmptyObject(userneeds)){return false;}
return _.any(permission,function(need){return(_.has(userneeds,need.method)&&_.all(need.value,function(value){return _.contains(userneeds[need.method],value);}));});};self.hasAnyPermission=function(){var result=false;_.each(arguments,function(permission){result=result||self.hasPermission(permission);});return result;};self.hasAllPermissions=function(){var result=true;_.each(arguments,function(permission){result=result&&self.hasPermission(permission);});return result;};self.hasPermissionKo=function(permission){return ko.pureComputed(function(){return self.hasPermission(permission);}).extend({notify:"always"});};self.hasAnyPermissionKo=function(){var permissions=arguments;return ko.pureComputed(function(){return self.hasAnyPermission.apply(null,permissions);}).extend({notify:"always"});};self.hasAllPermissionsKo=function(){var permissions=arguments;return ko.pureComputed(function(){return self.hasAllPermissions.apply(null,permissions);});};}
OCTOPRINT_VIEWMODELS.push({construct:LoginStateViewModel,elements:["#reauthenticate_dialog"]});});
;

// source: js/app/viewmodels/loginui.js
$(function(){function LoginUiViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.coreWizardAcl=parameters[2];self.onUserLoggedOut=self.onUserPermissionsChanged=function(){if(!self.loginState.hasAllPermissions(self.access.permissions.STATUS,self.access.permissions.SETTINGS_READ)&&(!CONFIG_FIRST_RUN||(self.coreWizardAcl&&self.coreWizardAcl.setup()))){location.reload();}};}
OCTOPRINT_VIEWMODELS.push({construct:LoginUiViewModel,dependencies:["loginStateViewModel","accessViewModel","coreWizardAclViewModel"],optional:["coreWizardAclViewModel"]});});
;

// source: js/app/viewmodels/navigation.js
$(function(){function NavigationViewModel(parameters){var self=this;self.loginState=parameters[0];self.appearance=parameters[1];self.settings=parameters[2];self.usersettings=parameters[3];self.system=parameters[4];self.access=parameters[5];self.offline=ko.observable(!ONLINE);self.offlinePopoverContent=function(){return("<p>"+
gettext("OctoPrint cannot reach the internet. If this is not "+"intentional, please check OctoPrint's network settings and "+"the connectivity check configuration. Updates, plugin repository "+"and anything else requiring access to the public internet will not "+"work.")+"</p>");};self.appearanceClasses=ko.pureComputed(function(){var classes=self.appearance.color();if(self.appearance.colorTransparent()){classes+=" transparent";}
return classes;});self.onServerReconnect=self.onServerConnect=self.onEventConnectivityChanged=function(){self.offline(!ONLINE);};}
OCTOPRINT_VIEWMODELS.push({construct:NavigationViewModel,dependencies:["loginStateViewModel","appearanceViewModel","settingsViewModel","userSettingsViewModel","systemViewModel","accessViewModel"],elements:["#navbar"]});});
;

// source: js/app/viewmodels/printerstate.js
$(function(){function PrinterStateViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.access=parameters[2];self.allViewModels=undefined;self.stateString=ko.observable(undefined);self.errorString=ko.observable(undefined);self.hasErrorString=ko.pureComputed(function(){return!!self.errorString();});self.resendCount=ko.observable(0);self.resendTotalTransmitted=ko.observable(0);self.resendRatio=ko.observable(0);self.resendRatioCritical=ko.pureComputed(function(){return(self.resendRatio()>=self.settings.serial_resendRatioThreshold()&&self.resendTotalTransmitted()>=self.settings.serial_resendRatioStart());});self.resendRatioNotification=undefined;self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isCancelling=ko.observable(undefined);self.isPausing=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.isSdReady=ko.observable(undefined);self.isBusy=ko.pureComputed(function(){return(self.isPrinting()||self.isCancelling()||self.isPausing()||self.isPaused());});self.enablePrint=ko.pureComputed(function(){return(self.isOperational()&&(self.isReady()||self.isPaused())&&!self.isPrinting()&&!self.isCancelling()&&!self.isPausing()&&self.loginState.hasPermission(self.access.permissions.PRINT)&&self.filename());});self.enablePause=ko.pureComputed(function(){return(self.isOperational()&&(self.isPrinting()||self.isPaused())&&!self.isCancelling()&&!self.isPausing()&&self.loginState.hasPermission(self.access.permissions.PRINT));});self.enableCancel=ko.pureComputed(function(){return(self.isOperational()&&(self.isPrinting()||self.isPaused())&&!self.isCancelling()&&!self.isPausing()&&self.loginState.loggedIn());});self.filename=ko.observable(undefined);self.filepath=ko.observable(undefined);self.filedisplay=ko.observable(undefined);self.filesize=ko.observable(undefined);self.filepos=ko.observable(undefined);self.filedate=ko.observable(undefined);self.progress=ko.observable(undefined);self.printTime=ko.observable(undefined);self.printTimeLeft=ko.observable(undefined);self.printTimeLeftOrigin=ko.observable(undefined);self.sd=ko.observable(undefined);self.timelapse=ko.observable(undefined);self.user=ko.observable(undefined);self.busyFiles=ko.observableArray([]);self.filament=ko.observableArray([]);self.estimatedPrintTime=ko.observable(undefined);self.lastPrintTime=ko.observable(undefined);self.currentHeight=ko.observable(undefined);self.errorInfoAvailable=ko.observable(false);self.errorInfo={};self.TITLE_PRINT_BUTTON_PAUSED=gettext("Restarts the print job from the beginning");self.TITLE_PRINT_BUTTON_UNPAUSED=gettext("Starts the print job");self.TITLE_PAUSE_BUTTON_PAUSED=gettext("Resumes the print job");self.TITLE_PAUSE_BUTTON_UNPAUSED=gettext("Pauses the print job");self.titlePrintButton=ko.observable(self.TITLE_PRINT_BUTTON_UNPAUSED);self.titlePauseButton=ko.observable(self.TITLE_PAUSE_BUTTON_UNPAUSED);var estimatedPrintTimeStringHlpr=function(fmt){if(self.lastPrintTime())return fmt(self.lastPrintTime());if(self.estimatedPrintTime())return fmt(self.estimatedPrintTime());return"-";};self.estimatedPrintTimeString=ko.pureComputed(function(){return estimatedPrintTimeStringHlpr(self.settings.appearance_fuzzyTimes()?formatFuzzyPrintTime:formatDuration);});self.estimatedPrintTimeExactString=ko.pureComputed(function(){return estimatedPrintTimeStringHlpr(formatDuration);});self.byteString=ko.pureComputed(function(){if(!self.filesize())return"-";var filepos=self.filepos()?formatSize(self.filepos()):"-";return filepos+" / "+formatSize(self.filesize());});self.heightString=ko.pureComputed(function(){if(!self.currentHeight())return"-";return _.sprintf("%.02fmm",self.currentHeight());});self.printTimeString=ko.pureComputed(function(){if(!self.printTime())return"-";return formatDuration(self.printTime());});var printTimeLeftStringHlpr=function(fmt){if(self.printTimeLeft()===undefined){if(!self.printTime()||!(self.isPrinting()||self.isPaused())){return"-";}else{return gettext("Still stabilizing...");}}else{return fmt(self.printTimeLeft());}};self.printTimeLeftString=ko.pureComputed(function(){return printTimeLeftStringHlpr(self.settings.appearance_fuzzyTimes()?formatFuzzyPrintTime:formatDuration);});self.printTimeLeftExactString=ko.pureComputed(function(){return printTimeLeftStringHlpr(formatDuration);});self.printTimeLeftOriginString=ko.pureComputed(function(){var value=self.printTimeLeftOrigin();switch(value){case"linear":{return gettext("Based on a linear approximation (very low accuracy, especially at the beginning of the print)");}
case"analysis":{return gettext("Based on the estimate from analysis of file (medium accuracy)");}
case"mixed-analysis":{return gettext("Based on a mix of estimate from analysis and calculation (medium accuracy)");}
case"average":{return gettext("Based on the average total of past prints of this model with the same printer profile (usually good accuracy)");}
case"mixed-average":{return gettext("Based on a mix of average total from past prints and calculation (usually good accuracy)");}
case"estimate":{return gettext("Based on the calculated estimate (best accuracy)");}
default:{return"";}}});self.printTimeLeftOriginClass=ko.pureComputed(function(){var value=self.printTimeLeftOrigin();switch(value){default:case"linear":{return"text-error";}
case"analysis":case"mixed-analysis":{return"text-warning";}
case"average":case"mixed-average":case"estimate":{return"text-success";}}});self.progressString=ko.pureComputed(function(){if(!self.progress())return 0;return self.progress();});self.progressBarString=ko.pureComputed(function(){if(!self.progress()){return"";}
return _.sprintf("%d%%",self.progress());});self.pauseString=ko.pureComputed(function(){if(self.isPaused())return gettext("Continue");else return gettext("Pause");});self.timelapseString=ko.pureComputed(function(){var timelapse=self.timelapse();if(!timelapse||!timelapse.hasOwnProperty("type"))return"-";var type=timelapse["type"];if(type==="zchange"){return gettext("On Z Change");}else if(type==="timed"){return(gettext("Timed")+" ("+
timelapse["options"]["interval"]+" "+
gettext("sec")+")");}else{return"-";}});self.userString=ko.pureComputed(function(){var user=self.user();if(user==="_api"){user="API client";}
var file=self.filename();return user?user:file?"-":"";});self.dateString=ko.pureComputed(function(){var date=self.filedate();if(!date){return gettext("unknown");}
return formatDate(date,{seconds:true});});self.fromCurrentData=function(data){self._fromData(data);};self.fromHistoryData=function(data){self._fromData(data);};self.fromTimelapseData=function(data){self.timelapse(data);};self._fromData=function(data){self._processStateData(data.state);self._processJobData(data.job);self._processProgressData(data.progress);self._processZData(data.currentZ);self._processBusyFiles(data.busyFiles);self._processResends(data.resends);self._checkResendRatioCriticality();};self._processStateData=function(data){var prevPaused=self.isPaused();self.stateString(gettext(data.text));self.errorString(data.error);self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isCancelling(data.flags.cancelling);self.isPausing(data.flags.pausing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isSdReady(data.flags.sdReady);if(self.isPaused()!==prevPaused){if(self.isPaused()){self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED);self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED);}else{self.titlePrintButton(self.TITLE_PRINT_BUTTON_UNPAUSED);self.titlePauseButton(self.TITLE_PAUSE_BUTTON_UNPAUSED);}}};self._processJobData=function(data){if(data.file){self.filename(data.file.name);self.filepath(data.file.path);self.filesize(data.file.size);self.filedisplay(data.file.display);self.filedate(data.file.date);self.sd(data.file.origin==="sdcard");}else{self.filename(undefined);self.filepath(undefined);self.filesize(undefined);self.filedisplay(undefined);self.filedate(undefined);self.sd(undefined);}
self.estimatedPrintTime(data.estimatedPrintTime);self.lastPrintTime(data.lastPrintTime);var result=[];if(data.filament&&typeof data.filament==="object"&&_.keys(data.filament).length>0){var keys=_.keys(data.filament);keys.sort();_.each(keys,function(key){if(!_.startsWith(key,"tool")||!data.filament[key]||!data.filament[key].hasOwnProperty("length")||data.filament[key].length<=0)
return;result.push({name:ko.observable(gettext("Tool")+" "+key.substr("tool".length)),data:ko.observable(data.filament[key])});});}
self.filament(result);self.user(data.user);};self._processProgressData=function(data){if(data.completion){self.progress(data.completion);}else{self.progress(undefined);}
self.filepos(data.filepos);self.printTime(data.printTime);self.printTimeLeft(data.printTimeLeft);self.printTimeLeftOrigin(data.printTimeLeftOrigin);};self._processZData=function(data){self.currentHeight(data);};self._processBusyFiles=function(data){var busyFiles=[];_.each(data,function(entry){if(entry.hasOwnProperty("path")&&entry.hasOwnProperty("origin")){busyFiles.push(entry.origin+":"+entry.path);}});self.busyFiles(busyFiles);};self._processResends=function(data){self.resendCount(data.count);self.resendTotalTransmitted(data.transmitted);self.resendRatio(data.ratio);};self._checkResendRatioCriticality=function(){if(self.resendRatioCritical()){if(self.resendRatioNotification===undefined){var message=gettext("<p>%(ratio)d%% of transmitted lines have triggered resend "+"requests. The communication with the printer is unreliable "+"and this will cause print artefacts and failures.</p><p>Please "+"see <a href='%(url)s' target='_blank'>this FAQ entry</a> "+"on tips on how to solve this.</p>");message=_.sprintf(message,{ratio:self.resendRatio(),url:"https://faq.octoprint.org/communication-errors"});self.resendRatioNotification=new PNotify({title:gettext("Critical resend ratio!"),text:message,type:"error",hide:false});}}else if(self.resendRatioNotification!==undefined){self.resendRatioNotification.remove();self.resendRatioNotification=undefined;}};self.print=function(){if(self.isPaused()){showConfirmationDialog({message:gettext("This will restart the print job from the beginning."),onproceed:function(){OctoPrint.job.restart();}});}else{var proceed=function(p){var prevented=false;var callback=function(){OctoPrint.job.start();};callViewModels(self.allViewModels,"onBeforePrintStart",function(method){prevented=prevented||method(callback)===false;});if(!prevented){callback();}};if(!self.settings.feature_printStartConfirmation()){proceed();}else{showConfirmationDialog({message:gettext("This will start a new print job. Please check that the print bed is clear."),question:gettext("Do you want to start the print job now?"),cancel:gettext("No"),proceed:gettext("Yes"),onproceed:proceed,nofade:true});}}};self.onlyPause=function(){OctoPrint.job.pause();};self.onlyResume=function(){OctoPrint.job.resume();};self.pause=function(action){OctoPrint.job.togglePause();};self.cancel=function(){if(!self.settings.feature_printCancelConfirmation()){OctoPrint.job.cancel();}else{showConfirmationDialog({message:gettext("This will cancel your print."),cancel:gettext("No, continue the print"),proceed:gettext("Yes, cancel the print"),onproceed:function(){OctoPrint.job.cancel();},nofade:true});}};self.showFirmwareErrorModal=(data)=>{if(!data){data=self.errorInfo;}
if(!data)return;const modal=$("#firmwareErrorModal");if(!modal.length)return;$("#firmwareErrorModalError",modal).text(data.error);switch(data.consequence){case"emergency":{$("#firmwareErrorModalM112",modal).show();$("#firmwareErrorModalDisconnect",modal).hide();$("#firmwareErrorModalCancel",modal).hide();break;}
case"disconnect":{$("#firmwareErrorModalM112",modal).hide();$("#firmwareErrorModalDisconnect",modal).show();$("#firmwareErrorModalCancel",modal).hide();break;}
case"cancel":{$("#firmwareErrorModalM112",modal).hide();$("#firmwareErrorModalDisconnect",modal).hide();$("#firmwareErrorModalCancel",modal).show();break;}
default:{$("#firmwareErrorModalM112",modal).hide();$("#firmwareErrorModalDisconnect",modal).hide();$("#firmwareErrorModalCancel",modal).hide();break;}}
if(data.faq){$("#firmwareErrorModalFaq a",modal).attr("href","https://faq.octoprint.org/"+data.faq);$("#firmwareErrorModalFaq",modal).show();}else{$("#firmwareErrorModalFaq",modal).hide();}
const logs=$("#firmwareErrorModalLogs",modal);const logOutput=$("#firmwareErrorModalLogsOutput",logs);if(data.logs){logOutput.empty();_.each(data.logs,(line)=>{logOutput.append('<span class="line">'+_.escape(line)+"\n"+"</span>");});logs.show();}else{logs.hide();}
modal.modal("show");logOutput.scrollTop(logOutput.prop("scrollHeight"));};self.requestErrorInfo=()=>{OctoPrint.printer.getErrorInfo().then((data)=>{if(data&&data.error&&data.error!==""){self.errorInfoAvailable(true);self.errorInfo=data;}else{self.errorInfoAvailable(false);self.errorInfo={};}});};self.onEventError=(payload)=>{if(payload.reason==="firmware"){self.errorInfo=payload;self.errorInfoAvailable(true);self.showFirmwareErrorModal();}};self.onEventConnecting=self.onEventPrintCancelling=self.onEventPrintStarted=()=>{self.requestErrorInfo();};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=()=>{self.requestErrorInfo();};self.onAllBound=(allViewModels)=>{self.allViewModels=allViewModels;};}
OCTOPRINT_VIEWMODELS.push({construct:PrinterStateViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel"],elements:["#state_wrapper","#drop_overlay"]});});
;

// source: js/app/viewmodels/printerprofiles.js
$(function(){var cleanProfile=function(){return{id:"",name:"",model:"",color:"default",volume:{formFactor:"rectangular",width:200,depth:200,height:200,origin:"lowerleft",custom_box:false},heatedBed:true,heatedChamber:false,axes:{x:{speed:6000,inverted:false},y:{speed:6000,inverted:false},z:{speed:200,inverted:false},e:{speed:300,inverted:false}},extruder:{count:1,offsets:[[0,0]],nozzleDiameter:0.4,sharedNozzle:false,defaultExtrusionLength:5}};};function EditedProfileViewModel(profiles){var self=this;self.profiles=profiles;self.isNew=ko.observable(false);self.name=ko.observable();self.color=ko.observable();self.identifier=ko.observable();self.identifierPlaceholder=ko.observable();self.model=ko.observable();self.volumeWidth=ko.observable();self.volumeHeight=ko.observable();self.volumeDepth=ko.observable();self.volumeFormFactor=ko.observable();self.volumeOrigin=ko.observable();self.volumeFormFactor.subscribe(function(value){if(value=="circular"){self.volumeOrigin("center");}});self.volumeOrigin.subscribe(function(){self.toBoundingBoxPlaceholders(self.defaultBoundingBox(self.volumeWidth(),self.volumeDepth(),self.volumeHeight(),self.volumeOrigin()));});self.heatedBed=ko.observable();self.heatedChamber=ko.observable();self.nozzleDiameter=ko.observable();self.extruders=ko.observable();self.extruderOffsets=ko.observableArray();self.sharedNozzle=ko.observable();self.defaultExtrusionLength=ko.observable();self.axisXSpeed=ko.observable();self.axisYSpeed=ko.observable();self.axisZSpeed=ko.observable();self.axisESpeed=ko.observable();self.axisXInverted=ko.observable(false);self.axisYInverted=ko.observable(false);self.axisZInverted=ko.observable(false);self.axisEInverted=ko.observable(false);self.customBoundingBox=ko.observable(false);self.boundingBoxMinX=ko.observable();self.boundingBoxMinY=ko.observable();self.boundingBoxMinZ=ko.observable();self.boundingBoxMaxX=ko.observable();self.boundingBoxMaxY=ko.observable();self.boundingBoxMaxZ=ko.observable();self.boundingBoxMinXPlaceholder=ko.observable();self.boundingBoxMinYPlaceholder=ko.observable();self.boundingBoxMinZPlaceholder=ko.observable();self.boundingBoxMaxXPlaceholder=ko.observable();self.boundingBoxMaxYPlaceholder=ko.observable();self.boundingBoxMaxZPlaceholder=ko.observable();self.koExtruderOffsets=ko.pureComputed(function(){var extruderOffsets=self.extruderOffsets();var numExtruders=self.extruders();if(!numExtruders){numExtruders=1;}
if(numExtruders-1>extruderOffsets.length){for(var i=extruderOffsets.length;i<numExtruders;i++){extruderOffsets[i]={idx:i+1,x:ko.observable(0),y:ko.observable(0)};}
self.extruderOffsets(extruderOffsets);}
return extruderOffsets.slice(0,numExtruders-1);});self.nameInvalid=ko.pureComputed(function(){return!self.name();});self.sizeInvalid=ko.pureComputed(function(){return(!(self.volumeWidth()>0&&self.volumeWidth()<10000)||!(self.volumeDepth()>0&&self.volumeDepth()<10000)||!(self.volumeHeight()>0&&self.volumeHeight()<10000));});self.identifierInvalid=ko.pureComputed(function(){var identifier=self.identifier();var placeholder=self.identifierPlaceholder();var data=identifier;if(!identifier){data=placeholder;}
var validCharacters=data&&data==self._sanitize(data);var existingProfile=self.profiles.getItem(function(item){return item.id==data;});return(!data||!validCharacters||(self.isNew()&&existingProfile!=undefined));});self.identifierInvalidText=ko.pureComputed(function(){if(!self.identifierInvalid()){return"";}
if(!self.identifier()&&!self.identifierPlaceholder()){return gettext("Identifier must be set");}else if(self.identifier()!=self._sanitize(self.identifier())){return gettext("Invalid characters, only a-z, A-Z, 0-9, -, ., _, ( and ) are allowed");}else{return gettext("A profile with such an identifier already exists");}});self.name.subscribe(function(){self.identifierPlaceholder(self._sanitize(self.name()).toLowerCase());});self.valid=function(){return(!self.nameInvalid()&&!self.identifierInvalid()&&!self.sizeInvalid());};self.availableColors=ko.observable([{key:"default",name:gettext("default")},{key:"red",name:gettext("red")},{key:"orange",name:gettext("orange")},{key:"yellow",name:gettext("yellow")},{key:"green",name:gettext("green")},{key:"blue",name:gettext("blue")},{key:"black",name:gettext("black")}]);self.availableOrigins=ko.pureComputed(function(){var formFactor=self.volumeFormFactor();var possibleOrigins={lowerleft:gettext("Lower Left"),center:gettext("Center")};var keys=[];if(formFactor=="rectangular"){keys=["lowerleft","center"];}else if(formFactor=="circular"){keys=["center"];}
var result=[];_.each(keys,function(key){result.push({key:key,name:possibleOrigins[key]});});return result;});self.fromProfileData=function(data){self.isNew(data===undefined);if(data===undefined){data=cleanProfile();}
self.identifier(data.id);self.name(data.name);self.color(data.color);self.model(data.model);self.volumeWidth(data.volume.width);self.volumeHeight(data.volume.height);self.volumeDepth(data.volume.depth);self.volumeFormFactor(data.volume.formFactor);self.volumeOrigin(data.volume.origin);if(data.volume.custom_box){self.toBoundingBoxData(data.volume.custom_box,true);}else{var box=self.defaultBoundingBox(data.volume.width,data.volume.depth,data.volume.height,data.volume.origin);self.toBoundingBoxData(box,false);}
self.heatedBed(data.heatedBed);self.heatedChamber(data.heatedChamber);self.nozzleDiameter(data.extruder.nozzleDiameter);self.sharedNozzle(data.extruder.sharedNozzle);self.defaultExtrusionLength(data.extruder.defaultExtrusionLength);self.extruders(data.extruder.count);var offsets=[];if(data.extruder.count>1){_.each(_.slice(data.extruder.offsets,1),function(offset,index){offsets.push({idx:index+1,x:ko.observable(offset[0]),y:ko.observable(offset[1])});});}
self.extruderOffsets(offsets);self.axisXSpeed(data.axes.x.speed);self.axisXInverted(data.axes.x.inverted);self.axisYSpeed(data.axes.y.speed);self.axisYInverted(data.axes.y.inverted);self.axisZSpeed(data.axes.z.speed);self.axisZInverted(data.axes.z.inverted);self.axisESpeed(data.axes.e.speed);self.axisEInverted(data.axes.e.inverted);};self.toProfileData=function(){var identifier=self.identifier();if(!identifier){identifier=self.identifierPlaceholder();}
var defaultProfile=cleanProfile();var valid=function(value,f,def){var v=f(value);if(isNaN(v)){return def;}
return v;};var runChecks=function(value,def,checks){if(checks.gt!==undefined){if(!(value>checks.gt)){return def;}}
if(checks.lt!==undefined){if(!(value<checks.lt)){return def;}}
return value;};var validFloat=function(value,def,checks){var v=valid(value,parseFloat,def);if(checks){v=runChecks(value,def,checks);}
return v;};var validInt=function(value,def,checks){var v=valid(value,parseInt,def);if(checks){v=runChecks(value,def,checks);}
return v;};var profile={id:identifier,name:self.name(),color:self.color(),model:self.model(),volume:{width:validFloat(self.volumeWidth(),defaultProfile.volume.width,{gt:0,lt:10000}),depth:validFloat(self.volumeDepth(),defaultProfile.volume.depth,{gt:0,lt:10000}),height:validFloat(self.volumeHeight(),defaultProfile.volume.height,{gt:0,lt:10000}),formFactor:self.volumeFormFactor(),origin:self.volumeOrigin()},heatedBed:self.heatedBed(),heatedChamber:self.heatedChamber(),extruder:{count:runChecks(parseInt(self.extruders()),1,{gt:0,lt:100}),offsets:[[0.0,0.0]],nozzleDiameter:validFloat(self.nozzleDiameter(),defaultProfile.extruder.nozzleDiameter),sharedNozzle:self.sharedNozzle(),defaultExtrusionLength:validInt(self.defaultExtrusionLength(),defaultProfile.extruder.defaultExtrusionLength)},axes:{x:{speed:validInt(self.axisXSpeed(),defaultProfile.axes.x.speed,{gt:0}),inverted:self.axisXInverted()},y:{speed:validInt(self.axisYSpeed(),defaultProfile.axes.y.speed,{gt:0}),inverted:self.axisYInverted()},z:{speed:validInt(self.axisZSpeed(),defaultProfile.axes.z.speed,{gt:0}),inverted:self.axisZInverted()},e:{speed:validInt(self.axisESpeed(),defaultProfile.axes.e.speed,{gt:0}),inverted:self.axisEInverted()}}};self.fillBoundingBoxData(profile);var offsetX,offsetY;if(self.extruders()>1){for(var i=0;i<self.extruders()-1;i++){var offset=[0.0,0.0];if(i<self.extruderOffsets().length){offsetX=validFloat(self.extruderOffsets()[i]["x"](),0.0);offsetY=validFloat(self.extruderOffsets()[i]["y"](),0.0);offset=[offsetX,offsetY];}
profile.extruder.offsets.push(offset);}}
if(profile.volume.formFactor=="circular"){profile.volume.depth=profile.volume.width;}
return profile;};self.defaultBoundingBox=function(width,depth,height,origin){if(origin=="center"){var halfWidth=width/2.0;var halfDepth=depth/2.0;return{x_min:-halfWidth,y_min:-halfDepth,z_min:0.0,x_max:halfWidth,y_max:halfDepth,z_max:height};}else{return{x_min:0.0,y_min:0.0,z_min:0.0,x_max:width,y_max:depth,z_max:height};}};self.toBoundingBoxData=function(box,custom){self.customBoundingBox(custom);if(custom){self.boundingBoxMinX(box.x_min);self.boundingBoxMinY(box.y_min);self.boundingBoxMinZ(box.z_min);self.boundingBoxMaxX(box.x_max);self.boundingBoxMaxY(box.y_max);self.boundingBoxMaxZ(box.z_max);}else{self.boundingBoxMinX(undefined);self.boundingBoxMinY(undefined);self.boundingBoxMinZ(undefined);self.boundingBoxMaxX(undefined);self.boundingBoxMaxY(undefined);self.boundingBoxMaxZ(undefined);}
self.toBoundingBoxPlaceholders(box);};self.toBoundingBoxPlaceholders=function(box){self.boundingBoxMinXPlaceholder(box.x_min);self.boundingBoxMinYPlaceholder(box.y_min);self.boundingBoxMinZPlaceholder(box.z_min);self.boundingBoxMaxXPlaceholder(box.x_max);self.boundingBoxMaxYPlaceholder(box.y_max);self.boundingBoxMaxZPlaceholder(box.z_max);};self.fillBoundingBoxData=function(profile){if(self.customBoundingBox()){var defaultBox=self.defaultBoundingBox(self.volumeWidth(),self.volumeDepth(),self.volumeHeight(),self.volumeOrigin());profile.volume.custom_box={x_min:self.boundingBoxMinX()!==undefined?Math.min(self.boundingBoxMinX(),defaultBox.x_min):defaultBox.x_min,y_min:self.boundingBoxMinY()!==undefined?Math.min(self.boundingBoxMinY(),defaultBox.y_min):defaultBox.y_min,z_min:self.boundingBoxMinZ()!==undefined?Math.min(self.boundingBoxMinZ(),defaultBox.z_min):defaultBox.z_min,x_max:self.boundingBoxMaxX()!==undefined?Math.max(self.boundingBoxMaxX(),defaultBox.x_max):defaultBox.x_max,y_max:self.boundingBoxMaxY()!==undefined?Math.max(self.boundingBoxMaxY(),defaultBox.y_max):defaultBox.y_max,z_max:self.boundingBoxMaxZ()!==undefined?Math.max(self.boundingBoxMaxZ(),defaultBox.z_max):defaultBox.z_max};}else{profile.volume.custom_box=false;}};self._sanitize=function(name){return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g,"").replace(/ /g,"_");};self.fromProfileData(cleanProfile());}
function PrinterProfilesViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.requestInProgress=ko.observable(false);self.profiles=new ItemListHelper("printerProfiles",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;}},{},"name",[],[],10);self.defaultProfile=ko.observable();self.currentProfile=ko.observable();self.createProfileEditor=function(data){var editor=new EditedProfileViewModel(self.profiles);if(data!==undefined){editor.fromProfileData(data);}
return editor;};self.editor=self.createProfileEditor();self.currentProfileData=ko.observable();self.enableEditorSubmitButton=ko.pureComputed(function(){return self.editor.valid()&&!self.requestInProgress();});self.makeDefault=function(data){var profile={id:data.id,default:true};self.updateProfile(profile);};self.canMakeDefault=function(data){return!data.isdefault();};self.canRemove=function(data){return!data.iscurrent()&&!data.isdefault();};self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.CONNECTION)){return;}
return OctoPrint.printerprofiles.list().done(self.fromResponse);};self.fromResponse=function(data){var items=[];var defaultProfile=undefined;var currentProfile=undefined;var currentProfileData=undefined;_.each(data.profiles,function(entry){if(entry.default){defaultProfile=entry.id;}
if(entry.current){currentProfile=entry.id;currentProfileData=ko.mapping.fromJS(entry,self.currentProfileData);}
entry["isdefault"]=ko.observable(entry.default);entry["iscurrent"]=ko.observable(entry.current);items.push(entry);});self.profiles.updateItems(items);self.defaultProfile(defaultProfile);if(currentProfile&&currentProfileData){self.currentProfile(currentProfile);self.currentProfileData(currentProfileData);}else{log.warn("Current printer profile could not be detected, using default values");self.currentProfile("");self.currentProfileData(ko.mapping.fromJS(cleanProfile(),self.currentProfileData));}};self.addProfile=function(callback){var profile=self.editor.toProfileData();self.requestInProgress(true);OctoPrint.printerprofiles.add(profile).done(function(){if(callback!==undefined){callback();}
self.requestData();}).fail(function(xhr){var text=gettext("There was unexpected error while saving the printer profile, please consult the logs.");new PNotify({title:gettext("Could not add profile"),text:text,type:"error",hide:false});}).always(function(){self.requestInProgress(false);});};self.removeProfile=function(data){var perform=function(){self.requestInProgress(true);OctoPrint.printerprofiles.delete(data.id,{url:data.resource}).done(function(){self.requestData().always(function(){self.requestInProgress(false);});}).fail(function(xhr){var text;if(xhr.status==409){text=gettext("Cannot delete the default profile or the currently active profile.");}else{text=gettext("There was unexpected error while removing the printer profile, please consult the logs.");}
new PNotify({title:gettext("Could not delete profile"),text:text,type:"error",hide:false});self.requestInProgress(false);});};showConfirmationDialog(_.sprintf(gettext('You are about to delete the printer profile "%(name)s".'),{name:_.escape(data.name)}),perform);};self.updateProfile=function(profile,callback){if(profile==undefined){profile=self.editor.toProfileData();}
self.requestInProgress(true);OctoPrint.printerprofiles.update(profile.id,profile).done(function(){if(callback!==undefined){callback();}
self.requestData().always(function(){self.requestInProgress(false);});}).fail(function(){var text=gettext("There was unexpected error while updating the printer profile, please consult the logs.");new PNotify({title:gettext("Could not update profile"),text:text,type:"error",hide:false});self.requestInProgress(false);});};self.showEditProfileDialog=function(data){self.editor.fromProfileData(data);var editDialog=$("#settings_printerProfiles_editDialog");var confirmButton=$("button.btn-confirm",editDialog);var dialogTitle=$("h3.modal-title",editDialog);var add=data===undefined;dialogTitle.text(add?gettext("Add Printer Profile"):_.sprintf(gettext('Edit Printer Profile "%(name)s"'),{name:_.escape(data.name)}));confirmButton.unbind("click");confirmButton.bind("click",function(){if(self.enableEditorSubmitButton()){self.confirmEditProfile(add);}});$('ul.nav-pills a[data-toggle="tab"]:first',editDialog).tab("show");editDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});};self.confirmEditProfile=function(add){var callback=function(){$("#settings_printerProfiles_editDialog").modal("hide");};if(add){self.addProfile(callback);}else{self.updateProfile(undefined,callback);}};self.onSettingsShown=self.requestData;self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};}
OCTOPRINT_VIEWMODELS.push({construct:PrinterProfilesViewModel,dependencies:["loginStateViewModel","accessViewModel"]});});
;

// source: js/app/viewmodels/settings.js
$(function(){function SettingsViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.printerProfiles=parameters[2];self.about=parameters[3];self.users=parameters[4];var firstRequest=$.Deferred();self.firstRequest=firstRequest.promise();self.allViewModels=[];self.receiving=ko.observable(false);self.sending=ko.observable(false);self.exchanging=ko.pureComputed(function(){return self.receiving()||self.sending();});self.outstanding=[];self.active=false;self.sawUpdateEventWhileActive=false;self.ignoreNextUpdateEvent=false;self.settingsDialog=undefined;self.settings_dialog_update_detected=undefined;self.translationManagerDialog=undefined;self.translationUploadElement=$("#settings_appearance_managelanguagesdialog_upload");self.translationUploadButton=$("#settings_appearance_managelanguagesdialog_upload_start");self.translationUploadFilename=ko.observable();self.invalidTranslationArchive=ko.pureComputed(function(){var name=self.translationUploadFilename();return name!==undefined&&!_.endsWith(name.toLocaleLowerCase(),".zip");});self.enableTranslationUpload=ko.pureComputed(function(){var name=self.translationUploadFilename();return(name!==undefined&&name.trim()!=""&&!self.invalidTranslationArchive());});self.translations=new ItemListHelper("settings.translations",{locale:function(a,b){if(a["locale"].toLocaleLowerCase()<b["locale"].toLocaleLowerCase())
return-1;if(a["locale"].toLocaleLowerCase()>b["locale"].toLocaleLowerCase())
return 1;return 0;}},{},"locale",[],[],0);self.appearance_available_colors=ko.observable([{key:"default",name:gettext("default")},{key:"red",name:gettext("red")},{key:"orange",name:gettext("orange")},{key:"yellow",name:gettext("yellow")},{key:"green",name:gettext("green")},{key:"blue",name:gettext("blue")},{key:"violet",name:gettext("violet")},{key:"black",name:gettext("black")},{key:"white",name:gettext("white")}]);self.appearance_colorName=function(color){switch(color){case"red":return gettext("red");case"orange":return gettext("orange");case"yellow":return gettext("yellow");case"green":return gettext("green");case"blue":return gettext("blue");case"violet":return gettext("violet");case"black":return gettext("black");case"white":return gettext("white");case"default":return gettext("default");default:return color;}};self.webcam_available_videocodecs=["libx264","mpeg2video"];var auto_locale={language:"_default",display:gettext("Autodetect from browser"),english:undefined};self.locales=ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES),function(n){return n.display;})));self.locale_languages=_.keys(AVAILABLE_LOCALES);self.api_key=ko.observable(undefined);self.api_allowCrossOrigin=ko.observable(undefined);self.apiKeyVisible=ko.observable(false);self.appearance_name=ko.observable(undefined);self.appearance_color=ko.observable(undefined);self.appearance_colorTransparent=ko.observable();self.appearance_colorIcon=ko.observable();self.appearance_defaultLanguage=ko.observable();self.appearance_showFahrenheitAlso=ko.observable(undefined);self.appearance_fuzzyTimes=ko.observable(undefined);self.appearance_closeModalsWithClick=ko.observable(undefined);self.appearance_showInternalFilename=ko.observable(undefined);self.printer_defaultExtrusionLength=ko.observable(undefined);self.webcam_webcamEnabled=ko.observable(undefined);self.webcam_timelapseEnabled=ko.observable(undefined);self.webcam_snapshotTimeout=ko.observable(undefined);self.webcam_snapshotSslValidation=ko.observable(undefined);self.webcam_ffmpegPath=ko.observable(undefined);self.webcam_ffmpegCommandline=ko.observable(undefined);self.webcam_bitrate=ko.observable(undefined);self.webcam_ffmpegThreads=ko.observable(undefined);self.webcam_ffmpegVideoCodec=ko.observable(undefined);self.webcam_watermark=ko.observable(undefined);self.webcam_defaultWebcam=ko.observable(undefined);self.webcam_snapshotWebcam=ko.observable(undefined);self.webcam_webcams=ko.observableArray([]);self.feature_temperatureGraph=ko.observable(undefined);self.feature_sdSupport=ko.observable(undefined);self.feature_keyboardControl=ko.observable(undefined);self.feature_pollWatched=ko.observable(undefined);self.feature_modelSizeDetection=ko.observable(undefined);self.feature_rememberFileFolder=ko.observable(undefined);self.feature_printStartConfirmation=ko.observable(undefined);self.feature_printCancelConfirmation=ko.observable(undefined);self.feature_uploadOverwriteConfirmation=ko.observable(undefined);self.feature_g90InfluencesExtruder=ko.observable(undefined);self.feature_autoUppercaseBlacklist=ko.observable(undefined);self.feature_enableDragDropUpload=ko.observable(undefined);self.gcodeAnalysis_runAt=ko.observable(undefined);self.serial_port=ko.observable();self.serial_baudrate=ko.observable();self.serial_exclusive=ko.observable();self.serial_lowLatency=ko.observable();self.serial_portOptions=ko.observableArray([]);self.serial_baudrateOptions=ko.observableArray([]);self.serial_autoconnect=ko.observable(undefined);self.serial_timeoutConnection=ko.observable(undefined);self.serial_timeoutDetectionFirst=ko.observable(undefined);self.serial_timeoutDetectionConsecutive=ko.observable(undefined);self.serial_timeoutCommunication=ko.observable(undefined);self.serial_timeoutCommunicationBusy=ko.observable(undefined);self.serial_timeoutTemperature=ko.observable(undefined);self.serial_timeoutTemperatureTargetSet=ko.observable(undefined);self.serial_timeoutTemperatureAutoreport=ko.observable(undefined);self.serial_timeoutSdStatus=ko.observable(undefined);self.serial_timeoutSdStatusAutoreport=ko.observable(undefined);self.serial_timeoutPosAutoreport=ko.observable(undefined);self.serial_timeoutBaudrateDetectionPause=ko.observable(undefined);self.serial_timeoutPositionLogWait=ko.observable(undefined);self.serial_log=ko.observable(undefined);self.serial_additionalPorts=ko.observable(undefined);self.serial_additionalBaudrates=ko.observable(undefined);self.serial_blacklistedPorts=ko.observable(undefined);self.serial_blacklistedBaudrates=ko.observable(undefined);self.serial_longRunningCommands=ko.observable(undefined);self.serial_checksumRequiringCommands=ko.observable(undefined);self.serial_blockedCommands=ko.observable(undefined);self.serial_ignoredCommands=ko.observable(undefined);self.serial_pausingCommands=ko.observable(undefined);self.serial_sdCancelCommand=ko.observable(undefined);self.serial_emergencyCommands=ko.observable(undefined);self.serial_helloCommand=ko.observable(undefined);self.serial_serialErrorBehaviour=ko.observable("cancel");self.serial_triggerOkForM29=ko.observable(undefined);self.serial_waitForStart=ko.observable(undefined);self.serial_waitToLoadSdFileList=ko.observable(undefined);self.serial_sendChecksum=ko.observable("print");self.serial_sendChecksumWithUnknownCommands=ko.observable(undefined);self.serial_unknownCommandsNeedAck=ko.observable(undefined);self.serial_sdRelativePath=ko.observable(undefined);self.serial_sdLowerCase=ko.observable(undefined);self.serial_sdAlwaysAvailable=ko.observable(undefined);self.serial_swallowOkAfterResend=ko.observable(undefined);self.serial_repetierTargetTemp=ko.observable(undefined);self.serial_disableExternalHeatupDetection=ko.observable(undefined);self.serial_ignoreIdenticalResends=ko.observable(undefined);self.serial_firmwareDetection=ko.observable(undefined);self.serial_blockWhileDwelling=ko.observable(undefined);self.serial_useParityWorkaround=ko.observable(undefined);self.serial_sanityCheckTools=ko.observable(undefined);self.serial_supportResendsWithoutOk=ko.observable(undefined);self.serial_logPositionOnPause=ko.observable(undefined);self.serial_logPositionOnCancel=ko.observable(undefined);self.serial_abortHeatupOnCancel=ko.observable(undefined);self.serial_maxTimeoutsIdle=ko.observable(undefined);self.serial_maxTimeoutsPrinting=ko.observable(undefined);self.serial_maxTimeoutsLong=ko.observable(undefined);self.serial_capAutoreportTemp=ko.observable(undefined);self.serial_capAutoreportSdStatus=ko.observable(undefined);self.serial_capAutoreportPos=ko.observable(undefined);self.serial_capBusyProtocol=ko.observable(undefined);self.serial_capEmergencyParser=ko.observable(undefined);self.serial_capExtendedM20=ko.observable(undefined);self.serial_capLfnWrite=ko.observable(undefined);self.serial_sendM112OnError=ko.observable(undefined);self.serial_disableSdPrintingDetection=ko.observable(undefined);self.serial_ackMax=ko.observable(undefined);self.serial_resendRatioThreshold=ko.observable(100);self.serial_resendRatioStart=ko.observable(100);self.serial_ignoreEmptyPorts=ko.observable(undefined);self.serial_enableShutdownActionCommand=ko.observable(undefined);self.folder_uploads=ko.observable(undefined);self.folder_timelapse=ko.observable(undefined);self.folder_watched=ko.observable(undefined);self.scripts_gcode_beforePrintStarted=ko.observable(undefined);self.scripts_gcode_afterPrintDone=ko.observable(undefined);self.scripts_gcode_afterPrintCancelled=ko.observable(undefined);self.scripts_gcode_afterPrintPaused=ko.observable(undefined);self.scripts_gcode_beforePrintResumed=ko.observable(undefined);self.scripts_gcode_afterPrinterConnected=ko.observable(undefined);self.scripts_gcode_beforePrinterDisconnected=ko.observable(undefined);self.scripts_gcode_afterToolChange=ko.observable(undefined);self.scripts_gcode_beforeToolChange=ko.observable(undefined);self.temperature_profiles=ko.observableArray(undefined);self.temperature_cutoff=ko.observable(undefined);self.temperature_sendAutomatically=ko.observable(undefined);self.temperature_sendAutomaticallyAfter=ko.observable(undefined);self.system_actions=ko.observableArray([]);self.terminalFilters=ko.observableArray([]);self.server_commands_systemShutdownCommand=ko.observable(undefined);self.server_commands_systemRestartCommand=ko.observable(undefined);self.server_commands_serverRestartCommand=ko.observable(undefined);self.server_diskspace_warning=ko.observable();self.server_diskspace_critical=ko.observable();self.server_diskspace_warning_str=sizeObservable(self.server_diskspace_warning);self.server_diskspace_critical_str=sizeObservable(self.server_diskspace_critical);self.server_onlineCheck_enabled=ko.observable();self.server_onlineCheck_interval=ko.observable();self.server_onlineCheck_host=ko.observable();self.server_onlineCheck_port=ko.observable();self.server_onlineCheck_name=ko.observable();self.server_pluginBlacklist_enabled=ko.observable();self.server_pluginBlacklist_url=ko.observable();self.server_pluginBlacklist_ttl=ko.observable();self.server_allowFraming=ko.observable();self.settings=undefined;self.lastReceivedSettings=undefined;self.webcam_ffmpegPathText=ko.observable();self.webcam_ffmpegPathOk=ko.observable(false);self.webcam_ffmpegPathBroken=ko.observable(false);self.webcam_ffmpegPathReset=function(){self.webcam_ffmpegPathText("");self.webcam_ffmpegPathOk(false);self.webcam_ffmpegPathBroken(false);};self.server_onlineCheckText=ko.observable();self.server_onlineCheckOk=ko.observable(false);self.server_onlineCheckBroken=ko.observable(false);self.server_onlineCheckReset=function(){self.server_onlineCheckText("");self.server_onlineCheckOk(false);self.server_onlineCheckBroken(false);};self.server_onlineCheckResolutionText=ko.observable();self.server_onlineCheckResolutionOk=ko.observable(false);self.server_onlineCheckResolutionBroken=ko.observable(false);self.server_onlineCheckResolutionReset=function(){self.server_onlineCheckResolutionText("");self.server_onlineCheckResolutionOk(false);self.server_onlineCheckResolutionBroken(false);};var folderTypes=["uploads","timelapse","watched"];var checkForDuplicateFolders=function(){_.each(folderTypes,function(folderType){var path=self["folder_"+folderType]();var duplicate=false;_.each(folderTypes,function(otherFolderType){if(folderType!==otherFolderType){duplicate=duplicate||path===self["folder_"+otherFolderType]();}});self.testFolderConfigDuplicate[folderType](duplicate);});};self.testFolderConfigText={};self.testFolderConfigOk={};self.testFolderConfigBroken={};self.testFolderConfigDuplicate={};self.testFolderConfigError={};self.testFolderConfigSuccess={};_.each(folderTypes,function(folderType){self.testFolderConfigText[folderType]=ko.observable("");self.testFolderConfigOk[folderType]=ko.observable(false);self.testFolderConfigBroken[folderType]=ko.observable(false);self.testFolderConfigDuplicate[folderType]=ko.observable(false);self.testFolderConfigError[folderType]=ko.pureComputed(function(){return(self.testFolderConfigBroken[folderType]()||self.testFolderConfigDuplicate[folderType]());});self.testFolderConfigSuccess[folderType]=ko.pureComputed(function(){return(self.testFolderConfigOk[folderType]()&&!self.testFolderConfigDuplicate[folderType]());});self["folder_"+folderType].subscribe(checkForDuplicateFolders);});self.testFolderConfigReset=function(){_.each(folderTypes,function(folderType){self.testFolderConfigText[folderType]("");self.testFolderConfigOk[folderType](false);self.testFolderConfigBroken[folderType](false);});};self.testFoldersDuplicate=ko.pureComputed(function(){var foundDupe=false;_.each(folderTypes,function(folderType){foundDupe=foundDupe||self.testFolderConfigDuplicate[folderType]();});return foundDupe;});self.observableCopies={feature_waitForStart:"serial_waitForStart",feature_waitToLoadSdFileList:"serial_waitToLoadSdFileList",feature_sendChecksum:"serial_sendChecksum",feature_sdRelativePath:"serial_sdRelativePath",feature_sdAlwaysAvailable:"serial_sdAlwaysAvailable",feature_swallowOkAfterResend:"serial_swallowOkAfterResend",feature_repetierTargetTemp:"serial_repetierTargetTemp",feature_disableExternalHeatupDetection:"serial_disableExternalHeatupDetection",feature_ignoreIdenticalResends:"serial_ignoreIdenticalResends",feature_firmwareDetection:"serial_firmwareDetection",feature_blockWhileDwelling:"serial_blockWhileDwelling",serial_:"feature_"};_.each(self.observableCopies,function(value,key){if(self.hasOwnProperty(value)){self[key]=self[value];}});self.webcamCompat={webcam_streamUrl:"streamUrl",webcam_streamRatio:"streamRatio",webcam_streamTimeout:"streamTimeout",webcam_streamWebrtcIceServers:"webrtcIceServers",webcam_snapshotUrl:"snapshotUrl",webcam_flipH:"flipH",webcam_flipV:"flipV",webcam_rotate90:"rotate90",webcam_cacheBuster:"cacheBuster"};self.addTemperatureProfile=function(){self.temperature_profiles.push({name:"New",extruder:0,bed:0,chamber:0});};self.removeTemperatureProfile=function(profile){self.temperature_profiles.remove(profile);};self.addTerminalFilter=function(){self.terminalFilters.push({name:"New",regex:"(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"});};self.removeTerminalFilter=function(filter){self.terminalFilters.remove(filter);};self.testWebcamFfmpegPathBusy=ko.observable(false);self.testWebcamFfmpegPath=function(){if(!self.webcam_ffmpegPath()){return;}
if(self.testWebcamFfmpegPathBusy()){return;}
self.testWebcamFfmpegPathBusy(true);OctoPrint.util.testExecutable(self.webcam_ffmpegPath()).done(function(response){if(!response.result){if(!response.exists){self.webcam_ffmpegPathText(gettext("The path doesn't exist"));}else if(!response.typeok){self.webcam_ffmpegPathText(gettext("The path is not a file"));}else if(!response.access){self.webcam_ffmpegPathText(gettext("The path is not an executable"));}}else{self.webcam_ffmpegPathText(gettext("The path is valid"));}
self.webcam_ffmpegPathOk(response.result);self.webcam_ffmpegPathBroken(!response.result);}).always(function(){self.testWebcamFfmpegPathBusy(false);});};self.testOnlineConnectivityConfigBusy=ko.observable(false);self.testOnlineConnectivityConfig=function(){if(!self.server_onlineCheck_host())return;if(!self.server_onlineCheck_port())return;if(self.testOnlineConnectivityConfigBusy())return;self.testOnlineConnectivityConfigBusy(true);OctoPrint.util.testServer(self.server_onlineCheck_host(),self.server_onlineCheck_port()).done(function(response){if(!response.result){self.server_onlineCheckText(gettext("The server is not reachable"));}else{self.server_onlineCheckText(gettext("The server is reachable"));}
self.server_onlineCheckOk(response.result);self.server_onlineCheckBroken(!response.result);}).always(function(){self.testOnlineConnectivityConfigBusy(false);});};self.testOnlineConnectivityResolutionConfigBusy=ko.observable(false);self.testOnlineConnectivityResolutionConfig=function(){if(!self.server_onlineCheck_name())return;if(self.testOnlineConnectivityResolutionConfigBusy())return;self.testOnlineConnectivityResolutionConfigBusy(true);OctoPrint.util.testResolution(self.server_onlineCheck_name()).done(function(response){if(!response.result){self.server_onlineCheckResolutionText(gettext("Name cannot be resolved"));}else{self.server_onlineCheckResolutionText(gettext("Name can be resolved"));}
self.server_onlineCheckResolutionOk(response.result);self.server_onlineCheckResolutionBroken(!response.result);}).always(function(){self.testOnlineConnectivityResolutionConfigBusy(false);});};self.testFolderConfigBusy=ko.observable(false);self.testFolderConfig=function(folder){var observable="folder_"+folder;if(!self.hasOwnProperty(observable))return;if(self.testFolderConfigBusy())return;self.testFolderConfigBusy(true);var opts={check_type:"dir",check_access:"w",allow_create_dir:true,check_writable_dir:true};var path=self[observable]();OctoPrint.util.testPath(path,opts).done(function(response){if(!response.result){if(response.broken_symlink){self.testFolderConfigText[folder](gettext("The path is a broken symlink."));}else if(!response.exists){self.testFolderConfigText[folder](gettext("The path does not exist and cannot be created."));}else if(!response.typeok){self.testFolderConfigText[folder](gettext("The path is not a folder."));}else if(!response.access){self.testFolderConfigText[folder](gettext("The path is not writable."));}}else{self.testFolderConfigText[folder](gettext("The path is valid"));}
self.testFolderConfigOk[folder](response.result);self.testFolderConfigBroken[folder](!response.result);}).always(function(){self.testFolderConfigBusy(false);});};self.onSettingsHidden=function(){self.webcam_ffmpegPathReset();self.server_onlineCheckReset();self.server_onlineCheckResolutionReset();self.testFolderConfigReset();};self.isDialogActive=function(){return self.settingsDialog.is(":visible");};self.onStartup=function(){self.settingsDialog=$("#settings_dialog");self.settingsUpdatedDialog=$("#settings_dialog_update_detected");self.translationManagerDialog=$("#settings_appearance_managelanguagesdialog");self.translationUploadElement=$("#settings_appearance_managelanguagesdialog_upload");self.translationUploadButton=$("#settings_appearance_managelanguagesdialog_upload_start");self.translationUploadElement.fileupload({dataType:"json",maxNumberOfFiles:1,autoUpload:false,add:function(e,data){if(data.files.length==0){return false;}
self.translationUploadFilename(data.files[0].name);self.translationUploadButton.unbind("click");self.translationUploadButton.bind("click",function(){data.submit();return false;});},done:function(e,data){self.translationUploadButton.unbind("click");self.translationUploadFilename(undefined);self.fromTranslationResponse(data.result);},fail:function(e,data){self.translationUploadButton.unbind("click");self.translationUploadFilename(undefined);}});};self.onAllBound=function(allViewModels){self.allViewModels=allViewModels;self.settingsDialog.on("show",function(event){OctoPrint.coreui.settingsOpen=true;if(event.target.id=="settings_dialog"){self.requestTranslationData();callViewModels(allViewModels,"onSettingsShown");}});self.settingsDialog.on("hidden",function(event){OctoPrint.coreui.settingsOpen=false;if(event.target.id=="settings_dialog"){callViewModels(allViewModels,"onSettingsHidden");}});self.settingsDialog.on("beforeSave",function(){callViewModels(allViewModels,"onSettingsBeforeSave");});$(".reload_all",self.settingsUpdatedDialog).click(function(e){e.preventDefault();self.settingsUpdatedDialog.modal("hide");self.requestData();return false;});$(".reload_nonconflicts",self.settingsUpdatedDialog).click(function(e){e.preventDefault();self.settingsUpdatedDialog.modal("hide");self.requestData(true);return false;});$('ul.nav-list a[data-toggle="tab"]',self.settingsDialog).on("show",function(){self._resetScrollPosition();});};self.show=function(tab){self.selectTab(tab);self._resetScrollPosition();self.settingsDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});return false;};self.hide=function(){self.settingsDialog.modal("hide");};self.generateApiKey=function(){if(!CONFIG_ACCESS_CONTROL)return;showConfirmationDialog(gettext("This will generate a new API Key. The old API Key will cease to function immediately."),function(){OctoPrint.settings.generateApiKey().done(function(response){self.api_key(response.apikey);self.requestData();});});};self.deleteApiKey=()=>{if(!CONFIG_ACCESS_CONTROL)return;if(!self.api_key())return;showConfirmationDialog(gettext("This will delete the API Key. It will cease to to function immediately."),function(){OctoPrint.settings.deleteApiKey().done(()=>{self.api_key(undefined);});});};self.copyApiKey=function(){copyToClipboard(self.api_key());};self.revealingApiKey=ko.observable(false);self.revealApiKey=()=>{self.loginState.reauthenticateIfNecessary(()=>{self.revealingApiKey(true);self.requestData().always(()=>{self.revealingApiKey(false);});});};self.showTranslationManager=function(){self.translationManagerDialog.modal();return false;};self.requestData=function(local){var callback=undefined;if(arguments.length===2||_.isFunction(local)){var exc=new Error();log.warn("The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:",exc.stack||exc.stacktrace||"<n/a>");if(arguments.length===2){callback=arguments[0];local=arguments[1];}else{callback=local;local=false;}}
var callbackHandler=function(){if(!callback)return;try{callback();}catch(exc){log.error("Error calling settings callback",callback,":",`${exc.message}\n${exc.stack || exc}`);}};if(self.receiving()){var deferred=$.Deferred();self.outstanding.push(deferred);if(callback){deferred.done(callbackHandler);}
return deferred.promise();}
self.receiving(true);return OctoPrint.settings.get().always(function(){self.receiving(false);}).done(function(response){self.fromResponse(response,local);if(callback){var deferred=$.Deferred();deferred.done(callbackHandler);self.outstanding.push(deferred);}
var args=arguments;_.each(self.outstanding,function(deferred){deferred.resolve(args);});self.outstanding=[];}).fail(function(){var args=arguments;_.each(self.outstanding,function(deferred){deferred.reject(args);});self.outstanding=[];});};self.requestTranslationData=function(){return OctoPrint.languages.list().done(self.fromTranslationResponse);};self.fromTranslationResponse=function(response){var translationsByLocale={};_.each(response.language_packs,function(item,key){_.each(item.languages,function(pack){var locale=pack.locale;if(!_.has(translationsByLocale,locale)){translationsByLocale[locale]={locale:locale,display:pack.locale_display,english:pack.locale_english,packs:[]};}
translationsByLocale[locale]["packs"].push({identifier:key,display:item.display,pack:pack});});});var translations=[];_.each(translationsByLocale,function(item){item["packs"].sort(function(a,b){if(a.identifier=="_core")return-1;if(b.identifier=="_core")return 1;if(a.display<b.display)return-1;if(a.display>b.display)return 1;return 0;});translations.push(item);});self.translations.updateItems(translations);};self.languagePackDisplay=function(item){return(item.display+
(item.english!=undefined?" ("+item.english+")":""));};self.languagePacksAvailable=ko.pureComputed(function(){return self.translations.allSize()>0;});self.deleteLanguagePack=function(locale,pack){OctoPrint.languages.delete(locale,pack).done(self.fromTranslationResponse);};self.getLocalData=function(){var data={};if(self.settings!=undefined){data=ko.mapping.toJS(self.settings);}
var specialMappings={feature:{autoUppercaseBlacklist:function(){return splitTextToArray(self.feature_autoUppercaseBlacklist(),",",true);}},serial:{additionalPorts:function(){return commentableLinesToArray(self.serial_additionalPorts());},additionalBaudrates:function(){return _.map(splitTextToArray(self.serial_additionalBaudrates(),",",true,function(item){return!isNaN(parseInt(item));}),function(item){return parseInt(item);});},blacklistedPorts:function(){return commentableLinesToArray(self.serial_blacklistedPorts());},blacklistedBaudrates:function(){return _.map(splitTextToArray(self.serial_blacklistedBaudrates(),",",true,function(item){return!isNaN(parseInt(item));}),function(item){return parseInt(item);});},longRunningCommands:function(){return splitTextToArray(self.serial_longRunningCommands(),",",true);},checksumRequiringCommands:function(){return splitTextToArray(self.serial_checksumRequiringCommands(),",",true);},blockedCommands:function(){return splitTextToArray(self.serial_blockedCommands(),",",true);},ignoredCommands:function(){return splitTextToArray(self.serial_ignoredCommands(),",",true);},pausingCommands:function(){return splitTextToArray(self.serial_pausingCommands(),",",true);},emergencyCommands:function(){return splitTextToArray(self.serial_emergencyCommands(),",",true);},externalHeatupDetection:function(){return!self.serial_disableExternalHeatupDetection();},alwaysSendChecksum:function(){return self.serial_sendChecksum()==="always";},neverSendChecksum:function(){return self.serial_sendChecksum()==="never";},ignoreErrorsFromFirmware:function(){return self.serial_serialErrorBehaviour()==="ignore";},disconnectOnErrors:function(){return self.serial_serialErrorBehaviour()==="disconnect";}},scripts:{gcode:function(){var result={};var prefix="scripts_gcode_";var observables=_.filter(_.keys(self),function(key){return _.startsWith(key,prefix);});_.each(observables,function(observable){var script=observable.substring(prefix.length);result[script]=self[observable]();});return result;}},temperature:{profiles:function(){var result=[];_.each(self.temperature_profiles(),function(profile){try{result.push({name:profile.name,extruder:Math.floor(_.isNumber(profile.extruder)?profile.extruder:parseInt(profile.extruder)),bed:Math.floor(_.isNumber(profile.bed)?profile.bed:parseInt(profile.bed)),chamber:Math.floor(_.isNumber(profile.chamber)?profile.chamber:_.isNumber(parseInt(profile.chamber))?parseInt(profile.chamber):0)});}catch(ex){}});return result;}}};var mapFromObservables=function(data,mapping,keyPrefix){var flag=false;var result={};_.forOwn(data,function(value,key){var observable=key;if(keyPrefix!==undefined){observable=keyPrefix+"_"+observable;}
if(self.observableCopies.hasOwnProperty(observable)){return;}
if(self.webcamCompat.hasOwnProperty(observable)){return;}
if(mapping&&mapping[key]&&_.isFunction(mapping[key])){result[key]=mapping[key]();flag=true;}else if(_.isPlainObject(value)){var subresult=mapFromObservables(value,mapping&&mapping[key]?mapping[key]:undefined,observable);if(subresult!==undefined){result[key]=subresult;flag=true;}}else if(self.hasOwnProperty(observable)){result[key]=self[observable]();flag=true;}});return flag?result:undefined;};var dataFromObservables=mapFromObservables(data,specialMappings);data=deepMerge(data,dataFromObservables);return data;};self.reauthenticationTimeout=undefined;self.fromResponse=function(response,local){var serverChangedData;var clientChangedData;if(local){serverChangedData=getOnlyChangedData(response,self.lastReceivedSettings);clientChangedData=getOnlyChangedData(self.getLocalData(),self.lastReceivedSettings);}else{serverChangedData=response;clientChangedData=undefined;}
self.lastReceivedSettings=response;if(self.settings===undefined){self.settings=ko.mapping.fromJS(serverChangedData);}else{ko.mapping.fromJS(serverChangedData,self.settings);}
var specialMappings={appearance:{defaultLanguage:function(value){self.appearance_defaultLanguage("_default");if(_.includes(self.locale_languages,value)){self.appearance_defaultLanguage(value);}}},feature:{autoUppercaseBlacklist:function(value){self.feature_autoUppercaseBlacklist(value.join(", "));}},serial:{additionalPorts:function(value){self.serial_additionalPorts(value.join("\n"));},additionalBaudrates:function(value){self.serial_additionalBaudrates(value.join(", "));},blacklistedPorts:function(value){self.serial_blacklistedPorts(value.join("\n"));},blacklistedBaudrates:function(value){self.serial_blacklistedBaudrates(value.join(", "));},longRunningCommands:function(value){self.serial_longRunningCommands(value.join(", "));},checksumRequiringCommands:function(value){self.serial_checksumRequiringCommands(value.join(", "));},blockedCommands:function(value){self.serial_blockedCommands(value.join(", "));},ignoredCommands:function(value){self.serial_ignoredCommands(value.join(", "));},pausingCommands:function(value){self.serial_pausingCommands(value.join(", "));},emergencyCommands:function(value){self.serial_emergencyCommands(value.join(", "));},externalHeatupDetection:function(value){self.serial_disableExternalHeatupDetection(!value);},alwaysSendChecksum:function(value){if(value){self.serial_sendChecksum("always");}},neverSendChecksum:function(value){if(value){self.serial_sendChecksum("never");}},ignoreErrorsFromFirmware:function(value){if(value){self.serial_serialErrorBehaviour("ignore");}},disconnectOnErrors:function(value){if(value){self.serial_serialErrorBehaviour("disconnect");}}},terminalFilters:function(value){self.terminalFilters($.extend(true,[],value));},temperature:{profiles:function(value){self.temperature_profiles($.extend(true,[],value));}}};_.each(self.webcamCompat,(mapped,key)=>{if(self.settings.hasOwnProperty(key))return;if(!self.settings.webcam.hasOwnProperty(mapped))return;const message="Please use the webcam system introduced with 1.9.0, the "+
key+" config setting is deprecated and will be removed in a future release. Stacktrace:";self[key]=ko.pureComputed({read:()=>{const exc=new Error();log.warn(message,exc.stack||exc.stacktrace||"<n/a>");return self.settings.webcam[mapped]();},write:(value)=>{const exc=new Error();log.warn(message,exc.stack||exc.stacktrace||"<n/a>");self.settings.webcam[mapped](value);},owner:self});});var mapToObservables=function(data,mapping,local,keyPrefix){if(!_.isPlainObject(data)){return;}
_.forOwn(data,function(value,key){var observable=key;if(keyPrefix!=undefined){observable=keyPrefix+"_"+observable;}
if(self.observableCopies.hasOwnProperty(observable)){return;}
if(self.webcamCompat.hasOwnProperty(observable)){return;}
var haveLocalVersion=local&&local.hasOwnProperty(key);if(mapping&&mapping[key]&&_.isFunction(mapping[key])&&!haveLocalVersion){mapping[key](value);}else if(_.isPlainObject(value)){mapToObservables(value,mapping&&mapping[key]?mapping[key]:undefined,local&&local[key]?local[key]:undefined,observable);}else if(!haveLocalVersion&&self.hasOwnProperty(observable)){self[observable](value);}});};mapToObservables(serverChangedData,specialMappings,clientChangedData);firstRequest.resolve();self.apiKeyVisible(self.loginState.checkCredentialsSeen());if(self.apiKeyVisible()){self.reauthenticationTimeout=self.loginState.afterReauthenticationTimeout(()=>{self.requestData();},self.reauthenticationTimeout);}};self.cancelData=function(){self.fromResponse(self.lastReceivedSettings);self.hide();};self.saveData=function(data,successCallback,setAsSending){var options;if(_.isPlainObject(successCallback)){options=successCallback;}else{options={success:successCallback,sending:setAsSending===true};}
self.settingsDialog.trigger("beforeSave");self.sawUpdateEventWhileSending=false;self.sending(data===undefined||options.sending||false);if(data===undefined){var localData=self.getLocalData();data=getOnlyChangedData(localData,self.lastReceivedSettings);}
if(self.testFoldersDuplicate()){delete data.folder;}
self.active=true;return OctoPrint.settings.save(data).done(function(data,status,xhr){self.ignoreNextUpdateEvent=!self.sawUpdateEventWhileSending;self.active=false;self.receiving(true);self.sending(false);try{self.fromResponse(data);if(options.success)options.success(data,status,xhr);}finally{self.receiving(false);}}).fail(function(xhr,status,error){self.sending(false);self.active=false;if(options.error)options.error(xhr,status,error);}).always(function(xhr,status){if(options.complete)options.complete(xhr,status);});};self.onEventSettingsUpdated=function(){if(self.active){self.sawUpdateEventWhileActive=true;}
var preventSettingsRefresh=_.any(self.allViewModels,function(viewModel){if(viewModel.hasOwnProperty("onSettingsPreventRefresh")){try{return viewModel["onSettingsPreventRefresh"]();}catch(e){log.warn("Error while calling onSettingsPreventRefresh on",viewModel,":",e);return false;}}else{return false;}});if(preventSettingsRefresh){return;}
if(self.isDialogActive()){if(self.sending()||self.receiving()||self.active||self.ignoreNextUpdateEvent){self.ignoreNextUpdateEvent=false;return;}
if(!hasDataChanged(self.getLocalData(),self.lastReceivedSettings)){self.requestData();}else{self.settingsUpdatedDialog.modal("show");}}else{self.requestData();}};self._resetScrollPosition=function(){$("#settings_dialog_content",self.settingsDialog).scrollTop(0);$('#settings_dialog_content ul.nav-pills a[data-toggle="tab"]:first',self.settingsDialog).tab("show");$('#settings_dialog_content ul.nav-list a[data-toggle="tab"]:first',self.settingsDialog).tab("show");$('#settings_dialog_content ul.nav-tabs a[data-toggle="tab"]:first',self.settingsDialog).tab("show");};self.selectTab=function(tab){if(tab!=undefined){if(!_.startsWith(tab,"#")){tab="#"+tab;}
$('ul.nav-list a[href="'+tab+'"]',self.settingsDialog).tab("show");}else{$('ul.nav-list a[data-toggle="tab"]:first',self.settingsDialog).tab("show");}};self.onServerReconnect=function(){self.requestData();};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){if(!self._startupComplete)return;self.requestData();};self.validURL=function(str){var pattern=new RegExp("^(https?:\\/\\/)?"+"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|"+"((\\d{1,3}\\.){3}\\d{1,3}))"+"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*"+"(\\?[;&a-z\\d%_.~+=-]*)?"+"(\\#[-a-z\\d_]*)?$","i");return!!pattern.test(str);};}
OCTOPRINT_VIEWMODELS.push({construct:SettingsViewModel,dependencies:["loginStateViewModel","accessViewModel","printerProfilesViewModel","aboutViewModel","usersViewModel"],elements:["#settings_dialog","#navbar_settings"]});});
;

// source: js/app/viewmodels/slicing.js
$(function(){function SlicingViewModel(parameters){var self=this;self.loginState=parameters[0];self.printerProfiles=parameters[1];self.printerState=parameters[2];self.access=parameters[3];self.file=ko.observable(undefined);self.target=undefined;self.path=undefined;self.data=undefined;self.defaultSlicer=undefined;self.defaultProfile=undefined;self.destinationFilename=ko.observable();self.gcodeFilename=self.destinationFilename;self.title=ko.observable();self.slicer=ko.observable();self.slicers=ko.observableArray();self.profile=ko.observable();self.profiles=ko.observableArray();self.printerProfile=ko.observable();self.slicerSameDevice=ko.observable();self.allViewModels=undefined;self.slicersForFile=function(file){if(file===undefined){return[];}
return _.filter(self.configuredSlicers(),function(slicer){return _.any(slicer.sourceExtensions,function(extension){return _.endsWith(file.toLowerCase(),"."+extension.toLowerCase());});});};self.profilesForSlicer=function(key){if(key==undefined){key=self.slicer();}
if(key==undefined||!self.data.hasOwnProperty(key)){return;}
var slicer=self.data[key];var selectedProfile=undefined;self.profiles.removeAll();_.each(_.values(slicer.profiles),function(profile){var name=profile.displayName;if(name==undefined){name=profile.key;}
if(profile.default){selectedProfile=profile.key;}
self.profiles.push({key:profile.key,name:name});});self.profile(selectedProfile);self.defaultProfile=selectedProfile;};self.resetProfiles=function(){self.profiles.removeAll();self.profile(undefined);};self.metadataForSlicer=function(key){if(key==undefined||!self.data.hasOwnProperty(key)){return;}
var slicer=self.data[key];self.slicerSameDevice(slicer.sameDevice);};self.resetMetadata=function(){self.slicerSameDevice(true);};self.configuredSlicers=ko.pureComputed(function(){return _.filter(self.slicers(),function(slicer){return slicer.configured;});});self.matchingSlicers=ko.computed(function(){var slicers=self.slicersForFile(self.file());var containsSlicer=function(key){return _.any(slicers,function(slicer){return slicer.key==key;});};var current=self.slicer();if(!containsSlicer(current)){if(self.defaultSlicer!==undefined&&containsSlicer(self.defaultSlicer)){self.slicer(self.defaultSlicer);}else{self.slicer(undefined);self.resetProfiles();}}else{self.profilesForSlicer(self.slicer());}
return slicers;});self.afterSlicingOptions=[{value:"none",text:gettext("Do nothing")},{value:"select",text:gettext("Select for printing")},{value:"print",text:gettext("Start printing")}];self.afterSlicing=ko.observable("none");self.show=function(target,file,force,path,options){options=options||{};if(!self.enableSlicingDialog()&&!force){return;}
var filename=file;if(filename.lastIndexOf("/")!=0){path=path||filename.substr(0,filename.lastIndexOf("/"));filename=filename.substr(filename.lastIndexOf("/")+1);}
var display=options.display||filename;var destination=display.substr(0,display.lastIndexOf("."));self.requestData();self.target=target;self.file(file);self.path=path;self.title(_.sprintf(gettext("Slicing %(filename)s"),{filename:_.escape(display)}));self.destinationFilename(destination);self.printerProfile(self.printerProfiles.currentProfile());self.afterSlicing("none");$("#slicing_configuration_dialog").modal("show");};self.slicer.subscribe(function(newValue){if(newValue===undefined){self.resetProfiles();self.resetMetadata();}else{self.profilesForSlicer(newValue);self.metadataForSlicer(newValue);}});self.enableSlicingDialog=ko.pureComputed(function(){return self.configuredSlicers().length>0;});self.enableSlicingDialogForFile=function(file){return self.slicersForFile(file).length>0;};self.enableSliceButton=ko.pureComputed(function(){return(self.destinationFilename()!=undefined&&self.destinationFilename().trim()!=""&&self.slicer()!=undefined&&self.profile()!=undefined&&(!(self.printerState.isPrinting()||self.printerState.isPaused())||!self.slicerSameDevice()));});self.sliceButtonTooltip=ko.pureComputed(function(){if(!self.enableSliceButton()){if((self.printerState.isPrinting()||self.printerState.isPaused())&&self.slicerSameDevice()){return gettext("Cannot slice on the same device while printing");}else{return gettext("Cannot slice, not all parameters specified");}}else{return gettext("Start the slicing process");}});self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.SLICE)){return;}
return OctoPrint.slicing.listAllSlicersAndProfiles().done(function(data){self.fromResponse(data);});};self.destinationExtension=ko.pureComputed(function(){var fallback="???";if(self.slicer()===undefined){return fallback;}
var slicer=self.data[self.slicer()];if(slicer===undefined){return fallback;}
var extensions=slicer.extensions;if(extensions===undefined){return fallback;}
var destinationExtensions=extensions.destination;if(destinationExtensions===undefined||!destinationExtensions.length){return fallback;}
return destinationExtensions[0]||fallback;});self.fromResponse=function(data){self.data=data;var selectedSlicer=undefined;self.slicers.removeAll();_.each(_.values(data),function(slicer){var name=slicer.displayName;if(name==undefined){name=slicer.key;}
if(slicer.default&&slicer.configured){selectedSlicer=slicer.key;}
var props={key:slicer.key,name:name,configured:slicer.configured,sourceExtensions:slicer.extensions.source,destinationExtensions:slicer.extensions.destination,sameDevice:slicer.sameDevice};self.slicers.push(props);});self.defaultSlicer=selectedSlicer;if(self.allViewModels){callViewModels(self.allViewModels,"onSlicingData",[data]);}};self.slice=function(){if(!self.enableSliceButton()){return;}
var destinationFilename=self.destinationFilename();var destinationExtensions=self.data[self.slicer()]&&self.data[self.slicer()].extensions&&self.data[self.slicer()].extensions.destination?self.data[self.slicer()].extensions.destination:["???"];if(!_.any(destinationExtensions,function(extension){return _.endsWith(destinationFilename.toLowerCase(),"."+extension.toLowerCase());})){destinationFilename=destinationFilename+"."+destinationExtensions[0];}
var data={slicer:self.slicer(),profile:self.profile(),printerProfile:self.printerProfile(),destination:destinationFilename};if(self.path!=undefined){data["path"]=self.path;}
if(self.afterSlicing()=="print"){data["print"]=true;}else if(self.afterSlicing()=="select"){data["select"]=true;}
OctoPrint.files.slice(self.target,self.file(),data).done(function(){$("#slicing_configuration_dialog").modal("hide");self.destinationFilename(undefined);self.slicer(self.defaultSlicer);self.profile(self.defaultProfile);});};self._sanitize=function(name){return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g,"").replace(/ /g,"_");};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};self.onEventSettingsUpdated=function(payload){self.requestData();};self.onAllBound=function(allViewModels){self.allViewModels=allViewModels;};}
OCTOPRINT_VIEWMODELS.push({construct:SlicingViewModel,dependencies:["loginStateViewModel","printerProfilesViewModel","printerStateViewModel","accessViewModel"],elements:["#slicing_configuration_dialog"]});});
;

// source: js/app/viewmodels/system.js
$(function(){function SystemViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.lastCommandResponse=undefined;self.systemActions=ko.observableArray([]);self._startupNotification=undefined;self.requestData=function(){self.requestCommandData();self.requestStartupData();};self.requestCommandData=function(){if(!self.loginState.hasPermission(self.access.permissions.SYSTEM)){return $.Deferred().reject().promise();}
return OctoPrint.system.getCommands().done(self.fromCommandResponse);};self.fromCommandResponse=function(response){var actions=[];if(response.core&&response.core.length){_.each(response.core,function(data){var action=_.extend({},data);action.actionSource="core";actions.push(action);});if((response.custom&&response.custom.length)||(response.plugin&&response.plugin.length)){actions.push({action:"divider"});}}
_.each(response.plugin,function(data){var action=_.extend({},data);action.actionSource="plugin";actions.push(action);if(response.custom&&response.custom.length){actions.push({action:"divider"});}});_.each(response.custom,function(data){var action=_.extend({},data);action.actionSource="custom";actions.push(action);});self.lastCommandResponse=response;self.systemActions(actions);};self.requestStartupData=function(){if(!self.loginState.hasPermission(self.access.permissions.SYSTEM)){return $.Deferred().reject().promise();}
return OctoPrint.system.getStartupData().done(self.fromStartupResponse);};self.fromStartupResponse=function(response){const startupData=response.startup;if(startupData.flagged_basefolders){if(self._startupNotification)self._startupNotification.remove();let html="<p>"+
gettext("The following folder(s) were found to be unusable by OctoPrint during startup and have been turned back to the default:")+"</p>";html+="<ul>";_.each(startupData.flagged_basefolders,(value,key)=>{html+="<li><code>"+
_.escape(key)+"</code>: "+
_.escape(value)+"</li>";});html+="</ul>";html+="<p>"+
gettext("Please check the permissions of these folders and make sure they are writable by the user running OctoPrint. In case of network shares, make sure they have been mounted <em>before</em> OctoPrint starts.")+"</p>";self._startupNotification=new PNotify({title:gettext("Warning"),text:html,type:"warning",hide:false});}};self.triggerCommand=function(commandSpec){if(!self.loginState.hasPermission(self.access.permissions.SYSTEM)){return $.Deferred().reject().promise();}
var deferred=$.Deferred();var callback=function(){OctoPrint.system.executeCommand(commandSpec.actionSource,commandSpec.action).done(function(){var text;if(commandSpec.async){text=gettext('The command "%(command)s" was triggered asynchronously');}else{text=gettext('The command "%(command)s" executed successfully');}
new PNotify({title:"Success",text:_.sprintf(text,{command:_.escape(commandSpec.name)}),type:"success"});deferred.resolve(["success",arguments]);}).fail(function(jqXHR,textStatus,errorThrown){if(!commandSpec.hasOwnProperty("ignore")||!commandSpec.ignore){var error="<p>"+
_.sprintf(gettext('The command "%(command)s" could not be executed.'),{command:_.escape(commandSpec.name)})+"</p>";error+=pnotifyAdditionalInfo("<pre>"+_.escape(jqXHR.responseText)+"</pre>");new PNotify({title:gettext("Error"),text:error,type:"error",hide:false});deferred.reject(["error",arguments]);}else{deferred.resolve(["ignored",arguments]);}});};if(commandSpec.confirm){showConfirmationDialog({message:commandSpec.confirm,onproceed:function(){callback();},oncancel:function(){deferred.reject("cancelled",arguments);}});}else{callback();}
return deferred.promise();};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(user){if(self.loginState.hasPermission(self.access.permissions.SYSTEM)){self.requestData();}else{self.lastCommandResponse=undefined;self.systemActions([]);}};self.onEventSettingsUpdated=function(){if(self.loginState.hasPermission(self.access.permissions.SYSTEM)){self.requestData();}};}
OCTOPRINT_VIEWMODELS.push({construct:SystemViewModel,dependencies:["loginStateViewModel","accessViewModel"]});});
;

// source: js/app/viewmodels/temperature.js
$(function(){function TemperatureViewModel(parameters){var self=this;self.loginState=parameters[0];self.settingsViewModel=parameters[1];self.access=parameters[2];self.printerState=parameters[3];self._createToolEntry=function(){var entry={name:ko.observable(),key:ko.observable(),actual:ko.observable(0),target:ko.observable(0),offset:ko.observable(0),newTarget:ko.observable(),newOffset:ko.observable()};entry.newTargetValid=ko.pureComputed(function(){var value=entry.newTarget();try{value=parseInt(value);}catch(exc){return false;}
return value>=0&&value<=999;});entry.newOffsetValid=ko.pureComputed(function(){var value=entry.newOffset();try{value=parseInt(value);}catch(exc){return false;}
return-50<=value<=50;});entry.offset.subscribe(function(newValue){if(self.changingOffset.item!==undefined&&self.changingOffset.item.key()===entry.key()){self.changingOffset.offset(newValue);}});return entry;};self.changingOffset={offset:ko.observable(0),newOffset:ko.observable(0),name:ko.observable(""),item:undefined,title:ko.pureComputed(function(){return _.sprintf(gettext("Changing Offset of %(name)s"),{name:_.escape(self.changingOffset.name())});}),description:ko.pureComputed(function(){return _.sprintf(gettext('Use the form below to specify a new offset to apply to all temperature commands sent from printed files for "%(name)s"'),{name:_.escape(self.changingOffset.name())});})};self.changeOffsetDialog=undefined;self.loginStateSubscription=undefined;self.tools=ko.observableArray([]);self.hasTools=ko.pureComputed(function(){return self.tools().length>0;});self.hasBed=ko.observable(true);self.hasChamber=ko.observable(false);self.visible=ko.pureComputed(function(){return self.hasTools()||self.hasBed();});self.bedTemp=self._createToolEntry();self.bedTemp["name"](gettext("Bed"));self.bedTemp["key"]("bed");self.chamberTemp=self._createToolEntry();self.chamberTemp["name"](gettext("Chamber"));self.chamberTemp["key"]("chamber");self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.temperature_profiles=self.settingsViewModel.temperature_profiles;self.temperature_cutoff=self.settingsViewModel.temperature_cutoff;self.heaterOptions=ko.observable({});self._printerProfileInitialized=false;self._currentTemperatureDataBacklog=[];self._historyTemperatureDataBacklog=[];self._graphUpdater=undefined;self._printerProfileUpdated=function(){var graphColors=["red","orange","green","brown","purple"];var heaterOptions={};var tools=[];var color;const currentProfileData=self.settingsViewModel.printerProfiles.currentProfileData();if(!currentProfileData)return;var numExtruders=currentProfileData?currentProfileData.extruder.count():0;var sharedNozzle=currentProfileData?currentProfileData.extruder.sharedNozzle():false;if(numExtruders&&numExtruders>1&&!sharedNozzle){for(var extruder=0;extruder<numExtruders;extruder++){color=graphColors.shift();if(!color)color="black";heaterOptions["tool"+extruder]={name:"T"+extruder,color:color};if(tools.length<=extruder||!tools[extruder]){tools[extruder]=self._createToolEntry();}
tools[extruder]["name"](gettext("Tool")+" "+extruder);tools[extruder]["key"]("tool"+extruder);}}else if(numExtruders===1||sharedNozzle){color=graphColors[0];heaterOptions["tool0"]={name:"T",color:color};if(tools.length<1||!tools[0]){tools[0]=self._createToolEntry();}
tools[0]["name"](gettext("Tool"));tools[0]["key"]("tool0");}
if(currentProfileData&&currentProfileData.heatedBed()){self.hasBed(true);heaterOptions["bed"]={name:gettext("Bed"),color:"blue"};}else{self.hasBed(false);}
if(currentProfileData&&currentProfileData.heatedChamber()){self.hasChamber(true);heaterOptions["chamber"]={name:gettext("Chamber"),color:"black"};}else{self.hasChamber(false);}
self.heaterOptions(heaterOptions);self.tools(tools);if(!self._printerProfileInitialized){self._triggerBacklog();}
self.updatePlot();};self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function(){self._printerProfileUpdated();self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);self.settingsViewModel.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);self.settingsViewModel.printerProfiles.currentProfileData().heatedChamber.subscribe(self._printerProfileUpdated);});self.markings=[];self.showStateMarks=ko.observable(loadFromLocalStorage("temperatureGraph.showStateMarks",true));self.showStateMarks.subscribe(function(newValue){saveToLocalStorage("temperatureGraph.showStateMarks",newValue);self.updatePlot();});self.toggleStateMarks=function(){self.showStateMarks(!self.showStateMarks());};self.temperatures=[];self.plot=undefined;self.plotHoverPos=undefined;self.plotLegendTimeout=undefined;self.fromCurrentData=function(data){self.markings=data.markings;self._processStateData(data.state);if(!self._printerProfileInitialized){self._currentTemperatureDataBacklog.push(data);}else{self._processTemperatureUpdateData(data.serverTime,data.temps);}
self._processOffsetData(data.offsets);};self.fromHistoryData=function(data){self.markings=data.markings;self._processStateData(data.state);if(!self._printerProfileInitialized){self._historyTemperatureDataBacklog.push(data);}else{self._processTemperatureHistoryData(data.serverTime,data.temps);}
self._processOffsetData(data.offsets);};self._triggerBacklog=function(){_.each(self._historyTemperatureDataBacklog,function(data){self._processTemperatureHistoryData(data.serverTime,data.temps);});_.each(self._currentTemperatureDataBacklog,function(data){self._processTemperatureUpdateData(data.serverTime,data.temps);});self._historyTemperatureDataBacklog=[];self._currentTemperatureDataBacklog=[];self._printerProfileInitialized=true;};self._processStateData=function(data){self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);};self._processTemperatureUpdateData=function(serverTime,data){if(data.length===0)return;var lastData=data[data.length-1];var tools=self.tools();for(var i=0;i<tools.length;i++){if(lastData.hasOwnProperty("tool"+i)){tools[i]["actual"](lastData["tool"+i].actual);tools[i]["target"](lastData["tool"+i].target);}else{tools[i]["actual"](0);tools[i]["target"](0);}}
if(lastData.hasOwnProperty("bed")){self.bedTemp["actual"](lastData.bed.actual);self.bedTemp["target"](lastData.bed.target);}else{self.bedTemp["actual"](0);self.bedTemp["target"](0);}
if(lastData.hasOwnProperty("chamber")){self.chamberTemp["actual"](lastData.chamber.actual);self.chamberTemp["target"](lastData.chamber.target);}else{self.chamberTemp["actual"](0);self.chamberTemp["target"](0);}
if(!CONFIG_TEMPERATURE_GRAPH)return;self.temperatures=self._processTemperatureData(serverTime,data,self.temperatures);self.updatePlot();};self._processTemperatureHistoryData=function(serverTime,data){self.temperatures=self._processTemperatureData(serverTime,data);self.updatePlot();};self._processOffsetData=function(data){var tools=self.tools();for(var i=0;i<tools.length;i++){if(data.hasOwnProperty("tool"+i)){tools[i]["offset"](data["tool"+i]);}else{tools[i]["offset"](0);}}
if(data.hasOwnProperty("bed")){self.bedTemp["offset"](data["bed"]);}else{self.bedTemp["offset"](0);}
if(data.hasOwnProperty("chamber")){self.chamberTemp["offset"](data["chamber"]);}else{self.chamberTemp["offset"](0);}};self._processTemperatureData=function(serverTime,data,result){var types=_.keys(self.heaterOptions());var clientTime=Date.now();if(!result){result={};}
_.each(types,function(type){if(!result.hasOwnProperty(type)){result[type]={actual:[],target:[]};}
if(!result[type].hasOwnProperty("actual"))result[type]["actual"]=[];if(!result[type].hasOwnProperty("target"))result[type]["target"]=[];});_.each(data,function(d){var timeDiff=(serverTime-d.time)*1000;var time=clientTime-timeDiff;_.each(types,function(type){if(!d[type])return;result[type].actual.push([time,d[type].actual]);result[type].target.push([time,d[type].target]);});});var temperature_cutoff=self.temperature_cutoff();if(temperature_cutoff!==undefined){const minTime=clientTime-temperature_cutoff*60*1000;var filterOld=function(item){return item[0]>=minTime;};_.each(_.keys(self.heaterOptions()),function(d){const actualLen=result[d].actual.length;result[d].actual=_.filter(result[d].actual,filterOld);if(actualLen&&result[d].actual.length<=actualLen){result[d].actual.unshift([minTime,undefined]);}
const targetLen=result[d].target.length;result[d].target=_.filter(result[d].target,filterOld);if(targetLen&&result[d].target.length<=targetLen){result[d].target.unshift([minTime,undefined]);}});}
return result;};self.profileText=function(heater,profile){var text=gettext("Set %(name)s (%(value)s)");var format=function(temp){if(temp===0||temp===undefined||temp===null){return gettext("Off");}else{return""+temp+"°C";}};var value;if(heater==="all"){value=gettext("Tool")+": %(extruder)s";if(self.hasBed()){value+="/"+gettext("Bed")+": %(bed)s";}
if(self.hasChamber()){value+="/"+gettext("Chamber")+": %(chamber)s";}
value=_.sprintf(value,{extruder:format(profile.extruder),bed:format(profile.bed),chamber:format(profile.chamber)});}else if(heater.key()==="bed"){value=format(profile.bed);}else if(heater.key()==="chamber"){value=format(profile.chamber);}else{value=format(profile.extruder);}
return _.sprintf(text,{name:_.escape(profile.name),value:_.escape(value)});};self.updatePlot=function(){var graph=$("#temperature-graph");if(!graph.length)return;if(!self.plot)return;var plotInfo=self._getPlotInfo();if(plotInfo===undefined)return;var newMax=Math.max(Math.max.apply(null,plotInfo.max)*1.1,310);if(newMax!==self.plot.getAxes().yaxis.max){self._initializePlot(true,plotInfo);}else{self.plot.setData(plotInfo.data);self.plot.setupGrid();self.updateLegend(self._replaceLegendLabel);self.plot.draw();}};self._drawMarkings=function(){var graph=$("#temperature-graph");if(!self.plot){return[];}
$(".temperature-mark-label").remove();if(!self.showStateMarks()){return[];}
var graphWidth=self.plot.width();var yAxisLabelWidth=40;var markingsLabelMargin=0;var lineWidth=2;var marks=self.markings.map(function(mark){var time=parseInt(mark.time*1000);var o=self.plot.pointOffset({x:time,y:self.plot.getAxes().yaxis.max});var markLabel=mark.type;if(mark.label){markLabel=gettext(mark.label);}
var label=$("<div></div>");label.html(markLabel);label.addClass("temperature-mark-label");label.addClass("temperature-mark-type-"+mark.type);if(o.left>yAxisLabelWidth){graph.append(label);if(o.left>graphWidth+
yAxisLabelWidth-
label.outerHeight()-
markingsLabelMargin){label.css("left",o.left-label.outerHeight()-markingsLabelMargin+"px");label.css("border-radius","5px 0 0 0");}else{label.css("left",o.left+markingsLabelMargin+"px");label.css("border-radius","0 0 0 5px");}
label.css("top",o.top+label.outerWidth()+"px");}
return{color:label.css("background-color"),lineWidth:lineWidth,xaxis:{from:time,to:time}};});return marks;};[gettext("Start"),gettext("Done"),gettext("Cancel"),gettext("Pause"),gettext("Resume"),gettext("Connected"),gettext("Disconnected")];self._initializePlot=function(force,plotInfo){var graph=$("#temperature-graph");if(!graph.length)return;if(self.plot&&!force)return;plotInfo=plotInfo||self._getPlotInfo();if(plotInfo===undefined)return;var options={yaxis:{min:0,max:Math.max(Math.max.apply(null,plotInfo.max)*1.1,310),ticks:10,tickFormatter:(val,axis)=>{if(val===undefined||val===0)return"";return val+"°C";}},xaxis:{mode:"time",ticks:(axis)=>{if(axis.max===undefined||axis.min===undefined||axis.datamax===axis.datamin)
return[];const tickSize=5*60*1000;const ticks=[];let val=axis.max;while(val>axis.min){ticks.push(val);val-=tickSize;}
return ticks;},tickFormatter:(val,axis)=>{var timestampUtc=Date.now();var diff=timestampUtc-val;var diffInMins=Math.round(diff/(60*1000));if(diffInMins<0){return"";}else if(diffInMins===0){return gettext("now");}else{return"- "+diffInMins+" "+gettext("min");}}},legend:{position:"sw",noColumns:2,backgroundOpacity:0}};if(!OctoPrint.coreui.browser.mobile){options["crosshair"]={mode:"x"};options["grid"]={hoverable:true,autoHighlight:false,markings:self._drawMarkings};}
self.plot=$.plot(graph,plotInfo.data,options);};self._getPlotInfo=function(){var data=[];var heaterOptions=self.heaterOptions();if(!heaterOptions)return undefined;var maxTemps=[310/1.1];var now=Date.now();var showFahrenheit=self._shallShowFahrenheit();_.each(_.keys(heaterOptions),function(type){if(type==="bed"&&!self.hasBed()){return;}
var actuals=[];var targets=[];if(self.temperatures[type]){actuals=self.temperatures[type].actual;targets=self.temperatures[type].target;}
var actualTemp=actuals&&actuals.length?formatTemperature(actuals[actuals.length-1][1],showFahrenheit):"-";var targetTemp=targets&&targets.length?formatTemperature(targets[targets.length-1][1],showFahrenheit,1):"-";data.push({label:gettext("Actual")+" "+
heaterOptions[type].name+": "+
actualTemp,color:heaterOptions[type].color,data:actuals.length?actuals:[[now,undefined]]});data.push({label:gettext("Target")+" "+
heaterOptions[type].name+": "+
targetTemp,color:pusher.color(heaterOptions[type].color).tint(0.5).html(),data:targets.length?targets:[[now,undefined]],dashes:{show:true}});maxTemps.push(self.getMaxTemp(actuals,targets));});return{max:maxTemps,data:data};};self.updateLegend=function(replaceLegendLabel){self.plotLegendTimeout=undefined;var resetLegend=function(){_.each(dataset,function(series,index){var value=series.data&&series.data.length?series.data[series.data.length-1][1]:undefined;replaceLegendLabel(index,series,value);});};var pos=self.plotHoverPos;if(pos&&!OctoPrint.coreui.browser.mobile){var i;var axes=self.plot.getAxes();var dataset=self.plot.getData();if(pos.x<axes.xaxis.min||pos.x>axes.xaxis.max||pos.y<axes.yaxis.min||pos.y>axes.yaxis.max){resetLegend();}else{_.each(dataset,function(series,index){for(i=0;i<series.data.length;i++){if(series.data[i][0]>pos.x){break;}}
var y;var p1=series.data[i-1];var p2=series.data[i];if(p1===undefined&&p2===undefined){y=undefined;}else if(p1===undefined){y=p2[1];}else if(p2===undefined){y=p1[1];}else{y=p1[1]+
((p2[1]-p1[1])*(pos.x-p1[0]))/(p2[0]-p1[0]);}
replaceLegendLabel(index,series,y,true);});}}else{resetLegend();}
self.plot.setupGrid();};self.getMaxTemp=function(actuals,targets){var maxTemp=0;actuals.forEach(function(pair){if(pair[1]>maxTemp){maxTemp=pair[1];}});targets.forEach(function(pair){if(pair[1]>maxTemp){maxTemp=pair[1];}});return maxTemp;};self.incrementTarget=function(item){var value=item.newTarget();if(value===undefined||(typeof value==="string"&&value.trim()==="")){value=item.target();}
try{value=parseInt(value);if(value>999)return;item.newTarget(value+1);self.autosendTarget(item);}catch(ex){}};self.decrementTarget=function(item){var value=item.newTarget();if(value===undefined||(typeof value==="string"&&value.trim()==="")){value=item.target();}
try{value=parseInt(value);if(value<=0)return;item.newTarget(value-1);self.autosendTarget(item);}catch(ex){}};var _sendTimeout={};self.autosendTarget=function(item){if(!self.settingsViewModel.temperature_sendAutomatically())return;var delay=self.settingsViewModel.temperature_sendAutomaticallyAfter()*1000;var name=item.name();if(_sendTimeout[name]){window.clearTimeout(_sendTimeout[name]);}
_sendTimeout[name]=window.setTimeout(function(){self.setTarget(item);delete _sendTimeout[name];},delay);};self.clearAutosendTarget=function(item){var name=item.name();if(_sendTimeout[name]){window.clearTimeout(_sendTimeout[name]);delete _sendTimeout[name];}};self.setTarget=function(item,form){var value=item.newTarget();if(form!==undefined){$(form).find("input").blur();}
if(value===undefined||(typeof value==="string"&&value.trim()===""))
return OctoPrintClient.createRejectedDeferred();self.clearAutosendTarget(item);return self.setTargetToValue(item,value);};self.setTargetsFromProfile=function(temperatureProfile){if(temperatureProfile===undefined){console.log("temperatureProfile is undefined!");return;}
if(self.hasBed()){self.setTargetFromProfile(self.bedTemp,temperatureProfile);}
if(self.hasChamber()){self.setTargetFromProfile(self.chamberTemp,temperatureProfile);}
self.tools().forEach(function(element){self.setTargetFromProfile(element,temperatureProfile);});};self.setTargetFromProfile=function(item,profile){if(!profile)return OctoPrintClient.createRejectedDeferred();self.clearAutosendTarget(item);var target;if(item.key()==="bed"){target=profile.bed;}else if(item.key()==="chamber"){target=profile.chamber;}else{target=profile.extruder;}
if(target===undefined)target=0;return self.setTargetToValue(item,target);};self.setTargetsToZero=function(){if(self.hasBed()){self.setTargetToZero(self.bedTemp);}
if(self.hasChamber()){self.setTargetToZero(self.chamberTemp);}
self.tools().forEach(function(element){self.setTargetToZero(element);});};self.setTargetToZero=function(item){self.clearAutosendTarget(item);return self.setTargetToValue(item,0);};self.setTargetToValue=function(item,value){self.clearAutosendTarget(item);try{value=parseInt(value);}catch(ex){return OctoPrintClient.createRejectedDeferred();}
if(value<0||value>999)return OctoPrintClient.createRejectedDeferred();var onSuccess=function(){item.target(value);item.newTarget("");};if(item.key()==="bed"){return self._setBedTemperature(value).done(onSuccess);}else if(item.key()==="chamber"){return self._setChamberTemperature(value).done(onSuccess);}else{return self._setToolTemperature(item.key(),value).done(onSuccess);}};self.changeOffset=function(item){self.changingOffset.item=item;self.changingOffset.name(item.name());self.changingOffset.offset(item.offset());self.changingOffset.newOffset(item.offset());self.changeOffsetDialog.modal("show");};self.incrementChangeOffset=function(){var value=self.changingOffset.newOffset();if(value===undefined||(typeof value==="string"&&value.trim()===""))
value=self.changingOffset.offset();try{value=parseInt(value);if(value>=50)return;self.changingOffset.newOffset(value+1);}catch(ex){}};self.decrementChangeOffset=function(){var value=self.changingOffset.newOffset();if(value===undefined||(typeof value==="string"&&value.trim()===""))
value=self.changingOffset.offset();try{value=parseInt(value);if(value<=-50)return;self.changingOffset.newOffset(value-1);}catch(ex){}};self.deleteChangeOffset=function(){self.changingOffset.newOffset(0);};self.confirmChangeOffset=function(){var item=self.changingOffset.item;item.newOffset(self.changingOffset.newOffset());self.setOffset(item).done(function(){self.changeOffsetDialog.modal("hide");self.changingOffset.offset(0);self.changingOffset.newOffset(0);self.changingOffset.name("");self.changingOffset.item=undefined;});};self.setOffset=function(item){var value=item.newOffset();if(value===undefined||(typeof value==="string"&&value.trim()===""))
return OctoPrintClient.createRejectedDeferred();return self.setOffsetToValue(item,value);};self.setOffsetToZero=function(item){return self.setOffsetToValue(item,0);};self.setOffsetToValue=function(item,value){try{value=parseInt(value);}catch(ex){return OctoPrintClient.createRejectedDeferred();}
if(value<-50||value>50)
return OctoPrintClient.createRejectedDeferred();var onSuccess=function(){item.offset(value);item.newOffset("");};if(item.key()==="bed"){return self._setBedOffset(value).done(onSuccess);}else if(item.key()==="chamber"){return self._setChamberOffset(value).done(onSuccess);}else{return self._setToolOffset(item.key(),value).done(onSuccess);}};self._setToolTemperature=function(tool,temperature){var data={};data[tool]=parseInt(temperature);return OctoPrint.printer.setToolTargetTemperatures(data);};self._setToolOffset=function(tool,offset){var data={};data[tool]=parseInt(offset);return OctoPrint.printer.setToolTemperatureOffsets(data);};self._setBedTemperature=function(temperature){return OctoPrint.printer.setBedTargetTemperature(parseInt(temperature));};self._setBedOffset=function(offset){return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));};self._setChamberTemperature=function(temperature){return OctoPrint.printer.setChamberTargetTemperature(parseInt(temperature));};self._setChamberOffset=function(offset){return OctoPrint.printer.setChamberTemperatureOffset(parseInt(offset));};self._replaceLegendLabel=function(index,series,value,emph){var showFahrenheit=self._shallShowFahrenheit();var temp;if(index%2===0){temp=formatTemperature(value,showFahrenheit);}else{temp=formatTemperature(value,showFahrenheit,1);}
if(emph){temp="<em>"+temp+"</em>";}
series.label=series.label.replace(/:.*/,": "+temp);};self._shallShowFahrenheit=function(){return self.settingsViewModel.settings!==undefined?self.settingsViewModel.settings.appearance.showFahrenheitAlso():false;};self.handleEnter=function(event,type,item){if(event.keyCode===13){if(type==="target"){self.setTarget(item).done(function(){event.target.blur();});}else if(type==="offset"){self.confirmChangeOffset();}}};self.handleFocus=function(event,type,item){if(type==="target"){var value=item.newTarget();if(value===undefined||(typeof value==="string"&&value.trim()==="")){item.newTarget(item.target());}
window.setTimeout(function(){event.target.select();},0);}else if(type==="offset"){window.setTimeout(function(){event.target.select();},0);}};self.initOrUpdate=function(){if(OctoPrint.coreui.selectedTab!=="#temp"||!$("#temp").is(":visible")){return;}
if(!self.plot){self._initializePlot();}else{self.updatePlot();}};self.onAfterTabChange=function(){self.initOrUpdate();};self.onStartup=function(){var graph=$("#temperature-graph");if(graph.length&&!OctoPrint.coreui.browser.mobile){graph.bind("plothover",function(event,pos,item){self.plotHoverPos=pos;if(!self.plotLegendTimeout){self.plotLegendTimeout=window.setTimeout(function(){self.updateLegend(self._replaceLegendLabel);},50);}});}
self.changeOffsetDialog=$("#change_offset_dialog");self._graphUpdater=setInterval(()=>{if(self.printerState.isOperational())return;const now=Date.now()/1000;const entry={};_.each(_.keys(self.heaterOptions()),(type)=>{entry[type]={actual:undefined,target:undefined};});entry["time"]=now;self.temperatures=self._processTemperatureData(now,[entry],self.temperatures);self.updatePlot();},1000);};self.onStartupComplete=function(){self.initOrUpdate();self._printerProfileUpdated();};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.initOrUpdate();};}
OCTOPRINT_VIEWMODELS.push({construct:TemperatureViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel","printerStateViewModel"],elements:["#temp","#temp_link","#change_offset_dialog"]});});
;

// source: js/app/viewmodels/terminal.js
$(function(){function TerminalViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.access=parameters[2];self.tabActive=false;self.previousScroll=undefined;self.log=ko.observableArray([]);self.log.extend({throttle:500});self.plainLogLines=ko.observableArray([]);self.plainLogLines.extend({throttle:500});self.buffer=ko.observable(300);self.upperLimit=ko.observable(1499);self.command=ko.observable(undefined);self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.autoscrollEnabled=ko.observable(true);self.filters=self.settings.terminalFilters;self.filterRegex=ko.observable();self.cmdHistory=[];self.cmdHistoryIdx=-1;self.enableFancyFunctionality=ko.observable(true);self.disableTerminalLogDuringPrinting=ko.observable(false);self.acceptableFancyTime=500;self.acceptableUnfancyTime=300;self.reenableTimeout=5000;self.forceFancyFunctionality=ko.observable(false);self.forceTerminalLogDuringPrinting=ko.observable(false);self.fancyFunctionality=ko.pureComputed(function(){return self.enableFancyFunctionality()||self.forceFancyFunctionality();});self.terminalLogDuringPrinting=ko.pureComputed(function(){return(!self.disableTerminalLogDuringPrinting()||self.forceTerminalLogDuringPrinting());});self.displayedLines=ko.pureComputed(function(){if(!self.enableFancyFunctionality()){return self.log();}
var regex=self.filterRegex();var lineVisible=function(entry){return regex===undefined||!entry.line.match(regex);};var filtered=false;var result=[];var lines=self.log();_.each(lines,function(entry){if(lineVisible(entry)){result.push(entry);filtered=false;}else if(!filtered){result.push(self._toInternalFormat("[...]","filtered"));filtered=true;}});return result;});self.plainLogOutput=ko.pureComputed(function(){if(self.fancyFunctionality()){return;}
return self.plainLogLines().join("\n");});self.lineCount=ko.pureComputed(function(){if(!self.fancyFunctionality()){return;}
var regex=self.filterRegex();var lineVisible=function(entry){return regex===undefined||!entry.line.match(regex);};var lines=self.log();var total=lines.length;var displayed=_.filter(lines,lineVisible).length;var filtered=total-displayed;if(filtered>0){if(total>self.upperLimit()){return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered, buffer full)"),{displayed:displayed,total:total,filtered:filtered});}else{return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"),{displayed:displayed,total:total,filtered:filtered});}}else{if(total>self.upperLimit()){return _.sprintf(gettext("showing %(displayed)d lines (buffer full)"),{displayed:displayed});}else{return _.sprintf(gettext("showing %(displayed)d lines"),{displayed:displayed});}}});self.autoscrollEnabled.subscribe(function(newValue){if(newValue){self.log(self.log.slice(-self.buffer()));}});self.activeFilters=ko.observableArray([]);self.activeFilters.subscribe(function(e){self.updateFilterRegex();});self.blacklist=[];self.settings.feature_autoUppercaseBlacklist.subscribe(function(newValue){self.blacklist=splitTextToArray(newValue,",",true);});self._reenableFancyTimer=undefined;self._reenableUnfancyTimer=undefined;self._disableFancy=function(difference){if(self.enableFancyFunctionality()){log.warn("Terminal: Detected slow client (needed "+
difference+"ms for processing new log data), disabling fancy terminal functionality");self.enableFancyFunctionality(false);}
if(self._reenableFancyTimer){window.clearTimeout(self._reenableFancyTimer);self._reenableFancyTimer=undefined;}};self._reenableFancy=function(difference){if(self._reenableFancyTimer)return;if(self.enableFancyFunctionality())return;self._reenableFancyTimer=window.setTimeout(function(){log.info("Terminal: Client speed recovered, enabling fancy terminal functionality");self.enableFancyFunctionality(true);},self.reenableTimeout);};self._disableUnfancy=function(difference){if(!self.disableTerminalLogDuringPrinting()){log.warn("Terminal: Detected very slow client (needed "+
difference+"ms for processing new log data), completely disabling terminal output during printing");self.disableTerminalLogDuringPrinting(true);}
if(self._reenableUnfancyTimer){window.clearTimeout(self._reenableUnfancyTimer);self._reenableUnfancyTimer=undefined;}};self._reenableUnfancy=function(){if(self._reenableUnfancyTimer)return;if(!self.disableTerminalLogDuringPrinting())return;self._reenableUnfancyTimer=window.setTimeout(function(){log.info("Terminal: Client speed recovered, enabling terminal output during printing");self.disableTerminalLogDuringPrinting(false);},self.reenableTimeout);};self.fromCurrentData=function(data){self._processStateData(data.state);var start=new Date().getTime();self._processCurrentLogData(data.logs);var end=new Date().getTime();var difference=end-start;if(difference>=self.acceptableFancyTime){self._disableFancy(difference);}else if(difference>=self.acceptableUnfancyTime){self._disableUnfancy(difference);}else if(difference<self.acceptableFancyTime/2.0){self._reenableFancy(difference);}else if(difference<self.acceptableUnfancyTime/2.0){self._reenableUnfancy(difference);}};self.fromHistoryData=function(data){self._processStateData(data.state);self._processHistoryLogData(data.logs);};self._processCurrentLogData=function(data){if(!data)return;var length=self.log().length;if(length>=self.upperLimit()){return;}
if(!self.terminalLogDuringPrinting()&&self.isPrinting()){var last=self.plainLogLines()[self.plainLogLines().length-1];var disabled="--- client too slow, log output disabled while printing ---";if(last!==disabled){self.plainLogLines.push(disabled);}
return;}
var newData=data.length+length>self.upperLimit()?data.slice(0,self.upperLimit()-length):data;if(!newData){return;}
if(!self.fancyFunctionality()){self.plainLogLines(self.plainLogLines().concat(newData).slice(-self.buffer()));self.updateOutput();return;}
var newLog=self.log().concat(_.map(newData,function(line){return self._toInternalFormat(line);}));if(newData.length!==data.length){var cutoff="--- too many lines to buffer, cut off ---";newLog.push(self._toInternalFormat(cutoff,"cut"));}
if(self.autoscrollEnabled()){newLog=newLog.slice(-self.buffer());}
self.log(newLog);self.updateOutput();};self._processHistoryLogData=function(data){if(!data)return;self.plainLogLines(data);self.log(_.map(data,self._toInternalFormat));self.updateOutput();};self._toInternalFormat=function(line,display,type){if(display===undefined){display="line";}
if(type===undefined||typeof type!="string"){if(line.startsWith("Recv:")){type="recv";}else if(line.startsWith("Send:")){type="send";}else if(line.startsWith("Warn:")){type="warn";}}
return{line:escapeUnprintableCharacters(line),display:display,type:type};};self._processStateData=function(data){self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);};self.updateFilterRegex=function(){var filterRegexStr=self.activeFilters().join("|").trim();if(filterRegexStr===""){self.filterRegex(undefined);}else{self.filterRegex(new RegExp(filterRegexStr));}
self.updateOutput();};self.updateOutput=function(){if(self.tabActive&&OctoPrint.coreui.browserTabVisible&&self.autoscrollEnabled()){self.scrollToEnd();}};self.terminalScrollEvent=_.throttle(function(){var container=self.fancyFunctionality()?$("#terminal-output"):$("#terminal-output-lowfi");var pos=container.scrollTop();var scrollingUp=self.previousScroll!==undefined&&pos<self.previousScroll;if(self.autoscrollEnabled()&&scrollingUp){var maxScroll=container[0].scrollHeight-container[0].offsetHeight;if(pos<=maxScroll){self.autoscrollEnabled(false);}}
self.previousScroll=pos;},250);self.gotoTerminalCommand=function(){var sel=getSelection().toString();if(sel){return;}
$("#terminal-command").focus();};self.toggleAutoscroll=function(){self.autoscrollEnabled(!self.autoscrollEnabled());if(self.autoscrollEnabled()){self.updateOutput();}};self.selectAll=function(){var container=self.fancyFunctionality()?$("#terminal-output"):$("#terminal-output-lowfi");if(container.length){container.selectText();}};self.scrollToEnd=function(){var container=self.fancyFunctionality()?$("#terminal-output"):$("#terminal-output-lowfi");if(container.length){container.scrollTop(container[0].scrollHeight);}};self.copyAll=function(){var lines;if(self.fancyFunctionality()){lines=_.map(self.log(),"line");}else{lines=self.plainLogLines();}
copyToClipboard(lines.join("\n"));};self.clearAllLogs=function(){self.log([]);self.plainLogLines([]);};var commandRe=/^(([gmt][0-9]+)(\.[0-9+])?)(\s.*)?/i;self.sendCommand=function(){var command=self.command();if(!command){return;}
var commandToSend=command;var commandMatch=commandToSend.match(commandRe);if(commandMatch!==null){var fullCode=commandMatch[1].toUpperCase();var mainCode=commandMatch[2].toUpperCase();if(self.blacklist.indexOf(mainCode)<0&&self.blacklist.indexOf(fullCode)<0){commandToSend=commandToSend.toUpperCase();}else{commandToSend=fullCode+(commandMatch[4]!==undefined?commandMatch[4]:"");}}
if(commandToSend){OctoPrint.control.sendGcode(commandToSend).done(function(){self.cmdHistory.push(command);self.cmdHistory.slice(-300);self.cmdHistoryIdx=self.cmdHistory.length;self.command("");});}};self.fakeAck=function(){OctoPrint.connection.fakeAck();};self.handleKeyDown=function(event){var keyCode=event.keyCode;if(keyCode===38||keyCode===40){if(keyCode===38&&self.cmdHistory.length>0&&self.cmdHistoryIdx>0){self.cmdHistoryIdx--;}else if(keyCode===40&&self.cmdHistoryIdx<self.cmdHistory.length-1){self.cmdHistoryIdx++;}
if(self.cmdHistoryIdx>=0&&self.cmdHistoryIdx<self.cmdHistory.length){self.command(self.cmdHistory[self.cmdHistoryIdx]);}
return false;}
return true;};self.handleKeyUp=function(event){if(event.keyCode===13){self.sendCommand();}
return true;};self.onAfterTabChange=function(current,previous){self.tabActive=current==="#term";self.updateOutput();};self.onBrowserTabVisibilityChange=function(status){self.updateOutput();};self.onEventCommandSuppressed=function(payload){var setting=self.settings.settings.serial.notifySuppressedCommands();if(setting==="never"||(setting==="warn"&&payload.severity==="info")){return;}
var severity=payload.severity;if(severity==="warn"){severity="error";}else if(severity==="info"){severity="warn";}
var text="<p>"+
gettext("The command <code>%(command)s</code> was not sent "+"to the printer:")+"</p><p><pre>%(message)s</pre></p>";new PNotify({title:gettext("Suppressed command"),text:_.sprintf(text,payload),type:severity,hide:false});};self.onEventInvalidToolReported=function(payload){new PNotify({title:gettext("Invalid tool reported"),text:_.sprintf(gettext("Your printer reported tool T%(tool)d as invalid, "+"reverting back to T%(fallback)d"),payload),type:"error",hide:false});};}
OCTOPRINT_VIEWMODELS.push({construct:TerminalViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel"],elements:["#term","#term_link"]});});
;

// source: js/app/viewmodels/timelapse.js
$(function(){function TimelapseViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.settings=parameters[2];self.renderProgressBar=undefined;self.timelapsePopup=undefined;self.defaultFps=25;self.defaultPostRoll=0;self.defaultInterval=10;self.defaultRetractionZHop=0;self.defaultMinDelay=5.0;self.timelapseType=ko.observable(undefined);self.timelapseTimedInterval=ko.observable(self.defaultInterval);self.timelapsePostRoll=ko.observable(self.defaultPostRoll);self.timelapseFps=ko.observable(self.defaultFps);self.timelapseRetractionZHop=ko.observable(self.defaultRetractionZHop);self.timelapseMinDelay=ko.observable(self.defaultMinDelay);self.snapshotWebcam=ko.pureComputed(function(){var snapshotWebcamName=self.settings.webcam_snapshotWebcam();return self.settings.webcam_webcams().find(function(w){return snapshotWebcamName==w.name;});});self.canSnapshot=ko.pureComputed(function(){if(!self.snapshotWebcam()){return false;}else{return self.snapshotWebcam().canSnapshot;}});self.snapshotDisplay=ko.pureComputed(function(){if(!self.snapshotWebcam()){return"";}else{return self.snapshotWebcam().snapshotDisplay;}});self.renderProgress=ko.observable();self.renderTarget=ko.observable();self.renderAnimation=ko.observable(false);self.renderProgressString=ko.pureComputed(function(){if(!self.renderTarget()){return 0;}
if(self.renderAnimation()){return 100;}
if(!self.renderProgress()){return 0;}
return self.renderProgress();});self.renderProgressBarString=ko.pureComputed(function(){if(!self.renderTarget()){return"";}
if(self.renderAnimation()){return _.sprintf(gettext("Rendering %(target)s..."),{target:self.renderTarget()});}
var progress=self.renderProgress();if(!progress){progress=0;}
return _.sprintf(gettext("Rendering %(target)s... (%(progress)d%%)"),{target:self.renderTarget(),progress:progress});});self.serverConfig=ko.observable();self.persist=ko.observable(false);self.isDirty=ko.observable(false);self.isErrorOrClosed=ko.observable(undefined);self.isOperational=ko.observable(undefined);self.isPrinting=ko.observable(undefined);self.isPaused=ko.observable(undefined);self.isError=ko.observable(undefined);self.isReady=ko.observable(undefined);self.isLoading=ko.observable(undefined);self.markedForFileDeletion=ko.observableArray([]);self.markedForUnrenderedDeletion=ko.observableArray([]);self.isTemporary=ko.pureComputed(function(){return self.isDirty()&&!self.persist();});self.isBusy=ko.pureComputed(function(){return self.isPrinting()||self.isPaused();});self.timelapseTypeSelected=ko.pureComputed(function(){return"off"!==self.timelapseType();});self.intervalInputEnabled=ko.pureComputed(function(){return"timed"===self.timelapseType();});self.saveButtonEnabled=ko.pureComputed(function(){return(self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN)&&self.isDirty()&&!self.isPrinting());});self.resetButtonEnabled=ko.pureComputed(function(){return self.saveButtonEnabled()&&self.serverConfig()!==undefined;});self.timelapseType.subscribe(function(){self.isDirty(true);});self.timelapseTimedInterval.subscribe(function(){self.isDirty(true);});self.timelapsePostRoll.subscribe(function(){self.isDirty(true);});self.timelapseFps.subscribe(function(){self.isDirty(true);});self.timelapseRetractionZHop.subscribe(function(newValue){self.isDirty(true);});self.timelapseMinDelay.subscribe(function(){self.isDirty(true);});self.persist.subscribe(function(){self.isDirty(true);});self.listHelper=new ItemListHelper("timelapseFiles",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;},date:function(a,b){if(a["date"]>b["date"])return-1;if(a["date"]<b["date"])return 1;return 0;},size:function(a,b){if(a["bytes"]>b["bytes"])return-1;if(a["bytes"]<b["bytes"])return 1;return 0;}},{},"name",[],[],CONFIG_TIMELAPSEFILESPERPAGE);self.unrenderedListHelper=new ItemListHelper("unrenderedTimelapseFiles",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;},creation:function(a,b){if(a["date"]>b["date"])return-1;if(a["date"]<b["date"])return 1;return 0;},size:function(a,b){if(a["bytes"]>b["bytes"])return-1;if(a["bytes"]<b["bytes"])return 1;return 0;}},{},"name",[],[],CONFIG_TIMELAPSEFILESPERPAGE);self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_LIST))
return;OctoPrint.timelapse.get(true).done(self.fromResponse);};self.fromResponse=function(response){var config=response.config;if(config===undefined)return;self.listHelper.updateItems(response.files);self.listHelper.resetPage();if(response.unrendered){self.unrenderedListHelper.updateItems(response.unrendered);self.unrenderedListHelper.resetPage();}
self.fromConfig(response.config);self.serverConfig(response.config);};self.fromConfig=function(config){self.timelapseType(config.type);if(config.type==="timed"&&config.interval!==undefined&&config.interval>0){self.timelapseTimedInterval(config.interval);}else{self.timelapseTimedInterval(self.defaultInterval);}
if(config.type==="zchange"&&config.retractionZHop!==undefined&&config.retractionZHop>0){self.timelapseRetractionZHop(config.retractionZHop);}else{self.timelapseRetractionZHop(self.defaultRetractionZHop);}
if(config.type==="zchange"&&config.minDelay!==undefined&&config.minDelay>=0){self.timelapseMinDelay(config.minDelay);}else{self.timelapseMinDelay(self.defaultMinDelay);}
if(config.postRoll!==undefined&&config.postRoll>=0){self.timelapsePostRoll(config.postRoll);}else{self.timelapsePostRoll(self.defaultPostRoll);}
if(config.fps!==undefined&&config.fps>0){self.timelapseFps(config.fps);}else{self.timelapseFps(self.defaultFps);}
self.persist(false);self.isDirty(false);};self.fromCurrentData=function(data){self._processStateData(data.state);};self.fromHistoryData=function(data){self._processStateData(data.state);};self._processStateData=function(data){self.isErrorOrClosed(data.flags.closedOrError);self.isOperational(data.flags.operational);self.isPaused(data.flags.paused);self.isPrinting(data.flags.printing);self.isError(data.flags.error);self.isReady(data.flags.ready);self.isLoading(data.flags.loading);};self.markFilesOnPage=function(){self.markedForFileDeletion(_.uniq(self.markedForFileDeletion().concat(_.map(self.listHelper.paginatedItems(),"name"))));};self.markAllFiles=function(){self.markedForFileDeletion(_.map(self.listHelper.allItems,"name"));};self.clearMarkedFiles=function(){self.markedForFileDeletion.removeAll();};self.isTimelapseViewable=function(data){var url=data.url;return(self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DOWNLOAD)&&url.indexOf(".mp4")>=0);};self.showTimelapsePreview=function(data){if(!self.isTimelapseViewable(data))return;var url=data.url;var previewModal=$("#timelapsePreviewModal");previewModal.children("div.modal-body").children("video").attr("src",url);previewModal.off("hidden.bs.modal").on("hidden.bs.modal",function(){$(this).attr("src","");});previewModal.modal("show");};self.removeFile=function(filename){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
return;var perform=function(){OctoPrint.timelapse.delete(filename).done(function(){self.markedForFileDeletion.remove(filename);self.requestData();}).fail(function(jqXHR){var html="<p>"+
_.sprintf(gettext("Failed to remove timelapse %(name)s.</p><p>Please consult octoprint.log for details.</p>"),{name:_.escape(filename)});html+=pnotifyAdditionalInfo('<pre style="overflow: auto">'+
_.escape(jqXHR.responseText)+"</pre>");new PNotify({title:gettext("Could not remove timelapse"),text:html,type:"error",hide:false});});};showConfirmationDialog(_.sprintf(gettext('You are about to delete timelapse file "%(name)s".'),{name:_.escape(filename)}),perform);};self.removeMarkedFiles=function(){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DELETE))
return;var perform=function(){self._bulkRemove(self.markedForFileDeletion(),"files").done(function(){self.markedForFileDeletion.removeAll();});};showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d timelapse files."),{count:self.markedForFileDeletion().length}),perform);};self.enableBulkDownload=ko.pureComputed(function(){return(self.markedForFileDeletion().length&&!self.isBusy()&&!self.bulkDownloadUrlTooLong());});self.bulkDownloadUrlTooLong=ko.pureComputed(function(){return BASEURL.length+self.bulkDownloadUrl().length>=2000;});self.bulkDownloadButtonUrl=ko.pureComputed(function(){var files=self.markedForFileDeletion();if(!files.length||self.bulkDownloadUrlTooLong()){return"javascript:void(0)";}
return self.bulkDownloadUrl();});self.bulkDownloadUrl=function(){var files=self.markedForFileDeletion();return OctoPrint.timelapse.bulkDownloadUrl(files);};self.markUnrenderedOnPage=function(){self.markedForUnrenderedDeletion(_.uniq(self.markedForUnrenderedDeletion().concat(_.map(self.unrenderedListHelper.paginatedItems(),"name"))));};self.markAllUnrendered=function(){self.markedForUnrenderedDeletion(_.map(self.unrenderedListHelper.allItems,"name"));};self.clearMarkedUnrendered=function(){self.markedForUnrenderedDeletion.removeAll();};self.removeUnrendered=function(name){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_MANAGE_UNRENDERED))
return;var perform=function(){OctoPrint.timelapse.deleteUnrendered(name).done(function(){self.markedForUnrenderedDeletion.remove(name);self.requestData();});};showConfirmationDialog(_.sprintf(gettext('You are about to delete unrendered timelapse "%(name)s".'),{name:_.escape(name)}),perform);};self.removeMarkedUnrendered=function(){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_MANAGE_UNRENDERED))
return;var perform=function(){self._bulkRemove(self.markedForUnrenderedDeletion(),"unrendered").done(function(){self.markedForUnrenderedDeletion.removeAll();});};showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d unrendered timelapses."),{count:self.markedForUnrenderedDeletion().length}),perform);};self._bulkRemove=function(files,type){var title,message,handler;if(type==="files"){title=gettext("Deleting timelapse files");message=_.sprintf(gettext("Deleting %(count)d timelapse files..."),{count:files.length});handler=function(filename){return OctoPrint.timelapse.delete(filename).done(function(){deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."),{filename:_.escape(filename)}),true);}).fail(function(jqXHR){var short=_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."),{filename:_.escape(filename)});var long=_.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"),{filename:_.escape(filename),error:_.escape(jqXHR.responseText)});deferred.notify(short,long,false);});};}else if(type==="unrendered"){title=gettext("Deleting unrendered timelapses");message=_.sprintf(gettext("Deleting %(count)d unrendered timelapses..."),{count:files.length});handler=function(filename){return OctoPrint.timelapse.deleteUnrendered(filename).done(function(){deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."),{filename:_.escape(filename)}),true);}).fail(function(){deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."),{filename:_.escape(filename)}),false);});};}else{return;}
var deferred=$.Deferred();var promise=deferred.promise();var options={title:title,message:message,max:files.length,output:true};showProgressModal(options,promise);var requests=[];_.each(files,function(filename){var request=handler(filename);requests.push(request);});$.when.apply($,_.map(requests,wrapPromiseWithAlways)).done(function(){deferred.resolve();self.requestData();});return promise;};self.renderUnrendered=function(name){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN))
return;OctoPrint.timelapse.renderUnrendered(name).done(self.requestData);};self.save=function(){if(!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN))
return;var payload={type:self.timelapseType(),postRoll:self.timelapsePostRoll(),fps:self.timelapseFps(),save:self.persist()};if(self.timelapseType()==="timed"){payload["interval"]=self.timelapseTimedInterval();}
if(self.timelapseType()==="zchange"){payload["retractionZHop"]=self.timelapseRetractionZHop();payload["minDelay"]=self.timelapseMinDelay();}
OctoPrint.timelapse.saveConfig(payload).done(self.fromResponse);};self.reset=function(){if(self.serverConfig()===undefined)return;self.fromConfig(self.serverConfig());};self.displayTimelapsePopup=function(options){if(self.timelapsePopup!==undefined){self.timelapsePopup.remove();}
_.extend(options,{callbacks:{before_close:function(notice){if(self.timelapsePopup===notice){self.timelapsePopup=undefined;}}}});self.timelapsePopup=new PNotify(options);};self.onDataUpdaterReconnect=function(){self.requestData();};self.onEventPostRollStart=function(payload){var title=gettext("Capturing timelapse postroll");var text;if(!payload.postroll_duration){text=_.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."));}else{var format={time:moment().add(payload.postroll_duration,"s").format("LT")};if(payload.postroll_duration>60){format.duration=_.sprintf(gettext("%(minutes)d min"),{minutes:payload.postroll_duration/60});text=_.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s (so until %(time)s)..."),format);}else{format.duration=_.sprintf(gettext("%(seconds)d sec"),{seconds:payload.postroll_duration});text=_.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."),format);}}
self.displayTimelapsePopup({title:title,text:text,hide:false});};self._warnAboutCaptureFailThreshold=3;self._warnAboutCaptureFailCounter=0;self._warnedAboutCaptureFail=false;self.onEventPrintStarted=function(payload){self._warnAboutCaptureFailCounter=0;self._warnedAboutCaptureFail=false;};self.onEventCaptureDone=function(payload){self._warnAboutCaptureFailCounter=0;self._warnedAboutCaptureFail=false;};self.onEventCaptureFailed=function(payload){self._warnAboutCaptureFailCounter++;if(self._warnedAboutCaptureFail||self._warnAboutCaptureFailCounter<=self._warnAboutCaptureFailThreshold){return;}
self._warnedAboutCaptureFail=true;var html="<p>"+
gettext("Failed repeatedly to capture timelapse frame from webcam - is the snapshot webcam configured correctly and the camera on?");var additional="";if(payload.snapshotDisplay){additional+='Snapshot info: <pre style="overflow: auto">'+
payload.snapshotDisplay+"</pre>";}
if(payload.webcamDisplay){additional+='Webcam: <pre style="overflow: auto">'+
payload.webcamDisplay+"</pre>";}
if(payload.error){additional+='Error: <pre style="overflow: auto">'+payload.error+"</pre>";}
if(additional){html+=pnotifyAdditionalInfo(additional);}
new PNotify({title:gettext("Could not capture snapshots"),text:html,type:"error",hide:false});};self.onEventMovieRendering=function(payload){self.displayTimelapsePopup({title:gettext("Rendering timelapse"),text:_.sprintf(gettext("Now rendering timelapse %(movie_prefix)s. Due to performance reasons it is not recommended to start a print job while a movie is still rendering."),{movie_prefix:_.escape(payload.movie_prefix)}),hide:false});self.renderProgress(0);self.renderTarget(payload.movie_prefix);self.renderAnimation(true);};self.onRenderProgress=function(percentage){self.renderProgress(percentage);self.renderAnimation(false);};self.onEventMovieFailed=function(payload){var title,html;if(payload.reason==="no_frames"){title=gettext("Cannot render timelapse");html="<p>"+
_.sprintf(gettext("Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the snapshot webcam configured correctly?"),{movie_prefix:_.escape(payload.movie_prefix)})+"</p>";}else if((payload.reason="returncode")){title=gettext("Rendering timelapse failed");html="<p>"+
_.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed with return code %(returncode)s"),{movie_prefix:_.escape(payload.movie_prefix),returncode:_.escape(payload.returncode)})+"</p>";html+=pnotifyAdditionalInfo('<pre style="overflow: auto">'+payload.error+"</pre>");}else{title=gettext("Rendering timelapse failed");html="<p>"+
_.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed due to an unknown error, please consult the log file"),{movie_prefix:_.escape(payload.movie_prefix)})+"</p>";}
self.displayTimelapsePopup({title:title,text:html,type:"error",hide:false});self.renderProgress(0);self.renderTarget(undefined);self.renderAnimation(false);};self.onEventMovieDone=function(payload){self.displayTimelapsePopup({title:gettext("Timelapse ready"),text:_.sprintf(gettext("New timelapse %(movie_prefix)s is done rendering."),{movie_prefix:_.escape(payload.movie_prefix)}),type:"success",callbacks:{before_close:function(notice){if(self.timelapsePopup===notice){self.timelapsePopup=undefined;}}}});self.requestData();self.renderProgress(0);self.renderTarget(undefined);self.renderAnimation(false);};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();self.renderProgressBar=$("#render_progress");};}
OCTOPRINT_VIEWMODELS.push({construct:TimelapseViewModel,dependencies:["loginStateViewModel","accessViewModel","settingsViewModel"],elements:["#timelapse","#timelapse_link","#timelapsePreviewModal"]});});
;

// source: js/app/viewmodels/uistate.js
$(function(){function UiStateViewModel(parameters){var self=this;self.loading=ko.observable(CONFIG_LOADINGANIMATION);self.loading_error=ko.observable(false);self.visible=ko.pureComputed(function(){return!self.loading();});self.showLoadingError=function(error){log.error("Loading error: "+
error+" Please check prior messages and 'octoprint.log' for possible reasons.");$("#page-container-loading-header").text("Loading failed");$("#page-container-loading-spinner").removeClass("fa-spinner fa-spin").addClass("fa-exclamation-triangle text-error");$("#page-container-loading-error").html(error+" "+
_.sprintf("Please check your <a href='%(browser)s' target='_blank' rel='noopener noreferrer'>browser's error console</a> and <code><a href='%(octoprint)s' target='_blank' rel='noopener noreferrer'>octoprint.log</a></code> for possible reasons.Also make sure that the server is actually running by reloading this page.",{browser:"https://faq.octoprint.org/browser-console",octoprint:"https://faq.octoprint.org/logs"})).show();};}
OCTOPRINT_VIEWMODELS.push({construct:UiStateViewModel,elements:["#page-container-main","#page-container-loading"]});});
;

// source: js/app/viewmodels/users.js
$(function(){function UsersViewModel(parameters){var self=this;self.access=parameters[0];self.deprecatedUsersMethod=function(oldFct){var newFct=oldFct;if(arguments.length===2){newFct=arguments[1];}
OctoPrintClient.deprecatedMethod(self,"UsersViewModel",oldFct,"AccessViewModel.users",newFct,function(){self.access.users[newFct](this.arguments);});};self.deprecatedUsersVariable=function(oldVar){var newVar=oldVar;if(arguments.length===2){newVar=arguments[1];}
OctoPrintClient.deprecatedVariable(self,"UsersViewModel",oldVar,"AccessViewModel.users",newVar,function(){return self.access.users[newVar];},function(val){self.access.users[newVar]=val;});};self.deprecatedUsersVariable("listHelper");self.deprecatedUsersVariable("emptyUser");self.deprecatedUsersVariable("currentUser");self.deprecatedUsersVariable("editorUsername");self.deprecatedUsersVariable("editorGroups");self.deprecatedUsersVariable("editorPermissions");self.deprecatedUsersVariable("editorPassword");self.deprecatedUsersVariable("editorRepeatedPassword");self.deprecatedUsersVariable("editorApikey");self.deprecatedUsersVariable("editorActive");self.deprecatedUsersVariable("editorPasswordMismatch");self.deprecatedUsersMethod("requestData");self.deprecatedUsersMethod("fromResponse");self.deprecatedUsersMethod("showAddUserDialog");self.deprecatedUsersMethod("confirmAddUser");self.deprecatedUsersMethod("showEditUserDialog");self.deprecatedUsersMethod("confirmEditUser");self.deprecatedUsersMethod("showChangePasswordDialog");self.deprecatedUsersMethod("confirmChangePassword");self.deprecatedUsersMethod("confirmGenerateApikey");self.deprecatedUsersMethod("copyApikey");self.deprecatedUsersMethod("confirmDeleteApikey");self.deprecatedUsersMethod("_updateApikey");self.deprecatedUsersMethod("addUser");self.deprecatedUsersMethod("removeUser");self.deprecatedUsersMethod("updateUser");self.deprecatedUsersMethod("updatePassword");self.deprecatedUsersMethod("generateApikey");self.deprecatedUsersMethod("deleteApikey");}
OCTOPRINT_VIEWMODELS.push({construct:UsersViewModel,dependencies:["accessViewModel"]});});
;

// source: js/app/viewmodels/usersettings.js
$(function(){function UserSettingsViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.users=self.access.users;self.userSettingsDialog=undefined;var auto_locale={language:"_default",display:gettext("Site default"),english:undefined};self.locales=ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES),function(n){return n.display;})));self.locale_languages=_.keys(AVAILABLE_LOCALES);self.access_password=ko.observable(undefined);self.access_repeatedPassword=ko.observable(undefined);self.access_currentPassword=ko.observable(undefined);self.access_currentPasswordMismatch=ko.observable(false);self.access_apikey=ko.observable(undefined);self.interface_language=ko.observable(undefined);self.currentUser=ko.observable(undefined);self.currentUser.subscribe(function(newUser){self.access_password(undefined);self.access_repeatedPassword(undefined);self.access_currentPassword(undefined);self.access_currentPasswordMismatch(false);self.access_apikey(undefined);self.interface_language("_default");if(newUser!==undefined){self.access_apikey(newUser.apikey);if(newUser.settings.hasOwnProperty("interface")&&newUser.settings.interface.hasOwnProperty("language")){self.interface_language(newUser.settings.interface.language);}}});self.access_currentPassword.subscribe(function(){self.access_currentPasswordMismatch(false);});self.passwordMismatch=ko.pureComputed(function(){return self.access_password()!==self.access_repeatedPassword();});self.show=function(user){if(!CONFIG_ACCESS_CONTROL)return;if(user===undefined){user=self.loginState.currentUser();}
var process=function(user){self.currentUser(user);self.userSettingsDialog.modal("show");};OctoPrint.access.users.get(user.name).done(function(data){process(data);}).fail(function(){log.warn("Could not fetch current user data, proceeding with client side data copy");process(user);});};self.save=function(){if(!CONFIG_ACCESS_CONTROL)return;self.userSettingsDialog.trigger("beforeSave");function saveSettings(){var settings={interface:{language:self.interface_language()}};self.updateSettings(self.currentUser().name,settings).done(function(){self.currentUser(undefined);self.userSettingsDialog.modal("hide");self.loginState.reloadUser();});}
if(self.access_password()&&!self.passwordMismatch()){self.users.updatePassword(self.currentUser().name,self.access_password(),self.access_currentPassword()).done(function(){saveSettings();}).fail(function(xhr){if(xhr.status===403){self.access_currentPasswordMismatch(true);}});}else{saveSettings();}};self.copyApikey=function(){copyToClipboard(self.access_apikey());};self.generateApikey=function(){if(!CONFIG_ACCESS_CONTROL)return;var generate=function(){self.users.generateApikey(self.currentUser().name).done(function(response){self.access_apikey(response.apikey);});};if(self.access_apikey()){showConfirmationDialog(gettext("This will generate a new API Key. The old API Key will cease to function immediately."),generate);}else{generate();}};self.deleteApikey=function(){if(!CONFIG_ACCESS_CONTROL)return;if(!self.access_apikey())return;showConfirmationDialog(gettext("This will delete the API Key. It will cease to to function immediately."),function(){self.users.deleteApikey(self.currentUser().name).done(function(){self.access_apikey(undefined);});});};self.updateSettings=function(username,settings){return OctoPrint.access.users.saveSettings(username,settings);};self.saveEnabled=function(){return!self.passwordMismatch();};self.onStartup=function(){self.userSettingsDialog=$("#usersettings_dialog");};self.onAllBound=function(allViewModels){self.userSettingsDialog.on("show",function(){callViewModels(allViewModels,"onUserSettingsShown");});self.userSettingsDialog.on("hidden",function(){callViewModels(allViewModels,"onUserSettingsHidden");});self.userSettingsDialog.on("beforeSave",function(){callViewModels(allViewModels,"onUserSettingsBeforeSave");});};}
OCTOPRINT_VIEWMODELS.push({construct:UserSettingsViewModel,dependencies:["loginStateViewModel","accessViewModel"],elements:["#usersettings_dialog"]});});
;

// source: js/app/viewmodels/wizard.js
$(function(){function WizardViewModel(parameters){var self=this;self.loginState=parameters[0];self.settingsViewModel=parameters[1];self.wizardDialog=undefined;self.reloadOverlay=undefined;self.allViewModels=undefined;self.finishing=false;self.wizards=[];self.isDialogActive=function(){return self.wizardDialog.is(":visible");};self.showDialog=function(){if(!CONFIG_WIZARD||(!CONFIG_FIRST_RUN&&!self.loginState.isAdmin()))
return;self.getWizardDetails().done(function(response){callViewModels(self.allViewModels,"onWizardDetails",[response]);if(!self.isDialogActive()){self.wizardDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});}
callViewModels(self.allViewModels,"onWizardShow");callViewModels(self.allViewModels,"onBeforeWizardTabChange",[OCTOPRINT_INITIAL_WIZARD,undefined]);callViewModels(self.allViewModels,"onAfterWizardTabChange",[OCTOPRINT_INITIAL_WIZARD]);});};self.closeDialog=function(){self.wizardDialog.modal("hide");};self.onStartup=function(){self.wizardDialog=$("#wizard_dialog");self.wizardDialog.on("show",function(event){OctoPrint.coreui.wizardOpen=true;});self.wizardDialog.on("hidden",function(event){OctoPrint.coreui.wizardOpen=false;});self.reloadOverlay=$("#reloadui_overlay");};self.onUserLoggedIn=function(){self.showDialog();};self.onAllBound=function(allViewModels){self.allViewModels=allViewModels;self.wizardDialog.bootstrapWizard({tabClass:"nav nav-list",nextSelector:".button-next",previousSelector:".button-previous",finishSelector:".button-finish",withVisible:false,onTabClick:function(){return false;},onTabShow:function(tab,navigation,index){if(index<0||tab.length==0){return true;}
var total=self.wizardDialog.bootstrapWizard("navigationLength");if(index==total){self.wizardDialog.find(".button-next").hide();self.wizardDialog.find(".button-finish").show().removeClass("disabled");}else{self.wizardDialog.find(".button-finish").hide();self.wizardDialog.find(".button-next").show();}
var active=tab[0].id;if(active!=undefined){callViewModels(allViewModels,"onAfterWizardTabChange",[active]);}},onTabChange:function(tab,navigation,index,nextTabIndex,nextTab){var current,next;if(index==undefined||index<0||nextTabIndex==undefined||nextTabIndex<0||index==nextTabIndex||tab.length==0||nextTab.length==0){return;}
current=tab[0].id;next=nextTab[0].id;if(current!=undefined&&next!=undefined){var result=true;callViewModels(allViewModels,"onBeforeWizardTabChange",function(method){result=method(next,current)!==false&&result;});callViewModels(allViewModels,"onWizardTabChange",function(method,viewModel){log.warn("View model",viewModel,'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"');result=method(current,next)!==false&&result;});return result;}},onFinish:function(tab,navigation,index){var closeDialog=true;callViewModels(allViewModels,"onBeforeWizardFinish",function(method){closeDialog=closeDialog&&method()!==false;});if(closeDialog){var reload=false;callViewModels(allViewModels,"onWizardFinish",function(method){reload=method()=="reload"||reload;});self.finishWizard().done(function(){self.closeDialog();if(reload){self.reloadOverlay.show();}
callViewModels(allViewModels,"onAfterWizardFinish");});}}});self.showDialog();};self.getWizardDetails=function(){return OctoPrint.wizard.get().done(function(response){self.wizards=_.filter(_.keys(response),function(key){return(response[key]&&response[key]["required"]&&!response[key]["ignored"]);});});};self.finishWizard=function(){var deferred=$.Deferred();self.finishing=true;self.settingsViewModel.saveData().done(function(){OctoPrint.wizard.finish(self.wizards).done(function(){deferred.resolve(arguments);}).fail(function(){deferred.reject(arguments);}).always(function(){self.finishing=false;});}).fail(function(){deferred.reject(arguments);});return deferred;};self.onSettingsPreventRefresh=function(){return self.isDialogActive();};}
OCTOPRINT_VIEWMODELS.push({construct:WizardViewModel,dependencies:["loginStateViewModel","settingsViewModel"],elements:["#wizard_dialog"]});});
;

// source: js/app/viewmodels/about.js
$(function(){function AboutViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.aboutDialog=undefined;self.aboutContent=undefined;self.aboutTabs=undefined;self.systeminfo=ko.observableArray();self.devmode=getQueryParameterByName("devmode")!==null;self.getSystemInfo=function(){if(!self.loginState.hasPermission(self.access.permissions.SYSTEM))return;return OctoPrint.system.getInfo().done(self.fromSystemInfo);};self.fromSystemInfo=function(r){var systeminfo=[];_.forOwn(r.systeminfo,function(value,key){systeminfo.push({key:key,value:value});});self.systeminfo(systeminfo);};self.copySystemInfo=function(){var text="";_.each(self.systeminfo(),function(entry){text+=entry.key+": "+entry.value+"\r\n";});copyToClipboard(text);};self.show=function(tab){if(tab){$('a[href="#'+tab+'"]',self.aboutTabs).tab("show");}else{$("a:first",self.aboutTabs).tab("show");}
self.aboutContent.scrollTop(0);const maxHeight=$.fn.modal.defaults.maxHeight()-80-60;self.aboutDialog.modal({minHeight:function(){return Math.max(maxHeight,250);},maxHeight:maxHeight}).css({"margin-left":function(){return-($(this).width()/2);}});self.getSystemInfo();return false;};self.hide=function(){self.aboutDialog.modal("hide");};self.onStartup=function(){self.aboutDialog=$("#about_dialog");self.aboutTabs=$("#about_dialog_tabs");self.aboutContent=$("#about_dialog_content");$('a[data-toggle="tab"]',self.aboutTabs).on("show",function(){self.aboutContent.scrollTop(0);});};self.onAllBound=function(allViewModels){self.aboutDialog.on("show",function(){callViewModels(allViewModels,"onAboutShown");});self.aboutDialog.on("hidden",function(){callViewModels(allViewModels,"onAboutHidden");});};self.showTab=function(tab){$('a[href="#'+tab+'"]',self.aboutTabs).tab("show");};}
OCTOPRINT_VIEWMODELS.push({construct:AboutViewModel,elements:["#about_dialog","#footer_about","#footer_achievements","#footer_systeminfo"],dependencies:["loginStateViewModel","accessViewModel"]});});
;

// source: plugin/achievements/js/achievements.js
$(function(){function AchievementsViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.stats=undefined;self.statsFetched=ko.observable(false);self.dummy=ko.observable();self.achievements=ko.observableArray([]);self.hiddenAchievements=ko.observable();self.achievedAchievements=ko.observable();self.totalAchievements=ko.observable();self.collectingSince=ko.pureComputed(()=>{self.dummy();if(!self.statsFetched()){return"n/a";}
return`${formatDate(self.stats.created())} (${formatTimeAgo(
                self.stats.created()
            )})`;});self.collectionVersion=ko.pureComputed(()=>{if(!self.statsFetched()){return"n/a";}
return`OctoPrint ${self.stats.created_version()}`;});self.prints=ko.pureComputed(()=>{if(!self.statsFetched()){return"n/a";}
if(self.stats.prints_started()===0){return gettext("No prints yet");}
return _.sprintf(gettext("%(prints)s (%(finished)s finished)"),{prints:this.stats.prints_started(),finished:self.stats.prints_finished()});});self.duration=ko.pureComputed(()=>{if(!self.statsFetched()){return"n/a";}
if(!self.stats.print_duration_finished()){return _.sprintf(gettext("%(total)s"),{total:formatDuration(self.stats.print_duration_total())});}else{return _.sprintf(gettext("%(total)s (%(finished)s finished)"),{total:formatDuration(self.stats.print_duration_total()),finished:formatDuration(self.stats.print_duration_finished())});}});self.longestPrint=ko.pureComputed(()=>{self.dummy();if(!self.statsFetched()){return"n/a";}
return _.sprintf(gettext("%(duration)s (finished on %(date)s, %(timeSince)s)"),{duration:formatDuration(self.stats.longest_print_duration()),date:formatDate(self.stats.longest_print_date()),timeSince:formatTimeAgo(self.stats.longest_print_date())});});self.hiddenAchievementsText=ko.pureComputed(()=>{return _.sprintf(gettext("... and %(count)s hidden achievements!"),{count:self.hiddenAchievements()});});self.requestData=()=>{if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACHIEVEMENTS_VIEW)){return;}
OctoPrint.plugins.achievements.get().done(self.fromResponse);};self.fromResponse=(response)=>{self.fromStatsResponse(response.stats);self.fromAchievementsResponse(response.achievements);const achieved=_.filter(self.achievements(),(achievement)=>achievement.achieved).length;self.achievedAchievements(achieved);self.hiddenAchievements(response.hidden_achievements);self.totalAchievements(response.achievements.length+response.hidden_achievements);};self.fromStatsResponse=(response)=>{if(self.stats===undefined){self.stats=ko.mapping.fromJS(response);self.statsFetched(true);}else{ko.mapping.fromJS(response,self.stats);}};self.fromAchievementsResponse=(response)=>{self.achievements(response);};self.CALLS_TO_ACTION=[gettext('Enjoying OctoPrint? Looks like it! <a href="%(url)s" target="_blank" rel="noopener noreferer">It might be time to give something back then</a> - thank you!'),gettext('Getting value from OctoPrint? <a href="%(url)s" target="_blank" rel="noopener noreferer">Then please consider supporting its sole maintainer with a donation</a> - thank you!'),gettext('Has OctoPrint helped you enjoy your printer more? <a href="%(url)s" target="_blank" rel="noopener noreferer">Then please consider supporting its continued development</a> - thank you!')];self.showAchievement=(achievement)=>{let html=`<div class="achievement"><div class="achievement-logo"><svg viewBox="0 0 24 24"><use href="#achievement-logo-${achievement.logo}"></use></svg></div><div class="achievement-content"><strong>${achievement.name}</strong><br />${achievement.description}</div></div>`;if(achievement.nag){const idx=Math.floor(Math.random()*self.CALLS_TO_ACTION.length);const cta=self.CALLS_TO_ACTION[idx];html+="<p class='achievement-nag'>"+
_.sprintf(cta,{url:"https://octoprint.org/support-octoprint/?utm_source=octoprint&utm_medium=achievement_popup&utm_campaign=funding"})+"</p>";}
html+=`<small class="achievement-link"><a href="javascript:void(0)" onclick="OctoPrint.coreui.viewmodels.aboutViewModel.show('about_plugin_achievements')">`+
gettext("Show all achievements...")+"</a></small>";const options={title:gettext("Achievement unlocked!"),text:html,type:"success",icon:"icon-star",hide:false,addclass:"achievement-popup"};new PNotify(options);};self.triggerTestAchievement=(nag)=>{self.showAchievement({name:"Test Achievement",description:"I am a test achievement.",logo:"trophy",nag:!!nag});};self.onEventPluginAchievementsAchievementUnlocked=(payload)=>{if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACHIEVEMENTS_VIEW)){return;}
self.showAchievement(payload);self.requestData();};self.onServerReconnect=self.onUserLoggedIn=()=>{if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACHIEVEMENTS_VIEW)){return;}
self.requestData();};self.onAboutShown=()=>{self.dummy.notifySubscribers();};}
OCTOPRINT_VIEWMODELS.push({construct:AchievementsViewModel,dependencies:["loginStateViewModel","accessViewModel"],elements:["#about_plugin_achievements","#about_plugin_achievements_2"]});});
;

// source: plugin/action_command_notification/js/action_command_notification.js
$(function(){function ActionCommandNotificationViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.settings=parameters[2];self.notifications=ko.observableArray([]);self.sortDesc=ko.observable(false);self.sortDesc.subscribe(function(){self._toLocalStorage();});self.regexValid=function(){try{new RegExp(self.settings.settings.plugins.action_command_notification.filter());return true;}catch(e){return false;}};self.toDateTimeString=function(timestamp){return formatDate(timestamp);};self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW))
return;OctoPrint.plugins.action_command_notification.get().done(self.fromResponse);};self.fromResponse=function(response){var notifications=response.notifications;if(self.sortDesc()){notifications.reverse();}
self.notifications(notifications);};self.clear=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR))
return;OctoPrint.plugins.action_command_notification.clear();};self.toggleSorting=function(){self.sortDesc(!self.sortDesc());self.requestData();};self.onStartup=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};self.onDataUpdaterPluginMessage=function(plugin,data){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW))
return;if(plugin!=="action_command_notification"){return;}
self.requestData();if(data.message&&self.settings.settings.plugins.action_command_notification.enable_popups()){new PNotify({title:gettext("Printer Notification"),text:data.message,hide:false,icon:"fa fa-bell-o",buttons:{sticker:false,closer:true}});}};var optionsLocalStorageKey="plugin.action_command_notification.options";self._toLocalStorage=function(){saveToLocalStorage(optionsLocalStorageKey,{sortDesc:self.sortDesc()});};self._fromLocalStorage=function(){var data=loadFromLocalStorage(optionsLocalStorageKey);if(data["sortDesc"]!==undefined){self.sortDesc(!!data["sortDesc"]);}};self._fromLocalStorage();}
OCTOPRINT_VIEWMODELS.push({construct:ActionCommandNotificationViewModel,dependencies:["loginStateViewModel","accessViewModel","settingsViewModel"],elements:["#sidebar_plugin_action_command_notification_wrapper","#settings_plugin_action_command_notification"]});});
;

// source: plugin/action_command_prompt/js/action_command_prompt.js
$(function(){function ActionCommandPromptViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.modal=ko.observable(undefined);self.text=ko.observable();self.buttons=ko.observableArray([]);self.active=ko.pureComputed(function(){return self.text()!==undefined;});self.visible=ko.pureComputed(function(){return self.modal()!==undefined;});self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT))
return;OctoPrint.plugins.action_command_prompt.get().done(self.fromResponse);};self.fromResponse=function(data){if(data&&data.hasOwnProperty("text")&&data.hasOwnProperty("choices")){self.text(data.text);self.buttons(data.choices);self.showPrompt();}else{self.text(undefined);self.buttons([]);}};self.showPrompt=function(){var text=self.text();var buttons=self.buttons();var opts={title:gettext("Message from your printer"),message:text,selections:buttons,maycancel:true,onselect:function(index){if(index>-1){self._select(index);}},onclose:function(){self.modal(undefined);}};self.modal(showSelectionDialog(opts));};self._select=function(index){OctoPrint.plugins.action_command_prompt.select(index);};self._closePrompt=function(){var modal=self.modal();if(modal){modal.modal("hide");}};self.onStartupComplete=function(){self.requestData();};self.onDataUpdaterPluginMessage=function(plugin,data){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT))
return;if(plugin!=="action_command_prompt"){return;}
switch(data.action){case"show":{self.text(data.text);self.buttons(data.choices);self.showPrompt();break;}
case"close":{self.text(undefined);self.buttons([]);self._closePrompt();break;}}};}
OCTOPRINT_VIEWMODELS.push({construct:ActionCommandPromptViewModel,dependencies:["loginStateViewModel","accessViewModel"],elements:["#navbar_plugin_action_command_prompt"]});});
;

// source: plugin/announcements/js/announcements.js
$(function(){function AnnouncementsViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.access=parameters[2];self.channels=new ItemListHelper("plugin.announcements.channels",{channel:function(a,b){if(a["channel"].toLocaleLowerCase()<b["channel"].toLocaleLowerCase())
return-1;if(a["channel"].toLocaleLowerCase()>b["channel"].toLocaleLowerCase())
return 1;return 0;}},{},"name",[],[],5);self.unreadArticles=ko.observableArray([]);self.markingAllAsRead=ko.observable(false);self.unread=ko.observable(0);self.unreadText=ko.pureComputed(()=>self.unread()?(self.unread()>9?"∞":""+self.unread()):"");self.unreadSuffix=ko.pureComputed(()=>self.unread()?"("+self.unread()+")":"");self.hiddenChannels=[];self.channelNotifications={};self.announcementDialog=undefined;self.announcementDialogContent=undefined;self.announcementDialogTabs=undefined;self.setupTabLink=function(item){$("a[data-toggle='tab']",item).on("show",self.resetContentScroll);};self.resetContentScroll=function(){self.announcementDialogContent.scrollTop(0);};self.toggleButtonCss=function(data){var icon=data.enabled?"fa fa-toggle-on":"fa fa-toggle-off";var disabled=self.enableToggle(data)?"":" disabled";return icon+disabled;};self.toggleButtonTitle=function(data){return data.forced?gettext("Cannot be toggled"):data.enabled?gettext("Disable Channel"):gettext("Enable Channel");};self.enableToggle=function(data){return!data.forced;};self.cleanedLink=function(data){var link=data.link;if(!link)return link;var queryPos=link.indexOf("?");if(queryPos!==-1){link=link.substr(0,queryPos);}
return link;};self.markRead=function(channel,until,reload){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;reload=!!reload;var url=PLUGIN_BASEURL+"announcements/channels/"+channel;var payload={command:"read",until:until};$.ajax({url:url,type:"POST",dataType:"json",data:JSON.stringify(payload),contentType:"application/json; charset=UTF-8",success:function(){if(reload){self.retrieveData();}}});};self.markAllRead=function(reload){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;reload=!!reload;var url=PLUGIN_BASEURL+"announcements/channels";var payload={command:"read"};self.markingAllAsRead(true);$.ajax({url:url,type:"POST",dataType:"json",data:JSON.stringify(payload),contentType:"application/json; charset=UTF-8",success:function(){if(reload){self.retrieveData();}}}).always(()=>{self.markingAllAsRead(false);});};self.toggleChannel=function(channel){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE))
return;var url=PLUGIN_BASEURL+"announcements/channels/"+channel;var payload={command:"toggle"};$.ajax({url:url,type:"POST",dataType:"json",data:JSON.stringify(payload),contentType:"application/json; charset=UTF-8",success:function(){self.retrieveData();}});};self.refreshAnnouncements=function(){self.retrieveData(true);};self.retrieveData=function(force){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;var url=PLUGIN_BASEURL+"announcements/channels";if(force){url+="?force=true";}
$.ajax({url:url,type:"GET",dataType:"json",success:function(data){self.fromResponse(data);}});};self.fromResponse=function(data){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;var currentTab=$("li.active a",self.announcementDialogTabs).attr("href");var unread=0;var channels=[];var unreadArticles=[];_.each(data.channels,function(value){value.last=value.data.length?value.data[0].published:undefined;value.count=value.data.length;value.title=value.channel+(value.unread?" ("+value.unread+")":"");unread+=value.unread;if(value.unread){_.each(_.filter(value.data,(entry)=>!entry.read),(entry)=>{const extended={...entry};extended.channel=value.channel;unreadArticles.push(extended);});}
channels.push(value);});self.channels.updateItems(channels);self.unread(unread);unreadArticles.sort((a,b)=>a.published<b.published);self.unreadArticles(unreadArticles);self.displayAnnouncements(channels);self.selectTab(currentTab);};self.showAnnouncementDialog=function(channel){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;$("#plugin_announcements_dialog_content article img").lazyload();self.announcementDialogContent.scrollTop(0);if(!self.announcementDialog.hasClass("in")){self.announcementDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);}}).css({"margin-left":function(){return-($(this).width()/2);}});}
var tab=undefined;if(channel){tab="#plugin_announcements_dialog_channel_"+channel;}
self.selectTab(tab);return false;};self.selectTab=function(tab){if(tab!=undefined){if(!_.startsWith(tab,"#")){tab="#"+tab;}
$('a[href="'+tab+'"]',self.announcementDialogTabs).tab("show");}else{$("a:first",self.announcementDialogTabs).tab("show");}};self.displayAnnouncements=function(channels){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ))
return;var displayLimit=self.settings.settings.plugins.announcements.display_limit();var maxLength=self.settings.settings.plugins.announcements.summary_limit();var cutAfterNewline=function(text){text=text.trim();var firstNewlinePos=text.indexOf("\n");if(firstNewlinePos>0){text=text.substr(0,firstNewlinePos).trim();}
return text;};var stripParagraphs=function(text){if(_.startsWith(text,"<p>")){text=text.substr("<p>".length);}
if(_.endsWith(text,"</p>")){text=text.substr(0,text.length-"</p>".length);}
return text.replace(/<\/p>\s*<p>/gi,"<br>");};_.each(channels,function(value){var key=value.key;var channel=value.channel;var priority=value.priority;var items=value.data;if(value.priority!==1){return;}
if($.inArray(key,self.hiddenChannels)>-1){return;}
var newItems=_.filter(items,(entry)=>!entry.read);if(newItems.length==0){return;}
var displayedItems;if(newItems.length>displayLimit){displayedItems=newItems.slice(0,displayLimit);}else{displayedItems=newItems;}
var rest=newItems.length-displayedItems.length;var text="<ul style='margin-top: 10px; margin-bottom: 10px'>";_.each(displayedItems,function(item){var limitedSummary=stripParagraphs(item.summary_without_images.trim());if(limitedSummary.length>maxLength){limitedSummary=limitedSummary.substr(0,maxLength);limitedSummary=limitedSummary.substr(0,Math.min(limitedSummary.length,limitedSummary.lastIndexOf(" ")));limitedSummary+="...";}
text+="<li><a href='"+
item.link+"' target='_blank' rel='noreferrer noopener'>"+
cutAfterNewline(item.title)+"</a><br><small>"+
formatTimeAgo(item.published)+"</small><p>"+
limitedSummary+"</p></li>";});text+="</ul>";if(rest){text+="<p>"+
gettext(_.sprintf("... and %(rest)d more.",{rest:rest}))+"</p>";}
text+="<small>"+
gettext("You can edit your announcement subscriptions under Settings > Announcements.")+"</small>";var options={title:channel,text:text,hide:false,confirm:{confirm:true,buttons:[{text:gettext("Later"),click:function(notice){notice.remove();self.hiddenChannels.push(key);}},{text:gettext("Mark read"),click:function(notice){notice.remove();self.markRead(key,value.last);}},{text:gettext("Read..."),addClass:"btn-primary",click:function(notice){notice.remove();self.showAnnouncementDialog(key);self.markRead(key,value.last);}}]},buttons:{sticker:false,closer:false}};if(priority===1){options.type="error";}
if(self.channelNotifications[key]){self.channelNotifications[key].remove();}
self.channelNotifications[key]=new PNotify(options);});};self.hideAnnouncements=function(){_.each(self.channelNotifications,function(notification,key){notification.remove();});self.channelNotifications={};};self.configureAnnouncements=function(){self.settings.show("settings_plugin_announcements");};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)){self.hideAnnouncements();}else{self.retrieveData();}};self.onStartup=function(){self.announcementDialog=$("#plugin_announcements_dialog");self.announcementDialogContent=$("#plugin_announcements_dialog_content");self.announcementDialogTabs=$("#plugin_announcements_dialog_tabs");};self.onEventConnectivityChanged=function(payload){if(!payload||!payload.new)return;self.retrieveData();};}
OCTOPRINT_VIEWMODELS.push({construct:AnnouncementsViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel"],elements:["#plugin_announcements_dialog","#settings_plugin_announcements","#navbar_plugin_announcements"]});});
;

// source: plugin/appkeys/js/appkeys.js
$(function(){function AppKeysDialogViewModel(parameters){var self=this;self.dialog=undefined;self.onStartup=function(){self.dialog=$("#plugin_appkeys_keygenerated");self.dialog.on("hidden",()=>{self.resetDialog();});};self.showDialog=function(title,data){if(self.dialog===undefined)return;var qrcode={text:data.api_key,size:180,fill:"#000",background:null,label:"",fontname:"sans",fontcolor:"#000",radius:0,ecLevel:"L"};self.dialog.find("#plugin_appkeys_keygenerated_title").text(title);self.dialog.find("#plugin_appkeys_keygenerated_user").text(data.user_id);self.dialog.find("#plugin_appkeys_keygenerated_app").text(data.app_id);self.dialog.find("#plugin_appkeys_keygenerated_key_text").text(data.api_key);self.dialog.find("#plugin_appkeys_keygenerated_key_copy").off().click(function(){copyToClipboard(data.api_key);});self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode").empty().qrcode(qrcode);self.dialog.modal("show");};self.resetDialog=()=>{if(self.dialog===undefined)return;self.dialog.find("#plugin_appkeys_keygenerated_title").text("");self.dialog.find("#plugin_appkeys_keygenerated_user").text("");self.dialog.find("#plugin_appkeys_keygenerated_app").text("");self.dialog.find("#plugin_appkeys_keygenerated_key_text").text("");self.dialog.find("#plugin_appkeys_keygenerated_key_copy").off();self.dialog.find("#plugin_appkeys_keygenerated_key_qrcode").empty();};}
function UserAppKeysViewModel(parameters){var self=this;self.dialog=parameters[0];self.loginState=parameters[1];self.keys=new ItemListHelper("plugin.appkeys.userkeys",{app:function(a,b){if(a["app_id"].toLowerCase()<b["app_id"].toLowerCase())return-1;if(a["app_id"].toLowerCase()>b["app_id"].toLowerCase())return 1;return 0;}},{},"app",[],[],5);self.pending={};self.openRequests={};self.editorApp=ko.observable();self.requestData=function(){return OctoPrint.plugins.appkeys.getKeys().done(self.fromResponse);};self.fromResponse=function(response){self.keys.updateItems(response.keys);self.pending=response.pending;_.each(self.pending,function(data,token){self.openRequests[token]=self.promptForAccess(data.app_id,token);});};self.generateKey=function(){self.loginState.reauthenticateIfNecessary(()=>{OctoPrint.plugins.appkeys.generateKey(self.editorApp()).done(self.requestData).done(function(){self.editorApp("");});});};self.revokeKey=(data)=>{const app=data.app_id;self.loginState.reauthenticateIfNecessary(()=>{showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key for %(app)s."),{app:_.escape(app)}),()=>{OctoPrint.plugins.appkeys.revokeKeyForApp(app).done(self.requestData);});});};self.showKeyDetails=(data)=>{self.loginState.reauthenticateIfNecessary(()=>{OctoPrint.plugins.appkeys.getKey(data.app_id).done((response)=>{self.dialog.showDialog(gettext("Details"),response.key);});});};self.allowApp=function(token){return OctoPrint.plugins.appkeys.decide(token,true).done(self.requestData);};self.denyApp=function(token){return OctoPrint.plugins.appkeys.decide(token,false).done(self.requestData);};self.promptForAccess=function(app,token){var message=gettext('"<strong>%(app)s</strong>" has requested access to control OctoPrint through the API.');message=_.sprintf(message,{app:_.escape(app)});message="<p>"+
message+"</p><p>"+
gettext("Do you want to allow access to this application with your user account?")+"</p>";return new PNotify({title:gettext("Access Request"),text:message,hide:false,icon:"fa fa-key",confirm:{confirm:true,buttons:[{text:gettext("Allow"),click:function(notice){self.loginState.reauthenticateIfNecessary(()=>{self.allowApp(token);notice.remove();});}},{text:gettext("Deny"),click:function(notice){self.denyApp(token);notice.remove();}}]},buttons:{sticker:false,closer:false}});};self.onUserSettingsShown=function(){self.requestData();};self.onUserLoggedIn=function(){self.requestData();};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="appkeys"){return;}
var app,token,user;if(data.type==="request_access"&&self.loginState.isUser()){app=data.app_name;token=data.user_token;user=data.user_id;if(user&&user!==self.loginState.username()){return;}
if(self.pending[token]!==undefined){return;}
self.openRequests[token]=self.promptForAccess(app,token);}else if(data.type==="end_request"){token=data.user_token;if(self.openRequests[token]!==undefined){if(self.openRequests[token].state!=="closed"){self.openRequests[token].remove();}
delete self.openRequests[token];}}};}
function AllAppKeysViewModel(parameters){var self=this;self.dialog=parameters[0];self.loginState=parameters[1];self.access=parameters[2];self.keys=new ItemListHelper("plugin.appkeys.allkeys",{user_app:function(a,b){if(a["user_id"]>b["user_id"])return 1;if(a["user_id"]<b["user_id"])return-1;if(a["app_id"].toLowerCase()>b["app_id"].toLowerCase())return 1;if(a["app_id"].toLowerCase()<b["app_id"].toLowerCase())return-1;return 0;}},{},"user_app",[],[],10);self.users=ko.observableArray([]);self.apps=ko.observableArray([]);self.editorApp=ko.observable();self.editorUser=ko.observable();self.markedForDeletion=ko.observableArray([]);self.onSettingsShown=function(){self.requestData();self.editorUser(self.loginState.username());self.editorApp("");};self.onUserLoggedIn=function(){self.requestData();self.editorUser(self.loginState.username());self.editorApp("");};self.requestData=function(){return OctoPrint.plugins.appkeys.getAllKeys().done(self.fromResponse);};self.fromResponse=function(response){self.keys.updateItems(response.keys);var users=[];var apps=[];_.each(response.keys,function(key){users.push(key.user_id);apps.push(key.app_id.toLowerCase());});users=_.uniq(users);users.sort();self.users(users);apps=_.uniq(apps);apps.sort();self.apps(apps);};self.showKeyDetails=(data)=>{self.loginState.reauthenticateIfNecessary(()=>{OctoPrint.plugins.appkeys.getKey(data.app_id,data.user_id).done((response)=>{self.dialog.showDialog(gettext("Details"),response.key);});});};self.generateKey=function(){self.loginState.reauthenticateIfNecessary(()=>{OctoPrint.plugins.appkeys.generateKeyForUser(self.editorUser(),self.editorApp()).done(self.requestData).done(function(){self.editorUser(self.loginState.username());self.editorApp("");}).done(function(data){self.dialog.showDialog(gettext("New key generated!"),data);});});};self.revokeKey=function(data){const app=data.app_id;const user=data.user_id;showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key for %(app)s for user %(user)s."),{app:_.escape(app),user:_.escape(user)}),()=>{self.loginState.reauthenticateIfNecessary(()=>{OctoPrint.plugins.appkeys.revokeKeyForApp(app,user).done(self.requestData);});});};self.revokeMarked=function(){showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."),{count:self.markedForDeletion().length}),()=>{self.loginState.forceReauthentication(()=>{self._bulkRevoke(self.markedForDeletion()).done(()=>{self.markedForDeletion.removeAll();});});});};self.markAllOnPageForDeletion=function(){self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(),(item)=>`${item.user_id}:${item.app_id}`))));};self.markAllForDeletion=function(){self.markedForDeletion(_.uniq(_.map(self.keys.allItems,(item)=>`${item.user_id}:${item.app_id}`)));};self.markAllByUserForDeletion=function(user){self.markAllByFilterForDeletion(function(e){return e.user_id===user;});};self.markAllByAppForDeletion=function(app){self.markAllByFilterForDeletion(function(e){return e.app_id.toLowerCase()===app;});};self.markAllByFilterForDeletion=function(filter){self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems,filter),(item)=>`${item.user_id}:${item.app_id}`))));};self.clearMarked=function(){self.markedForDeletion.removeAll();};self._bulkRevoke=function(keys){var title,message,handler;title=gettext("Revoking application keys");message=_.sprintf(gettext("Revoking %(count)d application keys..."),{count:keys.length});handler=function(id){const[user,app]=rsplit(id,":",1);return OctoPrint.plugins.appkeys.revokeKeyForApp(app,user).done(function(){deferred.notify(_.sprintf(gettext("Revoked %(app)s for %(user)s..."),{app:_.escape(app),user:_.escape(user)}),true);}).fail(function(jqXHR){var short=_.sprintf(gettext("Revocation of %(app)s for user %(user)s failed, continuing..."),{app:_.escape(app),user:_.escape(user)});var long=_.sprintf(gettext("Deletion of %(app)s for user %(user)s failed: %(error)s"),{app:_.escape(app),user:_.escape(user),error:_.escape(jqXHR.responseText)});deferred.notify(short,long,false);});};var deferred=$.Deferred();var promise=deferred.promise();var options={title:title,message:message,max:keys.length,output:true};showProgressModal(options,promise);var requests=[];_.each(keys,function(key){var request=handler(key);requests.push(request);});$.when.apply($,_.map(requests,wrapPromiseWithAlways)).done(function(){deferred.resolve();self.requestData();});return promise;};}
OCTOPRINT_VIEWMODELS.push([AppKeysDialogViewModel,[],[]]);OCTOPRINT_VIEWMODELS.push([UserAppKeysViewModel,["appKeysDialogViewModel","loginStateViewModel"],["#usersettings_plugin_appkeys"]]);OCTOPRINT_VIEWMODELS.push([AllAppKeysViewModel,["appKeysDialogViewModel","loginStateViewModel","accessViewModel"],["#settings_plugin_appkeys"]]);});
;

// source: plugin/backup/js/backup.js
$(function(){function BackupViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.backups=new ItemListHelper("plugin.backup.backups",{date:function(a,b){if(a["date"]>b["date"])return-1;if(a["date"]<b["date"])return 1;return 0;}},{},"date",[],[],10);self.markedForBackupDeletion=ko.observableArray([]);self.excludeFromBackup=ko.observableArray([]);self.backupInProgress=ko.observable(false);self.restoreSupported=ko.observable(true);self.maxUploadSize=ko.observable(0);self.backupUploadData=undefined;self.backupUploadName=ko.observable();self.backupUploadSource=undefined;self.isAboveUploadSize=function(data){return data.size>self.maxUploadSize();};const backupFileuploadOptionsFactory=(source)=>{return{dataType:"json",maxNumberOfFiles:1,autoUpload:false,add:(e,data)=>{if(data.files.length===0){return false;}
self.backupUploadName(data.files[0].name);self.backupUploadData=data;self.backupUploadSource=source;},done:(e,data)=>{self.backupUploadName(undefined);self.backupUploadData=undefined;self.backupUploadSource=undefined;}};};$("#settings-backup-upload").fileupload(backupFileuploadOptionsFactory("settings"));$("#wizard-backup-upload").fileupload(backupFileuploadOptionsFactory("wizard"));self.restoreInProgress=ko.observable(false);self.restoreTitle=ko.observable();self.restoreDialog=undefined;self.restoreOutput=undefined;self.unknownPlugins=ko.observableArray([]);self.loglines=ko.observableArray([]);self.requestData=function(){OctoPrint.plugins.backup.get().done(self.fromResponse);};self.fromResponse=function(response){self.backups.updateItems(response.backups);self.unknownPlugins(response.unknown_plugins);self.restoreSupported(response.restore_supported);self.maxUploadSize(response.max_upload_size);};self.reauthenticateDownload=(url)=>{self.loginState.reauthenticateIfNecessary(()=>{const link=document.createElement("a");link.href=url;link.download="";document.body.appendChild(link);link.click();document.body.removeChild(link);});};self.createBackup=function(){var excluded=self.excludeFromBackup();OctoPrint.plugins.backup.createBackup(excluded).done(function(){self.excludeFromBackup([]);});};self.removeBackup=function(backup){var perform=function(){OctoPrint.plugins.backup.deleteBackup(backup).done(function(){self.requestData();});};showConfirmationDialog(_.sprintf(gettext('You are about to delete backup file "%(name)s".'),{name:_.escape(backup)}),perform);};self.restoreBackup=function(backup){if(!self.restoreSupported())return;showConfirmationDialog(_.sprintf(gettext('You are about to restore the backup file "%(name)s". This cannot be undone.'),{name:_.escape(backup)}),()=>{self.loginState.reauthenticateIfNecessary(()=>{self.restoreInProgress(true);self.loglines.removeAll();self.loglines.push({line:"Preparing to restore...",stream:"message"});self.loglines.push({line:" ",stream:"message"});self.restoreDialog.modal({keyboard:false,backdrop:"static",show:true});OctoPrint.plugins.backup.restoreBackup(backup);});});};self.performRestoreFromUpload=function(){if(self.backupUploadData===undefined)return;const proceed=()=>{self.restoreInProgress(true);self.loglines.removeAll();self.loglines.push({line:"Uploading backup, this can take a while. Please wait...",stream:"message"});self.loglines.push({line:" ",stream:"message"});self.restoreDialog.modal({keyboard:false,backdrop:"static",show:true});self.backupUploadData.submit();};showConfirmationDialog(_.sprintf(gettext('You are about to upload and restore the backup file "%(name)s". This cannot be undone.'),{name:_.escape(self.backupUploadName())}),()=>{if(self.backupUploadSource==="wizard"){proceed();}else{self.loginState.reauthenticateIfNecessary(proceed);}});};self.deleteUnknownPluginRecord=function(){var perform=function(){OctoPrint.plugins.backup.deleteUnknownPlugins().done(function(){self.requestData();});};showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),perform);};self.markFilesOnPage=function(){self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(),"name"))));};self.markAllFiles=function(){self.markedForBackupDeletion(_.map(self.backups.allItems,"name"));};self.clearMarkedFiles=function(){self.markedForBackupDeletion.removeAll();};self.removeMarkedFiles=function(){var perform=function(){self._bulkRemove(self.markedForBackupDeletion()).done(function(){self.markedForBackupDeletion.removeAll();});};showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."),{count:self.markedForBackupDeletion().length}),perform);};self.onStartup=function(){self.restoreDialog=$("#settings_plugin_backup_restoredialog");self.restoreOutput=$("#settings_plugin_backup_restoredialog_output");};self.onSettingsShown=function(){self.requestData();};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="backup")return;if(data.type==="backup_done"){self.requestData();self.backupInProgress(false);new PNotify({title:gettext("Backup created successfully"),type:"success"});}else if(data.type==="backup_started"){self.backupInProgress(true);}else if(data.type==="backup_error"){self.requestData();self.backupInProgress(false);new PNotify({title:gettext("Creating the backup failed"),text:_.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"),{error:_.escape(data.error)}),type:"error",hide:false});}else if(data.type==="restore_started"){self.loglines.push({line:gettext("Restoring from backup..."),stream:"message"});self.loglines.push({line:" ",stream:"message"});}else if(data.type==="restore_failed"){self.loglines.push({line:" ",stream:"message"});self.loglines.push({line:gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."),stream:"error"});self.restoreInProgress(false);}else if(data.type==="restore_done"){self.loglines.push({line:" ",stream:"message"});self.loglines.push({line:gettext("Restore successful! The server will now be restarted!"),stream:"message"});self.restoreInProgress(false);}else if(data.type==="installing_plugin"){self.loglines.push({line:" ",stream:"message"});self.loglines.push({line:_.sprintf(gettext('Installing plugin "%(plugin)s"...'),{plugin:_.escape(data.plugin)}),stream:"message"});}else if(data.type==="plugin_incompatible"){self.loglines.push({line:" ",stream:"message"});self.loglines.push({line:_.sprintf(gettext('Cannot install plugin "%(plugin)s" due to it being incompatible to this OctoPrint version and/or underlying operating system'),{plugin:_.escape(data.plugin.key)}),stream:"stderr"});}else if(data.type==="unknown_plugins"){if(data.plugins.length>0){self.loglines.push({line:" ",stream:"message"});self.loglines.push({line:_.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"),{count:data.plugins.length}),stream:"message"});_.each(data.plugins,function(plugin){self.loglines.push({line:plugin.name+": "+plugin.url,stream:"message"});});self.loglines.push({line:" ",stream:"message"});self.unknownPlugins(data.plugins);}}else if(data.type==="logline"){self.loglines.push(self._preprocessLine({line:data.line,stream:data.stream}));self._scrollRestoreOutputToEnd();}};self._scrollRestoreOutputToEnd=function(){self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight-self.restoreOutput.height());};self._forcedStdoutLine=/You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;self._preprocessLine=function(line){if(line.stream==="stderr"&&line.line.match(self._forcedStdoutLine)){line.stream="stdout";}
return line;};self._bulkRemove=function(files){var title,message,handler;title=gettext("Deleting backups");message=_.sprintf(gettext("Deleting %(count)d backups..."),{count:files.length});handler=function(filename){return OctoPrint.plugins.backup.deleteBackup(filename).done(function(){deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."),{filename:_.escape(filename)}),true);}).fail(function(jqXHR){var short=_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."),{filename:_.escape(filename)});var long=_.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"),{filename:_.escape(filename),error:_.escape(jqXHR.responseText)});deferred.notify(short,long,false);});};var deferred=$.Deferred();var promise=deferred.promise();var options={title:title,message:message,max:files.length,output:true};showProgressModal(options,promise);var requests=[];_.each(files,function(filename){var request=handler(filename);requests.push(request);});$.when.apply($,_.map(requests,wrapPromiseWithAlways)).done(function(){deferred.resolve();self.requestData();});return promise;};}
OCTOPRINT_VIEWMODELS.push({construct:BackupViewModel,dependencies:["loginStateViewModel","settingsViewModel"],elements:["#settings_plugin_backup","#wizard_plugin_backup"]});});
;

// source: plugin/classicwebcam/js/classicwebcam.js
$(function(){function ClassicWebcamViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.webcamStreamVisible=false;self.webcamDisableTimeout=undefined;self.webcamLoaded=ko.observable(false);self.webcamMjpgEnabled=ko.observable(false);self.webcamHlsEnabled=ko.observable(false);self.webcamWebRTCEnabled=ko.observable(false);self.webcamError=ko.observable(false);self.webcamMuted=ko.observable(true);self.webRTCPeerConnection=null;self.webcamElementHls=null;self.webcamElementWebrtc=null;self.webcamRatioClass=ko.pureComputed(function(){if(self.settings.streamRatio()=="4:3"){return"ratio43";}else{return"ratio169";}});self.webcamClass=ko.pureComputed(function(){if(self.settings.rotate90()){return"webcam_rotated "+self.webcamRatioClass();}else{return"webcam_unrotated "+self.webcamRatioClass();}});self.onBeforeBinding=function(){self.settings.rotate90.subscribe(function(){window.setTimeout(function(){self._updateVideoTagWebcamLayout();},1);});self.streamUrlEscaped=ko.pureComputed(function(){return encodeURI(self.settings.streamUrl());});self.webcamStreamType=ko.pureComputed(function(){try{return self.determineWebcamStreamType(self.streamUrlEscaped());}catch(e){console.error(e);self.webcamError(true);return"mjpg";}});self.webcamStreamValid=ko.pureComputed(function(){var url=self.streamUrlEscaped();return!url||validateWebcamUrl(url);});};self.onWebcamVisibilityChange=function(visible){self.webcamStreamVisible=visible;if(self.webcamStreamVisible){self._enableWebcam();}else{self._disableWebcam();}};self.onWebcamRefresh=function(){var streamType=self.webcamStreamType();if(streamType=="mjpg"){if(OctoPrint.coreui.browser.safari){return;}
$("#webcam_image").attr("src","");self._switchToMjpgWebcam();log.info("Triggered refresh of mjpg webcam stream");}};self.onEventSettingsUpdated=function(payload){self._enableWebcamIfVisible();};self._getActiveWebcamVideoElement=function(){if(self.webcamWebRTCEnabled()){return self.webcamElementWebrtc;}else{return self.webcamElementHls;}};self.launchWebcamPictureInPicture=function(){self._getActiveWebcamVideoElement().requestPictureInPicture();};self.launchWebcamFullscreen=function(){self._getActiveWebcamVideoElement().requestFullscreen();};self.toggleWebcamMute=function(){self.webcamMuted(!self.webcamMuted());self.webcamElementWebrtc.muted=self.webcamMuted();self.webcamElementHls.muted=self.webcamMuted();};self._disableWebcam=function(){if(OctoPrint.coreui.browser.safari){return;}
var timeout=self.settings.streamTimeout()||5;self.webcamDisableTimeout=setTimeout(function(){log.debug("Unloading webcam stream after",timeout,"seconds");$("#webcam_image").attr("src","");self.webcamLoaded(false);},timeout*1000);};self._enableWebcamIfVisible=function(){if(self.webcamStreamVisible){self._enableWebcam();}};self._enableWebcam=function(){if(self.webcamDisableTimeout!=undefined){clearTimeout(self.webcamDisableTimeout);}
if(self.settings.webcamEnabled()==false){console.log("Webcam not enabled");return;}
var streamType=self.webcamStreamType();if(streamType=="mjpg"){self._switchToMjpgWebcam();}else if(streamType=="hls"){self._switchToHlsWebcam();}else if(isWebRTCAvailable()&&streamType=="webrtc"){self._switchToWebRTCWebcam();}else{throw"Unknown stream type "+streamType;}};self.onWebcamLoaded=function(){if(self.webcamLoaded())return;log.debug("Webcam stream loaded");self.webcamLoaded(true);self.webcamError(false);};self.onWebcamErrored=function(){log.debug("Webcam stream failed to load/was unloaded");self.webcamLoaded(false);self.webcamError(true);};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){self.syncWebcamElements();};self.syncWebcamElements=function(){self.webcamElementHls=document.getElementById("webcam_hls");self.webcamElementWebrtc=document.getElementById("webcam_webrtc");};self.onStartup=function(){self.syncWebcamElements();};self._switchToMjpgWebcam=function(){var webcamImage=$("#webcam_image");var currentSrc=webcamImage.attr("src");if(OctoPrint.coreui.browser.safari&&currentSrc!=undefined){return;}
var newSrc=self.streamUrlEscaped();if(currentSrc!=newSrc){if(self.settings.cacheBuster()){if(newSrc.lastIndexOf("?")>-1){newSrc+="&";}else{newSrc+="?";}
newSrc+=new Date().getTime();}
self.webcamLoaded(false);self.webcamError(false);webcamImage.attr("src",newSrc);self.webcamHlsEnabled(false);self.webcamMjpgEnabled(true);self.webcamWebRTCEnabled(false);}};self._switchToHlsWebcam=function(){var video=self.webcamElementHls;video.onresize=self._updateVideoTagWebcamLayout;if(self.webRTCPeerConnection!=null){self.webRTCPeerConnection.close();self.webRTCPeerConnection=null;}
if(video!=null&&typeof video.canPlayType!=undefined&&video.canPlayType("application/vnd.apple.mpegurl")=="probably"){video.src=self.streamUrlEscaped();}else if(Hls.isSupported()){self.hls=new Hls();self.hls.loadSource(self.streamUrlEscaped());self.hls.attachMedia(video);}
self.webcamMjpgEnabled(false);self.webcamHlsEnabled(true);self.webcamWebRTCEnabled(false);};self._switchToWebRTCWebcam=function(){if(!isWebRTCAvailable()){return;}
var video=self.webcamElementWebrtc;video.onresize=self._updateVideoTagWebcamLayout;if(self.hls!=null){self.webcamElementHls.src=null;self.hls.destroy();self.hls=null;}
if(self.webRTCPeerConnection!=null&&self.webRTCPeerConnection.connectionState!="connected"){self.webRTCPeerConnection.close();self.webRTCPeerConnection=null;}
if(self.webRTCPeerConnection==null){self.webRTCPeerConnection=startWebRTC(video,self.streamUrlEscaped(),self.settings.streamWebrtcIceServers());}
self.webcamMjpgEnabled(false);self.webcamHlsEnabled(false);self.webcamWebRTCEnabled(true);};self._updateVideoTagWebcamLayout=function(){var player=self._getActiveWebcamVideoElement();var rotationContainer=document.querySelector("#webcam_video_container .webcam_rotated");var rotationTarget=document.querySelector("#webcam_video_container .webcam_rotated .rotation_target");var unrotationContainer=document.querySelector("#webcam_video_container .webcam_unrotated");var unrotationTarget=document.querySelector("#webcam_video_container .webcam_unrotated .rotation_target");if(rotationContainer){var height=rotationContainer.offsetWidth;rotationContainer.style.height=height+"px";rotationTarget.style.height=rotationContainer.offsetWidth+"px";rotationTarget.style.width=rotationContainer.offsetHeight+"px";rotationContainer.style.paddingBottom=0;}
if(unrotationContainer){unrotationContainer.style.height=null;unrotationContainer.style.paddingBottom=0;unrotationTarget.style.height=null;unrotationTarget.style.width=null;}};self.determineWebcamStreamType=function(streamUrl){if(!streamUrl){throw"Empty streamUrl. Cannot determine stream type.";}
var parsed=validateWebcamUrl(streamUrl);if(!parsed){throw"Invalid streamUrl. Cannot determine stream type.";}
if(parsed.protocol==="webrtc:"||parsed.protocol==="webrtcs:"){return"webrtc";}
var lastDotPosition=parsed.pathname.lastIndexOf(".");if(lastDotPosition!==-1){var extension=parsed.pathname.substring(lastDotPosition+1);if(extension.toLowerCase()==="m3u8"){return"hls";}}
return"mjpg";};}
OCTOPRINT_VIEWMODELS.push({construct:ClassicWebcamViewModel,dependencies:["loginStateViewModel","classicWebcamSettingsViewModel"],elements:["#classicwebcam_container"]});});
;

// source: plugin/classicwebcam/js/classicwebcam_settings.js
$(function(){function ClassicWebcamSettingsViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self._subscriptions=[];self.webRtcServersToText=function(list){self.streamWebrtcIceServersText(self.streamWebrtcIceServers().join(", "));};self.textToWebRtcServers=function(list){self.streamWebrtcIceServers(splitTextToArray(self.streamWebrtcIceServersText(),",",true));};self.onBeforeBinding=function(){self.snapshotUrl=self.settings.settings.plugins.classicwebcam.snapshot;self.snapshotTimeout=self.settings.settings.plugins.classicwebcam.snapshotTimeout;self.snapshotSslValidation=self.settings.settings.plugins.classicwebcam.snapshotSslValidation;self.flipH=self.settings.settings.plugins.classicwebcam.flipH;self.flipV=self.settings.settings.plugins.classicwebcam.flipV;self.rotate90=self.settings.settings.plugins.classicwebcam.rotate90;self.streamUrl=self.settings.settings.plugins.classicwebcam.stream;self.webcamEnabled=self.settings.settings.webcam.webcamEnabled;self.streamRatio=self.settings.settings.plugins.classicwebcam.streamRatio;self.streamTimeout=self.settings.settings.plugins.classicwebcam.streamTimeout;self.streamWebrtcIceServers=self.settings.settings.plugins.classicwebcam.streamWebrtcIceServers;self.streamWebrtcIceServersText=ko.observable("");self.cacheBuster=self.settings.settings.plugins.classicwebcam.cacheBuster;self.available_ratios=["16:9","4:3"];self.webRtcServersToText();self.streamWebrtcIceServers.subscribe(function(value){self.webRtcServersToText();});};self.onSettingsBeforeSave=function(){self.textToWebRtcServers();};self.onUserSettingsHidden=function(){self.webRtcServersToText();};self.streamUrlEscaped=ko.pureComputed(function(){return encodeURI(self.streamUrl());});self.streamType=ko.pureComputed(function(){try{return determineWebcamStreamType(self.streamUrlEscaped());}catch(e){return"";}});self.streamValid=ko.pureComputed(function(){var url=self.streamUrlEscaped();return!url||validateWebcamUrl(url);});self.testWebcamStreamUrlBusy=ko.observable(false);self.testWebcamStreamUrl=function(){var url=self.streamUrlEscaped();if(!url){return;}
if(self.testWebcamStreamUrlBusy()){return;}
var text=gettext("If you see your webcam stream below, the entered stream URL is ok.");var streamType;try{streamType=self.streamType();}catch(e){streamType="";}
var webcam_element;var webrtc_peer_connection;if(streamType==="mjpg"){webcam_element=$('<img src="'+url+'">');}else if(streamType==="hls"){webcam_element=$('<video id="webcam_hls" muted autoplay style="width: 100%"/>');video_element=webcam_element[0];if(video_element.canPlayType("application/vnd.apple.mpegurl")){video_element.src=url;}else if(Hls.isSupported()){var hls=new Hls();hls.loadSource(url);hls.attachMedia(video_element);}}else if(isWebRTCAvailable()&&streamType==="webrtc"){webcam_element=$('<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"/>');video_element=webcam_element[0];webrtc_peer_connection=startWebRTC(video_element,url,self.streamWebrtcIceServers());}else{throw"Unknown stream type "+streamType;}
var message=$("<div id='webcamTestContainer'></div>").append($("<p></p>")).append(text).append(webcam_element);self.testWebcamStreamUrlBusy(true);showMessageDialog({title:gettext("Stream test"),message:message,onclose:function(){self.testWebcamStreamUrlBusy(false);if(webrtc_peer_connection!=null){webrtc_peer_connection.close();webrtc_peer_connection=null;}}});};self.testWebcamSnapshotUrlBusy=ko.observable(false);self.testWebcamSnapshotUrl=function(viewModel,event){if(!self.snapshotUrl()){return;}
if(self.testWebcamSnapshotUrlBusy()){return;}
var errorText=gettext("Could not retrieve snapshot URL, please double check the URL");var errorTitle=gettext("Snapshot test failed");self.testWebcamSnapshotUrlBusy(true);OctoPrint.util.testUrl(self.snapshotUrl(),{method:"GET",response:"bytes",timeout:self.settings.settings.webcam.snapshotTimeout(),validSsl:self.settings.settings.webcam.snapshotSslValidation(),content_type_whitelist:["image/*"],content_type_guess:true}).done(function(response){if(!response.result){if(response.status&&response.response&&response.response.content_type){errorText=gettext("Could retrieve the snapshot URL, but it didn't look like an "+"image. Got this as a content type header: <code>%(content_type)s</code>. Please "+"double check that the URL is returning static images, not multipart data "+"or videos.");errorText=_.sprintf(errorText,{content_type:_.escape(response.response.content_type)});}
showMessageDialog({title:errorTitle,message:errorText,onclose:function(){self.testWebcamSnapshotUrlBusy(false);}});return;}
const content=response.response.content;const contentType=response.response.assumed_content_type;const text=gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");const mimeType=contentType?contentType.split(";")[0]:"image/jpeg";const textElement=$("<p></p>").text(text);const imgElement=$("<img>").attr("src","data:"+mimeType+";base64,"+content).css("border","1px solid black");const message=$("<p></p>").append(textElement).append(imgElement);showMessageDialog({title:gettext("Snapshot test"),message:message,onclose:function(){self.testWebcamSnapshotUrlBusy(false);}});}).fail(function(){showMessageDialog({title:errorTitle,message:errorText,onclose:function(){self.testWebcamSnapshotUrlBusy(false);}});});};}
OCTOPRINT_VIEWMODELS.push({construct:ClassicWebcamSettingsViewModel,dependencies:["loginStateViewModel","settingsViewModel"],elements:["#classicwebcam_settings"]});});
;

// source: plugin/classicwebcam/js/classicwebcam_wizard.js
$(function(){function ClassicWebcamWizardViewModel(parameters){var self=this;self.settingsViewModel=parameters[0];self.onWizardFinish=function(){if(self.settingsViewModel.streamUrl()){return"reload";}};}
OCTOPRINT_VIEWMODELS.push({construct:ClassicWebcamWizardViewModel,dependencies:["classicWebcamSettingsViewModel"],elements:["#wizard_classicwebcam"]});});
;

// source: plugin/errortracking/js/sentry.min.js
/*! @sentry/browser 6.18.2 (22f518e) | https://github.com/getsentry/sentry-javascript */
var Sentry=function(t){var n=function(t,r){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])},n(t,r)};function r(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function i(){this.constructor=t}n(t,r),t.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e=function(){return e=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++)for(var e in n=arguments[r])Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e]);return t},e.apply(this,arguments)};function o(t){var n="function"==typeof Symbol&&Symbol.iterator,r=n&&t[n],i=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(t,n){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var i,e,o=r.call(t),u=[];try{for(;(void 0===n||n-- >0)&&!(i=o.next()).done;)u.push(i.value)}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(u(arguments[n]));return t}t.Severity=void 0,(i=t.Severity||(t.Severity={})).Fatal="fatal",i.Error="error",i.Warning="warning",i.Log="log",i.Info="info",i.Debug="debug",i.Critical="critical";var c={};function s(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:c}var f=Object.prototype.toString;function h(t){switch(f.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return x(t,Error)}}function v(t,n){return f.call(t)==="[object "+n+"]"}function d(t){return v(t,"ErrorEvent")}function l(t){return v(t,"DOMError")}function p(t){return v(t,"String")}function y(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function m(t){return v(t,"Object")}function b(t){return"undefined"!=typeof Event&&x(t,Event)}function w(t){return"undefined"!=typeof Element&&x(t,Element)}function g(t){return Boolean(t&&t.then&&"function"==typeof t.then)}function x(t,n){try{return t instanceof n}catch(t){return!1}}function E(t,n){try{for(var r=t,i=[],e=0,o=0,u=" > ".length,a=void 0;r&&e++<5&&!("html"===(a=_(r,n))||e>1&&o+i.length*u+a.length>=80);)i.push(a),o+=a.length,r=r.parentNode;return i.reverse().join(" > ")}catch(t){return"<unknown>"}}function _(t,n){var r,i,e,o,u,a=t,c=[];if(!a||!a.tagName)return"";c.push(a.tagName.toLowerCase());var s=n&&n.length?n.filter((function(t){return a.getAttribute(t)})).map((function(t){return[t,a.getAttribute(t)]})):null;if(s&&s.length)s.forEach((function(t){c.push("["+t[0]+'="'+t[1]+'"]')}));else if(a.id&&c.push("#"+a.id),(r=a.className)&&p(r))for(i=r.split(/\s+/),u=0;u<i.length;u++)c.push("."+i[u]);var f=["type","name","title","alt"];for(u=0;u<f.length;u++)e=f[u],(o=a.getAttribute(e))&&c.push("["+e+'="'+o+'"]');return c.join("")}var j=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,n){return t.__proto__=n,t}:function(t,n){for(var r in n)Object.prototype.hasOwnProperty.call(t,r)||(t[r]=n[r]);return t});var k=function(t){function n(n){var r=this.constructor,i=t.call(this,n)||this;return i.message=n,i.name=r.prototype.constructor.name,j(i,r.prototype),i}return r(n,t),n}(Error),S=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;function O(t,n){void 0===n&&(n=!1);var r=t.host,i=t.path,e=t.pass,o=t.port,u=t.projectId;return t.protocol+"://"+t.publicKey+(n&&e?":"+e:"")+"@"+r+(o?":"+o:"")+"/"+(i?i+"/":i)+u}function T(t){return"user"in t&&!("publicKey"in t)&&(t.publicKey=t.user),{user:t.publicKey||"",protocol:t.protocol,publicKey:t.publicKey||"",pass:t.pass||"",host:t.host,port:t.port||"",path:t.path||"",projectId:t.projectId}}function D(t){var n="string"==typeof t?function(t){var n=S.exec(t);if(!n)throw new k("Invalid Sentry Dsn: "+t);var r=u(n.slice(1),6),i=r[0],e=r[1],o=r[2],a=void 0===o?"":o,c=r[3],s=r[4],f=void 0===s?"":s,h="",v=r[5],d=v.split("/");if(d.length>1&&(h=d.slice(0,-1).join("/"),v=d.pop()),v){var l=v.match(/^\d+/);l&&(v=l[0])}return T({host:c,pass:a,path:h,projectId:v,port:f,protocol:i,publicKey:e})}(t):T(t);return n}var R=["fatal","error","warning","log","info","debug","critical"],N=s(),I="Sentry Logger ";function M(t){var n=s();if(!("console"in n))return t();var r=n.console,i={};["debug","info","warn","error","log","assert"].forEach((function(t){t in n.console&&r[t].__sentry_original__&&(i[t]=r[t],r[t]=r[t].__sentry_original__)}));var e=t();return Object.keys(i).forEach((function(t){r[t]=i[t]})),e}var q=function(){function t(){this.t=!1}return t.prototype.disable=function(){this.t=!1},t.prototype.enable=function(){this.t=!0},t.prototype.log=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];this.t&&M((function(){var n;(n=N.console).log.apply(n,a([I+"[Log]:"],t))}))},t.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];this.t&&M((function(){var n;(n=N.console).warn.apply(n,a([I+"[Warn]:"],t))}))},t.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];this.t&&M((function(){var n;(n=N.console).error.apply(n,a([I+"[Error]:"],t))}))},t}();N.__SENTRY__=N.__SENTRY__||{};var A=N.__SENTRY__.logger||(N.__SENTRY__.logger=new q);function C(t){if(!t.length)return[];var n=t,r=n[0].function||"",i=n[n.length-1].function||"";return-1===r.indexOf("captureMessage")&&-1===r.indexOf("captureException")||(n=n.slice(1)),-1!==i.indexOf("sentryWrapped")&&(n=n.slice(0,-1)),n.slice(0,50).map((function(t){return e(e({},t),{filename:t.filename||n[0].filename,function:t.function||"?"})})).reverse()}var L="<anonymous>";function U(t){try{return t&&"function"==typeof t&&t.name||L}catch(t){return L}}function H(t,n){return void 0===n&&(n=0),"string"!=typeof t||0===n||t.length<=n?t:t.substr(0,n)+"..."}function F(t,n){if(!Array.isArray(t))return"";for(var r=[],i=0;i<t.length;i++){var e=t[i];try{r.push(String(e))}catch(t){r.push("[value cannot be serialized]")}}return r.join(n)}function P(t,n){return!!p(t)&&(v(n,"RegExp")?n.test(t):"string"==typeof n&&-1!==t.indexOf(n))}function X(t,n,r){if(n in t){var i=t[n],e=r(i);if("function"==typeof e)try{W(e,i)}catch(t){}t[n]=e}}function B(t,n,r){Object.defineProperty(t,n,{value:r,writable:!0,configurable:!0})}function W(t,n){var r=n.prototype||{};t.prototype=n.prototype=r,B(t,"__sentry_original__",n)}function $(t){return t.__sentry_original__}function J(t){if(h(t)){var n=t,r={message:n.message,name:n.name,stack:n.stack};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i]);return r}if(b(t)){var e=t,o={};o.type=e.type;try{o.target=w(e.target)?E(e.target):Object.prototype.toString.call(e.target)}catch(t){o.target="<unknown>"}try{o.currentTarget=w(e.currentTarget)?E(e.currentTarget):Object.prototype.toString.call(e.currentTarget)}catch(t){o.currentTarget="<unknown>"}for(var u in"undefined"!=typeof CustomEvent&&x(t,CustomEvent)&&(o.detail=e.detail),e)Object.prototype.hasOwnProperty.call(e,u)&&(o[u]=e[u]);return o}return t}function z(t){return function(t){return~-encodeURI(t).split(/%..|./).length}(JSON.stringify(t))}function G(t,n,r){void 0===n&&(n=3),void 0===r&&(r=102400);var i=Q(t,n);return z(i)>r?G(t,n-1,r):i}function K(t,n){return"domain"===n&&t&&"object"==typeof t&&t.i?"[Domain]":"domainEmitter"===n?"[DomainEmitter]":"undefined"!=typeof global&&t===global?"[Global]":"undefined"!=typeof window&&t===window?"[Window]":"undefined"!=typeof document&&t===document?"[Document]":m(r=t)&&"nativeEvent"in r&&"preventDefault"in r&&"stopPropagation"in r?"[SyntheticEvent]":"number"==typeof t&&t!=t?"[NaN]":void 0===t?"[undefined]":"function"==typeof t?"[Function: "+U(t)+"]":"symbol"==typeof t?"["+String(t)+"]":"bigint"==typeof t?"[BigInt: "+String(t)+"]":t;var r}function V(t,n,r,i){var e,o;void 0===r&&(r=1/0),void 0===i&&(e="function"==typeof WeakSet,o=e?new WeakSet:[],i=[function(t){if(e)return!!o.has(t)||(o.add(t),!1);for(var n=0;n<o.length;n++)if(o[n]===t)return!0;return o.push(t),!1},function(t){if(e)o.delete(t);else for(var n=0;n<o.length;n++)if(o[n]===t){o.splice(n,1);break}}]);var a=u(i,2),c=a[0],s=a[1];if(0===r)return function(t){if("string"==typeof t)return t;var n=Object.prototype.toString.call(t);if("[object Object]"===n)return"[Object]";if("[object Array]"===n)return"[Array]";var r=K(t);return y(r)?r:n}(n);if(null!=n&&"function"==typeof n.toJSON)return n.toJSON();var f=K(n,t);if(y(f))return f;var h=J(n),v=Array.isArray(n)?[]:{};if(c(n))return"[Circular ~]";for(var d in h)if(Object.prototype.hasOwnProperty.call(h,d)){var l=h[d];v[d]=V(d,l,r-1,i)}return s(n),v}function Q(t,n){try{return V("",t,n)}catch(t){return"**non-serializable**"}}function Y(t,n){void 0===n&&(n=40);var r=Object.keys(J(t));if(r.sort(),!r.length)return"[object has no keys]";if(r[0].length>=n)return H(r[0],n);for(var i=r.length;i>0;i--){var e=r.slice(0,i).join(", ");if(!(e.length>n))return i===r.length?e:H(e,n)}return""}function Z(t){var n,r;if(m(t)){var i=t,e={};try{for(var u=o(Object.keys(i)),a=u.next();!a.done;a=u.next()){var c=a.value;void 0!==i[c]&&(e[c]=Z(i[c]))}}catch(t){n={error:t}}finally{try{a&&!a.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}return e}return Array.isArray(t)?t.map(Z):t}function tt(){if(!("fetch"in s()))return!1;try{return new Headers,new Request(""),new Response,!0}catch(t){return!1}}function nt(t){return t&&/^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(t.toString())}function rt(){if(!tt())return!1;try{return new Request("_",{referrerPolicy:"origin"}),!0}catch(t){return!1}}var it,et=s(),ot={},ut={};function at(t){if(!ut[t])switch(ut[t]=!0,t){case"console":!function(){if(!("console"in et))return;["debug","info","warn","error","log","assert"].forEach((function(t){t in et.console&&X(et.console,t,(function(n){return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];st("console",{args:r,level:t}),n&&n.apply(et.console,r)}}))}))}();break;case"dom":!function(){if(!("document"in et))return;var t=st.bind(null,"dom"),n=lt(t,!0);et.document.addEventListener("click",n,!1),et.document.addEventListener("keypress",n,!1),["EventTarget","Node"].forEach((function(n){var r=et[n]&&et[n].prototype;r&&r.hasOwnProperty&&r.hasOwnProperty("addEventListener")&&(X(r,"addEventListener",(function(n){return function(r,i,e){if("click"===r||"keypress"==r)try{var o=this,u=o.__sentry_instrumentation_handlers__=o.__sentry_instrumentation_handlers__||{},a=u[r]=u[r]||{refCount:0};if(!a.handler){var c=lt(t);a.handler=c,n.call(this,r,c,e)}a.refCount+=1}catch(t){}return n.call(this,r,i,e)}})),X(r,"removeEventListener",(function(t){return function(n,r,i){if("click"===n||"keypress"==n)try{var e=this,o=e.__sentry_instrumentation_handlers__||{},u=o[n];u&&(u.refCount-=1,u.refCount<=0&&(t.call(this,n,u.handler,i),u.handler=void 0,delete o[n]),0===Object.keys(o).length&&delete e.__sentry_instrumentation_handlers__)}catch(t){}return t.call(this,n,r,i)}})))}))}();break;case"xhr":!function(){if(!("XMLHttpRequest"in et))return;var t=XMLHttpRequest.prototype;X(t,"open",(function(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=this,e=n[1],o=i.__sentry_xhr__={method:p(n[0])?n[0].toUpperCase():n[0],url:n[1]};p(e)&&"POST"===o.method&&e.match(/sentry_key/)&&(i.__sentry_own_request__=!0);var u=function(){if(4===i.readyState){try{o.status_code=i.status}catch(t){}st("xhr",{args:n,endTimestamp:Date.now(),startTimestamp:Date.now(),xhr:i})}};return"onreadystatechange"in i&&"function"==typeof i.onreadystatechange?X(i,"onreadystatechange",(function(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return u(),t.apply(i,n)}})):i.addEventListener("readystatechange",u),t.apply(i,n)}})),X(t,"send",(function(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return this.__sentry_xhr__&&void 0!==n[0]&&(this.__sentry_xhr__.body=n[0]),st("xhr",{args:n,startTimestamp:Date.now(),xhr:this}),t.apply(this,n)}}))}();break;case"fetch":!function(){if(!function(){if(!tt())return!1;var t=s();if(nt(t.fetch))return!0;var n=!1,r=t.document;if(r&&"function"==typeof r.createElement)try{var i=r.createElement("iframe");i.hidden=!0,r.head.appendChild(i),i.contentWindow&&i.contentWindow.fetch&&(n=nt(i.contentWindow.fetch)),r.head.removeChild(i)}catch(t){}return n}())return;X(et,"fetch",(function(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i={args:n,fetchData:{method:ft(n),url:ht(n)},startTimestamp:Date.now()};return st("fetch",e({},i)),t.apply(et,n).then((function(t){return st("fetch",e(e({},i),{endTimestamp:Date.now(),response:t})),t}),(function(t){throw st("fetch",e(e({},i),{endTimestamp:Date.now(),error:t})),t}))}}))}();break;case"history":!function(){if(!function(){var t=s(),n=t.chrome,r=n&&n.app&&n.app.runtime,i="history"in t&&!!t.history.pushState&&!!t.history.replaceState;return!r&&i}())return;var t=et.onpopstate;function n(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n.length>2?n[2]:void 0;if(i){var e=it,o=String(i);it=o,st("history",{from:e,to:o})}return t.apply(this,n)}}et.onpopstate=function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=et.location.href,e=it;if(it=i,st("history",{from:e,to:i}),t)try{return t.apply(this,n)}catch(t){}},X(et.history,"pushState",n),X(et.history,"replaceState",n)}();break;case"error":pt=et.onerror,et.onerror=function(t,n,r,i,e){return st("error",{column:i,error:e,line:r,msg:t,url:n}),!!pt&&pt.apply(this,arguments)};break;case"unhandledrejection":yt=et.onunhandledrejection,et.onunhandledrejection=function(t){return st("unhandledrejection",t),!yt||yt.apply(this,arguments)};break;default:A.warn("unknown instrumentation type:",t)}}function ct(t,n){ot[t]=ot[t]||[],ot[t].push(n),at(t)}function st(t,n){var r,i;if(t&&ot[t])try{for(var e=o(ot[t]||[]),u=e.next();!u.done;u=e.next()){var a=u.value;try{a(n)}catch(t){0}}}catch(t){r={error:t}}finally{try{u&&!u.done&&(i=e.return)&&i.call(e)}finally{if(r)throw r.error}}}function ft(t){return void 0===t&&(t=[]),"Request"in et&&x(t[0],Request)&&t[0].method?String(t[0].method).toUpperCase():t[1]&&t[1].method?String(t[1].method).toUpperCase():"GET"}function ht(t){return void 0===t&&(t=[]),"string"==typeof t[0]?t[0]:"Request"in et&&x(t[0],Request)?t[0].url:String(t[0])}var vt,dt;function lt(t,n){return void 0===n&&(n=!1),function(r){if(r&&dt!==r&&!function(t){if("keypress"!==t.type)return!1;try{var n=t.target;if(!n||!n.tagName)return!0;if("INPUT"===n.tagName||"TEXTAREA"===n.tagName||n.isContentEditable)return!1}catch(t){}return!0}(r)){var i="keypress"===r.type?"input":r.type;(void 0===vt||function(t,n){if(!t)return!0;if(t.type!==n.type)return!0;try{if(t.target!==n.target)return!0}catch(t){}return!1}(dt,r))&&(t({event:r,name:i,global:n}),dt=r),clearTimeout(vt),vt=et.setTimeout((function(){vt=void 0}),1e3)}}}var pt=null;var yt=null;function mt(){var t=s(),n=t.crypto||t.msCrypto;if(void 0!==n&&n.getRandomValues){var r=new Uint16Array(8);n.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var i=function(t){for(var n=t.toString(16);n.length<4;)n="0"+n;return n};return i(r[0])+i(r[1])+i(r[2])+i(r[3])+i(r[4])+i(r[5])+i(r[6])+i(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,(function(t){var n=16*Math.random()|0;return("x"===t?n:3&n|8).toString(16)}))}function bt(t){if(!t)return{};var n=t.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!n)return{};var r=n[6]||"",i=n[8]||"";return{host:n[4],path:n[5],protocol:n[2],relative:n[5]+r+i}}function wt(t){return t.exception&&t.exception.values?t.exception.values[0]:void 0}function gt(t){var n=t.message,r=t.event_id;if(n)return n;var i=wt(t);return i?i.type&&i.value?i.type+": "+i.value:i.type||i.value||r||"<unknown>":r||"<unknown>"}function xt(t,n,r){var i=t.exception=t.exception||{},e=i.values=i.values||[],o=e[0]=e[0]||{};o.value||(o.value=n||""),o.type||(o.type=r||"Error")}function Et(t,n){var r=wt(t);if(r){var i=r.mechanism;if(r.mechanism=e(e(e({},{type:"generic",handled:!0}),i),n),n&&"data"in n){var o=e(e({},i&&i.data),n.data);r.mechanism.data=o}}}function _t(t){if(t&&t.__sentry_captured__)return!0;try{B(t,"__sentry_captured__",!0)}catch(t){}return!1}function jt(t){return new St((function(n){n(t)}))}function kt(t){return new St((function(n,r){r(t)}))}var St=function(){function t(t){var n=this;this.o=0,this.u=[],this.h=function(t){n.v(1,t)},this.l=function(t){n.v(2,t)},this.v=function(t,r){0===n.o&&(g(r)?r.then(n.h,n.l):(n.o=t,n.p=r,n.m()))},this.m=function(){if(0!==n.o){var t=n.u.slice();n.u=[],t.forEach((function(t){t[0]||(1===n.o&&t[1](n.p),2===n.o&&t[2](n.p),t[0]=!0)}))}};try{t(this.h,this.l)}catch(t){this.l(t)}}return t.prototype.then=function(n,r){var i=this;return new t((function(t,e){i.u.push([!1,function(r){if(n)try{t(n(r))}catch(t){e(t)}else t(r)},function(n){if(r)try{t(r(n))}catch(t){e(t)}else e(n)}]),i.m()}))},t.prototype.catch=function(t){return this.then((function(t){return t}),t)},t.prototype.finally=function(n){var r=this;return new t((function(t,i){var e,o;return r.then((function(t){o=!1,e=t,n&&n()}),(function(t){o=!0,e=t,n&&n()})).then((function(){o?i(e):t(e)}))}))},t}();function Ot(t){var n=[];function r(t){return n.splice(n.indexOf(t),1)[0]}return{$:n,add:function(i){if(!(void 0===t||n.length<t))return kt(new k("Not adding Promise due to buffer limit reached."));var e=i();return-1===n.indexOf(e)&&n.push(e),e.then((function(){return r(e)})).then(null,(function(){return r(e).then(null,(function(){}))})),e},drain:function(t){return new St((function(r,i){var e=n.length;if(!e)return r(!0);var o=setTimeout((function(){t&&t>0&&r(!1)}),t);n.forEach((function(t){jt(t).then((function(){--e||(clearTimeout(o),r(!0))}),i)}))}))}}}function Tt(n){return"warn"===n?t.Severity.Warning:function(t){return-1!==R.indexOf(t)}(n)?n:t.Severity.Log}var Dt={nowSeconds:function(){return Date.now()/1e3}};var Rt=function(){var t=s().performance;if(t&&t.now)return{now:function(){return t.now()},timeOrigin:Date.now()-t.now()}}(),Nt=void 0===Rt?Dt:{nowSeconds:function(){return(Rt.timeOrigin+Rt.now())/1e3}},It=Dt.nowSeconds.bind(Dt),Mt=Nt.nowSeconds.bind(Nt);function qt(t,n){return void 0===n&&(n=[]),[t,n]}function At(t){var n=u(t,2),r=n[0],i=n[1],e=JSON.stringify(r);return i.reduce((function(t,n){var r=u(n,2),i=r[0],e=r[1],o=y(e)?String(e):JSON.stringify(e);return t+"\n"+JSON.stringify(i)+"\n"+o}),e)}!function(){var t=s().performance;if(t&&t.now){var n=36e5,r=t.now(),i=Date.now(),e=t.timeOrigin?Math.abs(t.timeOrigin+r-i):n,o=e<n,u=t.timing&&t.timing.navigationStart,a="number"==typeof u?Math.abs(u+r-i):n;(o||a<n)&&(e<=a&&t.timeOrigin)}}();var Ct=function(){function t(){this.g=!1,this._=[],this.j=[],this.k=[],this.S={},this.O={},this.T={},this.D={},this.R={}}return t.clone=function(n){var r=new t;return n&&(r.k=a(n.k),r.O=e({},n.O),r.T=e({},n.T),r.D=e({},n.D),r.S=n.S,r.N=n.N,r.I=n.I,r.M=n.M,r.q=n.q,r.A=n.A,r.j=a(n.j),r.C=n.C),r},t.prototype.addScopeListener=function(t){this._.push(t)},t.prototype.addEventProcessor=function(t){return this.j.push(t),this},t.prototype.setUser=function(t){return this.S=t||{},this.M&&this.M.update({user:t}),this.L(),this},t.prototype.getUser=function(){return this.S},t.prototype.getRequestSession=function(){return this.C},t.prototype.setRequestSession=function(t){return this.C=t,this},t.prototype.setTags=function(t){return this.O=e(e({},this.O),t),this.L(),this},t.prototype.setTag=function(t,n){var r;return this.O=e(e({},this.O),((r={})[t]=n,r)),this.L(),this},t.prototype.setExtras=function(t){return this.T=e(e({},this.T),t),this.L(),this},t.prototype.setExtra=function(t,n){var r;return this.T=e(e({},this.T),((r={})[t]=n,r)),this.L(),this},t.prototype.setFingerprint=function(t){return this.A=t,this.L(),this},t.prototype.setLevel=function(t){return this.N=t,this.L(),this},t.prototype.setTransactionName=function(t){return this.q=t,this.L(),this},t.prototype.setTransaction=function(t){return this.setTransactionName(t)},t.prototype.setContext=function(t,n){var r;return null===n?delete this.D[t]:this.D=e(e({},this.D),((r={})[t]=n,r)),this.L(),this},t.prototype.setSpan=function(t){return this.I=t,this.L(),this},t.prototype.getSpan=function(){return this.I},t.prototype.getTransaction=function(){var t=this.getSpan();return t&&t.transaction},t.prototype.setSession=function(t){return t?this.M=t:delete this.M,this.L(),this},t.prototype.getSession=function(){return this.M},t.prototype.update=function(n){if(!n)return this;if("function"==typeof n){var r=n(this);return r instanceof t?r:this}return n instanceof t?(this.O=e(e({},this.O),n.O),this.T=e(e({},this.T),n.T),this.D=e(e({},this.D),n.D),n.S&&Object.keys(n.S).length&&(this.S=n.S),n.N&&(this.N=n.N),n.A&&(this.A=n.A),n.C&&(this.C=n.C)):m(n)&&(n=n,this.O=e(e({},this.O),n.tags),this.T=e(e({},this.T),n.extra),this.D=e(e({},this.D),n.contexts),n.user&&(this.S=n.user),n.level&&(this.N=n.level),n.fingerprint&&(this.A=n.fingerprint),n.requestSession&&(this.C=n.requestSession)),this},t.prototype.clear=function(){return this.k=[],this.O={},this.T={},this.S={},this.D={},this.N=void 0,this.q=void 0,this.A=void 0,this.C=void 0,this.I=void 0,this.M=void 0,this.L(),this},t.prototype.addBreadcrumb=function(t,n){var r="number"==typeof n?Math.min(n,100):100;if(r<=0)return this;var i=e({timestamp:It()},t);return this.k=a(this.k,[i]).slice(-r),this.L(),this},t.prototype.clearBreadcrumbs=function(){return this.k=[],this.L(),this},t.prototype.applyToEvent=function(t,n){if(this.T&&Object.keys(this.T).length&&(t.extra=e(e({},this.T),t.extra)),this.O&&Object.keys(this.O).length&&(t.tags=e(e({},this.O),t.tags)),this.S&&Object.keys(this.S).length&&(t.user=e(e({},this.S),t.user)),this.D&&Object.keys(this.D).length&&(t.contexts=e(e({},this.D),t.contexts)),this.N&&(t.level=this.N),this.q&&(t.transaction=this.q),this.I){t.contexts=e({trace:this.I.getTraceContext()},t.contexts);var r=this.I.transaction&&this.I.transaction.name;r&&(t.tags=e({transaction:r},t.tags))}return this.U(t),t.breadcrumbs=a(t.breadcrumbs||[],this.k),t.breadcrumbs=t.breadcrumbs.length>0?t.breadcrumbs:void 0,t.sdkProcessingMetadata=this.R,this.H(a(Lt(),this.j),t,n)},t.prototype.setSDKProcessingMetadata=function(t){return this.R=e(e({},this.R),t),this},t.prototype.H=function(t,n,r,i){var o=this;return void 0===i&&(i=0),new St((function(u,a){var c=t[i];if(null===n||"function"!=typeof c)u(n);else{var s=c(e({},n),r);g(s)?s.then((function(n){return o.H(t,n,r,i+1).then(u)})).then(null,a):o.H(t,s,r,i+1).then(u).then(null,a)}}))},t.prototype.L=function(){var t=this;this.g||(this.g=!0,this._.forEach((function(n){n(t)})),this.g=!1)},t.prototype.U=function(t){t.fingerprint=t.fingerprint?Array.isArray(t.fingerprint)?t.fingerprint:[t.fingerprint]:[],this.A&&(t.fingerprint=t.fingerprint.concat(this.A)),t.fingerprint&&!t.fingerprint.length&&delete t.fingerprint},t}();function Lt(){var t=s();return t.__SENTRY__=t.__SENTRY__||{},t.__SENTRY__.globalEventProcessors=t.__SENTRY__.globalEventProcessors||[],t.__SENTRY__.globalEventProcessors}function Ut(t){Lt().push(t)}var Ht=function(){function t(t){this.errors=0,this.sid=mt(),this.duration=0,this.status="ok",this.init=!0,this.ignoreDuration=!1;var n=Mt();this.timestamp=n,this.started=n,t&&this.update(t)}return t.prototype.update=function(t){if(void 0===t&&(t={}),t.user&&(!this.ipAddress&&t.user.ip_address&&(this.ipAddress=t.user.ip_address),this.did||t.did||(this.did=t.user.id||t.user.email||t.user.username)),this.timestamp=t.timestamp||Mt(),t.ignoreDuration&&(this.ignoreDuration=t.ignoreDuration),t.sid&&(this.sid=32===t.sid.length?t.sid:mt()),void 0!==t.init&&(this.init=t.init),!this.did&&t.did&&(this.did=""+t.did),"number"==typeof t.started&&(this.started=t.started),this.ignoreDuration)this.duration=void 0;else if("number"==typeof t.duration)this.duration=t.duration;else{var n=this.timestamp-this.started;this.duration=n>=0?n:0}t.release&&(this.release=t.release),t.environment&&(this.environment=t.environment),!this.ipAddress&&t.ipAddress&&(this.ipAddress=t.ipAddress),!this.userAgent&&t.userAgent&&(this.userAgent=t.userAgent),"number"==typeof t.errors&&(this.errors=t.errors),t.status&&(this.status=t.status)},t.prototype.close=function(t){t?this.update({status:t}):"ok"===this.status?this.update({status:"exited"}):this.update()},t.prototype.toJSON=function(){return Z({sid:""+this.sid,init:this.init,started:new Date(1e3*this.started).toISOString(),timestamp:new Date(1e3*this.timestamp).toISOString(),status:this.status,errors:this.errors,did:"number"==typeof this.did||"string"==typeof this.did?""+this.did:void 0,duration:this.duration,attrs:{release:this.release,environment:this.environment,ip_address:this.ipAddress,user_agent:this.userAgent}})},t}(),Ft=function(){function t(t,n,r){void 0===n&&(n=new Ct),void 0===r&&(r=4),this.F=r,this.P=[{}],this.getStackTop().scope=n,t&&this.bindClient(t)}return t.prototype.isOlderThan=function(t){return this.F<t},t.prototype.bindClient=function(t){this.getStackTop().client=t,t&&t.setupIntegrations&&t.setupIntegrations()},t.prototype.pushScope=function(){var t=Ct.clone(this.getScope());return this.getStack().push({client:this.getClient(),scope:t}),t},t.prototype.popScope=function(){return!(this.getStack().length<=1)&&!!this.getStack().pop()},t.prototype.withScope=function(t){var n=this.pushScope();try{t(n)}finally{this.popScope()}},t.prototype.getClient=function(){return this.getStackTop().client},t.prototype.getScope=function(){return this.getStackTop().scope},t.prototype.getStack=function(){return this.P},t.prototype.getStackTop=function(){return this.P[this.P.length-1]},t.prototype.captureException=function(t,n){var r=this.X=n&&n.event_id?n.event_id:mt(),i=n;if(!n){var o=void 0;try{throw new Error("Sentry syntheticException")}catch(t){o=t}i={originalException:t,syntheticException:o}}return this.B("captureException",t,e(e({},i),{event_id:r})),r},t.prototype.captureMessage=function(t,n,r){var i=this.X=r&&r.event_id?r.event_id:mt(),o=r;if(!r){var u=void 0;try{throw new Error(t)}catch(t){u=t}o={originalException:t,syntheticException:u}}return this.B("captureMessage",t,n,e(e({},o),{event_id:i})),i},t.prototype.captureEvent=function(t,n){var r=n&&n.event_id?n.event_id:mt();return"transaction"!==t.type&&(this.X=r),this.B("captureEvent",t,e(e({},n),{event_id:r})),r},t.prototype.lastEventId=function(){return this.X},t.prototype.addBreadcrumb=function(t,n){var r=this.getStackTop(),i=r.scope,o=r.client;if(i&&o){var u=o.getOptions&&o.getOptions()||{},a=u.beforeBreadcrumb,c=void 0===a?null:a,s=u.maxBreadcrumbs,f=void 0===s?100:s;if(!(f<=0)){var h=It(),v=e({timestamp:h},t),d=c?M((function(){return c(v,n)})):v;null!==d&&i.addBreadcrumb(d,f)}}},t.prototype.setUser=function(t){var n=this.getScope();n&&n.setUser(t)},t.prototype.setTags=function(t){var n=this.getScope();n&&n.setTags(t)},t.prototype.setExtras=function(t){var n=this.getScope();n&&n.setExtras(t)},t.prototype.setTag=function(t,n){var r=this.getScope();r&&r.setTag(t,n)},t.prototype.setExtra=function(t,n){var r=this.getScope();r&&r.setExtra(t,n)},t.prototype.setContext=function(t,n){var r=this.getScope();r&&r.setContext(t,n)},t.prototype.configureScope=function(t){var n=this.getStackTop(),r=n.scope,i=n.client;r&&i&&t(r)},t.prototype.run=function(t){var n=Xt(this);try{t(this)}finally{Xt(n)}},t.prototype.getIntegration=function(t){var n=this.getClient();if(!n)return null;try{return n.getIntegration(t)}catch(n){return A.warn("Cannot retrieve integration "+t.id+" from the current Hub"),null}},t.prototype.startSpan=function(t){return this.W("startSpan",t)},t.prototype.startTransaction=function(t,n){return this.W("startTransaction",t,n)},t.prototype.traceHeaders=function(){return this.W("traceHeaders")},t.prototype.captureSession=function(t){if(void 0===t&&(t=!1),t)return this.endSession();this.J()},t.prototype.endSession=function(){var t=this.getStackTop(),n=t&&t.scope,r=n&&n.getSession();r&&r.close(),this.J(),n&&n.setSession()},t.prototype.startSession=function(t){var n=this.getStackTop(),r=n.scope,i=n.client,o=i&&i.getOptions()||{},u=o.release,a=o.environment,c=(s().navigator||{}).userAgent,f=new Ht(e(e(e({release:u,environment:a},r&&{user:r.getUser()}),c&&{userAgent:c}),t));if(r){var h=r.getSession&&r.getSession();h&&"ok"===h.status&&h.update({status:"exited"}),this.endSession(),r.setSession(f)}return f},t.prototype.J=function(){var t=this.getStackTop(),n=t.scope,r=t.client;if(n){var i=n.getSession&&n.getSession();i&&r&&r.captureSession&&r.captureSession(i)}},t.prototype.B=function(t){for(var n,r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];var e=this.getStackTop(),o=e.scope,u=e.client;u&&u[t]&&(n=u)[t].apply(n,a(r,[o]))},t.prototype.W=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=Pt(),e=i.__SENTRY__;if(e&&e.extensions&&"function"==typeof e.extensions[t])return e.extensions[t].apply(this,n);A.warn("Extension method "+t+" couldn't be found, doing nothing.")},t}();function Pt(){var t=s();return t.__SENTRY__=t.__SENTRY__||{extensions:{},hub:void 0},t}function Xt(t){var n=Pt(),r=Wt(n);return $t(n,t),r}function Bt(){var t,n=Pt();return(t=n)&&t.__SENTRY__&&t.__SENTRY__.hub&&!Wt(n).isOlderThan(4)||$t(n,new Ft),Wt(n)}function Wt(t){return t&&t.__SENTRY__&&t.__SENTRY__.hub||(t.__SENTRY__=t.__SENTRY__||{},t.__SENTRY__.hub=new Ft),t.__SENTRY__.hub}function $t(t,n){return!!t&&(t.__SENTRY__=t.__SENTRY__||{},t.__SENTRY__.hub=n,!0)}function Jt(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var i=Bt();if(i&&i[t])return i[t].apply(i,a(n));throw new Error("No hub defined or "+t+" was not found on the hub, please open a bug report.")}function captureException(t,n){var r;try{throw new Error("Sentry syntheticException")}catch(t){r=t}return Jt("captureException",t,{captureContext:n,originalException:t,syntheticException:r})}function zt(t){Jt("withScope",t)}function Gt(t){var n=t.protocol?t.protocol+":":"",r=t.port?":"+t.port:"";return n+"//"+t.host+r+(t.path?"/"+t.path:"")+"/api/"}function Kt(t,n){return""+Gt(t)+t.projectId+"/"+n+"/"}function Vt(t){return n={sentry_key:t.publicKey,sentry_version:"7"},Object.keys(n).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])})).join("&");var n}function Qt(t){return function(t){return Kt(t,"store")}(t)+"?"+Vt(t)}function Yt(t,n){return n||function(t){return Kt(t,"envelope")}(t)+"?"+Vt(t)}var Zt=[];function tn(t){return t.reduce((function(t,n){return t.every((function(t){return n.name!==t.name}))&&t.push(n),t}),[])}function nn(t){var n={};return function(t){var n=t.defaultIntegrations&&a(t.defaultIntegrations)||[],r=t.integrations,i=a(tn(n));Array.isArray(r)?i=a(i.filter((function(t){return r.every((function(n){return n.name!==t.name}))})),tn(r)):"function"==typeof r&&(i=r(i),i=Array.isArray(i)?i:[i]);var e=i.map((function(t){return t.name})),o="Debug";return-1!==e.indexOf(o)&&i.push.apply(i,a(i.splice(e.indexOf(o),1))),i}(t).forEach((function(t){n[t.name]=t,function(t){-1===Zt.indexOf(t.name)&&(t.setupOnce(Ut,Bt),Zt.push(t.name),A.log("Integration installed: "+t.name))}(t)})),B(n,"initialized",!0),n}var rn="Not capturing exception because it's already been captured.",en=function(){function t(t,n){this.G={},this.K=0,this.V=new t(n),this.Y=n,n.dsn&&(this.Z=D(n.dsn))}return t.prototype.captureException=function(t,n,r){var i=this;if(!_t(t)){var e=n&&n.event_id;return this.tt(this.nt().eventFromException(t,n).then((function(t){return i.rt(t,n,r)})).then((function(t){e=t}))),e}A.log(rn)},t.prototype.captureMessage=function(t,n,r,i){var e=this,o=r&&r.event_id,u=y(t)?this.nt().eventFromMessage(String(t),n,r):this.nt().eventFromException(t,r);return this.tt(u.then((function(t){return e.rt(t,r,i)})).then((function(t){o=t}))),o},t.prototype.captureEvent=function(t,n,r){if(!(n&&n.originalException&&_t(n.originalException))){var i=n&&n.event_id;return this.tt(this.rt(t,n,r).then((function(t){i=t}))),i}A.log(rn)},t.prototype.captureSession=function(t){this.it()&&("string"!=typeof t.release||(this.et(t),t.update({init:!1})))},t.prototype.getDsn=function(){return this.Z},t.prototype.getOptions=function(){return this.Y},t.prototype.getTransport=function(){return this.nt().getTransport()},t.prototype.flush=function(t){var n=this;return this.ot(t).then((function(r){return n.getTransport().close(t).then((function(t){return r&&t}))}))},t.prototype.close=function(t){var n=this;return this.flush(t).then((function(t){return n.getOptions().enabled=!1,t}))},t.prototype.setupIntegrations=function(){this.it()&&!this.G.initialized&&(this.G=nn(this.Y))},t.prototype.getIntegration=function(t){try{return this.G[t.id]||null}catch(n){return A.warn("Cannot retrieve integration "+t.id+" from the current Client"),null}},t.prototype.ut=function(t,n){var r,i,u=!1,a=!1,c=n.exception&&n.exception.values;if(c){a=!0;try{for(var s=o(c),f=s.next();!f.done;f=s.next()){var h=f.value.mechanism;if(h&&!1===h.handled){u=!0;break}}}catch(t){r={error:t}}finally{try{f&&!f.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}}var v="ok"===t.status;(v&&0===t.errors||v&&u)&&(t.update(e(e({},u&&{status:"crashed"}),{errors:t.errors||Number(a||u)})),this.captureSession(t))},t.prototype.et=function(t){this.nt().sendSession(t)},t.prototype.ot=function(t){var n=this;return new St((function(r){var i=0,e=setInterval((function(){0==n.K?(clearInterval(e),r(!0)):(i+=1,t&&i>=t&&(clearInterval(e),r(!1)))}),1)}))},t.prototype.nt=function(){return this.V},t.prototype.it=function(){return!1!==this.getOptions().enabled&&void 0!==this.Z},t.prototype.at=function(t,n,r){var i=this,o=this.getOptions().normalizeDepth,u=void 0===o?3:o,a=e(e({},t),{event_id:t.event_id||(r&&r.event_id?r.event_id:mt()),timestamp:t.timestamp||It()});this.ct(a),this.st(a);var c=n;r&&r.captureContext&&(c=Ct.clone(c).update(r.captureContext));var s=jt(a);return c&&(s=c.applyToEvent(a,r)),s.then((function(t){return t&&(t.sdkProcessingMetadata=e(e({},t.sdkProcessingMetadata),{normalizeDepth:Q(u)})),"number"==typeof u&&u>0?i.ft(t,u):t}))},t.prototype.ft=function(t,n){if(!t)return null;var r=e(e(e(e(e({},t),t.breadcrumbs&&{breadcrumbs:t.breadcrumbs.map((function(t){return e(e({},t),t.data&&{data:Q(t.data,n)})}))}),t.user&&{user:Q(t.user,n)}),t.contexts&&{contexts:Q(t.contexts,n)}),t.extra&&{extra:Q(t.extra,n)});return t.contexts&&t.contexts.trace&&(r.contexts.trace=t.contexts.trace),t.sdkProcessingMetadata=e(e({},t.sdkProcessingMetadata),{baseClientNormalized:!0}),r},t.prototype.ct=function(t){var n=this.getOptions(),r=n.environment,i=n.release,e=n.dist,o=n.maxValueLength,u=void 0===o?250:o;"environment"in t||(t.environment="environment"in n?r:"production"),void 0===t.release&&void 0!==i&&(t.release=i),void 0===t.dist&&void 0!==e&&(t.dist=e),t.message&&(t.message=H(t.message,u));var a=t.exception&&t.exception.values&&t.exception.values[0];a&&a.value&&(a.value=H(a.value,u));var c=t.request;c&&c.url&&(c.url=H(c.url,u))},t.prototype.st=function(t){var n=Object.keys(this.G);n.length>0&&(t.sdk=t.sdk||{},t.sdk.integrations=a(t.sdk.integrations||[],n))},t.prototype.ht=function(t){this.nt().sendEvent(t)},t.prototype.rt=function(t,n,r){return this.vt(t,n,r).then((function(t){return t.event_id}),(function(t){A.error(t)}))},t.prototype.vt=function(t,n,r){var i=this,e=this.getOptions(),o=e.beforeSend,u=e.sampleRate,a=this.getTransport();function c(t,n){a.recordLostEvent&&a.recordLostEvent(t,n)}if(!this.it())return kt(new k("SDK not enabled, will not capture event."));var s="transaction"===t.type;return!s&&"number"==typeof u&&Math.random()>u?(c("sample_rate","event"),kt(new k("Discarding event because it's not included in the random sample (sampling rate = "+u+")"))):this.at(t,r,n).then((function(r){if(null===r)throw c("event_processor",t.type||"event"),new k("An event processor returned null, will not send event.");return n&&n.data&&!0===n.data.__sentry__||s||!o?r:function(t){var n="`beforeSend` method has to return `null` or a valid event.";if(g(t))return t.then((function(t){if(!m(t)&&null!==t)throw new k(n);return t}),(function(t){throw new k("beforeSend rejected with "+t)}));if(!m(t)&&null!==t)throw new k(n);return t}(o(r,n))})).then((function(n){if(null===n)throw c("before_send",t.type||"event"),new k("`beforeSend` returned `null`, will not send event.");var e=r&&r.getSession&&r.getSession();return!s&&e&&i.ut(e,n),i.ht(n),n})).then(null,(function(t){if(t instanceof k)throw t;throw i.captureException(t,{data:{__sentry__:!0},originalException:t}),new k("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: "+t)}))},t.prototype.tt=function(t){var n=this;this.K+=1,t.then((function(t){return n.K-=1,t}),(function(t){return n.K-=1,t}))},t}();var on=function(){function t(){}return t.prototype.sendEvent=function(t){return jt({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:"skipped"})},t.prototype.close=function(t){return jt(!0)},t}(),un=function(){function t(t){this.Y=t,this.Y.dsn||A.warn("No DSN provided, backend will not do anything."),this.dt=this.lt()}return t.prototype.eventFromException=function(t,n){throw new k("Backend has to implement `eventFromException` method")},t.prototype.eventFromMessage=function(t,n,r){throw new k("Backend has to implement `eventFromMessage` method")},t.prototype.sendEvent=function(t){this.dt.sendEvent(t).then(null,(function(t){0}))},t.prototype.sendSession=function(t){this.dt.sendSession&&this.dt.sendSession(t).then(null,(function(t){0}))},t.prototype.getTransport=function(){return this.dt},t.prototype.lt=function(){return new on},t}();function an(t){if(t.metadata&&t.metadata.sdk){var n=t.metadata.sdk;return{name:n.name,version:n.version}}}function cn(t,n){var r,i=an(n),o=t.type||"event",u="transaction"===o||!!n.tunnel,c=(t.sdkProcessingMetadata||{}).transactionSampling||{},s=c.method,f=c.rate;!function(t,n){n&&(t.sdk=t.sdk||{},t.sdk.name=t.sdk.name||n.name,t.sdk.version=t.sdk.version||n.version,t.sdk.integrations=a(t.sdk.integrations||[],n.integrations||[]),t.sdk.packages=a(t.sdk.packages||[],n.packages||[]))}(t,n.metadata.sdk),t.tags=t.tags||{},t.extra=t.extra||{},t.sdkProcessingMetadata&&t.sdkProcessingMetadata.baseClientNormalized||(t.tags.skippedNormalization=!0,t.extra.normalizeDepth=t.sdkProcessingMetadata?t.sdkProcessingMetadata.normalizeDepth:"unset"),delete t.sdkProcessingMetadata;try{r=JSON.stringify(t)}catch(n){t.tags.JSONStringifyError=!0,t.extra.JSONStringifyError=n;try{r=JSON.stringify(Q(t))}catch(t){var h=t;r=JSON.stringify({message:"JSON.stringify error after renormalization",extra:{message:h.message,stack:h.stack}})}}var v={body:r,type:o,url:u?Yt(n.dsn,n.tunnel):Qt(n.dsn)};if(u){var d=qt(e(e({event_id:t.event_id,sent_at:(new Date).toISOString()},i&&{sdk:i}),!!n.tunnel&&{dsn:O(n.dsn)}),[[{type:o,sample_rates:[{id:s,rate:f}]},v.body]]);v.body=At(d)}return v}var sn,fn="6.18.2",hn=function(){function t(){this.name=t.id}return t.prototype.setupOnce=function(){sn=Function.prototype.toString,Function.prototype.toString=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=$(this)||this;return sn.apply(r,t)}},t.id="FunctionToString",t}(),vn=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/],dn=function(){function t(n){void 0===n&&(n={}),this.Y=n,this.name=t.id}return t.prototype.setupOnce=function(){Ut((function(n){var r=Bt();if(!r)return n;var i=r.getIntegration(t);if(i){var e=r.getClient(),o=e?e.getOptions():{},u="function"==typeof i.yt?i.yt(o):{};return"function"!=typeof i.bt?n:i.bt(n,u)?null:n}return n}))},t.prototype.bt=function(t,n){return!!this.wt(t,n)||(!!this.gt(t,n)||(!!this.xt(t,n)||!this.Et(t,n)))},t.prototype.wt=function(t,n){if(!n.ignoreInternal)return!1;try{return"SentryError"===t.exception.values[0].type}catch(t){}return!1},t.prototype.gt=function(t,n){return!(!n.ignoreErrors||!n.ignoreErrors.length)&&this._t(t).some((function(t){return n.ignoreErrors.some((function(n){return P(t,n)}))}))},t.prototype.xt=function(t,n){if(!n.denyUrls||!n.denyUrls.length)return!1;var r=this.jt(t);return!!r&&n.denyUrls.some((function(t){return P(r,t)}))},t.prototype.Et=function(t,n){if(!n.allowUrls||!n.allowUrls.length)return!0;var r=this.jt(t);return!r||n.allowUrls.some((function(t){return P(r,t)}))},t.prototype.yt=function(t){return void 0===t&&(t={}),{allowUrls:a(this.Y.whitelistUrls||[],this.Y.allowUrls||[],t.whitelistUrls||[],t.allowUrls||[]),denyUrls:a(this.Y.blacklistUrls||[],this.Y.denyUrls||[],t.blacklistUrls||[],t.denyUrls||[]),ignoreErrors:a(this.Y.ignoreErrors||[],t.ignoreErrors||[],vn),ignoreInternal:void 0===this.Y.ignoreInternal||this.Y.ignoreInternal}},t.prototype._t=function(t){if(t.message)return[t.message];if(t.exception)try{var n=t.exception.values&&t.exception.values[0]||{},r=n.type,i=void 0===r?"":r,e=n.value,o=void 0===e?"":e;return[""+o,i+": "+o]}catch(t){return[]}return[]},t.prototype.kt=function(t){void 0===t&&(t=[]);for(var n=t.length-1;n>=0;n--){var r=t[n];if(r&&"<anonymous>"!==r.filename&&"[native code]"!==r.filename)return r.filename||null}return null},t.prototype.jt=function(t){try{if(t.stacktrace)return this.kt(t.stacktrace.frames);var n;try{n=t.exception.values[0].stacktrace.frames}catch(t){}return n?this.kt(n):null}catch(t){return null}},t.id="InboundFilters",t}(),ln=Object.freeze({__proto__:null,FunctionToString:hn,InboundFilters:dn}),pn="?";function yn(t,n,r,i){var e={filename:t,function:n,in_app:!0};return void 0!==r&&(e.lineno=r),void 0!==i&&(e.colno=i),e}var mn=/^\s*at (?:(.*?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,bn=/\((\S*)(?::(\d+))(?::(\d+))\)/,wn=[30,function(t){var n=mn.exec(t);if(n){if(n[2]&&0===n[2].indexOf("eval")){var r=bn.exec(n[2]);r&&(n[2]=r[1],n[3]=r[2],n[4]=r[3])}var i=u(Dn(n[1]||pn,n[2]),2),e=i[0];return yn(i[1],e,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}}],gn=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xn=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,En=[50,function(t){var n,r=gn.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){var i=xn.exec(r[3]);i&&(r[1]=r[1]||"eval",r[3]=i[1],r[4]=i[2],r[5]="")}var e=r[3],o=r[1]||pn;return o=(n=u(Dn(o,e),2))[0],yn(e=n[1],o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}}],_n=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,jn=[40,function(t){var n=_n.exec(t);return n?yn(n[2],n[1]||pn,+n[3],n[4]?+n[4]:void 0):void 0}],kn=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Sn=[10,function(t){var n=kn.exec(t);return n?yn(n[2],n[3]||pn,+n[1]):void 0}],On=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Tn=[20,function(t){var n=On.exec(t);return n?yn(n[5],n[3]||n[4]||pn,+n[1],+n[2]):void 0}],Dn=function(t,n){var r=-1!==t.indexOf("safari-extension"),i=-1!==t.indexOf("safari-web-extension");return r||i?[-1!==t.indexOf("@")?t.split("@")[0]:pn,r?"safari-extension:"+n:"safari-web-extension:"+n]:[t,n]};function Rn(t){var n=In(t),r={type:t&&t.name,value:qn(t)};return n.length&&(r.stacktrace={frames:n}),void 0===r.type&&""===r.value&&(r.value="Unrecoverable error caught"),r}function Nn(t){return{exception:{values:[Rn(t)]}}}function In(t){var n=t.stacktrace||t.stack||"",r=function(t){if(t){if("number"==typeof t.framesToPop)return t.framesToPop;if(Mn.test(t.message))return 1}return 0}(t);try{return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=t.sort((function(t,n){return t[0]-n[0]})).map((function(t){return t[1]}));return function(t,n){var i,e,u,a;void 0===n&&(n=0);var c=[];try{for(var s=o(t.split("\n").slice(n)),f=s.next();!f.done;f=s.next()){var h=f.value;try{for(var v=(u=void 0,o(r)),d=v.next();!d.done;d=v.next()){var l=(0,d.value)(h);if(l){c.push(l);break}}}catch(t){u={error:t}}finally{try{d&&!d.done&&(a=v.return)&&a.call(v)}finally{if(u)throw u.error}}}}catch(t){i={error:t}}finally{try{f&&!f.done&&(e=s.return)&&e.call(s)}finally{if(i)throw i.error}}return C(c)}}(Sn,Tn,wn,jn,En)(n,r)}catch(t){}return[]}var Mn=/Minified React error #\d+;/i;function qn(t){var n=t&&t.message;return n?n.error&&"string"==typeof n.error.message?n.error.message:n:"No error message"}function An(n,r,i){var e=Ln(n,r&&r.syntheticException||void 0,i);return Et(e),e.level=t.Severity.Error,r&&r.event_id&&(e.event_id=r.event_id),jt(e)}function Cn(n,r,i,e){void 0===r&&(r=t.Severity.Info);var o=Un(n,i&&i.syntheticException||void 0,e);return o.level=r,i&&i.event_id&&(o.event_id=i.event_id),jt(o)}function Ln(t,n,r,i){var o;if(d(t)&&t.error)return Nn(t.error);if(l(t)||v(t,"DOMException")){var u=t;if("stack"in t)o=Nn(t);else{var a=u.name||(l(u)?"DOMError":"DOMException"),c=u.message?a+": "+u.message:a;xt(o=Un(c,n,r),c)}return"code"in u&&(o.tags=e(e({},o.tags),{"DOMException.code":""+u.code})),o}return h(t)?Nn(t):m(t)||b(t)?(o=function(t,n,r){var i={exception:{values:[{type:b(t)?t.constructor.name:r?"UnhandledRejection":"Error",value:"Non-Error "+(r?"promise rejection":"exception")+" captured with keys: "+Y(t)}]},extra:{__serialized__:G(t)}};if(n){var e=In(n);e.length&&(i.stacktrace={frames:e})}return i}(t,n,i),Et(o,{synthetic:!0}),o):(xt(o=Un(t,n,r),""+t,void 0),Et(o,{synthetic:!0}),o)}function Un(t,n,r){var i={message:t};if(r&&n){var e=In(n);e.length&&(i.stacktrace={frames:e})}return i}var Hn,Fn=s();function Pn(){if(Hn)return Hn;if(nt(Fn.fetch))return Hn=Fn.fetch.bind(Fn);var t=Fn.document,n=Fn.fetch;if(t&&"function"==typeof t.createElement)try{var r=t.createElement("iframe");r.hidden=!0,t.head.appendChild(r);var i=r.contentWindow;i&&i.fetch&&(n=i.fetch),t.head.removeChild(r)}catch(t){0}return Hn=n.bind(Fn)}function Xn(t,n){if("[object Navigator]"===Object.prototype.toString.call(Fn&&Fn.navigator)&&"function"==typeof Fn.navigator.sendBeacon)return Fn.navigator.sendBeacon.bind(Fn.navigator)(t,n);if(tt()){var r=Pn();r(t,{body:n,method:"POST",credentials:"omit",keepalive:!0}).then(null,(function(t){console.error(t)}))}else;}function Bn(t){return"event"===t?"error":t}var Wn=s(),$n=function(){function t(t){var n,r,i,e=this;this.options=t,this.St=Ot(30),this.Ot={},this.Tt={},this.Dt=(n=t.dsn,r=t.Rt,i=t.tunnel,{initDsn:n,metadata:r||{},dsn:D(n),tunnel:i}),this.url=Qt(this.Dt.dsn),this.options.sendClientReports&&Wn.document&&Wn.document.addEventListener("visibilitychange",(function(){"hidden"===Wn.document.visibilityState&&e.Nt()}))}return t.prototype.sendEvent=function(t){return this.It(cn(t,this.Dt),t)},t.prototype.sendSession=function(t){return this.It(function(t,n){var r=an(n),i="aggregates"in t?"sessions":"session";return{body:At(qt(e(e({sent_at:(new Date).toISOString()},r&&{sdk:r}),!!n.tunnel&&{dsn:O(n.dsn)}),[[{type:i},t]])),type:i,url:Yt(n.dsn,n.tunnel)}}(t,this.Dt),t)},t.prototype.close=function(t){return this.St.drain(t)},t.prototype.recordLostEvent=function(t,n){var r;if(this.options.sendClientReports){var i=Bn(n)+":"+t;A.log("Adding outcome: "+i),this.Tt[i]=(null!=(r=this.Tt[i])?r:0)+1}},t.prototype.Nt=function(){if(this.options.sendClientReports){var t=this.Tt;if(this.Tt={},Object.keys(t).length){A.log("Flushing outcomes:\n"+JSON.stringify(t,null,2));var n,r,i,e=Yt(this.Dt.dsn,this.Dt.tunnel),o=Object.keys(t).map((function(n){var r=u(n.split(":"),2),i=r[0];return{reason:r[1],category:i,quantity:t[n]}})),a=(n=o,qt((r=this.Dt.tunnel&&O(this.Dt.dsn))?{dsn:r}:{},[[{type:"client_report"},{timestamp:i||It(),discarded_events:n}]]));try{Xn(e,At(a))}catch(t){A.error(t)}}else A.log("No outcomes to flush")}},t.prototype.Mt=function(t){t.requestType;var n,r=t.response,i=t.headers,e=t.resolve,o=t.reject,u=(n=r.status)>=200&&n<300?"success":429===n?"rate_limit":n>=400&&n<500?"invalid":n>=500?"failed":"unknown";this.qt(i);"success"!==u?o(r):e({status:u})},t.prototype.At=function(t){var n=Bn(t);return this.Ot[n]||this.Ot.all},t.prototype.Ct=function(t){return this.At(t)>new Date(Date.now())},t.prototype.qt=function(t){var n,r,i,e,u=Date.now(),a=t["x-sentry-rate-limits"],c=t["retry-after"];if(a){try{for(var s=o(a.trim().split(",")),f=s.next();!f.done;f=s.next()){var h=f.value.split(":",2),v=parseInt(h[0],10),d=1e3*(isNaN(v)?60:v);try{for(var l=(i=void 0,o(h[1].split(";"))),p=l.next();!p.done;p=l.next()){var y=p.value;this.Ot[y||"all"]=new Date(u+d)}}catch(t){i={error:t}}finally{try{p&&!p.done&&(e=l.return)&&e.call(l)}finally{if(i)throw i.error}}}}catch(t){n={error:t}}finally{try{f&&!f.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}return!0}return!!c&&(this.Ot.all=new Date(u+function(t,n){void 0===n&&(n=Date.now());var r=parseInt(""+t,10);if(!isNaN(r))return 1e3*r;var i=Date.parse(""+t);return isNaN(i)?6e4:i-n}(c,u)),!0)},t}(),Jn=function(t){function n(n,r){void 0===r&&(r=Pn());var i=t.call(this,n)||this;return i.Lt=r,i}return r(n,t),n.prototype.It=function(t,n){var r=this;if(this.Ct(t.type))return this.recordLostEvent("ratelimit_backoff",t.type),Promise.reject({event:n,type:t.type,reason:"Transport for "+t.type+" requests locked till "+this.At(t.type)+" due to too many requests.",status:429});var i={body:t.body,method:"POST",referrerPolicy:rt()?"origin":""};return void 0!==this.options.fetchParameters&&Object.assign(i,this.options.fetchParameters),void 0!==this.options.headers&&(i.headers=this.options.headers),this.St.add((function(){return new St((function(n,e){r.Lt(t.url,i).then((function(i){var o={"x-sentry-rate-limits":i.headers.get("X-Sentry-Rate-Limits"),"retry-after":i.headers.get("Retry-After")};r.Mt({requestType:t.type,response:i,headers:o,resolve:n,reject:e})})).catch(e)}))})).then(void 0,(function(n){throw n instanceof k?r.recordLostEvent("queue_overflow",t.type):r.recordLostEvent("network_error",t.type),n}))},n}($n),zn=function(t){function n(){return null!==t&&t.apply(this,arguments)||this}return r(n,t),n.prototype.It=function(t,n){var r=this;return this.Ct(t.type)?(this.recordLostEvent("ratelimit_backoff",t.type),Promise.reject({event:n,type:t.type,reason:"Transport for "+t.type+" requests locked till "+this.At(t.type)+" due to too many requests.",status:429})):this.St.add((function(){return new St((function(n,i){var e=new XMLHttpRequest;for(var o in e.onreadystatechange=function(){if(4===e.readyState){var o={"x-sentry-rate-limits":e.getResponseHeader("X-Sentry-Rate-Limits"),"retry-after":e.getResponseHeader("Retry-After")};r.Mt({requestType:t.type,response:e,headers:o,resolve:n,reject:i})}},e.open("POST",t.url),r.options.headers)Object.prototype.hasOwnProperty.call(r.options.headers,o)&&e.setRequestHeader(o,r.options.headers[o]);e.send(t.body)}))})).then(void 0,(function(n){throw n instanceof k?r.recordLostEvent("queue_overflow",t.type):r.recordLostEvent("network_error",t.type),n}))},n}($n),Gn=Object.freeze({__proto__:null,BaseTransport:$n,FetchTransport:Jn,XHRTransport:zn}),Kn=function(n){function i(){return null!==n&&n.apply(this,arguments)||this}return r(i,n),i.prototype.eventFromException=function(t,n){return An(t,n,this.Y.attachStacktrace)},i.prototype.eventFromMessage=function(n,r,i){return void 0===r&&(r=t.Severity.Info),Cn(n,r,i,this.Y.attachStacktrace)},i.prototype.lt=function(){if(!this.Y.dsn)return n.prototype.lt.call(this);var t=e(e({},this.Y.transportOptions),{dsn:this.Y.dsn,tunnel:this.Y.tunnel,sendClientReports:this.Y.sendClientReports,Rt:this.Y.Rt});return this.Y.transport?new this.Y.transport(t):tt()?new Jn(t):new zn(t)},i}(un),Vn=s(),Qn=0;function Yn(){return Qn>0}function Zn(){Qn+=1,setTimeout((function(){Qn-=1}))}function tr(t,n,r){if(void 0===n&&(n={}),"function"!=typeof t)return t;try{var i=t.__sentry_wrapped__;if(i)return i;if($(t))return t}catch(n){return t}var sentryWrapped=function(){var i=Array.prototype.slice.call(arguments);try{r&&"function"==typeof r&&r.apply(this,arguments);var o=i.map((function(t){return tr(t,n)}));return t.apply(this,o)}catch(t){throw Zn(),zt((function(r){r.addEventProcessor((function(t){return n.mechanism&&(xt(t,void 0,void 0),Et(t,n.mechanism)),t.extra=e(e({},t.extra),{arguments:i}),t})),captureException(t)})),t}};try{for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(sentryWrapped[o]=t[o])}catch(t){}W(sentryWrapped,t),B(t,"__sentry_wrapped__",sentryWrapped);try{Object.getOwnPropertyDescriptor(sentryWrapped,"name").configurable&&Object.defineProperty(sentryWrapped,"name",{get:function(){return t.name}})}catch(t){}return sentryWrapped}function nr(t){if(void 0===t&&(t={}),Vn.document&&t.eventId&&t.dsn){var n=Vn.document.createElement("script");n.async=!0,n.src=function(t,n){var r=D(t),i=Gt(r)+"embed/error-page/",e="dsn="+O(r);for(var o in n)if("dsn"!==o)if("user"===o){if(!n.user)continue;n.user.name&&(e+="&name="+encodeURIComponent(n.user.name)),n.user.email&&(e+="&email="+encodeURIComponent(n.user.email))}else e+="&"+encodeURIComponent(o)+"="+encodeURIComponent(n[o]);return i+"?"+e}(t.dsn,t),t.onLoad&&(n.onload=t.onLoad);var r=Vn.document.head||Vn.document.body;r&&r.appendChild(n)}}var rr=function(){function t(n){this.name=t.id,this.Ut={onerror:ir,onunhandledrejection:er},this.Y=e({onerror:!0,onunhandledrejection:!0},n)}return t.prototype.setupOnce=function(){Error.stackTraceLimit=50;var t=this.Y;for(var n in t){var r=this.Ut[n];r&&t[n]&&(ur(n),r(),this.Ut[n]=void 0)}},t.id="GlobalHandlers",t}();function ir(){ct("error",(function(n){var r=u(cr(),2),i=r[0],e=r[1];if(i.getIntegration(rr)){var o=n.msg,a=n.url,c=n.line,s=n.column,f=n.error;if(!(Yn()||f&&f.__sentry_own_request__)){var h=void 0===f&&p(o)?function(t,n,r,i){var e=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,o=d(t)?t.message:t,u="Error",a=o.match(e);a&&(u=a[1],o=a[2]);return or({exception:{values:[{type:u,value:o}]}},n,r,i)}(o,a,c,s):or(Ln(f||o,void 0,e,!1),a,c,s);h.level=t.Severity.Error,ar(i,f,h,"onerror")}}}))}function er(){ct("unhandledrejection",(function(n){var r=u(cr(),2),i=r[0],e=r[1];if(i.getIntegration(rr)){var o=n;try{"reason"in n?o=n.reason:"detail"in n&&"reason"in n.detail&&(o=n.detail.reason)}catch(t){}if(Yn()||o&&o.__sentry_own_request__)return!0;var a=y(o)?{exception:{values:[{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(o)}]}}:Ln(o,void 0,e,!0);a.level=t.Severity.Error,ar(i,o,a,"onunhandledrejection")}}))}function or(t,n,r,i){var e=t.exception=t.exception||{},o=e.values=e.values||[],u=o[0]=o[0]||{},a=u.stacktrace=u.stacktrace||{},c=a.frames=a.frames||[],f=isNaN(parseInt(i,10))?void 0:i,h=isNaN(parseInt(r,10))?void 0:r,v=p(n)&&n.length>0?n:function(){var t=s();try{return t.document.location.href}catch(t){return""}}();return 0===c.length&&c.push({colno:f,filename:v,function:"?",in_app:!0,lineno:h}),t}function ur(t){0}function ar(t,n,r,i){Et(r,{handled:!1,type:i}),t.captureEvent(r,{originalException:n})}function cr(){var t=Bt(),n=t.getClient();return[t,n&&n.getOptions().attachStacktrace]}var sr=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],fr=function(){function t(n){this.name=t.id,this.Y=e({XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0},n)}return t.prototype.setupOnce=function(){var t=s();this.Y.setTimeout&&X(t,"setTimeout",hr),this.Y.setInterval&&X(t,"setInterval",hr),this.Y.requestAnimationFrame&&X(t,"requestAnimationFrame",vr),this.Y.XMLHttpRequest&&"XMLHttpRequest"in t&&X(XMLHttpRequest.prototype,"send",dr);var n=this.Y.eventTarget;n&&(Array.isArray(n)?n:sr).forEach(lr)},t.id="TryCatch",t}();function hr(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n[0];return n[0]=tr(i,{mechanism:{data:{function:U(t)},handled:!0,type:"instrument"}}),t.apply(this,n)}}function vr(t){return function(n){return t.call(this,tr(n,{mechanism:{data:{function:"requestAnimationFrame",handler:U(t)},handled:!0,type:"instrument"}}))}}function dr(t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=this,e=["onload","onerror","onprogress","onreadystatechange"];return e.forEach((function(t){t in i&&"function"==typeof i[t]&&X(i,t,(function(n){var r={mechanism:{data:{function:t,handler:U(n)},handled:!0,type:"instrument"}},i=$(n);return i&&(r.mechanism.data.handler=U(i)),tr(n,r)}))})),t.apply(this,n)}}function lr(t){var n=s(),r=n[t]&&n[t].prototype;r&&r.hasOwnProperty&&r.hasOwnProperty("addEventListener")&&(X(r,"addEventListener",(function(n){return function(r,i,e){try{"function"==typeof i.handleEvent&&(i.handleEvent=tr(i.handleEvent.bind(i),{mechanism:{data:{function:"handleEvent",handler:U(i),target:t},handled:!0,type:"instrument"}}))}catch(t){}return n.call(this,r,tr(i,{mechanism:{data:{function:"addEventListener",handler:U(i),target:t},handled:!0,type:"instrument"}}),e)}})),X(r,"removeEventListener",(function(t){return function(n,r,i){var e=r;try{var o=e&&e.__sentry_wrapped__;o&&t.call(this,n,o,i)}catch(t){}return t.call(this,n,e,i)}})))}var pr=function(){function t(n){this.name=t.id,this.Y=e({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},n)}return t.prototype.addSentryBreadcrumb=function(t){this.Y.sentry&&Bt().addBreadcrumb({category:"sentry."+("transaction"===t.type?"transaction":"event"),event_id:t.event_id,level:t.level,message:gt(t)},{event:t})},t.prototype.setupOnce=function(){this.Y.console&&ct("console",yr),this.Y.dom&&ct("dom",function(t){function n(n){var r,i="object"==typeof t?t.serializeAttribute:void 0;"string"==typeof i&&(i=[i]);try{r=n.event.target?E(n.event.target,i):E(n.event,i)}catch(t){r="<unknown>"}0!==r.length&&Bt().addBreadcrumb({category:"ui."+n.name,message:r},{event:n.event,name:n.name,global:n.global})}return n}(this.Y.dom)),this.Y.xhr&&ct("xhr",mr),this.Y.fetch&&ct("fetch",br),this.Y.history&&ct("history",wr)},t.id="Breadcrumbs",t}();function yr(t){var n={category:"console",data:{arguments:t.args,logger:"console"},level:Tt(t.level),message:F(t.args," ")};if("assert"===t.level){if(!1!==t.args[0])return;n.message="Assertion failed: "+(F(t.args.slice(1)," ")||"console.assert"),n.data.arguments=t.args.slice(1)}Bt().addBreadcrumb(n,{input:t.args,level:t.level})}function mr(t){if(t.endTimestamp){if(t.xhr.__sentry_own_request__)return;var n=t.xhr.__sentry_xhr__||{},r=n.method,i=n.url,e=n.status_code,o=n.body;Bt().addBreadcrumb({category:"xhr",data:{method:r,url:i,status_code:e},type:"http"},{xhr:t.xhr,input:o})}else;}function br(n){n.endTimestamp&&(n.fetchData.url.match(/sentry_key/)&&"POST"===n.fetchData.method||(n.error?Bt().addBreadcrumb({category:"fetch",data:n.fetchData,level:t.Severity.Error,type:"http"},{data:n.error,input:n.args}):Bt().addBreadcrumb({category:"fetch",data:e(e({},n.fetchData),{status_code:n.response.status}),type:"http"},{input:n.args,response:n.response})))}function wr(t){var n=s(),r=t.from,i=t.to,e=bt(n.location.href),o=bt(r),u=bt(i);o.path||(o=e),e.protocol===u.protocol&&e.host===u.host&&(i=u.relative),e.protocol===o.protocol&&e.host===o.host&&(r=o.relative),Bt().addBreadcrumb({category:"navigation",data:{from:r,to:i}})}var gr=function(){function t(n){void 0===n&&(n={}),this.name=t.id,this.Ht=n.key||"cause",this.Ft=n.limit||5}return t.prototype.setupOnce=function(){Ut((function(n,r){var i=Bt().getIntegration(t);return i?function(t,n,r,i){if(!(r.exception&&r.exception.values&&i&&x(i.originalException,Error)))return r;var e=xr(n,i.originalException,t);return r.exception.values=a(e,r.exception.values),r}(i.Ht,i.Ft,n,r):n}))},t.id="LinkedErrors",t}();function xr(t,n,r,i){if(void 0===i&&(i=[]),!x(n[r],Error)||i.length+1>=t)return i;var e=Rn(n[r]);return xr(t,n[r],r,a([e],i))}var Er=s(),_r=function(){function t(){this.name=t.id}return t.prototype.setupOnce=function(){Ut((function(n){if(Bt().getIntegration(t)){if(!Er.navigator&&!Er.location&&!Er.document)return n;var r=n.request&&n.request.url||Er.location&&Er.location.href,i=(Er.document||{}).referrer,o=(Er.navigator||{}).userAgent,u=e(e(e({},n.request&&n.request.headers),i&&{Referer:i}),o&&{"User-Agent":o}),a=e(e({},r&&{url:r}),{headers:u});return e(e({},n),{request:a})}return n}))},t.id="UserAgent",t}(),jr=function(){function t(){this.name=t.id}return t.prototype.setupOnce=function(n,r){n((function(n){var i=r().getIntegration(t);if(i){try{if(function(t,n){if(!n)return!1;if(function(t,n){var r=t.message,i=n.message;if(!r&&!i)return!1;if(r&&!i||!r&&i)return!1;if(r!==i)return!1;if(!Sr(t,n))return!1;if(!kr(t,n))return!1;return!0}(t,n))return!0;if(function(t,n){var r=Or(n),i=Or(t);if(!r||!i)return!1;if(r.type!==i.type||r.value!==i.value)return!1;if(!Sr(t,n))return!1;if(!kr(t,n))return!1;return!0}(t,n))return!0;return!1}(n,i.Pt))return A.warn("Event dropped due to being a duplicate of previously captured event."),null}catch(t){return i.Pt=n}return i.Pt=n}return n}))},t.id="Dedupe",t}();function kr(t,n){var r=Tr(t),i=Tr(n);if(!r&&!i)return!0;if(r&&!i||!r&&i)return!1;if(r=r,(i=i).length!==r.length)return!1;for(var e=0;e<i.length;e++){var o=i[e],u=r[e];if(o.filename!==u.filename||o.lineno!==u.lineno||o.colno!==u.colno||o.function!==u.function)return!1}return!0}function Sr(t,n){var r=t.fingerprint,i=n.fingerprint;if(!r&&!i)return!0;if(r&&!i||!r&&i)return!1;r=r,i=i;try{return!(r.join("")!==i.join(""))}catch(t){return!1}}function Or(t){return t.exception&&t.exception.values&&t.exception.values[0]}function Tr(t){var n=t.exception;if(n)try{return n.values[0].stacktrace.frames}catch(t){return}else if(t.stacktrace)return t.stacktrace.frames}var Dr=Object.freeze({__proto__:null,GlobalHandlers:rr,TryCatch:fr,Breadcrumbs:pr,LinkedErrors:gr,UserAgent:_r,Dedupe:jr}),Rr=function(t){function n(n){void 0===n&&(n={});return n.Rt=n.Rt||{},n.Rt.sdk=n.Rt.sdk||{name:"sentry.javascript.browser",packages:[{name:"npm:@sentry/browser",version:fn}],version:fn},t.call(this,Kn,n)||this}return r(n,t),n.prototype.showReportDialog=function(t){void 0===t&&(t={}),s().document&&(this.it()?nr(e(e({},t),{dsn:t.dsn||this.getDsn()})):A.error("Trying to call showReportDialog with Sentry Client disabled"))},n.prototype.at=function(n,r,i){return n.platform=n.platform||"javascript",t.prototype.at.call(this,n,r,i)},n.prototype.ht=function(n){var r=this.getIntegration(pr);r&&r.addSentryBreadcrumb(n),t.prototype.ht.call(this,n)},n}(en),Nr=[new dn,new hn,new fr,new pr,new rr,new gr,new jr,new _r];function Ir(t){t.startSession({ignoreDuration:!0}),t.captureSession()}var Mr={},qr=s();qr.Sentry&&qr.Sentry.Integrations&&(Mr=qr.Sentry.Integrations);var Ar=e(e(e({},Mr),ln),Dr);return t.BrowserClient=Rr,t.Hub=Ft,t.Integrations=Ar,t.SDK_NAME="sentry.javascript.browser",t.SDK_VERSION=fn,t.Scope=Ct,t.Session=Ht,t.Transports=Gn,t.addBreadcrumb=function(t){Jt("addBreadcrumb",t)},t.addGlobalEventProcessor=Ut,t.captureEvent=function(t){return Jt("captureEvent",t)},t.captureException=captureException,t.captureMessage=function(t,n){var r;try{throw new Error(t)}catch(t){r=t}return Jt("captureMessage",t,"string"==typeof n?n:void 0,e({originalException:t,syntheticException:r},"string"!=typeof n?{captureContext:n}:void 0))},t.close=function(t){var n=Bt().getClient();return n?n.close(t):jt(!1)},t.configureScope=function(t){Jt("configureScope",t)},t.defaultIntegrations=Nr,t.eventFromException=An,t.eventFromMessage=Cn,t.flush=function(t){var n=Bt().getClient();return n?n.flush(t):jt(!1)},t.forceLoad=function(){},t.getCurrentHub=Bt,t.getHubFromCarrier=Wt,t.init=function(t){if(void 0===t&&(t={}),void 0===t.defaultIntegrations&&(t.defaultIntegrations=Nr),void 0===t.release){var n=s();n.SENTRY_RELEASE&&n.SENTRY_RELEASE.id&&(t.release=n.SENTRY_RELEASE.id)}void 0===t.autoSessionTracking&&(t.autoSessionTracking=!0),void 0===t.sendClientReports&&(t.sendClientReports=!0),function(t,n){!0===n.debug&&A.enable();var r=Bt(),i=r.getScope();i&&i.update(n.initialScope);var e=new t(n);r.bindClient(e)}(Rr,t),t.autoSessionTracking&&function(){if(void 0===s().document)return void 0;var t=Bt();if(!t.captureSession)return;Ir(t),ct("history",(function(t){var n=t.from,r=t.to;void 0!==n&&n!==r&&Ir(Bt())}))}()},t.injectReportDialog=nr,t.lastEventId=function(){return Bt().lastEventId()},t.makeMain=Xt,t.onLoad=function(t){t()},t.setContext=function(t,n){Jt("setContext",t,n)},t.setExtra=function(t,n){Jt("setExtra",t,n)},t.setExtras=function(t){Jt("setExtras",t)},t.setTag=function(t,n){Jt("setTag",t,n)},t.setTags=function(t){Jt("setTags",t)},t.setUser=function(t){Jt("setUser",t)},t.showReportDialog=function(t){void 0===t&&(t={});var n=Bt(),r=n.getScope();r&&(t.user=e(e({},r.getUser()),t.user)),t.eventId||(t.eventId=n.lastEventId());var i=n.getClient();i&&i.showReportDialog(t)},t.startTransaction=function(t,n){return Jt("startTransaction",e({},t),n)},t.withScope=zt,t.wrap=function(t){return tr(t)()},t}({});


;

// source: plugin/errortracking/js/errortracking.js
$(function(){function ErrorTrackingViewModel(parameters){var self=this;self.settings=parameters[0];self.loginState=parameters[1];var notification=undefined;var performCheck=function(){if(!self.loginState.isAdmin())return;if(self.settings.settings.plugins.errortracking.enabled())return;var releaseChannel=self.settings.settings.plugins.softwareupdate.octoprint_release_channel();if(releaseChannel==="rc/maintenance"||releaseChannel==="rc/devel"){if(notification!==undefined)return;try{var ignoredString=localStorage["plugin.errortracking.notification_ignored"];var ignored=false;if(ignoredString){ignored=JSON.parse(ignoredString);}
if(ignored)return;}catch(ex){log.error("Error while reading plugin.errortracking.notification_ignored from local storage");}
notification=new PNotify({title:gettext("Enable error reporting?"),text:gettext("<p>It looks like you are tracking an OctoPrint RC release channel. It "+"would be great if you would enable error reporting so that any kind of errors that occur "+"with an RC can be looked into more easily. Thank you!</p>"+"<p><small>You can find more information on error reporting "+"under Settings > Error Tracking</small></p>"),hide:false,confirm:{confirm:true,buttons:[{text:gettext("Ignore"),click:function(){notification.remove();notification=undefined;new PNotify({text:gettext('You can still enable error tracking via "Settings" > "Error Tracking"')});if(Modernizr.localstorage){localStorage["plugin.errortracking.notification_ignored"]=JSON.stringify(true);}}},{text:gettext("Enable"),addClass:"btn-primary",click:function(){self.settings.saveData({plugins:{errortracking:{enabled:true}}}).done(function(){notification.remove();notification=undefined;location.reload(true);});}}]},buttons:{closer:false,sticker:false}});}else if(notification!==undefined){notification.remove();notification=undefined;}};var subbed=false;self.onStartup=self.onUserLoggedIn=self.onUserLoggedOut=function(){performCheck();if(self.settings&&self.settings.settings&&self.settings.settings.plugins&&self.settings.settings.plugins.softwareupdate&&!subbed){subbed=true;self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(performCheck);}};}
OCTOPRINT_VIEWMODELS.push({construct:ErrorTrackingViewModel,dependencies:["settingsViewModel","loginStateViewModel"]});});
;

// source: plugin/eventmanager/js/events.js
$(function(){function eventManagerViewModel(parameters){var self=this;self.settingsViewModel=parameters[0];self.selectedCommand=ko.observable();self.eventDetails=function(data){if(data===false){return{event:ko.observable(""),command:ko.observable(""),name:ko.observable(""),type:ko.observable(""),enabled:ko.observable(true),debug:ko.observable(false)};}else{if(!data.hasOwnProperty("enabled")){data["enabled"]=ko.observable(true);}
if(!data.hasOwnProperty("debug")){data["debug"]=ko.observable(false);}
return data;}};self.addEvent=function(){self.selectedCommand(self.eventDetails(false));self.settingsViewModel.settings.plugins.eventmanager.subscriptions.push(self.selectedCommand());$("#EventManagerEditor").modal("show");};self.editEvent=function(data){self.selectedCommand(self.eventDetails(data));$("#EventManagerEditor").modal("show");};self.removeEvent=function(data){self.settingsViewModel.settings.plugins.eventmanager.subscriptions.remove(data);};}
OCTOPRINT_VIEWMODELS.push({construct:eventManagerViewModel,dependencies:["settingsViewModel"],elements:["#settings_plugin_eventmanager"]});});
;

// source: plugin/file_check/js/file_check.js
$(function(){function FileCheckViewModel(parameters){const self=this;self.loginState=parameters[0];self.access=parameters[1];self.settingsViewModel=parameters[2];self.printerState=parameters[3];self.filesViewModel=parameters[4];self.fullCheckAvailable=ko.observable(false);self.checkResult=ko.observable();self.checkRunning=ko.observable(false);self.lastCheckTimestamp=ko.observable();self.lastCheckCurrent=ko.observable();self.issueNotification=undefined;const ISSUES={travel_speed:{title:gettext("Travel Speed Placeholder"),message:gettext("Your file still contains a place holder <code>{travel_speed}</code>. "+"This is a common issue when using old start/stop GCODE code snippets in current versions of "+"Cura, as the placeholder name switched to <code>{speed_travel}</code> at some point and "+"no longer gets replaced in current versions. You need to fix this in your slicer and reslice "+"your file, do not print it like it is as it will cause issues!")},leaked_api_key:{title:gettext("Leaked API Key"),message:gettext("Your file contains an API key that is not supposed to be there. "+"This is caused by a bug in your slicer, and known to happen with PrusaSlicer (<= 2.1.1), "+"BambuStudio (<= 1.8.4) and OrcaSlicer (<= 1.9.0). "+"Do not share this file with anyone, update your slicer to a patched version immediately, "+"and reslice your file. Also consider changing your API key in OctoPrint, as it might have been leaked by your slicer "+"to third parties through any GCODE files shared previously."),severity:"error"}};self.checksArray=ko.pureComputed(()=>{return Object.keys(ISSUES).map((key)=>{return{key:key,title:ISSUES[key].title,message:ISSUES[key].message,enabled:ko.pureComputed({read:()=>{return!self.settingsViewModel.settings.plugins.file_check.ignored_checks().includes(key);},write:(value)=>{if(value){self.settingsViewModel.settings.plugins.file_check.ignored_checks.remove(key);}else{self.settingsViewModel.settings.plugins.file_check.ignored_checks.push(key);}}})};});});self.lastCheckTimestampText=ko.pureComputed(()=>{return formatDate(self.lastCheckTimestamp(),{placeholder:gettext("unknown")});});self.lastCheckStateText=ko.pureComputed(()=>{if(self.lastCheckCurrent()){return gettext("Up to date");}else{return gettext("Outdated");}});self.lastCheckStateClass=ko.pureComputed(()=>{if(self.lastCheckCurrent()){return"text-success";}else{return"text-error";}});self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_FILE_CHECK_RUN))
return $.Deferred().reject();return OctoPrint.plugins.file_check.get().done(self.fromResponse);};self.fromResponse=function(response){self.fullCheckAvailable(response.native_grep);self.checkResult(response.check_result);self.lastCheckTimestamp(response.last_full_check.timestamp);self.lastCheckCurrent(response.last_full_check.current);};self.checkAll=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_FILE_CHECK_RUN))
return;showConfirmationDialog({title:gettext("Run File Check on all files?"),message:gettext("This will perform a check of all of your uploaded files for known issues. "+"Depending on the amount of files this could take several minutes. "+"It should not be done while a print is running."),onproceed:()=>{self.checkRunning(true);OctoPrint.plugins.file_check.checkAll();}});};self.hasCheckResult=function(storage,file){if(!storage)return null;if(_.isPlainObject(storage)){file=storage.path;storage=storage.origin;}else if(!file){file=storage;storage="local";}
const key=`${storage}:${file}`;return(self.checkResult()&&self.checkResult()[key]&&self.loginState.hasPermission(self.access.permissions.PLUGIN_FILE_CHECK_RUN));};self.showCheckResult=function(storage,file){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_FILE_CHECK_RUN))
return;if(_.isPlainObject(storage)){file=storage.path;storage=storage.origin;}else if(!file){file=storage;storage="local";}
const key=`${storage}:${file}`;const data=self.checkResult()[key];if(!data)return;const getMessage=(issue)=>{return $("<p/>",{html:ISSUES[issue].message});};const getReadMore=(issue)=>{return $("<p/>").append($("<a/>",{href:"https://faq.octoprint.org/file-check-"+
issue.replaceAll("_","-"),target:"_blank",rel:"noreferrer noopener",text:gettext("Read more...")}));};const title=gettext("File Check detected the following issues:");let message;if(data.length===1){const issue=data[0];message=$("<div/>").append(getMessage(issue)).append(getReadMore(issue));}else{message=$("<ul/>").append(data.map((issue)=>$("<li/>").append(getMessage(issue)).append(getReadMore(issue))));}
showMessageDialog({title:title,message:message});};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="file_check")return;if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_FILE_CHECK_RUN))
return;switch(data["action"]){case"notify":{self._handleNotification(data);break;}
case"check_update":{self._handleCheckUpdate(data);break;}}};self._handleNotification=function(data){let severity="warning";const result=[];for(const t of data["types"]){if(!ISSUES[t])continue;const spec=ISSUES[t];const message=spec["message"];if(spec["severity"]==="error"){severity="error";}
const faq="<a href='https://faq.octoprint.org/file-check-"+
t.replaceAll("_","-")+"' target='_blank' rel='noreferrer noopener'>"+
gettext("Read more...")+"</a>";result.push("<p>"+message+"</p><p>"+faq+"</p>");}
if(result.length===0){return;}
let text;if(result.length===1){text=result[0];}else{text="<ul>"+result.map((r)=>`<li>${r}</li>`).join("")+"</ul>";}
self.issueNotification&&self.issueNotification.remove();self.issueNotification=new PNotify({title:_.sprintf(gettext("File Check detected issues with %(path)s!"),data),text:text,hide:false,type:severity});self._handleCheckUpdate();};self._handleCheckUpdate=function(data){self.requestData().done(()=>{self.checkRunning(false);});};self.onStartup=function(){self.filesViewModel.fileCheckViewModel=self;self.printerState.fileCheckViewModel=self;const regex=/<div class="uploaded">/;const template="<div class='filecheck_result' data-bind='visible: $root.fileCheckViewModel.hasCheckResult($data) && $root.loginState.hasPermission($root.access.permissions.PLUGIN_FILE_CHECK_RUN)'><small>"+"<a href='javascript:void(0)' class='text-error' style='text-decoration: underline' data-bind='click: function() { $root.fileCheckViewModel.showCheckResult($data) }'>"+"<i class='fas fa-exclamation-circle'></i> "+
gettext("File Check detected issues with this file!")+"</a></small></div>";$("#files_template_machinecode").text((idx,text)=>{const position=text.search(regex);return text.substring(0,position)+template+text.substring(position);});$("#state .accordion-inner hr:nth-of-type(2)").before($("<small/>",{attr:{"data-bind":"visible: $root.fileCheckViewModel.hasCheckResult($root.filepath()) && $root.loginState.hasPermission($root.access.permissions.PLUGIN_FILE_CHECK_RUN)"}}).append($("<a/>",{href:"javascript:void(0);",class:"text-error",style:"text-decoration: underline",attr:{"data-bind":"click: function() { $root.fileCheckViewModel.showCheckResult($root.filepath()) }"}}).append($("<i/>",{class:"fas fa-exclamation-circle"})).append(" "+
gettext("File Check detected issues with this file!"))).after($("<br/>")));};self.onAfterBinding=function(){self.settingsViewModel.settings.plugins.file_check.ignored_checks.subscribe(()=>{self.requestData();});};self.onUserLoggedIn=self.onUserLoggedOut=function(){self.requestData();};}
OCTOPRINT_VIEWMODELS.push({construct:FileCheckViewModel,dependencies:["loginStateViewModel","accessViewModel","settingsViewModel","printerStateViewModel","filesViewModel"],elements:["#wizard_plugin_file_check","#settings_plugin_file_check"]});});
;

// source: plugin/firmware_check/js/firmware_check.js
$(function(){function FirmwareCheckViewModel(parameters){var self=this;self.loginState=parameters[0];self.printerState=parameters[1];self.access=parameters[2];self.settings=parameters[3];self.warnings=ko.observableArray([]);self.infos=ko.observableArray([]);self.disablingInfos=ko.observable(false);self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_FIRMWARE_CHECK_DISPLAY)){self.warnings([]);return;}
OctoPrint.plugins.firmware_check.get().done(self.fromResponse).fail(function(){self.warnings([]);});};self.fromResponse=function(data){var warnings=[];var infos=[];_.each(data,function(data,warning_type){var item={type:warning_type,message:gettext(data.message),severity:data.severity,url:data.url};if(data.severity==="info"){if(!self.settings.settings.plugins.firmware_check.ignore_infos()){infos.push(item);}}else{warnings.push(item);}});self.warnings(warnings);self.infos(infos);};self.onStartup=function(){self.requestData();};var subbed=false;self.onStartup=self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){if(self.settings&&self.settings.settings&&self.settings.settings.plugins&&self.settings.settings.plugins.firmware_check&&!subbed){subbed=true;self.settings.settings.plugins.firmware_check.ignore_infos.subscribe(function(){self.requestData();});}
self.requestData();};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="firmware_check")return;if(!data.hasOwnProperty("type"))return;if(data.type==="update"){self.requestData();}};self.cssClass=function(data){if(data.severity){return"firmware_check_warning_"+data.severity;}else{return undefined;}};self.warningText=function(data){switch(data.type){case"firmware-unsafe":return gettext("Critical Warning: Firmware Unsafe");case"firmware-broken":return gettext("Warning: Firmware Broken");case"firmware-development":return gettext("Info: Firmware Development Build");default:return data.severity==="critical"?gettext("Critical Warning"):data.severity==="warning"?gettext("Warning"):gettext("Info");}};self.disableInfos=function(){if(self.loginState.hasPermission(self.access.permissions.SETTINGS)){self.disablingInfos(true);OctoPrint.settings.savePluginSettings("firmware_check",{ignore_infos:true}).always(function(){self.disablingInfos(false);});}};}
OCTOPRINT_VIEWMODELS.push({construct:FirmwareCheckViewModel,dependencies:["loginStateViewModel","printerStateViewModel","accessViewModel","settingsViewModel"],elements:["#sidebar_plugin_firmware_check_warning_wrapper","#sidebar_plugin_firmware_check_info_wrapper"]});});
;

// source: plugin/gcodeviewer/js/gcodeviewer.js
$(function(){function GcodeViewModel(parameters){var self=this;self.loginState=parameters[0];self.settings=parameters[1];self.access=parameters[2];self.sizeThresholdStr=undefined;self.mobileSizeThresholdStr=undefined;self.compressionSizeThresholdStr=undefined;self.ui_progress_busy=ko.observable(false);self.ui_progress_percentage=ko.observable();self.ui_progress_type=ko.observable();self.ui_progress_text=ko.pureComputed(function(){var text="";switch(self.ui_progress_type()){case"parsing":{text=gettext("Parsing...")+" ("+
self.ui_progress_percentage().toFixed(0)+"%)";break;}
case"analyzing":{text=gettext("Analyzing...")+" ("+
self.ui_progress_percentage().toFixed(0)+"%)";break;}
case"done":{text=gettext("Ready!");break;}}
return text;});self.ui_modelInfo=ko.observable("");self.ui_layerInfo=ko.observable("");self.tabActive=false;self.enableReload=ko.observable(false);self.waitForApproval=ko.observable(false);self.selectedFile={path:ko.observable(undefined),date:ko.observable(undefined),size:ko.observable(undefined)};self.needsLoad=false;self.renderer_centerModel=ko.observable(false);self.renderer_centerViewport=ko.observable(false);self.renderer_zoomOnModel=ko.observable(false);self.renderer_showMoves=ko.observable(true);self.renderer_showRetracts=ko.observable(true);self.renderer_showPrinthead=ko.observable(true);self.renderer_showSegmentStarts=ko.observable(false);self.renderer_showDebugArcs=ko.observable(false);self.renderer_chromeArcFix=ko.observable(OctoPrint.coreui.browser.chrome);self.renderer_showBoundingBox=ko.observable(false);self.renderer_showLayerBoundingBox=ko.observable(false);self.renderer_showFullSize=ko.observable(false);self.renderer_extrusionWidthEnabled=ko.observable(false);self.renderer_extrusionWidth=ko.observable(2);self.renderer_showNext=ko.observable(false);self.renderer_showCurrent=ko.observable(false);self.renderer_showPrevious=ko.observable(false);self.renderer_syncProgress=ko.observable(true);self.reader_hideEmptyLayers=ko.observable(true);self.reader_ignoreOutsideBed=ko.observable(true);self.reader_forceCompression=ko.observable(false);self.layerSelectionEnabled=ko.observable(false);self.layerUpEnabled=ko.observable(false);self.layerDownEnabled=ko.observable(false);self.synchronizeOptionsAndReload=function(additionalRendererOptions,additionalReaderOptions){self.synchronizeOptions(additionalRendererOptions,additionalReaderOptions);self.reload();};self.synchronizeOptions=function(additionalRendererOptions,additionalReaderOptions){var renderer={moveModel:self.renderer_centerModel(),centerViewport:self.renderer_centerViewport(),showMoves:self.renderer_showMoves(),showRetracts:self.renderer_showRetracts(),showHead:self.renderer_showPrinthead(),showSegmentStarts:self.renderer_showSegmentStarts(),showDebugArcs:self.renderer_showDebugArcs(),chromeArcFix:self.renderer_chromeArcFix(),showBoundingBox:self.renderer_showBoundingBox(),showLayerBoundingBox:self.renderer_showLayerBoundingBox(),showFullSize:self.renderer_showFullSize(),extrusionWidth:self.renderer_extrusionWidthEnabled()?self.renderer_extrusionWidth():1,showNextLayer:self.renderer_showNext(),showCurrentLayer:self.renderer_showCurrent(),showPreviousLayer:self.renderer_showPrevious(),zoomInOnModel:self.renderer_zoomOnModel(),onInternalOptionChange:self._onInternalRendererOptionChange};if(additionalRendererOptions){_.extend(renderer,additionalRendererOptions);}
var reader={purgeEmptyLayers:self.reader_hideEmptyLayers(),ignoreOutsideBed:self.reader_ignoreOutsideBed(),alwaysCompress:self.settings.settings.plugins.gcodeviewer.alwaysCompress(),compressionSizeThreshold:self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold(),forceCompression:self.reader_forceCompression()};if(additionalReaderOptions){_.extend(reader,additionalReaderOptions);}
GCODE.ui.updateOptions({renderer:renderer,reader:reader});};self.rendererOptionUpdated=function(){self.synchronizeOptions();self._toLocalStorage();};self.readerOptionUpdated=function(){self.synchronizeOptionsAndReload();self._toLocalStorage();};self.renderer_centerModel.subscribe(self.rendererOptionUpdated);self.renderer_centerViewport.subscribe(self.rendererOptionUpdated);self.renderer_zoomOnModel.subscribe(self.rendererOptionUpdated);self.renderer_showMoves.subscribe(self.rendererOptionUpdated);self.renderer_showRetracts.subscribe(self.rendererOptionUpdated);self.renderer_showPrinthead.subscribe(self.rendererOptionUpdated);self.renderer_showSegmentStarts.subscribe(self.rendererOptionUpdated);self.renderer_showDebugArcs.subscribe(self.rendererOptionUpdated);self.renderer_chromeArcFix.subscribe(self.rendererOptionUpdated);self.renderer_showBoundingBox.subscribe(self.rendererOptionUpdated);self.renderer_showLayerBoundingBox.subscribe(self.rendererOptionUpdated);self.renderer_showFullSize.subscribe(self.rendererOptionUpdated);self.renderer_extrusionWidthEnabled.subscribe(self.rendererOptionUpdated);self.renderer_extrusionWidth.subscribe(self.rendererOptionUpdated);self.renderer_showNext.subscribe(self.rendererOptionUpdated);self.renderer_showCurrent.subscribe(self.rendererOptionUpdated);self.renderer_showPrevious.subscribe(self.rendererOptionUpdated);self.reader_hideEmptyLayers.subscribe(self.readerOptionUpdated);self.reader_ignoreOutsideBed.subscribe(self.readerOptionUpdated);self.reader_forceCompression.subscribe(self.readerOptionUpdated);self._printerProfileUpdated=function(){if(!self.enabled)return;var currentProfileData=self.settings.printerProfiles.currentProfileData();if(!currentProfileData)return;var options={reader:{},renderer:{}};var dirty=false;var toolOffsets=self._retrieveToolOffsets(currentProfileData);if(toolOffsets){options.reader.toolOffsets=toolOffsets;dirty=true;}
var bedDimensions=self._retrieveBedDimensions(currentProfileData);if(bedDimensions){options.renderer.bed=bedDimensions;options.reader.bed=bedDimensions;dirty=true;}
if(dirty){GCODE.ui.updateOptions(options);}};self.settings.printerProfiles.currentProfileData.subscribe(function(){self._printerProfileUpdated();if(self.settings.printerProfiles.currentProfileData()){if(self.settings.printerProfiles.currentProfileData().extruder){self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().extruder.offsets.subscribe(self._printerProfileUpdated);}
if(self.settings.printerProfiles.currentProfileData().volume){self.settings.printerProfiles.currentProfileData().volume.width.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().volume.depth.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().volume.formFactor.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().volume.origin.subscribe(self._printerProfileUpdated);}
if(self.settings.printerProfiles.currentProfileData().axes){self.settings.printerProfiles.currentProfileData().axes.x.inverted.subscribe(self._printerProfileUpdated);self.settings.printerProfiles.currentProfileData().axes.y.inverted.subscribe(self._printerProfileUpdated);}}});self.settings.feature_g90InfluencesExtruder.subscribe(function(){GCODE.ui.updateOptions({reader:{g90InfluencesExtruder:self.settings.feature_g90InfluencesExtruder()}});});self._retrieveBedDimensions=function(currentProfileData){if(currentProfileData===undefined){currentProfileData=self.settings.printerProfiles.currentProfileData();}
if(currentProfileData&&currentProfileData.volume&&currentProfileData.volume.formFactor()&&currentProfileData.volume.width()&&currentProfileData.volume.depth()){var x=undefined,y=undefined,r=undefined,circular=false,centeredOrigin=false;var formFactor=currentProfileData.volume.formFactor();if(formFactor==="circular"){r=currentProfileData.volume.width()/2;circular=true;centeredOrigin=true;}else{x=currentProfileData.volume.width();y=currentProfileData.volume.depth();if(currentProfileData.volume.origin){centeredOrigin=currentProfileData.volume.origin()==="center";}}
return{x:x,y:y,r:r,circular:circular,centeredOrigin:centeredOrigin};}else{return undefined;}};self._retrieveToolOffsets=function(currentProfileData){if(currentProfileData==undefined){currentProfileData=self.settings.printerProfiles.currentProfileData();}
if(currentProfileData&&currentProfileData.extruder){var offsets=[];if(currentProfileData.extruder.offsets()&&!currentProfileData.extruder.sharedNozzle()){_.each(currentProfileData.extruder.offsets(),function(offset){offsets.push({x:offset[0],y:offset[1]});});}
return offsets;}else{return undefined;}};self._retrieveAxesConfiguration=function(currentProfileData){if(currentProfileData==undefined){currentProfileData=self.settings.printerProfiles.currentProfileData();}
if(currentProfileData&&currentProfileData.axes){var invertX=false,invertY=false;if(currentProfileData.axes.x){invertX=currentProfileData.axes.x.inverted();}
if(currentProfileData.axes.y){invertY=currentProfileData.axes.y.inverted();}
return{x:invertX,y:invertY};}else{return undefined;}};self.loadedFilepath=undefined;self.loadedFileDate=undefined;self.loadedFileSize=undefined;self.status="idle";self.enabled=false;self.currentlyPrinting=false;self.layerSlider=undefined;self.layerCommandSlider=undefined;self.currentLayer=undefined;self.currentCommand=undefined;self.maxLayer=undefined;self.initialize=function(){self.sizeThresholdStr=sizeObservable(self.settings.settings.plugins.gcodeviewer.sizeThreshold);self.mobileSizeThresholdStr=sizeObservable(self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold);self.compressionSizeThresholdStr=sizeObservable(self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold);var layerSliderElement=$("#gcode_slider_layers");var commandSliderElement=$("#gcode_slider_commands");var containerElement=$("#gcode_canvas");if(!(layerSliderElement.length&&commandSliderElement.length&&containerElement.length)){return;}
self._configureLayerSlider(layerSliderElement);self._configureLayerCommandSlider(commandSliderElement);self._configureContainerElement(containerElement);self.settings.firstRequest.done(function(){var initResult=GCODE.ui.init({container:"#gcode_canvas",onProgress:self._onProgress,onModelLoaded:self._onModelLoaded,onLayerSelected:self._onLayerSelected,onFileLoaded:self._onFileLoaded,bed:self._retrieveBedDimensions(),toolOffsets:self._retrieveToolOffsets(),invertAxes:self._retrieveAxesConfiguration(),bedZ:self.settings.settings.gcodeAnalysis.bedZ()});if(!initResult){log.info("Could not initialize GCODE viewer component");return;}
self.settings.settings.plugins.gcodeviewer.alwaysCompress.subscribe(self.readerOptionUpdated);self.settings.settings.plugins.gcodeviewer.compressionSizeThreshold.subscribe(self.readerOptionUpdated);self.synchronizeOptions();self.enabled=true;self._fromLocalStorage();});};self.reset=function(){self.enableReload(false);self.loadedFilepath=undefined;self.loadedFileDate=undefined;self.loadedFileSize=undefined;self.clear();};self.resetViewport=function(){GCODE.ui.resetViewport();};self.resetOptions=function(){self.renderer_centerModel(false);self.renderer_centerViewport(false);self.renderer_zoomOnModel(false);self.renderer_showMoves(true);self.renderer_showRetracts(true);self.renderer_showPrinthead(true);self.renderer_showSegmentStarts(false);self.renderer_showDebugArcs(false);self.renderer_chromeArcFix(OctoPrint.coreui.browser.chrome);self.renderer_showBoundingBox(false);self.renderer_showLayerBoundingBox(false);self.renderer_showFullSize(false);self.renderer_extrusionWidthEnabled(false);self.renderer_extrusionWidth(2);self.renderer_showNext(false);self.renderer_showCurrent(false);self.renderer_showPrevious(false);self.renderer_syncProgress(true);self.reader_hideEmptyLayers(true);self.reader_ignoreOutsideBed(true);self.reader_forceCompression(false);};self.clear=function(){GCODE.ui.clear();};self._configureLayerSlider=function(layerSliderElement){self.layerSlider=layerSliderElement.slider({id:"gcode_layer_slider",reversed:true,selection:"after",orientation:"vertical",min:0,max:1,step:1,value:0,enabled:false,formatter:function(value){return("Layer #"+
(value+1)+" (Z = "+
GCODE.renderer.getZ(value)+")");}}).on("slide",self.changeLayer);};self._configureLayerCommandSlider=function(commandSliderElement){self.layerCommandSlider=commandSliderElement.slider({id:"gcode_command_slider",orientation:"horizontal",min:0,max:1,step:1,value:[0,1],enabled:false}).on("slide",self.changeCommandRange);};self._configureContainerElement=function(containerElement){containerElement.mousedown(function(event){if(event.which===2){event.preventDefault();}});};self.loadFile=function(path,date,size,force){self.enableReload(false);self.needsLoad=false;if(self.status==="idle"&&(force||self.cachedPath!==path||self.cachedDate!==date||self.cachedSize!==size)){self.status="request";self.cachedPath=path;self.cachedDate=date;self.cachedSize=size;var par={url:OctoPrint.files.downloadPath("local",path),path:path,size:size,skipUntil:self.settings.settings.plugins.gcodeviewer.skipUntilThis()};GCODE.renderer.clear();self._onProgress("parsing");GCODE.gCodeReader.loadFile(par);if(self.layerSlider!==undefined){self.layerSlider.slider("disable");}
if(self.layerCommandSlider!==undefined){self.layerCommandSlider.slider("disable");}}};self._onFileLoaded=function(){self.loadedFilepath=self.cachedPath;self.loadedFileDate=self.cachedDate;self.loadedFileSize=self.cachedSize;self.status="idle";self.enableReload(true);};self.reload=function(){if(!self.enableReload())return;self.loadFile(self.loadedFilepath,self.loadedFileDate,self.loadedFileSize,true);};self.fromHistoryData=function(data){self._processData(data);};self.fromCurrentData=function(data){self._processData(data);};self._renderPercentage=function(percentage){var cmdIndex=GCODE.gCodeReader.getCmdIndexForPercentage(percentage);if(!cmdIndex)return;GCODE.renderer.render(cmdIndex.layer,0,cmdIndex.cmd);GCODE.ui.updateLayerInfo(cmdIndex.layer);if(self.layerSlider!==undefined){self.layerSlider.slider("setValue",cmdIndex.layer);}
if(self.layerCommandSlider!==undefined){self.layerCommandSlider.slider("setValue",[0,cmdIndex.cmd]);}};self._processData=function(data){if(!data.job.file||(!data.job.file.path&&(self.loadedFilepath||self.loadedFileDate))){self.waitForApproval(false);self.loadedFilepath=undefined;self.loadedFileDate=undefined;self.loadedFileSize=undefined;self.selectedFile.path(undefined);self.selectedFile.date(undefined);self.selectedFile.size(undefined);self.clear();return;}
if(!self.enabled)return;self.currentlyPrinting=data.state.flags&&(data.state.flags.printing||data.state.flags.paused);if(self.loadedFilepath&&self.loadedFilepath===data.job.file.path&&self.loadedFileDate===data.job.file.date&&self.loadedFileSize===data.job.file.size){if(OctoPrint.coreui.browserTabVisible&&self.tabActive&&self.currentlyPrinting&&self.renderer_syncProgress()&&!self.waitForApproval()){self._renderPercentage(data.progress.completion);}}else{if(self.status==="idle")self.clear();if(data.job.file.path&&data.job.file.origin!=="sdcard"&&self.status!=="request"&&(!self.waitForApproval()||self.selectedFile.path()!==data.job.file.path||self.selectedFile.date()!==data.job.file.date||self.selectedFile.size()!==data.job.file.size)){self.selectedFile.path(data.job.file.path);self.selectedFile.date(data.job.file.date);self.selectedFile.size(data.job.file.size);if(data.job.file.size>self.settings.settings.plugins.gcodeviewer.sizeThreshold()||(OctoPrint.coreui.browser.mobile&&data.job.file.size>self.settings.settings.plugins.gcodeviewer.mobileSizeThreshold())){self.waitForApproval(true);self.loadedFilepath=undefined;self.loadedFileDate=undefined;self.loadedFileSize=undefined;}else{self.waitForApproval(false);if(self.tabActive){self.loadFile(data.job.file.path,data.job.file.date,data.job.file.size);}else{self.needsLoad=true;}}}}};self.onEventPrintDone=function(){if(self.renderer_syncProgress()&&!self.waitForApproval()){self._renderPercentage(100.0);}};self.approveLargeFile=function(){self.waitForApproval(false);self.loadFile(self.selectedFile.path(),self.selectedFile.date(),self.selectedFile.size());};self._onProgress=function(type,percentage){self.ui_progress_type(type);self.ui_progress_percentage(percentage===undefined?100:percentage);self.ui_progress_busy(percentage===undefined);};self._onModelLoaded=function(model){if(!model){self.ui_modelInfo("");if(self.layerSlider!==undefined){self.layerSlider.slider("disable");self.layerSlider.slider("setMax",1);self.layerSlider.slider("setValue",0);self.layerSelectionEnabled(false);self.layerDownEnabled(false);self.layerUpEnabled(false);}
self.currentLayer=0;self.maxLayer=0;}else{var output=[];output.push(gettext("Model size")+": "+
model.width.toFixed(2)+"mm &times; "+
model.depth.toFixed(2)+"mm &times; "+
model.height.toFixed(2)+"mm");output.push(gettext("Estimated layer height")+": "+
model.layerHeight.toFixed(2)+
gettext("mm"));output.push(gettext("Estimated total print time")+": "+
formatFuzzyPrintTime(model.printTime));output.push(gettext("Layers with extrusion")+": "+
model.layersPrinted.toFixed(0));self.ui_modelInfo(output.join("<br>"));self.maxLayer=model.layersActive-1;if(self.layerSlider!==undefined){self.layerSlider.slider("enable");self.layerSlider.slider("setMax",self.maxLayer);self.layerSlider.slider("setValue",0);self.layerSelectionEnabled(true);self.layerDownEnabled(false);self.layerUpEnabled(self.maxLayer>0);}}};self._onLayerSelected=function(layer){if(!layer){self.ui_layerInfo("");if(self.layerCommandSlider!==undefined){self.layerCommandSlider.slider("disable");self.layerCommandSlider.slider("setMax",1);self.layerCommandSlider.slider("setValue",[0,1]);self.layerDownEnabled(false);self.layerUpEnabled(false);}
self.currentCommand=[0,1];}else{var output=[];output.push(gettext("Layer number")+": "+(layer.number+1));output.push(gettext("Layer height")+" (mm): "+layer.height);output.push(gettext("GCODE commands")+": "+layer.commands);if(layer.filament!==undefined){if(layer.filament.length===1){output.push(gettext("Filament")+": "+
layer.filament[0].toFixed(2)+"mm");}else{for(var i=0;i<layer.filament.length;i++){if(layer.filament[i]!==undefined){output.push(gettext("Filament")+" ("+
gettext("Tool")+" "+
i+"): "+
layer.filament[i].toFixed(2)+"mm");}}}}
output.push(gettext("Estimated print time")+": "+
formatDuration(layer.printTime));self.ui_layerInfo(output.join("<br>"));if(self.layerCommandSlider!==undefined){self.layerCommandSlider.slider("enable");self.layerCommandSlider.slider("setMax",layer.commands-1);self.layerCommandSlider.slider("setValue",[0,layer.commands-1]);self.layerDownEnabled(layer.number>0);self.layerUpEnabled(layer.number<self.maxLayer);}}};self._onInternalRendererOptionChange=function(options){if(!options)return;for(var opt in options){if(!options.hasOwnProperty(opt))continue;if(opt==="zoomInOnModel"&&options[opt]!==self.renderer_zoomOnModel()){self.renderer_zoomOnModel(false);}else if(opt==="centerViewport"&&options[opt]!==self.renderer_centerViewport()){self.renderer_centerViewport(false);}else if(opt==="moveModel"&&options[opt]!==self.renderer_centerModel()){self.renderer_centerModel(false);}}};self.changeLayer=function(event){if(self.currentlyPrinting&&self.renderer_syncProgress())
self.renderer_syncProgress(false);var value=event.value;if(self.currentLayer!==undefined&&self.currentLayer===value)return;self.currentLayer=value;GCODE.ui.changeSelectedLayer(value);};self.onMouseOver=function(data,event){if(!self.settings.feature_keyboardControl())return;$("#canvas_container").focus();};self.onMouseOut=function(data,event){if(!self.settings.feature_keyboardControl())return;$("#canvas_container").blur();};self.onKeyDown=function(data,event){if(!self.settings.feature_keyboardControl()||self.layerSlider===undefined)
return;var value=self.currentLayer;switch(event.which){case 33:value=value+10;break;case 34:value=value-10;break;case 38:value=value+1;break;case 40:value=value-1;break;}
self.shiftLayer(value);};self.changeCommandRange=function(event){if(self.currentlyPrinting&&self.renderer_syncProgress())
self.renderer_syncProgress(false);var tuple=event.value;if(self.currentCommand!==undefined&&self.currentCommand[0]===tuple[0]&&self.currentCommand[1]===tuple[1])
return;self.currentCommand=tuple;GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"),tuple[0],tuple[1]);};self.onDataUpdaterReconnect=function(){self.reset();};self.onBeforeBinding=function(){self.initialize();};self.onTabChange=function(current,previous){self.tabActive=current==="#gcode";if(self.tabActive&&self.needsLoad){self.loadFile(self.selectedFile.path(),self.selectedFile.date(),self.selectedFile.size());}};self.shiftLayer=function(value){if(value!==self.currentLayer){self.layerSlider.slider("setValue",value);value=self.layerSlider.slider("getValue");self.layerSlider.trigger({type:"slideStart",value:value}).trigger({type:"slide",value:value}).trigger({type:"slideStop",value:value});}};self.incrementLayer=function(){var value=self.layerSlider.slider("getValue")+1;self.shiftLayer(value);};self.decrementLayer=function(){var value=self.layerSlider.slider("getValue")-1;self.shiftLayer(value);};var optionsLocalStorageKey="core.gcodeviewer.options";self._toLocalStorage=function(){saveToLocalStorage(optionsLocalStorageKey,{centerViewPort:self.renderer_centerViewport(),zoomOnModel:self.renderer_zoomOnModel(),showMoves:self.renderer_showMoves(),showRetracts:self.renderer_showRetracts(),showPrinthead:self.renderer_showPrinthead(),showSegmentStarts:self.renderer_showSegmentStarts(),showDebugArcs:self.renderer_showDebugArcs(),chromeArcFix:self.renderer_chromeArcFix(),showPrevious:self.renderer_showPrevious(),showCurrent:self.renderer_showCurrent(),showNext:self.renderer_showNext(),showFullsize:self.renderer_showFullSize(),showBoundingBox:self.renderer_showBoundingBox(),showLayerBoundingBox:self.renderer_showLayerBoundingBox(),hideEmptyLayers:self.reader_hideEmptyLayers()});};self._fromLocalStorage=function(){self.resetOptions();var current=loadFromLocalStorage(optionsLocalStorageKey);if(current["centerViewPort"]!==undefined)
self.renderer_centerViewport(current["centerViewPort"]);if(current["zoomOnModel"]!==undefined)
self.renderer_zoomOnModel(current["zoomOnModel"]);if(current["showMoves"]!==undefined)
self.renderer_showMoves(current["showMoves"]);if(current["showRetracts"]!==undefined)
self.renderer_showRetracts(current["showRetracts"]);if(current["showPrinthead"]!==undefined)
self.renderer_showPrinthead(current["showPrinthead"]);if(current["showSegmentStarts"]!==undefined)
self.renderer_showSegmentStarts(current["showSegmentStarts"]);if(current["showDebugArcs"]!==undefined)
self.renderer_showDebugArcs(current["showDebugArcs"]);if(current["chromeArcFix"]!==undefined)
self.renderer_chromeArcFix(current["chromeArcFix"]);if(current["showPrevious"]!==undefined)
self.renderer_showPrevious(current["showPrevious"]);if(current["showCurrent"]!==undefined)
self.renderer_showCurrent(current["showCurrent"]);if(current["showNext"]!==undefined)
self.renderer_showNext(current["showNext"]);if(current["showFullsize"]!==undefined)
self.renderer_showFullSize(current["showFullsize"]);if(current["showBoundingBox"]!==undefined)
self.renderer_showBoundingBox(current["showBoundingBox"]);if(current["showLayerBoundingBox"]!==undefined)
self.renderer_showLayerBoundingBox(current["showLayerBoundingBox"]);if(current["hideEmptyLayers"]!==undefined)
self.reader_hideEmptyLayers(current["hideEmptyLayers"]);};}
OCTOPRINT_VIEWMODELS.push({construct:GcodeViewModel,dependencies:["loginStateViewModel","settingsViewModel","accessViewModel"],elements:["#gcode","#gcode_link","#settings_plugin_gcodeviewer"]});});
;

// source: plugin/gcodeviewer/js/viewer/ui.js
var GCODE={};GCODE.ui=(function(){var uiOptions={container:undefined,toolOffsets:undefined,bedDimensions:undefined,onProgress:undefined,onModelLoaded:undefined,onLayerSelected:undefined,onFileLoaded:undefined};var setProgress=function(type,progress){if(uiOptions["onProgress"]){uiOptions.onProgress(type,progress);}};var switchLayer=function(layerNum,onlyInfo){if(!onlyInfo){var segmentCount=GCODE.renderer.getLayerNumSegments(layerNum);GCODE.renderer.render(layerNum,0,segmentCount-1);}
if(uiOptions["onLayerSelected"]){var z=GCODE.renderer.getZ(layerNum);var modelInfo=GCODE.gCodeReader.getModelInfo();uiOptions.onLayerSelected({number:layerNum,height:z,commands:GCODE.renderer.getLayerNumSegments(layerNum),filament:GCODE.gCodeReader.getLayerFilament(z),printTime:modelInfo?modelInfo.printTimeByLayer[z]:undefined});}};var switchCommands=function(layerNum,first,last){GCODE.renderer.render(layerNum,first,last);};var processMessage=function(e){var data=e.data;switch(data.cmd){case"returnModel":if(uiOptions["onFileLoaded"]){uiOptions.onFileLoaded();}
GCODE.ui.worker.postMessage({cmd:"analyzeModel",msg:{}});break;case"analyzeDone":setProgress("done",100);GCODE.gCodeReader.processAnalyzeModelDone(data.msg);var activeModel=GCODE.gCodeReader.passDataToRenderer();if(uiOptions["onModelLoaded"]){uiOptions.onModelLoaded({width:data.msg.modelSize.x,depth:data.msg.modelSize.y,height:data.msg.modelSize.z,filament:data.msg.totalFilament,printTime:data.msg.printTime,layerHeight:data.msg.layerHeight,layersPrinted:data.msg.layerCnt,layersTotal:data.msg.layerTotal,layersActive:activeModel.length});}
switchLayer(0);break;case"returnLayers":GCODE.gCodeReader.processLayersFromWorker(data.msg);setProgress("parsing",data.msg.progress/2);break;case"analyzeProgress":setProgress("analyzing",50+data.msg.progress/2);break;}};var checkCapabilities=function(){var warnings=[];var fatal=[];var errorList=document.getElementById("errorList");if(fatal.length>0){if(errorList){errorList.innerHTML="<ul>"+fatal.join("")+"</ul>";}
console.log("Initialization failed: unsupported browser.");return false;}
if(!Modernizr.webgl&&GCODE.renderer3d){warnings.push("<li>Your browser doesn't seem to support HTML5 Web GL, 3d mode is not recommended, going to be SLOW!</li>");GCODE.renderer3d.setOption({rendererType:"canvas"});}
if(warnings.length>0){if(errorList){errorList.innerHTML="<ul>"+warnings.join("")+"</ul>";}
console.log("Initialization succeeded with warnings.",warnings);}
return true;};var setOptions=function(options){if(!options)return;for(var opt in options){if(options[opt]===undefined)continue;if(options.hasOwnProperty(opt)){uiOptions[opt]=options[opt];}}};return{worker:undefined,init:function(options){if(options)setOptions(options);if(!options.container){return false;}
var capabilitiesResult=checkCapabilities();if(!capabilitiesResult){return false;}
setProgress("",0);this.worker=new Worker(GCODE_WORKER);this.worker.addEventListener("message",processMessage,false);GCODE.renderer.setOption({container:options.container,bed:options.bed});GCODE.gCodeReader.setOption({toolOffsets:options.toolOffsets,bed:options.bed,bedZ:options.bedZ});GCODE.renderer.render(0,0);return true;},clear:function(){GCODE.gCodeReader.clear();GCODE.renderer.clear();setProgress("",0);if(uiOptions["onLayerSelected"]){uiOptions.onLayerSelected();}
if(uiOptions["onModelLoaded"]){uiOptions.onModelLoaded();}},resetViewport:function(){GCODE.renderer.resetViewport();},updateLayerInfo:function(layerNum){switchLayer(layerNum,true);},updateOptions:function(options){setOptions(options.ui);if(options.reader){GCODE.gCodeReader.setOption(options.reader);}
if(options.renderer){GCODE.renderer.setOption(options.renderer);}},changeSelectedLayer:function(newLayerNum){switchLayer(newLayerNum);},changeSelectedCommands:function(layerNum,first,last){switchCommands(layerNum,first,last);}};})();
;

// source: plugin/gcodeviewer/js/viewer/reader.js
GCODE.gCodeReader=(function(){var gcode,lines;var max={x:undefined,y:undefined,z:undefined};var min={x:undefined,y:undefined,z:undefined};var modelSize={x:undefined,y:undefined,z:undefined};var boundingBox={minX:undefined,maxX:undefined,minY:undefined,maxY:undefined,minZ:undefined,maxZ:undefined};var filamentByLayer={};var printTimeByLayer;var totalFilament=0;var printTime=0;var speeds={};var speedsByLayer={};var gCodeOptions={sortLayers:false,purgeEmptyLayers:true,analyzeModel:false,toolOffsets:[{x:0,y:0}],bed:{x:undefined,y:undefined,r:undefined,circular:undefined,centeredOrigin:undefined},ignoreOutsideBed:false,g90InfluencesExtruder:false,bedZ:0,alwaysCompress:false,compressionSizeThreshold:0,forceCompression:false};var model=[];var emptyLayers=[];var percentageByLayer=[];var rendererModel=undefined;var rendererEmptyLayers=undefined;var rendererPercentageByLayer=undefined;var layerPercentageLookup=[];var cachedLayer=undefined;var cachedCmd=undefined;var prepareGCode=function(totalSize){if(!lines)return;gcode=[];var i,byteCount;byteCount=0;for(i=0;i<lines.length;i++){byteCount+=lines[i].length+1;gcode.push({line:lines[i],percentage:(byteCount*100)/totalSize});}
lines=[];};var searchInPercentageTree=function(key){function searchInLayers(lower,upper,key){while(lower<upper){var middle=Math.floor((lower+upper)/2);if(layerPercentageLookup[middle][0]<=key&&layerPercentageLookup[middle][1]>key)
return middle;if(layerPercentageLookup[middle][0]>key){upper=middle-1;}else{lower=middle+1;}}
return lower;}
function searchInCmds(layer,lower,upper,key){var cmds=GCODE.renderer.getLayer(layer);while(lower<upper){var middle=Math.floor((lower+upper)/2);if(cmds[middle].percentage==key||(cmds[middle].percentage<=key&&cmds[middle+1].percentage>key))
return middle;if(cmds[middle].percentage>key){upper=middle-1;}else{lower=middle+1;}}
return lower;}
if(rendererModel===undefined)return undefined;if(key==null)return{layer:cachedLayer,cmd:cachedCmd};var layer=searchInLayers(0,rendererModel.length-1,key);var cmds=GCODE.renderer.getLayer(layer);if(cmds===undefined)return undefined;var cmd=searchInCmds(layer,0,cmds.length-1,key);cachedLayer=layer;cachedCmd=cmd;return{layer:layer,cmd:cmd};};var cleanModel=function(m){if(!m)return[];var result=[];rendererEmptyLayers=[];rendererPercentageByLayer=[];for(var i=0;i<m.length;i++){if(!m[i])continue;if(gCodeOptions["purgeEmptyLayers"]&&emptyLayers[i])continue;result.push(m[i]);rendererPercentageByLayer.push(percentageByLayer[i]);if(emptyLayers[i])rendererEmptyLayers[result.length-1]=true;}
return result;};var rebuildLayerPercentageLookup=function(m){var result=[];if(m&&m.length>0){for(var i=0;i<m.length-1;i++){var start=rendererPercentageByLayer[i]!==undefined?rendererPercentageByLayer[i]:-1;var end=-1;for(var j=i+1;j<m.length;j++){if(!rendererEmptyLayers[j]){end=rendererPercentageByLayer[j];break;}}
result[i]=[start,end];}
result[result.length]=[rendererPercentageByLayer[m.length-1],100];}
layerPercentageLookup=result;};return{clear:function(){model=[];max={x:undefined,y:undefined,z:undefined};min={x:undefined,y:undefined,z:undefined};modelSize={x:undefined,y:undefined,z:undefined};boundingBox={minX:undefined,maxX:undefined,minY:undefined,maxY:undefined,minZ:undefined,maxZ:undefined};rendererModel=undefined;rendererEmptyLayers=undefined;rendererPercentageByLayer=undefined;layerPercentageLookup=undefined;cachedLayer=undefined;cachedCmd=undefined;},loadFile:function(reader){this.clear();var mustCompress=gCodeOptions["forceCompression"]||gCodeOptions["alwaysCompress"]||(gCodeOptions["compressionSizeThreshold"]>0&&gCodeOptions["compressionSizeThreshold"]<=reader.size);GCODE.ui.worker.postMessage({cmd:"downloadAndParseGCode",msg:{url:reader.url,path:reader.path,skipUntil:reader.skipUntil,options:{firstReport:5,toolOffsets:gCodeOptions["toolOffsets"],bed:gCodeOptions["bed"],ignoreOutsideBed:gCodeOptions["ignoreOutsideBed"],g90InfluencesExtruder:gCodeOptions["g90InfluencesExtruder"],bedZ:gCodeOptions["bedZ"],compress:mustCompress}}});},setOption:function(options){var dirty=false;_.forOwn(options,function(value,key){if(value===undefined)return;dirty=dirty||gCodeOptions[key]!==value;gCodeOptions[key]=value;});if(dirty){if(model&&model.length>0)this.passDataToRenderer();}},passDataToRenderer:function(){rendererModel=cleanModel(model);rebuildLayerPercentageLookup(rendererModel);GCODE.renderer.doRender(rendererModel,0);return rendererModel;},processLayersFromWorker:function(msg){for(var i=0;i<msg.layers.length;i++){model[msg.layers[i]]=msg.model[msg.layers[i]];}},processAnalyzeModelDone:function(msg){min=msg.min;max=msg.max;modelSize=msg.modelSize;boundingBox=msg.boundingBox;totalFilament=msg.totalFilament;filamentByLayer=msg.filamentByLayer;speeds=msg.speeds;speedsByLayer=msg.speedsByLayer;printTime=msg.printTime;printTimeByLayer=msg.printTimeByLayer;emptyLayers=msg.emptyLayers;percentageByLayer=msg.percentageByLayer;},getLayerFilament:function(z){return filamentByLayer[z];},getLayerSpeeds:function(z){return speedsByLayer[z]?speedsByLayer[z]:{};},getModelInfo:function(){return{min:min,max:max,modelSize:modelSize,boundingBox:boundingBox,totalFilament:totalFilament,speeds:speeds,speedsByLayer:speedsByLayer,printTime:printTime,printTimeByLayer:printTimeByLayer};},getGCodeLines:function(layer,fromSegments,toSegments){var result={first:GCODE.renderer.getLayer(layer)[fromSegments].gcodeLine,last:GCODE.renderer.getLayer(layer)[toSegments].gcodeLine};return result;},getCmdIndexForPercentage:function(percentage){return searchInPercentageTree(percentage);}};})();
;

// source: plugin/gcodeviewer/js/viewer/renderer.js
GCODE.renderer=(function(){var canvas;var ctx;var viewportChanged=true;var lineWidthFactor=1/2.8;var zoomFactorDelta=0.4;var gridStep=10;var ctxHeight,ctxWidth;var prevX=0,prevY=0;var pixelRatio=window.devicePixelRatio||1;var layerNumStore,progressStore={from:0,to:-1};var lastX,lastY;var dragStart;var scaleFactor=1.1;var model=undefined;var modelInfo=undefined;var initialized=false;var renderOptions={colorGrid:"#bbbbbb",bgColorGrid:"#ffffff",bgColorOffGrid:"#eeeeee",colorLine:["#000000","#3333cc","#cc3333","#33cc33","#cc33cc"],colorMove:"#00ff00",colorRetract:"#ff0000",colorRestart:"#0000ff",colorHead:"#00ff00",colorSegmentStart:"#666666",showMoves:true,showRetracts:true,extrusionWidth:1*pixelRatio,sizeRetractSpot:2*pixelRatio,sizeHeadSpot:2*pixelRatio,modelCenter:{x:0,y:0},differentiateColors:true,showNextLayer:false,showCurrentLayer:false,showPreviousLayer:false,showBoundingBox:false,showLayerBoundingBox:false,showFullSize:false,showHead:false,showSegmentStarts:false,sizeSegmentStart:2*pixelRatio,showDebugArcs:false,chromeArcFix:false,moveModel:true,zoomInOnModel:false,zoomInOnBed:false,centerViewport:false,invertAxes:{x:false,y:false},bed:{x:200,y:200},container:undefined,onInternalOptionChange:undefined,onViewportChange:undefined,onDragStart:undefined,onDrag:undefined,onDragStop:undefined};var offsetModelX=0,offsetModelY=0;var offsetBedX=0,offsetBedY=0;var scaleX=1,scaleY=1;var speeds=[];var speedsByLayer={};var currentInvertX=false,currentInvertY=false;var deg0=0.0;var deg90=Math.PI/2.0;var deg180=Math.PI;var deg270=Math.PI*1.5;var deg360=Math.PI*2.0;var layerCache=[];var decompress=function(data){if(!(data instanceof Uint8Array))return data;return JSON.parse(pako.inflate(data,{to:"string"}));};var getLayer=function(layer){if(!model[layer])return undefined;if(!layerCache[layer])layerCache[layer]=decompress(model[layer]);return layerCache[layer];};var cleanCache=function(layer){var newCache=[];for(var l in layerCache){if(l==layer||l==layer+1)newCache[l]=layerCache[l];if(l==layer-1&&renderOptions["showPreviousLayer"])
newCache[l]=layerCache[l];}
layerCache=newCache;};function notifyIfViewportChanged(){if(viewportChanged){if(renderOptions["onViewportChange"]){renderOptions["onViewportChange"](ctx.getTransform());}
viewportChanged=false;}}
var reRender=function(){if(!model)return;log.debug("Rerendering layer "+
layerNumStore+" of "+
model.length+" with "+
GCODE.renderer.getLayerNumSegments(layerNumStore)+" segments");applyOffsets(layerNumStore);applyZoom(layerNumStore);notifyIfViewportChanged();var p1=ctx.transformedPoint(0,0);var p2=ctx.transformedPoint(canvas.width,canvas.height);ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);drawGrid();drawBoundingBox(layerNumStore);if(model&&model.length){if(layerNumStore<model.length){if(renderOptions["showNextLayer"]&&layerNumStore<model.length-1){drawLayer(layerNumStore+1,0,GCODE.renderer.getLayerNumSegments(layerNumStore+1),true);}
if(renderOptions["showCurrentLayer"]&&layerNumStore<model.length){drawLayer(layerNumStore,0,GCODE.renderer.getLayerNumSegments(layerNumStore),true);}
if(renderOptions["showPreviousLayer"]&&layerNumStore>0){drawLayer(layerNumStore-1,0,GCODE.renderer.getLayerNumSegments(layerNumStore-1),true);}
drawLayer(layerNumStore,progressStore.from,progressStore.to);}else{console.log("Got request to render non-existent layer");}
cleanCache(layerNumStore);}};function getLayerBounds(layer){if(!model||!model[layer])return;var cmds=getLayer(layer);var firstExtrusion;var i;var factorIn=function(cmd){return cmd&&cmd.extrude&&(cmd.x!==undefined||cmd.y!==undefined);};for(i=0;i<cmds.length;i++){if(factorIn(cmds[i]))break;}
if(i===cmds.length)return;firstExtrusion=i;var minX=cmds[firstExtrusion].prevX,maxX=cmds[firstExtrusion].prevX,minY=cmds[firstExtrusion].prevY,maxY=cmds[firstExtrusion].prevY;for(i=firstExtrusion;i<cmds.length;i++){if(factorIn(cmds[i])){minX=Math.min(minX,cmds[i].prevX);maxX=Math.max(maxX,cmds[i].prevX);if(cmds[i].x!==undefined){minX=Math.min(minX,cmds[i].x);maxX=Math.max(maxX,cmds[i].x);}
minY=Math.min(minY,cmds[i].prevY);maxY=Math.max(maxY,cmds[i].prevY);if(cmds[i].y!==undefined){minY=Math.min(minY,cmds[i].y);maxY=Math.max(maxY,cmds[i].y);}
if(!!cmds[i].direction){var dir=cmds[i].direction;var arc=getArcParams(cmds[i]);var startAngle,endAngle;if(dir<0){startAngle=arc.startAngle;endAngle=arc.endAngle;}else{startAngle=arc.endAngle;endAngle=arc.startAngle;}
if(startAngle<0)startAngle+=deg360;if(endAngle<0)endAngle+=deg360;var intersectsAngle=function(sA,eA,angle){return((sA>=angle&&(eA<=angle||eA>sA))||(sA<=angle&&eA<=angle&&eA>sA));};if(intersectsAngle(startAngle,endAngle,deg0)){maxX=Math.max(maxX,arc.x+arc.r);}
if(intersectsAngle(startAngle,endAngle,deg90)){maxY=Math.max(maxY,arc.y+arc.r);}
if(intersectsAngle(startAngle,endAngle,deg180)){minX=Math.min(minX,arc.x-arc.r);}
if(intersectsAngle(startAngle,endAngle,deg270)){minY=Math.min(minY,arc.y-arc.r);}}}}
return{minX:minX,maxX:maxX,minY:minY,maxY:maxY};}
function getArcParams(cmd){var x=cmd.x!==undefined?cmd.x:cmd.prevX;var y=cmd.y!==undefined?cmd.y:cmd.prevY;var centerX=cmd.prevX+cmd.i;var centerY=cmd.prevY+cmd.j;return{x:centerX,y:centerY,r:Math.sqrt(cmd.i*cmd.i+cmd.j*cmd.j),startAngle:Math.atan2(cmd.prevY-centerY,cmd.prevX-centerX),endAngle:Math.atan2(y-centerY,x-centerX),startX:cmd.prevX,startY:cmd.prevY,endX:x,endY:y};}
function trackTransforms(ctx){var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");var xform=svg.createSVGMatrix();ctx.getTransform=function(){return xform;};var savedTransforms=[];var save=ctx.save;ctx.save=function(){savedTransforms.push(xform.translate(0,0));return save.call(ctx);};var restore=ctx.restore;ctx.restore=function(){xform=savedTransforms.pop();viewportChanged=true;return restore.call(ctx);};var scale=ctx.scale;ctx.scale=function(sx,sy){xform=xform.scaleNonUniform(sx,sy);viewportChanged=true;return scale.call(ctx,sx,sy);};var rotate=ctx.rotate;ctx.rotate=function(radians){xform=xform.rotate((radians*180)/Math.PI);viewportChanged=true;return rotate.call(ctx,radians);};var translate=ctx.translate;ctx.translate=function(dx,dy){xform=xform.translate(dx,dy);viewportChanged=true;return translate.call(ctx,dx,dy);};var transform=ctx.transform;ctx.transform=function(a,b,c,d,e,f){var m2=svg.createSVGMatrix();m2.a=a;m2.b=b;m2.c=c;m2.d=d;m2.e=e;m2.f=f;xform=xform.multiply(m2);viewportChanged=true;return transform.call(ctx,a,b,c,d,e,f);};var setTransform=ctx.setTransform;ctx.setTransform=function(a,b,c,d,e,f){xform.a=a;xform.b=b;xform.c=c;xform.d=d;xform.e=e;xform.f=f;viewportChanged=true;return setTransform.call(ctx,a,b,c,d,e,f);};var pt=svg.createSVGPoint();ctx.transformedPoint=function(x,y){pt.x=x;pt.y=y;return pt.matrixTransform(xform.inverse());};}
var bezierArc=function(x,y,radius,startAngle,endAngle,anticlockwise){var signedLength;var tau=2*Math.PI;if(!anticlockwise&&endAngle-startAngle>=tau){signedLength=tau;}else if(anticlockwise&&startAngle-endAngle>=tau){signedLength=-tau;}else{var delta=endAngle-startAngle;signedLength=delta-tau*Math.floor(delta/tau);if(Math.abs(delta)>1e-12&&signedLength<1e-12)signedLength=tau;if(anticlockwise&&signedLength>0)signedLength=signedLength-tau;}
var minCurves=Math.ceil(Math.abs(signedLength)/(Math.PI/2));var numCurves=Math.ceil(Math.max(minCurves,Math.sqrt(radius)));var cpRadius=radius*(2-Math.cos(signedLength/(numCurves*2)));var step=signedLength/numCurves;this.lineTo(x+radius*Math.cos(startAngle),y+radius*Math.sin(startAngle));for(var i=0,a=startAngle+step,a2=startAngle+step/2;i<numCurves;++i,a+=step,a2+=step)
this.quadraticCurveTo(x+cpRadius*Math.cos(a2),y+cpRadius*Math.sin(a2),x+radius*Math.cos(a),y+radius*Math.sin(a));};var applyContextPatches=function(){if(!ctx.origArc)ctx.origArc=ctx.arc;ctx.circle=function(x,y,r){ctx.origArc(x,y,r,0,2*Math.PI,true);};if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){if(renderOptions["chromeArcFix"]){ctx.arc=bezierArc;log.info("Chrome Arc Fix enabled");}else{ctx.arc=ctx.origArc;log.info("Chrome Arc Fix disabled");}}};var startCanvas=function(){var jqueryCanvas=$(renderOptions["container"]);canvas=jqueryCanvas[0];ctx=canvas.getContext("2d");applyContextPatches();canvas.style.height=canvas.height+"px";canvas.style.width=canvas.width+"px";canvas.height=canvas.height*pixelRatio;canvas.width=canvas.width*pixelRatio;ctxHeight=canvas.height;ctxWidth=canvas.width;lastX=ctxWidth/2;lastY=ctxHeight/2;ctx.lineWidth=2*lineWidthFactor;ctx.lineCap="round";trackTransforms(ctx);canvas.addEventListener("mousedown",function(event){document.body.style.mozUserSelect=document.body.style.webkitUserSelect=document.body.style.userSelect="none";lastX=(event.offsetX||event.pageX-canvas.offsetLeft)*pixelRatio;lastY=(event.offsetY||event.pageY-canvas.offsetTop)*pixelRatio;var pt=ctx.transformedPoint(lastX,lastY);if(!renderOptions["onDragStart"]||renderOptions["onDragStart"](pt)!==false)
dragStart=pt;},false);canvas.addEventListener("mousemove",function(event){lastX=(event.offsetX||event.pageX-canvas.offsetLeft)*pixelRatio;lastY=(event.offsetY||event.pageY-canvas.offsetTop)*pixelRatio;if(dragStart!==undefined){var pt=ctx.transformedPoint(lastX,lastY);if(renderOptions["onDrag"]&&renderOptions["onDrag"](pt)===false)
return;ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y);reRender();renderOptions["centerViewport"]=false;renderOptions["zoomInOnModel"]=false;renderOptions["zoomInOnBed"]=false;offsetModelX=0;offsetModelY=0;offsetBedX=0;offsetBedY=0;scaleX=1;scaleY=1;if(renderOptions["onInternalOptionChange"]!==undefined){renderOptions["onInternalOptionChange"]({centerViewport:false,moveModel:false,zoomInOnModel:false,zoomInOnBed:false});}}},false);canvas.addEventListener("mouseup",function(event){dragStart=undefined;if(renderOptions["onDragStop"]){var x=(event.offsetX||event.pageX-canvas.offsetLeft)*pixelRatio;var y=(event.offsetY||event.pageY-canvas.offsetTop)*pixelRatio;renderOptions["onDragStop"](ctx.transformedPoint(x,y));}},false);var zoom=function(clicks){var pt=ctx.transformedPoint(lastX,lastY);ctx.translate(pt.x,pt.y);var factor=Math.pow(scaleFactor,clicks);ctx.scale(factor,factor);ctx.translate(-pt.x,-pt.y);reRender();renderOptions["zoomInOnModel"]=false;renderOptions["zoomInOnBed"]=false;offsetModelX=0;offsetModelY=0;offsetBedX=0;offsetBedY=0;scaleX=1;scaleY=1;if(renderOptions["onInternalOptionChange"]!==undefined){renderOptions["onInternalOptionChange"]({zoomInOnModel:false,zoomInOnBed:false});}};var handleScroll=function(event){var delta;if(event.detail<0||event.wheelDelta>0){delta=zoomFactorDelta;}else{delta=-1*zoomFactorDelta;}
if(delta)zoom(delta);return event.preventDefault()&&false;};canvas.addEventListener("DOMMouseScroll",handleScroll,false);canvas.addEventListener("mousewheel",handleScroll,false);};var drawGrid=function(){ctx.translate(offsetBedX,offsetBedY);if(renderOptions["bed"]["circular"]){drawCircularGrid();}else{drawRectangularGrid();}
ctx.translate(-offsetBedX,-offsetBedY);};var drawRectangularGrid=function(){var x,y;var width=renderOptions["bed"]["x"];var height=renderOptions["bed"]["y"];var minX,maxX,minY,maxY;if(renderOptions["bed"]["centeredOrigin"]){var halfWidth=width/2;var halfHeight=height/2;minX=-halfWidth;maxX=halfWidth;minY=-halfHeight;maxY=halfHeight;}else{minX=0;maxX=width;minY=0;maxY=height;}
ctx.beginPath();ctx.strokeStyle=renderOptions["colorGrid"];ctx.fillStyle="#ffffff";ctx.lineWidth=2*lineWidthFactor;ctx.rect(minX,minY,width,height);ctx.moveTo(minX,0);ctx.lineTo(maxX,0);ctx.moveTo(0,minY);ctx.lineTo(0,maxY);ctx.fill();ctx.stroke();ctx.beginPath();ctx.circle(0,0,2);ctx.stroke();ctx.strokeStyle=renderOptions["colorGrid"];var gridline=0;for(x=0;x<=maxX;x+=gridStep){ctx.beginPath();if(gridline%5===0){ctx.lineWidth=1.5*lineWidthFactor;}else{ctx.lineWidth=lineWidthFactor;}
gridline+=1;ctx.moveTo(x,minY);ctx.lineTo(x,maxY);if(renderOptions["bed"]["centeredOrigin"]){ctx.moveTo(-1*x,minY);ctx.lineTo(-1*x,maxY);}
ctx.stroke();}
gridline=0;for(y=0;y<=maxY;y+=gridStep){ctx.beginPath();if(gridline%5===0){ctx.lineWidth=1.5*lineWidthFactor;}else{ctx.lineWidth=lineWidthFactor;}
gridline+=1;ctx.moveTo(minX,y);ctx.lineTo(maxX,y);if(renderOptions["bed"]["centeredOrigin"]){ctx.moveTo(minX,-1*y);ctx.lineTo(maxX,-1*y);}
ctx.stroke();}};var drawCircularGrid=function(){var i;ctx.strokeStyle=renderOptions["colorGrid"];ctx.fillStyle="#ffffff";ctx.lineWidth=2*lineWidthFactor;ctx.beginPath();var r=renderOptions["bed"]["r"];ctx.circle(0,0,r);ctx.moveTo(-1*r,0);ctx.lineTo(r,0);ctx.moveTo(0,r);ctx.lineTo(0,-1*r);ctx.fill();ctx.stroke();ctx.beginPath();ctx.circle(0,0,2);ctx.stroke();ctx.strokeStyle=renderOptions["colorGrid"];ctx.lineWidth=lineWidthFactor;ctx.beginPath();for(i=0;i<=r;i+=gridStep){var x=i;var y=Math.sqrt(r*r-x*x);ctx.moveTo(x,-1*y);ctx.lineTo(x,y);ctx.moveTo(y,-1*x);ctx.lineTo(-1*y,-1*x);ctx.moveTo(-1*x,-1*y);ctx.lineTo(-1*x,y);ctx.moveTo(y,x);ctx.lineTo(-1*y,x);}
ctx.stroke();};var drawBoundingBox=function(layerNum){if(!modelInfo)return;var minX,minY,width,height;var draw=function(x,y,w,h,c){ctx.beginPath();ctx.strokeStyle=c;ctx.setLineDash([2,5]);ctx.rect(x,y,w,h);ctx.stroke();};if(renderOptions["showFullSize"]){minX=modelInfo.min.x;minY=modelInfo.min.y;width=modelInfo.modelSize.x;height=modelInfo.modelSize.y;draw(minX,minY,width,height,"#0000ff");}
if(renderOptions["showBoundingBox"]){minX=modelInfo.boundingBox.minX;minY=modelInfo.boundingBox.minY;width=modelInfo.boundingBox.maxX-minX;height=modelInfo.boundingBox.maxY-minY;draw(minX,minY,width,height,"#ff0000");}
if(renderOptions["showLayerBoundingBox"]){var layerBounds=getLayerBounds(layerNum);if(layerBounds){minX=layerBounds.minX;minY=layerBounds.minY;width=layerBounds.maxX-minX;height=layerBounds.maxY-minY;draw(minX,minY,width,height,"#00ff00");}}
ctx.setLineDash([1,0]);};var drawTriangle=function(centerX,centerY,length,up){var ax,bx,cx,ay,by,cy;var h=Math.sqrt(0.75*length*length)/2;ax=centerX-length/2;bx=ax+length;cx=centerX;if(up){ay=centerY-h;by=centerY-h;cy=centerY+h;}else{ay=centerY+h;by=centerY+h;cy=centerY-h;}
var origLineJoin=ctx.lineJoin;ctx.lineJoin="miter";ctx.beginPath();ctx.moveTo(ax,ay);ctx.lineTo(bx,by);ctx.moveTo(bx,by);ctx.lineTo(cx,cy);ctx.lineTo(ax,ay);ctx.stroke();ctx.fill();ctx.lineJoin=origLineJoin;};var drawCross=function(centerX,centerY,size){var x1,y1,x2,y2;var half=size/2;x1=centerX-half;x2=centerX+half;y1=centerY-half;y2=centerY+half;ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.moveTo(x1,y2);ctx.lineTo(x2,y1);ctx.stroke();};var drawDebugArc=function(arc,ccw){ctx.moveTo(arc.x,arc.y);ctx.lineTo(arc.startX,arc.startY);ctx.moveTo(arc.x,arc.y);ctx.lineTo(arc.endX,arc.endY);ctx.moveTo(arc.startX,arc.startY);ctx.lineTo(arc.endX,arc.endY);ctx.moveTo(arc.startX,arc.startY);ctx.arc(arc.x,arc.y,arc.r,arc.startAngle,arc.endAngle,ccw);};var drawLayer=function(layerNum,fromProgress,toProgress,isNotCurrentLayer){log.trace("Drawing layer "+
layerNum+" from "+
fromProgress+" to "+
toProgress+" (current: "+
!isNotCurrentLayer+")");var i;isNotCurrentLayer=isNotCurrentLayer!==undefined?isNotCurrentLayer:false;if(!model||!model[layerNum])return;var cmds=getLayer(layerNum);var x,y;if(cmds[0].prevX!==undefined&&cmds[0].prevY!==undefined){prevX=cmds[0].prevX;prevY=cmds[0].prevY;}else if(fromProgress>0){prevX=cmds[fromProgress-1].x;prevY=cmds[fromProgress-1].y;}else if(model[layerNum-1]){prevX=undefined;prevY=undefined;var prevModelLayer=getLayer(layerNum-1);for(i=prevModelLayer.length-1;i>=0;i--){if(prevX===undefined&&prevModelLayer[i].x!==undefined){prevX=prevModelLayer[i].x;if(prevY!==undefined)break;}
if(prevY===undefined&&prevModelLayer[i].y!==undefined){prevY=prevModelLayer[i].y;if(prevX!==undefined)break;}}}
if(prevX===undefined)prevX=0;if(prevY===undefined)prevY=0;var sizeRetractSpot=renderOptions["sizeRetractSpot"]*lineWidthFactor*2;var sizeSegmentStart=renderOptions["sizeSegmentStart"]*lineWidthFactor*2;var alpha=(renderOptions["showNextLayer"]||renderOptions["showCurrentLayer"]||renderOptions["showPreviousLayer"])&&isNotCurrentLayer?0.3:1.0;var colorLine={};var colorMove={};var colorRetract={};var colorRestart={};var colorSegmentStart={};function getColorLineForTool(tool){var rv=colorLine[tool];if(rv===undefined){var lineColor=renderOptions["colorLine"][tool];if(lineColor===undefined)lineColor=renderOptions["colorLine"][0];var shade=tool*0.15;rv=colorLine[tool]=pusher.color(lineColor).shade(shade).alpha(alpha).html();}
return rv;}
function getColorMoveForTool(tool){var rv=colorMove[tool];if(rv===undefined){var shade=tool*0.15;rv=colorMove[tool]=pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html();}
return rv;}
function getColorRetractForTool(tool){var rv=colorRetract[tool];if(rv===undefined){var shade=tool*0.15;rv=colorRetract[tool]=pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html();}
return rv;}
function getColorRestartForTool(tool){var rv=colorRestart[tool];if(rv===undefined){var shade=tool*0.15;rv=colorRestart[tool]=pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html();}
return rv;}
function getColorSegmentStartForTool(tool){var rv=colorSegmentStart[tool];if(rv===undefined){var shade=tool*0.15;rv=colorSegmentStart[tool]=pusher.color(renderOptions["colorSegmentStart"]).shade(shade).alpha(alpha).html();}
return rv;}
var prevPathType="fill";function strokePathIfNeeded(newPathType,strokeStyle){if(newPathType!==prevPathType||newPathType==="fill"){if(prevPathType!=="fill"){ctx.stroke();}
prevPathType=newPathType;ctx.beginPath();if(newPathType!=="fill"){ctx.strokeStyle=strokeStyle;ctx.moveTo(prevX,prevY);}}}
ctx.lineJoin="round";for(i=fromProgress;i<=toProgress;i++){if(typeof cmds[i]==="undefined")continue;var cmd=cmds[i];if(cmd.prevX!==undefined&&cmd.prevY!==undefined){prevX=cmd.prevX;prevY=cmd.prevY;}
if(cmd.x===undefined||isNaN(cmd.x)){x=prevX;}else{x=cmd.x;}
if(cmd.y===undefined||isNaN(cmd.y)){y=prevY;}else{y=cmd.y;}
var tool=cmd.tool||0;if(!cmd.extrude&&!cmd.noMove){if(cmd.retract==-1){if(renderOptions["showRetracts"]&&!isNotCurrentLayer){strokePathIfNeeded("fill");ctx.fillStyle=getColorRetractForTool(tool);ctx.strokeStyle=ctx.fillStyle;drawTriangle(prevX,prevY,sizeRetractSpot,true);}}
strokePathIfNeeded("move",getColorMoveForTool(tool));if(renderOptions["showMoves"]&&!isNotCurrentLayer){ctx.lineWidth=lineWidthFactor;if(cmd.direction!==undefined&&cmd.direction!==0){var arc=getArcParams(cmd);var ccw=cmd.direction<0;ctx.arc(arc.x,arc.y,arc.r,arc.startAngle,arc.endAngle,ccw);}else{ctx.lineTo(x,y);}}}else if(cmd.extrude){if(cmd.retract==0){strokePathIfNeeded("extrude",getColorLineForTool(tool));ctx.lineWidth=renderOptions["extrusionWidth"]*lineWidthFactor;if(cmd.direction!==undefined&&cmd.direction!==0){var arc=getArcParams(cmd);var ccw=cmd.direction<0;if(renderOptions["showDebugArcs"]&&!isNotCurrentLayer){strokePathIfNeeded("debugarc","#ff0000");drawDebugArc(arc,ccw);strokePathIfNeeded("extrude",getColorLineForTool(tool));}
ctx.arc(arc.x,arc.y,arc.r,arc.startAngle,arc.endAngle,ccw);}else{ctx.lineTo(x,y);}}else{if(renderOptions["showRetracts"]&&!isNotCurrentLayer){strokePathIfNeeded("fill");ctx.fillStyle=getColorRestartForTool(tool);ctx.strokeStyle=ctx.fillStyle;drawTriangle(prevX,prevY,sizeRetractSpot,false);}}
if(renderOptions["showSegmentStarts"]&&!isNotCurrentLayer){strokePathIfNeeded("fill");ctx.strokeStyle=getColorSegmentStartForTool(tool);drawCross(x,y,sizeSegmentStart);}}
prevX=x;prevY=y;}
if(prevPathType!="fill"){ctx.stroke();}
if(renderOptions["showHead"]&&!isNotCurrentLayer){var sizeHeadSpot=renderOptions["sizeHeadSpot"]*lineWidthFactor+lineWidthFactor/2;var shade=tool*0.15;ctx.fillStyle=pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html();ctx.beginPath();ctx.circle(prevX,prevY,sizeHeadSpot);ctx.fill();}};var applyOffsets=function(layerNum){var canvasCenter;var layerBounds;if(ctx)ctx.translate(-offsetModelX,-offsetModelY);if(renderOptions["centerViewport"]||renderOptions["zoomInOnModel"]){canvasCenter=ctx.transformedPoint(canvas.width/2,canvas.height/2);layerBounds=getLayerBounds(layerNum);if(layerBounds){offsetModelX=canvasCenter.x-(layerBounds.minX+layerBounds.maxX)/2;offsetModelY=canvasCenter.y-(layerBounds.minY+layerBounds.maxY)/2;}else{offsetModelX=0;offsetModelY=0;}
offsetBedX=0;offsetBedY=0;}else if(renderOptions["moveModel"]){layerBounds=getLayerBounds(layerNum);if(layerBounds){offsetModelX=renderOptions["bed"]["x"]/2-
(layerBounds.minX+layerBounds.maxX)/2;offsetModelY=renderOptions["bed"]["y"]/2-
(layerBounds.minY+layerBounds.maxY)/2;offsetBedX=-1*(renderOptions["bed"]["x"]/2-
(layerBounds.minX+layerBounds.maxX)/2);offsetBedY=-1*(renderOptions["bed"]["y"]/2-
(layerBounds.minY+layerBounds.maxY)/2);}}else{offsetModelX=0;offsetModelY=0;offsetBedX=0;offsetBedY=0;}
if(ctx)ctx.translate(offsetModelX,offsetModelY);};var applyZoom=function(layerNum){var pt=ctx.transformedPoint(canvas.width/2,canvas.height/2);var transform=ctx.getTransform();if(scaleX&&scaleY&&transform.a&&transform.d){ctx.translate(pt.x,pt.y);ctx.scale(1/scaleX,1/scaleY);ctx.translate(-pt.x,-pt.y);transform=ctx.getTransform();}
if(renderOptions["zoomInOnModel"]){var layerBounds=getLayerBounds(layerNum);if(layerBounds){var width=Math.max(layerBounds.maxX-layerBounds.minX,renderOptions["extrusionWidth"]*50);var length=Math.max(layerBounds.maxY-layerBounds.minY,renderOptions["extrusionWidth"]*50);var scaleF=width>length?(canvas.width-10)/width:(canvas.height-10)/length;if(transform.a&&transform.d){scaleX=(scaleF/transform.a)*(renderOptions["invertAxes"]["x"]?-1:1);scaleY=(scaleF/transform.d)*(renderOptions["invertAxes"]["y"]?1:-1);ctx.translate(pt.x,pt.y);ctx.scale(scaleX,scaleY);ctx.translate(-pt.x,-pt.y);}}}};var applyInversion=function(){var width=canvas.width-10;var height=canvas.height-10;if(currentInvertX||currentInvertY){ctx.scale(currentInvertX?-1:1,currentInvertY?-1:1);ctx.translate(currentInvertX?-width:0,currentInvertY?height:0);}
var invertX=renderOptions["invertAxes"]["x"];var invertY=renderOptions["invertAxes"]["y"];if(invertX||invertY){ctx.translate(invertX?width:0,invertY?-height:0);ctx.scale(invertX?-1:1,invertY?-1:1);}
currentInvertX=invertX;currentInvertY=invertY;};var resetViewport=function(){ctx.setTransform(1,0,0,1,0,0);ctx.scale(1,-1);var bedWidth=renderOptions["bed"]["x"];var bedHeight=renderOptions["bed"]["y"];if(renderOptions["bed"]["circular"]){bedWidth=bedHeight=renderOptions["bed"]["r"]*2;}
var viewportRatio=Math.min((canvas.width-10)/bedWidth,(canvas.height-10)/bedHeight);var translationX,translationY;if(renderOptions["bed"]["circular"]||renderOptions["bed"]["centeredOrigin"]){translationX=canvas.width/2;translationY=canvas.height/2;}else{translationX=(canvas.width-bedWidth*viewportRatio)/2;translationY=bedHeight*viewportRatio+
(canvas.height-bedHeight*viewportRatio)/2;}
ctx.translate(translationX,-translationY);ctx.scale(viewportRatio,viewportRatio);lineWidthFactor=1/viewportRatio;offsetModelX=0;offsetModelY=0;offsetBedX=0;offsetBedY=0;};return{init:function(){startCanvas();resetViewport();initialized=true;},setOption:function(options){var mustRefresh=false;var mustReset=false;var mustReapplyPatches=false;var dirty=false;for(var opt in options){if(!renderOptions.hasOwnProperty(opt)||!options.hasOwnProperty(opt))
continue;if(options[opt]===undefined)continue;if(renderOptions[opt]==options[opt])continue;dirty=true;renderOptions[opt]=options[opt];if($.inArray(opt,["moveModel","centerViewport","zoomInOnModel","bed","invertAxes","onViewportChange","chromeArcFix"])>-1){mustRefresh=true;}
if($.inArray(opt,["bed","onViewportChange"])>-1){mustReset=true;}
if($.inArray(opt,["chromeArcFix"])>-1){mustReapplyPatches=true;}}
if(!dirty)return;if(initialized){if(mustReset){resetViewport();}
if(mustReapplyPatches){applyContextPatches();}
if(mustRefresh){this.refresh();}else{reRender();}}},getOptions:function(){return renderOptions;},debugGetModel:function(){return model;},render:function(layerNum,fromProgress,toProgress){if(!initialized)this.init();layerNumStore=layerNum;progressStore.from=fromProgress;progressStore.to=toProgress;reRender();},getModelNumLayers:function(){return model?model.length:1;},getLayerNumSegments:function(layer){if(model){return model[layer]?getLayer(layer).length:1;}else{return 1;}},getLayer:function(layer){return getLayer(layer);},clear:function(){offsetModelX=0;offsetModelY=0;offsetBedX=0;offsetBedY=0;scaleX=1;scaleY=1;speeds=[];speedsByLayer={};modelInfo=undefined;layerCache=[];this.doRender([],0);},doRender:function(mdl,layerNum){model=mdl;modelInfo=undefined;prevX=0;prevY=0;if(!initialized)this.init();var toProgress=1;if(model&&model.length){modelInfo=GCODE.gCodeReader.getModelInfo();speeds=modelInfo.speeds;speedsByLayer=modelInfo.speedsByLayer;if(model[layerNum]){toProgress=getLayer(layerNum).length;}}
applyInversion();scaleX=1;scaleY=1;this.render(layerNum,0,toProgress);},refresh:function(layerNum){if(layerNum===undefined)layerNum=layerNumStore;this.doRender(model,layerNum);},resetViewport:function(){resetViewport();reRender();},getZ:function(layerNum){if(!model||!model[layerNum]){return"-1";}
var cmds=getLayer(layerNum);for(var i=0;i<cmds.length;i++){if(cmds[i].prevZ!==undefined)return cmds[i].prevZ;}
return"-1";}};})();
;

// source: plugin/gcodeviewer/js/lib/pako.js
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):((global=typeof globalThis!=="undefined"?globalThis:global||self),factory((global.pako={})));})(this,function(exports){"use strict";var Z_FIXED$1=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN$1=2;function zero$1(buf){var len=buf.length;while(--len>=0){buf[len]=0;}}
var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH$1=3;var MAX_MATCH$1=258;var LENGTH_CODES$1=29;var LITERALS$1=256;var L_CODES$1=LITERALS$1+1+LENGTH_CODES$1;var D_CODES$1=30;var BL_CODES$1=19;var HEAP_SIZE$1=2*L_CODES$1+1;var MAX_BITS$1=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);var extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);var extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);var bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);var static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);var _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);var base_length=new Array(LENGTH_CODES$1);zero$1(base_length);var base_dist=new Array(D_CODES$1);zero$1(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length;}
var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc;}
var d_code=function d_code(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)];};var put_short=function put_short(s,w){s.pending_buf[s.pending++]=w&0xff;s.pending_buf[s.pending++]=(w>>>8)&0xff;};var send_bits=function send_bits(s,value,length){if(s.bi_valid>Buf_size-length){s.bi_buf|=(value<<s.bi_valid)&0xffff;put_short(s,s.bi_buf);s.bi_buf=value>>(Buf_size-s.bi_valid);s.bi_valid+=length-Buf_size;}else{s.bi_buf|=(value<<s.bi_valid)&0xffff;s.bi_valid+=length;}};var send_code=function send_code(s,c,tree){send_bits(s,tree[c*2],tree[c*2+1]);};var bi_reverse=function bi_reverse(code,len){var res=0;do{res|=code&1;code>>>=1;res<<=1;}while(--len>0);return res>>>1;};var bi_flush=function bi_flush(s){if(s.bi_valid===16){put_short(s,s.bi_buf);s.bi_buf=0;s.bi_valid=0;}else if(s.bi_valid>=8){s.pending_buf[s.pending++]=s.bi_buf&0xff;s.bi_buf>>=8;s.bi_valid-=8;}};var gen_bitlen=function gen_bitlen(s,desc){var tree=desc.dyn_tree;var max_code=desc.max_code;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var extra=desc.stat_desc.extra_bits;var base=desc.stat_desc.extra_base;var max_length=desc.stat_desc.max_length;var h;var n,m;var bits;var xbits;var f;var overflow=0;for(bits=0;bits<=MAX_BITS$1;bits++){s.bl_count[bits]=0;}
tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;h<HEAP_SIZE$1;h++){n=s.heap[h];bits=tree[tree[n*2+1]*2+
1]+
1;if(bits>max_length){bits=max_length;overflow++;}
tree[n*2+1]=bits;if(n>max_code){continue;}
s.bl_count[bits]++;xbits=0;if(n>=base){xbits=extra[n-base];}
f=tree[n*2];s.opt_len+=f*(bits+xbits);if(has_stree){s.static_len+=f*(stree[n*2+1]+
xbits);}}
if(overflow===0){return;}
do{bits=max_length-1;while(s.bl_count[bits]===0){bits--;}
s.bl_count[bits]--;s.bl_count[bits+1]+=2;s.bl_count[max_length]--;overflow-=2;}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){m=s.heap[--h];if(m>max_code){continue;}
if(tree[m*2+1]!==bits){s.opt_len+=(bits-tree[m*2+1])*tree[m*2];tree[m*2+1]=bits;}
n--;}}};var gen_codes=function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS$1+1);var code=0;var bits;var n;for(bits=1;bits<=MAX_BITS$1;bits++){next_code[bits]=code=(code+bl_count[bits-1])<<1;}
for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0){continue;}
tree[n*2]=bi_reverse(next_code[len]++,len);}};var tr_static_init=function tr_static_init(){var n;var bits;var length;var code;var dist;var bl_count=new Array(MAX_BITS$1+1);length=0;for(code=0;code<LENGTH_CODES$1-1;code++){base_length[code]=length;for(n=0;n<1<<extra_lbits[code];n++){_length_code[length++]=code;}}
_length_code[length-1]=code;dist=0;for(code=0;code<16;code++){base_dist[code]=dist;for(n=0;n<1<<extra_dbits[code];n++){_dist_code[dist++]=code;}}
dist>>=7;for(;code<D_CODES$1;code++){base_dist[code]=dist<<7;for(n=0;n<1<<(extra_dbits[code]-7);n++){_dist_code[256+dist++]=code;}}
for(bits=0;bits<=MAX_BITS$1;bits++){bl_count[bits]=0;}
n=0;while(n<=143){static_ltree[n*2+1]=8;n++;bl_count[8]++;}
while(n<=255){static_ltree[n*2+1]=9;n++;bl_count[9]++;}
while(n<=279){static_ltree[n*2+1]=7;n++;bl_count[7]++;}
while(n<=287){static_ltree[n*2+1]=8;n++;bl_count[8]++;}
gen_codes(static_ltree,L_CODES$1+1,bl_count);for(n=0;n<D_CODES$1;n++){static_dtree[n*2+1]=5;static_dtree[n*2]=bi_reverse(n,5);}
static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS);};var init_block=function init_block(s){var n;for(n=0;n<L_CODES$1;n++){s.dyn_ltree[n*2]=0;}
for(n=0;n<D_CODES$1;n++){s.dyn_dtree[n*2]=0;}
for(n=0;n<BL_CODES$1;n++){s.bl_tree[n*2]=0;}
s.dyn_ltree[END_BLOCK*2]=1;s.opt_len=s.static_len=0;s.last_lit=s.matches=0;};var bi_windup=function bi_windup(s){if(s.bi_valid>8){put_short(s,s.bi_buf);}else if(s.bi_valid>0){s.pending_buf[s.pending++]=s.bi_buf;}
s.bi_buf=0;s.bi_valid=0;};var copy_block=function copy_block(s,buf,len,header){bi_windup(s);if(header){put_short(s,len);put_short(s,~len);}
s.pending_buf.set(s.window.subarray(buf,buf+len),s.pending);s.pending+=len;};var smaller=function smaller(tree,n,m,depth){var _n2=n*2;var _m2=m*2;return(tree[_n2]<tree[_m2]||(tree[_n2]===tree[_m2]&&depth[n]<=depth[m]));};var pqdownheap=function pqdownheap(s,tree,k){var v=s.heap[k];var j=k<<1;while(j<=s.heap_len){if(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)){j++;}
if(smaller(tree,v,s.heap[j],s.depth)){break;}
s.heap[k]=s.heap[j];k=j;j<<=1;}
s.heap[k]=v;};var compress_block=function compress_block(s,ltree,dtree){var dist;var lc;var lx=0;var code;var extra;if(s.last_lit!==0){do{dist=(s.pending_buf[s.d_buf+lx*2]<<8)|s.pending_buf[s.d_buf+lx*2+1];lc=s.pending_buf[s.l_buf+lx];lx++;if(dist===0){send_code(s,lc,ltree);}else{code=_length_code[lc];send_code(s,code+LITERALS$1+1,ltree);extra=extra_lbits[code];if(extra!==0){lc-=base_length[code];send_bits(s,lc,extra);}
dist--;code=d_code(dist);send_code(s,code,dtree);extra=extra_dbits[code];if(extra!==0){dist-=base_dist[code];send_bits(s,dist,extra);}}}while(lx<s.last_lit);}
send_code(s,END_BLOCK,ltree);};var build_tree=function build_tree(s,desc){var tree=desc.dyn_tree;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var elems=desc.stat_desc.elems;var n,m;var max_code=-1;var node;s.heap_len=0;s.heap_max=HEAP_SIZE$1;for(n=0;n<elems;n++){if(tree[n*2]!==0){s.heap[++s.heap_len]=max_code=n;s.depth[n]=0;}else{tree[n*2+1]=0;}}
while(s.heap_len<2){node=s.heap[++s.heap_len]=max_code<2?++max_code:0;tree[node*2]=1;s.depth[node]=0;s.opt_len--;if(has_stree){s.static_len-=stree[node*2+1];}}
desc.max_code=max_code;for(n=s.heap_len>>1;n>=1;n--){pqdownheap(s,tree,n);}
node=elems;do{n=s.heap[1];s.heap[1]=s.heap[s.heap_len--];pqdownheap(s,tree,1);m=s.heap[1];s.heap[--s.heap_max]=n;s.heap[--s.heap_max]=m;tree[node*2]=tree[n*2]+
tree[m*2];s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1;tree[n*2+1]=tree[m*2+1]=node;s.heap[1]=node++;pqdownheap(s,tree,1);}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1];gen_bitlen(s,desc);gen_codes(tree,max_code,s.bl_count);};var scan_tree=function scan_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3;}
tree[(max_code+1)*2+1]=0xffff;for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue;}else if(count<min_count){s.bl_tree[curlen*2]+=count;}else if(curlen!==0){if(curlen!==prevlen){s.bl_tree[curlen*2]++;}
s.bl_tree[REP_3_6*2]++;}else if(count<=10){s.bl_tree[REPZ_3_10*2]++;}else{s.bl_tree[REPZ_11_138*2]++;}
count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3;}else if(curlen===nextlen){max_count=6;min_count=3;}else{max_count=7;min_count=4;}}};var send_tree=function send_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3;}
for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue;}else if(count<min_count){do{send_code(s,curlen,s.bl_tree);}while(--count!==0);}else if(curlen!==0){if(curlen!==prevlen){send_code(s,curlen,s.bl_tree);count--;}
send_code(s,REP_3_6,s.bl_tree);send_bits(s,count-3,2);}else if(count<=10){send_code(s,REPZ_3_10,s.bl_tree);send_bits(s,count-3,3);}else{send_code(s,REPZ_11_138,s.bl_tree);send_bits(s,count-11,7);}
count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3;}else if(curlen===nextlen){max_count=6;min_count=3;}else{max_count=7;min_count=4;}}};var build_bl_tree=function build_bl_tree(s){var max_blindex;scan_tree(s,s.dyn_ltree,s.l_desc.max_code);scan_tree(s,s.dyn_dtree,s.d_desc.max_code);build_tree(s,s.bl_desc);for(max_blindex=BL_CODES$1-1;max_blindex>=3;max_blindex--){if(s.bl_tree[bl_order[max_blindex]*2+1]!==0){break;}}
s.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex;};var send_all_trees=function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5);send_bits(s,dcodes-1,5);send_bits(s,blcodes-4,4);for(rank=0;rank<blcodes;rank++){send_bits(s,s.bl_tree[bl_order[rank]*2+1],3);}
send_tree(s,s.dyn_ltree,lcodes-1);send_tree(s,s.dyn_dtree,dcodes-1);};var detect_data_type=function detect_data_type(s){var black_mask=0xf3ffc07f;var n;for(n=0;n<=31;n++,black_mask>>>=1){if(black_mask&1&&s.dyn_ltree[n*2]!==0){return Z_BINARY;}}
if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0){return Z_TEXT;}
for(n=32;n<LITERALS$1;n++){if(s.dyn_ltree[n*2]!==0){return Z_TEXT;}}
return Z_BINARY;};var static_init_done=false;var _tr_init$1=function _tr_init(s){if(!static_init_done){tr_static_init();static_init_done=true;}
s.l_desc=new TreeDesc(s.dyn_ltree,static_l_desc);s.d_desc=new TreeDesc(s.dyn_dtree,static_d_desc);s.bl_desc=new TreeDesc(s.bl_tree,static_bl_desc);s.bi_buf=0;s.bi_valid=0;init_block(s);};var _tr_stored_block$1=function _tr_stored_block(s,buf,stored_len,last){send_bits(s,(STORED_BLOCK<<1)+(last?1:0),3);copy_block(s,buf,stored_len,true);};var _tr_align$1=function _tr_align(s){send_bits(s,STATIC_TREES<<1,3);send_code(s,END_BLOCK,static_ltree);bi_flush(s);};var _tr_flush_block$1=function _tr_flush_block(s,buf,stored_len,last){var opt_lenb,static_lenb;var max_blindex=0;if(s.level>0){if(s.strm.data_type===Z_UNKNOWN$1){s.strm.data_type=detect_data_type(s);}
build_tree(s,s.l_desc);build_tree(s,s.d_desc);max_blindex=build_bl_tree(s);opt_lenb=(s.opt_len+3+7)>>>3;static_lenb=(s.static_len+3+7)>>>3;if(static_lenb<=opt_lenb){opt_lenb=static_lenb;}}else{opt_lenb=static_lenb=stored_len+5;}
if(stored_len+4<=opt_lenb&&buf!==-1){_tr_stored_block$1(s,buf,stored_len,last);}else if(s.strategy===Z_FIXED$1||static_lenb===opt_lenb){send_bits(s,(STATIC_TREES<<1)+(last?1:0),3);compress_block(s,static_ltree,static_dtree);}else{send_bits(s,(DYN_TREES<<1)+(last?1:0),3);send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1);compress_block(s,s.dyn_ltree,s.dyn_dtree);}
init_block(s);if(last){bi_windup(s);}};var _tr_tally$1=function _tr_tally(s,dist,lc){s.pending_buf[s.d_buf+s.last_lit*2]=(dist>>>8)&0xff;s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&0xff;s.pending_buf[s.l_buf+s.last_lit]=lc&0xff;s.last_lit++;if(dist===0){s.dyn_ltree[lc*2]++;}else{s.matches++;dist--;s.dyn_ltree[(_length_code[lc]+LITERALS$1+1)*2]++;s.dyn_dtree[d_code(dist)*2]++;}
return s.last_lit===s.lit_bufsize-1;};var _tr_init_1=_tr_init$1;var _tr_stored_block_1=_tr_stored_block$1;var _tr_flush_block_1=_tr_flush_block$1;var _tr_tally_1=_tr_tally$1;var _tr_align_1=_tr_align$1;var trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};var adler32=function adler32(adler,buf,len,pos){var s1=(adler&0xffff)|0,s2=((adler>>>16)&0xffff)|0,n=0;while(len!==0){n=len>2000?2000:len;len-=n;do{s1=(s1+buf[pos++])|0;s2=(s2+s1)|0;}while(--n);s1%=65521;s2%=65521;}
return s1|(s2<<16)|0;};var adler32_1=adler32;var makeTable=function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?0xedb88320^(c>>>1):c>>>1;}
table[n]=c;}
return table;};var crcTable=new Uint32Array(makeTable());var crc32=function crc32(crc,buf,len,pos){var t=crcTable;var end=pos+len;crc^=-1;for(var i=pos;i<end;i++){crc=(crc>>>8)^t[(crc^buf[i])&0xff];}
return crc^-1;};var crc32_1=crc32;var messages={"2":"need dictionary","1":"stream end","0":"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var _tr_init=trees._tr_init,_tr_stored_block=trees._tr_stored_block,_tr_flush_block=trees._tr_flush_block,_tr_tally=trees._tr_tally,_tr_align=trees._tr_align;var Z_NO_FLUSH$2=constants$2.Z_NO_FLUSH,Z_PARTIAL_FLUSH=constants$2.Z_PARTIAL_FLUSH,Z_FULL_FLUSH$1=constants$2.Z_FULL_FLUSH,Z_FINISH$3=constants$2.Z_FINISH,Z_BLOCK$1=constants$2.Z_BLOCK,Z_OK$3=constants$2.Z_OK,Z_STREAM_END$3=constants$2.Z_STREAM_END,Z_STREAM_ERROR$2=constants$2.Z_STREAM_ERROR,Z_DATA_ERROR$2=constants$2.Z_DATA_ERROR,Z_BUF_ERROR$1=constants$2.Z_BUF_ERROR,Z_DEFAULT_COMPRESSION$1=constants$2.Z_DEFAULT_COMPRESSION,Z_FILTERED=constants$2.Z_FILTERED,Z_HUFFMAN_ONLY=constants$2.Z_HUFFMAN_ONLY,Z_RLE=constants$2.Z_RLE,Z_FIXED=constants$2.Z_FIXED,Z_DEFAULT_STRATEGY$1=constants$2.Z_DEFAULT_STRATEGY,Z_UNKNOWN=constants$2.Z_UNKNOWN,Z_DEFLATED$2=constants$2.Z_DEFLATED;var MAX_MEM_LEVEL=9;var MAX_WBITS$1=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=0x20;var INIT_STATE=42;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=0x03;var err=function err(strm,errorCode){strm.msg=messages[errorCode];return errorCode;};var rank=function rank(f){return(f<<1)-(f>4?9:0);};var zero=function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0;}};var HASH_ZLIB=function HASH_ZLIB(s,prev,data){return((prev<<s.hash_shift)^data)&s.hash_mask;};var HASH=HASH_ZLIB;var flush_pending=function flush_pending(strm){var s=strm.state;var len=s.pending;if(len>strm.avail_out){len=strm.avail_out;}
if(len===0){return;}
strm.output.set(s.pending_buf.subarray(s.pending_out,s.pending_out+len),strm.next_out);strm.next_out+=len;s.pending_out+=len;strm.total_out+=len;strm.avail_out-=len;s.pending-=len;if(s.pending===0){s.pending_out=0;}};var flush_block_only=function flush_block_only(s,last){_tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last);s.block_start=s.strstart;flush_pending(s.strm);};var put_byte=function put_byte(s,b){s.pending_buf[s.pending++]=b;};var putShortMSB=function putShortMSB(s,b){s.pending_buf[s.pending++]=(b>>>8)&0xff;s.pending_buf[s.pending++]=b&0xff;};var read_buf=function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size){len=size;}
if(len===0){return 0;}
strm.avail_in-=len;buf.set(strm.input.subarray(strm.next_in,strm.next_in+len),start);if(strm.state.wrap===1){strm.adler=adler32_1(strm.adler,buf,len,start);}else if(strm.state.wrap===2){strm.adler=crc32_1(strm.adler,buf,len,start);}
strm.next_in+=len;strm.total_in+=len;return len;};var longest_match=function longest_match(s,cur_match){var chain_length=s.max_chain_length;var scan=s.strstart;var match;var len;var best_len=s.prev_length;var nice_match=s.nice_match;var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0;var _win=s.window;var wmask=s.w_mask;var prev=s.prev;var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match){chain_length>>=2;}
if(nice_match>s.lookahead){nice_match=s.lookahead;}
do{match=cur_match;if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue;}
scan+=2;match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break;}
scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len];}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len;}
return s.lookahead;};var fill_window=function fill_window(s){var _w_size=s.w_size;var p,n,m,more,str;do{more=s.window_size-s.lookahead-s.strstart;if(s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){s.window.set(s.window.subarray(_w_size,_w_size+_w_size),0);s.match_start-=_w_size;s.strstart-=_w_size;s.block_start-=_w_size;n=s.hash_size;p=n;do{m=s.head[--p];s.head[p]=m>=_w_size?m-_w_size:0;}while(--n);n=_w_size;p=n;do{m=s.prev[--p];s.prev[p]=m>=_w_size?m-_w_size:0;}while(--n);more+=_w_size;}
if(s.strm.avail_in===0){break;}
n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more);s.lookahead+=n;if(s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert;s.ins_h=s.window[str];s.ins_h=HASH(s,s.ins_h,s.window[str+1]);while(s.insert){s.ins_h=HASH(s,s.ins_h,s.window[str+MIN_MATCH-1]);s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;s.insert--;if(s.lookahead+s.insert<MIN_MATCH){break;}}}}while(s.lookahead<MIN_LOOKAHEAD&&s.strm.avail_in!==0);};var deflate_stored=function deflate_stored(s,flush){var max_block_size=0xffff;if(max_block_size>s.pending_buf_size-5){max_block_size=s.pending_buf_size-5;}
for(;;){if(s.lookahead<=1){fill_window(s);if(s.lookahead===0&&flush===Z_NO_FLUSH$2){return BS_NEED_MORE;}
if(s.lookahead===0){break;}}
s.strstart+=s.lookahead;s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){s.lookahead=s.strstart-max_start;s.strstart=max_start;flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}}
s.insert=0;if(flush===Z_FINISH$3){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED;}
return BS_FINISH_DONE;}
if(s.strstart>s.block_start){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
return BS_NEED_MORE;};var deflate_fast=function deflate_fast(s,flush){var hash_head;var bflush;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH$2){return BS_NEED_MORE;}
if(s.lookahead===0){break;}}
hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+MIN_MATCH-1]);hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart;}
if(hash_head!==0&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);}
if(s.match_length>=MIN_MATCH){bflush=_tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;if(s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do{s.strstart++;s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+MIN_MATCH-1]);hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart;}while(--s.match_length!==0);s.strstart++;}else{s.strstart+=s.match_length;s.match_length=0;s.ins_h=s.window[s.strstart];s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+1]);}}else{bflush=_tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;}
if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}}
s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH$3){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED;}
return BS_FINISH_DONE;}
if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
return BS_BLOCK_DONE;};var deflate_slow=function deflate_slow(s,flush){var hash_head;var bflush;var max_insert;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH$2){return BS_NEED_MORE;}
if(s.lookahead===0){break;}}
hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+MIN_MATCH-1]);hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart;}
s.prev_length=s.match_length;s.prev_match=s.match_start;s.match_length=MIN_MATCH-1;if(hash_head!==0&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);if(s.match_length<=5&&(s.strategy===Z_FILTERED||(s.match_length===MIN_MATCH&&s.strstart-s.match_start>4096))){s.match_length=MIN_MATCH-1;}}
if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH;bflush=_tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH);s.lookahead-=s.prev_length-1;s.prev_length-=2;do{if(++s.strstart<=max_insert){s.ins_h=HASH(s,s.ins_h,s.window[s.strstart+MIN_MATCH-1]);hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart;}}while(--s.prev_length!==0);s.match_available=0;s.match_length=MIN_MATCH-1;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}}else if(s.match_available){bflush=_tr_tally(s,0,s.window[s.strstart-1]);if(bflush){flush_block_only(s,false);}
s.strstart++;s.lookahead--;if(s.strm.avail_out===0){return BS_NEED_MORE;}}else{s.match_available=1;s.strstart++;s.lookahead--;}}
if(s.match_available){bflush=_tr_tally(s,0,s.window[s.strstart-1]);s.match_available=0;}
s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH$3){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED;}
return BS_FINISH_DONE;}
if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
return BS_BLOCK_DONE;};var deflate_rle=function deflate_rle(s,flush){var bflush;var prev;var scan,strend;var _win=s.window;for(;;){if(s.lookahead<=MAX_MATCH){fill_window(s);if(s.lookahead<=MAX_MATCH&&flush===Z_NO_FLUSH$2){return BS_NEED_MORE;}
if(s.lookahead===0){break;}}
s.match_length=0;if(s.lookahead>=MIN_MATCH&&s.strstart>0){scan=s.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=MAX_MATCH-(strend-scan);if(s.match_length>s.lookahead){s.match_length=s.lookahead;}}}
if(s.match_length>=MIN_MATCH){bflush=_tr_tally(s,1,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;s.strstart+=s.match_length;s.match_length=0;}else{bflush=_tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;}
if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}}
s.insert=0;if(flush===Z_FINISH$3){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED;}
return BS_FINISH_DONE;}
if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
return BS_BLOCK_DONE;};var deflate_huff=function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){fill_window(s);if(s.lookahead===0){if(flush===Z_NO_FLUSH$2){return BS_NEED_MORE;}
break;}}
s.match_length=0;bflush=_tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}}
s.insert=0;if(flush===Z_FINISH$3){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED;}
return BS_FINISH_DONE;}
if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE;}}
return BS_BLOCK_DONE;};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func;}
var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];var lm_init=function lm_init(s){s.window_size=2*s.w_size;zero(s.head);s.max_lazy_match=configuration_table[s.level].max_lazy;s.good_match=configuration_table[s.level].good_length;s.nice_match=configuration_table[s.level].nice_length;s.max_chain_length=configuration_table[s.level].max_chain;s.strstart=0;s.block_start=0;s.lookahead=0;s.insert=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;s.ins_h=0;};function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED$2;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new Uint16Array(HEAP_SIZE*2);this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2);this.bl_tree=new Uint16Array((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new Uint16Array(MAX_BITS+1);this.heap=new Uint16Array(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new Uint16Array(2*L_CODES+1);zero(this.depth);this.l_buf=0;this.lit_bufsize=0;this.last_lit=0;this.d_buf=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0;}
var deflateResetKeep=function deflateResetKeep(strm){if(!strm||!strm.state){return err(strm,Z_STREAM_ERROR$2);}
strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;var s=strm.state;s.pending=0;s.pending_out=0;if(s.wrap<0){s.wrap=-s.wrap;}
s.status=s.wrap?INIT_STATE:BUSY_STATE;strm.adler=s.wrap===2?0:1;s.last_flush=Z_NO_FLUSH$2;_tr_init(s);return Z_OK$3;};var deflateReset=function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK$3){lm_init(strm.state);}
return ret;};var deflateSetHeader=function deflateSetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR$2;}
if(strm.state.wrap!==2){return Z_STREAM_ERROR$2;}
strm.state.gzhead=head;return Z_OK$3;};var deflateInit2=function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm){return Z_STREAM_ERROR$2;}
var wrap=1;if(level===Z_DEFAULT_COMPRESSION$1){level=6;}
if(windowBits<0){wrap=0;windowBits=-windowBits;}else if(windowBits>15){wrap=2;windowBits-=16;}
if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED$2||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED){return err(strm,Z_STREAM_ERROR$2);}
if(windowBits===8){windowBits=9;}
var s=new DeflateState();strm.state=s;s.strm=strm;s.wrap=wrap;s.gzhead=null;s.w_bits=windowBits;s.w_size=1<<s.w_bits;s.w_mask=s.w_size-1;s.hash_bits=memLevel+7;s.hash_size=1<<s.hash_bits;s.hash_mask=s.hash_size-1;s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH);s.window=new Uint8Array(s.w_size*2);s.head=new Uint16Array(s.hash_size);s.prev=new Uint16Array(s.w_size);s.lit_bufsize=1<<(memLevel+6);s.pending_buf_size=s.lit_bufsize*4;s.pending_buf=new Uint8Array(s.pending_buf_size);s.d_buf=1*s.lit_bufsize;s.l_buf=(1+2)*s.lit_bufsize;s.level=level;s.strategy=strategy;s.method=method;return deflateReset(strm);};var deflateInit=function deflateInit(strm,level){return deflateInit2(strm,level,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1);};var deflate$2=function deflate(strm,flush){var beg,val;if(!strm||!strm.state||flush>Z_BLOCK$1||flush<0){return strm?err(strm,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;}
var s=strm.state;if(!strm.output||(!strm.input&&strm.avail_in!==0)||(s.status===FINISH_STATE&&flush!==Z_FINISH$3)){return err(strm,strm.avail_out===0?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);}
s.strm=strm;var old_flush=s.last_flush;s.last_flush=flush;if(s.status===INIT_STATE){if(s.wrap===2){strm.adler=0;put_byte(s,31);put_byte(s,139);put_byte(s,8);if(!s.gzhead){put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,OS_CODE);s.status=BUSY_STATE;}else{put_byte(s,(s.gzhead.text?1:0)+
(s.gzhead.hcrc?2:0)+
(!s.gzhead.extra?0:4)+
(!s.gzhead.name?0:8)+
(!s.gzhead.comment?0:16));put_byte(s,s.gzhead.time&0xff);put_byte(s,(s.gzhead.time>>8)&0xff);put_byte(s,(s.gzhead.time>>16)&0xff);put_byte(s,(s.gzhead.time>>24)&0xff);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,s.gzhead.os&0xff);if(s.gzhead.extra&&s.gzhead.extra.length){put_byte(s,s.gzhead.extra.length&0xff);put_byte(s,(s.gzhead.extra.length>>8)&0xff);}
if(s.gzhead.hcrc){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending,0);}
s.gzindex=0;s.status=EXTRA_STATE;}}
else{var header=(Z_DEFLATED$2+((s.w_bits-8)<<4))<<8;var level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2){level_flags=0;}else if(s.level<6){level_flags=1;}else if(s.level===6){level_flags=2;}else{level_flags=3;}
header|=level_flags<<6;if(s.strstart!==0){header|=PRESET_DICT;}
header+=31-(header%31);s.status=BUSY_STATE;putShortMSB(s,header);if(s.strstart!==0){putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&0xffff);}
strm.adler=1;}}
if(s.status===EXTRA_STATE){if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&0xffff)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){break;}}
put_byte(s,s.gzhead.extra[s.gzindex]&0xff);s.gzindex++;}
if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
if(s.gzindex===s.gzhead.extra.length){s.gzindex=0;s.status=NAME_STATE;}}else{s.status=NAME_STATE;}}
if(s.status===NAME_STATE){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break;}}
if(s.gzindex<s.gzhead.name.length){val=s.gzhead.name.charCodeAt(s.gzindex++)&0xff;}else{val=0;}
put_byte(s,val);}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
if(val===0){s.gzindex=0;s.status=COMMENT_STATE;}}else{s.status=COMMENT_STATE;}}
if(s.status===COMMENT_STATE){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break;}}
if(s.gzindex<s.gzhead.comment.length){val=s.gzhead.comment.charCodeAt(s.gzindex++)&0xff;}else{val=0;}
put_byte(s,val);}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32_1(strm.adler,s.pending_buf,s.pending-beg,beg);}
if(val===0){s.status=HCRC_STATE;}}else{s.status=HCRC_STATE;}}
if(s.status===HCRC_STATE){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size){flush_pending(strm);}
if(s.pending+2<=s.pending_buf_size){put_byte(s,strm.adler&0xff);put_byte(s,(strm.adler>>8)&0xff);strm.adler=0;s.status=BUSY_STATE;}}else{s.status=BUSY_STATE;}}
if(s.pending!==0){flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK$3;}}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH$3){return err(strm,Z_BUF_ERROR$1);}
if(s.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR$1);}
if(strm.avail_in!==0||s.lookahead!==0||(flush!==Z_NO_FLUSH$2&&s.status!==FINISH_STATE)){var bstate=s.strategy===Z_HUFFMAN_ONLY?deflate_huff(s,flush):s.strategy===Z_RLE?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s.status=FINISH_STATE;}
if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s.last_flush=-1;}
return Z_OK$3;}
if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH){_tr_align(s);}else if(flush!==Z_BLOCK$1){_tr_stored_block(s,0,0,false);if(flush===Z_FULL_FLUSH$1){zero(s.head);if(s.lookahead===0){s.strstart=0;s.block_start=0;s.insert=0;}}}
flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK$3;}}}
if(flush!==Z_FINISH$3){return Z_OK$3;}
if(s.wrap<=0){return Z_STREAM_END$3;}
if(s.wrap===2){put_byte(s,strm.adler&0xff);put_byte(s,(strm.adler>>8)&0xff);put_byte(s,(strm.adler>>16)&0xff);put_byte(s,(strm.adler>>24)&0xff);put_byte(s,strm.total_in&0xff);put_byte(s,(strm.total_in>>8)&0xff);put_byte(s,(strm.total_in>>16)&0xff);put_byte(s,(strm.total_in>>24)&0xff);}else{putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&0xffff);}
flush_pending(strm);if(s.wrap>0){s.wrap=-s.wrap;}
return s.pending!==0?Z_OK$3:Z_STREAM_END$3;};var deflateEnd=function deflateEnd(strm){if(!strm||!strm.state){return Z_STREAM_ERROR$2;}
var status=strm.state.status;if(status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE){return err(strm,Z_STREAM_ERROR$2);}
strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR$2):Z_OK$3;};var deflateSetDictionary=function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;if(!strm||!strm.state){return Z_STREAM_ERROR$2;}
var s=strm.state;var wrap=s.wrap;if(wrap===2||(wrap===1&&s.status!==INIT_STATE)||s.lookahead){return Z_STREAM_ERROR$2;}
if(wrap===1){strm.adler=adler32_1(strm.adler,dictionary,dictLength,0);}
s.wrap=0;if(dictLength>=s.w_size){if(wrap===0){zero(s.head);s.strstart=0;s.block_start=0;s.insert=0;}
var tmpDict=new Uint8Array(s.w_size);tmpDict.set(dictionary.subarray(dictLength-s.w_size,dictLength),0);dictionary=tmpDict;dictLength=s.w_size;}
var avail=strm.avail_in;var next=strm.next_in;var input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary;fill_window(s);while(s.lookahead>=MIN_MATCH){var str=s.strstart;var n=s.lookahead-(MIN_MATCH-1);do{s.ins_h=HASH(s,s.ins_h,s.window[str+MIN_MATCH-1]);s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;}while(--n);s.strstart=str;s.lookahead=MIN_MATCH-1;fill_window(s);}
s.strstart+=s.lookahead;s.block_start=s.strstart;s.insert=s.lookahead;s.lookahead=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;strm.next_in=next;strm.input=input;strm.avail_in=avail;s.wrap=wrap;return Z_OK$3;};var deflateInit_1=deflateInit;var deflateInit2_1=deflateInit2;var deflateReset_1=deflateReset;var deflateResetKeep_1=deflateResetKeep;var deflateSetHeader_1=deflateSetHeader;var deflate_2$1=deflate$2;var deflateEnd_1=deflateEnd;var deflateSetDictionary_1=deflateSetDictionary;var deflateInfo="pako deflate (from Nodeca project)";var deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo:deflateInfo};function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function(obj){return typeof obj;};}else{_typeof=function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}
return _typeof(obj);}
var _has=function _has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key);};var assign=function assign(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source){continue;}
if(_typeof(source)!=="object"){throw new TypeError(source+"must be non-object");}
for(var p in source){if(_has(source,p)){obj[p]=source[p];}}}
return obj;};var flattenChunks=function flattenChunks(chunks){var len=0;for(var i=0,l=chunks.length;i<l;i++){len+=chunks[i].length;}
var result=new Uint8Array(len);for(var _i=0,pos=0,_l=chunks.length;_i<_l;_i++){var chunk=chunks[_i];result.set(chunk,pos);pos+=chunk.length;}
return result;};var common={assign:assign,flattenChunks:flattenChunks};var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,new Uint8Array(1));}catch(__){STR_APPLY_UIA_OK=false;}
var _utf8len=new Uint8Array(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1;}
_utf8len[254]=_utf8len[254]=1;var string2buf=function string2buf(str){if(typeof TextEncoder==="function"&&TextEncoder.prototype.encode){return new TextEncoder().encode(str);}
var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++){c=str.charCodeAt(m_pos);if((c&0xfc00)===0xd800&&m_pos+1<str_len){c2=str.charCodeAt(m_pos+1);if((c2&0xfc00)===0xdc00){c=0x10000+((c-0xd800)<<10)+(c2-0xdc00);m_pos++;}}
buf_len+=c<0x80?1:c<0x800?2:c<0x10000?3:4;}
buf=new Uint8Array(buf_len);for(i=0,m_pos=0;i<buf_len;m_pos++){c=str.charCodeAt(m_pos);if((c&0xfc00)===0xd800&&m_pos+1<str_len){c2=str.charCodeAt(m_pos+1);if((c2&0xfc00)===0xdc00){c=0x10000+((c-0xd800)<<10)+(c2-0xdc00);m_pos++;}}
if(c<0x80){buf[i++]=c;}else if(c<0x800){buf[i++]=0xc0|(c>>>6);buf[i++]=0x80|(c&0x3f);}else if(c<0x10000){buf[i++]=0xe0|(c>>>12);buf[i++]=0x80|((c>>>6)&0x3f);buf[i++]=0x80|(c&0x3f);}else{buf[i++]=0xf0|(c>>>18);buf[i++]=0x80|((c>>>12)&0x3f);buf[i++]=0x80|((c>>>6)&0x3f);buf[i++]=0x80|(c&0x3f);}}
return buf;};var buf2binstring=function buf2binstring(buf,len){if(len<65534){if(buf.subarray&&STR_APPLY_UIA_OK){return String.fromCharCode.apply(null,buf.length===len?buf:buf.subarray(0,len));}}
var result="";for(var i=0;i<len;i++){result+=String.fromCharCode(buf[i]);}
return result;};var buf2string=function buf2string(buf,max){var len=max||buf.length;if(typeof TextDecoder==="function"&&TextDecoder.prototype.decode){return new TextDecoder().decode(buf.subarray(0,max));}
var i,out;var utf16buf=new Array(len*2);for(out=0,i=0;i<len;){var c=buf[i++];if(c<0x80){utf16buf[out++]=c;continue;}
var c_len=_utf8len[c];if(c_len>4){utf16buf[out++]=0xfffd;i+=c_len-1;continue;}
c&=c_len===2?0x1f:c_len===3?0x0f:0x07;while(c_len>1&&i<len){c=(c<<6)|(buf[i++]&0x3f);c_len--;}
if(c_len>1){utf16buf[out++]=0xfffd;continue;}
if(c<0x10000){utf16buf[out++]=c;}else{c-=0x10000;utf16buf[out++]=0xd800|((c>>10)&0x3ff);utf16buf[out++]=0xdc00|(c&0x3ff);}}
return buf2binstring(utf16buf,out);};var utf8border=function utf8border(buf,max){max=max||buf.length;if(max>buf.length){max=buf.length;}
var pos=max-1;while(pos>=0&&(buf[pos]&0xc0)===0x80){pos--;}
if(pos<0){return max;}
if(pos===0){return max;}
return pos+_utf8len[buf[pos]]>max?pos:max;};var strings={string2buf:string2buf,buf2string:buf2string,utf8border:utf8border};function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0;}
var zstream=ZStream;var toString$1=Object.prototype.toString;var Z_NO_FLUSH$1=constants$2.Z_NO_FLUSH,Z_SYNC_FLUSH=constants$2.Z_SYNC_FLUSH,Z_FULL_FLUSH=constants$2.Z_FULL_FLUSH,Z_FINISH$2=constants$2.Z_FINISH,Z_OK$2=constants$2.Z_OK,Z_STREAM_END$2=constants$2.Z_STREAM_END,Z_DEFAULT_COMPRESSION=constants$2.Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY=constants$2.Z_DEFAULT_STRATEGY,Z_DEFLATED$1=constants$2.Z_DEFLATED;function Deflate$1(options){this.options=common.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},options||{});var opt=this.options;if(opt.raw&&opt.windowBits>0){opt.windowBits=-opt.windowBits;}else if(opt.gzip&&opt.windowBits>0&&opt.windowBits<16){opt.windowBits+=16;}
this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream();this.strm.avail_out=0;var status=deflate_1$2.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy);if(status!==Z_OK$2){throw new Error(messages[status]);}
if(opt.header){deflate_1$2.deflateSetHeader(this.strm,opt.header);}
if(opt.dictionary){var dict;if(typeof opt.dictionary==="string"){dict=strings.string2buf(opt.dictionary);}else if(toString$1.call(opt.dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(opt.dictionary);}else{dict=opt.dictionary;}
status=deflate_1$2.deflateSetDictionary(this.strm,dict);if(status!==Z_OK$2){throw new Error(messages[status]);}
this._dict_set=true;}}
Deflate$1.prototype.push=function(data,flush_mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var status,_flush_mode;if(this.ended){return false;}
if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH$2:Z_NO_FLUSH$1;if(typeof data==="string"){strm.input=strings.string2buf(data);}else if(toString$1.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data);}else{strm.input=data;}
strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize;}
if((_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue;}
status=deflate_1$2.deflate(strm,_flush_mode);if(status===Z_STREAM_END$2){if(strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out));}
status=deflate_1$2.deflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===Z_OK$2;}
if(strm.avail_out===0){this.onData(strm.output);continue;}
if(_flush_mode>0&&strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue;}
if(strm.avail_in===0)break;}
return true;};Deflate$1.prototype.onData=function(chunk){this.chunks.push(chunk);};Deflate$1.prototype.onEnd=function(status){if(status===Z_OK$2){this.result=common.flattenChunks(this.chunks);}
this.chunks=[];this.err=status;this.msg=this.strm.msg;};function deflate$1(input,options){var deflator=new Deflate$1(options);deflator.push(input,true);if(deflator.err){throw deflator.msg||messages[deflator.err];}
return deflator.result;}
function deflateRaw$1(input,options){options=options||{};options.raw=true;return deflate$1(input,options);}
function gzip$1(input,options){options=options||{};options.gzip=true;return deflate$1(input,options);}
var Deflate_1$1=Deflate$1;var deflate_2=deflate$1;var deflateRaw_1$1=deflateRaw$1;var gzip_1$1=gzip$1;var constants$1=constants$2;var deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};var BAD$1=30;var TYPE$1=12;var inffast=function inflate_fast(strm,start){var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;var state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8;}
here=lcode[hold&lmask];dolen:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=(here>>>16)&0xff;if(op===0){output[_out++]=here&0xffff;}else if(op&16){len=here&0xffff;op&=15;if(op){if(bits<op){hold+=input[_in++]<<bits;bits+=8;}
len+=hold&((1<<op)-1);hold>>>=op;bits-=op;}
if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8;}
here=dcode[hold&dmask];dodist:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=(here>>>16)&0xff;if(op&16){dist=here&0xffff;op&=15;if(bits<op){hold+=input[_in++]<<bits;bits+=8;if(bits<op){hold+=input[_in++]<<bits;bits+=8;}}
dist+=hold&((1<<op)-1);if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD$1;break top;}
hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD$1;break top;}}
from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op<len){len-=op;do{output[_out++]=s_window[from++];}while(--op);from=_out-dist;from_source=output;}}else if(wnext<op){from+=wsize+wnext-op;op-=wnext;if(op<len){len-=op;do{output[_out++]=s_window[from++];}while(--op);from=0;if(wnext<len){op=wnext;len-=op;do{output[_out++]=s_window[from++];}while(--op);from=_out-dist;from_source=output;}}}else{from+=wnext-op;if(op<len){len-=op;do{output[_out++]=s_window[from++];}while(--op);from=_out-dist;from_source=output;}}
while(len>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3;}
if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++];}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3;}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++];}}}}else if((op&64)===0){here=dcode[(here&0xffff)+(hold&((1<<op)-1))];continue dodist;}else{strm.msg="invalid distance code";state.mode=BAD$1;break top;}
break;}}else if((op&64)===0){here=lcode[(here&0xffff)+(hold&((1<<op)-1))];continue dolen;}else if(op&32){state.mode=TYPE$1;break top;}else{strm.msg="invalid literal/length code";state.mode=BAD$1;break top;}
break;}}while(_in<last&&_out<end);len=bits>>3;_in-=len;bits-=len<<3;hold&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold;state.bits=bits;return;};var MAXBITS=15;var ENOUGH_LENS$1=852;var ENOUGH_DISTS$1=592;var CODES$1=0;var LENS$1=1;var DISTS$1=2;var lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]);var lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]);var dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]);var dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var inflate_table=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var bits=opts.bits;var len=0;var sym=0;var min=0,max=0;var root=0;var curr=0;var drop=0;var left=0;var used=0;var huff=0;var incr;var fill;var low;var mask;var next;var base=null;var base_index=0;var end;var count=new Uint16Array(MAXBITS+1);var offs=new Uint16Array(MAXBITS+1);var extra=null;var extra_index=0;var here_bits,here_op,here_val;for(len=0;len<=MAXBITS;len++){count[len]=0;}
for(sym=0;sym<codes;sym++){count[lens[lens_index+sym]]++;}
root=bits;for(max=MAXBITS;max>=1;max--){if(count[max]!==0){break;}}
if(root>max){root=max;}
if(max===0){table[table_index++]=(1<<24)|(64<<16)|0;table[table_index++]=(1<<24)|(64<<16)|0;opts.bits=1;return 0;}
for(min=1;min<max;min++){if(count[min]!==0){break;}}
if(root<min){root=min;}
left=1;for(len=1;len<=MAXBITS;len++){left<<=1;left-=count[len];if(left<0){return-1;}}
if(left>0&&(type===CODES$1||max!==1)){return-1;}
offs[1]=0;for(len=1;len<MAXBITS;len++){offs[len+1]=offs[len]+count[len];}
for(sym=0;sym<codes;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym;}}
if(type===CODES$1){base=extra=work;end=19;}else if(type===LENS$1){base=lbase;base_index-=257;extra=lext;extra_index-=257;end=256;}else{base=dbase;extra=dext;end=-1;}
huff=0;sym=0;len=min;next=table_index;curr=root;drop=0;low=-1;used=1<<root;mask=used-1;if((type===LENS$1&&used>ENOUGH_LENS$1)||(type===DISTS$1&&used>ENOUGH_DISTS$1)){return 1;}
for(;;){here_bits=len-drop;if(work[sym]<end){here_op=0;here_val=work[sym];}else if(work[sym]>end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]];}else{here_op=32+64;here_val=0;}
incr=1<<(len-drop);fill=1<<curr;min=fill;do{fill-=incr;table[next+(huff>>drop)+fill]=(here_bits<<24)|(here_op<<16)|here_val|0;}while(fill!==0);incr=1<<(len-1);while(huff&incr){incr>>=1;}
if(incr!==0){huff&=incr-1;huff+=incr;}else{huff=0;}
sym++;if(--count[len]===0){if(len===max){break;}
len=lens[lens_index+work[sym]];}
if(len>root&&(huff&mask)!==low){if(drop===0){drop=root;}
next+=min;curr=len-drop;left=1<<curr;while(curr+drop<max){left-=count[curr+drop];if(left<=0){break;}
curr++;left<<=1;}
used+=1<<curr;if((type===LENS$1&&used>ENOUGH_LENS$1)||(type===DISTS$1&&used>ENOUGH_DISTS$1)){return 1;}
low=huff&mask;table[low]=(root<<24)|(curr<<16)|(next-table_index)|0;}}
if(huff!==0){table[next+huff]=((len-drop)<<24)|(64<<16)|0;}
opts.bits=root;return 0;};var inftrees=inflate_table;var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH$1=constants$2.Z_FINISH,Z_BLOCK=constants$2.Z_BLOCK,Z_TREES=constants$2.Z_TREES,Z_OK$1=constants$2.Z_OK,Z_STREAM_END$1=constants$2.Z_STREAM_END,Z_NEED_DICT$1=constants$2.Z_NEED_DICT,Z_STREAM_ERROR$1=constants$2.Z_STREAM_ERROR,Z_DATA_ERROR$1=constants$2.Z_DATA_ERROR,Z_MEM_ERROR$1=constants$2.Z_MEM_ERROR,Z_BUF_ERROR=constants$2.Z_BUF_ERROR,Z_DEFLATED=constants$2.Z_DEFLATED;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;var zswap32=function zswap32(q){return(((q>>>24)&0xff)+
((q>>>8)&0xff00)+
((q&0xff00)<<8)+
((q&0xff)<<24));};function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new Uint16Array(320);this.work=new Uint16Array(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0;}
var inflateResetKeep=function inflateResetKeep(strm){if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
var state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1;}
state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new Int32Array(ENOUGH_LENS);state.distcode=state.distdyn=new Int32Array(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK$1;};var inflateReset=function inflateReset(strm){if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
var state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm);};var inflateReset2=function inflateReset2(strm,windowBits){var wrap;if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
var state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits;}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15;}}
if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR$1;}
if(state.window!==null&&state.wbits!==windowBits){state.window=null;}
state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm);};var inflateInit2=function inflateInit2(strm,windowBits){if(!strm){return Z_STREAM_ERROR$1;}
var state=new InflateState();strm.state=state;state.window=null;var ret=inflateReset2(strm,windowBits);if(ret!==Z_OK$1){strm.state=null;}
return ret;};var inflateInit=function inflateInit(strm){return inflateInit2(strm,DEF_WBITS);};var virgin=true;var lenfix,distfix;var fixedtables=function fixedtables(state){if(virgin){lenfix=new Int32Array(512);distfix=new Int32Array(32);var sym=0;while(sym<144){state.lens[sym++]=8;}
while(sym<256){state.lens[sym++]=9;}
while(sym<280){state.lens[sym++]=7;}
while(sym<288){state.lens[sym++]=8;}
inftrees(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5;}
inftrees(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false;}
state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5;};var updatewindow=function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0;state.window=new Uint8Array(state.wsize);}
if(copy>=state.wsize){state.window.set(src.subarray(end-state.wsize,end),0);state.wnext=0;state.whave=state.wsize;}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy;}
state.window.set(src.subarray(end-copy,end-copy+dist),state.wnext);copy-=dist;if(copy){state.window.set(src.subarray(end-copy,end),0);state.wnext=copy;state.whave=state.wsize;}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0;}
if(state.whave<state.wsize){state.whave+=dist;}}}
return 0;};var inflate$2=function inflate(strm,flush){var state;var input,output;var next;var put;var have,left;var hold;var bits;var _in,_out;var copy;var from;var from_source;var here=0;var here_bits,here_op,here_val;var last_bits,last_op,last_val;var len;var ret;var hbuf=new Uint8Array(4);var opts;var n;var order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!strm||!strm.state||!strm.output||(!strm.input&&strm.avail_in!==0)){return Z_STREAM_ERROR$1;}
state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO;}
put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK$1;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break;}
while(bits<16){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(state.wrap&2&&hold===0x8b1f){state.check=0;hbuf[0]=hold&0xff;hbuf[1]=(hold>>>8)&0xff;state.check=crc32_1(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break;}
state.flags=0;if(state.head){state.head.done=false;}
if(!(state.wrap&1)||(((hold&0xff)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break;}
if((hold&0x0f)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break;}
hold>>>=4;bits-=4;len=(hold&0x0f)+8;if(state.wbits===0){state.wbits=len;}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break;}
state.dmax=1<<state.wbits;strm.adler=state.check=1;state.mode=hold&0x200?DICTID:TYPE;hold=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.flags=hold;if((state.flags&0xff)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break;}
if(state.flags&0xe000){strm.msg="unknown header flags set";state.mode=BAD;break;}
if(state.head){state.head.text=(hold>>8)&1;}
if(state.flags&0x0200){hbuf[0]=hold&0xff;hbuf[1]=(hold>>>8)&0xff;state.check=crc32_1(state.check,hbuf,2,0);}
hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(state.head){state.head.time=hold;}
if(state.flags&0x0200){hbuf[0]=hold&0xff;hbuf[1]=(hold>>>8)&0xff;hbuf[2]=(hold>>>16)&0xff;hbuf[3]=(hold>>>24)&0xff;state.check=crc32_1(state.check,hbuf,4,0);}
hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(state.head){state.head.xflags=hold&0xff;state.head.os=hold>>8;}
if(state.flags&0x0200){hbuf[0]=hold&0xff;hbuf[1]=(hold>>>8)&0xff;state.check=crc32_1(state.check,hbuf,2,0);}
hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&0x0400){while(bits<16){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.length=hold;if(state.head){state.head.extra_len=hold;}
if(state.flags&0x0200){hbuf[0]=hold&0xff;hbuf[1]=(hold>>>8)&0xff;state.check=crc32_1(state.check,hbuf,2,0);}
hold=0;bits=0;}else if(state.head){state.head.extra=null;}
state.mode=EXTRA;case EXTRA:if(state.flags&0x0400){copy=state.length;if(copy>have){copy=have;}
if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Uint8Array(state.head.extra_len);}
state.head.extra.set(input.subarray(next,next+copy),len);}
if(state.flags&0x0200){state.check=crc32_1(state.check,input,copy,next);}
have-=copy;next+=copy;state.length-=copy;}
if(state.length){break inf_leave;}}
state.length=0;state.mode=NAME;case NAME:if(state.flags&0x0800){if(have===0){break inf_leave;}
copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len);}}while(len&&copy<have);if(state.flags&0x0200){state.check=crc32_1(state.check,input,copy,next);}
have-=copy;next+=copy;if(len){break inf_leave;}}else if(state.head){state.head.name=null;}
state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&0x1000){if(have===0){break inf_leave;}
copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.comment+=String.fromCharCode(len);}}while(len&&copy<have);if(state.flags&0x0200){state.check=crc32_1(state.check,input,copy,next);}
have-=copy;next+=copy;if(len){break inf_leave;}}else if(state.head){state.head.comment=null;}
state.mode=HCRC;case HCRC:if(state.flags&0x0200){while(bits<16){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(hold!==(state.check&0xffff)){strm.msg="header crc mismatch";state.mode=BAD;break;}
hold=0;bits=0;}
if(state.head){state.head.hcrc=(state.flags>>9)&1;state.head.done=true;}
strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
strm.adler=state.check=zswap32(hold);hold=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;return Z_NEED_DICT$1;}
strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush===Z_BLOCK||flush===Z_TREES){break inf_leave;}
case TYPEDO:if(state.last){hold>>>=bits&7;bits-=bits&7;state.mode=CHECK;break;}
while(bits<3){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.last=hold&0x01;hold>>>=1;bits-=1;switch(hold&0x03){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave;}
break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD;}
hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if((hold&0xffff)!==((hold>>>16)^0xffff)){strm.msg="invalid stored block lengths";state.mode=BAD;break;}
state.length=hold&0xffff;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave;}
case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have;}
if(copy>left){copy=left;}
if(copy===0){break inf_leave;}
output.set(input.subarray(next,next+copy),put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break;}
state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.nlen=(hold&0x1f)+257;hold>>>=5;bits-=5;state.ndist=(hold&0x1f)+1;hold>>>=5;bits-=5;state.ncode=(hold&0x0f)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break;}
state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.lens[order[state.have++]]=hold&0x07;hold>>>=3;bits-=3;}
while(state.have<19){state.lens[order[state.have++]]=0;}
state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inftrees(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break;}
state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold&((1<<state.lenbits)-1)];here_bits=here>>>24;here_op=(here>>>16)&0xff;here_val=here&0xffff;if(here_bits<=bits){break;}
if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(here_val<16){hold>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val;}else{if(here_val===16){n=here_bits+2;while(bits<n){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
hold>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break;}
len=state.lens[state.have-1];copy=3+(hold&0x03);hold>>>=2;bits-=2;}else if(here_val===17){n=here_bits+3;while(bits<n){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
hold>>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&0x07);hold>>>=3;bits-=3;}else{n=here_bits+7;while(bits<n){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
hold>>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&0x7f);hold>>>=7;bits-=7;}
if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break;}
while(copy--){state.lens[state.have++]=len;}}}
if(state.mode===BAD){break;}
if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break;}
state.lenbits=9;opts={bits:state.lenbits};ret=inftrees(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break;}
state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inftrees(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break;}
state.mode=LEN_;if(flush===Z_TREES){break inf_leave;}
case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inffast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1;}
break;}
state.back=0;for(;;){here=state.lencode[hold&((1<<state.lenbits)-1)];here_bits=here>>>24;here_op=(here>>>16)&0xff;here_val=here&0xffff;if(here_bits<=bits){break;}
if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(here_op&&(here_op&0xf0)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+
((hold&((1<<(last_bits+last_op))-1))>>last_bits)];here_bits=here>>>24;here_op=(here>>>16)&0xff;here_val=here&0xffff;if(last_bits+here_bits<=bits){break;}
if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
hold>>>=last_bits;bits-=last_bits;state.back+=last_bits;}
hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break;}
if(here_op&32){state.back=-1;state.mode=TYPE;break;}
if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break;}
state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.length+=hold&((1<<state.extra)-1);hold>>>=state.extra;bits-=state.extra;state.back+=state.extra;}
state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&((1<<state.distbits)-1)];here_bits=here>>>24;here_op=(here>>>16)&0xff;here_val=here&0xffff;if(here_bits<=bits){break;}
if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if((here_op&0xf0)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+
((hold&((1<<(last_bits+last_op))-1))>>last_bits)];here_bits=here>>>24;here_op=(here>>>16)&0xff;here_val=here&0xffff;if(last_bits+here_bits<=bits){break;}
if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
hold>>>=last_bits;bits-=last_bits;state.back+=last_bits;}
hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break;}
state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
state.offset+=hold&((1<<state.extra)-1);hold>>>=state.extra;bits-=state.extra;state.back+=state.extra;}
if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break;}
state.mode=MATCH;case MATCH:if(left===0){break inf_leave;}
copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break;}}
if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy;}else{from=state.wnext-copy;}
if(copy>state.length){copy=state.length;}
from_source=state.window;}else{from_source=output;from=put-state.offset;copy=state.length;}
if(copy>left){copy=left;}
left-=copy;state.length-=copy;do{output[put++]=from_source[from++];}while(--copy);if(state.length===0){state.mode=LEN;}
break;case LIT:if(left===0){break inf_leave;}
output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave;}
have--;hold|=input[next++]<<bits;bits+=8;}
_out-=left;strm.total_out+=_out;state.total+=_out;if(_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,put-_out):adler32_1(state.check,output,_out,put-_out);}
_out=left;if((state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break;}
hold=0;bits=0;}
state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave;}
have--;hold+=input[next++]<<bits;bits+=8;}
if(hold!==(state.total&0xffffffff)){strm.msg="incorrect length check";state.mode=BAD;break;}
hold=0;bits=0;}
state.mode=DONE;case DONE:ret=Z_STREAM_END$1;break inf_leave;case BAD:ret=Z_DATA_ERROR$1;break inf_leave;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1;}}
strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;if(state.wsize||(_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush!==Z_FINISH$1))){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out));}
_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&&_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,strm.next_out-_out):adler32_1(state.check,output,_out,strm.next_out-_out);}
strm.data_type=state.bits+
(state.last?64:0)+
(state.mode===TYPE?128:0)+
(state.mode===LEN_||state.mode===COPY_?256:0);if(((_in===0&&_out===0)||flush===Z_FINISH$1)&&ret===Z_OK$1){ret=Z_BUF_ERROR;}
return ret;};var inflateEnd=function inflateEnd(strm){if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
var state=strm.state;if(state.window){state.window=null;}
strm.state=null;return Z_OK$1;};var inflateGetHeader=function inflateGetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
var state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR$1;}
state.head=head;head.done=false;return Z_OK$1;};var inflateSetDictionary=function inflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var state;var dictid;var ret;if(!strm||!strm.state){return Z_STREAM_ERROR$1;}
state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR$1;}
if(state.mode===DICT){dictid=1;dictid=adler32_1(dictid,dictionary,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR$1;}}
ret=updatewindow(strm,dictionary,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR$1;}
state.havedict=1;return Z_OK$1;};var inflateReset_1=inflateReset;var inflateReset2_1=inflateReset2;var inflateResetKeep_1=inflateResetKeep;var inflateInit_1=inflateInit;var inflateInit2_1=inflateInit2;var inflate_2$1=inflate$2;var inflateEnd_1=inflateEnd;var inflateGetHeader_1=inflateGetHeader;var inflateSetDictionary_1=inflateSetDictionary;var inflateInfo="pako inflate (from Nodeca project)";var inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo:inflateInfo};function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false;}
var gzheader=GZheader;var toString=Object.prototype.toString;var Z_NO_FLUSH=constants$2.Z_NO_FLUSH,Z_FINISH=constants$2.Z_FINISH,Z_OK=constants$2.Z_OK,Z_STREAM_END=constants$2.Z_STREAM_END,Z_NEED_DICT=constants$2.Z_NEED_DICT,Z_STREAM_ERROR=constants$2.Z_STREAM_ERROR,Z_DATA_ERROR=constants$2.Z_DATA_ERROR,Z_MEM_ERROR=constants$2.Z_MEM_ERROR;function Inflate$1(options){this.options=common.assign({chunkSize:1024*64,windowBits:15,to:""},options||{});var opt=this.options;if(opt.raw&&opt.windowBits>=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15;}}
if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32;}
if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15;}}
this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream();this.strm.avail_out=0;var status=inflate_1$2.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK){throw new Error(messages[status]);}
this.header=new gzheader();inflate_1$2.inflateGetHeader(this.strm,this.header);if(opt.dictionary){if(typeof opt.dictionary==="string"){opt.dictionary=strings.string2buf(opt.dictionary);}else if(toString.call(opt.dictionary)==="[object ArrayBuffer]"){opt.dictionary=new Uint8Array(opt.dictionary);}
if(opt.raw){status=inflate_1$2.inflateSetDictionary(this.strm,opt.dictionary);if(status!==Z_OK){throw new Error(messages[status]);}}}}
Inflate$1.prototype.push=function(data,flush_mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_flush_mode,last_avail_out;if(this.ended)return false;if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH:Z_NO_FLUSH;if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data);}else{strm.input=data;}
strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize;}
status=inflate_1$2.inflate(strm,_flush_mode);if(status===Z_NEED_DICT&&dictionary){status=inflate_1$2.inflateSetDictionary(strm,dictionary);if(status===Z_OK){status=inflate_1$2.inflate(strm,_flush_mode);}else if(status===Z_DATA_ERROR){status=Z_NEED_DICT;}}
while(strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap>0&&data[strm.next_in]!==0){inflate_1$2.inflateReset(strm);status=inflate_1$2.inflate(strm,_flush_mode);}
switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:this.onEnd(status);this.ended=true;return false;}
last_avail_out=strm.avail_out;if(strm.next_out){if(strm.avail_out===0||status===Z_STREAM_END){if(this.options.to==="string"){var next_out_utf8=strings.utf8border(strm.output,strm.next_out);var tail=strm.next_out-next_out_utf8;var utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail)
strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0);this.onData(utf8str);}else{this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));}}}
if(status===Z_OK&&last_avail_out===0)continue;if(status===Z_STREAM_END){status=inflate_1$2.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return true;}
if(strm.avail_in===0)break;}
return true;};Inflate$1.prototype.onData=function(chunk){this.chunks.push(chunk);};Inflate$1.prototype.onEnd=function(status){if(status===Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("");}else{this.result=common.flattenChunks(this.chunks);}}
this.chunks=[];this.err=status;this.msg=this.strm.msg;};function inflate$1(input,options){var inflator=new Inflate$1(options);inflator.push(input);if(inflator.err)throw inflator.msg||messages[inflator.err];return inflator.result;}
function inflateRaw$1(input,options){options=options||{};options.raw=true;return inflate$1(input,options);}
var Inflate_1$1=Inflate$1;var inflate_2=inflate$1;var inflateRaw_1$1=inflateRaw$1;var ungzip$1=inflate$1;var constants=constants$2;var inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants:constants};var Deflate=deflate_1$1.Deflate,deflate=deflate_1$1.deflate,deflateRaw=deflate_1$1.deflateRaw,gzip=deflate_1$1.gzip;var Inflate=inflate_1$1.Inflate,inflate=inflate_1$1.inflate,inflateRaw=inflate_1$1.inflateRaw,ungzip=inflate_1$1.ungzip;var Deflate_1=Deflate;var deflate_1=deflate;var deflateRaw_1=deflateRaw;var gzip_1=gzip;var Inflate_1=Inflate;var inflate_1=inflate;var inflateRaw_1=inflateRaw;var ungzip_1=ungzip;var constants_1=constants$2;var pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};exports.Deflate=Deflate_1;exports.Inflate=Inflate_1;exports.constants=constants_1;exports["default"]=pako;exports.deflate=deflate_1;exports.deflateRaw=deflateRaw_1;exports.gzip=gzip_1;exports.inflate=inflate_1;exports.inflateRaw=inflateRaw_1;exports.ungzip=ungzip_1;Object.defineProperty(exports,"__esModule",{value:true});});
;

// source: plugin/logging/js/logging.js
$(function(){function LoggingViewModel(parameters){var self=this;self.loginState=parameters[0];self.access=parameters[1];self.availableLoggers=ko.observableArray();self.availableLoggersName=ko.observable();self.availableLoggersLevel=ko.observable();self.configuredLoggers=ko.observableArray();self.configuredLoggersChanged=false;self.serialLogEnabled=ko.observable();self.pluginTimingsLogEnabled=ko.observable();self.freeSpace=ko.observable(undefined);self.totalSpace=ko.observable(undefined);self.markedForDeletion=ko.observableArray([]);self.availableLoggersSorted=ko.computed(function(){return _.sortBy(self.availableLoggers());});self.listHelper=new ItemListHelper("logFiles",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;},modification:function(a,b){if(a["date"]>b["date"])return-1;if(a["date"]<b["date"])return 1;return 0;},size:function(a,b){if(a["size"]>b["size"])return-1;if(a["size"]<b["size"])return 1;return 0;}},{},"name",[],[],CONFIG_LOGFILESPERPAGE);self.requestData=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
OctoPrint.plugins.logging.get().done(self.fromResponse);};self.fromResponse=function(response){self.fromLogsResponse(response.logs);self.fromSetupResponse(response.setup);self.fromSerialLogResponse(response.serial_log);self.fromPluginTimingsLogResponse(response.plugintimings_log);};self.fromLogsResponse=function(response){if(!response)return;var files=response.files;if(files===undefined)return;self.listHelper.updateItems(files);self.freeSpace(response.free);self.totalSpace(response.total);};self.fromSetupResponse=function(response){if(!response)return;var levels=[];var configuredLoggers=[];_.each(response.levels,function(level,logger){var item={component:logger,level:ko.observable(level)};item.level.subscribe(function(){self.configuredLoggersHasChanged();});levels.push(item);configuredLoggers.push(logger);});var sortedLevels=_.sortBy(levels,function(o){return o.component;});self.configuredLoggers(sortedLevels);var availableLoggers=_.difference(response.loggers,configuredLoggers);self.availableLoggers(availableLoggers);self.configuredLoggersChanged=false;};self.fromSerialLogResponse=function(response){if(!response)return;self.serialLogEnabled(response.enabled);};self.fromPluginTimingsLogResponse=function(response){if(!response)return;self.pluginTimingsLogEnabled(response.enabled);};self.serialLogPopoverContent=function(){return self.popoverContent("serial.log");};self.pluginTimingsLogPopoverContent=function(){return self.popoverContent("plugintimings.log");};self.popoverContent=function(logfile){var free=self.freeSpace();var total=self.totalSpace();var content="<p>"+
_.sprintf(gettext("You currently have <code>%(logfile)s</code> enabled. Please remember to turn it off "+"again once your are done debugging whatever issue prompted you to turn it on."),{logfile:logfile})+"</p><p>"+
gettext("It can negatively impact print performance and also take up a lot of storage space "+"depending on how long you keep it enabled and thus should only be used for "+"debugging.")+"</p>";if(free!==undefined&&total!==undefined){content+="<p class='muted'><small><strong>"+
gettext("Log storage:")+"</strong> "+
formatSize(free)+" / "+
formatSize(total)+"</small></p>";}
return content;};self.configuredLoggersHasChanged=function(){self.configuredLoggersChanged=true;};self.addLogger=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
var component=self.availableLoggersName();if(!component){return;}
var level=self.availableLoggersLevel();self.configuredLoggers.push({component:component,level:ko.observable(level)});self.availableLoggers.remove(component);self.configuredLoggersHasChanged();};self.removeLogger=function(logger){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
self.configuredLoggers.remove(logger);self.availableLoggers.push(logger.component);self.configuredLoggersHasChanged();};self.removeFile=function(filename){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
var perform=function(){OctoPrint.plugins.logging.deleteLog(filename).done(self.requestData);};showConfirmationDialog(_.sprintf(gettext('You are about to delete log file "%(name)s".'),{name:_.escape(filename)}),perform);};self.markFilesOnPage=function(){self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(),"name"))));};self.markAllFiles=function(){self.markedForDeletion(_.map(self.listHelper.allItems,"name"));};self.clearMarkedFiles=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
self.markedForDeletion.removeAll();};self.removeMarkedFiles=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
var perform=function(){self._bulkRemove(self.markedForDeletion(),"files").done(function(){self.markedForDeletion.removeAll();});};showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."),{count:self.markedForDeletion().length}),perform);};self.enableBulkDownload=ko.pureComputed(function(){return self.markedForDeletion().length&&!self.bulkDownloadUrlTooLong();});self.bulkDownloadUrlTooLong=ko.pureComputed(function(){return BASEURL.length+self.bulkDownloadUrl().length>=2000;});self.bulkDownloadButtonUrl=ko.pureComputed(function(){var files=self.markedForDeletion();if(!files.length||self.bulkDownloadUrlTooLong()){return"javascript:void(0)";}
return self.bulkDownloadUrl();});self.bulkDownloadUrl=function(){var files=self.markedForDeletion();return OctoPrint.plugins.logging.bulkDownloadUrl(files);};self.onServerReconnect=self.onUserLoggedIn=self.onEventSettingsUpdated=self.onSettingsShown=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
self.requestData();};self.onSettingsBeforeSave=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
if(self.configuredLoggersChanged){console.log("ConfiguredLoggers has changed. Saving!");var levels={};_.each(self.configuredLoggers(),function(data){levels[data.component]=data.level();});OctoPrint.plugins.logging.updateLevels(levels);}else{console.log("ConfiguredLoggers has not changed. Not saving.");}};self._bulkRemove=function(files){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_LOGGING_MANAGE)){return;}
var title=gettext("Deleting log files");var message=_.sprintf(gettext("Deleting %(count)d log files..."),{count:files.length});var handler=function(filename){return OctoPrint.plugins.logging.deleteLog(filename).done(function(){deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."),{filename:_.escape(filename)}),true);}).fail(function(jqXHR){var short=_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."),{filename:_.escape(filename)});var long=_.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"),{filename:_.escape(filename),error:_.escape(jqXHR.responseText)});deferred.notify(short,long,false);});};var deferred=$.Deferred();var promise=deferred.promise();var options={title:title,message:message,max:files.length,output:true};showProgressModal(options,promise);var requests=[];_.each(files,function(filename){var request=handler(filename);requests.push(request);});$.when.apply($,_.map(requests,wrapPromiseWithAlways)).done(function(){deferred.resolve();self.requestData();});return promise;};}
OCTOPRINT_VIEWMODELS.push({construct:LoggingViewModel,additionalNames:["logsViewModel"],dependencies:["loginStateViewModel","accessViewModel"],elements:["#settings_plugin_logging","#navbar_plugin_logging_seriallog","#navbar_plugin_logging_plugintimingslog"]});});
;

// source: plugin/pluginmanager/js/pluginmanager.js
$(function(){function PluginManagerViewModel(parameters){var self=this;self.loginState=parameters[0];self.settingsViewModel=parameters[1];self.printerState=parameters[2];self.systemViewModel=parameters[3];self.access=parameters[4];self.piSupport=parameters[5];self.config_repositoryUrl=ko.observable();self.config_repositoryTtl=ko.observable();self.config_noticesUrl=ko.observable();self.config_noticesTtl=ko.observable();self.config_pipAdditionalArgs=ko.observable();self.config_pipForceUser=ko.observable();self.config_confirmUninstall=ko.observable();self.config_confirmDisable=ko.observable();self.configurationDialog=$("#settings_plugin_pluginmanager_configurationdialog");self.plugins=new ItemListHelper("plugin.pluginmanager.installedplugins",{name:function(a,b){if(a["name"].toLocaleLowerCase()<b["name"].toLocaleLowerCase())
return-1;if(a["name"].toLocaleLowerCase()>b["name"].toLocaleLowerCase())
return 1;return 0;}},{"bundled":function(item){return item.bundled;},"3rdparty":function(item){return!item.bundled;},"enabled":function(item){return item.enabled;},"disabled":function(item){return!item.enabled;}},"name",[],[["bundled","3rdparty"],["enabled","disabled"]],0);self.plugins.currentFilters.subscribe(function(){self.clearPluginsSelection();});self.pluginLookup={};self.repositoryplugins=new ItemListHelper("plugin.pluginmanager.repositoryplugins",{title:function(a,b){if(a.title.toLocaleLowerCase()<b.title.toLocaleLowerCase())
return-1;if(a.title.toLocaleLowerCase()>b.title.toLocaleLowerCase())
return 1;return 0;},published:function(a,b){if(a.published.toLocaleLowerCase()>b.published.toLocaleLowerCase())
return-1;if(a.published.toLocaleLowerCase()<b.published.toLocaleLowerCase())
return 1;return 0;},popularity:function(a,b){var countA=a.stats&&a.stats.instances_month?a.stats.instances_month:0;var countB=b.stats&&b.stats.instances_month?b.stats.instances_month:0;if(countA>countB)return-1;if(countA<countB)return 1;return 0;},release_date:function(a,b){var valA=a.github&&a.github.latest_release?a.github.latest_release.date.toLocaleLowerCase():"";var valB=b.github&&b.github.latest_release?b.github.latest_release.date.toLocaleLowerCase():"";if(valA>valB)return-1;if(valA<valB)return 1;return 0;},push_date:function(a,b){var valA=a.github?a.github.last_push.toLocaleLowerCase():"";var valB=b.github?b.github.last_push.toLocaleLowerCase():"";if(valA>valB)return-1;if(valA<valB)return 1;return 0;},stars:function(a,b){var valA=a.github?a.github.stars:0;var valB=b.github?b.github.stars:0;if(valA>valB)return-1;if(valA<valB)return 1;return 0;}},{filter_installed:function(plugin){return!self.installed(plugin);},filter_incompatible:function(plugin){return(plugin.is_compatible.octoprint&&plugin.is_compatible.os&&plugin.is_compatible.python);},filter_abandoned:function(plugin){return!plugin.abandoned;}},"popularity",["filter_installed","filter_incompatible"],[],0);self.orphans=new ItemListHelper("plugin.pluginmanager.orphans",{identifier:function(a,b){if(a["identifier"].toLocaleLowerCase()<b["identifier"].toLocaleLowerCase())
return-1;if(a["identifier"].toLocaleLowerCase()>b["identifier"].toLocaleLowerCase())
return 1;return 0;}},{},"identifier",[],[],0);self.selectedPlugins=ko.observableArray([]);self.uploadElement=$("#settings_plugin_pluginmanager_repositorydialog_upload");self.uploadButton=$("#settings_plugin_pluginmanager_repositorydialog_upload_start");self.repositoryAvailable=ko.observable(undefined);self.repositorySearchQuery=ko.observable();self.repositorySearchQuery.subscribe(function(){self.performRepositorySearch();});self.listingSearchQuery=ko.observable();self.listingSearchQuery.subscribe(function(){self.performListingSearch();});self.installUrl=ko.observable();self.uploadFilename=ko.observable();self.loglines=ko.observableArray([]);self.installedPlugins=ko.observableArray([]);self.followDependencyLinks=ko.observable(false);self.pipAvailable=ko.observable(true);self.pipVersion=ko.observable();self.pipInstallDir=ko.observable();self.pipUseUser=ko.observable();self.pipVirtualEnv=ko.observable();self.pipAdditionalArgs=ko.observable();self.pipPython=ko.observable();self.safeMode=ko.observable();self.online=ko.observable();self.supportedArchiveExtensions=ko.observableArray([]);self.supportedPythonExtensions=ko.observableArray([]);self.supportedJsonExtensions=ko.observableArray([]);var createExtensionsHelp=function(extensions){return _.reduce(extensions,function(result,ext,index){return(result+'"'+
ext+'"'+
(index<extensions.length-2?", ":index==extensions.length-2?" "+gettext("and")+" ":""));},"");};self.supportedExtensionsHelp=ko.pureComputed(function(){var archiveExts=createExtensionsHelp(self.supportedArchiveExtensions());var pythonExts=createExtensionsHelp(self.supportedPythonExtensions());var jsonExts=createExtensionsHelp(self.supportedJsonExtensions());return _.sprintf(gettext("This does not look like a valid plugin. Valid plugins should be "+"either archives installable via <code>pip</code> that "+"have the extension %(archiveExtensions)s, or single file python "+"plugins with the extension %(pythonExtensions)s, or a plugin list "+"export with the extension %(jsonExtensions)s."),{archiveExtensions:archiveExts,pythonExtensions:pythonExts,jsonExtensions:jsonExts});});self.requestError=ko.observable(false);self.pipUseUserString=ko.pureComputed(function(){return self.pipUseUser()?"yes":"no";});self.pipVirtualEnvString=ko.pureComputed(function(){return self.pipVirtualEnv()?"yes":"no";});self.working=ko.observable(false);self.workingTitle=ko.observable();self.workingDialog=undefined;self.workingOutput=undefined;self.toggling=ko.observable(false);self.restartCommandSpec=undefined;self.systemViewModel.systemActions.subscribe(function(){var lastResponse=self.systemViewModel.lastCommandResponse;if(!lastResponse||!lastResponse.core){self.restartCommandSpec=undefined;return;}
var restartSpec=_.filter(lastResponse.core,function(spec){return spec.action=="restart";});self.restartCommandSpec=restartSpec!=undefined&&restartSpec.length>0?restartSpec[0]:undefined;});self.noticeNotifications=[];self.hiddenNoticeNotifications={};self.noticeCount=ko.observable(0);self.notification=undefined;self.logContents={steps:[],action:{reload:false,refresh:false,reconnect:false}};self.noticeCountText=ko.pureComputed(function(){var count=self.noticeCount();if(count===0){return gettext("There are no plugin notices. Great!");}else if(count===1){return gettext("There is a plugin notice for one of your installed plugins.");}else{return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."),{count:count});}});self.enableManagement=ko.pureComputed(function(){return!self.printerState.isBusy();});self.enableBulk=function(data){return self.enableToggle(data,true)&&!data.bundled;};self.enableToggle=function(data,ignoreToggling){var command=self._getToggleCommand(data);var not_safemode_victim=!data.safe_mode_victim;var not_blacklisted=!data.blacklisted;var not_incompatible=!data.incompatible;ignoreToggling=!!ignoreToggling;return(self.enableManagement()&&(ignoreToggling||!self.toggling())&&(command==="disable"||(not_safemode_victim&&not_blacklisted&&not_incompatible))&&data.key!=="pluginmanager");};self.enableUninstall=function(data){return(self.enableManagement()&&(data.origin!=="entry_point"||self.pipAvailable())&&data.managable&&!data.bundled&&data.key!=="pluginmanager"&&!data.pending_uninstall);};self.enableCleanup=function(data){return(self.enableManagement()&&data.key!=="pluginmanager"&&!data.pending_uninstall);};self.enableRepoInstall=function(data){return(self.pipAvailable()&&!self.safeMode()&&!self.throttled()&&self.online()&&self.isCompatible(data));};self.throttled=ko.pureComputed(function(){return(self.piSupport&&self.piSupport.currentIssue()&&!self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled());});self.invalidUrl=ko.pureComputed(function(){var allowedUrlSchemes=["http","https","git","git+http","git+https","git+ssh","git+git","hg+http","hg+https","hg+static-http","hg+ssh","svn","svn+svn","svn+http","svn+https","svn+ssh","bzr+http","bzr+https","bzr+ssh","bzr+sftp","brz+ftp","bzr+lp"];var url=self.installUrl();var lowerUrl=url!==undefined?url.toLocaleLowerCase():undefined;var lowerUrlStartsWithScheme=function(scheme){return _.startsWith(lowerUrl,scheme+"://");};return(url!==undefined&&url.trim()!==""&&!_.any(allowedUrlSchemes,lowerUrlStartsWithScheme));});self.enableUrlInstall=ko.pureComputed(function(){var url=self.installUrl();return(self.enableManagement()&&self.pipAvailable()&&!self.safeMode()&&!self.throttled()&&self.online()&&url!==undefined&&url.trim()!==""&&!self.invalidUrl());});self.hasExtension=function(name,extensions){const lowerName=name.toLocaleLowerCase();return extensions.some((ext)=>lowerName.endsWith(ext));};self.invalidFile=ko.pureComputed(function(){var allowedFileExtensions=self.supportedArchiveExtensions().concat(self.supportedPythonExtensions()).concat(self.supportedJsonExtensions());var name=self.uploadFilename();return name!==undefined&&!self.hasExtension(name,allowedFileExtensions);});self.enableFileInstall=ko.pureComputed(function(){var name=self.uploadFilename();return(self.enableManagement()&&self.pipAvailable()&&!self.safeMode()&&!self.throttled()&&name!==undefined&&name.trim()!==""&&!self.invalidFile());});self.uploadElement.fileupload({dataType:"json",maxNumberOfFiles:1,autoUpload:false,add:function(e,data){if(data.files.length===0){return false;}
var name=data.files[0].name;self.uploadFilename(name);var isJsonFile=name!==undefined&&self.hasExtension(name,self.supportedJsonExtensions());self.uploadButton.unbind("click");self.uploadButton.bind("click",function(){const proceed=()=>{self.loginState.reauthenticateIfNecessary(()=>{self._markWorking(isJsonFile?gettext("Installing plugins..."):gettext("Installing plugin..."),isJsonFile?gettext("Installing plugins from uploaded file..."):gettext("Installing plugin from uploaded file..."));data.formData={dependency_links:self.followDependencyLinks()};data.submit();});};if(isJsonFile){showConfirmationDialog({title:gettext("Confirm installation of multiple plugins"),message:gettext("Please confirm you want to perform all plugins specified in the json file."),cancel:gettext("Cancel"),proceed:gettext("Install"),proceedClass:"primary",onproceed:proceed});}else{proceed();}
return false;});},done:function(e,data){var response=data.result;if(!response.in_progress){if(response.result){self._markDone();}else{self._markDone(response.reason);}}
self.uploadButton.unbind("click");self.uploadFilename(undefined);},fail:function(e,data){if(data&&data.errorThrown==="CONFLICT"){self._markDone("There's already another plugin install in progress.");}else{new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});self._markDone("Could not install plugin, unknown error.");}
self.uploadButton.unbind("click");self.uploadFilename(undefined);}});self.performListingSearch=function(){var query=self.listingSearchQuery();if(query!==undefined&&query.trim()!==""){query=query.toLocaleLowerCase();self.plugins.changeSearchFunction(function(entry){return(entry&&(entry["name"].toLocaleLowerCase().indexOf(query)>-1||(entry.description&&entry.description.toLocaleLowerCase().indexOf(query)>-1)));});}else{self.plugins.resetSearch();}};self.multiInstallQueue=ko.observableArray([]);self.queuedInstalls=ko.observableArray([]);self.multiInstallRunning=ko.observable(false);self.multiInstallInitialSize=ko.observable(0);self.multiInstallValid=function(){return(self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)&&self.pipAvailable()&&!self.safeMode()&&!self.throttled()&&self.online()&&self.multiInstallQueue().length>0&&self.multiInstallQueue().every(self.isCompatible));};self.repoInstallSelectedButtonText=function(){return self.multiInstallQueue().some(self.installed)?"(Re)install selected":"Install selected";};self.repoInstallSelectedConfirm=function(){if(!self.multiInstallValid())return;if(self.multiInstallQueue().length===1){self.installFromRepository(self.multiInstallQueue()[0]);return;}
var question="<ul>";self.multiInstallQueue().forEach(function(plugin){var action=self.installed(plugin)?gettext("Reinstall"):gettext("Install");question+=_.sprintf("<li>%(action)s <em><b>%(name)s@%(version)s</b></em></li>",{action:_.escape(action),name:_.escape(plugin.title),version:_.escape(plugin.github.latest_release.tag)});});question+="</ul>";showConfirmationDialog({title:gettext("Confirm installation of multiple plugins"),message:gettext("Please confirm you want to perform these actions:"),question:question,cancel:gettext("Cancel"),proceed:gettext("Install"),proceedClass:"primary",onproceed:self.startMultiInstall});};self.startMultiInstall=function(){if(self.multiInstallRunning()||!self.multiInstallValid())return;self.multiInstallRunning(true);self.multiInstallInitialSize(self.multiInstallQueue().length);self._markWorking(gettext("Installing multiple plugins"),gettext("Starting installation of multiple plugins..."));self.performMultiInstallJob();};self.performMultiInstallJob=function(){if(!self.multiInstallRunning()||self.multiInstallQueue().length===0)
return;var plugin=self.multiInstallQueue.pop();self.installFromRepository(plugin);};self.alertMultiInstallJobDone=function(response){if(!self.multiInstallRunning()||response.action!="install"||!response.result)
return;if(self.multiInstallQueue().length===0){self.installUrl("");self.multiInstallQueue([]);self.multiInstallRunning(false);self._markDone();}else{self.performMultiInstallJob();}};self.performRepositorySearch=function(){var query=self.repositorySearchQuery();if(query!==undefined&&query.trim()!==""){query=query.toLocaleLowerCase();self.repositoryplugins.changeSearchFunction(function(entry){return(entry&&(entry["title"].toLocaleLowerCase().indexOf(query)>-1||entry["description"].toLocaleLowerCase().indexOf(query)>-1));});}else{self.repositoryplugins.resetSearch();}
return false;};self.fromPluginsResponse=function(data,options){var evalNotices=options.eval_notices||false;var ignoreNoticeHidden=options.ignore_notice_hidden||false;var ignoreNoticeIgnored=options.ignore_notice_ignored||false;if(evalNotices)self._removeAllNoticeNotifications();var installedPlugins=[];var noticeCount=0;var lookup={};_.each(data,function(plugin){lookup[plugin.key]=plugin;installedPlugins.push(plugin.key);if(evalNotices&&plugin.notifications&&plugin.notifications.length){_.each(plugin.notifications,function(notification){noticeCount++;if(!ignoreNoticeIgnored&&self._isNoticeNotificationIgnored(plugin.key,notification.date))
return;if(!ignoreNoticeHidden&&self._isNoticeNotificationHidden(plugin.key,notification.date))
return;self._showPluginNotification(plugin,notification);});}});if(evalNotices)self.noticeCount(noticeCount);self.installedPlugins(installedPlugins);self.plugins.updateItems(data);self.pluginLookup=lookup;};self.fromOrphanResponse=function(data){var orphans=[];_.each(data,function(value,key){orphans.push({identifier:key,settings:value.settings,data:value.data});});self.orphans.updateItems(orphans);};self.fromRepositoryResponse=function(data){self.repositoryAvailable(data.available);if(data.available){self.repositoryplugins.updateItems(data.plugins);}else{self.repositoryplugins.updateItems([]);}};self.fromPipResponse=function(data){self.pipAvailable(data.available);if(data.available){self.pipVersion(data.version);self.pipInstallDir(data.install_dir);self.pipUseUser(data.use_user);self.pipVirtualEnv(data.virtual_env);self.pipAdditionalArgs(data.additional_args);self.pipPython(data.python);}else{self.pipVersion(undefined);self.pipInstallDir(undefined);self.pipUseUser(undefined);self.pipVirtualEnv(undefined);self.pipAdditionalArgs(undefined);}};self.fromSupportedExtensionsResponse=function(data){if(!data)return;self.supportedArchiveExtensions(data.archive||[]);self.supportedPythonExtensions(data.python||[]);self.supportedJsonExtensions(data.json||[]);};self.dataPluginsDeferred=undefined;self.requestPluginData=function(options){if(!_.isPlainObject(options)){options={};}
if(self.dataPluginsDeferred&&self.dataPluginsDeferred.state()==="pending"&&!!!options.refresh){return self.dataPluginsDeferred.promise();}
var deferred=new $.Deferred();if(!!!options.refresh){self.dataPluginsDeferred=deferred;}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){deferred.fail();return deferred.promise();}
OctoPrint.plugins.pluginmanager.getPlugins(!!options.refresh).fail(function(){self.requestError(true);deferred.reject();}).done(function(data){self.requestError(false);self.fromPluginsResponse(data.plugins,options);self.fromPipResponse(data.pip);self.fromSupportedExtensionsResponse(data.supported_extensions);self.safeMode(data.safe_mode||false);deferred.resolveWith(data);});return deferred.promise();};self.dataOrphansDeferred=undefined;self.requestOrphanData=function(options){if(!_.isPlainObject(options)){options={};}
if(self.dataOrphansDeferred&&self.dataOrphansDeferred.state()==="pending"&&!!!options.refresh){return self.dataOrphansDeferred.promise();}
var deferred=new $.Deferred();if(!!!options.refresh){self.dataOrphansDeferred=deferred;}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){deferred.fail();return deferred.promise();}
OctoPrint.plugins.pluginmanager.getOrphans(!!options.refresh).fail(function(){deferred.reject();}).done(function(data){self.fromOrphanResponse(data.orphans);deferred.resolveWith(data);});return deferred.promise();};self.dataRepositoryDeferred=undefined;self.requestRepositoryData=function(options){if(!_.isPlainObject(options)){options={};}
if(self.dataRepositoryDeferred&&self.dataRepositoryDeferred.state()==="pending"&&!!!options.refresh){return self.dataRepositoryDeferred.promise();}
var deferred=new $.Deferred();if(!!!options.refresh){self.dataRepositoryDeferred=deferred;}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){deferred.fail();return deferred.promise();}
OctoPrint.plugins.pluginmanager.getRepository(!!options.refresh,{ifModified:true}).fail(function(){deferred.reject();}).done(function(data,status,xhr){if(xhr.status===304)return;self.fromRepositoryResponse(data.repository);self.online(data.online!==undefined?data.online:true);deferred.resolveWith(data);});return deferred.promise();};self.togglePlugin=function(data){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){return;}
if(!self.enableManagement()){return;}
if(data.key==="pluginmanager")return;var onSuccess=function(){self.requestPluginData().always(function(){self.toggling(false);});},onError=function(){self.toggling(false);new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});};var performDisabling=function(){if(self.toggling())return;self.toggling(true);OctoPrint.plugins.pluginmanager.disable(data.key).done(onSuccess).fail(onError);};var performEnabling=function(){if(data.safe_mode_victim)return;if(self.toggling())return;self.toggling(true);OctoPrint.plugins.pluginmanager.enable(data.key).done(onSuccess).fail(onError);};if(self._getToggleCommand(data)==="enable"){performEnabling();}else{if(data.disabling_discouraged){var message=_.sprintf(gettext('You are about to disable "%(name)s".'),{name:_.escape(data.name)})+"</p><p>"+
data.disabling_discouraged;showConfirmationDialog({title:gettext("This is not recommended"),message:message,question:gettext("Do you still want to disable it?"),cancel:gettext("Keep enabled"),proceed:gettext("Disable anyway"),onproceed:performDisabling});}
else if(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()){showConfirmationDialog({message:_.sprintf(gettext('You are about to disable "%(name)s"'),{name:_.escape(data.name)}),cancel:gettext("Keep enabled"),proceed:gettext("Disable plugin"),onproceed:performDisabling,nofade:true});}else{performDisabling();}}};self._bulkOperation=function(plugins,title,message,successText,failureText,statusText,callback,alreadyCheck){var deferred=$.Deferred();var promise=deferred.promise();var options={title:title,message:_.sprintf(message,{count:plugins.length}),max:plugins.length,output:true};showProgressModal(options,promise);var handle=function(key){var d=$.Deferred();var plugin=self.pluginLookup[key];if(!plugin){deferred.notify(_.sprintf(gettext("Can't resolve plugin with key %(key)s, skipping..."),{key:key}),false);d.reject();return d.promise();}
if(!self.enableBulk(plugin)){deferred.notify(_.sprintf(gettext("Plugin %(plugin)s doesn't support bulk operations, skipping..."),{plugin:plugin.name||key}),false);d.reject();return d.promise();}
if(alreadyCheck(plugin)){deferred.notify(_.sprintf(gettext("Plugin %(plugin)s is already %(status)s (or pending), skipping..."),{plugin:plugin.name||key,status:statusText}),true);d.reject();return d.promise();}
callback(plugin).done(function(){deferred.notify(_.sprintf(successText,{plugin:plugin.name||key}),true);d.resolve();}).fail(function(){deferred.notify(_.sprintf(failureText,{plugin:plugin.name||key}),false);d.reject();});return d.promise();};var operations=[];_.each(plugins,function(key){operations.push(handle(key));});$.when.apply($,_.map(operations,wrapPromiseWithAlways)).done(function(){deferred.resolve();self.requestPluginData();});return promise;};self.enableSelectedPlugins=function(){if(self.selectedPlugins().length===0)return;var callback=function(plugin){return OctoPrint.plugins.pluginmanager.enable(plugin.key);};var check=function(plugin){return plugin.enabled||plugin.pending_enable;};self.toggling(true);self._bulkOperation(self.selectedPlugins(),gettext("Enabling plugins"),gettext("Enabling %(count)i plugins"),gettext("Enabled plugin %(plugin)s..."),gettext("Enabling plugin %(plugin)s failed, continuing..."),gettext("enabled"),callback,check).done(function(){self.selectedPlugins([]);}).always(function(){self.toggling(false);});};self.disableSelectedPlugins=function(){if(self.selectedPlugins().length===0)return;var callback=function(plugin){return OctoPrint.plugins.pluginmanager.disable(plugin.key);};var check=function(plugin){return!plugin.enabled||plugin.pending_disable;};self.toggling(true);self._bulkOperation(self.selectedPlugins(),gettext("Disabling plugins"),gettext("Disabling %(count)i plugins"),gettext("Disabled plugin %(plugin)s..."),gettext("Disabling plugin %(plugin)s failed, continuing..."),gettext("disabled"),callback,check).done(function(){self.selectedPlugins([]);}).always(function(){self.toggling(false);});};self.selectAllVisiblePlugins=function(){var selection=[];_.each(self.plugins.paginatedItems(),function(plugin){if(!self.enableBulk(plugin))return;selection.push(plugin.key);});self.selectedPlugins(selection);};self.clearPluginsSelection=function(){self.selectedPlugins([]);};self.showRepository=()=>{self.loginState.reauthenticateIfNecessary(()=>{self.repositoryDialog.modal({minHeight:function(){return Math.max($.fn.modal.defaults.maxHeight()-80,250);},show:true});});};self.pluginDetails=function(data){window.open(data.page);};self.installFromRepository=function(data){self.installPlugin(data.archive,data.title,self.installed(data)?data.id:undefined,data.follow_dependency_links||self.followDependencyLinks(),true);};self.removeFromQueue=function(plugin){var data={plugin:{command:self.installed(plugin)?"reinstall":"install",url:plugin.archive,dependency_links:plugin.follow_dependency_links||self.followDependencyLinks()}};OctoPrint.simpleApiCommand("pluginmanager","clear_queued_plugin",data).done(function(response){self.queuedInstalls(response.queued_installs);});};self.installPlugin=function(url,name,reinstall,followDependencyLinks,fromRepo){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)){return;}
if(self.throttled()){return;}
if(url===undefined){url=self.installUrl();}
if(!url)return;if(followDependencyLinks===undefined){followDependencyLinks=self.followDependencyLinks();}
self.loginState.reauthenticateIfNecessary(()=>{var workTitle,workText;if(!reinstall){workTitle=gettext("Installing plugin...");if(name){workText=_.sprintf(gettext('Installing plugin "%(name)s" from %(url)s...'),{url:_.escape(url),name:_.escape(name)});}else{workText=_.sprintf(gettext("Installing plugin from %(url)s..."),{url:_.escape(url)});}}else{workTitle=gettext("Reinstalling plugin...");workText=_.sprintf(gettext('Reinstalling plugin "%(name)s" from %(url)s...'),{url:_.escape(url),name:_.escape(name)});}
if(self.multiInstallRunning()){workTitle=_.sprintf("[%(index)d/%(total)d] ",{index:this.multiInstallInitialSize()-
self.multiInstallQueue().length,total:this.multiInstallInitialSize()})+workTitle;}
self._markWorking(workTitle,workText);var onSuccess=function(response){self.installUrl("");if(response.hasOwnProperty("queued_installs")){self.queuedInstalls(response.queued_installs);var text='<div class="row-fluid"><p>'+
gettext("The following plugins are queued to be installed.")+"</p><ul><li>"+
_.map(response.queued_installs,function(info){var plugin=ko.utils.arrayFirst(self.repositoryplugins.paginatedItems(),function(item){return item.archive===info.url;});return plugin.title;}).join("</li><li>")+"</li></ul></div>";if(typeof self.installQueuePopup!=="undefined"){self.installQueuePopup.update({text:text});if(self.installQueuePopup.state==="closed"){self.installQueuePopup.open();}}else{self.installQueuePopup=new PNotify({title:gettext("Plugin installs queued"),text:text,type:"notice"});}
if(self.multiInstallQueue().length>0){self.performMultiInstallJob();}else{self.multiInstallRunning(false);self.workingDialog.modal("hide");self._markDone();}}},onError=function(jqXHR){if(jqXHR.status===409){self._markDone("There's already another plugin install in progress.");}else{self._markDone("Could not install plugin, unknown error, please consult octoprint.log for details");new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});}};if(reinstall){OctoPrint.plugins.pluginmanager.reinstall(reinstall,url,followDependencyLinks,fromRepo).done(onSuccess).fail(onError);}else{OctoPrint.plugins.pluginmanager.install(url,followDependencyLinks,fromRepo).done(onSuccess).fail(onError);}});};self.uninstallPlugin=function(data){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){return;}
if(!self.enableUninstall(data)){return;}
if(data.bundled)return;if(data.key==="pluginmanager")return;var performUninstall=function(cleanup){self._markWorking(gettext("Uninstalling plugin..."),_.sprintf(gettext('Uninstalling plugin "%(name)s"'),{name:_.escape(data.name)}));OctoPrint.plugins.pluginmanager.uninstall(data.key,cleanup).done(function(){self.requestPluginData();}).fail(function(){new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});}).always(function(){self._markDone();});};showConfirmationDialog({message:_.sprintf(gettext('You are about to uninstall the plugin "%(name)s"'),{name:_.escape(data.name)}),cancel:gettext("Keep installed"),proceed:[gettext("Uninstall"),gettext("Uninstall & clean up data")],onproceed:function(button){performUninstall(button===1);},nofade:true});};self.cleanupPlugin=function(data){var key,name;if(_.isObject(data)){key=data.key;name=data.name;}else{key=name=data;}
if(!self.loginState.isAdmin()){return;}
if(key==="pluginmanager")return;var performCleanup=function(){self._markWorking(gettext("Cleaning up plugin data..."),_.sprintf(gettext('Cleaning up data of plugin "%(name)s"'),{name:_.escape(name)}));OctoPrint.plugins.pluginmanager.cleanup(key).done(function(){self.requestOrphanData();}).fail(function(){new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});}).always(function(){self._markDone();});};showConfirmationDialog({message:_.sprintf(gettext('You are about to cleanup the plugin data of "%(name)s". This operation cannot be reversed.'),{name:_.escape(name)}),cancel:gettext("Keep data"),proceed:gettext("Cleanup data"),onproceed:performCleanup,nofade:true});};self.cleanupAll=function(){if(!self.loginState.isAdmin()){return;}
var performCleanup=function(){var title=gettext("Cleaning up all left over plugin data...");self._markWorking(title,title);OctoPrint.plugins.pluginmanager.cleanupAll().fail(function(){new PNotify({title:gettext("Something went wrong"),text:gettext("Please consult octoprint.log for details"),type:"error",hide:false});}).always(function(){self._markDone();});};showConfirmationDialog({message:gettext("You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."),cancel:gettext("Keep data"),proceed:gettext("Cleanup all data"),onproceed:performCleanup,nofade:true});};self.refreshRepository=function(){if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)){return;}
self.requestRepositoryData({refresh:true});};self.refreshNotices=function(){if(!self.loginState.isAdmin()){return;}
self.requestPluginData({refresh:true,eval_notices:true,ignore_notice_hidden:true,ignore_notice_ignored:true});};self.reshowNotices=function(){if(!self.loginState.isAdmin()){return;}
self.requestPluginData({eval_notices:true,ignore_notice_hidden:true,ignore_notice_ignored:true});};self.showPluginSettings=function(){self._copyConfig();self.configurationDialog.modal();};self.savePluginSettings=function(){var repository=self.config_repositoryUrl();if(repository!==null&&repository.trim()===""){repository=null;}
var repositoryTtl;try{repositoryTtl=parseInt(self.config_repositoryTtl());}catch(ex){repositoryTtl=null;}
var notices=self.config_noticesUrl();if(notices!==null&&notices.trim()===""){notices=null;}
var noticesTtl;try{noticesTtl=parseInt(self.config_noticesTtl());}catch(ex){noticesTtl=null;}
var pipArgs=self.config_pipAdditionalArgs();if(pipArgs!==null&&pipArgs.trim()===""){pipArgs=null;}
var data={plugins:{pluginmanager:{repository:repository,repository_ttl:repositoryTtl,notices:notices,notices_ttl:noticesTtl,pip_args:pipArgs,pip_force_user:self.config_pipForceUser(),confirm_disable:self.config_confirmDisable()}}};self.settingsViewModel.saveData(data,function(){self.configurationDialog.modal("hide");self._copyConfig();self.requestPluginData({refresh:true,eval_notices:true});if(self.repositoryAvailable()!==undefined){self.requestRepositoryData({refresh:true});}});};self._copyConfig=function(){self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());self.config_noticesUrl(self.settingsViewModel.settings.plugins.pluginmanager.notices());self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());};self.installed=function(data){return _.includes(self.installedPlugins(),data.id);};self.isCompatible=function(data){return(data.is_compatible.octoprint&&data.is_compatible.os&&data.is_compatible.python);};self.installButtonAction=function(data){if(self.enableRepoInstall(data)){if(!self.installQueued(data)){self.installFromRepository(data);}else{self.removeFromQueue(data);}}else{return false;}};self.installButtonText=function(data){if(!self.isCompatible(data)){if(data.disabled){return gettext("Disabled");}else{return gettext("Incompatible");}}
if(self.installQueued(data)){return gettext("Dequeue");}else if(self.installed(data)){return gettext("Reinstall");}else{return gettext("Install");}};self._processPluginManagementResult=function(response,action,plugin){if(response.type=="partial_result"){if(!response.result){self.loglines.push({line:gettext("Error!"),stream:"error"});self.loglines.push({line:response.reason,stream:"error"});if(response.faq){self.loglines.push({line:_.sprintf(gettext("You can find more info on this issue in the FAQ at %(url)s"),{url:faq}),stream:"error"});}}
self.loglines.push({line:"",stream:"separator"});self.loglines.push({line:_.repeat("+",50),stream:"separator"});self.loglines.push({line:"",stream:"separator"});}else{if(response.result){if(self.queuedInstalls().length>0&&action==="install"){var plugin_dequeue=ko.utils.arrayFirst(self.queuedInstalls(),function(item){return item.url===response.source;});if(plugin_dequeue){self.queuedInstalls.remove(plugin_dequeue);}
if(self.queuedInstalls().length===0){self.multiInstallRunning(false);self._markDone();}}else if(self.multiInstallRunning()&&action==="install"){self.alertMultiInstallJobDone(response);}else{self._markDone();}}else{self._markDone(response.reason,response.faq);}}
self._addPluginManagementLog(response,action,plugin);self._displayPluginManagementNotification();};self._extractActionAndNameFromResult=function(result){var action=result.action;var name="Unknown";if(result.hasOwnProperty("plugin")){if(result.plugin!=="unknown"){if(_.isPlainObject(result.plugin)){name=result.plugin.name;}else{name=result.plugin;}}}
return{action:action,name:name};};self._addPluginManagementLog=function(response,action,plugin){self.logContents.action.restart=self.logContents.action.restart||response.needs_restart;self.logContents.action.refresh=self.logContents.action.refresh||response.needs_refresh;self.logContents.action_reconnect=self.logContents.action.reconnect||response.needs_reconnect;self.logContents.steps.push({action:action,plugin:plugin,result:response.result,faq:response.faq});};self._displayPluginManagementNotification=function(){var title=gettext("Plugin management log");var text="<p><ul>";var steps=self.logContents.steps;if(steps.length>5){var count=steps.length-5;var line;if(count>1){line=gettext("%(count)d earlier actions...");}else{line=gettext("%(count)d earlier action");}
text+="<li><em>"+_.sprintf(line,{count:count})+"</em></li>";steps=steps.slice(steps.length-5);}
var negativeResult=false;_.each(steps,function(step){var line=undefined;switch(step.action){case"install":{line=gettext("Install <em>%(plugin)s</em>: %(result)s");break;}
case"uninstall":{line=gettext("Uninstall <em>%(plugin)s</em>: %(result)s");break;}
case"enable":{line=gettext("Enable <em>%(plugin)s</em>: %(result)s");break;}
case"disable":{line=gettext("Disable <em>%(plugin)s</em>: %(result)s");break;}
case"cleanup":{line=gettext("Cleanup <em>%(plugin)s</em>: %(result)s");break;}
case"cleanup_all":{line=gettext("Cleanup all: %(result)s");break;}
default:{return;}}
text+="<li>"+
_.sprintf(line,{plugin:_.escape(step.plugin),result:step.result?'<i class="fa fa-check"></i>':'<i class="fa fa-remove"></i>'})+
(step.result===false&&step.faq?' (<a href="" target="_blank" rel="noopener noreferer">'+
gettext("Why?")+"</a>)":"")+"</li>";negativeResult=negativeResult||step.result===false;});text+="</ul></p>";var confirm=undefined;var type="success";if(self.logContents.action.restart){text+="<p>"+
gettext("A restart is needed for the changes to take effect.")+"</p>";type="warning";if(self.restartCommandSpec&&!self.multiInstallRunning()&&!self.working()){var restartClicked=false;confirm={confirm:true,buttons:[{text:gettext("Restart now"),click:function(notice){if(restartClicked)return;restartClicked=true;showConfirmationDialog({message:gettext("<strong>This will restart your OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),onproceed:function(){OctoPrint.system.executeCommand("core","restart").done(function(){notice.remove();new PNotify({title:gettext("Restart in progress"),text:gettext("The server is now being restarted in the background")});}).fail(function(){new PNotify({title:gettext("Something went wrong"),text:gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")});});},onclose:function(){restartClicked=false;}});}}]};}}else if(self.logContents.action.refresh){text+="<p>"+
gettext("A refresh is needed for the changes to take effect.")+"</p>";type="warning";if(!self.multiInstallRunning()&&!self.working()){var refreshClicked=false;confirm={confirm:true,buttons:[{text:gettext("Reload now"),click:function(){if(refreshClicked)return;refreshClicked=true;location.reload(true);}}]};}}else if(self.logContents.action_reconnect){text+="<p>"+
gettext("A reconnect to the printer is needed for the changes to take effect.")+"</p>";type="warning";}
if(negativeResult)type="error";var options={title:title,text:text,type:type,hide:false};if(confirm!==undefined){options.confirm=confirm;if(self.logNotification===undefined){self.logNotification=PNotify.singleButtonNotify(options);}else{self.logNotification.update(options);self.logNotification=PNotify.fixSingleButton(self.logNotification,options);}}else{if(self.logNotification===undefined){self.logNotification=new PNotify(options);}else{self.logNotification.update(options);}}
if(self.logNotification.state!=="open"&&self.logNotification.state!=="opening"){self.logNotification.open();}};self._markWorking=function(title,line){self.working(true);self.workingTitle(title);self.loglines.removeAll();self.loglines.push({line:line,stream:"message"});self._scrollWorkingOutputToEnd();self.workingDialog.modal({keyboard:false,backdrop:"static",show:true});};self._markDone=function(error,faq){self.working(false);if(error){self.loglines.push({line:gettext("Error!"),stream:"error"});self.loglines.push({line:error,stream:"error"});if(faq){self.loglines.push({line:_.sprintf(gettext("You can find more info on this issue in the FAQ at %(url)s"),{url:faq}),stream:"error"});}}else{self.loglines.push({line:gettext("Done!"),stream:"message"});}
self._scrollWorkingOutputToEnd();};self._scrollWorkingOutputToEnd=function(){self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight-self.workingOutput.height());};self._getToggleCommand=function(data){var disable=(data.enabled||(data.safe_mode_victim&&!data.forced_disabled)||data.pending_enable)&&!data.pending_disable;return disable?"disable":"enable";};self.toggleButtonCss=function(data){var icon,disabled;if(self.toggling()){icon="fa fa-spin fa-spinner";disabled=" disabled";}else{icon=self._getToggleCommand(data)==="enable"?"fa fa-toggle-off":"fa fa-toggle-on";disabled=self.enableToggle(data)?"":" disabled";}
return icon+disabled;};self.toggleButtonTitle=function(data){var command=self._getToggleCommand(data);if(command==="enable"){if(data.blacklisted){return gettext("Blacklisted");}else if(data.safe_mode_victim){return gettext("Disabled due to active safe mode");}else{return gettext("Enable Plugin");}}else{return gettext("Disable Plugin");}};self.showPluginNotifications=function(plugin){if(!plugin.notifications||plugin.notifications.length===0)return;self._removeAllNoticeNotificationsForPlugin(plugin.key);_.each(plugin.notifications,function(notification){self._showPluginNotification(plugin,notification);});};self.showPluginNotificationsLinkText=function(plugins){if(!plugins.notifications||plugins.notifications.length===0)return;var count=plugins.notifications.length;var importantCount=_.filter(plugins.notifications,function(notification){return notification.important;}).length;if(count>1){if(importantCount){return _.sprintf(gettext("There are %(count)d notices (%(important)d marked as important) available regarding this plugin - click to show!"),{count:count,important:importantCount});}else{return _.sprintf(gettext("There are %(count)d notices available regarding this plugin - click to show!"),{count:count});}}else{if(importantCount){return gettext("There is an important notice available regarding this plugin - click to show!");}else{return gettext("There is a notice available regarding this plugin - click to show!");}}};self._showPluginNotification=function(plugin,notification){var name=plugin.name;var version=plugin.version;var important=notification.important;var link=notification.link;var title;if(important){title=_.sprintf(gettext('Important notice regarding plugin "%(name)s"'),{name:_.escape(name)});}else{title=_.sprintf(gettext('Notice regarding plugin "%(name)s"'),{name:_.escape(name)});}
var text="";if(notification.versions&&notification.versions.length>0){var versions=_.map(notification.versions,function(v){return v===version?"<strong>"+_.escape(v)+"</strong>":_.escape(v);}).join(", ");text+="<small>"+
_.sprintf(gettext("Affected versions: %(versions)s"),{versions:versions})+"</small>";}else{text+="<small>"+gettext("Affected versions: all")+"</small>";}
text+="<p>"+notification.text+"</p>";if(link){text+="<p><a href='"+
link+"' target='_blank'>"+
gettext("Read more...")+"</a></p>";}
var beforeClose=function(notification){if(!self.noticeNotifications[plugin.key])return;self.noticeNotifications[plugin.key]=_.without(self.noticeNotifications[plugin.key],notification);};var options={title:title,text:text,type:important?"error":"notice",before_close:beforeClose,hide:false,confirm:{confirm:true,buttons:[{text:gettext("Later"),click:function(notice){self._hideNoticeNotification(plugin.key,notification.date);notice.remove();notice.get().trigger("pnotify.cancel",notice);}},{text:gettext("Mark read"),click:function(notice){self._ignoreNoticeNotification(plugin.key,notification.date);notice.remove();notice.get().trigger("pnotify.cancel",notice);}}]},buttons:{sticker:false,closer:false}};if(!self.noticeNotifications[plugin.key]){self.noticeNotifications[plugin.key]=[];}
self.noticeNotifications[plugin.key].push(new PNotify(options));};self._removeAllNoticeNotifications=function(){_.each(_.keys(self.noticeNotifications),function(key){self._removeAllNoticeNotificationsForPlugin(key);});};self._removeAllNoticeNotificationsForPlugin=function(key){if(!self.noticeNotifications[key]||!self.noticeNotifications[key].length)
return;_.each(self.noticeNotifications[key],function(notification){notification.remove();});};self._hideNoticeNotification=function(key,date){if(!self.hiddenNoticeNotifications[key]){self.hiddenNoticeNotifications[key]=[];}
if(!_.contains(self.hiddenNoticeNotifications[key],date)){self.hiddenNoticeNotifications[key].push(date);}};self._isNoticeNotificationHidden=function(key,date){if(!self.hiddenNoticeNotifications[key])return false;return _.any(_.map(self.hiddenNoticeNotifications[key],function(d){return date===d;}));};var noticeLocalStorageKey="plugin.pluginmanager.seen_notices";self._ignoreNoticeNotification=function(key,date){if(!Modernizr.localstorage)return false;if(!self.loginState.isAdmin())return false;var currentString=localStorage[noticeLocalStorageKey];var current;if(currentString===undefined){current={};}else{current=JSON.parse(currentString);}
if(!current[self.loginState.username()]){current[self.loginState.username()]={};}
if(!current[self.loginState.username()][key]){current[self.loginState.username()][key]=[];}
if(!_.contains(current[self.loginState.username()][key],date)){current[self.loginState.username()][key].push(date);localStorage[noticeLocalStorageKey]=JSON.stringify(current);}};self._isNoticeNotificationIgnored=function(key,date){if(!Modernizr.localstorage)return false;if(localStorage[noticeLocalStorageKey]===undefined)return false;var knownData=JSON.parse(localStorage[noticeLocalStorageKey]);if(!self.loginState.isAdmin())return true;var userData=knownData[self.loginState.username()];if(userData===undefined)return false;return userData[key]&&_.contains(userData[key],date);};self.onBeforeBinding=function(){self.settings=self.settingsViewModel.settings;};self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){if(self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){self.requestPluginData({eval_notices:true});}else{self._resetNotifications();}};self.onSettingsShown=function(){if(self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){self.requestRepositoryData();self.requestOrphanData();}};self.onEventConnectivityChanged=function(payload){self.requestPluginData({eval_notices:true});};self._resetNotifications=function(){self._closeAllNotifications();self.logContents.action.restart=self.logContents.action.reload=self.logContents.action.reconnect=false;self.logContents.steps=[];};self._closeAllNotifications=function(){if(self.logNotification){self.logNotification.remove();}};self.onServerDisconnect=function(){self._resetNotifications();return true;};self.onStartup=function(){self.workingDialog=$("#settings_plugin_pluginmanager_workingdialog");self.workingOutput=$("#settings_plugin_pluginmanager_workingdialog_output");self.repositoryDialog=$("#settings_plugin_pluginmanager_repositorydialog");};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="pluginmanager"){return;}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)){return;}
if(!data.hasOwnProperty("type")){return;}
var messageType=data.type;if(messageType==="loglines"&&(self.working()||self.queuedInstalls().length>0)){_.each(data.loglines,function(line){self.loglines.push(self._preprocessLine(line));});self._scrollWorkingOutputToEnd();}else if(messageType==="result"||messageType==="partial_result"){var{action,name}=self._extractActionAndNameFromResult(data);self._processPluginManagementResult(data,action,name);if(messageType==="result"){self._displayPluginManagementNotification();self.requestPluginData();}}else if(messageType==="queued_installs"){if(data.hasOwnProperty("queued")){self.queuedInstalls(data.queued);var queuedInstallsPopupOptions={title:gettext("Queued Installs"),text:"",type:"notice",icon:false,hide:false,buttons:{closer:false,sticker:false},history:{history:false}};if(data.print_failed&&data.queued.length>0){queuedInstallsPopupOptions.title=gettext("Queued Installs Paused");queuedInstallsPopupOptions.text='<div class="row-fluid"><p>'+
gettext("The following plugins are queued to be installed.")+"</p><ul><li>"+
_.map(self.queuedInstalls(),function(info){var plugin=ko.utils.arrayFirst(self.repositoryplugins.paginatedItems(),function(item){return item.archive===info.url;});return plugin.title;}).join("</li><li>")+"</li></ul></div>";queuedInstallsPopupOptions.confirm={confirm:true,buttons:[{text:gettext("Continue Installs"),addClass:"btn-block btn-primary",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.continue",[notice,value]);}},{text:gettext("Cancel Installs"),addClass:"btn-block btn-danger",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.cancel",[notice,value]);}}]};}else if(data.hasOwnProperty("timeout_value")&&data.timeout_value>0&&data.queued.length>0){var progress_percent=Math.floor((data.timeout_value/60)*100);var progress_class=progress_percent<25?"progress-danger":progress_percent>75?"progress-success":"progress-warning";var countdownText=_.sprintf(gettext("Installing in %(sec)i secs..."),{sec:data.timeout_value});queuedInstallsPopupOptions.title=gettext("Starting Queued Installs");queuedInstallsPopupOptions.text='<div class="row-fluid"><p>'+
gettext("The following plugins are going to be installed.")+"</p><ul><li>"+
_.map(self.queuedInstalls(),function(info){var plugin=ko.utils.arrayFirst(self.repositoryplugins.paginatedItems(),function(item){return item.archive===info.url;});return plugin.title;}).join("</li><li>")+'</li></ul></p></div><div class="progress progress-softwareupdate '+
progress_class+'"><div class="bar">'+
countdownText+'</div><div class="progress-text" style="clip-path: inset(0 0 0 '+
progress_percent+"%);-webkit-clip-path: inset(0 0 0 "+
progress_percent+'%);">'+
countdownText+"</div></div>";queuedInstallsPopupOptions.confirm={confirm:true,buttons:[{text:gettext("Cancel Installs"),addClass:"btn-block btn-danger",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.cancel",[notice,value]);}},{text:"",addClass:"hidden"}]};}else if(data.hasOwnProperty("timeout_value")&&data.timeout_value===0&&data.queued.length>0){self.multiInstallRunning(true);self._markWorking(gettext("Installing queued plugins"),gettext("Starting installation of multiple plugins..."));self.queuedInstallsPopup.remove();self.queuedInstallsPopup=undefined;return;}else{if(typeof self.queuedInstallsPopup!=="undefined"){self.queuedInstallsPopup.remove();self.queuedInstallsPopup=undefined;}
return;}
if(typeof self.queuedInstallsPopup!=="undefined"){self.queuedInstallsPopup.update(queuedInstallsPopupOptions);}else{self.queuedInstallsPopup=new PNotify(queuedInstallsPopupOptions);self.queuedInstallsPopup.get().on("pnotify.cancel",function(){self.queuedInstallsPopup=undefined;self.cancelQueuedInstalls();});self.queuedInstallsPopup.get().on("pnotify.continue",function(){self.queuedInstallsPopup=undefined;self.performQueuedInstalls();});}}}};self.cancelQueuedInstalls=function(){OctoPrint.simpleApiCommand("pluginmanager","clear_queued_installs",{}).done(function(response){self.queuedInstalls(response.queued_installs);});};self.installQueued=function(plugin){var plugin_queued=ko.utils.arrayFirst(self.queuedInstalls(),function(item){return item.url===plugin.archive;});return typeof plugin_queued!=="undefined";};self.performQueuedInstalls=function(){self.queuedInstalls().forEach(function(plugin){var queued_plugin=ko.utils.arrayFirst(self.repositoryplugins.paginatedItems(),function(item){return plugin.url===item.archive;});self.multiInstallQueue.push(queued_plugin);});self.startMultiInstall();};self._forcedStdoutLine=/You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;self._preprocessLine=function(line){if(line.stream==="stderr"&&line.line.match(self._forcedStdoutLine)){line.stream="stdout";}
return line;};}
OCTOPRINT_VIEWMODELS.push({construct:PluginManagerViewModel,dependencies:["loginStateViewModel","settingsViewModel","printerStateViewModel","systemViewModel","accessViewModel","piSupportViewModel"],optional:["piSupportViewModel"],elements:["#settings_plugin_pluginmanager"]});});
;

// source: plugin/softwareupdate/js/softwareupdate.js
$(function(){function SoftwareUpdateViewModel(parameters){var self=this;self.loginState=parameters[0];self.printerState=parameters[1];self.settings=parameters[2];self.access=parameters[3];self.piSupport=parameters[4];self.popup=undefined;self.updateInProgress=false;self.cancelInProgress=false;self.waitingForRestart=false;self.restartTimeout=undefined;self.currentlyBeingUpdated=[];self.queuedUpdates=ko.observableArray([]);self.working=ko.observable(false);self.workingTitle=ko.observable();self.workingDialog=undefined;self.workingOutput=undefined;self.loglines=ko.observableArray([]);self.checking=ko.observable(false);self.octoprintReleasedVersion=ko.observable();self.octoprintUnconfigured=ko.pureComputed(function(){return(self.settings.settings.plugins.softwareupdate.octoprint_type()==="git_commit"&&self.error_checkoutFolder());});self.octoprintUnreleased=ko.pureComputed(function(){return(self.settings.settings.plugins.softwareupdate.octoprint_type()==="github_release"&&!self.octoprintReleasedVersion());});self.environmentSupported=ko.observable(true);self.environmentVersions=ko.observableArray([]);self.storageSufficient=ko.observable(true);self.storageFree=ko.observableArray([]);self.cacheTimestamp=ko.observable();self.cacheTimestampText=ko.pureComputed(function(){return formatDate(self.cacheTimestamp());});self.config_cacheTtl=ko.observable();self.config_notifyUsers=ko.observable();self.config_trackedBranch=ko.observable();self.config_checkoutFolder=ko.observable();self.config_pipTarget=ko.observable();self.config_checkType=ko.observable();self.config_releaseChannel=ko.observable();self.config_pipEnableCheck=ko.observable();self.config_minimumFreeStorage=ko.observable();self.config_githubToken=ko.observable();self.config_githubTokenSet=ko.observable(false);self.error_checkoutFolder=ko.pureComputed(function(){return(self.config_checkType()==="git_commit"&&(!self.config_checkoutFolder()||self.config_checkoutFolder().trim()===""));});self.enableUpdate=ko.pureComputed(function(){return(!self.updateInProgress&&self.environmentSupported()&&self.storageSufficient()&&!self.throttled());});self.enableUpdateAll=ko.pureComputed(function(){return self.enableUpdate()&&self.availableAndPossible().length>0;});self.enableUpdateEnabled=ko.pureComputed(function(){return(self.enableUpdate()&&self.availableAndPossibleAndEnabled().length>0);});self.enableCancelQueued=ko.pureComputed(function(){return self.queuedUpdates().length>0;});self.updateQueued=function(item){return self.queuedUpdates().indexOf(item.key)>-1;};self.enable_configSave=ko.pureComputed(function(){return(self.config_checkType()==="github_release"||self.config_checkType()==="github_commit"||(self.config_checkType()==="git_commit"&&!self.error_checkoutFolder()));});self.configurationDialog=undefined;self._updateClicked=false;self.config_availableCheckTypes=ko.observableArray([]);self.config_availableReleaseChannels=ko.observableArray([]);self.reloadOverlay=$("#reloadui_overlay");self.versions=new ItemListHelper("plugin.softwareupdate.versions",{name:function(a,b){if(a.key.toLocaleLowerCase()==="octoprint")return-1;if(b.key.toLocaleLowerCase()==="octoprint")return 1;if(a.displayName.toLocaleLowerCase()<b.displayName.toLocaleLowerCase())
return-1;if(a.displayName.toLocaleLowerCase()>b.displayName.toLocaleLowerCase())
return 1;return 0;}},{},"name",[],[],0);self.octoprintData={item:undefined,current:ko.observable("unknown"),available:ko.observable("unknown")};self.updatelog=ko.observableArray([]);self.availableAndPossible=ko.pureComputed(function(){return _.filter(self.versions.items(),function(info){return info.updateAvailable&&info.updatePossible;});});self.availableAndPossibleAndEnabled=ko.pureComputed(function(){return _.filter(self.versions.items(),function(info){return info.updateAvailable&&info.updatePossible&&!info.disabled;});});self.availableAndQueued=ko.pureComputed(function(){return _.filter(self.versions.items(),function(info){return(info.updateAvailable&&info.updatePossible&&self.queuedUpdates.indexOf(info.key)>-1);});});self.throttled=ko.pureComputed(function(){return(self.piSupport&&self.piSupport.currentIssue()&&!self.settings.settings.plugins.softwareupdate.ignore_throttled());});self.onUserPermissionsChanged=self.onUserLoggedIn=self.onUserLoggedOut=function(){if(self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)){self.performCheck();}else{self._closePopup();}
if(self.loginState.hasPermission(self.access.permissions.ADMIN)){self.requestUpdatelog();}};self._showPopup=function(options,eventListeners,singleButtonNotify){singleButtonNotify=singleButtonNotify||false;self._closePopup();if(singleButtonNotify){self.popup=PNotify.singleButtonNotify(options);}else{self.popup=new PNotify(options);}
if(eventListeners){var popupObj=self.popup.get();_.each(eventListeners,function(value,key){popupObj.on(key,value);});}};self._updatePopup=function(options){if(self.popup===undefined){self._showPopup(options);}else{self.popup.update(options);}};self._closePopup=function(){if(self.popup!==undefined){self.popup.remove();}};self.showPluginSettings=function(){self._copyConfig();self.configurationDialog.modal();};self.deleteGithubTokenApiKey=function(){var data={plugins:{softwareupdate:{credentials:{github:undefined}}}};self.settings.saveData(data,{success:function(){self.performCheck();},complete:function(){self.config_githubToken("");self.config_githubTokenSet(false);},sending:true});};self.savePluginSettings=function(viewModel,event){var target=$(event.target);target.prepend('<i class="fa fa-spinner fa-spin"></i> ');var githubToken=self.config_githubToken();var data={plugins:{softwareupdate:{cache_ttl:parseInt(self.config_cacheTtl()),notify_users:self.config_notifyUsers(),octoprint_type:self.config_checkType(),octoprint_release_channel:self.config_releaseChannel(),octoprint_checkout_folder:self.config_checkoutFolder(),octoprint_tracked_branch:self.config_trackedBranch(),octoprint_pip_target:self.config_pipTarget(),pip_enable_check:self.config_pipEnableCheck(),minimum_free_storage:self.config_minimumFreeStorage()}}};if(githubToken){data.plugins.softwareupdate.credentials={github:githubToken};}
self.settings.saveData(data,{success:function(){self.configurationDialog.modal("hide");self._copyConfig();self.performCheck();},complete:function(){$("i.fa-spinner",target).remove();self.config_githubToken("");},sending:true});};self.onBeforeBinding=function(){self.queuedUpdates(self.settings.settings.plugins.softwareupdate.queued_updates());};self._copyConfig=function(){var availableCheckTypes=[{key:"github_release",name:gettext("Release")},{key:"github_commit",name:gettext("Github Commit")},{key:"git_commit",name:gettext("Local checkout")}];self.config_availableCheckTypes(availableCheckTypes);var availableReleaseChannels=[];_.each(self.settings.settings.plugins.softwareupdate.octoprint_branch_mappings(),function(mapping){availableReleaseChannels.push({key:mapping.branch(),name:gettext(mapping.name()||mapping.branch())});});self.config_availableReleaseChannels(availableReleaseChannels);self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());self.config_notifyUsers(self.settings.settings.plugins.softwareupdate.notify_users());self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());self.config_trackedBranch(self.settings.settings.plugins.softwareupdate.octoprint_tracked_branch());self.config_pipTarget(self.settings.settings.plugins.softwareupdate.octoprint_pip_target());self.config_pipEnableCheck(self.settings.settings.plugins.softwareupdate.pip_enable_check());self.config_minimumFreeStorage(self.settings.settings.plugins.softwareupdate.minimum_free_storage());self.config_githubTokenSet(self.settings.settings.plugins.softwareupdate.credentials.github_set());};self._copyConfigBack=function(){self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder(self.config_checkoutFolder());self.settings.settings.plugins.softwareupdate.octoprint_type(self.config_checkType());};self._enrichInformation=function(key,information){information["key"]=key;if(!information.hasOwnProperty("displayName")||information.displayName===""){information.displayName=information.key;}
if(!information.hasOwnProperty("displayVersion")||information.displayVersion===""){information.displayVersion=information.information.local.name;}
if(!information.hasOwnProperty("releaseNotes")||information.releaseNotes===""){information.releaseNotes=undefined;}
var fullNameTemplate=gettext("%(name)s: %(version)s");information.fullNameLocal=_.sprintf(fullNameTemplate,{name:_.escape(information.displayName),version:_.escape(information.displayVersion)});var fullNameRemoteVars={name:_.escape(information.displayName),version:gettext("unknown")};if(information.hasOwnProperty("information")&&information.information.hasOwnProperty("remote")&&information.information.remote.hasOwnProperty("name")){fullNameRemoteVars.version=_.escape(information.information.remote.name);}
information.fullNameRemote=_.sprintf(fullNameTemplate,fullNameRemoteVars);if(information.releaseChannels&&information.releaseChannels.current){information.releaseChannels.current=ko.observable(information.releaseChannels.current);information.releaseChannels.current.subscribe(function(selected){var patch={};patch[key]={channel:selected};OctoPrint.plugins.softwareupdate.configure(patch).done(function(){self.performCheck(false,false,false,[key]);});});}
information.toggleDisabled=function(){var patch={};patch[key]={disabled:!information.disabled};OctoPrint.plugins.softwareupdate.configure(patch).done(function(){self.performCheck(false,false,false,[key]);});};information.notificationIconTitle=function(){var update=information.updateAvailable?gettext("Update available"):gettext("Up-to-date");var notifications=information.disabled?gettext("notifications are muted"):gettext("notifications are enabled");return update+" ("+notifications+")";};return information;};self.fromCheckResponse=function(data,ignoreSeen,showIfNothingNew){self.cacheTimestamp(data.timestamp);var versions=[];_.each(data.information,function(value,key){self._enrichInformation(key,value);versions.push(value);});self.versions.updateItems(versions);var octoprint=data.information["octoprint"];self.octoprintReleasedVersion(!octoprint||octoprint.releasedVersion);self.environmentSupported(data.environment.supported);self.environmentVersions(data.environment.versions);self.storageSufficient(data.storage.sufficient);self.storageFree(data.storage.free);if(data.status==="inProgress"){self._markWorking(gettext("Updating..."),gettext("Updating, please wait."));return;}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)&&!self.settings.settings.plugins.softwareupdate.notify_users())
return;if(data.status==="updateAvailable"||data.status==="updatePossible"){var text="<div class='softwareupdate_notification'>"+
gettext("There are updates available for the following components:");text+="<ul class='fa-ul'>";_.each(self.versions.items(),function(update_info){if(update_info.updateAvailable&&!update_info.disabled&&update_info.compatible){text+="<li>"+"<i class='fa fa-li "+
(update_info.updatePossible&&self.environmentSupported()&&self.storageSufficient()?"fa-check":"fa-remove")+"'></i>"+"<span class='name' title='"+
update_info.fullNameRemote+"'>"+
update_info.fullNameRemote+"</span>"+
(update_info.releaseNotes?'<a href="'+
update_info.releaseNotes+'" target="_blank">'+
gettext("Release Notes")+"</a>":"")+"</li>";}});text+="</ul>";if(!self.environmentSupported()){text+="<p><small>"+
gettext("This version of the Python environment is not supported for direct updates.")+"</small></p>";}else if(!self.storageSufficient()){text+="<p><small>"+
gettext("There's currently not enough free disk space available for a direct update.")+"</small></p>";}else{text+="<p><small>"+
gettext('Those components marked with <i class="fa fa-check"></i> can be updated directly.')+"</small></p>";}
if(!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)){text+="<p><small>"+
gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.")+"</small></p>";}
text+="</div>";var options={title:gettext("Update Available"),text:text,hide:false};var eventListeners={};var singleButtonNotify=false;if(data.status==="updatePossible"&&self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)){options["confirm"]={confirm:true,buttons:[{text:gettext("Ignore"),click:function(){self._markNotificationAsSeen(data.information);self._showPopup({text:gettext('You can make this message display again via "Settings" > "Software Update" > "Check for update now"')});}},{text:gettext("Update now"),addClass:"btn-primary",click:function(){if(self._updateClicked)return;self._updateClicked=true;self.updateEnabled();}}]};options["buttons"]={closer:false,sticker:false};}else{options["confirm"]={confirm:true,buttons:[{text:gettext("Ignore"),click:function(notice){notice.remove();self._markNotificationAsSeen(data.information);}}]};options["buttons"]={closer:false,sticker:false};singleButtonNotify=true;}
if((ignoreSeen||!self._hasNotificationBeenSeen(data.information))&&!OctoPrint.coreui.wizardOpen){self._showPopup(options,eventListeners,singleButtonNotify);}}else if(data.status==="current"){if(showIfNothingNew){self._showPopup({title:gettext("Everything is up-to-date"),type:"success"});}else{self._closePopup();}}};self.performCheck=function(showIfNothingNew,force,ignoreSeen,entries){self.checking(true);OctoPrint.plugins.softwareupdate.check({entries:entries,force:force}).done(function(data){self.fromCheckResponse(data,ignoreSeen,showIfNothingNew);}).always(function(){self.checking(false);});};self.fromUpdatelogResponse=function(response){self.updatelog(response.updatelog);};self.requestUpdatelog=function(){OctoPrint.plugins.softwareupdate.getUpdatelog().done(self.fromUpdatelogResponse);};self.iconTitleForEntry=function(data){if(data.updatePossible){return"";}else if(!data.online&&data.information&&data.information.needs_online){return gettext("No internet connection");}else if(data.error){return self.errorTextForEntry(data);}else{return gettext("Update not possible");}};self.errorTextForEntry=function(data){if(!data.error){return"";}
switch(data.error){case"unknown_check":{return gettext("Unknown update check, configuration ok?");}
case"needs_online":{return gettext("Cannot check for update, need online connection");}
case"network":{return gettext("Network error while checking for update, please check the logs");}
case"api":{return gettext("API error while checking for update, please check the logs");}
case"ratelimit":{return gettext("Rate limit exceeded while checking for update, please try again later");}
case"check":{return gettext("Check internal error while checking for update, please check the logs");}
case"unknown":{return gettext("Unknown error while checking for update, please check the logs");}
case"update":{return gettext("Unknown error while checking if update is possible, please check the logs");}
case"windows":{return _.sprintf(gettext('Update not possible under Windows due to its strict file locking behaviour, please <a href="%(url)s" target="_blank">see the FAQ</a>'),{url:"https://faq.octoprint.org/update-not-possible-windows"});}
default:{return"";}}};self._markNotificationAsSeen=function(data){if(!Modernizr.localstorage)return false;var currentString=localStorage["plugin.softwareupdate.seen_information"];var current;if(currentString===undefined){current={};}else{current=JSON.parse(currentString);}
current[self.loginState.username()]=self._informationToRemoteVersions(data);localStorage["plugin.softwareupdate.seen_information"]=JSON.stringify(current);};self._hasNotificationBeenSeen=function(data){if(!Modernizr.localstorage)return false;if(localStorage["plugin.softwareupdate.seen_information"]===undefined)
return false;var knownData=JSON.parse(localStorage["plugin.softwareupdate.seen_information"]);var userData=knownData[self.loginState.username()];if(userData===undefined)return false;var freshData=self._informationToRemoteVersions(data);var hasBeenSeen=true;_.each(freshData,function(value,key){if(!_.has(userData,key)||userData[key]!==freshData[key]){hasBeenSeen=false;}});return hasBeenSeen;};self._informationToRemoteVersions=function(data){var result={};_.each(data,function(value,key){result[key]=value.information.remote.value;});return result;};self.performUpdate=function(force,items){if(!self.updateAccess())return;self.updateInProgress=true;var options={title:gettext("Updating..."),text:gettext("Now updating, please wait."),icon:"fa fa-cog fa-spin",hide:false,buttons:{closer:false,sticker:false}};self._showPopup(options);OctoPrint.plugins.softwareupdate.update(items,force).done(function(data){if(data.hasOwnProperty("queued")){self.queuedUpdates(data.queued);var message="<p>"+
gettext("The install of the following plugin update(s) has been queued for after current print is finished or cancelled.")+'</p><p><div class="row-fluid"><ul><li>'+
_.map(self.availableAndQueued(),function(info){return info.displayName;}).join("</li><li>")+"</li></ul></div></p>";self._showPopup({title:gettext("Updates Queued"),text:message,type:"info",buttons:{sticker:false}});self.updateInProgress=false;return;}
self.currentlyBeingUpdated=data.checks;self._markWorking(gettext("Updating..."),gettext("Updating, please wait."));}).fail(function(response){self.updateInProgress=false;var message="<p>"+
gettext("The update could not be started. Is it already active? Please consult octoprint.log for details.")+"</p><pre>"+
_.escape(response.responseJSON.error)+"</pre>";self._showPopup({title:gettext("Update not started!"),text:message,type:"error",hide:false,buttons:{sticker:false}});});};self.updateAll=function(force){return self.update(force,self.availableAndPossible());};self.updateEnabled=function(force){return self.update(force,self.availableAndPossibleAndEnabled());};self.updateAccess=function(){return(self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)||CONFIG_FIRST_RUN);};self.update=function(force,items){if(self.updateInProgress||!self.updateAccess()){self._updateClicked=false;return;}
if(items===undefined){items=self.availableAndPossibleAndEnabled();}
if(self.throttled()){self._showPopup({title:gettext("Can't update while throttled"),text:gettext("Your system is currently throttled. OctoPrint refuses to run updates while in this state due to possible stability issues."),type:"error"});self._updateClicked=false;return;}
var html="<p>"+
gettext("This will update the following components and restart the server:")+"</p>";html+="<ul>";_.each(items,function(item){html+="<li>"+'<span class="name" title="'+
item.fullNameRemote+'">'+
item.fullNameRemote+"</span>";if(item.releaseNotes){html+='<br><a href="'+
item.releaseNotes+'" target="_blank" rel="noreferrer noopener">'+
gettext("Release Notes")+"</a>";}
html+="</li>";});html+="</ul>";html+="<p>"+
gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.")+"</p>"+"<p>"+
gettext("Updates will be queued if currently printing,")+" <strong>"+
gettext("however this action may disrupt any ongoing print if OctoPrint is not currently controlling it.")+"</strong>"+"</p>"+"<p>"+
gettext("Are you sure you want to proceed?")+"</p>";showConfirmationDialog({title:gettext("Are you sure you want to update now?"),html:html,proceed:gettext("Proceed"),onproceed:function(){self.performUpdate(force===true,_.map(items,function(info){return info.key;}));},onclose:function(){self._updateClicked=false;}});};self._showWorkingDialog=function(title){if(!(self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)||CONFIG_FIRST_RUN)){return;}
self.working(true);self.workingTitle(title);self.workingDialog.modal({keyboard:false,backdrop:"static",show:true});};self._markWorking=function(title,line,stream){if(stream===undefined){stream="message";}
self.loglines.removeAll();self.loglines.push({line:line,stream:stream});self._showWorkingDialog(title);};self._markDone=function(line,stream){if(stream===undefined){stream="message";}
self.working(false);self.loglines.push({line:"",stream:stream});self.loglines.push({line:line,stream:stream});self._scrollWorkingOutputToEnd();};self._scrollWorkingOutputToEnd=function(){self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight-self.workingOutput.height());};self.onBeforeWizardTabChange=function(next,current){if(next&&next==="#wizard_plugin_softwareupdate"){self._copyConfig();}else if(current&&current==="#wizard_plugin_softwareupdate"){self._copyConfigBack();}
return true;};self.onAfterWizardFinish=function(){self.performCheck();};self.onStartup=function(){self.workingDialog=$("#settings_plugin_softwareupdate_workingdialog");self.workingOutput=$("#settings_plugin_softwareupdate_workingdialog_output");self.configurationDialog=$("#settings_plugin_softwareupdate_configurationdialog");};self.onServerDisconnect=function(){if(self.restartTimeout!==undefined){clearTimeout(self.restartTimeout);}
return true;};self.onEventConnectivityChanged=function(payload){if(!payload||!payload.new)return;self.performCheck();};self.onWizardDetails=function(data){if(data.softwareupdate&&data.softwareupdate.details&&data.softwareupdate.details.update){var value=data.softwareupdate.details.update;self._enrichInformation("octoprint",value);self.octoprintData.item=value;self.octoprintData.current(value.information.local.name);self.octoprintData.available(value.information.remote.name);}};self.onDataUpdaterReconnect=function(){if(self.waitingForRestart){self.waitingForRestart=false;self.updateInProgress=false;if(!self.reloadOverlay.is(":visible")){self.reloadOverlay.show();}}};self.cancelQueued=function(items){self.cancelInProgress=true;OctoPrint.plugins.softwareupdate.cancelQueued({targets:_.map(items,function(info){return info.key;})}).done(function(data){self.queuedUpdates(data.queued);self.cancelInProgress=false;}).fail(function(response){console.log(response);self.cancelInProgress=false;});};self.onDataUpdaterPluginMessage=function(plugin,data){if(plugin!=="softwareupdate"){return;}
var messageType=data.type;var messageData=data.data;var options=undefined;var restartType=undefined;var title=undefined;var text=undefined;switch(messageType){case"loglines":case"updating":case"restarting":case"restart_manually":case"restart_failed":case"success":case"error":{if(!self.working()){self._markWorking(gettext("Updating..."),gettext("Updating, please wait."));}
break;}}
switch(messageType){case"loglines":{_.each(messageData.loglines,function(line){self.loglines.push(self._preprocessLine(line));});self._scrollWorkingOutputToEnd();break;}
case"updating":{text=_.sprintf(gettext("Now updating %(name)s to %(version)s"),{name:_.escape(messageData.name),version:_.escape(messageData.version)});self.loglines.push({line:"",stream:"separator"});self.loglines.push({line:_.repeat("+",text.length),stream:"separator"});self.loglines.push({line:text,stream:"message"});self.loglines.push({line:_.repeat("+",text.length),stream:"separator"});self._scrollWorkingOutputToEnd();self._updatePopup({text:text,hide:false,buttons:{sticker:false}});break;}
case"restarting":{title=gettext("Update successful, restarting!");text=gettext("The update finished successfully and the server will now be restarted.");options={title:title,text:text,type:"success",hide:false,buttons:{sticker:false}};self.loglines.push({line:text,stream:"message"});self._scrollWorkingOutputToEnd();self.waitingForRestart=true;self.restartTimeout=setTimeout(function(){title=gettext("Restart failed");text=gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult octoprint.log on what went wrong.");self._showPopup({title:title,text:text,type:"error",hide:false,buttons:{sticker:false}});self.waitingForRestart=false;self._markDone(text,"message_error");},60000);break;}
case"restart_manually":{restartType=messageData.restart_type;text=gettext("The update finished successfully, please restart OctoPrint now.");if(restartType==="environment"){text=gettext("The update finished successfully, please reboot the server now.");}
title=gettext("Update successful, restart required!");options={title:title,text:text,type:"success",hide:false,buttons:{sticker:false}};self.updateInProgress=false;self._markDone(text);break;}
case"restart_failed":{restartType=messageData.restart_type;text=gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult octoprint.log on what went wrong here.");if(restartType==="environment"){text=gettext("Rebooting the server failed, please reboot it manually. You might also want to consult octoprint.log on what went wrong here.");}
title=gettext("Restart failed");options={title:title,test:text,type:"error",hide:false,buttons:{sticker:false}};self.waitingForRestart=false;self.updateInProgress=false;self._markDone(text,"message_error");break;}
case"success":{title=gettext("Update successful!");text=gettext("The update finished successfully.");options={title:title,text:text,type:"success",hide:false,buttons:{sticker:false}};self.updateInProgress=false;self._markDone(text);break;}
case"error":{title=gettext("Update failed!");text=gettext("The update did not finish successfully. Please consult <code>octoprint.log</code> and <code>plugin_softwareupdate_console.log</code> for details.");self._showPopup({title:title,text:text,type:"error",hide:false,buttons:{sticker:false}});self.updateInProgress=false;self._markDone(text,"message_error");break;}
case"update_versions":{self.performCheck();break;}
case"queued_updates":{if(!self.updateAccess()){return;}
if(messageData.hasOwnProperty("targets")){self.queuedUpdates(messageData.targets);var queuedUpdatesPopupOptions={title:title,text:text,type:"notice",icon:false,hide:false,buttons:{closer:false,sticker:false},history:{history:false}};if(messageData.print_failed&&messageData.targets.length>0){queuedUpdatesPopupOptions.title=gettext("Queued Updates Paused");queuedUpdatesPopupOptions.text='<div class="row-fluid"><ul><li>'+
_.map(self.availableAndQueued(),function(info){return info.displayName;}).join("</li><li>")+"</li></ul></div>";queuedUpdatesPopupOptions.confirm={confirm:true,buttons:[{text:gettext("Continue Updates"),addClass:"btn-block btn-primary",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.continue",[notice,value]);}},{text:gettext("Cancel Updates"),addClass:"btn-block btn-danger",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.cancel",[notice,value]);}}]};}else if(messageData.hasOwnProperty("timeout_value")&&messageData.timeout_value>0&&messageData.targets.length>0){var progress_percent=Math.floor((messageData.timeout_value/60)*100);var progress_class=progress_percent<25?"progress-danger":progress_percent>75?"progress-success":"progress-warning";var countdownText=_.sprintf(gettext("Updating in %(sec)i secs..."),{sec:messageData.timeout_value});queuedUpdatesPopupOptions.title=gettext("Starting Queued Updates");queuedUpdatesPopupOptions.text='<div class="row-fluid"><p></p><ul><li>'+
_.map(self.availableAndQueued(),function(info){return info.displayName;}).join("</li><li>")+'</li></ul></p></div><div class="progress progress-softwareupdate '+
progress_class+'"><div class="bar">'+
countdownText+'</div><div class="progress-text" style="clip-path: inset(0 0 0 '+
progress_percent+"%);-webkit-clip-path: inset(0 0 0 "+
progress_percent+'%);">'+
countdownText+"</div></div>";queuedUpdatesPopupOptions.confirm={confirm:true,buttons:[{text:gettext("Cancel Updates"),addClass:"btn-block btn-danger",promptTrigger:true,click:function(notice,value){notice.remove();notice.get().trigger("pnotify.cancel",[notice,value]);}},{text:"",addClass:"hidden"}]};}else{if(typeof self.queuedUpdatesPopup!=="undefined"){self.queuedUpdatesPopup.remove();self.queuedUpdatesPopup=undefined;}
return;}
if(typeof self.queuedUpdatesPopup!=="undefined"){self.queuedUpdatesPopup.update(queuedUpdatesPopupOptions);}else{self.queuedUpdatesPopup=new PNotify(queuedUpdatesPopupOptions);self.queuedUpdatesPopup.get().on("pnotify.cancel",function(){self.queuedUpdatesPopup=undefined;self.cancelQueued();});self.queuedUpdatesPopup.get().on("pnotify.continue",function(){self.queuedUpdatesPopup=undefined;self.performUpdate(true,self.queuedUpdates());self._updateClicked=false;});}}else{if(typeof self.queuedUpdatesPopup!=="undefined"){self.queuedUpdatesPopup.remove();self.queuedUpdatesPopup=undefined;}}}
if(options!==undefined){self._showPopup(options);}}
self._forcedStdoutPatterns=["You are using pip version .*?, however version .*? is available.","You should consider upgrading via the '.*?' command.","'.*?' does not exist -- can't clean it"];self._forcedStdoutLine=new RegExp(self._forcedStdoutPatterns.join("|"));self._preprocessLine=function(line){if(line.stream==="stderr"&&line.line.match(self._forcedStdoutLine)){line.stream="stdout";}
return line;};};}
OCTOPRINT_VIEWMODELS.push({construct:SoftwareUpdateViewModel,dependencies:["loginStateViewModel","printerStateViewModel","settingsViewModel","accessViewModel","piSupportViewModel"],optional:["piSupportViewModel"],elements:["#settings_plugin_softwareupdate","#softwareupdate_confirmation_dialog","#wizard_plugin_softwareupdate_update","#wizard_plugin_softwareupdate_settings"]});});
;

// source: plugin/tracking/js/usage.js
$(function(){function UsageViewModel(parameters){var self=this;self.settingsViewModel=parameters[0];self.setup=ko.observable(false);self.decision=ko.observable();self.active=ko.observable();self.required=false;self.onStartupComplete=function(){OctoPrint.plugins.tracking.track("webui_load",{browser_name:OctoPrint.coreui.browser.browser_name,browser_version:OctoPrint.coreui.browser.browser_version,os_name:OctoPrint.coreui.browser.os_name,os_version:OctoPrint.coreui.browser.os_version});};self.enableUsage=function(){self.settingsViewModel.settings.plugins.tracking.enabled(true);self.decision(true);self._sendData();};self.disableUsage=function(){self.settingsViewModel.settings.plugins.tracking.enabled(false);self.decision(false);self._sendData();};self.onBeforeWizardTabChange=function(next,current){if(!self.required)return true;if(!current||!_.startsWith(current,"wizard_plugin_tracking")||self.setup()){return true;}
self._showDecisionNeededDialog();return false;};self.onBeforeWizardFinish=function(){if(!self.required)return true;if(self.setup()){return true;}
self._showDecisionNeededDialog();return false;};self.onWizardDetails=function(response){self.required=response&&response.tracking&&response.tracking.required;};self._showDecisionNeededDialog=function(){showMessageDialog({title:gettext("Please set up anonymous usage tracking"),message:gettext("You haven't yet decided on whether to enable or disable anonymous usage tracking. You need to either enable or disable it before continuing.")});};self._sendData=function(){var data={plugins:{tracking:{enabled:self.settingsViewModel.settings.plugins.tracking.enabled()}}};self.active(true);self.settingsViewModel.saveData(data).done(function(){self.setup(true);self.active(false);}).fail(function(){self.decision(false);self.setup(true);self.active(false);var message=gettext("Please open a <a href='%(bugreport)s' target='_blank' rel='noopener noreferrer'>"+"bug report</a> on this. Make sure to include all requested information, including your "+"<a href='%(jsconsole)s' target='_blank' rel='noopener noreferrer'>JS console</a> and "+"<code>octoprint.log</code>.");new PNotify({title:gettext("Something went wrong"),text:_.sprintf(message,{bugreport:"https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report",jsconsole:"https://webmasters.stackexchange.com/a/77337"}),type:"error",hide:false});});};}
OCTOPRINT_VIEWMODELS.push([UsageViewModel,["settingsViewModel"],"#wizard_plugin_tracking"]);});
;

// source: js/app/dataupdater.js
function DataUpdater(allViewModels,connectCallback,disconnectCallback){var self=this;self.allViewModels=allViewModels;self.connectCallback=connectCallback;self.disconnectCallback=disconnectCallback;self._pluginHash=undefined;self._configHash=undefined;self._connectedDeferred=undefined;self._initializedDeferred=undefined;self._throttleFactor=1;self._baseProcessingLimit=500.0;self._lastProcessingTimes=[];self._lastProcessingTimesSize=20;self._safeModePopup=undefined;self._reloadPopup=undefined;self.increaseThrottle=function(){self.setThrottle(self._throttleFactor+1);};self.decreaseThrottle=function(){if(self._throttleFactor<=1){return;}
self.setThrottle(self._throttleFactor-1);};self.setThrottle=function(throttle){self._throttleFactor=throttle;self._send("throttle",self._throttleFactor);log.debug("DataUpdater: New SockJS throttle factor:",self._throttleFactor," new processing limit:",self._baseProcessingLimit*self._throttleFactor);};self._send=function(message,data){var payload={};payload[message]=data;self._socket.send(JSON.stringify(payload));};self.connect=function(){if(self._connectedDeferred){self._connectedDeferred.reject("reconnect");}
self._connectedDeferred=$.Deferred();OctoPrint.socket.connect({debug:!!SOCKJS_DEBUG,connectTimeout:SOCKJS_CONNECT_TIMEOUT});return self._connectedDeferred.promise();};self.reconnect=function(){if(self._connectedDeferred){self._connectedDeferred.reject("reconnect");}
self._connectedDeferred=$.Deferred();OctoPrint.socket.reconnect();return self._connectedDeferred.promise();};self.initialized=function(){if(self._initializedDeferred){self._initializedDeferred.resolve();self._initializedDeferred=undefined;}};self._onReconnectAttempt=function(trial){if(trial<=0){return;}
var handled=false;callViewModelsIf(self.allViewModels,"onServerDisconnect",function(){return!handled;},function(method){var result=method();handled=(result!==undefined&&!result)||handled;});if(handled){return true;}
showOfflineOverlay(gettext("Server is offline"),gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),self.reconnect);};self._onReconnectFailed=function(){var handled=false;callViewModelsIf(self.allViewModels,"onServerDisconnect",function(){return!handled;},function(method){var result=method();handled=(result!==undefined&&!result)||handled;});if(handled){return;}
$("#offline_overlay_title").text(gettext("Server is offline"));$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));};self._onDisconnected=function(code){if(self._initializedDeferred){self._initializedDeferred.reject();}
self._initializedDeferred=undefined;if(self.disconnectCallback){self.disconnectCallback();}};self._onConnectTimeout=function(){if(self._connectedDeferred){self._connectedDeferred.reject("timeout");}};self._onConnectMessage=function(event){if(self._initializedDeferred){self._initializedDeferred.reject();}
self._initializedDeferred=$.Deferred();if(self.connectCallback){self.connectCallback();}
var data=event.data;PERMISSIONS=data["permissions"];var oldVersion=VERSION;VERSION=data["version"];DISPLAY_VERSION=data["display_version"];BRANCH=data["branch"];PYTHON_VERSION=data["python_version"];$("span.version").text(DISPLAY_VERSION);$("span.python_version").text(PYTHON_VERSION);ONLINE=data["online"];var oldPluginHash=self._pluginHash;self._pluginHash=data["plugin_hash"];var oldConfigHash=self._configHash;self._configHash=data["config_hash"];log.info("Connected to the server");if(self._connectedDeferred){self._connectedDeferred.resolve();self._connectedDeferred=undefined;}
self._ifInitialized(function(){if(self._safeModePopup)self._safeModePopup.remove();if(data["safe_mode"]){log.info("❗ Safe mode is active. Third party plugins and language packs are disabled and cannot be enabled.");log.info("❗ Reason for safe mode: "+data["safe_mode"]);var reason=gettext("Unknown");switch(data["safe_mode"]){case"flag":{reason=gettext("Command line flag");break;}
case"settings":{reason=gettext("Setting in config.yaml");break;}
case"incomplete_startup":{reason=gettext("Problem during last startup");break;}}
self._safeModePopup=new PNotify({title:gettext("Safe mode is active"),text:_.sprintf(gettext("<p>The server is currently running in safe mode. Third party plugins and language packs are disabled and cannot be enabled.</p><p>Reason: %(reason)s</p>"),{reason:_.escape(reason)}),hide:false});}
if($("#offline_overlay").is(":visible")){hideOfflineOverlay();log.info("Triggering reconnect on all view models");callViewModels(self.allViewModels,"onServerReconnect");callViewModels(self.allViewModels,"onDataUpdaterReconnect");}else{log.info("Triggering connect on all view models");callViewModels(self.allViewModels,"onServerConnect");}
const versionChanged=oldVersion!==VERSION;const pluginsChanged=oldPluginHash!==undefined&&oldPluginHash!==self._pluginHash;const configChanged=oldConfigHash!==undefined&&oldConfigHash!==self._configHash;if(versionChanged){showReloadOverlay();}else if(pluginsChanged||configChanged){if(self._reloadPopup)self._reloadPopup.remove();let text;if(pluginsChanged&&configChanged){text=gettext("A client reconnect happened and the configuration of the server and the active UI relevant plugins have changed.");}else if(pluginsChanged){text=gettext("A client reconnect happened and the active UI relevant plugins have changed.");}else if(configChanged){text=gettext("A client reconnect happened and the configuration of the server has changed.");}
self._reloadPopup=new PNotify({title:gettext("Page reload recommended"),text:"<p>"+
text+"</p>"+"<p>"+
gettext("Due to this a reload of the UI is recommended. "+"Please reload the UI now by clicking "+'the "Reload" button below. This will not interrupt '+"any print jobs you might have ongoing.")+"</p>",hide:false,confirm:{confirm:true,buttons:[{text:gettext("Ignore"),click:function(){self._reloadPopup.remove();}},{text:gettext("Reload"),addClass:"btn-primary",click:function(){self._reloadPopup.remove();location.reload(true);}}]},buttons:{closer:false,sticker:false}});}
log.info("Server (re)connect processed");});};self._onHistoryData=function(event){self._ifInitialized(function(){callViewModels(self.allViewModels,"fromHistoryData",[event.data]);});};self._onCurrentData=function(event){self._ifInitialized(function(){callViewModels(self.allViewModels,"fromCurrentData",[event.data]);});};self._onSlicingProgress=function(event){self._ifInitialized(function(){$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"),{percentage:Math.round(event.data["progress"])}));var data=event.data;callViewModels(self.allViewModels,"onSlicingProgress",[data["slicer"],data["model_path"],data["machinecode_path"],data["progress"]]);});};self._onRenderProgress=function(event){self._ifInitialized(function(){var data=event.data;callViewModels(self.allViewModels,"onRenderProgress",[data["progress"]]);});};self._printerErrorCancelNotification=undefined;self._printerErrorDisconnectNotification=undefined;self._printerResetNotification=undefined;self._onEvent=function(event){self._ifInitialized(function(){var type=event.data["type"];var payload=event.data["payload"];var title,text,severity;log.debug("Got event "+type+" with payload: "+JSON.stringify(payload));if(type==="PrintCancelling"&&payload.firmwareError){if(self._printerErrorCancelNotification!==undefined){self._printerErrorCancelNotification.remove();}
self._printerErrorCancelNotification=new PNotify({title:gettext("Error reported by printer"),text:_.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"),{firmwareError:_.escape(payload.firmwareError)}),type:"error",hide:false});}else if(type==="Error"&&payload.error){severity="error";switch(payload.reason){case"firmware":{title=gettext("Error reported by printer");text=_.sprintf(gettext("Your printer's firmware reported an error. Due to that OctoPrint will disconnect. Reported error: %(error)s"),{error:_.escape(payload.error)});break;}
case"resend":case"resend_loop":case"timeout":{title=gettext("Communication error");text=_.sprintf(gettext("There was a communication error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"),{error:_.escape(payload.error)});break;}
case"connection":{title=gettext("Error connecting to printer");text=_.sprintf(gettext("There was an error while trying to connect to your printer. Error: %(error)s"),{error:_.escape(payload.error)});break;}
case"start_print":{title=gettext("Error starting a print");text=_.sprintf(gettext("There was an error while trying to start a print job. Error: %(error)s"),{error:_.escape(payload.error)});break;}
case"autodetect":{title=gettext("Could not autodetect your printer");text=_.sprintf(gettext('No working connection parameters could be found. Are you sure your printer is physically connected and supported? Refer to <a href="%(url)s" target="_blank" rel="noopener noreferer">the FAQ</a> for help in debugging this.'),{url:"https://faq.octoprint.org/connection-error"});break;}
default:{title=gettext("Unknown error");text=_.sprintf(gettext("There was an unknown error while talking to your printer. Please consult the terminal output and octoprint.log for details. Error: %(error)s"),{error:_.escape(payload.error)});break;}}
if(title&&text){if(self._printerErrorDisconnectNotification!==undefined){self._printerErrorDisconnectNotification.remove();}
self._printerErrorDisconnectNotification=new PNotify({title:title,text:text,type:severity,hide:false});}}else if(type==="PrinterReset"){if(payload.idle){text=gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");severity="alert";}else{text=gettext("It looks like your printer reset while a connection was active. Due to this the ongoing job was aborted. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");severity="error";}
if(self._printerResetNotification!==undefined){self._printerResetNotification.remove();}
self._printerResetNotification=new PNotify({title:gettext("Printer reset detected"),text:text,type:severity,hide:false});}else if(type==="ConnectivityChanged"){ONLINE=payload.new;}else if(type==="SettingsUpdated"){self._configHash=payload.config_hash;}
var legacyEventHandlers={UpdatedFiles:"onUpdatedFiles",MetadataStatisticsUpdated:"onMetadataStatisticsUpdated",MetadataAnalysisFinished:"onMetadataAnalysisFinished",SlicingDone:"onSlicingDone",SlicingCancelled:"onSlicingCancelled",SlicingFailed:"onSlicingFailed"};const camelCaseType=type.split("_").map((item)=>item.charAt(0).toUpperCase()+item.slice(1)).join("");_.each(self.allViewModels,function(viewModel){if(viewModel.hasOwnProperty("onEvent"+camelCaseType)){viewModel["onEvent"+camelCaseType](payload);}else if(type!==camelCaseType&&viewModel.hasOwnProperty("onEvent"+type)){viewModel["onEvent"+type](payload);}else if(legacyEventHandlers.hasOwnProperty(type)&&viewModel.hasOwnProperty(legacyEventHandlers[type])){log.warn("View model "+
viewModel.name+" is using legacy event handler "+
legacyEventHandlers[type]+", new handler is called "+
legacyEventHandlers[type]);viewModel[legacyEventHandlers[type]](payload);}});});};self._onTimelapse=function(event){self._ifInitialized(function(){callViewModels(self.allViewModels,"fromTimelapseData",[event.data]);});};self._onPluginMessage=function(event){self._ifInitialized(function(){callViewModels(self.allViewModels,"onDataUpdaterPluginMessage",[event.data.plugin,event.data.data]);});};self._onReauthMessage=function(event){self._ifInitialized(function(){callViewModels(self.allViewModels,"onDataUpdaterReauthRequired",[event.data.reason]);});};self._onIncreaseRate=function(measurement,minimum){log.debug("We are fast ("+measurement+" < "+minimum+"), increasing refresh rate");OctoPrint.socket.increaseRate();};self._onDecreaseRate=function(measurement,maximum){log.debug("We are slow ("+measurement+" > "+maximum+"), reducing refresh rate");OctoPrint.socket.decreaseRate();};self._ifInitialized=function(callback){if(self._initializedDeferred){self._initializedDeferred.done(callback);}else{callback();}};OctoPrint.socket.onDisconnected=self._onDisconnected;OctoPrint.socket.onReconnectAttempt=self._onReconnectAttempt;OctoPrint.socket.onReconnectFailed=self._onReconnectFailed;OctoPrint.socket.onConnectTimeout=self._onConnectTimeout;OctoPrint.socket.onRateTooHigh=self._onDecreaseRate;OctoPrint.socket.onRateTooLow=self._onIncreaseRate;OctoPrint.socket.onMessage("connected",self._onConnectMessage).onMessage("history",self._onHistoryData).onMessage("current",self._onCurrentData).onMessage("slicingProgress",self._onSlicingProgress).onMessage("renderProgress",self._onRenderProgress).onMessage("event",self._onEvent).onMessage("timelapse",self._onTimelapse).onMessage("plugin",self._onPluginMessage).onMessage("reauthRequired",self._onReauthMessage);}
;

// source: js/app/helpers.js
function ItemListHelper(listType,supportedSorting,supportedFilters,defaultSorting,defaultFilters,exclusiveFilters,defaultPageSize,persistPageSize){var self=this;self.listType=listType;self.supportedSorting=supportedSorting;self.supportedFilters=supportedFilters;self.defaultSorting=defaultSorting;self.defaultFilters=defaultFilters;self.exclusiveFilters=exclusiveFilters;self.defaultPageSize=defaultPageSize;self.persistPageSize=!!persistPageSize;self.searchFunction=undefined;self.allItems=[];self.allSize=ko.observable(0);self.items=ko.observableArray([]);self.pageSize=ko.observable(self.defaultPageSize);self.currentPage=ko.observable(0);self.currentSorting=ko.observable(self.defaultSorting);self.currentFilters=ko.observableArray(self.defaultFilters);self.selectedItem=ko.observable(undefined);self.filterSearch=ko.observable(true);self.storageIds={currentSorting:self.listType+"."+"currentSorting",currentFilters:self.listType+"."+"currentFilters",pageSize:self.listType+"."+"pageSize"};self.refresh=function(){self._updateItems();};self.updateItems=function(items){if(items===undefined)items=[];self.allItems=items;self.allSize(items.length);self._updateItems();};self.selectItem=function(matcher){var itemList=self.items();for(var i=0;i<itemList.length;i++){if(matcher(itemList[i])){self.selectedItem(itemList[i]);return true;}}
return false;};self.selectNone=function(){self.selectedItem(undefined);};self.isSelected=function(data){return self.selectedItem()===data;};self.isSelectedByMatcher=function(matcher){return matcher(self.selectedItem());};self.removeItem=function(matcher){var index=self.getIndex(matcher,true);if(index>-1){self.allItems.splice(index,1);self._updateItems();}};self.updateItem=function(matcher,item){var index=self.allItems.findIndex(matcher);if(index>-1){self.allItems[index]=item;self._updateItems();}};self.addItem=function(item){self.allItems.push(item);self._updateItems();};self.paginatedItems=ko.dependentObservable(function(){if(self.items()===undefined){return[];}else if(self.pageSize()===0){return self.items();}else{var from=Math.max(self.currentPage()*self.pageSize(),0);var to=Math.min(from+self.pageSize(),self.items().length);return self.items().slice(from,to);}});self.lastPage=ko.dependentObservable(function(){return self.pageSize()===0?1:Math.ceil(self.items().length/self.pageSize())-1;});self.pages=ko.dependentObservable(function(){var pages=[];var i;if(self.pageSize()===0){pages.push({number:0,text:1});}else if(self.lastPage()<7){for(i=0;i<self.lastPage()+1;i++){pages.push({number:i,text:i+1});}}else{pages.push({number:0,text:1});if(self.currentPage()<5){for(i=1;i<5;i++){pages.push({number:i,text:i+1});}
pages.push({number:-1,text:"…"});}else if(self.currentPage()>self.lastPage()-5){pages.push({number:-1,text:"…"});for(i=self.lastPage()-4;i<self.lastPage();i++){pages.push({number:i,text:i+1});}}else{pages.push({number:-1,text:"…"});for(i=self.currentPage()-1;i<=self.currentPage()+1;i++){pages.push({number:i,text:i+1});}
pages.push({number:-1,text:"…"});}
pages.push({number:self.lastPage(),text:self.lastPage()+1});}
return pages;});self.switchToItem=function(matcher){var pos=-1;var itemList=self.items();for(var i=0;i<itemList.length;i++){if(matcher(itemList[i])){pos=i;break;}}
if(pos>-1){var page=Math.floor(pos/self.pageSize());self.changePage(page);}};self.changePage=function(newPage){if(newPage<0||newPage>self.lastPage())return;self.currentPage(newPage);};self.prevPage=function(){if(self.currentPage()>0){self.currentPage(self.currentPage()-1);}};self.nextPage=function(){if(self.currentPage()<self.lastPage()){self.currentPage(self.currentPage()+1);}};self.getIndex=function(matcher,all){var itemList;if(all!==undefined&&all===true){itemList=self.allItems;}else{itemList=self.items();}
for(var i=0;i<itemList.length;i++){if(matcher(itemList[i])){return i;}}
return-1;};self.getItem=function(matcher,all){var index=self.getIndex(matcher,all);if(all!==undefined&&all===true){return index>-1?self.allItems[index]:undefined;}else{return index>-1?self.items()[index]:undefined;}};self.resetPage=function(){if(self.currentPage()>self.lastPage()){self.currentPage(self.lastPage());}};self.changeSearchFunction=function(searchFunction){self.searchFunction=searchFunction;self.changePage(0);self._updateItems();};self.resetSearch=function(){self.changeSearchFunction(undefined);};self.changeSorting=function(sorting){if(!_.contains(_.keys(self.supportedSorting),sorting))return;self.currentSorting(sorting);self._saveCurrentSortingToLocalStorage();self.changePage(0);self._updateItems();};self.setFilterSearch=function(enabled){if(self.filterSearch()===enabled)return;self.filterSearch(enabled);self.changePage(0);self._updateItems();};self.toggleFilterSearch=function(){self.setFilterSearch(!self.filterSearch());};self.toggleFilter=function(filter){if(!_.contains(_.keys(self.supportedFilters),filter))return;if(_.contains(self.currentFilters(),filter)){self.removeFilter(filter);}else{self.addFilter(filter);}};self.addFilter=function(filter){if(!_.contains(_.keys(self.supportedFilters),filter))return;for(var i=0;i<self.exclusiveFilters.length;i++){if(_.contains(self.exclusiveFilters[i],filter)){for(var j=0;j<self.exclusiveFilters[i].length;j++){if(self.exclusiveFilters[i][j]===filter)continue;self.removeFilter(self.exclusiveFilters[i][j]);}}}
var filters=self.currentFilters();filters.push(filter);self.currentFilters(filters);self._saveCurrentFiltersToLocalStorage();self.changePage(0);self._updateItems();};self.removeFilter=function(filter){if(!_.contains(_.keys(self.supportedFilters),filter))return;var filters=self.currentFilters();filters=_.without(filters,filter);self.currentFilters(filters);self._saveCurrentFiltersToLocalStorage();self.changePage(0);self._updateItems();};self._updateItems=function(){var comparator=undefined;var currentSorting=self.currentSorting();if(typeof currentSorting!=="undefined"&&typeof self.supportedSorting[currentSorting]!=="undefined"){comparator=self.supportedSorting[currentSorting];}
var result=self.allItems;var hasSearch=typeof self.searchFunction!=="undefined"&&self.searchFunction;if(!hasSearch||self.filterSearch()){var filters=self.currentFilters();_.each(filters,function(filter){if(typeof filter!=="undefined"&&typeof supportedFilters[filter]!=="undefined")
result=_.filter(result,supportedFilters[filter]);});}
if(hasSearch){result=_.filter(result,self.searchFunction);}
if(typeof comparator!=="undefined")result.sort(comparator);self.items(result);};self._saveCurrentSortingToLocalStorage=function(){if(self._initializeLocalStorage()){var currentSorting=self.currentSorting();if(currentSorting!==undefined)
localStorage[self.storageIds.currentSorting]=currentSorting;else localStorage[self.storageIds.currentSorting]=undefined;}};self._loadCurrentSortingFromLocalStorage=function(){if(self._initializeLocalStorage()){if(_.contains(_.keys(supportedSorting),localStorage[self.storageIds.currentSorting]))
self.currentSorting(localStorage[self.storageIds.currentSorting]);else self.currentSorting(defaultSorting);}};self._saveCurrentFiltersToLocalStorage=function(){if(self._initializeLocalStorage()){var filters=_.intersection(_.keys(self.supportedFilters),self.currentFilters());localStorage[self.storageIds.currentFilters]=JSON.stringify(filters);}};self._loadCurrentFiltersFromLocalStorage=function(){if(self._initializeLocalStorage()){self.currentFilters(_.intersection(_.keys(self.supportedFilters),JSON.parse(localStorage[self.storageIds.currentFilters])));}};self._savePageSizeToLocalStorage=function(pageSize){if(self._initializeLocalStorage()&&self.persistPageSize){localStorage[self.storageIds.pageSize]=pageSize;}};self.pageSize.subscribe(self._savePageSizeToLocalStorage);self._loadPageSizeFromLocalStorage=function(){if(self._initializeLocalStorage()&&self.persistPageSize){self.pageSize(parseInt(localStorage[self.storageIds.pageSize]));}};self._initializeLocalStorage=function(){if(!Modernizr.localstorage)return false;if(localStorage[self.storageIds.currentSorting]!==undefined&&localStorage[self.storageIds.currentFilters]!==undefined&&JSON.parse(localStorage[self.storageIds.currentFilters])instanceof Array&&localStorage[self.storageIds.pageSize]!==undefined)
return true;localStorage[self.storageIds.currentSorting]=self.defaultSorting;localStorage[self.storageIds.currentFilters]=JSON.stringify(self.defaultFilters);localStorage[self.storageIds.pageSize]=self.defaultPageSize;return true;};self._loadCurrentFiltersFromLocalStorage();self._loadCurrentSortingFromLocalStorage();self._loadPageSizeFromLocalStorage();}
function formatSize(bytes){if(!bytes)return"-";var units=["bytes","KB","MB","GB"];for(var i=0;i<units.length;i++){if(bytes<1024){return _.sprintf("%3.1f%s",bytes,units[i]);}
bytes/=1024;}
return _.sprintf("%.1f%s",bytes,"TB");}
function formatHuman(number){if(number===undefined)return"-";if(number<1000)return number;return _.sprintf("%.1fK",number/1000);}
function bytesFromSize(size){if(size===undefined||size.trim()==="")return undefined;var parsed=size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);var number=parsed[1];var unit=parsed[2].trim();if(unit==="")return parseFloat(number);var units={b:1,byte:1,bytes:1,kb:1024,mb:Math.pow(1024,2),gb:Math.pow(1024,3),tb:Math.pow(1024,4)};unit=unit.toLowerCase();if(!units.hasOwnProperty(unit)){return undefined;}
var factor=units[unit];return number*factor;}
function formatDuration(seconds){if(!seconds)return"-";if(seconds<1)return"00:00:00";var s=seconds%60;var m=(seconds%3600)/60;var h=seconds/3600;return _.sprintf(gettext("%(hour)02d:%(minute)02d:%(second)02d"),{hour:h,minute:m,second:s});}
function formatFuzzyEstimation(seconds,base){if(!seconds||seconds<1)return"-";var m;if(base!==undefined){m=moment(base);}else{m=moment();}
m.add(seconds,"s");return m.fromNow(true);}
function formatFuzzyPrintTime(totalSeconds){if(!totalSeconds||totalSeconds<1)return"-";var d=moment.duration(totalSeconds,"seconds");var seconds=d.seconds();var minutes=d.minutes();var hours=d.hours();var days=d.days();var replacements={days:days,hours:hours,minutes:minutes,seconds:seconds,totalSeconds:totalSeconds};var text="-";if(days>=1){if(hours>=16){replacements.days+=1;if(replacements.days===1){text=gettext("%(days)d day");}else{text=gettext("%(days)d days");}}else if(hours>=8&&hours<16){text=gettext("%(days)d.5 days");}else{if(days===1){text=gettext("%(days)d day");}else{text=gettext("%(days)d days");}}}else if(hours>=1){if(hours<12){if(minutes<15){if(hours===1){text=gettext("%(hours)d hour");}else{text=gettext("%(hours)d hours");}}else if(minutes>=15&&minutes<45){text=gettext("%(hours)d.5 hours");}else{replacements.hours+=1;if(replacements.hours===1){text=gettext("%(hours)d hour");}else{text=gettext("%(hours)d hours");}}}else{if(hours===23&&minutes>30){text=gettext("1 day");}else{if(minutes>30){replacements.hours+=1;}
text=gettext("%(hours)d hours");}}}else if(minutes>=1){if(minutes<2){if(seconds<30){text=gettext("a minute");}else{text=gettext("2 minutes");}}else if(minutes<30){if(seconds>30){replacements.minutes+=1;}
text=gettext("%(minutes)d minutes");}else if(minutes<=40){text=gettext("40 minutes");}else if(minutes<=50){text=gettext("50 minutes");}else{text=gettext("1 hour");}}else{if(seconds<30){text=gettext("a few seconds");}else{text=gettext("less than a minute");}}
return _.sprintf(text,replacements);}
function formatDate(unixTimestamp,options){if(!options){options={seconds:false};}
var placeholder=options.placeholder||"-";if(!unixTimestamp)return placeholder;var format=gettext("YYYY-MM-DD HH:mm");if(options.seconds){format=gettext("YYYY-MM-DD HH:mm:ss");}
return moment.unix(unixTimestamp).format(format);}
function formatTimeAgo(unixTimestamp,placeholder){placeholder=placeholder||"-";if(!unixTimestamp)return placeholder;return moment.unix(unixTimestamp).fromNow();}
function formatFilament(filament){if(!filament||!filament["length"])return"-";var result="%(length).02fm";if(filament.hasOwnProperty("volume")&&filament.volume){result+=" / "+"%(volume).02fcm³";}
return _.sprintf(result,{length:filament["length"]/1000,volume:filament["volume"]});}
function cleanTemperature(temp,offThreshold){if(temp===undefined||!_.isNumber(temp))return"-";if(offThreshold!==undefined&&temp<offThreshold)return gettext("off");return temp;}
function formatTemperature(temp,showF,offThreshold,returnUnicode){if(temp===undefined||!_.isNumber(temp)||isNaN(temp))return"-";if(offThreshold!==undefined&&temp<offThreshold)return gettext("off");var degreeSymbol="&deg;";if(returnUnicode!==undefined&&returnUnicode){degreeSymbol="\u00B0";}
if(showF){return _.sprintf("%.1f%sC (%.1f%sF)",temp,degreeSymbol,(temp*9)/5+32,degreeSymbol);}else{return _.sprintf("%.1f%sC",temp,degreeSymbol);}}
function formatNumberK(num){if(num>1000){num=num/1000.0;return _.sprintf("%.2fk",num);}else{return _.sprintf("%i",num);}}
function rsplit(str,sep,limit){const parts=str.split(sep);return limit?[parts.slice(0,-limit).join(sep)].concat(parts.slice(-limit)):parts;}
function pnotifyAdditionalInfo(inner){return('<div class="pnotify_additional_info">'+'<div class="pnotify_more"><a href="#" onclick="$(this).children().toggleClass(\'icon-caret-right icon-caret-down\').parent().parent().next().slideToggle(\'fast\')">More <i class="icon-caret-right"></i></a></div>'+'<div class="pnotify_more_container hide">'+
inner+"</div>"+"</div>");}
function ping(url,callback){var img=new Image();var calledBack=false;img.onload=function(){callback(true);calledBack=true;};img.onerror=function(){if(!calledBack){callback(true);calledBack=true;}};img.src=url;setTimeout(function(){if(!calledBack){callback(false);calledBack=true;}},1500);}
function showOfflineOverlay(title,message,reconnectCallback){if(title===undefined){title=gettext("Server is offline");}
$("#offline_overlay_title").text(title);$("#offline_overlay_message").html(message);$("#offline_overlay_reconnect").click(reconnectCallback);var overlay=$("#offline_overlay");if(!overlay.is(":visible"))overlay.show();}
function hideOfflineOverlay(){$("#offline_overlay").hide();}
function showMessageDialog(msg,options){options=options||{};if(_.isPlainObject(msg)){options=msg;}else{options.message=msg;}
var title=options.title||"";var message=options.message||"";var close=options.close||gettext("Close");var onclose=options.onclose||undefined;var onshow=options.onshow||undefined;var onshown=options.onshown||undefined;var nofade=options.nofade||false;if(_.isString(message)){message=$("<p>"+message+"</p>");}
var modalHeader=$('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>'+
title+"</h3>");var modalBody=$(message);var modalFooter=$('<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">'+
close+"</a>");var modal=$("<div></div>").addClass("modal hide");if(!nofade){modal.addClass("fade-in");}
modal.append($("<div></div>").addClass("modal-header").append(modalHeader)).append($("<div></div>").addClass("modal-body").append(modalBody)).append($("<div></div>").addClass("modal-footer").append(modalFooter));modal.on("hidden",function(){if(onclose&&_.isFunction(onclose)){onclose();}});if(onshow){modal.on("show",onshow);}
if(onshown){modal.on("shown",onshown);}
modal.modal("show");return modal;}
function showConfirmationDialog(msg,onacknowledge,options){options=options||{};if(_.isPlainObject(msg)){options=msg;}else{options.message=msg;options.onproceed=onacknowledge;}
var title=options.title||gettext("Are you sure?");var message=options.message||"";var question=options.question||gettext("Are you sure you want to proceed?");var html=options.html;var checkboxes=options.checkboxes;var cancel=options.cancel||gettext("Cancel");var proceed=options.proceed||gettext("Proceed");var proceedClass=options.proceedClass||"danger";var onproceed=options.onproceed||undefined;var oncancel=options.oncancel||undefined;var onclose=options.onclose||undefined;var dialogClass=options.dialogClass||"";var nofade=options.nofade||false;var noclose=options.noclose||false;var modalHeader;if(noclose){modalHeader=$("<h3>"+title+"</h3>");}else{modalHeader=$('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>'+
title+"</h3>");}
var modalBody;if(html){modalBody=$(html);}else{modalBody=$("<p>"+message+"</p><p>"+question+"</p>");}
var cancelButton=$('<a href="javascript:void(0)" class="btn">'+cancel+"</a>").attr("data-dismiss","modal").attr("aria-hidden","true");if(!_.isArray(proceed)){proceed=[proceed];}
var proceedButtons=[];_.each(proceed,function(text){proceedButtons.push($('<a href="javascript:void(0)" class="btn">'+text+"</a>").addClass("btn-"+proceedClass));});var modal=$("<div></div>").addClass("modal hide");if(!nofade){modal.addClass("fade-in");}
var buttons=$("<div></div>").addClass("modal-footer").append(cancelButton);_.each(proceedButtons,function(button){buttons.append(button);});modal.addClass(dialogClass).append($("<div></div>").addClass("modal-header").append(modalHeader)).append($("<div></div>").addClass("modal-body").append(modalBody)).append(buttons);modal.on("hidden",function(event){if(onclose&&_.isFunction(onclose)){onclose(event);}});var modalOptions={};if(noclose){modalOptions.backdrop="static";modalOptions.keyboard=false;}
modal.modal(modalOptions);_.each(proceedButtons,function(button,idx){button.click(function(e){e.preventDefault();if(onproceed&&_.isFunction(onproceed)){onproceed(idx,e);}
modal.modal("hide");});});cancelButton.click(function(e){if(oncancel&&_.isFunction(oncancel)){oncancel(e);}});return modal;}
function showSelectionDialog(options){var title=options.title;var message=options.message||undefined;var selections=options.selections||[];var maycancel=options.maycancel||false;var cancel=options.cancel||undefined;var onselect=options.onselect||undefined;var onclose=options.onclose||undefined;var dialogClass=options.dialogClass||"";var nofade=options.nofade||false;var modalHeader;if(maycancel){modalHeader=$('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>'+
title+"</h3>");}else{modalHeader=$("<h3>"+title+"</h3>");}
var buttons=[];var selectionBody=$("<div></div>");var container;var additionalClass;if(selections.length===1){container=selectionBody;additionalClass="btn-block";}else if(selections.length===2){container=$("<div class='row-fluid'></div>");selectionBody.append(container);additionalClass="span6";}else{container=selectionBody;additionalClass="btn-block";}
_.each(selections,function(s,i){var button=$('<button class="btn" style="white-space: normal; word-wrap: break-word" data-index="'+
i+'">'+
selections[i]+"</button>");if(additionalClass){button.addClass(additionalClass);}
container.append(button);buttons.push(button);if(selections.length>2&&i<selections.length-1){container=$("<div class='row-fluid'></div>");selectionBody.append(container);}});var headerDiv=$("<div></div>").addClass("modal-header").append(modalHeader);var bodyDiv=$("<div></div>").addClass("modal-body");if(message){bodyDiv.append($("<p>"+message+"</p>"));}
bodyDiv.append(selectionBody);var modal=$("<div></div>").addClass("modal hide");if(!nofade){modal.addClass("fade-in");}
if(!cancel){modal.data("backdrop","static").data("keyboard","false");}
modal.addClass(dialogClass).append(headerDiv).append(bodyDiv);modal.on("hidden",function(event){if(onclose&&_.isFunction(onclose)){onclose(event);}});modal.modal("show");_.each(buttons,function(button){button.click(function(e){e.preventDefault();var index=button.data("index");if(index<0){return;}
if(onselect&&_.isFunction(onselect)){onselect(index,e);}
modal.modal("hide");});});return modal;}
function showProgressModal(options,promise){var title=options.title||gettext("Progress");var message=options.message||"";var buttonText=options.button||gettext("Close");var max=options.max||undefined;var close=options.close||false;var output=options.output||false;var dialogClass=options.dialogClass||"";var barClassSuccess=options.barClassSuccess||"";var barClassFailure=options.barClassFailure||"bar-danger";var outputClassSuccess=options.outputClassSuccess||"";var outputClassFailure=options.outputClassFailure||"text-error";var modalHeader=$("<h3>"+title+"</h3>");var paragraph=$("<p>"+message+"</p>");var progress=$('<div class="progress progress-text-centered"></div>');var progressBar=$('<div class="bar"></div>').addClass(barClassSuccess);var progressText=$('<span class="progress-text-back"></span>');if(max===undefined){progress.addClass("progress-striped active");progressBar.width("100%");}
progress.append(progressBar).append(progressText);var button=$('<button class="btn">'+buttonText+"</button>").prop("disabled",true).attr("data-dismiss","modal").attr("aria-hidden","true");var modalBody=$("<div></div>").addClass("modal-body").append(paragraph).append(progress);var pre;if(output){pre=$("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");modalBody.append(pre);}
var modal=$("<div></div>").addClass("modal hide fade-in").addClass(dialogClass).append($("<div></div>").addClass("modal-header").append(modalHeader)).append(modalBody).append($("<div></div>").addClass("modal-footer").append(button));modal.modal({keyboard:false,backdrop:"static",show:true});var counter=0;promise.progress(function(){var short,long,success;if(arguments.length===2){short=long=arguments[0];success=arguments[1];}else if(arguments.length===3){short=arguments[0];long=arguments[1];success=arguments[2];}else{throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");}
var value;if(max===undefined||max<=0){value=100;}else{counter++;value=Math.max(Math.min((counter*100)/max,100),0);}
progressBar.width(String(value)+"%");progressText.text(short);if(value<50&&progressText.hasClass("progress-text-front")){progressText.removeClass("progress-text-front").addClass("progress-text-back");}else if(value>=50&&progressText.hasClass("progress-text-back")){progressText.removeClass("progress-text-back").addClass("progress-text-front");}
if(!success&&!progressBar.hasClass(barClassFailure)){progressBar.removeClass(barClassSuccess).addClass(barClassFailure);}
if(output&&pre){if(success){pre.append($("<span class='"+outputClassSuccess+"'>"+long+"</span>"));}else{pre.append($("<span class='"+outputClassFailure+"'>"+long+"</span>"));}
pre.scrollTop(pre[0].scrollHeight-pre.height());}}).done(function(){button.prop("disabled",false);if(close){modal.modal("hide");}}).fail(function(){button.prop("disabled",false);});return modal;}
function showReloadOverlay(){$("#reloadui_overlay").show();}
function wrapPromiseWithAlways(p){var deferred=$.Deferred();p.always(function(){deferred.resolve.apply(deferred,arguments);});return deferred.promise();}
function commentableLinesToArray(lines){return splitTextToArray(lines,"\n",true,function(item){return!_.startsWith(item,"#");});}
function splitTextToArray(text,sep,stripEmpty,filter){return _.filter(_.map(text.split(sep),function(item){return item?item.trim():"";}),function(item){return(stripEmpty?item:true)&&(filter?filter(item):true);});}
function hasDataChanged(data,oldData){if(data==oldData&&data==undefined){return false;}
if(_.isPlainObject(data)&&_.isPlainObject(oldData)){return _.any(_.keys(data),function(key){return hasDataChanged(data[key],oldData[key]);});}else{return!_.isEqual(data,oldData);}}
function getOnlyChangedData(data,oldData){if(data==undefined){return{};}
if(oldData==undefined){return data;}
var f=function(root,oldRoot){if(!_.isPlainObject(root)){return root;}
var retval={};_.forOwn(root,function(value,key){var oldValue=undefined;if(oldRoot!=undefined&&oldRoot.hasOwnProperty(key)){oldValue=oldRoot[key];}
if(_.isPlainObject(value)){if(oldValue==undefined){retval[key]=value;}else if(hasDataChanged(value,oldValue)){retval[key]=f(value,oldValue);}}else{if(!(value==oldValue&&value==undefined)&&!_.isEqual(value,oldValue)){retval[key]=value;}}});return retval;};return f(data,oldData);}
function setOnViewModels(allViewModels,key,value){setOnViewModelsIf(allViewModels,key,value,undefined);}
function setOnViewModelsIf(allViewModels,key,value,condition){if(!allViewModels)return;_.each(allViewModels,function(viewModel){setOnViewModelIf(viewModel,key,value,condition);});}
function setOnViewModel(viewModel,key,value){setOnViewModelIf(viewModel,key,value,undefined);}
function setOnViewModelIf(viewModel,key,value,condition){if(condition===undefined||!_.isFunction(condition)){condition=function(){return true;};}
try{if(!condition(viewModel)){return;}
viewModel[key]=value;}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Error while setting",key,"to",value,"on view model",viewModel.constructor.name,":",`${exc.message}\n${exc.stack || exc}`);}}
function callViewModels(allViewModels,method,callback){callViewModelsIf(allViewModels,method,undefined,callback);}
function callViewModelsIf(allViewModels,method,condition,callback){if(!allViewModels)return;_.each(allViewModels,function(viewModel){try{callViewModelIf(viewModel,method,condition,callback);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Error calling",method,"on view model",viewModel.constructor.name,":",`${exc.message}\n${exc.stack || exc}`);}});}
function callViewModel(viewModel,method,callback,raiseErrors){callViewModelIf(viewModel,method,undefined,callback,raiseErrors);}
function callViewModelIf(viewModel,method,condition,callback,raiseErrors){raiseErrors=raiseErrors===true||false;if(condition===undefined||!_.isFunction(condition)){condition=function(){return true;};}
if(!_.isFunction(viewModel[method])||!condition(viewModel,method))return;var parameters=undefined;if(!_.isFunction(callback)){if(callback===undefined){parameters=undefined;log.trace("Calling method",method,"on view model");}else if(_.isArray(callback)){parameters=callback;log.trace("Calling method",method,"on view model with specified parameters",parameters);}else{return;}
callback=undefined;}else{log.trace("Providing method",method,"on view model to specified callback",callback);}
try{if(callback===undefined){if(parameters!==undefined){viewModel[method].apply(viewModel,parameters);}else{viewModel[method]();}}else{callback(viewModel[method],viewModel);}}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
if(raiseErrors){throw exc;}else{log.error("Error calling",method,"on view model",viewModel.constructor.name,":",`${exc.message}\n${exc.stack || exc}`);}}}
var sizeObservable=function(observable){return ko.computed({read:function(){return formatSize(observable());},write:function(value){var result=bytesFromSize(value);if(result!==undefined){observable(result);}}});};var getQueryParameterByName=function(name,url){if(!url){url=fetchWindowLocation().href;}
name=name.replace(/[\[\]]/g,"\\$&");var regex=new RegExp("[?&]"+name+"(=([^&#]*)|&|#|$)"),results=regex.exec(url);if(!results)return null;if(!results[2])return"";return decodeURIComponent(results[2].replace(/\+/g," "));};var escapeUnprintableCharacters=function(str){var result="";var index=0;var charCode;while(!isNaN((charCode=str.charCodeAt(index)))){if((charCode<32&&charCode!==9&&charCode!==10&&charCode!==13)||charCode===127||(charCode>=128&&charCode<=159)||charCode===255){result+="\\x"+(charCode>15?"":"0")+charCode.toString(16);}else{result+=str[index];}
index++;}
return result;};var copyToClipboard=function(text){var temp=$("<textarea>");$("body").append(temp);temp.val(text).select();document.execCommand("copy");temp.remove();};var getExternalHostUrl=function(){var loc=fetchWindowLocation();var port="";if((loc.protocol==="http:"&&loc.port!=="80")||(loc.protocol==="https:"&&loc.port!=="443")){port=":"+loc.port;}
return loc.protocol+"//"+loc.hostname+port;};var validateWebcamUrl=function(streamUrl){if(!streamUrl){return false;}
var lower=streamUrl.toLowerCase();var toParse=streamUrl;if(lower.startsWith("//")){toParse=fetchWindowLocation().protocol+streamUrl;}else if(lower.startsWith("/")){toParse=getExternalHostUrl()+streamUrl;}else if(lower.startsWith("http:")||lower.startsWith("https:")||lower.startsWith("webrtc:")||lower.startsWith("webrtcs:")){toParse=streamUrl;}else{return false;}
try{return new URL(toParse);}catch(e){return false;}};var determineWebcamStreamType=function(streamUrl){if(!streamUrl){throw"Empty streamUrl. Cannot determine stream type.";}
var parsed=validateWebcamUrl(streamUrl);if(!parsed){throw"Invalid streamUrl. Cannot determine stream type.";}
if(parsed.protocol==="webrtc:"||parsed.protocol==="webrtcs:"){return"webrtc";}
var lastDotPosition=parsed.pathname.lastIndexOf(".");if(lastDotPosition!==-1){var extension=parsed.pathname.substring(lastDotPosition+1);if(extension.toLowerCase()==="m3u8"){return"hls";}}
return"mjpg";};var saveToLocalStorage=function(key,data){if(!Modernizr.localstorage)return;localStorage[key]=JSON.stringify(data);};var loadFromLocalStorage=function(key,defaultValue){defaultValue=defaultValue===undefined?{}:defaultValue;if(!Modernizr.localstorage)return defaultValue;var currentString=localStorage[key];var current;if(currentString===undefined){current=defaultValue;}else{try{current=JSON.parse(currentString);}catch(ex){current=defaultValue;}}
return current;};var deepMerge=function(target,source){if(!_.isObject(target)){return target;}
_.forOwn(source,function(value,key){if(target.hasOwnProperty(key)&&_.isPlainObject(target[key])&&_.isPlainObject(value)){target[key]=deepMerge(target[key],value);}else{target[key]=value;}});return target;};var isWebRTCAvailable=function(){return(typeof RTCPeerConnection=="function"&&typeof RTCPeerConnection.prototype.addEventListener=="function"&&typeof RTCPeerConnection.prototype.addTransceiver=="function"&&typeof RTCPeerConnection.prototype.createOffer=="function"&&typeof RTCPeerConnection.prototype.setLocalDescription=="function"&&typeof RTCPeerConnection.prototype.removeEventListener=="function"&&typeof RTCPeerConnection.prototype.addEventListener=="function"&&typeof RTCPeerConnection.prototype.setRemoteDescription=="function");};var negotiateWebRTC=function(streamUrl){pc.addTransceiver("video",{direction:"recvonly"});pc.addTransceiver("audio",{direction:"recvonly"});return pc.createOffer().then(function(offer){return pc.setLocalDescription(offer);}).then(function(){return new Promise(function(resolve){if(pc.iceGatheringState==="complete"){resolve();}else{function checkState(){if(pc.iceGatheringState==="complete"){pc.removeEventListener("icegatheringstatechange",checkState);resolve();}}
pc.addEventListener("icegatheringstatechange",checkState);}});}).then(function(){var offer=pc.localDescription;streamUrl="http"+streamUrl.slice("webrtc".length);return $.ajax({url:streamUrl,type:"POST",dataType:"json",data:JSON.stringify({sdp:offer.sdp,type:offer.type}),contentType:"application/json; charset=UTF-8"});}).then(function(response){return pc.setRemoteDescription(response);}).catch(function(e){console.error(e);});};var startWebRTC=function(videoElement,streamUrl,iceServers){var config={sdpSemantics:"unified-plan"};if(iceServers){config.iceServers=[{urls:iceServers}];}
pc=new RTCPeerConnection(config);pc.addEventListener("track",function(evt){if(evt.track.kind=="video"){videoElement.srcObject=evt.streams[0];}});negotiateWebRTC(streamUrl);return pc;};var fetchWindowLocation=function(){return window.location;};
;

// source: js/app/main.js
$(function(){OctoPrint=window.OctoPrint;$("#page-container-loading").show();_.mixin({sprintf:sprintf,vsprintf:vsprintf});ko.options.createChildContextWithAs=true;ko.options.foreachHidesDestroyed=true;log.setLevel(CONFIG_DEBUG?log.levels.DEBUG:log.levels.INFO);OctoPrint.options.baseurl=BASEURL;var l10n=getQueryParameterByName("l10n");if(l10n){OctoPrint.options.locale=l10n;}
OctoPrint.coreui=(function(){var exports={browserTabVisibility:undefined,selectedTab:undefined,settingsOpen:false,wizardOpen:false,browser:{chrome:false,firefox:false,safari:false,ie:false,edge:false,opera:false,mobile:false,desktop:false,browser_name:"unknown",browser_version:"unknown",os_name:"unknown",os_version:"unknown"},viewmodels:{},startedUp:false};var browserVisibilityCallbacks=[];var getHiddenProp=function(){var prefixes=["webkit","moz","ms","o"];if("hidden"in document){return"hidden";}
var vendorPrefix=_.find(prefixes,function(prefix){return prefix+"Hidden"in document;});if(vendorPrefix!==undefined){return vendorPrefix+"Hidden";}
return undefined;};var isHidden=function(){var prop=getHiddenProp();if(!prop)return false;return document[prop];};var updateBrowserVisibility=function(){var visible=!isHidden();exports.browserTabVisible=visible;_.each(browserVisibilityCallbacks,function(callback){callback(visible);});};var prop=getHiddenProp();if(prop){var eventName=prop.replace(/[H|h]idden/,"")+"visibilitychange";document.addEventListener(eventName,updateBrowserVisibility);updateBrowserVisibility();}
var navigator=window.navigator;var userAgent=((navigator&&navigator.userAgent)||"").toLowerCase();var vendor=((navigator&&navigator.vendor)||"").toLowerCase();exports.browser.opera=userAgent.match(/opera|opr/)!==null;exports.browser.chrome=!exports.browser.opera&&/google inc/.test(vendor)&&userAgent.match(/chrome|crios/)!==null;exports.browser.firefox=userAgent.match(/firefox|fxios/)!==null;exports.browser.ie=userAgent.match(/msie|trident/)!==null;exports.browser.edge=userAgent.match(/edge/)!==null;exports.browser.safari=!exports.browser.chrome&&!exports.browser.edge&&!exports.browser.opera&&userAgent.match(/safari/)!==null;exports.browser.mobile=$.browser.mobile;exports.browser.desktop=!exports.browser.mobile;var uap=UAParser();exports.browser.browser_name=uap.browser.name;exports.browser.browser_version=uap.browser.version;exports.browser.os_name=uap.os.name;exports.browser.os_version=uap.os.version;if(exports.browser.safari){$("html").addClass("safari");}
exports.isVisible=function(){return!isHidden();};exports.onBrowserVisibilityChange=function(callback){browserVisibilityCallbacks.push(callback);};exports.hashFromTabChange=false;exports.onTabChange=function(current,previous){log.debug("Selected OctoPrint tab changed: previous = "+
previous+", current = "+
current);OctoPrint.coreui.selectedTab=current;callViewModels(allViewModels,"onTabChange",[current,previous]);};exports.onAfterTabChange=function(current,previous){callViewModels(allViewModels,"onAfterTabChange",[current,previous]);};exports.updateTab=function(force){force=!!force;if(exports.hashFromTabChange){exports.hashFromTabChange=false;return;}
var selectTab=function(tab){if(tab.hash!==exports.selectedTab){if($(tab).parent("li").hasClass("active")&&force){var current=tab.hash;var previous=exports.selectedTab;exports.onTabChange(current,previous);exports.onAfterTabChange(current,previous);}else{$(tab).tab("show");}}else{window.location.hash=tab.hash;}};var tabs=$("#tabs");var hashtag=window.location.hash;if(hashtag){var selectedTab=tabs.find('a[href="'+hashtag+'"]:visible');if(selectedTab.length){selectTab(selectedTab[0]);return;}}
var firstTab=tabs.find("a[data-toggle=tab]:visible").eq(0);if(firstTab.length){selectTab(firstTab[0]);}};return exports;})();log.debug("Browser environment:",OctoPrint.coreui.browser);$.ajaxSetup({beforeSend:function(xhr,settings){var csrfToken=OctoPrint.getCookie("csrf_token");if(!/^(GET|HEAD|OPTIONS)$/.test(settings.type)&&csrfToken&&!this.crossDomain){xhr.setRequestHeader("X-CSRF-Token",csrfToken);}}});$.ajaxPrefilter(function(options,originalOptions,jqXHR){if(options.type!=="GET"){if(options.hasOwnProperty("headers")){options.headers["Cache-Control"]="no-cache";}else{options.headers={"Cache-Control":"no-cache"};}}});$.widget("blueimp.fileupload",$.blueimp.fileupload,{options:{dropZone:null,pasteZone:null,headers:OctoPrint.getRequestHeaders("POST")}});var catalog=window["BABEL_TO_LOAD_"+LOCALE];if(catalog===undefined){catalog={messages:undefined,plural_expr:undefined,locale:undefined,domain:undefined};}
babel.Translations.load(catalog).install();moment.locale(LOCALE);[gettext("Offline"),gettext("Offline after error"),gettext("Error"),gettext("Opening serial connection"),gettext("Detecting serial connection"),gettext("Connecting"),gettext("Operational"),gettext("Starting"),gettext("Starting print from SD"),gettext("Starting to send file to SD"),gettext("Printing from SD"),gettext("Sending file to SD"),gettext("Printing"),gettext("Paused"),gettext("Closed"),gettext("Transferring file to SD"),gettext("Pausing"),gettext("Resuming"),gettext("Cancelling"),gettext("Finishing")];PNotify.prototype.options.styling="bootstrap2";PNotify.prototype.options.mouse_reset=false;PNotify.prototype.options.stack.firstpos1=40+20;PNotify.prototype.options.stack.firstpos2=20;PNotify.prototype.options.stack.spacing1=20;PNotify.prototype.options.stack.spacing2=20;PNotify.prototype.options.stack.context=$("#page-container-main");PNotify.prototype.options.delay=5000;PNotify.prototype.options.animate_speed="fast";PNotify.prototype.options.maxheight.maxheight=function(){return $(window).height()-170;};PNotify.singleButtonNotify=function(options){if(!options.confirm||!options.confirm.buttons||!options.confirm.buttons.length){return new PNotify(options);}
var autoDisplay=options.auto_display!==false;var params=$.extend(true,{},options);params.auto_display=false;var notify=new PNotify(params);notify=PNotify.fixSingleButton(notify,options);if(autoDisplay){notify.open();}
return notify;};PNotify.fixSingleButton=function(notify,options){if(!options.confirm||!options.confirm.buttons||!options.confirm.buttons.length){return notify;}
notify.options.confirm.buttons=[notify.options.confirm.buttons[0]];notify.modules.confirm.makeDialog(notify,notify.options.confirm);return notify;};var viewModelMap={};if(!function f(){}.name){Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];}});}
var _createViewModelInstance=function(viewModel,viewModelMap,optionalDependencyPass){var viewModelParametersMap=function(parameter){if(optionalDependencyPass&&viewModel.optional.indexOf(parameter)!==-1&&!viewModelMap[parameter]){log.debug("Resolving optional parameter",[parameter],"without viewmodel");return null;}
return viewModelMap[parameter]||undefined;};var constructorParameters=_.map(viewModel.dependencies,viewModelParametersMap)||[];if(constructorParameters.indexOf(undefined)!==-1){log.debug("Postponing",viewModel.name,"due to missing parameters:",_.keys(_.pick(_.object(viewModel.dependencies,constructorParameters),_.isUndefined)));return;}
constructorParameters=viewModel.returnObject?_.object(viewModel.dependencies,constructorParameters):constructorParameters;log.debug("Constructing",viewModel.name,"with parameters:",viewModel.dependencies);return new viewModel.construct(constructorParameters);};var additionalBindings={};_.each(OCTOPRINT_ADDITIONAL_BINDINGS,function(bindings){var viewModelId=bindings[0];var viewModelBindTargets=bindings[1];if(!_.isArray(viewModelBindTargets)){viewModelBindTargets=[viewModelBindTargets];}
if(!additionalBindings.hasOwnProperty(viewModelId)){additionalBindings[viewModelId]=viewModelBindTargets;}else{additionalBindings[viewModelId]=additionalBindings[viewModelId].concat(viewModelBindTargets);}});var _getViewModelId=function(name){return name.substr(0,1).toLowerCase()+name.substr(1);};var unprocessedViewModels=OCTOPRINT_VIEWMODELS.slice();unprocessedViewModels=unprocessedViewModels.concat(ADDITIONAL_VIEWMODELS);var allViewModels=[];var allViewModelData=[];var pass=1;var optionalDependencyPass=false;log.info("Starting dependency resolution...");while(unprocessedViewModels.length>0){log.debug("Dependency resolution, pass #"+pass);var startLength=unprocessedViewModels.length;var postponed=[];while(unprocessedViewModels.length>0){var viewModel=unprocessedViewModels.shift();if(!_.isPlainObject(viewModel)){viewModel={construct:_.isArray(viewModel)?viewModel[0]:viewModel,dependencies:viewModel[1]||[],elements:viewModel[2]||[],optional:viewModel[3]||[]};}
if(!_.isFunction(viewModel.construct)){log.error("No function to instantiate with",viewModel);continue;}
viewModel.name=viewModel.name||_getViewModelId(viewModel.construct.name)||_.uniqueId("unnamedViewModel");viewModel.additionalNames=viewModel.additionalNames||[];_.each(["dependencies","elements","optional","additionalNames"],function(key){if(viewModel[key]===undefined){viewModel[key]=[];}else{viewModel[key]=_.isArray(viewModel[key])?viewModel[key]:[viewModel[key]];}});if(_.has(viewModelMap,viewModel.name)){log.error("Duplicate name while instantiating "+viewModel.name);continue;}
var viewModelInstance;try{viewModelInstance=_createViewModelInstance(viewModel,viewModelMap,optionalDependencyPass);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Error instantiating",viewModel.name,":",`${exc.message}\n${exc.stack || exc}`);continue;}
if(viewModelInstance===undefined){postponed.push(viewModel);continue;}
var viewModelBindTargets=viewModel.elements;if(additionalBindings.hasOwnProperty(viewModel.name)){viewModelBindTargets=viewModelBindTargets.concat(additionalBindings[viewModel.name]);}
allViewModelData.push([viewModelInstance,viewModelBindTargets]);allViewModels.push(viewModelInstance);viewModelMap[viewModel.name]=viewModelInstance;if(viewModel.additionalNames.length){var registeredAdditionalNames=[];_.each(viewModel.additionalNames,function(additionalName){if(!_.has(viewModelMap,additionalName)){viewModelMap[additionalName]=viewModelInstance;registeredAdditionalNames.push(additionalName);}});if(registeredAdditionalNames.length){log.debug("Registered",viewModel.name,"under these additional names:",registeredAdditionalNames);}}}
unprocessedViewModels=unprocessedViewModels.concat(postponed);if(unprocessedViewModels.length===startLength){if(!optionalDependencyPass){log.debug("Resolving next pass with optional dependencies flag enabled");optionalDependencyPass=true;}else{log.error("Could not instantiate the following view models due to unresolvable dependencies:");_.each(unprocessedViewModels,function(entry){log.error(entry.name+" (missing: "+
_.filter(entry.dependencies,function(id){return!_.has(viewModelMap,id);}).join(", ")+" )");});break;}}
log.debug("Dependency resolution pass #"+
pass+" finished, "+
unprocessedViewModels.length+" view models left to process");pass++;}
log.info("... dependency resolution done");OctoPrint.coreui.viewmodels=viewModelMap;$.fn.modal.defaults.maxHeight=function(){return $(window).height()-165;};$.fn.selectText=function(){var doc=document;var element=this[0];var range,selection;if(doc.body.createTextRange){range=document.body.createTextRange();range.moveToElementText(element);range.select();}else if(window.getSelection){selection=window.getSelection();range=document.createRange();range.selectNodeContents(element);selection.removeAllRanges();selection.addRange(range);}};$.fn.isChildOf=function(element){return $(element).has(this).length>0;};$.fn.contextMenu=function(settings){return this.each(function(){$(this).on("contextmenu",function(e){if(e.ctrlKey)return;$(settings.menuSelector).data("invokedOn",$(e.target)).data("contextParent",$(this)).show().css({"position":"fixed","left":getMenuPosition(e.clientX,"width","scrollLeft"),"top":getMenuPosition(e.clientY,"height","scrollTop"),"z-index":9999}).off("click").on("click",function(e){if(e.target.tagName.toLowerCase()==="input")return;$(this).hide();settings.menuSelected.call(this,$(this).data("invokedOn"),$(this).data("contextParent"),$(e.target));});return false;});$(document).click(function(){$(settings.menuSelector).hide();});});function getMenuPosition(mouse,direction,scrollDir){var win=$(window)[direction](),scroll=$(window)[scrollDir](),menu=$(settings.menuSelector)[direction](),position=mouse+scroll;if(mouse+menu>win&&menu<mouse)position-=menu;return position;}};$.fn.lazyload=function(){return this.each(function(){if(this.tagName.toLowerCase()!=="img")return;var src=this.getAttribute("data-src");if(src){this.setAttribute("src",src);this.removeAttribute("data-src");}});};var tabs=$("#tabs").find('a[data-toggle="tab"]');tabs.on("show",function(e){var current=e.target.hash;var previous=e.relatedTarget?e.relatedTarget.hash:undefined;OctoPrint.coreui.onTabChange(current,previous);});tabs.on("shown",function(e){var current=e.target.hash;var previous=e.relatedTarget?e.relatedTarget.hash:undefined;OctoPrint.coreui.onAfterTabChange(current,previous);var scrollmem=$("body").scrollTop()||$("html").scrollTop();OctoPrint.coreui.hashFromTabChange=true;window.location.hash=current;$("html,body").scrollTop(scrollmem);});$(".dropdown input, .dropdown label").click(function(e){e.stopPropagation();});$(document).bind("drop dragover",function(e){e.preventDefault();});$("#reloadui_overlay_reload").click(function(){location.reload();});if(!_.has(viewModelMap,"settingsViewModel")){throw new Error("settingsViewModel is missing, can't run UI");}
if(!_.has(viewModelMap,"accessViewModel")||!viewModelMap["accessViewModel"].permissions){throw new Error("accessViewmodel is missing or incomplete, can't run UI");}
if(!_.has(viewModelMap,"loginStateViewModel")){throw new Error("loginStateViewModel is missing, can't run UI");}
if(!_.has(viewModelMap,"uiStateViewModel")){throw new Error("uiStateViewModel is missing, can't run UI");}
var bindViewModels=function(){try{log.info("Going to bind "+allViewModelData.length+" view models...");_.each(allViewModelData,function(viewModelData){try{if(!Array.isArray(viewModelData)||viewModelData.length!==2){if(typeof Sentry!=="undefined"){Sentry.captureException(new Error("View model data for"+
viewModelData.constructor.name+"has wrong format, expected 2-tuple (viewModel, targets), got:"+
viewModelData));}
log.error("View model data for",viewModelData.constructor.name,"has wrong format, expected 2-tuple (viewModel, targets), got:",viewModelData);return;}
var viewModel=viewModelData[0];var targets=viewModelData[1];if(targets===undefined){log.error("No binding targets defined for view model",viewMode.constructor.name);return;}
if(!_.isArray(targets)){targets=[targets];}
try{callViewModel(viewModel,"onBeforeBinding",undefined,true);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Error calling onBeforeBinding on view model",viewModel.constructor.name,":",`${exc.message}\n${exc.stack || exc}`);return;}
if(targets!==undefined){if(!_.isArray(targets)){targets=[targets];}
viewModel._bindings=[];_.each(targets,function(target){if(target===undefined){log.error("Undefined target for view model",viewModel.constructor.name);return;}
var object;if(!(target instanceof jQuery)){try{object=$(target);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Error while attempting to jquery-fy target",target,"of view model",viewModel.constructor.name,":",`${exc.message}\n${exc.stack || exc}`);return;}}else{object=target;}
if(object===undefined||!object.length){log.info("Did not bind view model",viewModel.constructor.name,"to target",target,"since it does not exist");return;}
var element=object.get(0);if(element===undefined){log.info("Did not bind view model",viewModel.constructor.name,"to target",target,"since it does not exist");return;}
try{ko.applyBindings(viewModel,element);viewModel._bindings.push(target);callViewModel(viewModel,"onBoundTo",[target,element],true);log.debug("View model",viewModel.constructor.name,"bound to",target);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
log.error("Could not bind view model",viewModel.constructor.name,"to target",target,":",`${exc.message}\n${exc.stack || exc}`);}});}
viewModel._unbound=viewModel._bindings===undefined||viewModel._bindings.length===0;viewModel._bound=viewModel._bindings&&viewModel._bindings.length>0;callViewModel(viewModel,"onAfterBinding");}catch(exc){var name;try{name=viewModel.constructor.name;}catch(exc){name="n/a";}
log.error("Error while processing view model",name,"for binding:",`${exc.message}\n${exc.stack || exc}`);}});callViewModels(allViewModels,"onAllBound",[allViewModels]);log.info("... binding done");OctoPrint.coreui.onBrowserVisibilityChange(function(status){log.debug("Browser tab is now "+(status?"visible":"hidden"));callViewModels(allViewModels,"onBrowserTabVisibilityChange",[status]);});$(window).on("hashchange",function(){OctoPrint.coreui.updateTab();});log.info("Application startup complete");viewModelMap["uiStateViewModel"].loading(false);}catch(exc){if(typeof Sentry!=="undefined"){Sentry.captureException(exc);}
viewModelMap["uiStateViewModel"].showLoadingError("Application startup failed.");throw exc;}
callViewModels(allViewModels,"onStartupComplete");setOnViewModels(allViewModels,"_startupComplete",true);OctoPrint.coreui.updateTab(true);$(".nav-pills, .nav-tabs").tabdrop();OctoPrint.coreui.startedUp=true;};var fetchSettings=function(){log.info("Finalizing application startup");callViewModels(allViewModels,"onStartup");viewModelMap["settingsViewModel"].requestData().done(function(){var adjustModalDefaultBehaviour=function(){if(viewModelMap["settingsViewModel"].appearance_closeModalsWithClick()){$.fn.modal.defaults.backdrop=true;}else{$.fn.modal.defaults.backdrop="static";}};adjustModalDefaultBehaviour();viewModelMap["settingsViewModel"].appearance_closeModalsWithClick.subscribe(adjustModalDefaultBehaviour);window.setTimeout(bindViewModels,0);}).fail(function(){viewModelMap["uiStateViewModel"].showLoadingError("Initial settings fetch failed.");});};log.info("Initial application setup done, connecting to server...");var onServerConnect=function(){viewModelMap["accessViewModel"].permissions.initialize();return viewModelMap["loginStateViewModel"].requestData().done(function(){dataUpdater.initialized();}).fail(function(){viewModelMap["uiStateViewModel"].showLoadingError("Passive login failed.");});};var dataUpdater=new DataUpdater(allViewModels);dataUpdater.connect().done(function(){dataUpdater.connectCallback=onServerConnect;$("#page-container-loading-header").html(gettext("Loading OctoPrint's UI, please wait..."));onServerConnect().done(function(){window.setTimeout(fetchSettings,0);});}).fail(function(){viewModelMap["uiStateViewModel"].showLoadingError("Socket connection failed.");});});
;
